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.

✨ feat(stats): add daily token-usage mode to activity heatmap (#15417)

Arvin Xu2eb9e34fda06
diff --git a/locales/en-US/auth.json b/locales/en-US/auth.json
index ae026d808ed..260b1f7a22d 100644
--- a/locales/en-US/auth.json
+++ b/locales/en-US/auth.json
@@ -151,7 +151,9 @@
"heatmaps.months.oct": "Oct",
"heatmaps.months.sep": "Sep",
"heatmaps.tooltip": "{{count}} messages were created on {{date}}",
+ "heatmaps.tooltipTokens": "{{count}} tokens were used on {{date}}",
"heatmaps.totalCount": "A total of {{count}} messages sent in the past year",
+ "heatmaps.totalCountTokens": "A total of {{count}} tokens used in the past year",
"login": "Log In",
"loginGuide.f1": "Get free usage",
"loginGuide.f2": "Sync messages across devices",
@@ -211,6 +213,11 @@
"stats.days": "days",
"stats.empty.desc": "Please accumulate more chat data to view",
"stats.empty.title": "No Data",
+ "stats.heatmapStats.currentStreak": "Current Streak",
+ "stats.heatmapStats.longestStreak": "Longest Streak",
+ "stats.heatmapStats.longestTask": "Longest Task",
+ "stats.heatmapStats.peakTokens": "Peak Daily Tokens",
+ "stats.heatmapStats.totalTokens": "Total Tokens",
"stats.lastYearActivity": "Activity in the past year",
"stats.loginGuide.f1": "Get free usage",
"stats.loginGuide.f2": "Sync messages across devices",
@@ -222,6 +229,7 @@
"stats.modelsRank.right": "Messages",
"stats.modelsRank.title": "Model Usage Rank",
"stats.share.title": "My AI Activity Index",
+ "stats.tokens": "Tokens",
"stats.topics": "Topics",
"stats.topicsRank.left": "Topic",
"stats.topicsRank.right": "Messages",
diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.json
index 31d63e2b9c2..e5f673495c9 100644
--- a/locales/zh-CN/auth.json
+++ b/locales/zh-CN/auth.json
@@ -151,7 +151,9 @@
"heatmaps.months.oct": "十月",
"heatmaps.months.sep": "九月",
"heatmaps.tooltip": "{{date}} 当日产生 {{count}} 条消息",
+ "heatmaps.tooltipTokens": "{{date}} 当日消耗 {{count}} tokens",
"heatmaps.totalCount": "过去一年共发送 {{count}} 条消息",
+ "heatmaps.totalCountTokens": "过去一年共消耗 {{count}} tokens",
"login": "登录",
"loginGuide.f1": "获取免费使用额度",
"loginGuide.f2": "跨设备同步消息",
@@ -211,6 +213,11 @@
"stats.days": "天",
"stats.empty.desc": "先积累一些对话,再回来查看",
"stats.empty.title": "暂无数据",
+ "stats.heatmapStats.currentStreak": "当前连续天数",
+ "stats.heatmapStats.longestStreak": "最长连续天数",
+ "stats.heatmapStats.longestTask": "最长任务时长",
+ "stats.heatmapStats.peakTokens": "峰值单日 Token",
+ "stats.heatmapStats.totalTokens": "累计 Token 数",
"stats.lastYearActivity": "过去一年活跃度",
"stats.loginGuide.f1": "获取免费用量",
"stats.loginGuide.f2": "多端同步消息",
@@ -222,6 +229,7 @@
"stats.modelsRank.right": "消息数",
"stats.modelsRank.title": "模型使用率",
"stats.share.title": "我的 AI 活跃指数",
+ "stats.tokens": "Tokens",
"stats.topics": "话题数",
"stats.topicsRank.left": "话题",
"stats.topicsRank.right": "消息数",
diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.ts
index 5a314bb3732..8ab608b82fb 100644
--- a/packages/database/src/models/__tests__/agentOperation.test.ts
+++ b/packages/database/src/models/__tests__/agentOperation.test.ts
@@ -183,4 +183,63 @@ describe('AgentOperationModel', () => {
expect(await attackerModel.findById(operationId)).toBeNull();
});
});
+
+ describe('getMaxDurationSeconds', () => {
+ it('returns the longest wall-clock duration, ignoring in-flight and other users', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+
+ await serverDB.insert(agentOperations).values([
+ // 5 minutes
+ {
+ completedAt: new Date('2026-05-13T10:05:00.000Z'),
+ id: 'op-dur-1',
+ startedAt: new Date('2026-05-13T10:00:00.000Z'),
+ status: 'done',
+ userId,
+ },
+ // 1 hour — the longest
+ {
+ completedAt: new Date('2026-05-13T12:00:00.000Z'),
+ id: 'op-dur-2',
+ startedAt: new Date('2026-05-13T11:00:00.000Z'),
+ status: 'done',
+ userId,
+ },
+ // in-flight: no completedAt -> excluded
+ {
+ completedAt: null,
+ id: 'op-dur-running',
+ startedAt: new Date('2026-05-13T09:00:00.000Z'),
+ status: 'running',
+ userId,
+ },
+ // another user's much longer op -> excluded
+ {
+ completedAt: new Date('2026-05-13T20:00:00.000Z'),
+ id: 'op-dur-other',
+ startedAt: new Date('2026-05-13T10:00:00.000Z'),
+ status: 'done',
+ userId: otherUserId,
+ },
+ ]);
+
+ const result = await model.getMaxDurationSeconds();
+ expect(result).toBe(3600);
+ });
+
+ it('returns 0 when there are no completed operations', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+
+ await serverDB.insert(agentOperations).values({
+ completedAt: null,
+ id: 'op-dur-none',
+ startedAt: new Date('2026-05-13T09:00:00.000Z'),
+ status: 'running',
+ userId,
+ });
+
+ const result = await model.getMaxDurationSeconds();
+ expect(result).toBe(0);
+ });
+ });
});
diff --git a/packages/database/src/models/__tests__/messages/message.stats.test.ts b/packages/database/src/models/__tests__/messages/message.stats.test.ts
index 49c1e2fb078..ff8b93ee2d9 100644
--- a/packages/database/src/models/__tests__/messages/message.stats.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.stats.test.ts
@@ -507,6 +507,96 @@ describe('MessageModel Statistics Tests', () => {
});
});
+ describe('getTokenHeatmaps', () => {
+ it('should sum assistant metadata.usage.totalTokens per day and scale levels', async () => {
+ vi.useFakeTimers();
+ const fixedDate = new Date('2023-04-07T13:00:00Z');
+ vi.setSystemTime(fixedDate);
+
+ const today = dayjs(fixedDate);
+ const twoDaysAgoDate = today.subtract(2, 'day').format('YYYY-MM-DD');
+ const oneDayAgoDate = today.subtract(1, 'day').format('YYYY-MM-DD');
+ const todayDate = today.format('YYYY-MM-DD');
+
+ await serverDB.insert(messages).values([
+ // two days ago: 100 + 50 = 150 tokens
+ {
+ id: 'a1',
+ userId,
+ role: 'assistant',
+ metadata: { usage: { totalTokens: 100 } },
+ createdAt: today.subtract(2, 'day').toDate(),
+ },
+ {
+ id: 'a2',
+ userId,
+ role: 'assistant',
+ metadata: { usage: { totalTokens: 50 } },
+ createdAt: today.subtract(2, 'day').toDate(),
+ },
+ // a non-assistant message with usage on the same day must be ignored
+ {
+ id: 'u1',
+ userId,
+ role: 'user',
+ metadata: { usage: { totalTokens: 9999 } },
+ createdAt: today.subtract(2, 'day').toDate(),
+ },
+ // one day ago: 300 tokens (busiest day -> level 4)
+ {
+ id: 'a3',
+ userId,
+ role: 'assistant',
+ metadata: { usage: { totalTokens: 300 } },
+ createdAt: today.subtract(1, 'day').toDate(),
+ },
+ // today: assistant message without usage -> contributes 0
+ {
+ id: 'a4',
+ userId,
+ role: 'assistant',
+ metadata: {},
+ createdAt: today.toDate(),
+ },
+ // another user's tokens must be ignored
+ {
+ id: 'o1',
+ userId: otherUserId,
+ role: 'assistant',
+ metadata: { usage: { totalTokens: 8888 } },
+ createdAt: today.subtract(1, 'day').toDate(),
+ },
+ ]);
+
+ const result = await messageModel.getTokenHeatmaps();
+
+ expect(result.length).toBeGreaterThanOrEqual(366);
+ expect(result.length).toBeLessThan(368);
+
+ const twoDaysAgo = result.find((item) => item.date === twoDaysAgoDate);
+ expect(twoDaysAgo?.count).toBe(150);
+ // 150 / 300 * 4 = 2
+ expect(twoDaysAgo?.level).toBe(2);
+
+ const oneDayAgo = result.find((item) => item.date === oneDayAgoDate);
+ expect(oneDayAgo?.count).toBe(300);
+ expect(oneDayAgo?.level).toBe(4);
+
+ const todayData = result.find((item) => item.date === todayDate);
+ expect(todayData?.count).toBe(0);
+ expect(todayData?.level).toBe(0);
+
+ vi.useRealTimers();
+ });
+
+ it('should return all-zero data when there are no messages', async () => {
+ const result = await messageModel.getTokenHeatmaps();
+
+ expect(result.length).toBeGreaterThanOrEqual(366);
+ expect(result.every((item) => item.count === 0 && item.level === 0)).toBe(true);
+ });
+ });
+
describe('rankModels', () => {
it('should rank models by usage count', async () => {
// Create test data
diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.ts
index 061bf064cd2..af09493075c 100644
--- a/packages/database/src/models/agentOperation.ts
+++ b/packages/database/src/models/agentOperation.ts
@@ -1,4 +1,6 @@
-import { and, eq } from 'drizzle-orm';
+import { and, eq, gte, isNotNull, sql } from 'drizzle-orm';
+
+import { today } from '@/utils/time';
import type {
AgentOperationAppContext,
@@ -135,4 +137,33 @@ export class AgentOperationModel {
.limit(1);
return row ?? null;
}
+
+ /**
+ * Longest single operation (agent run) wall-clock execution time over the last
+ * year, in seconds. Wall clock (`completedAt - startedAt`) is the most faithful
+ * "task duration" — it spans the whole run including tool calls and waiting,
+ * not just LLM compute. Returns 0 when there are no completed operations.
+ */
+ async getMaxDurationSeconds(): Promise<number> {
+ const startDate = today().subtract(1, 'year').startOf('day').toDate();
+
+ const [row] = await this.db
+ .select({
+ seconds:
+ sql<number>`COALESCE(MAX(EXTRACT(EPOCH FROM (${agentOperations.completedAt} - ${agentOperations.startedAt}))), 0)`.mapWith(
+ Number,
+ ),
+ })
+ .from(agentOperations)
+ .where(
+ and(
+ eq(agentOperations.userId, this.userId),
+ isNotNull(agentOperations.startedAt),
+ isNotNull(agentOperations.completedAt),
+ gte(agentOperations.createdAt, startDate),
+ ),
+ );
+
+ return row?.seconds ?? 0;
+ }
}
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 67fc12a64e0..3e0ac7d80aa 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -1555,6 +1555,80 @@ export class MessageModel {
return heatmapData;
};
+ /**
+ * Daily token-usage heatmap for the last year.
+ *
+ * Sums `metadata.usage.totalTokens` of assistant messages bucketed by the day
+ * each message was created — so tokens land on the day they were actually
+ * consumed (a long-running topic spreads across days instead of piling onto
+ * its creation date). `metadata.usage` is the source of truth for usage, so we
+ * aggregate it directly in SQL rather than pulling rows into JS. `level` is
+ * scaled relative to the busiest day so the heatmap stays readable regardless
+ * of absolute token volume.
+ */
+ getTokenHeatmaps = async (): Promise<HeatmapsProps['data']> => {
+ const startDate = today().subtract(1, 'year').startOf('day');
+ const endDate = today().endOf('day');
+
+ const result = await this.db
+ .select({
+ date: sql`DATE(${messages.createdAt})`.as('heatmaps_date'),
+ tokens:
+ sql<number>`COALESCE(SUM((${messages.metadata}->'usage'->>'totalTokens')::numeric), 0)`.mapWith(
+ Number,
+ ),
+ })
+ .from(messages)
+ .where(
+ genWhere([
+ eq(messages.userId, this.userId),
+ eq(messages.role, 'assistant'),
+ genRangeWhere(
+ [startDate.format('YYYY-MM-DD'), endDate.add(1, 'day').format('YYYY-MM-DD')],
+ messages.createdAt,
+ (date) => date.toDate(),
+ ),
+ ]),
+ )
+ .groupBy(sql`heatmaps_date`)
+ .orderBy(desc(sql`heatmaps_date`));
+
+ const dateTokenMap = new Map<string, number>();
+ let maxTokens = 0;
+ for (const item of result) {
+ if (item?.date) {
+ const dateStr = dayjs(item.date as string).format('YYYY-MM-DD');
+ const tokens = item.tokens || 0;
+ dateTokenMap.set(dateStr, tokens);
+ if (tokens > maxTokens) maxTokens = tokens;
+ }
+ }
+
+ const heatmapData: HeatmapsProps['data'] = [];
+ let currentDate = startDate.clone();
+
+ while (currentDate.isBefore(endDate) || currentDate.isSame(endDate, 'day')) {
+ const formattedDate = currentDate.format('YYYY-MM-DD');
+ const tokens = dateTokenMap.get(formattedDate) || 0;
+
+ // Scale to 1-4 relative to the busiest day; 0 tokens stays at level 0.
+ const level =
+ tokens > 0 && maxTokens > 0
+ ? Math.min(4, Math.max(1, Math.ceil((tokens / maxTokens) * 4)))
+ : 0;
+
+ heatmapData.push({
+ count: tokens,
+ date: formattedDate,
+ level,
+ });
+
+ currentDate = currentDate.add(1, 'day');
+ }
+
+ return heatmapData;
+ };
+
hasMoreThanN = async (n: number): Promise<boolean> => {
const result = await this.db
.select({ id: messages.id })
diff --git a/src/locales/default/auth.ts b/src/locales/default/auth.ts
index ca064dccfdd..e4824630d5e 100644
--- a/src/locales/default/auth.ts
+++ b/src/locales/default/auth.ts
@@ -161,7 +161,9 @@ export default {
'heatmaps.months.oct': 'Oct',
'heatmaps.months.sep': 'Sep',
'heatmaps.tooltip': '{{count}} messages were created on {{date}}',
+ 'heatmaps.tooltipTokens': '{{count}} tokens were used on {{date}}',
'heatmaps.totalCount': 'A total of {{count}} messages sent in the past year',
+ 'heatmaps.totalCountTokens': 'A total of {{count}} tokens used in the past year',
'login': 'Log In',
'loginGuide.f1': 'Get free usage',
'loginGuide.f2': 'Sync messages across devices',
@@ -223,6 +225,11 @@ export default {
'stats.days': 'days',
'stats.empty.desc': 'Please accumulate more chat data to view',
'stats.empty.title': 'No Data',
+ 'stats.heatmapStats.currentStreak': 'Current Streak',
+ 'stats.heatmapStats.longestStreak': 'Longest Streak',
+ 'stats.heatmapStats.longestTask': 'Longest Task',
+ 'stats.heatmapStats.peakTokens': 'Peak Daily Tokens',
+ 'stats.heatmapStats.totalTokens': 'Total Tokens',
'stats.lastYearActivity': 'Activity in the past year',
'stats.loginGuide.f1': 'Get free usage',
'stats.loginGuide.f2': 'Sync messages across devices',
@@ -238,6 +245,7 @@ export default {
'stats.topicsRank.left': 'Topic',
'stats.topicsRank.right': 'Messages',
'stats.topicsRank.title': 'Topic Content Rank',
+ 'stats.tokens': 'Tokens',
'stats.updatedAt': 'Updated at',
'stats.welcome': '{{username}}, this is your <span>{{days}}</span> day with {{appName}}',
'stats.words': 'Total Words',
diff --git a/src/routes/(main)/settings/stats/features/components/StatsFormGroup.tsx b/src/routes/(main)/settings/stats/features/components/StatsFormGroup.tsx
index ff19cdb4366..68fce8c92aa 100644
--- a/src/routes/(main)/settings/stats/features/components/StatsFormGroup.tsx
+++ b/src/routes/(main)/settings/stats/features/components/StatsFormGroup.tsx
@@ -6,6 +6,7 @@ import { type ReactNode } from 'react';
import { memo } from 'react';
interface StatsFormGroupProps extends Omit<BlockProps, 'title'> {
+ afterTitle?: ReactNode;
children: ReactNode;
extra?: ReactNode;
fontSize?: number;
@@ -13,13 +14,16 @@ interface StatsFormGroupProps extends Omit<BlockProps, 'title'> {
}
const StatsFormGroup = memo<StatsFormGroupProps>(
- ({ fontSize = 18, children, extra, title, ...rest }) => {
+ ({ fontSize = 18, afterTitle, children, extra, title, ...rest }) => {
return (
<Block gap={16} variant={'borderless'} {...rest}>
<Flexbox horizontal align={'center'} justify={'space-between'}>
- <Text fontSize={fontSize} weight={500}>
- {title}
- </Text>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={fontSize} weight={500}>
+ {title}
+ </Text>
+ {afterTitle}
+ </Flexbox>
<Flexbox horizontal align={'center'} gap={8}>
{extra}
</Flexbox>
diff --git a/src/routes/(main)/settings/stats/features/visualization/AiHeatmaps.tsx b/src/routes/(main)/settings/stats/features/visualization/AiHeatmaps.tsx
index 35138060ccf..655804f8b85 100644
--- a/src/routes/(main)/settings/stats/features/visualization/AiHeatmaps.tsx
+++ b/src/routes/(main)/settings/stats/features/visualization/AiHeatmaps.tsx
@@ -1,22 +1,30 @@
import { type HeatmapsProps } from '@lobehub/charts';
import { Heatmaps } from '@lobehub/charts';
-import { Flexbox, Icon, Tag } from '@lobehub/ui';
+import { Flexbox, Icon, Segmented, Tag } from '@lobehub/ui';
import { cssVar } from 'antd-style';
-import { FlameIcon } from 'lucide-react';
-import { memo } from 'react';
+import { CoinsIcon, FlameIcon, MessageSquareIcon } from 'lucide-react';
+import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useClientDataSWR } from '@/libs/swr';
import { messageService } from '@/services/message';
+import { formatIntergerNumber, formatShortenNumber } from '@/utils/format';
+import { HeatmapType } from '../../types';
import StatsFormGroup from '../components/StatsFormGroup';
+import HeatmapStats from './HeatmapStats';
const AiHeatmaps = memo<
Omit<HeatmapsProps, 'data' | 'ref'> & { inShare?: boolean; mobile?: boolean }
>(({ inShare, mobile, ...rest }) => {
const { t } = useTranslation('auth');
- const { data, isLoading } = useClientDataSWR('stats-heatmaps', async () =>
- messageService.getHeatmaps(),
+ const [type, setType] = useState<HeatmapType>(
+ inShare ? HeatmapType.Messages : HeatmapType.Tokens,
+ );
+ const isTokens = type === HeatmapType.Tokens;
+
+ const { data, isLoading } = useClientDataSWR(['stats-heatmaps', type].join('-'), async () =>
+ isTokens ? messageService.getTokenHeatmaps() : messageService.getHeatmaps(),
);
const days = data?.filter((item) => item.level > 0).length || '--';
@@ -28,8 +36,17 @@ const AiHeatmaps = memo<
blockRadius={mobile ? 2 : undefined}
blockSize={mobile ? 6 : 14}
data={data || []}
+ hideTotalCount={isTokens}
loading={isLoading || !data}
maxLevel={4}
+ customTooltip={(activity) =>
+ t(isTokens ? 'heatmaps.tooltipTokens' : 'heatmaps.tooltip', {
+ count: isTokens
+ ? formatShortenNumber(activity.count)
+ : formatIntergerNumber(activity.count),
+ date: activity.date,
+ })
+ }
labels={{
legend: {
less: t('heatmaps.legend.less'),
@@ -49,8 +66,8 @@ const AiHeatmaps = memo<
t('heatmaps.months.nov'),
t('heatmaps.months.dec'),
],
- tooltip: t('heatmaps.tooltip'),
- totalCount: t('heatmaps.totalCount'),
+ tooltip: isTokens ? t('heatmaps.tooltipTokens') : t('heatmaps.tooltip'),
+ totalCount: isTokens ? t('heatmaps.totalCountTokens') : t('heatmaps.totalCount'),
}}
style={{
alignSelf: 'center',
@@ -59,7 +76,28 @@ const AiHeatmaps = memo<
/>
);
- const tags = (
+ const typeSwitch = (
+ <Segmented
+ size={'small'}
+ value={type}
+ variant={'outlined'}
+ options={[
+ {
+ icon: <Icon icon={CoinsIcon} />,
+ label: t('stats.tokens'),
+ value: HeatmapType.Tokens,
+ },
+ {
+ icon: <Icon icon={MessageSquareIcon} />,
+ label: t('stats.messages'),
+ value: HeatmapType.Messages,
+ },
+ ]}
+ onChange={(v) => setType(v as HeatmapType)}
+ />
+ );
+
+ const dayTags = (
<Flexbox horizontal gap={8}>
<Tag variant={'filled'}>{[days, t('stats.days')].join(' ')}</Tag>
<Tag color={'success'} icon={<Icon icon={FlameIcon} />} variant={'filled'}>
@@ -80,7 +118,7 @@ const AiHeatmaps = memo<
>
{t('stats.lastYearActivity')}
</div>
- {tags}
+ {dayTags}
</Flexbox>
{content}
</Flexbox>
@@ -88,8 +126,16 @@ const AiHeatmaps = memo<
}
return (
- <StatsFormGroup extra={tags} fontSize={16} title={t('stats.lastYearActivity')}>
- {content}
+ <StatsFormGroup
+ afterTitle={typeSwitch}
+ extra={dayTags}
+ fontSize={16}
+ title={t('stats.lastYearActivity')}
+ >
+ <Flexbox gap={16}>
+ {isTokens && <HeatmapStats data={data} loading={isLoading || !data} />}
+ {content}
+ </Flexbox>
</StatsFormGroup>
);
});
diff --git a/src/routes/(main)/settings/stats/features/visualization/HeatmapStats.tsx b/src/routes/(main)/settings/stats/features/visualization/HeatmapStats.tsx
new file mode 100644
index 00000000000..cfe92be94b2
--- /dev/null
+++ b/src/routes/(main)/settings/stats/features/visualization/HeatmapStats.tsx
@@ -0,0 +1,110 @@
+import { type HeatmapsProps } from '@lobehub/charts';
+import { Block, Flexbox, Skeleton } from '@lobehub/ui';
+import { Divider } from 'antd';
+import { cssVar } from 'antd-style';
+import { Fragment, memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { topicService } from '@/services/topic';
+import { formatShortenNumber } from '@/utils/format';
+
+interface HeatmapStatsProps {
+ data?: HeatmapsProps['data'];
+ loading?: boolean;
+}
+
+/**
+ * Render a wall-clock duration in seconds as a compact "1h 15m" / "15m 20s" /
+ * "45s" string. Returns '--' when there is nothing to show.
+ */
+const formatDuration = (seconds?: number) => {
+ if (!seconds || seconds < 1) return '--';
+ const h = Math.floor(seconds / 3600);
+ const m = Math.floor((seconds % 3600) / 60);
+ const s = Math.floor(seconds % 60);
+ if (h > 0) return `${h}h ${m}m`;
+ if (m > 0) return `${m}m ${s}s`;
+ return `${s}s`;
+};
+
+/**
+ * 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.
+ */
+const HeatmapStats = memo<HeatmapStatsProps>(({ data, loading }) => {
+ const { t } = useTranslation('auth');
+
+ 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 };
+
+ 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;
+ if (run > longest) longest = run;
+ } else {
+ run = 0;
+ }
+ }
+
+ // Current streak: trailing consecutive active days. The last bucket (today)
+ // may legitimately be 0 because the day isn't over, so it doesn't break it.
+ let current = 0;
+ for (let i = data.length - 1; i >= 0; i -= 1) {
+ if (data[i].count > 0) current += 1;
+ else if (i === data.length - 1) continue;
+ else break;
+ }
+
+ return { current, cumulative, 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'),
+ loading: maxTaskDuration === undefined,
+ value: formatDuration(maxTaskDuration),
+ },
+ { label: t('stats.heatmapStats.currentStreak'), value: days(stats.current) },
+ { label: t('stats.heatmapStats.longestStreak'), value: days(stats.longest) },
+ ];
+
+ return (
+ <Block paddingBlock={16} paddingInline={8} variant={'outlined'}>
+ <Flexbox horizontal align={'center'} width={'100%'}>
+ {items.map((item, index) => (
+ <Fragment key={item.label}>
+ {index > 0 && <Divider style={{ height: 32, margin: 0 }} type={'vertical'} />}
+ <Flexbox align={'center'} flex={1} gap={4}>
+ <div style={{ fontSize: 20, fontWeight: 'bold' }}>
+ {loading || item.loading ? (
+ <Skeleton.Button active size={'small'} style={{ width: 56 }} />
+ ) : (
+ item.value
+ )}
+ </div>
+ <div style={{ color: cssVar.colorTextDescription, fontSize: 12 }}>{item.label}</div>
+ </Flexbox>
+ </Fragment>
+ ))}
+ </Flexbox>
+ </Block>
+ );
+});
+
+export default HeatmapStats;
diff --git a/src/routes/(main)/settings/stats/types.ts b/src/routes/(main)/settings/stats/types.ts
index c5ae3ab0617..c2b1d5503d3 100644
--- a/src/routes/(main)/settings/stats/types.ts
+++ b/src/routes/(main)/settings/stats/types.ts
@@ -13,3 +13,8 @@ export enum GroupBy {
Model = 'model',
Provider = 'provider',
}
+
+export enum HeatmapType {
+ Messages = 'messages',
+ Tokens = 'tokens',
+}
diff --git a/src/server/routers/lambda/message.ts b/src/server/routers/lambda/message.ts
index e851e668339..677e32e6e13 100644
--- a/src/server/routers/lambda/message.ts
+++ b/src/server/routers/lambda/message.ts
@@ -179,6 +179,10 @@ export const messageRouter = router({
return ctx.messageModel.getHeatmaps();
}),
+ getTokenHeatmaps: messageProcedure.query(async ({ ctx }) => {
+ return ctx.messageModel.getTokenHeatmaps();
+ }),
+
getMessages: publicProcedure
.use(serverDatabase)
.input(
diff --git a/src/server/routers/lambda/topic.ts b/src/server/routers/lambda/topic.ts
index 4a212cf726a..e85555d3302 100644
--- a/src/server/routers/lambda/topic.ts
+++ b/src/server/routers/lambda/topic.ts
@@ -8,6 +8,7 @@ import { eq, inArray } from 'drizzle-orm';
import { after } from 'next/server';
import { z } from 'zod';
+import { AgentOperationModel } from '@/database/models/agentOperation';
import { MessageModel } from '@/database/models/message';
import { TopicModel } from '@/database/models/topic';
import { TopicShareModel } from '@/database/models/topicShare';
@@ -31,6 +32,7 @@ const topicProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
return opts.next({
ctx: {
agentMigrationRepo: new AgentMigrationRepo(ctx.serverDB, ctx.userId),
+ agentOperationModel: new AgentOperationModel(ctx.serverDB, ctx.userId),
topicImporterRepo: new TopicImporterRepo(ctx.serverDB, ctx.userId),
topicModel: new TopicModel(ctx.serverDB, ctx.userId),
topicShareModel: new TopicShareModel(ctx.serverDB, ctx.userId),
@@ -353,6 +355,10 @@ export const topicRouter = router({
return result;
}),
+ getMaxTaskDuration: topicProcedure.query(async ({ ctx }) => {
+ return ctx.agentOperationModel.getMaxDurationSeconds();
+ }),
+
rankTopics: topicProcedure.input(z.number().max(50).optional()).query(async ({ ctx, input }) => {
return ctx.topicModel.rank(input);
}),
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index 26495fbe313..cb96359b2c9 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -66,6 +66,10 @@ export class MessageService {
return lambdaClient.message.getHeatmaps.query();
};
+ getTokenHeatmaps = async (): Promise<HeatmapsProps['data']> => {
+ return lambdaClient.message.getTokenHeatmaps.query();
+ };
+
updateMessageError = async (id: string, value: ChatMessageError, ctx?: MessageQueryContext) => {
const error = value.type
? value
diff --git a/src/services/topic/index.ts b/src/services/topic/index.ts
index 96e187f6ce9..ff1c9aaa2f6 100644
--- a/src/services/topic/index.ts
+++ b/src/services/topic/index.ts
@@ -74,6 +74,10 @@ export class TopicService {
return lambdaClient.topic.rankTopics.query(limit);
};
+ getMaxTaskDuration = async (): Promise<number> => {
+ return lambdaClient.topic.getMaxTaskDuration.query();
+ };
+
getRecentTopics = async (limit?: number): Promise<RecentTopic[]> => {
return lambdaClient.topic.recentTopics.query({ limit });
};