Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(runtimes): weekly usage dimension + tz-aware aggregation (MUL-2382) (#2822)
Jiayuan Zhang35fc318d68cd
diff --git a/packages/views/dashboard/components/dashboard-page.tsx b/packages/views/dashboard/components/dashboard-page.tsxindex 8f9a25588d..6c81fe316c 100644--- a/packages/views/dashboard/components/dashboard-page.tsx+++ b/packages/views/dashboard/components/dashboard-page.tsx@@ -28,14 +28,19 @@ import {DailyTokensChart,DailyTimeChart,DailyTasksChart,+ WeeklyCostChart,+ WeeklyTokensChart,+ WeeklyTimeChart,+ WeeklyTasksChart,} from "../../runtimes/components/charts";import { ProjectIcon } from "../../projects/components/project-icon";import { ActorAvatar } from "../../common/actor-avatar";import {- TimezoneSelect,- browserTimezone,-} from "../../common/timezone-select";-import { formatTokens } from "../../runtimes/utils";+ addDaysIso,+ aggregateByWeek,+ formatTokens,+ todayIso,+} from "../../runtimes/utils";import { useT } from "../../i18n";import {aggregateAgentTokens,@@ -43,20 +48,37 @@ import {aggregateDailyTasks,aggregateDailyTime,aggregateDailyTokens,+ aggregateWeeklyTasks,+ aggregateWeeklyTime,computeDailyTotals,formatDuration,mergeAgentDashboardRows,type AgentDashboardRow,} from "../utils";-// One-place source of truth for the period selector. Matches the runtime-// detail page so users see the same three options across the dashboards.+// Period selector — mirrors the runtime detail page so users see the same+// option set across both dashboards. `dims` declares which dimensions each+// range is allowed in: 7d at the weekly grain is one bar, 180d at the daily+// grain is 180 unreadable bars, so each end of the range belongs to a single+// dimension. Switching dimensions resets `days` if the current value isn't+// in the new dimension's allowed set (see `handleDimChange` below).const TIME_RANGES = [- { label: "7d", days: 7 },- { label: "30d", days: 30 },- { label: "90d", days: 90 },+ { 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 Dim = "daily" | "weekly";++const DEFAULT_DAYS_BY_DIM: Record<Dim, TimeRange> = {+ daily: 30,+ weekly: 90,+};++function rangesForDim(dim: Dim) {+ return TIME_RANGES.filter((r) => (r.dims as readonly string[]).includes(dim));+}// Sentinel for "no project filter" — kept distinct from the empty string// so it survives a refactor that ever lets a project be slug-keyed.@@ -75,6 +97,14 @@ function fmtMoney(n: number): string {return `$${n.toFixed(2)}`;}+// Weekly aggregation is locked to UTC: the dashboard daily rollup buckets+// data by UTC `bucket_date` (and the raw fallback queries by `DATE(...)`,+// also UTC), so any other zone for client-side week boundaries would put+// cross-midnight rows into the wrong calendar week. Runtime-detail can use+// the runtime's IANA tz because its rollup is materialized in that tz; the+// workspace rollup has no equivalent, so weekly is UTC-only here.+const WEEK_TZ = "UTC";+// Local segmented control — same visual language the runtime usage section// uses for its period / tab toggles. shadcn's Tabs is wired for full tab// pages with ARIA semantics the compact toolbar pill doesn't need.@@ -120,14 +150,19 @@ function Segmented<T extends string | number>({*/export function DashboardPage() {const { t } = useT("usage");- const { t: tRuntimes } = useT("runtimes");const wsId = useWorkspaceId();+ const [dim, setDim] = useState<Dim>("daily");const [days, setDays] = useState<TimeRange>(30);const [projectValue, setProjectValue] = useState<string>(ALL_PROJECTS);- // Default to the browser's resolved zone so day-boundary buckets match the- // user's local clock on first render. Pure client-state — the rollup queries- // are zone-agnostic today; this is the UI affordance the user can pin.- const [timezone, setTimezone] = useState<string>(() => browserTimezone());++ const allowedRanges = rangesForDim(dim);+ const handleDimChange = (next: Dim) => {+ setDim(next);+ const stillAllowed = (rangesForDim(next) as readonly { days: number }[]).some(+ (r) => r.days === days,+ );+ if (!stillAllowed) setDays(DEFAULT_DAYS_BY_DIM[next]);+ };// The user can save model prices from the runtimes page; re-render when// they do so the dashboard reflects the new rates.@@ -147,11 +182,22 @@ export function DashboardPage() {return projects.some((p) => p.id === projectValue) ? projectValue : null;}, [projectValue, projects]);- const dailyQuery = useQuery(dashboardUsageDailyOptions(wsId, days, projectId));+ // The weekly chart paints `ceil(days / 7)` trailing calendar weeks anchored+ // at today-in-UTC. In the worst case (today = Sunday) the leftmost Monday+ // sits `weekCount * 7 - 1` days back, so a vanilla `days=30` request would+ // silently truncate the leftmost bucket. Over-fetch the per-date queries+ // to cover the full first week; the per-agent rollups stay at `days` so+ // KPI/leaderboard labels (e.g. "Tasks · 30D") keep their advertised window.+ const weekCount = Math.max(1, Math.ceil(days / 7));+ const chartFetchDays = dim === "weekly" ? weekCount * 7 : days;++ const dailyQuery = useQuery(+ dashboardUsageDailyOptions(wsId, chartFetchDays, projectId),+ );const byAgentQuery = useQuery(dashboardUsageByAgentOptions(wsId, days, projectId));const runTimeQuery = useQuery(dashboardAgentRunTimeOptions(wsId, days, projectId));const runTimeDailyQuery = useQuery(- dashboardRunTimeDailyOptions(wsId, days, projectId),+ dashboardRunTimeDailyOptions(wsId, chartFetchDays, projectId),);const dailyUsage = dailyQuery.data ?? EMPTY_DAILY;@@ -159,6 +205,30 @@ export function DashboardPage() {const runTimeRows = runTimeQuery.data ?? EMPTY_RUNTIME;const runTimeDailyRows = runTimeDailyQuery.data ?? EMPTY_RUNTIME_DAILY;+ // Daily-aggregation surfaces (cost/tokens/time/tasks KPIs and the Daily+ // trend chart) re-scope to the user-selected `days` even when we+ // over-fetched for the weekly chart. UTC matches the bucket_date the+ // backend filters on, so the cutoff lands on the same calendar boundary+ // the rollup used.+ const dailyCutoffIso = useMemo(+ () => addDaysIso(todayIso(WEEK_TZ), -(days - 1)),+ [days],+ );+ const dailyUsageInWindow = useMemo(+ () =>+ dim === "weekly"+ ? dailyUsage.filter((u) => u.date >= dailyCutoffIso)+ : dailyUsage,+ [dailyUsage, dim, dailyCutoffIso],+ );+ const runTimeDailyInWindow = useMemo(+ () =>+ dim === "weekly"+ ? runTimeDailyRows.filter((r) => r.date >= dailyCutoffIso)+ : runTimeDailyRows,+ [runTimeDailyRows, dim, dailyCutoffIso],+ );+const isLoading =dailyQuery.isLoading ||byAgentQuery.isLoading ||@@ -176,16 +246,46 @@ export function DashboardPage() {runTimeDailyRows.length === 0;// Cost / token math — re-derived when usage, days, or pricings change.- const totals = useMemo(() => computeDailyTotals(dailyUsage), [dailyUsage]);- const dailyCost = useMemo(() => aggregateDailyCost(dailyUsage), [dailyUsage]);- const dailyTokens = useMemo(() => aggregateDailyTokens(dailyUsage), [dailyUsage]);+ const totals = useMemo(+ () => computeDailyTotals(dailyUsageInWindow),+ [dailyUsageInWindow],+ );+ const dailyCost = useMemo(+ () => aggregateDailyCost(dailyUsageInWindow),+ [dailyUsageInWindow],+ );+ const dailyTokens = useMemo(+ () => aggregateDailyTokens(dailyUsageInWindow),+ [dailyUsageInWindow],+ );const dailyTime = useMemo(- () => aggregateDailyTime(runTimeDailyRows),- [runTimeDailyRows],+ () => aggregateDailyTime(runTimeDailyInWindow),+ [runTimeDailyInWindow],);const dailyTasks = useMemo(- () => aggregateDailyTasks(runTimeDailyRows),- [runTimeDailyRows],+ () => aggregateDailyTasks(runTimeDailyInWindow),+ [runTimeDailyInWindow],+ );++ // Weekly aggregates — built from the over-fetched per-date queries so the+ // leftmost trailing week always has data even when the user-selected `days`+ // (e.g. 30D) is shorter than the chart's `weekCount * 7` span. Buckets are+ // pre-zeroed inside the helpers, so sparse weeks render as empty bars+ // instead of being dropped (MUL-2382 weekly window scoping). Locked to+ // UTC so the week boundaries match the backend's UTC `bucket_date`.+ const weekly = useMemo(+ () => aggregateByWeek(dailyUsage, WEEK_TZ, weekCount),+ [dailyUsage, weekCount],+ );+ const weeklyCost = weekly.weeklyCostStack;+ const weeklyTokens = weekly.weeklyTokens;+ const weeklyTime = useMemo(+ () => aggregateWeeklyTime(runTimeDailyRows, WEEK_TZ, weekCount),+ [runTimeDailyRows, weekCount],+ );+ const weeklyTasks = useMemo(+ () => aggregateWeeklyTasks(runTimeDailyRows, WEEK_TZ, weekCount),+ [runTimeDailyRows, weekCount],);const agentTokenRows = useMemo(() => aggregateAgentTokens(byAgentUsage),@@ -212,12 +312,10 @@ export function DashboardPage() {return (<div className="flex h-full flex-col">- {/* h-auto + min-h-12 + flex-wrap: the toolbar (project filter, range- switch, timezone select) overflows the single h-12 row on narrow- and medium widths once the timezone picker is added — letting the- right cluster wrap underneath keeps every control reachable- without an off-screen bleed. Wider viewports still render the- original single row. */}+ {/* h-auto + min-h-12 + flex-wrap: the toolbar (project filter,+ dimension switch, range switch) wraps on narrow viewports so every+ control stays reachable. Wider viewports still render the original+ single row. */}<PageHeader className="h-auto min-h-12 flex-wrap justify-between gap-y-1.5 px-5 py-1.5 sm:py-0"><div className="flex min-w-0 items-center gap-2"><BarChart3 className="h-4 w-4 shrink-0 text-muted-foreground" />@@ -229,16 +327,18 @@ export function DashboardPage() {value={projectValue}onChange={setProjectValue}/>+ <Segmented+ value={dim}+ onChange={handleDimChange}+ options={[+ { label: t(($) => $.dim.daily), value: "daily" as const },+ { label: t(($) => $.dim.weekly), value: "weekly" as const },+ ]}+ /><Segmentedvalue={days}onChange={setDays}- options={TIME_RANGES.map((r) => ({ label: r.label, value: r.days }))}- />- <TimezoneSelect- value={timezone}- onValueChange={setTimezone}- browserSuffix={tRuntimes(($) => $.detail.timezone_browser_suffix)}- triggerClassName="rounded-md font-mono text-xs"+ options={allowedRanges.map((r) => ({ label: r.label, value: r.days }))}/></div></PageHeader>@@ -290,14 +390,21 @@ export function DashboardPage() {/></div>- {/* Daily trend chart — toggle picks Tokens / Cost / Time /- Tasks. All four share the same x-axis (date) so the user- can mentally overlay them by switching the toggle. */}- <DailyTrendBlock+ {/* Trend chart — toggle picks Tokens / Cost / Time / Tasks+ and the parent's dim selector decides whether the bars are+ per-day or per-calendar-week. All four metrics share the+ same x-axis so the user can mentally overlay them by+ flipping the toggle. */}+ <TrendBlock+ dim={dim}dailyCost={dailyCost}dailyTokens={dailyTokens}dailyTime={dailyTime}dailyTasks={dailyTasks}+ weeklyCost={weeklyCost}+ weeklyTokens={weeklyTokens}+ weeklyTime={weeklyTime}+ weeklyTasks={weeklyTasks}lessThanMinuteLabel={t(($) => $.duration.less_than_minute)}/>@@ -375,17 +482,27 @@ function ProjectFilter({type DailyMetric = "tokens" | "cost" | "time" | "tasks";-function DailyTrendBlock({+function TrendBlock({+ dim,dailyCost,dailyTokens,dailyTime,dailyTasks,+ weeklyCost,+ weeklyTokens,+ weeklyTime,+ weeklyTasks,lessThanMinuteLabel,}: {+ dim: Dim;dailyCost: ReturnType<typeof aggregateDailyCost>;dailyTokens: ReturnType<typeof aggregateDailyTokens>;dailyTime: ReturnType<typeof aggregateDailyTime>;dailyTasks: ReturnType<typeof aggregateDailyTasks>;+ weeklyCost: ReturnType<typeof aggregateByWeek>["weeklyCostStack"];+ weeklyTokens: ReturnType<typeof aggregateByWeek>["weeklyTokens"];+ weeklyTime: ReturnType<typeof aggregateWeeklyTime>;+ weeklyTasks: ReturnType<typeof aggregateWeeklyTasks>;lessThanMinuteLabel: string;}) {const { t } = useT("usage");@@ -394,13 +511,18 @@ function DailyTrendBlock({// Empty-state is per-metric so each toggle option independently decides// whether it has data — e.g. tokens recorded but no terminal runs yet// should show Tokens normally while Time / Tasks fall through to empty.- const totalCost = dailyCost.reduce((sum, d) => sum + d.total, 0);- const totalTokens = dailyTokens.reduce(+ const costData = dim === "weekly" ? weeklyCost : dailyCost;+ const tokensData = dim === "weekly" ? weeklyTokens : dailyTokens;+ const timeData = dim === "weekly" ? weeklyTime : dailyTime;+ const tasksData = dim === "weekly" ? weeklyTasks : dailyTasks;++ const totalCost = costData.reduce((sum, d) => sum + d.total, 0);+ const totalTokens = tokensData.reduce((sum, d) => sum + d.input + d.output + d.cacheRead + d.cacheWrite,0,);- const totalSeconds = dailyTime.reduce((sum, d) => sum + d.totalSeconds, 0);- const totalTasks = dailyTasks.reduce(+ const totalSeconds = timeData.reduce((sum, d) => sum + d.totalSeconds, 0);+ const totalTasks = tasksData.reduce((sum, d) => sum + d.completed + d.failed,0,);@@ -414,13 +536,21 @@ function DailyTrendBlock({: totalTasks === 0;const title =- metric === "cost"- ? t(($) => $.daily.title_cost)- : metric === "tokens"- ? t(($) => $.daily.title_tokens)- : metric === "time"- ? t(($) => $.daily.title_time)- : t(($) => $.daily.title_tasks);+ dim === "weekly"+ ? metric === "cost"+ ? t(($) => $.weekly.title_cost)+ : metric === "tokens"+ ? t(($) => $.weekly.title_tokens)+ : metric === "time"+ ? t(($) => $.weekly.title_time)+ : t(($) => $.weekly.title_tasks)+ : metric === "cost"+ ? t(($) => $.daily.title_cost)+ : metric === "tokens"+ ? t(($) => $.daily.title_tokens)+ : metric === "time"+ ? t(($) => $.daily.title_time)+ : t(($) => $.daily.title_tasks);return (<div className="rounded-lg border bg-card p-4">@@ -445,6 +575,20 @@ function DailyTrendBlock({{t(($) => $.daily.no_data)}</p></div>+ ) : dim === "weekly" ? (+ metric === "cost" ? (+ <WeeklyCostChart data={weeklyCost} />+ ) : metric === "tokens" ? (+ <WeeklyTokensChart data={weeklyTokens} />+ ) : metric === "time" ? (+ <WeeklyTimeChart+ data={weeklyTime}+ formatY={(s) => formatDuration(s, lessThanMinuteLabel)}+ formatTooltip={(s) => formatDuration(s, lessThanMinuteLabel)}+ />+ ) : (+ <WeeklyTasksChart data={weeklyTasks} />+ )) : metric === "cost" ? (<DailyCostChart data={dailyCost} />) : metric === "tokens" ? (diff --git a/packages/views/dashboard/utils.test.ts b/packages/views/dashboard/utils.test.tsindex cf87b77b8e..6aac9de0bd 100644--- a/packages/views/dashboard/utils.test.ts+++ b/packages/views/dashboard/utils.test.ts@@ -1,7 +1,9 @@-import { describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {aggregateAgentTokens,aggregateDailyCost,+ aggregateWeeklyTasks,+ aggregateWeeklyTime,computeDailyTotals,formatDuration,mergeAgentDashboardRows,@@ -211,3 +213,95 @@ describe("formatDuration", () => {expect(formatDuration(0.4, "<1m")).toBe("<1m");});});++// ---------------------------------------------------------------------------+// Weekly run-time / tasks aggregation. Mirrors the runtimes-side+// aggregateByWeek tests: trailing N calendar weeks anchored at today-in-tz,+// pre-zeroed buckets, partial-week metadata, and rows outside the window+// dropped. We assert the same invariants on the workspace dashboard helpers+// so all four metrics behave consistently when the user toggles Weekly.+// ---------------------------------------------------------------------------++describe("aggregateWeeklyTime", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it("folds per-day run-time rows into Mon-anchored weekly totals", () => {+ // 2026-05-19 is a Tuesday → current week is Mon=05-18..Sun=05-24.+ vi.setSystemTime(new Date("2026-05-19T12:00:00Z"));+ const rows = [+ { date: "2026-05-11", total_seconds: 100, task_count: 0, failed_count: 0 },+ { date: "2026-05-17", total_seconds: 50, task_count: 0, failed_count: 0 },+ { date: "2026-05-18", total_seconds: 25, task_count: 0, failed_count: 0 },+ ];+ const result = aggregateWeeklyTime(rows, "UTC", 2);+ expect(result).toHaveLength(2);+ expect(result[0]).toMatchObject({+ weekStart: "2026-05-11",+ weekEnd: "2026-05-17",+ totalSeconds: 150,+ partial: false,+ daysCovered: 7,+ });+ expect(result[1]).toMatchObject({+ weekStart: "2026-05-18",+ totalSeconds: 25,+ partial: true,+ daysCovered: 2, // Mon + Tue+ });+ });++ it("drops rows that fall outside the trailing window and keeps empty buckets", () => {+ // Same MUL-2382 sparse-data regression we caught on the runtimes side:+ // an old populated week must not surface when the requested window+ // doesn't include it; in-range empty weeks must remain as zero buckets.+ vi.setSystemTime(new Date("2026-05-19T12:00:00Z"));+ const rows = [+ // 2026-04-13 is a Monday — exactly one week earlier than the oldest+ // in-range week (Mon=04-20) for a 5-week trailing window.+ { date: "2026-04-13", total_seconds: 999, task_count: 0, failed_count: 0 },+ ];+ const result = aggregateWeeklyTime(rows, "UTC", 5);+ expect(result.map((w) => w.weekStart)).toEqual([+ "2026-04-20",+ "2026-04-27",+ "2026-05-04",+ "2026-05-11",+ "2026-05-18",+ ]);+ for (const w of result) expect(w.totalSeconds).toBe(0);+ });+});++describe("aggregateWeeklyTasks", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it("splits completed and failed counts per calendar week", () => {+ vi.setSystemTime(new Date("2026-05-19T12:00:00Z"));+ const rows = [+ { date: "2026-05-12", total_seconds: 0, task_count: 5, failed_count: 1 },+ { date: "2026-05-18", total_seconds: 0, task_count: 3, failed_count: 0 },+ ];+ const result = aggregateWeeklyTasks(rows, "UTC", 2);+ expect(result[0]).toMatchObject({+ weekStart: "2026-05-11",+ completed: 4,+ failed: 1,+ });+ expect(result[1]).toMatchObject({+ weekStart: "2026-05-18",+ completed: 3,+ failed: 0,+ partial: true,+ });+ });+});diff --git a/packages/views/dashboard/utils.ts b/packages/views/dashboard/utils.tsindex 4f937306ce..c819fd2cca 100644--- a/packages/views/dashboard/utils.ts+++ b/packages/views/dashboard/utils.ts@@ -4,10 +4,20 @@ import type {DashboardAgentRunTime,DashboardRunTimeDaily,} from "@multica/core/types";-import { estimateCost, estimateCostBreakdown, type DailyTokenData } from "../runtimes/utils";+import {+ addDaysIso,+ estimateCost,+ estimateCostBreakdown,+ formatShortDate,+ todayIso,+ weekStartIso,+ type DailyTokenData,+} from "../runtimes/utils";import type {DailyTimeData,DailyTasksData,+ WeeklyTimeData,+ WeeklyTasksData,} from "../runtimes/components/charts";// ---------------------------------------------------------------------------@@ -217,6 +227,103 @@ export function mergeAgentDashboardRows(});}+// ---------------------------------------------------------------------------+// Weekly fold for run-time + tasks. Mirrors `aggregateByWeek` in+// `runtimes/utils.ts` which already covers cost / tokens — same calendar+// week semantics (Mon–Sun anchored at today-in-tz), same pre-zeroed buckets,+// same partial-week metadata. Workspace dashboard uses the user-chosen+// timezone here; the runtime page uses the runtime's IANA tz. Behaviour is+// identical apart from where the tz comes from.+// ---------------------------------------------------------------------------++interface WeekShell {+ weekStart: string;+ weekEnd: string;+ label: string;+ rangeLabel: string;+ partial: boolean;+ daysCovered: number;+}++// Build N trailing calendar week shells anchored at today-in-tz. Each shell+// carries the labels and partial-week metadata the chart components consume;+// downstream aggregators fold their own per-week values onto the matching+// shell.+function buildWeekShells(tz: string, weekCount: number): WeekShell[] {+ const count = Math.max(1, Math.floor(weekCount));+ const today = todayIso(tz);+ const currentWeekStart = weekStartIso(today);+ const firstWeekStart = addDaysIso(currentWeekStart, -(count - 1) * 7);+ const shells: WeekShell[] = [];+ for (let i = 0; i < count; i++) {+ const weekStart = addDaysIso(firstWeekStart, i * 7);+ const weekEnd = addDaysIso(weekStart, 6);+ const partial = today < weekEnd;+ // Inclusive count of how many days of this week have actually elapsed.+ // Closed weeks sit at 7; the current week reports 1..6.+ const clampedToday =+ today < weekStart ? weekStart : today < weekEnd ? today : weekEnd;+ const elapsed = Math.min(7, Math.max(1, diffDaysIso(weekStart, clampedToday) + 1));+ shells.push({+ weekStart,+ weekEnd,+ label: formatShortDate(weekStart),+ rangeLabel: `${formatShortDate(weekStart)} – ${formatShortDate(weekEnd)}`,+ partial,+ daysCovered: partial ? elapsed : 7,+ });+ }+ return shells;+}++function diffDaysIso(from: string, to: string): number {+ const [y1, m1, d1] = from.split("-").map(Number);+ const [y2, m2, d2] = to.split("-").map(Number);+ const a = Date.UTC(y1 ?? 1970, (m1 ?? 1) - 1, d1 ?? 1);+ const b = Date.UTC(y2 ?? 1970, (m2 ?? 1) - 1, d2 ?? 1);+ return Math.round((b - a) / 86_400_000);+}++export function aggregateWeeklyTime(+ rows: DashboardRunTimeDaily[],+ tz: string,+ weekCount: number,+): WeeklyTimeData[] {+ const shells = buildWeekShells(tz, weekCount);+ const totals = new Map<string, number>();+ for (const shell of shells) totals.set(shell.weekStart, 0);+ for (const r of rows) {+ const wkStart = weekStartIso(r.date);+ if (!totals.has(wkStart)) continue;+ totals.set(wkStart, (totals.get(wkStart) ?? 0) + r.total_seconds);+ }+ return shells.map((s) => ({ ...s, totalSeconds: totals.get(s.weekStart) ?? 0 }));+}++export function aggregateWeeklyTasks(+ rows: DashboardRunTimeDaily[],+ tz: string,+ weekCount: number,+): WeeklyTasksData[] {+ const shells = buildWeekShells(tz, weekCount);+ const buckets = new Map<string, { completed: number; failed: number }>();+ for (const shell of shells)+ buckets.set(shell.weekStart, { completed: 0, failed: 0 });+ for (const r of rows) {+ const wkStart = weekStartIso(r.date);+ const bucket = buckets.get(wkStart);+ if (!bucket) continue;+ const failed = r.failed_count;+ const completed = Math.max(0, r.task_count - failed);+ bucket.completed += completed;+ bucket.failed += failed;+ }+ return shells.map((s) => {+ const b = buckets.get(s.weekStart) ?? { completed: 0, failed: 0 };+ return { ...s, completed: b.completed, failed: b.failed };+ });+}+// Per-date run-time rows → one row per date with `totalSeconds` for the// DailyTimeChart. Sorted ascending so the x-axis reads oldest-to-newest,// matching the cost / tokens aggregators.diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.jsonindex 357521bb80..348ce80b13 100644--- a/packages/views/locales/en/runtimes.json+++ b/packages/views/locales/en/runtimes.json@@ -212,6 +212,7 @@},"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",@@ -220,10 +221,11 @@"kpi_tokens_hint": "in {{input}} · out {{output}}","when_title": "When this runtime spent","when_tab_daily": "Daily",- "when_tab_hourly": "Hourly",+ "when_tab_weekly": "Weekly","when_tab_heatmap": "Heatmap","daily_metric_cost": "Cost","daily_metric_tokens": "Tokens",+ "weekly_partial_label": "{{range}} (partial · {{covered}} / 7 days)","heatmap_caption": "Last 26 weeks · daily $ intensity (period selector ignored here)","legend_input": "Input","legend_output": "Output",diff --git a/packages/views/locales/en/usage.json b/packages/views/locales/en/usage.jsonindex 24c4eadc79..5611b5cc3e 100644--- a/packages/views/locales/en/usage.json+++ b/packages/views/locales/en/usage.json@@ -15,6 +15,11 @@"tasks_label": "Tasks · {{days}}D","tasks_hint": "{{failed}} failed"},+ "dim": {+ "label": "Dimension",+ "daily": "Daily",+ "weekly": "Weekly"+ },"daily": {"title_cost": "Daily cost","title_tokens": "Daily tokens",@@ -26,6 +31,13 @@"metric_tasks": "Tasks","no_data": "No usage in this window."},+ "weekly": {+ "title_cost": "Weekly cost",+ "title_tokens": "Weekly tokens",+ "title_time": "Weekly run time",+ "title_tasks": "Weekly tasks",+ "partial_label": "{{range}} (partial · {{covered}} / 7 days)"+ },"leaderboard": {"title": "Leaderboard","caption": "{{count}} agents",diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.jsonindex fe21b727db..52d2b5138e 100644--- a/packages/views/locales/zh-Hans/runtimes.json+++ b/packages/views/locales/zh-Hans/runtimes.json@@ -203,6 +203,7 @@},"usage": {"period_label": "时间范围",+ "dimension_label": "维度","kpi_cost_label": "费用 · {{days}} 天","kpi_cost_delta": "{{sign}}{{pct}}% 对比上期","kpi_cache_label": "缓存节省 · {{days}} 天",@@ -211,10 +212,11 @@"kpi_tokens_hint": "输入 {{input}} · 输出 {{output}}","when_title": "这个运行时在何时消耗","when_tab_daily": "按天",- "when_tab_hourly": "按小时",+ "when_tab_weekly": "按周","when_tab_heatmap": "热力图","daily_metric_cost": "费用","daily_metric_tokens": "Token",+ "weekly_partial_label": "{{range}}(未满 · 已过 {{covered}} / 7 天)","heatmap_caption": "最近 26 周 · 每日 $ 强度(此处忽略上方时间范围)","legend_input": "输入","legend_output": "输出",diff --git a/packages/views/locales/zh-Hans/usage.json b/packages/views/locales/zh-Hans/usage.jsonindex 9baf06d6f3..544bfc8222 100644--- a/packages/views/locales/zh-Hans/usage.json+++ b/packages/views/locales/zh-Hans/usage.json@@ -15,6 +15,11 @@"tasks_label": "任务数 · {{days}}天","tasks_hint": "失败 {{failed}} 个"},+ "dim": {+ "label": "维度",+ "daily": "按天",+ "weekly": "按周"+ },"daily": {"title_cost": "每日费用","title_tokens": "每日 Token",@@ -26,6 +31,13 @@"metric_tasks": "任务数","no_data": "所选时间范围内暂无消耗。"},+ "weekly": {+ "title_cost": "每周费用",+ "title_tokens": "每周 Token",+ "title_time": "每周运行时长",+ "title_tasks": "每周任务数",+ "partial_label": "{{range}}(未满 · 已过 {{covered}} / 7 天)"+ },"leaderboard": {"title": "排行榜","caption": "{{count}} 个智能体",diff --git a/packages/views/runtimes/components/charts/activity-heatmap.tsx b/packages/views/runtimes/components/charts/activity-heatmap.tsxindex 1a6624d58d..6625d677fc 100644--- a/packages/views/runtimes/components/charts/activity-heatmap.tsx+++ b/packages/views/runtimes/components/charts/activity-heatmap.tsx@@ -1,7 +1,7 @@import { useMemo } from "react";import type { RuntimeUsage } from "@multica/core/types";import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";-import { estimateCost } from "../../utils";+import { addDaysIso, estimateCost, todayIso, weekStartIso } from "../../utils";import { useT } from "../../../i18n";// 26 weeks (~6 months) gives the heatmap real presence in the wider chart@@ -11,8 +11,11 @@ import { useT } from "../../../i18n";const HEATMAP_WEEKS = 26;const CELL_SIZE = 16;const CELL_GAP = 3;-const DAY_LABELS = ["", "Mon", "", "Wed", "", "Fri", ""];-const WEEKDAY_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];+// Monday-first row order, matching ISO 8601 and the rest of the Weekly+// aggregation (see #MUL-2382). Rows labelled Mon / Wed / Fri keep the+// density readable.+const DAY_LABELS = ["Mon", "", "Wed", "", "Fri", "", ""];+const WEEKDAY_NAMES = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];// Cells use the brand-derived chart-1 hue with descending opacity instead// of a neutral foreground fade, so the heatmap reads as part of the same@@ -47,7 +50,13 @@ interface Insights {windowDays: number;}-export function ActivityHeatmap({ usage }: { usage: RuntimeUsage[] }) {+export function ActivityHeatmap({+ usage,+ tz,+}: {+ usage: RuntimeUsage[];+ tz: string;+}) {const { t } = useT("runtimes");// Memo dep — estimateCost (called inside the body below) consults the// user-override store, so saving a custom rate must invalidate the cells.@@ -61,22 +70,32 @@ export function ActivityHeatmap({ usage }: { usage: RuntimeUsage[] }) {dateCost.set(u.date, (dateCost.get(u.date) ?? 0) + estimateCost(u));}- const today = new Date();- const todayDay = today.getDay();- const startOffset = todayDay + (HEATMAP_WEEKS - 1) * 7;- const startDate = new Date(today);- startDate.setDate(today.getDate() - startOffset);+ // Anchor the grid on the Monday of the week containing "today" in the+ // runtime's tz, then walk back HEATMAP_WEEKS-1 weeks. All dates are+ // string-based YYYY-MM-DD so the host browser's tz can't shift a column.+ // We stop drawing cells once we pass `today` so the in-progress week is+ // partial (cells for "tomorrow onward" aren't rendered) — matches the+ // Weekly chart's partial-week treatment.+ const today = todayIso(tz);+ const lastWeekStart = weekStartIso(today);+ const startDate = addDaysIso(lastWeekStart, -(HEATMAP_WEEKS - 1) * 7);+ const todayIndex = (HEATMAP_WEEKS - 1) * 7 + ((() => {+ // Monday-based weekday of `today`: 0 = Mon ... 6 = Sun. Computed via+ // string subtraction so the host timezone can't shift the value.+ const [y, m, d] = today.split("-").map(Number);+ const dt = new Date(Date.UTC(y ?? 1970, (m ?? 1) - 1, d ?? 1));+ return (dt.getUTCDay() + 6) % 7;+ })());const allCells: {date: string;- dayOfWeek: number;+ dayOfWeek: number; // 0 = Mon ... 6 = Sunweek: number;cost: number;}[] = [];- const d = new Date(startDate);- for (let i = 0; i <= startOffset; i++) {- const dateStr = d.toISOString().slice(0, 10);- const dayOfWeek = d.getDay();+ for (let i = 0; i <= todayIndex; i++) {+ const dateStr = addDaysIso(startDate, i);+ const dayOfWeek = i % 7;const week = Math.floor(i / 7);allCells.push({date: dateStr,@@ -84,7 +103,6 @@ export function ActivityHeatmap({ usage }: { usage: RuntimeUsage[] }) {week,cost: dateCost.get(dateStr) ?? 0,});- d.setDate(d.getDate() + 1);}const nonZero = allCells.filter((c) => c.cost > 0).map((c) => c.cost);@@ -171,7 +189,7 @@ export function ActivityHeatmap({ usage }: { usage: RuntimeUsage[] }) {};return { cells: cellsWithLevel, monthLabels: months, insights };- }, [usage, pricings]);+ }, [usage, pricings, tz]);const labelWidth = 28;const svgWidth = labelWidth + HEATMAP_WEEKS * (CELL_SIZE + CELL_GAP);diff --git a/packages/views/runtimes/components/charts/hourly-activity-chart.tsx b/packages/views/runtimes/components/charts/hourly-activity-chart.tsxdeleted file mode 100644index c4061e4250..0000000000--- a/packages/views/runtimes/components/charts/hourly-activity-chart.tsx+++ /dev/null@@ -1,77 +0,0 @@-import { useMemo } from "react";-import {- BarChart,- Bar,- XAxis,- YAxis,- CartesianGrid,-} from "recharts";-import {- ChartContainer,- ChartTooltip,- ChartTooltipContent,- type ChartConfig,-} from "@multica/ui/components/ui/chart";--// Hour-of-day cost. The "WHEN" tab in the runtime detail uses this to show-// "during what hours of the day did this runtime spend money", which is-// fundamentally different from "how much per calendar day". Data is fed in-// by the parent (single orchestrator pattern) — this component is dumb.-const hourlyChartConfig = {- cost: { label: "Cost", color: "var(--color-chart-1)" },-} satisfies ChartConfig;--export interface HourlyCostPoint {- hour: number;- cost: number;-}--export function HourlyActivityChart({ data }: { data: HourlyCostPoint[] }) {- // Always render 24 buckets so the X axis is continuous. The parent passes- // pre-aggregated server data which may omit hours with zero activity;- // we fill those in with $0 here so visual gaps are intentional ("nothing- // ran at 03:00") rather than missing data.- const chartData = useMemo(() => {- const map = new Map(data.map((d) => [d.hour, d.cost]));- return Array.from({ length: 24 }, (_, i) => ({- hour: i,- label: `${i.toString().padStart(2, "0")}:00`,- cost: map.get(i) ?? 0,- }));- }, [data]);-- return (- <ChartContainer config={hourlyChartConfig} className="aspect-[3/1] w-full">- <BarChart data={chartData} margin={{ left: 0, right: 0, top: 4, bottom: 0 }}>- <CartesianGrid vertical={false} />- <XAxis- dataKey="label"- tickLine={false}- axisLine={false}- tickMargin={8}- interval={2}- fontSize={10}- />- <YAxis- tickLine={false}- axisLine={false}- tickMargin={8}- tickFormatter={(v: number) => `$${v}`}- width={40}- />- <ChartTooltip- content={- <ChartTooltipContent- formatter={(value) =>- typeof value === "number"- ? `$${value.toFixed(2)}`- : String(value)- }- />- }- />- <Bar dataKey="cost" fill="var(--color-cost)" radius={[2, 2, 0, 0]} />- </BarChart>- </ChartContainer>- );-}diff --git a/packages/views/runtimes/components/charts/index.ts b/packages/views/runtimes/components/charts/index.tsindex 3fae5d7298..cce5a345e8 100644--- a/packages/views/runtimes/components/charts/index.ts+++ b/packages/views/runtimes/components/charts/index.ts@@ -1,6 +1,9 @@export { DailyCostChart, costStackConfig } from "./daily-cost-chart";export { DailyTokensChart, tokenStackConfig } from "./daily-tokens-chart";+export { WeeklyCostChart, weeklyCostStackConfig } from "./weekly-cost-chart";+export { WeeklyTokensChart, weeklyTokenStackConfig } from "./weekly-tokens-chart";export { DailyTimeChart, type DailyTimeData } from "./daily-time-chart";export { DailyTasksChart, type DailyTasksData } from "./daily-tasks-chart";+export { WeeklyTimeChart, type WeeklyTimeData } from "./weekly-time-chart";+export { WeeklyTasksChart, type WeeklyTasksData } from "./weekly-tasks-chart";export { ActivityHeatmap } from "./activity-heatmap";-export { HourlyActivityChart } from "./hourly-activity-chart";diff --git a/packages/views/runtimes/components/charts/weekly-cost-chart.tsx b/packages/views/runtimes/components/charts/weekly-cost-chart.tsxnew file mode 100644index 0000000000..f2f76bca8f--- /dev/null+++ b/packages/views/runtimes/components/charts/weekly-cost-chart.tsx@@ -0,0 +1,108 @@+import {+ BarChart,+ Bar,+ XAxis,+ YAxis,+ CartesianGrid,+ Cell,+} from "recharts";+import {+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+ type ChartConfig,+} from "@multica/ui/components/ui/chart";+import type { WeeklyCostStackData } from "../../utils";+import { useT } from "../../../i18n";++// Same three-segment stack as DailyCostChart — keeping series, colours, and+// ordering identical so the user reads "Weekly" as a coarser cut of the same+// chart, not a different chart. Partial-week bars render at half-opacity so+// "this week is in progress" is visually obvious without a separate legend.+export const weeklyCostStackConfig = {+ input: { label: "Input", color: "var(--chart-1)" },+ output: { label: "Output", color: "var(--chart-2)" },+ cacheWrite: { label: "Cache write", color: "var(--chart-3)" },+} satisfies ChartConfig;++export function WeeklyCostChart({ data }: { data: WeeklyCostStackData[] }) {+ const { t } = useT("runtimes");+ return (+ <ChartContainer config={weeklyCostStackConfig} className="aspect-[3/1] w-full">+ <BarChart data={data} margin={{ left: 0, right: 0, top: 4, bottom: 0 }}>+ <CartesianGrid vertical={false} />+ <XAxis+ dataKey="label"+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ interval="preserveStartEnd"+ />+ <YAxis+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ tickFormatter={(v: number) => `$${v}`}+ width={50}+ />+ <ChartTooltip+ content={+ <ChartTooltipContent+ labelKey="rangeLabel"+ labelFormatter={(_label, payload) => {+ const row = payload[0]?.payload as WeeklyCostStackData | undefined;+ if (!row) return "";+ return row.partial+ ? t(($) => $.usage.weekly_partial_label, {+ range: row.rangeLabel,+ covered: row.daysCovered,+ })+ : row.rangeLabel;+ }}+ formatter={(value, name) =>+ typeof value === "number"+ ? `$${value.toFixed(2)} ${name}`+ : `${value} ${name}`+ }+ footer={(payload) => {+ const total = payload.reduce(+ (sum, item) =>+ sum + (typeof item.value === "number" ? item.value : 0),+ 0,+ );+ return (+ <div className="flex items-center justify-between gap-2 font-medium">+ <span>{t(($) => $.charts.tooltip_total)}</span>+ <span className="font-mono tabular-nums">+ ${total.toFixed(2)}+ </span>+ </div>+ );+ }}+ />+ }+ />+ <Bar dataKey="input" stackId="cost" fill="var(--color-input)">+ {data.map((d) => (+ <Cell key={d.weekStart} fillOpacity={d.partial ? 0.5 : 1} />+ ))}+ </Bar>+ <Bar dataKey="output" stackId="cost" fill="var(--color-output)">+ {data.map((d) => (+ <Cell key={d.weekStart} fillOpacity={d.partial ? 0.5 : 1} />+ ))}+ </Bar>+ <Bar+ dataKey="cacheWrite"+ stackId="cost"+ fill="var(--color-cacheWrite)"+ radius={[3, 3, 0, 0]}+ >+ {data.map((d) => (+ <Cell key={d.weekStart} fillOpacity={d.partial ? 0.5 : 1} />+ ))}+ </Bar>+ </BarChart>+ </ChartContainer>+ );+}diff --git a/packages/views/runtimes/components/charts/weekly-tasks-chart.tsx b/packages/views/runtimes/components/charts/weekly-tasks-chart.tsxnew file mode 100644index 0000000000..dcc1438827--- /dev/null+++ b/packages/views/runtimes/components/charts/weekly-tasks-chart.tsx@@ -0,0 +1,118 @@+import {+ BarChart,+ Bar,+ XAxis,+ YAxis,+ CartesianGrid,+ Cell,+} from "recharts";+import {+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+ type ChartConfig,+} from "@multica/ui/components/ui/chart";+import { useT } from "../../../i18n";++// Weekly counterpart of DailyTasksChart — same completed/failed stacked+// bar, but each bar groups a Mon–Sun calendar week. Partial-week bars at+// half opacity match WeeklyCostChart / WeeklyTokensChart so the in-progress+// week reads as visually subordinate everywhere.+const weeklyTasksChartConfig = {+ completed: { label: "Completed", color: "var(--chart-1)" },+ failed: { label: "Failed", color: "var(--chart-5)" },+} satisfies ChartConfig;++export interface WeeklyTasksData {+ weekStart: string;+ weekEnd: string;+ label: string;+ rangeLabel: string;+ partial: boolean;+ daysCovered: number;+ completed: number;+ failed: number;+}++export function WeeklyTasksChart({ data }: { data: WeeklyTasksData[] }) {+ const { t } = useT("usage");+ const { t: tRuntimes } = useT("runtimes");+ return (+ <ChartContainer+ config={weeklyTasksChartConfig}+ className="aspect-[3/1] w-full"+ >+ <BarChart data={data} margin={{ left: 0, right: 0, top: 4, bottom: 0 }}>+ <CartesianGrid vertical={false} />+ <XAxis+ dataKey="label"+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ interval="preserveStartEnd"+ />+ <YAxis+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ allowDecimals={false}+ width={40}+ />+ <ChartTooltip+ content={+ <ChartTooltipContent+ labelKey="rangeLabel"+ labelFormatter={(_label, payload) => {+ const row = payload[0]?.payload as WeeklyTasksData | undefined;+ if (!row) return "";+ return row.partial+ ? t(($) => $.weekly.partial_label, {+ range: row.rangeLabel,+ covered: row.daysCovered,+ })+ : row.rangeLabel;+ }}+ formatter={(value, name) => `${value} ${name}`}+ footer={(payload) => {+ const total = payload.reduce(+ (sum, item) =>+ sum ++ (typeof item.value === "number" ? item.value : 0),+ 0,+ );+ return (+ <div className="flex items-center justify-between gap-2 font-medium">+ <span>{tRuntimes(($) => $.charts.tooltip_total)}</span>+ <span className="font-mono tabular-nums">+ {total.toLocaleString()}+ </span>+ </div>+ );+ }}+ />+ }+ />+ <Bar+ dataKey="completed"+ stackId="tasks"+ fill="var(--color-completed)"+ radius={[0, 0, 0, 0]}+ >+ {data.map((d) => (+ <Cell key={`${d.weekStart}-c`} fillOpacity={d.partial ? 0.5 : 1} />+ ))}+ </Bar>+ <Bar+ dataKey="failed"+ stackId="tasks"+ fill="var(--color-failed)"+ radius={[3, 3, 0, 0]}+ >+ {data.map((d) => (+ <Cell key={`${d.weekStart}-f`} fillOpacity={d.partial ? 0.5 : 1} />+ ))}+ </Bar>+ </BarChart>+ </ChartContainer>+ );+}diff --git a/packages/views/runtimes/components/charts/weekly-time-chart.tsx b/packages/views/runtimes/components/charts/weekly-time-chart.tsxnew file mode 100644index 0000000000..c6f4b10a11--- /dev/null+++ b/packages/views/runtimes/components/charts/weekly-time-chart.tsx@@ -0,0 +1,100 @@+import {+ BarChart,+ Bar,+ XAxis,+ YAxis,+ CartesianGrid,+ Cell,+} from "recharts";+import {+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+ type ChartConfig,+} from "@multica/ui/components/ui/chart";+import { useT } from "../../../i18n";++// Weekly counterpart of DailyTimeChart — same single-series bar, but each+// bar represents Mon–Sun run-time totals. Partial weeks render at half+// opacity and tag their tooltip with "(partial · N / 7 days)" so the user+// can't misread an in-progress week as a sudden drop.+const weeklyTimeChartConfig = {+ totalSeconds: { label: "Run time", color: "var(--chart-1)" },+} satisfies ChartConfig;++export interface WeeklyTimeData {+ weekStart: string;+ weekEnd: string;+ label: string;+ rangeLabel: string;+ partial: boolean;+ daysCovered: number;+ totalSeconds: number;+}++export function WeeklyTimeChart({+ data,+ formatY,+ formatTooltip,+}: {+ data: WeeklyTimeData[];+ formatY: (seconds: number) => string;+ formatTooltip: (seconds: number) => string;+}) {+ const { t } = useT("usage");+ return (+ <ChartContainer+ config={weeklyTimeChartConfig}+ className="aspect-[3/1] w-full"+ >+ <BarChart data={data} margin={{ left: 0, right: 0, top: 4, bottom: 0 }}>+ <CartesianGrid vertical={false} />+ <XAxis+ dataKey="label"+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ interval="preserveStartEnd"+ />+ <YAxis+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ tickFormatter={(v: number) => formatY(v)}+ width={56}+ />+ <ChartTooltip+ content={+ <ChartTooltipContent+ labelKey="rangeLabel"+ labelFormatter={(_label, payload) => {+ const row = payload[0]?.payload as WeeklyTimeData | undefined;+ if (!row) return "";+ return row.partial+ ? t(($) => $.weekly.partial_label, {+ range: row.rangeLabel,+ covered: row.daysCovered,+ })+ : row.rangeLabel;+ }}+ formatter={(value, name) =>+ typeof value === "number"+ ? `${formatTooltip(value)} ${name}`+ : `${value} ${name}`+ }+ />+ }+ />+ <Bar+ dataKey="totalSeconds"+ fill="var(--color-totalSeconds)"+ radius={[3, 3, 0, 0]}+ >+ {data.map((d) => (+ <Cell key={d.weekStart} fillOpacity={d.partial ? 0.5 : 1} />+ ))}+ </Bar>+ </BarChart>+ </ChartContainer>+ );+}diff --git a/packages/views/runtimes/components/charts/weekly-tokens-chart.tsx b/packages/views/runtimes/components/charts/weekly-tokens-chart.tsxnew file mode 100644index 0000000000..c05cc6a2c2--- /dev/null+++ b/packages/views/runtimes/components/charts/weekly-tokens-chart.tsx@@ -0,0 +1,112 @@+import {+ BarChart,+ Bar,+ XAxis,+ YAxis,+ CartesianGrid,+ Cell,+} from "recharts";+import {+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+ type ChartConfig,+} from "@multica/ui/components/ui/chart";+import { formatTokens, type WeeklyTokenData } from "../../utils";+import { useT } from "../../../i18n";++// Mirror of DailyTokensChart's four-segment stack — same series and colours+// keep the Weekly view legible as a coarser cut of the Daily one.+export const weeklyTokenStackConfig = {+ input: { label: "Input", color: "var(--chart-1)" },+ output: { label: "Output", color: "var(--chart-2)" },+ cacheRead: { label: "Cache read", color: "var(--chart-4)" },+ cacheWrite: { label: "Cache write", color: "var(--chart-3)" },+} satisfies ChartConfig;++export function WeeklyTokensChart({ data }: { data: WeeklyTokenData[] }) {+ const { t } = useT("runtimes");+ return (+ <ChartContainer config={weeklyTokenStackConfig} className="aspect-[3/1] w-full">+ <BarChart data={data} margin={{ left: 0, right: 0, top: 4, bottom: 0 }}>+ <CartesianGrid vertical={false} />+ <XAxis+ dataKey="label"+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ interval="preserveStartEnd"+ />+ <YAxis+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ tickFormatter={(v: number) => formatTokens(v)}+ width={50}+ />+ <ChartTooltip+ content={+ <ChartTooltipContent+ labelKey="rangeLabel"+ labelFormatter={(_label, payload) => {+ const row = payload[0]?.payload as WeeklyTokenData | undefined;+ if (!row) return "";+ return row.partial+ ? t(($) => $.usage.weekly_partial_label, {+ range: row.rangeLabel,+ covered: row.daysCovered,+ })+ : row.rangeLabel;+ }}+ formatter={(value, name) =>+ typeof value === "number"+ ? `${formatTokens(value)} ${name}`+ : `${value} ${name}`+ }+ footer={(payload) => {+ const total = payload.reduce(+ (sum, item) =>+ sum + (typeof item.value === "number" ? item.value : 0),+ 0,+ );+ return (+ <div className="flex items-center justify-between gap-2 font-medium">+ <span>{t(($) => $.charts.tooltip_total)}</span>+ <span className="font-mono tabular-nums">+ {total.toLocaleString()}+ </span>+ </div>+ );+ }}+ />+ }+ />+ <Bar dataKey="input" stackId="tokens" fill="var(--color-input)">+ {data.map((d) => (+ <Cell key={d.weekStart} fillOpacity={d.partial ? 0.5 : 1} />+ ))}+ </Bar>+ <Bar dataKey="output" stackId="tokens" fill="var(--color-output)">+ {data.map((d) => (+ <Cell key={d.weekStart} fillOpacity={d.partial ? 0.5 : 1} />+ ))}+ </Bar>+ <Bar dataKey="cacheRead" stackId="tokens" fill="var(--color-cacheRead)">+ {data.map((d) => (+ <Cell key={d.weekStart} fillOpacity={d.partial ? 0.5 : 1} />+ ))}+ </Bar>+ <Bar+ dataKey="cacheWrite"+ stackId="tokens"+ fill="var(--color-cacheWrite)"+ radius={[3, 3, 0, 0]}+ >+ {data.map((d) => (+ <Cell key={d.weekStart} fillOpacity={d.partial ? 0.5 : 1} />+ ))}+ </Bar>+ </BarChart>+ </ChartContainer>+ );+}diff --git a/packages/views/runtimes/components/runtime-detail.tsx b/packages/views/runtimes/components/runtime-detail.tsxindex 0d876b6c65..df58ccaba1 100644--- a/packages/views/runtimes/components/runtime-detail.tsx+++ b/packages/views/runtimes/components/runtime-detail.tsx@@ -204,7 +204,7 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {cliVersion={cliVersion}daemonShort={daemonShort}/>- <UsageSection runtimeId={runtime.id} />+ <UsageSection runtime={runtime} /></div>{/* Right rail: serving agents + diagnostics */}diff --git a/packages/views/runtimes/components/usage-section.tsx b/packages/views/runtimes/components/usage-section.tsxindex 9f13fe74cc..5d2de96c3d 100644--- a/packages/views/runtimes/components/usage-section.tsx+++ b/packages/views/runtimes/components/usage-section.tsx@@ -7,11 +7,10 @@ import { Skeleton } from "@multica/ui/components/ui/skeleton";import { Button } from "@multica/ui/components/ui/button";import { useWorkspaceId } from "@multica/core/hooks";import { agentListOptions } from "@multica/core/workspace/queries";-import type { RuntimeUsage } from "@multica/core/types";+import type { RuntimeUsage, AgentRuntime } from "@multica/core/types";import {runtimeUsageOptions,runtimeUsageByAgentOptions,- runtimeUsageByHourOptions,} from "@multica/core/runtimes/queries";import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";import {@@ -19,11 +18,12 @@ import {estimateCost,estimateCacheSavings,aggregateByDate,+ aggregateByWeek,aggregateCostByAgent,aggregateCostByModel,- aggregateCostByHour,collectUnmappedModels,pctChange,+ sliceWindow,type CostByKey,} from "../utils";import { KpiCard } from "./shared";@@ -31,7 +31,8 @@ import { ActorAvatar } from "../../common/actor-avatar";import {DailyCostChart,DailyTokensChart,- HourlyActivityChart,+ WeeklyCostChart,+ WeeklyTokensChart,ActivityHeatmap,} from "./charts";import { CustomPricingDialog } from "./custom-pricing-dialog";@@ -40,13 +41,32 @@ import { useT } from "../../i18n";// 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 },- { label: "30d", days: 30 },- { label: "90d", days: 90 },+ { 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),+ );+}// ---------------------------------------------------------------------------// Local segmented control. shadcn's Tabs is wired for full tab pages with@@ -106,11 +126,17 @@ function fmtMoney(n: number): string {// KPI also benefits from having extra history available.// ----------------------------------------------------------------------------export function UsageSection({ runtimeId }: { runtimeId: string }) {+export function UsageSection({ runtime }: { runtime: AgentRuntime }) {const { t } = useT("runtimes");+ const runtimeId = runtime.id;+ // Tz comes from the runtime itself — the backend already buckets daily+ // rows on `start-of-day in runtime tz`, so we use the same axis for every+ // frontend window calculation. No "user timezone" option here on purpose.+ const tz = runtime.timezone;const { data: usage = [], isLoading: loading } = useQuery(runtimeUsageOptions(runtimeId, 180),);+ 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@@ -121,11 +147,23 @@ export function UsageSection({ runtimeId }: { runtimeId: string }) {if (loading) return <UsageSkeleton />;if (usage.length === 0) return <UsageEmpty />;- // Slice the cached 90-day window into the user's selected sub-window AND+ // Slice the cached 180-day window into the user's selected sub-window AND// the immediately prior window of equal length. The KPI delta ("+18% vs// prev") then compares like-for-like ranges instead of "this period vs- // all of history".- const { filtered, prevFiltered } = sliceWindow(usage, days);+ // all of history". Tz-aware so the cutoff lands on the same calendar+ // 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);@@ -140,22 +178,39 @@ export function UsageSection({ runtimeId }: { runtimeId: string }) {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- / hourly chart windows, and the cost-by aggregations. The Heatmap- tab is the only sub-view that ignores it (always shows 90d), and- its tab disables this control to telegraph that. */}- <div className="flex items-center justify-between gap-3">- <span className="text-xs uppercase tracking-wider text-muted-foreground">- {t(($) => $.usage.period_label)}- </span>- <Segmented- value={days}- onChange={setDays}- options={TIME_RANGES.map((r) => ({- label: r.label,- value: r.days,- }))}- />+ 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-xs 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-xs 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></div>{/* Pricing-gap banner. Sits above the KPI grid so a *partial* unmapping@@ -215,23 +270,23 @@ export function UsageSection({ runtimeId }: { runtimeId: string }) {/></div>- {/* Layer 2 — WHEN chart. Three tabs for three independent time- dimensions: by-date (Daily), by-hour-of-day (Hourly), by-calendar- (Heatmap). The period selector lives at the page top — this card- only owns the tab switch and chart legend. */}+ {/* 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- runtimeId={runtimeId}usage={usage}filtered={filtered}days={days}+ dim={dim}+ tz={tz}/>- {/* Layer 3 — WHO/WHAT burned the spend. By-hour was dropped — that- dimension lives in the WHEN chart now. */}+ {/* Layer 3 — WHO/WHAT burned the spend. */}<CostByBlock runtimeId={runtimeId} days={days} usage={filtered} />- {/* Layer 4 — Folded raw view. Hourly and Heatmap used to live here;- they were promoted into the WHEN chart's tabs, leaving only the+ {/* Layer 4 — Folded raw view. The Heatmap used to live here too; it+ was promoted into the WHEN chart's toggle, leaving only thebreakdown table behind. */}<FoldedRow usage={filtered} /></div>@@ -239,81 +294,69 @@ export function UsageSection({ runtimeId }: { runtimeId: string }) {}// ----------------------------------------------------------------------------// WhenChart — answers "WHEN was this runtime spending money?" along three-// independent time dimensions. Owning the tab state here (rather than-// downstream) means the period selector and chart legend can live in the-// same header row and stay in sync with whichever tab is active.+// 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.// ----------------------------------------------------------------------------type WhenTab = "daily" | "hourly" | "heatmap";+type Dim = Exclude<WhenTab, "heatmap">;type DailyMetric = "cost" | "tokens";function WhenChart({- runtimeId,usage,filtered,days,+ dim,+ tz,}: {- runtimeId: string;usage: RuntimeUsage[];filtered: RuntimeUsage[];days: TimeRange;+ dim: Dim;+ tz: string;}) {const { t } = useT("runtimes");- const [tab, setTab] = useState<WhenTab>("daily");- // Daily-tab metric toggle (Cost vs Tokens). Stored here rather than in- // DailyTab so the legend in the card header can react to the active- // metric without prop-drilling.- const [dailyMetric, setDailyMetric] = useState<DailyMetric>("cost");+ // Heatmap is the "independent" sibling — toggled here, not part of the+ // page-level dimension segmented (per the RFC).+ const [showHeatmap, setShowHeatmap] = useState(false);+ // Daily and Weekly share a Cost-vs-Tokens metric toggle.+ const [chartMetric, setChartMetric] = useState<DailyMetric>("cost");// Memo dep — the aggregates below run `estimateCost`, which now consults// the user override store. Without listing pricings here the memos cache// pre-override totals when query data hasn't changed.const pricings = useCustomPricingStore((s) => s.pricings);- // Lazy-fetch hourly cost — only needed when its tab is active. Daily and- // heatmap derive from the already-cached 90d usage prop.- const { data: byHourRows = [] } = useQuery({- ...runtimeUsageByHourOptions(runtimeId, days),- enabled: tab === "hourly",- });-const { dailyCostStack, dailyTokens } = useMemo(() => aggregateByDate(filtered),[filtered, pricings],);- const hourlyCost = useMemo(- () =>- aggregateCostByHour(byHourRows).map((row) => ({- hour: Number(row.key),- cost: row.cost,- })),- [byHourRows, pricings],+ // Weekly aggregation builds exactly N trailing calendar weeks anchored at+ // today (in the runtime tz). Buckets are pre-zeroed inside aggregateByWeek+ // so weeks with no usage render as empty bars; rows outside the window are+ // dropped. This avoids the earlier bug where slicing on a sparse 180-day+ // aggregate surfaced old populated weeks instead of in-range empty ones.+ const weekCount = Math.max(1, Math.ceil(days / 7));+ const { weeklyTokens, weeklyCostStack } = useMemo(+ () => aggregateByWeek(usage, tz, weekCount),+ [usage, tz, weekCount, pricings],);+ const metricToggleVisible = !showHeatmap;+ const legendIncludesCacheRead = !showHeatmap && chartMetric === "tokens";+return (<div className="rounded-lg border bg-card p-4"><div className="mb-3 flex flex-wrap items-center justify-between gap-3">- <div className="flex items-center gap-3">+ <div className="flex flex-wrap items-center gap-3"><h4 className="text-sm font-semibold">{t(($) => $.usage.when_title)}</h4>- <Segmented- value={tab}- onChange={setTab}- options={- [- { label: t(($) => $.usage.when_tab_daily), value: "daily" },- { label: t(($) => $.usage.when_tab_hourly), value: "hourly" },- { label: t(($) => $.usage.when_tab_heatmap), value: "heatmap" },- ] as const- }- />- {/* Cost/Tokens toggle lives next to the main tab control so all- chart-axis switches are in one place. Only meaningful on the- Daily tab — Hourly always renders cost; Heatmap has its own- caption. */}- {tab === "daily" && (+ {/* Cost / Tokens metric toggle — only meaningful when the chart+ actually has two series-types to switch between. */}+ {metricToggleVisible && (<Segmented- value={dailyMetric}- onChange={setDailyMetric}+ value={chartMetric}+ onChange={setChartMetric}options={[{ label: t(($) => $.usage.daily_metric_cost), value: "cost" },@@ -322,35 +365,51 @@ function WhenChart({}/>)}+ {/* Heatmap toggle — independent of the page-level dim segmented.+ "On" puts the card into a fixed 26-week long-view that ignores+ the period selector. */}+ <button+ type="button"+ onClick={() => setShowHeatmap((v) => !v)}+ className={`rounded-md border px-2.5 py-1 text-xs font-medium transition-colors ${+ showHeatmap+ ? "border-foreground bg-foreground text-background"+ : "border-border text-muted-foreground hover:text-foreground"+ }`}+ aria-pressed={showHeatmap}+ >+ {t(($) => $.usage.when_tab_heatmap)}+ </button></div>- {tab !== "heatmap" && (- <ChartLegend includeCacheRead={tab === "daily" && dailyMetric === "tokens"} />+ {!showHeatmap && (+ <ChartLegend includeCacheRead={legendIncludesCacheRead} />)}</div>- {/* Heatmap intentionally ignores the page period selector and always- shows the full 13-week window (a 7-day heatmap is just a row of- squares; the long view is the whole point). */}- {tab === "heatmap" && (+ {showHeatmap && (<p className="mb-2 text-center text-xs text-muted-foreground">{t(($) => $.usage.heatmap_caption)}</p>)}- {/* Stable canvas — every tab fits inside the same min-height so- switching never collapses or stretches the card vertically (and- the right-rail / lower sections never reflow as a side effect). */}<div className="min-h-[260px]">- {tab === "daily" && (+ {showHeatmap ? (+ <ActivityHeatmap usage={usage} tz={tz} />+ ) : dim === "daily" ? (<DailyTab- metric={dailyMetric}+ metric={chartMetric}costData={dailyCostStack}tokensData={dailyTokens}usage={filtered}/>+ ) : (+ <WeeklyTab+ metric={chartMetric}+ costData={weeklyCostStack}+ tokensData={weeklyTokens}+ usage={filtered}+ />)}- {tab === "hourly" && <HourlyTab data={hourlyCost} usage={filtered} />}- {tab === "heatmap" && <ActivityHeatmap usage={usage} />}</div></div>);@@ -383,16 +442,28 @@ function DailyTab({return <DailyCostChart data={costData} />;}-function HourlyTab({- data,+function WeeklyTab({+ metric,+ costData,+ tokensData,usage,}: {- data: { hour: number; cost: number }[];+ metric: DailyMetric;+ costData: Parameters<typeof WeeklyCostChart>[0]["data"];+ tokensData: Parameters<typeof WeeklyTokensChart>[0]["data"];usage: RuntimeUsage[];}) {- const totalCost = data.reduce((s, d) => s + d.cost, 0);+ if (metric === "tokens") {+ const totalTokens = tokensData.reduce(+ (s, d) => s + d.input + d.output + d.cacheRead + d.cacheWrite,+ 0,+ );+ if (totalTokens === 0) return <EmptyChartState usage={usage} />;+ return <WeeklyTokensChart data={tokensData} />;+ }+ const totalCost = costData.reduce((s, d) => s + d.total, 0);if (totalCost === 0) return <EmptyChartState usage={usage} />;- return <HourlyActivityChart data={data} />;+ return <WeeklyCostChart data={costData} />;}// ---------------------------------------------------------------------------@@ -521,9 +592,7 @@ function ChartLegend({ includeCacheRead = false }: { includeCacheRead?: boolean}// ----------------------------------------------------------------------------// Cost-by block: two-tab attribution view. By-hour was removed — that-// dimension lives in the WhenChart's "Hourly" tab, which is more legible-// as a 24-bucket bar than as a sorted list.+// Cost-by block: two-tab attribution view (by agent / by model).// ---------------------------------------------------------------------------function CostByBlock({@@ -671,8 +740,8 @@ function CostByList({// ---------------------------------------------------------------------------// Folded row — single chevron-toggle link revealing the raw breakdown-// table. Hourly distribution and Activity heatmap used to live here; both-// were promoted to WhenChart tabs, leaving only the table behind.+// table. The Activity heatmap used to live here too; it was promoted to a+// WhenChart toggle, leaving only the breakdown table behind.// ---------------------------------------------------------------------------function FoldedRow({ usage }: { usage: RuntimeUsage[] }) {@@ -776,23 +845,6 @@ function UsageEmpty() {// Helpers// ----------------------------------------------------------------------------function sliceWindow(usage: RuntimeUsage[], days: number) {- const now = new Date();- const cutoffCurrent = new Date(now);- cutoffCurrent.setDate(cutoffCurrent.getDate() - days);- const cutoffPrev = new Date(now);- cutoffPrev.setDate(cutoffPrev.getDate() - days * 2);- const isoCurrent = cutoffCurrent.toISOString().slice(0, 10);- const isoPrev = cutoffPrev.toISOString().slice(0, 10);-- return {- filtered: usage.filter((u) => u.date >= isoCurrent),- prevFiltered: usage.filter(- (u) => u.date >= isoPrev && u.date < isoCurrent,- ),- };-}-interface UsageTotals {input: number;output: number;diff --git a/packages/views/runtimes/utils.test.ts b/packages/views/runtimes/utils.test.tsindex 51d568d0cf..c8476ac5b2 100644--- a/packages/views/runtimes/utils.test.ts+++ b/packages/views/runtimes/utils.test.ts@@ -1,11 +1,17 @@-import { describe, it, expect, afterEach } from "vitest";+import { describe, it, expect, afterEach, beforeEach, vi } from "vitest";import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";+import type { RuntimeUsage } from "@multica/core/types";import {+ addDaysIso,+ aggregateByWeek,aggregateCostByModel,collectUnmappedModels,estimateCost,isModelPriced,+ sliceWindow,+ todayIso,+ weekStartIso,} from "./utils";afterEach(() => {@@ -350,3 +356,250 @@ describe("user-supplied custom pricing", () => {expect(after[0]?.cost).toBeCloseTo(2, 5);});});++// ---------------------------------------------------------------------------+// Calendar helpers + weekly aggregation. All of these run on YYYY-MM-DD+// strings (the wire shape of RuntimeUsage.date) and on a runtime-supplied+// IANA timezone — the host browser's tz should never affect the result.+// ---------------------------------------------------------------------------++describe("weekStartIso", () => {+ it("returns the Monday of the same ISO week", () => {+ // 2026-05-19 is a Tuesday → Monday is 2026-05-18.+ expect(weekStartIso("2026-05-19")).toBe("2026-05-18");+ });++ it("treats Monday as the start of its own week (idempotent)", () => {+ expect(weekStartIso("2026-05-18")).toBe("2026-05-18");+ });++ it("rolls Sunday back to the previous Monday", () => {+ // 2026-05-17 is a Sunday → Monday is 2026-05-11.+ expect(weekStartIso("2026-05-17")).toBe("2026-05-11");+ });++ it("crosses month and year boundaries", () => {+ // 2026-01-03 is a Saturday → Monday is 2025-12-29.+ expect(weekStartIso("2026-01-03")).toBe("2025-12-29");+ });+});++describe("addDaysIso", () => {+ it("adds across month boundary", () => {+ expect(addDaysIso("2026-05-30", 3)).toBe("2026-06-02");+ });++ it("subtracts across year boundary", () => {+ expect(addDaysIso("2026-01-02", -5)).toBe("2025-12-28");+ });+});++describe("todayIso", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it("uses the runtime's timezone, not the host's, to decide today", () => {+ // 2026-05-19 16:00 UTC. In Asia/Shanghai (UTC+8) it's already 2026-05-20.+ // In America/Los_Angeles (UTC-7 on this date) it's still 2026-05-19.+ vi.setSystemTime(new Date("2026-05-19T16:00:00Z"));+ expect(todayIso("Asia/Shanghai")).toBe("2026-05-20");+ expect(todayIso("America/Los_Angeles")).toBe("2026-05-19");+ expect(todayIso("UTC")).toBe("2026-05-19");+ });+});++describe("sliceWindow (timezone-aware)", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ function makeUsage(date: string): RuntimeUsage {+ return {+ runtime_id: "r",+ date,+ provider: "anthropic",+ model: "claude-sonnet-4-6",+ input_tokens: 0,+ output_tokens: 0,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ };+ }++ it("cuts the current window at today-in-tz, not today-in-host-utc", () => {+ // Host clock is 2026-05-19 23:00 UTC → still May 19 in UTC, May 20 in Shanghai.+ // A daily-usage row dated 2026-05-20 (the runtime's "today" in Shanghai)+ // should be included in the current window when tz=Asia/Shanghai.+ vi.setSystemTime(new Date("2026-05-19T23:00:00Z"));+ const usage = [+ makeUsage("2026-05-13"),+ makeUsage("2026-05-19"),+ makeUsage("2026-05-20"),+ ];+ const { filtered } = sliceWindow(usage, 7, "Asia/Shanghai");+ expect(filtered.map((u) => u.date)).toEqual([+ "2026-05-13",+ "2026-05-19",+ "2026-05-20",+ ]);+ });++ it("returns the immediately prior window of equal length", () => {+ vi.setSystemTime(new Date("2026-05-19T12:00:00Z"));+ const usage = [+ makeUsage("2026-05-01"),+ makeUsage("2026-05-08"),+ makeUsage("2026-05-15"),+ makeUsage("2026-05-19"),+ ];+ const { filtered, prevFiltered } = sliceWindow(usage, 7, "UTC");+ expect(filtered.map((u) => u.date)).toEqual(["2026-05-15", "2026-05-19"]);+ expect(prevFiltered.map((u) => u.date)).toEqual(["2026-05-08"]);+ });+});++describe("aggregateByWeek", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ function makeUsage(+ date: string,+ input: number,+ output: number,+ ): RuntimeUsage {+ return {+ runtime_id: "r",+ date,+ provider: "anthropic",+ model: "claude-sonnet-4-6",+ input_tokens: input,+ output_tokens: output,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ };+ }++ it("groups daily rows into Mon-anchored ISO weeks", () => {+ // 2026-05-24 is Sunday, so the calendar week containing "today" is+ // Mon=05-18..Sun=05-24. With weekCount=2 the window covers weeks+ // 2026-05-11 and 2026-05-18 — exactly the two weeks the rows fall in.+ vi.setSystemTime(new Date("2026-05-24T12:00:00Z"));+ // 2026-05-11 is Mon; 2026-05-17 is Sun (same week).+ // 2026-05-18 is Mon (next week).+ const rows = [+ makeUsage("2026-05-11", 1_000_000, 0),+ makeUsage("2026-05-17", 0, 1_000_000),+ makeUsage("2026-05-18", 2_000_000, 0),+ ];+ const { weeklyTokens } = aggregateByWeek(rows, "UTC", 2);+ expect(weeklyTokens).toHaveLength(2);+ expect(weeklyTokens[0]).toMatchObject({+ weekStart: "2026-05-11",+ weekEnd: "2026-05-17",+ input: 1_000_000,+ output: 1_000_000,+ partial: false,+ daysCovered: 7,+ });+ expect(weeklyTokens[1]).toMatchObject({+ weekStart: "2026-05-18",+ weekEnd: "2026-05-24",+ input: 2_000_000,+ partial: false,+ daysCovered: 7,+ });+ });++ it("flags the in-progress week as partial with days-elapsed count", () => {+ // 2026-05-20 is a Wednesday (Mon=05-18, Sun=05-24).+ vi.setSystemTime(new Date("2026-05-20T08:00:00Z"));+ const rows = [makeUsage("2026-05-18", 1_000_000, 0)];+ const { weeklyTokens } = aggregateByWeek(rows, "UTC", 1);+ expect(weeklyTokens[0]).toMatchObject({+ weekStart: "2026-05-18",+ weekEnd: "2026-05-24",+ partial: true,+ daysCovered: 3, // Mon, Tue, Wed+ });+ });++ it("sums costs per week using the model pricing table", () => {+ // 2026-05-17 sits in the calendar week of 2026-05-11..2026-05-17, so+ // weekCount=1 anchors the window on that same week.+ vi.setSystemTime(new Date("2026-05-17T12:00:00Z"));+ // 1M input × $3 + 1M output × $15 = $18 per row. Two rows in the same+ // week (Mon + Wed) → $36 weekly total.+ const rows = [+ makeUsage("2026-05-11", 1_000_000, 1_000_000),+ makeUsage("2026-05-13", 1_000_000, 1_000_000),+ ];+ const { weeklyCostStack } = aggregateByWeek(rows, "UTC", 1);+ expect(weeklyCostStack).toHaveLength(1);+ expect(weeklyCostStack[0]?.total).toBeCloseTo(36, 2);+ });++ it("emits trailing calendar weeks pinned to today, dropping older populated weeks", () => {+ // Regression for MUL-2382 weekly window scoping:+ // before the fix, aggregateByWeek built buckets only for weeks that had+ // data and the caller did `.slice(-weekCount)`. With sparse data (an old+ // populated week far outside the selected window plus an empty stretch+ // closer to today), that slice would surface the OLD populated week+ // instead of the trailing in-window weeks. The chart should now show+ // exactly the trailing calendar weeks, with the empty in-range weeks+ // present as zero-valued buckets rather than disappearing.+ vi.setSystemTime(new Date("2026-05-19T12:00:00Z"));+ // 30-day window @ 2026-05-19 → 5 trailing weeks (Mon=04-20, 04-27,+ // 05-04, 05-11, 05-18). 2026-04-13 (Mon) is one week earlier — outside+ // the window. No data in any of the 5 in-range weeks.+ const rows = [makeUsage("2026-04-13", 1_000_000, 1_000_000)];+ const { weeklyTokens, weeklyCostStack } = aggregateByWeek(rows, "UTC", 5);++ expect(weeklyTokens.map((w) => w.weekStart)).toEqual([+ "2026-04-20",+ "2026-04-27",+ "2026-05-04",+ "2026-05-11",+ "2026-05-18",+ ]);+ // Every in-range week is empty — the old populated week was dropped.+ for (const w of weeklyTokens) {+ expect(w.input).toBe(0);+ expect(w.output).toBe(0);+ expect(w.cacheRead).toBe(0);+ expect(w.cacheWrite).toBe(0);+ }+ for (const w of weeklyCostStack) {+ expect(w.total).toBe(0);+ }+ });++ it("keeps in-window weeks empty when nearby data sits inside the window", () => {+ // Sparse-but-in-range case: only the oldest in-window week has data;+ // the remaining trailing weeks must render as empty buckets, not be+ // collapsed to a single populated bar.+ vi.setSystemTime(new Date("2026-05-19T12:00:00Z"));+ const rows = [makeUsage("2026-04-22", 1_000_000, 1_000_000)]; // week of 04-20+ const { weeklyTokens } = aggregateByWeek(rows, "UTC", 5);+ expect(weeklyTokens).toHaveLength(5);+ expect(weeklyTokens[0]).toMatchObject({+ weekStart: "2026-04-20",+ input: 1_000_000,+ output: 1_000_000,+ });+ for (const w of weeklyTokens.slice(1)) {+ expect(w.input).toBe(0);+ expect(w.output).toBe(0);+ }+ });+});diff --git a/packages/views/runtimes/utils.ts b/packages/views/runtimes/utils.tsindex b7f4e19df6..098c35a44d 100644--- a/packages/views/runtimes/utils.ts+++ b/packages/views/runtimes/utils.ts@@ -1,7 +1,6 @@import type {RuntimeUsage,RuntimeUsageByAgent,- RuntimeUsageByHour,} from "@multica/core/types";import { getCustomPricing } from "@multica/core/runtimes/custom-pricing-store";@@ -353,6 +352,37 @@ export interface ModelDistribution {cost: number;}+export interface WeeklyTokenData {+ weekStart: string;+ weekEnd: string;+ // X-axis tick — Monday of the week, e.g. "May 12".+ label: string;+ // Tooltip header — inclusive range, e.g. "May 12 – May 18".+ rangeLabel: string;+ // True when `weekEnd` is in the future (today is mid-week). Surface this+ // in the chart so the bar can be drawn at reduced opacity / striped to+ // signal "don't read this as a finished week".+ partial: boolean;+ daysCovered: number;+ input: number;+ output: number;+ cacheRead: number;+ cacheWrite: number;+}++export interface WeeklyCostStackData {+ weekStart: string;+ weekEnd: string;+ label: string;+ rangeLabel: string;+ partial: boolean;+ daysCovered: number;+ input: number;+ output: number;+ cacheWrite: number;+ total: number;+}+export function aggregateByDate(usage: RuntimeUsage[]): {dailyTokens: DailyTokenData[];dailyCost: DailyCostData[];@@ -444,6 +474,210 @@ export function aggregateByDate(usage: RuntimeUsage[]): {return { dailyTokens, dailyCost, dailyCostStack, modelDist };}+// Fold daily-grain rows into ISO calendar weeks (Mon–Sun). Reuses the same+// 180-day cache the daily aggregation reads from — no extra request. The+// latest week is flagged `partial` when today (in the runtime's tz) is+// before Sunday, so the chart can render the in-progress bar at half+// opacity instead of letting the user misread "this week" as a dip.+//+// `weekCount` pins the output to exactly that many trailing calendar weeks+// ending at the week that contains today (in `tz`). Buckets are pre-zeroed,+// so sparse data — including weeks with no usage — renders as empty bars+// rather than disappearing. Rows whose week falls outside the window are+// dropped; without this guard `.slice(-weekCount)` on a sparse 180-day+// aggregate would surface old populated weeks instead of the empty+// in-range buckets the user asked for (MUL-2382 weekly window scoping).+// Accepts any row carrying `date` + token counts + the model needed for+// pricing. Both `RuntimeUsage` (runtime detail) and `DashboardUsageDaily`+// (workspace dashboard) match this shape — there's no behavioural difference,+// just slightly different surrounding fields neither aggregator cares about.+type WeeklyAggregable = Pick<+ RuntimeUsage,+ | "date"+ | "model"+ | "input_tokens"+ | "output_tokens"+ | "cache_read_tokens"+ | "cache_write_tokens"+>;++export function aggregateByWeek(+ usage: readonly WeeklyAggregable[],+ tz: string,+ weekCount: number,+): {+ weeklyTokens: WeeklyTokenData[];+ weeklyCostStack: WeeklyCostStackData[];+} {+ const count = Math.max(1, Math.floor(weekCount));+ const today = todayIso(tz);+ const currentWeekStart = weekStartIso(today);+ const firstWeekStart = addDaysIso(currentWeekStart, -(count - 1) * 7);++ type TokenAgg = Omit<WeeklyTokenData, "label" | "rangeLabel" | "partial" | "daysCovered" | "weekEnd">;+ const tokenMap = new Map<string, TokenAgg>();+ const stackMap = new Map<string, { input: number; output: number; cacheWrite: number }>();++ // Pre-seed every trailing calendar week in the window so sparse / empty+ // weeks still render as zero bars instead of being dropped.+ for (let i = 0; i < count; i++) {+ const wkStart = addDaysIso(firstWeekStart, i * 7);+ tokenMap.set(wkStart, {+ weekStart: wkStart,+ input: 0,+ output: 0,+ cacheRead: 0,+ cacheWrite: 0,+ });+ stackMap.set(wkStart, { input: 0, output: 0, cacheWrite: 0 });+ }++ for (const u of usage) {+ const wkStart = weekStartIso(u.date);+ if (wkStart < firstWeekStart || wkStart > currentWeekStart) continue;+ const tokens = tokenMap.get(wkStart);+ if (!tokens) continue;+ tokens.input += u.input_tokens;+ tokens.output += u.output_tokens;+ tokens.cacheRead += u.cache_read_tokens;+ tokens.cacheWrite += u.cache_write_tokens;++ const breakdown = estimateCostBreakdown(u);+ const stack = stackMap.get(wkStart);+ if (!stack) continue;+ stack.input += breakdown.input;+ stack.output += breakdown.output;+ stack.cacheWrite += breakdown.cacheWrite;+ }++ const decorate = (weekStart: string) => {+ const weekEnd = addDaysIso(weekStart, 6);+ const partial = today < weekEnd;+ // Inclusive count of how many days of this week have actually elapsed.+ // Sits at 7 for closed weeks, 1..6 for the current week.+ const elapsedDays = Math.min(+ 7,+ Math.max(+ 1,+ // Day index of `today` within [weekStart, weekEnd] + 1.+ diffDaysIso(weekStart, today < weekStart ? weekStart : today < weekEnd ? today : weekEnd) + 1,+ ),+ );+ return {+ weekStart,+ weekEnd,+ label: formatShortDate(weekStart),+ rangeLabel: `${formatShortDate(weekStart)} – ${formatShortDate(weekEnd)}`,+ partial,+ daysCovered: partial ? elapsedDays : 7,+ };+ };++ const weeklyTokens: WeeklyTokenData[] = [...tokenMap.values()]+ .sort((a, b) => a.weekStart.localeCompare(b.weekStart))+ .map((t) => ({ ...t, ...decorate(t.weekStart) }));++ const weeklyCostStack: WeeklyCostStackData[] = [...stackMap.entries()]+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([weekStart, s]) => {+ const round = (n: number) => Math.round(n * 100) / 100;+ const input = round(s.input);+ const output = round(s.output);+ const cacheWrite = round(s.cacheWrite);+ return {+ ...decorate(weekStart),+ input,+ output,+ cacheWrite,+ total: round(input + output + cacheWrite),+ };+ });++ return { weeklyTokens, weeklyCostStack };+}++// Slice a daily-grain usage series into the user's selected window AND the+// immediately prior window of equal length. "Today" is read in the runtime's+// timezone so the cutoff lands on the same calendar boundary the backend+// used when bucketing rows — without this the browser/runtime tz gap could+// shift the boundary by a day at the edges (#MUL-2382 sliceWindow tz bug).+export function sliceWindow(+ usage: readonly RuntimeUsage[],+ days: number,+ tz: string,+): { filtered: RuntimeUsage[]; prevFiltered: RuntimeUsage[] } {+ const today = todayIso(tz);+ const isoCurrent = addDaysIso(today, -days);+ const isoPrev = addDaysIso(today, -days * 2);+ return {+ filtered: usage.filter((u) => u.date >= isoCurrent),+ prevFiltered: usage.filter(+ (u) => u.date >= isoPrev && u.date < isoCurrent,+ ),+ };+}++function diffDaysIso(from: string, to: string): number {+ const [y1, m1, d1] = from.split("-").map(Number);+ const [y2, m2, d2] = to.split("-").map(Number);+ const a = Date.UTC(y1 ?? 1970, (m1 ?? 1) - 1, d1 ?? 1);+ const b = Date.UTC(y2 ?? 1970, (m2 ?? 1) - 1, d2 ?? 1);+ return Math.round((b - a) / 86_400_000);+}++// ---------------------------------------------------------------------------+// Calendar helpers — all date math runs on YYYY-MM-DD strings in the+// runtime's IANA timezone. The backend already groups daily usage by+// `start-of-day in runtime tz`, so we keep the entire frontend aggregation+// on the same axis (Daily / Weekly) to avoid one-day drift when the browser+// and runtime sit in different time zones.+// ---------------------------------------------------------------------------++// Today's calendar date (YYYY-MM-DD) in the given IANA timezone. `en-CA`+// gives ISO-shaped output without us having to assemble Intl parts by hand.+export function todayIso(tz: string): string {+ return new Intl.DateTimeFormat("en-CA", {+ timeZone: tz,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ }).format(new Date());+}++// Pure date arithmetic on a YYYY-MM-DD string. Uses UTC under the hood so+// DST transitions never shift the result by an hour and round to a+// neighbouring day.+export function addDaysIso(iso: string, days: number): string {+ const [y, m, d] = iso.split("-").map(Number);+ const dt = new Date(Date.UTC(y ?? 1970, (m ?? 1) - 1, d ?? 1));+ dt.setUTCDate(dt.getUTCDate() + days);+ return dt.toISOString().slice(0, 10);+}++// Monday-of-week as YYYY-MM-DD. ISO 8601 week-start, matching the heatmap+// and the team's day-to-day "this week" mental model. Pure string math —+// no `new Date()` reads — so it's stable under any host timezone.+export function weekStartIso(iso: string): string {+ const [y, m, d] = iso.split("-").map(Number);+ const dt = new Date(Date.UTC(y ?? 1970, (m ?? 1) - 1, d ?? 1));+ const day = dt.getUTCDay(); // 0 = Sun, 1 = Mon, ..., 6 = Sat+ const offset = (day + 6) % 7; // distance back to Monday+ dt.setUTCDate(dt.getUTCDate() - offset);+ return dt.toISOString().slice(0, 10);+}++// "May 12" — short, locale-aware month/day for a YYYY-MM-DD string. Parsing+// via UTC keeps the displayed day stable regardless of the browser's tz.+export function formatShortDate(iso: string): string {+ const [y, m, d] = iso.split("-").map(Number);+ const dt = new Date(Date.UTC(y ?? 1970, (m ?? 1) - 1, d ?? 1));+ return dt.toLocaleString("en", {+ month: "short",+ day: "numeric",+ timeZone: "UTC",+ });+}+// ---------------------------------------------------------------------------// Cost-by-X aggregations//@@ -496,24 +730,6 @@ export function aggregateCostByModel(rows: RuntimeUsage[]): CostByKey[] {return [...map.values()].sort((a, b) => b.cost - a.cost);}-// Per-(hour, model) rows → 24 fixed buckets (0..23). Hours with no activity-// stay in the list as empty rows so the bar chart axis stays continuous.-export function aggregateCostByHour(rows: RuntimeUsageByHour[]): CostByKey[] {- const buckets = new Map<number, CostByKey>();- for (let h = 0; h < 24; h++) {- buckets.set(h, { key: String(h), tokens: 0, cost: 0, taskCount: 0 });- }- for (const r of rows) {- const entry = buckets.get(r.hour);- if (!entry) continue;- entry.tokens +=- r.input_tokens + r.output_tokens + r.cache_read_tokens + r.cache_write_tokens;- entry.cost += estimateCost(r);- entry.taskCount += r.task_count;- }- return [...buckets.values()];-}-// "Cost · 30D" KPI hint: percentage delta vs. the immediately prior window// of equal length. Returns null when there's no comparable prior data// (caller renders nothing rather than a misleading "+∞%").