diff --git a/CHANGELOG.md b/CHANGELOG.md index f1be2465..c884c61e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 2026-11-15 · 大规模探索链路与节点阅读修复 + +- 修复循环引用将整组节点排成单列的问题;布局只避开回边的层级计算,原始节点、连线和证据保持完整,同层大量节点采用紧凑排列。 +- 新增可定位的图缩略导航和关系着色;选中画布外或过小的节点时定位到可读尺度,自动刷新继续保留用户视图。 +- 将多个目标资产链接放入详情正文的折叠区,避免固定操作区挤压正文;切换双图时不再继承空白详情栏。 + ## 2026-11-15 · 深度测评图阅读体验 - 整理任务标题、图工具栏及搜索间距,修复资产搜索焦点边框被裁切和控件挤靠,补充空资产提示。 diff --git a/docs/zh-CN/deep-assessments.md b/docs/zh-CN/deep-assessments.md index fd1e9036..94bd4c61 100644 --- a/docs/zh-CN/deep-assessments.md +++ b/docs/zh-CN/deep-assessments.md @@ -10,6 +10,8 @@ 节点详情默认使用较宽的阅读栏,可拖动图与详情之间的分隔线调整宽度;键盘聚焦分隔线后,左右方向键调整,Home 或双击恢复默认宽度。「展开阅读」将当前节点铺满工作区,点击「返回图」恢复分栏。摘要、执行说明、原始回执和来源分别展示;正文独立滚动,自动刷新保留阅读位置和已展开的来源,切换节点从顶部开始。窄屏改为上下布局,也可展开阅读。 +较大图显示缩略导航,可点击定位,也可聚焦后用方向键平移。节点类型和状态、关系颜色帮助区分链路;选中节点显示其相连关系的文字,位于画布外或缩得过小时自动定位到可读尺度。循环引用的回边保留,只在计算层级时避开,避免整组挤成单列。多个目标资产链接在正文中折叠展示,不占据固定底部操作区。全图仍按节点分页,大图概览不能保证每个节点的文字同时清晰,可选中节点或展开关联分支阅读。 + 资产范围切换、搜索和图操作集中在工具栏,说明与图例可按需展开。未关联资产或搜索无结果时显示明确提示;共享资产记录可展开查看。节点详情按字段显示资产信息,并保留原始记录和来源跳转。 「归档」保留目标、意图、图、回执、事实和漏洞关联,默认列表隐藏,可切换「已归档」查看和恢复。执行中、清理中或结果不明的任务必须先暂停并完成核对,不能直接归档。恢复归档只回到列表,待执行任务需要手动开始;归档记录不会被重启恢复或新事实唤醒。 diff --git a/scripts/deep-assessments-browser.test.cjs b/scripts/deep-assessments-browser.test.cjs index 8b0b8de4..3deb4b37 100644 --- a/scripts/deep-assessments-browser.test.cjs +++ b/scripts/deep-assessments-browser.test.cjs @@ -284,6 +284,9 @@ test('graph preserves the viewport through polling, side panel resize and tab ch await page.locator('[data-da-action="details"][data-id="t0"]').click(); await page.locator('#da-graph-select option[value="step:s3"]').waitFor({state:'attached'}); const before=await page.locator('#da-graph-canvas').boundingBox(); + const navigator=page.locator('.da-graph-minimap');await navigator.waitFor({state:'visible'}); + const panBefore=await page.evaluate(()=>fixtureGraph.pan());await navigator.press('ArrowRight'); + assert.equal((await page.evaluate(()=>fixtureGraph.pan())).x,panBefore.x-80); await page.evaluate(()=>{fixtureGraph.zoom(.8);fixtureGraph.pan({x:70,y:40});}); const positions=await page.evaluate(()=>Object.fromEntries(fixtureGraph.nodes().map(n=>[n.id(),n.position()]))); assert.ok(new Set(Object.values(positions).map(p=>p.x)).size>2); @@ -313,10 +316,11 @@ test('graph preserves the viewport through polling, side panel resize and tab ch test('long node details have an adjustable reader and keep their position through refreshes',async t=>{ const {page,state}=await fixture(t),task=state.tasks.get('t0'); + await page.setViewportSize({width:1572,height:870}); const instruction=Array.from({length:45},(_,i)=>`${i+1}. 检查本地样例记录,保存观察结果并注明来源。这里是用于验证长文本阅读布局的内容,不会执行网络操作。`).join('\n\n'); task.name='长文本阅读示例';task.graph={nodes:[ {id:'goal',kind:'goal',title:'整理样例证据',state:'running',body:'整理本地样例证据并形成可核对记录。',source:{}}, - {id:'step:read',kind:'step',step_id:'read',title:'核对样例记录与证据来源',state:'running',body:'已整理记录,正在核对原始回执。\n\nInstruction: '+instruction,source:{evidence:['receipt:sample']}}, + {id:'step:read',kind:'step',step_id:'read',title:'核对样例记录与证据来源',state:'running',body:'已整理记录,正在核对原始回执。\n\nInstruction: '+instruction,source:{evidence:['receipt:sample'],asset_ids:Array.from({length:13},(_,i)=>'fixture-asset-00000000-0000-0000-'+i)}}, {id:'receipt:sample',kind:'receipt',step_id:'read',title:'本地样例回执',state:'completed',body:Array.from({length:120},(_,i)=>`record ${i}: example.test /fixture — verified fixture`).join('\n'),source:{tool:'fixture'}} ],edges:[{source:'goal',target:'step:read',relation:'plans'},{source:'step:read',target:'receipt:sample',relation:'executes'}],total:2,folded:0,has_more:false}; await page.locator('[data-da-action="details"][data-id="t0"]').click(); @@ -330,10 +334,15 @@ test('long node details have an adjustable reader and keep their position throug const geometry=await content.evaluate(el=>({height:el.clientHeight,total:el.scrollHeight,font:parseFloat(getComputedStyle(el.querySelector('.da-node-prose')).fontSize),family:getComputedStyle(el.querySelector('.da-node-prose')).fontFamily})); assert.ok(geometry.height>=200&&geometry.total>geometry.height,JSON.stringify(geometry)); assert.ok(geometry.font>=14);assert.doesNotMatch(geometry.family,/monospace/i); + assert.ok((await panel.locator('.da-node-actions').boundingBox()).height<100); + assert.equal(await panel.locator('.da-node-actions [data-da-action="intent-asset"]').count(),0); + assert.equal(await panel.locator('.da-node-links [data-da-action="intent-asset"]').count(),13); + await panel.locator('.da-node-links summary').click(); await content.evaluate(el=>el.scrollTop=480); const scroll=await content.evaluate(el=>el.scrollTop); await page.evaluate(()=>DeepAssessments.refresh()); assert.equal(await content.evaluate(el=>el.scrollTop),scroll); + assert.equal(await panel.locator('.da-node-links').getAttribute('open'),''); await page.evaluate(()=>fixtureGraph.zoom(.75)); const separator=await bar.boundingBox(); await page.mouse.move(separator.x+separator.width/2,separator.y+40);await page.mouse.down();await page.mouse.move(separator.x-100,separator.y+40);await page.mouse.up(); @@ -400,3 +409,38 @@ test('asset search controls have room for focus and empty graphs explain the nex if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'asset-reader.png'),fullPage:true}); assert.deepEqual(state.errors,[]);assert.equal(state.requests.filter(r=>r.method==='POST').length,0); }); + +test('large cyclic evidence graphs keep lineage and focus a selected node at readable scale',async t=>{ + const {page,state}=await fixture(t),task=state.tasks.get('t0'); + await page.setViewportSize({width:1572,height:870}); + task.name='探索链路布局回归'; + const nodes=[{id:'goal',kind:'goal',title:'核对样例记录',body:'本地界面夹具',state:'running',source:{}}],edges=[]; + for(let i=0;i<12;i++){ + nodes.push({id:'step:'+i,kind:'step',step_id:String(i),title:'核对方向 '+i,state:i===5?'running':'completed',body:'样例记录核对结果。\n\nInstruction: 核对已有记录与证据来源,不发起网络操作。',source:{asset_ids:Array.from({length:13},(_,j)=>'fixture-asset-'+j)}}); + nodes.push({id:'fact:'+i,kind:'fact',step_id:String(i),title:'样例观察 '+i,state:'observed',body:'记录中的直接观察。',source:{}}); + nodes.push({id:'observation:'+i,kind:'observation',step_id:String(i),title:'阶段记录 '+i,state:'note',body:'阶段记录',source:{}}); + edges.push({source:i?'step:'+(i-1):'goal',target:'step:'+i,relation:i?'depends_on':'plans'},{source:'step:'+i,target:'fact:'+i,relation:'produces'},{source:'fact:'+i,target:'step:0',relation:'informs'},{source:'step:'+i,target:'observation:'+i,relation:'records'}); + for(let j=0;j<3;j++){ + const id='receipt:'+i+':'+j;nodes.push({id,kind:'receipt',step_id:String(i),title:'样例回执 '+j,state:'completed',body:'fixture output',source:{}}); + edges.push({source:'step:'+i,target:id,relation:'executes'},{source:id,target:'fact:'+i,relation:'supports'}); + } + } + task.graph={nodes,edges,total:nodes.length-1,folded:0,has_more:false}; + await page.locator('[data-da-action="details"][data-id="t0"]').click(); + await page.locator('#da-graph-select option[value="step:5"]').waitFor({state:'attached'}); + const graphState=await page.evaluate(()=>({nodes:fixtureGraph.nodes().length,edges:fixtureGraph.edges().length,columns:new Set(fixtureGraph.nodes().map(n=>n.position().x)).size})); + assert.equal(graphState.nodes,nodes.length);assert.equal(graphState.edges,edges.length);assert.ok(graphState.columns>5); + await page.locator('#da-graph-select').selectOption('step:5'); + await page.locator('.da-node-content').waitFor(); + await page.waitForFunction(()=>fixtureGraph.zoom()>=.65); + assert.ok((await page.locator('.da-node-content').boundingBox()).height>=200); + const pos=await page.evaluate(()=>({node:fixtureGraph.getElementById('step:5').renderedPosition(),width:fixtureGraph.width(),height:fixtureGraph.height()})); + assert.ok(pos.node.x>=0&&pos.node.x<=pos.width&&pos.node.y>=0&&pos.node.y<=pos.height); + const zoom=await page.evaluate(()=>fixtureGraph.zoom()); + await page.evaluate(()=>DeepAssessments.refresh());assert.equal(await page.evaluate(()=>fixtureGraph.zoom()),zoom); + if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'large-evidence-graph.png'),fullPage:true}); + await page.locator('[data-da-action="tab"][data-tab="assets"]').click();await page.locator('#da-asset-select').waitFor(); + await page.locator('[data-da-action="tab"][data-tab="graph"]').click();await page.locator('#da-graph-select').waitFor(); + assert.equal(await page.locator('#da-graph-node').isVisible(),false,'switching graphs must not expose an empty inherited panel'); + assert.deepEqual(state.errors,[]);assert.equal(state.requests.filter(r=>r.method==='POST').length,0); +}); diff --git a/web/static/css/deep-assessments.css b/web/static/css/deep-assessments.css index 5f3b4863..6c816ffb 100644 --- a/web/static/css/deep-assessments.css +++ b/web/static/css/deep-assessments.css @@ -293,8 +293,18 @@ body.da-drawer-open { overflow: hidden; } .da-node-properties { margin:0; display:grid; gap:12px; } .da-node-properties > div { display:grid; grid-template-columns:90px minmax(0,1fr); gap:12px; font-size:14px; line-height:1.7; } .da-node-properties dt { color:var(--text-secondary); }.da-node-properties dd { margin:0; overflow-wrap:anywhere; } -.da-node-actions { flex-shrink:0; padding:12px 18px; border-top:1px solid var(--border-color); background:var(--bg-primary); } +.da-node-actions { flex-shrink:0; padding:12px 18px; max-height:30%; overflow:auto; border-top:1px solid var(--border-color); background:var(--bg-primary); } .da-node-actions button { font-size:13px; } +.da-node-links { margin:16px 0; font-size:13px; } +.da-node-links > summary { cursor:pointer; margin-bottom:10px; } +.da-node-asset-links { display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); gap:8px; } +.da-node-asset-links button { text-align:left; font-size:12px; overflow-wrap:anywhere; } +#da-workspace #da-graph-canvas, #da-workspace #da-asset-canvas { position:relative; background-image:radial-gradient(var(--border-color) 1px,transparent 1px); background-size:18px 18px; } +.da-graph-minimap { position:absolute; right:12px; bottom:12px; z-index:2; width:150px; height:88px; border:1px solid var(--border-color); border-radius:6px; background:var(--bg-primary); box-shadow:0 2px 8px #0001; cursor:crosshair; opacity:.92; } +.da-graph-minimap:focus-visible { outline:2px solid var(--accent-color); outline-offset:2px; } +.da-relation-legend { display:flex; gap:16px; flex-wrap:wrap; margin-top:8px; } +.da-relation-legend span::before { content:""; display:inline-block; width:20px; height:2px; margin-right:6px; vertical-align:middle; background:var(--relation-color); } +.da-relation-depends_on { --relation-color:#6366f1; }.da-relation-informs { --relation-color:#059669; }.da-relation-produces { --relation-color:#d97706; }.da-relation-supports { --relation-color:#e11d48; } .da-node-empty { padding:24px 18px; color:var(--text-secondary); font-size:14px; } .da-asset-records { border:1px solid var(--border-color); border-radius:6px; padding:12px; } .da-asset-records[hidden] { display:none; }.da-asset-records > summary { cursor:pointer; font-size:13px; font-weight:600; } diff --git a/web/static/i18n/en-US.json b/web/static/i18n/en-US.json index 1086ce67..6c12461a 100644 --- a/web/static/i18n/en-US.json +++ b/web/static/i18n/en-US.json @@ -5500,7 +5500,8 @@ "instruction": "Instructions", "content": "Node content", "output": "Execution receipt" - } + }, + "graphNavigator": "Graph navigator: click to locate, arrow keys to pan" }, "assessmentFindingLinks": { "source": "Source assessment", diff --git a/web/static/i18n/ru-RU.json b/web/static/i18n/ru-RU.json index b8253e7e..97d7b249 100644 --- a/web/static/i18n/ru-RU.json +++ b/web/static/i18n/ru-RU.json @@ -5513,7 +5513,8 @@ "instruction": "Инструкции", "content": "Содержание узла", "output": "Результат выполнения" - } + }, + "graphNavigator": "Навигация по графу: нажмите для перехода, стрелки для перемещения" }, "assessmentFindingLinks": { "source": "Исходная оценка", diff --git a/web/static/i18n/zh-CN.json b/web/static/i18n/zh-CN.json index be6d4c92..57b0b78b 100644 --- a/web/static/i18n/zh-CN.json +++ b/web/static/i18n/zh-CN.json @@ -5442,7 +5442,8 @@ "path": "路径", "active": "活跃", "inactive": "停用" - } + }, + "graphNavigator": "图导航:点击定位,方向键平移" }, "assessmentFindingLinks": { "source": "来源深度测评", diff --git a/web/static/js/deep-assessment-graph.js b/web/static/js/deep-assessment-graph.js index 2cac8c61..ec52dfb4 100644 --- a/web/static/js/deep-assessment-graph.js +++ b/web/static/js/deep-assessment-graph.js @@ -1,7 +1,7 @@ /* Read-only graph renderer; task state and evidence remain owned by the backend. */ (function () { 'use strict'; - let chart = null, host = null, key = '', onSelect = null, observer = null, theme = '', size = null; + let chart = null, host = null, key = '', onSelect = null, observer = null, theme = '', size = null, mapElement = null, selectedID = '', mapFrame = null; const views = new Map(); function remember() { if(!chart || !key || !size?.width || !size?.height)return; @@ -22,6 +22,8 @@ function destroy() { remember(); observer?.disconnect(); observer = null; + if(mapFrame!==null)cancelAnimationFrame(mapFrame);mapFrame=null; + mapElement?.remove();mapElement=null;selectedID=''; chart?.destroy(); chart = null; host = null; key = ''; theme = ''; size=null; } function relationLabel(key) { @@ -38,45 +40,112 @@ { selector: 'node[kind = "digest"]', style: { 'border-style': 'dashed' } }, { selector: 'node[state = "running"]', style: { 'background-color': '#dbeafe', color: '#172033' } }, { selector: 'node:selected', style: { 'border-width': 4, 'overlay-opacity': .08, 'overlay-color': '#3b82f6' } }, - { selector: 'edge', style: { width: 1.5, 'line-color': '#94a3b8', 'target-arrow-color': '#94a3b8', 'target-arrow-shape': 'triangle', 'curve-style': 'bezier', label: 'data(relationLabel)', 'font-size': 10, color: text, 'text-background-color': surface, 'text-background-opacity': .8 } }, + { selector: 'edge', style: { width: 1.5, 'line-color': 'data(relationColor)', 'target-arrow-color': 'data(relationColor)', 'target-arrow-shape': 'triangle', 'curve-style': 'bezier', label: '', opacity:.65, 'font-size': 10, color: text, 'text-background-color': surface, 'text-background-opacity': .9 } }, + { selector: 'edge.da-connected', style: { label:'data(relationLabel)',width:2.5,opacity:1 } }, { selector: 'edge[relation = "supports"], edge[relation = "informs"]', style: { 'line-style': 'dashed' } }, ]; } - function layout(preferred = new Map()) { - if (!chart) return; - const nodes=chart.nodes().toArray().sort((a,b)=>a.id().localeCompare(b.id())); - const adjacency=new Map(nodes.map(n=>[n.id(),[]])); - chart.edges().forEach(e=>adjacency.get(e.source().id()).push(e.target().id())); - // Condense evidence/review cycles before assigning columns. - let nextIndex=0;const indices=new Map(),low=new Map(),stack=[],onStack=new Set(),components=[],component=new Map(); + // Only layout ignores DFS back edges. Every original relation remains rendered. + // Collapsing a strongly connected component into one rank made real evidence + // cycles turn an entire assessment into a single unreadable vertical column. + function computeLayout(nodes, edges, preferred = new Map()) { + const kindOrder={goal:0,domain:0,step:1,subdomain:1,ip:2,service:3,fact:4,finding:5,memory:6}; + const ordered=[...nodes].sort((a,b)=>(kindOrder[a.kind]??7)-(kindOrder[b.kind]??7)||a.id.localeCompare(b.id)); + const ids=new Set(ordered.map(n=>n.id)), outgoing=new Map(ordered.map(n=>[n.id,[]])); + const structural=new Set(['plans','depends_on','produces','executes','records','summarizes','exposes','serves','contains','associated_with']); + const valid=edges.filter(e=>ids.has(e.source)&&ids.has(e.target)&&e.source!==e.target); + for(const edge of [...valid].sort((a,b)=>Number(structural.has(b.relation))-Number(structural.has(a.relation))||a.target.localeCompare(b.target)))outgoing.get(edge.source).push(edge); + const state=new Map(),back=new Set(); const visit=id=>{ - indices.set(id,nextIndex);low.set(id,nextIndex++);stack.push(id);onStack.add(id); - for(const child of adjacency.get(id)){ - if(!indices.has(child)){visit(child);low.set(id,Math.min(low.get(id),low.get(child)));} - else if(onStack.has(child))low.set(id,Math.min(low.get(id),indices.get(child))); - } - if(low.get(id)===indices.get(id)){ - const members=[];let child; - do{child=stack.pop();onStack.delete(child);component.set(child,components.length);members.push(child);}while(child!==id); - components.push(members); + state.set(id,1); + for(const edge of outgoing.get(id)){ + if(state.get(edge.target)===1)back.add(edge); + else if(!state.has(edge.target))visit(edge.target); } + state.set(id,2); }; - nodes.forEach(n=>{if(!indices.has(n.id()))visit(n.id());}); - const outgoing=components.map(()=>new Set()),incoming=components.map(()=>0),depth=components.map(()=>0); - chart.edges().forEach(e=>{const from=component.get(e.source().id()),to=component.get(e.target().id());if(from!==to&&!outgoing[from].has(to)){outgoing[from].add(to);incoming[to]++;}}); - const queue=components.map((_,i)=>i).filter(i=>incoming[i]===0); - for(let i=0;iMath.abs(p.x-x)<250&&Math.abs(p.y-y)<120))y+=132; - const pos={x,y};positions.set(node.id(),pos);occupied.push(pos); + ordered.forEach(n=>{if(!state.has(n.id))visit(n.id);}); + const indegree=new Map(ordered.map(n=>[n.id,0])),rank=new Map(ordered.map(n=>[n.id,0])); + for(const edge of valid)if(!back.has(edge))indegree.set(edge.target,indegree.get(edge.target)+1); + const queue=ordered.filter(n=>!indegree.get(n.id)).map(n=>n.id); + for(let i=0;i(columns[rank.get(n.id)]??=[]).push(n.id)); + const neighbors=new Map(ordered.map(n=>[n.id,[]])); + for(const e of valid){neighbors.get(e.source).push(e.target);neighbors.get(e.target).push(e.source);} + // Stable barycenter sweeps reduce crossings without changing causal ranks. + for(let pass=0;pass<4;pass++){ + const direction=pass%2?-1:1; + for(let c=direction>0?1:columns.length-2;c>=0&&c[id,i])); + const scored=(columns[c]||[]).map((id,i)=>{ + const positions=neighbors.get(id).filter(n=>previous.has(n)).map(n=>previous.get(n)); + return {id,index:i,score:positions.length?positions.reduce((a,b)=>a+b,0)/positions.length:i}; + }); + columns[c]=scored.sort((a,b)=>a.score-b.score||a.index-b.index).map(n=>n.id); + } + } + const positions=new Map(),occupied=[],rows=Math.max(6,Math.ceil(Math.sqrt(nodes.length*.75))); + for(const node of ordered)if(preferred.has(node.id)){ + const p=preferred.get(node.id);positions.set(node.id,p);occupied.push(p); + } + let x=145; + for(const column of columns){ + if(!column?.length)continue; + column.forEach((id,i)=>{ + if(positions.has(id))return; + let p={x:x+Math.floor(i/rows)*300,y:70+(i%rows)*140}; + while(occupied.some(old=>Math.abs(old.x-p.x)<250&&Math.abs(old.y-p.y)<125))p={x:p.x,y:p.y+140}; + positions.set(id,p);occupied.push(p); + }); + x+=Math.ceil(column.length/rows)*300; + } + return positions; + } + function layout(preferred = new Map()) { + if(!chart)return; + const positions=computeLayout(chart.nodes().map(n=>n.data()),chart.edges().map(e=>e.data()),preferred); chart.layout({name:'preset',positions:n=>positions.get(n.id()),fit:false}).run(); } - function render(container, graph, taskKey, select, label) { + function updateMap() { + if(!chart || !mapElement || !host?.clientWidth)return; + mapElement.style.display=chart.nodes().length<8?'none':''; + const bounds=chart.nodes().boundingBox(),pad=40; + mapElement.setAttribute('viewBox',[bounds.x1-pad,bounds.y1-pad,bounds.w+pad*2,bounds.h+pad*2].join(' ')); + mapElement.replaceChildren(); + const rectangle=(x,y,width,height,fill,stroke)=>{ + const r=document.createElementNS('http://www.w3.org/2000/svg','rect'); + Object.entries({x,y,width,height,fill,stroke:stroke||'none'}).forEach(([k,v])=>r.setAttribute(k,String(v))); + mapElement.append(r);return r; + }; + chart.nodes().forEach(n=>{const p=n.position();rectangle(p.x-112,p.y-44,224,88,n.data('color'));}); + const e=chart.extent(),viewport=rectangle(e.x1,e.y1,e.w,e.h,'#3b82f61a','#2563eb'); + viewport.setAttribute('stroke-width','2');viewport.setAttribute('vector-effect','non-scaling-stroke'); + } + function installMap() { + mapElement=document.createElementNS('http://www.w3.org/2000/svg','svg'); + mapElement.classList.add('da-graph-minimap');mapElement.setAttribute('role','button');mapElement.setAttribute('tabindex','0'); + const path='deepAssessments.graphNavigator',label=window.t?.(path); + mapElement.setAttribute('aria-label',label&&label!==path?label:'图导航:点击定位,方向键平移'); + host.append(mapElement); + mapElement.addEventListener('pointerdown',e=>e.stopPropagation()); + mapElement.addEventListener('click',e=>{ + e.stopPropagation();const p=mapElement.createSVGPoint();p.x=e.clientX;p.y=e.clientY; + const matrix=mapElement.getScreenCTM();if(!matrix)return; + const center=p.matrixTransform(matrix.inverse()),zoom=chart.zoom(); + chart.pan({x:host.clientWidth/2-center.x*zoom,y:host.clientHeight/2-center.y*zoom});remember(); + }); + mapElement.addEventListener('keydown',e=>{ + const directions={ArrowLeft:[80,0],ArrowRight:[-80,0],ArrowUp:[0,80],ArrowDown:[0,-80]}; + if(directions[e.key]){e.preventDefault();chart.panBy({x:directions[e.key][0],y:directions[e.key][1]});remember();} + }); + chart.on('pan zoom position',()=>{if(mapFrame===null)mapFrame=requestAnimationFrame(()=>{mapFrame=null;updateMap();});});updateMap(); + } + function render(container, graph, taskKey, select, label, stateLabel = () => '') { onSelect = select; const nodes = graph?.nodes || []; if (host !== container || key !== taskKey) { destroy(); host = container; key = taskKey; } @@ -88,10 +157,11 @@ } return; } - const elements = nodes.map(node => ({ data: { id: node.id, kind: node.kind, state: node.state, label: label(node.kind) + '\n' + (Array.from(node.title).length > 42 ? Array.from(node.title).slice(0, 42).join('') + '…' : node.title), color: colors[node.kind] || colors.step } })); + const elements = nodes.map(node => ({ data: { id: node.id, kind: node.kind, state: node.state, label: label(node.kind) + (node.state?' · '+stateLabel(node.state):'') + '\n' + (Array.from(node.title).length > 42 ? Array.from(node.title).slice(0, 42).join('') + '…' : node.title), color: colors[node.kind] || colors.step } })); const ids = new Set(nodes.map(n => n.id)); for (const edge of graph.edges || []) if (ids.has(edge.source) && ids.has(edge.target)) { - elements.push({ data: { id: 'edge:' + JSON.stringify([edge.source, edge.relation, edge.target]), ...edge, relationLabel: relationLabel(edge.relation) } }); + const relationColor=({plans:'#6366f1',depends_on:'#6366f1',informs:'#059669',derives:'#059669',produces:'#d97706',supports:'#e11d48',reviews:'#e11d48',summarizes:'#a855f7',archives:'#a855f7'})[edge.relation]||'#94a3b8'; + elements.push({ data: { id: 'edge:' + JSON.stringify([edge.source, edge.relation, edge.target]), ...edge, relationLabel: relationLabel(edge.relation),relationColor } }); } if (!chart) { chart = window.cytoscape({ container: host, elements, style: styles(), layout: { name: 'preset' }, minZoom: .12, maxZoom: 2.2, wheelSensitivity: .25 }); @@ -99,6 +169,7 @@ const saved=views.get(taskKey); layout(saved?.positions);size={width:host.clientWidth,height:host.clientHeight}; if(saved){chart.zoom(saved.zoom);chart.pan({x:size.width/2-saved.center.x*saved.zoom,y:size.height/2-saved.center.y*saved.zoom});}else fit(); + installMap(); if (typeof ResizeObserver === 'function') { observer = new ResizeObserver(resize); observer.observe(host); } } else { const existing = new Set(chart.elements().map(e => e.id())); @@ -117,7 +188,7 @@ layout(positions); chart.zoom(zoom); chart.pan(pan); } - resize(); + resize();updateMap(); } const currentTheme = document.documentElement.getAttribute('data-theme') || document.body.className; if (theme !== currentTheme) { chart.style(styles()); theme = currentTheme; } @@ -126,5 +197,17 @@ if (!chart || !host) return; chart.zoom({ level: chart.zoom() * factor, renderedPosition: { x: host.clientWidth / 2, y: host.clientHeight / 2 } }); } - window.DeepAssessmentGraph = { render, destroy, select: id => { if (chart) { chart.nodes().unselect(); chart.getElementById(id).select(); } }, fit, relayout: () => { layout(); fit(); }, zoomIn: () => zoom(1.25), zoomOut: () => zoom(.8) }; + function selectNode(id) { + if(!chart)return; + const changed=selectedID!==id;selectedID=id; + chart.nodes().unselect();const node=chart.getElementById(id);node.select(); + chart.edges().removeClass('da-connected');node.connectedEdges().addClass('da-connected'); + if(changed&&node.length){ + const p=node.position(),zoom=Math.max(.65,chart.zoom()),rendered=node.renderedPosition(); + if(chart.zoom()<.65||rendered.x<0||rendered.x>host.clientWidth||rendered.y<0||rendered.y>host.clientHeight){ + chart.zoom(zoom);chart.pan({x:host.clientWidth/2-p.x*zoom,y:host.clientHeight/2-p.y*zoom}); + } + } + } + window.DeepAssessmentGraph = { render, destroy, computeLayout, select:selectNode, fit, relayout: () => { layout(); fit(); }, zoomIn: () => zoom(1.25), zoomOut: () => zoom(.8) }; })(); diff --git a/web/static/js/deep-assessment-graph.test.cjs b/web/static/js/deep-assessment-graph.test.cjs new file mode 100644 index 00000000..8a1cb525 --- /dev/null +++ b/web/static/js/deep-assessment-graph.test.cjs @@ -0,0 +1,49 @@ +const {test}=require('node:test'); +const assert=require('node:assert/strict'); +const fs=require('node:fs'); +const path=require('node:path'); +const vm=require('node:vm'); +const context={window:{}}; +vm.runInNewContext(fs.readFileSync(path.join(__dirname,'deep-assessment-graph.js'),'utf8'),context); +const layout=context.window.DeepAssessmentGraph.computeLayout; + +test('evidence feedback cycles retain distinct causal columns and every node',()=>{ + const nodes=[{id:'goal',kind:'goal'},{id:'step:a',kind:'step'},{id:'step:b',kind:'step'},{id:'receipt:a',kind:'receipt'},{id:'fact:a',kind:'fact'}]; + const edges=[ + {source:'goal',target:'step:a',relation:'plans'}, + {source:'step:a',target:'receipt:a',relation:'executes'}, + {source:'receipt:a',target:'fact:a',relation:'supports'}, + {source:'fact:a',target:'step:a',relation:'informs'}, + {source:'step:a',target:'step:b',relation:'depends_on'}, + {source:'step:b',target:'fact:a',relation:'reviews'}, + ]; + const original=JSON.stringify({nodes,edges}),positions=layout(nodes,edges); + assert.equal(positions.size,nodes.length); + assert.ok(positions.get('receipt:a').x>positions.get('step:a').x); + assert.ok(positions.get('step:b').x>positions.get('step:a').x); + assert.ok(new Set([...positions.values()].map(p=>p.x)).size>=4); + assert.equal(JSON.stringify({nodes,edges}),original,'layout must not delete evidence or relations'); +}); + +test('large sibling groups wrap into compact columns without overlapping',()=>{ + const nodes=[{id:'goal',kind:'goal'},...Array.from({length:80},(_,i)=>({id:'receipt:'+i,kind:'receipt'}))]; + const edges=nodes.slice(1).map(n=>({source:'goal',target:n.id,relation:'executes'})); + const positions=layout(nodes,edges),points=[...positions.values()]; + assert.equal(positions.size,81); + assert.ok(Math.max(...points.map(p=>p.y))-Math.min(...points.map(p=>p.y))<1500); + assert.ok(new Set(points.map(p=>p.x)).size>3); + for(let i=0;i=250||Math.abs(points[i].y-points[j].y)>=125); + } + assert.deepEqual([...layout(nodes,edges)], [...positions]); +}); + +test('polling keeps existing positions while placing new evidence safely',()=>{ + const nodes=[{id:'goal',kind:'goal'},{id:'step:a',kind:'step'}]; + const edges=[{source:'goal',target:'step:a',relation:'plans'}]; + const existing=layout(nodes,edges); + nodes.push({id:'fact:new',kind:'fact'});edges.push({source:'step:a',target:'fact:new',relation:'produces'}); + const next=layout(nodes,edges,existing); + for(const [id,p] of existing)assert.deepEqual(next.get(id),p); + assert.equal(next.size,3); +}); diff --git a/web/static/js/deep-assessments.js b/web/static/js/deep-assessments.js index f8e1f6ad..76e6d1b5 100644 --- a/web/static/js/deep-assessments.js +++ b/web/static/js/deep-assessments.js @@ -343,13 +343,13 @@ function renderGraph(body) { if (!body.querySelector('#da-graph-canvas')) { window.DeepAssessmentGraph?.destroy(); - body.innerHTML = `
${button('graph-home', L('graphHome'))}${button('graph-fit', L('graphFit'))}${button('graph-details',L(S.detailsOpen?'hideDetails':'showDetails'),'aria-expanded="'+S.detailsOpen+'"')}${button('graph-layout',L('graphLayout'))}${button('graph-in', '+', 'aria-label="Zoom in"')}${button('graph-out', '−', 'aria-label="Zoom out"')}
${esc(L('graphHelp'))}

