feat(projects): make attack path graphs easier to read

This commit is contained in:
Sycun 2026-11-20 14:26:03 +08:00
parent 229c83f64f
commit 65e6a86c70
55 changed files with 990 additions and 401 deletions

View File

@ -63,50 +63,52 @@ export default function ProjectDetail({ projectId, tab, refreshToken = 0, onTabC
return (
<div className="project-detail">
<ErrorBanner error={errorProp(project.error)} onRetry={project.reload} />
<SectionCard className="project-detail-head">
<div className="project-detail-head-main">
<div className="project-detail-title-row">
<Title heading={4} className="project-detail-title">
{current?.name || t('projects.projectNotFound', null, '项目不存在')}
</Title>
{current?.pinned ? <Tag size="small" color="blue">{t('projects.pinned', null, '置顶')}</Tag> : null}
<Tag size="small" color={(current?.status || 'active') === 'archived' ? 'grey' : 'green'}>
{(current?.status || 'active') === 'archived'
? t('projects.statusArchived', null, '已归档')
: t('projects.statusActive', null, '进行中')}
</Tag>
<div className="project-detail-summary">
<ErrorBanner error={errorProp(project.error)} onRetry={project.reload} />
<SectionCard className="project-detail-head">
<div className="project-detail-head-main">
<div className="project-detail-title-row">
<Title heading={4} className="project-detail-title">
{current?.name || t('projects.projectNotFound', null, '项目不存在')}
</Title>
{current?.pinned ? <Tag size="small" color="blue">{t('projects.pinned', null, '置顶')}</Tag> : null}
<Tag size="small" color={(current?.status || 'active') === 'archived' ? 'grey' : 'green'}>
{(current?.status || 'active') === 'archived'
? t('projects.statusArchived', null, '已归档')
: t('projects.statusActive', null, '进行中')}
</Tag>
</div>
{current?.description
? <Paragraph className="project-detail-desc">{current.description}</Paragraph>
: <Text type="tertiary" size="small">{t('projects.noProjectDescription', null, '暂无项目描述')}</Text>}
<Text type="tertiary" size="small">
{t('projects.updatedPrefix', { time: formatDateTime(current?.updated_at) }, `更新于 ${formatDateTime(current?.updated_at)}`)}
{' · '}ID: <code>{projectId}</code>
</Text>
</div>
{current?.description
? <Paragraph className="project-detail-desc">{current.description}</Paragraph>
: <Text type="tertiary" size="small">{t('projects.noProjectDescription', null, '暂无项目描述')}</Text>}
<Text type="tertiary" size="small">
{t('projects.updatedPrefix', { time: formatDateTime(current?.updated_at) }, `更新于 ${formatDateTime(current?.updated_at)}`)}
{' · '}ID: <code>{projectId}</code>
</Text>
</div>
<Space>
<Button
icon={<IconRefresh />}
theme="borderless"
loading={project.loading || stats.loading}
onClick={() => { project.reload(); stats.reload(); }}
/>
<Button type="primary" disabled={!canWrite} onClick={() => openFactForm('')}>
{t('projects.addFactCta', null, '+ 添加事实')}
</Button>
</Space>
</SectionCard>
<Space>
<Button
icon={<IconRefresh />}
theme="borderless"
loading={project.loading || stats.loading}
onClick={() => { project.reload(); stats.reload(); }}
/>
<Button type="primary" disabled={!canWrite} onClick={() => openFactForm('')}>
{t('projects.addFactCta', null, '+ 添加事实')}
</Button>
</Space>
</SectionCard>
<StatGrid metrics={metrics} columns={4} />
<StatGrid metrics={metrics} columns={4} />
<Tabs
type="line"
tabList={tabList}
activeKey={tab || 'facts'}
onChange={key => onTabChange?.(key)}
className="project-tabs"
/>
<Tabs
type="line"
tabList={tabList}
activeKey={tab || 'facts'}
onChange={key => onTabChange?.(key)}
className="project-tabs"
/>
</div>
{(!tab || tab === 'facts') && (
<FactsPanel

View File

@ -0,0 +1,252 @@
import { useEffect, useRef, useState } from 'react';
import { NODE_COLORS } from './helpers';
const STAGE = { target: 0, infra: 1, auth: 1, finding: 2, chain: 3, exploit: 3, poc: 3, vulnerability: 4 };
const LABEL_WIDTH = 144;
const LABEL_HEIGHT = 23;
const overlaps = (a, b) => a.x < b.x + b.width && b.x < a.x + a.width
&& a.y < b.y + b.height && b.y < a.y + a.height;
function graphPositions(nodes, edges, selectedId) {
const adjacent = new Map(nodes.map(node => [node.id, new Set()]));
const outgoing = new Set();
for (const edge of edges) {
adjacent.get(edge.source).add(edge.target);
adjacent.get(edge.target).add(edge.source);
if (edge.source === selectedId) outgoing.add(edge.target);
}
const stageOf = node => STAGE[node.type] ?? 5;
const stage = node => {
if (!selectedId) return stageOf(node);
if (node.id === selectedId) return 1;
return outgoing.has(node.id) ? 2 : 0;
};
const sorted = [...nodes].sort((a, b) => stageOf(a) - stageOf(b) || a.id.localeCompare(b.id));
const byId = new Map(sorted.map(node => [node.id, node]));
const groups = new Map();
const visited = new Set();
// Keep related branches in the same order across the stage columns.
for (const node of sorted) {
if (visited.has(node.id)) continue;
const queue = [node.id];
visited.add(node.id);
for (const id of queue) {
const key = stage(byId.get(id));
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(id);
for (const neighbor of [...adjacent.get(id)].sort()) {
if (visited.has(neighbor)) continue;
visited.add(neighbor);
queue.push(neighbor);
}
}
}
const positions = new Map();
const rows = Math.max(5, Math.min(32, Math.ceil(Math.sqrt(nodes.length) * 1.25)));
let x = 0;
for (const key of [...groups.keys()].sort((a, b) => a - b)) {
const group = groups.get(key);
const columnSize = Math.ceil(group.length / Math.ceil(group.length / rows));
for (let start = 0; start < group.length; start += columnSize) {
const column = group.slice(start, start + columnSize);
column.forEach((id, index) => positions.set(id, {
x, y: (index - (column.length - 1) / 2) * 63
}));
x += 172;
}
x += 34;
}
return positions;
}
const STYLE = [
{
selector: 'node',
style: { 'background-color': 'data(color)', width: 21, height: 21 }
},
{ selector: 'node[type = "target"]', style: { width: 25, height: 25 } },
{
selector: 'node[type = "missing"]',
style: { 'background-opacity': 0.15, 'border-width': 2, 'border-color': 'data(color)', 'border-style': 'dashed' }
},
{ selector: 'node.current', style: { width: 30, height: 30, 'underlay-color': 'data(color)', 'underlay-opacity': 0.22, 'underlay-padding': 6 } },
{
selector: 'edge',
style: {
width: 1.75, 'line-color': '#8191a9', 'target-arrow-color': '#8191a9',
'target-arrow-shape': 'triangle', 'arrow-scale': 0.9,
'curve-style': 'bezier', opacity: 0.55
}
},
{ selector: 'edge.focused', style: { width: 2, opacity: 0.92 } },
{ selector: 'edge[type = "links_vuln"]', style: { 'line-color': '#d45363', 'target-arrow-color': '#d45363' } },
{ selector: 'edge[confidence = "tentative"]', style: { 'line-style': 'dashed', 'line-dash-pattern': [5, 4] } }
];
function placeLabels(cy, nodes, selectedId, hoveredId, measure) {
const width = cy.width();
const height = cy.height();
const scale = cy.zoom();
const points = cy.nodes().map(element => {
const { x, y } = element.renderedPosition();
return { id: element.id(), x, y, radius: Math.max(3, element.renderedOuterWidth() / 2) };
}).filter(({ x, y }) => x >= 0 && x <= width && y >= 0 && y <= height);
const occupied = points.map(({ x, y, radius }) => ({
x: x - radius - 1, y: y - radius - 1, width: radius * 2 + 2, height: radius * 2 + 2
}));
const priority = ({ id }) => {
if (id === selectedId) return 0;
if (id === hoveredId) return 1;
const type = nodes.get(id).type;
if (type === 'target') return 2;
if (type === 'chain') return 3;
return 4;
};
const labels = [];
for (const point of points.sort((a, b) => priority(a) - priority(b))) {
const { id, x, y, radius } = point;
if (scale < 0.46 && priority(point) > 3) continue;
const node = nodes.get(id);
const title = ((node.label !== '—' && node.label) || node.fact_key || id).replace(/\s+/g, ' ').trim() || id;
const maxWidth = scale < 0.55 && hoveredId !== id && selectedId !== id ? 96 : LABEL_WIDTH;
const boxWidth = Math.min(maxWidth, Math.ceil(measure(title)) + 21);
const center = Math.max(4, Math.min(x - boxWidth / 2, width - boxWidth - 4));
const candidates = [
{ x: center, y: y + radius + 4 },
{ x: center, y: y - radius - LABEL_HEIGHT - 4 },
{ x: x + radius + 5, y: y - LABEL_HEIGHT / 2 },
{ x: x - radius - boxWidth - 5, y: y - LABEL_HEIGHT / 2 }
];
if (!selectedId) candidates.push(...candidates.splice(0, 2));
const box = candidates.map(candidate => ({ ...candidate, width: boxWidth, height: LABEL_HEIGHT }))
.find(rect => rect.x >= 3 && rect.x + rect.width <= width - 3
&& rect.y >= 3 && rect.y + rect.height <= height - 3
&& !occupied.some(other => overlaps(rect, other)));
if (!box) continue;
occupied.push({ x: box.x - 3, y: box.y - 2, width: box.width + 6, height: box.height + 4 });
labels.push({ id, title, box });
}
return labels;
}
export default function FactGraphCanvas({ nodes, edges, selectedId, onSelect, chartRef, label, errorText }) {
const canvas = useRef(null);
const [labels, setLabels] = useState([]);
const [failed, setFailed] = useState(false);
useEffect(() => {
const container = canvas.current;
let disposed = false;
let cy;
let resize;
let frame;
let hoveredId;
let fitted = true;
let fitting = false;
setLabels([]);
setFailed(false);
import('cytoscape').then(({ default: cytoscape }) => {
if (disposed) return;
const byId = new Map(nodes.map(node => [node.id, node]));
const positions = graphPositions(nodes, edges, selectedId);
cy = cytoscape({
container,
elements: [
...nodes.map(node => ({
group: 'nodes',
data: { id: node.id, type: node.type || 'note', color: NODE_COLORS[node.type] || NODE_COLORS.missing },
position: positions.get(node.id),
classes: node.id === selectedId ? 'current' : ''
})),
...edges.map((edge, index) => ({
group: 'edges',
classes: selectedId ? 'focused' : '',
data: { ...edge, id: `edge|${index}|${edge.id || ''}` }
}))
],
style: STYLE,
layout: { name: 'preset', fit: false },
minZoom: 0.006, maxZoom: 3, wheelSensitivity: 0.2,
boxSelectionEnabled: false, autounselectify: true, autoungrabify: true
});
const measure = document.createElement('canvas').getContext('2d');
measure.font = `500 12px ${getComputedStyle(container).fontFamily}`;
const place = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => setLabels(
placeLabels(cy, byId, selectedId, hoveredId, title => measure.measureText(title).width)
));
};
const fit = () => {
fitting = true;
fitted = true;
cy.fit(cy.elements(), Math.min(56, cy.width() / 8));
if (cy.zoom() > 1) cy.zoom(1).center();
fitting = false;
place();
};
chartRef.current = {
fit,
zoom: factor => cy.zoom({
level: cy.zoom() * factor,
renderedPosition: { x: cy.width() / 2, y: cy.height() / 2 }
})
};
cy.on('viewport', () => {
if (!fitting) fitted = false;
place();
});
cy.on('tap', 'node', event => onSelect(event.target.id()));
cy.on('mouseover', 'node', event => { hoveredId = event.target.id(); place(); });
cy.on('mouseout', 'node', () => { hoveredId = undefined; place(); });
let width = cy.width();
let height = cy.height();
resize = new ResizeObserver(() => {
cy.resize();
const nextWidth = cy.width();
const nextHeight = cy.height();
if (width === nextWidth && height === nextHeight) return;
if (fitted) fit();
else cy.panBy({ x: (nextWidth - width) / 2, y: (nextHeight - height) / 2 });
width = nextWidth;
height = nextHeight;
});
resize.observe(container);
fit();
}).catch(() => { if (!disposed) setFailed(true); });
return () => {
disposed = true;
cancelAnimationFrame(frame);
resize?.disconnect();
cy?.destroy();
chartRef.current = null;
};
}, [nodes, edges, selectedId, onSelect, chartRef]);
return (
<div className="project-graph-canvas-wrap" role="group" aria-label={label}>
<div ref={canvas} className="project-graph-canvas" />
<div className="project-graph-labels">
{labels.map(({ id, title, box }) => (
<button
type="button"
className="project-graph-label"
key={id}
title={title}
aria-pressed={id === selectedId}
style={{ left: box.x, top: box.y, width: box.width }}
onClick={() => onSelect(id)}
dir="auto"
>
{title}
</button>
))}
</div>
{failed && <div className="project-graph-overlay" role="alert">{errorText}</div>}
</div>
);
}

View File

@ -1,179 +1,73 @@
/** 事实关系图:cytoscape 动态加载,节点点击展示事实详情。 */
import { useEffect, useMemo, useRef, useState } from 'react';
import { Button, Checkbox, Empty, Input, Select, Space, Tag, Typography } from '@douyinfe/semi-ui';
import { IconRefresh, IconSearch } from '@douyinfe/semi-icons';
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import { Button, Checkbox, Empty, Input, Select, Space, Spin, Tag, Typography } from '@douyinfe/semi-ui';
import { IconMinus, IconPlus, IconRefresh, IconSearch } from '@douyinfe/semi-icons';
import { api } from '../../lib/http';
import { useT } from '../../lib/i18n';
import { useResource } from '../../components/hooks';
import { ErrorBanner, SectionCard, confirmAction, toastError, toastSuccess } from '../../components/ui';
import { CONFIDENCE_META, NODE_COLORS, NODE_TYPE_LABEL, errorProp, errText } from './helpers';
import FactGraphCanvas from './fact-graph-canvas';
const { Text } = Typography;
const EMPTY = [];
const nodeTitle = node => node.summary || node.label || node.fact_key || node.id;
function themeColors(container) {
const styles = getComputedStyle(container);
const read = (name, fallback) => styles.getPropertyValue(name).trim() || fallback;
return {
text: read('--semi-color-text-0', '#1f2329'),
muted: read('--semi-color-text-2', '#646a73'),
border: read('--semi-color-border', '#e5e6eb'),
bg: read('--semi-color-bg-1', '#ffffff')
function GraphSearch({ nodes, onSelect, t }) {
const [query, setQuery] = useState('');
const [open, setOpen] = useState(false);
const resultsId = useId();
const search = query.trim().toLowerCase();
const matches = useMemo(() => nodes.filter(node => !search
|| [node.fact_key, node.label, node.summary, node.category].join(' ').toLowerCase().includes(search)
), [nodes, search]);
const select = id => {
onSelect(id);
setOpen(false);
setQuery('');
};
}
function buildStyle(colors) {
return [
{
selector: 'node',
style: {
'background-color': 'data(color)',
label: 'data(label)',
width: 26,
height: 26,
'font-size': 10,
color: colors.text,
'text-valign': 'bottom',
'text-halign': 'center',
'text-margin-y': 6,
'text-wrap': 'wrap',
'text-max-width': 132,
'border-width': 2,
'border-color': colors.bg,
'text-outline-width': 0
}
},
{
selector: 'node[type = "missing"]',
style: { 'border-style': 'dashed', 'border-color': '#94a3b8' }
},
{
selector: 'node:selected',
style: { 'border-width': 4, 'border-color': '#f59e0b' }
},
{
selector: 'edge',
style: {
width: 1.5,
'line-color': colors.border,
'target-arrow-color': colors.border,
'target-arrow-shape': 'triangle',
'arrow-scale': 0.7,
'curve-style': 'bezier',
'font-size': 8,
color: colors.muted,
label: 'data(type)',
'text-rotation': 'autorotate',
'text-background-color': colors.bg,
'text-background-opacity': 0.85,
'text-background-padding': 1
}
},
{ selector: 'edge[confidence = "tentative"]', style: { 'line-style': 'dashed', 'line-dash-pattern': [4, 3] } },
{ selector: 'edge[type = "links_vuln"]', style: { 'line-color': '#dc2626', 'target-arrow-color': '#dc2626', 'line-style': 'dotted' } }
];
}
function GraphCanvas({ graph, search, onSelect, onReady }) {
const containerRef = useRef(null);
const cyRef = useRef(null);
const selectRef = useRef(onSelect);
const readyRef = useRef(onReady);
const [ready, setReady] = useState(false);
const [importError, setImportError] = useState(null);
selectRef.current = onSelect;
readyRef.current = onReady;
useEffect(() => {
const container = containerRef.current;
if (!container || !graph?.nodes?.length) return undefined;
let cancelled = false;
let instance = null;
setImportError(null);
import('cytoscape')
.then(mod => {
if (cancelled || !containerRef.current) return;
const cytoscape = mod.default || mod;
const colors = themeColors(containerRef.current);
const elements = [
...graph.nodes.map(node => ({
group: 'nodes',
data: {
id: node.id,
label: node.label || node.fact_key,
fact_key: node.fact_key,
type: node.type || 'note',
category: node.category,
confidence: node.confidence,
summary: node.summary,
color: NODE_COLORS[node.type] || NODE_COLORS.missing
}
})),
...(graph.edges || []).map((edge, index) => ({
group: 'edges',
data: {
id: edge.id || `e-${index}`,
source: edge.source,
target: edge.target,
type: edge.type,
confidence: edge.confidence
}
}))
];
instance = cytoscape({
container: containerRef.current,
elements,
style: buildStyle(colors),
layout: { name: 'cose', animate: false, padding: 36, idealEdgeLength: 110, nodeRepulsion: 9000, fit: true },
wheelSensitivity: 0.2,
boxSelectionEnabled: false,
minZoom: 0.2,
maxZoom: 2.5
});
cyRef.current = instance;
instance.on('tap', 'node', event => selectRef.current?.(event.target.data()));
instance.on('tap', event => {
if (event.target === instance) selectRef.current?.(null);
});
readyRef.current?.(instance);
setReady(true);
})
.catch(error => {
if (!cancelled) setImportError(error);
});
return () => {
cancelled = true;
setReady(false);
cyRef.current = null;
readyRef.current?.(null);
if (instance) instance.destroy();
};
}, [graph]);
useEffect(() => {
const cy = cyRef.current;
if (!cy) return;
const query = search.trim().toLowerCase();
cy.batch(() => {
cy.nodes().forEach(node => {
const data = node.data();
const hit = !query || [data.fact_key, data.label, data.summary, data.category]
.join(' ').toLowerCase().includes(query);
node.style('opacity', hit ? 1 : 0.16);
});
});
}, [search, ready, graph]);
return (
<div className="project-graph-canvas-wrap">
<div ref={containerRef} className="project-graph-canvas" />
{importError ? (
<div className="project-graph-overlay">
<Text type="danger">cytoscape 加载失败,请刷新页面重试</Text>
<div className="project-graph-search" onBlur={event => {
if (!event.currentTarget.contains(event.relatedTarget)) setOpen(false);
}}>
<Input
prefix={<IconSearch />}
value={query}
showClear
placeholder={t('projects.graphSearchPlaceholder', null, '搜索节点…')}
aria-label={t('projects.graphSearchSr', null, '搜索节点')}
aria-controls={open ? resultsId : undefined}
onChange={value => { setQuery(value); setOpen(true); }}
onFocus={() => setOpen(true)}
onClick={() => setOpen(true)}
onKeyDown={event => {
if (event.key === 'Escape' && open) setOpen(false);
if (event.key === 'Enter' && open && matches.length && !event.nativeEvent.isComposing) {
event.preventDefault();
select(matches[0].id);
}
}}
/>
{open && (
<div className="project-graph-search-results" id={resultsId}>
<div className="project-graph-search-count" role="status">
{matches.length
? t('projects.graphSearchCount', { count: matches.length }, `${matches.length} 个节点`)
: t('projects.graphNoMatches', null, '未找到匹配节点')}
</div>
{matches.length > 0 && <ul className="project-graph-search-list">
{matches.map(node => (
<li key={node.id}>
<button className="project-graph-search-hit" type="button" onClick={() => select(node.id)}>
<span title={nodeTitle(node)}>{nodeTitle(node)}</span>
<code dir="auto">{node.fact_key || node.id}</code>
</button>
</li>
))}
</ul>}
</div>
) : null}
)}
</div>
);
}
@ -184,25 +78,58 @@ export default function FactGraphPanel({
const t = useT();
const [view, setView] = useState('path');
const [hideDeprecated, setHideDeprecated] = useState(true);
const [search, setSearch] = useState('');
const [selected, setSelected] = useState(null);
const [selectedId, setSelectedId] = useState('');
const [showEdges, setShowEdges] = useState(false);
const cyRef = useRef(null);
const chartRef = useRef(null);
const sideRef = useRef(null);
const scope = `${view}:${hideDeprecated}`;
const graph = useResource(async () => ({
scope,
data: await api.get(`/projects/${projectId}/fact-graph`, {
view, exclude_deprecated: hideDeprecated ? '1' : '0'
})
}), [projectId, scope, revision]);
const graph = useResource(() => api.get(`/projects/${projectId}/fact-graph`, {
view,
exclude_deprecated: hideDeprecated ? '1' : '0'
}), [projectId, view, hideDeprecated, revision]);
const currentGraph = graph.data?.scope === scope ? graph.data.data : null;
const nodes = currentGraph?.nodes || EMPTY;
const byId = useMemo(() => new Map(nodes.map(node => [node.id, node])), [nodes]);
const edges = useMemo(() => (currentGraph?.edges || EMPTY)
.filter(edge => byId.has(edge.source) && byId.has(edge.target)), [currentGraph, byId]);
const nodes = graph.data?.nodes || [];
const edges = graph.data?.edges || [];
const selected = byId.get(selectedId);
useEffect(() => {
if (sideRef.current) sideRef.current.scrollTop = 0;
}, [selected?.id]);
const shownEdges = useMemo(() => selected
? edges.filter(edge => edge.source === selected.id || edge.target === selected.id)
: edges, [edges, selected]);
const shownNodes = useMemo(() => {
if (!selected) return nodes;
const neighborhood = new Set([selected.id]);
for (const edge of shownEdges) {
neighborhood.add(edge.source);
neighborhood.add(edge.target);
}
return nodes.filter(node => neighborhood.has(node.id));
}, [nodes, selected, shownEdges]);
const types = Object.keys(NODE_COLORS).filter(type => shownNodes.some(node => node.type === type));
const typeLabel = type => t(`projects.graphNodeTypes.${type}`, null, NODE_TYPE_LABEL[type] || type);
const openNode = useCallback(id => setSelectedId(id), []);
const edgeList = useResource(
() => (showEdges ? api.get(`/projects/${projectId}/fact-edges`) : Promise.resolve(null)),
[projectId, showEdges, revision]
);
const deleteEdge = (edge) => {
const refresh = () => {
if (onChanged) onChanged();
else {
graph.reload();
if (showEdges) edgeList.reload();
}
};
const deleteEdge = edge => {
confirmAction({
title: t('projects.graphDeleteEdge', null, '删边'),
content: t('projects.confirmDeleteGraphEdge', null, '确定删除此关系边?'),
@ -211,78 +138,161 @@ export default function FactGraphPanel({
try {
await api.del(`/projects/${projectId}/fact-edges/${edge.id}`);
toastSuccess(t('projects.graphEdgeDeleteSuccess', null, '边已删除'));
graph.reload({ silent: true });
edgeList.reload({ silent: true });
onChanged?.();
refresh();
} catch (error) {
toastError(errText(error, t('projects.graphEdgeDeleteFailed', null, '删除边失败')));
}
}
});
};
const stats = (nodeCount, edgeCount) => t(
'projects.graphStats', { nodes: nodeCount, edges: edgeCount }, `${nodeCount} 个节点 · ${edgeCount} 条关系`
);
const selectedEdges = useMemo(() => {
if (!selected) return [];
return edges
.filter(edge => edge.source === selected.id || edge.target === selected.id)
.map(edge => ({
...edge,
outgoing: edge.source === selected.id,
peer: edge.source === selected.id ? edge.target : edge.source
}));
}, [edges, selected]);
useEffect(() => { setSelected(null); }, [projectId, view, hideDeprecated]);
const graphLabel = t('projects.tabGraph', null, '攻击路径');
const factSelected = selected && selected.type !== 'missing' && !selected.id.startsWith('vuln:');
return (
<SectionCard
title={t('projects.tabGraph', null, '攻击路径')}
description={t('projects.graphToolbarHint', null, '攻击路径图箭头与事实存储方向一致(source → target)')}
title={graphLabel}
className="project-graph-card"
extra={(
<Space>
<Text type="tertiary" size="small">
{t('projects.graphStats', { nodes: nodes.length, edges: edges.length }, `节点: ${nodes.length} | 边: ${edges.length}`)}
</Text>
<Button icon={<IconRefresh />} theme="borderless" loading={graph.loading} onClick={() => { graph.reload(); onChanged?.(); }} />
<Text type="tertiary" size="small">{stats(nodes.length, edges.length)}</Text>
<Button
icon={<IconRefresh />}
aria-label={t('common.refresh', null, '刷新')}
theme="borderless"
loading={graph.loading}
onClick={refresh}
/>
</Space>
)}
>
<ErrorBanner error={errorProp(graph.error)} onRetry={graph.reload} />
<div className="project-toolbar">
<div className="project-toolbar project-graph-toolbar">
<Select
value={view}
onChange={setView}
style={{ width: 150 }}
aria-label={t('projects.graphScope', null, '关系范围')}
onChange={next => { setSelectedId(''); setView(next); }}
style={{ width: 134 }}
optionList={[
{ value: 'path', label: t('projects.graphViewPath', null, '攻击路径') },
{ value: 'full', label: t('projects.graphViewFull', null, '完整关系') }
]}
/>
<Input
prefix={<IconSearch />}
value={search}
showClear
placeholder={t('projects.graphSearchPlaceholder', null, '搜索节点…')}
aria-label={t('projects.graphSearchSr', null, '搜索节点')}
onChange={setSearch}
style={{ width: 240 }}
/>
<Checkbox checked={hideDeprecated} onChange={event => setHideDeprecated(event.target.checked)}>
<GraphSearch nodes={nodes} onSelect={openNode} t={t} />
<Checkbox checked={hideDeprecated} onChange={event => {
setSelectedId('');
setHideDeprecated(event.target.checked);
}}>
{t('projects.hideDeprecated', null, '隐藏废弃')}
</Checkbox>
<Button
theme="borderless"
disabled={!graph.data}
onClick={() => cyRef.current?.fit(undefined, 36)}
>
{t('projects.graphCenter', null, '居中')}
</Button>
<Button theme="borderless" onClick={() => setShowEdges(value => !value)}>
{t('projects.graphEdgesTitle', null, '关系边')}({edges.length})
<Button className="project-graph-edges-toggle" aria-expanded={showEdges} onClick={() => setShowEdges(value => !value)}>
{t('projects.graphEdgesTitle', null, '关系边')}
</Button>
</div>
{!graph.loading && !nodes.length ? (
{nodes.length > 0 ? (
<>
<div className="project-graph-status">
{selected ? (
<>
<Button size="small" theme="light" type="primary" onClick={() => setSelectedId('')}>
{t('projects.graphBackToOverview', null, '返回全图')}
</Button>
<Text size="small" aria-live="polite">
{t('projects.graphFocus', { stats: stats(shownNodes.length, shownEdges.length) }, `聚焦直接关系 · ${stats(shownNodes.length, shownEdges.length)}`)}
</Text>
</>
) : (
<Text type="tertiary" size="small">
{t('projects.graphOverviewHint', null, '点选节点查看直接关系,放大后显示更多标签。')}
</Text>
)}
</div>
<div className={`project-graph-layout${selected && shownNodes.length <= 6 ? ' is-compact' : ''}`}>
<div className="project-graph-viewport">
<FactGraphCanvas
nodes={shownNodes}
edges={shownEdges}
selectedId={selected?.id}
onSelect={openNode}
chartRef={chartRef}
label={t('projects.graphCanvas', null, '攻击路径画布')}
errorText={t('projects.graphRenderError', null, '图谱加载失败,请刷新重试。')}
/>
<div className="project-graph-footer">
<div className="project-graph-legend">
{types.map(type => (
<span key={type}>
<i aria-hidden="true" style={{ background: NODE_COLORS[type] }} />
{typeLabel(type)}
</span>
))}
{shownEdges.some(edge => edge.confidence === 'tentative') && (
<span><i className="project-graph-legend-dash" aria-hidden="true" />{t('projects.graphTentativeEdge', null, '待确认关系')}</span>
)}
</div>
<Space spacing={4}>
<Button size="small" icon={<IconMinus />} aria-label={t('projects.graphZoomOut', null, '缩小')} onClick={() => chartRef.current?.zoom(1 / 1.3)} />
<Button size="small" icon={<IconPlus />} aria-label={t('projects.graphZoomIn', null, '放大')} onClick={() => chartRef.current?.zoom(1.3)} />
<Button size="small" onClick={() => chartRef.current?.fit()}>{t('projects.graphFit', null, '适合画布')}</Button>
</Space>
</div>
</div>
{selected && (
<aside ref={sideRef} className="project-graph-side" aria-label={t('projects.graphNodeDetails', null, '节点详情')}>
<div className="project-detail-stack">
<div>
<Text strong>{nodeTitle(selected)}</Text>
<code className="project-graph-node-key" dir="auto">{selected.fact_key || selected.id}</code>
<div className="project-graph-side-tags">
<Tag size="small" color="blue" type="light">{typeLabel(selected.type)}</Tag>
<Tag size="small" color={CONFIDENCE_META[selected.confidence]?.color || 'grey'}>
{CONFIDENCE_META[selected.confidence]
? t(`projects.graphConfidence.${selected.confidence}`, null, CONFIDENCE_META[selected.confidence].label)
: selected.confidence || '—'}
</Tag>
</div>
</div>
{factSelected && (
<Space>
<Button size="small" onClick={() => onOpenFact(selected.fact_key)}>{t('projects.details', null, '详情')}</Button>
<Button size="small" disabled={!canWrite} onClick={() => onEditFact(selected.fact_key)}>
{t('common.edit', null, '编辑')}
</Button>
</Space>
)}
<div>
<Text strong size="small">{t('projects.graphDirectLinks', null, '直接关系')} · {shownEdges.length}</Text>
{shownEdges.length ? (
<ul className="project-graph-neighbors">
{shownEdges.map((edge, index) => {
const outgoing = edge.source === selected.id;
const peer = byId.get(outgoing ? edge.target : edge.source);
return (
<li key={edge.id || index}>
<div className="project-graph-edge-meta">
<span>{outgoing ? '→' : '←'} {outgoing ? t('projects.graphEdgeOutgoing', null, '出边') : t('projects.graphEdgeIncoming', null, '入边')}</span>
<code>{edge.type}</code>
{edge.confidence === 'tentative' && <span>{t('projects.graphConfidence.tentative', null, '待确认')}</span>}
</div>
<button type="button" className="project-graph-peer project-link-button" onClick={() => openNode(peer.id)} title={peer.fact_key}>
{nodeTitle(peer)}
</button>
</li>
);
})}
</ul>
) : <div><Text type="tertiary" size="small">{t('projects.graphEdgesEmpty', null, '暂无关系边')}</Text></div>}
</div>
</div>
</aside>
)}
</div>
</>
) : graph.loading ? (
<div className="project-graph-loading"><Spin /></div>
) : currentGraph && !graph.error ? (
<Empty
title={t('projects.graphEmptyTitle', null, '构建攻击路径图')}
description={t('projects.graphEmpty', null, '暂无路径图数据。为 finding/exploit 类事实添加关系边(discovered_on → target/*)后将在此展示。')}
@ -297,59 +307,7 @@ export default function FactGraphPanel({
{t('projects.graphEmptyCta', null, '添加第一条事实')}
</Button>
</Empty>
) : (
<div className="project-graph-layout">
<GraphCanvas
graph={graph.data}
search={search}
onSelect={setSelected}
onReady={instance => { cyRef.current = instance; }}
/>
<div className={`project-graph-side${selected ? ' is-open' : ''}`}>
{selected ? (
<div className="project-detail-stack">
<div>
<Text strong>{selected.fact_key}</Text>
<div className="project-graph-side-tags">
<Tag size="small" color="blue" type="light">{NODE_TYPE_LABEL[selected.type] || selected.type}</Tag>
<Tag size="small" color={(CONFIDENCE_META[selected.confidence] || {}).color || 'grey'}>
{(CONFIDENCE_META[selected.confidence] || {}).label || selected.confidence || '—'}
</Tag>
</div>
</div>
<Text type="tertiary" size="small">{selected.summary || '—'}</Text>
<div>
<Text strong size="small">{t('projects.graphEdgesTitle', null, '关系边')}</Text>
{selectedEdges.length ? (
<ul className="project-link-list">
{selectedEdges.map(edge => (
<li key={edge.id}>
<span className="project-graph-edge-dir">
{edge.outgoing
? t('projects.graphEdgeOutgoing', null, '出边')
: t('projects.graphEdgeIncoming', null, '入边')}
</span>
<code>{edge.type}</code>
{' '}
<span title={edge.peer}>{edge.outgoing ? '→' : '←'} {edge.peer}</span>
</li>
))}
</ul>
) : <Text type="tertiary" size="small">{t('projects.graphEdgesEmpty', null, '暂无关系边')}</Text>}
</div>
<Space>
<Button size="small" onClick={() => onOpenFact(selected.fact_key)}>{t('projects.details', null, '详情')}</Button>
<Button size="small" disabled={!canWrite} onClick={() => onEditFact(selected.fact_key)}>
{t('common.edit', null, '编辑')}
</Button>
</Space>
</div>
) : (
<Text type="tertiary" size="small">点击节点查看事实详情</Text>
)}
</div>
</div>
)}
) : null}
{showEdges ? (
<div className="project-edge-table">

View File

@ -220,7 +220,7 @@ export default function ProjectsPage() {
<ErrorBanner error={errorProp(overview.error)} onRetry={overview.reload} />
<StatGrid metrics={metrics} columns={4} />
<div className="project-layout">
<div className={`project-layout${selectedId && activeTab === 'graph' ? ' project-layout--graph' : ''}`}>
<SectionCard
title={t('projects.projectList', null, '项目列表')}
className="project-list-card"

View File

@ -51,6 +51,8 @@
.project-detail > .cs-section-card:last-child,
.project-detail-col > .cs-section-card:last-child { flex: 1; }
.project-detail-summary { display: contents; }
.project-detail-head .semi-card-body {
display: flex;
align-items: flex-start;
@ -136,49 +138,170 @@
.project-link-list { margin: 6px 0 0; padding-left: 18px; font-size: 12px; line-height: 1.7; }
.project-link-list code { font-size: 11px; }
.project-layout--graph { align-items: start; }
.project-layout--graph .project-detail-col,
.project-layout--graph .project-detail { display: contents; }
.project-layout--graph .project-detail-summary { display: block; min-width: 0; }
.project-layout--graph .project-tabs { margin-bottom: 0; }
.project-layout--graph .project-graph-card { grid-column: 1 / -1; }
.project-graph-card, .project-graph-card .semi-card-body { min-width: 0; }
.project-graph-toolbar { margin-bottom: 12px; }
.project-graph-edges-toggle { margin-inline-start: auto; }
.project-graph-search {
position: relative;
flex: 1 1 200px;
min-width: min(180px, 100%);
max-width: 380px;
}
.project-graph-search-results {
position: absolute;
z-index: 5;
inset-inline: 0;
top: calc(100% + 5px);
border: 1px solid var(--semi-color-border);
border-radius: 8px;
background: var(--semi-color-bg-2);
box-shadow: var(--semi-shadow-elevated);
overflow: hidden;
}
.project-graph-search-count {
padding: 8px 12px;
color: var(--semi-color-text-2);
font-size: 12px;
border-bottom: 1px solid var(--semi-color-border);
}
.project-graph-search-list, .project-graph-neighbors { list-style: none; margin: 0; padding: 0; }
.project-graph-search-list { max-height: min(280px, 40svh); overflow: auto; }
.project-graph-search-hit {
display: grid;
gap: 4px;
width: 100%;
padding: 8px 12px;
border: 0;
background: transparent;
color: var(--semi-color-text-0);
cursor: pointer;
text-align: start;
font: inherit;
}
.project-graph-search-hit:hover, .project-graph-search-hit:focus-visible { background: var(--semi-color-fill-0); }
.project-graph-search-hit > * { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.project-graph-search-hit code { color: var(--semi-color-text-2); font-size: 11px; }
.project-graph-status {
display: flex;
min-height: 27px;
align-items: center;
flex-wrap: wrap;
gap: 6px 10px;
margin-bottom: 8px;
}
.project-graph-layout {
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: stretch;
--project-graph-height: clamp(360px, 55svh, 680px);
}
.project-graph-layout.is-compact { --project-graph-height: 320px; }
.project-graph-viewport { flex: 999 1 470px; min-width: 0; }
.project-graph-canvas-wrap {
position: relative;
flex: 1 1 auto;
min-width: 0;
height: 520px;
height: var(--project-graph-height);
border: 1px solid var(--semi-color-border);
border-radius: var(--cs-radius, 10px);
background: var(--semi-color-bg-1);
background: radial-gradient(circle, var(--semi-color-border) 1px, transparent 1px) 0 0 / 18px 18px var(--semi-color-bg-1);
overflow: hidden;
}
.project-graph-canvas { width: 100%; height: 100%; }
.project-graph-overlay {
.project-graph-overlay, .project-graph-labels { position: absolute; inset: 0; }
.project-graph-overlay, .project-graph-loading { display: grid; place-items: center; }
.project-graph-overlay { padding: 16px; color: var(--semi-color-danger); background: var(--semi-color-bg-1); }
.project-graph-loading { min-height: 180px; }
.project-graph-labels { pointer-events: none; }
.project-graph-label {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: var(--semi-color-bg-1);
opacity: .92;
}
.project-graph-side {
flex: 0 0 0;
width: 0;
height: 23px;
padding: 0 7px;
overflow: hidden;
transition: flex-basis .18s ease, width .18s ease;
text-overflow: ellipsis;
white-space: nowrap;
border: 1px solid var(--semi-color-border);
border-radius: 5px;
background: var(--semi-color-bg-1);
color: var(--semi-color-text-0);
font-family: inherit;
font-weight: 500;
font-size: 12px;
line-height: 21px;
text-align: start;
cursor: pointer;
pointer-events: auto;
}
.project-graph-side.is-open {
flex-basis: 300px;
width: 300px;
padding: 10px;
.project-graph-label:hover, .project-graph-label[aria-pressed="true"] {
border-color: var(--semi-color-primary);
color: var(--semi-color-primary);
background: var(--semi-color-primary-light-default);
}
.project-graph-footer {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 8px 12px;
margin-top: 8px;
}
.project-graph-legend {
display: flex;
flex: 1 1 200px;
flex-wrap: wrap;
gap: 6px 12px;
color: var(--semi-color-text-2);
font-size: 12px;
}
.project-graph-legend span { display: inline-flex; align-items: center; gap: 5px; }
.project-graph-legend i { width: 8px; height: 8px; border-radius: 50%; }
.project-graph-legend .project-graph-legend-dash {
width: 16px;
height: 0;
border-radius: 0;
border-top: 2px dashed currentColor;
}
.project-graph-side {
flex: 1 1 240px;
min-width: 0;
max-height: var(--project-graph-height);
padding: 14px;
border: 1px solid var(--semi-color-border);
border-radius: var(--cs-radius, 10px);
background: var(--semi-color-bg-1);
overflow: auto;
max-height: 520px;
overflow-wrap: anywhere;
}
.project-graph-side-tags { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 8px; }
.project-graph-node-key {
display: block;
margin-top: 5px;
color: var(--semi-color-text-2);
font-size: 11px;
}
.project-graph-neighbors { margin-top: 6px; }
.project-graph-neighbors li { padding: 8px 0; border-top: 1px solid var(--semi-color-border); }
.project-graph-edge-meta {
display: flex;
flex-wrap: wrap;
gap: 4px 8px;
color: var(--semi-color-text-2);
font-size: 11px;
}
.project-graph-peer { text-align: start; font-size: 12px; line-height: 1.5; }
@media (max-width: 600px) {
.project-graph-search { flex-basis: 165px; min-width: min(125px, 100%); max-width: none; }
.project-graph-layout { --project-graph-height: clamp(320px, 48svh, 440px); }
.project-graph-layout.is-compact { --project-graph-height: 260px; }
}
.project-graph-side-tags { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 6px; }
.project-graph-edge-dir { color: var(--semi-color-text-2); margin-right: 4px; }
.project-graph-empty-steps {
display: flex;

View File

@ -0,0 +1,134 @@
import { test, expect, ready, PROJECT, UI_PERMISSIONS } from './fixtures.mjs';
const graphPath = `/api/projects/${PROJECT.id}/fact-graph`;
function makeNodes(type, count, title) {
return Array.from({ length: count }, (_, index) => {
const key = type === 'vulnerability' ? `vuln:sample-${index}` : `${type}/sample-${index}`;
const name = `${title} ${index + 1}`;
return { id: key, fact_key: key, type, category: type, label: name, summary: name, confidence: 'confirmed' };
});
}
function denseGraph() {
const targets = makeNodes('target', 18, '示例入口');
const infra = makeNodes('infra', 15, '环境与服务记录');
const findings = makeNodes('finding', 47, '长标题的匿名发现与关联事实说明');
const chains = makeNodes('chain', 16, '相关事实的链路分支');
const vulns = makeNodes('vulnerability', 31, '关联问题');
const edges = [];
const link = (source, target, type, confidence = 'confirmed') => {
edges.push({ id: `example-${edges.length}`, source: source.id, target: target.id, type, confidence });
};
infra.forEach((node, i) => link(targets[i], node, 'depends_on'));
findings.forEach((node, i) => link(targets[i % targets.length], node, 'discovered_on', 'tentative'));
chains.forEach((node, i) => link(findings[i + 1], node, 'leads_to'));
vulns.forEach((node, i) => link(findings[i], node, 'links_vuln'));
for (let i = 0; i < 32; i++) link(findings[i + 1], targets[(i + 2) % targets.length], 'depends_on');
return { nodes: [...targets, ...infra, ...findings, ...chains, ...vulns], edges };
}
test('project graph: dense overview keeps labels legible and search follows the stored connections', async ({ page, mockApi }, testInfo) => {
const graph = denseGraph();
const selected = graph.nodes.find(node => node.id === 'finding/sample-0');
const detail = { ...selected, body: '匿名事实正文,用于验证详情入口。' };
mockApi.respond('GET', graphPath, { json: graph });
mockApi.respond('GET', `/api/projects/${PROJECT.id}/facts`, { json: detail });
await page.goto(`/static/app/#/projects?id=${PROJECT.id}&tab=graph`);
const main = await ready(page);
const canvas = main.getByRole('group', { name: '攻击路径画布' });
const labels = canvas.getByRole('button');
await expect(labels.first()).toBeVisible();
await expect(main.getByText('节点: 127 | 边: 141', { exact: true })).toBeVisible();
const reads = mockApi.calls('GET', graphPath).length;
const boxes = await labels.evaluateAll(items => items.map(item => {
const { left, top, right, bottom } = item.getBoundingClientRect();
return { left, top, right, bottom, fontSize: getComputedStyle(item).fontSize };
}));
expect(boxes.length).toBeGreaterThan(4);
expect(boxes.length).toBeLessThan(graph.nodes.length);
for (const [index, box] of boxes.entries()) {
expect(box.fontSize).toBe('12px');
for (const other of boxes.slice(index + 1)) {
expect(box.left < other.right && box.right > other.left && box.top < other.bottom && box.bottom > other.top).toBe(false);
}
}
await main.locator('.project-graph-card').screenshot({ path: testInfo.outputPath('project-graph-overview.png') });
const search = main.getByRole('textbox', { name: '搜索节点' });
await search.fill('不匹配的节点');
await expect(main.getByText('未找到匹配节点')).toBeVisible();
await search.fill(selected.fact_key);
const result = main.locator('.project-graph-search-results').getByRole('button', { name: new RegExp(selected.label) });
await expect(result).toBeVisible();
await result.click();
const side = main.getByRole('complementary', { name: '节点详情' });
await expect(side.getByText(selected.fact_key)).toBeVisible();
await expect(main.getByText('聚焦直接关系 · 节点: 3 | 边: 2')).toBeVisible();
await expect(side.getByText('← 入边', { exact: true })).toBeVisible();
await expect(side.getByText('→ 出边', { exact: true })).toBeVisible();
await expect(canvas.getByRole('button', { name: selected.label })).toHaveAttribute('aria-pressed', 'true');
await main.locator('.project-graph-card').screenshot({ path: testInfo.outputPath('project-graph-focus.png') });
await side.getByRole('button', { name: '详情', exact: true }).click();
await expect(page.getByText(detail.body)).toBeVisible();
await page.locator('.semi-sidesheet').getByRole('button', { name: '关闭', exact: true }).click();
await side.getByRole('button', { name: '关联问题 1', exact: true }).click();
await expect(side.getByText('vuln:sample-0')).toBeVisible();
await expect(side.getByRole('button', { name: '详情', exact: true })).toHaveCount(0);
await main.getByRole('button', { name: '返回全图' }).click();
await expect(side).toHaveCount(0);
expect(mockApi.calls('GET', graphPath)).toHaveLength(reads);
expect(mockApi.writes()).toEqual([]);
});
test.describe('project graph on a phone', () => {
test.use({ viewport: { width: 390, height: 844 }, appPermissions: UI_PERMISSIONS.filter(value => value !== 'project:write') });
test('zoom controls, keyboard search, filters and read-only relationship list work in dark mode', async ({ page, mockApi }, testInfo) => {
const target = makeNodes('target', 1, '移动端入口')[0];
const finding = makeNodes('finding', 1, '移动端发现')[0];
const prior = { ...makeNodes('note', 1, '历史节点')[0], confidence: 'deprecated' };
const edge = { id: 'mobile-edge', source: finding.id, target: target.id, type: 'depends_on', confidence: 'tentative' };
mockApi.respond('GET', graphPath, (_, url) => ({
json: {
nodes: url.searchParams.get('view') === 'full' && url.searchParams.get('exclude_deprecated') === '0'
? [target, finding, prior] : [target, finding],
edges: [edge]
}
}));
mockApi.respond('GET', `/api/projects/${PROJECT.id}/fact-edges`, { json: [{
id: edge.id, source_fact_key: edge.source, target_fact_key: edge.target, edge_type: edge.type, confidence: edge.confidence
}] });
await page.addInitScript(() => localStorage.setItem('cyberstrike-theme', 'dark'));
await page.goto(`/static/app/#/projects?id=${PROJECT.id}&tab=graph`);
const main = await ready(page);
const card = main.locator('.project-graph-card');
const canvas = card.getByRole('group', { name: '攻击路径画布' });
await expect(canvas.getByRole('button', { name: target.label })).toBeVisible();
await card.getByRole('button', { name: '放大', exact: true }).click();
await card.getByRole('button', { name: '缩小', exact: true }).click();
await card.getByRole('button', { name: '适合画布' }).click();
const search = card.getByRole('textbox', { name: '搜索节点' });
await search.fill(finding.id);
await search.press('Enter');
const side = card.getByRole('complementary', { name: '节点详情' });
await expect(side.getByRole('button', { name: '编辑' })).toBeDisabled();
await expect(side.getByText('→ 出边')).toBeVisible();
expect(await card.evaluate(node => node.scrollWidth)).toBeLessThanOrEqual(await card.evaluate(node => node.clientWidth) + 1);
await card.screenshot({ path: testInfo.outputPath('project-graph-mobile-dark.png') });
await card.locator('.semi-select').click();
await page.getByRole('option', { name: '完整关系' }).click();
await card.getByText('隐藏废弃', { exact: true }).click();
await expect(card.getByText('节点: 3 | 边: 1', { exact: true })).toBeVisible();
await expect(side).toHaveCount(0);
await card.getByRole('button', { name: '关系边', exact: true }).click();
await expect(card.getByRole('button', { name: '删边' })).toBeDisabled();
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{F as r,H as i,L as a,M as o,W as s,at as c,ct as l,i as u,ot as d,wt as f,xt as p}from"./semi-DCiGoqD2.js";import{F as m,I as h,P as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-BlUtaMjd.js";var k=e(t(),1),A=e(n(),1),{Text:j}=s;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),s=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.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)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(r,{children:[(0,A.jsx)(a,{icon:(0,A.jsx)(d,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(a,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(l,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(r,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(r,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(r,{children:[(0,A.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(p,{}),onClick:()=>L({record:t,form:{}})}),s&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(f,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(i,{prefix:(0,A.jsx)(c,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(u,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(u.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(u.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(u.Input,{field:`description`,label:`描述`}),(0,A.jsx)(u.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(u.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(u.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,St as s,Tt as c,W as l,at as u,ct as d,i as f,ot as p}from"./semi-CXF9U6uC.js";import{F as m,I as h,P as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-COBLZkaI.js";var k=e(t(),1),A=e(n(),1),{Text:j}=l;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),l=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.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)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(r,{children:[(0,A.jsx)(a,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(a,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(d,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(r,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(r,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(r,{children:[(0,A.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(s,{}),onClick:()=>L({record:t,form:{}})}),l&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(c,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(i,{prefix:(0,A.jsx)(u,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(f,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(f.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(f.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(f.Input,{field:`description`,label:`描述`}),(0,A.jsx)(f.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(f.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(f.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};

View File

@ -1 +1 @@
import{I as e,L as t}from"./index-BlUtaMjd.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-COBLZkaI.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,L as n,W as r}from"./semi-DCiGoqD2.js";import{E as i,P as a,k as o}from"./index-BlUtaMjd.js";import"./c2-shared-CUybI5fp.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)(t,{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(t=>(0,c.jsx)(n,{size:`small`,theme:t.value===e?`solid`:`borderless`,type:t.value===e?`primary`:`tertiary`,onClick:()=>r(t.value),children:o(`c2.${i}.preset${t.value===`all`?`All`:t.value}`,null,t.label)},t.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{F as t,L as n,W as r}from"./semi-CXF9U6uC.js";import{E as i,P as a,k as o}from"./index-COBLZkaI.js";import"./c2-shared-Ch6uRgJN.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)(t,{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(t=>(0,c.jsx)(n,{size:`small`,theme:t.value===e?`solid`:`borderless`,type:t.value===e?`primary`:`tertiary`,onClick:()=>r(t.value),children:o(`c2.${i}.preset${t.value===`all`?`All`:t.value}`,null,t.label)},t.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

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{F as r,H as i,L as a,M as o,W as s,at as c,ot as l,wt as u}from"./semi-DCiGoqD2.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-BlUtaMjd.js";var T=e(t(),1),E=e(n(),1),{Text:D}=s;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[s,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:s||void 0,limit:k}),[s,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)(o,{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)(r,{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)(r,{children:[(0,E.jsx)(i,{prefix:(0,E.jsx)(c,{}),placeholder:`按会话 ID 过滤`,value:s,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{F as r,H as i,L as a,M as o,Tt as s,W as c,at as l,ot as u}from"./semi-CXF9U6uC.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-COBLZkaI.js";var T=e(t(),1),E=e(n(),1),{Text:D}=c;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[c,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:c||void 0,limit:k}),[c,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)(u,{}),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)(o,{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)(r,{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)(s,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(r,{children:[(0,E.jsx)(i,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:c,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};

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{W as r,i}from"./semi-DCiGoqD2.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-BlUtaMjd.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=o(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,maskClosable:!1,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await a.put(`/projects/${t.id}`,n):await a.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{W as r,i}from"./semi-CXF9U6uC.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-COBLZkaI.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=o(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,maskClosable:!1,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await a.put(`/projects/${t.id}`,n):await a.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};

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{F as r,H as i,L as a,M as o,W as s,at as c,ct as l,i as u,ot as d,wt as f,xt as p}from"./semi-DCiGoqD2.js";import{F as m,I as h,P as g,a as _,b as v,c as y,l as b,m as x,p as S,s as C,x as w,y as T}from"./index-BlUtaMjd.js";var E=e(t(),1),D=e(n(),1),{Text:O}=s;function k(){let e=g(),{hasPermission:t}=m(),n=t(`roles:write`),s=t(`roles:delete`),[k,A]=(0,E.useState)(``),[j,M]=(0,E.useState)(null),[N,P]=(0,E.useState)(!1),F=_(()=>h.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 h.post(`/roles`,t),await h.del(`/roles/${encodeURIComponent(n)}`)):n?await h.put(`/roles/${encodeURIComponent(n)}`,t):await h.post(`/roles`,t),w(`角色已保存`),M(null),F.reload()}catch(e){v(e,`保存角色失败`)}finally{P(!1)}},R=e=>T({title:`删除角色「${e.name}」?`,content:`已绑定该角色的对话将失去对应提示词与工具配置。`,onOk:async()=>{await h.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)(r,{children:[(0,D.jsx)(a,{icon:(0,D.jsx)(d,{}),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)(r,{vertical:!0,spacing:0,align:`start`,children:[(0,D.jsxs)(r,{children:[(0,D.jsx)(O,{strong:!0,children:e}),t.enabled===!1&&(0,D.jsx)(o,{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)(r,{wrap:!0,spacing:4,children:[e.slice(0,4).map(e=>(0,D.jsx)(o,{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)(r,{children:[n&&(0,D.jsx)(a,{size:`small`,theme:`borderless`,icon:(0,D.jsx)(p,{}),onClick:()=>M({role:t,form:{}}),children:`编辑`}),s&&(0,D.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,D.jsx)(f,{}),onClick:()=>R(t)})]})}],dataSource:I,rowKey:`name`,loading:F.loading,pagination:{pageSize:20},toolbar:(0,D.jsx)(i,{prefix:(0,D.jsx)(c,{}),value:k,onChange:A,placeholder:`搜索角色名称`,style:{width:260}})})]}),(0,D.jsx)(y,{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{F as r,H as i,L as a,M as o,St as s,Tt as c,W as l,at as u,ct as d,i as f,ot as p}from"./semi-CXF9U6uC.js";import{F as m,I as h,P as g,a as _,b as v,c as y,l as b,m as x,p as S,s as C,x as w,y as T}from"./index-COBLZkaI.js";var E=e(t(),1),D=e(n(),1),{Text:O}=l;function k(){let e=g(),{hasPermission:t}=m(),n=t(`roles:write`),l=t(`roles:delete`),[k,A]=(0,E.useState)(``),[j,M]=(0,E.useState)(null),[N,P]=(0,E.useState)(!1),F=_(()=>h.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 h.post(`/roles`,t),await h.del(`/roles/${encodeURIComponent(n)}`)):n?await h.put(`/roles/${encodeURIComponent(n)}`,t):await h.post(`/roles`,t),w(`角色已保存`),M(null),F.reload()}catch(e){v(e,`保存角色失败`)}finally{P(!1)}},R=e=>T({title:`删除角色「${e.name}」?`,content:`已绑定该角色的对话将失去对应提示词与工具配置。`,onOk:async()=>{await h.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)(r,{children:[(0,D.jsx)(a,{icon:(0,D.jsx)(p,{}),onClick:()=>F.reload(),loading:F.loading,children:`刷新`}),n&&(0,D.jsx)(a,{theme:`solid`,type:`primary`,icon:(0,D.jsx)(d,{}),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)(r,{vertical:!0,spacing:0,align:`start`,children:[(0,D.jsxs)(r,{children:[(0,D.jsx)(O,{strong:!0,children:e}),t.enabled===!1&&(0,D.jsx)(o,{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)(r,{wrap:!0,spacing:4,children:[e.slice(0,4).map(e=>(0,D.jsx)(o,{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)(r,{children:[n&&(0,D.jsx)(a,{size:`small`,theme:`borderless`,icon:(0,D.jsx)(s,{}),onClick:()=>M({role:t,form:{}}),children:`编辑`}),l&&(0,D.jsx)(a,{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)(i,{prefix:(0,D.jsx)(u,{}),value:k,onChange:A,placeholder:`搜索角色名称`,style:{width:260}})})]}),(0,D.jsx)(y,{title:j?.role?`编辑角色`:`新建角色`,visible:!!j,onCancel:()=>M(null),onOk:L,confirmLoading:N,width:760,children:(0,D.jsxs)(f,{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)(f.Input,{field:`name`,label:`角色名称`,rules:[{required:!0,message:`请输入角色名称`}]}),(0,D.jsx)(f.Input,{field:`description`,label:`描述`}),(0,D.jsx)(f.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::toolName`}),(0,D.jsx)(f.TextArea,{field:`user_prompt`,label:`用户提示词(追加到用户消息前)`,autosize:{minRows:6,maxRows:18}}),(0,D.jsx)(f.Slot,{label:`启用`,children:(0,D.jsx)(f.Switch,{field:`enabled`})})]})},j?.role?.name||`new-role`)]})}export{k as default};

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,L as n,W as r,ot as i,wt as a}from"./semi-DCiGoqD2.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-BlUtaMjd.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)(t,{children:[(0,b.jsx)(n,{icon:(0,b.jsx)(i,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(n,{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,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(n,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(a,{}),onClick:()=>O(t.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{F as t,L as n,Tt as r,W as i,ot as a}from"./semi-CXF9U6uC.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-COBLZkaI.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=i;function S(){let e=u(),{hasPermission:i}=s(),y=i(`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)(t,{children:[(0,b.jsx)(n,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(n,{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,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(n,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(r,{}),onClick:()=>O(t.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

View File

@ -18,10 +18,10 @@
} catch (error) { /* first paint fallback */ }
})();
</script>
<script type="module" crossorigin src="/static/app/assets/index-BlUtaMjd.js"></script>
<script type="module" crossorigin src="/static/app/assets/index-COBLZkaI.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-DCiGoqD2.js">
<link rel="modulepreload" crossorigin href="/static/app/assets/semi-CXF9U6uC.js">
<link rel="stylesheet" crossorigin href="/static/app/assets/semi-BUXPdXzR.css">
<link rel="stylesheet" crossorigin href="/static/app/assets/index-BwdEm4YK.css">
</head>

View File

@ -505,7 +505,37 @@
"noBoundAssets": "لا توجد أصول مرتبطة بهذا المشروع",
"assetCount": "{{count}} أصل",
"factToolbarHint": "يتضمّن الفهرس المفتاح والملخّص فقط (يجب أن يشمل ماذا + أين + كيفية التحقّق)؛ ضع سلسلة الهجوم / إثبات المفهوم في المتن، وأعد الإنتاج عبر get_project_fact.",
"graphToolbarHint": "تطابق أسهم الرسم روابط الحقائق المخزّنة (المصدر → الهدف). تُرتّب العُقد طبقياً: الهدف ← البنية التحتية ← النتيجة ← الاستغلال. الحواف المتقطّعة مبدئية.",
"graphScope": "نطاق العلاقات",
"graphSearchCount": "العُقد · {{count}}",
"graphNoMatches": "لا توجد عُقد مطابقة",
"graphBackToOverview": "العودة إلى النظرة العامة",
"graphFocus": "العلاقات المباشرة · {{stats}}",
"graphOverviewHint": "اختر عقدة لعرض علاقاتها. كبّر الرسم لرؤية مزيد من التسميات.",
"graphCanvas": "لوحة مسار الهجوم",
"graphRenderError": "تعذّر تحميل الرسم. حدّث الصفحة للمحاولة مجددًا.",
"graphTentativeEdge": "علاقة مبدئية",
"graphZoomOut": "تصغير",
"graphZoomIn": "تكبير",
"graphFit": "ملاءمة اللوحة",
"graphNodeDetails": "تفاصيل العقدة",
"graphDirectLinks": "العلاقات المباشرة",
"graphNodeTypes": {
"target": "هدف",
"auth": "مصادقة",
"infra": "بنية تحتية",
"finding": "نتيجة",
"chain": "سلسلة هجوم",
"exploit": "استغلال",
"poc": "تحقق",
"vulnerability": "ثغرة",
"note": "ملاحظة",
"missing": "مفقودة"
},
"graphConfidence": {
"confirmed": "مؤكدة",
"tentative": "مبدئية",
"deprecated": "مهملة"
},
"graphView": "عرض",
"graphViewPath": "مسار الهجوم",
"graphViewFull": "الرسم الكامل",

View File

@ -506,7 +506,37 @@
"noBoundAssets": "No assets are bound to this project",
"assetCount": "{{count}} assets",
"factToolbarHint": "Index includes key and summary only (must include what + where + how to verify); put attack chain / POC in body, and reproduce via get_project_fact.",
"graphToolbarHint": "Graph arrows match stored fact links (source → target). Nodes are layered target→infra→finding→exploit. Dashed edges are tentative.",
"graphScope": "Relationship scope",
"graphSearchCount": "{{count}} nodes",
"graphNoMatches": "No matching nodes",
"graphBackToOverview": "Back to overview",
"graphFocus": "Direct connections · {{stats}}",
"graphOverviewHint": "Select a node to see its connections. Zoom in to reveal more labels.",
"graphCanvas": "Attack path canvas",
"graphRenderError": "Could not load the graph. Refresh to retry.",
"graphTentativeEdge": "Tentative link",
"graphZoomOut": "Zoom out",
"graphZoomIn": "Zoom in",
"graphFit": "Fit to canvas",
"graphNodeDetails": "Node details",
"graphDirectLinks": "Direct connections",
"graphNodeTypes": {
"target": "Target",
"auth": "Authentication",
"infra": "Infrastructure",
"finding": "Finding",
"chain": "Attack chain",
"exploit": "Exploit",
"poc": "Validation",
"vulnerability": "Vulnerability",
"note": "Note",
"missing": "Missing"
},
"graphConfidence": {
"confirmed": "Confirmed",
"tentative": "Tentative",
"deprecated": "Deprecated"
},
"graphView": "View",
"graphViewPath": "Attack path",
"graphViewFull": "Full graph",

View File

@ -518,7 +518,37 @@
"noBoundAssets": "К этому проекту не привязаны активы",
"assetCount": "{{count}} активов",
"factToolbarHint": "В индекс входят только ключ и краткое содержание (что, где и как проверить). Цепочку атаки и POC помещайте в тело; воспроизведение — через get_project_fact.",
"graphToolbarHint": "Стрелки совпадают с сохранёнными связями фактов (источник → цель). Слои узлов: цель → инфраструктура → находка → эксплуатация. Пунктир — предварительные связи.",
"graphScope": "Область связей",
"graphSearchCount": "Узлы · {{count}}",
"graphNoMatches": "Подходящие узлы не найдены",
"graphBackToOverview": "К общему виду",
"graphFocus": "Прямые связи · {{stats}}",
"graphOverviewHint": "Выберите узел, чтобы увидеть его связи. Увеличьте масштаб, чтобы увидеть больше подписей.",
"graphCanvas": "Граф путей атаки",
"graphRenderError": "Не удалось загрузить граф. Обновите страницу.",
"graphTentativeEdge": "Предварительная связь",
"graphZoomOut": "Уменьшить",
"graphZoomIn": "Увеличить",
"graphFit": "Уместить на экране",
"graphNodeDetails": "Сведения об узле",
"graphDirectLinks": "Прямые связи",
"graphNodeTypes": {
"target": "Цель",
"auth": "Аутентификация",
"infra": "Инфраструктура",
"finding": "Находка",
"chain": "Цепочка атаки",
"exploit": "Эксплуатация",
"poc": "Проверка",
"vulnerability": "Уязвимость",
"note": "Заметка",
"missing": "Отсутствует"
},
"graphConfidence": {
"confirmed": "Подтверждено",
"tentative": "Предварительно",
"deprecated": "Устарело"
},
"graphView": "Вид",
"graphViewPath": "Путь атаки",
"graphViewFull": "Весь граф",

View File

@ -494,7 +494,37 @@
"noBoundAssets": "暂无绑定到此项目的资产",
"assetCount": "{{count}} 个资产",
"factToolbarHint": "索引仅含 key 与摘要(须含「什么 + 在哪 + 如何验证」);攻击链 / POC 写在 body,Agent 通过 get_project_fact 复现",
"graphToolbarHint": "攻击路径图箭头与事实存储方向一致(source → target);节点按 target→infra→finding→exploit 分层排布。虚线边为待确认。",
"graphScope": "关系范围",
"graphSearchCount": "{{count}} 个节点",
"graphNoMatches": "未找到匹配节点",
"graphBackToOverview": "返回全图",
"graphFocus": "聚焦直接关系 · {{stats}}",
"graphOverviewHint": "点选节点查看直接关系,放大后显示更多标签。",
"graphCanvas": "攻击路径画布",
"graphRenderError": "图谱加载失败,请刷新重试。",
"graphTentativeEdge": "待确认关系",
"graphZoomOut": "缩小",
"graphZoomIn": "放大",
"graphFit": "适合画布",
"graphNodeDetails": "节点详情",
"graphDirectLinks": "直接关系",
"graphNodeTypes": {
"target": "目标",
"auth": "认证",
"infra": "基础设施",
"finding": "发现",
"chain": "攻击链",
"exploit": "利用",
"poc": "验证",
"vulnerability": "漏洞",
"note": "备注",
"missing": "缺失"
},
"graphConfidence": {
"confirmed": "已确认",
"tentative": "待确认",
"deprecated": "已废弃"
},
"graphView": "视图",
"graphViewPath": "攻击路径",
"graphViewFull": "完整关系",