Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

💄 style(stats): add token-usage mode to activity heatmap (#15425)

Arvin Xu2fb0970cf9c3
diff --git a/packages/utils/src/format.test.ts b/packages/utils/src/format.test.ts
index 031056033ef..80c77529fc3 100644
--- a/packages/utils/src/format.test.ts
+++ b/packages/utils/src/format.test.ts
@@ -139,7 +139,14 @@ describe('format', () => {
it('should format numbers 10,000,000 and above correctly', () => {
expect(formatShortenNumber(10000000)).toBe('10.0M');
expect(formatShortenNumber(123456789)).toBe('123.5M');
- expect(formatShortenNumber(9876543210)).toBe('9876.5M');
+ });
+
+ it('should format billions and trillions correctly', () => {
+ expect(formatShortenNumber(1000000000)).toBe('1.0B');
+ expect(formatShortenNumber(9876543210)).toBe('9.9B');
+ expect(formatShortenNumber(15065800000)).toBe('15.1B');
+ expect(formatShortenNumber(1000000000000)).toBe('1.0T');
+ expect(formatShortenNumber(2500000000000)).toBe('2.5T');
});
});
diff --git a/packages/utils/src/format.ts b/packages/utils/src/format.ts
index c0dd9846553..319e60d8e86 100644
--- a/packages/utils/src/format.ts
+++ b/packages/utils/src/format.ts
@@ -51,8 +51,12 @@ export const formatShortenNumber = (num: any) => {
// Use Intl.NumberFormat to add thousand separators
const formattedWithComma = new Intl.NumberFormat('en-US').format(num);
- // Format as K or M
- if (num >= 1_000_000) {
+ // Format as K, M, B or T
+ if (num >= 1_000_000_000_000) {
+ return (num / 1_000_000_000_000).toFixed(1) + 'T';
+ } else if (num >= 1_000_000_000) {
+ return (num / 1_000_000_000).toFixed(1) + 'B';
+ } else if (num >= 1_000_000) {
return (num / 1_000_000).toFixed(1) + 'M';
} else if (num >= 10_000) {
return (num / 1000).toFixed(1) + 'K';
diff --git a/src/routes/(main)/settings/stats/features/overview/ShareButton/Preview.tsx b/src/routes/(main)/settings/stats/features/overview/ShareButton/Preview.tsx
index 638778067aa..efc353d9101 100644
--- a/src/routes/(main)/settings/stats/features/overview/ShareButton/Preview.tsx
+++ b/src/routes/(main)/settings/stats/features/overview/ShareButton/Preview.tsx
@@ -1,4 +1,4 @@
-import { imageUrl,OFFICIAL_URL } from '@lobechat/const';
+import { imageUrl, OFFICIAL_URL } from '@lobechat/const';
import { Center, Flexbox, Grid, lobeStaticStylish } from '@lobehub/ui';
import { createStaticStyles, cx, responsive } from 'antd-style';
import { memo } from 'react';
@@ -9,7 +9,7 @@ import UserAvatar from '@/features/User/UserAvatar';
import AiHeatmaps from '../../visualization/AiHeatmaps';
import TotalMessages from '../TotalMessages';
-import TotalWords from '../TotalWords';
+import TotalTokens from '../TotalTokens';
const styles = createStaticStyles(({ css, cssVar }) => ({
avatar: css`
@@ -133,7 +133,7 @@ const Preview = memo(() => {
/>
<Grid gap={8} maxItemWidth={100} rows={2} width={'100%'}>
<TotalMessages inShare />
- <TotalWords inShare />
+ <TotalTokens inShare />
</Grid>
</Flexbox>
<div className={styles.footer}>{OFFICIAL_URL}</div>
diff --git a/src/routes/(main)/settings/stats/features/overview/TotalTokens.tsx b/src/routes/(main)/settings/stats/features/overview/TotalTokens.tsx
new file mode 100644
index 00000000000..8cee02e2dad
--- /dev/null
+++ b/src/routes/(main)/settings/stats/features/overview/TotalTokens.tsx
@@ -0,0 +1,75 @@
+import dayjs from 'dayjs';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import Statistic from '@/components/Statistic';
+import StatisticCard from '@/components/StatisticCard';
+import TitleWithPercentage from '@/components/StatisticCard/TitleWithPercentage';
+import { useClientDataSWR } from '@/libs/swr';
+import { messageService } from '@/services/message';
+import { formatShortenNumber } from '@/utils/format';
+import { lastMonth } from '@/utils/time';
+
+import { HeatmapType } from '../../types';
+import TotalCard from './ShareButton/TotalCard';
+
+/**
+ * Cumulative token count. Derived from the daily token-heatmap series (same SWR
+ * key as the heatmap, so the request is deduped) rather than a separate query:
+ * `count` sums the whole window and `prevCount` sums up to the end of last month
+ * so the card shows the same month-over-month delta as its siblings.
+ */
+const TotalTokens = memo<{ inShare?: boolean }>(({ inShare }) => {
+ const { t } = useTranslation('auth');
+
+ const { data, isLoading } = useClientDataSWR(
+ ['stats-heatmaps', HeatmapType.Tokens].join('-'),
+ () => messageService.getTokenHeatmaps(),
+ );
+
+ const { count, prevCount } = useMemo(() => {
+ if (!data?.length) return { count: 0, prevCount: 0 };
+
+ const lastMonthEnd = lastMonth();
+ let count = 0;
+ let prevCount = 0;
+ for (const item of data) {
+ count += item.count;
+ if (!dayjs(item.date).isAfter(lastMonthEnd)) prevCount += item.count;
+ }
+ return { count, prevCount };
+ }, [data]);
+
+ if (inShare)
+ return (
+ <TotalCard
+ count={formatShortenNumber(prevCount) || '--'}
+ title={t('stats.heatmapStats.totalTokens')}
+ />
+ );
+
+ return (
+ <StatisticCard
+ loading={isLoading || !data}
+ statistic={{
+ description: (
+ <Statistic title={t('date.prevMonth')} value={formatShortenNumber(prevCount) || '--'} />
+ ),
+ precision: 0,
+ style: {
+ fontWeight: 'bold',
+ },
+ value: formatShortenNumber(count) || '--',
+ }}
+ title={
+ <TitleWithPercentage
+ count={count}
+ prvCount={prevCount}
+ title={t('stats.heatmapStats.totalTokens')}
+ />
+ }
+ />
+ );
+});
+
+export default TotalTokens;
diff --git a/src/routes/(main)/settings/stats/features/overview/TotalWords.tsx b/src/routes/(main)/settings/stats/features/overview/TotalWords.tsx
deleted file mode 100644
index 6cf83f7a255..00000000000
--- a/src/routes/(main)/settings/stats/features/overview/TotalWords.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import Statistic from '@/components/Statistic';
-import StatisticCard from '@/components/StatisticCard';
-import TitleWithPercentage from '@/components/StatisticCard/TitleWithPercentage';
-import { useClientDataSWR } from '@/libs/swr';
-import { messageService } from '@/services/message';
-import { formatShortenNumber } from '@/utils/format';
-import { lastMonth } from '@/utils/time';
-
-import TotalCard from './ShareButton/TotalCard';
-
-const TotalWords = memo<{ inShare?: boolean }>(({ inShare }) => {
- const { t } = useTranslation('auth');
-
- const { data, isLoading } = useClientDataSWR('stats-words', async () => ({
- count: await messageService.countWords(),
- prevCount: await messageService.countWords({ endDate: lastMonth().format('YYYY-MM-DD') }),
- }));
-
- if (inShare)
- return (
- <TotalCard count={formatShortenNumber(data?.prevCount) || '--'} title={t('stats.words')} />
- );
-
- return (
- <StatisticCard
- loading={isLoading || !data}
- statistic={{
- description: (
- <Statistic
- title={t('date.prevMonth')}
- value={formatShortenNumber(data?.prevCount) || '--'}
- />
- ),
- precision: 0,
- style: {
- fontWeight: 'bold',
- },
- value: formatShortenNumber(data?.count) || '--',
- }}
- title={
- <TitleWithPercentage
- count={data?.count}
- prvCount={data?.prevCount}
- title={t('stats.words')}
- />
- }
- />
- );
-});
-
-export default TotalWords;
diff --git a/src/routes/(main)/settings/stats/features/overview/index.ts b/src/routes/(main)/settings/stats/features/overview/index.ts
index 3fcdeaeb65d..71a23634a0e 100644
--- a/src/routes/(main)/settings/stats/features/overview/index.ts
+++ b/src/routes/(main)/settings/stats/features/overview/index.ts
@@ -1,6 +1,6 @@
export { default as ShareButton } from './ShareButton';
export { default as TotalAssistants } from './TotalAssistants';
export { default as TotalMessages } from './TotalMessages';
+export { default as TotalTokens } from './TotalTokens';
export { default as TotalTopics } from './TotalTopics';
-export { default as TotalWords } from './TotalWords';
export { default as Welcome } from './Welcome';
diff --git a/src/routes/(main)/settings/stats/features/visualization/AiHeatmaps.tsx b/src/routes/(main)/settings/stats/features/visualization/AiHeatmaps.tsx
index 655804f8b85..aca35880c8d 100644
--- a/src/routes/(main)/settings/stats/features/visualization/AiHeatmaps.tsx
+++ b/src/routes/(main)/settings/stats/features/visualization/AiHeatmaps.tsx
@@ -132,10 +132,8 @@ const AiHeatmaps = memo<
fontSize={16}
title={t('stats.lastYearActivity')}
>
- <Flexbox gap={16}>
- {isTokens && <HeatmapStats data={data} loading={isLoading || !data} />}
- {content}
- </Flexbox>
+ <HeatmapStats />
+ {content}
</StatsFormGroup>
);
});
diff --git a/src/routes/(main)/settings/stats/features/visualization/HeatmapStats.tsx b/src/routes/(main)/settings/stats/features/visualization/HeatmapStats.tsx
index cfe92be94b2..fbc23f725ef 100644
--- a/src/routes/(main)/settings/stats/features/visualization/HeatmapStats.tsx
+++ b/src/routes/(main)/settings/stats/features/visualization/HeatmapStats.tsx
@@ -1,4 +1,3 @@
-import { type HeatmapsProps } from '@lobehub/charts';
import { Block, Flexbox, Skeleton } from '@lobehub/ui';
import { Divider } from 'antd';
import { cssVar } from 'antd-style';
@@ -6,13 +5,11 @@ import { Fragment, memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useClientDataSWR } from '@/libs/swr';
+import { messageService } from '@/services/message';
import { topicService } from '@/services/topic';
import { formatShortenNumber } from '@/utils/format';
-interface HeatmapStatsProps {
- data?: HeatmapsProps['data'];
- loading?: boolean;
-}
+import { HeatmapType } from '../../types';
/**
* Render a wall-clock duration in seconds as a compact "1h 15m" / "15m 20s" /
@@ -29,26 +26,32 @@ const formatDuration = (seconds?: number) => {
};
/**
- * Token-dimension summary row for the activity heatmap. The cumulative / peak /
- * streak figures are derived from the heatmap `data` array (no extra request);
- * the longest-task duration comes from the agent operations' wall-clock time.
+ * Token-dimension summary row for the activity heatmap. The peak / streak figures
+ * are derived from the daily token-heatmap series (same SWR key as the heatmap,
+ * so the request is deduped); the longest-task duration comes from the agent
+ * operations' wall-clock time. The cumulative token total lives in the overview
+ * cards above, so it is intentionally not repeated here.
*/
-const HeatmapStats = memo<HeatmapStatsProps>(({ data, loading }) => {
+const HeatmapStats = memo(() => {
const { t } = useTranslation('auth');
+ const { data, isLoading } = useClientDataSWR(
+ ['stats-heatmaps', HeatmapType.Tokens].join('-'),
+ () => messageService.getTokenHeatmaps(),
+ );
+ const loading = isLoading || !data;
+
const { data: maxTaskDuration } = useClientDataSWR('stats-max-task-duration', () =>
topicService.getMaxTaskDuration(),
);
const stats = useMemo(() => {
- if (!data?.length) return { current: 0, cumulative: 0, longest: 0, peak: 0 };
+ if (!data?.length) return { current: 0, longest: 0, peak: 0 };
- let cumulative = 0;
let peak = 0;
let longest = 0;
let run = 0;
for (const item of data) {
- cumulative += item.count;
if (item.count > peak) peak = item.count;
if (item.count > 0) {
run += 1;
@@ -67,13 +70,12 @@ const HeatmapStats = memo<HeatmapStatsProps>(({ data, loading }) => {
else break;
}
- return { current, cumulative, longest, peak };
+ return { current, longest, peak };
}, [data]);
const days = (n: number) => [n, t('stats.days')].join(' ');
const items = [
- { label: t('stats.heatmapStats.totalTokens'), value: formatShortenNumber(stats.cumulative) },
{ label: t('stats.heatmapStats.peakTokens'), value: formatShortenNumber(stats.peak) },
{
label: t('stats.heatmapStats.longestTask'),
diff --git a/src/routes/(main)/settings/stats/features/visualization/index.ts b/src/routes/(main)/settings/stats/features/visualization/index.ts
index a9a59ddbdcb..aa804005e37 100644
--- a/src/routes/(main)/settings/stats/features/visualization/index.ts
+++ b/src/routes/(main)/settings/stats/features/visualization/index.ts
@@ -1 +1,2 @@
export { default as AiHeatmaps } from './AiHeatmaps';
+export { default as HeatmapStats } from './HeatmapStats';
diff --git a/src/routes/(main)/settings/stats/index.tsx b/src/routes/(main)/settings/stats/index.tsx
index 1cf2353f12a..76391ffec6a 100644
--- a/src/routes/(main)/settings/stats/index.tsx
+++ b/src/routes/(main)/settings/stats/index.tsx
@@ -17,8 +17,8 @@ import {
ShareButton,
TotalAssistants,
TotalMessages,
+ TotalTokens,
TotalTopics,
- TotalWords,
Welcome,
} from './features/overview';
import { AssistantsRank, ModelsRank, TopicsRank } from './features/rankings';
@@ -70,7 +70,7 @@ const StatsSetting = memo<{ mobile?: boolean }>(({ mobile }) => {
<TotalAssistants mobile={mobile} />
<TotalTopics mobile={mobile} />
<TotalMessages mobile={mobile} />
- <TotalWords />
+ <TotalTokens />
</Grid>
<Divider dashed />
<AiHeatmaps mobile={mobile} />