fix(frontend): restore vulnerability grouping and settings controls

This commit is contained in:
Sycun 2026-11-19 09:48:25 +08:00
parent 8c2d815239
commit 9bdda0b392
70 changed files with 1067 additions and 307 deletions

View File

@ -121,3 +121,10 @@
.settings-field-wide { grid-column: span 1; }
.settings-yaml-input .semi-input-textarea { min-height: 300px; }
}
.settings-update-source-form {
display: flex;
flex-direction: column;
gap: 8px;
max-width: 760px;
}

View File

@ -372,24 +372,24 @@ function AuditDetail({ id, categoryLabel, actionLabel, resultLabel }) {
{ label: t('settingsAudit.detailResult', null, '结果'), value: <ResultTag result={log.result} label={resultLabel(log.result)} /> },
{ label: t('settingsAudit.detailCategory', null, '类别'), value: categoryLabel(log.category) },
{ label: t('settingsAudit.colAction', null, '操作'), value: actionLabel(log.action) },
{ label: 'actor', value: log.actor || '—' },
{ label: t('settingsDisplay.actor', null, '操作者'), value: log.actor || '—' },
{ label: t('settingsAudit.colIp', null, 'IP'), value: <Mono>{log.clientIp || '—'}</Mono> },
{ label: 'level', value: log.level || '—' },
{ label: 'resource_type', value: log.resourceType || '—' },
{ label: t('settingsDisplay.level', null, '日志级别'), value: log.level || '—' },
{ label: t('settingsDisplay.resourceType', null, '资源类型'), value: log.resourceType || '—' },
{ label: t('settingsAudit.resourceIdLabel', null, '资源 ID'), value: <Mono>{log.resourceId || '—'}</Mono> },
{
label: 'resource_available',
value: log.resourceAvailable === undefined ? '—' : String(log.resourceAvailable)
label: t('settingsDisplay.resourceAvailable', null, '资源是否可访问'),
value: log.resourceAvailable == null ? '—' : log.resourceAvailable ? t('common.yes', null, '是') : t('common.no', null, '否')
},
{ label: 'session', value: <Mono>{log.sessionHint || '—'}</Mono> },
{ label: 'userAgent', value: truncate(log.userAgent || '—', 80) }
{ label: t('settingsDisplay.session', null, '会话标识'), value: <Mono>{log.sessionHint || '—'}</Mono> },
{ label: t('settingsDisplay.userAgent', null, '客户端标识'), value: truncate(log.userAgent || '—', 80) }
]}
/>
<div className="settings-audit-message-block">
<Text type="tertiary" size="small">{t('settingsAudit.detailMessage', null, '说明')}</Text>
<Text>{log.message || '—'}</Text>
</div>
{log.detail && <JsonViewer value={log.detail} collapsed title="detail" />}
{log.detail && <JsonViewer value={log.detail} collapsed title={t('settingsDisplay.details', null, '详情')} />}
</div>
);
}

View File

