// Pure canvas helpers: presentation/connection guidance only, never execution. export const portLabel = name => ({requirement:'需求文本',query:'检索词',document:'需求文档',citations:'知识引用',snapshot:'上下文',design:'设计方案',patch:'候选代码',source:'受检源码',policy_evidence:'策略凭据',candidate:'构建产物',test_evidence:'测试凭据',preview_evidence:'预览凭据',manifest:'交付清单'}[name] || name); export const nodeTitle = node => node?.definition?.label || node?.atom?.name || node?.id || '未知节点'; export function ancestors(graph, target){ const seen=new Set(),pending=[target];while(pending.length){const id=pending.pop();for(const e of graph.control_edges||[]){if(e.target===id&&!seen.has(e.source)){seen.add(e.source);pending.push(e.source);}}}seen.delete(target);return seen; } export function inputCandidates(graph,nodes,target,port){ const node=nodes.find(n=>n.id===target),input=node?.atom?.inputs?.find(p=>p.name===port);if(!input)return []; const upstream=ancestors(graph,target),result=[];for(const source of nodes){if(!upstream.has(source.id))continue;for(const output of source.atom?.outputs||[]){if(output.type===input.type)result.push({source:source.id,source_port:output.name,target,target_port:port,type:output.type});}}return result; } export function inferMappings(graph,nodes,source,target){ const node=nodes.find(n=>n.id===target),mappings=[];for(const input of node?.atom?.inputs||[]){ if(Object.hasOwn(node.definition.inputs||{},input.name)||(graph.data_edges||[]).some(e=>e.target===target&&e.target_port===input.name))continue; const candidates=inputCandidates(graph,nodes,target,input.name).filter(e=>e.source_port===input.name),direct=candidates.filter(e=>e.source===source); const selected=direct.length===1?direct[0]:candidates.length===1?candidates[0]:null; if(selected)mappings.push({source:selected.source,source_port:selected.source_port,target,target_port:input.name}); }return mappings; } export function connectionIssues(graph,nodes){ const issues=[];for(const node of nodes){const n=node.definition; if(n.kind!=='start'&&!(graph.control_edges||[]).some(e=>e.target===node.id))issues.push({code:'CANVAS_CONTROL_IN',location:'nodes.'+node.id,message:nodeTitle(node)+':尚未连接上游控制线。',severity:'error'}); if(n.kind!=='end'&&!(graph.control_edges||[]).some(e=>e.source===node.id))issues.push({code:'CANVAS_CONTROL_OUT',location:'nodes.'+node.id,message:nodeTitle(node)+':尚未连接下游控制线。',severity:'error'}); for(const port of node.atom?.inputs||[]){if(port.required!==false&&!Object.hasOwn(n.inputs||{},port.name)&&!(graph.data_edges||[]).some(e=>e.target===node.id&&e.target_port===port.name))issues.push({code:'CANVAS_INPUT_MISSING',location:'nodes.'+node.id+'.'+port.name,message:nodeTitle(node)+':'+portLabel(port.name)+'未连接,请选择上游输出,不需要手工填写中间数据。',severity:'error'});} for(const port of node.atom?.outputs||[]){if(!(graph.data_edges||[]).some(e=>e.source===node.id&&e.source_port===port.name))issues.push({code:'CANVAS_OUTPUT_UNUSED',location:'nodes.'+node.id+'.outputs.'+port.name,message:nodeTitle(node)+':'+portLabel(port.name)+'尚未连接到下游,此输出不会被下游使用。',severity:'warning'});} }return issues; } export function resolveIssueLocation(graph,location){ const raw=String(location||''),path=raw.replace(/^graph\./,''); const edge=path.match(/^(control_edges|data_edges|resource_edges)\.(\d+)(?:\.|$)/); if(edge){const index=Number(edge[2]);return graph[edge[1]]?.[index]?{kind:'edge',type:edge[1],index,edge:graph[edge[1]][index]}:{kind:'global',field:raw,reason:'该连线已被修改或移除,请重新校验。'};} if(path.startsWith('nodes.')){const tail=path.slice(6),byId=[...graph.nodes].sort((a,b)=>b.id.length-a.id.length).find(n=>tail===n.id||tail.startsWith(n.id+'.'));if(byId)return {kind:'node',id:byId.id,field:tail.slice(byId.id.length).replace(/^\./,'')};const numeric=tail.match(/^(\d+)(?:\.(.*))?$/);if(numeric&&graph.nodes[Number(numeric[1])])return {kind:'node',id:graph.nodes[Number(numeric[1])].id,field:numeric[2]||''};} return {kind:'global',field:raw,reason:'此项为全局配置或图结构问题,不对应单个节点。'}; } export function searchNodes(nodes,query){const q=String(query||'').trim().toLowerCase();return q?nodes.filter(n=>[n.id,n.definition.label,n.atom?.name,n.definition.operation_ref].some(v=>String(v||'').toLowerCase().includes(q))).map(n=>n.id):[];} export function withoutNode(graph,id){ const copy=structuredClone(graph);copy.nodes=copy.nodes.filter(n=>n.id!==id); for(const type of ['control_edges','data_edges'])copy[type]=copy[type].filter(e=>e.source!==id&&e.target!==id); copy.resource_edges=copy.resource_edges.filter(e=>e.node!==id);return copy; } // A port is complete only when its control and data connections are complete. export function portStates(graph,nodes,node){ const issues=connectionIssues(graph,nodes).filter(i=>i.location==='nodes.'+node.id||i.location.startsWith('nodes.'+node.id+'.')); const incoming=issues.some(i=>['CANVAS_CONTROL_IN','CANVAS_INPUT_MISSING'].includes(i.code)); const outgoing=issues.some(i=>['CANVAS_CONTROL_OUT','CANVAS_OUTPUT_UNUSED'].includes(i.code)); return {input:incoming?'missing':'connected',output:outgoing?'missing':'connected',incomplete:incoming||outgoing||Boolean(node.missing)}; } // Pixel velocity stays independent of zoom; the world grows around the gesture. export function edgeVelocity(point,rect){ if(point.xrect.right+32||point.yrect.bottom+32)return {x:0,y:0}; const axis=(v,lo,hi)=>vhi-48?Math.min(1,(v-hi+48)/48):0; return {x:axis(point.x,rect.left,rect.right)*.7,y:axis(point.y,rect.top,rect.bottom)*.7}; } export function spaceForPoint(world,x,y){ const sx=x<24?Math.ceil((24-x)/512)*512:0,sy=y<24?Math.ceil((24-y)/512)*512:0; return {x:x+sx,y:y+sy,sx,sy,width:Math.max(world.width+sx,x+sx+282),height:Math.max(world.height+sy,y+sy+160)}; } // Draft mutations and local trials use the same Skill and job APIs as the workbench. export function createEditor(ctx){ const {store,$,$$,esc,json,api,error,status,openWorkflow,draw,fit,layout,selectNode,navigate,showValidation,focusIssue,centerNode,feedback,edgePan,ensureSpace}=ctx; const state={dirty:false,pending:null,history:[],future:[],generation:0,timer:null,starting:false,active:false}; const editable=()=>Boolean(store.canEdit&&store.flow?.source.kind==='draft'); const id=()=>store.flow.definition.skill_id; const graph=()=>store.flow.definition.graph; const key=()=> 'zkcoding.workflow.trials.'+store.actorId; function remembered(){try{return JSON.parse(localStorage.getItem(key())||'{}')}catch{return {}}} function remember(job){const r=remembered();r[id()]=job.id;localStorage.setItem(key(),JSON.stringify(r));} async function request(path,body,method='POST'){ const response=await fetch(path,{method,headers:{'Content-Type':'application/json','X-CSRF-Token':store.csrf},body:JSON.stringify(body)}); const result=await response.json();if(!response.ok){const detail=(result.details?.issues||result.issues||[]).slice(0,6).map(i=>i.location+': '+i.message).join(';');const err=Error((result.message||result.code||'请求失败')+(detail?' '+detail:''));err.httpStatus=response.status;err.code=result.code;throw err;}return result; } function sync(){ store.flow.nodes=graph().nodes.map(n=>({id:n.id,definition:n,atom:n.kind==='operation'?store.atoms.find(a=>a.ref===n.operation_ref):system(n),missing:n.kind==='operation'&&!store.atoms.some(a=>a.ref===n.operation_ref)})); const degree=new Map(graph().nodes.map(n=>[n.id,0])),children=new Map(graph().nodes.map(n=>[n.id,new Set()]));for(const e of graph().control_edges){if(degree.has(e.source)&°ree.has(e.target)&&!children.get(e.source).has(e.target)){children.get(e.source).add(e.target);degree.set(e.target,degree.get(e.target)+1);}}const pending=[...degree.keys()].filter(k=>degree.get(k)===0).sort(),order=[];while(pending.length){const n=pending.shift();order.push(n);for(const target of [...children.get(n)].sort()){degree.set(target,degree.get(target)-1);if(degree.get(target)===0)pending.push(target);}}store.flow.execution_order=order.length===graph().nodes.length?order:graph().nodes.map(n=>n.id); } function system(n){const ref='system:'+n.kind+(n.approval_scope?':'+n.approval_scope:'');const registered=store.atoms.find(a=>a.ref===ref);if(registered)return registered;return {operation_id:'system:'+n.kind+(n.approval_scope?':'+n.approval_scope:''),handler_ref:'interpreter.'+n.kind,state:'system',inputs:n.kind==='end'?[{name:'manifest',type:'object',required:true}]:[],outputs:n.kind==='start'?[{name:'requirement',type:'string',required:true},{name:'query',type:'string',required:true}]:[],version:null,name:n.label||n.kind};} function snapshot(){return {definition:structuredClone(store.flow.definition),positions:structuredClone(store.positions)};} function checkpoint(){state.history.push(snapshot());if(state.history.length>30)state.history.shift();state.future=[];} function changed(redraw=true){$('#notice').hidden=true;state.dirty=true;store.trace=null;sync();if($('#saveDraft'))$('#saveDraft').textContent='保存草稿 *';if($('.source-note'))$('.source-note').textContent='草稿 r'+store.flow.source.revision+' · 有未保存修改 · '+graph().nodes.length+' 节点;试运行会绑定保存后的版本';status('草稿有修改,尚未影响已发布版本或正在运行的任务');if(redraw)draw();} function restore(snapshot){store.flow.definition=snapshot.definition;store.positions=snapshot.positions;sync();changed();if(store.selected&&graph().nodes.some(n=>n.id===store.selected))selectNode(store.selected);} function history(back){const from=back?state.history:state.future,to=back?state.future:state.history;if(!from.length)return;to.push(snapshot());restore(from.pop());} function selection(){const button=$('#deleteSelection');if(!button)return;button.disabled=!editable()||(!store.selected&&!store.selectedEdge);button.title=!editable()?'此版本或当前角色只读':button.disabled?'先选中节点或连线':'删除选中节点或连线(Delete / Backspace),可撤销';} function removeSelected(){ if(!editable()){feedback('当前版本或角色只读,不能删除。',true);return;} const edge=store.selectedEdge,nid=store.selected;if(!edge&&!nid)return; if(edge&&!graph()[edge.type]?.[edge.index])return;if(!edge&&!graph().nodes.some(n=>n.id===nid))return; checkpoint();edgePan.stop();state.pending=null; if(edge)graph()[edge.type].splice(edge.index,1); else {store.flow.definition.graph=withoutNode(graph(),nid);delete store.positions[nid];if(store.flow.definition.editor_positions)delete store.flow.definition.editor_positions[nid];} store.selected=null;store.selectedEdge=null;changed();$('#inspector').hidden=true;$('#inspectorRail').hidden=false;selection(); feedback(edge?'已删除连线,可撤销;缺失连接已标红,保存草稿后保留。':'已删除节点及其相连控制线、数据线和资源引用,可撤销;保存草稿后保留。',true); } function flush(){if(!editable())return;const textarea=$('#nodeLiteralInputs');if(textarea){const parsed=JSON.parse(textarea.value);if(!parsed||Array.isArray(parsed)||typeof parsed!=='object')throw Error('节点固定输入必须为 JSON 对象');const n=graph().nodes.find(n=>n.id===store.selected);if(n&&JSON.stringify(n.inputs)!==JSON.stringify(parsed)){n.inputs=parsed;changed(false);}}} async function save(force=true){ if(!editable())throw Error('此版本只读,请先复制草稿');flush();if(!force&&!state.dirty)return {revision:store.flow.source.revision}; const current=id(),selected=store.selected;const definition=structuredClone(store.flow.definition); if(Object.values(store.positions).some(p=>p.x>10000||p.y>10000))throw Error('当前布局超出现有保存范围(坐标 10000),请自动布局或移近后保存;草稿未被覆盖。'); definition.editor_positions=Object.fromEntries(Object.entries(store.positions).map(([k,p])=>[k,{x:Number(p.x),y:Number(p.y)}])); const saved=await request('/api/v1/admin/skills/'+encodeURIComponent(current)+'/draft',{draft:definition,expected_revision:store.flow.source.revision},'PUT'); store.workflows=await api('workflows');state.dirty=false;await openWorkflow(current);if(selected&&graph().nodes.some(n=>n.id===selected))selectNode(selected);status('已保存草稿 r'+saved.revision+';节点版本、输入、附件、连线与布局均已保存');return saved; } function finishConnection(source,target){state.pending=null;if(!target){feedback('未连接:请把端点拖到目标节点左侧输入圆点。',true);return;}if(source===target){feedback('不能连接节点自身。',true);return;}if(store.edge==='resource'){feedback('资源引用不通过节点端点连接,请切换控制流程或输入输出映射。',true);return;}if(store.edge==='data')mapping(source,target);else addControl(source,target);} function wireNodes(){ if(!$('#nodes'))return; $$('.node .port').forEach(port=>{ const out=port.classList.contains('out'),node=port.closest('[data-node]').dataset.node; port.setAttribute('role','button');port.tabIndex=0;port.setAttribute('aria-label',out?'连接输出':'连接输入');port.title=editable()?(out?'拖到目标的输入圆点,或点击后再选目标':'接收上游连线'):'此版本只读'; if(state.pending===node&&out)port.classList.add('connecting');let drag=null,suppress=false; const clean=()=>{edgePan.stop();$('#connectionDrag')?.remove();$$('.drop-ready').forEach(e=>e.classList.remove('drop-ready'));}; port.onpointerdown=e=>{e.stopPropagation();if(!editable()||!out||e.button!==0)return;drag={x:e.clientX,y:e.clientY,moved:false};port.setPointerCapture(e.pointerId);}; const paint=point=>{ const v=$('#canvasViewport').getBoundingClientRect(),p=store.positions[node];let path=$('#connectionDrag');if(!path){path=document.createElementNS('http://www.w3.org/2000/svg','path');path.id='connectionDrag';path.setAttribute('fill','none');path.setAttribute('stroke','#487ff0');path.setAttribute('stroke-width','2.5');path.setAttribute('stroke-dasharray','5 3');$('#edges').append(path);} const x=(point.x-v.left-store.x)/store.scale,y=(point.y-v.top-store.y)/store.scale;path.setAttribute('d',`M${p.x+218},${p.y+48} C${p.x+260},${p.y+48} ${x-30},${y} ${x},${y}`); $$('.drop-ready').forEach(el=>el.classList.remove('drop-ready'));document.elementFromPoint(point.x,point.y)?.closest('.port.in')?.classList.add('drop-ready'); }; port.onpointermove=e=>{if(!drag)return;e.stopPropagation();if(Math.hypot(e.clientX-drag.x,e.clientY-drag.y)<4&&!drag.moved)return;drag.moved=true;paint({x:e.clientX,y:e.clientY});edgePan.update(e,paint);}; port.onpointerup=e=>{e.stopPropagation();if(!drag)return;const moved=drag.moved;drag=null;edgePan.stop();if(port.hasPointerCapture(e.pointerId))port.releasePointerCapture(e.pointerId);if(moved){suppress=true;const target=document.elementFromPoint(e.clientX,e.clientY)?.closest('.port.in')?.closest('[data-node]')?.dataset.node;clean();finishConnection(node,target);setTimeout(()=>{suppress=false;},0);}}; port.onpointercancel=()=>{drag=null;clean();feedback('已取消连线。');}; port.onclick=e=>{e.stopPropagation();if(suppress)return;if(!editable()){feedback('此版本只读,请选择当前草稿后编辑。',true);return;}if(out){state.pending=node;$$('.port.connecting').forEach(p=>p.classList.remove('connecting'));port.classList.add('connecting');feedback('已选“'+nodeTitle(store.flow.nodes.find(n=>n.id===node))+'”的输出,点击目标左侧输入圆点。');}else if(state.pending)finishConnection(state.pending,node);else feedback('请先选择来源节点右侧输出圆点,也可以从输出圆点拖入此端点。',true);}; port.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();port.click();}}; }); } function wireEdges(){ $$('#edges [data-edge],#edges [data-hit-edge]').forEach(path=>{path.style.pointerEvents='stroke';path.style.cursor='pointer';path.onclick=e=>{e.stopPropagation();edgePanel(Number(path.dataset.edge??path.dataset.hitEdge));};}); } function addControl(source,target){ const sn=graph().nodes.find(n=>n.id===source),tn=graph().nodes.find(n=>n.id===target);if(!sn||!tn)return; if(sn.kind==='end'||tn.kind==='start'||ancestors(graph(),source).has(target)){feedback('无法连接:会形成循环或违反开始/结束方向,图未改变。',true);return;} const exists=graph().control_edges.some(e=>e.source===source&&e.target===target);if(!exists)checkpoint(); if(!exists)graph().control_edges.push({source,target});sync();const automatic=inferMappings(graph(),store.flow.nodes,source,target);if(exists&&automatic.length)checkpoint();graph().data_edges.push(...automatic); if(!exists||automatic.length)changed();selectNode(target); const missing=connectionIssues(graph(),store.flow.nodes).filter(i=>i.location.startsWith('nodes.'+target+'.')); feedback((exists?'控制线已存在':'控制连线已建立')+(automatic.length?';已自动接入 '+automatic.length+' 个同名同类型的上游输出。':';已有输入来源保持不变。')+(missing.length?' 仍有 '+missing.length+' 项连接提示,右侧可选择输入来源。':''),missing.length>0); } function edgePanel(index,type=null,issue=null){ type=type||({data:'data_edges',control:'control_edges',resource:'resource_edges'}[store.edge]);const edge=graph()[type]?.[index];if(!edge)return;store.selectedEdge={type,index};$$('#edges .selected-edge').forEach(e=>e.classList.remove('selected-edge'));$('#edges [data-edge="'+index+'"]')?.classList.add('selected-edge'); $('#inspectorRail').hidden=true;$('#inspector').hidden=false; $('#inspector').innerHTML=`

