Spaces:
Sleeping
Sleeping
File size: 39,401 Bytes
5ca3c16 7ebebb0 5ca3c16 7ebebb0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | import {createEditor,portLabel,nodeTitle,connectionIssues,resolveIssueLocation,searchNodes,portStates,spaceForPoint,edgeVelocity} from './workflow-editor.js';
const $=(s,r=document)=>r.querySelector(s), $$=(s,r=document)=>[...r.querySelectorAll(s)];
const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
const json=v=>esc(JSON.stringify(v,null,2));
const stateName={not_started:'未开始',started:'执行中',active:'执行中',completed:'已完成',approved:'已确认',waiting:'待确认',recorded:'已有输出 / 复用',failed:'失败',unknown:'结果未知',queued:'排队中',running:'执行中',waiting_approval:'等待确认',succeeded:'已结束',cancelled:'已取消',verified:'技术通过'};
const label=v=>stateName[v]||v||'—';
const time=v=>v?new Date(v*1000).toLocaleString('zh-CN',{hour12:false}):'—';
const store={workflows:[],atoms:[],flow:null,trace:null,selected:null,positions:{},scale:1,x:0,y:0,palette:false,edge:'control',route:0,views:{},searchMatches:[],searchIndex:0};
const content=$('#content');
const edgePan={frame:0,point:null,paint:null,last:0,
update(e,paint){this.point={x:e.clientX,y:e.clientY};this.paint=paint;if(!this.frame){this.last=performance.now();this.frame=requestAnimationFrame(t=>this.tick(t));}},
tick(t){this.frame=0;const v=$('#canvasViewport');if(!v||!this.point)return;const speed=edgeVelocity(this.point,v.getBoundingClientRect()),dt=Math.min(32,t-this.last);this.last=t;if(speed.x||speed.y){store.x-=speed.x*dt;store.y-=speed.y*dt;transform();this.paint?.(this.point);}this.frame=requestAnimationFrame(t=>this.tick(t));},
stop(){cancelAnimationFrame(this.frame);this.frame=0;this.point=null;this.paint=null;}
};
function ensureSpace(x,y){
const area=spaceForPoint(store.world,x,y);
if(area.sx||area.sy){for(const p of Object.values(store.positions)){p.x+=area.sx;p.y+=area.sy;}store.x-=area.sx*store.scale;store.y-=area.sy*store.scale;transform();$$('[data-node]').forEach(b=>{const p=store.positions[b.dataset.node];b.style.left=p.x+'px';b.style.top=p.y+'px';});}
store.world={width:area.width,height:area.height};$('#canvas').style.width=area.width+'px';$('#canvas').style.height=area.height+'px';return {x:area.x,y:area.y};
}
window.addEventListener('blur',()=>edgePan.stop());
const editor=createEditor({store,$,$$,esc,json,api,error,status,openWorkflow,draw,fit,layout,selectNode,navigate,showValidation,focusIssue,centerNode,feedback,edgePan,ensureSpace});
async function api(path){const r=await fetch('/api/v1/admin/'+path,{cache:'no-store'});const d=await r.json();if(!r.ok)throw Error(d.message||d.code||'读取失败');return d;}
function status(text){$('#status').textContent=text;}
function error(e){$('#notice').hidden=false;$('#notice').textContent=e.message;status('读取失败,请检查权限或服务');}
function navigate(hash){if(location.hash===hash)route();else location.hash=hash;}
const title=(name,note,actions='')=>`<div class="page-intro"><div><h1>${esc(name)}</h1><p>${esc(note)}</p></div><div class="page-actions">${actions}</div></div>`;
const pill=(s,text)=>`<span class="pill ${esc(s)}">${esc(text||label(s))}</span>`;
function groupName(g){return {domain:'领域编程工作流',reference:'通用开发框架',other:'其他已保存工作流'}[g];}
function workflows(){
$('#pageTitle').textContent='工作流管理';
content.innerHTML=`<div class="page">${title('让开发全过程看得见','从需求到交付,查看现有编排定义与真实运行。')}<div class="info">从原子库拖入节点并连线,在开始节点填写需求、上传附件,保存后可试运行并查看生成结果。</div>${['domain','reference','other'].map(g=>{const items=store.workflows.filter(w=>w.group===g);return items.length?`<div class="section-title"><h2>${groupName(g)}<small>${items.length} 个工作流</small></h2></div><div class="cards">${items.map((w,i)=>`<button class="workflow-card" data-workflow="${esc(w.id)}"><div class="card-heading"><span class="icon">${g==='domain'?['E','W','M'][i]:'◇'}</span><div><h3>${esc(w.name)}</h3><small>${esc(w.id)}</small></div></div><p>${esc(w.description)}</p><div class="journey">需求 → 设计 → 编码 → 构建 → 测试 → 预览 → 验收</div><div class="card-foot"><span>${w.nodes} 节点 · ${w.control_edges} 条控制连线</span><span class="badge">草稿 r${w.revision}</span><span>打开画布 ↗</span></div></button>`).join('')}</div>`:''}).join('')}</div>`;
$$('[data-workflow]').forEach(b=>b.onclick=()=>navigate('#workflow='+encodeURIComponent(b.dataset.workflow)));
status('已读取 '+store.workflows.length+' 个真实工作流;未创建或修改定义');
}
function atomCategory(a){return a.state==='system'?'system':a.model_calls?'model':'tool';}
function atoms(){
$('#pageTitle').textContent='原子管理';
content.innerHTML=`<div class="page">${title('可复用的原子操作','独立管理能力定义,工作流节点引用精确版本。','<button disabled title="后续阶段接入外部原子的校验与执行器装配">+ 导入原子</button>')}<div class="search-row"><input id="atomSearch" aria-label="搜索原子" placeholder="搜索名称、标识或执行器"><select id="atomCategory" aria-label="原子分类"><option value="">全部分类</option><option value="tool">工具原子</option><option value="model">模型原子</option><option value="system">系统能力</option></select></div><div class="cards" id="atomCards"></div><p class="muted spaced">外部原子可独立编写;导入装配尚未开放,上传定义不等于执行器已支持。系统能力沿用现有解释器类型。</p></div>`;
const render=()=>{const q=$('#atomSearch').value.trim().toLowerCase(),cat=$('#atomCategory').value;const groups=new Map();store.atoms.forEach(a=>{if((!cat||atomCategory(a)===cat)&&(!q||[a.name,a.operation_id,a.handler_ref].join(' ').toLowerCase().includes(q))){if(!groups.has(a.operation_id))groups.set(a.operation_id,[]);groups.get(a.operation_id).push(a);}});$('#atomCards').innerHTML=[...groups.values()].map(v=>{const a=v[v.length-1];return `<button class="atom-card" data-atom="${esc(a.ref)}"><span class="icon">${a.state==='system'?'◇':a.model_calls?'✦':'▦'}</span><span class="atom-body"><span class="card-heading"><h3>${esc(a.name)}</h3></span><p>${esc(a.operation_id)} · ${esc(a.handler_ref)}</p><span class="badge">${a.state==='system'?'解释器内置':v.length+' 个版本'}</span><span class="badge">${{tool:'工具原子',model:'模型原子',system:'系统能力'}[atomCategory(a)]}</span><p>${a.references.filter(r=>r.kind==='draft').length} 个草稿节点引用 · 查看详情 ↗</p></span></button>`}).join('')||'<p class="empty">没有匹配的原子</p>';$$('[data-atom]').forEach(b=>b.onclick=()=>atomDetail(b.dataset.atom));};$('#atomSearch').oninput=render;$('#atomCategory').onchange=render;render();status('原子目录 · 独立卡片清单 · 只读');
}
function ports(ps){return (ps||[]).map(p=>`<div class="port-row">${esc(p.name)} <small>${esc(p.type)}${p.required?' · 必填':''}</small></div>`).join('')||'<p class="muted">无声明端口</p>';}
function kv(o){return '<dl class="kv">'+Object.entries(o).map(([k,v])=>`<dt>${esc(k)}</dt><dd>${esc(v??'—')}</dd>`).join('')+'</dl>';}
function atomDetail(ref,override=null){
$('.modal-backdrop')?.remove();const a=override||store.atoms.find(a=>a.ref===ref);if(!a)return;
const versions=store.atoms.filter(v=>v.operation_id===a.operation_id), refs=a.references||store.atoms.find(v=>v.ref===ref)?.references||[];
const modal=document.createElement('div');modal.className='modal-backdrop';modal.innerHTML=`<article class="atom-detail" role="dialog" aria-modal="true" aria-label="原子详情"><header><div><small>原子详情 · ${esc(ref)}</small><h2>${esc(a.name)}</h2></div><button id="closeAtom" aria-label="关闭原子详情">×</button></header><div class="version-list">${versions.map(v=>`<button class="${v.ref===ref?'active':''}" data-version="${esc(v.ref)}">${esc(v.version||'系统能力')}</button>`).join('')}</div>${override?'<div class="info">以下为此运行 / 工作流绑定的精确原子定义。</div>':''}${kv({'标识':a.operation_id,'版本':a.version||'现有 kind,无 AO 版本','执行器':a.handler_ref,'状态':a.retired?'已停用':a.state,'超时':a.timeout_seconds?a.timeout_seconds+' 秒':'解释器规则','模型调用':a.model_calls??'—','Token 上限':a.token_limit??'—','重放规则':a.replay||'解释器确认','权限':(a.permissions||[]).join('、')||'平台统一校验'})}<h3>输入契约</h3>${ports(a.inputs)}<h3>输出契约</h3>${ports(a.outputs)}<h3>参数与错误处理</h3><p class="muted">${esc(a.note||'当前注册契约没有通用参数 Schema 或自定义 on_error 字段;节点固定输入及映射单独查看。编译/测试修复和预算由现有编排器约束。')}</p><h3>被哪些节点引用</h3>${refs.map(r=>`<a class="reference" href="#workflow=${encodeURIComponent(r.workflow)}" data-close-modal>${esc(r.name)} / ${esc(r.node)}<small> · ${esc(r.source)}</small></a>`).join('')||'<p class="muted">无可见引用</p>'}<details><summary>完整注册字段(凭据已隐藏)</summary><pre>${json(Object.fromEntries(Object.entries(a).filter(([k])=>!['references'].includes(k))))}</pre></details></article>`;document.body.append(modal);$('#closeAtom').onclick=()=>modal.remove();modal.onclick=e=>{if(e.target===modal)modal.remove();};$$('[data-version]',modal).forEach(b=>b.onclick=()=>atomDetail(b.dataset.version));$$('[data-close-modal]',modal).forEach(b=>b.onclick=()=>modal.remove());$('#closeAtom').focus();
}
async function runs(){
$('#pageTitle').textContent='运行记录';
content.innerHTML=`<div class="page">${title('追踪每一次真实运行','运行绑定当时的不可变定义;技术通过与用户验收分别显示。')}<div class="search-row"><select id="runWorkflow" aria-label="筛选工作流"><option value="">全部工作流</option>${store.workflows.map(w=>`<option value="${esc(w.id)}">${esc(w.name)}</option>`).join('')}</select><button id="refreshRuns">刷新</button></div><div class="table-wrap"><table><thead><tr><th>工作流 / 任务</th><th>运行状态</th><th>版本绑定</th><th>时间</th><th></th></tr></thead><tbody id="runRows"></tbody></table></div><button id="moreRuns" class="spaced" hidden>加载更多</button></div>`;
let cursor=null;const generation=store.route;const load=async(more=false)=>{try{const data=await api('workflow-runs?limit=30'+($('#runWorkflow').value?'&workflow='+encodeURIComponent($('#runWorkflow').value):'')+(more&&cursor?'&before='+cursor:''));if(generation!==store.route)return;if(!more)$('#runRows').innerHTML='';$('#runRows').insertAdjacentHTML('beforeend',data.items.map(r=>`<tr><td>${esc(r.name)}<small>${esc(r.id)}</small></td><td>${pill(r.status,r.lease_expired?'租约已过期,结果待核实':r.pending_scope==='acceptance'?'等待用户验收':label(r.status))}${r.web_status==='verified'?'<small>独立构建 / 测试已通过</small>':r.web_status&&r.web_status!==r.status?'<small>任务记录:'+esc(label(r.web_status))+'</small>':''}${r.error?`<small>${esc(r.error)}</small>`:''}</td><td><small>${esc(r.release_ref)}</small></td><td>${time(r.created_at)}</td><td><button class="run-open" data-run="${esc(r.id)}">查看运行 ↗</button></td></tr>`).join(''));cursor=data.before;$('#moreRuns').hidden=!cursor;$$('[data-run]').forEach(b=>b.onclick=()=>navigate('#run='+b.dataset.run));status('已读取实际运行记录;未重放任务');}catch(e){error(e)}};$('#runWorkflow').onchange=()=>load();$('#refreshRuns').onclick=()=>load();$('#moreRuns').onclick=()=>load(true);await load();
}
async function openWorkflow(id,{run=null,release=null}={}){
const loadingRoute=store.route;content.inert=true;content.setAttribute('aria-busy','true');
try {
const key=store.route;store.flow=await api('workflows/'+encodeURIComponent(id)+(run?'?run_id='+encodeURIComponent(run):release?'?release_ref='+encodeURIComponent(release):''));if(key!==store.route)return;
store.trace=run?await api('workflow-runs/'+encodeURIComponent(run)):null;if(key!==store.route)return;
store.selected=null;store.palette=false;store.edge='control';store.positions={};$('#pageTitle').textContent=run?'运行记录 / 流程快照':'工作流管理 / 完整流程';
const f=store.flow,s=f.source,sourceText=s.kind==='draft'?'草稿 r'+s.revision:s.kind==='run'?'运行绑定快照':'不可变版本';
content.innerHTML=`<div class="designer-page"><div class="toolbar"><button id="backWorkflows" aria-label="返回工作流列表">←</button><div class="title"><strong>${esc(f.definition.name)}</strong><small>${esc(id)} · ${esc(sourceText)}</small></div><select id="sourceSelect" aria-label="定义来源"><option value="draft">当前草稿 r${store.workflows.find(w=>w.id===id)?.revision||'?'}</option>${s.kind==='run'?`<option value="run" selected>当前运行快照</option>`:''}${f.releases.map(r=>`<option value="${esc(r.ref)}" ${s.kind==='release'&&s.ref===r.ref?'selected':''}>${esc(r.scope==='local-validation-only'?'本地验证快照':'已发布定义')} ${esc(r.ref.split('@').pop())}</option>`).join('')}</select><span id="editorMode" class="mode-badge"></span><button id="showValidation">定义校验${f.issues.length?' · '+f.issues.length+' 项':''}</button><button id="cloneWorkflow">复制草稿</button><button id="saveDraft">保存草稿</button><button id="trialWorkflow" class="primary">▶ 试运行</button><button id="flowRuns">运行记录</button></div><div class="source-note">${esc(s.kind==='run'?s.ref+' · '+s.release_ref:sourceText)} · 定义摘要 ${esc(s.digest.slice(0,16))} · ${f.nodes.length} 节点 / ${f.definition.graph.control_edges.length} 控制连线 ${f.issues.length?' · 存在表达或校验缺口':''}</div><div class="designer"><aside class="palette" id="palette" hidden><h3>原子节点库</h3><input id="paletteSearch" aria-label="搜索节点库" placeholder="搜索原子名称"><div id="paletteItems"></div><p class="muted">拖入画布添加独立节点。点击节点右侧圆点,再点目标左侧圆点连线。</p></aside><section class="canvas-shell"><div class="canvas-caption"><span>需求 → 设计 → 编码 → 构建 → 独立测试 → 预览 → 验收交付</span><span>拖动画布平移 · 节点可移位 · 滚轮缩放</span></div><div id="canvasFeedback" class="canvas-feedback" role="status">拖动输出圆点到输入圆点;绿色已连接,红色待连接。靠近画布边缘自动平移。<button id="connectionSummary"></button></div><div class="canvas-viewport" id="canvasViewport"><div class="canvas" id="canvas" aria-label="工作流画布"><svg id="edges" class="edges" aria-label="工作流连线"></svg><div id="nodes"></div></div></div><div class="canvas-controls"><button id="togglePalette">▦ 原子库</button><button id="zoomOut" aria-label="缩小">−</button><span id="zoomValue">100%</span><button id="zoomIn" aria-label="放大">+</button><button id="fit">完整视图</button><button id="autoLayout">自动布局</button><input id="locate" class="locate-box" aria-label="定位节点" placeholder="搜索节点名称 / ID"><span id="locateCount" aria-live="polite"></span><button id="locatePrev" aria-label="上一个匹配节点" disabled>‹</button><button id="locateNext" aria-label="下一个匹配节点" disabled>›</button><label>连线 <select id="edgeView"><option value="control">控制流程</option><option value="data">输入输出映射</option><option value="resource">资源引用</option></select></label></div><div class="canvas-note">${esc(f.boundary)}</div></section><aside class="inspector-rail" id="inspectorRail"><button id="openInspector" title="选择节点后展开属性">‹</button><span>节点属性</span></aside><aside class="inspector" id="inspector" hidden></aside></div><section class="trace-panel" id="tracePanel" ${run?'':'hidden'}></section><section class="trial-result" id="trialResult" hidden></section></div>`;
// The hidden attribute must win over display:flex in the layout CSS.
$('#backWorkflows').onclick=()=>navigate('#workflows');$('#sourceSelect').value=s.kind==='draft'?'draft':s.kind==='run'?'run':s.ref;
$('#sourceSelect').onchange=()=>{const v=$('#sourceSelect').value;if(v==='run')return;openWorkflow(id,{release:v==='draft'?null:v}).catch(error)};
$('#flowRuns').onclick=()=>{navigate('#runs');};$('#showValidation').onclick=showValidation;
$('#fit').onclick=fit;$('#autoLayout').onclick=()=>{layout();draw();status('已自动布局;缩放和平移保持不变,点击完整视图可查看全图');};
$('#zoomIn').onclick=()=>zoom(store.scale*1.18);$('#zoomOut').onclick=()=>zoom(store.scale/1.18);$('#edgeView').onchange=e=>{store.edge=e.target.value;drawEdges();};
$('#togglePalette').onclick=()=>{store.palette=!store.palette;$('#palette').hidden=!store.palette;};$('#paletteSearch').oninput=renderPalette;renderPalette();
$('#openInspector').onclick=()=>selectNode(store.selected||orderedNodes()[0]?.id);
$('#locate').oninput=()=>{store.searchMatches=searchNodes(store.flow.nodes,$('#locate').value);store.searchIndex=0;applySearch();};
$('#locateNext').onclick=()=>{store.searchIndex=(store.searchIndex+1)%store.searchMatches.length;applySearch();};$('#locatePrev').onclick=()=>{store.searchIndex=(store.searchIndex-1+store.searchMatches.length)%store.searchMatches.length;applySearch();};$('#locate').onkeydown=e=>{if(e.key==='Enter'&&store.searchMatches.length){e.preventDefault();store.searchIndex=(store.searchIndex+(e.shiftKey?-1:1)+store.searchMatches.length)%store.searchMatches.length;applySearch();}};
$('#connectionSummary').onclick=()=>showValidation({issues:connectionIssues(f.definition.graph,f.nodes),scope:'连接检查(当前草稿)'});
bindPan();layout();draw();if(run)renderTrace();await editor.mount();const view=store.views[id];requestAnimationFrame(()=>{if(view){Object.assign(store,view);transform();}else fit();});
status(s.kind==='draft'?'拖入原子编辑草稿,保存后试运行':'显示不可变历史定义与精确原子版本');
} finally {if(loadingRoute===store.route){content.inert=false;content.removeAttribute('aria-busy');}}
}
function orderedNodes(){const m=new Map(store.flow.nodes.map(n=>[n.id,n]));return [...new Set([...store.flow.execution_order,...m.keys()])].map(id=>m.get(id)).filter(Boolean);}
function layout(){orderedNodes().forEach((n,i)=>{const row=Math.floor(i/4),col=row%2?3-i%4:i%4;store.positions[n.id]={x:30+col*267,y:28+row*146};});const rows=Math.ceil(store.flow.nodes.length/4);store.world={width:1078,height:Math.max(176,rows*146+12)};$('#canvas').style.width=store.world.width+'px';$('#canvas').style.height=store.world.height+'px';}
function transform(){$('#canvas').style.transform=`translate(${store.x}px,${store.y}px) scale(${store.scale})`;$('#zoomValue').textContent=Math.round(store.scale*100)+'%';if(store.flow)store.views[store.flow.definition.skill_id]={scale:store.scale,x:store.x,y:store.y};}
function fit(){if(!$('#canvasViewport'))return;const r=$('#canvasViewport').getBoundingClientRect();store.scale=Math.min(1.2,(r.width-28)/store.world.width,(r.height-18)/store.world.height);store.scale=Math.max(.12,store.scale);store.x=(r.width-store.world.width*store.scale)/2;store.y=(r.height-store.world.height*store.scale)/2;transform();}
function zoom(s,cx=null,cy=null){const r=$('#canvasViewport').getBoundingClientRect();const x=cx??r.width/2,y=cy??r.height/2;const old=store.scale;store.scale=Math.max(.12,Math.min(2,s));store.x=x-(x-store.x)*store.scale/old;store.y=y-(y-store.y)*store.scale/old;transform();}
function draw(){const f=store.flow,audit=connectionIssues(f.definition.graph,f.nodes);$('#nodes').innerHTML=orderedNodes().map((n,i)=>{const p=store.positions[n.id],a=n.atom,ns=store.trace?.nodes[n.id],sys=n.definition.kind!=='operation',problems=audit.filter(e=>e.location==='nodes.'+n.id||e.location.startsWith('nodes.'+n.id+'.')),ports=portStates(f.definition.graph,f.nodes,n),bad=ports.incomplete,ins=(a?.inputs||[]).map(p=>portLabel(p.name)).join('、')||'无',outs=(a?.outputs||[]).map(p=>portLabel(p.name)).join('、')||'无';return `<button class="node ${sys?'system':''} ${esc(ns?.status||'')} ${store.selected===n.id?'selected':''} ${bad?'connection-error':''}" data-node="${esc(n.id)}" aria-label="${esc(n.definition.label||a?.name||n.id)}"><div class="node-heading"><span>${sys?'◇':a?.model_calls?'✦':'▦'}</span>${esc(n.definition.label||a?.name||n.id)}<span>${String(i+1).padStart(2,'0')}</span></div><div class="node-meta" title="${esc(ins)}">输入 · ${esc(ins)}</div><div class="node-bottom"><span title="${esc(outs)}">输出 · ${esc(outs)}</span><span class="state">${esc(ns?label(ns.status):n.missing?'无法映射':bad?'待连线':problems.length?'输出未使用':'')}</span></div>${n.definition.kind!=='start'?`<i class="port in ${ports.input}" title="连接输入"></i>`:''}${n.definition.kind!=='end'?`<i class="port out ${ports.output}" title="连接输出"></i>`:''}</button>`}).join('');$$('[data-node]').forEach(b=>{const p=store.positions[b.dataset.node];b.style.left=p.x+'px';b.style.top=p.y+'px';b.style.zIndex=store.frontNode===b.dataset.node?'3':'';let drag=null,moved=false;
const move=point=>{if(!drag)return;const r=$('#canvasViewport').getBoundingClientRect();Object.assign(p,ensureSpace((point.x-r.left-store.x)/store.scale-drag.gx,(point.y-r.top-store.y)/store.scale-drag.gy));b.style.left=p.x+'px';b.style.top=p.y+'px';drawEdges();};
b.onpointerdown=e=>{if(e.button!==0)return;e.stopPropagation();const r=$('#canvasViewport').getBoundingClientRect();drag={x:e.clientX,y:e.clientY,gx:(e.clientX-r.left-store.x)/store.scale-p.x,gy:(e.clientY-r.top-store.y)/store.scale-p.y};moved=false;b.setPointerCapture(e.pointerId)};
b.onpointermove=e=>{if(!drag)return;if(Math.abs(e.clientX-drag.x)+Math.abs(e.clientY-drag.y)>5)moved=true;if(moved){move({x:e.clientX,y:e.clientY});edgePan.update(e,move);}};
const end=()=>{drag=null;edgePan.stop();if(moved)editor.moved()};b.onpointerup=end;b.onpointercancel=end;b.onclick=e=>{e.stopPropagation();if(!moved)selectNode(b.dataset.node)}});drawEdges();editor.wireNodes();editor.selection();updateConnectionSummary();}
function drawEdges(){const g=store.flow.definition.graph,svg=$('#edges');const color=store.edge==='data'?'#67a6bd':store.edge==='resource'?'#d1a465':'#9aaed1';let paths='';const marker=`<defs><marker id="arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M 0 0 L 10 5 L 0 10 z" fill="${color}"/></marker></defs>`;
const edges=store.edge==='data'?g.data_edges:store.edge==='resource'?g.resource_edges:g.control_edges;
edges.forEach((e,i)=>{if(store.edge==='resource'){const p=store.positions[e.node];if(p)paths+=`<g data-edge="${i}"><rect x="${p.x+10}" y="${p.y+102}" width="198" height="20" rx="4" fill="#fff5e4"/><text x="${p.x+17}" y="${p.y+116}" font-size="9" fill="#a87c35">${esc(e.kind)} · ${esc(e.resource)}</text></g>`;return;}
const a=store.positions[e.source],b=store.positions[e.target];if(!a||!b)return;
const x1=a.x+218,y1=a.y+48,x2=b.x,y2=b.y+48;let d;
if(b.x>a.x+233){const bend=(x1+x2)/2;d=`M${x1},${y1} C${bend},${y1} ${bend},${y2} ${x2},${y2}`;}
else {const lane=a.y===b.y?a.y-12-(i%3)*6:b.y>a.y?a.y+118:a.y-22;d=`M${x1},${y1} L${x1+18},${y1} L${x1+18},${lane} L${x2-18},${lane} L${x2-18},${y2} L${x2},${y2}`;}
paths+=`<path data-edge="${i}" d="${d}" fill="none" stroke="${color}" stroke-width="1.6" ${store.edge==='data'?'stroke-dasharray="5 3"':''} marker-end="url(#arrow)"><title>${esc(e.source+(e.source_port?'.'+e.source_port:'')+' → '+e.target+(e.target_port?'.'+e.target_port:''))}</title></path><path data-hit-edge="${i}" d="${d}" fill="none" stroke="transparent" stroke-width="14"/>`;});svg.innerHTML=marker+paths;if(store.selectedEdge?.type===({control:'control_edges',data:'data_edges',resource:'resource_edges'}[store.edge]))svg.querySelector('[data-edge="'+store.selectedEdge.index+'"]')?.classList.add('selected-edge');editor.wireEdges();
}
function bindPan(){const v=$('#canvasViewport');let drag=null,moved=false;v.onpointerdown=e=>{if(e.target.closest('.node')||e.target.closest('[data-edge],[data-hit-edge]'))return;drag={x:e.clientX,y:e.clientY,ox:store.x,oy:store.y};moved=false;v.setPointerCapture(e.pointerId)};v.onpointermove=e=>{if(!drag)return;if(Math.abs(e.clientX-drag.x)+Math.abs(e.clientY-drag.y)>4)moved=true;store.x=drag.ox+e.clientX-drag.x;store.y=drag.oy+e.clientY-drag.y;transform()};v.onpointerup=()=>{if(drag&&!moved)closeInspector();drag=null};v.onwheel=e=>{e.preventDefault();const r=v.getBoundingClientRect();zoom(store.scale*(e.deltaY<0?1.1:1/1.1),e.clientX-r.left,e.clientY-r.top)};editor.dropTarget(v);}
function renderPalette(){const q=$('#paletteSearch').value.toLowerCase();$('#paletteItems').innerHTML=store.atoms.filter(a=>(a.name+' '+a.ref).toLowerCase().includes(q)).map(a=>`<button data-palette-atom="${esc(a.ref)}">${esc(a.name)}<small>${esc(a.ref)}</small></button>`).join('');$$('[data-palette-atom]').forEach(b=>b.onclick=()=>atomDetail(b.dataset.paletteAtom));editor.palette();}
function closeInspector(){if(!$('#inspector'))return;store.selected=null;store.selectedEdge=null;editor.selection();$('#inspector').hidden=true;$('#inspectorRail').hidden=false;$$('.node.selected').forEach(n=>n.classList.remove('selected'));}
function selectNode(id){const f=store.flow,n=f.nodes.find(n=>n.id===id);if(!n)return;store.selected=id;store.frontNode=id;store.selectedEdge=null;const g=f.definition.graph,a=n.atom,ns=store.trace?.nodes[id];$('#inspectorRail').hidden=true;$('#inspector').hidden=false;
$('#inspector').innerHTML=`<header><div><small>节点实例 · ${esc(id)}</small><h2>${esc(nodeTitle(n))}</h2></div><button id="closeInspector" aria-label="收起节点属性">×</button></header><div class="inspector-body"><button id="nodeAtom" ${a?'':'disabled'}>查看原子定义 ↗</button>${n.missing?'<div class="info warning">此原子无法映射,未伪造定义。</div>':''}<section class="readonly-mappings" ${store.canEdit&&f.source.kind==='draft'?'hidden':''}><h3>输入来源</h3>${g.data_edges.filter(e=>e.target===id).map(e=>`<div class="mapping">${esc(portLabel(e.target_port))} ← ${esc(nodeTitle(f.nodes.find(n=>n.id===e.source)))} · ${esc(portLabel(e.source_port))}</div>`).join('')||'<p class="muted">无数据连线输入</p>'}</section><h3>输出去向</h3>${g.data_edges.filter(e=>e.source===id).map(e=>`<div class="mapping">${esc(portLabel(e.source_port))} → ${esc(nodeTitle(f.nodes.find(n=>n.id===e.target)))} · ${esc(portLabel(e.target_port))}</div>`).join('')||'<p class="muted">尚无下游使用此输出,请连接下游输入。</p>'}<details class="technical-details"><summary>原子版本、契约与原始配置</summary>${kv({'绑定原子':n.definition.operation_ref||a?.operation_id,'执行器':a?.handler_ref||'无法映射','权限':(a?.permissions||[]).join('、')||'平台统一约束','超时':a?.timeout_seconds?a.timeout_seconds+' 秒':'解释器规则'})}<h3>输入 / 输出契约</h3>${ports(a?.inputs)}${ports(a?.outputs)}<h3>节点已有固定输入</h3><pre>${json(n.definition.inputs||{})}</pre><h3>资源引用</h3><pre>${json(g.resource_edges.filter(e=>e.node===id))}</pre>${(n.definition.operation_ref||'').startsWith('AO02@')?`<p class="muted">执行器实际检索全部 knowledge_bindings:</p><pre>${json(f.definition.knowledge_bindings)}</pre>`:''}<h3>错误处理与预算</h3><p class="muted">由既有编排器统一处理,节点没有独立 on_error 配置。</p><pre>${json(f.definition.budget)}</pre><h3>原始节点字段</h3><pre>${json(n.definition)}</pre></details>${ns?`<h3>本次运行</h3>${kv({'状态':label(ns.status),'错误':ns.error||'—','耗时':ns.attempts.length?ns.attempts.map(t=>t.seconds+' 秒 ('+label(t.status)+')').join(' / '):'无成对事件,不能推算'})}${ns.status==='recorded'?'<p class="muted">存在沿用或已记录输出,无本次完整执行事件。</p>':''}<h3>输出摘要</h3><pre>${json(ns.output)}</pre><h3>确认记录</h3><pre>${json(ns.approvals)}</pre>`:''}</div>`;
$('#closeInspector').onclick=closeInspector;$('#nodeAtom').onclick=()=>atomDetail(n.definition.operation_ref||a.operation_id,{...a,ref:n.definition.operation_ref||a.operation_id});editor.nodePanel(n);draw();
}
function feedback(message,warning=false){const el=$('#canvasFeedback');if(!el)return;let text=$('#connectionMessage');if(!text){text=document.createElement('span');text.id='connectionMessage';el.prepend(text);for(const node of [...el.childNodes])if(node.nodeType===3)node.remove();}text.textContent=message;el.classList.toggle('warning',warning);status(message);}
function updateConnectionSummary(){const issues=connectionIssues(store.flow.definition.graph,store.flow.nodes);if($('#connectionSummary')){$('#connectionSummary').textContent=issues.length?'连接待完善 · '+issues.length+' 项':'输入输出连接完整';$('#connectionSummary').classList.toggle('has-issues',issues.length>0);}}
function centerNode(id){const p=store.positions[id];if(!p)return;const r=$('#canvasViewport').getBoundingClientRect();store.x=r.width/2-(p.x+109)*store.scale;store.y=r.height/2-(p.y+48)*store.scale;transform();const node=$$('[data-node]').find(n=>n.dataset.node===id);if(node){node.classList.add('focus-target');setTimeout(()=>node.classList.remove('focus-target'),1800);}}
function applySearch(){const q=$('#locate').value.trim(),matches=store.searchMatches;$('#locateCount').textContent=!q?'':matches.length?(store.searchIndex+1)+' / '+matches.length:'未找到';$('#locatePrev').disabled=matches.length<2;$('#locateNext').disabled=matches.length<2;if(matches.length){const id=matches[store.searchIndex];selectNode(id);centerNode(id);feedback('找到 '+matches.length+' 个节点,当前:'+nodeTitle(store.flow.nodes.find(n=>n.id===id)));}else if(q)feedback('未找到“'+q+'”对应的节点。',true);}
function showValidation(report=null){const f=store.flow,provided=report&&Array.isArray(report.issues),issues=provided?report.issues:[...f.issues,...connectionIssues(f.definition.graph,f.nodes)];$('#inspectorRail').hidden=true;$('#inspector').hidden=false;$('#inspector').innerHTML=`<header><div><small>${esc(report?.scope||'定义与连接校验')}</small><h2>校验结果与定位</h2></div><button id="closeInspector" aria-label="收起节点属性">×</button></header><div class="inspector-body"><div class="info ${issues.length?'warning':''}">${issues.length?'发现 '+issues.length+' 项,请点击定位':'图结构、端口类型及必填映射静态校验通过'}</div><p class="muted">节点错误打开对应输入;连线错误高亮实际连线;全局错误显示配置范围。此检查不代替执行权限、预算与隔离安全校验。</p>${issues.map((i,index)=>`<div class="issue ${i.severity==='warning'?'issue-warning':''}"><strong>${esc(i.code)}</strong><p>${esc(i.message)}</p><button data-issue-index="${index}" data-issue-location="${esc(i.location)}">${esc(resolveIssueLocation(f.definition.graph,i.location).kind==='node'?'定位节点':resolveIssueLocation(f.definition.graph,i.location).kind==='edge'?'定位连线':'查看全局配置')} · ${esc(i.location)}</button></div>`).join('')}<details><summary>定义源与当前停用记录</summary><pre>${json(f.source)}</pre><pre>${json(f.retirements)}</pre></details></div>`;$('#closeInspector').onclick=closeInspector;$$('[data-issue-index]').forEach(b=>b.onclick=()=>focusIssue(issues[Number(b.dataset.issueIndex)]));}
function focusIssue(issue){const f=store.flow,target=resolveIssueLocation(f.definition.graph,issue.location);if(target.kind==='node'){selectNode(target.id);centerNode(target.id);const port=target.field.replace(/^inputs\./,'').split('.')[0];const field=$$('[data-input-port]').find(e=>e.dataset.inputPort===port);if(field){field.classList.add('field-error');field.scrollIntoView({block:'nearest'});}const msg=document.createElement('div');msg.className='info warning located-issue';msg.textContent=issue.message;$('.inspector-body').prepend(msg);feedback('已定位:'+nodeTitle(f.nodes.find(n=>n.id===target.id))+' · '+issue.message,true);}else if(target.kind==='edge'){store.edge={control_edges:'control',data_edges:'data',resource_edges:'resource'}[target.type];$('#edgeView').value=store.edge;store.selectedEdge={type:target.type,index:target.index};drawEdges();editor.edgePanel(target.index,target.type,issue);const endpoints=target.type==='resource_edges'?[target.edge.node]:[target.edge.source,target.edge.target],ps=endpoints.map(id=>store.positions[id]).filter(Boolean);if(ps.length){const r=$('#canvasViewport').getBoundingClientRect();store.x=r.width/2-(ps.reduce((s,p)=>s+p.x+109,0)/ps.length)*store.scale;store.y=r.height/2-(ps.reduce((s,p)=>s+p.y+48,0)/ps.length)*store.scale;transform();}feedback('已定位实际连线:'+issue.message,true);}else{$('#inspectorRail').hidden=true;$('#inspector').hidden=false;$('#inspector').innerHTML=`<header><h2>全局配置问题</h2><button id="closeInspector" aria-label="收起节点属性">×</button></header><div class="inspector-body"><div class="info warning">${esc(issue.message)}</div><p>${esc(target.reason)}</p><p>位置:${esc(target.field)}</p><pre>${json(f.definition[target.field.split('.')[0]]??{scope:target.field})}</pre></div>`;$('#closeInspector').onclick=closeInspector;feedback('全局问题:'+issue.message,true);}}
function renderTrace(){const t=store.trace;$('#tracePanel').innerHTML=`<div class="trace-head"><span><strong>运行轨迹</strong> · ${esc(t.id)} · ${pill(t.status,t.lease_expired?'租约已过期,结果待核实':t.pending?.scope==='acceptance'?'等待用户验收':label(t.status))} ${t.error?esc(t.error):''} ${t.web_status&&t.web_status!==t.status?' · 任务记录:'+esc(label(t.web_status)):''}</span><span><a href="${esc(t.record_url)}" target="_blank" rel="noopener">原始运行记录 ↗</a> <button id="refreshTrace">刷新</button> <button id="collapseTrace" aria-label="收起运行轨迹">收起</button></span></div><div id="traceEvents"></div><button id="moreEvents" ${t.after?'':'hidden'}>加载后续日志 (${t.total_events} 条)</button>`;appendEvents(t.events);$('#moreEvents').onclick=async()=>{try{const p=await api('workflow-runs/'+encodeURIComponent(t.id)+'?after='+t.after);appendEvents(p.events);t.after=p.after;$('#moreEvents').hidden=!t.after}catch(e){error(e)}};$('#refreshTrace').onclick=()=>openWorkflow(t.workflow,{run:t.id}).catch(error);$('#collapseTrace').onclick=()=>{$('#tracePanel').style.maxHeight=$('#tracePanel').style.maxHeight?'':'49px'};}
function appendEvents(events){$('#traceEvents').insertAdjacentHTML('beforeend',events.map(e=>`<div class="event"><span>${time(e.timestamp)}</span><button data-event-node="${esc(e.stage)}">${esc(e.stage)}</button><span class="${e.code?'error':''}">${esc(label(e.status))} ${esc(e.code||'')}</span><small>${esc(e.summary)}</small></div>`).join(''));$$('[data-event-node]').forEach(b=>{const known=store.flow.nodes.some(n=>n.id===b.dataset.eventNode);b.title=known?'定位实际节点':'运行器内部事件,不是工作流节点';b.onclick=()=>{if(known)selectNode(b.dataset.eventNode);else status('运行器内部事件 '+b.dataset.eventNode+',未虚构图节点');};});}
async function route(){if(!store.actorId){showLogin();return;}const current=++store.route;$('#notice').hidden=true;$('.modal-backdrop')?.remove();const h=location.hash.slice(1)||'workflows';$$('[data-page]').forEach(a=>a.classList.toggle('active',a.dataset.page===(h.startsWith('run=')?'runs':h.startsWith('workflow=')?'workflows':h)));try{if(h==='atoms')atoms();else if(h==='runs')await runs();else if(h.startsWith('workflow='))await openWorkflow(decodeURIComponent(h.slice(9)));else if(h.startsWith('run=')){const t=await api('workflow-runs/'+encodeURIComponent(h.slice(4)));if(current===store.route)await openWorkflow(t.workflow,{run:t.id})}else workflows();}catch(e){if(current===store.route)error(e);}}
window.addEventListener('hashchange',route);window.addEventListener('resize',()=>{if($('#canvas'))transform()});document.addEventListener('keydown',e=>{if(e.key==='Escape'){if($('.modal-backdrop'))$('.modal-backdrop').remove();else closeInspector()}});
async function loadAdmin(){
const session=await fetch('/api/session',{cache:'no-store'}).then(r=>r.json());
if(!session.authenticated){showLogin();return;}
store.canEdit=session.actor?.roles?.some(r=>['admin','skill_manager'].includes(r));store.actorId=session.actor?.user_id;store.csrf=session.csrf;store.previewOrigin=session.preview_origin;
$('#account').innerHTML='<span>'+esc(session.username||'已登录')+'</span> <button id="adminLogout">退出</button>';
$('#adminLogout').onclick=async()=>{const r=await fetch('/api/session/logout',{method:'POST',headers:{'X-CSRF-Token':store.csrf}});if(r.ok){edgePan.stop();store.actorId=null;store.canEdit=false;store.selected=null;store.selectedEdge=null;store.flow=null;showLogin();}else error(Error('退出未完成,请重试'));};
try{[store.workflows,store.atoms]=await Promise.all([api('workflows'),api('workflow-atoms')]);$('#connection').textContent='已连接真实配置';await route();}
catch(e){store.actorId=null;showLogin(e.message);}
}
function showLogin(message=''){store.actorId=null;store.canEdit=false;edgePan.stop();
$('#notice').hidden=true;$('#account').textContent='未登录';$('#connection').textContent='管理端独立登录';$('#pageTitle').textContent='登录管理端';
content.inert=false;content.removeAttribute('aria-busy');content.innerHTML=`<div class="admin-login"><form id="adminLogin"><h1>登录管理端</h1><p>使用已有账号直接登录,无需先打开工作台。</p><label>账号<input id="adminUsername" name="username" autocomplete="username" value="manager" required></label><label>密码<input id="adminPassword" name="password" type="password" autocomplete="current-password" required></label><p id="adminLoginError" role="alert">${esc(message)}</p><button type="submit" class="primary">登录</button><small>使用已有管理账号密码;演示管理员为 manager(周宁)。</small></form></div>`;
$('#adminLogin').onsubmit=async e=>{e.preventDefault();const button=e.target.querySelector('[type=submit]');button.disabled=true;$('#adminLoginError').textContent='';try{const r=await fetch('/api/session/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username:$('#adminUsername').value.trim(),password:$('#adminPassword').value})});const data=await r.json();if(!r.ok)throw Error(data.message||'登录失败');$('#adminPassword').value='';await loadAdmin();}catch(err){$('#adminLoginError').textContent=err.message;}finally{button.disabled=false;}};
status('使用真实账号登录后按已有角色权限访问管理端');
}
if(location.hostname==='dellweb3-vibecoding.hf.space'){$('.nav-bottom').firstChild.textContent='HF 演示环境';$('.phase').textContent='草稿编辑 · 空间内试运行';$('footer span:last-child').textContent='工作台与预览 · 同一 HTTPS 入口';}
await loadAdmin();
|