Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
@@ -0,0 +1,118 @@
/*
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 React, { useState } from 'react';
import { Button } from '@douyinfe/semi-ui';
import { showError } from '../../../helpers';
import CopyTokensModal from './modals/CopyTokensModal';
import DeleteTokensModal from './modals/DeleteTokensModal';
const TokensActions = ({
selectedKeys,
setEditingToken,
setShowEdit,
batchCopyTokens,
batchDeleteTokens,
copyText,
t,
}) => {
// Modal states
const [showCopyModal, setShowCopyModal] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
// Handle copy selected tokens with options
const handleCopySelectedTokens = () => {
if (selectedKeys.length === 0) {
showError(t('请至少选择一个令牌!'));
return;
}
setShowCopyModal(true);
};
// Handle delete selected tokens with confirmation
const handleDeleteSelectedTokens = () => {
if (selectedKeys.length === 0) {
showError(t('请至少选择一个令牌!'));
return;
}
setShowDeleteModal(true);
};
// Handle delete confirmation
const handleConfirmDelete = () => {
batchDeleteTokens();
setShowDeleteModal(false);
};
return (
<>
<div className='flex flex-wrap gap-2 w-full md:w-auto order-2 md:order-1'>
<Button
type='primary'
className='flex-1 md:flex-initial'
onClick={() => {
setEditingToken({
id: undefined,
});
setShowEdit(true);
}}
size='small'
>
{t('添加令牌')}
</Button>
<Button
type='tertiary'
className='flex-1 md:flex-initial'
onClick={handleCopySelectedTokens}
size='small'
>
{t('复制所选令牌')}
</Button>
<Button
type='danger'
className='w-full md:w-auto'
onClick={handleDeleteSelectedTokens}
size='small'
>
{t('删除所选令牌')}
</Button>
</div>
<CopyTokensModal
visible={showCopyModal}
onCancel={() => setShowCopyModal(false)}
selectedKeys={selectedKeys}
copyText={copyText}
t={t}
/>
<DeleteTokensModal
visible={showDeleteModal}
onCancel={() => setShowDeleteModal(false)}
onConfirm={handleConfirmDelete}
selectedKeys={selectedKeys}
t={t}
/>
</>
);
};
export default TokensActions;
@@ -0,0 +1,511 @@
/*
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 React from 'react';
import {
Button,
Dropdown,
Space,
SplitButtonGroup,
Tag,
AvatarGroup,
Avatar,
Tooltip,
Progress,
Popover,
Typography,
Input,
Modal,
} from '@douyinfe/semi-ui';
import {
timestamp2string,
renderGroup,
renderQuota,
getModelCategories,
showError,
} from '../../../helpers';
import {
IconTreeTriangleDown,
IconCopy,
IconEyeOpened,
IconEyeClosed,
} from '@douyinfe/semi-icons';
// progress color helper
const getProgressColor = (pct) => {
if (pct === 100) return 'var(--semi-color-success)';
if (pct <= 10) return 'var(--semi-color-danger)';
if (pct <= 30) return 'var(--semi-color-warning)';
return undefined;
};
// Render functions
function renderTimestamp(timestamp) {
return <>{timestamp2string(timestamp)}</>;
}
// Render status column only (no usage)
const renderStatus = (text, record, t) => {
const enabled = text === 1;
let tagColor = 'black';
let tagText = t('未知状态');
if (enabled) {
tagColor = 'green';
tagText = t('已启用');
} else if (text === 2) {
tagColor = 'red';
tagText = t('已禁用');
} else if (text === 3) {
tagColor = 'yellow';
tagText = t('已过期');
} else if (text === 4) {
tagColor = 'grey';
tagText = t('已耗尽');
}
return (
<Tag color={tagColor} shape='circle' size='small'>
{tagText}
</Tag>
);
};
// Render group column
const renderGroupColumn = (text, t) => {
if (text === 'auto') {
return (
<Tooltip
content={t(
'当前分组为 auto,会自动选择最优分组,当一个组不可用时自动降级到下一个组(熔断机制)',
)}
position='top'
>
<Tag color='white' shape='circle'>
{' '}
{t('智能熔断')}{' '}
</Tag>
</Tooltip>
);
}
return renderGroup(text);
};
// Render token key column with show/hide and copy functionality
const renderTokenKey = (text, record, showKeys, setShowKeys, copyText) => {
const fullKey = 'sk-' + record.key;
const maskedKey =
'sk-' + record.key.slice(0, 4) + '**********' + record.key.slice(-4);
const revealed = !!showKeys[record.id];
return (
<div className='w-[200px]'>
<Input
readOnly
value={revealed ? fullKey : maskedKey}
size='small'
suffix={
<div className='flex items-center'>
<Button
theme='borderless'
size='small'
type='tertiary'
icon={revealed ? <IconEyeClosed /> : <IconEyeOpened />}
aria-label='toggle token visibility'
onClick={(e) => {
e.stopPropagation();
setShowKeys((prev) => ({ ...prev, [record.id]: !revealed }));
}}
/>
<Button
theme='borderless'
size='small'
type='tertiary'
icon={<IconCopy />}
aria-label='copy token key'
onClick={async (e) => {
e.stopPropagation();
await copyText(fullKey);
}}
/>
</div>
}
/>
</div>
);
};
// Render model limits column
const renderModelLimits = (text, record, t) => {
if (record.model_limits_enabled && text) {
const models = text.split(',').filter(Boolean);
const categories = getModelCategories(t);
const vendorAvatars = [];
const matchedModels = new Set();
Object.entries(categories).forEach(([key, category]) => {
if (key === 'all') return;
if (!category.icon || !category.filter) return;
const vendorModels = models.filter((m) =>
category.filter({ model_name: m }),
);
if (vendorModels.length > 0) {
vendorAvatars.push(
<Tooltip
key={key}
content={vendorModels.join(', ')}
position='top'
showArrow
>
<Avatar
size='extra-extra-small'
alt={category.label}
color='transparent'
>
{category.icon}
</Avatar>
</Tooltip>,
);
vendorModels.forEach((m) => matchedModels.add(m));
}
});
const unmatchedModels = models.filter((m) => !matchedModels.has(m));
if (unmatchedModels.length > 0) {
vendorAvatars.push(
<Tooltip
key='unknown'
content={unmatchedModels.join(', ')}
position='top'
showArrow
>
<Avatar size='extra-extra-small' alt='unknown'>
{t('其他')}
</Avatar>
</Tooltip>,
);
}
return <AvatarGroup size='extra-extra-small'>{vendorAvatars}</AvatarGroup>;
} else {
return (
<Tag color='white' shape='circle'>
{t('无限制')}
</Tag>
);
}
};
// Render IP restrictions column
const renderAllowIps = (text, t) => {
if (!text || text.trim() === '') {
return (
<Tag color='white' shape='circle'>
{t('无限制')}
</Tag>
);
}
const ips = text
.split('\n')
.map((ip) => ip.trim())
.filter(Boolean);
const displayIps = ips.slice(0, 1);
const extraCount = ips.length - displayIps.length;
const ipTags = displayIps.map((ip, idx) => (
<Tag key={idx} shape='circle'>
{ip}
</Tag>
));
if (extraCount > 0) {
ipTags.push(
<Tooltip
key='extra'
content={ips.slice(1).join(', ')}
position='top'
showArrow
>
<Tag shape='circle'>{'+' + extraCount}</Tag>
</Tooltip>,
);
}
return <Space wrap>{ipTags}</Space>;
};
// Render separate quota usage column
const renderQuotaUsage = (text, record, t) => {
const { Paragraph } = Typography;
const used = parseInt(record.used_quota) || 0;
const remain = parseInt(record.remain_quota) || 0;
const total = used + remain;
if (record.unlimited_quota) {
const popoverContent = (
<div className='text-xs p-2'>
<Paragraph copyable={{ content: renderQuota(used) }}>
{t('已用额度')}: {renderQuota(used)}
</Paragraph>
</div>
);
return (
<Popover content={popoverContent} position='top'>
<Tag color='white' shape='circle'>
{t('无限额度')}
</Tag>
</Popover>
);
}
const percent = total > 0 ? (remain / total) * 100 : 0;
const popoverContent = (
<div className='text-xs p-2'>
<Paragraph copyable={{ content: renderQuota(used) }}>
{t('已用额度')}: {renderQuota(used)}
</Paragraph>
<Paragraph copyable={{ content: renderQuota(remain) }}>
{t('剩余额度')}: {renderQuota(remain)} ({percent.toFixed(0)}%)
</Paragraph>
<Paragraph copyable={{ content: renderQuota(total) }}>
{t('总额度')}: {renderQuota(total)}
</Paragraph>
</div>
);
return (
<Popover content={popoverContent} position='top'>
<Tag color='white' shape='circle'>
<div className='flex flex-col items-end'>
<span className='text-xs leading-none'>{`${renderQuota(remain)} / ${renderQuota(total)}`}</span>
<Progress
percent={percent}
stroke={getProgressColor(percent)}
aria-label='quota usage'
format={() => `${percent.toFixed(0)}%`}
style={{ width: '100%', marginTop: '1px', marginBottom: 0 }}
/>
</div>
</Tag>
</Popover>
);
};
// Render operations column
const renderOperations = (
text,
record,
onOpenLink,
setEditingToken,
setShowEdit,
manageToken,
refresh,
t,
) => {
let chatsArray = [];
try {
const raw = localStorage.getItem('chats');
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) {
for (let i = 0; i < parsed.length; i++) {
const item = parsed[i];
const name = Object.keys(item)[0];
if (!name) continue;
chatsArray.push({
node: 'item',
key: i,
name,
value: item[name],
onClick: () => onOpenLink(name, item[name], record),
});
}
}
} catch (_) {
showError(t('聊天链接配置错误,请联系管理员'));
}
return (
<Space wrap>
<SplitButtonGroup
className='overflow-hidden'
aria-label={t('项目操作按钮组')}
>
<Button
size='small'
type='tertiary'
onClick={() => {
if (chatsArray.length === 0) {
showError(t('请联系管理员配置聊天链接'));
} else {
const first = chatsArray[0];
onOpenLink(first.name, first.value, record);
}
}}
>
{t('聊天')}
</Button>
<Dropdown trigger='click' position='bottomRight' menu={chatsArray}>
<Button
type='tertiary'
icon={<IconTreeTriangleDown />}
size='small'
></Button>
</Dropdown>
</SplitButtonGroup>
{record.status === 1 ? (
<Button
type='danger'
size='small'
onClick={async () => {
await manageToken(record.id, 'disable', record);
await refresh();
}}
>
{t('禁用')}
</Button>
) : (
<Button
size='small'
onClick={async () => {
await manageToken(record.id, 'enable', record);
await refresh();
}}
>
{t('启用')}
</Button>
)}
<Button
type='tertiary'
size='small'
onClick={() => {
setEditingToken(record);
setShowEdit(true);
}}
>
{t('编辑')}
</Button>
<Button
type='danger'
size='small'
onClick={() => {
Modal.confirm({
title: t('确定是否要删除此令牌?'),
content: t('此修改将不可逆'),
onOk: () => {
(async () => {
await manageToken(record.id, 'delete', record);
await refresh();
})();
},
});
}}
>
{t('删除')}
</Button>
</Space>
);
};
export const getTokensColumns = ({
t,
showKeys,
setShowKeys,
copyText,
manageToken,
onOpenLink,
setEditingToken,
setShowEdit,
refresh,
}) => {
return [
{
title: t('名称'),
dataIndex: 'name',
},
{
title: t('状态'),
dataIndex: 'status',
key: 'status',
render: (text, record) => renderStatus(text, record, t),
},
{
title: t('剩余额度/总额度'),
key: 'quota_usage',
render: (text, record) => renderQuotaUsage(text, record, t),
},
{
title: t('分组'),
dataIndex: 'group',
key: 'group',
render: (text) => renderGroupColumn(text, t),
},
{
title: t('密钥'),
key: 'token_key',
render: (text, record) =>
renderTokenKey(text, record, showKeys, setShowKeys, copyText),
},
{
title: t('可用模型'),
dataIndex: 'model_limits',
render: (text, record) => renderModelLimits(text, record, t),
},
{
title: t('IP限制'),
dataIndex: 'allow_ips',
render: (text) => renderAllowIps(text, t),
},
{
title: t('创建时间'),
dataIndex: 'created_time',
render: (text, record, index) => {
return <div>{renderTimestamp(text)}</div>;
},
},
{
title: t('过期时间'),
dataIndex: 'expired_time',
render: (text, record, index) => {
return (
<div>
{record.expired_time === -1 ? t('永不过期') : renderTimestamp(text)}
</div>
);
},
},
{
title: '',
dataIndex: 'operate',
fixed: 'right',
render: (text, record, index) =>
renderOperations(
text,
record,
onOpenLink,
setEditingToken,
setShowEdit,
manageToken,
refresh,
t,
),
},
];
};
@@ -0,0 +1,44 @@
/*
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 React from 'react';
import { Typography } from '@douyinfe/semi-ui';
import { Key } from 'lucide-react';
import CompactModeToggle from '../../common/ui/CompactModeToggle';
const { Text } = Typography;
const TokensDescription = ({ compactMode, setCompactMode, t }) => {
return (
<div className='flex flex-col md:flex-row justify-between items-start md:items-center gap-2 w-full'>
<div className='flex items-center text-blue-500'>
<Key size={16} className='mr-2' />
<Text>{t('令牌管理')}</Text>
</div>
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
</div>
);
};
export default TokensDescription;
@@ -0,0 +1,106 @@
/*
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 React, { useRef } from 'react';
import { Form, Button } from '@douyinfe/semi-ui';
import { IconSearch } from '@douyinfe/semi-icons';
const TokensFilters = ({
formInitValues,
setFormApi,
searchTokens,
loading,
searching,
t,
}) => {
// Handle form reset and immediate search
const formApiRef = useRef(null);
const handleReset = () => {
if (!formApiRef.current) return;
formApiRef.current.reset();
setTimeout(() => {
searchTokens();
}, 100);
};
return (
<Form
initValues={formInitValues}
getFormApi={(api) => {
setFormApi(api);
formApiRef.current = api;
}}
onSubmit={searchTokens}
allowEmpty={true}
autoComplete='off'
layout='horizontal'
trigger='change'
stopValidateWithError={false}
className='w-full md:w-auto order-1 md:order-2'
>
<div className='flex flex-col md:flex-row items-center gap-2 w-full md:w-auto'>
<div className='relative w-full md:w-56'>
<Form.Input
field='searchKeyword'
prefix={<IconSearch />}
placeholder={t('搜索关键字')}
showClear
pure
size='small'
/>
</div>
<div className='relative w-full md:w-56'>
<Form.Input
field='searchToken'
prefix={<IconSearch />}
placeholder={t('密钥')}
showClear
pure
size='small'
/>
</div>
<div className='flex gap-2 w-full md:w-auto'>
<Button
type='tertiary'
htmlType='submit'
loading={loading || searching}
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('查询')}
</Button>
<Button
type='tertiary'
onClick={handleReset}
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('重置')}
</Button>
</div>
</div>
</Form>
);
};
export default TokensFilters;
+124
View File
@@ -0,0 +1,124 @@
/*
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 React, { useMemo } from 'react';
import { Empty } from '@douyinfe/semi-ui';
import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../common/illustrations';
import { getTokensColumns } from './TokensColumnDefs';
const TokensTable = (tokensData) => {
const {
tokens,
loading,
activePage,
pageSize,
tokenCount,
compactMode,
handlePageChange,
handlePageSizeChange,
rowSelection,
handleRow,
showKeys,
setShowKeys,
copyText,
manageToken,
onOpenLink,
setEditingToken,
setShowEdit,
refresh,
t,
} = tokensData;
// Get all columns
const columns = useMemo(() => {
return getTokensColumns({
t,
showKeys,
setShowKeys,
copyText,
manageToken,
onOpenLink,
setEditingToken,
setShowEdit,
refresh,
});
}, [
t,
showKeys,
setShowKeys,
copyText,
manageToken,
onOpenLink,
setEditingToken,
setShowEdit,
refresh,
]);
// Handle compact mode by removing fixed positioning
const tableColumns = useMemo(() => {
return compactMode
? columns.map((col) => {
if (col.dataIndex === 'operate') {
const { fixed, ...rest } = col;
return rest;
}
return col;
})
: columns;
}, [compactMode, columns]);
return (
<CardTable
columns={tableColumns}
dataSource={tokens}
scroll={compactMode ? undefined : { x: 'max-content' }}
pagination={{
currentPage: activePage,
pageSize: pageSize,
total: tokenCount,
showSizeChanger: true,
pageSizeOptions: [10, 20, 50, 100],
onPageSizeChange: handlePageSizeChange,
onPageChange: handlePageChange,
}}
hidePagination={true}
loading={loading}
rowSelection={rowSelection}
onRow={handleRow}
empty={
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className='rounded-xl overflow-hidden'
size='middle'
/>
);
};
export default TokensTable;
+431
View File
@@ -0,0 +1,431 @@
/*
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 React, { useEffect, useRef, useState } from 'react';
import {
Notification,
Button,
Space,
Toast,
Select,
} from '@douyinfe/semi-ui';
import {
API,
showError,
getModelCategories,
selectFilter,
} from '../../../helpers';
import CardPro from '../../common/ui/CardPro';
import TokensTable from './TokensTable';
import TokensActions from './TokensActions';
import TokensFilters from './TokensFilters';
import TokensDescription from './TokensDescription';
import EditTokenModal from './modals/EditTokenModal';
import { useTokensData } from '../../../hooks/tokens/useTokensData';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../../helpers/utils';
function TokensPage({ labelReplace } = {}) {
// Define the function first, then pass it into the hook to avoid TDZ errors
const openFluentNotificationRef = useRef(null);
const tokensData = useTokensData((key) =>
openFluentNotificationRef.current?.(key),
);
const isMobile = useIsMobile();
// Create a wrapped translation function that replaces labels if needed
const originalT = tokensData.t;
const t = labelReplace
? (key, options) => {
const result = originalT(key, options);
return typeof result === 'string'
? result.replace(/令牌/g, labelReplace)
: result;
}
: originalT;
const latestRef = useRef({
tokens: [],
selectedKeys: [],
t: (k) => k,
selectedModel: '',
prefillKey: '',
});
const [modelOptions, setModelOptions] = useState([]);
const [selectedModel, setSelectedModel] = useState('');
const [fluentNoticeOpen, setFluentNoticeOpen] = useState(false);
const [prefillKey, setPrefillKey] = useState('');
// Keep latest data for handlers inside notifications
useEffect(() => {
latestRef.current = {
tokens: tokensData.tokens,
selectedKeys: tokensData.selectedKeys,
t: t,
selectedModel,
prefillKey,
};
}, [
tokensData.tokens,
tokensData.selectedKeys,
t,
selectedModel,
prefillKey,
]);
const loadModels = async () => {
try {
const res = await API.get('/api/user/models');
const { success, message, data } = res.data || {};
if (success) {
const categories = getModelCategories(tokensData.t);
const options = (data || []).map((model) => {
let icon = null;
for (const [key, category] of Object.entries(categories)) {
if (key !== 'all' && category.filter({ model_name: model })) {
icon = category.icon;
break;
}
}
return {
label: (
<span className='flex items-center gap-1'>
{icon}
{model}
</span>
),
value: model,
};
});
setModelOptions(options);
} else {
showError(tokensData.t(message));
}
} catch (e) {
showError(e.message || 'Failed to load models');
}
};
function openFluentNotification(key) {
const { t } = latestRef.current;
const SUPPRESS_KEY = 'fluent_notify_suppressed';
if (modelOptions.length === 0) {
// fire-and-forget; a later effect will refresh the notice content
loadModels();
}
if (!key && localStorage.getItem(SUPPRESS_KEY) === '1') return;
const container = document.getElementById('fluent-new-api-container');
if (!container) {
Toast.warning(t('未检测到 FluentRead(流畅阅读),请确认扩展已启用'));
return;
}
setPrefillKey(key || '');
setFluentNoticeOpen(true);
Notification.info({
id: 'fluent-detected',
title: t('检测到 FluentRead(流畅阅读)'),
content: (
<div>
<div style={{ marginBottom: 8 }}>
{key
? t('请选择模型。')
: t('选择模型后可一键填充当前选中令牌(或本页第一个令牌)。')}
</div>
<div style={{ marginBottom: 8 }}>
<Select
placeholder={t('请选择模型')}
optionList={modelOptions}
onChange={setSelectedModel}
filter={selectFilter}
style={{ width: 320 }}
showClear
searchable
emptyContent={t('暂无数据')}
/>
</div>
<Space>
<Button
theme='solid'
type='primary'
onClick={handlePrefillToFluent}
>
{t('一键填充到 FluentRead')}
</Button>
{!key && (
<Button
type='warning'
onClick={() => {
localStorage.setItem(SUPPRESS_KEY, '1');
Notification.close('fluent-detected');
Toast.info(t('已关闭后续提醒'));
}}
>
{t('不再提醒')}
</Button>
)}
<Button
type='tertiary'
onClick={() => Notification.close('fluent-detected')}
>
{t('关闭')}
</Button>
</Space>
</div>
),
duration: 0,
});
}
// assign after definition so hook callback can call it safely
openFluentNotificationRef.current = openFluentNotification;
// Prefill to Fluent handler
const handlePrefillToFluent = () => {
const {
tokens,
selectedKeys,
t,
selectedModel: chosenModel,
prefillKey: overrideKey,
} = latestRef.current;
const container = document.getElementById('fluent-new-api-container');
if (!container) {
Toast.error(t('未检测到 Fluent 容器'));
return;
}
if (!chosenModel) {
Toast.warning(t('请选择模型'));
return;
}
let status = localStorage.getItem('status');
let serverAddress = '';
if (status) {
try {
status = JSON.parse(status);
serverAddress = status.server_address || '';
} catch (_) {}
}
if (!serverAddress) serverAddress = window.location.origin;
let apiKeyToUse = '';
if (overrideKey) {
apiKeyToUse = 'sk-' + overrideKey;
} else {
const token =
selectedKeys && selectedKeys.length === 1
? selectedKeys[0]
: tokens && tokens.length > 0
? tokens[0]
: null;
if (!token) {
Toast.warning(t('没有可用令牌用于填充'));
return;
}
apiKeyToUse = 'sk-' + token.key;
}
const payload = {
id: 'new-api',
baseUrl: serverAddress,
apiKey: apiKeyToUse,
model: chosenModel,
};
container.dispatchEvent(
new CustomEvent('fluent:prefill', { detail: payload }),
);
Toast.success(t('已发送到 Fluent'));
Notification.close('fluent-detected');
};
// Show notification when Fluent container is available
useEffect(() => {
const onAppeared = () => {
openFluentNotification();
};
const onRemoved = () => {
setFluentNoticeOpen(false);
Notification.close('fluent-detected');
};
window.addEventListener('fluent-container:appeared', onAppeared);
window.addEventListener('fluent-container:removed', onRemoved);
return () => {
window.removeEventListener('fluent-container:appeared', onAppeared);
window.removeEventListener('fluent-container:removed', onRemoved);
};
}, []);
// When modelOptions or language changes while the notice is open, refresh the content
useEffect(() => {
if (fluentNoticeOpen) {
openFluentNotification();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [modelOptions, selectedModel, tokensData.t, fluentNoticeOpen]);
useEffect(() => {
const selector = '#fluent-new-api-container';
const root = document.body || document.documentElement;
const existing = document.querySelector(selector);
if (existing) {
console.log('Fluent container detected (initial):', existing);
window.dispatchEvent(
new CustomEvent('fluent-container:appeared', { detail: existing }),
);
}
const isOrContainsTarget = (node) => {
if (!(node && node.nodeType === 1)) return false;
if (node.id === 'fluent-new-api-container') return true;
return (
typeof node.querySelector === 'function' &&
!!node.querySelector(selector)
);
};
const observer = new MutationObserver((mutations) => {
for (const m of mutations) {
// appeared
for (const added of m.addedNodes) {
if (isOrContainsTarget(added)) {
const el = document.querySelector(selector);
if (el) {
console.log('Fluent container appeared:', el);
window.dispatchEvent(
new CustomEvent('fluent-container:appeared', { detail: el }),
);
}
break;
}
}
// removed
for (const removed of m.removedNodes) {
if (isOrContainsTarget(removed)) {
const elNow = document.querySelector(selector);
if (!elNow) {
console.log('Fluent container removed');
window.dispatchEvent(new CustomEvent('fluent-container:removed'));
}
break;
}
}
}
});
observer.observe(root, { childList: true, subtree: true });
return () => observer.disconnect();
}, []);
const {
// Edit state
showEdit,
editingToken,
closeEdit,
refresh,
// Actions state
selectedKeys,
setEditingToken,
setShowEdit,
batchCopyTokens,
batchDeleteTokens,
copyText,
// Filters state
formInitValues,
setFormApi,
searchTokens,
loading,
searching,
// Description state
compactMode,
setCompactMode,
// Translation - excluded, using wrapped t instead
// t,
} = tokensData;
// Create tokensData with wrapped t for TokensTable
const wrappedTokensData = { ...tokensData, t };
return (
<>
<EditTokenModal
refresh={refresh}
editingToken={editingToken}
visiable={showEdit}
handleClose={closeEdit}
labelReplace={labelReplace}
/>
<CardPro
type='type1'
descriptionArea={
<TokensDescription
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
}
actionsArea={
<div className='flex flex-col md:flex-row justify-between items-center gap-2 w-full'>
<TokensActions
selectedKeys={selectedKeys}
setEditingToken={setEditingToken}
setShowEdit={setShowEdit}
batchCopyTokens={batchCopyTokens}
batchDeleteTokens={batchDeleteTokens}
copyText={copyText}
t={t}
/>
<div className='w-full md:w-full lg:w-auto order-1 md:order-2'>
<TokensFilters
formInitValues={formInitValues}
setFormApi={setFormApi}
searchTokens={searchTokens}
loading={loading}
searching={searching}
t={t}
/>
</div>
</div>
}
paginationArea={createCardProPagination({
currentPage: tokensData.activePage,
pageSize: tokensData.pageSize,
total: tokensData.tokenCount,
onPageChange: tokensData.handlePageChange,
onPageSizeChange: tokensData.handlePageSizeChange,
isMobile: isMobile,
t: t,
})}
t={t}
>
<TokensTable {...wrappedTokensData} />
</CardPro>
</>
);
}
export default TokensPage;
@@ -0,0 +1,64 @@
/*
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 React from 'react';
import { Modal, Button, Space } from '@douyinfe/semi-ui';
const CopyTokensModal = ({ visible, onCancel, selectedKeys, copyText, t }) => {
// Handle copy with name and key format
const handleCopyWithName = async () => {
let content = '';
for (let i = 0; i < selectedKeys.length; i++) {
content += selectedKeys[i].name + ' sk-' + selectedKeys[i].key + '\n';
}
await copyText(content);
onCancel();
};
// Handle copy with key only format
const handleCopyKeyOnly = async () => {
let content = '';
for (let i = 0; i < selectedKeys.length; i++) {
content += 'sk-' + selectedKeys[i].key + '\n';
}
await copyText(content);
onCancel();
};
return (
<Modal
title={t('复制令牌')}
icon={null}
visible={visible}
onCancel={onCancel}
footer={
<Space>
<Button type='tertiary' onClick={handleCopyWithName}>
{t('名称+密钥')}
</Button>
<Button onClick={handleCopyKeyOnly}>{t('仅密钥')}</Button>
</Space>
}
>
{t('请选择你的复制方式')}
</Modal>
);
};
export default CopyTokensModal;
@@ -0,0 +1,47 @@
/*
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 React from 'react';
import { Modal } from '@douyinfe/semi-ui';
const DeleteTokensModal = ({
visible,
onCancel,
onConfirm,
selectedKeys,
t,
}) => {
return (
<Modal
title={t('批量删除令牌')}
visible={visible}
onCancel={onCancel}
onOk={onConfirm}
type='warning'
>
<div>
{t('确定要删除所选的 {{count}} 个令牌吗?', {
count: selectedKeys.length,
})}
</div>
</Modal>
);
};
export default DeleteTokensModal;
@@ -0,0 +1,745 @@
/*
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 React, { useEffect, useState, useContext, useRef } from 'react';
import {
API,
showError,
showSuccess,
renderGroupOption,
getModelCategories,
selectFilter,
} from '../../../../helpers';
import { FormQuotaInput } from '../../../common/ui/QuotaInput';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import {
Button,
Modal,
Spin,
Form,
Collapsible,
DatePicker,
} from '@douyinfe/semi-ui';
import { IconChevronDown } from '@douyinfe/semi-icons';
import {
Key,
CreditCard,
Shield,
X,
Check,
Settings2,
Calendar,
Hash,
Layers,
Infinity,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { StatusContext } from '../../../../context/Status';
const EditTokenModal = (props) => {
const { t: originalT } = useTranslation();
const t = props.labelReplace
? (key, options) => {
const result = originalT(key, options);
return typeof result === 'string'
? result.replace(/令牌/g, props.labelReplace)
: result;
}
: originalT;
const [statusState] = useContext(StatusContext);
const [loading, setLoading] = useState(false);
const [advancedOpen, setAdvancedOpen] = useState(false);
const [neverExpire, setNeverExpire] = useState(true);
const [expireDate, setExpireDate] = useState(null);
const isMobile = useIsMobile();
const formApiRef = useRef(null);
const [models, setModels] = useState([]);
const [skillOptions, setSkillOptions] = useState([]);
const [groups, setGroups] = useState([]);
const isEdit = props.editingToken.id !== undefined;
// 默认分组配置
const DEFAULT_GROUP = 'claude专用分组';
// 生成默认名称:claude + 随机两位整数
const generateDefaultName = () => {
const randomNum = Math.floor(Math.random() * 100)
.toString()
.padStart(2, '0');
return `claude${randomNum}`;
};
const getInitValues = () => ({
name: generateDefaultName(),
remain_quota: 0,
unlimited_quota: true,
model_limits_enabled: false,
model_limits: [],
allow_ips: '',
group: '', // 分组在 loadGroups 后动态设置
tokenCount: 1,
// 技能注入:默认关闭,存量密钥零影响
skill_injection_enabled: false,
skill_ids: [],
});
const handleCancel = () => {
setAdvancedOpen(false);
setNeverExpire(true);
setExpireDate(null);
props.handleClose();
};
const setExpiredTime = (month, day, hour, minute) => {
if (month === 0 && day === 0 && hour === 0 && minute === 0) {
setNeverExpire(true);
setExpireDate(null);
return;
}
setNeverExpire(false);
let now = new Date();
let timestamp = now.getTime();
let ms = month * 30 * 24 * 60 * 60 * 1000;
ms += day * 24 * 60 * 60 * 1000;
ms += hour * 60 * 60 * 1000;
ms += minute * 60 * 1000;
setExpireDate(new Date(timestamp + ms));
};
// 设置默认分组:优先 claude专用分组,否则第一个分组
const setDefaultGroup = (groupOptions) => {
if (!formApiRef.current || groupOptions.length === 0) return;
const hasDefaultGroup = groupOptions.some((g) => g.value === DEFAULT_GROUP);
const defaultValue = hasDefaultGroup
? DEFAULT_GROUP
: groupOptions[0].value;
formApiRef.current.setValue('group', defaultValue);
};
// 绑定技能的候选集取自技能超市目录(平台已发布集)。
// 这里刻意不做治理判定:企业密钥即便勾了企业未启用的技能,
// 后端解析层也只会收窄不会扩权(skillinject.resolveOrganization),
// 前端再判一次只会产生两套口径。
const loadSkillOptions = async () => {
// 必须翻页取全,不能"取一页当全量":服务端单页上限 100,而平台已发布技能
// 有数百个,只取首页会让第 101 个之后的技能永远无法被绑定,且界面上毫无提示。
// 这与 R19 修掉的企业技能市场固定 200 一页是同一型缺陷。
const pageSize = 100;
const maxPages = 20; // 兜底,防止服务端 total 异常时无限翻页
try {
const collected = [];
let offset = 0;
for (let page = 0; page < maxPages; page += 1) {
const res = await API.get('/api/skills/market', {
params: { page_size: pageSize, offset },
});
if (!res.data?.success) break;
const batch = res.data.data || [];
collected.push(...batch);
offset += batch.length;
if (batch.length < pageSize || offset >= (res.data.total || 0)) break;
}
setSkillOptions(
collected.map((skill) => ({
label: skill.name || skill.canonical_id,
value: skill.id,
})),
);
} catch (_error) {
setSkillOptions([]);
}
};
const loadModels = async () => {
let res = await API.get(`/api/user/models`);
const { success, message, data } = res.data;
if (success) {
const categories = getModelCategories(t);
let localModelOptions = data.map((model) => {
let icon = null;
for (const [key, category] of Object.entries(categories)) {
if (key !== 'all' && category.filter({ model_name: model })) {
icon = category.icon;
break;
}
}
return {
label: (
<span className='flex items-center gap-1'>
{icon}
{model}
</span>
),
value: model,
};
});
setModels(localModelOptions);
} else {
showError(t(message));
}
};
const loadGroups = async () => {
let res = await API.get(`/api/user/self/groups`);
const { success, message, data } = res.data;
if (success) {
let localGroupOptions = Object.entries(data).map(([group, info]) => ({
label: group,
value: group,
ratio: info.ratio,
description: info.desc,
fullLabel: info.desc,
}));
if (statusState?.status?.default_use_auto_group) {
if (localGroupOptions.some((group) => group.value === 'auto')) {
localGroupOptions.sort((a, b) => (a.value === 'auto' ? -1 : 1));
}
}
setGroups(localGroupOptions);
// 新建模式下设置默认分组
if (!isEdit) {
setDefaultGroup(localGroupOptions);
}
} else {
showError(t(message));
}
};
const loadToken = async () => {
setLoading(true);
let res = await API.get(`/api/token/${props.editingToken.id}`);
const { success, message, data } = res.data;
if (success) {
// 处理过期时间
if (data.expired_time === -1) {
setNeverExpire(true);
setExpireDate(null);
} else {
setNeverExpire(false);
setExpireDate(new Date(data.expired_time * 1000));
}
if (data.model_limits !== '') {
data.model_limits = data.model_limits.split(',');
} else {
data.model_limits = [];
}
// tokens.skill_ids 存的是 JSON 数组文本,表单要的是数组。
// 解析失败退化为空数组(=跟随身份有效集),不因一条坏数据卡住整个编辑页。
if (typeof data.skill_ids === 'string') {
try {
const parsed = JSON.parse(data.skill_ids || '[]');
data.skill_ids = Array.isArray(parsed) ? parsed : [];
} catch (_error) {
data.skill_ids = [];
}
} else if (!Array.isArray(data.skill_ids)) {
data.skill_ids = [];
}
// 移除 expired_time,因为我们单独管理
const { expired_time, ...restData } = data;
if (formApiRef.current) {
formApiRef.current.setValues({ ...getInitValues(), ...restData });
}
if (
data.model_limits?.length > 0 ||
data.allow_ips ||
!data.unlimited_quota ||
data.skill_injection_enabled
) {
setAdvancedOpen(true);
}
} else {
showError(message);
}
setLoading(false);
};
useEffect(() => {
if (formApiRef.current) {
if (!isEdit) {
formApiRef.current.setValues(getInitValues());
}
}
loadModels();
loadGroups();
loadSkillOptions();
}, [props.editingToken.id]);
useEffect(() => {
if (props.visiable) {
if (isEdit) {
loadToken();
} else {
formApiRef.current?.setValues(getInitValues());
setAdvancedOpen(false);
setNeverExpire(true);
setExpireDate(null);
// 如果 groups 已加载,设置默认分组
if (groups.length > 0) {
setDefaultGroup(groups);
}
}
} else {
formApiRef.current?.reset();
setAdvancedOpen(false);
setNeverExpire(true);
setExpireDate(null);
}
}, [props.visiable, props.editingToken.id]);
const generateRandomSuffix = () => {
const characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < 6; i++) {
result += characters.charAt(
Math.floor(Math.random() * characters.length),
);
}
return result;
};
// 创建/编辑共用的载荷构造(R26 教训:双分支各自维护同构逻辑,漏一边就出
// skill_ids 未序列化这类漂移故障,统一出口杜绝分叉)。
// - remain_quota 表单值是字符串,落库要整数
// - model_limits 表单值是数组,接口契约是逗号分隔文本
// - skill_ids 表单值是数组,tokens.skill_ids 落库是 JSON 数组文本;
// 空数组语义是"跟随身份有效集",与"未开启注入"不是一回事,
// 因此关闭注入时也如实提交空数组。
const buildTokenPayload = (values, expired_time) => {
const { tokenCount: _tc, ...payload } = values;
payload.remain_quota = parseInt(payload.remain_quota);
payload.expired_time = expired_time;
payload.model_limits = payload.model_limits.join(',');
payload.model_limits_enabled = payload.model_limits.length > 0;
payload.skill_ids = JSON.stringify(payload.skill_ids || []);
return payload;
};
const submit = async (values) => {
// 验证过期时间
if (!neverExpire && !expireDate) {
showError(t('请选择过期时间'));
return;
}
if (!neverExpire && expireDate && expireDate.getTime() <= Date.now()) {
showError(t('过期时间不能早于当前时间'));
return;
}
setLoading(true);
// 计算过期时间
const expired_time = neverExpire
? -1
: Math.ceil(expireDate.getTime() / 1000);
if (isEdit) {
const localInputs = buildTokenPayload(values, expired_time);
let res = await API.put(`/api/token/`, {
...localInputs,
id: parseInt(props.editingToken.id),
});
const { success, message } = res.data;
if (success) {
showSuccess(t('令牌更新成功!'));
props.refresh();
props.handleClose();
} else {
showError(t(message));
}
} else {
const count = parseInt(values.tokenCount, 10) || 1;
let successCount = 0;
for (let i = 0; i < count; i++) {
const localInputs = buildTokenPayload(values, expired_time);
const baseName =
values.name.trim() === '' ? 'default' : values.name.trim();
if (i !== 0 || values.name.trim() === '') {
localInputs.name = `${baseName}-${generateRandomSuffix()}`;
} else {
localInputs.name = baseName;
}
let res = await API.post(`/api/token/`, localInputs);
const { success, message } = res.data;
if (success) {
successCount++;
} else {
showError(t(message));
break;
}
}
if (successCount > 0) {
showSuccess(t('令牌创建成功,请在列表页面点击复制获取令牌!'));
props.refresh();
props.handleClose();
}
}
setLoading(false);
formApiRef.current?.setValues(getInitValues());
};
// 自定义标签组件
const FieldLabel = ({ icon: Icon, iconColor, children, required }) => (
<div className='flex items-center gap-1.5 mb-1'>
<Icon size={14} className={iconColor} />
<span className='text-sm font-medium text-gray-700 dark:text-gray-300'>
{children}
</span>
{required && <span className='text-red-500 text-sm'>*</span>}
</div>
);
return (
<Modal
title={null}
visible={props.visiable}
onCancel={handleCancel}
centered
width={isMobile ? '95%' : 480}
closeIcon={null}
header={null}
footer={null}
maskClosable={false}
className='edit-token-modal'
bodyStyle={{ padding: 0 }}
style={{ borderRadius: '16px', overflow: 'hidden' }}
>
<div className='bg-white dark:bg-neutral-900'>
{/* 头部 */}
<div className='flex items-center justify-between px-5 py-4 border-b border-gray-100 dark:border-neutral-800 bg-gradient-to-r from-brand/[0.06] to-transparent'>
<div className='flex items-center gap-3'>
<div className='p-2 rounded-xl bg-gradient-to-br from-brand-from to-brand-to shadow-lg shadow-brand/30'>
<Key size={18} className='text-white' />
</div>
<div>
<h2 className='text-base font-semibold text-gray-800 dark:text-gray-100'>
{isEdit ? t('编辑令牌') : t('创建令牌')}
</h2>
<p className='text-xs text-gray-500 dark:text-gray-400'>
{isEdit ? t('修改令牌配置') : t('快速创建访问令牌')}
</p>
</div>
</div>
<button
onClick={handleCancel}
className='p-1.5 rounded-lg text-gray-400 hover:text-gray-600 hover:bg-gray-100 dark:hover:bg-neutral-800 transition-colors'
>
<X size={18} />
</button>
</div>
{/* 表单内容 */}
<Spin spinning={loading}>
<Form
key={isEdit ? 'edit' : 'new'}
initValues={getInitValues()}
getFormApi={(api) => (formApiRef.current = api)}
onSubmit={submit}
>
{({ values }) => (
<div className='px-5 py-4 max-h-[65vh] overflow-y-auto space-y-4 modal-scrollbar'>
{/* 基础配置区块 */}
<div className='p-4 rounded-xl bg-white dark:bg-neutral-900 border border-gray-200/60 dark:border-neutral-700/60 space-y-4'>
<div className='flex items-center gap-2 pb-2 border-b border-gray-200/60 dark:border-neutral-700/60'>
<div className='w-1 h-4 rounded-full bg-gradient-to-b from-brand-from to-brand-to' />
<span className='text-sm font-medium text-gray-700 dark:text-gray-300'>
{t('基础配置')}
</span>
</div>
{/* 名称 */}
<div>
<FieldLabel icon={Key} iconColor='text-brand' required>
{t('名称')}
</FieldLabel>
<Form.Input
field='name'
noLabel
placeholder={t('请输入令牌名称')}
rules={[{ required: true, message: t('请输入名称') }]}
showClear
/>
</div>
{/* 秘钥分组 */}
<div>
<FieldLabel icon={Layers} iconColor='text-brand'>
{t('令牌分组')}
</FieldLabel>
{groups.length > 0 ? (
<Form.Select
field='group'
noLabel
placeholder={t('选择分组,默认为用户分组')}
optionList={groups}
renderOptionItem={renderGroupOption}
showClear
style={{ width: '100%' }}
/>
) : (
<Form.Select
field='group'
noLabel
placeholder={t('管理员未设置用户可选分组')}
disabled
style={{ width: '100%' }}
/>
)}
</div>
{/* 过期时间 */}
<div>
<FieldLabel icon={Calendar} iconColor='text-brand' required>
{t('过期时间')}
</FieldLabel>
{neverExpire ? (
<div
className='flex items-center gap-2 px-3 py-2.5 bg-brand/[0.08] border border-brand/20 rounded-lg cursor-pointer hover:bg-brand/[0.12] transition-colors'
onClick={() => {
setNeverExpire(false);
const oneMonthLater = new Date();
oneMonthLater.setMonth(oneMonthLater.getMonth() + 1);
setExpireDate(oneMonthLater);
}}
>
<Infinity size={16} className='text-brand' />
<span className='text-sm font-medium text-brand-deep'>
{t('永不过期')}
</span>
<span className='text-xs text-brand/70 ml-auto'>
{t('点击修改')}
</span>
</div>
) : (
<DatePicker
type='dateTime'
value={expireDate}
onChange={(date) => setExpireDate(date)}
placeholder={t('选择过期时间')}
showClear
style={{ width: '100%' }}
disabledDate={(date) =>
date &&
date < new Date(new Date().setHours(0, 0, 0, 0))
}
/>
)}
{/* 快捷按钮 */}
<div className='flex flex-wrap gap-1.5 mt-2'>
{[
{
label: t('永不过期'),
args: [0, 0, 0, 0],
active: neverExpire,
},
{ label: t('一个月'), args: [1, 0, 0, 0] },
{ label: t('一周'), args: [0, 7, 0, 0] },
{ label: t('一天'), args: [0, 1, 0, 0] },
].map((item, idx) => (
<button
key={idx}
type='button'
onClick={() => setExpiredTime(...item.args)}
className={`px-2.5 py-1 text-xs font-medium rounded-lg transition-all ${
item.active
? 'bg-brand text-white shadow-sm shadow-brand/30'
: 'bg-white dark:bg-neutral-700 text-gray-600 dark:text-gray-300 hover:bg-brand/[0.08] hover:text-brand-deep hover:border-brand/30 border border-gray-200 dark:border-neutral-600'
}`}
>
{item.label}
</button>
))}
</div>
</div>
{/* 新建数量 */}
{!isEdit && (
<div>
<FieldLabel icon={Hash} iconColor='text-brand'>
{t('新建数量')}
</FieldLabel>
<Form.InputNumber
field='tokenCount'
noLabel
min={1}
max={100}
rules={[
{ required: true, message: t('请输入新建数量') },
]}
style={{ width: '100%' }}
/>
<p className='text-[11px] text-gray-400 mt-1'>
{t('批量创建时会在名称后自动添加随机后缀')}
</p>
</div>
)}
</div>
{/* 高级设置区块 */}
<div className='rounded-xl border border-gray-200 dark:border-neutral-700 overflow-hidden'>
<button
type='button'
onClick={() => setAdvancedOpen(!advancedOpen)}
className='w-full flex items-center justify-between px-4 py-3 bg-white dark:bg-neutral-900 hover:bg-gray-50 dark:hover:bg-neutral-800 transition-colors'
>
<div className='flex items-center gap-2'>
<Settings2 size={15} className='text-brand' />
<span className='text-sm font-medium text-gray-700 dark:text-gray-300'>
{t('高级设置')}
</span>
<span className='text-[11px] text-gray-400 dark:text-gray-500 ml-1'>
{t('额度、模型限制、IP白名单')}
</span>
</div>
<IconChevronDown
size={16}
className={`text-gray-400 transition-transform duration-200 ${advancedOpen ? 'rotate-180' : ''}`}
/>
</button>
<Collapsible isOpen={advancedOpen} keepDOM>
<div className='px-4 pb-4 pt-2 bg-white dark:bg-neutral-900 space-y-4'>
{/* 额度设置 */}
<div className='space-y-3'>
<div className='flex items-center gap-1.5'>
<CreditCard size={14} className='text-brand' />
<span className='text-sm font-medium text-gray-700 dark:text-gray-300'>
{t('额度设置')}
</span>
</div>
<Form.Switch
field='unlimited_quota'
label={t('无限额度')}
extraText={t('开启后令牌不限制使用额度')}
/>
{!values.unlimited_quota && (
<FormQuotaInput
field='remain_quota'
label={t('额度上限')}
rules={[
{ required: true, message: t('请输入额度') },
]}
style={{ width: '100%' }}
/>
)}
</div>
<div className='h-px bg-brand/50 dark:bg-brand-deep/30' />
{/* 访问限制 */}
<div className='space-y-3'>
<div className='flex items-center gap-1.5'>
<Shield size={14} className='text-brand' />
<span className='text-sm font-medium text-gray-700 dark:text-gray-300'>
{t('访问限制')}
</span>
</div>
<Form.Select
field='model_limits'
label={t('模型限制')}
placeholder={t('留空则支持所有模型')}
multiple
optionList={models}
extraText={t('非必要不建议启用')}
filter={selectFilter}
autoClearSearchValue={false}
searchPosition='dropdown'
showClear
style={{ width: '100%' }}
/>
<Form.TextArea
field='allow_ips'
label={t('IP白名单')}
placeholder={t('允许的IP,一行一个')}
autosize
rows={2}
extraText={t('不填则不限制,IP可能被伪造')}
showClear
style={{ width: '100%' }}
/>
<Form.Switch
field='skill_injection_enabled'
label={t('技能注入')}
extraText={t(
'开启后,用该密钥调用对话类接口时会自动前置技能约束。注入文本按正常 prompt token 计费,归属本密钥所属方。',
)}
/>
<Form.Select
field='skill_ids'
label={t('绑定技能')}
placeholder={t('留空则跟随「我的技能」')}
multiple
optionList={skillOptions}
extraText={t(
'最多同时生效 5 个。注意:前置注入会改变 system 前缀,已使用 prompt 缓存的高频调用可能缓存失效、成本上升。',
)}
filter={selectFilter}
autoClearSearchValue={false}
searchPosition='dropdown'
showClear
style={{ width: '100%' }}
/>
</div>
</div>
</Collapsible>
</div>
</div>
)}
</Form>
</Spin>
{/* 底部按钮 */}
<div className='flex gap-3 px-5 py-4 border-t border-gray-100 dark:border-neutral-800 bg-white dark:bg-neutral-900'>
<Button
theme='solid'
className='flex-1 !h-10 !rounded-xl !font-medium !border-0 !text-white !bg-gradient-to-r !from-brand-from !via-brand !to-brand-to shadow-lg shadow-brand/30 hover:!opacity-90'
onClick={() => formApiRef.current?.submitForm()}
icon={<Check size={16} />}
loading={loading}
>
{isEdit ? t('保存修改') : t('创建令牌')}
</Button>
<Button
theme='light'
className='!h-10 !px-5 !rounded-xl'
onClick={handleCancel}
>
{t('取消')}
</Button>
</div>
</div>
</Modal>
);
};
export default EditTokenModal;