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='')=>`
`;
const pill=(s,text)=>`${esc(text||label(s))} `;
function groupName(g){return {domain:'领域编程工作流',reference:'通用开发框架',other:'其他已保存工作流'}[g];}
function workflows(){
$('#pageTitle').textContent='工作流管理';
content.innerHTML=`${title('让开发全过程看得见','从需求到交付,查看现有编排定义与真实运行。')}
从原子库拖入节点并连线,在开始节点填写需求、上传附件,保存后可试运行并查看生成结果。
${['domain','reference','other'].map(g=>{const items=store.workflows.filter(w=>w.group===g);return items.length?`
${groupName(g)}${items.length} 个工作流 ${items.map((w,i)=>`
${g==='domain'?['E','W','M'][i]:'◇'}
${esc(w.name)} ${esc(w.id)} ${esc(w.description)}
需求 → 设计 → 编码 → 构建 → 测试 → 预览 → 验收
`).join('')}
`:''}).join('')}
`;
$$('[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=`${title('可复用的原子操作','独立管理能力定义,工作流节点引用精确版本。','
+ 导入原子 ')}
全部分类 工具原子 模型原子 系统能力
外部原子可独立编写;导入装配尚未开放,上传定义不等于执行器已支持。系统能力沿用现有解释器类型。
`;
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 `${a.state==='system'?'◇':a.model_calls?'✦':'▦'} ${esc(a.name)} ${esc(a.operation_id)} · ${esc(a.handler_ref)}
${a.state==='system'?'解释器内置':v.length+' 个版本'} ${{tool:'工具原子',model:'模型原子',system:'系统能力'}[atomCategory(a)]} ${a.references.filter(r=>r.kind==='draft').length} 个草稿节点引用 · 查看详情 ↗
`}).join('')||'没有匹配的原子
';$$('[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=>`${esc(p.name)} ${esc(p.type)}${p.required?' · 必填':''}
`).join('')||'无声明端口
';}
function kv(o){return ''+Object.entries(o).map(([k,v])=>`${esc(k)} ${esc(v??'—')} `).join('')+' ';}
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=`${versions.map(v=>`${esc(v.version||'系统能力')} `).join('')}
${override?'以下为此运行 / 工作流绑定的精确原子定义。
':''}${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('、')||'平台统一校验'})}输入契约 ${ports(a.inputs)}输出契约 ${ports(a.outputs)}参数与错误处理 ${esc(a.note||'当前注册契约没有通用参数 Schema 或自定义 on_error 字段;节点固定输入及映射单独查看。编译/测试修复和预算由现有编排器约束。')}
被哪些节点引用 ${refs.map(r=>`${esc(r.name)} / ${esc(r.node)} · ${esc(r.source)} `).join('')||'无可见引用
'}完整注册字段(凭据已隐藏) ${json(Object.fromEntries(Object.entries(a).filter(([k])=>!['references'].includes(k))))} `;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=`${title('追踪每一次真实运行','运行绑定当时的不可变定义;技术通过与用户验收分别显示。')}
全部工作流 ${store.workflows.map(w=>`${esc(w.name)} `).join('')}刷新
加载更多 `;
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=>`${esc(r.name)}${esc(r.id)} ${pill(r.status,r.lease_expired?'租约已过期,结果待核实':r.pending_scope==='acceptance'?'等待用户验收':label(r.status))}${r.web_status==='verified'?'独立构建 / 测试已通过 ':r.web_status&&r.web_status!==r.status?'任务记录:'+esc(label(r.web_status))+' ':''}${r.error?`${esc(r.error)} `:''} ${esc(r.release_ref)} ${time(r.created_at)} 查看运行 ↗ `).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=`${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?' · 存在表达或校验缺口':''}
需求 → 设计 → 编码 → 构建 → 独立测试 → 预览 → 验收交付 拖动画布平移 · 节点可移位 · 滚轮缩放
拖动输出圆点到输入圆点;绿色已连接,红色待连接。靠近画布边缘自动平移。
▦ 原子库 − 100% + 完整视图 自动布局 ‹ › 连线 控制流程 输入输出映射 资源引用
${esc(f.boundary)}
`;
// 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 `${sys?'◇':a?.model_calls?'✦':'▦'} ${esc(n.definition.label||a?.name||n.id)}${String(i+1).padStart(2,'0')}
输入 · ${esc(ins)}
输出 · ${esc(outs)} ${esc(ns?label(ns.status):n.missing?'无法映射':bad?'待连线':problems.length?'输出未使用':'')}
${n.definition.kind!=='start'?` `:''}${n.definition.kind!=='end'?` `:''} `}).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=` `;
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+=`${esc(e.kind)} · ${esc(e.resource)} `;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+=`${esc(e.source+(e.source_port?'.'+e.source_port:'')+' → '+e.target+(e.target_port?'.'+e.target_port:''))} `;});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=>`${esc(a.name)}${esc(a.ref)} `).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=`查看原子定义 ↗ ${n.missing?'
此原子无法映射,未伪造定义。
':''}
输入来源 ${g.data_edges.filter(e=>e.target===id).map(e=>`${esc(portLabel(e.target_port))} ← ${esc(nodeTitle(f.nodes.find(n=>n.id===e.source)))} · ${esc(portLabel(e.source_port))}
`).join('')||'无数据连线输入
'}输出去向 ${g.data_edges.filter(e=>e.source===id).map(e=>`
${esc(portLabel(e.source_port))} → ${esc(nodeTitle(f.nodes.find(n=>n.id===e.target)))} · ${esc(portLabel(e.target_port))}
`).join('')||'
尚无下游使用此输出,请连接下游输入。
'}
原子版本、契约与原始配置 ${kv({'绑定原子':n.definition.operation_ref||a?.operation_id,'执行器':a?.handler_ref||'无法映射','权限':(a?.permissions||[]).join('、')||'平台统一约束','超时':a?.timeout_seconds?a.timeout_seconds+' 秒':'解释器规则'})}输入 / 输出契约 ${ports(a?.inputs)}${ports(a?.outputs)}节点已有固定输入 ${json(n.definition.inputs||{})} 资源引用 ${json(g.resource_edges.filter(e=>e.node===id))} ${(n.definition.operation_ref||'').startsWith('AO02@')?`执行器实际检索全部 knowledge_bindings:
${json(f.definition.knowledge_bindings)} `:''}错误处理与预算 由既有编排器统一处理,节点没有独立 on_error 配置。
${json(f.definition.budget)} 原始节点字段 ${json(n.definition)} ${ns?`
本次运行 ${kv({'状态':label(ns.status),'错误':ns.error||'—','耗时':ns.attempts.length?ns.attempts.map(t=>t.seconds+' 秒 ('+label(t.status)+')').join(' / '):'无成对事件,不能推算'})}${ns.status==='recorded'?'
存在沿用或已记录输出,无本次完整执行事件。
':''}
输出摘要 ${json(ns.output)} 确认记录 ${json(ns.approvals)} `:''}
`;
$('#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=`${issues.length?'发现 '+issues.length+' 项,请点击定位':'图结构、端口类型及必填映射静态校验通过'}
节点错误打开对应输入;连线错误高亮实际连线;全局错误显示配置范围。此检查不代替执行权限、预算与隔离安全校验。
${issues.map((i,index)=>`
${esc(i.code)} ${esc(i.message)}
${esc(resolveIssueLocation(f.definition.graph,i.location).kind==='node'?'定位节点':resolveIssueLocation(f.definition.graph,i.location).kind==='edge'?'定位连线':'查看全局配置')} · ${esc(i.location)} `).join('')}
定义源与当前停用记录 ${json(f.source)} ${json(f.retirements)} `;$('#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=`${esc(issue.message)}
${esc(target.reason)}
位置:${esc(target.field)}
${json(f.definition[target.field.split('.')[0]]??{scope:target.field})} `;$('#closeInspector').onclick=closeInspector;feedback('全局问题:'+issue.message,true);}}
function renderTrace(){const t=store.trace;$('#tracePanel').innerHTML=`运行轨迹 · ${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)):''}原始运行记录 ↗ 刷新 收起
加载后续日志 (${t.total_events} 条) `;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=>`${time(e.timestamp)} ${esc(e.stage)} ${esc(label(e.status))} ${esc(e.code||'')} ${esc(e.summary)}
`).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=''+esc(session.username||'已登录')+' 退出 ';
$('#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=``;
$('#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();