Skip to content

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

Go

feat: animate numeric metrics with NumberFlow (#5317)

Jiayuan Zhangabeee82cd09a
diff --git a/packages/core/dashboard/queries.test.ts b/packages/core/dashboard/queries.test.ts
new file mode 100644
index 0000000000..79df6815bd
--- /dev/null
+++ b/packages/core/dashboard/queries.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ dashboardAgentRunTimeOptions,
+ dashboardRunTimeDailyOptions,
+ dashboardUsageByAgentOptions,
+ dashboardUsageDailyOptions,
+} from "./queries";
+
+type QueryOptionsWithPlaceholder = {
+ queryKey: readonly unknown[];
+ placeholderData?: unknown;
+};
+
+function resolvePlaceholder(
+ options: QueryOptionsWithPlaceholder,
+ previousData: unknown,
+ previousKey: readonly unknown[] | undefined,
+) {
+ expect(options.placeholderData).toBeTypeOf("function");
+ return (
+ options.placeholderData as (
+ data: unknown,
+ query: { queryKey: readonly unknown[] } | undefined,
+ ) => unknown
+ )(
+ previousData,
+ previousKey ? { queryKey: previousKey } : undefined,
+ );
+}
+
+const optionBuilders = [
+ dashboardUsageDailyOptions,
+ dashboardUsageByAgentOptions,
+ dashboardAgentRunTimeOptions,
+ dashboardRunTimeDailyOptions,
+] as const;
+
+describe("dashboard range placeholders", () => {
+ it.each(optionBuilders)(
+ "keeps the previous %s result when only the day range changes",
+ (buildOptions) => {
+ const previous = [{ sentinel: "30d" }];
+ const previousOptions = buildOptions("ws-1", 30, null, "UTC");
+ const nextOptions = buildOptions("ws-1", 7, null, "UTC");
+
+ expect(
+ resolvePlaceholder(nextOptions, previous, previousOptions.queryKey),
+ ).toBe(previous);
+ },
+ );
+
+ it("does not carry placeholder data across workspace, project, or timezone scopes", () => {
+ const previous = [{ sentinel: "previous-scope" }];
+ const nextOptions = dashboardUsageDailyOptions(
+ "ws-1",
+ 7,
+ "project-1",
+ "Asia/Shanghai",
+ );
+ const previousScopes = [
+ dashboardUsageDailyOptions(
+ "ws-2",
+ 30,
+ "project-1",
+ "Asia/Shanghai",
+ ),
+ dashboardUsageDailyOptions("ws-1", 30, "project-2", "Asia/Shanghai"),
+ dashboardUsageDailyOptions("ws-1", 30, "project-1", "UTC"),
+ ];
+
+ for (const previousOptions of previousScopes) {
+ expect(
+ resolvePlaceholder(nextOptions, previous, previousOptions.queryKey),
+ ).toBeUndefined();
+ }
+ });
+
+ it("keeps the initial loading state honest when there is no previous query", () => {
+ const options = dashboardUsageDailyOptions("ws-1", 30, null, "UTC");
+
+ expect(resolvePlaceholder(options, undefined, undefined)).toBeUndefined();
+ });
+});
diff --git a/packages/core/dashboard/queries.ts b/packages/core/dashboard/queries.ts
index dba26de556..1417f58a74 100644
--- a/packages/core/dashboard/queries.ts
+++ b/packages/core/dashboard/queries.ts
@@ -1,4 +1,4 @@
-import { queryOptions } from "@tanstack/react-query";
+import { keepPreviousData, queryOptions } from "@tanstack/react-query";
import { api } from "../api";
export const dashboardKeys = {
@@ -32,6 +32,20 @@ export const dashboardKeys = {
// 5-min rollup cadence on the server, 60s background refetch on the client.
const STALE_TIME = 60 * 1000;
+// Range changes should keep the previous result mounted so KPI cards and
+// charts transition in place instead of falling back to a full-page skeleton.
+// Scope changes are deliberately excluded: carrying data across workspaces,
+// projects, report kinds, or timezones would briefly display the wrong data.
+function isSameDashboardScope(
+ previousKey: readonly unknown[] | undefined,
+ nextKey: readonly unknown[],
+): boolean {
+ if (!previousKey || previousKey.length !== nextKey.length) return false;
+ return previousKey.every(
+ (part, index) => index === 3 || Object.is(part, nextKey[index]),
+ );
+}
+
// `tz` participates in every dashboard key so a Preferences change
// repoints the cache. All four series — token rollups and the
// atq.completed_at-based run-time series — slice their day boundary in
@@ -42,8 +56,9 @@ export function dashboardUsageDailyOptions(
projectId: string | null,
tz: string,
) {
+ const queryKey = dashboardKeys.daily(wsId, days, projectId, tz);
return queryOptions({
- queryKey: dashboardKeys.daily(wsId, days, projectId, tz),
+ queryKey,
queryFn: () =>
api.getDashboardUsageDaily({
days,
@@ -52,6 +67,10 @@ export function dashboardUsageDailyOptions(
}),
enabled: !!wsId,
staleTime: STALE_TIME,
+ placeholderData: (previousData, previousQuery) =>
+ isSameDashboardScope(previousQuery?.queryKey, queryKey)
+ ? keepPreviousData(previousData)
+ : undefined,
});
}
@@ -61,8 +80,9 @@ export function dashboardUsageByAgentOptions(
projectId: string | null,
tz: string,
) {
+ const queryKey = dashboardKeys.byAgent(wsId, days, projectId, tz);
return queryOptions({
- queryKey: dashboardKeys.byAgent(wsId, days, projectId, tz),
+ queryKey,
queryFn: () =>
api.getDashboardUsageByAgent({
days,
@@ -71,6 +91,10 @@ export function dashboardUsageByAgentOptions(
}),
enabled: !!wsId,
staleTime: STALE_TIME,
+ placeholderData: (previousData, previousQuery) =>
+ isSameDashboardScope(previousQuery?.queryKey, queryKey)
+ ? keepPreviousData(previousData)
+ : undefined,
});
}
@@ -80,8 +104,9 @@ export function dashboardAgentRunTimeOptions(
projectId: string | null,
tz: string,
) {
+ const queryKey = dashboardKeys.agentRuntime(wsId, days, projectId, tz);
return queryOptions({
- queryKey: dashboardKeys.agentRuntime(wsId, days, projectId, tz),
+ queryKey,
queryFn: () =>
api.getDashboardAgentRunTime({
days,
@@ -90,6 +115,10 @@ export function dashboardAgentRunTimeOptions(
}),
enabled: !!wsId,
staleTime: STALE_TIME,
+ placeholderData: (previousData, previousQuery) =>
+ isSameDashboardScope(previousQuery?.queryKey, queryKey)
+ ? keepPreviousData(previousData)
+ : undefined,
});
}
@@ -99,8 +128,9 @@ export function dashboardRunTimeDailyOptions(
projectId: string | null,
tz: string,
) {
+ const queryKey = dashboardKeys.runTimeDaily(wsId, days, projectId, tz);
return queryOptions({
- queryKey: dashboardKeys.runTimeDaily(wsId, days, projectId, tz),
+ queryKey,
queryFn: () =>
api.getDashboardRunTimeDaily({
days,
@@ -109,5 +139,9 @@ export function dashboardRunTimeDailyOptions(
}),
enabled: !!wsId,
staleTime: STALE_TIME,
+ placeholderData: (previousData, previousQuery) =>
+ isSameDashboardScope(previousQuery?.queryKey, queryKey)
+ ? keepPreviousData(previousData)
+ : undefined,
});
}
diff --git a/packages/ui/components/ui/number-flow.tsx b/packages/ui/components/ui/number-flow.tsx
new file mode 100644
index 0000000000..c882c23ba2
--- /dev/null
+++ b/packages/ui/components/ui/number-flow.tsx
@@ -0,0 +1,154 @@
+"use client"
+
+import NumberFlowPrimitive, {
+ NumberFlowGroup,
+ type NumberFlowProps,
+} from "@number-flow/react"
+
+import { cn } from "../../lib/utils"
+
+function NumberFlow({
+ className,
+ isolate = true,
+ respectMotionPreference = true,
+ ...props
+}: NumberFlowProps) {
+ return (
+ <NumberFlowPrimitive
+ className={cn("tabular-nums", className)}
+ isolate={isolate}
+ respectMotionPreference={respectMotionPreference}
+ {...props}
+ />
+ )
+}
+
+type NumberFlowFormat = NonNullable<NumberFlowProps["format"]>
+
+type CurrencyNumberFlowProps = Omit<
+ NumberFlowProps,
+ "format" | "prefix" | "suffix" | "value"
+> & {
+ value: number
+ prefix?: string
+ fractionThreshold?: number
+}
+
+function CurrencyNumberFlow({
+ value,
+ prefix = "$",
+ fractionThreshold = 100,
+ locales,
+ "aria-label": ariaLabel,
+ ...props
+}: CurrencyNumberFlowProps) {
+ const fractionDigits = Math.abs(value) >= fractionThreshold ? 0 : 2
+ const format: NumberFlowFormat = {
+ minimumFractionDigits: fractionDigits,
+ maximumFractionDigits: fractionDigits,
+ useGrouping: false,
+ }
+ const formatted = new Intl.NumberFormat(locales, format).format(value)
+
+ return (
+ <NumberFlow
+ value={value}
+ locales={locales}
+ prefix={prefix}
+ format={format}
+ aria-label={ariaLabel ?? `${prefix}${formatted}`}
+ {...props}
+ />
+ )
+}
+
+type CompactNumberFlowProps = Omit<
+ NumberFlowProps,
+ "format" | "suffix" | "value"
+> & {
+ value: number
+ suffixCase?: "lower" | "upper"
+}
+
+function CompactNumberFlow({
+ value,
+ suffixCase = "upper",
+ locales,
+ "aria-label": ariaLabel,
+ ...props
+}: CompactNumberFlowProps) {
+ const magnitude = Math.abs(value)
+ const divisor =
+ magnitude >= 1_000_000 ? 1_000_000 : magnitude >= 1_000 ? 1_000 : 1
+ const scaledValue = value / divisor
+ const fractionDigits =
+ divisor > 1 && Math.abs(scaledValue % 1) >= 0.05 ? 1 : 0
+ const suffix =
+ divisor === 1_000_000
+ ? suffixCase === "upper"
+ ? "M"
+ : "m"
+ : divisor === 1_000
+ ? suffixCase === "upper"
+ ? "K"
+ : "k"
+ : undefined
+ const format: NumberFlowFormat = {
+ minimumFractionDigits: fractionDigits,
+ maximumFractionDigits: fractionDigits,
+ useGrouping: divisor === 1,
+ }
+ const formatted = new Intl.NumberFormat(locales, format).format(scaledValue)
+
+ return (
+ <NumberFlow
+ value={scaledValue}
+ locales={locales}
+ suffix={suffix}
+ format={format}
+ aria-label={ariaLabel ?? `${formatted}${suffix ?? ""}`}
+ {...props}
+ />
+ )
+}
+
+type CappedNumberFlowProps = Omit<
+ NumberFlowProps,
+ "format" | "suffix" | "value"
+> & {
+ value: number
+ max?: number
+}
+
+function CappedNumberFlow({
+ value,
+ max = 99,
+ "aria-label": ariaLabel,
+ ...props
+}: CappedNumberFlowProps) {
+ const cappedValue = Math.min(Math.max(value, 0), max)
+
+ return (
+ <NumberFlow
+ value={cappedValue}
+ suffix={value > max ? "+" : undefined}
+ format={{ maximumFractionDigits: 0, useGrouping: false }}
+ aria-label={ariaLabel ?? String(value)}
+ {...props}
+ />
+ )
+}
+
+export {
+ CappedNumberFlow,
+ CompactNumberFlow,
+ CurrencyNumberFlow,
+ NumberFlow,
+ NumberFlowGroup,
+}
+export type {
+ CappedNumberFlowProps,
+ CompactNumberFlowProps,
+ CurrencyNumberFlowProps,
+ NumberFlowProps,
+}
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 77c14640db..3896ec9310 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -27,6 +27,7 @@
"dependencies": {
"@base-ui/react": "^1.3.0",
"@emoji-mart/data": "^1.2.1",
+ "@number-flow/react": "^0.6.1",
"@tanstack/react-table": "catalog:",
"class-variance-authority": "catalog:",
"clsx": "catalog:",
diff --git a/packages/views/agents/components/tabs/activity-tab.tsx b/packages/views/agents/components/tabs/activity-tab.tsx
index f6ae1c1916..9018b42fb0 100644
--- a/packages/views/agents/components/tabs/activity-tab.tsx
+++ b/packages/views/agents/components/tabs/activity-tab.tsx
@@ -16,6 +16,7 @@ import {
TooltipContent,
TooltipTrigger,
} from "@multica/ui/components/ui/tooltip";
+import { NumberFlow } from "@multica/ui/components/ui/number-flow";
import { useQueries, useQuery } from "@tanstack/react-query";
import type {
Agent,
@@ -314,9 +315,10 @@ function Last30dSection({
activity: AgentActivity | undefined;
avgDurationMs: number;
}) {
- const { t } = useT("agents");
+ const { t, i18n } = useT("agents");
const summary = summarizeActivityWindow(activity, 30);
const { totalRuns, totalFailed } = summary;
+ const locales = i18n.resolvedLanguage ?? i18n.language;
const successPct =
totalRuns > 0
? Math.round(((totalRuns - totalFailed) / totalRuns) * 100)
@@ -330,9 +332,13 @@ function Last30dSection({
<div className="flex items-end justify-between gap-5">
<div className="flex min-w-0 flex-col gap-1">
<div className="flex items-baseline gap-1.5">
- <span className="text-3xl font-bold leading-none tabular-nums">
- {totalRuns}
- </span>
+ <NumberFlow
+ value={totalRuns}
+ locales={locales}
+ format={{ maximumFractionDigits: 0 }}
+ aria-label={String(totalRuns)}
+ className="text-3xl font-bold leading-none"
+ />
<span className="text-sm text-muted-foreground">
{t(($) => $.tab_body.activity.runs, { count: totalRuns })}
</span>
diff --git a/packages/views/dashboard/components/dashboard-page.test.tsx b/packages/views/dashboard/components/dashboard-page.test.tsx
index ebf8428f8a..0073813d63 100644
--- a/packages/views/dashboard/components/dashboard-page.test.tsx
+++ b/packages/views/dashboard/components/dashboard-page.test.tsx
@@ -10,6 +10,11 @@ import { renderWithI18n } from "../../test/i18n";
// Capture every queryKey passed to useQuery. queryOptions() inside the
// dashboard options builders runs for real, so the key is the production key.
const queryKeys = vi.hoisted(() => [] as unknown[][]);
+const dashboardDataRef = vi.hoisted(() => ({ current: false }));
+
+function todayIso() {
+ return new Date().toISOString().slice(0, 10);
+}
vi.mock("@tanstack/react-query", async () => {
const actual =
@@ -20,6 +25,43 @@ vi.mock("@tanstack/react-query", async () => {
...actual,
useQuery: (opts: { queryKey: unknown[] }) => {
queryKeys.push(opts.queryKey);
+ if (dashboardDataRef.current) {
+ const kind = opts.queryKey[2];
+ const data =
+ kind === "daily"
+ ? [
+ {
+ date: todayIso(),
+ provider: "anthropic",
+ model: "claude-sonnet-4-6",
+ input_tokens: 1_000,
+ output_tokens: 2_000,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ task_count: 2,
+ },
+ ]
+ : kind === "agent-runtime"
+ ? [
+ {
+ agent_id: "agent-1",
+ total_seconds: 3 * 3_600 + 17 * 60,
+ task_count: 12,
+ failed_count: 1,
+ },
+ ]
+ : kind === "runtime-daily"
+ ? [
+ {
+ date: todayIso(),
+ total_seconds: 3 * 3_600 + 17 * 60,
+ task_count: 12,
+ failed_count: 1,
+ },
+ ]
+ : [];
+ return { data, isLoading: false, isSuccess: true };
+ }
return { data: undefined, isLoading: true };
},
};
@@ -56,6 +98,7 @@ import { DashboardPage } from "./dashboard-page";
describe("DashboardPage — viewing timezone drives the query key", () => {
beforeEach(() => {
queryKeys.length = 0;
+ dashboardDataRef.current = false;
cleanup();
});
@@ -97,4 +140,27 @@ describe("DashboardPage — viewing timezone drives the query key", () => {
expect(utcKeys[i]).not.toEqual(tokyoKeys[i]);
}
});
+
+ it("renders every workspace KPI as an animated number", () => {
+ dashboardDataRef.current = true;
+ tzRef.current = "UTC";
+
+ const { container } = renderWithI18n(<DashboardPage />);
+ const flows = Array.from(
+ container.querySelectorAll("number-flow-react"),
+ );
+
+ expect(flows).toHaveLength(5);
+ expect(flows.map((flow) => flow.getAttribute("aria-label"))).toEqual(
+ expect.arrayContaining(["$0.03", "3K", "12"]),
+ );
+ expect(container).toHaveTextContent("3h 17m");
+ expect(
+ flows.every(
+ (flow) =>
+ (flow as HTMLElement & { respectMotionPreference?: boolean })
+ .respectMotionPreference === true,
+ ),
+ ).toBe(true);
+ });
});
diff --git a/packages/views/dashboard/components/dashboard-page.tsx b/packages/views/dashboard/components/dashboard-page.tsx
index a8a515d638..75286e46b0 100644
--- a/packages/views/dashboard/components/dashboard-page.tsx
+++ b/packages/views/dashboard/components/dashboard-page.tsx
@@ -4,6 +4,12 @@ import { useMemo, useState } from "react";
import { BarChart3, FolderKanban, Trash2 } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import {
+ CompactNumberFlow,
+ CurrencyNumberFlow,
+ NumberFlow,
+ NumberFlowGroup,
+} from "@multica/ui/components/ui/number-flow";
import {
Select,
SelectContent,
@@ -103,11 +109,6 @@ const EMPTY_RUNTIME: import("@multica/core/types").DashboardAgentRunTime[] = [];
const EMPTY_RUNTIME_DAILY: import("@multica/core/types").DashboardRunTimeDaily[] = [];
const EMPTY_AGENTS: Agent[] = [];
-function fmtMoney(n: number): string {
- if (n >= 100) return `$${n.toFixed(0)}`;
- return `$${n.toFixed(2)}`;
-}
-
// 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.
@@ -140,6 +141,43 @@ function Segmented<T extends string | number>({
);
}
+function DurationNumberFlow({
+ seconds,
+ lessThanMinuteLabel,
+ locales,
+}: {
+ seconds: number;
+ lessThanMinuteLabel: string;
+ locales?: Intl.LocalesArgument;
+}) {
+ const label = formatDuration(seconds, lessThanMinuteLabel);
+ const parts = Array.from(label.matchAll(/(\d+)([a-z]+)/gi), (match) => ({
+ value: Number(match[1]),
+ unit: match[2] ?? "",
+ }));
+
+ if (parts.length === 0) return label;
+
+ return (
+ <>
+ <span className="sr-only">{label}</span>
+ <NumberFlowGroup>
+ <span aria-hidden className="inline-flex items-baseline gap-1">
+ {parts.map((part) => (
+ <NumberFlow
+ key={part.unit}
+ value={part.value}
+ locales={locales}
+ suffix={part.unit}
+ format={{ maximumFractionDigits: 0, useGrouping: false }}
+ />
+ ))}
+ </span>
+ </NumberFlowGroup>
+ </>
+ );
+}
+
/**
* Workspace + project token / run-time dashboard.
*
@@ -152,9 +190,10 @@ function Segmented<T extends string | number>({
* and the runtime page using one pricing table.
*/
export function DashboardPage() {
- const { t } = useT("usage");
+ const { t, i18n } = useT("usage");
const wsId = useWorkspaceId();
const viewTZ = useViewingTimezone();
+ const locales = i18n.resolvedLanguage ?? i18n.language;
const [dim, setDim] = useState<Dim>("daily");
const [days, setDays] = useState<TimeRange>(30);
const [projectValue, setProjectValue] = useState<string>(ALL_PROJECTS);
@@ -389,13 +428,23 @@ export function DashboardPage() {
<div className="grid grid-cols-1 divide-y rounded-lg border bg-card sm:grid-cols-2 sm:divide-x sm:divide-y-0 lg:grid-cols-4">
<KpiCard
label={t(($) => $.kpi.cost_label, { days })}
- value={fmtMoney(totals.cost)}
+ value={
+ <CurrencyNumberFlow value={totals.cost} locales={locales} />
+ }
/>
<KpiCard
label={t(($) => $.kpi.tokens_label, { days })}
- value={formatTokens(
- totals.input + totals.output + totals.cacheRead + totals.cacheWrite,
- )}
+ value={
+ <CompactNumberFlow
+ value={
+ totals.input +
+ totals.output +
+ totals.cacheRead +
+ totals.cacheWrite
+ }
+ locales={locales}
+ />
+ }
hint={t(($) => $.kpi.tokens_hint, {
input: formatTokens(totals.input),
output: formatTokens(totals.output),
@@ -403,17 +452,27 @@ export function DashboardPage() {
/>
<KpiCard
label={t(($) => $.kpi.run_time_label, { days })}
- value={formatDuration(
- runTimeTotals.totalSeconds,
- t(($) => $.duration.less_than_minute),
- )}
+ value={
+ <DurationNumberFlow
+ seconds={runTimeTotals.totalSeconds}
+ lessThanMinuteLabel={t(($) => $.duration.less_than_minute)}
+ locales={locales}
+ />
+ }
hint={t(($) => $.kpi.run_time_hint, {
tasks: runTimeTotals.taskCount,
})}
/>
<KpiCard
label={t(($) => $.kpi.tasks_label, { days })}
- value={String(runTimeTotals.taskCount)}
+ value={
+ <NumberFlow
+ value={runTimeTotals.taskCount}
+ locales={locales}
+ format={{ maximumFractionDigits: 0 }}
+ aria-label={String(runTimeTotals.taskCount)}
+ />
+ }
hint={t(($) => $.kpi.tasks_hint, {
failed: runTimeTotals.failedCount,
})}
diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsx
index 7eb399a4d7..92fe4e844f 100644
--- a/packages/views/inbox/components/inbox-page.tsx
+++ b/packages/views/inbox/components/inbox-page.tsx
@@ -42,6 +42,7 @@ import {
ResizableHandle,
} from "@multica/ui/components/ui/resizable";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import { NumberFlow } from "@multica/ui/components/ui/number-flow";
import {
DropdownMenu,
DropdownMenuTrigger,
@@ -227,9 +228,12 @@ export function InboxPage() {
<div className="flex items-center gap-2">
<h1 className="text-sm font-semibold">{t(($) => $.page.title)}</h1>
{unreadCount > 0 && (
- <span className="text-xs text-muted-foreground">
- {unreadCount}
- </span>
+ <NumberFlow
+ value={unreadCount}
+ format={{ maximumFractionDigits: 0 }}
+ aria-label={String(unreadCount)}
+ className="text-xs text-muted-foreground"
+ />
)}
</div>
<DropdownMenu>
diff --git a/packages/views/layout/app-sidebar.test.tsx b/packages/views/layout/app-sidebar.test.tsx
index 4d383140fc..bb0af436b1 100644
--- a/packages/views/layout/app-sidebar.test.tsx
+++ b/packages/views/layout/app-sidebar.test.tsx
@@ -302,6 +302,8 @@ describe("personal nav — Chat", () => {
// and renders the label + badge as its children.
const chatNav = (container: HTMLElement) =>
container.querySelector<HTMLElement>('button[data-href="/acme/chat"]');
+ const chatBadge = (container: HTMLElement) =>
+ chatNav(container)?.querySelector("number-flow-react") ?? null;
it("renders a Chat nav link to the workspace chat route", () => {
const { container } = render(<AppSidebar />);
@@ -311,13 +313,13 @@ describe("personal nav — Chat", () => {
it("badges the Chat nav with the summed unread_count of chat sessions", () => {
chatSessions.current = [{ id: "a", unread_count: 3 }, { id: "b", unread_count: 2 }, { id: "c", unread_count: 0 }];
const { container } = render(<AppSidebar />);
- expect(chatNav(container)?.textContent).toContain("5");
+ expect(chatBadge(container)).toHaveAttribute("aria-label", "5");
});
it("shows no Chat unread badge when every session is read", () => {
chatSessions.current = [{ id: "a", unread_count: 0 }, { id: "b" }];
const { container } = render(<AppSidebar />);
- expect(chatNav(container)?.textContent ?? "").not.toMatch(/\d/);
+ expect(chatBadge(container)).toBeNull();
});
it("excludes the session being viewed on the chat page from the badge", () => {
@@ -328,7 +330,7 @@ describe("personal nav — Chat", () => {
navigation.current = { pathname: "/acme/chat" };
chatStore.current = { activeSessionId: "a", isOpen: false };
const { container } = render(<AppSidebar />);
- expect(chatNav(container)?.textContent).toContain("3");
+ expect(chatBadge(container)).toHaveAttribute("aria-label", "3");
});
it("excludes the viewed session when the floating chat window is open off-route", () => {
@@ -336,7 +338,7 @@ describe("personal nav — Chat", () => {
navigation.current = { pathname: "/acme/issues" };
chatStore.current = { activeSessionId: "a", isOpen: true };
const { container } = render(<AppSidebar />);
- expect(chatNav(container)?.textContent).toContain("3");
+ expect(chatBadge(container)).toHaveAttribute("aria-label", "3");
});
it("still counts a remembered selection when no chat surface is showing it", () => {
@@ -346,6 +348,6 @@ describe("personal nav — Chat", () => {
navigation.current = { pathname: "/acme/issues" };
chatStore.current = { activeSessionId: "a", isOpen: false };
const { container } = render(<AppSidebar />);
- expect(chatNav(container)?.textContent).toContain("5");
+ expect(chatBadge(container)).toHaveAttribute("aria-label", "5");
});
});
diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsx
index 285720c2dc..a51cc4bd4e 100644
--- a/packages/views/layout/app-sidebar.tsx
+++ b/packages/views/layout/app-sidebar.tsx
@@ -41,6 +41,7 @@ import { WorkspaceAvatar } from "../workspace/workspace-avatar";
import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from "@multica/ui/components/ui/collapsible";
+import { CappedNumberFlow } from "@multica/ui/components/ui/number-flow";
import { StatusIcon } from "../issues/components/status-icon";
import { useIssueDraftStore } from "@multica/core/issues/stores/draft-store";
import { openCreateIssueWithPreference } from "@multica/core/issues/stores/create-mode-store";
@@ -675,14 +676,16 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
<item.icon />
<span>{t(($) => $.nav[item.labelKey])}</span>
{item.key === "inbox" && unreadCount > 0 && (
- <span className="ml-auto text-xs">
- {unreadCount > 99 ? "99+" : unreadCount}
- </span>
+ <CappedNumberFlow
+ value={unreadCount}
+ className="ml-auto text-xs"
+ />
)}
{item.key === "chat" && chatUnreadCount > 0 && (
- <span className="ml-auto text-xs">
- {chatUnreadCount > 99 ? "99+" : chatUnreadCount}
- </span>
+ <CappedNumberFlow
+ value={chatUnreadCount}
+ className="ml-auto text-xs"
+ />
)}
</SidebarMenuButton>
</SidebarMenuItem>
diff --git a/packages/views/runtimes/components/runtime-list.tsx b/packages/views/runtimes/components/runtime-list.tsx
index 851edb0f3b..8a604cb355 100644
--- a/packages/views/runtimes/components/runtime-list.tsx
+++ b/packages/views/runtimes/components/runtime-list.tsx
@@ -11,6 +11,7 @@ import {
} from "lucide-react";
import { toast } from "sonner";
import { useQuery } from "@tanstack/react-query";
+import { CurrencyNumberFlow } from "@multica/ui/components/ui/number-flow";
import type {
Agent,
AgentRuntime,
@@ -360,8 +361,9 @@ function HealthCell({
const COST_CELL_DAYS = 14;
export function CostCell({ runtimeId }: { runtimeId: string }) {
- const { t } = useT("runtimes");
+ const { t, i18n } = useT("runtimes");
const tz = useViewingTimezone();
+ const locales = i18n.resolvedLanguage ?? i18n.language;
const { data: usage = [] } = useQuery(
runtimeUsageOptions(runtimeId, COST_CELL_DAYS, tz),
);
@@ -396,7 +398,12 @@ export function CostCell({ runtimeId }: { runtimeId: string }) {
: `${delta > 0 ? "↑" : "↓"}${Math.abs(delta)}%`;
return (
<div className="flex w-full flex-col items-end leading-tight">
- <span className="text-sm font-medium tabular-nums">{fmt}</span>
+ <CurrencyNumberFlow
+ value={cost7d}
+ locales={locales}
+ aria-label={fmt}
+ className="text-sm font-medium"
+ />
{deltaLabel && (
<span className={`text-[11px] tabular-nums ${deltaTone}`}>
{deltaLabel}
diff --git a/packages/views/runtimes/components/shared.tsx b/packages/views/runtimes/components/shared.tsx
index a9911f2ad2..433b41e9c9 100644
--- a/packages/views/runtimes/components/shared.tsx
+++ b/packages/views/runtimes/components/shared.tsx
@@ -179,7 +179,7 @@ export function KpiCard({
accent,
}: {
label: string;
- value: string;
+ value: React.ReactNode;
hint?: React.ReactNode;
accent?: "brand" | "success" | "default";
}) {
diff --git a/packages/views/runtimes/components/usage-section.test.tsx b/packages/views/runtimes/components/usage-section.test.tsx
index a79fecc4e0..adb750e178 100644
--- a/packages/views/runtimes/components/usage-section.test.tsx
+++ b/packages/views/runtimes/components/usage-section.test.tsx
@@ -58,10 +58,15 @@ vi.mock("@tanstack/react-query", async () => {
await vi.importActual<typeof import("@tanstack/react-query")>(
"@tanstack/react-query",
);
+ const dateDaysAgo = (days: number) => {
+ const date = new Date();
+ date.setUTCDate(date.getUTCDate() - days);
+ return date.toISOString().slice(0, 10);
+ };
const usageRows = [
{
runtime_id: "r-1",
- date: "2026-05-19",
+ date: dateDaysAgo(0),
provider: "anthropic",
model: "claude-sonnet-4-6",
input_tokens: 1_000,
@@ -69,6 +74,16 @@ vi.mock("@tanstack/react-query", async () => {
cache_read_tokens: 0,
cache_write_tokens: 0,
},
+ {
+ runtime_id: "r-1",
+ date: dateDaysAgo(15),
+ provider: "anthropic",
+ model: "claude-sonnet-4-6",
+ input_tokens: 2_000,
+ output_tokens: 0,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ },
];
return {
...actual,
@@ -146,4 +161,23 @@ describe("UsageSection — Viewing timezone wiring", () => {
expect(screen.getByTestId("heatmap-tz").textContent).toBe(VIEWER_TZ);
});
+
+ it("renders KPI values with NumberFlow and updates them when the period changes", () => {
+ render(<UsageSection runtime={RUNTIME} />, { wrapper: Wrapper });
+
+ const flows = Array.from(document.querySelectorAll("number-flow-react"));
+ expect(flows).toHaveLength(3);
+ expect(flows.at(-1)).toHaveAttribute("aria-label", "3K");
+ expect(
+ flows.every(
+ (flow) =>
+ (flow as HTMLElement & { respectMotionPreference?: boolean })
+ .respectMotionPreference === true,
+ ),
+ ).toBe(true);
+
+ fireEvent.click(screen.getByRole("button", { name: "7d" }));
+
+ expect(flows.at(-1)).toHaveAttribute("aria-label", "1K");
+ });
});
diff --git a/packages/views/runtimes/components/usage-section.tsx b/packages/views/runtimes/components/usage-section.tsx
index dba1ce3847..f4bdb41e22 100644
--- a/packages/views/runtimes/components/usage-section.tsx
+++ b/packages/views/runtimes/components/usage-section.tsx
@@ -5,6 +5,10 @@ import { BarChart3, ChevronRight, AlertCircle } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { Button } from "@multica/ui/components/ui/button";
+import {
+ CompactNumberFlow,
+ CurrencyNumberFlow,
+} from "@multica/ui/components/ui/number-flow";
import { useWorkspaceId } from "@multica/core/hooks";
import { agentListOptions } from "@multica/core/workspace/queries";
import type { RuntimeUsage, AgentRuntime } from "@multica/core/types";
@@ -128,7 +132,7 @@ function fmtMoney(n: number): string {
// ---------------------------------------------------------------------------
export function UsageSection({ runtime }: { runtime: AgentRuntime }) {
- const { t } = useT("runtimes");
+ const { t, i18n } = useT("runtimes");
const runtimeId = runtime.id;
// Reports render in the viewer's timezone — the backend slices the UTC
// hourly rollup on the same `tz` we pass here, so every frontend window
@@ -175,6 +179,7 @@ export function UsageSection({ runtime }: { runtime: AgentRuntime }) {
cacheableTokens > 0 ? Math.round((totals.cacheRead / cacheableTokens) * 100) : 0;
const costDelta = pctChange(totals.cost, prevTotals.cost);
+ const locales = i18n.resolvedLanguage ?? i18n.language;
return (
<div className="space-y-5">
@@ -224,7 +229,13 @@ export function UsageSection({ runtime }: { runtime: AgentRuntime }) {
<div className="grid grid-cols-3 divide-x rounded-lg border bg-card">
<KpiCard
label={t(($) => $.usage.kpi_cost_label, { days })}
- value={fmtMoney(totals.cost)}
+ value={
+ <CurrencyNumberFlow
+ value={totals.cost}
+ locales={locales}
+ aria-label={fmtMoney(totals.cost)}
+ />
+ }
hint={
costDelta == null ? undefined : (
<span
@@ -246,7 +257,13 @@ export function UsageSection({ runtime }: { runtime: AgentRuntime }) {
/>
<KpiCard
label={t(($) => $.usage.kpi_cache_label, { days })}
- value={fmtMoney(totals.cacheSavings)}
+ value={
+ <CurrencyNumberFlow
+ value={totals.cacheSavings}
+ locales={locales}
+ aria-label={fmtMoney(totals.cacheSavings)}
+ />
+ }
accent={totals.cacheSavings > 0 ? "success" : "default"}
hint={
<span>
@@ -259,7 +276,13 @@ export function UsageSection({ runtime }: { runtime: AgentRuntime }) {
/>
<KpiCard
label={t(($) => $.usage.kpi_tokens_label, { days })}
- value={formatTokens(tokensTotal)}
+ value={
+ <CompactNumberFlow
+ value={tokensTotal}
+ locales={locales}
+ aria-label={formatTokens(tokensTotal)}
+ />
+ }
hint={
<span>
{t(($) => $.usage.kpi_tokens_hint, {
@@ -870,4 +893,3 @@ function computeTotals(rows: RuntimeUsage[]): UsageTotals {
{ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, cacheSavings: 0 },
);
}
-
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6038bcda56..23141b9d69 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -830,6 +830,9 @@ importers:
'@emoji-mart/data':
specifier: ^1.2.1
version: 1.2.1
+ '@number-flow/react':
+ specifier: ^0.6.1
'@tanstack/react-table':
specifier: 'catalog:'
@@ -2780,6 +2783,12 @@ packages:
resolution: {integrity: sha512-/xGlezI6xfGO9NwuJlnwz/K14qD1kCSAGtacBHnGzeAIuJGazcp45KP5NuyARXoKb7cwulAGWVsbeSxdG/cb0Q==}
engines: {node: ^18.17.0 || >=20.5.0}
+ '@number-flow/[email protected]':
+ resolution: {integrity: sha512-JsvB8FrmtRmn251jbJnFD7Tr6Sv/eQMLUAlbshGo4CfAPk0qgNYTio9HuFoETqtuflcJHQezeGsSTPbUn1oplw==}
+ peerDependencies:
+ react: ^18 || ^19
+ react-dom: ^18 || ^19
+
'@open-draft/[email protected]':
resolution: {integrity: sha512-CecwLWx3rhxVQF6V4bAgPS5t+So2sTbPgAzafKkVizyi7tlwpcFpdFqq+wqF2OwNBmqFuu6tOyouTuxgpMfzmA==}
@@ -6179,6 +6188,9 @@ packages:
jiti:
optional: true
+ resolution: {integrity: sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==}
+
resolution: {integrity: sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -8435,6 +8447,9 @@ packages:
resolution: {integrity: sha512-2vPPEi+Z7WqML2jZYddDIfy5Dqb0r2fze2zTxNNknZaFpVHU3mFB3R+DWeJWGVx0ecvttSGlJTI+WG+8Z4cDWw==}
+ resolution: {integrity: sha512-5NUCwZA6J/kZeEzqApOyq7KOf1Wu/oxjpp/95HB0NBNBFlpK/Pp7i4jH8h0LIXyRDKSTewDAUaYHL7IBrk19Ew==}
+
resolution: {integrity: sha512-9M5kpuOLyTPogMtZiQUIxdAZxl7Dxs6tVBbJErSumsqGMuhVSoUbkfeZ3XNPpLpwBBtqY5QDUzGwggLHX3slQg==}
engines: {node: '>=20.19.4'}
@@ -12598,6 +12613,13 @@ snapshots:
dependencies:
semver: 7.7.4
+ dependencies:
+ esm-env: 1.2.2
+ number-flow: 0.6.1
+ react: 19.2.3
+ react-dom: 19.2.3([email protected])
+
'@open-draft/[email protected]': {}
'@open-draft/[email protected]':
@@ -16820,6 +16842,8 @@ snapshots:
transitivePeerDependencies:
- supports-color
+
dependencies:
acorn: 8.16.0
@@ -19723,6 +19747,10 @@ snapshots:
+ dependencies:
+ esm-env: 1.2.2
+
dependencies:
flow-enums-runtime: 0.0.6