${esc(L('graphHint'))}

${['goal','step','fact','finding','observation','receipt','memory','digest','guidance'].map(k => `${esc(graphKind(k))}`).join('')}
${separator()}
`; + body.innerHTML = `
${button('graph-home', L('graphHome'))}${button('graph-fit', L('graphFit'))}${button('graph-details',L(S.detailsOpen?'hideDetails':'showDetails'),'aria-expanded="'+S.detailsOpen+'"')}${button('graph-layout',L('graphLayout'))}${button('graph-in', '+', 'aria-label="Zoom in"')}${button('graph-out', '−', 'aria-label="Zoom out"')}
${esc(L('graphHelp'))}

${esc(L('graphHint'))}

${['goal','step','fact','finding','observation','receipt','memory','digest','guidance'].map(k => `${esc(graphKind(k))}`).join('')}
${['depends_on','informs','produces','supports'].map(k=>`${esc(tr('graphRelations.'+k,({depends_on:'依赖',informs:'派生',produces:'产出',supports:'支持'})[k]))}`).join('')}
${separator()}
`; } if (!S.graph) { $('da-graph-meta').textContent = L('loading'); return; } $('da-graph-meta').textContent = `${L('graphVisible')} ${Math.max(0, S.graph.nodes.length - 1)} / ${S.graph.total} · ${L('graphFolded')} ${S.graph.folded}`; $('da-graph-select').innerHTML = `` + S.graph.nodes.map(n => ``).join(''); const task = S.id; - window.DeepAssessmentGraph?.render($('da-graph-canvas'), S.graph, task + '/' + S.graphScope + '/' + S.graphOffset, node => { if (S.id === task) void selectGraphNode(node); }, graphKind); + window.DeepAssessmentGraph?.render($('da-graph-canvas'), S.graph, task + '/' + S.graphScope + '/' + S.graphOffset, node => { if (S.id === task) void selectGraphNode(node); }, graphKind, graphState); $('da-graph-pages').innerHTML = `${S.graphOffset ? button('graph-previous', L('previous')) : ''}${S.graph.has_more ? button('graph-next', L('next')) : ''}`; renderGraphNode(); } @@ -358,8 +358,10 @@ const panel=$('da-graph-node');if(!panel)return; const n=S.graphNode; if(!window.AssessmentNodePanel){panel.textContent=n?n.title+'\n'+n.body:L('graphSelect');return;} - const actions=n?`${window.AssessmentExplorationViews?.canAssets()?(n.source?.asset_ids||[]).map(id=>button('intent-asset',L('linkedAssets')+' '+id,`data-asset="${esc(id)}"`)).join(''):''}${n.kind==='finding'?button('open-finding',L('openFinding'),`data-vulnerability="${esc(n.id.slice(8))}"`):''}${n.step_id?button('fact-proof',L('sourceStep'),`data-step="${esc(n.step_id)}"`):''}${['step','digest'].includes(n.kind)?button('graph-expand',L('graphExpand'),`data-node="${esc(n.id)}"`):''}${S.nodeMore?button('graph-more',L('graphMore')):''}`:''; - window.AssessmentNodePanel.render(panel,n?{id:n.id,key:S.id+'/'+n.id,title:n.title,kind:graphKind(n.kind),state:graphState(n.state),sections:window.AssessmentNodePanel.sections(n),source:n.source,actionsHTML:actions}:{emptyText:L('graphSelect')}); + const assets=window.AssessmentExplorationViews?.canAssets()?(n?.source?.asset_ids||[]):[]; + const links=assets.length?``:''; + const actions=n?`${n.kind==='finding'?button('open-finding',L('openFinding'),`data-vulnerability="${esc(n.id.slice(8))}"`):''}${n.step_id?button('fact-proof',L('sourceStep'),`data-step="${esc(n.step_id)}"`):''}${['step','digest'].includes(n.kind)?button('graph-expand',L('graphExpand'),`data-node="${esc(n.id)}"`):''}${S.nodeMore?button('graph-more',L('graphMore')):''}`:''; + window.AssessmentNodePanel.render(panel,n?{id:n.id,key:S.id+'/'+n.id,title:n.title,kind:graphKind(n.kind),state:graphState(n.state),sections:window.AssessmentNodePanel.sections(n),source:n.source,contentHTML:links,actionsHTML:actions}:{emptyText:L('graphSelect')}); } async function selectGraphNode(node, append = false) { const task = S.id, request = ++S.nodeRequest; @@ -419,7 +421,7 @@ if (name === 'refresh') return await refresh(); if (name === 'previous' || name === 'next') { S.page += name === 'previous' ? -1 : 1; S.page = Math.max(0, S.page); writeListRoute();return await refresh(); } if (name === 'select' || name === 'details') { ++S.drawerEpoch; S.focusStepId = ''; S.focusedStep = null; S.originFindingId = ''; S.originFinding = null; S.findingOffset = 0; if (S.id !== data.id) { S.id = data.id; S.readerExpanded=false; S.detailsOpen=false; S.extra=null; S.intentAsset=''; S.intentStatus=''; window.AssessmentExplorationViews?.reset(S.id); S.task = null; S.tab = 'graph'; S.stepOffset = 0; S.stepMore = false; S.stepTotal = 0; S.graph = null; S.graphScope = ''; S.graphOffset = 0; S.graphNode = null; ++S.nodeRequest; S.events = []; S.receipts = []; S.receiptOffset = 0; $('da-guidance').value = ''; $('da-workspace').querySelector('.da-detail-scroll').scrollTop = 0; } writeListRoute();writeRoute(true);showWorkspace();return await refresh(); } - if (name === 'tab') { if(S.tab!==data.tab)S.readerExpanded=false;S.tab = data.tab; writeRoute(); $('da-workspace').querySelector('.da-detail-scroll').scrollTop = 0; return await refresh(); } + if (name === 'tab') { if(S.tab!==data.tab){S.readerExpanded=false;S.detailsOpen=false;}S.tab = data.tab; writeRoute(); $('da-workspace').querySelector('.da-detail-scroll').scrollTop = 0; return await refresh(); } if (name === 'open-finding' || name === 'all-findings') { closeDrawer('da-form-drawer'); hideWorkspace(); window.AssessmentFindingLinks?.openFinding(name === 'open-finding' ? data.vulnerability : '', S.id); return; } if (name === 'finding-evidence') { S.originFindingId = data.vulnerability; S.focusStepId = data.step; S.focusedStep = null; S.originFinding = null; S.tab = 'evidence'; S.receiptOffset = 0; writeRoute(); return await refresh(); } if (name === 'clear-source') { S.focusStepId = ''; S.focusedStep = null; S.originFindingId = ''; S.originFinding = null; S.receiptOffset = 0; writeRoute(); return await refresh(); } diff --git a/web/templates/index.html b/web/templates/index.html index 0029edf4..22b186be 100644 --- a/web/templates/index.html +++ b/web/templates/index.html @@ -50,7 +50,7 @@ - + @@ -7141,10 +7141,10 @@ - - - - + + + +