1005 lines
31 KiB
React
1005 lines
31 KiB
React
/*
|
|
Copyright (C) 2025 QuantumNous
|
|
|
|
This program is free software: you can redistribute it and/or modify
|
|
it under the terms of the GNU Affero General Public License as
|
|
published by the Free Software Foundation, either version 3 of the
|
|
License, or (at your option) any later version.
|
|
|
|
This program is distributed in the hope that it will be useful,
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
GNU Affero General Public License for more details.
|
|
|
|
You should have received a copy of the GNU Affero General Public License
|
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
For commercial licensing, please contact support@quantumnous.com
|
|
*/
|
|
|
|
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
|
|
import {
|
|
EyeOff as ActionEyeOff,
|
|
Eye as ActionEye,
|
|
Copy as ActionCopy,
|
|
BookOpen as ActionBookOpen,
|
|
HelpCircle as ActionHelpCircle,
|
|
Plus as ActionPlus,
|
|
Search as ActionSearch,
|
|
} from '@/components/common/icons/ActionIcons';
|
|
import { writeClipboardText } from '../../helpers/clipboard';
|
|
import { ConsoleCollectionSearch } from '../../components/console/ConsoleCollection';
|
|
import {
|
|
ConsoleFilterField,
|
|
ConsoleFilterGrid,
|
|
} from '../../components/console/ConsolePrimitives';
|
|
import TableEmpty from '../../components/common/table/TableEmpty';
|
|
import React, { useState, useRef, useEffect, useContext } from 'react';
|
|
import Table from '../../components/ui/CenterActionTable';
|
|
import {
|
|
Alert,
|
|
Button,
|
|
Card,
|
|
Drawer,
|
|
Empty,
|
|
Input,
|
|
Spin,
|
|
Switch,
|
|
Tag,
|
|
Tooltip,
|
|
} from 'antd';
|
|
import { Modal, Pagination } from '@/components/ui';
|
|
import { ShieldCheck } from 'lucide-react';
|
|
import Joyride, { STATUS, ACTIONS, EVENTS } from 'react-joyride';
|
|
import { useTokensData } from '../../hooks/tokens/useTokensData';
|
|
import EditTokenModal from '../../components/table/tokens/modals/EditTokenModal';
|
|
import {
|
|
API,
|
|
showError,
|
|
showInfo,
|
|
showSuccess,
|
|
getModelCategories,
|
|
} from '../../helpers';
|
|
import { useLocation, useNavigate } from 'react-router-dom';
|
|
import PageBackground from '../../components/common/PageBackground';
|
|
import UserCenterPageHeader from '../../components/common/UserCenterPageHeader';
|
|
import TableColumnSettings from '../../components/common/table/ColumnSettings';
|
|
import { CUSTOMER_SERVICE_OPEN_EVENT } from '../../components/customer-service';
|
|
import { StatusContext } from '../../context/Status';
|
|
import { UserContext } from '../../context/User';
|
|
import { isHeaderActionButtonVisible } from '../../helpers/navigationVisibility';
|
|
import {
|
|
flushCreationEvents,
|
|
trackCreationEvent,
|
|
} from '../../helpers/creationEvents';
|
|
import './key-management.css';
|
|
|
|
const KEY_MASK = '••••••••••••••••';
|
|
|
|
// 列宽按设计图 1582px 表格实测比例换算(table-layout: fixed 下按比例铺满)。
|
|
const COLUMN_WIDTHS = {
|
|
name: 150,
|
|
key: 300,
|
|
group: 150,
|
|
status: 100,
|
|
expired_time: 180,
|
|
quota: 100,
|
|
models: 100,
|
|
actions: 130,
|
|
};
|
|
|
|
// 列设置:只控制本页表格列的显示,不持久化、不改请求。
|
|
const COLUMN_OPTIONS = [
|
|
{ value: 'name', label: '名称' },
|
|
{ value: 'key', label: '密钥' },
|
|
{ value: 'group', label: '分组' },
|
|
{ value: 'status', label: '状态' },
|
|
{ value: 'expired_time', label: '过期时间' },
|
|
{ value: 'quota', label: '额度' },
|
|
{ value: 'models', label: '模型' },
|
|
{ value: 'actions', label: '操作' },
|
|
];
|
|
|
|
// 启用/禁用之外的状态在开关旁补充语义标签。
|
|
const extraStatusTag = {
|
|
3: { label: '已过期', color: 'error' },
|
|
4: { label: '已耗尽', color: 'warning' },
|
|
};
|
|
|
|
// Actions and values remain owned by useTokensData and the page.
|
|
const KeyTable = ({
|
|
tokens,
|
|
loading,
|
|
visibleColumns,
|
|
emptyText,
|
|
onCopy,
|
|
onEdit,
|
|
onToggle,
|
|
onDelete,
|
|
showKeys,
|
|
onToggleShowKey,
|
|
onViewModels,
|
|
t,
|
|
}) => {
|
|
const columns = [
|
|
{
|
|
title: t('名称'),
|
|
key: 'name',
|
|
dataIndex: 'name',
|
|
render: (name) => (
|
|
<span className='km-name'>{name || t('未命名密钥')}</span>
|
|
),
|
|
},
|
|
{
|
|
title: t('密钥'),
|
|
key: 'key',
|
|
render: (_, token) => {
|
|
const shown = !!showKeys[token.id];
|
|
return (
|
|
<div className='km-key-cell'>
|
|
<code className='km-key-code'>
|
|
sk-{shown ? token.key : KEY_MASK}
|
|
</code>
|
|
<Tooltip title={shown ? t('隐藏密钥') : t('显示密钥')}>
|
|
<Button
|
|
type='text'
|
|
size='small'
|
|
aria-label={shown ? t('隐藏密钥') : t('显示密钥')}
|
|
aria-pressed={shown}
|
|
icon={
|
|
shown ? <ActionEyeOff size={16} /> : <ActionEye size={16} />
|
|
}
|
|
onClick={() => onToggleShowKey(token.id)}
|
|
/>
|
|
</Tooltip>
|
|
<Tooltip title={t('复制密钥')}>
|
|
<Button
|
|
type='text'
|
|
size='small'
|
|
className='km-copy-btn tour-copy-btn'
|
|
aria-label={t('复制密钥')}
|
|
icon={<ActionCopy size={16} />}
|
|
onClick={() => onCopy('sk-' + token.key)}
|
|
/>
|
|
</Tooltip>
|
|
</div>
|
|
);
|
|
},
|
|
},
|
|
{
|
|
title: t('分组'),
|
|
key: 'group',
|
|
render: (_, token) => {
|
|
const group = token.group || token.groups;
|
|
return (
|
|
<Tooltip
|
|
title={
|
|
group === 'auto'
|
|
? t('自动选择最优分组,当一个组不可用时自动降级')
|
|
: group
|
|
}
|
|
>
|
|
<Tag color='blue' variant='filled'>
|
|
{group === 'auto' ? t('智能熔断') : group || t('默认')}
|
|
</Tag>
|
|
</Tooltip>
|
|
);
|
|
},
|
|
},
|
|
{
|
|
title: t('状态'),
|
|
key: 'status',
|
|
render: (_, token) => {
|
|
const extra = extraStatusTag[token.status];
|
|
return (
|
|
<div className='km-status-cell'>
|
|
<Switch
|
|
size='small'
|
|
checked={token.status === 1}
|
|
checkedChildren={t('启用')}
|
|
unCheckedChildren={t('禁用')}
|
|
aria-label={token.status === 1 ? t('禁用') : t('启用')}
|
|
onChange={() => onToggle(token)}
|
|
/>
|
|
{extra ? (
|
|
<Tag color={extra.color} variant='filled'>
|
|
{t(extra.label)}
|
|
</Tag>
|
|
) : null}
|
|
</div>
|
|
);
|
|
},
|
|
},
|
|
{
|
|
title: t('过期时间'),
|
|
key: 'expired_time',
|
|
dataIndex: 'expired_time',
|
|
render: (time) =>
|
|
time === -1
|
|
? t('永不过期')
|
|
: time
|
|
? new Date(time * 1000).toLocaleString()
|
|
: '—',
|
|
},
|
|
{
|
|
title: t('额度'),
|
|
key: 'quota',
|
|
render: (_, token) =>
|
|
token.unlimited_quota === true || token.remain_quota < 0 ? (
|
|
<Tag color='success' variant='filled'>
|
|
{t('无限制')}
|
|
</Tag>
|
|
) : (
|
|
'¥' + ((token.remain_quota || 0) / 500000).toFixed(2)
|
|
),
|
|
},
|
|
{
|
|
title: t('模型'),
|
|
key: 'models',
|
|
render: (_, token) => (
|
|
<Button
|
|
type='link'
|
|
size='small'
|
|
className='km-link-btn tour-models-btn'
|
|
onClick={() => onViewModels(token)}
|
|
>
|
|
{token.model_limits_enabled && token.model_limits
|
|
? t('{{count}} 个模型', {
|
|
count: token.model_limits.split(',').filter(Boolean).length,
|
|
})
|
|
: token.group && token.group !== 'auto'
|
|
? t('模型列表')
|
|
: t('全部模型')}
|
|
</Button>
|
|
),
|
|
},
|
|
{
|
|
title: t('操作'),
|
|
key: 'actions',
|
|
render: (_, token) => (
|
|
<div className='km-actions'>
|
|
<Button
|
|
type='link'
|
|
size='small'
|
|
className='km-link-btn tour-edit-btn'
|
|
onClick={() => onEdit(token)}
|
|
>
|
|
{t('编辑')}
|
|
</Button>
|
|
<Button
|
|
type='link'
|
|
size='small'
|
|
danger
|
|
className='km-link-btn'
|
|
onClick={() => onDelete(token)}
|
|
>
|
|
{t('删除')}
|
|
</Button>
|
|
</div>
|
|
),
|
|
},
|
|
]
|
|
.filter((column) => visibleColumns.includes(column.key))
|
|
.map((column) => ({ ...column, width: COLUMN_WIDTHS[column.key] }));
|
|
|
|
return (
|
|
<Table
|
|
rowKey='id'
|
|
size='middle'
|
|
className='km-table'
|
|
tableLayout='fixed'
|
|
onRow={(_, index) => ({ className: index === 0 ? 'tour-key-row' : '' })}
|
|
columns={columns}
|
|
dataSource={tokens}
|
|
loading={loading}
|
|
pagination={false}
|
|
locale={{ emptyText }}
|
|
scroll={{
|
|
x: columns.reduce((sum, column) => sum + column.width, 0),
|
|
}}
|
|
/>
|
|
);
|
|
};
|
|
|
|
// 脱敏保护提示:仅当脱敏对用户内容实际生效时展示,让用户安心使用。
|
|
const DesensitizeNotice = ({ t }) => {
|
|
const [status, setStatus] = useState(null);
|
|
useEffect(() => {
|
|
let mounted = true;
|
|
API.get('/api/user/desensitize-status')
|
|
.then((res) => {
|
|
if (mounted && res?.data?.success) setStatus(res.data.data);
|
|
})
|
|
.catch(() => {});
|
|
return () => {
|
|
mounted = false;
|
|
};
|
|
}, []);
|
|
|
|
if (!status?.enabled) return null;
|
|
const cats = (status.categories || []).join('、');
|
|
|
|
return (
|
|
<Alert
|
|
className='km-notice'
|
|
type='success'
|
|
showIcon
|
|
icon={<ShieldCheck size={18} />}
|
|
title={
|
|
<>
|
|
{t('您的敏感数据已自动脱敏保护')}{' '}
|
|
<Tag color='success' variant='filled'>
|
|
{t('已开启')}
|
|
</Tag>
|
|
</>
|
|
}
|
|
description={
|
|
<>
|
|
{t(
|
|
'调用大模型时,{{cats}} 等敏感信息会在发送给模型前自动脱敏,绝不出境或外泄。',
|
|
{ cats },
|
|
)}
|
|
{status.reversible &&
|
|
t('模型回复中会自动还原,您看到的仍是原始内容,使用体验不受影响。')}
|
|
</>
|
|
}
|
|
/>
|
|
);
|
|
};
|
|
|
|
// 可用模型列表抽屉(设计图:密钥管理-列表 点击模型列表 打开右侧抽屉)
|
|
const ModelsDrawer = ({ visible, onClose, token, t }) => {
|
|
const [models, setModels] = useState([]);
|
|
const [loading, setLoading] = useState(false);
|
|
const categories = getModelCategories(t);
|
|
|
|
useEffect(() => {
|
|
if (!visible || !token) return;
|
|
|
|
const loadModels = async () => {
|
|
setLoading(true);
|
|
try {
|
|
// 如果密钥有模型限制,使用限制的模型列表
|
|
if (token.model_limits_enabled && token.model_limits) {
|
|
const limitedModels = token.model_limits.split(',').filter(Boolean);
|
|
setModels(limitedModels);
|
|
} else {
|
|
// 否则获取该密钥所属分组下的可用模型
|
|
const groupValue = token.group || token.groups;
|
|
// 如果分组为 auto 或空,获取用户所有分组的模型
|
|
const apiUrl =
|
|
groupValue && groupValue !== 'auto'
|
|
? `/api/user/models?group=${encodeURIComponent(groupValue)}`
|
|
: '/api/user/models';
|
|
|
|
const res = await API.get(apiUrl);
|
|
if (res.data.success) {
|
|
setModels(res.data.data || []);
|
|
} else {
|
|
showError(t(res.data.message));
|
|
}
|
|
}
|
|
} catch (error) {
|
|
showError(error.message);
|
|
}
|
|
setLoading(false);
|
|
};
|
|
|
|
loadModels();
|
|
}, [visible, token, t]);
|
|
|
|
// 按分类组织模型
|
|
const groupedModels = {};
|
|
models.forEach((model) => {
|
|
let category = 'other';
|
|
for (const [key, cat] of Object.entries(categories)) {
|
|
if (key !== 'all' && cat.filter && cat.filter({ model_name: model })) {
|
|
category = key;
|
|
break;
|
|
}
|
|
}
|
|
if (!groupedModels[category]) {
|
|
groupedModels[category] = [];
|
|
}
|
|
groupedModels[category].push(model);
|
|
});
|
|
|
|
const copyModel = async (model) => {
|
|
try {
|
|
await writeClipboardText(model);
|
|
showSuccess(t('已复制: {{model}}', { model: model }));
|
|
} catch {
|
|
showError(t('复制失败,请手动复制'));
|
|
}
|
|
};
|
|
|
|
return (
|
|
<Drawer
|
|
title={t('可用模型列表')}
|
|
open={visible}
|
|
onClose={onClose}
|
|
placement='right'
|
|
size={440}
|
|
rootClassName='km-models-drawer'
|
|
mask={{ closable: true }}
|
|
>
|
|
<dl className='km-models-info'>
|
|
<dt>{t('密钥名称')}</dt>
|
|
<dd>{token?.name || t('未命名密钥')}</dd>
|
|
{token?.group ? (
|
|
<>
|
|
<dt>{t('密钥分组')}</dt>
|
|
<dd>{token.group === 'auto' ? t('智能熔断') : token.group}</dd>
|
|
</>
|
|
) : null}
|
|
</dl>
|
|
|
|
{loading ? (
|
|
<div className='km-models-state'>
|
|
<Spin />
|
|
</div>
|
|
) : models.length === 0 ? (
|
|
<div className='km-models-state'>
|
|
<Empty
|
|
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
|
description={t('暂无可用模型')}
|
|
/>
|
|
</div>
|
|
) : (
|
|
Object.entries(groupedModels).map(([category, categoryModels]) => {
|
|
const cat = categories[category] || { label: t('其他') };
|
|
return (
|
|
<section key={category} className='km-models-group'>
|
|
<div className='km-models-group-head'>
|
|
{cat.label}
|
|
<span>{categoryModels.length}</span>
|
|
</div>
|
|
<div className='km-models-group-body'>
|
|
{categoryModels.map((model) => (
|
|
<Tooltip key={model} title={t('点击复制模型名称')}>
|
|
<Tag
|
|
variant='filled'
|
|
className='km-model-chip'
|
|
role='button'
|
|
tabIndex={0}
|
|
onClick={() => copyModel(model)}
|
|
onKeyDown={(event) => {
|
|
if (event.key === 'Enter' || event.key === ' ') {
|
|
event.preventDefault();
|
|
copyModel(model);
|
|
}
|
|
}}
|
|
>
|
|
{model}
|
|
</Tag>
|
|
</Tooltip>
|
|
))}
|
|
</div>
|
|
</section>
|
|
);
|
|
})
|
|
)}
|
|
</Drawer>
|
|
);
|
|
};
|
|
|
|
const KeyManagement = ({ embedded = false }) => {
|
|
const navigate = useNavigate();
|
|
const location = useLocation();
|
|
// 从新创作台"获取 API 代码 → 创建密钥"进入(WP C-1):创建成功记 key_created_from_studio(每次进入一次)
|
|
const fromStudioRef = useRef(
|
|
new URLSearchParams(location.search).get('from') === 'creation_studio',
|
|
);
|
|
const handleTokenCreated = (count) => {
|
|
if (!fromStudioRef.current) return;
|
|
fromStudioRef.current = false;
|
|
trackCreationEvent('key_created_from_studio', { count });
|
|
flushCreationEvents();
|
|
};
|
|
const [statusState] = useContext(StatusContext);
|
|
const [userState] = useContext(UserContext);
|
|
const openFluentNotificationRef = useRef(null);
|
|
const tokensData = useTokensData((key) =>
|
|
openFluentNotificationRef.current?.(key),
|
|
);
|
|
const [searchValue, setSearchValue] = useState('');
|
|
const [showKeys, setShowKeys] = useState({});
|
|
const [modelsSheetVisible, setModelsSheetVisible] = useState(false);
|
|
const [selectedToken, setSelectedToken] = useState(null);
|
|
const [runTour, setRunTour] = useState(false);
|
|
const [visibleColumns, setVisibleColumns] = useState(
|
|
COLUMN_OPTIONS.map((option) => option.value),
|
|
);
|
|
|
|
const {
|
|
tokens,
|
|
loading,
|
|
activePage,
|
|
tokenCount,
|
|
pageSize,
|
|
showEdit,
|
|
editingToken,
|
|
setEditingToken,
|
|
setShowEdit,
|
|
closeEdit,
|
|
refresh,
|
|
copyText,
|
|
manageToken,
|
|
handlePageChange,
|
|
handlePageSizeChange,
|
|
t: originalT,
|
|
} = tokensData;
|
|
|
|
// 设计图统一称“密钥”:沿用原 密钥 文案键,仅替换显示词。
|
|
const t = (key, options) => {
|
|
const result = originalT(key, options);
|
|
return typeof result === 'string'
|
|
? result.replace(/密钥|密钥/g, '密钥')
|
|
: result;
|
|
};
|
|
|
|
let headerActionButtonsConfig = statusState?.status?.HeaderActionButtons;
|
|
if (!headerActionButtonsConfig) {
|
|
try {
|
|
headerActionButtonsConfig = JSON.parse(
|
|
localStorage.getItem('status') || '{}',
|
|
).HeaderActionButtons;
|
|
} catch (_error) {
|
|
headerActionButtonsConfig = null;
|
|
}
|
|
}
|
|
const tutorialButtonVisible = isHeaderActionButtonVisible(
|
|
headerActionButtonsConfig,
|
|
'tutorial',
|
|
userState?.user?.group,
|
|
);
|
|
|
|
// 判断是否有密钥
|
|
const hasKeys = tokens.length > 0;
|
|
|
|
// 新手引导步骤 - 根据是否有密钥动态调整
|
|
const tourSteps = hasKeys
|
|
? [
|
|
// 有密钥时:完整引导
|
|
{
|
|
target: '.tour-create-btn',
|
|
content: (
|
|
<div>
|
|
<div className='flex items-center gap-2 mb-2'>
|
|
<span className='text-lg'>✨</span>
|
|
<span className='font-semibold'>{t('创建密钥')}</span>
|
|
</div>
|
|
<div className='text-sm text-gray-600 dark:text-gray-300'>
|
|
{t('点击这里创建新密钥,设置名称和使用额度')}
|
|
</div>
|
|
</div>
|
|
),
|
|
placement: 'bottom',
|
|
disableBeacon: true,
|
|
spotlightClicks: true,
|
|
},
|
|
{
|
|
target: '.tour-key-row',
|
|
content: (
|
|
<div>
|
|
<div className='flex items-center gap-2 mb-2'>
|
|
<span className='text-lg'>
|
|
{I18N_TECHNICAL_TEXT.CLIPBOARD_ICON}
|
|
</span>
|
|
<span className='font-semibold'>{t('密钥卡片')}</span>
|
|
</div>
|
|
<div className='text-sm text-gray-600 dark:text-gray-300'>
|
|
{t('每张卡片展示密钥的状态、名称和剩余额度')}
|
|
</div>
|
|
<div className='mt-2 text-xs text-gray-400'>
|
|
{I18N_TECHNICAL_TEXT.TIP_ICON} {t('绿色状态点表示密钥已启用')}
|
|
</div>
|
|
</div>
|
|
),
|
|
placement: 'bottom',
|
|
},
|
|
{
|
|
target: '.tour-copy-btn',
|
|
content: (
|
|
<div>
|
|
<div className='flex items-center gap-2 mb-2'>
|
|
<span className='text-lg'>
|
|
{I18N_TECHNICAL_TEXT.CLIPBOARD_ICON}
|
|
</span>
|
|
<span className='font-semibold'>{t('复制密钥')}</span>
|
|
</div>
|
|
<div className='text-sm text-gray-600 dark:text-gray-300'>
|
|
{t('点击复制完整密钥(sk-xxx 格式)')}
|
|
</div>
|
|
<div className='mt-2 p-2 bg-gray-100 dark:bg-neutral-800 rounded text-xs font-mono'>
|
|
{I18N_TECHNICAL_TEXT.SK_XXXXXXXXXXXXXXXX}
|
|
</div>
|
|
</div>
|
|
),
|
|
placement: 'top',
|
|
spotlightClicks: true,
|
|
},
|
|
{
|
|
target: '.tour-edit-btn',
|
|
content: (
|
|
<div>
|
|
<div className='flex items-center gap-2 mb-2'>
|
|
<span className='text-lg'>
|
|
{I18N_TECHNICAL_TEXT.SETTINGS_ICON}
|
|
</span>
|
|
<span className='font-semibold'>{t('管理密钥')}</span>
|
|
</div>
|
|
<div className='text-sm text-gray-600 dark:text-gray-300'>
|
|
{t('编辑密钥名称、额度、过期时间等设置')}
|
|
</div>
|
|
<div className='mt-3 text-xs text-gray-400'>
|
|
{I18N_TECHNICAL_TEXT.TIP_ICON}{' '}
|
|
{t('点击右上角问号可随时重新查看引导')}
|
|
</div>
|
|
</div>
|
|
),
|
|
placement: 'top',
|
|
spotlightClicks: true,
|
|
},
|
|
]
|
|
: [
|
|
// 没有密钥时:简化引导,只显示创建按钮
|
|
{
|
|
target: '.tour-create-btn',
|
|
content: (
|
|
<div>
|
|
<div className='flex items-center gap-2 mb-2'>
|
|
<span className='text-lg'>
|
|
{I18N_TECHNICAL_TEXT.ROCKET_ICON}
|
|
</span>
|
|
<span className='font-semibold'>
|
|
{t('开始创建您的第一个密钥')}
|
|
</span>
|
|
</div>
|
|
<div className='text-sm text-gray-600 dark:text-gray-300'>
|
|
{t('点击这里创建密钥,创建后可用于调用 API 服务')}
|
|
</div>
|
|
<div className='mt-3 p-2 bg-brand/5 dark:bg-brand-deep/20 rounded-lg text-xs text-brand-deep dark:text-brand-from'>
|
|
{I18N_TECHNICAL_TEXT.TIP_ICON}{' '}
|
|
{t('创建密钥后,可再次点击右上角问号查看完整操作指引')}
|
|
</div>
|
|
</div>
|
|
),
|
|
placement: 'bottom',
|
|
disableBeacon: true,
|
|
spotlightClicks: true,
|
|
},
|
|
];
|
|
|
|
// 引导完成回调
|
|
const handleTourCallback = (data) => {
|
|
const { status, action, type } = data;
|
|
|
|
// 处理所有关闭场景:完成、跳过、点击关闭按钮、点击遮罩层关闭
|
|
const finishedStatuses = [STATUS.FINISHED, STATUS.SKIPPED];
|
|
const closeActions = [ACTIONS.CLOSE, ACTIONS.SKIP];
|
|
|
|
if (finishedStatuses.includes(status) || closeActions.includes(action)) {
|
|
setRunTour(false);
|
|
}
|
|
|
|
// 处理目标元素未找到的情况
|
|
if (type === EVENTS.TARGET_NOT_FOUND) {
|
|
setRunTour(false);
|
|
}
|
|
};
|
|
|
|
// 手动启动引导
|
|
const startTour = () => {
|
|
setRunTour(true);
|
|
};
|
|
|
|
const handleToggleShowKey = (id) => {
|
|
setShowKeys((prev) => ({ ...prev, [id]: !prev[id] }));
|
|
};
|
|
|
|
const handleEdit = (token) => {
|
|
setEditingToken(token);
|
|
setShowEdit(true);
|
|
};
|
|
|
|
const handleToggle = (token) => {
|
|
const action = token.status === 1 ? 'disable' : 'enable';
|
|
Modal.confirm({
|
|
title:
|
|
action === 'disable'
|
|
? t('确定要禁用此密钥吗?')
|
|
: t('确定要启用此密钥吗?'),
|
|
onOk: () => manageToken(token.id, action, token),
|
|
});
|
|
};
|
|
|
|
const handleDelete = (token) => {
|
|
Modal.confirm({
|
|
title: t('确定要删除此密钥吗?'),
|
|
content: t('删除后将无法恢复'),
|
|
okType: 'danger',
|
|
onOk: async () => {
|
|
await manageToken(token.id, 'delete', token);
|
|
refresh();
|
|
},
|
|
});
|
|
};
|
|
|
|
const handleCreate = () => {
|
|
setEditingToken({ id: undefined });
|
|
setShowEdit(true);
|
|
};
|
|
|
|
const handleViewModels = (token) => {
|
|
setSelectedToken(token);
|
|
setModelsSheetVisible(true);
|
|
};
|
|
|
|
// 设计图标注:“联系客服”等同于打开右下角客服面板;客服未启用时给出提示。
|
|
const openCustomerService = () => {
|
|
const handled = !window.dispatchEvent(
|
|
new CustomEvent(CUSTOMER_SERVICE_OPEN_EVENT, { cancelable: true }),
|
|
);
|
|
if (!handled) showInfo(t('暂无可用客服'));
|
|
};
|
|
|
|
// Filter tokens(本页原本即输即筛;“搜索”/回车只是立即应用当前输入,不发请求)
|
|
const filteredTokens = tokens.filter(
|
|
(token) =>
|
|
!searchValue ||
|
|
token.name?.toLowerCase().includes(searchValue.toLowerCase()) ||
|
|
token.key?.toLowerCase().includes(searchValue.toLowerCase()) ||
|
|
token.group?.toLowerCase().includes(searchValue.toLowerCase()),
|
|
);
|
|
|
|
return (
|
|
<>
|
|
{/* 新手引导 */}
|
|
<Joyride
|
|
steps={tourSteps}
|
|
run={runTour}
|
|
continuous
|
|
showSkipButton
|
|
showProgress
|
|
showCloseButton
|
|
hideBackButton={false}
|
|
disableCloseOnEsc={false}
|
|
disableScrollParentFix
|
|
disableOverlayClose={false}
|
|
scrollToFirstStep
|
|
scrollOffset={100}
|
|
callback={handleTourCallback}
|
|
styles={{
|
|
options: {
|
|
primaryColor: 'var(--brand-primary-hover)',
|
|
zIndex: 10000,
|
|
overlayColor: 'rgba(0, 0, 0, 0.6)',
|
|
arrowColor: '#fff',
|
|
backgroundColor: '#fff',
|
|
textColor: '#333',
|
|
},
|
|
tooltip: {
|
|
borderRadius: 16,
|
|
padding: 20,
|
|
boxShadow: '0 20px 40px rgba(0, 0, 0, 0.15)',
|
|
animation: 'none',
|
|
},
|
|
tooltipContainer: {
|
|
textAlign: 'left',
|
|
},
|
|
tooltipContent: {
|
|
padding: 0,
|
|
},
|
|
buttonNext: {
|
|
borderRadius: 10,
|
|
padding: '10px 20px',
|
|
fontSize: 14,
|
|
fontWeight: 500,
|
|
backgroundColor: 'var(--brand-primary-hover)',
|
|
transition: 'all 0.2s ease',
|
|
},
|
|
buttonBack: {
|
|
borderRadius: 10,
|
|
padding: '10px 16px',
|
|
fontSize: 14,
|
|
marginRight: 8,
|
|
transition: 'all 0.2s ease',
|
|
},
|
|
buttonSkip: {
|
|
borderRadius: 10,
|
|
padding: '10px 16px',
|
|
fontSize: 13,
|
|
color: '#999',
|
|
transition: 'all 0.2s ease',
|
|
},
|
|
buttonClose: {
|
|
top: 12,
|
|
right: 12,
|
|
width: 28,
|
|
height: 28,
|
|
opacity: 0.6,
|
|
transition: 'opacity 0.2s ease',
|
|
},
|
|
spotlight: {
|
|
borderRadius: 12,
|
|
transition: 'opacity 0.3s ease',
|
|
},
|
|
overlay: {
|
|
transition: 'opacity 0.3s ease',
|
|
},
|
|
tooltipFooter: {
|
|
marginTop: 16,
|
|
},
|
|
}}
|
|
locale={{
|
|
back: t('上一步'),
|
|
close: t('关闭'),
|
|
last: `${t('开始使用')} 🚀`,
|
|
next: `${t('下一步')} →`,
|
|
skip: t('跳过'),
|
|
}}
|
|
floaterProps={{
|
|
disableAnimation: false,
|
|
hideArrow: false,
|
|
offset: 10,
|
|
styles: {
|
|
floater: {
|
|
filter: 'none',
|
|
transition: 'opacity 0.3s ease-out, transform 0.3s ease-out',
|
|
},
|
|
arrow: {
|
|
length: 8,
|
|
spread: 12,
|
|
},
|
|
},
|
|
options: {
|
|
preventOverflow: {
|
|
boundariesElement: 'viewport',
|
|
},
|
|
},
|
|
}}
|
|
spotlightPadding={4}
|
|
/>
|
|
<div
|
|
className={`ui-key-page km-page relative ${embedded ? 'ui-key-page-embedded min-h-full' : 'km-page-standalone min-h-screen'}`}
|
|
>
|
|
{/* 独立路由保留原背景层;用户中心嵌入时由宿主提供背景 */}
|
|
{!embedded && <PageBackground grid animate />}
|
|
|
|
<div className='km-content uc-page relative'>
|
|
<UserCenterPageHeader
|
|
title={t('密钥管理')}
|
|
subtitle={t('管理模型调用的访问密钥')}
|
|
extra={
|
|
<>
|
|
{tutorialButtonVisible ? (
|
|
<Tooltip title={t('新手教程')}>
|
|
<Button
|
|
aria-label={t('新手教程')}
|
|
icon={<ActionBookOpen size={16} />}
|
|
onClick={() => navigate('/tutorial?from=key-management')}
|
|
/>
|
|
</Tooltip>
|
|
) : null}
|
|
<Tooltip title={t('查看操作指引')}>
|
|
<Button
|
|
aria-label={t('查看操作指引')}
|
|
icon={<ActionHelpCircle size={16} />}
|
|
onClick={startTour}
|
|
/>
|
|
</Tooltip>
|
|
</>
|
|
}
|
|
/>
|
|
|
|
{/* 脱敏保护提示(仅脱敏生效时展示) */}
|
|
<DesensitizeNotice t={t} />
|
|
|
|
<div className='km-panels'>
|
|
<ConsoleCollectionSearch className='km-card km-search-card tour-search-input'>
|
|
<ConsoleFilterGrid
|
|
onReset={() => setSearchValue('')}
|
|
onSearch={() => setSearchValue(searchValue.trim())}
|
|
>
|
|
<ConsoleFilterField label={t('密钥查询')} id='km-search-input'>
|
|
<Input
|
|
id='km-search-input'
|
|
prefix={<ActionSearch size={14} />}
|
|
placeholder={t('搜索密钥名称、Key 或分组')}
|
|
value={searchValue}
|
|
onChange={(event) => setSearchValue(event.target.value)}
|
|
allowClear
|
|
/>
|
|
</ConsoleFilterField>
|
|
</ConsoleFilterGrid>
|
|
</ConsoleCollectionSearch>
|
|
|
|
<Card className='km-card km-list-card'>
|
|
<div className='km-list-head console-list-tools'>
|
|
<h2>{t('密钥列表')}</h2>
|
|
<div className='km-list-actions console-list-tool-actions'>
|
|
<Button
|
|
type='link'
|
|
className='km-contact-link'
|
|
onClick={openCustomerService}
|
|
>
|
|
{t('创建密钥后不知道怎么用?联系客服')}
|
|
</Button>
|
|
<TableColumnSettings
|
|
columns={COLUMN_OPTIONS.map((option) => ({
|
|
key: option.value,
|
|
title: t(option.label),
|
|
}))}
|
|
value={visibleColumns}
|
|
defaultValue={COLUMN_OPTIONS.map((option) => option.value)}
|
|
onChange={setVisibleColumns}
|
|
/>
|
|
<Button
|
|
type='primary'
|
|
icon={<ActionPlus size={16} />}
|
|
className='tour-create-btn'
|
|
onClick={handleCreate}
|
|
>
|
|
{t('创建密钥')}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
<KeyTable
|
|
tokens={filteredTokens}
|
|
loading={loading}
|
|
visibleColumns={visibleColumns}
|
|
emptyText={<TableEmpty />}
|
|
onCopy={copyText}
|
|
onEdit={handleEdit}
|
|
onToggle={handleToggle}
|
|
onDelete={handleDelete}
|
|
showKeys={showKeys}
|
|
onToggleShowKey={handleToggleShowKey}
|
|
onViewModels={handleViewModels}
|
|
t={t}
|
|
/>
|
|
|
|
{tokenCount > 0 ? (
|
|
<Pagination
|
|
className='km-pagination'
|
|
size='small'
|
|
total={tokenCount}
|
|
currentPage={activePage}
|
|
pageSize={pageSize}
|
|
showSizeChanger
|
|
showTotal={(total) => t('共 {{total}} 条', { total })}
|
|
onPageChange={handlePageChange}
|
|
onPageSizeChange={handlePageSizeChange}
|
|
/>
|
|
) : null}
|
|
</Card>
|
|
</div>
|
|
</div>
|
|
|
|
{/* 创建/编辑抽屉 */}
|
|
<EditTokenModal
|
|
refresh={refresh}
|
|
editingToken={editingToken}
|
|
visiable={showEdit}
|
|
handleClose={closeEdit}
|
|
labelReplace='密钥'
|
|
presentation='drawer'
|
|
onCreated={handleTokenCreated}
|
|
/>
|
|
|
|
{/* 可用模型列表抽屉 */}
|
|
<ModelsDrawer
|
|
visible={modelsSheetVisible}
|
|
onClose={() => setModelsSheetVisible(false)}
|
|
token={selectedToken}
|
|
t={t}
|
|
/>
|
|
</div>
|
|
</>
|
|
);
|
|
};
|
|
|
|
export default KeyManagement;
|