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.

♻️ refactor: remove @ant-design/pro-components via custom StatisticCard and LiteTable (#17578)

Innei2989e96a5e25
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index 80dfaf77c55..e7d8c121b3e 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -91,6 +91,33 @@ It intentionally does not expose Zustand's `getState` or `setState`. If a test
repeatedly needs mutation, add a dev-only supported action or fixture command
instead of normalizing temporary `setState` HMR patches.
+### In-SPA navigation that preserves instrumentation
+
+`app-probe.sh goto` and `location.assign("app://renderer/…")` perform a FULL
+reload — any `window.fetch` wrapper or debug global installed via `eval` is
+wiped, and its absence reads as "the request never fired". To change route while
+keeping instrumentation alive, drive react-router through history:
+
+```js
+history.pushState({}, '', '/settings/apikey');
+dispatchEvent(new PopStateEvent('popstate'));
+```
+
+This remounts the route component (SWR revalidates, list fetch observable by the
+wrapper) without recreating the JS context. Leave-and-return with this pattern is
+the way to capture a page's first-load request after installing a fetch wrapper.
+
+### Safe mutation-error injection against a real (cloud) account
+
+To exercise a mutation error branch when the app points at the user's real cloud
+backend, replace the react-query `mutationFn` body with an immediate
+`Promise.reject(...)` via HMR — the mutation then fails before ANY network call,
+so clicking a real row (even the user's own data) has zero server effect. Switch
+error shapes through a window flag (e.g. plain `Error` vs
+`{ data: { code: 'FORBIDDEN' } }`) and prove HMR liveness with a module-level
+marker before clicking. Snapshot the dirty file first and restore byte-identically
+(cmp), never `git checkout --`.
+
### Runtime proof
Client and server agent runtimes can produce the same visible result. Prove the
diff --git a/locales/en-US/auth.json b/locales/en-US/auth.json
index 3ed37e711dd..eb9b6615611 100644
--- a/locales/en-US/auth.json
+++ b/locales/en-US/auth.json
@@ -32,7 +32,7 @@
"apikey.list.columns.key": "Key",
"apikey.list.columns.lastUsedAt": "Last Used",
"apikey.list.columns.name": "Name",
- "apikey.list.columns.status": "Enabled Status",
+ "apikey.list.columns.status": "Enabled",
"apikey.list.empty": "No API Keys yet",
"apikey.list.title": "API Key List",
"apikey.validation.required": "This field cannot be empty",
diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.json
index 018713f53cb..d5d476dc44a 100644
--- a/locales/zh-CN/auth.json
+++ b/locales/zh-CN/auth.json
@@ -32,7 +32,7 @@
"apikey.list.columns.key": "密钥",
"apikey.list.columns.lastUsedAt": "最后使用时间",
"apikey.list.columns.name": "名称",
- "apikey.list.columns.status": "启用状态",
+ "apikey.list.columns.status": "启用",
"apikey.list.empty": "暂无 API Key",
"apikey.list.title": "API Key 列表",
"apikey.validation.required": "内容不得为空",
diff --git a/package.json b/package.json
index 16496d7ab35..8b8ae337d6e 100644
--- a/package.json
+++ b/package.json
@@ -176,7 +176,6 @@
},
"dependencies": {
"@ant-design/icons": "^6.3.2",
- "@ant-design/pro-components": "^2.8.10",
"@anthropic-ai/sdk": "^0.73.0",
"@atlaskit/pragmatic-drag-and-drop": "^1.8.1",
"@atlaskit/pragmatic-drag-and-drop-hitbox": "^1.2.0",
diff --git a/packages/locales/src/default/auth.ts b/packages/locales/src/default/auth.ts
index f6228e8b3f8..2197fc399b3 100644
--- a/packages/locales/src/default/auth.ts
+++ b/packages/locales/src/default/auth.ts
@@ -35,7 +35,7 @@ export default {
'apikey.list.columns.key': 'Key',
'apikey.list.columns.lastUsedAt': 'Last Used',
'apikey.list.columns.name': 'Name',
- 'apikey.list.columns.status': 'Enabled Status',
+ 'apikey.list.columns.status': 'Enabled',
'apikey.list.empty': 'No API Keys yet',
'apikey.list.title': 'API Key List',
'apikey.validation.required': 'This field cannot be empty',
diff --git a/src/components/LiteTable/index.tsx b/src/components/LiteTable/index.tsx
new file mode 100644
index 00000000000..4437de1a069
--- /dev/null
+++ b/src/components/LiteTable/index.tsx
@@ -0,0 +1,210 @@
+import { Center } 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;
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ body: css`
+ overflow-x: auto;
+ `,
+ container: css`
+ container-type: inline-size;
+ `,
+ table: css`
+ border-collapse: collapse;
+ width: 100%;
+ min-width: max-content;
+ font-size: 13px;
+
+ th,
+ td {
+ padding-block: 8px;
+ padding-inline: 8px;
+ text-align: start;
+ vertical-align: middle;
+ }
+
+ thead th {
+ font-weight: 500;
+ color: ${cssVar.colorTextSecondary};
+ white-space: nowrap;
+ background: ${cssVar.colorFillQuaternary};
+ }
+
+ tr {
+ th:first-child,
+ td:first-child {
+ padding-inline-start: 24px;
+ }
+
+ th:last-child,
+ td:last-child {
+ padding-inline-end: 24px;
+ }
+ }
+
+ tbody tr:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+
+ @container (max-width: ${LIST_BREAKPOINT}px) {
+ display: block;
+ min-width: 0;
+
+ thead {
+ display: none;
+ }
+
+ tbody {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ padding-inline: 16px;
+ }
+
+ tbody tr {
+ display: grid;
+ grid-template-columns: 1fr auto;
+ align-items: center;
+
+ padding-block: 4px 8px;
+ padding-inline: 16px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ &:hover {
+ background: transparent;
+ }
+ }
+
+ td {
+ display: flex;
+ grid-column: 1 / -1;
+ gap: 16px;
+ align-items: center;
+ justify-content: space-between;
+
+ padding-block: 6px;
+ padding-inline: 0 !important;
+ }
+
+ td[data-label]::before {
+ content: attr(data-label);
+ flex-shrink: 0;
+ color: ${cssVar.colorTextSecondary};
+ }
+
+ td:not([data-label], [data-list-slot]) {
+ justify-content: flex-end;
+ }
+
+ td[data-list-slot='title'] {
+ grid-column: 1;
+ grid-row: 1;
+ justify-content: flex-start;
+
+ padding-block: 8px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ font-size: 14px;
+ font-weight: 600;
+ }
+
+ td[data-list-slot='extra'] {
+ grid-column: 2;
+ grid-row: 1;
+ justify-content: flex-end;
+
+ padding-block: 8px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ }
+
+ td[data-list-slot='actions'] {
+ justify-content: flex-end;
+ }
+ }
+ `,
+}));
+
+export interface LiteTableColumn<RecordType> {
+ key: string;
+ listLabel?: string | false;
+ listSlot?: 'actions' | 'extra' | 'title';
+ render: (record: RecordType, index: number) => ReactNode;
+ title: ReactNode;
+ width?: number | string;
+}
+
+export interface LiteTableProps<RecordType> {
+ className?: string;
+ columns: LiteTableColumn<RecordType>[];
+ dataSource?: RecordType[];
+ emptyText?: ReactNode;
+ loading?: boolean;
+ rowKey: (record: RecordType) => string;
+}
+
+const LiteTableInner = <RecordType,>({
+ className,
+ columns,
+ dataSource,
+ emptyText,
+ loading,
+ rowKey,
+}: LiteTableProps<RecordType>) => {
+ const items = dataSource ?? [];
+ const initialLoading = !!loading && items.length === 0;
+
+ return (
+ <div aria-busy={initialLoading} className={cx(styles.container, className)}>
+ {initialLoading ? (
+ <Center height={240} width={'100%'}>
+ <DotsLoading size={6} />
+ </Center>
+ ) : items.length === 0 ? (
+ emptyText
+ ) : (
+ <div className={styles.body}>
+ <table className={styles.table}>
+ <thead>
+ <tr>
+ {columns.map((column) => (
+ <th key={column.key} style={{ width: column.width }}>
+ {column.title}
+ </th>
+ ))}
+ </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>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ );
+};
+
+const LiteTable = memo(LiteTableInner) as typeof LiteTableInner;
+
+export default LiteTable;
diff --git a/src/components/StatisticCard/index.test.tsx b/src/components/StatisticCard/index.test.tsx
new file mode 100644
index 00000000000..7925bbebbb0
--- /dev/null
+++ b/src/components/StatisticCard/index.test.tsx
@@ -0,0 +1,130 @@
+import { render, screen } from '@testing-library/react';
+import { type ComponentProps, type ReactNode } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import StatisticCard from './index';
+
+vi.mock('@lobehub/ui', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ return {
+ ...actual,
+ Block: ({
+ children,
+ className,
+ padding,
+ paddingBlock,
+ paddingInline,
+ style,
+ variant,
+ }: {
+ children?: ReactNode;
+ className?: string;
+ padding?: number | string;
+ paddingBlock?: number | string;
+ paddingInline?: number | string;
+ style?: ComponentProps<'div'>['style'];
+ variant?: string;
+ }) => (
+ <div
+ className={className}
+ data-padding={padding}
+ data-padding-block={paddingBlock}
+ data-padding-inline={paddingInline}
+ data-testid="block"
+ data-variant={variant}
+ style={style}
+ >
+ {children}
+ </div>
+ ),
+ };
+});
+
+describe('StatisticCard', () => {
+ it('renders title and formatted value with prefix, suffix and precision', () => {
+ render(
+ <StatisticCard
+ statistic={{ precision: 2, prefix: '$', suffix: 'k', value: 1234.5 }}
+ title="Total Cost"
+ />,
+ );
+
+ expect(screen.getByText('Total Cost')).toBeInTheDocument();
+ expect(screen.getByText('$')).toBeInTheDocument();
+ expect(screen.getByText('1,234')).toBeInTheDocument();
+ expect(screen.getByText('.50')).toBeInTheDocument();
+ expect(screen.getByText('k')).toBeInTheDocument();
+ });
+
+ it('renders a custom node title as-is', () => {
+ render(
+ <StatisticCard statistic={{ value: 1 }} title={<span data-testid="custom-title">Hi</span>} />,
+ );
+
+ expect(screen.getByTestId('custom-title')).toHaveTextContent('Hi');
+ });
+
+ it('renders description below the value and extra in the header', () => {
+ render(
+ <StatisticCard
+ extra={<button type="button">More</button>}
+ statistic={{ description: <span>desc line</span>, value: 10 }}
+ title="Tokens"
+ />,
+ );
+
+ expect(screen.getByText('desc line')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'More' })).toBeInTheDocument();
+ });
+
+ it('replaces extra with a small spinner while loading', () => {
+ const { container } = render(
+ <StatisticCard
+ loading
+ extra={<button type="button">More</button>}
+ statistic={{ value: 10 }}
+ title="Tokens"
+ />,
+ );
+
+ expect(screen.queryByText('More')).toBeNull();
+ expect(container.querySelector('.ant-spin')).not.toBeNull();
+ });
+
+ it('applies valueStyle to the statistic content', () => {
+ const { container } = render(
+ <StatisticCard
+ statistic={{ value: 10, valueStyle: { color: 'rgb(255, 0, 0)' } }}
+ title="Savings"
+ />,
+ );
+
+ expect(container.querySelector('.ant-statistic-content')).toHaveStyle({
+ color: 'rgb(255, 0, 0)',
+ });
+ });
+
+ it('passes variant and padding props through to Block', () => {
+ render(
+ <StatisticCard
+ padding={24}
+ paddingBlock={8}
+ paddingInline={16}
+ title="T"
+ variant="outlined"
+ />,
+ );
+
+ const block = screen.getByTestId('block');
+ expect(block).toHaveAttribute('data-variant', 'outlined');
+ expect(block).toHaveAttribute('data-padding', '24');
+ expect(block).toHaveAttribute('data-padding-block', '8');
+ expect(block).toHaveAttribute('data-padding-inline', '16');
+ });
+
+ it('defaults to the borderless variant', () => {
+ render(<StatisticCard title="T" />);
+
+ expect(screen.getByTestId('block')).toHaveAttribute('data-variant', 'borderless');
+ });
+});
diff --git a/src/components/StatisticCard/index.tsx b/src/components/StatisticCard/index.tsx
index 4266dd4f261..e589aca472c 100644
--- a/src/components/StatisticCard/index.tsx
+++ b/src/components/StatisticCard/index.tsx
@@ -1,144 +1,73 @@
-import { type StatisticCardProps as AntdStatisticCardProps } from '@ant-design/pro-components';
-import { StatisticCard as AntdStatisticCard } from '@ant-design/pro-components';
import { type BlockProps } from '@lobehub/ui';
-import { Block, Text } from '@lobehub/ui';
-import { Spin } from 'antd';
-import { createStaticStyles, cx, responsive, useResponsive } from 'antd-style';
+import { Block, Flexbox, Text } from '@lobehub/ui';
+import { Spin, Statistic } from 'antd';
+import { createStaticStyles, responsive } from 'antd-style';
+import { type CSSProperties, type ReactNode } from 'react';
import { memo } from 'react';
const prefixCls = 'ant';
const styles = createStaticStyles(({ css, cssVar }) => ({
- card: css`
- border-radius: ${cssVar.borderRadiusLG};
+ header: css`
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ justify-content: space-between;
${responsive.sm} {
- border: none;
- border-radius: 0;
- background: ${cssVar.colorBgContainer};
+ flex-wrap: wrap;
+ margin-block-end: 8px;
}
`,
- cardDark: css`
- border: 1px solid ${cssVar.colorFillTertiary};
- `,
- cardLight: css`
- border: 1px solid ${cssVar.colorFillSecondary};
- `,
- container: css`
- ${responsive.sm} {
- border: none;
- border-radius: 0;
- background: ${cssVar.colorBgContainer};
- }
-
- .${prefixCls}-pro-card-title {
- overflow: hidden;
-
- ${responsive.sm} {
- margin: 0;
- font-size: 14px;
- line-height: 16px !important;
- }
- }
-
- .${prefixCls}-pro-card-body {
- padding: 0;
- .${prefixCls}-pro-statistic-card-content {
- position: relative;
- width: 100%;
- padding-block-end: 16px;
- padding-inline: 16px;
- .${prefixCls}-pro-statistic-card-chart {
- position: relative;
- width: 100%;
- }
- }
-
- .${prefixCls}-pro-statistic-card-footer {
- overflow: hidden;
-
- margin: 0;
- padding: 0;
- border-end-start-radius: ${cssVar.borderRadiusLG};
- border-end-end-radius: ${cssVar.borderRadiusLG};
- }
- }
-
- .${prefixCls}-pro-card-loading-content {
- padding-block: 16px;
- padding-inline: 16px;
- }
-
- .${prefixCls}-pro-card-header {
- padding-block-start: 0;
- padding-inline: 0;
-
- .${prefixCls}-pro-card-title {
- line-height: 32px;
- }
-
- + .${prefixCls}-pro-card-body {
- padding-block-start: 0;
- }
-
- ${responsive.sm} {
- flex-wrap: wrap;
- gap: 8px;
-
- margin-block-end: 8px;
- padding-block-start: 0;
- padding-inline: 0;
- }
- }
-
+ statistic: css`
.${prefixCls}-statistic-content-value-int, .${prefixCls}-statistic-content-value-decimal {
font-size: 24px;
font-weight: bold;
line-height: 1.2;
}
+ `,
+ title: css`
+ overflow: hidden;
+ flex: 1;
- .${prefixCls}-pro-statistic-card-chart {
- margin: 0;
- }
-
- .${prefixCls}-pro-statistic-card-content {
- display: flex;
- flex-direction: column;
- gap: 16px;
-
- padding-block-end: 0 !important;
- padding-inline: 0 !important;
- }
-
- .${prefixCls}-pro-statistic-card-content-horizontal {
- flex-direction: row;
- align-items: center;
+ font-size: 16px;
+ font-weight: 500;
+ line-height: 32px;
+ color: ${cssVar.colorText};
- .${prefixCls}-pro-statistic-card-chart {
- align-self: center;
- }
+ ${responsive.sm} {
+ font-size: 14px;
+ line-height: 16px;
}
`,
- icon: css`
- border-radius: ${cssVar.borderRadius};
- background: ${cssVar.colorFillSecondary};
- `,
- raw: css`
- border: none !important;
- background: transparent !important;
- `,
}));
-interface StatisticCardProps
- extends
- AntdStatisticCardProps,
- Pick<BlockProps, 'variant' | 'padding' | 'paddingBlock' | 'paddingInline'> {}
+export interface StatisticConfig {
+ description?: ReactNode;
+ precision?: number;
+ prefix?: ReactNode;
+ style?: CSSProperties;
+ suffix?: ReactNode;
+ value?: number | string;
+ valueStyle?: CSSProperties;
+}
+
+export interface StatisticCardProps extends Pick<
+ BlockProps,
+ 'variant' | 'padding' | 'paddingBlock' | 'paddingInline'
+> {
+ className?: string;
+ extra?: ReactNode;
+ loading?: boolean;
+ statistic?: StatisticConfig;
+ style?: CSSProperties;
+ title?: ReactNode;
+}
const StatisticCard = memo<StatisticCardProps>(
({
title,
className,
-
variant = 'borderless',
loading,
extra,
@@ -146,10 +75,8 @@ const StatisticCard = memo<StatisticCardProps>(
padding,
paddingBlock,
paddingInline,
- ...rest
+ statistic,
}) => {
- const { mobile } = useResponsive();
-
return (
<Block
className={className}
@@ -160,12 +87,9 @@ const StatisticCard = memo<StatisticCardProps>(
style={style}
variant={variant}
>
- <AntdStatisticCard
- bordered={!mobile}
- className={cx(styles.container, styles.raw)}
- extra={loading ? <Spin percent={'auto'} size={'small'} /> : extra}
- title={
- typeof title === 'string' ? (
+ <div className={styles.header}>
+ <div className={styles.title}>
+ {typeof title === 'string' ? (
<Text
as={'h2'}
ellipsis={{ rows: 1, tooltip: true }}
@@ -181,10 +105,23 @@ const StatisticCard = memo<StatisticCardProps>(
</Text>
) : (
title
- )
- }
- {...rest}
- />
+ )}
+ </div>
+ {loading ? <Spin percent={'auto'} size={'small'} /> : extra}
+ </div>
+ {statistic && (
+ <Flexbox gap={16} style={statistic.style}>
+ <Statistic
+ className={styles.statistic}
+ precision={statistic.precision}
+ prefix={statistic.prefix}
+ styles={statistic.valueStyle ? { content: statistic.valueStyle } : undefined}
+ suffix={statistic.suffix}
+ value={statistic.value}
+ />
+ {statistic.description}
+ </Flexbox>
+ )}
</Block>
);
},
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index ae854678dfd..32d1823f9f9 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -715,6 +715,11 @@ export const chatToolKeys = {
// header is `portal:` not `document:`.
// =========================================================================
+// ---- api key (settings/apikey) -------------------------------------------
+export const apiKeyKeys = {
+ list: def('apiKey:list', () => ['apiKey:list']),
+};
+
// ---- stats (settings/stats + user header counts) ------------------------
export const statsKeys = {
agentUsageStat: def(
diff --git a/src/routes/(main)/settings/apikey/features/ApiKey.test.tsx b/src/routes/(main)/settings/apikey/features/ApiKey.test.tsx
new file mode 100644
index 00000000000..64a56566af8
--- /dev/null
+++ b/src/routes/(main)/settings/apikey/features/ApiKey.test.tsx
@@ -0,0 +1,316 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { SWRConfig } from 'swr';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { type ApiKeyItem, type CreateApiKeyParams } from '@/types/apiKey';
+
+import ApiKey from './ApiKey';
+
+const hoisted = vi.hoisted(() => ({
+ createApiKeyModal: vi.fn(),
+ message: { error: vi.fn(), success: vi.fn(), warning: vi.fn() },
+ state: {
+ activeWorkspaceId: null as string | null,
+ allowed: true,
+ manageSettingsAllowed: true,
+ reason: '',
+ },
+ trpc: {
+ createApiKey: vi.fn(),
+ deleteApiKey: vi.fn(),
+ getApiKeys: vi.fn(),
+ updateApiKey: vi.fn(),
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('antd', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ return {
+ ...actual,
+ App: { useApp: () => ({ message: hoisted.message }) },
+ };
+});
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => hoisted.state.activeWorkspaceId,
+ useActiveWorkspaceId: () => hoisted.state.activeWorkspaceId,
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: (permission: string) => ({
+ allowed:
+ permission === 'manage_settings'
+ ? hoisted.state.manageSettingsAllowed
+ : hoisted.state.allowed,
+ reason: hoisted.state.reason,
+ }),
+}));
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ apiKey: {
+ createApiKey: { mutate: hoisted.trpc.createApiKey },
+ deleteApiKey: { mutate: hoisted.trpc.deleteApiKey },
+ getApiKeys: { query: hoisted.trpc.getApiKeys },
+ updateApiKey: { mutate: hoisted.trpc.updateApiKey },
+ },
+ },
+}));
+
+vi.mock('./index', () => ({
+ ApiKeyDisplay: ({ apiKey }: { apiKey?: string }) => <span>{apiKey}</span>,
+ createApiKeyModal: hoisted.createApiKeyModal,
+ EditableCell: ({
+ disabled,
+ onSubmit,
+ type,
+ value,
+ }: {
+ disabled?: boolean;
+ onSubmit: (value: string) => void;
+ type: string;
+ value: string | null;
+ }) => (
+ <span>
+ <span>{value}</span>
+ <button disabled={disabled} type="button" onClick={() => onSubmit('renamed')}>
+ {`edit-${type}`}
+ </button>
+ </span>
+ ),
+}));
+
+const makeItem = (over: Partial<ApiKeyItem> = {}): ApiKeyItem => ({
+ accessedAt: new Date('2026-01-01'),
+ createdAt: new Date('2026-01-01'),
+ enabled: true,
+ id: 'key-1',
+ isMine: true,
+ key: 'lb-plain-secret',
+ lastUsedAt: null,
+ name: 'My Key',
+ updatedAt: new Date('2026-01-01'),
+ userId: 'me',
+ ...over,
+});
+
+const renderPage = () => {
+ const queryClient = new QueryClient({
+ defaultOptions: { mutations: { retry: false }, queries: { retry: false } },
+ });
+
+ return render(
+ <SWRConfig value={{ dedupingInterval: 0, provider: () => new Map() }}>
+ <QueryClientProvider client={queryClient}>
+ <ApiKey />
+ </QueryClientProvider>
+ </SWRConfig>,
+ );
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ hoisted.state.activeWorkspaceId = null;
+ hoisted.state.allowed = true;
+ hoisted.state.manageSettingsAllowed = true;
+ hoisted.state.reason = '';
+ hoisted.trpc.getApiKeys.mockResolvedValue([makeItem()]);
+ hoisted.trpc.createApiKey.mockResolvedValue({});
+ hoisted.trpc.updateApiKey.mockResolvedValue({});
+ hoisted.trpc.deleteApiKey.mockResolvedValue({});
+});
+
+describe('ApiKey', () => {
+ it('shows loading, then empty state when the first fetch returns no keys', async () => {
+ let resolveList!: (items: ApiKeyItem[]) => void;
+ hoisted.trpc.getApiKeys.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveList = resolve;
+ }),
+ );
+
+ const { container } = renderPage();
+
+ await waitFor(() => expect(container.querySelector('[aria-busy="true"]')).not.toBeNull());
+ expect(hoisted.trpc.getApiKeys).toHaveBeenCalledTimes(1);
+
+ resolveList([]);
+
+ expect(await screen.findByText('apikey.list.empty')).toBeInTheDocument();
+ });
+
+ it('renders fetched keys with their plaintext for the owner', async () => {
+ renderPage();
+
+ expect(await screen.findByText('My Key')).toBeInTheDocument();
+ expect(screen.getByText('lb-plain-secret')).toBeInTheDocument();
+ expect(screen.getByRole('switch')).toBeChecked();
+ });
+
+ it('creates a key through the modal and refreshes the list', async () => {
+ renderPage();
+ await screen.findByText('My Key');
+
+ fireEvent.click(screen.getByRole('button', { name: 'apikey.list.actions.create' }));
+
+ expect(hoisted.createApiKeyModal).toHaveBeenCalledTimes(1);
+ const { onSubmit } = hoisted.createApiKeyModal.mock.calls[0][0] as {
+ onSubmit: (values: CreateApiKeyParams) => Promise<void>;
+ };
+
+ await onSubmit({ expiresAt: null, name: 'new key' });
+
+ expect(hoisted.trpc.createApiKey).toHaveBeenCalledWith({ expiresAt: null, name: 'new key' });
+ await waitFor(() => expect(hoisted.trpc.getApiKeys).toHaveBeenCalledTimes(2));
+ });
+
+ it('renames a key and refreshes the list', async () => {
+ renderPage();
+ await screen.findByText('My Key');
+
+ fireEvent.click(screen.getByRole('button', { name: 'edit-text' }));
+
+ await waitFor(() =>
+ expect(hoisted.trpc.updateApiKey).toHaveBeenCalledWith({
+ id: 'key-1',
+ value: { name: 'renamed' },
+ }),
+ );
+ await waitFor(() => expect(hoisted.trpc.getApiKeys).toHaveBeenCalledTimes(2));
+ });
+
+ it('toggles a key off and refreshes the list', async () => {
+ renderPage();
+ await screen.findByText('My Key');
+
+ fireEvent.click(screen.getByRole('switch'));
+
+ await waitFor(() =>
+ expect(hoisted.trpc.updateApiKey).toHaveBeenCalledWith({
+ id: 'key-1',
+ value: { enabled: false },
+ }),
+ );
+ await waitFor(() => expect(hoisted.trpc.getApiKeys).toHaveBeenCalledTimes(2));
+ });
+
+ it('deletes a key after Popconfirm confirmation and refreshes the list', async () => {
+ renderPage();
+ await screen.findByText('My Key');
+
+ fireEvent.click(screen.getByRole('button', { name: 'apikey.list.actions.delete' }));
+
+ await screen.findByText('apikey.list.actions.deleteConfirm.title');
+ fireEvent.click(
+ screen.getByRole('button', { name: 'apikey.list.actions.deleteConfirm.actions.ok' }),
+ );
+
+ await waitFor(() => expect(hoisted.trpc.deleteApiKey).toHaveBeenCalledWith({ id: 'key-1' }));
+ await waitFor(() => expect(hoisted.trpc.getApiKeys).toHaveBeenCalledTimes(2));
+ });
+
+ it('shows the permission toast on forbidden errors without refreshing', async () => {
+ hoisted.trpc.updateApiKey.mockRejectedValue({ data: { code: 'FORBIDDEN' } });
+ renderPage();
+ await screen.findByText('My Key');
+
+ fireEvent.click(screen.getByRole('switch'));
+
+ await waitFor(() => expect(hoisted.message.error).toHaveBeenCalledWith('manageOnlyCreator'));
+ expect(hoisted.trpc.getApiKeys).toHaveBeenCalledTimes(1);
+ });
+
+ it('shows the generic toast on other mutation errors without refreshing', async () => {
+ hoisted.trpc.updateApiKey.mockRejectedValue(new Error('boom'));
+ renderPage();
+ await screen.findByText('My Key');
+
+ fireEvent.click(screen.getByRole('switch'));
+
+ await waitFor(() => expect(hoisted.message.error).toHaveBeenCalledWith('operationFailed'));
+ expect(hoisted.trpc.getApiKeys).toHaveBeenCalledTimes(1);
+ });
+
+ it('disables create and every row action without create_content permission', async () => {
+ hoisted.state.allowed = false;
+ hoisted.state.reason = 'no-permission';
+ renderPage();
+ await screen.findByText('My Key');
+
+ expect(screen.getByRole('button', { name: 'apikey.list.actions.create' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'edit-text' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'edit-date' })).toBeDisabled();
+ expect(screen.getByRole('switch')).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'no-permission' })).toBeDisabled();
+ });
+
+ it('allows a workspace admin to manage another member key while keeping its secret masked', async () => {
+ hoisted.state.activeWorkspaceId = 'ws-1';
+ hoisted.trpc.getApiKeys.mockResolvedValue([
+ makeItem(),
+ makeItem({ id: 'key-2', isMine: false, key: '', name: 'Other Key', userId: 'other' }),
+ ]);
+ renderPage();
+ await screen.findByText('Other Key');
+
+ const otherRow = screen.getByText('Other Key').closest('tr')!;
+ expect(within(otherRow).getByText(`lb-${'*'.repeat(12)}`)).toBeInTheDocument();
+ expect(within(otherRow).getByRole('button', { name: 'edit-text' })).toBeEnabled();
+ expect(within(otherRow).getByRole('switch')).toBeEnabled();
+ expect(
+ within(otherRow).getByRole('button', { name: 'apikey.list.actions.delete' }),
+ ).toBeEnabled();
+
+ const mineRow = screen.getByText('My Key').closest('tr')!;
+ expect(within(mineRow).getByText('lb-plain-secret')).toBeInTheDocument();
+ expect(within(mineRow).getByRole('button', { name: 'edit-text' })).toBeEnabled();
+ expect(within(mineRow).getByRole('switch')).toBeEnabled();
+ });
+
+ it('disables create and row actions for workspace members without settings permission', async () => {
+ hoisted.state.activeWorkspaceId = 'ws-1';
+ hoisted.state.manageSettingsAllowed = false;
+ renderPage();
+ await screen.findByText('My Key');
+
+ expect(screen.getByRole('button', { name: 'apikey.list.actions.create' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'edit-text' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'edit-date' })).toBeDisabled();
+ expect(screen.getByRole('switch')).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'manageOnlyCreator' })).toBeDisabled();
+ });
+
+ it('shows the unavailable copy with tooltip when key decryption failed', async () => {
+ hoisted.trpc.getApiKeys.mockResolvedValue([makeItem({ keyDecryptionFailed: true })]);
+ renderPage();
+
+ const unavailable = await screen.findByText('apikey.display.unavailable');
+ expect(unavailable).toHaveAttribute('title', 'apikey.display.unavailableDescription');
+ });
+
+ it('shows the creator column only in workspace mode', async () => {
+ hoisted.state.activeWorkspaceId = 'ws-1';
+ hoisted.trpc.getApiKeys.mockResolvedValue([
+ makeItem({ creator: 'Bob', isMine: false, key: '', userId: 'other' }),
+ ]);
+ renderPage();
+
+ expect(
+ await screen.findByRole('columnheader', { name: 'apikey.list.columns.creator' }),
+ ).toBeInTheDocument();
+ expect(screen.getByText('Bob')).toBeInTheDocument();
+ });
+
+ it('hides the creator column in personal mode', async () => {
+ renderPage();
+ await screen.findByText('My Key');
+
+ expect(screen.queryByRole('columnheader', { name: 'apikey.list.columns.creator' })).toBeNull();
+ });
+});
diff --git a/src/routes/(main)/settings/apikey/features/ApiKey.tsx b/src/routes/(main)/settings/apikey/features/ApiKey.tsx
index 04afa277565..2a4ece36cc2 100644
--- a/src/routes/(main)/settings/apikey/features/ApiKey.tsx
+++ b/src/routes/(main)/settings/apikey/features/ApiKey.tsx
@@ -1,19 +1,20 @@
'use client';
-import { type ActionType, type ProColumns } from '@ant-design/pro-components';
-import { ProTable } from '@ant-design/pro-components';
-import { Center, Empty } from '@lobehub/ui';
+import { Center, Empty, Text } from '@lobehub/ui';
import { Button, Switch } from '@lobehub/ui/base-ui';
import { useMutation } from '@tanstack/react-query';
import { App, Popconfirm } from 'antd';
import { createStaticStyles } from 'antd-style';
import { Trash } from 'lucide-react';
import { type FC } from 'react';
-import { useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { type LiteTableColumn } from '@/components/LiteTable';
+import LiteTable from '@/components/LiteTable';
import { usePermission } from '@/hooks/usePermission';
+import { useClientDataSWR } from '@/libs/swr';
+import { apiKeyKeys } from '@/libs/swr/keys';
import { lambdaClient } from '@/libs/trpc/client';
import { type ApiKeyItem, type CreateApiKeyParams, type UpdateApiKeyParams } from '@/types/apiKey';
import { isForbiddenError } from '@/utils/forbiddenError';
@@ -22,22 +23,19 @@ import { ApiKeyDisplay, createApiKeyModal, EditableCell } from './index';
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
- .ant-pro-card-body {
- padding-inline: 0;
-
- .ant-pro-table-list-toolbar-container {
- padding-block-start: 0;
- }
- }
+ overflow: hidden;
+ padding-block: 16px;
+ border-radius: ${cssVar.borderRadius};
+ background: ${cssVar.colorBgContainer};
`,
header: css`
display: flex;
- justify-content: flex-end;
- margin-block-end: ${cssVar.margin};
- `,
- table: css`
- border-radius: ${cssVar.borderRadius};
- background: ${cssVar.colorBgContainer};
+ gap: 16px;
+ align-items: center;
+ justify-content: space-between;
+
+ padding-block-end: 16px;
+ padding-inline: 24px;
`,
}));
@@ -60,7 +58,9 @@ const ApiKey: FC = () => {
'Only the creator or a workspace owner can do this',
);
- const actionRef = useRef<ActionType>(null);
+ const { data, isLoading, mutate } = useClientDataSWR<ApiKeyItem[]>(apiKeyKeys.list(), () =>
+ lambdaClient.apiKey.getApiKeys.query(),
+ );
const notifyMutationError = (error: unknown) => {
message.error(
@@ -73,7 +73,7 @@ const ApiKey: FC = () => {
const createMutation = useMutation({
mutationFn: (params: CreateApiKeyParams) => lambdaClient.apiKey.createApiKey.mutate(params),
onSuccess: () => {
- actionRef.current?.reload();
+ mutate();
},
});
@@ -82,7 +82,7 @@ const ApiKey: FC = () => {
lambdaClient.apiKey.updateApiKey.mutate({ id, value: params }),
onError: notifyMutationError,
onSuccess: () => {
- actionRef.current?.reload();
+ mutate();
},
});
@@ -90,7 +90,7 @@ const ApiKey: FC = () => {
mutationFn: (id: string) => lambdaClient.apiKey.deleteApiKey.mutate({ id }),
onError: notifyMutationError,
onSuccess: () => {
- actionRef.current?.reload();
+ mutate();
},
});
@@ -103,11 +103,11 @@ const ApiKey: FC = () => {
});
};
- const columns: ProColumns<ApiKeyItem>[] = [
+ const columns: LiteTableColumn<ApiKeyItem>[] = [
{
- dataIndex: 'name',
key: 'name',
- render: (_, apiKey) => {
+ listSlot: 'title',
+ render: (apiKey) => {
const canManage = checkManageable(apiKey.userId);
return (
<span title={canManage ? undefined : manageTooltip}>
@@ -131,10 +131,8 @@ const ApiKey: FC = () => {
title: t('apikey.list.columns.name'),
},
{
- dataIndex: 'key',
- ellipsis: true,
key: 'key',
- render: (_, apiKey) =>
+ render: (apiKey) =>
// Plaintext is returned only for the caller's own keys; other members'
// rows are masked (owners can manage them but never see the secret).
apiKey.isMine === false ? (
@@ -152,18 +150,17 @@ const ApiKey: FC = () => {
...(activeWorkspaceId
? [
{
- dataIndex: 'creator',
key: 'creator',
- renderText: (_: unknown, apiKey: ApiKeyItem) => apiKey.creator || '-',
+ render: (apiKey: ApiKeyItem) => apiKey.creator || '-',
title: t('apikey.list.columns.creator'),
width: 140,
- } satisfies ProColumns<ApiKeyItem>,
+ } satisfies LiteTableColumn<ApiKeyItem>,
]
: []),
{
- dataIndex: 'enabled',
key: 'enabled',
- render: (_, apiKey: ApiKeyItem) => {
+ listSlot: 'extra',
+ render: (apiKey: ApiKeyItem) => {
const canManage = checkManageable(apiKey.userId);
return (
<span style={{ display: 'inline-flex' }} title={canManage ? undefined : manageTooltip}>
@@ -182,9 +179,8 @@ const ApiKey: FC = () => {
width: 100,
},
{
- dataIndex: 'expiresAt',
key: 'expiresAt',
- render: (_, apiKey) => {
+ render: (apiKey) => {
const canManage = checkManageable(apiKey.userId);
return (
<span title={canManage ? undefined : manageTooltip}>
@@ -212,15 +208,15 @@ const ApiKey: FC = () => {
width: 170,
},
{
- dataIndex: 'lastUsedAt',
key: 'lastUsedAt',
- renderText: (_, apiKey: ApiKeyItem) =>
+ render: (apiKey: ApiKeyItem) =>
apiKey.lastUsedAt?.toLocaleString() || t('apikey.display.neverUsed'),
title: t('apikey.list.columns.lastUsedAt'),
},
{
key: 'action',
- render: (_: any, apiKey: ApiKeyItem) => {
+ listSlot: 'actions',
+ render: (apiKey: ApiKeyItem) => {
const canManage = checkManageable(apiKey.userId);
return (
<Popconfirm
@@ -258,43 +254,29 @@ const ApiKey: FC = () => {
return (
<div className={styles.container}>
- <ProTable
- actionRef={actionRef}
- className={styles.table}
+ <div className={styles.header}>
+ <Text as={'h3'} style={{ fontSize: 16, fontWeight: 500, margin: 0 }}>
+ {t('apikey.list.title')}
+ </Text>
+ <Button
+ disabled={!canCreate}
+ title={canCreate ? undefined : canEdit ? manageTooltip : reason}
+ type="primary"
+ onClick={handleCreate}
+ >
+ {t('apikey.list.actions.create')}
+ </Button>
+ </div>
+ <LiteTable
columns={columns}
- headerTitle={t('apikey.list.title')}
- options={false}
- pagination={false}
- rowKey="id"
- search={false}
- locale={{
- emptyText: (
- <Center height={240} width={'100%'}>
- <Empty description={t('apikey.list.empty')} />
- </Center>
- ),
- }}
- request={async () => {
- const apiKeys = await lambdaClient.apiKey.getApiKeys.query();
-
- return {
- data: apiKeys,
- success: true,
- };
- }}
- toolbar={{
- actions: [
- <Button
- disabled={!canCreate}
- key="create"
- title={canCreate ? undefined : canEdit ? manageTooltip : reason}
- type="primary"
- onClick={handleCreate}
- >
- {t('apikey.list.actions.create')}
- </Button>,
- ],
- }}
+ dataSource={data}
+ loading={isLoading}
+ rowKey={(apiKey) => apiKey.id}
+ emptyText={
+ <Center height={240} width={'100%'}>
+ <Empty description={t('apikey.list.empty')} />
+ </Center>
+ }
/>
</div>
);