From 1d1db56a0451e87a7e2274357675dccb3ea8fba1 Mon Sep 17 00:00:00 2001 From: Sycun <165354365+Sycun@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:43:27 +0800 Subject: [PATCH] feat(deep-assessment): clarify exploration flow and task summary --- .../src/pages/deep-assessments/GraphBrief.jsx | 69 +++ .../pages/deep-assessments/GraphCanvas.jsx | 311 ++++++++++++ .../src/pages/deep-assessments/GraphTab.jsx | 453 +++++++----------- .../src/pages/deep-assessments/Workbench.jsx | 2 +- .../src/pages/deep-assessments/graphLayout.js | 154 ++++++ .../src/pages/deep-assessments/page.css | 184 ++++++- web/frontend/tests/ui.spec.mjs | 140 +++++- ...Fswit.js => agents-management-BYr104J9.js} | 2 +- ...-docs-DrZBFtJn.js => api-docs-CTygpWCQ.js} | 2 +- ...-BAx49DmG.js => asset-library-DlVeaTS8.js} | 2 +- ...D7JIEDtF.js => asset-overview-CcL8WS2g.js} | 2 +- ...ents-Cp-GJMyz.js => c2-events-CoO9k8do.js} | 2 +- ...s-wI9hP5bO.js => c2-listeners-BbfCauO0.js} | 2 +- ...ds-CIOqYU-D.js => c2-payloads-Bch2Zx-S.js} | 2 +- ...es-ClkQWayP.js => c2-profiles-D-ykTEmi.js} | 2 +- ...ns-Bg1hjSzL.js => c2-sessions-qbGOeEta.js} | 2 +- ...ared-CbaqmFYG.js => c2-shared-DdWdvkU_.js} | 2 +- ...ared-HC4EGRVp.js => c2-shared-ssbP-zZZ.js} | 2 +- ...tasks-CgETOE9Q.js => c2-tasks-Cz4h_2Z-.js} | 2 +- .../{chat-CAQD0-9q.js => chat-C9C0tf1B.js} | 2 +- ...les-CCNEGxTF.js => chat-files-CprhkoqQ.js} | 2 +- ...oard-CSEJJamH.js => dashboard-Dmsjeplf.js} | 2 +- .../app/assets/deep-assessments-C9cuKMjV.js | 2 + .../app/assets/deep-assessments-DNnss0mA.css | 1 + .../app/assets/deep-assessments-DUgX1CCm.css | 1 - .../app/assets/deep-assessments-Dxp_hiCJ.js | 2 - .../{hitl-BbEnPABm.js => hitl-MjbzCA9X.js} | 2 +- .../{index-DhiAuEy4.js => index-CexI4Ljq.js} | 4 +- ...t-YgA_NbUR.js => info-collect-D-N4iLM2.js} | 2 +- ...f8.js => knowledge-management-DTuEuCEL.js} | 2 +- ...s => knowledge-retrieval-logs-BSh0bSRM.js} | 2 +- ...CNxoT5yR.js => mcp-management-D01azo4R.js} | 2 +- ...or-CT7coQ73.js => mcp-monitor-DByr6Zb0.js} | 2 +- ...-C3MIFHIg.js => platform-rbac-DREYcjVj.js} | 2 +- ...m-DvD8IPYc.js => project-form-y4OIC73_.js} | 2 +- ...jects-DbdKx38Y.js => projects-DIolFeZo.js} | 2 +- ...zpm1Lc.js => roles-management-u_0mxo4G.js} | 2 +- ...tings-D9pbAHAI.js => settings-tGRfA_Sa.js} | 2 +- ...x0Mlo.js => skills-management-CdMkcVvO.js} | 2 +- ...h9Mjnwcb.js => skills-monitor-BgB8SQ9E.js} | 2 +- .../{tasks-z7zfeQnJ.js => tasks-xyvgn3YG.js} | 2 +- ...ard-DPifFVzN.js => tool-guard-B0mKbewj.js} | 2 +- ...5WvEo-W.js => vulnerabilities-Cu_FIERb.js} | 2 +- ...shell-BS16gIV1.js => webshell-BwM2LRBi.js} | 2 +- ...lows-CWCq2saC.js => workflows-BNW4bAwz.js} | 2 +- web/static/app/index.html | 2 +- 46 files changed, 1053 insertions(+), 338 deletions(-) create mode 100644 web/frontend/src/pages/deep-assessments/GraphBrief.jsx create mode 100644 web/frontend/src/pages/deep-assessments/GraphCanvas.jsx create mode 100644 web/frontend/src/pages/deep-assessments/graphLayout.js rename web/static/app/assets/{agents-management-DttFswit.js => agents-management-BYr104J9.js} (97%) rename web/static/app/assets/{api-docs-DrZBFtJn.js => api-docs-CTygpWCQ.js} (98%) rename web/static/app/assets/{asset-library-BAx49DmG.js => asset-library-DlVeaTS8.js} (99%) rename web/static/app/assets/{asset-overview-D7JIEDtF.js => asset-overview-CcL8WS2g.js} (98%) rename web/static/app/assets/{c2-events-Cp-GJMyz.js => c2-events-CoO9k8do.js} (96%) rename web/static/app/assets/{c2-listeners-wI9hP5bO.js => c2-listeners-BbfCauO0.js} (97%) rename web/static/app/assets/{c2-payloads-CIOqYU-D.js => c2-payloads-Bch2Zx-S.js} (97%) rename web/static/app/assets/{c2-profiles-ClkQWayP.js => c2-profiles-D-ykTEmi.js} (98%) rename web/static/app/assets/{c2-sessions-Bg1hjSzL.js => c2-sessions-qbGOeEta.js} (98%) rename web/static/app/assets/{c2-shared-CbaqmFYG.js => c2-shared-DdWdvkU_.js} (94%) rename web/static/app/assets/{c2-shared-HC4EGRVp.js => c2-shared-ssbP-zZZ.js} (96%) rename web/static/app/assets/{c2-tasks-CgETOE9Q.js => c2-tasks-Cz4h_2Z-.js} (97%) rename web/static/app/assets/{chat-CAQD0-9q.js => chat-C9C0tf1B.js} (99%) rename web/static/app/assets/{chat-files-CCNEGxTF.js => chat-files-CprhkoqQ.js} (99%) rename web/static/app/assets/{dashboard-CSEJJamH.js => dashboard-Dmsjeplf.js} (99%) create mode 100644 web/static/app/assets/deep-assessments-C9cuKMjV.js create mode 100644 web/static/app/assets/deep-assessments-DNnss0mA.css delete mode 100644 web/static/app/assets/deep-assessments-DUgX1CCm.css delete mode 100644 web/static/app/assets/deep-assessments-Dxp_hiCJ.js rename web/static/app/assets/{hitl-BbEnPABm.js => hitl-MjbzCA9X.js} (99%) rename web/static/app/assets/{index-DhiAuEy4.js => index-CexI4Ljq.js} (96%) rename web/static/app/assets/{info-collect-YgA_NbUR.js => info-collect-D-N4iLM2.js} (99%) rename web/static/app/assets/{knowledge-management-BCcXsWf8.js => knowledge-management-DTuEuCEL.js} (98%) rename web/static/app/assets/{knowledge-retrieval-logs-DdCxMhrQ.js => knowledge-retrieval-logs-BSh0bSRM.js} (96%) rename web/static/app/assets/{mcp-management-CNxoT5yR.js => mcp-management-D01azo4R.js} (99%) rename web/static/app/assets/{mcp-monitor-CT7coQ73.js => mcp-monitor-DByr6Zb0.js} (99%) rename web/static/app/assets/{platform-rbac-C3MIFHIg.js => platform-rbac-DREYcjVj.js} (99%) rename web/static/app/assets/{project-form-DvD8IPYc.js => project-form-y4OIC73_.js} (95%) rename web/static/app/assets/{projects-DbdKx38Y.js => projects-DIolFeZo.js} (99%) rename web/static/app/assets/{roles-management-BKzpm1Lc.js => roles-management-u_0mxo4G.js} (96%) rename web/static/app/assets/{settings-D9pbAHAI.js => settings-tGRfA_Sa.js} (99%) rename web/static/app/assets/{skills-management-CzKx0Mlo.js => skills-management-CdMkcVvO.js} (97%) rename web/static/app/assets/{skills-monitor-h9Mjnwcb.js => skills-monitor-BgB8SQ9E.js} (95%) rename web/static/app/assets/{tasks-z7zfeQnJ.js => tasks-xyvgn3YG.js} (99%) rename web/static/app/assets/{tool-guard-DPifFVzN.js => tool-guard-B0mKbewj.js} (99%) rename web/static/app/assets/{vulnerabilities-D5WvEo-W.js => vulnerabilities-Cu_FIERb.js} (99%) rename web/static/app/assets/{webshell-BS16gIV1.js => webshell-BwM2LRBi.js} (99%) rename web/static/app/assets/{workflows-CWCq2saC.js => workflows-BNW4bAwz.js} (99%) diff --git a/web/frontend/src/pages/deep-assessments/GraphBrief.jsx b/web/frontend/src/pages/deep-assessments/GraphBrief.jsx new file mode 100644 index 00000000..3e1c0c45 --- /dev/null +++ b/web/frontend/src/pages/deep-assessments/GraphBrief.jsx @@ -0,0 +1,69 @@ +import { Button, Tag, Typography } from '@douyinfe/semi-ui'; +import { formatDateTime } from '../../lib/format'; +import { statusText } from './labels'; + +const { Text, Paragraph } = Typography; +const PREVIEW_LIMIT = 6; + +export default function GraphBrief({ task, t, onIntent, onGoIntents }) { + const steps = task.steps || []; + const titles = new Map(steps.map(step => [step.id, step.title || step.id])); + const completed = steps.filter(step => step.status === 'completed').length; + const summary = task.summary?.trim(); + + return ( +
+ + 目标拆解与阶段总结 + + {steps.length ? `${steps.length} 个意图 · ${completed} 个已完成` : '暂无意图'} + + +
+
+ {t('deepAssessments.objective', null, '目标')} + {task.objective || task.name || '—'} + {steps.length ? ( + <> +
    + {steps.slice(0, PREVIEW_LIMIT).map(step => { + const dependencies = (step.depends_on || []).map(id => titles.get(id) || id); + return ( +
  • +
    + + {step.status ? {statusText(t, step.status)} : null} +
    + {dependencies.length ? ( + + 上游依赖 · {dependencies.slice(0, 2).join('、')} + {dependencies.length > 2 ? ` 等 ${dependencies.length} 项` : ''} + + ) : null} +
  • + ); + })} +
+ {steps.length > PREVIEW_LIMIT ? ( + + ) : null} + + ) : ( + 已有计划中的意图会显示在这里。 + )} +
+
+ 阶段总结 + + {summary || '当前还没有保存的阶段总结。'} + + {summary && task.updated_at ? ( + 测评更新于 {formatDateTime(task.updated_at)} + ) : null} +
+
+
+ ); +} diff --git a/web/frontend/src/pages/deep-assessments/GraphCanvas.jsx b/web/frontend/src/pages/deep-assessments/GraphCanvas.jsx new file mode 100644 index 00000000..9c697988 --- /dev/null +++ b/web/frontend/src/pages/deep-assessments/GraphCanvas.jsx @@ -0,0 +1,311 @@ +import { Fragment, useEffect, useRef, useState } from 'react'; +import { toastError } from '../../components/ui'; +import { GRAPH_KIND_COLOR } from './labels'; +import { GRAPH_COLUMN_GAP, graphPositions } from './graphLayout'; + +const STYLE = [ + { + selector: 'node', + style: { + 'background-color': 'data(color)', + width: 23, height: 23, + 'border-width': 2, 'border-color': '#ffffff' + } + }, + { selector: 'node[kind = "goal"]', style: { width: 31, height: 31 } }, + { selector: 'node[boundary = 1]', style: { shape: 'round-rectangle', width: 17, height: 17 } }, + { selector: 'node.current', style: { 'border-color': '#0066ff', 'border-width': 4 } }, + { + selector: 'edge', + style: { + width: 1.8, + 'line-color': 'data(color)', + 'target-arrow-color': 'data(color)', + 'target-arrow-shape': 'triangle', + 'arrow-scale': 0.8, + 'curve-style': 'bezier', + opacity: 0.74 + } + }, + { + selector: 'edge.flow', + style: { 'curve-style': 'round-taxi', 'taxi-direction': 'rightward', 'taxi-radius': 16 } + }, + { + selector: 'edge.long-flow', + style: { + 'curve-style': 'unbundled-bezier', 'control-point-weights': 0.45, + 'control-point-distances': 'data(bend)' + } + }, + { selector: 'edge[projection = "archive"]', style: { 'line-style': 'dashed' } }, + { selector: 'edge[projection = "details"]', style: { 'line-style': 'dotted' } }, + { selector: 'node.dim', style: { opacity: 0.32 } }, + { selector: 'edge.dim', style: { opacity: 0.12 } }, + { + selector: 'edge.related', + style: { width: 2.8, opacity: 1, 'z-index': 2 } + }, + { selector: '.hidden', style: { display: 'none' } } +]; + +const LABEL_WIDTH = 148; +const LABEL_HEIGHT = 22; +const LABEL_PADDING = 7; +const LABEL_PRIORITY = { goal: 0, finding: 1, step: 2, guidance: 3, fact: 4, digest: 5 }; +const overlaps = (a, b) => a.x < b.x + b.width && a.x + a.width > b.x + && a.y < b.y + b.height && a.y + a.height > b.y; + +function visibleLabels(cy, model, selected, hovered, measure) { + const width = cy.width(); + const height = cy.height(); + const zoom = cy.zoom(); + const items = cy.nodes(':visible').map(node => { + const item = model.nodes.get(node.id()); + const { x, y } = node.renderedPosition(); + const radius = node.renderedOuterWidth() / 2 + 2; + const priority = node === selected ? -2 : node === hovered ? -1 + : (LABEL_PRIORITY[item.kind] ?? 6) + (item.boundary ? 8 : 0); + return { node, item, x, y, radius, priority }; + }).filter(({ x, y, radius }) => x >= -radius && x <= width + radius && y >= -radius && y <= height + radius); + const occupied = items.map(({ x, y, radius }) => ({ + x: x - radius, y: y - radius, width: radius * 2, height: radius * 2 + })); + const labels = []; + items.sort((a, b) => a.priority - b.priority); + + for (const { node, item, x, y, radius, priority } of items) { + if (zoom < 0.64 && priority > 3) continue; + if (node.hasClass('dim') && priority >= 0) continue; + const title = (item.title || item.id).replace(/\s+/g, ' ').trim() || item.id; + const labelWidth = Math.min(LABEL_WIDTH, Math.ceil(measure(title)) + LABEL_PADDING * 2); + const left = Math.max(4, Math.min(x - labelWidth / 2, width - labelWidth - 4)); + const top = y + radius + 4; + const candidates = [{ x: left, y: top, width: labelWidth, height: LABEL_HEIGHT }]; + if (priority <= 3) { + candidates.push( + { ...candidates[0], y: y - radius - LABEL_HEIGHT - 4 }, + { ...candidates[0], x: x + radius + 5, y: y - LABEL_HEIGHT / 2 }, + { ...candidates[0], x: x - radius - labelWidth - 5, y: y - LABEL_HEIGHT / 2 } + ); + } + if (priority <= 0) { + // A fitted overview can leave only a few pixels between nodes on a phone. + for (const offset of [28, 54, 80, 106, 132]) { + candidates.push( + { ...candidates[0], y: top + offset, displaced: true }, + { ...candidates[0], y: y - radius - LABEL_HEIGHT - 4 - offset, displaced: true } + ); + } + } + const box = candidates.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: LABEL_HEIGHT + 4 }); + const below = box.y > y; + const leader = box.displaced ? { + left: x, + top: below ? y + radius : box.y + LABEL_HEIGHT, + height: below ? box.y - y - radius : y - radius - box.y - LABEL_HEIGHT + } : null; + labels.push({ id: item.id, title, box, leader, selected: priority === -2 }); + } + return labels; +} + +export function fitGraph(cy) { + const nodes = cy.nodes(':visible'); + if (nodes.empty()) return; + cy.fit(nodes, 45); + if (cy.zoom() > 1) cy.zoom(1).center(nodes); +} + +export function zoomGraph(cy, factor) { + cy.zoom({ + level: cy.zoom() * factor, + renderedPosition: { x: cy.width() / 2, y: cy.height() / 2 } + }); +} + +export default function GraphCanvas({ model, graphKey, selectedId, showAll, locate, onSelect, cyRef }) { + const containerRef = useRef(null); + const chartRef = useRef(null); + const viewRef = useRef(null); + const controlsRef = useRef({ selectedId, showAll, locate, onSelect }); + const [labels, setLabels] = useState([]); + + useEffect(() => { + controlsRef.current = { selectedId, showAll, locate, onSelect }; + chartRef.current?.syncSelection(); + }, [selectedId, showAll, locate, onSelect]); + + useEffect(() => { + const container = containerRef.current; + if (!model.nodes.size) { + setLabels([]); + return undefined; + } + let disposed = false; + let cy; + let frame; + let resize; + let hovered; + let centeredRequest; + let previousSelection; + let previousShowAll = controlsRef.current.showAll; + setLabels([]); + + import('cytoscape').then(({ default: cytoscape }) => { + if (disposed) return; + const positions = graphPositions(model); + const elements = [ + ...[...model.nodes.values()].map(node => ({ + data: { + id: node.id, kind: node.kind, boundary: Number(Boolean(node.boundary)), + color: GRAPH_KIND_COLOR[node.kind] || '#86909c' + }, + position: positions.get(node.id) + })), + ...model.edges.map(edge => { + const source = positions.get(edge.source); + const target = positions.get(edge.target); + const spansColumns = target.x - source.x > GRAPH_COLUMN_GAP * 1.5; + return { + data: { + ...edge, projection: edge.projection || '', + bend: target.y < source.y ? -28 : 28 + }, + classes: model.layoutEdges.has(edge.id) ? (spansColumns ? 'long-flow' : 'flow') : '' + }; + }) + ]; + cy = cytoscape({ + container, elements, style: STYLE, + layout: { name: 'preset', fit: false }, + wheelSensitivity: 0.2, minZoom: 0.005, maxZoom: 3, + boxSelectionEnabled: false, + autounselectify: true + }); + cyRef.current = cy; + const measurement = document.createElement('canvas').getContext('2d'); + measurement.font = `12px ${getComputedStyle(container).fontFamily}`; + const widths = new Map(); + const measure = title => { + if (!widths.has(title)) widths.set(title, measurement.measureText(title).width); + return widths.get(title); + }; + const selectedNode = () => cy.$id(controlsRef.current.selectedId)[0]; + const updateLabels = () => { + cancelAnimationFrame(frame); + frame = requestAnimationFrame(() => setLabels(visibleLabels(cy, model, selectedNode(), hovered, measure))); + }; + const syncSelection = () => { + const { showAll, locate } = controlsRef.current; + const selected = selectedNode(); + const related = selected?.connectedEdges() || cy.collection(); + const neighbors = related.connectedNodes(); + const overview = !showAll && model.dense && model.overview.size > 0; + cy.batch(() => { + // Selection is controlled by the detail panel, including label and search picks. + cy.nodes().forEach(node => { + const nearby = node === selected || neighbors.has(node); + node.toggleClass('current', node === selected); + node.toggleClass('dim', Boolean(selected && !nearby)); + node.toggleClass('hidden', overview && !nearby && !model.overview.has(node.id())); + }); + cy.edges().forEach(edge => { + const incident = related.has(edge); + edge.toggleClass('related', incident); + edge.toggleClass('dim', Boolean(selected && !incident)); + edge.toggleClass('hidden', !showAll && model.dense && !model.backbone.has(edge.id()) && !incident); + }); + }); + if (locate && locate !== centeredRequest && selected?.id() === locate.id) { + centeredRequest = locate; + const zoom = Math.max(cy.zoom(), 1); + cy.zoom(zoom).center(selected); + } else if (!selected && (showAll !== previousShowAll || (overview && previousSelection?.hidden()))) { + fitGraph(cy); + } + previousSelection = selected; + previousShowAll = showAll; + updateLabels(); + }; + chartRef.current = { syncSelection }; + const saved = viewRef.current; + const restore = saved?.key === graphKey; + if (restore) { + cy.viewport(saved); + centeredRequest = controlsRef.current.locate; + } + syncSelection(); + if (!restore && !centeredRequest) fitGraph(cy); + cy.on('pan zoom position', updateLabels); + cy.on('tap', event => { + if (event.target === cy) controlsRef.current.onSelect(''); + else if (event.target.isNode()) controlsRef.current.onSelect(event.target.id()); + }); + cy.on('mouseover', 'node', event => { hovered = event.target; updateLabels(); }); + cy.on('mouseout', 'node', () => { hovered = undefined; updateLabels(); }); + + let width = cy.width(); + let height = cy.height(); + resize = new ResizeObserver(() => { + const previousWidth = width; + const previousHeight = height; + cy.resize(); + const nextWidth = cy.width(); + const nextHeight = cy.height(); + cy.panBy({ x: (nextWidth - width) / 2, y: (nextHeight - height) / 2 }); + width = nextWidth; + height = nextHeight; + const selected = selectedNode(); + const point = selected?.renderedPosition(); + if (point && (point.x < 30 || point.x > width - 30 || point.y < 30 || point.y > height - 30)) { + cy.center(selected); + } else if (!selected && (nextWidth < previousWidth || nextHeight < previousHeight)) { + fitGraph(cy); + } + updateLabels(); + }); + resize.observe(container); + }).catch(error => { if (!disposed) toastError(error, '图谱渲染失败'); }); + + return () => { + disposed = true; + cancelAnimationFrame(frame); + resize?.disconnect(); + if (cy) { + viewRef.current = { key: graphKey, zoom: cy.zoom(), pan: cy.pan() }; + cy.destroy(); + } + chartRef.current = null; + cyRef.current = null; + }; + }, [model, graphKey, cyRef]); + + return ( +
+
+
+ {labels.map(({ id, title, box, leader, selected }) => ( + + {leader ? + ))} +
+
+ ); +} diff --git a/web/frontend/src/pages/deep-assessments/GraphTab.jsx b/web/frontend/src/pages/deep-assessments/GraphTab.jsx index 0fca7a3e..e78c3bb5 100644 --- a/web/frontend/src/pages/deep-assessments/GraphTab.jsx +++ b/web/frontend/src/pages/deep-assessments/GraphTab.jsx @@ -1,76 +1,26 @@ /** 探索图:cytoscape 渲染、节点下钻与证据路径。 */ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useMemo, useRef, useState } from 'react'; import { Button, Empty, RadioGroup, Select, Space, Tag, Typography } from '@douyinfe/semi-ui'; import { api } from '../../lib/http'; import { useT } from '../../lib/i18n'; -import { useTheme } from '../../lib/theme'; import { useResource } from '../../components/hooks'; import { SectionCard, ErrorBanner, JsonViewer, KeyValueList, toastError } from '../../components/ui'; import { formatDateTime } from '../../lib/format'; -import { GRAPH_KIND_COLOR, kindText, stateText, truncateText } from './labels'; +import { kindText, stateText, truncateText } from './labels'; +import GraphCanvas, { fitGraph, zoomGraph } from './GraphCanvas'; +import GraphBrief from './GraphBrief'; +import { prepareGraph, graphPositions } from './graphLayout'; const { Text, Paragraph } = Typography; -const CY_STYLE = [ - { - selector: 'node', - style: { - 'background-color': 'data(color)', - label: 'data(label)', - 'font-size': 10, - 'text-wrap': 'wrap', - 'text-max-width': 120, - 'text-valign': 'bottom', - 'text-margin-y': 5, - 'text-outline-width': 1.5, - width: 26, - height: 26, - 'border-width': 2, - 'border-color': '#ffffff' - } - }, - { - selector: 'node[boundary = 1]', - style: { shape: 'round-rectangle', width: 18, height: 18, opacity: 0.7 } - }, - { - selector: 'node:selected', - style: { 'border-color': '#0066ff', 'border-width': 4 } - }, - { - selector: 'edge', - style: { - width: 1, - 'line-color': '#c9cdd4', - 'target-arrow-color': '#c9cdd4', - 'target-arrow-shape': 'triangle', - 'arrow-scale': 0.7, - 'curve-style': 'bezier', - opacity: 0.85 - } - }, - { - selector: 'edge[projection = "archive"]', - style: { 'line-style': 'dashed', 'line-color': '#d9d9d9' } - }, - { - selector: 'edge[projection = "details"]', - style: { 'line-style': 'dotted' } - } -]; - -function updateLabelColors(cy) { - const { color, backgroundColor } = getComputedStyle(cy.container()); - cy.nodes().style({ color, 'text-outline-color': backgroundColor }); -} - -export default function GraphTab({ id, reloadToken }) { +export default function GraphTab({ id, task, reloadToken, onGoIntents }) { const t = useT(); - const { theme } = useTheme(); const [view, setView] = useState('summary'); const [scope, setScope] = useState(''); const [offset, setOffset] = useState(0); const [selectedId, setSelectedId] = useState(''); + const [showAll, setShowAll] = useState(false); + const [locate, setLocate] = useState(null); const [node, setNode] = useState(null); const [relations, setRelations] = useState([]); const [linksOffset, setLinksOffset] = useState(0); @@ -80,156 +30,85 @@ export default function GraphTab({ id, reloadToken }) { const [nodeLoading, setNodeLoading] = useState(false); const [pathView, setPathView] = useState(null); const [pathLoading, setPathLoading] = useState(false); - const containerRef = useRef(null); const cyRef = useRef(null); - const selectRef = useRef(() => {}); + const nodeRequest = useRef(0); + const graphKey = JSON.stringify([id, view, scope, offset]); const resource = useResource( - () => api.get(`/deep-assessments/${id}/graph`, { view, scope, offset, limit: 80 }), + async () => ({ + key: graphKey, + graph: await api.get(`/deep-assessments/${id}/graph`, { view, scope, offset, limit: 80 }) + }), [id, view, scope, offset, reloadToken] ); - const graph = resource.data; - const nodes = graph?.nodes || []; + const graph = resource.data?.graph; + const model = useMemo(() => prepareGraph(graph), [graph]); + const nodes = [...model.nodes.values()]; + const collapsedNodes = model.overview.size ? model.nodes.size - model.overview.size : 0; + const canExpand = model.dense && (collapsedNodes > 0 || model.edges.length > model.backbone.size); const selectNode = useCallback(async (nodeId, options = {}) => { - const { appendBody = false, appendLinks = false } = options; - if (!nodeId) return; + const { appendBody = false, appendLinks = false, center = false } = options; + const request = ++nodeRequest.current; setSelectedId(nodeId); - const cy = cyRef.current; - if (cy) { - cy.elements().unselect(); - cy.$id(nodeId).select(); + if (center) setLocate({ id: nodeId }); + if (!appendBody && !appendLinks) { + setNode(null); + setRelations([]); + setPathView(null); } - setNodeLoading(true); + setPathLoading(false); + setNodeLoading(Boolean(nodeId)); + if (!nodeId) return; try { const data = await api.get(`/deep-assessments/${id}/graph/node`, { node_id: nodeId, offset: appendBody ? bodyOffset : 0, links_offset: appendLinks ? linksOffset : 0 }); - const next = data?.node || null; - setNode(prev => ( - appendBody && prev && next && prev.id === next.id - ? { ...next, body: `${prev.body || ''}${next.body || ''}` } - : next - )); - setBodyOffset(Number(data?.next_offset) || 0); - setBodyMore(Boolean(data?.has_more)); - setRelations(prev => (appendLinks ? [...prev, ...(data?.relations || [])] : (data?.relations || []))); - setLinksOffset(Number(data?.relations_next_offset) || 0); - setLinksMore(Boolean(data?.relations_has_more)); - setPathView(null); + if (request !== nodeRequest.current) return; + if (!appendLinks) { + const next = data?.node || null; + setNode(prev => ( + appendBody && prev && next && prev.id === next.id + ? { ...next, body: `${prev.body || ''}${next.body || ''}` } + : next + )); + setBodyOffset(Number(data?.next_offset) || 0); + setBodyMore(Boolean(data?.has_more)); + } + if (!appendBody) { + setRelations(prev => (appendLinks ? [...prev, ...(data?.relations || [])] : (data?.relations || []))); + setLinksOffset(Number(data?.relations_next_offset) || 0); + setLinksMore(Boolean(data?.relations_has_more)); + } } catch (error) { - toastError(error, '读取节点失败'); + if (request === nodeRequest.current) toastError(error, '读取节点失败'); } finally { - setNodeLoading(false); + if (request === nodeRequest.current) setNodeLoading(false); } }, [id, bodyOffset, linksOffset]); - useEffect(() => { selectRef.current = selectNode; }, [selectNode]); - - // cytoscape 仅在图谱页按需加载,容器高度由页面样式固定。 - useEffect(() => { - const source = graph?.nodes || []; - if (!source.length || !containerRef.current) { - if (cyRef.current) { - cyRef.current.destroy(); - cyRef.current = null; - } - return undefined; - } - let disposed = false; - let cy = null; - const unique = []; - const seen = new Set(); - source.forEach(item => { - if (!seen.has(item.id)) { - seen.add(item.id); - unique.push(item); - } - }); - import('cytoscape').then(module => { - const cytoscape = module.default || module; - if (disposed || !containerRef.current) return; - const elements = [ - ...unique.map(item => ({ - data: { - id: item.id, - label: truncateText(item.title || item.id, 32), - kind: item.kind, - state: item.state, - color: GRAPH_KIND_COLOR[item.kind] || '#86909c', - boundary: item.boundary ? 1 : 0 - } - })), - ...(graph.edges || []) - .filter(edge => seen.has(edge.source) && seen.has(edge.target)) - .map((edge, index) => ({ - data: { - id: `edge-${index}`, - source: edge.source, - target: edge.target, - relation: edge.relation, - projection: edge.projection || '' - } - })) - ]; - cy = cytoscape({ - container: containerRef.current, - elements, - style: CY_STYLE, - layout: { - name: unique.length > 45 ? 'cose' : 'breadthfirst', - directed: true, - padding: 28, - animate: false, - spacingFactor: 1.2 - }, - wheelSensitivity: 0.2, - minZoom: 0.15, - maxZoom: 3 - }); - updateLabelColors(cy); - cy.on('tap', 'node', event => selectRef.current?.(event.target.id())); - cyRef.current = cy; - }).catch(error => { - toastError(error, '图谱渲染失败'); - }); - return () => { - disposed = true; - if (cy) cy.destroy(); - if (cyRef.current === cy) cyRef.current = null; - }; - }, [graph]); - - useEffect(() => { - if (cyRef.current) updateLabelColors(cyRef.current); - }, [theme]); - const loadPath = async () => { if (!node) return; + const request = nodeRequest.current; setPathLoading(true); try { const data = await api.get(`/deep-assessments/${id}/evidence-path`, { fact_id: node.id }); - setPathView(data); + if (request === nodeRequest.current) setPathView(data); } catch (error) { - toastError(error, '读取证据路径失败'); + if (request === nodeRequest.current) toastError(error, '读取证据路径失败'); } finally { - setPathLoading(false); + if (request === nodeRequest.current) setPathLoading(false); } }; - const fit = () => cyRef.current?.fit(undefined, 30); const relayout = () => { const cy = cyRef.current; if (!cy) return; - cy.layout({ - name: cy.nodes().length > 45 ? 'cose' : 'breadthfirst', - directed: true, - padding: 28, - animate: true, - spacingFactor: 1.2 - }).run(); + const positions = graphPositions(model); + cy.nodes().positions(node => positions.get(node.id())); + fitGraph(cy); }; const headExtra = ( @@ -246,14 +125,13 @@ export default function GraphTab({ id, reloadToken }) { onChange={event => { setView(event.target.value); setOffset(0); }} /> - - ); const nodeOptions = nodes.map(item => ({ value: item.id, + title: item.title || item.id, label: `${item.boundary ? '引用 · ' : ''}${kindText(t, item.kind)} · ${truncateText(item.title || item.id, 40)}` })); @@ -261,10 +139,16 @@ export default function GraphTab({ id, reloadToken }) {
resource.reload()} /> + selectNode(`step:${stepId}`, { center: true })} + onGoIntents={onGoIntents} + />
当前页节点 {graph?.primary_count ?? Math.max(0, nodes.length - 1)} / {graph?.total ?? 0} @@ -282,18 +166,20 @@ export default function GraphTab({ id, reloadToken }) { {resource.loading && !graph ? 正在读取图谱… : null}