From 65e6a86c70536291f475365aa4378ce9236974fb Mon Sep 17 00:00:00 2001 From: Sycun <165354365+Sycun@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:26:03 +0800 Subject: [PATCH] feat(projects): make attack path graphs easier to read --- web/frontend/src/pages/projects/detail.jsx | 84 +-- .../src/pages/projects/fact-graph-canvas.jsx | 252 +++++++++ .../src/pages/projects/fact-graph.jsx | 504 ++++++++---------- web/frontend/src/pages/projects/index.jsx | 2 +- web/frontend/src/pages/projects/page.css | 169 +++++- web/frontend/tests/project-graph.spec.mjs | 134 +++++ ...o5Wjf.js => agents-management-D6-ju2Bm.js} | 2 +- ...-docs-D6Lc0TOK.js => api-docs-BKtvz5Ql.js} | 2 +- ...-BI8bVuYj.js => asset-library-CLwePIvk.js} | 4 +- ...CB1l1Zfr.js => asset-overview-CIckd9-D.js} | 2 +- ...et-BZG-CCGP.js => assetTarget-EXnMPa2I.js} | 2 +- ...ents-DT1tb_Pg.js => c2-events-B8wEXV_N.js} | 2 +- ...s-C9nOcYPm.js => c2-listeners-8AXDhYHX.js} | 2 +- ...ds-BVStOJPL.js => c2-payloads-CJb2LK_o.js} | 2 +- ...es-CLyN0Xt2.js => c2-profiles-BfrfIUPa.js} | 2 +- ...ns-CFM49k1s.js => c2-sessions-B3Z8hL7k.js} | 2 +- ...ared-CUybI5fp.js => c2-shared-Ch6uRgJN.js} | 2 +- ...ared-CZqnVh_t.js => c2-shared-Cvh7bGxW.js} | 2 +- ...tasks-xKKQM7CB.js => c2-tasks-B_qgMOxh.js} | 2 +- web/static/app/assets/chat-BQR5RAOd.js | 5 + web/static/app/assets/chat-cDiXw_dD.js | 5 - ...les-CyMTjo9h.js => chat-files-CBX2YEbV.js} | 2 +- ...oard-DOkdy6la.js => dashboard-n2rtArh9.js} | 2 +- .../app/assets/deep-assessments-Bt_Go429.js | 2 - .../app/assets/deep-assessments-CG7-3R4_.js | 2 + .../{hitl-IvWmsz2u.js => hitl-D0NqvLIQ.js} | 2 +- .../{index-BlUtaMjd.js => index-COBLZkaI.js} | 10 +- ...t-C6XWIqCL.js => info-collect-CkLN8PNY.js} | 2 +- .../assets/knowledge-management-CJFervXB.js | 1 + .../assets/knowledge-management-lEi8ysMC.js | 1 - ...s => knowledge-retrieval-logs-DSvPR3sK.js} | 2 +- ...C_g05l3y.js => mcp-management-DDQ34JWP.js} | 2 +- ...or-Br6VW_gs.js => mcp-monitor-OmVMjStv.js} | 2 +- ...-Cuv5ZMfM.js => platform-rbac-WsYqW8Aq.js} | 2 +- ...m-hMtGlL1C.js => project-form-C9CZDZHW.js} | 2 +- web/static/app/assets/projects-B9nWhdUC.js | 4 - web/static/app/assets/projects-BnCCZJXy.js | 4 + web/static/app/assets/projects-eRY58Gte.css | 1 + web/static/app/assets/projects-uruC7Nc5.css | 1 - ...nPycA4.js => roles-management-Cg3Hzs8h.js} | 2 +- .../{semi-DCiGoqD2.js => semi-CXF9U6uC.js} | 10 +- ...tings-WuTxqVSQ.js => settings-ZRl3jFzK.js} | 6 +- ...eJSWe.js => skills-management-AxVmbKmN.js} | 2 +- ...BWkztiQ6.js => skills-monitor-OJ8QB4VQ.js} | 2 +- .../{tasks-CbqpurLh.js => tasks-BK6aUZES.js} | 2 +- ...ard-DV-MKmCd.js => tool-guard-B7r4-GRR.js} | 2 +- .../app/assets/vulnerabilities-BY-B8job.js | 1 - .../app/assets/vulnerabilities-DmbtmCA6.js | 1 + ...shell-CE-_XvuA.js => webshell-mgMuHlIr.js} | 2 +- ...lows-DSXEweUg.js => workflows-4Y1F2HB1.js} | 2 +- web/static/app/index.html | 4 +- web/static/i18n/ar-SA.json | 32 +- web/static/i18n/en-US.json | 32 +- web/static/i18n/ru-RU.json | 32 +- web/static/i18n/zh-CN.json | 32 +- 55 files changed, 990 insertions(+), 401 deletions(-) create mode 100644 web/frontend/src/pages/projects/fact-graph-canvas.jsx create mode 100644 web/frontend/tests/project-graph.spec.mjs rename web/static/app/assets/{agents-management-beTo5Wjf.js => agents-management-D6-ju2Bm.js} (77%) rename web/static/app/assets/{api-docs-D6Lc0TOK.js => api-docs-BKtvz5Ql.js} (97%) rename web/static/app/assets/{asset-library-BI8bVuYj.js => asset-library-CLwePIvk.js} (81%) rename web/static/app/assets/{asset-overview-CB1l1Zfr.js => asset-overview-CIckd9-D.js} (88%) rename web/static/app/assets/{assetTarget-BZG-CCGP.js => assetTarget-EXnMPa2I.js} (97%) rename web/static/app/assets/{c2-events-DT1tb_Pg.js => c2-events-B8wEXV_N.js} (95%) rename web/static/app/assets/{c2-listeners-C9nOcYPm.js => c2-listeners-8AXDhYHX.js} (97%) rename web/static/app/assets/{c2-payloads-BVStOJPL.js => c2-payloads-CJb2LK_o.js} (96%) rename web/static/app/assets/{c2-profiles-CLyN0Xt2.js => c2-profiles-BfrfIUPa.js} (97%) rename web/static/app/assets/{c2-sessions-CFM49k1s.js => c2-sessions-B3Z8hL7k.js} (98%) rename web/static/app/assets/{c2-shared-CUybI5fp.js => c2-shared-Ch6uRgJN.js} (94%) rename web/static/app/assets/{c2-shared-CZqnVh_t.js => c2-shared-Cvh7bGxW.js} (95%) rename web/static/app/assets/{c2-tasks-xKKQM7CB.js => c2-tasks-B_qgMOxh.js} (96%) create mode 100644 web/static/app/assets/chat-BQR5RAOd.js delete mode 100644 web/static/app/assets/chat-cDiXw_dD.js rename web/static/app/assets/{chat-files-CyMTjo9h.js => chat-files-CBX2YEbV.js} (98%) rename web/static/app/assets/{dashboard-DOkdy6la.js => dashboard-n2rtArh9.js} (79%) delete mode 100644 web/static/app/assets/deep-assessments-Bt_Go429.js create mode 100644 web/static/app/assets/deep-assessments-CG7-3R4_.js rename web/static/app/assets/{hitl-IvWmsz2u.js => hitl-D0NqvLIQ.js} (99%) rename web/static/app/assets/{index-BlUtaMjd.js => index-COBLZkaI.js} (50%) rename web/static/app/assets/{info-collect-C6XWIqCL.js => info-collect-CkLN8PNY.js} (88%) create mode 100644 web/static/app/assets/knowledge-management-CJFervXB.js delete mode 100644 web/static/app/assets/knowledge-management-lEi8ysMC.js rename web/static/app/assets/{knowledge-retrieval-logs-DGSfadhu.js => knowledge-retrieval-logs-DSvPR3sK.js} (80%) rename web/static/app/assets/{mcp-management-C_g05l3y.js => mcp-management-DDQ34JWP.js} (98%) rename web/static/app/assets/{mcp-monitor-Br6VW_gs.js => mcp-monitor-OmVMjStv.js} (99%) rename web/static/app/assets/{platform-rbac-Cuv5ZMfM.js => platform-rbac-WsYqW8Aq.js} (66%) rename web/static/app/assets/{project-form-hMtGlL1C.js => project-form-C9CZDZHW.js} (90%) delete mode 100644 web/static/app/assets/projects-B9nWhdUC.js create mode 100644 web/static/app/assets/projects-BnCCZJXy.js create mode 100644 web/static/app/assets/projects-eRY58Gte.css delete mode 100644 web/static/app/assets/projects-uruC7Nc5.css rename web/static/app/assets/{roles-management-BOnPycA4.js => roles-management-Cg3Hzs8h.js} (71%) rename web/static/app/assets/{semi-DCiGoqD2.js => semi-CXF9U6uC.js} (76%) rename web/static/app/assets/{settings-WuTxqVSQ.js => settings-ZRl3jFzK.js} (87%) rename web/static/app/assets/{skills-management-J70eJSWe.js => skills-management-AxVmbKmN.js} (84%) rename web/static/app/assets/{skills-monitor-BWkztiQ6.js => skills-monitor-OJ8QB4VQ.js} (83%) rename web/static/app/assets/{tasks-CbqpurLh.js => tasks-BK6aUZES.js} (99%) rename web/static/app/assets/{tool-guard-DV-MKmCd.js => tool-guard-B7r4-GRR.js} (65%) delete mode 100644 web/static/app/assets/vulnerabilities-BY-B8job.js create mode 100644 web/static/app/assets/vulnerabilities-DmbtmCA6.js rename web/static/app/assets/{webshell-CE-_XvuA.js => webshell-mgMuHlIr.js} (99%) rename web/static/app/assets/{workflows-DSXEweUg.js => workflows-4Y1F2HB1.js} (99%) diff --git a/web/frontend/src/pages/projects/detail.jsx b/web/frontend/src/pages/projects/detail.jsx index 6d80db1d..01c5e325 100644 --- a/web/frontend/src/pages/projects/detail.jsx +++ b/web/frontend/src/pages/projects/detail.jsx @@ -63,50 +63,52 @@ export default function ProjectDetail({ projectId, tab, refreshToken = 0, onTabC return (
- - -
-
- - {current?.name || t('projects.projectNotFound', null, '项目不存在')} - - {current?.pinned ? {t('projects.pinned', null, '置顶')} : null} - - {(current?.status || 'active') === 'archived' - ? t('projects.statusArchived', null, '已归档') - : t('projects.statusActive', null, '进行中')} - +
+ + +
+
+ + {current?.name || t('projects.projectNotFound', null, '项目不存在')} + + {current?.pinned ? {t('projects.pinned', null, '置顶')} : null} + + {(current?.status || 'active') === 'archived' + ? t('projects.statusArchived', null, '已归档') + : t('projects.statusActive', null, '进行中')} + +
+ {current?.description + ? {current.description} + : {t('projects.noProjectDescription', null, '暂无项目描述')}} + + {t('projects.updatedPrefix', { time: formatDateTime(current?.updated_at) }, `更新于 ${formatDateTime(current?.updated_at)}`)} + {' · '}ID: {projectId} +
- {current?.description - ? {current.description} - : {t('projects.noProjectDescription', null, '暂无项目描述')}} - - {t('projects.updatedPrefix', { time: formatDateTime(current?.updated_at) }, `更新于 ${formatDateTime(current?.updated_at)}`)} - {' · '}ID: {projectId} - -
- - - - + + + + - + - onTabChange?.(key)} - className="project-tabs" - /> + onTabChange?.(key)} + className="project-tabs" + /> +
{(!tab || tab === 'facts') && ( 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 ( +
+
+
+ {labels.map(({ id, title, box }) => ( + + ))} +
+ {failed &&
{errorText}
} +
+ ); +} diff --git a/web/frontend/src/pages/projects/fact-graph.jsx b/web/frontend/src/pages/projects/fact-graph.jsx index 03a92a38..9a68f0c9 100644 --- a/web/frontend/src/pages/projects/fact-graph.jsx +++ b/web/frontend/src/pages/projects/fact-graph.jsx @@ -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 ( -
-
- {importError ? ( -
- cytoscape 加载失败,请刷新页面重试 +
{ + if (!event.currentTarget.contains(event.relatedTarget)) setOpen(false); + }}> + } + 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 && ( +
+
+ {matches.length + ? t('projects.graphSearchCount', { count: matches.length }, `${matches.length} 个节点`) + : t('projects.graphNoMatches', null, '未找到匹配节点')} +
+ {matches.length > 0 &&
    + {matches.map(node => ( +
  • + +
  • + ))} +
}
- ) : null} + )}
); } @@ -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 ( - - {t('projects.graphStats', { nodes: nodes.length, edges: edges.length }, `节点: ${nodes.length} | 边: ${edges.length}`)} - - -
- - {!graph.loading && !nodes.length ? ( + {nodes.length > 0 ? ( + <> +
+ {selected ? ( + <> + + + {t('projects.graphFocus', { stats: stats(shownNodes.length, shownEdges.length) }, `聚焦直接关系 · ${stats(shownNodes.length, shownEdges.length)}`)} + + + ) : ( + + {t('projects.graphOverviewHint', null, '点选节点查看直接关系,放大后显示更多标签。')} + + )} +
+
+
+ +
+
+ {types.map(type => ( + +