Skip to content

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

💄 style(settings): polish workspace settings pages (#17696)

René Wangbd73f6b53268
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 4bc59cc2b5e..7f4c0c70a37 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -2656,6 +2656,8 @@
"workspaceSetting.group.agent": "Agent",
"workspaceSetting.group.general": "General",
"workspaceSetting.storage.comingSoon": "Workspace-scoped data import & export is coming soon.",
+ "workspaceSetting.storage.danger.reset.confirm.content": "Every workspace setting goes back to its default, for everyone in the workspace. Agents, conversations, and files are not touched.",
+ "workspaceSetting.storage.danger.reset.confirm.ok": "Reset Settings",
"workspaceSetting.storage.danger.reset.desc": "Restore all workspace settings to defaults. Workspace data will not be deleted.",
"workspaceSetting.storage.danger.reset.title": "Reset Workspace Settings",
"workspaceSetting.storage.telemetry.desc": "Help us improve {{appName}} with anonymous workspace usage data",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 0a1b593cedd..8b2138d193d 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -2656,6 +2656,8 @@
"workspaceSetting.group.agent": "智能体",
"workspaceSetting.group.general": "通用",
"workspaceSetting.storage.comingSoon": "工作区范围的数据导入和导出即将推出。",
+ "workspaceSetting.storage.danger.reset.confirm.content": "工作区的所有设置都会恢复为默认值,对工作区中的每个人生效。智能体、会话和文件不受影响。",
+ "workspaceSetting.storage.danger.reset.confirm.ok": "重置设置",
"workspaceSetting.storage.danger.reset.desc": "将所有工作区设置恢复为默认值。工作区数据不会被删除。",
"workspaceSetting.storage.danger.reset.title": "重置工作区设置",
"workspaceSetting.storage.telemetry.desc": "通过匿名工作区使用数据帮助我们改进 {{appName}}",
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index fccaedff00a..2dfbb9373a1 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -2891,6 +2891,9 @@ When I am ___, I need ___
'workspaceSetting.tab.general': 'General',
'workspaceSetting.tab.members': 'Members',
'workspaceSetting.storage.comingSoon': 'Workspace-scoped data import & export is coming soon.',
+ 'workspaceSetting.storage.danger.reset.confirm.content':
+ 'Every workspace setting goes back to its default, for everyone in the workspace. Agents, conversations, and files are not touched.',
+ 'workspaceSetting.storage.danger.reset.confirm.ok': 'Reset Settings',
'workspaceSetting.storage.danger.reset.desc':
'Restore all workspace settings to defaults. Workspace data will not be deleted.',
'workspaceSetting.storage.danger.reset.title': 'Reset Workspace Settings',
diff --git a/packages/utils/src/format.test.ts b/packages/utils/src/format.test.ts
index ed3bcdf3ddf..8300f363209 100644
--- a/packages/utils/src/format.test.ts
+++ b/packages/utils/src/format.test.ts
@@ -11,6 +11,7 @@ import {
formatShortenNumber,
formatSize,
formatSpeed,
+ formatSpendTime,
formatTime,
formatTokenNumber,
formatUsageValue,
@@ -310,4 +311,28 @@ describe('format', () => {
expect(formatDate(date)).toBe(expectedFormat);
});
});
+
+ describe('formatSpendTime', () => {
+ it('should drop the year for entries from the current year', () => {
+ const date = dayjs().month(6).date(12).hour(12).minute(12).second(32);
+ expect(formatSpendTime(date.toDate())).toBe(date.format('MMM D HH:mm:ss'));
+ });
+
+ it('should keep the year for entries from another year', () => {
+ const date = dayjs().subtract(1, 'year').month(6).date(12);
+ expect(formatSpendTime(date.toDate())).toBe(date.format('MMM D, YYYY HH:mm:ss'));
+ });
+
+ it('should accept an ISO string', () => {
+ const iso = dayjs().subtract(2, 'year').startOf('year').toISOString();
+ expect(formatSpendTime(iso)).toBe(dayjs(iso).format('MMM D, YYYY HH:mm:ss'));
+ });
+
+ it('should fall back for empty and unparseable input', () => {
+ expect(formatSpendTime()).toBe('--');
+ expect(formatSpendTime(null)).toBe('--');
+ expect(formatSpendTime('')).toBe('--');
+ expect(formatSpendTime('not a date')).toBe('--');
+ });
+ });
});
diff --git a/packages/utils/src/format.ts b/packages/utils/src/format.ts
index e8d929ebc73..d96cb824b76 100644
--- a/packages/utils/src/format.ts
+++ b/packages/utils/src/format.ts
@@ -139,3 +139,17 @@ export const formatDate = (date?: Date) => {
return dayjs(date).format('YYYY-MM-DD');
};
+
+/**
+ * Log-style timestamp: `Jul 12 12:12:32`. The year only shows up when the entry
+ * is not from the current year, so the common case stays short.
+ */
+export const formatSpendTime = (value?: Date | string | null): string => {
+ if (!value) return '--';
+
+ const time = dayjs(value);
+ if (!time.isValid()) return '--';
+
+ const format = time.year() === dayjs().year() ? 'MMM D HH:mm:ss' : 'MMM D, YYYY HH:mm:ss';
+ return time.format(format);
+};
diff --git a/src/components/ListSkeleton/index.tsx b/src/components/ListSkeleton/index.tsx
new file mode 100644
index 00000000000..6863b717c45
--- /dev/null
+++ b/src/components/ListSkeleton/index.tsx
@@ -0,0 +1,42 @@
+'use client';
+
+import { Flexbox, Skeleton } from '@lobehub/ui';
+import { memo } from 'react';
+
+interface ListSkeletonProps {
+ /**
+ * Inline padding of each placeholder row — match whatever the real row uses
+ * so loading → loaded is a content swap, not a relayout (ux §4.1).
+ */
+ paddingInline?: number;
+ rows?: number;
+}
+
+/**
+ * Placeholder for a list of icon + title + subtitle rows (devices, credentials,
+ * …). Skeletonises only the row text and leaves the surrounding card chrome to
+ * the caller, so the list keeps its shape while the fetch is in flight.
+ */
+const ListSkeleton = memo<ListSkeletonProps>(({ paddingInline = 12, rows = 4 }) => (
+ <Flexbox gap={2} width={'100%'}>
+ {Array.from({ length: rows }, (_, index) => (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={16}
+ key={index}
+ style={{ paddingBlock: 12, paddingInline }}
+ >
+ <Skeleton.Avatar active shape={'square'} size={48} />
+ <Flexbox flex={1} gap={8}>
+ <Skeleton.Button active size={'small'} style={{ height: 14, width: 140 }} />
+ <Skeleton.Button active size={'small'} style={{ height: 12, width: 200 }} />
+ </Flexbox>
+ </Flexbox>
+ ))}
+ </Flexbox>
+));
+
+ListSkeleton.displayName = 'ListSkeleton';
+
+export default ListSkeleton;
diff --git a/src/components/LiteTable/index.tsx b/src/components/LiteTable/index.tsx
index 4437de1a069..5afc6c367b1 100644
--- a/src/components/LiteTable/index.tsx
+++ b/src/components/LiteTable/index.tsx
@@ -1,12 +1,13 @@
-import { Center } from '@lobehub/ui';
+import { Skeleton } from '@lobehub/ui';
import { createStaticStyles, cx } from 'antd-style';
import { type ReactNode } from 'react';
import { memo } from 'react';
-import DotsLoading from '@/components/DotsLoading';
-
const LIST_BREAKPOINT = 600;
+/** Placeholder rows shown before the first load settles. */
+const SKELETON_ROWS = 4;
+
const styles = createStaticStyles(({ css, cssVar }) => ({
body: css`
overflow-x: auto;
@@ -159,15 +160,18 @@ const LiteTableInner = <RecordType,>({
const items = dataSource ?? [];
const initialLoading = !!loading && items.length === 0;
+ const listLabelOf = (column: LiteTableColumn<RecordType>) =>
+ column.listSlot || column.listLabel === false
+ ? undefined
+ : (column.listLabel ?? (typeof column.title === 'string' ? column.title : undefined));
+
return (
<div aria-busy={initialLoading} className={cx(styles.container, className)}>
- {initialLoading ? (
- <Center height={240} width={'100%'}>
- <DotsLoading size={6} />
- </Center>
- ) : items.length === 0 ? (
+ {!initialLoading && items.length === 0 ? (
emptyText
) : (
+ // The loading state keeps the table chrome and skeletonises only the
+ // cells, so settling is a content swap rather than a relayout (ux §4.1).
<div className={styles.body}>
<table className={styles.table}>
<thead>
@@ -180,23 +184,37 @@ const LiteTableInner = <RecordType,>({
</tr>
</thead>
<tbody>
- {items.map((record, index) => (
- <tr key={rowKey(record)}>
- {columns.map((column) => {
- const label =
- column.listSlot || column.listLabel === false
- ? undefined
- : (column.listLabel ??
- (typeof column.title === 'string' ? column.title : undefined));
-
- return (
- <td data-label={label} data-list-slot={column.listSlot} key={column.key}>
- {column.render(record, index)}
- </td>
- );
- })}
- </tr>
- ))}
+ {initialLoading
+ ? Array.from({ length: SKELETON_ROWS }, (_, index) => (
+ <tr key={index}>
+ {columns.map((column) => (
+ <td
+ data-label={listLabelOf(column)}
+ data-list-slot={column.listSlot}
+ key={column.key}
+ >
+ <Skeleton.Button
+ active
+ size={'small'}
+ style={{ height: 14, minWidth: 0, width: '100%' }}
+ />
+ </td>
+ ))}
+ </tr>
+ ))
+ : items.map((record, index) => (
+ <tr key={rowKey(record)}>
+ {columns.map((column) => (
+ <td
+ data-label={listLabelOf(column)}
+ data-list-slot={column.listSlot}
+ key={column.key}
+ >
+ {column.render(record, index)}
+ </td>
+ ))}
+ </tr>
+ ))}
</tbody>
</table>
</div>
diff --git a/src/components/SpendType/index.tsx b/src/components/SpendType/index.tsx
new file mode 100644
index 00000000000..6010db3027e
--- /dev/null
+++ b/src/components/SpendType/index.tsx
@@ -0,0 +1,55 @@
+import { Icon, Tooltip } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { CircleDotDashed, Database, ImagePlus, MessageSquareText, Video } from 'lucide-react';
+import { memo, type ReactNode } from 'react';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ chat: css`
+ color: ${cssVar.colorInfo};
+ `,
+ embedding: css`
+ color: ${cssVar.purple};
+ `,
+ imageGeneration: css`
+ color: ${cssVar.colorSuccess};
+ `,
+ videoGeneration: css`
+ color: ${cssVar.colorWarning};
+ `,
+}));
+
+export type SpendTypeValue = 'chat' | 'embedding' | 'imageGeneration' | 'videoGeneration';
+
+interface SpendTypeProps {
+ /** The readable label — shown on hover, since the cell itself is icon-only. */
+ children?: ReactNode;
+ type: SpendTypeValue;
+}
+
+const getIcon = (type: string) => {
+ switch (type) {
+ case 'chat': {
+ return MessageSquareText;
+ }
+ case 'embedding': {
+ return Database;
+ }
+ case 'imageGeneration': {
+ return ImagePlus;
+ }
+ case 'videoGeneration': {
+ return Video;
+ }
+ default: {
+ return CircleDotDashed;
+ }
+ }
+};
+
+const SpendType = memo<SpendTypeProps>(({ type, children }) => (
+ <Tooltip title={children}>
+ <Icon className={styles[type]} icon={getIcon(type)} size={16} />
+ </Tooltip>
+));
+
+export default SpendType;
diff --git a/src/components/TablePagination/PageSizeSelect.tsx b/src/components/TablePagination/PageSizeSelect.tsx
new file mode 100644
index 00000000000..87b5a503f63
--- /dev/null
+++ b/src/components/TablePagination/PageSizeSelect.tsx
@@ -0,0 +1,41 @@
+'use client';
+
+import { Select } from '@lobehub/ui/base-ui';
+import { memo, type ReactNode } from 'react';
+
+interface PageSizeOption {
+ label?: ReactNode;
+ value: number;
+}
+
+interface PageSizeSelectProps {
+ className?: string;
+ disabled?: boolean;
+ onChange?: (value: number) => void;
+ options: PageSizeOption[];
+ value?: number;
+}
+
+/** The "N / page" picker in the table footer. */
+const PageSizeSelect = memo<PageSizeSelectProps>(
+ ({ className, disabled, onChange, options, value }) => (
+ <Select
+ className={className}
+ disabled={disabled}
+ size={'small'}
+ value={value}
+ variant={'filled'}
+ options={options.map((option) => ({
+ label: option.label ?? String(option.value),
+ value: option.value,
+ }))}
+ onChange={(next) => {
+ if (typeof next === 'number') onChange?.(next);
+ }}
+ />
+ ),
+);
+
+PageSizeSelect.displayName = 'TablePageSizeSelect';
+
+export default PageSizeSelect;
diff --git a/src/components/TablePagination/index.tsx b/src/components/TablePagination/index.tsx
new file mode 100644
index 00000000000..9823f3097d4
--- /dev/null
+++ b/src/components/TablePagination/index.tsx
@@ -0,0 +1,164 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cx } from 'antd-style';
+import { ChevronLeft, ChevronRight } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatIntergerNumber } from '@/utils/format';
+
+import PageSizeSelect from './PageSizeSelect';
+
+const DEFAULT_PAGE_SIZE_OPTIONS = [10, 20, 50, 100];
+/** Pages either side of the current one that stay visible before an ellipsis. */
+const SIBLINGS = 1;
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ ellipsis: css`
+ min-width: 24px;
+ color: ${cssVar.colorTextQuaternary};
+ text-align: center;
+ `,
+ root: css`
+ padding-block: 10px;
+ padding-inline: 12px;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ total: css`
+ font-size: 13px;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorTextSecondary};
+ `,
+}));
+
+type PageItem = number | 'ellipsis-end' | 'ellipsis-start';
+
+/**
+ * `1 … 4 5 6 … 703` — the first and last page stay reachable at any depth, with
+ * a window around the current one in between.
+ */
+const getPageItems = (current: number, totalPages: number): PageItem[] => {
+ // Everything fits without gaps: first + last + window + both ellipses.
+ if (totalPages <= SIBLINGS * 2 + 5) {
+ return Array.from({ length: totalPages }, (_, index) => index + 1);
+ }
+
+ const start = Math.max(2, current - SIBLINGS);
+ const end = Math.min(totalPages - 1, current + SIBLINGS);
+ const items: PageItem[] = [1];
+
+ if (start > 2) items.push('ellipsis-start');
+ for (let page = start; page <= end; page += 1) items.push(page);
+ if (end < totalPages - 1) items.push('ellipsis-end');
+ items.push(totalPages);
+
+ return items;
+};
+
+interface TablePaginationProps {
+ className?: string;
+ current: number;
+ onChange: (current: number, pageSize: number) => void;
+ pageSize: number;
+ /** Sizes offered by the "N / page" picker. Must contain the current `pageSize`. */
+ pageSizeOptions?: number[];
+ total: number;
+}
+
+/**
+ * Footer for data tables: the range on the left where reading starts, the
+ * controls on the right where the hand already is.
+ */
+const TablePagination = memo<TablePaginationProps>(
+ ({
+ className,
+ current,
+ onChange,
+ pageSize,
+ pageSizeOptions = DEFAULT_PAGE_SIZE_OPTIONS,
+ total,
+ }) => {
+ const { t } = useTranslation('spend');
+
+ const totalPages = Math.max(1, Math.ceil(total / pageSize));
+ const page = Math.min(current, totalPages);
+ const from = total === 0 ? 0 : (page - 1) * pageSize + 1;
+ const to = Math.min(total, page * pageSize);
+
+ const goTo = (next: number) => {
+ const clamped = Math.min(totalPages, Math.max(1, next));
+ if (clamped !== page) onChange(clamped, pageSize);
+ };
+
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={cx(styles.root, className)}
+ gap={12}
+ justify={'space-between'}
+ >
+ <span className={styles.total}>
+ {t('table.pagination.range', {
+ from: formatIntergerNumber(from),
+ to: formatIntergerNumber(to),
+ total: formatIntergerNumber(total),
+ })}
+ </span>
+ <Flexbox horizontal align={'center'} gap={4}>
+ <PageSizeSelect
+ value={pageSize}
+ options={pageSizeOptions.map((size) => ({
+ label: t('table.pagination.perPage', { size }),
+ value: size,
+ }))}
+ onChange={(nextSize) => {
+ // Keep the first row of the current view in sight rather than
+ // dropping the reader back to page one.
+ const firstRow = (page - 1) * pageSize;
+ onChange(Math.floor(firstRow / nextSize) + 1, nextSize);
+ }}
+ />
+ <Button
+ aria-label={t('table.pagination.prev')}
+ disabled={page <= 1}
+ icon={ChevronLeft}
+ size={'small'}
+ type={'text'}
+ onClick={() => goTo(page - 1)}
+ />
+ {getPageItems(page, totalPages).map((item) =>
+ typeof item === 'number' ? (
+ <Button
+ key={item}
+ size={'small'}
+ type={item === page ? 'fill' : 'text'}
+ onClick={() => goTo(item)}
+ >
+ {item}
+ </Button>
+ ) : (
+ <span className={styles.ellipsis} key={item}>
+ …
+ </span>
+ ),
+ )}
+ <Button
+ aria-label={t('table.pagination.next')}
+ disabled={page >= totalPages}
+ icon={ChevronRight}
+ size={'small'}
+ type={'text'}
+ onClick={() => goTo(page + 1)}
+ />
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+TablePagination.displayName = 'TablePagination';
+
+export default TablePagination;
diff --git a/src/components/TotalToken/index.tsx b/src/components/TotalToken/index.tsx
new file mode 100644
index 00000000000..177aa927d02
--- /dev/null
+++ b/src/components/TotalToken/index.tsx
@@ -0,0 +1,60 @@
+import { Flexbox, Icon, Tag, Tooltip } from '@lobehub/ui';
+import { useTheme } from 'antd-style';
+import { ArrowDownToDot, ArrowUpFromDot } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+// 使用Intl.NumberFormat来添加千分号
+const formatNumber = (num: any) => {
+ return new Intl.NumberFormat('en-US').format(num);
+};
+
+const getColor = (token: number) => {
+ if (token > 100_000) return 'error';
+
+ if (token > 50_000) return 'warning';
+
+ return 'success';
+};
+
+interface TotalTokenProps {
+ totalInputTokens?: number | null;
+ totalOutputTokens?: number | null;
+ totalTokens: number;
+}
+
+/** `12,345 = 10,000 + 2,345` — the total, then how it splits input vs output. */
+const TotalToken = memo<TotalTokenProps>(({ totalTokens, totalInputTokens, totalOutputTokens }) => {
+ const theme = useTheme();
+ const { t } = useTranslation('spend');
+ return typeof totalInputTokens === 'number' && typeof totalOutputTokens === 'number' ? (
+ <Flexbox horizontal align={'center'} gap={2} style={{ color: theme.colorTextDescription }}>
+ <Tag color={getColor(totalTokens)} size={'small'} variant={'filled'}>
+ {formatNumber(totalTokens)}
+ </Tag>
+ =
+ <Tooltip title={t('table.totalToken.input')}>
+ <Tag icon={<Icon icon={ArrowDownToDot} />} size={'small'} variant={'filled'}>
+ {formatNumber(totalInputTokens)}
+ </Tag>
+ </Tooltip>
+ +
+ <Tooltip title={t('table.totalToken.output')}>
+ <Tag icon={<Icon icon={ArrowUpFromDot} />} size={'small'} variant={'filled'}>
+ {formatNumber(totalOutputTokens)}
+ </Tag>
+ </Tooltip>
+ </Flexbox>
+ ) : (
+ <Tag
+ color={getColor(totalTokens)}
+ size={'small'}
+ style={{ color: theme.colorTextDescription, fontSize: 14 }}
+ variant={'filled'}
+ >
+ {formatNumber(totalTokens)}
+ </Tag>
+ );
+});
+
+export default TotalToken;
diff --git a/src/features/DeviceManager/DeviceManager.tsx b/src/features/DeviceManager/DeviceManager.tsx
index f8d4b48668f..322fd8e58bf 100644
--- a/src/features/DeviceManager/DeviceManager.tsx
+++ b/src/features/DeviceManager/DeviceManager.tsx
@@ -20,6 +20,7 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncBoundary from '@/components/AsyncBoundary';
+import SharedListSkeleton from '@/components/ListSkeleton';
import { useElectronStore } from '@/store/electron';
import DeviceDetailPanel from './DeviceDetailPanel';
@@ -253,16 +254,8 @@ const ListSkeleton = memo<{ withHeader?: boolean }>(({ withHeader }) => (
<Skeleton.Button active size={'small'} style={{ height: 16, minWidth: 80, width: 80 }} />
</Flexbox>
)}
- <Flexbox gap={2} padding={4}>
- {[0, 1, 2, 3].map((i) => (
- <Flexbox horizontal align={'center'} gap={16} key={i} style={{ padding: 12 }}>
- <Skeleton.Avatar active shape={'square'} size={48} />
- <Flexbox flex={1} gap={8}>
- <Skeleton.Button active size={'small'} style={{ height: 14, width: 140 }} />
- <Skeleton.Button active size={'small'} style={{ height: 12, width: 200 }} />
- </Flexbox>
- </Flexbox>
- ))}
+ <Flexbox padding={4}>
+ <SharedListSkeleton />
</Flexbox>
</Flexbox>
));
diff --git a/src/features/ServiceModel/ModelAssignmentsForm.tsx b/src/features/ServiceModel/ModelAssignmentsForm.tsx
index 94712a5079b..da46ccb3369 100644
--- a/src/features/ServiceModel/ModelAssignmentsForm.tsx
+++ b/src/features/ServiceModel/ModelAssignmentsForm.tsx
@@ -150,7 +150,9 @@ const ModelAssignmentsForm = memo(() => {
</Flexbox>
</Tooltip>
),
- desc: t('defaultAgent.model.desc'),
+ // No `desc` here or on the rows below: in Model Assignments the label plus
+ // the picker already say what the row does, and a line of prose per row
+ // just pushes the list apart. The other groups keep theirs.
label: t('defaultAgent.title'),
};
@@ -176,7 +178,6 @@ const ModelAssignmentsForm = memo(() => {
</Flexbox>
</Tooltip>
),
- desc: t(`systemAgent.${key}.modelDesc`),
label: t(`systemAgent.${key}.title`),
} satisfies FormItemProps;
});
diff --git a/src/features/Workspace/__tests__/workspaceAwarePath.test.ts b/src/features/Workspace/__tests__/workspaceAwarePath.test.ts
index c72b37673ee..1ff32a85e23 100644
--- a/src/features/Workspace/__tests__/workspaceAwarePath.test.ts
+++ b/src/features/Workspace/__tests__/workspaceAwarePath.test.ts
@@ -91,6 +91,11 @@ describe('buildWorkspaceAwarePath', () => {
);
// Legacy alias — prefixed, then the router redirects to `credential`.
expect(buildWorkspaceAwarePath('/settings/creds', 'acme')).toBe('/acme/settings/creds');
+ expect(buildWorkspaceAwarePath('/settings/statistics', 'acme')).toBe(
+ '/acme/settings/statistics',
+ );
+ // Legacy alias — prefixed, then the router redirects to `statistics`.
+ expect(buildWorkspaceAwarePath('/settings/stats', 'acme')).toBe('/acme/settings/stats');
expect(buildWorkspaceAwarePath('/settings/oauth-apps', 'acme')).toBe(
'/acme/settings/oauth-apps',
);
diff --git a/src/features/Workspace/workspaceAwarePath.ts b/src/features/Workspace/workspaceAwarePath.ts
index 70532399f5d..662c0f5b9c4 100644
--- a/src/features/Workspace/workspaceAwarePath.ts
+++ b/src/features/Workspace/workspaceAwarePath.ts
@@ -48,6 +48,9 @@ export const WORKSPACE_SETTINGS_TABS: ReadonlySet<string> = new Set([
'provider',
'service-model',
'skill',
+ 'statistics',
+ // Legacy alias for `statistics` — the routers keep a redirect, so prefixed
+ // deep-links still land on `/:slug/settings/statistics`.
'stats',
'storage',
'usage',
diff --git a/src/features/WorkspaceSetting/Layout.test.tsx b/src/features/WorkspaceSetting/Layout.test.tsx
index 5d4198c4e89..47adc7bfeaa 100644
--- a/src/features/WorkspaceSetting/Layout.test.tsx
+++ b/src/features/WorkspaceSetting/Layout.test.tsx
@@ -35,7 +35,7 @@ vi.mock('./hooks/useCategory', () => ({
{ key: 'apikey', label: 'API Keys' },
{ key: 'service-model', label: 'Default Models' },
{ key: 'credential', label: 'Credentials' },
- { key: 'stats', label: 'Stats' },
+ { key: 'statistics', label: 'Statistics' },
{ key: 'storage', label: 'Storage' },
{ key: 'usage', label: 'Usage' },
{ key: 'audit-log', label: 'Audit Log' },
@@ -66,7 +66,7 @@ describe('WorkspaceSettingsContentLayout', () => {
['apikey', 'API Keys'],
['service-model', 'Default Models'],
['credential', 'Credentials'],
- ['stats', 'Stats'],
+ ['statistics', 'Statistics'],
['storage', 'Storage'],
['usage', 'Usage'],
])('renders the compact header for the %s tab', (tab, title) => {
diff --git a/src/routes/(main)/[workspaceSlug]/settings/credential/features/PersonalCredsSection/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/credential/features/PersonalCredsSection/index.tsx
index 444944bd70b..7954811aa05 100644
--- a/src/routes/(main)/[workspaceSlug]/settings/credential/features/PersonalCredsSection/index.tsx
+++ b/src/routes/(main)/[workspaceSlug]/settings/credential/features/PersonalCredsSection/index.tsx
@@ -1,12 +1,13 @@
'use client';
import { Flexbox } from '@lobehub/ui';
-import { Empty, Spin } from 'antd';
+import { Empty } from 'antd';
import { createStaticStyles } from 'antd-style';
import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncBoundary from '@/components/AsyncBoundary';
+import ListSkeleton from '@/components/ListSkeleton';
import { lambdaQuery } from '@/libs/trpc/client';
import CredItem from '@/routes/(main)/settings/creds/features/CredItem';
@@ -69,11 +70,7 @@ const PersonalCredsSection: FC<PersonalCredsSectionProps> = ({ onWorkspaceCredsC
errorVariant={'block'}
isEmpty={credentials.length === 0}
isLoading={isLoading}
- loading={
- <Flexbox align={'center'} justify={'center'} style={{ padding: 32 }}>
- <Spin />
- </Flexbox>
- }
+ loading={<ListSkeleton paddingInline={0} />}
onRetry={() => refetch()}
>
<Flexbox gap={0}>
diff --git a/src/routes/(main)/[workspaceSlug]/settings/stats/index.test.tsx b/src/routes/(main)/[workspaceSlug]/settings/statistics/index.test.tsx
similarity index 100%
rename from src/routes/(main)/[workspaceSlug]/settings/stats/index.test.tsx
rename to src/routes/(main)/[workspaceSlug]/settings/statistics/index.test.tsx
diff --git a/src/routes/(main)/[workspaceSlug]/settings/stats/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/statistics/index.tsx
similarity index 100%
rename from src/routes/(main)/[workspaceSlug]/settings/stats/index.tsx
rename to src/routes/(main)/[workspaceSlug]/settings/statistics/index.tsx
diff --git a/src/routes/(main)/settings/creds/features/CredsList.tsx b/src/routes/(main)/settings/creds/features/CredsList.tsx
index a6897ad7ed2..2ceccd0dc8f 100644
--- a/src/routes/(main)/settings/creds/features/CredsList.tsx
+++ b/src/routes/(main)/settings/creds/features/CredsList.tsx
@@ -5,13 +5,14 @@ import { Flexbox } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
import { useMutation } from '@tanstack/react-query';
import { TRPCClientError } from '@trpc/client';
-import { Empty, Spin } from 'antd';
+import { Empty } from 'antd';
import { createStaticStyles } from 'antd-style';
import { LogIn } from 'lucide-react';
import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncBoundary from '@/components/AsyncBoundary';
+import ListSkeleton from '@/components/ListSkeleton';
import { usePermission } from '@/hooks/usePermission';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
@@ -76,11 +77,7 @@ const CredsList: FC = () => {
};
if (isAuthLoading) {
- return (
- <Flexbox align={'center'} justify={'center'} style={{ padding: 48 }}>
- <Spin />
- </Flexbox>
- );
+ return <ListSkeleton paddingInline={0} />;
}
if (!isAuthenticated) {
@@ -112,11 +109,7 @@ const CredsList: FC = () => {
errorVariant={'block'}
isEmpty={credentials.length === 0}
isLoading={isLoading}
- loading={
- <Flexbox align={'center'} justify={'center'} style={{ padding: 48 }}>
- <Spin />
- </Flexbox>
- }
+ loading={<ListSkeleton paddingInline={0} />}
onRetry={() => refetch()}
>
<Flexbox gap={0}>
diff --git a/src/routes/(main)/settings/stats/features/components/TimeLabel.tsx b/src/routes/(main)/settings/stats/features/components/TimeLabel.tsx
index 85ff3349dba..a47027394bd 100644
--- a/src/routes/(main)/settings/stats/features/components/TimeLabel.tsx
+++ b/src/routes/(main)/settings/stats/features/components/TimeLabel.tsx
@@ -7,7 +7,8 @@ import { memo } from 'react';
const TimeLabel = memo<{
date?: string;
icon: LucideIcon;
- title: string;
+ /** Omit when the icon already says what the value is. */
+ title?: string;
}>(({ date, icon, title }) => {
return (
<Flexbox
@@ -20,7 +21,7 @@ const TimeLabel = memo<{
}}
>
<Icon icon={icon} />
- {title}:{' '}
+ {title ? `${title}: ` : null}
{date ? <span style={{ fontWeight: 'bold' }}>{date}</span> : <Icon spin icon={Loader2} />}
</Flexbox>
);
diff --git a/src/routes/(main)/settings/stats/features/overview/WorkspaceWelcome.tsx b/src/routes/(main)/settings/stats/features/overview/WorkspaceWelcome.tsx
index b05c2badb48..edb8b162895 100644
--- a/src/routes/(main)/settings/stats/features/overview/WorkspaceWelcome.tsx
+++ b/src/routes/(main)/settings/stats/features/overview/WorkspaceWelcome.tsx
@@ -19,7 +19,6 @@ const formatEnglishNumber = (number: number) => {
const WorkspaceWelcome = memo<{ mobile?: boolean }>(({ mobile }) => {
const { t, i18n } = useTranslation('auth');
- const { t: tSetting } = useTranslation('setting');
const workspace = useActiveWorkspace();
const members = useWorkspaceMembers();
@@ -56,11 +55,7 @@ const WorkspaceWelcome = memo<{ mobile?: boolean }>(({ mobile }) => {
/>
</Flexbox>
<Flexbox horizontal gap={16} wrap={'wrap'}>
- <TimeLabel
- date={String(memberCount)}
- icon={UsersIcon}
- title={tSetting('workspaceSetting.tab.members')}
- />
+ <TimeLabel date={String(memberCount)} icon={UsersIcon} />
<TimeLabel
date={dayjs(workspace.createdAt).format('YYYY-MM-DD')}
icon={Clock3Icon}
diff --git a/src/routes/(main)/settings/stats/features/usage/UsageTable.tsx b/src/routes/(main)/settings/stats/features/usage/UsageTable.tsx
index 50be54210ad..1c24d939027 100644
--- a/src/routes/(main)/settings/stats/features/usage/UsageTable.tsx
+++ b/src/routes/(main)/settings/stats/features/usage/UsageTable.tsx
@@ -1,21 +1,53 @@
import { ProviderIcon } from '@lobehub/icons';
-import { Flexbox, Tag, Text, Tooltip } from '@lobehub/ui';
+import { Flexbox, Text, Tooltip } from '@lobehub/ui';
import { type TableColumnType } from 'antd';
-import { cssVar } from 'antd-style';
-import { memo, useEffect } from 'react';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
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 { useClientDataSWR } from '@/libs/swr';
import { statsKeys } from '@/libs/swr/keys';
import { usageService } from '@/services/usage';
-import { formatDate, formatNumber } from '@/utils/format';
+import { formatNumber, formatSpendTime } from '@/utils/format';
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];
+
+/**
+ * Sortable columns and the number each row sorts by. Pagination is ours now, so
+ * antd only ever sees one page — sorting has to run over the whole result set
+ * here, before it gets sliced.
+ */
+const SORT_VALUES: Record<string, (row: any) => number> = {
+ createdAt: (row) => new Date(row.createdAt).getTime(),
+ spend: (row) => row.spend ?? 0,
+ totalTokens: (row) => row.totalTokens ?? 0,
+};
+
+interface SortState {
+ field: string;
+ order: 'ascend' | 'descend';
+}
+
+const styles = createStaticStyles(({ css }) => ({
+ // Line the footer up with InlineTable's first/last cells.
+ pagination: css`
+ padding-inline: 24px;
+ `,
+}));
+
const UsageTable = memo<UsageChartProps>(({ dateStrings }) => {
const { t } = useTranslation('auth');
+ // Columns shared with the workspace spend breakdown read from the same
+ // namespace, so the two tables stay worded alike.
+ const { t: tSpend } = useTranslation('spend');
const { data, isLoading, mutate } = useClientDataSWR(statsKeys.usageLogs(), async () =>
usageService.findByMonth(dateStrings),
@@ -27,6 +59,7 @@ const UsageTable = memo<UsageChartProps>(({ dateStrings }) => {
const [pageSize, setPageSize] = useQueryParam('pageSize', parseAsInteger.withDefault(5), {
clearOnDefault: true,
});
+ const [sort, setSort] = useState<SortState | null>(null);
useEffect(() => {
if (dateStrings) {
@@ -34,17 +67,49 @@ const UsageTable = memo<UsageChartProps>(({ dateStrings }) => {
}
}, [dateStrings]);
+ const sorted = useMemo(() => {
+ const getValue = sort && SORT_VALUES[sort.field];
+ if (!data || !getValue) return data;
+
+ const direction = sort.order === 'ascend' ? 1 : -1;
+ return [...data].sort((a, b) => (getValue(a) - getValue(b)) * direction);
+ }, [data, sort]);
+
+ const total = sorted?.length ?? 0;
+ // A shrinking result set can leave `currentPage` past the end; clamp for
+ // display so the table never goes blank while the URL catches up.
+ const page = Math.min(currentPage, Math.max(1, Math.ceil(total / pageSize)));
+ const pageData = useMemo(
+ () => sorted?.slice((page - 1) * pageSize, page * pageSize),
+ [sorted, page, pageSize],
+ );
+
+ // Column order mirrors the workspace spend breakdown: when it happened, what
+ // it was, which model, how many tokens, what it cost, how fast.
const columns: TableColumnType<any>[] = [
{
- hidden: true,
- key: 'id',
- title: 'ID',
+ dataIndex: 'createdAt',
+ key: 'createdAt',
+ render: (value) => <span style={{ textWrap: 'nowrap' }}>{formatSpendTime(value)}</span>,
+ sorter: true,
+ sortOrder: sort?.field === 'createdAt' ? sort.order : null,
+ title: tSpend('table.columns.time'),
+ width: 150,
+ },
+ {
+ dataIndex: 'type',
+ key: 'type',
+ render: (value: SpendTypeValue) => (
+ <SpendType type={value}>{tSpend(`table.columns.type.enums.${value}`)}</SpendType>
+ ),
+ title: tSpend('table.columns.type.title'),
+ width: 80,
},
{
dataIndex: 'model',
key: 'model',
render: (value, record) => (
- <Flexbox horizontal align={'start'} gap={16}>
+ <Flexbox horizontal align={'center'} gap={16}>
<ProviderIcon
provider={record.provider}
size={18}
@@ -59,84 +124,80 @@ const UsageTable = memo<UsageChartProps>(({ dateStrings }) => {
</Tooltip>
</Flexbox>
),
- title: t('usage.table.model'),
+ title: tSpend('table.columns.model'),
},
{
- dataIndex: 'type',
- filters: [
- {
- text: 'Chat',
- value: 'chat',
- },
- ],
- key: 'type',
- onFilter: (value, record) => record.callType === value,
- render: (value) => {
- return <Tag>{value}</Tag>;
- },
- title: t('usage.table.type'),
- },
- {
- dataIndex: 'totalInputTokens',
- key: 'inputTokens',
- title: t('usage.table.inputTokens'),
+ dataIndex: 'totalTokens',
+ key: 'totalTokens',
+ render: (value, record) => (
+ <TotalToken
+ totalInputTokens={record.totalInputTokens}
+ totalOutputTokens={record.totalOutputTokens}
+ totalTokens={value ?? 0}
+ />
+ ),
+ sorter: true,
+ sortOrder: sort?.field === 'totalTokens' ? sort.order : null,
+ title: tSpend('table.columns.totalTokens'),
+ width: 180,
},
{
- dataIndex: 'totalOutputTokens',
- key: 'outputTokens',
- title: t('usage.table.outputTokens'),
+ align: 'end',
+ dataIndex: 'spend',
+ key: 'spend',
+ // Kept in dollars, unlike the workspace breakdown's credits column.
+ render: (value) => `$${formatNumber(value, 6)}`,
+ sorter: true,
+ sortOrder: sort?.field === 'spend' ? sort.order : null,
+ title: t('usage.table.spend'),
},
{
+ align: 'end',
dataIndex: 'tps',
key: 'tps',
- render: (value) => formatNumber(value, 2),
+ render: (value) => (value ? formatNumber(value, 2) : '--'),
title: t('usage.table.tps'),
},
{
+ align: 'end',
dataIndex: 'ttft',
key: 'ttft',
- render: (value) => formatNumber(value / 1000, 2),
+ render: (value) => (value ? formatNumber(value / 1000, 2) : '--'),
title: t('usage.table.ttft'),
},
- {
- dataIndex: 'spend',
- key: 'spend',
- render: (value) => {
- return `$${formatNumber(value, 6)}`;
- },
- title: t('usage.table.spend'),
- },
- {
- dataIndex: 'createdAt',
- key: 'createdAt',
- render: (value) => {
- return formatDate(new Date(value));
- },
- sortDirections: ['descend'],
- sorter: (a, b) => a.createdAt - b.createdAt,
- title: t('usage.table.createdAt'),
- },
];
return (
- <InlineTable
- columns={columns}
- dataSource={data}
- loading={isLoading}
- rowKey={(record) => record.id || `${record.model}-${record.createdAt}-${record.provider}`}
- size="small"
- pagination={{
- current: currentPage,
- onChange: (page) => {
- setCurrentPage(page);
- },
- onShowSizeChange: (current, size) => {
- setCurrentPage(current);
- setPageSize(size);
- },
- pageSize,
- }}
- />
+ <>
+ <InlineTable
+ columns={columns}
+ dataSource={pageData}
+ loading={isLoading}
+ rowKey={(record) => record.id || `${record.model}-${record.createdAt}-${record.provider}`}
+ size="small"
+ onChange={(_pagination, _filters, sorter) => {
+ const next = Array.isArray(sorter) ? sorter[0] : sorter;
+ const field = String(next?.columnKey ?? '');
+ 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);
+ }}
+ />
+ {total > 0 && (
+ <TablePagination
+ className={styles.pagination}
+ current={page}
+ pageSize={pageSize}
+ pageSizeOptions={PAGE_SIZE_OPTIONS}
+ total={total}
+ onChange={(nextPage, nextPageSize) => {
+ setCurrentPage(nextPage);
+ setPageSize(nextPageSize);
+ }}
+ />
+ )}
+ </>
);
});
diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsx
index d43275125c9..ed5abb5c098 100644
--- a/src/spa/router/desktopRouter.config.desktop.tsx
+++ b/src/spa/router/desktopRouter.config.desktop.tsx
@@ -54,7 +54,7 @@ import WorkspaceSlugSettingsPlansPage from '@/routes/(main)/[workspaceSlug]/sett
import WorkspaceSlugSettingsProviderPage from '@/routes/(main)/[workspaceSlug]/settings/provider';
import WorkspaceSlugSettingsServiceModelPage from '@/routes/(main)/[workspaceSlug]/settings/service-model';
import WorkspaceSlugSettingsSkillPage from '@/routes/(main)/[workspaceSlug]/settings/skill';
-import WorkspaceSlugSettingsStatsPage from '@/routes/(main)/[workspaceSlug]/settings/stats';
+import WorkspaceSlugSettingsStatisticsPage from '@/routes/(main)/[workspaceSlug]/settings/statistics';
import WorkspaceSlugSettingsStoragePage from '@/routes/(main)/[workspaceSlug]/settings/storage';
import WorkspaceSlugSettingsUsagePage from '@/routes/(main)/[workspaceSlug]/settings/usage';
import AcceptanceWorkspace from '@/routes/(main)/acceptance';
@@ -737,7 +737,9 @@ export const createMainAreaChildren = (): RouteObject[] => [
{ element: <WorkspaceSlugSettingsGeneralPage />, path: 'general' },
{ element: <WorkspaceSlugSettingsMembersPage />, path: 'members' },
{ element: <WorkspaceSlugSettingsNotificationPage />, path: 'notification' },
- { element: <WorkspaceSlugSettingsStatsPage />, path: 'stats' },
+ { element: <WorkspaceSlugSettingsStatisticsPage />, path: 'statistics' },
+ // Legacy `/:slug/settings/stats` URLs — kept for deep-links.
+ { element: redirectElement('../statistics'), path: 'stats' },
{ element: <WorkspaceSlugSettingsPlansPage />, path: 'plans' },
{ element: <WorkspaceSlugSettingsBillingPage />, path: 'billing' },
{ element: <WorkspaceSlugSettingsCreditsPage />, path: 'credits' },
diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsx
index e75ca15dd35..a4927bdeda1 100644
--- a/src/spa/router/desktopRouter.config.tsx
+++ b/src/spa/router/desktopRouter.config.tsx
@@ -882,9 +882,14 @@ export const createMainAreaChildren = (): RouteObject[] => [
},
{
element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/stats'),
- 'Desktop > Workspace > Settings > Stats',
+ () => import('@/routes/(main)/[workspaceSlug]/settings/statistics'),
+ 'Desktop > Workspace > Settings > Statistics',
),
+ path: 'statistics',
+ },
+ // Legacy `/:slug/settings/stats` URLs — kept for deep-links.
+ {
+ element: redirectElement('../statistics'),
path: 'stats',
},
{
diff --git a/src/types/workspaceSettings.ts b/src/types/workspaceSettings.ts
index 60ccc506292..2571fbd7c5b 100644
--- a/src/types/workspaceSettings.ts
+++ b/src/types/workspaceSettings.ts
@@ -21,7 +21,7 @@ export enum WorkspaceSettingsTabs {
Provider = 'provider',
ServiceModel = 'service-model',
Skill = 'skill',
- Stats = 'stats',
+ Stats = 'statistics',
Storage = 'storage',
Usage = 'usage',
}