🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(stats): move usage statistics onto @lobechat/replica (#22779)
Arvin Xu1ef709302b4e
diff --git a/src/features/AgentUsage/hooks.test.ts b/src/features/AgentUsage/hooks.test.tsnew file mode 100644index 00000000000..5020128743e--- /dev/null+++ b/src/features/AgentUsage/hooks.test.ts@@ -0,0 +1,128 @@+/**+ * @vitest-environment happy-dom+ *+ * An agent's usage tab paints from the local copy after a reload: the numbers+ * the last session saw are there before the network answers, then the server's+ * answer replaces them.+ */+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ getAgentUsageStats: vi.fn(),+ scope: 'agent-usage-user:personal',+}));++vi.mock(import('@/libs/swr/useCacheScope'), async (importOriginal) => ({+ ...(await importOriginal()),+ getCacheScope: () => mocks.scope,+ isScopeTrusted: () => true,+ useCacheScope: () => mocks.scope,+}));++vi.mock('@/services/usage', () => ({+ usageService: { getAgentUsageStats: mocks.getAgentUsageStats },+}));++// Each boot re-imports the hook's module graph from scratch.+vi.setConfig({ testTimeout: 30_000 });++/** A reload: fresh modules (stores, SWR cache) over the same browser storage. */+const boot = async (agentId = 'agent-1') => {+ vi.resetModules();+ const { setScopedMutate } = await import('@/libs/swr/mutate');+ const { useAgentUsageStats } = await import('./hooks');++ const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+ };+ const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++ return renderHook(() => useAgentUsageStats(agentId, '30d', 'day'), { wrapper });+};++const never = () => new Promise<never>(() => {});++const stats = (totalSpend: number) => ({ buckets: [], byModel: [], summary: { totalSpend } });++/** Let the server answer reach the persisted copy. */+const flushPersist = () => act(() => new Promise((resolve) => setTimeout(resolve, 100)));++describe('useAgentUsageStats', () => {+ beforeEach(() => {+ mocks.scope = `agent-usage-${Math.random().toString(36).slice(2)}:personal`;+ });++ afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ });++ it('returns the last stats after a reload before the network answers', async () => {+ mocks.getAgentUsageStats.mockResolvedValue(stats(42));+ const first = await boot();+ await waitFor(() => expect(first.result.current.data).toEqual(stats(42)));+ await flushPersist();+ first.unmount();++ mocks.getAgentUsageStats.mockImplementation(never);+ const second = await boot();++ await waitFor(() => expect(second.result.current.data).toEqual(stats(42)));+ expect(second.result.current.isLoading).toBe(false);+ });++ it('replaces the restored stats with the server answer', async () => {+ mocks.getAgentUsageStats.mockResolvedValue(stats(42));+ const first = await boot();+ await waitFor(() => expect(first.result.current.data).toEqual(stats(42)));+ await flushPersist();+ first.unmount();++ mocks.getAgentUsageStats.mockResolvedValue(stats(50));+ const second = await boot();++ await waitFor(() => expect(second.result.current.data).toEqual(stats(50)));+ });++ it("does not return another identity's stats", async () => {+ mocks.getAgentUsageStats.mockResolvedValue(stats(42));+ const first = await boot();+ await waitFor(() => expect(first.result.current.data).toEqual(stats(42)));+ await flushPersist();+ first.unmount();++ mocks.scope = 'agent-usage-other-user:personal';+ mocks.getAgentUsageStats.mockImplementation(never);+ const second = await boot();++ await flushPersist();+ expect(second.result.current.data).toBeUndefined();+ expect(second.result.current.isLoading).toBe(true);+ });++ it('keeps each agent under its own entry', async () => {+ mocks.getAgentUsageStats.mockResolvedValue(stats(42));+ const first = await boot('agent-1');+ await waitFor(() => expect(first.result.current.data).toEqual(stats(42)));+ await flushPersist();+ first.unmount();++ mocks.getAgentUsageStats.mockImplementation(never);+ const second = await boot('agent-2');++ await flushPersist();+ expect(second.result.current.data).toBeUndefined();+ });+});diff --git a/src/features/AgentUsage/hooks.ts b/src/features/AgentUsage/hooks.tsindex b0fe07772cd..01461c166e7 100644--- a/src/features/AgentUsage/hooks.ts+++ b/src/features/AgentUsage/hooks.ts@@ -1,8 +1,6 @@import dayjs from 'dayjs';-import { useClientDataSWR } from '@/libs/swr';-import { statsKeys } from '@/libs/swr/keys';-import { usageService } from '@/services/usage';+import { type AgentUsageParams, statsActions, statsSelectors, useStatsStore } from '@/store/stats';import { type AgentUsageGranularity } from '@/types/usage/usageRecord';export type TimeRange = '7d' | '30d' | '90d';@@ -13,24 +11,39 @@ export const RANGE_DAYS: Record<TimeRange, number> = {'90d': 90,};+/** The usage read of one agent over the last `range` days, ending today. */+export const agentUsageParams = (+ agentId: string,+ range: TimeRange,+ granularity: AgentUsageGranularity,+): AgentUsageParams => ({+ agentId,+ endAt: dayjs().endOf('day').format('YYYY-MM-DD'),+ granularity,+ startAt: dayjs()+ .subtract(RANGE_DAYS[range] - 1, 'day')+ .startOf('day')+ .format('YYYY-MM-DD'),+});++/** The tab's initial range and granularity, also seeded by `agentUsageLoader`. */+export const DEFAULT_RANGE: TimeRange = '30d';+export const DEFAULT_GRANULARITY: AgentUsageGranularity = 'day';+/*** Fetch rich usage + cost stats for a single agent over the selected time range* and granularity. The range resolves to an inclusive `[startAt, endAt]` of the- * last N days (ending today).+ * last N days (ending today). Each range paints its last local copy on revisit+ * and revalidates in the background.*/export const useAgentUsageStats = (agentId: string,range: TimeRange,granularity: AgentUsageGranularity,) => {- const endAt = dayjs().endOf('day').format('YYYY-MM-DD');- const startAt = dayjs()- .subtract(RANGE_DAYS[range] - 1, 'day')- .startOf('day')- .format('YYYY-MM-DD');+ const params = agentId ? agentUsageParams(agentId, range, granularity) : null;+ const { error, revalidate } = statsActions.useFetchAgentUsage(params);+ const data = useStatsStore(statsSelectors.agentUsage(params));- return useClientDataSWR(- agentId ? statsKeys.agentUsageStat(agentId, startAt, endAt, granularity) : null,- async () => usageService.getAgentUsageStats({ agentId, endAt, granularity, startAt }),- );+ return { data, error, isLoading: !!params && !data, revalidate };};diff --git a/src/features/AgentUsage/index.tsx b/src/features/AgentUsage/index.tsxindex 0f582d9958a..b6acee4ff63 100644--- a/src/features/AgentUsage/index.tsx+++ b/src/features/AgentUsage/index.tsx@@ -13,7 +13,13 @@ import { useAgentStore } from '@/store/agent';import { type AgentUsageGranularity } from '@/types/usage/usageRecord';import { StyleSheet } from '@/utils/styles';-import { RANGE_DAYS, type TimeRange, useAgentUsageStats } from './hooks';+import {+ DEFAULT_GRANULARITY,+ DEFAULT_RANGE,+ RANGE_DAYS,+ type TimeRange,+ useAgentUsageStats,+} from './hooks';import ModelBreakdown from './ModelBreakdown';import StatCards from './StatCards';import UsageTrendChart from './UsageTrendChart';@@ -41,15 +47,15 @@ const AgentUsage = memo(() => {const { t } = useTranslation('spend');const activeAgentId = useAgentStore((s) => s.activeAgentId);- const [range, setRange] = useState<TimeRange>('30d');- const [granularity, setGranularity] = useState<AgentUsageGranularity>('day');+ const [range, setRange] = useState<TimeRange>(DEFAULT_RANGE);+ const [granularity, setGranularity] = useState<AgentUsageGranularity>(DEFAULT_GRANULARITY);const handleGranularityChange = (nextGranularity: AgentUsageGranularity) => {setGranularity(nextGranularity);if (nextGranularity === 'week' && range === '7d') setRange('30d');};- const { data, isLoading, error, mutate } = useAgentUsageStats(+ const { data, isLoading, error, revalidate } = useAgentUsageStats(activeAgentId ?? '',range,granularity,@@ -124,7 +130,7 @@ const AgentUsage = memo(() => {</Flexbox></Flexbox>{showError ? (- <AsyncError error={error} variant={'metric'} onRetry={() => mutate()} />+ <AsyncError error={error} variant={'metric'} onRetry={() => revalidate()} />) : (<StatCardsisLoading={isLoading}diff --git a/src/features/Settings/stats/features/overview/TotalAssistants.tsx b/src/features/Settings/stats/features/overview/TotalAssistants.tsxindex 01c00d11433..814a63c2047 100644--- a/src/features/Settings/stats/features/overview/TotalAssistants.tsx+++ b/src/features/Settings/stats/features/overview/TotalAssistants.tsx@@ -5,20 +5,15 @@ import AsyncBoundary from '@/components/AsyncBoundary';import Statistic from '@/components/Statistic';import StatisticCard from '@/components/StatisticCard';import TitleWithPercentage from '@/components/StatisticCard/TitleWithPercentage';-import { useClientDataSWR } from '@/libs/swr';-import { statsKeys } from '@/libs/swr/keys';-import { agentService } from '@/services/agent';+import { statsActions, statsSelectors, useStatsStore } from '@/store/stats';import { formatIntergerNumber } from '@/utils/format';-import { lastMonth } from '@/utils/time';import TotalCard from './ShareButton/TotalCard';const TotalMessages = memo<{ inShare?: boolean; mobile?: boolean }>(({ inShare }) => {const { t } = useTranslation('auth');- const { data, isLoading, error, mutate } = useClientDataSWR(statsKeys.agents(), async () => ({- count: await agentService.countAgents(),- prevCount: await agentService.countAgents({ endDate: lastMonth().format('YYYY-MM-DD') }),- }));+ const { error, revalidate } = statsActions.useFetchTotal('agents');+ const data = useStatsStore(statsSelectors.total('agents'));if (inShare)return (@@ -29,9 +24,9 @@ const TotalMessages = memo<{ inShare?: boolean; mobile?: boolean }>(({ inShare });return (- <AsyncBoundary data={data} error={error} errorVariant={'metric'} onRetry={() => mutate()}>+ <AsyncBoundary data={data} error={error} errorVariant={'metric'} onRetry={() => revalidate()}><StatisticCard- loading={isLoading || !data}+ loading={!data}statistic={{description: (<Statisticdiff --git a/src/features/Settings/stats/features/overview/TotalMessages.tsx b/src/features/Settings/stats/features/overview/TotalMessages.tsxindex cf9fbe71658..4948f072bf0 100644--- a/src/features/Settings/stats/features/overview/TotalMessages.tsx+++ b/src/features/Settings/stats/features/overview/TotalMessages.tsx@@ -5,29 +5,15 @@ import AsyncBoundary from '@/components/AsyncBoundary';import Statistic from '@/components/Statistic';import StatisticCard from '@/components/StatisticCard';import TitleWithPercentage from '@/components/StatisticCard/TitleWithPercentage';-import { useClientDataSWR } from '@/libs/swr';-import { statsKeys } from '@/libs/swr/keys';-import { messageService } from '@/services/message';+import { statsActions, statsSelectors, useStatsStore } from '@/store/stats';import { formatIntergerNumber } from '@/utils/format';-import { lastMonth } from '@/utils/time';import TotalCard from './ShareButton/TotalCard';const TotalMessages = memo<{ inShare?: boolean; mobile?: boolean }>(({ inShare }) => {const { t } = useTranslation('auth');- const { data, isLoading, error, mutate } = useClientDataSWR(statsKeys.messages(), async () => {- // The total is a planner estimate, but the last-month baseline is derived- // from it with an exact count of this month's messages (cheap — date-- // bounded) rather than a second estimate: without multicolumn statistics- // the planner can badly misjudge a user×date predicate, which would turn- // the growth percentage next to the number into noise.- const count = await messageService.countMessages({ approximate: true });- const sinceLastMonth = await messageService.countMessages({- startDate: lastMonth().add(1, 'day').format('YYYY-MM-DD'),- });-- return { count, prevCount: Math.max(count - sinceLastMonth, 0) };- });+ const { error, revalidate } = statsActions.useFetchTotal('messages');+ const data = useStatsStore(statsSelectors.total('messages'));if (inShare)return (@@ -38,9 +24,9 @@ const TotalMessages = memo<{ inShare?: boolean; mobile?: boolean }>(({ inShare });return (- <AsyncBoundary data={data} error={error} errorVariant={'metric'} onRetry={() => mutate()}>+ <AsyncBoundary data={data} error={error} errorVariant={'metric'} onRetry={() => revalidate()}><StatisticCard- loading={isLoading || !data}+ loading={!data}statistic={{description: (<Statisticdiff --git a/src/features/Settings/stats/features/overview/TotalTokens.tsx b/src/features/Settings/stats/features/overview/TotalTokens.tsxindex 0077ae95e1b..40d87304e16 100644--- a/src/features/Settings/stats/features/overview/TotalTokens.tsx+++ b/src/features/Settings/stats/features/overview/TotalTokens.tsx@@ -6,9 +6,7 @@ import AsyncBoundary from '@/components/AsyncBoundary';import Statistic from '@/components/Statistic';import StatisticCard from '@/components/StatisticCard';import TitleWithPercentage from '@/components/StatisticCard/TitleWithPercentage';-import { useClientDataSWR } from '@/libs/swr';-import { statsKeys } from '@/libs/swr/keys';-import { messageService } from '@/services/message';+import { statsActions, statsSelectors, useStatsStore } from '@/store/stats';import { formatShortenNumber } from '@/utils/format';import { lastMonth } from '@/utils/time';@@ -16,18 +14,17 @@ 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:+ * Cumulative token count. Derived from the daily token-heatmap series (same replica+ * entry 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, error, mutate } = useClientDataSWR(- statsKeys.heatmaps(HeatmapType.Tokens),- () => messageService.getTokenHeatmaps(),- );+ const { error, revalidate } = statsActions.useFetchHeatmap(HeatmapType.Tokens);+ // A restored empty series is not a confident zero until the server confirms it.+ const data = useStatsStore(statsSelectors.settledHeatmap(HeatmapType.Tokens));const { count, prevCount } = useMemo(() => {if (!data?.length) return { count: 0, prevCount: 0 };@@ -53,9 +50,9 @@ const TotalTokens = memo<{ inShare?: boolean }>(({ inShare }) => {// Metric variant: a failed fetch must never fall through to a confident `$0`// — show a failed marker + Retry where the number would sit (ux Read §1.1).return (- <AsyncBoundary data={data} error={error} errorVariant={'metric'} onRetry={() => mutate()}>+ <AsyncBoundary data={data} error={error} errorVariant={'metric'} onRetry={() => revalidate()}><StatisticCard- loading={isLoading || !data}+ loading={!data}statistic={{description: (<Statistic title={t('date.prevMonth')} value={formatShortenNumber(prevCount) || '--'} />diff --git a/src/features/Settings/stats/features/overview/TotalTopics.tsx b/src/features/Settings/stats/features/overview/TotalTopics.tsxindex da96cf82b1e..85575c85ec3 100644--- a/src/features/Settings/stats/features/overview/TotalTopics.tsx+++ b/src/features/Settings/stats/features/overview/TotalTopics.tsx@@ -5,20 +5,15 @@ import AsyncBoundary from '@/components/AsyncBoundary';import Statistic from '@/components/Statistic';import StatisticCard from '@/components/StatisticCard';import TitleWithPercentage from '@/components/StatisticCard/TitleWithPercentage';-import { useClientDataSWR } from '@/libs/swr';-import { statsKeys } from '@/libs/swr/keys';-import { topicService } from '@/services/topic';+import { statsActions, statsSelectors, useStatsStore } from '@/store/stats';import { formatIntergerNumber } from '@/utils/format';-import { lastMonth } from '@/utils/time';import TotalCard from './ShareButton/TotalCard';const TotalMessages = memo<{ inShare?: boolean; mobile?: boolean }>(({ inShare }) => {const { t } = useTranslation('auth');- const { data, isLoading, error, mutate } = useClientDataSWR(statsKeys.topics(), async () => ({- count: await topicService.countTopics(),- prevCount: await topicService.countTopics({ endDate: lastMonth().format('YYYY-MM-DD') }),- }));+ const { error, revalidate } = statsActions.useFetchTotal('topics');+ const data = useStatsStore(statsSelectors.total('topics'));if (inShare)return (@@ -26,9 +21,9 @@ const TotalMessages = memo<{ inShare?: boolean; mobile?: boolean }>(({ inShare });return (- <AsyncBoundary data={data} error={error} errorVariant={'metric'} onRetry={() => mutate()}>+ <AsyncBoundary data={data} error={error} errorVariant={'metric'} onRetry={() => revalidate()}><StatisticCard- loading={isLoading || !data}+ loading={!data}statistic={{description: (<Statisticdiff --git a/src/features/Settings/stats/features/overview/Welcome.tsx b/src/features/Settings/stats/features/overview/Welcome.tsxindex 06508899255..bcbd09b5faa 100644--- a/src/features/Settings/stats/features/overview/Welcome.tsx+++ b/src/features/Settings/stats/features/overview/Welcome.tsx@@ -4,9 +4,7 @@ import { Clock3Icon, ClockArrowUp } from 'lucide-react';import { memo } from 'react';import { Trans, useTranslation } from 'react-i18next';-import { useClientDataSWR } from '@/libs/swr';-import { statsKeys } from '@/libs/swr/keys';-import { userService } from '@/services/user';+import { statsActions, statsSelectors, useStatsStore } from '@/store/stats';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';import { formatIntergerNumber } from '@/utils/format';@@ -27,9 +25,8 @@ const Welcome = memo<{ mobile?: boolean }>(({ mobile }) => {userProfileSelectors.username(s),]);- const { data, isLoading } = useClientDataSWR(statsKeys.welcome(), async () =>- userService.getUserRegistrationDuration(),- );+ statsActions.useFetchRegistration();+ const data = useStatsStore(statsSelectors.registration);return (<Flexbox padding={mobile ? 16 : 0}>@@ -46,12 +43,11 @@ const Welcome = memo<{ mobile?: boolean }>(({ mobile }) => {i18nKey="stats.welcome"ns={'auth'}components={{- span:- isLoading || !data ? (- <Skeleton height={24} style={{ minWidth: 40 }} width={40} />- ) : (- <span style={{ fontWeight: 'bold' }} />- ),+ span: !data ? (+ <Skeleton height={24} style={{ minWidth: 40 }} width={40} />+ ) : (+ <span style={{ fontWeight: 'bold' }} />+ ),}}values={{appName: BRANDING_NAME,diff --git a/src/features/Settings/stats/features/rankings/AssistantsRank.tsx b/src/features/Settings/stats/features/rankings/AssistantsRank.tsxindex 3d8dc3d810d..6f2bb8c32e8 100644--- a/src/features/Settings/stats/features/rankings/AssistantsRank.tsx+++ b/src/features/Settings/stats/features/rankings/AssistantsRank.tsx@@ -13,11 +13,9 @@ import ImperativeModal from '@/components/ImperativeModal';import { DEFAULT_INBOX_AVATAR } from '@/const/meta';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import Link from '@/libs/router/Link';-import { useClientDataSWR } from '@/libs/swr';-import { statsKeys } from '@/libs/swr/keys';-import { agentService } from '@/services/agent';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';+import { statsActions, statsSelectors, useStatsStore } from '@/store/stats';import { type AgentRankItem } from '@/types/agent';import StatsFormGroup from '../components/StatsFormGroup';@@ -27,9 +25,11 @@ export const AssistantsRank = memo<{ mobile?: boolean }>(({ mobile }) => {const { t } = useTranslation(['auth', 'chat']);const navigate = useWorkspaceAwareNavigate();const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);- const { data, isLoading, error, mutate } = useClientDataSWR(statsKeys.rankAgents(), async () =>- agentService.rankAgents(),- );+ const { error, revalidate } = statsActions.useFetchRank('agents');+ // A restored empty ranking stays unsettled until the server confirms it, so+ // a failed refresh surfaces the error instead of an endless loading state.+ const data = useStatsStore(statsSelectors.settledRank('agents'));+ const loading = !data;const showExtra = Boolean(data && data?.length > 5);@@ -75,12 +75,17 @@ export const AssistantsRank = memo<{ mobile?: boolean }>(({ mobile }) => {)}>- <AsyncBoundary data={data} error={error} errorVariant={'block'} onRetry={() => mutate()}>+ <AsyncBoundary+ data={data}+ error={error}+ errorVariant={'block'}+ onRetry={() => revalidate()}+ ><BarListdata={data?.slice(0, 5).map((item) => mapData(item)) || []}height={220}leftLabel={t('stats.assistantsRank.left')}- loading={isLoading || !data}+ loading={loading}rightLabel={t('stats.assistantsRank.right')}noDataText={{desc: t('stats.empty.desc'),@@ -93,7 +98,7 @@ export const AssistantsRank = memo<{ mobile?: boolean }>(({ mobile }) => {{showExtra && (<ImperativeModalfooter={null}- loading={isLoading || !data}+ loading={loading}open={open}title={t('stats.assistantsRank.title')}onCancel={() => setOpen(false)}@@ -102,7 +107,7 @@ export const AssistantsRank = memo<{ mobile?: boolean }>(({ mobile }) => {data={data?.map((item) => mapData(item)) || []}height={340}leftLabel={t('stats.assistantsRank.left')}- loading={isLoading || !data}+ loading={loading}rightLabel={t('stats.assistantsRank.right')}onValueChange={(item) => navigate(item.link)}/>diff --git a/src/features/Settings/stats/features/rankings/ModelsRank.tsx b/src/features/Settings/stats/features/rankings/ModelsRank.tsxindex a9f6bdfd780..89b16680504 100644--- a/src/features/Settings/stats/features/rankings/ModelsRank.tsx+++ b/src/features/Settings/stats/features/rankings/ModelsRank.tsx@@ -8,18 +8,18 @@ import { useTranslation } from 'react-i18next';import AsyncBoundary from '@/components/AsyncBoundary';import ImperativeModal from '@/components/ImperativeModal';import { ModelIcon } from '@/components/LobeIcons';-import { useClientDataSWR } from '@/libs/swr';-import { statsKeys } from '@/libs/swr/keys';-import { messageService } from '@/services/message';+import { statsActions, statsSelectors, useStatsStore } from '@/store/stats';import StatsFormGroup from '../components/StatsFormGroup';export const TopicsRank = memo(() => {const [open, setOpen] = useState(false);const { t } = useTranslation('auth');- const { data, isLoading, error, mutate } = useClientDataSWR(statsKeys.rankModels(), async () =>- messageService.rankModels(),- );+ const { error, revalidate } = statsActions.useFetchRank('models');+ // A restored empty ranking stays unsettled until the server confirms it, so+ // a failed refresh surfaces the error instead of an endless loading state.+ const data = useStatsStore(statsSelectors.settledRank('models'));+ const loading = !data;const showExtra = Boolean(data && data?.length > 5);@@ -44,12 +44,17 @@ export const TopicsRank = memo(() => {) : undefined}>- <AsyncBoundary data={data} error={error} errorVariant={'block'} onRetry={() => mutate()}>+ <AsyncBoundary+ data={data}+ error={error}+ errorVariant={'block'}+ onRetry={() => revalidate()}+ ><BarListdata={data?.slice(0, 5).map((item) => mapData(item)) || []}height={220}leftLabel={t('stats.modelsRank.left')}- loading={isLoading || !data}+ loading={loading}rightLabel={t('stats.modelsRank.right')}noDataText={{desc: t('stats.empty.desc'),@@ -61,7 +66,7 @@ export const TopicsRank = memo(() => {{showExtra && (<ImperativeModalfooter={null}- loading={isLoading || !data}+ loading={loading}open={open}title={t('stats.modelsRank.title')}onCancel={() => setOpen(false)}@@ -70,7 +75,7 @@ export const TopicsRank = memo(() => {data={data?.map((item) => mapData(item)) || []}height={340}leftLabel={t('stats.modelsRank.left')}- loading={isLoading || !data}+ loading={loading}rightLabel={t('stats.modelsRank.right')}/></ImperativeModal>diff --git a/src/features/Settings/stats/features/rankings/TopicsRank.tsx b/src/features/Settings/stats/features/rankings/TopicsRank.tsxindex 5e3fa8780cd..d73a8324b3b 100644--- a/src/features/Settings/stats/features/rankings/TopicsRank.tsx+++ b/src/features/Settings/stats/features/rankings/TopicsRank.tsx@@ -10,11 +10,9 @@ import AsyncBoundary from '@/components/AsyncBoundary';import ImperativeModal from '@/components/ImperativeModal';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import Link from '@/libs/router/Link';-import { useClientDataSWR } from '@/libs/swr';-import { statsKeys } from '@/libs/swr/keys';-import { topicService } from '@/services/topic';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';+import { statsActions, statsSelectors, useStatsStore } from '@/store/stats';import { type TopicRankItem } from '@/types/topic';import StatsFormGroup from '../components/StatsFormGroup';@@ -24,9 +22,11 @@ export const TopicsRank = memo<{ mobile?: boolean }>(({ mobile }) => {const { t } = useTranslation('auth');const navigate = useWorkspaceAwareNavigate();const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);- const { data, isLoading, error, mutate } = useClientDataSWR(statsKeys.rankTopics(), async () =>- topicService.rankTopics(),- );+ const { error, revalidate } = statsActions.useFetchRank('topics');+ // A restored empty ranking stays unsettled until the server confirms it, so+ // a failed refresh surfaces the error instead of an endless loading state.+ const data = useStatsStore(statsSelectors.settledRank('topics'));+ const loading = !data;const showExtra = Boolean(data && data?.length > 5);@@ -62,12 +62,17 @@ export const TopicsRank = memo<{ mobile?: boolean }>(({ mobile }) => {)}>- <AsyncBoundary data={data} error={error} errorVariant={'block'} onRetry={() => mutate()}>+ <AsyncBoundary+ data={data}+ error={error}+ errorVariant={'block'}+ onRetry={() => revalidate()}+ ><BarListdata={data?.slice(0, 5).map((item) => mapData(item)) || []}height={220}leftLabel={t('stats.topicsRank.left')}- loading={isLoading || !data}+ loading={loading}rightLabel={t('stats.topicsRank.right')}noDataText={{desc: t('stats.empty.desc'),@@ -80,7 +85,7 @@ export const TopicsRank = memo<{ mobile?: boolean }>(({ mobile }) => {{showExtra && (<ImperativeModalfooter={null}- loading={isLoading || !data}+ loading={loading}open={open}title={t('stats.topicsRank.title')}onCancel={() => setOpen(false)}@@ -89,7 +94,7 @@ export const TopicsRank = memo<{ mobile?: boolean }>(({ mobile }) => {data={data?.map((item) => mapData(item)) || []}height={340}leftLabel={t('stats.topicsRank.left')}- loading={isLoading || !data}+ loading={loading}rightLabel={t('stats.topicsRank.right')}onValueChange={(item) => navigate(item.link)}/>diff --git a/src/features/Settings/stats/features/usage/UsageTable.test.tsx b/src/features/Settings/stats/features/usage/UsageTable.test.tsxindex c66dd0315db..cdb877dc7fb 100644--- a/src/features/Settings/stats/features/usage/UsageTable.test.tsx+++ b/src/features/Settings/stats/features/usage/UsageTable.test.tsx@@ -35,12 +35,10 @@ const rows = Array.from({ length: 12 }, (_, index) => ({type: index === 0 ? 'speechRecognition' : 'chat',}));-vi.mock('@/libs/swr', () => ({- useClientDataSWR: () => ({ data: rows, isLoading: false, mutate: vi.fn() }),-}));--vi.mock('@/services/usage', () => ({- usageService: { findByMonth: vi.fn() },+vi.mock('@/store/stats', () => ({+ statsActions: { useFetchUsageLogs: () => ({ error: undefined, revalidate: vi.fn() }) },+ statsSelectors: { settledUsageLogs: () => () => rows },+ useStatsStore: (selector: (state: unknown) => unknown) => selector({}),}));// Keep pagination lightweight while exercising the actual type column renderer.diff --git a/src/features/Settings/stats/features/usage/UsageTable.tsx b/src/features/Settings/stats/features/usage/UsageTable.tsxindex ec0783212da..2fbd437368b 100644--- a/src/features/Settings/stats/features/usage/UsageTable.tsx+++ b/src/features/Settings/stats/features/usage/UsageTable.tsx@@ -1,18 +1,17 @@import { Flexbox, type TableColumn, Text, Tooltip } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';-import { memo, useEffect, useMemo, useState } from 'react';+import { memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';+import AsyncBoundary from '@/components/AsyncBoundary';import InlineTable from '@/components/InlineTable';import { ProviderIcon } from '@/components/LobeIcons';import SpendType, { type SpendTypeValue } from '@/components/SpendType';import TablePagination from '@/components/TablePagination';import TotalToken from '@/components/TotalToken';import { parseAsInteger, useQueryStates } from '@/hooks/useQueryParam';-import { useClientDataSWR } from '@/libs/swr';-import { statsKeys } from '@/libs/swr/keys';-import { usageService } from '@/services/usage';+import { statsActions, statsSelectors, useStatsStore } from '@/store/stats';import { formatNumber, formatSpendTime } from '@/utils/format';import { type UsageChartProps } from '../../types';@@ -48,9 +47,11 @@ const UsageTable = memo<UsageChartProps>(({ dateStrings }) => {// namespace, so the two tables stay worded alike.const { t: tSpend } = useTranslation('spend');- const { data, isLoading, mutate } = useClientDataSWR(statsKeys.usageLogs(), async () =>- usageService.findByMonth(dateStrings),- );+ const { error, revalidate } = statsActions.useFetchUsageLogs(dateStrings);+ // A restored empty month stays unsettled until the server confirms it, so a+ // failed refresh surfaces the error instead of an endless loading state.+ const data = useStatsStore(statsSelectors.settledUsageLogs(dateStrings));+ const isLoading = !data;// Page and page size move together — the size picker keeps the first visible// row in view, so it recalculates the page as well. One update, one@@ -64,12 +65,6 @@ const UsageTable = memo<UsageChartProps>(({ dateStrings }) => {);const [sort, setSort] = useState<SortState | null>(null);- useEffect(() => {- if (dateStrings) {- mutate();- }- }, [dateStrings]);-const sorted = useMemo(() => {const getValue = sort && SORT_VALUES[sort.field];if (!data || !getValue) return data;@@ -168,7 +163,7 @@ const UsageTable = memo<UsageChartProps>(({ dateStrings }) => {];return (- <>+ <AsyncBoundary data={data} error={error} errorVariant={'block'} onRetry={() => revalidate()}><InlineTablecolumns={columns}dataSource={pageData}@@ -197,7 +192,7 @@ const UsageTable = memo<UsageChartProps>(({ dateStrings }) => {}/>)}- </>+ </AsyncBoundary>);});diff --git a/src/features/Settings/stats/features/visualization/AiHeatmaps.tsx b/src/features/Settings/stats/features/visualization/AiHeatmaps.tsxindex 7ab368e5184..640c2f69497 100644--- a/src/features/Settings/stats/features/visualization/AiHeatmaps.tsx+++ b/src/features/Settings/stats/features/visualization/AiHeatmaps.tsx@@ -5,9 +5,8 @@ import { CoinsIcon, FlameIcon, MessageSquareIcon } from 'lucide-react';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useClientDataSWR } from '@/libs/swr';-import { statsKeys } from '@/libs/swr/keys';-import { messageService } from '@/services/message';+import AsyncBoundary from '@/components/AsyncBoundary';+import { statsActions, statsSelectors, useStatsStore } from '@/store/stats';import { formatIntergerNumber, formatShortenNumber } from '@/utils/format';import { HeatmapType } from '../../types';@@ -23,57 +22,61 @@ const AiHeatmaps = memo<);const isTokens = type === HeatmapType.Tokens;- const { data, isLoading } = useClientDataSWR(statsKeys.heatmaps(type), async () =>- isTokens ? messageService.getTokenHeatmaps() : messageService.getHeatmaps(),- );+ const { error, revalidate } = statsActions.useFetchHeatmap(type);+ // A restored empty year stays unsettled until the server confirms it, so a+ // failed refresh surfaces the error instead of an endless loading state.+ const data = useStatsStore(statsSelectors.settledHeatmap(type));+ const loading = !data;const days = data?.filter((item) => item.level > 0).length || '--';const hotDays = data?.filter((item) => item.level >= 3).length || '--';const content = (- <Heatmaps- blockMargin={mobile ? 3 : undefined}- 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'),- more: t('heatmaps.legend.more'),- },- months: [- t('heatmaps.months.jan'),- t('heatmaps.months.feb'),- t('heatmaps.months.mar'),- t('heatmaps.months.apr'),- t('heatmaps.months.may'),- t('heatmaps.months.jun'),- t('heatmaps.months.jul'),- t('heatmaps.months.aug'),- t('heatmaps.months.sep'),- t('heatmaps.months.oct'),- t('heatmaps.months.nov'),- t('heatmaps.months.dec'),- ],- tooltip: isTokens ? t('heatmaps.tooltipTokens') : t('heatmaps.tooltip'),- totalCount: isTokens ? t('heatmaps.totalCountTokens') : t('heatmaps.totalCount'),- }}- style={{- alignSelf: 'center',- }}- {...rest}- />+ <AsyncBoundary data={data} error={error} errorVariant={'block'} onRetry={() => revalidate()}>+ <Heatmaps+ blockMargin={mobile ? 3 : undefined}+ blockRadius={mobile ? 2 : undefined}+ blockSize={mobile ? 6 : 14}+ data={data || []}+ hideTotalCount={isTokens}+ loading={loading}+ 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'),+ more: t('heatmaps.legend.more'),+ },+ months: [+ t('heatmaps.months.jan'),+ t('heatmaps.months.feb'),+ t('heatmaps.months.mar'),+ t('heatmaps.months.apr'),+ t('heatmaps.months.may'),+ t('heatmaps.months.jun'),+ t('heatmaps.months.jul'),+ t('heatmaps.months.aug'),+ t('heatmaps.months.sep'),+ t('heatmaps.months.oct'),+ t('heatmaps.months.nov'),+ t('heatmaps.months.dec'),+ ],+ tooltip: isTokens ? t('heatmaps.tooltipTokens') : t('heatmaps.tooltip'),+ totalCount: isTokens ? t('heatmaps.totalCountTokens') : t('heatmaps.totalCount'),+ }}+ style={{+ alignSelf: 'center',+ }}+ {...rest}+ />+ </AsyncBoundary>);const typeSwitch = (diff --git a/src/features/Settings/stats/features/visualization/HeatmapStats.tsx b/src/features/Settings/stats/features/visualization/HeatmapStats.tsxindex 75554cb086e..8cbc90b75dc 100644--- a/src/features/Settings/stats/features/visualization/HeatmapStats.tsx+++ b/src/features/Settings/stats/features/visualization/HeatmapStats.tsx@@ -3,10 +3,7 @@ import { Block, cssVar, Divider, Flexbox, Skeleton } from '@lobehub/ui';import { Fragment, memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { useClientDataSWR } from '@/libs/swr';-import { statsKeys } from '@/libs/swr/keys';-import { messageService } from '@/services/message';-import { topicService } from '@/services/topic';+import { statsActions, statsSelectors, useStatsStore } from '@/store/stats';import { formatShortenNumber } from '@/utils/format';import { HeatmapType } from '../../types';@@ -22,7 +19,7 @@ const formatDuration = (seconds?: number) => {/*** 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,+ * are derived from the daily token-heatmap series (same replica entry 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.@@ -30,14 +27,12 @@ const formatDuration = (seconds?: number) => {const HeatmapStats = memo(() => {const { t } = useTranslation('auth');- const { data, isLoading } = useClientDataSWR(statsKeys.heatmaps(HeatmapType.Tokens), () =>- messageService.getTokenHeatmaps(),- );- const loading = isLoading || !data;+ statsActions.useFetchHeatmap(HeatmapType.Tokens);+ const data = useStatsStore(statsSelectors.settledHeatmap(HeatmapType.Tokens));+ const loading = !data;- const { data: maxTaskDuration } = useClientDataSWR(statsKeys.maxTaskDuration(), () =>- topicService.getMaxTaskDuration(),- );+ statsActions.useFetchMaxTaskDuration();+ const maxTaskDuration = useStatsStore(statsSelectors.maxTaskDuration);const stats = useMemo(() => {if (!data?.length) return { current: 0, longest: 0, peak: 0 };diff --git a/src/features/Settings/stats/index.tsx b/src/features/Settings/stats/index.tsxindex c7e92c404be..2a6d1e93faf 100644--- a/src/features/Settings/stats/index.tsx+++ b/src/features/Settings/stats/index.tsx@@ -5,14 +5,12 @@ import { Form } from '@lobehub/ui/form';import { ProviderIcon } from '@lobehub/ui/icons';import dayjs from 'dayjs';import { Brain, UserIcon } from 'lucide-react';-import { memo, type ReactNode, useEffect, useState } from 'react';+import { memo, type ReactNode, useState } from 'react';import { useTranslation } from 'react-i18next';import AsyncBoundary from '@/components/AsyncBoundary';import SettingHeader from '@/features/Settings/features/SettingHeader';-import { useClientDataSWR } from '@/libs/swr';-import { statsKeys } from '@/libs/swr/keys';-import { usageService } from '@/services/usage';+import { statsActions, statsSelectors, useStatsStore } from '@/store/stats';import {ShareButton,@@ -57,15 +55,10 @@ const StatsSetting = memo<StatsSettingProps>(const [dateRange, setDateRange] = useState<dayjs.Dayjs>(dayjs(new Date()));const [dateStrings, setDateStrings] = useState<string>();- const { data, isLoading, error, mutate } = useClientDataSWR(statsKeys.usageStat(), async () =>- usageService.findAndGroupByDay(dateStrings),- );-- useEffect(() => {- if (dateStrings) {- mutate();- }- }, [dateStrings]);+ // Keyed by month: each picked month keeps its own local copy.+ const { error, revalidate } = statsActions.useFetchUsageByDay(dateStrings);+ const data = useStatsStore(statsSelectors.usageByDay(dateStrings));+ const isLoading = !data;const handleDateChange = (month: dayjs.Dayjs | null) => {if (!month) return;@@ -145,7 +138,12 @@ const StatsSetting = memo<StatsSettingProps>(</>}>- <AsyncBoundary data={data} error={error} errorVariant={'block'} onRetry={() => mutate()}>+ <AsyncBoundary+ data={data}+ error={error}+ errorVariant={'block'}+ onRetry={() => revalidate()}+ ><UsageCardsdata={data}groupBy={groupBy}diff --git a/src/features/User/DataStatistics.tsx b/src/features/User/DataStatistics.tsxindex 32ae2055a2b..56e728a780b 100644--- a/src/features/User/DataStatistics.tsx+++ b/src/features/User/DataStatistics.tsx@@ -6,14 +6,9 @@ import { isUndefined } from 'es-toolkit/compat';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { useClientDataSWR } from '@/libs/swr';-import { statsKeys } from '@/libs/swr/keys';-import { agentService } from '@/services/agent';-import { messageService } from '@/services/message';-import { topicService } from '@/services/topic';import { useServerConfigStore } from '@/store/serverConfig';+import { statsActions, statsSelectors, useStatsStore } from '@/store/stats';import { formatShortenNumber } from '@/utils/format';-import { today } from '@/utils/time';const styles = createStaticStyles(({ css, cssVar }) => ({card: css`@@ -43,25 +38,13 @@ const styles = createStaticStyles(({ css, cssVar }) => ({const DataStatistics = memo<Omit<FlexboxProps, 'children'>>(({ style, ...rest }) => {const mobile = useServerConfigStore((s) => s.isMobile);- // assistants (counted from the agents table — the sidebar list source of truth)- const { data: agents, isLoading: agentsLoading } = useClientDataSWR(statsKeys.countAgents(), () =>- agentService.countAgents(),- );- // topics- const { data: topics, isLoading: topicsLoading } = useClientDataSWR(statsKeys.countTopics(), () =>- topicService.countTopics(),- );- // messages- const { data: { messages, messagesToday } = {}, isLoading: messagesLoading } = useClientDataSWR(- statsKeys.countMessages(),- async () => ({- messages: await messageService.countMessages({ approximate: true }),- // today's delta stays exact — it is small, cheap, and shown as "+N"- messagesToday: await messageService.countMessages({- startDate: today().format('YYYY-MM-DD'),- }),- }),- );+ statsActions.useFetchCount('agents');+ statsActions.useFetchCount('topics');+ statsActions.useFetchCount('messages');+ const agents = useStatsStore(statsSelectors.count('agents'))?.count;+ const topics = useStatsStore(statsSelectors.count('topics'))?.count;+ const { count: messages, today: messagesToday } =+ useStatsStore(statsSelectors.count('messages')) ?? {};const { t } = useTranslation('common');@@ -69,17 +52,17 @@ const DataStatistics = memo<Omit<FlexboxProps, 'children'>>(({ style, ...rest })const items = [{- count: agentsLoading || isUndefined(agents) ? loading : agents,+ count: isUndefined(agents) ? loading : agents,key: 'sessions',title: t('dataStatistics.sessions'),},{- count: topicsLoading || isUndefined(topics) ? loading : topics,+ count: isUndefined(topics) ? loading : topics,key: 'topics',title: t('dataStatistics.topics'),},{- count: messagesLoading || isUndefined(messages) ? loading : messages,+ count: isUndefined(messages) ? loading : messages,countToady: messagesToday,key: 'messages',title: t('dataStatistics.messages'),diff --git a/src/libs/swr/keys.frozen.test.ts b/src/libs/swr/keys.frozen.test.tsindex a62dc87ced5..6a48181eb4a 100644--- a/src/libs/swr/keys.frozen.test.ts+++ b/src/libs/swr/keys.frozen.test.ts@@ -129,22 +129,6 @@ const LEGACY_SWR_KEYS = ['shareKeys.topic','shareKeys.topicInfo','shareKeys.visitorTopics',- 'statsKeys.agentUsageStat',- 'statsKeys.agents',- 'statsKeys.countAgents',- 'statsKeys.countMessages',- 'statsKeys.countTopics',- 'statsKeys.heatmaps',- 'statsKeys.maxTaskDuration',- 'statsKeys.messages',- 'statsKeys.rankAgents',- 'statsKeys.rankModels',- 'statsKeys.rankTopics',- 'statsKeys.sessions',- 'statsKeys.topics',- 'statsKeys.usageLogs',- 'statsKeys.usageStat',- 'statsKeys.welcome','taskLabelKeys.list','threadKeys.list','toolKeys.agentSkillDetail',diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 92e1e5158e3..9b16772fa79 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -553,35 +553,6 @@ export const apiKeyKeys = {list: def('apiKey:list', () => ['apiKey:list']),};-// ---- stats (settings/stats + user header counts) -------------------------export const statsKeys = {- agentUsageStat: def(- 'stats:agentUsageStat',- (agentId: string, startAt: string, endAt: string, granularity: string) => [- 'stats:agentUsageStat',- agentId,- startAt,- endAt,- granularity,- ],- ),- agents: def('stats:agents', () => ['stats:agents']),- countAgents: def('stats:countAgents', () => ['stats:countAgents']),- countMessages: def('stats:countMessages', () => ['stats:countMessages']),- countTopics: def('stats:countTopics', () => ['stats:countTopics']),- heatmaps: def('stats:heatmaps', (type: string) => ['stats:heatmaps', type]),- maxTaskDuration: def('stats:maxTaskDuration', () => ['stats:maxTaskDuration']),- messages: def('stats:messages', () => ['stats:messages']),- rankAgents: def('stats:rankAgents', () => ['stats:rankAgents']),- rankModels: def('stats:rankModels', () => ['stats:rankModels']),- rankTopics: def('stats:rankTopics', () => ['stats:rankTopics']),- sessions: def('stats:sessions', () => ['stats:sessions']),- topics: def('stats:topics', () => ['stats:topics']),- usageLogs: def('stats:usageLogs', () => ['stats:usageLogs']),- usageStat: def('stats:usageStat', () => ['stats:usageStat']),- welcome: def('stats:welcome', () => ['stats:welcome']),-};-// ---- messenger / platform integration -----------------------------------export const messengerKeys = {agentsForBinding: def('messenger:agentsForBinding', (workspaceId: string | null | undefined) => [@@ -945,7 +916,6 @@ export const swrKeys = {resource: resourceKeys,serverConfig: serverConfigKeys,share: shareKeys,- stats: statsKeys,taskLabel: taskLabelKeys,thread: threadKeys,tool: toolKeys,diff --git a/src/routes/(main)/agent/statistics/agentUsageLoader.ts b/src/routes/(main)/agent/statistics/agentUsageLoader.tsnew file mode 100644index 00000000000..6860681546f--- /dev/null+++ b/src/routes/(main)/agent/statistics/agentUsageLoader.ts@@ -0,0 +1,25 @@+import type { LoaderFunctionArgs } from 'react-router';++import { agentUsageParams, DEFAULT_GRANULARITY, DEFAULT_RANGE } from '@/features/AgentUsage/hooks';+import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';+import { statsActions } from '@/store/stats';++/**+ * Route loader for an agent's usage tab (`/agent/:aid/statistics`).+ *+ * Route loaders run before React commits the route: the only point where the+ * persisted usage stats (an async IndexedDB read) can land before the tab+ * paints its loading state. Seeds the tab's initial range.+ */+export const agentUsageLoader = async ({ params }: LoaderFunctionArgs): Promise<null> => {+ if (!params.aid) return null;++ await settleWithin(+ statsActions.preHydrateAgentUsage(+ agentUsageParams(params.aid, DEFAULT_RANGE, DEFAULT_GRANULARITY),+ ),+ PRE_PAINT_HYDRATE_TIMEOUT,+ );++ return null;+};diff --git a/src/routes/(main)/settings/statsPageLoader.ts b/src/routes/(main)/settings/statsPageLoader.tsnew file mode 100644index 00000000000..7c315f53cf3--- /dev/null+++ b/src/routes/(main)/settings/statsPageLoader.ts@@ -0,0 +1,15 @@+import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';+import { statsActions } from '@/store/stats';++/**+ * Route loader for the Settings → Stats tab.+ *+ * Route loaders run before React commits the route: the only point where the+ * persisted stats (async IndexedDB reads) can land before the cards paint their+ * loading state.+ */+export const statsPageLoader = async (): Promise<null> => {+ await settleWithin(statsActions.preHydrateStatsPage(), PRE_PAINT_HYDRATE_TIMEOUT);++ return null;+};diff --git a/src/spa/router/agentPageRoutes.tsx b/src/spa/router/agentPageRoutes.tsxindex f67336f87d3..39cc71df81d 100644--- a/src/spa/router/agentPageRoutes.tsx+++ b/src/spa/router/agentPageRoutes.tsx@@ -16,6 +16,7 @@ import {topicsRouteMeta,} from '@/routes/(main)/agent/features/routeMeta';import { agentDocumentListLoader } from '@/spa/router/agentDocumentListLoader';+import { agentUsageLoader } from '@/spa/router/agentUsageLoader';import { channelDataLoader } from '@/spa/router/channelDataLoader';import { selfLearningLoader } from '@/spa/router/expertiseLoaders';import { NoRouteSkeleton, routeMeta } from '@/spa/router/routeMeta';@@ -120,6 +121,7 @@ export const agentPageChildren: RouteObject[] = ['Desktop > Chat > Statistics',),handle: { meta: agentStatisticsRouteMeta },+ loader: agentUsageLoader,path: 'statistics',},{diff --git a/src/spa/router/agentUsageLoader.ts b/src/spa/router/agentUsageLoader.tsnew file mode 100644index 00000000000..c1fc8d57838--- /dev/null+++ b/src/spa/router/agentUsageLoader.ts@@ -0,0 +1,14 @@+import type { LoaderFunctionArgs } from 'react-router';++/**+ * Route-table entry for the agent usage tab pre-paint hydrate.+ *+ * The real loader imports the stats store. The route tables sit in the entry+ * chunk's static graph, so importing it directly would pull the store into the+ * first screen; resolving it on first use keeps it in the usage tab's lazy+ * chunks, which load in parallel with this one.+ */+export const agentUsageLoader = (args: LoaderFunctionArgs) =>+ import('@/routes/(main)/agent/statistics/agentUsageLoader').then((module) =>+ module.agentUsageLoader(args),+ );diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex 597600429b8..3e5102f7fb1 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -50,6 +50,7 @@ import { agentAccessLoader, agentGroupAccessLoader } from '@/spa/router/resourceimport { resourceRoute } from '@/spa/router/resourceRoutes';import { NoRouteSkeleton, routeMeta } from '@/spa/router/routeMeta';import { LegacySandboxStorageRedirect } from '@/spa/router/sandboxStorageRedirect';+import { settingsTabLoader } from '@/spa/router/statsPageLoader';import { taskWorkspaceChildren } from '@/spa/router/taskWorkspaceRoutes';import { withSegmentFallback } from '@/spa/router/withSegmentFallback';import { workspaceSettingsContentRoute } from '@/spa/router/workspaceSettingsRoutes';@@ -613,6 +614,7 @@ const createMainAreaChildrenDefinition = (options: MainAreaRouteOptions = {}): R'Desktop > Settings > Tab',),handle: { meta: settingsRouteMeta },+ loader: settingsTabLoader,path: ':tab',},// Tabs that need a sub-segment (e.g. /settings/messenger/discord) reusediff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsxindex 1d932977e74..8dbefd91357 100644--- a/src/spa/router/mobileRouter.config.tsx+++ b/src/spa/router/mobileRouter.config.tsx@@ -23,6 +23,7 @@ import { mobileUnsupportedRoutes, mobileWorkspaceRoutes } from '@/spa/router/mobimport { mobileWorkspaceSettingsChildren } from '@/spa/router/mobileWorkspaceSettingsRoutes';import { routeMeta } from '@/spa/router/routeMeta';import { LegacySandboxStorageRedirect } from '@/spa/router/sandboxStorageRedirect';+import { statsPageLoader } from '@/spa/router/statsPageLoader';import { SettingsTabs } from '@/store/global/initialState';import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';@@ -44,7 +45,13 @@ const personalSettingsTabRoutes: RouteObject[] = [...new Set(Object.values(Setti.flatMap((tab) => {const meta = createSettingsTitleRouteMeta(tab);return [- { element: settingsTabElement, handle: { meta, settingsTab: tab }, path: tab },+ {+ element: settingsTabElement,+ handle: { meta, settingsTab: tab },+ // `/settings/stats` matches this static segment, not `:tab`.+ loader: tab === SettingsTabs.Stats ? statsPageLoader : undefined,+ path: tab,+ },{ element: settingsTabSubElement, handle: { meta, settingsTab: tab }, path: `${tab}/:sub` },];});diff --git a/src/spa/router/statsPageLoader.test.ts b/src/spa/router/statsPageLoader.test.tsnew file mode 100644index 00000000000..ac103d2f39d--- /dev/null+++ b/src/spa/router/statsPageLoader.test.ts@@ -0,0 +1,45 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const preHydrateStatsPage = vi.hoisted(() => vi.fn());++vi.mock('@/store/stats', () => ({ statsActions: { preHydrateStatsPage } }));++const { settingsTabLoader, statsPageLoader } = await import('./statsPageLoader');++const args = (tab: string) => ({ params: { tab } }) as never;++describe('statsPageLoader', () => {+ beforeEach(() => {+ preHydrateStatsPage.mockReset();+ });++ it('seeds the stats replicas on a static stats route, which carries no `:tab` param', async () => {+ preHydrateStatsPage.mockResolvedValue([]);++ await expect(statsPageLoader()).resolves.toBeNull();+ expect(preHydrateStatsPage).toHaveBeenCalledTimes(1);+ });++ it('does not hold the route on a slow storage read', async () => {+ preHydrateStatsPage.mockReturnValue(new Promise(() => {}));++ await expect(statsPageLoader()).resolves.toBeNull();+ });+});++describe('settingsTabLoader', () => {+ beforeEach(() => {+ preHydrateStatsPage.mockReset();+ preHydrateStatsPage.mockResolvedValue([]);+ });++ it('seeds the stats replicas before the stats tab commits', async () => {+ await expect(settingsTabLoader(args('stats'))).resolves.toBeNull();+ expect(preHydrateStatsPage).toHaveBeenCalledTimes(1);+ });++ it('leaves other settings tabs alone', async () => {+ await settingsTabLoader(args('appearance'));+ expect(preHydrateStatsPage).not.toHaveBeenCalled();+ });+});diff --git a/src/spa/router/statsPageLoader.ts b/src/spa/router/statsPageLoader.tsnew file mode 100644index 00000000000..049a35c3f51--- /dev/null+++ b/src/spa/router/statsPageLoader.ts@@ -0,0 +1,20 @@+import type { LoaderFunctionArgs } from 'react-router';++import { SettingsTabs } from '@/store/global/initialState';++/**+ * Route-table entries for the Settings → Stats pre-paint hydrate.+ *+ * The real loader imports the stats store. The route tables sit in the entry+ * chunk's static graph, so importing it directly would pull the store into the+ * first screen; resolving it on first use keeps it in the stats tab's lazy+ * chunks.+ */++/** For a route that only renders the stats tab (a static `stats` segment). */+export const statsPageLoader = () =>+ import('@/routes/(main)/settings/statsPageLoader').then((module) => module.statsPageLoader());++/** For the generic `:tab` route: only the stats tab has anything to seed. */+export const settingsTabLoader = ({ params }: LoaderFunctionArgs) =>+ params.tab === SettingsTabs.Stats ? statsPageLoader() : null;diff --git a/src/spa/router/statsPageLoader.wiring.test.ts b/src/spa/router/statsPageLoader.wiring.test.tsnew file mode 100644index 00000000000..f0cc1906fc3--- /dev/null+++ b/src/spa/router/statsPageLoader.wiring.test.ts@@ -0,0 +1,42 @@+// @vitest-environment happy-dom+import { matchRoutes } from 'react-router';+import { describe, expect, it, vi } from 'vitest';++import { agentUsageLoader } from './agentUsageLoader';+import { desktopRoutes } from './desktopRouter.config';+import { mobileRoutes } from './mobileRouter.config';+import { settingsTabLoader, statsPageLoader } from './statsPageLoader';++const loaderModules = vi.hoisted(() => ({ evaluated: [] as string[] }));++// Evaluating a real loader means the stats store reached the entry chunk's+// first-screen graph.+vi.mock('@/routes/(main)/settings/statsPageLoader', () => {+ loaderModules.evaluated.push('stats');+ return { statsPageLoader: vi.fn(async () => null) };+});+vi.mock('@/routes/(main)/agent/statistics/agentUsageLoader', () => {+ loaderModules.evaluated.push('agentUsage');+ return { agentUsageLoader: vi.fn(async () => null) };+});++/** The loader of the route that renders `pathname` (the deepest match). */+const leafLoader = (routes: Parameters<typeof matchRoutes>[0], pathname: string) =>+ matchRoutes(routes, pathname)?.at(-1)?.route.loader;++describe('stats loader wiring', () => {+ it('does not load the store-backed loaders while the route tables load', () => {+ expect(loaderModules.evaluated).toEqual([]);+ });++ it('pre-hydrates the stats tab on the route that renders it', () => {+ expect(leafLoader(desktopRoutes, '/settings/stats')).toBe(settingsTabLoader);+ // Mobile renders `/settings/stats` from a static `stats` segment, which+ // outranks `:tab` and carries no `tab` param.+ expect(leafLoader(mobileRoutes, '/settings/stats')).toBe(statsPageLoader);+ });++ it('pre-hydrates an agent usage tab', () => {+ expect(leafLoader(desktopRoutes, '/agent/agt_1/statistics')).toBe(agentUsageLoader);+ });+});diff --git a/src/store/stats/action.test.ts b/src/store/stats/action.test.tsnew file mode 100644index 00000000000..e55e3daa2cb--- /dev/null+++ b/src/store/stats/action.test.ts@@ -0,0 +1,329 @@+/**+ * @vitest-environment happy-dom+ *+ * Every stats read is a replica persisted to IndexedDB: a reload paints the+ * last numbers before the network answers, then the server's answer replaces+ * them.+ */+import { randomUUID } from 'node:crypto';++import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import dayjs from 'dayjs';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope, REPLICA_INDEX_KEY } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { messageService } from '@/services/message';+import { topicService } from '@/services/topic';+import { usageService } from '@/services/usage';++import { statsActions } from './action';+import { initialState } from './initialState';+import {+ statsHeatmapResource,+ statsRankResource,+ statsTotalResource,+ usageByDayResource,+ usageLogsResource,+} from './projection';+import { statsSelectors } from './selectors';+import { useStatsStore } from './store';++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++const deferred = <T>() => {+ let resolve!: (value: T) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, reject, resolve };+};++const cells = (...counts: number[]) =>+ counts.map((count, index) => ({ count, date: `2026-01-0${index + 1}`, level: count ? 1 : 0 }));++const read = () => useStatsStore.getState();++describe('stats replicas', () => {+ let scope = '';+ const resources = [+ statsHeatmapResource,+ statsRankResource,+ statsTotalResource,+ usageByDayResource,+ usageLogsResource,+ ];++ beforeEach(() => {+ scope = `stats-user-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ act(() => useStatsStore.setState(initialState, false));+ });++ afterEach(async () => {+ cleanup();+ vi.useRealTimers();+ for (const resource of resources) {+ await resource.storage!.remove({ queryKey: REPLICA_INDEX_KEY, scope });+ }+ vi.restoreAllMocks();+ });++ it('paints a persisted total before the network answers, then replaces it', async () => {+ await statsTotalResource.storage!.set(+ { queryKey: statsTotalResource.storageKey('topics'), scope },+ { data: { count: 5, prevCount: 3 }, updatedAt: 1 },+ );+ const count = deferred<number>();+ vi.spyOn(topicService, 'countTopics').mockReturnValue(count.promise);++ renderHook(() => statsActions.useFetchTotal('topics'), { wrapper });++ await waitFor(() =>+ expect(statsSelectors.total('topics')(read())).toEqual({ count: 5, prevCount: 3 }),+ );++ await act(async () => count.resolve(9));+ await waitFor(() => expect(statsSelectors.total('topics')(read())?.count).toBe(9));+ });++ it('reads a restored empty heatmap as unconfirmed until the server answers', async () => {+ await statsHeatmapResource.storage!.set(+ { queryKey: statsHeatmapResource.storageKey('tokens'), scope },+ { data: [], updatedAt: 1 },+ );+ const network = deferred<ReturnType<typeof cells>>();+ vi.spyOn(messageService, 'getTokenHeatmaps').mockReturnValue(network.promise);++ renderHook(() => statsActions.useFetchHeatmap('tokens'), { wrapper });++ await waitFor(() => expect(statsSelectors.heatmap('tokens')(read())).toEqual([]));+ expect(statsSelectors.settledHeatmap('tokens')(read())).toBeUndefined();++ await act(async () => network.resolve([]));+ await waitFor(() => expect(statsSelectors.settledHeatmap('tokens')(read())).toEqual([]));+ });++ it('keeps a restored empty ranking unsettled until the server confirms it', async () => {+ await statsRankResource.storage!.set(+ { queryKey: statsRankResource.storageKey('topics'), scope },+ { data: [], updatedAt: 1 },+ );+ const network = deferred<never[]>();+ vi.spyOn(topicService, 'rankTopics').mockReturnValue(network.promise);++ renderHook(() => statsActions.useFetchRank('topics'), { wrapper });++ await waitFor(() => expect(statsSelectors.rank('topics')(read())).toEqual([]));+ expect(statsSelectors.settledRank('topics')(read())).toBeUndefined();++ await act(async () => network.resolve([]));+ await waitFor(() => expect(statsSelectors.settledRank('topics')(read())).toEqual([]));+ });++ it('surfaces the error when a restored empty ranking fails to refresh', async () => {+ await statsRankResource.storage!.set(+ { queryKey: statsRankResource.storageKey('models'), scope },+ { data: [], updatedAt: 1 },+ );+ vi.spyOn(messageService, 'rankModels').mockRejectedValue(new Error('offline'));++ const { result } = renderHook(() => statsActions.useFetchRank('models'), { wrapper });++ await waitFor(() => expect(result.current.error).toBeTruthy());+ // Unsettled data + an error: the card's AsyncBoundary renders the error and Retry.+ expect(statsSelectors.settledRank('models')(read())).toBeUndefined();+ });++ it('settles a restored non-empty ranking at once', async () => {+ const stored = [{ count: 3, id: 'gpt', name: 'gpt' }];+ await statsRankResource.storage!.set(+ { queryKey: statsRankResource.storageKey('models'), scope },+ { data: stored as never, updatedAt: 1 },+ );+ vi.spyOn(messageService, 'rankModels').mockReturnValue(new Promise(() => {}));++ renderHook(() => statsActions.useFetchRank('models'), { wrapper });++ await waitFor(() => expect(statsSelectors.settledRank('models')(read())).toEqual(stored));+ });++ it('answers every card that reads the token heatmap with one request', async () => {+ const spy = vi.spyOn(messageService, 'getTokenHeatmaps').mockResolvedValue(cells(1, 2));++ // TotalTokens, AiHeatmaps and HeatmapStats mount together on the page.+ renderHook(+ () => {+ statsActions.useFetchHeatmap('tokens');+ statsActions.useFetchHeatmap('tokens');+ statsActions.useFetchHeatmap('tokens');+ },+ { wrapper },+ );++ await waitFor(() => expect(statsSelectors.heatmap('tokens')(read())).toHaveLength(2));+ expect(spy).toHaveBeenCalledTimes(1);+ });++ it('keeps the last numbers when a background refresh fails', async () => {+ await statsHeatmapResource.storage!.set(+ { queryKey: statsHeatmapResource.storageKey('messages'), scope },+ { data: cells(4), updatedAt: 1 },+ );+ vi.spyOn(messageService, 'getHeatmaps').mockRejectedValue(new Error('offline'));++ const { result } = renderHook(() => statsActions.useFetchHeatmap('messages'), { wrapper });++ await waitFor(() => expect(result.current.error).toBeTruthy());+ expect(statsSelectors.heatmap('messages')(read())).toEqual(cells(4));+ });++ it('reads each picked month under its own entry', async () => {+ const spy = vi+ .spyOn(usageService, 'findAndGroupByDay')+ .mockImplementation(async (mo) => [{ day: mo }] as never);+ const thisMonth = dayjs().format('YYYY-MM');++ const { rerender } = renderHook(+ ({ month }: { month?: string }) => statsActions.useFetchUsageByDay(month),+ { initialProps: {} as { month?: string }, wrapper },+ );+ await waitFor(() => expect(statsSelectors.usageByDay()(read())).toEqual([{ day: thisMonth }]));+ // No picked month reads this calendar month by name.+ expect(spy).toHaveBeenLastCalledWith(thisMonth);++ rerender({ month: '2026-01' });+ await waitFor(() =>+ expect(statsSelectors.usageByDay('2026-01')(read())).toEqual([{ day: '2026-01' }]),+ );+ expect(spy).toHaveBeenLastCalledWith('2026-01');+ // The current month's copy is still there to switch back to.+ expect(statsSelectors.usageByDay()(read())).toEqual([{ day: thisMonth }]);+ });++ it("does not paint last month's usage under a new month", async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date(2026, 1, 3));+ await usageByDayResource.storage!.set(+ { queryKey: usageByDayResource.storageKey('2026-01'), scope },+ { data: [{ day: 'january' }] as never, updatedAt: 1 },+ );+ const network = deferred<never[]>();+ const spy = vi.spyOn(usageService, 'findAndGroupByDay').mockReturnValue(network.promise);++ const { result } = renderHook(() => statsActions.useFetchUsageByDay(), { wrapper });++ await waitFor(() => expect(result.current.isHydrated).toBe(true));+ expect(statsSelectors.usageByDay()(read())).toBeUndefined();+ expect(spy).toHaveBeenCalledWith('2026-02');++ await act(async () => network.resolve([{ day: 'february' }] as never));+ await waitFor(() => expect(statsSelectors.usageByDay()(read())).toEqual([{ day: 'february' }]));+ vi.useRealTimers();+ });++ it('surfaces the error when a restored empty usage table fails to refresh', async () => {+ await usageLogsResource.storage!.set(+ { queryKey: usageLogsResource.storageKey('2026-01'), scope },+ { data: [], updatedAt: 1 },+ );+ vi.spyOn(usageService, 'findByMonth').mockRejectedValue(new Error('offline'));++ const { result } = renderHook(() => statsActions.useFetchUsageLogs('2026-01'), { wrapper });++ await waitFor(() => expect(result.current.error).toBeTruthy());+ // Unsettled data + an error: the table's AsyncBoundary renders the error and Retry.+ expect(statsSelectors.settledUsageLogs('2026-01')(read())).toBeUndefined();+ });++ it('surfaces the error when a restored empty heatmap fails to refresh', async () => {+ await statsHeatmapResource.storage!.set(+ { queryKey: statsHeatmapResource.storageKey('messages'), scope },+ { data: [], updatedAt: 1 },+ );+ vi.spyOn(messageService, 'getHeatmaps').mockRejectedValue(new Error('offline'));++ const { result } = renderHook(() => statsActions.useFetchHeatmap('messages'), { wrapper });++ await waitFor(() => expect(result.current.error).toBeTruthy());+ expect(statsSelectors.settledHeatmap('messages')(read())).toBeUndefined();+ });++ it('reads a restored empty usage table as unconfirmed until the server answers', async () => {+ await usageLogsResource.storage!.set(+ { queryKey: usageLogsResource.storageKey('2026-01'), scope },+ { data: [], updatedAt: 1 },+ );+ const network = deferred<never[]>();+ vi.spyOn(usageService, 'findByMonth').mockReturnValue(network.promise);++ renderHook(() => statsActions.useFetchUsageLogs('2026-01'), { wrapper });++ await waitFor(() => expect(statsSelectors.usageLogs('2026-01')(read())).toEqual([]));+ expect(statsSelectors.settledUsageLogs('2026-01')(read())).toBeUndefined();++ await act(async () => network.resolve([]));+ await waitFor(() => expect(statsSelectors.settledUsageLogs('2026-01')(read())).toEqual([]));+ });++ it('seeds the stats page from storage before any card mounts', async () => {+ await statsTotalResource.storage!.set(+ { queryKey: statsTotalResource.storageKey('agents'), scope },+ { data: { count: 14, prevCount: 1 }, updatedAt: 1 },+ );+ await statsHeatmapResource.storage!.set(+ { queryKey: statsHeatmapResource.storageKey('tokens'), scope },+ { data: cells(3), updatedAt: 1 },+ );+ await usageByDayResource.storage!.set(+ { queryKey: usageByDayResource.storageKey(dayjs().format('YYYY-MM')), scope },+ { data: [{ day: 'stored' }] as never, updatedAt: 1 },+ );++ await statsActions.preHydrateStatsPage();++ // No `useSync` has mounted: the route loader alone filled the store.+ expect(statsSelectors.total('agents')(read())).toEqual({ count: 14, prevCount: 1 });+ expect(statsSelectors.heatmap('tokens')(read())).toEqual(cells(3));+ expect(statsSelectors.usageByDay()(read())).toEqual([{ day: 'stored' }]);+ expect(statsSelectors.settledHeatmap('tokens')(read())).toEqual(cells(3));+ });++ it("drops the previous identity's numbers on reset", async () => {+ vi.spyOn(topicService, 'countTopics').mockResolvedValue(3);+ renderHook(() => statsActions.useFetchTotal('topics'), { wrapper });+ await waitFor(() => expect(statsSelectors.total('topics')(read())?.count).toBe(3));+ cleanup();++ act(() => statsActions.reset());++ expect(statsSelectors.total('topics')(read())).toBeUndefined();+ await waitFor(async () =>+ expect(+ await statsTotalResource.storage!.get({+ queryKey: statsTotalResource.storageKey('topics'),+ scope,+ }),+ ).toBeUndefined(),+ );+ });+});diff --git a/src/store/stats/action.ts b/src/store/stats/action.tsnew file mode 100644index 00000000000..0de24af2eef--- /dev/null+++ b/src/store/stats/action.ts@@ -0,0 +1,297 @@+import { cacheScope, createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';+import { agentService } from '@/services/agent';+import { messageService } from '@/services/message';+import { topicService } from '@/services/topic';+import { usageService } from '@/services/usage';+import { userService } from '@/services/user';+import type { StoreSetter } from '@/store/types';+import type { AgentUsageStats } from '@/types/usage/usageRecord';+import { setNamespace } from '@/utils/storeDebug';+import { lastMonth, today } from '@/utils/time';++import { initialState, type StatsState } from './initialState';+import {+ type AgentUsageParams,+ agentUsageResource,+ SINGLE_KEY,+ type StatsCount,+ type StatsCountKind,+ statsCountResource,+ type StatsHeatmap,+ type StatsHeatmapKind,+ statsHeatmapResource,+ statsMaxTaskDurationResource,+ type StatsRankKind,+ type StatsRankMap,+ statsRankResource,+ type StatsRegistration,+ statsRegistrationResource,+ type StatsTotal,+ type StatsTotalKind,+ statsTotalResource,+ type UsageByDay,+ usageByDayResource,+ type UsageLogs,+ usageLogsResource,+ usageMonthKey,+} from './projection';+import { useStatsStore } from './store';++const n = setNamespace('stats');++type Setter = StoreSetter<StatsState>;++/**+ * Several cards read the same entry at once (the token heatmap feeds the total+ * card, the heatmap and its summary), so one request answers every mounted+ * reader. Explicit revalidations (retry) are not deduped.+ */+const STATS_DEDUPE_MS = 10_000;++const SYNC_OPTIONS = { dedupingInterval: STATS_DEDUPE_MS };++const STATS_TOTAL_KINDS: StatsTotalKind[] = ['agents', 'topics', 'messages'];+const STATS_RANK_KINDS: StatsRankKind[] = ['agents', 'models', 'topics'];++const fetchTotal = async (kind: StatsTotalKind): Promise<StatsTotal> => {+ switch (kind) {+ case 'agents': {+ return {+ count: await agentService.countAgents(),+ prevCount: await agentService.countAgents({ endDate: lastMonth().format('YYYY-MM-DD') }),+ };+ }+ case 'topics': {+ return {+ count: await topicService.countTopics(),+ prevCount: await topicService.countTopics({ endDate: lastMonth().format('YYYY-MM-DD') }),+ };+ }+ case 'messages': {+ // The total is a planner estimate, but the last-month baseline is derived+ // from it with an exact count of this month's messages (cheap — date-+ // bounded) rather than a second estimate: without multicolumn statistics+ // the planner can badly misjudge a user×date predicate, which would turn+ // the growth percentage next to the number into noise.+ const count = await messageService.countMessages({ approximate: true });+ const sinceLastMonth = await messageService.countMessages({+ startDate: lastMonth().add(1, 'day').format('YYYY-MM-DD'),+ });+ return { count, prevCount: Math.max(count - sinceLastMonth, 0) };+ }+ }+};++const fetchCount = async (kind: StatsCountKind): Promise<StatsCount> => {+ switch (kind) {+ // assistants are counted from the agents table — the sidebar list source of truth+ case 'agents': {+ return { count: await agentService.countAgents() };+ }+ case 'topics': {+ return { count: await topicService.countTopics() };+ }+ case 'messages': {+ return {+ count: await messageService.countMessages({ approximate: true }),+ // today's delta stays exact — it is small, cheap, and shown as "+N"+ today: await messageService.countMessages({ startDate: today().format('YYYY-MM-DD') }),+ };+ }+ }+};++const fetchRank = (kind: StatsRankKind): Promise<StatsRankMap[StatsRankKind]> => {+ switch (kind) {+ case 'agents': {+ return agentService.rankAgents();+ }+ case 'models': {+ return messageService.rankModels();+ }+ case 'topics': {+ return topicService.rankTopics();+ }+ }+};++export class StatsActionImpl {+ readonly #agentUsage;+ readonly #count;+ readonly #heatmap;+ readonly #maxTaskDuration;+ readonly #rank;+ readonly #registration;+ readonly #set: Setter;+ readonly #total;+ readonly #usageByDay;+ readonly #usageLogs;++ constructor(set: Setter, get: () => StatsState) {+ this.#set = set;++ this.#total = createReplicaSlice(statsTotalResource, {+ actionPrefix: 'statsTotal',+ fetcher: fetchTotal,+ get,+ set,+ stateKey: 'totalReplica',+ view: recordLens<StatsState, StatsTotal>('totalMap'),+ });+ this.#count = createReplicaSlice(statsCountResource, {+ actionPrefix: 'statsCount',+ fetcher: fetchCount,+ get,+ set,+ stateKey: 'countReplica',+ view: recordLens<StatsState, StatsCount>('countMap'),+ });+ this.#heatmap = createReplicaSlice(statsHeatmapResource, {+ actionPrefix: 'statsHeatmap',+ fetcher: (kind) =>+ kind === 'tokens' ? messageService.getTokenHeatmaps() : messageService.getHeatmaps(),+ get,+ set,+ stateKey: 'heatmapReplica',+ view: recordLens<StatsState, StatsHeatmap>('heatmapMap'),+ });+ this.#rank = createReplicaSlice(statsRankResource, {+ actionPrefix: 'statsRank',+ fetcher: fetchRank,+ get,+ set,+ stateKey: 'rankReplica',+ view: recordLens<StatsState, StatsRankMap[StatsRankKind]>('rankMap'),+ });+ this.#registration = createReplicaSlice(statsRegistrationResource, {+ actionPrefix: 'statsRegistration',+ fetcher: () => userService.getUserRegistrationDuration(),+ get,+ set,+ stateKey: 'registrationReplica',+ view: recordLens<StatsState, StatsRegistration>('registrationMap'),+ });+ this.#maxTaskDuration = createReplicaSlice(statsMaxTaskDurationResource, {+ actionPrefix: 'statsMaxTaskDuration',+ fetcher: () => topicService.getMaxTaskDuration(),+ get,+ set,+ stateKey: 'maxTaskDurationReplica',+ view: recordLens<StatsState, number>('maxTaskDurationMap'),+ });+ this.#usageByDay = createReplicaSlice(usageByDayResource, {+ actionPrefix: 'usageByDay',+ fetcher: (month) => usageService.findAndGroupByDay(month),+ get,+ set,+ stateKey: 'usageByDayReplica',+ view: recordLens<StatsState, UsageByDay>('usageByDayMap'),+ });+ this.#usageLogs = createReplicaSlice(usageLogsResource, {+ actionPrefix: 'usageLogs',+ fetcher: (month) => usageService.findByMonth(month),+ get,+ set,+ stateKey: 'usageLogsReplica',+ view: recordLens<StatsState, UsageLogs>('usageLogsMap'),+ });+ this.#agentUsage = createReplicaSlice(agentUsageResource, {+ actionPrefix: 'agentUsage',+ fetcher: (params) => usageService.getAgentUsageStats(params),+ get,+ set,+ stateKey: 'agentUsageReplica',+ view: recordLens<StatsState, AgentUsageStats>('agentUsageMap'),+ });+ }++ useFetchTotal = (kind: StatsTotalKind): ReplicaSyncResult =>+ this.#total.useSync(kind, SYNC_OPTIONS);++ useFetchCount = (kind: StatsCountKind): ReplicaSyncResult =>+ this.#count.useSync(kind, SYNC_OPTIONS);++ useFetchHeatmap = (kind: StatsHeatmapKind): ReplicaSyncResult =>+ this.#heatmap.useSync(kind, SYNC_OPTIONS);++ useFetchRank = (kind: StatsRankKind): ReplicaSyncResult => this.#rank.useSync(kind, SYNC_OPTIONS);++ useFetchRegistration = (): ReplicaSyncResult =>+ this.#registration.useSync(SINGLE_KEY, SYNC_OPTIONS);++ useFetchMaxTaskDuration = (): ReplicaSyncResult =>+ this.#maxTaskDuration.useSync(SINGLE_KEY, SYNC_OPTIONS);++ /** `month` is `YYYY-MM`; omitted reads the current month. */+ useFetchUsageByDay = (month?: string): ReplicaSyncResult =>+ this.#usageByDay.useSync(usageMonthKey(month), SYNC_OPTIONS);++ useFetchUsageLogs = (month?: string): ReplicaSyncResult =>+ this.#usageLogs.useSync(usageMonthKey(month), SYNC_OPTIONS);++ useFetchAgentUsage = (params: AgentUsageParams | null): ReplicaSyncResult =>+ this.#agentUsage.useSync(params, SYNC_OPTIONS);++ /**+ * Seed the persisted Settings → Stats entries before the route commits (see+ * `statsPageLoader`): `useSync` only hydrates after mount, which would leave+ * the cards on their loading state for the IndexedDB read.+ */+ preHydrateStatsPage = (): Promise<unknown> => {+ const scope = cacheScope.get();+ // The slots may still hold the previous identity's rows; drop them before seeding.+ for (const slice of [+ this.#total,+ this.#heatmap,+ this.#rank,+ this.#registration,+ this.#maxTaskDuration,+ this.#usageByDay,+ this.#usageLogs,+ ]) {+ slice.ensureScope(scope);+ }++ return Promise.all([+ ...STATS_TOTAL_KINDS.map((kind) => this.#total.hydrate(kind, scope)),+ // The heatmap opens on its token tab.+ this.#heatmap.hydrate('tokens', scope),+ ...STATS_RANK_KINDS.map((kind) => this.#rank.hydrate(kind, scope)),+ this.#registration.hydrate(SINGLE_KEY, scope),+ this.#maxTaskDuration.hydrate(SINGLE_KEY, scope),+ // The usage section opens on the current month.+ this.#usageByDay.hydrate(usageMonthKey(), scope),+ this.#usageLogs.hydrate(usageMonthKey(), scope),+ ]);+ };++ /** Same as `preHydrateStatsPage`, for an agent's usage tab (`agentUsageLoader`). */+ preHydrateAgentUsage = (params: AgentUsageParams): Promise<boolean> => {+ const scope = cacheScope.get();+ this.#agentUsage.ensureScope(scope);+ return this.#agentUsage.hydrate(params, scope);+ };++ reset = (): void => {+ // `clear()` drops in-flight reads of the previous data context and this+ // scope's persisted rows, so a new identity never paints the old numbers.+ for (const slice of [+ this.#agentUsage,+ this.#count,+ this.#heatmap,+ this.#maxTaskDuration,+ this.#rank,+ this.#registration,+ this.#total,+ this.#usageByDay,+ this.#usageLogs,+ ]) {+ void slice.clear();+ }+ this.#set(initialState, false, n('reset'));+ };+}++const { getState, setState } = useStatsStore;++export const statsActions = new StatsActionImpl(setState, getState);diff --git a/src/store/stats/index.ts b/src/store/stats/index.tsnew file mode 100644index 00000000000..ff546fb3bd1--- /dev/null+++ b/src/store/stats/index.ts@@ -0,0 +1,4 @@+export { statsActions } from './action';+export type { AgentUsageParams, StatsHeatmapKind, StatsRankKind } from './projection';+export { statsSelectors } from './selectors';+export { useStatsStore } from './store';diff --git a/src/store/stats/initialState.ts b/src/store/stats/initialState.tsnew file mode 100644index 00000000000..1a4fac13d59--- /dev/null+++ b/src/store/stats/initialState.ts@@ -0,0 +1,64 @@+import { createReplicaState, type ReplicaState } from '@/libs/replica';+import type { AgentUsageStats } from '@/types/usage/usageRecord';++import type {+ StatsCount,+ StatsHeatmap,+ StatsRankKind,+ StatsRankMap,+ StatsRegistration,+ StatsTotal,+ UsageByDay,+ UsageLogs,+} from './projection';++export interface StatsState {+ /** One agent's usage per `agentUsageKey` (replica view). */+ agentUsageMap: Record<string, AgentUsageStats>;+ agentUsageReplica: ReplicaState<AgentUsageStats>;+ /** User panel counters per `StatsCountKind` (replica view). */+ countMap: Record<string, StatsCount>;+ countReplica: ReplicaState<StatsCount>;+ /** Daily activity cells per `StatsHeatmapKind` (replica view). */+ heatmapMap: Record<string, StatsHeatmap>;+ heatmapReplica: ReplicaState<StatsHeatmap>;+ /** Longest task duration (ms) under `SINGLE_KEY` (replica view). */+ maxTaskDurationMap: Record<string, number>;+ maxTaskDurationReplica: ReplicaState<number>;+ /** Top agents / models / topics per `StatsRankKind` (replica view). */+ rankMap: Partial<StatsRankMap>;+ rankReplica: ReplicaState<StatsRankMap[StatsRankKind]>;+ /** Account age under `SINGLE_KEY` (replica view). */+ registrationMap: Record<string, StatsRegistration>;+ registrationReplica: ReplicaState<StatsRegistration>;+ /** Overview totals per `StatsTotalKind` (replica view). */+ totalMap: Record<string, StatsTotal>;+ totalReplica: ReplicaState<StatsTotal>;+ /** Daily usage per month key (replica view). */+ usageByDayMap: Record<string, UsageByDay>;+ usageByDayReplica: ReplicaState<UsageByDay>;+ /** Usage records per month key (replica view). */+ usageLogsMap: Record<string, UsageLogs>;+ usageLogsReplica: ReplicaState<UsageLogs>;+}++export const initialState: StatsState = {+ agentUsageMap: {},+ agentUsageReplica: createReplicaState(),+ countMap: {},+ countReplica: createReplicaState(),+ heatmapMap: {},+ heatmapReplica: createReplicaState(),+ maxTaskDurationMap: {},+ maxTaskDurationReplica: createReplicaState(),+ rankMap: {},+ rankReplica: createReplicaState(),+ registrationMap: {},+ registrationReplica: createReplicaState(),+ totalMap: {},+ totalReplica: createReplicaState(),+ usageByDayMap: {},+ usageByDayReplica: createReplicaState(),+ usageLogsMap: {},+ usageLogsReplica: createReplicaState(),+};diff --git a/src/store/stats/projection.ts b/src/store/stats/projection.tsnew file mode 100644index 00000000000..942947d1574--- /dev/null+++ b/src/store/stats/projection.ts@@ -0,0 +1,144 @@+import type { AgentRankItem, ModelRankItem, TopicRankItem } from '@lobechat/types';+import type { HeatmapsProps } from '@lobehub/charts';+import dayjs from 'dayjs';++import { defineReplica } from '@/libs/replica';+import type { usageService } from '@/services/usage';+import type { AgentUsageGranularity, AgentUsageStats } from '@/types/usage/usageRecord';++/** The overview totals on Settings → Stats. */+export type StatsTotalKind = 'agents' | 'messages' | 'topics';++/** A total and its value at the end of last month (the month-over-month baseline). */+export interface StatsTotal {+ count: number;+ prevCount: number;+}++/** The user panel's counters (`DataStatistics`). */+export type StatsCountKind = 'agents' | 'messages' | 'topics';++export interface StatsCount {+ count: number;+ /** Messages only: today's exact delta, shown as "+N". */+ today?: number;+}++export type StatsHeatmapKind = 'messages' | 'tokens';++export type StatsHeatmap = HeatmapsProps['data'];++export interface StatsRankMap {+ agents: AgentRankItem[];+ models: ModelRankItem[];+ topics: TopicRankItem[];+}++export type StatsRankKind = keyof StatsRankMap;++export interface StatsRegistration {+ createdAt: string;+ duration: number;+ updatedAt: string;+}++export type UsageByDay = Awaited<ReturnType<typeof usageService.findAndGroupByDay>>;+export type UsageLogs = Awaited<ReturnType<typeof usageService.findByMonth>>;++export interface AgentUsageParams {+ agentId: string;+ endAt: string;+ granularity: AgentUsageGranularity;+ startAt: string;+}++/** The only entry of a resource that answers one parameterless read. */+export const SINGLE_KEY = 'self';++/**+ * Every stats read is persisted to IndexedDB under the replica's user ++ * workspace scope, so Settings → Stats, the user panel and an agent's usage tab+ * paint the last numbers on reload and revalidate in the background.+ */+export const statsTotalResource = defineReplica<StatsTotalKind, StatsTotal>({+ key: (kind) => kind,+ name: 'statsTotal',+ storage: 'indexedDB',+ version: 1,+});++export const statsCountResource = defineReplica<StatsCountKind, StatsCount>({+ key: (kind) => kind,+ name: 'statsCount',+ storage: 'indexedDB',+ version: 1,+});++/** A year of daily cells per heatmap. */+export const statsHeatmapResource = defineReplica<StatsHeatmapKind, StatsHeatmap>({+ key: (kind) => kind,+ name: 'statsHeatmap',+ storage: 'indexedDB',+ version: 1,+});++export const statsRankResource = defineReplica<StatsRankKind, StatsRankMap[StatsRankKind]>({+ key: (kind) => kind,+ name: 'statsRank',+ storage: 'indexedDB',+ version: 1,+});++export const statsRegistrationResource = defineReplica<typeof SINGLE_KEY, StatsRegistration>({+ key: () => SINGLE_KEY,+ name: 'statsRegistration',+ storage: 'indexedDB',+ version: 1,+});++export const statsMaxTaskDurationResource = defineReplica<typeof SINGLE_KEY, number>({+ key: () => SINGLE_KEY,+ name: 'statsMaxTaskDuration',+ storage: 'indexedDB',+ version: 1,+});++/**+ * Month key (`YYYY-MM`). No picked month means this calendar month, read by+ * its own key: a fixed "current" key would paint last month's persisted usage+ * under this month's picker after a month rolls over.+ */+export const usageMonthKey = (month?: string): string => month || dayjs().format('YYYY-MM');++/** Daily usage of one month — the usage cards and trend chart. */+export const usageByDayResource = defineReplica<string, UsageByDay>({+ key: (month) => month,+ name: 'usageByDay',+ persist: { maxEntries: 6 },+ storage: 'indexedDB',+ version: 1,+});++/**+ * Every usage record of one month (the usage table). One row per model call,+ * so a busy month is large: only the last two months viewed survive a reload.+ */+export const usageLogsResource = defineReplica<string, UsageLogs>({+ key: (month) => month,+ name: 'usageLogs',+ persist: { maxEntries: 2 },+ storage: 'indexedDB',+ version: 1,+});++export const agentUsageKey = ({ agentId, endAt, granularity, startAt }: AgentUsageParams) =>+ [agentId, startAt, endAt, granularity].join('|');++/** One agent's usage + cost over a date range (the agent's usage tab). */+export const agentUsageResource = defineReplica<AgentUsageParams, AgentUsageStats>({+ key: agentUsageKey,+ name: 'agentUsage',+ persist: { maxEntries: 20 },+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/stats/selectors.ts b/src/store/stats/selectors.tsnew file mode 100644index 00000000000..4dee3ed4cc0--- /dev/null+++ b/src/store/stats/selectors.ts@@ -0,0 +1,112 @@+import type { AgentUsageStats } from '@/types/usage/usageRecord';++import type { StatsState } from './initialState';+import {+ agentUsageKey,+ type AgentUsageParams,+ SINGLE_KEY,+ type StatsCount,+ type StatsCountKind,+ type StatsHeatmap,+ type StatsHeatmapKind,+ type StatsRankKind,+ type StatsRankMap,+ type StatsRegistration,+ type StatsTotal,+ type StatsTotalKind,+ type UsageByDay,+ type UsageLogs,+ usageMonthKey,+} from './projection';++/** Each read is `undefined` until the local copy or the server fills it. */+const total =+ (kind: StatsTotalKind) =>+ (s: StatsState): StatsTotal | undefined =>+ s.totalMap[kind];++const count =+ (kind: StatsCountKind) =>+ (s: StatsState): StatsCount | undefined =>+ s.countMap[kind];++const heatmap =+ (kind: StatsHeatmapKind) =>+ (s: StatsState): StatsHeatmap | undefined =>+ s.heatmapMap[kind];++/**+ * The heatmap once it can be shown as is: a restored empty year may predate the+ * user's first message, so it stays `undefined` (loading, or the fetch error)+ * until this session's server answer confirms it.+ */+const settledHeatmap =+ (kind: StatsHeatmapKind) =>+ (s: StatsState): StatsHeatmap | undefined => {+ const data = s.heatmapMap[kind];+ if (!data || data.length > 0) return data;+ return s.heatmapReplica.entries[kind]?.source === 'server' ? data : undefined;+ };++const rank =+ <K extends StatsRankKind>(kind: K) =>+ (s: StatsState): StatsRankMap[K] | undefined =>+ s.rankMap[kind] as StatsRankMap[K] | undefined;++/**+ * The ranking once it can be shown as is: a restored empty ranking predates any+ * activity since, so it stays `undefined` (loading, or the fetch error) until+ * this session's server answer confirms it.+ */+const settledRank =+ <K extends StatsRankKind>(kind: K) =>+ (s: StatsState): StatsRankMap[K] | undefined => {+ const data = rank(kind)(s);+ if (!data || data.length > 0) return data;+ return s.rankReplica.entries[kind]?.source === 'server' ? data : undefined;+ };++const registration = (s: StatsState): StatsRegistration | undefined =>+ s.registrationMap[SINGLE_KEY];++const maxTaskDuration = (s: StatsState): number | undefined => s.maxTaskDurationMap[SINGLE_KEY];++const usageByDay =+ (month?: string) =>+ (s: StatsState): UsageByDay | undefined =>+ s.usageByDayMap[usageMonthKey(month)];++const usageLogs =+ (month?: string) =>+ (s: StatsState): UsageLogs | undefined =>+ s.usageLogsMap[usageMonthKey(month)];++/** Same as `settledHeatmap`: a restored empty month is not "no usage" until the server says so. */+const settledUsageLogs =+ (month?: string) =>+ (s: StatsState): UsageLogs | undefined => {+ const key = usageMonthKey(month);+ const data = s.usageLogsMap[key];+ if (!data || data.length > 0) return data;+ return s.usageLogsReplica.entries[key]?.source === 'server' ? data : undefined;+ };++const agentUsage =+ (params: AgentUsageParams | null) =>+ (s: StatsState): AgentUsageStats | undefined =>+ params ? s.agentUsageMap[agentUsageKey(params)] : undefined;++export const statsSelectors = {+ agentUsage,+ count,+ heatmap,+ maxTaskDuration,+ rank,+ settledHeatmap,+ settledRank,+ settledUsageLogs,+ registration,+ total,+ usageByDay,+ usageLogs,+};diff --git a/src/store/stats/store.ts b/src/store/stats/store.tsnew file mode 100644index 00000000000..eaec5d3a6fd--- /dev/null+++ b/src/store/stats/store.ts@@ -0,0 +1,15 @@+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';++import { createDevtools } from '../middleware/createDevtools';+import { expose } from '../middleware/expose';+import { initialState, type StatsState } from './initialState';++const devtools = createDevtools('stats');++export const useStatsStore = createWithEqualityFn<StatsState>()(+ devtools(() => initialState),+ shallow,+);++expose('stats', useStatsStore);diff --git a/src/store/utils/userDataStores.test.ts b/src/store/utils/userDataStores.test.tsindex 02761f05a5d..5b331029da2 100644--- a/src/store/utils/userDataStores.test.ts+++ b/src/store/utils/userDataStores.test.ts@@ -6,6 +6,7 @@ const expertiseReset = vi.hoisted(() => vi.fn());const pageReset = vi.hoisted(() => vi.fn());const resourcePermissionReset = vi.hoisted(() => vi.fn());const sandboxReset = vi.hoisted(() => vi.fn());+const statsReset = vi.hoisted(() => vi.fn());const workReset = vi.hoisted(() => vi.fn());const fakeStore = vi.hoisted(() => () => ({getState: () => {@@ -38,6 +39,7 @@ vi.mock('@/store/resourcePermission', () => ({resourcePermissionActions: { reset: resourcePermissionReset },}));vi.mock('@/store/sandbox', () => ({ sandboxActions: { reset: sandboxReset } }));+vi.mock('@/store/stats', () => ({ statsActions: { reset: statsReset } }));vi.mock('@/store/session', () => ({ useSessionStore: fakeStore() }));vi.mock('@/store/task', () => ({ useTaskStore: fakeStore() }));vi.mock('@/store/tool', () => ({ useToolStore: fakeStore() }));@@ -54,6 +56,7 @@ describe('stores.reset', () => {pageReset.mockClear();resourcePermissionReset.mockClear();sandboxReset.mockClear();+ statsReset.mockClear();workReset.mockClear();});@@ -73,6 +76,8 @@ describe('stores.reset', () => {// outlive the data context, even when the next one reuses the scope string.expect(resourcePermissionReset).toHaveBeenCalledTimes(1);expect(sandboxReset).toHaveBeenCalledTimes(1);+ // Another identity must not paint the previous one's usage numbers.+ expect(statsReset).toHaveBeenCalledTimes(1);expect(workReset).toHaveBeenCalledTimes(1);for (const reset of storeResets) expect(reset).toHaveBeenCalledTimes(1);expect(order[0]).toBe('mux');diff --git a/src/store/utils/userDataStores.ts b/src/store/utils/userDataStores.tsindex 4ebad196631..d6a3a8021a4 100644--- a/src/store/utils/userDataStores.ts+++ b/src/store/utils/userDataStores.ts@@ -22,6 +22,7 @@ import { projectFileActions } from '@/store/projectFile';import { resourcePermissionActions } from '@/store/resourcePermission';import { sandboxActions } from '@/store/sandbox';import { useSessionStore } from '@/store/session';+import { statsActions } from '@/store/stats';import { useTaskStore } from '@/store/task';import { useToolStore } from '@/store/tool';import { useUserStore } from '@/store/user';@@ -64,6 +65,7 @@ const resetableActions: ResetableStore[] = [projectFileActions,resourcePermissionActions,sandboxActions,+ statsActions,workActions,];