🤯 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
💄 style(apikey): redesign API Key management (#19328)
Arvin Xu33ba35e6cb4a
diff --git a/apps/server/src/routers/lambda/__tests__/apiKey.test.ts b/apps/server/src/routers/lambda/__tests__/apiKey.test.tsindex 1cfb8023fb8..409e154fba7 100644--- a/apps/server/src/routers/lambda/__tests__/apiKey.test.ts+++ b/apps/server/src/routers/lambda/__tests__/apiKey.test.ts@@ -12,6 +12,7 @@ const {} = vi.hoisted(() => {const apiKeyModel = {create: vi.fn(),+ createWithPlaintext: vi.fn(),delete: vi.fn(),deleteAll: vi.fn(),findById: vi.fn(),@@ -74,10 +75,11 @@ describe('apiKeyRouter workspace member access', () => {mockCanUseWorkspaceApiKeys.mockResolvedValue(true);mockGetApiKeyMemberCreation.mockResolvedValue('all_members');mockAuditCreate.mockResolvedValue(undefined);- mockApiKeyModel.create.mockResolvedValue({+ mockApiKeyModel.createWithPlaintext.mockResolvedValue({enabled: true,expiresAt: null,id: 'key-1',+ key: 'sk-lh-plaintext',name: 'Member integration',scopes: ['*'],userId: 'member-user',@@ -107,13 +109,15 @@ describe('apiKeyRouter workspace member access', () => {});it('allows members to create full-access keys when the workspace policy allows members', async () => {- await createCaller('member').createApiKey({+ const created = await createCaller('member').createApiKey({expiresAt: null,name: 'Member integration',scopes: ['*'],});- expect(mockApiKeyModel.create).toHaveBeenCalledWith({+ // The creation response is the one-time plaintext reveal for the UI.+ expect(created.key).toBe('sk-lh-plaintext');+ expect(mockApiKeyModel.createWithPlaintext).toHaveBeenCalledWith({expiresAt: null,name: 'Member integration',scopes: ['*'],@@ -133,7 +137,7 @@ describe('apiKeyRouter workspace member access', () => {await expect(createCaller('member').createApiKey({ name: 'Blocked', scopes: ['agent:read'] }),).rejects.toMatchObject({ code: 'FORBIDDEN' });- expect(mockApiKeyModel.create).not.toHaveBeenCalled();+ expect(mockApiKeyModel.createWithPlaintext).not.toHaveBeenCalled();});it('lets the creator edit scopes in place and records before/after grants', async () => {diff --git a/apps/server/src/routers/lambda/apiKey.ts b/apps/server/src/routers/lambda/apiKey.tsindex 7a190217da4..4374b9067c0 100644--- a/apps/server/src/routers/lambda/apiKey.ts+++ b/apps/server/src/routers/lambda/apiKey.ts@@ -101,7 +101,9 @@ export const apiKeyRouter = router({}const scopes = normalizeScopes(input.scopes);- const result = await ctx.apiKeyModel.create({ ...input, scopes });+ // Plaintext goes back to the creator exactly once so the UI can show a+ // copy-now step; list/detail reads keep returning the stored record.+ const result = await ctx.apiKeyModel.createWithPlaintext({ ...input, scopes });await recordApiKeyAudit(ctx, {action: 'api_key.created',metadata: { expiresAt: result.expiresAt, name: result.name, scopes: result.scopes ?? null },diff --git a/locales/en-US/auth.json b/locales/en-US/auth.jsonindex 69bbb57eaec..ec826fb959f 100644--- a/locales/en-US/auth.json+++ b/locales/en-US/auth.json@@ -3,6 +3,9 @@"agreement.confirm.content": "By selecting \"Agree and continue\", you confirm that you have read and agree to the <terms>Terms and Conditions</terms> and <privacy>Privacy Policy</privacy>.","agreement.confirm.ok": "Agree and continue","agreement.confirm.title": "Terms and Privacy Policy",+ "apikey.created.done": "Done",+ "apikey.created.hint": "You can view or copy this key again from the list at any time.",+ "apikey.created.title": "API Key created","apikey.detail.createdAt": "Created","apikey.detail.permissions.cancel": "Cancel","apikey.detail.permissions.edit": "Edit permissions",@@ -20,7 +23,14 @@"apikey.display.unavailable": "Secret unavailable","apikey.display.unavailableDescription": "This secret cannot be displayed. Recreate the API Key if you no longer have it.","apikey.form.fields.expiresAt.label": "Expiration Date",- "apikey.form.fields.expiresAt.placeholder": "Never expires",+ "apikey.form.fields.expiresAt.placeholder": "Select a date",+ "apikey.form.fields.expiresAt.presets.180d": "180 days",+ "apikey.form.fields.expiresAt.presets.1y": "1 year",+ "apikey.form.fields.expiresAt.presets.30d": "30 days",+ "apikey.form.fields.expiresAt.presets.60d": "60 days",+ "apikey.form.fields.expiresAt.presets.7d": "7 days",+ "apikey.form.fields.expiresAt.presets.90d": "90 days",+ "apikey.form.fields.expiresAt.presets.custom": "Custom date","apikey.form.fields.name.label": "Name","apikey.form.fields.name.placeholder": "Please enter API Key name","apikey.form.fields.scopes.fullAccess": "Full access",@@ -36,17 +46,22 @@"apikey.list.actions.deleteConfirm.actions.ok": "Confirm","apikey.list.actions.deleteConfirm.content": "Are you sure you want to delete this API Key?","apikey.list.actions.deleteConfirm.title": "Confirm Action",+ "apikey.list.actions.more": "More actions",+ "apikey.list.actions.viewDetails": "View details","apikey.list.actions.viewDocs": "API Docs","apikey.list.columns.creator": "Creator","apikey.list.columns.expiresAt": "Expiration Date","apikey.list.columns.key": "Key","apikey.list.columns.lastUsedAt": "Last Used","apikey.list.columns.name": "Name",+ "apikey.list.columns.scopes": "Scope","apikey.list.columns.status": "Enabled",+ "apikey.list.desc": "API Keys let external tools and scripts call the LobeHub API as you.","apikey.list.empty": "No API Keys yet","apikey.list.restrictedEmpty.desc": "Only workspace admins can create API Keys. Contact a workspace admin if you need one.","apikey.list.restrictedEmpty.title": "API Key creation is restricted","apikey.list.title": "API Key List",+ "apikey.scopes.count": "{{count}} scopes","apikey.scopes.fullAccess": "Full access","apikey.scopes.grantJoin": ": ","apikey.scopes.groups.agent": "Agents",@@ -64,6 +79,8 @@"apikey.scopes.read": "Read","apikey.scopes.separator": ", ","apikey.scopes.write": "Write",+ "apikey.status.disabled": "Disabled",+ "apikey.status.expired": "Expired","apikey.validation.required": "This field cannot be empty","authModal.description": "Your sign-in session has expired. Please sign in again to continue using cloud sync features.","authModal.later": "Later",diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.jsonindex 13dea0f023c..442816a569c 100644--- a/locales/zh-CN/auth.json+++ b/locales/zh-CN/auth.json@@ -3,6 +3,9 @@"agreement.confirm.content": "点击“同意并继续”即表示你已阅读并同意<terms>服务条款</terms>与<privacy>隐私政策</privacy>。","agreement.confirm.ok": "同意并继续","agreement.confirm.title": "确认服务条款与隐私政策",+ "apikey.created.done": "完成",+ "apikey.created.hint": "之后你也可以随时在列表中查看或复制该密钥。",+ "apikey.created.title": "API Key 已创建","apikey.detail.createdAt": "创建时间","apikey.detail.permissions.cancel": "取消","apikey.detail.permissions.edit": "编辑权限",@@ -20,7 +23,14 @@"apikey.display.unavailable": "密钥内容无法显示","apikey.display.unavailableDescription": "当前无法显示这条密钥的内容。如果你没有留存原始密钥,请重新创建。","apikey.form.fields.expiresAt.label": "过期时间",- "apikey.form.fields.expiresAt.placeholder": "永久有效",+ "apikey.form.fields.expiresAt.placeholder": "选择日期",+ "apikey.form.fields.expiresAt.presets.180d": "180 天",+ "apikey.form.fields.expiresAt.presets.1y": "1 年",+ "apikey.form.fields.expiresAt.presets.30d": "30 天",+ "apikey.form.fields.expiresAt.presets.60d": "60 天",+ "apikey.form.fields.expiresAt.presets.7d": "7 天",+ "apikey.form.fields.expiresAt.presets.90d": "90 天",+ "apikey.form.fields.expiresAt.presets.custom": "自定义日期","apikey.form.fields.name.label": "名称","apikey.form.fields.name.placeholder": "请输入 API Key 名称","apikey.form.fields.scopes.fullAccess": "完全访问",@@ -36,17 +46,22 @@"apikey.list.actions.deleteConfirm.actions.ok": "确认","apikey.list.actions.deleteConfirm.content": "删除后将无法再用此 API Key 访问接口。需要时你可以随时创建新的 API Key。","apikey.list.actions.deleteConfirm.title": "确认删除这个 API Key?",+ "apikey.list.actions.more": "更多操作",+ "apikey.list.actions.viewDetails": "查看详情","apikey.list.actions.viewDocs": "API 文档","apikey.list.columns.creator": "创建者","apikey.list.columns.expiresAt": "过期时间","apikey.list.columns.key": "密钥","apikey.list.columns.lastUsedAt": "最后使用时间","apikey.list.columns.name": "名称",+ "apikey.list.columns.scopes": "权限","apikey.list.columns.status": "启用",+ "apikey.list.desc": "API Key 用于让外部工具和脚本以你的身份调用 LobeHub API。","apikey.list.empty": "暂无 API Key","apikey.list.restrictedEmpty.desc": "仅工作区管理员可以创建 API Key。如有需要,请联系工作区管理员。","apikey.list.restrictedEmpty.title": "API Key 创建权限已受限","apikey.list.title": "API Key 列表",+ "apikey.scopes.count": "{{count}} 项权限","apikey.scopes.fullAccess": "完全访问","apikey.scopes.grantJoin": ":","apikey.scopes.groups.agent": "助手",@@ -64,6 +79,8 @@"apikey.scopes.read": "读取","apikey.scopes.separator": "、","apikey.scopes.write": "写入",+ "apikey.status.disabled": "已停用",+ "apikey.status.expired": "已过期","apikey.validation.required": "内容不得为空","authModal.description": "您的登录会话已过期,请重新登录以继续使用云同步功能。","authModal.later": "稍后",diff --git a/packages/locales/src/default/auth.ts b/packages/locales/src/default/auth.tsindex 77efb3add53..de98c9eff17 100644--- a/packages/locales/src/default/auth.ts+++ b/packages/locales/src/default/auth.ts@@ -5,6 +5,9 @@ export default {'By selecting "Agree and continue", you confirm that you have read and agree to the <terms>Terms and Conditions</terms> and <privacy>Privacy Policy</privacy>.','agreement.confirm.ok': 'Agree and continue','agreement.confirm.title': 'Terms and Privacy Policy',+ 'apikey.created.done': 'Done',+ 'apikey.created.hint': 'You can view or copy this key again from the list at any time.',+ 'apikey.created.title': 'API Key created','apikey.detail.createdAt': 'Created','apikey.detail.permissions.cancel': 'Cancel','apikey.detail.permissions.edit': 'Edit permissions',@@ -23,7 +26,14 @@ export default {'apikey.display.unavailableDescription':'This secret cannot be displayed. Recreate the API Key if you no longer have it.','apikey.form.fields.expiresAt.label': 'Expiration Date',- 'apikey.form.fields.expiresAt.placeholder': 'Never expires',+ 'apikey.form.fields.expiresAt.placeholder': 'Select a date',+ 'apikey.form.fields.expiresAt.presets.180d': '180 days',+ 'apikey.form.fields.expiresAt.presets.1y': '1 year',+ 'apikey.form.fields.expiresAt.presets.30d': '30 days',+ 'apikey.form.fields.expiresAt.presets.60d': '60 days',+ 'apikey.form.fields.expiresAt.presets.7d': '7 days',+ 'apikey.form.fields.expiresAt.presets.90d': '90 days',+ 'apikey.form.fields.expiresAt.presets.custom': 'Custom date','apikey.form.fields.name.label': 'Name','apikey.form.fields.name.placeholder': 'Please enter API Key name','apikey.form.fields.scopes.fullAccess': 'Full access',@@ -41,18 +51,23 @@ export default {'apikey.list.actions.deleteConfirm.actions.ok': 'Confirm','apikey.list.actions.deleteConfirm.content': 'Are you sure you want to delete this API Key?','apikey.list.actions.deleteConfirm.title': 'Confirm Action',+ 'apikey.list.actions.more': 'More actions',+ 'apikey.list.actions.viewDetails': 'View details','apikey.list.actions.viewDocs': 'API Docs','apikey.list.columns.creator': 'Creator','apikey.list.columns.expiresAt': 'Expiration Date','apikey.list.columns.key': 'Key','apikey.list.columns.lastUsedAt': 'Last Used','apikey.list.columns.name': 'Name',+ 'apikey.list.columns.scopes': 'Scope','apikey.list.columns.status': 'Enabled',+ 'apikey.list.desc': 'API Keys let external tools and scripts call the LobeHub API as you.','apikey.list.empty': 'No API Keys yet','apikey.list.restrictedEmpty.desc':'Only workspace admins can create API Keys. Contact a workspace admin if you need one.','apikey.list.restrictedEmpty.title': 'API Key creation is restricted','apikey.list.title': 'API Key List',+ 'apikey.scopes.count': '{{count}} scopes','apikey.scopes.fullAccess': 'Full access','apikey.scopes.grantJoin': ': ','apikey.scopes.groups.agent': 'Agents',@@ -70,6 +85,8 @@ export default {'apikey.scopes.read': 'Read','apikey.scopes.separator': ', ','apikey.scopes.write': 'Write',+ 'apikey.status.disabled': 'Disabled',+ 'apikey.status.expired': 'Expired','apikey.validation.required': 'This field cannot be empty','authModal.description':'Your sign-in session has expired. Please sign in again to continue using cloud sync features.',diff --git a/src/features/Settings/apikey/features/ApiKey.test.tsx b/src/features/Settings/apikey/features/ApiKey.test.tsxindex 768ad2c9d1b..072c81249b4 100644--- a/src/features/Settings/apikey/features/ApiKey.test.tsx+++ b/src/features/Settings/apikey/features/ApiKey.test.tsx@@ -10,6 +10,7 @@ import ApiKey from './ApiKey';import ScopeSelector from './ApiKeyModal/ScopeSelector';const hoisted = vi.hoisted(() => ({+ confirmModal: vi.fn((opts: { onOk?: () => void }) => opts.onOk?.()),createApiKeyModal: vi.fn(),state: {activeWorkspaceId: null as string | null,@@ -30,6 +31,24 @@ const hoisted = vi.hoisted(() => ({vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({...((await importOriginal()) as Record<string, unknown>),+ // Menu items surface as plain buttons so row actions are reachable in jsdom.+ DropdownMenu: ({+ children,+ items,+ }: {+ children?: React.ReactNode;+ items: { disabled?: boolean; key: string; label: string; onClick?: () => void }[];+ }) => (+ <span>+ {children}+ {items.map((item) => (+ <button disabled={item.disabled} key={item.key} type="button" onClick={item.onClick}>+ {item.label}+ </button>+ ))}+ </span>+ ),+ confirmModal: hoisted.confirmModal,toast: hoisted.toast,}));@@ -303,6 +322,10 @@ describe('ApiKey', () => {expect(screen.getByRole('button', { name: 'apikey.list.actions.create' })).toBeDisabled();+ // the row menu's destructive action is gated too+ const row = screen.getByText('My Key').closest('tr')!;+ expect(within(row).getByRole('button', { name: 'apikey.list.actions.delete' })).toBeDisabled();+// the drawer carries the whole management surface, so it must be gatedconst dialog = await openDetail('My Key');expect(within(dialog).getByRole('button', { name: 'edit-text' })).toBeDisabled();@@ -324,6 +347,10 @@ describe('ApiKey', () => {const otherRow = screen.getByText('Other Key').closest('tr')!;expect(within(otherRow).getByText(`sk-lh-${'*'.repeat(12)}`)).toBeInTheDocument();+ // central revocation is one row-menu click away for an admin+ expect(+ within(otherRow).getByRole('button', { name: 'apikey.list.actions.delete' }),+ ).toBeEnabled();// an admin can centrally revoke another member's key, but only its creator// can rename, disable, or edit the grants.@@ -409,15 +436,43 @@ describe('ApiKey', () => {expect(screen.queryByRole('columnheader', { name: 'apikey.list.columns.creator' })).toBeNull();});- it('keeps scopes out of the list — they live in the detail drawer', async () => {- hoisted.trpc.getApiKeys.mockResolvedValue([makeItem({ scopes: ['agent:read'] })]);+ it('summarises scopes as a compact tag — the full grant list stays in the drawer', async () => {+ hoisted.trpc.getApiKeys.mockResolvedValue([+ makeItem({ scopes: ['agent:read', 'mcp:read'] }),+ makeItem({ id: 'key-2', name: 'Full Key' }),+ ]);renderPage();await screen.findByText('My Key');- expect(screen.queryByRole('columnheader', { name: 'apikey.list.columns.scopes' })).toBeNull();- expect(screen.getByText('My Key').closest('tr')!.textContent).not.toContain(- 'apikey.scopes.groups.agent',- );+ const scopedRow = screen.getByText('My Key').closest('tr')!;+ expect(within(scopedRow).getByText('apikey.scopes.count')).toBeInTheDocument();+ expect(scopedRow.textContent).not.toContain('apikey.scopes.groups.agent');++ // scopes absent = legacy full access, same badge as an explicit `['*']`+ const fullRow = screen.getByText('Full Key').closest('tr')!;+ expect(within(fullRow).getByText('apikey.scopes.fullAccess')).toBeInTheDocument();+ });++ it('deletes a key from the row menu after confirmation', async () => {+ renderPage();+ await screen.findByText('My Key');++ const row = screen.getByText('My Key').closest('tr')!;+ fireEvent.click(within(row).getByRole('button', { name: 'apikey.list.actions.delete' }));++ expect(hoisted.confirmModal).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(hoisted.trpc.deleteApiKey).toHaveBeenCalledWith({ id: 'key-1' }));+ await waitFor(() => expect(hoisted.trpc.getApiKeys).toHaveBeenCalledTimes(2));+ });++ it('opens the detail drawer from the row menu', async () => {+ renderPage();+ await screen.findByText('My Key');++ const row = screen.getByText('My Key').closest('tr')!;+ fireEvent.click(within(row).getByRole('button', { name: 'apikey.list.actions.viewDetails' }));++ expect(await screen.findByRole('dialog')).toBeInTheDocument();});it('opens the detail drawer on row click listing only the granted scopes', async () => {diff --git a/src/features/Settings/apikey/features/ApiKey.tsx b/src/features/Settings/apikey/features/ApiKey.tsxindex f9ffe0796d0..e3cb6f7f18c 100644--- a/src/features/Settings/apikey/features/ApiKey.tsx+++ b/src/features/Settings/apikey/features/ApiKey.tsx@@ -2,10 +2,20 @@import { isDesktop } from '@lobechat/const';import { Center, Empty, Flexbox } from '@lobehub/ui';-import { Button, Text, toast } from '@lobehub/ui/base-ui';+import {+ ActionIcon,+ Button,+ confirmModal,+ DropdownMenu,+ Tag,+ Text,+ toast,+} from '@lobehub/ui/base-ui';import { useMutation } from '@tanstack/react-query';import { createStaticStyles } from 'antd-style';-import { BookOpen, ChevronRight } from 'lucide-react';+import dayjs from 'dayjs';+import relativeTime from 'dayjs/plugin/relativeTime';+import { BookOpen, Eye, MoreHorizontal, Trash } from 'lucide-react';import { type FC, useState } from 'react';import { useTranslation } from 'react-i18next';import urlJoin from 'url-join';@@ -13,6 +23,7 @@ import urlJoin from 'url-join';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { type LiteTableColumn } from '@/components/LiteTable';import LiteTable from '@/components/LiteTable';+import { isFullAccessApiKey } from '@/const/apiKeyScope';import { usePermission } from '@/hooks/usePermission';import { useClientDataSWR } from '@/libs/swr';import { apiKeyKeys } from '@/libs/swr/keys';@@ -33,26 +44,23 @@ const styles = createStaticStyles(({ css, cssVar }) => ({border-radius: ${cssVar.borderRadius};background: ${cssVar.colorBgContainer};`,- /* Always visible, not reveal-on-hover: the row's only job besides browsing is- to lead into the detail drawer, and a marker you must hover to discover- doesn't advertise that. Quiet by default, darker under the cursor. */- enterIcon: css`- color: ${cssVar.colorTextQuaternary};- transition: color 0.2s ease;-- tr:hover & {- color: ${cssVar.colorText};- }+ expired: css`+ color: ${cssVar.colorError};`,header: css`display: flex;gap: 16px;- align-items: center;+ align-items: flex-start;justify-content: space-between;padding-block-end: 16px;padding-inline: 24px;`,+ /* Dates and "never used / never expires" placeholders read as metadata, not+ content — keep them quieter than the name and key. */+ muted: css`+ color: ${cssVar.colorTextTertiary};+ `,/* The name doubles as the entry point into the detail drawer. */nameLink: css`font-weight: 500;@@ -63,6 +71,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));+dayjs.extend(relativeTime);++const isExpired = (apiKey: ApiKeyItem) =>+ !!apiKey.expiresAt && dayjs(apiKey.expiresAt).isBefore(dayjs());+const ApiKey: FC = () => {const { t } = useTranslation('auth');const { t: tc } = useTranslation('common');@@ -130,19 +143,38 @@ const ApiKey: FC = () => {const handleCreate = () => {if (!canCreate) return;createApiKeyModal({- onSubmit: async (values) => {- await createMutation.mutateAsync(values);+ onSubmit: async (values) => createMutation.mutateAsync(values),+ });+ };++ const confirmDelete = (apiKey: ApiKeyItem) => {+ confirmModal({+ cancelText: t('apikey.list.actions.deleteConfirm.actions.cancel'),+ content: t('apikey.list.actions.deleteConfirm.content'),+ okButtonProps: { danger: true },+ okText: t('apikey.list.actions.deleteConfirm.actions.ok'),+ onOk: async () => {+ await deleteMutation.mutateAsync(apiKey.id);},+ title: t('apikey.list.actions.deleteConfirm.title'),});};+ const canDeleteRow = (apiKey: ApiKeyItem) =>+ canEdit && (apiKey.isMine !== false || workspacePolicy.isAdmin);+const columns: LiteTableColumn<ApiKeyItem>[] = [{key: 'name',listSlot: 'title',// The name is the affordance into the detail drawer — styled as a link so// the row reads as navigable rather than inert.- render: (apiKey) => <span className={styles.nameLink}>{apiKey.name}</span>,+ render: (apiKey) => (+ <Flexbox horizontal align={'center'} gap={8}>+ <span className={styles.nameLink}>{apiKey.name}</span>+ {apiKey.enabled === false && <Tag>{t('apikey.status.disabled')}</Tag>}+ </Flexbox>+ ),title: t('apikey.list.columns.name'),},{@@ -163,10 +195,22 @@ const ApiKey: FC = () => {</span>),title: t('apikey.list.columns.key'),- width: 230,+ width: 220,+ },+ // A count summary can't truncate, so scopes earn a list column; the full+ // grant list still lives in the detail drawer (row click).+ {+ key: 'scopes',+ render: (apiKey) => (+ <Tag>+ {isFullAccessApiKey(apiKey.scopes)+ ? t('apikey.scopes.fullAccess')+ : t('apikey.scopes.count', { count: apiKey.scopes?.length ?? 0 })}+ </Tag>+ ),+ title: t('apikey.list.columns.scopes'),+ width: 110,},- // Scopes are deliberately absent from the list: the column could only ever- // truncate, and the detail drawer (row click) shows the full grant list....(activeWorkspaceId && workspacePolicy.isAdmin? [{@@ -179,32 +223,85 @@ const ApiKey: FC = () => {: []),{key: 'expiresAt',- render: (apiKey) => apiKey.expiresAt?.toLocaleString() || t('apikey.display.neverExpires'),+ render: (apiKey) =>+ apiKey.expiresAt ? (+ <span+ className={isExpired(apiKey) ? styles.expired : undefined}+ title={apiKey.expiresAt.toLocaleString()}+ >+ {isExpired(apiKey) ? t('apikey.status.expired') : apiKey.expiresAt.toLocaleDateString()}+ </span>+ ) : (+ <span className={styles.muted}>{t('apikey.display.neverExpires')}</span>+ ),title: t('apikey.list.columns.expiresAt'),- width: 170,+ width: 130,},{key: 'lastUsedAt',render: (apiKey: ApiKeyItem) =>- apiKey.lastUsedAt?.toLocaleString() || t('apikey.display.neverUsed'),+ apiKey.lastUsedAt ? (+ // Relative time answers "is this key still in use?" at a glance; the+ // exact timestamp stays one hover away.+ <span title={apiKey.lastUsedAt.toLocaleString()}>+ {dayjs(apiKey.lastUsedAt).fromNow()}+ </span>+ ) : (+ <span className={styles.muted}>{t('apikey.display.neverUsed')}</span>+ ),title: t('apikey.list.columns.lastUsedAt'),},- // Every management action (rename, expiry, enable/disable, delete) lives in- // the detail drawer: the list browses, the drawer owns one key's surface.+ // Browse actions stay on the row (Vercel-token style); the drawer remains+ // the full management surface for rename / expiry / scopes. In the narrow+ // card layout the menu sits beside the name (`extra`), not under the meta.{- key: 'enter',- render: () => <ChevronRight className={styles.enterIcon} size={16} />,+ key: 'actions',+ listSlot: 'extra',+ render: (apiKey) => (+ <span onClick={(e) => e.stopPropagation()}>+ <DropdownMenu+ placement={'bottomRight'}+ items={[+ {+ icon: Eye,+ key: 'view',+ label: t('apikey.list.actions.viewDetails'),+ onClick: () => setDetailId(apiKey.id),+ },+ {+ danger: true,+ disabled: !canDeleteRow(apiKey),+ icon: Trash,+ key: 'delete',+ label: t('apikey.list.actions.delete'),+ onClick: () => confirmDelete(apiKey),+ },+ ]}+ >+ <ActionIcon+ icon={MoreHorizontal}+ size={'small'}+ title={t('apikey.list.actions.more')}+ />+ </DropdownMenu>+ </span>+ ),title: '',- width: 40,+ width: 48,},];return (<div className={styles.container}><div className={styles.header}>- <Text as={'h3'} style={{ fontSize: 16, fontWeight: 500, margin: 0 }}>- {t('apikey.list.title')}- </Text>+ <Flexbox gap={4}>+ <Text as={'h3'} style={{ fontSize: 16, fontWeight: 500, margin: 0 }}>+ {t('apikey.list.title')}+ </Text>+ <Text style={{ fontSize: 13 }} type={'secondary'}>+ {t('apikey.list.desc')}+ </Text>+ </Flexbox><Flexbox horizontal gap={8}><Button href={docsHref} icon={BookOpen} target="_blank" type="text">{t('apikey.list.actions.viewDocs')}@@ -242,12 +339,10 @@ const ApiKey: FC = () => {/><ApiKeyDetailapiKey={detailApiKey}+ canDelete={canEdit && !!detailApiKey && canDeleteRow(detailApiKey)}canEdit={canEdit && !!detailApiKey && detailApiKey.isMine !== false}manageTooltip={canEdit ? manageTooltip : (reason ?? manageTooltip)}open={!!detailApiKey}- canDelete={- canEdit && !!detailApiKey && (detailApiKey.isMine !== false || workspacePolicy.isAdmin)- }onClose={() => setDetailId(undefined)}onDelete={async (id) => {await deleteMutation.mutateAsync(id);diff --git a/src/features/Settings/apikey/features/ApiKeyDatePicker/index.tsx b/src/features/Settings/apikey/features/ApiKeyDatePicker/index.tsxindex 47ff0473f4e..12f687a72a8 100644--- a/src/features/Settings/apikey/features/ApiKeyDatePicker/index.tsx+++ b/src/features/Settings/apikey/features/ApiKeyDatePicker/index.tsx@@ -8,9 +8,20 @@ import { useTranslation } from 'react-i18next';interface ApiKeyDatePickerProps extends Omit<DatePickerProps, 'onChange'> {onChange?: (date: Dayjs | null) => void;+ /**+ * The "never expires" footer clears the date. Hide it where "never" is+ * already a sibling choice (the create form's preset select), so the picker+ * only ever answers "which date".+ */+ showNeverExpiresFooter?: boolean;}-const ApiKeyDatePicker: FC<ApiKeyDatePickerProps> = ({ value, onChange, ...props }) => {+const ApiKeyDatePicker: FC<ApiKeyDatePickerProps> = ({+ value,+ onChange,+ showNeverExpiresFooter = true,+ ...props+}) => {const { t } = useTranslation('auth');const handleOnChange = (date: Dayjs[] | Dayjs | null) => {@@ -32,24 +43,26 @@ const ApiKeyDatePicker: FC<ApiKeyDatePickerProps> = ({ value, onChange, ...propsminDate={dayjs()}placeholder={t('apikey.form.fields.expiresAt.placeholder')}showNow={false}- renderExtraFooter={() => (- <Flex justify="center">- <a- role="button"- style={{ cursor: 'pointer' }}- tabIndex={0}- onClick={() => handleOnChange(null)}- onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- handleOnChange(null);- }- }}- >- {t('apikey.display.neverExpires')}- </a>- </Flex>- )}+ renderExtraFooter={() =>+ showNeverExpiresFooter && (+ <Flex justify="center">+ <a+ role="button"+ style={{ cursor: 'pointer' }}+ tabIndex={0}+ onClick={() => handleOnChange(null)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ handleOnChange(null);+ }+ }}+ >+ {t('apikey.display.neverExpires')}+ </a>+ </Flex>+ )+ }onChange={handleOnChange}/>);diff --git a/src/features/Settings/apikey/features/ApiKeyDisplay/index.tsx b/src/features/Settings/apikey/features/ApiKeyDisplay/index.tsxindex 99c6bd63eea..3a8921bb85e 100644--- a/src/features/Settings/apikey/features/ApiKeyDisplay/index.tsx+++ b/src/features/Settings/apikey/features/ApiKeyDisplay/index.tsx@@ -1,66 +1,59 @@-import { CopyOutlined, EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons';-import { Button, toast } from '@lobehub/ui/base-ui';-import { Flex } from 'antd';-import { type FC } from 'react';-import { useState } from 'react';+import { CopyButton, Flexbox } from '@lobehub/ui';+import { ActionIcon } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import { Eye, EyeOff } from 'lucide-react';+import { type FC, useState } from 'react';import { useTranslation } from 'react-i18next';+const styles = createStaticStyles(({ css, cssVar }) => ({+ key: css`+ overflow: hidden;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+}));+interface ApiKeyDisplayProps {apiKey?: string;}+/** Bullet run standing in for the hidden middle of the key. */+const MASK = '••••••••';+const ApiKeyDisplay: FC<ApiKeyDisplayProps> = ({ apiKey }) => {const { t } = useTranslation('auth');const [isVisible, setIsVisible] = useState(false);- const toggleVisibility = () => {- setIsVisible(!isVisible);- };-- const handleCopy = async () => {- if (!apiKey) return;-- try {- await navigator.clipboard.writeText(apiKey);- toast.success(t('apikey.display.copySuccess'));- } catch {- toast.error(t('apikey.display.copyError'));- }- };-- // Mask with the key's real prefix (e.g. `sk-lh-`) so the hidden state- // doesn't misrepresent the key format.- const maskPrefixLength = apiKey ? apiKey.lastIndexOf('-') + 1 : 0;- const displayValue =- apiKey &&- (isVisible- ? apiKey- : `${apiKey.slice(0, maskPrefixLength)}${'*'.repeat(apiKey.length - maskPrefixLength)}`);-if (!apiKey) {return t('apikey.display.autoGenerated');}+ // Mask keeps the key's real prefix (e.g. `sk-lh-`) and its last 4 characters+ // so rows stay tellable apart while hidden; fall back to a full mask for+ // keys too short to safely reveal a tail.+ const prefixLength = apiKey.lastIndexOf('-') + 1;+ const prefix = apiKey.slice(0, prefixLength);+ const canShowTail = apiKey.length - prefixLength > 8;+ const displayValue = isVisible+ ? apiKey+ : canShowTail+ ? `${prefix}${MASK}${apiKey.slice(-4)}`+ : `${prefix}${MASK}`;+return (- <Flex align="center" gap={8}>- <span style={{ fontSize: '14px' }}>{displayValue}</span>- <Flex>- <Button- icon={isVisible ? <EyeInvisibleOutlined /> : <EyeOutlined />}- size="small"- title={isVisible ? t('apikey.display.hide') : t('apikey.display.show')}- type="text"- onClick={toggleVisibility}- />- <Button- icon={<CopyOutlined />}- size="small"- title={t('apikey.display.copy')}- type="text"- onClick={handleCopy}- />- </Flex>- </Flex>+ <Flexbox horizontal align={'center'} gap={4}>+ <span className={styles.key}>{displayValue}</span>+ <ActionIcon+ icon={isVisible ? EyeOff : Eye}+ size={'small'}+ title={isVisible ? t('apikey.display.hide') : t('apikey.display.show')}+ onClick={() => setIsVisible(!isVisible)}+ />+ <CopyButton content={apiKey} size={'small'} title={t('apikey.display.copy')} />+ </Flexbox>);};diff --git a/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx b/src/features/Settings/apikey/features/ApiKeyModal/Content.tsxindex 86de5f96cf8..c3d928d9490 100644--- a/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx+++ b/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx@@ -1,9 +1,12 @@'use client';-import { Flexbox, Input } from '@lobehub/ui';-import { Button, useModalContext } from '@lobehub/ui/base-ui';+import { CopyButton, Flexbox, Icon, Input } from '@lobehub/ui';+import { Button, Select, Text, useModalContext } from '@lobehub/ui/base-ui';import { Form } from 'antd';+import { createStaticStyles } from 'antd-style';import { type Dayjs } from 'dayjs';+import dayjs from 'dayjs';+import { CheckCircle2 } from 'lucide-react';import { type FC, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -13,12 +16,45 @@ import { type CreateApiKeyParams } from '@/types/apiKey';import ApiKeyDatePicker from '../ApiKeyDatePicker';import ScopeSelector from './ScopeSelector';-type FormValues = Omit<CreateApiKeyParams, 'expiresAt' | 'scopes'> & {- expiresAt: Dayjs | null;-};+const styles = createStaticStyles(({ css, cssVar }) => ({+ keyBlock: css`+ padding-block: 10px;+ padding-inline: 12px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};++ background: ${cssVar.colorFillQuaternary};+ `,+ keyText: css`+ flex: 1;+ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ word-break: break-all;+ `,+ successIcon: css`+ color: ${cssVar.colorSuccess};+ `,+}));++type FormValues = Omit<CreateApiKeyParams, 'expiresAt' | 'scopes'>;++/** 'never' and 'custom' plus day-count presets, Vercel-token style. */+const EXPIRY_PRESETS = ['never', '7', '30', '60', '90', '180', '365', 'custom'] as const;+type ExpiryPreset = (typeof EXPIRY_PRESETS)[number];++const PRESET_LABEL_KEYS = {+ '7': 'apikey.form.fields.expiresAt.presets.7d',+ '30': 'apikey.form.fields.expiresAt.presets.30d',+ '60': 'apikey.form.fields.expiresAt.presets.60d',+ '90': 'apikey.form.fields.expiresAt.presets.90d',+ '180': 'apikey.form.fields.expiresAt.presets.180d',+ '365': 'apikey.form.fields.expiresAt.presets.1y',+ 'custom': 'apikey.form.fields.expiresAt.presets.custom',+ 'never': 'apikey.display.neverExpires',+} as const satisfies Record<ExpiryPreset, string>;export interface ApiKeyModalContentProps {- onSubmit: (values: CreateApiKeyParams) => Promise<void>;+ onSubmit: (values: CreateApiKeyParams) => Promise<{ key?: string | null } | void>;}const ApiKeyModalContent: FC<ApiKeyModalContentProps> = ({ onSubmit }) => {@@ -28,25 +64,64 @@ const ApiKeyModalContent: FC<ApiKeyModalContentProps> = ({ onSubmit }) => {const [loading, setLoading] = useState(false);const [fullAccess, setFullAccess] = useState(true);const [selectedScopes, setSelectedScopes] = useState<ApiKeyScope[]>([]);+ const [expiryPreset, setExpiryPreset] = useState<ExpiryPreset>('never');+ const [customDate, setCustomDate] = useState<Dayjs | null>(null);+ // Filled once creation succeeds; flips the modal to the copy-now step.+ const [createdKey, setCreatedKey] = useState<string>();const scopeMissing = !fullAccess && selectedScopes.length === 0;+ // "Custom date" without a date would silently fall back to never-expires.+ const customDateMissing = expiryPreset === 'custom' && !customDate;++ // The preset resolves to a date at submit time, so a form left open does not+ // silently shorten the key's lifetime.+ const resolveExpiresAt = (): Date | null => {+ if (expiryPreset === 'never') return null;+ if (expiryPreset === 'custom') return customDate ? customDate.toDate() : null;+ return dayjs().add(Number(expiryPreset), 'day').hour(23).minute(59).second(59).toDate();+ };const handleFinish = async (values: FormValues) => {- if (scopeMissing) return;+ if (scopeMissing || customDateMissing) return;setLoading(true);try {- await onSubmit({+ const created = await onSubmit({...values,- expiresAt: values.expiresAt ? values.expiresAt.toDate() : null,+ expiresAt: resolveExpiresAt(),scopes: fullAccess ? [API_KEY_FULL_ACCESS_SCOPE] : selectedScopes,} satisfies CreateApiKeyParams);- close();+ if (created?.key) {+ setCreatedKey(created.key);+ } else {+ close();+ }} finally {setLoading(false);}};+ if (createdKey) {+ return (+ <Flexbox gap={16}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Icon className={styles.successIcon} icon={CheckCircle2} size={18} />+ <Text style={{ fontWeight: 500 }}>{t('apikey.created.title')}</Text>+ </Flexbox>+ <Flexbox horizontal align={'center'} className={styles.keyBlock} gap={8}>+ <span className={styles.keyText}>{createdKey}</span>+ <CopyButton content={createdKey} size={'small'} title={t('apikey.display.copy')} />+ </Flexbox>+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {t('apikey.created.hint')}+ </Text>+ <Button block type={'primary'} onClick={() => close()}>+ {t('apikey.created.done')}+ </Button>+ </Flexbox>+ );+ }+const itemStyle = { marginBottom: 0 };return (@@ -61,12 +136,25 @@ const ApiKeyModalContent: FC<ApiKeyModalContentProps> = ({ onSubmit }) => {<Input placeholder={t('apikey.form.fields.name.placeholder')} /></Form.Item>- <Form.Item- label={t('apikey.form.fields.expiresAt.label')}- name={'expiresAt'}- style={itemStyle}- >- <ApiKeyDatePicker style={{ width: '100%' }} />+ <Form.Item label={t('apikey.form.fields.expiresAt.label')} style={itemStyle}>+ <Flexbox gap={8}>+ <Select+ value={expiryPreset}+ options={EXPIRY_PRESETS.map((preset) => ({+ label: t(PRESET_LABEL_KEYS[preset]),+ value: preset,+ }))}+ onChange={(value) => setExpiryPreset(value as ExpiryPreset)}+ />+ {expiryPreset === 'custom' && (+ <ApiKeyDatePicker+ showNeverExpiresFooter={false}+ style={{ width: '100%' }}+ value={customDate}+ onChange={setCustomDate}+ />+ )}+ </Flexbox></Form.Item><Form.Item@@ -85,7 +173,7 @@ const ApiKeyModalContent: FC<ApiKeyModalContentProps> = ({ onSubmit }) => {<Buttonblock- disabled={scopeMissing}+ disabled={scopeMissing || customDateMissing}htmlType={'submit'}loading={loading}type={'primary'}