@ -211,7 +211,7 @@ export default function BasicSection() {
<SectionCard
title={t('settings.rawTitle', null, '原始 YAML 配置')}
description={t('settings.rawDesc', null, '编辑后可先点「格式化并校验」检查语法;保存会写入 config.yaml 并立即应用。')}
description={t('settingsDisplay.rawYamlHelp', null, '查看或批量修改服务端高级配置。保存会写入支持的改动并尝试应用。')}
extra={(
<Space>
<Tag color={dirty ? 'amber' : 'green'} size="small">

View File

@ -15,15 +15,27 @@ const { Text } = Typography;
const MAIN_CHANNEL = '__main__';
const NO_CHANNELS = {};
const PROVIDERS = [
{ value: 'openai_compatible', label: 'OpenAI 兼容' },
{ value: 'claude', label: 'Claude(Anthropic Messages)' }
];
const CONTEXT_PROFILES = [
{ value: '', label: '默认(未知窗口)' },
{ value: 'auto', label: 'auto(自动)' },
{ value: 'local_auto', label: 'local_auto(本地服务)' },
{ value: 'custom', label: 'custom(手动运行时参数)' }
{ value: 'openai_compatible', key: 'settingsProbe.compatible', fallback: '兼容 OpenAI 的接口' },
{ value: 'claude', key: 'settingsBasic.providerClaude', fallback: 'Claude(Anthropic Messages)' }
];
const CONTEXT_PROFILES = ['', 'auto', 'local_auto', 'custom'];
const CONTEXT_WARNING_KEYS = {
context_window_unknown: 'contextWarnUnknown',
context_runtime_unknown: 'contextWarnRuntimeUnknown',
local_context_window_unknown: 'contextWarnWindowUnknown',
local_context_window_small: 'contextWarnWindowSmall',
max_total_tokens_clamped: 'contextWarnBudgetClamped',
max_completion_tokens_clamped: 'contextWarnCompletionClamped',
configured_budget_exceeds_context_window: 'contextWarnBudgetExceedsWindow',
ollama_v1_ignores_num_ctx: 'contextWarnOllamaV1',
ollama_runtime_context_unknown: 'contextWarnOllamaRuntime',
llamacpp_parallel_slots: 'contextWarnLlamaCppSlots'
};
const BACKEND_NAMES = { ollama: 'Ollama', llamacpp: 'llama.cpp', lmstudio: 'LM Studio', omlx: 'oMLX', vllm: 'vLLM' };
function profileLabel(t, value) {
return t('settingsProbe.profiles.' + (value || 'default'), null, value || '使用默认设置');
}
function numberValue(raw) {
const value = parseInt(raw, 10);
@ -57,18 +69,36 @@ function channelValues(config, id) {
};
}
function summarizeContext(payload) {
const rows = [
{ label: 'success', value: String(Boolean(payload.success)) },
{ label: 'model', value: payload.model || '—' },
{ label: 'latency_ms', value: payload.latency_ms != null ? `${payload.latency_ms} ms` : '—' },
{ label: 'context_window', value: payload.context_window ?? '—' },
{ label: 'context_backend', value: payload.context_backend || '—' },
{ label: 'context_source', value: payload.context_source || '—' },
{ label: 'context_profile', value: payload.context_profile || '(空)' },
{ label: 'effective_max_total_tokens', value: payload.effective_max_total_tokens ?? '—' }
function summarizeTest(t, payload) {
return [
{ label: t('settingsProbe.result', null, '测试结果'), value: <Tag color="green">{t('settingsBasic.testSuccess', null, '连接成功')}</Tag> },
{ label: t('settingsBasic.model', null, '模型'), value: payload.model || '—' },
{
label: t('settingsProbe.latency', null, '响应耗时'),
value: payload.latency_ms != null
? t('settingsProbe.milliseconds', { value: payload.latency_ms }, `${payload.latency_ms} 毫秒`)
: '—'
}
];
}
function summarizeContext(t, payload) {
const source = payload.context_source;
const sourceKey = source?.replace(/^omlx_models_(?=max_model_len|context_length|max_context_length)/, 'openai_models_');
const backend = payload.context_backend;
return [
...summarizeTest(t, payload),
{ label: t('settingsProbe.window', null, '上下文窗口'), value: payload.context_window ?? '—' },
{
label: t('settingsProbe.backend', null, '模型接口类型'),
value: backend === 'openai_compatible'
? t('settingsProbe.compatible', null, '兼容 OpenAI 的接口')
: BACKEND_NAMES[backend] || backend || '—'
},
{ label: t('settingsProbe.source', null, '窗口信息来源'), value: source ? t('settingsProbe.sources.' + sourceKey, null, source) : '—' },
{ label: t('settingsProbe.profile', null, '上下文配置'), value: profileLabel(t, payload.context_profile) },
{ label: t('settingsProbe.effectiveBudget', null, '实际可用上下文令牌数'), value: payload.effective_max_total_tokens ?? '—' }
];
return rows;
}
function ProbeOutput({ state }) {
@ -84,7 +114,7 @@ function ProbeOutput({ state }) {
type={payload.supported === false ? 'info' : 'danger'}
bordered
closeIcon={null}
description={payload.error || t('settingsBasic.modelsListFailed', '获取模型列表失败')}
description={payload.error || t('settingsBasic.modelsListFailed', null, '获取模型列表失败')}
/>
);
}
@ -92,7 +122,6 @@ function ProbeOutput({ state }) {
return (
<div className="settings-probe-result">
<Space spacing={8}>
<Tag color="green">success</Tag>
<Text>{t('settingsBasic.modelsListSuccess', { count: payload.count ?? models.length }, `已获取 ${payload.count ?? models.length} 个模型`)}</Text>
</Space>
<div className="settings-model-tags">
@ -109,32 +138,41 @@ function ProbeOutput({ state }) {
{payload.success ? (
<KeyValueList
columns={3}
items={[
{ label: 'success', value: <Tag color="green">true</Tag> },
{ label: 'model', value: payload.model || '—' },
{ label: 'latency_ms', value: payload.latency_ms != null ? `${payload.latency_ms} ms` : '—' }
]}
items={summarizeTest(t, payload)}
/>
) : (
<Banner type="danger" bordered closeIcon={null} description={payload.error || '连接失败'} />
<Banner type="danger" bordered closeIcon={null} description={payload.error || t('settingsBasic.testFailed', null, '连接失败')} />
)}
</div>
);
}
if (!payload.success) {
return <Banner type="danger" bordered closeIcon={null} description={payload.error || '连接失败'} />;
return <Banner type="danger" bordered closeIcon={null} description={payload.error || t('settingsBasic.testFailed', null, '连接失败')} />;
}
const warnings = Array.isArray(payload.context_warnings) ? payload.context_warnings : [];
return (
<div className="settings-probe-result">
<KeyValueList columns={3} items={summarizeContext(payload)} />
<KeyValueList columns={3} items={summarizeContext(t, payload)} />
{warnings.length > 0 && (
<Banner
type="warning"
bordered
closeIcon={null}
description={`context_warnings:${warnings.join('、')}`}
description={(
<div>
<Text strong>{t('settingsProbe.warnings', null, '上下文提示')}</Text>
<ul>
{[...new Set(warnings)].map(code => (
<li key={code}>
{Object.hasOwn(CONTEXT_WARNING_KEYS, code)
? t('settingsBasic.' + CONTEXT_WARNING_KEYS[code], null, code)
: t('settingsProbe.unknownWarning', { code }, `收到未识别的上下文提示(${code})`)}
</li>
))}
</ul>
</div>
)}
/>
)}
</div>
@ -154,10 +192,10 @@ export default function ProbePanel({ config, canWrite }) {
}, [channelId, config]);
const channelOptions = useMemo(() => [
{ value: MAIN_CHANNEL, label: t('settings.mainChannel', null, '主模型(openai 段)') },
{ value: MAIN_CHANNEL, label: t('settingsProbe.mainChannel', null, '主模型通道') },
...Object.keys(channels).map(id => ({
value: id,
label: `${id}${id === config.ai?.default_channel ? '(默认)' : ''}`
label: `${id}${id === config.ai?.default_channel ? t('settingsProbe.defaultChannelSuffix', null, '(默认)') : ''}`
}))
], [channels, config.ai?.default_channel, t]);
@ -259,37 +297,39 @@ export default function ProbePanel({ config, canWrite }) {
/>
</label>
<label className="settings-field">
<Text type="tertiary" size="small">provider</Text>
<Text type="tertiary" size="small">{t('settingsBasic.apiProvider', null, 'API 提供商')}</Text>
<Select
value={form.provider}
onChange={value => update('provider', value)}
optionList={PROVIDERS}
optionList={PROVIDERS.map(({ value, key, fallback }) => ({ value, label: t(key, null, fallback) }))}
style={{ width: '100%' }}
/>
</label>
<label className="settings-field settings-field-wide">
<Text type="tertiary" size="small">base_url</Text>
<Text type="tertiary" size="small">{t('settingsBasic.baseUrl', null, 'API 地址')}</Text>
<Input value={form.base_url} onChange={value => update('base_url', value)} placeholder="https://api.openai.com/v1" />
</label>
<label className="settings-field">
<Text type="tertiary" size="small">model</Text>
<Text type="tertiary" size="small">{t('settingsBasic.model', null, '模型')}</Text>
<Input value={form.model} onChange={value => update('model', value)} placeholder="gpt-4o-mini" />
</label>
<label className="settings-field">
<Text type="tertiary" size="small">api_key</Text>
<Text type="tertiary" size="small">{t('settingsBasic.apiKey', null, 'API 密钥')}</Text>
<Input value={form.api_key} onChange={value => update('api_key', value)} placeholder="********" />
</label>
<label className="settings-field">
<Text type="tertiary" size="small">context_profile</Text>
<Text type="tertiary" size="small">{t('settingsProbe.profile', null, '上下文配置')}</Text>
<Select
value={form.context_profile || ''}
onChange={value => update('context_profile', value)}
optionList={CONTEXT_PROFILES}
optionList={[...new Set([...CONTEXT_PROFILES, form.context_profile || ''])].map(value => ({
value, label: profileLabel(t, value)
}))}
style={{ width: '100%' }}
/>
</label>
<label className="settings-field">
<Text type="tertiary" size="small">max_total_tokens</Text>
<Text type="tertiary" size="small">{t('settingsBasic.maxTotalTokens', null, '最大上下文令牌数')}</Text>
<Input
value={String(form.max_total_tokens ?? '')}
onChange={value => update('max_total_tokens', value)}
@ -297,7 +337,7 @@ export default function ProbePanel({ config, canWrite }) {
/>
</label>
<label className="settings-field">
<Text type="tertiary" size="small">max_completion_tokens</Text>
<Text type="tertiary" size="small">{t('settingsBasic.maxCompletionTokens', null, '最大输出令牌数')}</Text>
<Input
value={String(form.max_completion_tokens ?? '')}
onChange={value => update('max_completion_tokens', value)}
@ -343,7 +383,7 @@ export default function ProbePanel({ config, canWrite }) {
<div className="settings-probe-card">
<Text strong>{t('settings.visionTestTitle', null, '视觉模型连接测试')}</Text>
<Hint>
{t('settings.visionTestHint', { model: vision.model || '—' }, `当前 vision.model:${vision.model || '未配置'};api_key 为空时回退主模型。`)}
{t('settingsProbe.visionHint', { model: vision.model || '—' }, `当前视觉模型 ${vision.model || '—'},未填写密钥时使用主模型配置。`)}
</Hint>
<Space>
<Button size="small" loading={visionBusy} disabled={!canWrite} onClick={testVision}>
@ -355,16 +395,23 @@ export default function ProbePanel({ config, canWrite }) {
<div className="settings-probe-card">
<Text strong>{t('settings.typeSafeTestTitle', null, 'TypeSafe / Jev 审批引擎测试')}</Text>
<Hint>
{t('settings.typeSafeTestHint', null, '读取 hitl.audit_model;Jev 不继承主模型密钥,api_key 必填或沿用已保存值。')}
{t('settingsProbe.auditHint', null, '审计模型使用独立的 API 密钥。可以填写新密钥,也可以沿用已保存的密钥。')}
</Hint>
<div className="settings-probe-inline">
<Input value={typeSafe.base_url} onChange={value => setTypeSafe(s => ({ ...s, base_url: value }))} placeholder="https://api.typesafe.ai" />
<Input value={typeSafe.api_key} onChange={value => setTypeSafe(s => ({ ...s, api_key: value }))} placeholder="********" />
<Input value={typeSafe.model} onChange={value => setTypeSafe(s => ({ ...s, model: value }))} placeholder="jev-latest" />
{[
['base_url', 'baseUrl', 'API 地址', 'https://api.typesafe.ai'],
['api_key', 'apiKey', 'API 密钥', '********'],
['model', 'model', '模型', 'jev-latest']
].map(([field, key, fallback, placeholder]) => (
<label key={field} className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.' + key, null, fallback)}</Text>
<Input value={typeSafe[field]} onChange={value => setTypeSafe(current => ({ ...current, [field]: value }))} placeholder={placeholder} />
</label>
))}
</div>
<Space>
<Button size="small" loading={typeSafeBusy} disabled={!canWrite} onClick={testTypeSafe}>
{t('settings.hitl.testAuditModel', null, '测试审计模型')}
{t('settingsProbe.testAuditModel', null, '测试审计模型')}
</Button>
</Space>
<ProbeOutput state={typeSafeState} />

View File

@ -384,10 +384,11 @@ export default function StorageSection() {
columns={3}
items={[
{ label: t('settingsStorage.colUnits', null, '项目数'), value: formatNumber(report.dry_run ? report.totals?.reclaimable_units : report.totals?.removed_units) },
{ label: report.dry_run ? t('settingsStorage.reclaimable', null, '可回收') : 'freed', value: formatBytes(report.dry_run ? report.totals?.reclaimable_bytes : report.totals?.freed_bytes) },
{ label: 'errors', value: formatNumber(report.totals?.errors) },
{ label: 'skipped_active', value: formatNumber(report.totals?.skipped_active) },
{ label: 'duration_ms', value: formatNumber(report.duration_ms) }
{ label: report.dry_run ? t('settingsStorage.reclaimable', null, '可回收') : t('settingsDisplay.freed', null, '已释放空间'), value: formatBytes(report.dry_run ? report.totals?.reclaimable_bytes : report.totals?.freed_bytes) },
{ label: t('settingsDisplay.errors', null, '错误数'), value: formatNumber(report.totals?.errors) },
{ label: t('settingsStorage.skippedActive', null, '跳过活跃'), value: formatNumber(report.totals?.skipped_active) },
{ label: t('settingsDisplay.cleanupDuration', null, '清理耗时'),
value: t('settingsProbe.milliseconds', { value: formatNumber(report.duration_ms ?? 0) }, `${formatNumber(report.duration_ms ?? 0)} 毫秒`) }
]}
/>
{(report.categories || []).filter(item => item.errors?.length).length > 0 && (

View File

@ -26,20 +26,20 @@ function cacheRate(summary) {
}
const BREAKDOWN_COLUMNS = [
{ key: 'events', title: 'events' },
{ key: 'modelCalls', title: 'modelCalls' },
{ key: 'promptTokens', title: 'prompt' },
{ key: 'completionTokens', title: 'completion' },
{ key: 'totalTokens', title: 'total' },
{ key: 'cachedTokens', title: 'cached' }
['events', 'settingsDisplay.events', '记录数'],
['modelCalls', 'dashboard.usageCalls', '模型调用'],
['promptTokens', 'dashboard.usageInput', '输入令牌'],
['completionTokens', 'dashboard.usageOutput', '输出令牌'],
['totalTokens', 'dashboard.usageTotal', '总令牌数'],
['cachedTokens', 'dashboard.usageCacheRead', '缓存读取']
];
function breakdownColumns(firstTitle) {
function breakdownColumns(t, firstTitle) {
return [
{ title: firstTitle, dataIndex: 'key', render: (value, row) => <Text strong>{row.label || value || '—'}</Text> },
...BREAKDOWN_COLUMNS.map(column => ({
title: column.title,
dataIndex: column.key,
...BREAKDOWN_COLUMNS.map(([dataIndex, key, fallback]) => ({
title: t(key, null, fallback),
dataIndex,
align: 'right',
render: value => formatNumber(count(value))
}))
@ -120,7 +120,7 @@ export default function TokenUsageSection() {
<Input
value={projectInput}
onChange={value => setProjectInput(value)}
placeholder="project_id(可选)"
placeholder={t('settingsDisplay.projectIdOptional', null, '项目 ID(可选)')}
style={{ width: 180 }}
showClear
/>
@ -143,7 +143,7 @@ export default function TokenUsageSection() {
<SectionCard title={t('tokenUsageUI.trendTitle', null, '每日用量')}>
<DataTable
columns={breakdownColumns(t('tokenUsageUI.colDay', null, '日期'))}
columns={breakdownColumns(t, t('tokenUsageUI.colDay', null, '日期'))}
dataSource={byDay}
rowKey="key"
loading={usage.loading}
@ -154,7 +154,7 @@ export default function TokenUsageSection() {
<SectionCard title={t('tokenUsageUI.modelTitle', null, '按模型')}>
<DataTable
columns={breakdownColumns(t('tokenUsageUI.colModel', null, '模型'))}
columns={breakdownColumns(t, t('tokenUsageUI.colModel', null, '模型'))}
dataSource={byModel}
rowKey="key"
loading={usage.loading}
@ -173,15 +173,15 @@ export default function TokenUsageSection() {
render: value => formatDateTime(value)
},
{ title: t('tokenUsageUI.colModel', null, '模型'), dataIndex: 'model', render: value => value || '—' },
{ title: 'source', dataIndex: 'source', render: value => value || '—' },
{ title: 'orchestration', dataIndex: 'orchestration', render: value => value || '—' },
{ title: t('settingsDisplay.usageSource', null, '用量来源'), dataIndex: 'source', render: value => value || '—' },
{ title: t('settingsDisplay.orchestration', null, '协作方式'), dataIndex: 'orchestration', render: value => value || '—' },
{
title: 'tokens',
title: t('settingsDisplay.tokensBreakdown', null, '输入 / 输出 / 总令牌数'),
align: 'right',
render: (_, row) => `${formatNumber(count(row.promptTokens))} / ${formatNumber(count(row.completionTokens))} / ${formatNumber(count(row.totalTokens))}`
},
{
title: 'conversation',
title: t('settingsDisplay.conversation', null, '对话'),
dataIndex: 'conversationId',
width: 200,
render: value => <Text type="tertiary">{truncate(value || '—', 18)}</Text>

View File

@ -1,11 +1,10 @@
/**
* 一键更新(只读 + 检查更新):GET /system/update、GET /system/update/job、
* POST /system/update/check。应用更新/重启/回滚属于本页面之外的运维动作,这里只展示状态。
* 更新源配置、远端版本检查和更新进度。
*/
import { useCallback, useEffect, useState } from 'react';
import { Banner, Button, Space, Tag, Timeline, Typography } from '@douyinfe/semi-ui';
import { Banner, Button, Input, Space, Tag, Timeline, Typography } from '@douyinfe/semi-ui';
import { IconRefresh, IconSearch } from '@douyinfe/semi-icons';
import { api } from '../../../lib/http';
import { api, errorMessage } from '../../../lib/http';
import { useAuth } from '../../../lib/auth';
import { useT } from '../../../lib/i18n';
import { useInterval, useResource } from '../../../components/hooks';
@ -26,6 +25,13 @@ function yesNo(t, value) {
: <Tag size="small" color="grey">{t('common.no', null, '否')}</Tag>;
}
function jobStateLabel(t, state) {
if (state === 'running') return t('update.stateRunning', null, '进行中');
if (state === 'succeeded') return t('update.stateSucceeded', null, '已完成');
if (state === 'failed') return t('update.stateFailed', null, '失败');
return t('update.stateUnknown', null, '未知状态');
}
function jobStateColor(state) {
if (state === 'succeeded') return 'green';
if (state === 'failed') return 'red';
@ -37,13 +43,16 @@ export default function UpdateSection() {
const t = useT();
const { hasPermission } = useAuth();
const canRead = hasPermission('update:read');
const canCheck = hasPermission('update:apply');
const canManage = hasPermission('update:apply');
const consoleRes = useResource(() => api.get('/system/update'), [canRead], { skip: !canRead });
const [job, setJob] = useState(null);
const [checking, setChecking] = useState(false);
const [checkResult, setCheckResult] = useState(null);
const [checkError, setCheckError] = useState(null);
const [sourceDraft, setSourceDraft] = useState(null);
const [savingSource, setSavingSource] = useState(false);
const [sourceError, setSourceError] = useState(null);
useEffect(() => {
if (consoleRes.data) setJob(consoleRes.data.job || null);
@ -59,32 +68,60 @@ export default function UpdateSection() {
}, []);
const running = job?.state === 'running';
const source = consoleRes.data?.source;
const sourceRepo = source?.repo || '';
const sourceValue = sourceDraft ?? sourceRepo;
const sourceChanged = sourceValue.trim() !== sourceRepo;
const sourceBusy = savingSource || checking || running || consoleRes.loading;
useInterval(pollJob, running ? 2000 : 0);
const check = async () => {
if (!canCheck) return;
if (!canManage || checking || savingSource) return;
setChecking(true);
setCheckError(null);
setCheckResult(null);
try {
const payload = await api.post('/system/update/check', {});
setCheckResult(payload?.status || null);
toastSuccess('已获取远端版本信息');
if (payload?.status && !payload.status.checkError) {
toastSuccess(t('updateUi.checkOk', null, '已获取远端版本信息'));
}
} catch (error) {
setCheckError(error);
toastError(error, t('update.checkFailed', null, '检查更新失败'));
toastError(t('update.checkFailed', { reason: errorMessage(error) }, errorMessage(error)));
} finally {
setChecking(false);
}
};
const saveSource = async event => {
event.preventDefault();
if (!source || !canManage || !sourceChanged || sourceBusy) return;
setSavingSource(true);
setSourceError(null);
try {
const payload = await api.post('/system/update/source', { repo: sourceValue.trim() });
if (!payload?.source || typeof payload.source.repo !== 'string') {
throw new Error(t('updateUi.sourceResponseMissing', null, '服务端未返回更新源,刷新后可核对配置。'));
}
consoleRes.setData(previous => ({ ...previous, source: payload.source }));
setSourceDraft(null);
setCheckResult(null);
setCheckError(null);
toastSuccess(t('update.sourceSaveOk', null, '更新源已保存'));
} catch (error) {
setSourceError(error);
} finally {
setSavingSource(false);
}
};
if (!canRead) {
return <PermissionBanner permission="update:read" label={t('settings.nav.update', null, '读取安装树版本')} />;
}
if (consoleRes.loading && !consoleRes.data) return <LoadingBlock rows={6} />;
const snapshot = checkResult || consoleRes.data?.status || {};
const source = consoleRes.data?.source || {};
const needsRestart = consoleRes.data?.needsRestart;
const binaryBuiltAt = consoleRes.data?.binaryBuiltAt;
@ -92,14 +129,14 @@ export default function UpdateSection() {
{ label: t('update.root', null, '安装目录'), value: <Mono>{snapshot.root || '—'}</Mono> },
{ label: t('update.gitTree', null, 'Git 安装树'), value: yesNo(t, snapshot.installed) },
{ label: t('update.branch', null, '分支'), value: snapshot.branch || '—' },
{ label: 'repo', value: <Mono>{source.repo || source.defaultRepo || snapshot.repo || '—'}</Mono> },
{ label: t('updateUi.repo', null, '更新源仓库'), value: <Mono>{source?.repo || source?.defaultRepo || snapshot.repo || '—'}</Mono> },
{ label: t('update.commit', null, '当前提交'), value: <Mono>{shortCommit(snapshot.commit)}</Mono> },
{ label: t('update.subject', null, '提交说明'), value: truncate(snapshot.subject || '—', 80) },
{ label: t('update.committedAt', null, '提交时间'), value: snapshot.committedAt ? formatDateTime(snapshot.committedAt) : '—' },
{ label: t('update.runningBuild', null, '运行构建'), value: consoleRes.data?.buildRevision ? shortCommit(consoleRes.data.buildRevision) : '—' },
{ label: 'Go 工具链', value: yesNo(t, snapshot.canBuild) },
{ label: '已构建二进制', value: yesNo(t, snapshot.hasBinary) },
{ label: 'buildPending', value: yesNo(t, snapshot.buildPending) },
{ label: t('update.toolchainFound', null, 'Go 工具链'), value: yesNo(t, snapshot.canBuild) },
{ label: t('update.binaryPresent', null, '已构建二进制'), value: yesNo(t, snapshot.hasBinary) },
{ label: t('updateUi.buildPending', null, '待编译'), value: yesNo(t, snapshot.buildPending) },
{
label: t('update.restartPending', null, '需重启激活'),
value: needsRestart
@ -107,8 +144,8 @@ export default function UpdateSection() {
{binaryBuiltAt && <Text type="tertiary" size="small">{formatDateTime(binaryBuiltAt)}</Text>}</Space>
: <Tag size="small" color="green">{t('common.no', null, '否')}</Tag>
},
{ label: 'localChanges', value: formatNumber((snapshot.localChanges || []).length) },
{ label: 'blockingChanges', value: formatNumber((snapshot.blockingChanges || []).length) }
{ label: t('updateUi.localChanges', null, '本机改动文件数'), value: formatNumber((snapshot.localChanges || []).length) },
{ label: t('updateUi.blockingChanges', null, '阻止更新的文件数'), value: formatNumber((snapshot.blockingChanges || []).length) }
];
const incoming = Array.isArray(snapshot.incoming) ? snapshot.incoming : [];
@ -118,10 +155,10 @@ export default function UpdateSection() {
<ErrorBanner error={consoleRes.error} onRetry={consoleRes.reload} />
<SectionCard
title={t('update.installTitle', null, '安装信息')}
description={t('update.intro', null, '这一页只读取安装树版本与更新任务进度;应用更新、重启、回滚不在本页触发。')}
description={t('updateUi.pageHint', null, '查看本机安装和更新进度,管理更新源并检查远端版本。')}
extra={(
<Space>
<Button icon={<IconRefresh />} onClick={consoleRes.reload} loading={consoleRes.loading}>
<Button icon={<IconRefresh />} onClick={consoleRes.reload} loading={consoleRes.loading} disabled={savingSource || checking}>
{t('common.refresh', null, '刷新')}
</Button>
<Button
@ -129,7 +166,7 @@ export default function UpdateSection() {
type="primary"
icon={<IconSearch />}
loading={checking}
disabled={!canCheck}
disabled={!canManage || savingSource}
onClick={check}
>
{t('update.checkBtn', null, '检查更新')}
@ -137,19 +174,55 @@ export default function UpdateSection() {
</Space>
)}
>
{!canCheck && (
{!canManage && (
<Hint>{t('update.checkPermissionHint', null, '检查更新会访问远端仓库,需要 update:apply 权限。')}</Hint>
)}
<KeyValueList items={facts} columns={3} />
{snapshot.goToolchain && (
<Hint>Go 工具链路径:<Mono>{snapshot.goToolchain}</Mono></Hint>
<Hint>{t('updateUi.toolchainPath', null, 'Go 工具链路径')} <Mono>{snapshot.goToolchain}</Mono></Hint>
)}
</SectionCard>
{source && (
<SectionCard title={t('update.sourceTitle', null, '更新源')}>
<form className="settings-update-source-form" onSubmit={saveSource}>
<label className="settings-field">
<Text size="small" type="tertiary">{t('update.sourceUrlLabel', null, '更新源仓库地址')}</Text>
<Input
value={sourceValue}
onChange={value => {
setSourceDraft(value);
setSourceError(null);
}}
placeholder={source.defaultRepo}
readOnly={!canManage}
disabled={savingSource}
/>
</label>
{canManage ? (
<>
<Hint>{t('update.sourceRepoHint', null, '留空即使用官方仓库。')}</Hint>
<Hint>{t('updateUi.sourceSaveOnly', null, '保存会修改配置文件中的 update.repo。')}</Hint>
<div>
<Button htmlType="submit" theme="solid" loading={savingSource}
disabled={!sourceChanged || sourceBusy}>
{t('update.sourceSaveBtn', null, '保存更新源')}
</Button>
</div>
{running && <Hint>{t('update.blockedJobRunning', null, '已有更新在进行中,请等它结束。')}</Hint>}
</>
) : (
<Hint>{t('updateUi.sourcePermission', null, '需要更新管理权限才能在这里保存地址。')}</Hint>
)}
<ErrorBanner error={sourceError} />
</form>
</SectionCard>
)}
<SectionCard title={t('update.remoteTitle', null, '远端版本')}>
<ErrorBanner error={checkError} onRetry={check} />
{!checkResult && !checkError && (
<Text type="tertiary">尚未检查远端版本(GET /system/update 不联网)。</Text>
<Text type="tertiary">{t('updateUi.versionUnchecked', null, '尚未检查远端版本。')}</Text>
)}
{checkResult && (
<>
@ -158,19 +231,19 @@ export default function UpdateSection() {
type="warning"
bordered
closeIcon={null}
description={`${t('update.checkFailed', null, '检查更新失败')}:${checkResult.checkError}`}
description={t('update.checkFailed', { reason: checkResult.checkError }, `检查失败:${checkResult.checkError}`)}
/>
) : (
<Space wrap spacing={8}>
<Tag size="small" color={checkResult.updateAvailable ? 'amber' : 'green'}>
{checkResult.updateAvailable
? t('update.behindCount', { count: checkResult.behind }, `落后 ${checkResult.behind} 个提交`)
: t('update.upToDate', null, '已是最新')}
? t('update.behindCount', { n: checkResult.behind }, `落后 ${checkResult.behind} 个提交`)
: t('update.upToDate', { commit: shortCommit(checkResult.commit) }, '已是最新')}
</Tag>
{checkResult.ahead > 0 && (
<Tag size="small" color="blue">{t('update.aheadCount', { count: checkResult.ahead }, `领先 ${checkResult.ahead} 个提交`)}</Tag>
<Tag size="small" color="blue">{t('update.aheadCount', { n: checkResult.ahead }, `领先 ${checkResult.ahead} 个提交`)}</Tag>
)}
{checkResult.diverged && <Tag size="small" color="red">diverged</Tag>}
{checkResult.diverged && <Tag size="small" color="red">{t('updateUi.diverged', null, '本机与远端提交历史已分叉')}</Tag>}
<Text type="tertiary">
{t('update.remoteHead', null, '远端 HEAD')}:<Mono>{shortCommit(checkResult.remoteCommit)}</Mono>
{checkResult.targetBranch ? `(${checkResult.targetBranch})` : ''}
@ -188,7 +261,7 @@ export default function UpdateSection() {
))}
</ul>
{checkResult.incomingTotal > incoming.length && (
<Hint>{t('update.incomingTruncated', { count: checkResult.incomingTotal }, `共 ${checkResult.incomingTotal} 个提交,仅显示前 ${incoming.length} 个`)}</Hint>
<Hint>{t('update.incomingTruncated', { total: checkResult.incomingTotal, shown: Math.min(10, incoming.length) }, `共 ${checkResult.incomingTotal} 个提交,仅显示前 ${incoming.length} 个`)}</Hint>
)}
</div>
)}
@ -198,7 +271,7 @@ export default function UpdateSection() {
<SectionCard
title={t('update.jobTitle', null, '更新任务进度')}
extra={job ? <Tag size="small" color={jobStateColor(job.state)}>{job.state}</Tag> : null}
extra={job ? <Tag size="small" color={jobStateColor(job.state)}>{jobStateLabel(t, job.state)}</Tag> : null}
>
{!job && <Text type="tertiary">{t('update.noJob', null, '暂无更新任务记录。')}</Text>}
{job && (
@ -206,19 +279,19 @@ export default function UpdateSection() {
<KeyValueList
columns={3}
items={[
{ label: 'id', value: <Mono>{shortCommit(job.id)}</Mono> },
{ label: 'kind', value: job.kind || '—' },
{ label: 'started', value: job.started ? formatDateTime(job.started) : '—' },
{ label: 'finished', value: job.finished ? formatDateTime(job.finished) : '—' },
{ label: 'restartRequested', value: yesNo(t, job.restartRequested) },
{ label: 'restartError', value: job.restartError || '—' }
{ label: t('updateUi.taskId', null, '任务编号'), value: <Mono>{shortCommit(job.id)}</Mono> },
{ label: t('updateUi.kind', null, '任务类型'), value: job.kind ? t('updateUi.kinds.' + job.kind, null, job.kind) : '—' },
{ label: t('updateUi.started', null, '开始时间'), value: job.started ? formatDateTime(job.started) : '—' },
{ label: t('updateUi.finished', null, '结束时间'), value: job.finished ? formatDateTime(job.finished) : '—' },
{ label: t('updateUi.restartRequested', null, '已请求重启'), value: yesNo(t, job.restartRequested) },
{ label: t('updateUi.restartError', null, '重启错误'), value: job.restartError || '—' }
]}
/>
{Array.isArray(job.steps) && job.steps.length > 0 && (
<Timeline className="settings-update-steps">
{job.steps.map((step, index) => (
<Timeline.Item key={`${step.phase}-${index}`}>
<Text strong>{step.phase}</Text>
<Text strong>{t('updateUi.phases.' + step.phase, null, step.phase)}</Text>
<div><Text type="tertiary" size="small">{truncate(step.message || '', 160)}</Text></div>
<Text type="tertiary" size="small">{step.at ? formatDateTime(step.at) : ''}</Text>
</Timeline.Item>
@ -229,12 +302,12 @@ export default function UpdateSection() {
<KeyValueList
columns={3}
items={[
{ label: 'fromCommit', value: <Mono>{shortCommit(job.result.fromCommit)}</Mono> },
{ label: 'toCommit', value: <Mono>{shortCommit(job.result.toCommit)}</Mono> },
{ label: 'commits', value: formatNumber(job.result.commits) },
{ label: 'filesTouched', value: formatNumber(job.result.filesTouched) },
{ label: 'keptContent', value: formatNumber((job.result.keptContent || []).length) },
{ label: 'overwritten', value: formatNumber((job.result.overwritten || []).length) }
{ label: t('updateUi.fromCommit', null, '更新前提交'), value: <Mono>{shortCommit(job.result.fromCommit)}</Mono> },
{ label: t('updateUi.toCommit', null, '更新后提交'), value: <Mono>{shortCommit(job.result.toCommit)}</Mono> },
{ label: t('update.resultCommits', null, '并入提交数'), value: formatNumber(job.result.commits) },
{ label: t('update.resultFiles', null, '改动文件数'), value: formatNumber(job.result.filesTouched) },
{ label: t('updateUi.keptContent', null, '保留的本机文件数'), value: formatNumber((job.result.keptContent || []).length) },
{ label: t('updateUi.overwritten', null, '覆盖的文件数'), value: formatNumber((job.result.overwritten || []).length) }
]}
/>
)}

View File

@ -9,7 +9,7 @@ function withEmpty(label, options) {
return [{ value: '', label }, ...options];
}
export default function FilterBar({ t, filters, options, projectOptions, onChange, onReset }) {
export default function FilterBar({ t, filters, options, projectOptions, hasGroupFilters, onChange, onReset }) {
const [keyword, setKeyword] = useState(filters.q);
const debounced = useDebounced(keyword, 380);
const lastEmitted = useRef(filters.q);
@ -102,7 +102,7 @@ export default function FilterBar({ t, filters, options, projectOptions, onChang
<Button
icon={<IconRefresh />}
theme="borderless"
disabled={!hasActiveFilters(filters) && !filters.sort}
disabled={!hasActiveFilters(filters) && !filters.sort && !hasGroupFilters}
onClick={onReset}
>
{t('vulnerabilityPage.clearAll', null, '重置全部')}

View File

@ -0,0 +1,102 @@
import { useEffect, useMemo, useState } from 'react';
import { Input, Spin, Tag, Tree, Typography } from '@douyinfe/semi-ui';
import { IconSearch } from '@douyinfe/semi-icons';
import { SEVERITY_CODES, severityText } from './shared';
const { Text } = Typography;
const severityColors = { critical: 'red', high: 'orange', medium: 'amber', low: 'blue', info: 'grey' };
const NO_EXPANDED_GROUPS = [];
function groupLabel(t, node) {
if (node.key.startsWith('task:')) {
return t('vulnerabilityPage.viewTaskGroup', { id: node.label || node.key.slice(5) });
}
if (node.label) return node.label;
if (node.key.startsWith('host:')) return t('vulnerabilityPage.unknownHost');
if (node.key.startsWith('queue:')) return t('vulnerabilityPage.taskQueueGroup', { id: node.key.slice(6) });
if (node.key.startsWith('assessment:')) return node.key.slice(11);
return t('vulnerabilityPage.viewNoTask');
}
function treeNode(t, node) {
const name = groupLabel(t, node);
return {
key: node.key,
value: node.key,
label: (
<span className="vulnerability-group-node">
<span className="vulnerability-group-name" title={name}>{name}</span>
<Tag size="small" color="grey">{node.count}</Tag>
</span>
),
children: node.children?.map(child => treeNode(t, child))
};
}
export function GroupNavigator({ t, mode, groups, selection, loading, search, onSearch, onSelect }) {
const [keyword, setKeyword] = useState(search);
const [expandedKeys, setExpandedKeys] = useState(null);
const isTask = mode === 'task';
const heading = t(isTask ? 'vulnerabilityPage.viewTask' : 'vulnerabilityPage.viewHost');
const searchLabel = t(isTask ? 'vulnerabilityPage.taskSearch' : 'vulnerabilityPage.hostSearch');
const treeData = useMemo(() => {
const all = t(isTask ? 'vulnerabilityPage.allTasks' : 'vulnerabilityPage.allHosts');
return [{ key: 'all', value: 'all', label: all }, ...groups.map(node => treeNode(t, node))];
}, [t, groups, isTask]);
const selectedParent = groups.find(node => node.children?.some(child => child.key === selection));
const expanded = expandedKeys ?? (selectedParent ? [selectedParent.key] : NO_EXPANDED_GROUPS);
useEffect(() => setKeyword(search), [search]);
useEffect(() => {
if (keyword.trim() === search) return;
const timeout = setTimeout(() => onSearch(keyword.trim()), 350);
return () => clearTimeout(timeout);
}, [keyword, search, onSearch]);
return (
<aside className="vulnerability-group-sidebar" aria-label={heading}>
<Text strong>{heading}</Text>
<Input
prefix={<IconSearch />}
aria-label={searchLabel}
placeholder={searchLabel}
value={keyword}
showClear
onChange={setKeyword}
/>
<Spin spinning={loading} wrapperClassName="vulnerability-group-scroll">
<Tree
aria-label={heading}
treeData={treeData}
value={selection || 'all'}
onSelect={key => onSelect(key === 'all' ? '' : key)}
expandedKeys={expanded}
onExpand={setExpandedKeys}
expandAction={false}
blockNode
/>
{!groups.length && !loading && (
<Text className="vulnerability-group-empty" type="tertiary" size="small">
{t('vulnerabilityPage.noMatchingGroups')}
</Text>
)}
</Spin>
</aside>
);
}
export function GroupOverview({ t, group }) {
return (
<div className="vulnerability-group-overview">
<Text strong className="vulnerability-group-name">{groupLabel(t, group)}</Text>
<div className="vulnerability-group-badges">
{SEVERITY_CODES.filter(code => group.severities?.[code]).map(code => (
<Tag key={code} color={severityColors[code]}>
{severityText(t, code)} {group.severities[code]}
</Tag>
))}
<Tag color="grey">{t('vulnerabilityPage.groupPending', { count: group.pending })}</Tag>
</div>
</div>
);
}

View File

@ -4,7 +4,7 @@
*/
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Button, Typography } from '@douyinfe/semi-ui';
import { Button, RadioGroup, Typography } from '@douyinfe/semi-ui';
import { IconPlus, IconRefresh } from '@douyinfe/semi-icons';
import { api, downloadFile } from '../../lib/http';
import { useAuth } from '../../lib/auth';
@ -15,6 +15,7 @@ import {
confirmAction, toastError, toastSuccess, toastWarning
} from '../../components/ui';
import FilterBar from './FilterBar';
import { GroupNavigator, GroupOverview } from './GroupNavigator';
import VulnTable from './List';
import DetailDrawer from './DetailDrawer';
import EditModal from './EditModal';
@ -27,6 +28,8 @@ import './page.css';
const { Text } = Typography;
const SEVERITY_TONE = { critical: 'danger', high: 'warning' };
const VIEWS = { none: 'viewList', host: 'viewHost', task: 'viewTask' };
const EMPTY_GROUPS = [];
export default function VulnerabilitiesPage() {
const t = useT();
@ -50,6 +53,12 @@ export default function VulnerabilitiesPage() {
? Number(params.get('page_size'))
: DEFAULT_PAGE_SIZE;
const detailId = (params.get('id') || '').trim();
const viewParam = params.get('group_by');
const groupView = viewParam === 'host' || viewParam === 'task' ? viewParam : '';
const groupSelection = groupView ? params.get('selection') || '' : '';
const groupSearchKey = groupView === 'task' ? 'task_q' : 'host_q';
const groupSearch = groupView ? params.get(groupSearchKey) || '' : '';
const groupSearchQuery = groupSearch ? { [groupSearchKey]: groupSearch } : {};
const canWrite = hasPermission('vulnerability:write');
const canDelete = hasPermission('vulnerability:delete') || canWrite;
@ -71,28 +80,50 @@ export default function VulnerabilitiesPage() {
}, [patchParams]);
const resetFilters = useCallback(() => {
const patch = { sort: undefined };
const patch = { sort: undefined, selection: undefined, host_q: undefined, task_q: undefined };
FILTER_KEYS.forEach(key => { patch[key] = undefined; });
patchParams(patch, { resetPage: true });
}, [patchParams]);
const changeGroupView = useCallback(view => {
patchParams({
group_by: view === 'none' ? undefined : view,
selection: undefined,
host_q: undefined,
task_q: undefined
}, { resetPage: true });
}, [patchParams]);
const selectGroup = useCallback(value => {
patchParams({ selection: value }, { resetPage: true });
}, [patchParams]);
const searchGroups = useCallback(value => {
patchParams({ [groupSearchKey]: value, selection: undefined }, { resetPage: true });
}, [groupSearchKey, patchParams]);
const openDetail = useCallback(id => patchParams({ id }), [patchParams]);
const closeDetail = useCallback(() => patchParams({ id: undefined }), [patchParams]);
// 列表只要摘要字段(handler 的 summary=true),详情/编辑另行按 id 取全量。
const listQuery = useMemo(() => ({
const listQuery = {
...filterQuery(filters),
...groupSearchQuery,
...(groupView ? { group_by: groupView, pagination: 'records', selection: groupSelection } : {}),
...(filters.sort ? { sort: filters.sort } : {}),
summary: 'true',
page,
limit: pageSize
}), [filters, page, pageSize]);
};
const listKey = JSON.stringify(listQuery);
// 把请求键随响应带回,避免用上一条筛选的响应纠正地址栏页码。
const list = useResource(async () => {
const payload = await api.get('/vulnerabilities', listQuery);
return { ...(payload || {}), __requestKey: listKey };
return { ...(payload || {}), __requestKey: listKey, __groupView: groupView };
}, [listKey]);
const listData = list.data?.__requestKey === listKey ? list.data : null;
const groups = list.data?.__groupView === groupView ? list.data?.navigation || EMPTY_GROUPS : EMPTY_GROUPS;
const selectedGroup = listData?.selection
? groups.flatMap(group => [group, ...(group.children || [])]).find(group => group.key === listData.selection)
: null;
const statQuery = useMemo(() => statsQuery(filters), [filters]);
const statKey = JSON.stringify(statQuery);
@ -146,11 +177,13 @@ export default function VulnerabilitiesPage() {
// 服务端会把越界页码收敛到最后一页,这里同步回地址栏,刷新后仍能恢复。
useEffect(() => {
const data = list.data;
if (!data || data.__requestKey !== listKey) return;
const serverPage = Number(data.page);
if (serverPage && serverPage !== page) patchParams({ page: serverPage });
}, [list.data, listKey, page, patchParams]);
if (!listData) return;
const patch = {};
const serverPage = Number(listData.page);
if (serverPage && serverPage !== page) patch.page = serverPage;
if (groupSelection && !listData.selection) patch.selection = undefined;
if (Object.keys(patch).length) patchParams(patch);
}, [listData, groupSelection, page, patchParams]);
const reloadList = list.reload;
const reloadStats = stats.reload;
@ -280,6 +313,7 @@ export default function VulnerabilitiesPage() {
try {
const payload = await api.get('/vulnerabilities/export', {
...filterQuery(filters),
...groupSearchQuery,
mode: 'summary',
group_by: 'conversation'
});
@ -302,7 +336,7 @@ export default function VulnerabilitiesPage() {
} finally {
setExporting(false);
}
}, [exporting, filters, t]);
}, [exporting, filters, groupSearchQuery, t]);
const handleDownload = useCallback(async record => {
try {
@ -362,7 +396,7 @@ export default function VulnerabilitiesPage() {
return [totalMetric, ...severityMetrics];
}, [t, statTotal, distinctCount, bySeverity, stats.loading, filters.severity, applyFilter]);
const totalRecords = Number(list.data?.total) || 0;
const totalRecords = Number(listData?.total) || 0;
const rangeStart = totalRecords ? (page - 1) * pageSize + 1 : 0;
const rangeEnd = totalRecords ? Math.min(page * pageSize, totalRecords) : 0;
const summaryText = totalRecords
@ -374,7 +408,7 @@ export default function VulnerabilitiesPage() {
const toolbar = (
<div className="vulnerability-toolbar-left">
<Text type="tertiary">
{selection.length
{listData && selection.length
? t('vulnerabilityPage.selectedCount', { count: selection.length }, `已选 ${selection.length} 项`)
: summaryText}
</Text>
@ -383,13 +417,13 @@ export default function VulnerabilitiesPage() {
size="small"
type="danger"
theme="light"
disabled={!selection.length}
disabled={!listData || !selection.length}
onClick={handleBatchDelete}
>
{t('vulnerabilityPage.batchDelete', null, '批量删除')}
</Button>
)}
{canDelete && hasActiveFilters(filters) && (
{canDelete && !groupSelection && !groupSearch && hasActiveFilters(filters) && (
<Button size="small" type="danger" theme="borderless" onClick={handleDeleteFiltered}>
{t('vulnerabilityPage.deleteFiltered', null, '删除筛选结果')}
</Button>
@ -408,7 +442,7 @@ export default function VulnerabilitiesPage() {
{t('common.refresh', null, '刷新')}
</Button>
<Button onClick={handleExport} loading={exporting}>
{t('vulnerabilityPage.batchExport', null, '批量导出')}
{t(groupSelection ? 'vulnerabilityPage.exportAllGroups' : 'vulnerabilityPage.batchExport')}
</Button>
{canWrite && (
<Button theme="solid" type="primary" icon={<IconPlus />} onClick={() => openEditor(null)}>
@ -424,39 +458,67 @@ export default function VulnerabilitiesPage() {
<ErrorBanner error={pageError} onRetry={refreshAll} />
<SectionCard
className="vulnerability-list-card"
title={t('vulnerabilityPage.listTitle', null, '漏洞记录')}
description={t('vulnerabilityPage.listHint', null, '按筛选条件服务端分页加载,点击行查看详情、复现证据与报告下载。')}
extra={(
<RadioGroup
aria-label={t('vulnerabilityPage.viewLabel')}
type="button"
value={groupView || 'none'}
options={Object.entries(VIEWS).map(([value, key]) => ({ value, label: t(`vulnerabilityPage.${key}`) }))}
onChange={event => changeGroupView(event.target.value)}
/>
)}
>
<FilterBar
t={t}
filters={filters}
options={options.data}
projectOptions={projectOptions}
hasGroupFilters={Boolean(groupSelection || groupSearch)}
onChange={applyFilter}
onReset={resetFilters}
/>
<VulnTable
t={t}
data={list.data?.vulnerabilities}
loading={list.loading}
page={page}
pageSize={pageSize}
total={totalRecords}
selection={selection}
onSelectionChange={setSelection}
onOpen={openDetail}
onEdit={openEditor}
onDelete={handleDelete}
onDownload={handleDownload}
sort={filters.sort}
onSort={value => applyFilter('sort', value)}
canWrite={canWrite}
canDelete={canDelete}
onPageChange={handlePageChange}
onPageSizeChange={handlePageSizeChange}
toolbar={toolbar}
onRefresh={refreshAll}
/>
<div className={groupView ? 'vulnerability-group-layout' : undefined}>
{groupView && (
<GroupNavigator
key={groupView}
t={t}
mode={groupView}
groups={groups}
selection={groupSelection}
search={groupSearch}
loading={list.loading}
onSearch={searchGroups}
onSelect={selectGroup}
/>
)}
<div className="vulnerability-group-results">
{selectedGroup && <GroupOverview t={t} group={selectedGroup} />}
<VulnTable
t={t}
data={listData?.vulnerabilities}
loading={list.loading}
page={page}
pageSize={pageSize}
total={totalRecords}
selection={listData ? selection : []}
onSelectionChange={setSelection}
onOpen={openDetail}
onEdit={openEditor}
onDelete={handleDelete}
onDownload={handleDownload}
sort={filters.sort}
onSort={value => applyFilter('sort', value)}
canWrite={canWrite}
canDelete={canDelete}
onPageChange={handlePageChange}
onPageSizeChange={handlePageSizeChange}
toolbar={toolbar}
onRefresh={refreshAll}
/>
</div>
</div>
</SectionCard>
<DetailDrawer

View File

@ -2,6 +2,69 @@
.vulnerability-page { min-width: 0; }
.vulnerability-list-card .semi-card-header {
flex-wrap: wrap;
gap: 10px;
}
.vulnerability-group-layout {
display: grid;
grid-template-columns: minmax(215px, 245px) minmax(0, 1fr);
align-items: start;
gap: 16px;
}
.vulnerability-group-sidebar {
display: grid;
gap: 10px;
min-width: 0;
padding: 12px;
background: var(--semi-color-fill-0);
border: 1px solid var(--semi-color-border);
border-radius: var(--semi-border-radius-medium);
}
.vulnerability-group-scroll {
min-height: 46px;
max-height: min(52vh, 520px);
overflow: auto;
overscroll-behavior: contain;
}
.vulnerability-group-node,
.vulnerability-group-overview,
.vulnerability-group-badges {
display: flex;
align-items: center;
gap: 8px;
}
.vulnerability-group-node,
.vulnerability-group-overview { justify-content: space-between; }
.vulnerability-group-scroll .semi-tree-label-text,
.vulnerability-group-results { min-width: 0; }
.vulnerability-group-scroll .semi-tree-label-text { flex: 1; }
.vulnerability-group-name {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.vulnerability-group-node .semi-tag { flex-shrink: 0; }
.vulnerability-group-empty { display: block; padding: 8px; }
.vulnerability-group-overview {
flex-wrap: wrap;
padding: 9px 12px;
margin-bottom: 10px;
background: var(--semi-color-primary-light-default);
border-radius: var(--semi-border-radius-medium);
}
.vulnerability-group-badges { flex-wrap: wrap; }
/* ── 筛选栏 ───────────────────────────────────────────── */
.vulnerability-filter-bar {
display: flex;
@ -257,6 +320,8 @@
}
@media (max-width: 960px) {
.vulnerability-group-layout { grid-template-columns: minmax(0, 1fr); }
.vulnerability-group-scroll { max-height: 210px; }
.vulnerability-filter-select,
.vulnerability-filter-select--wide { width: calc(50% - 4px); }
.vulnerability-filter-search { max-width: none; }

View File

@ -0,0 +1,111 @@
import { test, expect, ready, UI_PERMISSIONS } from './fixtures.mjs';
const currentRepo = 'https://example.test/team/current.git';
const newRepo = 'https://example.test/team/mirror.git';
const defaultRepo = 'https://example.test/default/project.git';
function mockUpdateStatus(mockApi) {
mockApi.respond('GET', '/api/system/update', { json: {
status: { installed: true, buildPending: false, localChanges: [], blockingChanges: [] },
source: { repo: currentRepo, configured: true, defaultRepo }
} });
}
test.describe('model probe localization', () => {
test.use({ appPermissions: [...UI_PERMISSIONS, 'config:write'] });
test('Chinese field names and probe diagnostics retain their meaning when the language changes', async ({ page, mockApi }) => {
mockApi.respond('GET', '/api/config', { json: {
ai: { default_channel: 'fixture-channel', channels: {
'fixture-channel': {
provider: 'openai_compatible', base_url: 'https://example.test/models',
model: 'fixture-model', api_key: '********', max_total_tokens: 100000
}
} },
vision: { model: 'fixture-vision' }, tools: []
} });
mockApi.respond('POST', '/api/config/test-openai', { json: {
success: true, model: 'fixture-model', latency_ms: 961,
context_backend: 'openai_compatible', context_warnings: ['context_window_unknown']
} });
mockApi.respond('POST', '/api/config/test-vision', { json: {
success: true, model: 'fixture-vision', latency_ms: 994
} });
await page.goto('/static/app/#/settings?section=models');
const main = await ready(page);
const probe = main.locator('.cs-section-card').filter({ has: page.locator('.settings-probe-form') });
await expect(probe.getByLabel('API 地址', { exact: true }).first()).toHaveValue('https://example.test/models');
await expect(probe.getByText('最大输出令牌数', { exact: true })).toBeVisible();
await probe.getByRole('button', { name: '测试连接', exact: true }).click();
await probe.getByRole('button', { name: '测试视觉模型', exact: true }).click();
await expect(probe.getByRole('cell', { name: /响应耗时.*961 毫秒/ })).toBeVisible();
await expect(probe.getByText('连接成功', { exact: true })).toHaveCount(2);
await expect(probe.getByText('961 毫秒', { exact: true })).toBeVisible();
await expect(probe.getByText('994 毫秒', { exact: true })).toBeVisible();
await expect(probe.getByText('未检测到上下文窗口,请手动填写', { exact: true })).toBeVisible();
await expect(probe.getByText(/context_warnings|context_window_unknown|latency_ms/)).toHaveCount(0);
expect(mockApi.calls('POST', '/api/config/test-openai')[0].body).toMatchObject({
provider: 'openai_compatible', base_url: 'https://example.test/models',
model: 'fixture-model', api_key: '********', max_total_tokens: 100000
});
await page.getByRole('button', { name: 'zh-CN', exact: true }).click();
await page.getByText('English', { exact: true }).click();
await expect(probe.getByRole('cell', { name: /Response latency.*961 ms/ })).toBeVisible();
await expect(probe.getByText('961 ms', { exact: true })).toBeVisible();
await expect(probe.getByText('Context notices', { exact: true })).toBeVisible();
});
});
test.describe('update source management', () => {
test.use({ appPermissions: [...UI_PERMISSIONS, 'update:apply'] });
test('save errors keep the draft and clearing the address restores the default without running an update', async ({ page, mockApi }) => {
mockUpdateStatus(mockApi);
await page.goto('/static/app/#/settings?section=update');
const main = await ready(page);
const address = main.getByRole('textbox', { name: '更新源仓库地址' });
await expect(address).toHaveValue(currentRepo);
await expect(main.getByText('待编译', { exact: false }).first()).toBeVisible();
const save = main.getByRole('button', { name: '保存更新源', exact: true });
await expect(save).toBeDisabled();
await address.fill(' ' + newRepo + ' ');
mockApi.fail('POST', '/api/system/update/source', '示例地址暂时无法保存');
await save.click();
await expect(main.getByText('示例地址暂时无法保存', { exact: true })).toBeVisible();
await expect(address).toHaveValue(' ' + newRepo + ' ');
mockApi.respond('POST', '/api/system/update/source', { json: {
source: { repo: newRepo, configured: true, defaultRepo }
} });
await save.click();
await expect(address).toHaveValue(newRepo);
await expect(main.getByText(newRepo, { exact: true })).toBeVisible();
await address.clear();
mockApi.respond('POST', '/api/system/update/source', { json: {
source: { repo: '', configured: false, defaultRepo }
} });
await save.click();
await expect(main.getByText(defaultRepo, { exact: true })).toBeVisible();
await expect(save).toBeDisabled();
expect(mockApi.writes().map(({ path, body }) => [path, body])).toEqual([
['/api/system/update/source', { repo: newRepo }],
['/api/system/update/source', { repo: newRepo }],
['/api/system/update/source', { repo: '' }]
]);
});
});
test('update viewers can read the source and see the server configuration location', async ({ page, mockApi }) => {
mockUpdateStatus(mockApi);
await page.goto('/static/app/#/settings?section=update');
const main = await ready(page);
const address = main.getByRole('textbox', { name: '更新源仓库地址' });
await expect(address).toHaveValue(currentRepo);
await expect(address).toHaveAttribute('readonly', '');
await expect(main.getByRole('button', { name: '保存更新源', exact: true })).toHaveCount(0);
await expect(main.getByText(/配置文件中修改 update\.repo/)).toBeVisible();
expect(mockApi.writes()).toEqual([]);
});

View File

@ -0,0 +1,94 @@
import { expect, label, screenshot, test, visit, VULNERABILITY } from './fixtures.mjs';
const listPath = '/api/vulnerabilities';
const hostKey = 'host:api.example.test';
const taskKey = 'task:example-task';
const finding = index => index === 20 ? VULNERABILITY : {
...VULNERABILITY,
id: `fixture-record-${index}`,
title: `示例漏洞 ${index + 1}`
};
function mockGroupedRecords(mockApi) {
const host = { key: hostKey, label: 'api.example.test', count: 21, severities: { critical: 21 }, pending: 21 };
const domain = { ...host, key: 'domain:example.test', label: 'example.test', children: [host] };
const task = { ...host, key: taskKey, label: 'example-task', count: 1, severities: { critical: 1 }, pending: 1 };
const queue = { ...task, key: 'queue:example-queue', label: '示例任务队列', children: [task] };
mockApi.respond('GET', listPath, (_, url) => {
const params = url.searchParams;
const mode = params.get('group_by');
const selection = params.get('selection') || '';
const limit = Number(params.get('limit'));
const search = params.get(mode === 'host' ? 'host_q' : 'task_q');
const selectedHost = selection === hostKey;
const total = mode === 'host' ? (selectedHost ? 21 : 24) : 1;
const page = Number(params.get('page'));
const start = (page - 1) * limit;
let navigation;
if (mode === 'host') navigation = [domain];
if (mode === 'task') navigation = search === '不存在' ? [] : [queue];
const count = navigation?.length === 0 ? 0 : total;
return { json: {
navigation,
selection: count ? selection : '',
page,
total: count,
total_pages: Math.max(1, Math.ceil(count / limit)),
vulnerabilities: Array.from({ length: Math.min(limit, Math.max(0, count - start)) }, (_, i) => finding(start + i))
} };
});
}
test('domain grouping retains severity, pages records, and opens details with the group selected', async ({ page, mockApi }, testInfo) => {
mockGroupedRecords(mockApi);
const main = await visit(page, 'vulnerabilities?severity=critical');
await main.getByText('按域名', { exact: true }).click();
const tree = main.getByRole('complementary', { name: '按域名' }).getByRole('tree');
await tree.getByRole('treeitem', { name: /example\.test/ }).getByLabel('Expand the tree item').click();
await tree.getByText('api.example.test', { exact: true }).click();
await expect(main.locator('.vulnerability-group-overview')).toContainText('待处理 21');
await expect(main.getByRole('button', { name: '删除筛选结果' })).toHaveCount(0);
await screenshot(page, testInfo, 'vulnerability-domain-view');
await main.getByRole('button', { name: 'Page 2', exact: true }).click();
await expect(main.getByText('显示 21–21 / 共 21 条漏洞', { exact: true })).toBeVisible();
await expect.poll(() => mockApi.calls('GET', listPath).some(call => {
const { group_by, pagination, selection, severity, page } = Object.fromEntries(new URLSearchParams(call.query));
return group_by === 'host' && pagination === 'records' && selection === hostKey && severity === 'critical' && page === '2';
})).toBe(true);
await main.getByText(VULNERABILITY.title, { exact: true }).click();
const drawer = page.getByRole('dialog');
await expect(drawer).toContainText(VULNERABILITY.description);
await drawer.getByRole('button', { name: label('common.close', '关闭'), exact: true }).click();
await expect(tree.getByRole('treeitem', { name: /api\.example\.test/ })).toHaveAttribute('aria-selected', 'true');
await expect(main.getByText(VULNERABILITY.title, { exact: true })).toBeVisible();
await page.reload();
await expect(tree.getByRole('treeitem', { name: /api\.example\.test/ })).toHaveAttribute('aria-selected', 'true');
await expect(main.getByText(VULNERABILITY.title, { exact: true })).toBeVisible();
expect(mockApi.writes()).toEqual([]);
});
test('task grouping searches and resets server filters, and the mobile view fits', async ({ page, mockApi }, testInfo) => {
mockGroupedRecords(mockApi);
await page.setViewportSize({ width: 390, height: 844 });
const main = await visit(page, 'vulnerabilities?group_by=task');
const tree = main.getByRole('complementary', { name: '按任务' }).getByRole('tree');
await tree.getByRole('treeitem', { name: /示例任务队列/ }).getByLabel('Expand the tree item').click();
await tree.getByText('任务 example-task', { exact: true }).click();
await expect(main.locator('.vulnerability-group-overview')).toContainText('任务 example-task');
await screenshot(page, testInfo, 'vulnerability-task-mobile');
expect(await main.evaluate(node => node.scrollWidth)).toBeLessThanOrEqual(391);
await main.getByRole('textbox', { name: '搜索任务、队列或标签…' }).fill('不存在');
await expect(main.getByText('暂无匹配的分组', { exact: true })).toBeVisible();
expect(Object.fromEntries(new URLSearchParams(mockApi.calls('GET', listPath).at(-1).query))).toMatchObject({
group_by: 'task', task_q: '不存在', page: '1'
});
await main.getByRole('button', { name: '重置全部' }).click();
await expect(tree.getByText('示例任务队列', { exact: true })).toBeVisible();
await main.getByText('列表', { exact: true }).click();
await expect(tree).toHaveCount(0);
await expect(main.getByText('示例漏洞 1', { exact: true })).toBeVisible();
expect(new URLSearchParams(mockApi.calls('GET', listPath).at(-1).query).has('group_by')).toBe(false);
expect(mockApi.writes()).toEqual([]);
});

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{A as r,B as i,F as a,H as o,N as s,S as c,at as l,i as u,nt as d,rt as f,vt as p,yt as m}from"./semi-DxL3rPNO.js";import{F as h,I as g,P as _,a as v,b as y,c as b,d as x,f as S,l as C,m as w,p as T,s as E,u as D,x as O,y as k}from"./index-BZm3l2iX.js";var A=e(t(),1),j=e(n(),1),{Text:M}=o;function N(){let e=_(),{hasPermission:t}=h(),n=t(`agents:write`),o=t(`agents:delete`),[N,P]=(0,A.useState)(``),[F,I]=(0,A.useState)(null),[L,R]=(0,A.useState)(null),[z,B]=(0,A.useState)(!1),V=v(()=>g.get(`/multi-agent/markdown-agents`),[]),H=(Array.isArray(V.data?.agents)?V.data.agents:[]).filter(e=>{if(!N)return!0;let t=N.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),U=async e=>{try{I(await g.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){y(e,`读取智能体失败`)}},W=async()=>{let e=await L.form.validate();B(!0);try{await g.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),O(`智能体已保存`),R(null),V.reload()}catch(e){y(e,`保存智能体失败`)}finally{B(!1)}},G=e=>k({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await g.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),O(`已删除`),V.reload()}});return(0,j.jsxs)(`div`,{children:[(0,j.jsx)(T,{title:e(`agents.title`,null,`智能体管理`),description:V.data?.dir?`目录:${V.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,j.jsxs)(s,{children:[(0,j.jsx)(a,{icon:(0,j.jsx)(f,{}),onClick:()=>V.reload(),loading:V.loading,children:`刷新`}),n&&(0,j.jsx)(a,{theme:`solid`,type:`primary`,icon:(0,j.jsx)(l,{}),onClick:()=>R({record:null,form:{}}),children:`新建智能体`})]})}),V.data?.error&&(0,j.jsx)(C,{error:V.data.error}),(0,j.jsxs)(w,{title:`智能体(${H.length})`,children:[(0,j.jsx)(C,{error:V.error,onRetry:()=>V.reload()}),(0,j.jsx)(E,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,j.jsxs)(s,{vertical:!0,spacing:0,align:`start`,children:[(0,j.jsxs)(s,{children:[(0,j.jsx)(M,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,j.jsx)(r,{size:`small`,color:`purple`,children:`编排器`})]}),(0,j.jsx)(M,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,j.jsx)(r,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,j.jsx)(M,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,j.jsxs)(s,{children:[(0,j.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>U(t),children:`详情`}),n&&(0,j.jsx)(a,{size:`small`,theme:`borderless`,icon:(0,j.jsx)(p,{}),onClick:()=>R({record:t,form:{}})}),o&&(0,j.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,j.jsx)(m,{}),onClick:()=>G(t)})]})}],dataSource:H,rowKey:`filename`,loading:V.loading,pagination:{pageSize:20},toolbar:(0,j.jsx)(i,{prefix:(0,j.jsx)(d,{}),value:N,onChange:P,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,j.jsx)(c,{title:L?.record?`编辑智能体`:`新建智能体`,visible:!!L,onCancel:()=>R(null),onOk:W,confirmLoading:z,width:760,children:(0,j.jsxs)(u,{getFormApi:e=>R(t=>t&&{...t,form:e}),initValues:L?.record?{filename:L.record.filename,name:L.record.name,description:L.record.description,kind:L.record.kind||`sub`}:{kind:`sub`},children:[(0,j.jsx)(u.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,j.jsx)(u.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,j.jsx)(u.Input,{field:`description`,label:`描述`}),(0,j.jsx)(u.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,j.jsx)(u.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,j.jsx)(u.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},L?.record?.filename||`new-agent`),(0,j.jsx)(b,{title:F?.name||`智能体详情`,visible:!!F,onCancel:()=>I(null),width:720,children:F&&(0,j.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,j.jsx)(x,{items:[{label:`文件名`,value:F.filename},{label:`ID`,value:F.id},{label:`类型`,value:F.kind},{label:`绑定角色`,value:F.bind_role||`—`},{label:`最大迭代`,value:F.max_iterations??`—`},{label:`工具`,value:Array.isArray(F.tools)&&F.tools.length?F.tools.join(`、`):`—`}]}),(0,j.jsx)(S,{content:F.instruction||F.raw||``}),(0,j.jsx)(D,{value:F.raw||F,title:`原始 Markdown`,collapsed:!0})]})})]})}export{N as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{C as r,I as i,P as a,U as o,V as s,bt as c,i as l,it as u,j as d,ot as f,rt as p,yt as m}from"./semi-CJoSwlZ2.js";import{F as h,I as g,P as _,a as v,b as y,c as b,d as x,f as S,l as C,m as w,p as T,s as E,u as D,x as O,y as k}from"./index-BDLJFuY8.js";var A=e(t(),1),j=e(n(),1),{Text:M}=o;function N(){let e=_(),{hasPermission:t}=h(),n=t(`agents:write`),o=t(`agents:delete`),[N,P]=(0,A.useState)(``),[F,I]=(0,A.useState)(null),[L,R]=(0,A.useState)(null),[z,B]=(0,A.useState)(!1),V=v(()=>g.get(`/multi-agent/markdown-agents`),[]),H=(Array.isArray(V.data?.agents)?V.data.agents:[]).filter(e=>{if(!N)return!0;let t=N.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),U=async e=>{try{I(await g.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){y(e,`读取智能体失败`)}},W=async()=>{let e=await L.form.validate();B(!0);try{await g.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),O(`智能体已保存`),R(null),V.reload()}catch(e){y(e,`保存智能体失败`)}finally{B(!1)}},G=e=>k({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await g.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),O(`已删除`),V.reload()}});return(0,j.jsxs)(`div`,{children:[(0,j.jsx)(T,{title:e(`agents.title`,null,`智能体管理`),description:V.data?.dir?`目录:${V.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,j.jsxs)(a,{children:[(0,j.jsx)(i,{icon:(0,j.jsx)(u,{}),onClick:()=>V.reload(),loading:V.loading,children:`刷新`}),n&&(0,j.jsx)(i,{theme:`solid`,type:`primary`,icon:(0,j.jsx)(f,{}),onClick:()=>R({record:null,form:{}}),children:`新建智能体`})]})}),V.data?.error&&(0,j.jsx)(C,{error:V.data.error}),(0,j.jsxs)(w,{title:`智能体(${H.length})`,children:[(0,j.jsx)(C,{error:V.error,onRetry:()=>V.reload()}),(0,j.jsx)(E,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,j.jsxs)(a,{vertical:!0,spacing:0,align:`start`,children:[(0,j.jsxs)(a,{children:[(0,j.jsx)(M,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,j.jsx)(d,{size:`small`,color:`purple`,children:`编排器`})]}),(0,j.jsx)(M,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,j.jsx)(d,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,j.jsx)(M,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,j.jsxs)(a,{children:[(0,j.jsx)(i,{size:`small`,theme:`borderless`,onClick:()=>U(t),children:`详情`}),n&&(0,j.jsx)(i,{size:`small`,theme:`borderless`,icon:(0,j.jsx)(m,{}),onClick:()=>R({record:t,form:{}})}),o&&(0,j.jsx)(i,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,j.jsx)(c,{}),onClick:()=>G(t)})]})}],dataSource:H,rowKey:`filename`,loading:V.loading,pagination:{pageSize:20},toolbar:(0,j.jsx)(s,{prefix:(0,j.jsx)(p,{}),value:N,onChange:P,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,j.jsx)(r,{title:L?.record?`编辑智能体`:`新建智能体`,visible:!!L,onCancel:()=>R(null),onOk:W,confirmLoading:z,width:760,children:(0,j.jsxs)(l,{getFormApi:e=>R(t=>t&&{...t,form:e}),initValues:L?.record?{filename:L.record.filename,name:L.record.name,description:L.record.description,kind:L.record.kind||`sub`}:{kind:`sub`},children:[(0,j.jsx)(l.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,j.jsx)(l.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,j.jsx)(l.Input,{field:`description`,label:`描述`}),(0,j.jsx)(l.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,j.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,j.jsx)(l.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},L?.record?.filename||`new-agent`),(0,j.jsx)(b,{title:F?.name||`智能体详情`,visible:!!F,onCancel:()=>I(null),width:720,children:F&&(0,j.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,j.jsx)(x,{items:[{label:`文件名`,value:F.filename},{label:`ID`,value:F.id},{label:`类型`,value:F.kind},{label:`绑定角色`,value:F.bind_role||`—`},{label:`最大迭代`,value:F.max_iterations??`—`},{label:`工具`,value:Array.isArray(F.tools)&&F.tools.length?F.tools.join(`、`):`—`}]}),(0,j.jsx)(S,{content:F.instruction||F.raw||``}),(0,j.jsx)(D,{value:F.raw||F,title:`原始 Markdown`,collapsed:!0})]})})]})}export{N as default};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
import{I as e,L as t}from"./index-BZm3l2iX.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};
import{I as e,L as t}from"./index-BDLJFuY8.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,H as n,N as r}from"./semi-DxL3rPNO.js";import{E as i,P as a,k as o}from"./index-BZm3l2iX.js";import"./c2-shared-BbPfxKDp.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=n,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:n,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(r,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(r=>(0,c.jsx)(t,{size:`small`,theme:r.value===e?`solid`:`borderless`,type:r.value===e?`primary`:`tertiary`,onClick:()=>n(r.value),children:o(`c2.${i}.preset${r.value===`all`?`All`:r.value}`,null,r.label)},r.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{I as t,P as n,U as r}from"./semi-CJoSwlZ2.js";import{E as i,P as a,k as o}from"./index-BDLJFuY8.js";import"./c2-shared-BVA2Xv1p.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=r,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:r,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(n,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(n=>(0,c.jsx)(t,{size:`small`,theme:n.value===e?`solid`:`borderless`,type:n.value===e?`primary`:`tertiary`,onClick:()=>r(n.value),children:o(`c2.${i}.preset${n.value===`all`?`All`:n.value}`,null,n.label)},n.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{A as r,B as i,F as a,H as o,N as s,nt as c,rt as l,yt as u}from"./semi-DxL3rPNO.js";import{E as d,F as f,I as p,P as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-BZm3l2iX.js";var T=e(t(),1),E=e(n(),1),{Text:D}=o;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[o,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:o||void 0,limit:k}),[o,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await p.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(a,{icon:(0,E.jsx)(l,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(r,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(s,{children:[(0,E.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(u,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(s,{children:[(0,E.jsx)(i,{prefix:(0,E.jsx)(c,{}),placeholder:`按会话 ID 过滤`,value:o,onChange:O,style:{width:260}}),(0,E.jsx)(i,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{I as r,P as i,U as a,V as o,bt as s,it as c,j as l,rt as u}from"./semi-CJoSwlZ2.js";import{E as d,F as f,I as p,P as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-BDLJFuY8.js";var T=e(t(),1),E=e(n(),1),{Text:D}=a;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[a,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:a||void 0,limit:k}),[a,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await p.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(r,{icon:(0,E.jsx)(c,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(l,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(i,{children:[(0,E.jsx)(r,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(r,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(s,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(i,{children:[(0,E.jsx)(o,{prefix:(0,E.jsx)(u,{}),placeholder:`按会话 ID 过滤`,value:a,onChange:O,style:{width:260}}),(0,E.jsx)(o,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{A as r,B as i,F as a,H as o,N as s,S as c,at as l,i as u,nt as d,rt as f,vt as p,yt as m}from"./semi-DxL3rPNO.js";import{F as h,I as g,P as _,a as v,b as y,l as b,m as x,p as S,s as C,x as w,y as T}from"./index-BZm3l2iX.js";var E=e(t(),1),D=e(n(),1),{Text:O}=o;function k(){let e=_(),{hasPermission:t}=h(),n=t(`roles:write`),o=t(`roles:delete`),[k,A]=(0,E.useState)(``),[j,M]=(0,E.useState)(null),[N,P]=(0,E.useState)(!1),F=v(()=>g.get(`/roles`),[]),I=(Array.isArray(F.data?.roles)?F.data.roles:[]).filter(e=>{if(!k)return!0;let t=k.toLowerCase();return[e.name,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),L=async()=>{let e=await j.form.validate();P(!0);try{let t={name:e.name.trim(),description:e.description?.trim()||``,user_prompt:e.user_prompt||``,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean),enabled:e.enabled!==!1},n=j.role?.name;n&&n!==t.name?(await g.post(`/roles`,t),await g.del(`/roles/${encodeURIComponent(n)}`)):n?await g.put(`/roles/${encodeURIComponent(n)}`,t):await g.post(`/roles`,t),w(`角色已保存`),M(null),F.reload()}catch(e){y(e,`保存角色失败`)}finally{P(!1)}},R=e=>T({title:`删除角色「${e.name}」?`,content:`已绑定该角色的对话将失去对应提示词与工具配置。`,onOk:async()=>{await g.del(`/roles/${encodeURIComponent(e.name)}`),w(`已删除`),F.reload()}});return(0,D.jsxs)(`div`,{children:[(0,D.jsx)(S,{title:e(`roles.title`,null,`角色管理`),description:`角色定义对话的系统提示词、可用工具与绑定工作流。`,extra:(0,D.jsxs)(s,{children:[(0,D.jsx)(a,{icon:(0,D.jsx)(f,{}),onClick:()=>F.reload(),loading:F.loading,children:`刷新`}),n&&(0,D.jsx)(a,{theme:`solid`,type:`primary`,icon:(0,D.jsx)(l,{}),onClick:()=>M({role:null,form:{}}),children:`新建角色`})]})}),(0,D.jsxs)(x,{title:`角色(${I.length})`,children:[(0,D.jsx)(b,{error:F.error,onRetry:()=>F.reload()}),(0,D.jsx)(C,{columns:[{title:`角色`,dataIndex:`name`,render:(e,t)=>(0,D.jsxs)(s,{vertical:!0,spacing:0,align:`start`,children:[(0,D.jsxs)(s,{children:[(0,D.jsx)(O,{strong:!0,children:e}),t.enabled===!1&&(0,D.jsx)(r,{size:`small`,color:`grey`,children:`已停用`})]}),(0,D.jsx)(O,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:t.description||`—`})]})},{title:`工具`,dataIndex:`tools`,width:260,render:e=>Array.isArray(e)&&e.length?(0,D.jsxs)(s,{wrap:!0,spacing:4,children:[e.slice(0,4).map(e=>(0,D.jsx)(r,{size:`small`,children:e},e)),e.length>4&&(0,D.jsxs)(O,{type:`tertiary`,children:[`+`,e.length-4]})]}):(0,D.jsx)(O,{type:`tertiary`,children:`未绑定`})},{title:`工作流`,dataIndex:`workflow_id`,width:160,render:e=>e||`—`},{title:`操作`,width:150,render:(e,t)=>(0,D.jsxs)(s,{children:[n&&(0,D.jsx)(a,{size:`small`,theme:`borderless`,icon:(0,D.jsx)(p,{}),onClick:()=>M({role:t,form:{}}),children:`编辑`}),o&&(0,D.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,D.jsx)(m,{}),onClick:()=>R(t)})]})}],dataSource:I,rowKey:`name`,loading:F.loading,pagination:{pageSize:20},toolbar:(0,D.jsx)(i,{prefix:(0,D.jsx)(d,{}),value:k,onChange:A,placeholder:`搜索角色名称`,style:{width:260}})})]}),(0,D.jsx)(c,{title:j?.role?`编辑角色`:`新建角色`,visible:!!j,onCancel:()=>M(null),onOk:L,confirmLoading:N,width:760,children:(0,D.jsxs)(u,{getFormApi:e=>M(t=>t&&{...t,form:e}),initValues:j?.role?{name:j.role.name,description:j.role.description,user_prompt:j.role.user_prompt,tools:Array.isArray(j.role.tools)?j.role.tools.join(`, `):``,enabled:j.role.enabled!==!1}:{enabled:!0},children:[(0,D.jsx)(u.Input,{field:`name`,label:`角色名称`,rules:[{required:!0,message:`请输入角色名称`}]}),(0,D.jsx)(u.Input,{field:`description`,label:`描述`}),(0,D.jsx)(u.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::toolName`}),(0,D.jsx)(u.TextArea,{field:`user_prompt`,label:`用户提示词(追加到用户消息前)`,autosize:{minRows:6,maxRows:18}}),(0,D.jsx)(u.Slot,{label:`启用`,children:(0,D.jsx)(u.Switch,{field:`enabled`})})]})},j?.role?.name||`new-role`)]})}export{k as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{C as r,I as i,P as a,U as o,V as s,bt as c,i as l,it as u,j as d,ot as f,rt as p,yt as m}from"./semi-CJoSwlZ2.js";import{F as h,I as g,P as _,a as v,b as y,l as b,m as x,p as S,s as C,x as w,y as T}from"./index-BDLJFuY8.js";var E=e(t(),1),D=e(n(),1),{Text:O}=o;function k(){let e=_(),{hasPermission:t}=h(),n=t(`roles:write`),o=t(`roles:delete`),[k,A]=(0,E.useState)(``),[j,M]=(0,E.useState)(null),[N,P]=(0,E.useState)(!1),F=v(()=>g.get(`/roles`),[]),I=(Array.isArray(F.data?.roles)?F.data.roles:[]).filter(e=>{if(!k)return!0;let t=k.toLowerCase();return[e.name,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),L=async()=>{let e=await j.form.validate();P(!0);try{let t={name:e.name.trim(),description:e.description?.trim()||``,user_prompt:e.user_prompt||``,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean),enabled:e.enabled!==!1},n=j.role?.name;n&&n!==t.name?(await g.post(`/roles`,t),await g.del(`/roles/${encodeURIComponent(n)}`)):n?await g.put(`/roles/${encodeURIComponent(n)}`,t):await g.post(`/roles`,t),w(`角色已保存`),M(null),F.reload()}catch(e){y(e,`保存角色失败`)}finally{P(!1)}},R=e=>T({title:`删除角色「${e.name}」?`,content:`已绑定该角色的对话将失去对应提示词与工具配置。`,onOk:async()=>{await g.del(`/roles/${encodeURIComponent(e.name)}`),w(`已删除`),F.reload()}});return(0,D.jsxs)(`div`,{children:[(0,D.jsx)(S,{title:e(`roles.title`,null,`角色管理`),description:`角色定义对话的系统提示词、可用工具与绑定工作流。`,extra:(0,D.jsxs)(a,{children:[(0,D.jsx)(i,{icon:(0,D.jsx)(u,{}),onClick:()=>F.reload(),loading:F.loading,children:`刷新`}),n&&(0,D.jsx)(i,{theme:`solid`,type:`primary`,icon:(0,D.jsx)(f,{}),onClick:()=>M({role:null,form:{}}),children:`新建角色`})]})}),(0,D.jsxs)(x,{title:`角色(${I.length})`,children:[(0,D.jsx)(b,{error:F.error,onRetry:()=>F.reload()}),(0,D.jsx)(C,{columns:[{title:`角色`,dataIndex:`name`,render:(e,t)=>(0,D.jsxs)(a,{vertical:!0,spacing:0,align:`start`,children:[(0,D.jsxs)(a,{children:[(0,D.jsx)(O,{strong:!0,children:e}),t.enabled===!1&&(0,D.jsx)(d,{size:`small`,color:`grey`,children:`已停用`})]}),(0,D.jsx)(O,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:t.description||`—`})]})},{title:`工具`,dataIndex:`tools`,width:260,render:e=>Array.isArray(e)&&e.length?(0,D.jsxs)(a,{wrap:!0,spacing:4,children:[e.slice(0,4).map(e=>(0,D.jsx)(d,{size:`small`,children:e},e)),e.length>4&&(0,D.jsxs)(O,{type:`tertiary`,children:[`+`,e.length-4]})]}):(0,D.jsx)(O,{type:`tertiary`,children:`未绑定`})},{title:`工作流`,dataIndex:`workflow_id`,width:160,render:e=>e||`—`},{title:`操作`,width:150,render:(e,t)=>(0,D.jsxs)(a,{children:[n&&(0,D.jsx)(i,{size:`small`,theme:`borderless`,icon:(0,D.jsx)(m,{}),onClick:()=>M({role:t,form:{}}),children:`编辑`}),o&&(0,D.jsx)(i,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,D.jsx)(c,{}),onClick:()=>R(t)})]})}],dataSource:I,rowKey:`name`,loading:F.loading,pagination:{pageSize:20},toolbar:(0,D.jsx)(s,{prefix:(0,D.jsx)(p,{}),value:k,onChange:A,placeholder:`搜索角色名称`,style:{width:260}})})]}),(0,D.jsx)(r,{title:j?.role?`编辑角色`:`新建角色`,visible:!!j,onCancel:()=>M(null),onOk:L,confirmLoading:N,width:760,children:(0,D.jsxs)(l,{getFormApi:e=>M(t=>t&&{...t,form:e}),initValues:j?.role?{name:j.role.name,description:j.role.description,user_prompt:j.role.user_prompt,tools:Array.isArray(j.role.tools)?j.role.tools.join(`, `):``,enabled:j.role.enabled!==!1}:{enabled:!0},children:[(0,D.jsx)(l.Input,{field:`name`,label:`角色名称`,rules:[{required:!0,message:`请输入角色名称`}]}),(0,D.jsx)(l.Input,{field:`description`,label:`描述`}),(0,D.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::toolName`}),(0,D.jsx)(l.TextArea,{field:`user_prompt`,label:`用户提示词(追加到用户消息前)`,autosize:{minRows:6,maxRows:18}}),(0,D.jsx)(l.Slot,{label:`启用`,children:(0,D.jsx)(l.Switch,{field:`enabled`})})]})},j?.role?.name||`new-role`)]})}export{k as default};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
.settings-page{flex-direction:column;min-width:0;display:flex}.settings-tabs .semi-tabs-content{min-width:0;padding-top:0}.settings-tabs .semi-tabs-pane{min-width:0}.settings-tabs .semi-tabs-bar-left{flex:0 0 156px;margin-inline-end:24px}.settings-tabs .semi-tabs-bar-left .semi-tabs-tab{text-align:start;border-radius:8px;margin-bottom:4px;padding:12px 16px;font-size:13px}.settings-tabs .semi-tabs-bar-left .semi-tabs-tab-active{background:var(--semi-color-primary-light-default)}.settings-tabs .semi-tabs-bar-top{margin-bottom:16px}.settings-tabs .semi-tabs-bar-top .semi-tabs-tab{font-size:13px}.settings-loading-block{padding:18px 4px}.settings-hint{color:var(--semi-color-text-2);font-size:12px;line-height:1.6;display:inline-block}.settings-mono{word-break:break-all;font-family:SFMono-Regular,Consolas,Liberation Mono,monospace;font-size:12px}.settings-yaml-toolbar{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:8px;margin-bottom:10px;display:flex}.settings-yaml-input .semi-input-textarea{-moz-tab-size:2;tab-size:2;min-height:420px;font-family:SFMono-Regular,Consolas,Liberation Mono,monospace;font-size:12.5px;line-height:1.6}.settings-yaml-notice{margin-bottom:12px}.settings-schema{flex-direction:column;gap:14px;display:flex}.settings-schema-table{border-collapse:collapse;width:100%;font-size:12.5px}.settings-schema-table th,.settings-schema-table td{border-bottom:1px solid var(--semi-color-border);text-align:left;vertical-align:top;padding:8px 10px}.settings-schema-table th{color:var(--semi-color-text-2);font-weight:600}.settings-probe-form{grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px 16px;display:grid}.settings-field{flex-direction:column;gap:6px;min-width:0;display:flex}.settings-field-wide{grid-column:span 2}.settings-probe-actions{margin-top:14px}.settings-probe-result{flex-direction:column;gap:10px;margin-top:12px;display:flex}.settings-model-tags{flex-wrap:wrap;gap:6px;max-height:190px;padding:2px;display:flex;overflow:auto}.settings-probe-secondary{border-top:1px solid var(--semi-color-border);grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:16px;margin-top:18px;padding-top:16px;display:grid}.settings-probe-card{flex-direction:column;gap:8px;min-width:0;display:flex}.settings-probe-inline{grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;display:grid}.settings-disk{flex-direction:column;gap:6px;max-width:720px;margin-bottom:16px;display:flex}.settings-policy-grid{grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:12px 16px;margin-bottom:10px;display:grid}.settings-incoming{margin-top:12px}.settings-incoming ul{margin:6px 0 0;padding-left:18px;font-size:12.5px;line-height:1.8}.settings-update-steps{max-height:360px;margin-top:16px;padding-right:4px;overflow:auto}.settings-audit-filters{flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:12px;display:flex}.settings-audit-banner{margin-bottom:12px}.settings-audit-detail{flex-direction:column;gap:16px;display:flex}.settings-audit-message-block{border:1px solid var(--semi-color-border);background:var(--semi-color-fill-0);word-break:break-word;border-radius:8px;flex-direction:column;gap:4px;padding:10px 12px;display:flex}.settings-appearance-status{margin-top:12px}@media (max-width:900px){.settings-field-wide{grid-column:span 1}.settings-yaml-input .semi-input-textarea{min-height:300px}}
.settings-page{flex-direction:column;min-width:0;display:flex}.settings-tabs .semi-tabs-content{min-width:0;padding-top:0}.settings-tabs .semi-tabs-pane{min-width:0}.settings-tabs .semi-tabs-bar-left{flex:0 0 156px;margin-inline-end:24px}.settings-tabs .semi-tabs-bar-left .semi-tabs-tab{text-align:start;border-radius:8px;margin-bottom:4px;padding:12px 16px;font-size:13px}.settings-tabs .semi-tabs-bar-left .semi-tabs-tab-active{background:var(--semi-color-primary-light-default)}.settings-tabs .semi-tabs-bar-top{margin-bottom:16px}.settings-tabs .semi-tabs-bar-top .semi-tabs-tab{font-size:13px}.settings-loading-block{padding:18px 4px}.settings-hint{color:var(--semi-color-text-2);font-size:12px;line-height:1.6;display:inline-block}.settings-mono{word-break:break-all;font-family:SFMono-Regular,Consolas,Liberation Mono,monospace;font-size:12px}.settings-yaml-toolbar{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:8px;margin-bottom:10px;display:flex}.settings-yaml-input .semi-input-textarea{-moz-tab-size:2;tab-size:2;min-height:420px;font-family:SFMono-Regular,Consolas,Liberation Mono,monospace;font-size:12.5px;line-height:1.6}.settings-yaml-notice{margin-bottom:12px}.settings-schema{flex-direction:column;gap:14px;display:flex}.settings-schema-table{border-collapse:collapse;width:100%;font-size:12.5px}.settings-schema-table th,.settings-schema-table td{border-bottom:1px solid var(--semi-color-border);text-align:left;vertical-align:top;padding:8px 10px}.settings-schema-table th{color:var(--semi-color-text-2);font-weight:600}.settings-probe-form{grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px 16px;display:grid}.settings-field{flex-direction:column;gap:6px;min-width:0;display:flex}.settings-field-wide{grid-column:span 2}.settings-probe-actions{margin-top:14px}.settings-probe-result{flex-direction:column;gap:10px;margin-top:12px;display:flex}.settings-model-tags{flex-wrap:wrap;gap:6px;max-height:190px;padding:2px;display:flex;overflow:auto}.settings-probe-secondary{border-top:1px solid var(--semi-color-border);grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:16px;margin-top:18px;padding-top:16px;display:grid}.settings-probe-card{flex-direction:column;gap:8px;min-width:0;display:flex}.settings-probe-inline{grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;display:grid}.settings-disk{flex-direction:column;gap:6px;max-width:720px;margin-bottom:16px;display:flex}.settings-policy-grid{grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:12px 16px;margin-bottom:10px;display:grid}.settings-incoming{margin-top:12px}.settings-incoming ul{margin:6px 0 0;padding-left:18px;font-size:12.5px;line-height:1.8}.settings-update-steps{max-height:360px;margin-top:16px;padding-right:4px;overflow:auto}.settings-audit-filters{flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:12px;display:flex}.settings-audit-banner{margin-bottom:12px}.settings-audit-detail{flex-direction:column;gap:16px;display:flex}.settings-audit-message-block{border:1px solid var(--semi-color-border);background:var(--semi-color-fill-0);word-break:break-word;border-radius:8px;flex-direction:column;gap:4px;padding:10px 12px;display:flex}.settings-appearance-status{margin-top:12px}@media (max-width:900px){.settings-field-wide{grid-column:span 1}.settings-yaml-input .semi-input-textarea{min-height:300px}}.settings-update-source-form{flex-direction:column;gap:8px;max-width:760px;display:flex}

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,H as n,N as r,rt as i,yt as a}from"./semi-DxL3rPNO.js";import{D as o,F as s,I as c,O as l,P as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-BZm3l2iX.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=n;function S(){let e=u(),{hasPermission:n}=s(),y=n(`skills:delete`),S=f(()=>c.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await c.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await c.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(r,{children:[(0,b.jsx)(t,{icon:(0,b.jsx)(i,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(t,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:l(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,n)=>y&&Number(n.total_calls)>0?(0,b.jsx)(t,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(a,{}),onClick:()=>O(n.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{I as t,P as n,U as r,bt as i,it as a}from"./semi-CJoSwlZ2.js";import{D as o,F as s,I as c,O as l,P as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-BDLJFuY8.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=r;function S(){let e=u(),{hasPermission:r}=s(),y=r(`skills:delete`),S=f(()=>c.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await c.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await c.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(n,{children:[(0,b.jsx)(t,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(t,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:l(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,n)=>y&&Number(n.total_calls)>0?(0,b.jsx)(t,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(i,{}),onClick:()=>O(n.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +0,0 @@
.vulnerability-page{min-width:0}.vulnerability-filter-bar{border-bottom:1px solid var(--semi-color-border);flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:14px;padding-bottom:14px;display:flex}.vulnerability-filter-search{flex:260px;min-width:200px;max-width:380px}.vulnerability-filter-select{width:150px}.vulnerability-filter-select--wide{width:190px}.vulnerability-filter-actions{align-items:center;gap:8px;margin-left:auto;display:flex}.vulnerability-toolbar-left,.vulnerability-table-toolbar{flex-wrap:wrap;align-items:center;gap:10px;display:flex}.vulnerability-sort-select{width:190px}.vulnerability-title-cell{flex-direction:column;gap:2px;min-width:0;display:flex}.vulnerability-title-text{color:var(--semi-color-text-0);text-overflow:ellipsis;white-space:nowrap;font-weight:500;overflow:hidden}.vulnerability-title-meta{color:var(--semi-color-text-2);text-overflow:ellipsis;white-space:nowrap;font-size:12px;overflow:hidden}.vulnerability-target-cell{flex-direction:column;gap:2px;min-width:0;display:flex}.vulnerability-target-text,.vulnerability-target-host{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.vulnerability-target-text{color:var(--semi-color-text-0)}.vulnerability-target-host{color:var(--semi-color-text-2);font-family:SFMono-Regular,Consolas,monospace;font-size:12px}.vulnerability-source-tags{flex-wrap:wrap;gap:4px;display:inline-flex}.vulnerability-time{font-variant-numeric:tabular-nums;color:var(--semi-color-text-1);white-space:nowrap}.vulnerability-inline-code{word-break:break-all;font-family:SFMono-Regular,Consolas,monospace;font-size:12px}.vulnerability-row-actions{flex-wrap:nowrap;align-items:center;gap:2px;display:flex}.vulnerability-detail-drawer .semi-sidesheet-header{border-bottom:1px solid var(--semi-color-border)}.vulnerability-drawer-title{flex-direction:column;gap:4px;min-width:0;display:flex}.vulnerability-drawer-title-text{text-overflow:ellipsis;white-space:nowrap;font-size:15px;font-weight:600;overflow:hidden}.vulnerability-drawer-meta{flex-wrap:wrap;align-items:center;gap:8px;font-size:12px;display:flex}.vulnerability-drawer-loading{justify-content:center;align-items:center;padding:64px 0;display:flex}.vulnerability-section{margin-bottom:18px}.vulnerability-section-head{justify-content:space-between;align-items:center;gap:8px;margin-bottom:6px;display:flex}.vulnerability-section-title{color:var(--semi-color-text-0);font-size:13px;font-weight:600}.vulnerability-section-body{min-width:0}.vulnerability-code{background:var(--semi-color-fill-0);border:1px solid var(--semi-color-border);border-radius:var(--semi-border-radius-medium);white-space:pre-wrap;word-break:break-word;max-height:380px;margin:0;padding:12px;font-family:SFMono-Regular,Consolas,monospace;font-size:12px;line-height:1.6;overflow:auto}.vulnerability-history-item{flex-direction:column;gap:6px;padding-bottom:4px;display:flex}.vulnerability-history-head{flex-wrap:wrap;align-items:center;gap:8px;display:flex}.vulnerability-snapshot{margin-top:4px}.vulnerability-related-row{flex-wrap:wrap;align-items:center;gap:10px;padding:4px 0;display:flex}.vulnerability-related-list{flex-direction:column;gap:6px;margin:0;padding:0;list-style:none;display:flex}.vulnerability-related-item{border:1px solid var(--semi-color-border);border-radius:var(--semi-border-radius-medium);background:var(--semi-color-bg-1);flex-wrap:wrap;align-items:baseline;gap:10px;padding:6px 10px;display:flex}.vulnerability-member-list{flex-wrap:wrap;gap:6px;display:flex}.vulnerability-download-panel{flex-direction:column;align-items:flex-start;gap:12px;padding:4px 0;display:flex}.vulnerability-form-grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:0 14px;display:grid}.vulnerability-field{min-width:0}.vulnerability-field--full{grid-column:1/-1}.vulnerability-modal-loading{justify-content:center;align-items:center;padding:48px 0;display:flex}@media (max-width:960px){.vulnerability-filter-select,.vulnerability-filter-select--wide{width:calc(50% - 4px)}.vulnerability-filter-search{max-width:none}}@media (max-width:640px){.vulnerability-filter-select,.vulnerability-filter-select--wide{width:100%}.vulnerability-form-grid{grid-template-columns:minmax(0,1fr)}.vulnerability-filter-actions{margin-left:0}}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -18,10 +18,10 @@
} catch (error) { /* first paint fallback */ }
})();
</script>
<script type="module" crossorigin src="/static/app/assets/index-BZm3l2iX.js"></script>
<script type="module" crossorigin src="/static/app/assets/index-BDLJFuY8.js"></script>
<link rel="modulepreload" crossorigin href="/static/app/assets/rolldown-runtime-WkwZ5CU-.js">
<link rel="modulepreload" crossorigin href="/static/app/assets/react-QV7DAAIx.js">
<link rel="modulepreload" crossorigin href="/static/app/assets/semi-DxL3rPNO.js">
<link rel="modulepreload" crossorigin href="/static/app/assets/semi-CJoSwlZ2.js">
<link rel="stylesheet" crossorigin href="/static/app/assets/semi-BUXPdXzR.css">
<link rel="stylesheet" crossorigin href="/static/app/assets/index-B_jDLAQv.css">
</head>

View File

@ -2977,8 +2977,11 @@
"taskPagination": "Showing {{start}}–{{end}} of {{total}} task groups",
"recordPagination": "Showing {{start}}–{{end}} of {{total}} findings",
"viewLabel": "Vulnerability view",
"viewList": "List",
"viewHost": "By host",
"viewTask": "By task",
"noMatchingGroups": "No matching groups",
"exportAllGroups": "Export filtered results across all groups",
"viewRaw": "Raw findings",
"viewTaskGroup": "Task {{id}}",
"viewNoTask": "No linked task",
@ -3092,6 +3095,102 @@
"deleteOk": "Deleted",
"deleteFailed": "Delete failed"
},
"settingsDisplay": {
"rawYamlHelp": "Generated from the current server configuration for viewing or bulk editing advanced options. Format and validate checks syntax; Save and apply writes supported changes and attempts to apply them.",
"events": "Records",
"usageSource": "Usage source",
"orchestration": "Orchestration",
"tokensBreakdown": "Input / output / total tokens",
"conversation": "Conversation",
"projectIdOptional": "Project ID (optional)",
"actor": "Actor",
"level": "Log level",
"resourceType": "Resource type",
"resourceAvailable": "Resource accessible",
"session": "Session ID",
"userAgent": "Client identifier",
"details": "Details",
"freed": "Space freed",
"errors": "Errors",
"cleanupDuration": "Cleanup duration"
},
"settingsProbe": {
"result": "Test result",
"latency": "Response latency",
"milliseconds": "{{value}} ms",
"window": "Context window",
"backend": "Model API type",
"source": "Context window source",
"profile": "Context profile",
"effectiveBudget": "Effective context token budget",
"warnings": "Context notices",
"unknownWarning": "Unrecognized context notice ({{code}})",
"defaultChannelSuffix": " (default)",
"compatible": "OpenAI-compatible API",
"mainChannel": "Primary model channel",
"visionHint": "Current vision model: {{model}}. An empty API key uses the primary model configuration.",
"auditHint": "The audit model uses a separate API key. You can enter a new key or keep the saved one.",
"testAuditModel": "Test audit model",
"profiles": {
"default": "Use defaults",
"auto": "Auto-detect",
"local_auto": "Local server (auto-detect)",
"local": "Local model",
"economy": "Reduce input token use",
"custom": "Custom runtime settings"
},
"sources": {
"ollama_ps": "Ollama runtime status",
"ollama_show_num_ctx": "Ollama context settings",
"ollama_show_model_max": "Ollama model specification",
"llamacpp_props": "llama.cpp runtime settings",
"lmstudio_loaded_context": "LM Studio loaded context",
"lmstudio_loaded_instance": "LM Studio loaded model instance",
"lmstudio_loaded_instance_config": "LM Studio instance configuration",
"lmstudio_model_max": "LM Studio model specification",
"openai_models_max_model_len": "Maximum sequence length from the model API",
"openai_models_context_length": "Context length from the model API",
"openai_models_max_context_length": "Maximum context length from the model API",
"omlx_models_status": "oMLX model status"
}
},
"updateUi": {
"pageHint": "View this installation and update progress, manage the update source, and check remote versions.",
"sourceSaveOnly": "Saving changes update.repo in the configuration file. Use Check for updates to read the remote version.",
"sourcePermission": "Saving a URL here requires update management permission. You can also change update.repo in the configuration file the service uses.",
"sourceResponseMissing": "The server did not return the update source. Refresh to verify the configuration.",
"repo": "Update repository",
"buildPending": "Build pending",
"localChanges": "Locally changed files",
"blockingChanges": "Files blocking updates",
"toolchainPath": "Go toolchain path",
"versionUnchecked": "The remote version has not been checked.",
"checkOk": "Remote version details retrieved",
"diverged": "Local and remote histories have diverged",
"taskId": "Job ID",
"kind": "Job type",
"started": "Started at",
"finished": "Finished at",
"restartRequested": "Restart requested",
"restartError": "Restart error",
"fromCommit": "Previous commit",
"toCommit": "New commit",
"keptContent": "Local files kept",
"overwritten": "Files overwritten",
"kinds": {
"apply": "Update",
"adopt": "Connect to update source",
"rollback": "Rollback"
},
"phases": {
"preflight": "Preflight check",
"fetch": "Read update source",
"protect": "Back up local files",
"build": "Build",
"done": "Complete",
"version": "Save version information"
}
},
"settingsBasic": {
"basicTitle": "Basic settings",
"openaiConfig": "AI channel config",
@ -3155,7 +3254,7 @@
"fetchModels": "Fetch list",
"modelsListFetching": "Fetching model list...",
"modelsListSelectPlaceholder": "Select a model",
"modelsListSuccess": "Loaded {count} models — use the dropdown on the right, or type in the input",
"modelsListSuccess": "Retrieved {{count}} models",
"modelsListFailed": "Failed to fetch model list",
"modelsListNeedApiKey": "Please enter API Key first",
"modelsListClaudeHint": "Claude does not support auto model list; enter the model name manually",

View File

@ -2965,8 +2965,11 @@
"taskPagination": "显示 {{start}}–{{end}} / 共 {{total}} 个任务组",
"recordPagination": "显示 {{start}}–{{end}} / 共 {{total}} 条漏洞",
"viewLabel": "漏洞视图",
"viewList": "列表",
"viewHost": "按域名",
"viewTask": "按任务",
"noMatchingGroups": "暂无匹配的分组",
"exportAllGroups": "导出全部分组的筛选结果",
"viewRaw": "原始漏洞",
"viewTaskGroup": "任务 {{id}}",
"viewNoTask": "未关联任务",
@ -3080,6 +3083,102 @@
"deleteOk": "已删除",
"deleteFailed": "删除失败"
},
"settingsDisplay": {
"rawYamlHelp": "由服务端当前配置生成,适合查看或批量修改高级选项。「格式化并校验」只检查语法;「保存并应用」会写入支持的改动并尝试应用。",
"events": "记录数",
"usageSource": "用量来源",
"orchestration": "协作方式",
"tokensBreakdown": "输入 / 输出 / 总令牌数",
"conversation": "对话",
"projectIdOptional": "项目 ID(可选)",
"actor": "操作者",
"level": "日志级别",
"resourceType": "资源类型",
"resourceAvailable": "资源是否可访问",
"session": "会话标识",
"userAgent": "客户端标识",
"details": "详情",
"freed": "已释放空间",
"errors": "错误数",
"cleanupDuration": "清理耗时"
},
"settingsProbe": {
"result": "测试结果",
"latency": "响应耗时",
"milliseconds": "{{value}} 毫秒",
"window": "上下文窗口",
"backend": "模型接口类型",
"source": "窗口信息来源",
"profile": "上下文配置",
"effectiveBudget": "实际可用上下文令牌数",
"warnings": "上下文提示",
"unknownWarning": "收到未识别的上下文提示({{code}})",
"defaultChannelSuffix": "(默认)",
"compatible": "兼容 OpenAI 的接口",
"mainChannel": "主模型通道",
"visionHint": "当前视觉模型 {{model}},未填写密钥时使用主模型配置。",
"auditHint": "审计模型使用独立的 API 密钥。可以填写新密钥,也可以沿用已保存的密钥。",
"testAuditModel": "测试审计模型",
"profiles": {
"default": "使用默认设置",
"auto": "自动识别",
"local_auto": "本地服务(自动识别)",
"local": "本地模型",
"economy": "节省输入令牌",
"custom": "自定义运行参数"
},
"sources": {
"ollama_ps": "Ollama 运行状态",
"ollama_show_num_ctx": "Ollama 上下文设置",
"ollama_show_model_max": "Ollama 模型规格",
"llamacpp_props": "llama.cpp 运行参数",
"lmstudio_loaded_context": "LM Studio 已加载模型的上下文",
"lmstudio_loaded_instance": "LM Studio 已加载的模型实例",
"lmstudio_loaded_instance_config": "LM Studio 模型实例配置",
"lmstudio_model_max": "LM Studio 模型规格",
"openai_models_max_model_len": "模型接口返回的最大序列长度",
"openai_models_context_length": "模型接口返回的上下文长度",
"openai_models_max_context_length": "模型接口返回的最大上下文长度",
"omlx_models_status": "oMLX 模型状态"
}
},
"updateUi": {
"pageHint": "查看本机安装和更新进度,管理更新源并检查远端版本。",
"sourceSaveOnly": "保存会修改配置文件中的 update.repo。检查远端版本请点击「检查更新」。",
"sourcePermission": "需要更新管理权限才能在这里保存地址。也可以在服务实际使用的配置文件中修改 update.repo。",
"sourceResponseMissing": "服务端未返回更新源,刷新后可核对配置。",
"repo": "更新源仓库",
"buildPending": "待编译",
"localChanges": "本机改动文件数",
"blockingChanges": "阻止更新的文件数",
"toolchainPath": "Go 工具链路径",
"versionUnchecked": "尚未检查远端版本。",
"checkOk": "已获取远端版本信息",
"diverged": "本机与远端提交历史已分叉",
"taskId": "任务编号",
"kind": "任务类型",
"started": "开始时间",
"finished": "结束时间",
"restartRequested": "已请求重启",
"restartError": "重启错误",
"fromCommit": "更新前提交",
"toCommit": "更新后提交",
"keptContent": "保留的本机文件数",
"overwritten": "覆盖的文件数",
"kinds": {
"apply": "更新",
"adopt": "接入更新源",
"rollback": "回滚"
},
"phases": {
"preflight": "更新前检查",
"fetch": "读取更新源",
"protect": "备份本机文件",
"build": "编译",
"done": "完成",
"version": "保存版本信息"
}
},
"settingsBasic": {
"basicTitle": "基本设置",
"openaiConfig": "AI 通道配置",
@ -3134,8 +3233,8 @@
"fofaConfigHint": "用于资产发现与导入,仅需配置 API Key。",
"agentConfig": "Agent 配置",
"knowledgeConfig": "知识库配置",
"baseUrl": "Base URL",
"apiKey": "API Key",
"baseUrl": "API 地址",
"apiKey": "API 密钥",
"model": "模型",
"openaiBaseUrlPlaceholder": "https://api.openai.com/v1",
"openaiApiKeyPlaceholder": "输入OpenAI API Key",
@ -3143,14 +3242,14 @@
"fetchModels": "获取列表",
"modelsListFetching": "正在获取模型列表...",
"modelsListSelectPlaceholder": "请选择模型",
"modelsListSuccess": "已加载 {count} 个模型,请用右侧下拉框选择,或继续在左侧输入",
"modelsListSuccess": "已获取 {{count}} 个模型",
"modelsListFailed": "获取模型列表失败",
"modelsListNeedApiKey": "请先填写 API Key",
"modelsListClaudeHint": "Claude 不支持自动获取模型列表,请手动填写",
"maxTotalTokens": "最大上下文 Token 数",
"maxTotalTokens": "最大上下文令牌数",
"maxTotalTokensPlaceholder": "120000",
"maxTotalTokensHint": "内存压缩和攻击链构建共用此配置,默认 120000",
"maxCompletionTokens": "最大输出 Token 数",
"maxCompletionTokens": "最大输出令牌数",
"maxCompletionTokensPlaceholder": "32768",
"maxCompletionTokensHint": "单次模型回复的输出上限,默认 32768",
"contextWindow": "模型上下文窗口(Token)",
@ -3163,7 +3262,7 @@
"contextWarnWindowUnknown": "本地档位未填写窗口,按 32768 估算",
"contextWarnWindowSmall": "窗口小于 16384,带工具的 agent 可能无法稳定运行",
"contextWarnBudgetClamped": "最大上下文预算已按模型窗口收紧",
"contextWarnCompletionClamped": "最大输出 Token 数已按模型窗口收紧",
"contextWarnCompletionClamped": "最大输出令牌数已按模型窗口收紧",
"contextWarnBudgetExceedsWindow": "填写的预算超过模型窗口,运行时会自动收紧",
"contextWarnOllamaV1": "Ollama 的 /v1 接口忽略 num_ctx,请在服务端设置 OLLAMA_CONTEXT_LENGTH 或 Modelfile",
"contextWarnOllamaRuntime": "Ollama 可能按显存把窗口压到模型上限以下,建议启动后查看 ollama ps",