Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: token activity shows a year of quartile-shaded days, with accurate counts behind it (#14600)
Michael Han665e7a6ada83
diff --git a/studio/backend/storage/profile_stats_db.py b/studio/backend/storage/profile_stats_db.pyindex 31eef345f31..9d2777d1923 100644--- a/studio/backend/storage/profile_stats_db.py+++ b/studio/backend/storage/profile_stats_db.py@@ -205,6 +205,7 @@ class _ApiUsageFold:self.completion_tokens = 0self.total_tokens = 0self.by_day: dict[date, int] = {}+ self.requests_by_day: dict[date, int] = {}self.models: dict[str, dict[str, Any]] = {}self.requests = 0@@ -240,6 +241,7 @@ def _fold_api_usage(if stamp is not None:day = stamp.date()fold.by_day[day] = fold.by_day.get(day, 0) + total_tokens+ fold.requests_by_day[day] = fold.requests_by_day.get(day, 0) + 1model_id = _clean_str(row["model"])if on_usage is not None:@@ -260,6 +262,7 @@ def _merge_api_activity(chat: _MessageFold, api: _ApiUsageFold) -> None:for day, tokens in api.by_day.items():bucket = chat.by_day.setdefault(day, {"tokens": 0, "messages": 0, "threads": set()})bucket["tokens"] += tokens+ bucket["apiRequests"] = bucket.get("apiRequests", 0) + api.requests_by_day.get(day, 0)for model_id, api_model in api.models.items():model = chat.models.setdefault(model_id,@@ -422,7 +425,10 @@ def _fold_messages(server = metadata.get("serverTimings")server = server if isinstance(server, dict) else {}- prompt_tokens = _as_int(usage.get("promptTokens")) or _as_int(server.get("prompt_n"))+ # prompt_n is only what llama.cpp evaluated; the usage chunk's promptTokens includes the cache hits.+ prompt_tokens = _as_int(usage.get("promptTokens")) or (+ _as_int(server.get("prompt_n")) + _as_int(server.get("cache_n"))+ )completion_tokens = _as_int(usage.get("completionTokens")) or _as_int(server.get("predicted_n"))@@ -497,6 +503,7 @@ def _daily_series(fold: _MessageFold, today: date, days: int) -> list[dict[str,"tokens": int(bucket["tokens"]) if bucket else 0,"messages": int(bucket["messages"]) if bucket else 0,"chats": len(bucket["threads"]) if bucket else 0,+ "apiRequests": int(bucket.get("apiRequests", 0)) if bucket else 0,})return seriesdiff --git a/studio/backend/tests/test_profile_stats.py b/studio/backend/tests/test_profile_stats.pyindex b7ab45e14df..7fbed16042f 100644--- a/studio/backend/tests/test_profile_stats.py+++ b/studio/backend/tests/test_profile_stats.py@@ -196,6 +196,7 @@ def test_mixed_chat_and_api_usage_combines_only_activity_metrics(stats_db):"tokens": 175,"messages": 2,"chats": 1,+ "apiRequests": 1,}assert stats["peakDay"] == {"date": today.date().isoformat(), "tokens": 175}assert stats["models"][0]["id"] == "unsloth/gpt-oss-20b"@@ -1646,9 +1647,10 @@ def test_server_timings_stand_in_for_a_missing_usage_chunk(stats_db):totals = compute_profile_stats(days = 7)["totals"]- assert totals["promptTokens"] == 400+ # prompt_n is only what llama.cpp evaluated; the usage chunk it stands in for counts the cache hits too.+ assert totals["promptTokens"] == 490assert totals["completionTokens"] == 120- assert totals["totalTokens"] == 520+ assert totals["totalTokens"] == 610assert totals["cachedTokens"] == 90diff --git a/studio/frontend/src/features/profile/api/profile-stats.ts b/studio/frontend/src/features/profile/api/profile-stats.tsindex fe508dde373..fabbacfde7e 100644--- a/studio/frontend/src/features/profile/api/profile-stats.ts+++ b/studio/frontend/src/features/profile/api/profile-stats.ts@@ -10,6 +10,8 @@ export type ProfileStatsDay = {tokens: number;messages: number;chats: number;+ /** Absent from older backends. */+ apiRequests?: number;};export type ProfileStatsModel = {diff --git a/studio/frontend/src/features/profile/components/stats/token-activity-card.tsx b/studio/frontend/src/features/profile/components/stats/token-activity-card.tsxindex 09a6ba50a26..16029eda916 100644--- a/studio/frontend/src/features/profile/components/stats/token-activity-card.tsx+++ b/studio/frontend/src/features/profile/components/stats/token-activity-card.tsx@@ -17,135 +17,43 @@ import {YAxis,} from "recharts";import type { ProfileStatsDay } from "../../api/profile-stats";-import { useActivityChartStore } from "../../stores/activity-chart-store";import {+ type ActivityCell,type ActivityMode,+ type HeatLevel,type WeekChartPoint,activitySummaryForMode,+ buildActivityColumns,formatCompactNumber,+ formatFullNumber,formatProfileCount,heatLevel,+ heatThresholds,+ monthLabelColumns,parseDayKey,seriesForMode,weekChartPoints,- windowBaseline,} from "../../utils/stats-format";import { StatsCard } from "./stat-primitives";import { roundIfSingleLine } from "@/lib/tooltip-pill";const DAYS_PER_WEEK = 7;-const CELL_SIZE = 11;+const WINDOW_WEEKS = 53;+const MIN_CELL = 9;const CELL_GAP = 3;-const COLUMN_WIDTH = CELL_SIZE + CELL_GAP;const MIN_COLUMNS = 8;-const HEAT_OPACITY = [0, 0.4, 0.62, 0.8, 1] as const;-// Weekly and cumulative are on/off, so they use one flat shade.-const SOLID_LEVEL = 4;-const MODES: ActivityMode[] = ["daily", "weekly", "cumulative"];--type Cell = {- key: string;- day: ProfileStatsDay | null;- value: number;+const MONTH_LABEL_SPAN = 3;+const HEAT_OPACITY: Record<Exclude<HeatLevel, 0>, number> = {+ 1: 0.28,+ 2: 0.5,+ 3: 0.75,+ 4: 1,};+const LEGEND_LEVELS: HeatLevel[] = [0, 1, 2, 3, 4];+const MODES: ActivityMode[] = ["daily", "weekly", "cumulative"];-/**- * Trim the series to the most recent `columns` weeks, ending on a partial- * current week. The grid never scrolls, so older days fall off the left.- */-function buildColumns(- daily: ProfileStatsDay[],- values: number[],- columns: number,- mode: ActivityMode,-): Cell[][] {- if (daily.length === 0 || columns <= 0) return [];-- const lastDay = daily.at(-1);- if (!lastDay) return [];- // Days after today in the final (partial) week.- const trailing =- DAYS_PER_WEEK -- 1 -- ((parseDayKey(lastDay.date).getDay() + 6) % DAYS_PER_WEEK);- const capacity = columns * DAYS_PER_WEEK - trailing;- const start = Math.max(0, daily.length - capacity);- const visible = daily.slice(start);- // Cumulative is a running total over what the grid shows, so a narrow card- // that drops older weeks has to rebase off the last hidden day.- const baseline = windowBaseline(values, start, mode);-- const cells: Cell[] = [];- // Pad so every column is a Monday-started week.- const firstVisible = visible[0];- if (!firstVisible) return [];- const leading = (parseDayKey(firstVisible.date).getDay() + 6) % DAYS_PER_WEEK;- for (let index = 0; index < leading; index += 1) {- cells.push({ key: `pad-${index}`, day: null, value: 0 });- }- for (const [index, day] of visible.entries()) {- cells.push({- key: day.date,- day,- value: (values[start + index] ?? 0) - baseline,- });- }-- const grid: Cell[][] = [];- for (let index = 0; index < cells.length; index += DAYS_PER_WEEK) {- grid.push(cells.slice(index, index + DAYS_PER_WEEK));- }- return grid;-}--/** Month captions under the grid, one per column where the month turns over. */-function buildMonthLabels(grid: Cell[][], locale: string) {- const formatter = new Intl.DateTimeFormat(locale, { month: "short" });- const labels: Array<{ key: string; column: number; text: string }> = [];- let lastMonth = -1;- for (const [columnIndex, column] of grid.entries()) {- const firstDay = column.find((cell) => cell.day !== null)?.day;- if (!firstDay) continue;- const date = parseDayKey(firstDay.date);- if (date.getMonth() === lastMonth) continue;- lastMonth = date.getMonth();- // Skip a label that would collide with the previous one, or run off the end.- const previous = labels.at(-1);- if (previous && columnIndex - previous.column < 3) continue;- if (columnIndex > grid.length - 3) continue;- labels.push({- key: firstDay.date,- column: columnIndex,- text: formatter.format(date),- });- }- return labels;-}--/**- * Per-column totals for the bar modes. Shading every day of an active week- * instead would fill the grid solid and hide the shape.- */-function columnSummary(column: Cell[]) {- let value = 0;- let tokens = 0;- let firstDay: string | null = null;- for (const cell of column) {- if (!cell.day) continue;- value = Math.max(value, cell.value);- tokens += cell.day.tokens;- firstDay ??= cell.day.date;- }- return { value, tokens, firstDay };-}+type Cell = ActivityCell<ProfileStatsDay>;-/** Bar height in cells, at least one for any activity. */-function barHeight(value: number, peakValue: number): number {- if (value <= 0 || peakValue <= 0) return 0;- return Math.max(1, Math.round((value / peakValue) * DAYS_PER_WEEK));-}--/** How many week columns fit the card's current width. */function useVisibleColumns(maxColumns: number) {const ref = useRef<HTMLDivElement>(null);const [columns, setColumns] = useState(maxColumns);@@ -156,8 +64,7 @@ function useVisibleColumns(maxColumns: number) {const measure = () => {const width = element.clientWidth;if (width <= 0) return;- // The final column carries no trailing gap.- const fits = Math.floor((width + CELL_GAP) / COLUMN_WIDTH);+ const fits = Math.floor((width + CELL_GAP) / (MIN_CELL + CELL_GAP));setColumns(Math.max(MIN_COLUMNS, Math.min(maxColumns, fits)));};measure();@@ -169,101 +76,125 @@ function useVisibleColumns(maxColumns: number) {return { ref, columns };}-const CELL_CLASS = "size-[11px] rounded-[3px]";--function Block({- title,- tone,-}: { title: string; tone: 0 | 1 | 2 | 3 | 4 | -1 }) {+function HeatSwatch({ level, title }: { level: HeatLevel | null; title?: string }) {return (<divtitle={title}className={cn(- CELL_CLASS,- tone === -1+ "aspect-square w-full rounded-[3px]",+ level === null? "bg-transparent"- : tone === 0+ : level === 0? "bg-muted-foreground/12": "bg-primary",)}- style={- tone > 0 ? { opacity: HEAT_OPACITY[tone as 1 | 2 | 3 | 4] } : undefined- }+ style={level ? { opacity: HEAT_OPACITY[level] } : undefined}/>);}-/** Daily: each day shaded by its own volume. */-function DayColumn({- column,- peak,+function DayHeatmap({+ grid,dateFormatter,}: {- column: Cell[];- peak: number;+ grid: Cell[][];dateFormatter: Intl.DateTimeFormat;}) {const t = useT();const locale = useLocale();-- return (- <div className="flex flex-col gap-[3px]">- {column.map((cell) => {- if (!cell.day) {- return <Block key={cell.key} title="" tone={-1} />;- }- return (- <Block- key={cell.key}- tone={heatLevel(cell.value, peak)}- title={t("settings.profile.stats.cellTooltip", {- tokens: formatProfileCount(cell.day.tokens, "token", locale),- messages: formatProfileCount(- cell.day.messages,- "message",- locale,- ),- date: dateFormatter.format(parseDayKey(cell.day.date)),- })}- />- );- })}- </div>+ const thresholds = useMemo(+ () => heatThresholds(grid.flat().map((cell) => cell.day?.tokens ?? 0)),+ [grid],);-}--/** Weekly and cumulative: one flat bar per column, anchored to the bottom. */-function BarColumn({- column,- peak,- dateFormatter,-}: {- column: Cell[];- peak: number;- dateFormatter: Intl.DateTimeFormat;-}) {- const t = useT();- const locale = useLocale();- const summary = columnSummary(column);- const height = barHeight(summary.value, peak);- // The bar is scaled by summary.value, which in cumulative mode is the- // running total. The tooltip says "week of", so it reports that week.- const title = summary.firstDay- ? t("settings.profile.stats.weekTooltip", {- date: dateFormatter.format(parseDayKey(summary.firstDay)),- tokens: formatProfileCount(summary.tokens, "token", locale),- })- : "";+ const monthFormatter = useMemo(+ () => new Intl.DateTimeFormat(locale, { month: "short" }),+ [locale],+ );+ const months = useMemo(() => monthLabelColumns(grid), [grid]);+ const dayActivity = (day: ProfileStatsDay) => {+ const parts: string[] = [];+ if (day.messages > 0 || !day.apiRequests) {+ parts.push(formatProfileCount(day.messages, "message", locale));+ }+ if (day.apiRequests) {+ parts.push(+ t("settings.profile.stats.apiRequests", {+ count: formatFullNumber(day.apiRequests, locale),+ }),+ );+ }+ return parts.join(", ");+ };+ const columnTemplate = `repeat(${grid.length}, minmax(0, 1fr))`;return (- <div className="flex flex-col gap-[3px]">- {Array.from({ length: DAYS_PER_WEEK }, (_, row) => (- <Block- key={column[row]?.key ?? `slot-${row}`}- title={title}- tone={row >= DAYS_PER_WEEK - height ? SOLID_LEVEL : 0}- />- ))}+ <div className="flex flex-col gap-2">+ <div+ className="grid grid-flow-col"+ style={{+ gridTemplateColumns: columnTemplate,+ gridTemplateRows: `repeat(${DAYS_PER_WEEK}, auto)`,+ gap: CELL_GAP,+ }}+ >+ {grid.flatMap((column) =>+ column.map((cell) =>+ cell.day ? (+ <HeatSwatch+ key={cell.key}+ level={heatLevel(cell.day.tokens, thresholds)}+ title={+ cell.day.tokens > 0+ ? t("settings.profile.stats.cellTooltip", {+ tokens: formatProfileCount(cell.day.tokens, "token", locale),+ messages: dayActivity(cell.day),+ date: dateFormatter.format(parseDayKey(cell.day.date)),+ })+ : t("settings.profile.stats.emptyDayTooltip", {+ date: dateFormatter.format(parseDayKey(cell.day.date)),+ })+ }+ />+ ) : (+ <HeatSwatch key={`${column[0]?.key}-${cell.key}`} level={null} />+ ),+ ),+ )}+ </div>+ {/* Same columns as the squares, so a month sits under the week its 1st falls in. One that+ starts in the last weeks ends flush with the grid instead of adding columns past it. */}+ <div+ className="grid text-ui-11 text-muted-foreground"+ style={{ gridTemplateColumns: columnTemplate, columnGap: CELL_GAP }}+ >+ {months.map((month) => {+ const tail = month.column > grid.length - MONTH_LABEL_SPAN;+ return (+ <span+ key={month.date}+ className="whitespace-nowrap"+ style={{+ gridRow: 1,+ gridColumn: tail+ ? `${Math.max(1, grid.length - MONTH_LABEL_SPAN + 1)} / -1`+ : `${month.column + 1} / span ${MONTH_LABEL_SPAN}`,+ justifySelf: tail ? "end" : "start",+ }}+ >+ {monthFormatter.format(parseDayKey(month.date))}+ </span>+ );+ })}+ </div>+ <div className="flex items-center justify-end gap-1.5 text-ui-11 text-muted-foreground">+ <span>{t("settings.profile.stats.less")}</span>+ {LEGEND_LEVELS.map((level) => (+ <div key={level} className="size-[11px]">+ <HeatSwatch level={level} />+ </div>+ ))}+ <span>{t("settings.profile.stats.more")}</span>+ </div></div>);}@@ -272,7 +203,6 @@ const WEEK_CHART_CONFIG = {tokens: { color: "var(--primary)" },} satisfies ChartConfig;-/** Opt-in view: Weekly as bars, Cumulative as a line, on labelled token and date axes. */function WeekChart({grid,mode,@@ -323,10 +253,15 @@ function WeekChart({}return (<div ref={roundIfSingleLine} className="tooltip-compact">- {t("settings.profile.stats.weekTooltip", {- date: dateFormatter.format(parseDayKey(point.week)),- tokens: formatProfileCount(point.tokens, "token", locale),- })}+ {t(+ mode === "weekly"+ ? "settings.profile.stats.weekTooltip"+ : "settings.profile.stats.cumulativeTooltip",+ {+ date: dateFormatter.format(parseDayKey(point.week)),+ tokens: formatProfileCount(point.tokens, "token", locale),+ },+ )}</div>);}}@@ -337,7 +272,7 @@ function WeekChart({return (<ChartContainerconfig={WEEK_CHART_CONFIG}- className="h-[calc(140px*var(--ui-space-scale,1))] w-full"+ className="h-[calc(160px*var(--ui-space-scale,1))] w-full">{mode === "weekly" ? (<BarChart data={data} margin={margin} accessibilityLayer={true}>@@ -377,51 +312,38 @@ export function TokenActivityCard({ daily }: { daily: ProfileStatsDay[] }) {const t = useT();const pillId = useId();const [mode, setMode] = useState<ActivityMode>("daily");- const maxColumns = Math.ceil(daily.length / DAYS_PER_WEEK) + 1;+ const maxColumns = Math.min(+ WINDOW_WEEKS,+ Math.ceil(daily.length / DAYS_PER_WEEK) + 1,+ );const { ref, columns } = useVisibleColumns(maxColumns);- const shaded = mode === "daily";- const showChart = useActivityChartStore((state) => state.showChart);- const setShowChart = useActivityChartStore((state) => state.setShowChart);- const charted = !shaded && showChart;const values = useMemo(() => seriesForMode(daily, mode), [daily, mode]);const grid = useMemo(- () => buildColumns(daily, values, columns, mode),+ () => buildActivityColumns(daily, values, columns, mode),[daily, values, columns, mode],);// The app language, not the browser's: those differ whenever the user picks// a language in Settings, and it has to be a dependency so switching while// the panel is open rebuilds the formatters.const locale = useLocale();- const monthLabels = useMemo(- () => buildMonthLabels(grid, locale),- [grid, locale],- );- // Daily scales against the busiest day, the bar modes against the busiest- // column, so a full-height bar always means the peak week.- const peak = useMemo(- () =>- shaded- ? grid.reduce(- (max, column) =>- column.reduce(- (best, cell) => Math.max(best, cell.day?.tokens ?? 0),- max,- ),- 0,- )- : grid.reduce(- (max, column) => Math.max(max, columnSummary(column).value),- 0,- ),- [grid, shaded],- );const summaryTotal = useMemo(() => activitySummaryForMode(grid, mode),[grid, mode],);+ const firstShown = grid[0]?.find((cell) => cell.day !== null)?.day?.date;const dateFormatter = useMemo(+ () =>+ new Intl.DateTimeFormat(locale, {+ weekday: "short",+ month: "short",+ day: "numeric",+ year: "numeric",+ }),+ [locale],+ );+ const sinceFormatter = useMemo(() =>new Intl.DateTimeFormat(locale, {month: "short",@@ -441,90 +363,35 @@ export function TokenActivityCard({ daily }: { daily: ProfileStatsDay[] }) {locale,formatCompactNumber(summaryTotal, locale),),- weeks: formatProfileCount(grid.length, "week", locale),+ since: firstShown ? sinceFormatter.format(parseDayKey(firstShown)) : "",})}action={- <div className="flex flex-wrap items-center justify-end gap-2">- {shaded ? null : (- <div className="hub-tab-toggle inline-flex h-8 w-fit items-center rounded-full">- <button- type="button"- onClick={() => setShowChart(!showChart)}- aria-pressed={showChart}- title={t("settings.profile.stats.chartToggleHint")}- className={cn(- "inline-flex h-8 items-center rounded-full px-3 text-ui-13 font-medium transition-colors",- showChart- ? "hub-tab-toggle-pill text-foreground"- : "text-muted-foreground hover:text-foreground",- )}- >- {t("settings.profile.stats.chartToggle")}- </button>- </div>- )}- <div className="hub-tab-toggle inline-flex h-8 w-fit items-center rounded-full">- {MODES.map((option) => (- <button- key={option}- type="button"- onClick={() => setMode(option)}- aria-pressed={mode === option}- className={cn(- "relative inline-flex h-8 items-center rounded-full px-3 text-ui-13 font-medium transition-colors",- mode === option- ? "text-foreground"- : "text-muted-foreground hover:text-foreground",- )}- >- {mode === option && (- <SegmentedPill group={`${pillId}-mode`} />- )}- {t(`settings.profile.stats.mode.${option}`)}- </button>- ))}- </div>+ <div className="hub-tab-toggle inline-flex h-8 w-fit items-center rounded-full">+ {MODES.map((option) => (+ <button+ key={option}+ type="button"+ onClick={() => setMode(option)}+ aria-pressed={mode === option}+ className={cn(+ "relative inline-flex h-8 items-center rounded-full px-3 text-ui-13 font-medium transition-colors",+ mode === option+ ? "text-foreground"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {mode === option && <SegmentedPill group={`${pillId}-mode`} />}+ {t(`settings.profile.stats.mode.${option}`)}+ </button>+ ))}</div>}>- {/* Measured, never scrolled: the grid is trimmed to fit instead. */}- <div ref={ref} className="w-full overflow-hidden">- {charted ? (- <WeekChart grid={grid} mode={mode} dateFormatter={dateFormatter} />+ <div ref={ref} className="w-full">+ {mode === "daily" ? (+ <DayHeatmap grid={grid} dateFormatter={dateFormatter} />) : (- <>- <div className="flex gap-[3px]">- {grid.map((column) =>- shaded ? (- <DayColumn- key={column[0]?.key ?? "column"}- column={column}- peak={peak}- dateFormatter={dateFormatter}- />- ) : (- <BarColumn- key={column[0]?.key ?? "column"}- column={column}- peak={peak}- dateFormatter={dateFormatter}- />- ),- )}- </div>-- <div className="relative mt-2 h-4">- {monthLabels.map((label) => (- <span- key={label.key}- className="absolute top-0 text-ui-11 text-muted-foreground"- style={{ left: `${label.column * COLUMN_WIDTH}px` }}- >- {label.text}- </span>- ))}- </div>- </>+ <WeekChart grid={grid} mode={mode} dateFormatter={sinceFormatter} />)}</div></StatsCard>diff --git a/studio/frontend/src/features/profile/stores/activity-chart-store.ts b/studio/frontend/src/features/profile/stores/activity-chart-store.tsdeleted file mode 100644index 85e53bdba57..00000000000--- a/studio/frontend/src/features/profile/stores/activity-chart-store.ts+++ /dev/null@@ -1,23 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0--import { create } from "zustand";-import { persist } from "zustand/middleware";--export const ACTIVITY_CHART_STORAGE_KEY = "unsloth_profile_activity_chart";--interface ActivityChartState {- showChart: boolean;- setShowChart: (showChart: boolean) => void;-}--/** Opt-in: Weekly and Cumulative keep the block grid until the user picks Chart. */-export const useActivityChartStore = create<ActivityChartState>()(- persist(- (set) => ({- showChart: false,- setShowChart: (showChart) => set({ showChart }),- }),- { name: ACTIVITY_CHART_STORAGE_KEY },- ),-);diff --git a/studio/frontend/src/features/profile/utils/stats-format.ts b/studio/frontend/src/features/profile/utils/stats-format.tsindex 44ef42d9f5d..f5ef6106d55 100644--- a/studio/frontend/src/features/profile/utils/stats-format.ts+++ b/studio/frontend/src/features/profile/utils/stats-format.ts@@ -300,20 +300,89 @@ export function formatMilliseconds(ms: number): string {return `${(ms / 1000).toFixed(1)}s`;}-/**- * Bucket a day's tokens into one of five heatmap intensities (0 = empty).- * Thresholds are relative to the busiest day so any usage scale looks alive.- */-export function heatLevel(tokens: number, peak: number): 0 | 1 | 2 | 3 | 4 {+export type HeatLevel = 0 | 1 | 2 | 3 | 4;++/** Quartiles of the active days, not ratios to the peak: one outlier washed out every other day. */+export function heatThresholds(values: readonly number[]): [number, number, number] {+ const active = values.filter((value) => value > 0).sort((a, b) => a - b);+ if (active.length === 0) return [0, 0, 0];+ const at = (fraction: number) =>+ active[Math.min(active.length - 1, Math.floor(fraction * active.length))] ?? 0;+ return [at(0.25), at(0.5), at(0.75)];+}++/** A day's shade, 0 for none. Days at a shared quartile (a lone day, days all alike) take the strongest. */+export function heatLevel(+ tokens: number,+ thresholds: readonly [number, number, number],+): HeatLevel {if (tokens <= 0) return 0;- if (peak <= 0) return 1;- const ratio = tokens / peak;- if (ratio > 0.6) return 4;- if (ratio > 0.3) return 3;- if (ratio > 0.1) return 2;+ const [q1, q2, q3] = thresholds;+ if (tokens > q3 || (q1 === q3 && tokens >= q3)) return 4;+ if (tokens > q2) return 3;+ if (tokens > q1) return 2;return 1;}+export type ActivityCell<Day> = { key: string; day: Day | null; value: number };++/** The latest `columns` Monday-started weeks; days after today stay `null`. */+export function buildActivityColumns<Day extends { date: string }>(+ daily: readonly Day[],+ values: readonly number[],+ columns: number,+ mode: ActivityMode,+): ActivityCell<Day>[][] {+ const lastDay = daily.at(-1);+ if (!lastDay || columns <= 0) return [];+ const trailing = DAYS_PER_WEEK - 1 - mondayIndex(lastDay.date);+ const capacity = columns * DAYS_PER_WEEK - trailing;+ const start = Math.max(0, daily.length - capacity);+ const visible = daily.slice(start);+ const firstVisible = visible[0];+ if (!firstVisible) return [];+ const baseline = windowBaseline([...values], start, mode);++ const cells: ActivityCell<Day>[] = [];+ for (let index = 0; index < mondayIndex(firstVisible.date); index += 1) {+ cells.push({ key: `pad-${index}`, day: null, value: 0 });+ }+ for (const [index, day] of visible.entries()) {+ cells.push({ key: day.date, day, value: (values[start + index] ?? 0) - baseline });+ }+ for (let index = 0; index < trailing; index += 1) {+ cells.push({ key: `after-${index}`, day: null, value: 0 });+ }+ const grid: ActivityCell<Day>[][] = [];+ for (let index = 0; index < cells.length; index += DAYS_PER_WEEK) {+ grid.push(cells.slice(index, index + DAYS_PER_WEEK));+ }+ return grid;+}++const DAYS_PER_WEEK = 7;++/** 0 for Monday through 6 for Sunday. */+function mondayIndex(dayKey: string): number {+ return (parseDayKey(dayKey).getDay() + 6) % DAYS_PER_WEEK;+}++/** One label per shown 1st; a leading partial month yields to it, never the reverse (lost Jan). */+export function monthLabelColumns(+ grid: ReadonlyArray<ReadonlyArray<{ day: { date: string } | null }>>,+): Array<{ column: number; date: string }> {+ const labels: Array<{ column: number; date: string }> = [];+ for (const [column, week] of grid.entries()) {+ const first = week.find((cell) => cell.day?.date.endsWith("-01"))?.day;+ if (first) labels.push({ column, date: first.date });+ }+ const leading = grid[0]?.find((cell) => cell.day !== null)?.day;+ if (leading && labels[0]?.column !== 0 && (labels[0]?.column ?? Number.POSITIVE_INFINITY) >= 3) {+ labels.unshift({ column: 0, date: leading.date });+ }+ return labels;+}+/** Local YYYY-MM-DD, matching the backend's day keys (which use local time). */export function toLocalDayKey(date: Date): string {const year = date.getFullYear();diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 740f3e569ce..a304b7d2d8b 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -2065,9 +2065,9 @@ export const ar = {longestStreak: "أطول تتابع",activityTitle: "نشاط التوكنات",activityDescription: {- daily: "{total} خلال آخر {weeks}",- weekly: "أسبوع الذروة {total} · آخر {weeks}",- cumulative: "{total} متراكمة خلال آخر {weeks}",+ daily: "{total} منذ {since}",+ weekly: "أكثر أسبوع نشاطا {total} · منذ {since}",+ cumulative: "{total} إجمالا منذ {since}",},mode: {daily: "يومي",@@ -2076,8 +2076,9 @@ export const ar = {},cellTooltip: "{date} · {tokens}، {messages}",weekTooltip: "أسبوع {date} · {tokens}",- chartToggle: "مخطط",- chartToggleHint: "عرض الأسبوعي والتراكمي كمخطط بمحاور معنونة",+ emptyDayTooltip: "{date} · لا نشاط",+ apiRequests: "{count} عبر API",+ cumulativeTooltip: "حتى أسبوع {date} · {tokens} إجمالا",less: "أقل",more: "أكثر",insightsTitle: "تحليل النشاط",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 64c202ecb73..ddfbe50e875 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -2094,9 +2094,9 @@ export const de = {longestStreak: "Längste Serie",activityTitle: "Token-Aktivität",activityDescription: {- daily: "Zeitraum: {weeks} · {total}",- weekly: "Spitzenwoche {total} · letzte {weeks}",- cumulative: "{total} kumuliert in den letzten {weeks}",+ daily: "{total} seit {since}",+ weekly: "Aktivste Woche {total} · seit {since}",+ cumulative: "{total} insgesamt seit {since}",},mode: {daily: "Täglich",@@ -2105,8 +2105,9 @@ export const de = {},cellTooltip: "{date} · {tokens}, {messages}",weekTooltip: "Woche vom {date} · {tokens}",- chartToggle: "Diagramm",- chartToggleHint: "Wöchentlich und Kumuliert als Diagramm mit beschrifteten Achsen anzeigen",+ emptyDayTooltip: "{date} · Keine Aktivität",+ apiRequests: "{count} über die API",+ cumulativeTooltip: "Bis zur Woche vom {date} · {tokens} insgesamt",less: "Weniger",more: "Mehr",insightsTitle: "Aktivitätsauswertung",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 7d057001d5c..21f9bb4593c 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -2128,9 +2128,9 @@ export const en = {longestStreak: "Longest streak",activityTitle: "Token activity",activityDescription: {- daily: "{total} over the last {weeks}",- weekly: "Peak week {total} · last {weeks}",- cumulative: "{total} accumulated over the last {weeks}",+ daily: "{total} since {since}",+ weekly: "Busiest week {total} · since {since}",+ cumulative: "{total} in total since {since}",},mode: {daily: "Daily",@@ -2138,9 +2138,10 @@ export const en = {cumulative: "Cumulative",},cellTooltip: "{date} · {tokens}, {messages}",+ emptyDayTooltip: "{date} · No activity",+ apiRequests: "{count} via API",weekTooltip: "Week of {date} · {tokens}",- chartToggle: "Chart",- chartToggleHint: "Show Weekly and Cumulative as a chart with labelled axes",+ cumulativeTooltip: "By the week of {date} · {tokens} in total",less: "Less",more: "More",insightsTitle: "Activity insights",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex c0300801c7a..1fa5f5812f9 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -2089,9 +2089,9 @@ export const es = {longestStreak: "Racha más larga",activityTitle: "Actividad de tokens",activityDescription: {- daily: "Período: {weeks} · {total}",- weekly: "Semana pico {total} · últimas {weeks}",- cumulative: "{total} acumulados en las últimas {weeks}",+ daily: "{total} desde el {since}",+ weekly: "Semana más activa {total} · desde el {since}",+ cumulative: "{total} en total desde el {since}",},mode: {daily: "Diaria",@@ -2100,8 +2100,9 @@ export const es = {},cellTooltip: "{date} · {tokens}, {messages}",weekTooltip: "Semana del {date} · {tokens}",- chartToggle: "Gráfico",- chartToggleHint: "Mostrar Semanal y Acumulada como gráfico con ejes etiquetados",+ emptyDayTooltip: "{date} · Sin actividad",+ apiRequests: "{count} vía API",+ cumulativeTooltip: "Hasta la semana del {date} · {tokens} en total",less: "Menos",more: "Más",insightsTitle: "Análisis de actividad",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 05728314883..41bf4d7d3da 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -2093,9 +2093,9 @@ export const fr = {longestStreak: "Plus longue série",activityTitle: "Activité en tokens",activityDescription: {- daily: "{total} au cours des {weeks} dernières",- weekly: "Semaine record {total} · {weeks} dernières",- cumulative: "{total} cumulés sur les {weeks} dernières",+ daily: "{total} depuis le {since}",+ weekly: "Semaine la plus active {total} · depuis le {since}",+ cumulative: "{total} au total depuis le {since}",},mode: {daily: "Quotidienne",@@ -2104,8 +2104,9 @@ export const fr = {},cellTooltip: "{date} · {tokens}, {messages}",weekTooltip: "Semaine du {date} · {tokens}",- chartToggle: "Graphique",- chartToggleHint: "Afficher Hebdomadaire et Cumulée sous forme de graphique avec axes légendés",+ emptyDayTooltip: "{date} · Aucune activité",+ apiRequests: "{count} via l'API",+ cumulativeTooltip: "Jusqu'à la semaine du {date} · {tokens} au total",less: "Moins",more: "Plus",insightsTitle: "Analyse de l'activité",diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex e901edbc598..ffa016cc1cd 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -2161,9 +2161,9 @@ export const he = {longestStreak: "רצף שיא",activityTitle: "פעילות טוקנים",activityDescription: {- daily: "{total} במהלך {weeks} האחרונים",- weekly: "שבוע שיא: {total} · {weeks} אחרונים",- cumulative: "{total} נצברו במהלך {weeks} האחרונים",+ daily: "{total} מאז {since}",+ weekly: "השבוע העמוס ביותר {total} · מאז {since}",+ cumulative: "{total} בסך הכול מאז {since}",},mode: {daily: "יומי",@@ -2172,8 +2172,9 @@ export const he = {},cellTooltip: "{date} · {tokens}, {messages}",weekTooltip: "שבוע של {date} · {tokens}",- chartToggle: "תרשים",- chartToggleHint: "הצגת שבועי ומצטבר כתרשים עם צירים מסומנים",+ emptyDayTooltip: "{date} · אין פעילות",+ apiRequests: "{count} דרך API",+ cumulativeTooltip: "עד שבוע {date} · {tokens} בסך הכול",less: "פחות",more: "יותר",insightsTitle: "תובנות פעילות",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 980b5096d36..abdea3175d6 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -2071,9 +2071,9 @@ export const hi = {longestStreak: "सबसे लंबी स्ट्रीक",activityTitle: "टोकन गतिविधि",activityDescription: {- daily: "अवधि: {weeks} · {total}",- weekly: "सबसे व्यस्त सप्ताह {total} · पिछले {weeks}",- cumulative: "पिछले {weeks} में कुल {total}",+ daily: "{since} से {total}",+ weekly: "सबसे व्यस्त सप्ताह {total} · {since} से",+ cumulative: "{since} से कुल {total}",},mode: {daily: "दैनिक",@@ -2082,8 +2082,9 @@ export const hi = {},cellTooltip: "{date} · {tokens}, {messages}",weekTooltip: "{date} वाला हफ़्ता · {tokens}",- chartToggle: "चार्ट",- chartToggleHint: "साप्ताहिक और संचयी को लेबल वाले अक्षों के साथ चार्ट के रूप में दिखाएँ",+ emptyDayTooltip: "{date} · कोई गतिविधि नहीं",+ apiRequests: "API से {count}",+ cumulativeTooltip: "{date} के सप्ताह तक · कुल {tokens}",less: "कम",more: "ज़्यादा",insightsTitle: "गतिविधि विश्लेषण",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 0d73c8119fb..85f141f4047 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -1998,9 +1998,9 @@ export const it = {longestStreak: "Serie più lunga",activityTitle: "Attività in token",activityDescription: {- daily: "Periodo: {weeks} · {total}",- weekly: "Settimana di punta {total} · ultime {weeks}",- cumulative: "{total} accumulati nelle ultime {weeks}",+ daily: "{total} dal {since}",+ weekly: "Settimana più attiva {total} · dal {since}",+ cumulative: "{total} in totale dal {since}",},mode: {daily: "Giornaliera",@@ -2009,8 +2009,9 @@ export const it = {},cellTooltip: "{date} · {tokens}, {messages}",weekTooltip: "Settimana del {date} · {tokens}",- chartToggle: "Grafico",- chartToggleHint: "Mostra Settimanale e Cumulativa come grafico con assi etichettati",+ emptyDayTooltip: "{date} · Nessuna attività",+ apiRequests: "{count} tramite API",+ cumulativeTooltip: "Fino alla settimana del {date} · {tokens} in totale",less: "Meno",more: "Più",insightsTitle: "Analisi dell'attività",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 4bbd8285540..e9c7cf182c0 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -2046,9 +2046,9 @@ export const ja = {longestStreak: "最長の連続日数",activityTitle: "トークンの推移",activityDescription: {- daily: "直近{weeks}で{total}",- weekly: "ピーク週 {total} · 直近{weeks}",- cumulative: "直近{weeks}で累計{total}",+ daily: "{since}以降 {total}",+ weekly: "最も多い週 {total} · {since}以降",+ cumulative: "{since}以降の累計 {total}",},mode: {daily: "日次",@@ -2057,8 +2057,9 @@ export const ja = {},cellTooltip: "{date} · {tokens}、{messages}",weekTooltip: "{date} の週 · {tokens}",- chartToggle: "グラフ",- chartToggleHint: "週次と累計を軸ラベル付きのグラフで表示",+ emptyDayTooltip: "{date} · アクティビティなし",+ apiRequests: "API経由 {count}",+ cumulativeTooltip: "{date}の週まで · 累計 {tokens}",less: "少ない",more: "多い",insightsTitle: "アクティビティの分析",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 357afd667f7..588384c7cce 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -2059,9 +2059,9 @@ export const ko = {longestStreak: "최장 연속 기록",activityTitle: "토큰 활동",activityDescription: {- daily: "최근 {weeks} 동안 {total}",- weekly: "최고 주 {total} · 최근 {weeks}",- cumulative: "최근 {weeks} 동안 누적 {total}",+ daily: "{since} 이후 {total}",+ weekly: "가장 많은 주 {total} · {since} 이후",+ cumulative: "{since} 이후 누적 {total}",},mode: {daily: "일별",@@ -2070,8 +2070,9 @@ export const ko = {},cellTooltip: "{date} · {tokens}, {messages}",weekTooltip: "{date} 주간 · {tokens}",- chartToggle: "차트",- chartToggleHint: "주별 및 누적을 축 레이블이 있는 차트로 표시",+ emptyDayTooltip: "{date} · 활동 없음",+ apiRequests: "API로 {count}건",+ cumulativeTooltip: "{date} 주까지 · 누적 {tokens}",less: "적음",more: "많음",insightsTitle: "활동 분석",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 90f156238b7..40fa434ba54 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -2081,9 +2081,9 @@ export const ptBR = {longestStreak: "Maior sequência",activityTitle: "Atividade de tokens",activityDescription: {- daily: "Período: {weeks} · {total}",- weekly: "Semana de pico {total} · últimas {weeks}",- cumulative: "{total} acumulados nas últimas {weeks}",+ daily: "{total} desde {since}",+ weekly: "Semana mais ativa {total} · desde {since}",+ cumulative: "{total} no total desde {since}",},mode: {daily: "Diária",@@ -2092,8 +2092,9 @@ export const ptBR = {},cellTooltip: "{date} · {tokens}, {messages}",weekTooltip: "Semana de {date} · {tokens}",- chartToggle: "Gráfico",- chartToggleHint: "Mostrar Semanal e Acumulada como gráfico com eixos rotulados",+ emptyDayTooltip: "{date} · Sem atividade",+ apiRequests: "{count} via API",+ cumulativeTooltip: "Até a semana de {date} · {tokens} no total",less: "Menos",more: "Mais",insightsTitle: "Análise de atividade",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex b827b64ec0b..7f440bb3bf5 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -2075,9 +2075,9 @@ export const ru = {longestStreak: "Самая длинная серия",activityTitle: "Активность по токенам",activityDescription: {- daily: "Период: {weeks} · {total}",- weekly: "Пиковая неделя {total} · последние {weeks}",- cumulative: "{total} накоплено за последние {weeks}",+ daily: "{total} с {since}",+ weekly: "Самая активная неделя {total} · с {since}",+ cumulative: "Всего {total} с {since}",},mode: {daily: "По дням",@@ -2086,8 +2086,9 @@ export const ru = {},cellTooltip: "{date} · {tokens}, {messages}",weekTooltip: "Неделя с {date} · {tokens}",- chartToggle: "График",- chartToggleHint: "Показывать режимы «По неделям» и «Накопительно» графиком с подписанными осями",+ emptyDayTooltip: "{date} · Нет активности",+ apiRequests: "{count} через API",+ cumulativeTooltip: "К неделе {date} · всего {tokens}",less: "Меньше",more: "Больше",insightsTitle: "Сводка по активности",diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex 7c2fde8c8d7..7056a086c65 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -2233,9 +2233,9 @@ export const sv = {longestStreak: "Längsta svit",activityTitle: "Tokenaktivitet",activityDescription: {- daily: "{total} under de senaste {weeks}",- weekly: "Toppvecka {total} · senaste {weeks}",- cumulative: "{total} sammanlagt under de senaste {weeks}",+ daily: "{total} sedan {since}",+ weekly: "Mest aktiva veckan {total} · sedan {since}",+ cumulative: "{total} totalt sedan {since}",},mode: {daily: "Dagligen",@@ -2244,8 +2244,9 @@ export const sv = {},cellTooltip: "{date} · {tokens}, {messages}",weekTooltip: "Veckan som börjar {date} · {tokens}",- chartToggle: "Diagram",- chartToggleHint: "Visa Veckovis och Kumulativt som ett diagram med märkta axlar",+ emptyDayTooltip: "{date} · Ingen aktivitet",+ apiRequests: "{count} via API",+ cumulativeTooltip: "Till veckan {date} · {tokens} totalt",less: "Mindre",more: "Mer",insightsTitle: "Aktivitetsinsikter",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex d00dc91a93e..c2135027e9b 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -2041,9 +2041,9 @@ export const zhCN = {longestStreak: "最长连续天数",activityTitle: "Token 活跃度",activityDescription: {- daily: "过去{weeks}共{total}",- weekly: "峰值周 {total} · 最近{weeks}",- cumulative: "过去{weeks}累计{total}",+ daily: "自 {since} 起共 {total}",+ weekly: "最活跃的一周 {total} · 自 {since} 起",+ cumulative: "自 {since} 起累计 {total}",},mode: {daily: "按天",@@ -2052,8 +2052,9 @@ export const zhCN = {},cellTooltip: "{date} · {tokens},{messages}",weekTooltip: "{date} 当周 · {tokens}",- chartToggle: "图表",- chartToggleHint: "以带坐标轴标签的图表显示按周和累计",+ emptyDayTooltip: "{date} · 无活动",+ apiRequests: "通过 API {count} 次",+ cumulativeTooltip: "截至 {date} 那一周 · 累计 {tokens}",less: "较少",more: "较多",insightsTitle: "活跃度分析",diff --git a/studio/frontend/tests/profile-stats-format.test.ts b/studio/frontend/tests/profile-stats-format.test.tsindex d51609066ad..09ce74799f3 100644--- a/studio/frontend/tests/profile-stats-format.test.ts+++ b/studio/frontend/tests/profile-stats-format.test.ts@@ -7,6 +7,7 @@ import test from "node:test";import {type ActivityGridColumn,activitySummaryForMode,+ buildActivityColumns,formatCompactNumber,formatDayCount,formatDuration,@@ -14,8 +15,11 @@ import {formatMilliseconds,formatProfileCount,heatLevel,+ heatThresholds,+ monthLabelColumns,parseDayKey,seriesForMode,+ toLocalDayKey,weekChartPoints,windowBaseline,} from "../src/features/profile/utils/stats-format.ts";@@ -172,14 +176,66 @@ test("profile counts follow the selected locale's plural rules", () => {assert.equal(formatProfileCount(1200, "token", "ar", "1.2K"), "1.2K توكن");});-test("heat levels are relative to the busiest day", () => {- assert.equal(heatLevel(0, 1000), 0);- assert.equal(heatLevel(50, 1000), 1);- assert.equal(heatLevel(200, 1000), 2);- assert.equal(heatLevel(400, 1000), 3);- assert.equal(heatLevel(1000, 1000), 4);- // A single active day with no other history still shows up.- assert.equal(heatLevel(5, 0), 1);+test("heat levels split the active days into quartiles", () => {+ const days = [0, 0, 100, 200, 300, 400, 500, 600, 700, 50_000];+ const thresholds = heatThresholds(days);+ assert.deepEqual(thresholds, [300, 500, 700]);+ assert.equal(heatLevel(0, thresholds), 0);+ assert.equal(heatLevel(100, thresholds), 1);+ assert.equal(heatLevel(400, thresholds), 2);+ assert.equal(heatLevel(600, thresholds), 3);+ // One outlier no longer drops every other day to the faintest shade.+ assert.equal(heatLevel(50_000, thresholds), 4);+ assert.notEqual(heatLevel(700, thresholds), 1);+});++test("a lone active day, or days all alike, take the strongest shade", () => {+ assert.equal(heatLevel(5, heatThresholds([0, 5, 0])), 4);+ assert.equal(heatLevel(80, heatThresholds([80, 80, 80])), 4);+ assert.deepEqual(heatThresholds([0, 0]), [0, 0, 0]);+ // Coinciding quartiles promote only the days at them, not a smaller day below.+ const repeated = heatThresholds([10, 100, 100, 100, 100, 100, 100, 100]);+ assert.equal(heatLevel(100, repeated), 4);+ assert.equal(heatLevel(10, repeated), 1);+});++test("the grid ends on today's week and pads only real gaps", () => {+ // Wed 2026-10-07 .. Wed 2026-10-21: three Monday-started weeks.+ const daily = Array.from({ length: 15 }, (_, index) => ({+ date: `2026-10-${String(7 + index).padStart(2, "0")}`,+ tokens: index,+ }));+ const grid = buildActivityColumns(daily, seriesForMode(daily, "daily"), 10, "daily");+ assert.equal(grid.length, 3);+ assert.ok(grid.every((column) => column.length === 7));+ // Monday and Tuesday before the first day, Thursday to Sunday after today.+ assert.deepEqual(grid[0]?.slice(0, 2).map((cell) => cell.day), [null, null]);+ assert.equal(grid[2]?.[2]?.day?.date, "2026-10-21");+ assert.deepEqual(grid[2]?.slice(3).map((cell) => cell.day), [null, null, null, null]);+ // Narrower than the series: the oldest week falls off, today stays.+ const narrow = buildActivityColumns(daily, seriesForMode(daily, "daily"), 2, "daily");+ assert.equal(narrow.length, 2);+ assert.equal(narrow[0]?.[0]?.day?.date, "2026-10-12");+});++test("every month whose 1st is shown gets a label, and a leading sliver yields", () => {+ const days = (from: string, count: number) => {+ const start = parseDayKey(from);+ return Array.from({ length: count }, (_, index) => {+ const date = new Date(start.getFullYear(), start.getMonth(), start.getDate() + index);+ return { date: toLocalDayKey(date), tokens: 0 };+ });+ };+ // Starts Mon 2025-12-22: Dec is a sliver two columns before January.+ const winter = days("2025-12-22", 60);+ const grid = buildActivityColumns(winter, seriesForMode(winter, "daily"), 20, "daily");+ const labels = monthLabelColumns(grid).map((label) => label.date.slice(0, 7));+ assert.deepEqual(labels, ["2026-01", "2026-02"]);+ // A sliver with room before the next month keeps its label.+ const autumn = days("2025-09-08", 60);+ const autumnGrid = buildActivityColumns(autumn, seriesForMode(autumn, "daily"), 20, "daily");+ assert.equal(monthLabelColumns(autumnGrid)[0]?.date, "2025-09-08");+ assert.equal(monthLabelColumns(autumnGrid)[1]?.date, "2025-10-01");});test("day keys parse as local dates, not UTC", () => {