${{data_edges:'输入输出连线',control_edges:'控制连线',resource_edges:'资源引用'}[type]}

${issue?`
${esc(issue.message)}
`:''}

${type==='resource_edges'?esc(nodeTitle(store.flow.nodes.find(n=>n.id===edge.node))+' → '+edge.resource):esc(nodeTitle(store.flow.nodes.find(n=>n.id===edge.source))+(edge.source_port?' · '+portLabel(edge.source_port):'')+' → '+nodeTitle(store.flow.nodes.find(n=>n.id===edge.target))+(edge.target_port?' · '+portLabel(edge.target_port):''))}

${json(edge)}
${editable()?'':'

只读版本,不能修改历史连线。

'}

连线引用真实执行定义。修改草稿不改变正在运行的版本。

`; store.selected=null;selection();$('#closeEdge').onclick=()=>{$('#inspector').hidden=true;$('#inspectorRail').hidden=false;store.selectedEdge=null;draw();};if($('#removeEdge'))$('#removeEdge').onclick=removeSelected; } function mapping(source,target){ const a=store.flow.nodes.find(n=>n.id===source),b=store.flow.nodes.find(n=>n.id===target);if(!a||!b)return; const modal=document.createElement('div');modal.className='modal-backdrop';modal.innerHTML=``;document.body.append(modal); const update=()=>{const output=a.atom?.outputs?.find(p=>p.name===$('#mappingSource').value),targets=(b.atom?.inputs||[]).filter(p=>p.type===output?.type);$('#mappingTarget').innerHTML=targets.map(p=>``).join('');const upstream=ancestors(graph(),target).has(source);$('#addMapping').disabled=!targets.length||!upstream;$('#mappingHint').textContent=!upstream?'请先连通控制流程:来源节点必须在目标节点之前。':!targets.length?'不能连接:输出类型 '+(output?.type||'无输出')+' 与目标输入不兼容。':'请选择端口,输入将直接使用上游真实输出。';}; $('#mappingSource').onchange=update;update();$('#closeMapping').onclick=()=>modal.remove();$('#addMapping').onclick=()=>{const sp=$('#mappingSource').value,tp=$('#mappingTarget').value;if(!sp||!tp||$('#addMapping').disabled)return;checkpoint();graph().data_edges=graph().data_edges.filter(e=>!(e.target===target&&e.target_port===tp));const n=graph().nodes.find(n=>n.id===target);delete n.inputs[tp];graph().data_edges.push({source,source_port:sp,target,target_port:tp});changed();modal.remove();selectNode(target);feedback('已连接:'+portLabel(tp)+' ← '+nodeTitle(a)+' · '+portLabel(sp));}; } function palette(){ $$('[data-palette-atom]').forEach(button=>{button.draggable=editable();button.title=editable()?'拖入画布添加节点;点击查看定义':!store.canEdit?'当前账号只读,请用管理账号登录':'历史版本只读,请选择当前草稿';button.ondragstart=e=>{if(!editable()){e.preventDefault();return;}const ref=button.dataset.paletteAtom;if(ref.startsWith('AO12@')||ref.startsWith('AO13@')){e.preventDefault();error(Error('修复由运行器管理,新的工作流不再加入模型检视'));return;}e.dataTransfer.setData('application/x-zkcoding-atom',ref);e.dataTransfer.effectAllowed='copy';};}); } function dropTarget(view){view.ondragover=e=>{if(editable()&&[...e.dataTransfer.types].includes('application/x-zkcoding-atom')){e.preventDefault();e.dataTransfer.dropEffect='copy';edgePan.update(e,()=>{});}};view.ondragleave=e=>{if(!view.contains(e.relatedTarget))edgePan.stop();};view.ondrop=e=>{e.preventDefault();edgePan.stop();const ref=e.dataTransfer.getData('application/x-zkcoding-atom');const atom=store.atoms.find(a=>a.ref===ref);if(!editable()||!atom)return;addAtom(atom,e.clientX,e.clientY);};} function addAtom(atom,clientX,clientY){ if(atom.retired||!['approved','system'].includes(atom.state)){error(Error('只能添加已批准且未停用的原子版本'));return;} if(atom.operation_id==='AO12'||atom.operation_id==='AO13'){error(Error('此能力由原运行器管理或已退出新流程'));return;} if(graph().nodes.length>=64){error(Error('工作流最多 64 个节点'));return;} checkpoint();const node={id:'node-'+crypto.randomUUID().slice(0,12),kind:'operation',operation_ref:atom.ref,approval_scope:null,inputs:{},label:atom.name}; if(atom.state==='system'){const parts=atom.operation_id.split(':');node.kind=parts[1];node.operation_ref=null;node.approval_scope=parts[2]||null;} graph().nodes.push(node);store.frontNode=node.id;const r=$('#canvasViewport').getBoundingClientRect();store.positions[node.id]=ensureSpace((clientX-r.left-store.x)/store.scale-109,(clientY-r.top-store.y)/store.scale-48); if(atom.operation_id==='AO02')graph().resource_edges.push({node:node.id,kind:'knowledge',resource:store.flow.definition.knowledge_bindings[0]?.name||'domain'}); if(['AO05','AO07'].includes(atom.operation_id))graph().resource_edges.push({node:node.id,kind:'framework',resource:store.flow.definition.framework_ref.split('@')[0]}); changed();selectNode(node.id);feedback('已拖入“'+node.label+'”。请从上游输出圆点拖到它的输入圆点,再连接下游;缺失输入/输出已标明。',true); } function nodePanel(wrapper){ if(!editable())return;const n=graph().nodes.find(v=>v.id===wrapper.id);if(!n)return;const body=$('.inspector-body');if(!body)return; const panel=document.createElement('section');panel.className='node-edit-panel'; panel.innerHTML=`

编辑节点

${n.kind==='start'?`UTF-8 文本,每份 ≤64 KiB;试运行 Prompt 与正文合计 ≤6000 字节,不会截断。
`:`
中间节点直接使用上游输出,不需要填写 JSON。请在下方选择输入来源。
`}

输入来源(上游输出)

已有数据连线
${graph().data_edges.filter(e=>e.target===n.id).map(e=>`
${esc(e.source+'.'+e.source_port+' → '+e.target_port)}
`).join('')||'尚无输入映射'}
`; body.prepend(panel); $('#saveNode').onclick=()=>save().catch(error); $('#removeNode').onclick=removeSelected; $$('[data-remove-mapping]').forEach(b=>b.onclick=()=>{checkpoint();graph().data_edges.splice(Number(b.dataset.removeMapping),1);changed();selectNode(n.id)}); $('#newMapping').onclick=()=>{const upstream=graph().nodes.find(v=>v.id!==n.id&&store.flow.nodes.find(w=>w.id===v.id)?.atom?.outputs?.length);if(!upstream){status('无可用来源节点');return;}chooseMapping(n.id);}; const links=graph().control_edges.filter(e=>e.source===n.id||e.target===n.id);$('#controlLinks').innerHTML='

控制连线

'+links.map(e=>`
${esc(e.source+' → '+e.target)}
`).join('');$$('[data-remove-control]').forEach(b=>b.onclick=()=>{checkpoint();graph().control_edges.splice(Number(b.dataset.removeControl),1);changed();selectNode(n.id)}); if(n.kind==='start'){ const bytes=()=>{$('#promptBytes').textContent=new TextEncoder().encode(n.inputs.requirement||'').length+' 字节(另计附件正文)';}; $('#workflowPrompt').onfocus=checkpoint;$('#workflowPrompt').oninput=e=>{n.inputs.requirement=e.target.value;changed(false);bytes()};bytes(); $('#workflowQuery').oninput=e=>{n.inputs.query=e.target.value;changed(false)}; $('#workflowFiles').onchange=async e=>{try{const files=[...e.target.files];if((n.inputs.attachments||[]).length+files.length>8)throw Error('最多 8 份附件');for(const file of files){const bytes=new Uint8Array(await file.arrayBuffer());if(bytes.length>65536)throw Error('单份附件超过 64 KiB');let binary='';for(const v of bytes)binary+=String.fromCharCode(v);const uploaded=await request('/api/v1/admin/workflow-input-files',{workflow_id:id(),name:file.name,content_base64:btoa(binary)});checkpoint();n.inputs.attachments=[...(n.inputs.attachments||[]),uploaded.id];changed(false);}await fileList(n);}catch(err){error(err)}finally{if($('#workflowFiles'))$('#workflowFiles').value=''}}; fileList(n).catch(error); }else renderInputBindings(n); } function renderInputBindings(n){ const node=store.flow.nodes.find(v=>v.id===n.id),ports=node?.atom?.inputs||[];$('#inputBindings').innerHTML=ports.map(port=>{const edge=graph().data_edges.find(e=>e.target===n.id&&e.target_port===port.name),literal=Object.hasOwn(n.inputs,port.name),candidates=inputCandidates(graph(),store.flow.nodes,n.id,port.name),value=edge?edge.source+'|'+edge.source_port:literal?'__literal':'';const isInvalid=edge&&!candidates.some(c=>c.source===edge.source&&c.source_port===edge.source_port);return `
${literal&&typeof n.inputs[port.name]==='string'?``:''}

${edge?esc('来自 '+nodeTitle(store.flow.nodes.find(v=>v.id===edge.source))+' 的 '+portLabel(edge.source_port)):literal?'已有固定输入;选择上游后会替换此固定值。':'未连接。先连通控制流程,再选择类型相符的上游输出。'}

`}).join('')||'

此系统节点无数据输入,按控制连线确认流程。

'; $$('[data-source-for]').forEach(select=>{const port=select.dataset.sourceFor,edge=graph().data_edges.find(e=>e.target===n.id&&e.target_port===port);select.value=edge?edge.source+'|'+edge.source_port:Object.hasOwn(n.inputs,port)?'__literal':'';select.onchange=()=>{checkpoint();graph().data_edges=graph().data_edges.filter(e=>!(e.target===n.id&&e.target_port===port));if(select.value==='__literal'){if(!Object.hasOwn(n.inputs,port))n.inputs[port]='';}else{delete n.inputs[port];if(select.value){const [source,source_port]=select.value.split('|');graph().data_edges.push({source,source_port,target:n.id,target_port:port});}}changed();selectNode(n.id);feedback(select.value?'已更新“'+portLabel(port)+'”的输入来源。':'“'+portLabel(port)+'”尚未连接,已标为待完善。',!select.value);};}); $$('[data-literal-for]').forEach(input=>input.oninput=()=>{n.inputs[input.dataset.literalFor]=input.value;changed(false)}); } function chooseMapping(target){ const modal=document.createElement('div');modal.className='modal-backdrop';modal.innerHTML=``;document.body.append(modal);$('#closeSource').onclick=()=>modal.remove();$('#confirmSource').onclick=()=>{const source=$('#sourceNode').value;modal.remove();mapping(source,target)}; } async function fileList(n){ const generation=store.route;const rows=await Promise.all((n.inputs.attachments||[]).map(ref=>api('workflows/'+encodeURIComponent(id())+'/input-files/'+encodeURIComponent(ref))));if(generation!==store.route||store.selected!==n.id||!$('#inputFiles'))return; $('#inputFiles').innerHTML=rows.map(f=>`
▤ ${esc(f.name)} ${f.bytes} 字节
`).join('');$$('[data-remove-file]').forEach(b=>b.onclick=()=>{checkpoint();n.inputs.attachments=n.inputs.attachments.filter(r=>r!==b.dataset.removeFile);changed(false);fileList(n).catch(error)}); } async function validate(forRun=false){ if(state.dirty)await save();const report=await request('/api/v1/admin/skills/'+encodeURIComponent(id())+'/validate',{}); const issues=[...report.issues,...(store.flow.issues||[]),...connectionIssues(graph(),store.flow.nodes)],unique=[...new Map(issues.map(i=>[i.code+'|'+i.location,i])).values()]; store.flow.issues=unique;showValidation({issues:unique,scope:'已保存草稿 r'+store.flow.source.revision+' · 实际定义校验'}); if(forRun&&unique.length)throw Error('工作流仍有未连接的输入、输出或配置问题,请点击右侧校验结果定位并连接后再试运行。'); if(unique.length)feedback('校验发现 '+unique.length+' 项,请点击右侧节点/连线/全局位置查看。',true);else feedback('图结构、必填输入与输入输出连接校验通过。');return {valid:!unique.some(i=>i.severity!=='warning'),issues:unique}; } async function startTrial(){ if(state.starting||state.active)return;state.starting=true;const button=$('#trialWorkflow');button.disabled=true;try{await save(false);await validate(true);const pendingKey=key()+'.pending.'+id();const old=JSON.parse(localStorage.getItem(pendingKey)||'null');const payload=old||{expected_revision:store.flow.source.revision,request_key:'canvas-'+crypto.randomUUID(),model:'auto'};localStorage.setItem(pendingKey,JSON.stringify(payload)); const job=await request('/api/v1/admin/workflows/'+encodeURIComponent(id())+'/trials',payload);localStorage.removeItem(pendingKey);remember(job);await poll(job.id,store.route); }catch(e){if(e.httpStatus&&e.httpStatus<500)localStorage.removeItem(key()+'.pending.'+id());error(e)}finally{state.starting=false;if($('#trialWorkflow'))$('#trialWorkflow').disabled=!editable()||state.active;} } async function poll(runId,generation){ if(generation!==store.route||!$('#trialResult'))return; const response=await fetch('/api/jobs/'+encodeURIComponent(runId),{cache:'no-store'});const job=await response.json();if(!response.ok)throw Error(job.message||job.code);if(generation!==store.route||!$('#trialResult'))return; const panel=$('#trialResult');panel.hidden=false; const verified=job.status==='verified',pending=['queued','working'].includes(job.status);state.active=pending;if($('#trialWorkflow')){$('#trialWorkflow').disabled=!editable()||pending||state.starting;$('#trialWorkflow').textContent=pending?'试运行中…':'▶ 试运行';} const preview=new URL('/preview-launch/?kind=run&reference='+encodeURIComponent(job.id),store.previewOrigin).href; panel.innerHTML=`
${verified?'运行完成 · 技术测试通过':pending?'正在试运行':job.status==='cancelled'?'已取消':'运行未通过'}任务 ${esc(job.id)} · 草稿 r${job.workflow?.revision??'?'} · ${esc(job.workflow?.digest?.slice(0,12)||'')}
查看运行画布 ↗

${esc(job.progress?.message||job.progress?.stage||job.error||'正在读取真实执行阶段')} ${job.error?esc(job.error):''}

${pending?'':''}${job.source?'':''}${verified?`打开网站预览 ↗下载工程`:''}下载运行记录
${verified?'独立构建与测试通过,页面实际业务仍待可用性验收。':'日志、用量和失败保留,未知任务不会自动重放。'} ${store.flow.source.kind==='draft'&&(state.dirty||job.workflow?.digest!==store.flow.source.digest)?'当前草稿已修改,本任务仍使用原快照。':''}
`; if(job.source)$('#viewCanvasFiles').onclick=()=>viewFiles(job.id).catch(error); if(verified){$('#materializeCanvas').onclick=async()=>{try{const project=await request('/api/jobs/'+encodeURIComponent(job.id)+'/project',{});$('#canvasProject').textContent='工程已保存:'+project.directory}catch(e){error(e)}};} if(pending)$('#cancelCanvasRun').onclick=async()=>{try{await request('/api/jobs/'+encodeURIComponent(job.id)+'/cancel',{});await poll(runId,generation)}catch(e){error(e)}}; if(!state.dirty&&job.workflow?.digest===store.flow.source.digest){store.trace=await api('workflow-runs/'+encodeURIComponent(runId));if(generation!==store.route)return;draw();} clearTimeout(state.timer);if(pending)state.timer=setTimeout(()=>poll(runId,generation).catch(error),1500); } async function viewFiles(runId){ const r=await fetch('/api/deliveries/run/'+encodeURIComponent(runId),{cache:'no-store'}),data=await r.json();if(!r.ok)throw Error(data.message||data.code); const modal=document.createElement('div');modal.className='modal-backdrop';modal.innerHTML=``;document.body.append(modal); let diff=false;const render=()=>{const f=data.files[Number($('#deliveryFile').value)];$('#deliveryContent').textContent=diff?(f.diff||'文件无差异'):f.content;};$('#closeFiles').onclick=()=>modal.remove();$('#deliveryFile').onchange=render;$('#viewContent').onclick=()=>{diff=false;render()};$('#viewDiff').onclick=()=>{diff=true;render()};$('#downloadFile').onclick=()=>{const f=data.files[Number($('#deliveryFile').value)],url=URL.createObjectURL(new Blob([f.content],{type:'text/plain;charset=utf-8'})),a=document.createElement('a');a.href=url;a.download=f.path.split('/').pop();a.click();setTimeout(()=>URL.revokeObjectURL(url),30000)};render(); } async function mount(){ edgePan.stop();state.generation++;clearTimeout(state.timer);state.dirty=false;state.pending=null;state.history=[];state.future=[]; // Definitions/instances share one browser model, mirroring the server authority. state.active=false;if(editable())sync(); const saved=store.flow.definition.editor_positions||{};for(const [nid,p] of Object.entries(saved)){if(store.positions[nid])store.positions[nid]={x:p.x,y:p.y};} store.world.width=Math.max(store.world.width,...Object.values(store.positions).map(p=>p.x+248));store.world.height=Math.max(store.world.height,...Object.values(store.positions).map(p=>p.y+124));$('#canvas').style.width=store.world.width+'px';$('#canvas').style.height=store.world.height+'px'; $('#showValidation').onclick=()=>editable()?validate(false).catch(error):showValidation(); $('#cloneWorkflow').disabled=!store.canEdit||store.flow.source.kind!=='draft';$('#cloneWorkflow').onclick=async()=>{try{const doc=await request('/api/v1/admin/workflows/'+encodeURIComponent(id())+'/clone',{});store.workflows=await api('workflows');navigate('#workflow='+doc.key)}catch(e){error(e)}}; const reason=!store.canEdit?'当前角色只能查看,请使用管理角色编辑':store.flow.source.kind!=='draft'?'历史快照只读,请选择当前草稿后编辑':'';$('#editorMode').textContent=editable()?'编辑草稿':store.flow.source.kind==='draft'?'只读 · 当前角色':'只读 · 不可变版本';for(const selector of ['#cloneWorkflow','#saveDraft','#trialWorkflow'])$(selector).title=reason;$('#saveDraft').disabled=!editable();$('#trialWorkflow').disabled=!editable()||state.starting;$('#saveDraft').onclick=()=>save().catch(error);$('#trialWorkflow').onclick=startTrial; const controls=$('.canvas-controls');controls.insertAdjacentHTML('beforeend','');$('#undoDraft').disabled=!editable();$('#redoDraft').disabled=!editable();$('#undoDraft').onclick=()=>history(true);$('#redoDraft').onclick=()=>history(false); const auto=$('#autoLayout').onclick;$('#autoLayout').onclick=()=>{if(editable())checkpoint();auto();if(editable())changed(false)}; const remove=document.createElement('button');remove.id='deleteSelection';remove.className='danger';remove.textContent='删除选中';remove.onclick=removeSelected;controls.append(remove);selection();draw();palette();dropTarget($('#canvasViewport')); const active=remembered()[id()];if(active&&store.flow.source.kind==='draft'){$('#trialWorkflow').disabled=true;poll(active,store.route).catch(error);} // Historical runs share exactly the same artifact/view/download/preview paths. if(store.flow.source.kind==='run')poll(store.flow.source.ref,store.route).catch(error); } window.addEventListener('keydown',e=>{if(e.key==='Escape'){edgePan.stop();state.pending=null;$('#connectionDrag')?.remove();$$('.port.connecting,.drop-ready').forEach(p=>{p.classList.remove('connecting');p.classList.remove('drop-ready')});}}); window.addEventListener('keydown',e=>{if(!['Delete','Backspace'].includes(e.key)||e.defaultPrevented||e.ctrlKey||e.altKey||e.metaKey||!$('#canvasViewport')||$('.modal-backdrop')||e.target.closest('input,textarea,select,[contenteditable="true"]'))return;if(editable()&&(store.selected||store.selectedEdge)){e.preventDefault();removeSelected();}}); window.addEventListener('dragend',()=>edgePan.stop()); window.addEventListener('hashchange',()=>edgePan.stop()); window.addEventListener('beforeunload',e=>{if(state.dirty&&editable()){e.preventDefault();e.returnValue='';}}); return {mount,palette,dropTarget,wireNodes,wireEdges,nodePanel,edgePanel,selection,moved(){if(editable()){changed(false);status('位置已调整,保存草稿后保留布局;执行语义由节点与连线决定')}}}; }