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.

πŸ› fix(stats): restore page switching in the usage table (#18247)

LiJian0845f703f23d
diff --git a/src/features/Settings/stats/features/usage/UsageTable.test.tsx b/src/features/Settings/stats/features/usage/UsageTable.test.tsx
new file mode 100644
index 00000000000..a8a197c53d2
--- /dev/null
+++ b/src/features/Settings/stats/features/usage/UsageTable.test.tsx
@@ -0,0 +1,103 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { MemoryRouter } from 'react-router';
+import { describe, expect, it, vi } from 'vitest';
+
+import UsageTable from './UsageTable';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@lobehub/icons', () => ({
+ ProviderIcon: ({ provider }: { provider: string }) => <span>{provider}</span>,
+}));
+
+const rows = Array.from({ length: 12 }, (_, index) => ({
+ createdAt: new Date(2026, 0, index + 1).toISOString(),
+ id: `row-${index + 1}`,
+ model: 'gpt-5-mini',
+ provider: 'openai',
+ spend: index,
+ totalInputTokens: index,
+ totalOutputTokens: index,
+ totalTokens: index * 2,
+ tps: 1,
+ ttft: 1,
+ type: 'chat',
+}));
+
+vi.mock('@/libs/swr', () => ({
+ useClientDataSWR: () => ({ data: rows, isLoading: false, mutate: vi.fn() }),
+}));
+
+vi.mock('@/services/usage', () => ({
+ usageService: { findByMonth: vi.fn() },
+}));
+
+// The rows on screen are the assertion, so the table only has to report which
+// slice it was handed.
+vi.mock('@/components/InlineTable', () => ({
+ default: ({ dataSource }: { dataSource?: { id: string }[] }) => (
+ <div data-testid="rows">{dataSource?.map((row) => row.id).join(',')}</div>
+ ),
+}));
+
+// Stands in for the real footer, whose `onChange` likewise reports the page and
+// the page size together on every interaction.
+vi.mock('@/components/TablePagination', () => ({
+ default: ({
+ current,
+ onChange,
+ pageSize,
+ }: {
+ current: number;
+ onChange: (page: number, size: number) => void;
+ pageSize: number;
+ }): ReactNode => (
+ <div>
+ <button type="button" onClick={() => onChange(current + 1, pageSize)}>
+ next-page
+ </button>
+ <button type="button" onClick={() => onChange(1, 10)}>
+ resize
+ </button>
+ </div>
+ ),
+}));
+
+const renderTable = () =>
+ render(
+ <MemoryRouter>
+ <UsageTable />
+ </MemoryRouter>,
+ );
+
+describe('UsageTable', () => {
+ it('moves to the next page when only the page changes', async () => {
+ renderTable();
+ expect(screen.getByTestId('rows')).toHaveTextContent('row-1,row-2,row-3,row-4,row-5');
+
+ // Page and page size are written in one update. Writing them through two
+ // separate query-param setters lost the page, because the second setter
+ // rebuilt the URL from the params captured before the first one navigated.
+ await userEvent.click(screen.getByText('next-page'));
+
+ expect(screen.getByTestId('rows')).toHaveTextContent('row-6,row-7,row-8,row-9,row-10');
+ });
+
+ it('keeps the page the size picker asked for when the page size changes', async () => {
+ renderTable();
+
+ await userEvent.click(screen.getByText('next-page'));
+ await userEvent.click(screen.getByText('resize'));
+
+ expect(screen.getByTestId('rows')).toHaveTextContent(
+ 'row-1,row-2,row-3,row-4,row-5,row-6,row-7,row-8,row-9,row-10',
+ );
+ });
+});
diff --git a/src/features/Settings/stats/features/usage/UsageTable.tsx b/src/features/Settings/stats/features/usage/UsageTable.tsx
index 1c24d939027..61adf2d7c4c 100644
--- a/src/features/Settings/stats/features/usage/UsageTable.tsx
+++ b/src/features/Settings/stats/features/usage/UsageTable.tsx
@@ -9,7 +9,7 @@ import InlineTable from '@/components/InlineTable';
import SpendType, { type SpendTypeValue } from '@/components/SpendType';
import TablePagination from '@/components/TablePagination';
import TotalToken from '@/components/TotalToken';
-import { parseAsInteger, useQueryParam } from '@/hooks/useQueryParam';
+import { parseAsInteger, useQueryStates } from '@/hooks/useQueryParam';
import { useClientDataSWR } from '@/libs/swr';
import { statsKeys } from '@/libs/swr/keys';
import { usageService } from '@/services/usage';
@@ -19,6 +19,7 @@ import { type UsageChartProps } from '../../types';
/** Sizes small enough to keep the table from crowding out the rest of the page. */
const PAGE_SIZE_OPTIONS = [5, 10, 20, 50];
+const DEFAULT_PAGE_SIZE = PAGE_SIZE_OPTIONS[0];
/**
* Sortable columns and the number each row sorts by. Pagination is ours now, so
@@ -53,12 +54,16 @@ const UsageTable = memo<UsageChartProps>(({ dateStrings }) => {
usageService.findByMonth(dateStrings),
);
- const [currentPage, setCurrentPage] = useQueryParam('current', parseAsInteger.withDefault(1), {
- clearOnDefault: true,
- });
- const [pageSize, setPageSize] = useQueryParam('pageSize', parseAsInteger.withDefault(5), {
- clearOnDefault: true,
- });
+ // 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
+ // navigation: see `useQueryStates`.
+ const [{ current: currentPage, pageSize }, setPagination] = useQueryStates(
+ {
+ current: parseAsInteger.withDefault(1),
+ pageSize: parseAsInteger.withDefault(DEFAULT_PAGE_SIZE),
+ },
+ { clearOnDefault: true },
+ );
const [sort, setSort] = useState<SortState | null>(null);
useEffect(() => {
@@ -181,7 +186,7 @@ const UsageTable = memo<UsageChartProps>(({ dateStrings }) => {
setSort(next?.order && SORT_VALUES[field] ? { field, order: next.order } : null);
// A re-sort makes the current page a different set of rows; start
// from the top rather than dropping the reader into the middle.
- setCurrentPage(1);
+ setPagination({ current: 1 });
}}
/>
{total > 0 && (
@@ -191,10 +196,9 @@ const UsageTable = memo<UsageChartProps>(({ dateStrings }) => {
pageSize={pageSize}
pageSizeOptions={PAGE_SIZE_OPTIONS}
total={total}
- onChange={(nextPage, nextPageSize) => {
- setCurrentPage(nextPage);
- setPageSize(nextPageSize);
- }}
+ onChange={(nextPage, nextPageSize) =>
+ setPagination({ current: nextPage, pageSize: nextPageSize })
+ }
/>
)}
</>
diff --git a/src/hooks/useQueryParam.test.tsx b/src/hooks/useQueryParam.test.tsx
new file mode 100644
index 00000000000..ec6fbabee58
--- /dev/null
+++ b/src/hooks/useQueryParam.test.tsx
@@ -0,0 +1,89 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { MemoryRouter, useLocation } from 'react-router';
+import { describe, expect, it } from 'vitest';
+
+import { parseAsInteger, parseAsString, useQueryStates } from './useQueryParam';
+
+const wrapper = ({ children }: { children: ReactNode }) => <MemoryRouter>{children}</MemoryRouter>;
+
+const renderPagination = () =>
+ renderHook(
+ () => ({
+ pagination: useQueryStates(
+ {
+ current: parseAsInteger.withDefault(1),
+ pageSize: parseAsInteger.withDefault(5),
+ },
+ { clearOnDefault: true },
+ ),
+ search: useLocation().search,
+ }),
+ { wrapper },
+ );
+
+describe('useQueryStates', () => {
+ it('reads defaults when the params are absent', () => {
+ const { result } = renderPagination();
+
+ expect(result.current.pagination[0]).toEqual({ current: 1, pageSize: 5 });
+ });
+
+ it('writes every param in a single navigation', () => {
+ const { result } = renderPagination();
+
+ // The page moves while the size stays at its default. Two separate setters
+ // would each rebuild the URL from the params captured before the other one
+ // navigated, so the page silently lost the race.
+ act(() => result.current.pagination[1]({ current: 3, pageSize: 5 }));
+
+ expect(result.current.pagination[0]).toEqual({ current: 3, pageSize: 5 });
+ expect(result.current.search).toBe('?current=3');
+ });
+
+ it('drops params that are back at their default when clearOnDefault is set', () => {
+ const { result } = renderPagination();
+
+ act(() => result.current.pagination[1]({ current: 3, pageSize: 20 }));
+ act(() => result.current.pagination[1]({ current: 1, pageSize: 5 }));
+
+ expect(result.current.search).toBe('');
+ });
+
+ it('leaves params it was not given alone', () => {
+ const { result } = renderPagination();
+
+ act(() => result.current.pagination[1]({ current: 2, pageSize: 20 }));
+ act(() => result.current.pagination[1]({ pageSize: 50 }));
+
+ expect(result.current.pagination[0]).toEqual({ current: 2, pageSize: 50 });
+ });
+
+ it('hands the updater the current values', () => {
+ const { result } = renderPagination();
+
+ act(() => result.current.pagination[1]({ current: 2 }));
+ act(() => result.current.pagination[1](({ current }) => ({ current: current + 1 })));
+
+ expect(result.current.pagination[0].current).toBe(3);
+ });
+
+ it('removes a param when its value serializes to null', () => {
+ const { result } = renderHook(
+ () => ({
+ state: useQueryStates({ q: parseAsString }),
+ search: useLocation().search,
+ }),
+ { wrapper },
+ );
+
+ act(() => result.current.state[1]({ q: 'lobe' }));
+ expect(result.current.search).toBe('?q=lobe');
+
+ act(() => result.current.state[1]({ q: null }));
+ expect(result.current.search).toBe('');
+ });
+});
diff --git a/src/hooks/useQueryParam.ts b/src/hooks/useQueryParam.ts
index 70d58fa1562..ded3031cc8e 100644
--- a/src/hooks/useQueryParam.ts
+++ b/src/hooks/useQueryParam.ts
@@ -153,6 +153,114 @@ export function useQueryParam<T>(
return [value, setValue];
}
+type ParserMap = Record<string, Parser<any> | ParserWithDefault<any>>;
+
+type QueryStatesValues<P extends ParserMap> = {
+ [K in keyof P]: P[K] extends Parser<infer T> ? T : never;
+};
+
+const readValues = <P extends ParserMap>(
+ parsers: P,
+ searchParams: URLSearchParams,
+): QueryStatesValues<P> =>
+ Object.fromEntries(
+ Object.keys(parsers).map((key) => {
+ const parser = parsers[key];
+ const parsed = parser.parse(searchParams.get(key));
+ return [key, parsed ?? (parser as ParserWithDefault<any>).defaultValue];
+ }),
+ ) as QueryStatesValues<P>;
+
+/**
+ * Read and write several query params that belong together.
+ *
+ * `useQueryParam`'s setter navigates on its own, and react-router hands the
+ * functional updater the params it captured at render time β€” not the live URL.
+ * So two setters fired from one event handler both start from the pre-event
+ * params and the second navigation drops whatever the first one wrote. Params
+ * that change together have to travel in a single update; this hook is that
+ * update.
+ */
+export function useQueryStates<P extends ParserMap>(
+ parsers: P,
+ options: Pick<QueryParamOptions<never>, 'clearOnDefault' | 'history'> = {},
+): [
+ QueryStatesValues<P>,
+ (
+ updates:
+ | Partial<QueryStatesValues<P>>
+ | ((prev: QueryStatesValues<P>) => Partial<QueryStatesValues<P>>),
+ ) => void,
+] {
+ const [searchParams, setSearchParams] = useSearchParams();
+
+ const { clearOnDefault = false, history = 'push' } = options;
+
+ // Refs keep `setValues` stable while still reading the latest config.
+ const parsersRef = useRef(parsers);
+ const searchParamsRef = useRef(searchParams);
+ const clearOnDefaultRef = useRef(clearOnDefault);
+ const historyRef = useRef(history);
+
+ useEffect(() => {
+ parsersRef.current = parsers;
+ searchParamsRef.current = searchParams;
+ clearOnDefaultRef.current = clearOnDefault;
+ historyRef.current = history;
+ });
+
+ const values = readValues(parsers, searchParams);
+
+ const setValues = useCallback(
+ (
+ updates:
+ | Partial<QueryStatesValues<P>>
+ | ((prev: QueryStatesValues<P>) => Partial<QueryStatesValues<P>>),
+ ) => {
+ const currentParsers = parsersRef.current;
+ const currentClearOnDefault = clearOnDefaultRef.current;
+ const currentHistory = historyRef.current;
+
+ const patch =
+ typeof updates === 'function'
+ ? updates(readValues(currentParsers, searchParamsRef.current))
+ : updates;
+
+ setSearchParams(
+ (prevParams) => {
+ const newSearchParams = new URLSearchParams(prevParams);
+
+ for (const key of Object.keys(patch)) {
+ const parser = currentParsers[key];
+ if (!parser) continue;
+
+ const serialized = parser.serialize(patch[key]);
+ const defaultValue = (parser as ParserWithDefault<any>).defaultValue;
+
+ if (
+ currentClearOnDefault &&
+ defaultValue !== undefined &&
+ serialized === parser.serialize(defaultValue)
+ ) {
+ newSearchParams.delete(key);
+ } else if (serialized === null || serialized === undefined) {
+ newSearchParams.delete(key);
+ } else {
+ newSearchParams.set(key, serialized);
+ }
+ }
+
+ return newSearchParams;
+ },
+ { replace: currentHistory === 'replace' },
+ );
+ },
+ [setSearchParams],
+ );
+
+ return [values, setValues];
+}
+
// ===== Parsers =====
/**