From 32bd0487c824f1a4bbf6aa435ff50885a01bbdec Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 21 Nov 2026 00:34:09 +0800 Subject: [PATCH 1/7] fix(sop): bind assistant-generated project roles --- web/app.js | 27 ++++- web/app/agents.js | 10 +- web/app/flow-canvas.css | 2 + web/app/flows.js | 33 ++++-- web/index.html | 6 +- web/orchestrate.js | 155 ++++++++++++++++++++------ web/orchestrate_models_test.js | 24 +++- web/syntax_test.go | 2 +- webtest/tests/flow-designer.test.mjs | 3 + webtest/tests/orchestrate-ai.test.mjs | 27 +++++ 10 files changed, 227 insertions(+), 62 deletions(-) diff --git a/web/app.js b/web/app.js index 36c167d9..7a2c692e 100644 --- a/web/app.js +++ b/web/app.js @@ -737,12 +737,25 @@ function scopedWorkflows(){ return all.filter(w=>!catalogGeneric(w)&&catalogOwned(w.projectId)); } function catalogAgents(){return (state.data?.agents||[]).filter(a=>catalogVisible(a.projectId,a.shared))} +function projectWorkflowAgent(agent,projectId){ + return !!agent.projectId&&(agent.projectId===projectId||agent.shared); +} function workflowAgents(){ if(catalogGeneric(state.workflow))return state.genericTemplateAgents||[]; const projectId=state.workflow?.projectId||state.projectFilter||''; - return (state.data?.agents||[]).filter(a=>!!a.projectId&&(a.projectId===projectId||(a.shared&&a.projectId!==projectId))); + return (state.data?.agents||[]).filter(a=>projectWorkflowAgent(a,projectId)); } function workflowAgent(id){return workflowAgents().find(a=>a.id===id)} +async function refreshWorkflowAgents(){ + const wf=state.workflow; + if(catalogGeneric(wf))return hydrateGenericWorkflowRoles(wf); + const projectId=wf?.projectId||state.projectFilter; + if(!projectId)return; + const agents=await api('/api/agents?projectId='+encodeURIComponent(projectId),{silent:true}); + if(state.workflow!==wf)return; + const ids=new Set(agents.map(a=>a.id)); + state.data.agents=(state.data.agents||[]).filter(a=>!projectWorkflowAgent(a,projectId)&&!ids.has(a.id)).concat(agents); +} function clearGenericTemplateAgents(){state.genericTemplateAgents=[];state.genericTemplateAgentWorkflowId=''} async function hydrateGenericWorkflowRoles(wf=state.workflow){ if(!catalogGeneric(wf)){ @@ -1101,7 +1114,7 @@ function bind(){ $('#refreshDashboard').onclick=refreshDashboard; $('#refreshIssues').onclick=refreshIssues; $('#refreshSOPs').onclick=refreshWorkflowMetrics; - $('#agentSearch').oninput=renderAgents;$('#agentPrev').onclick=agentWizardPrev;$('#agentNext').onclick=agentWizardNext;$$('[data-wizard-steps="agent"] [data-agent-tab]').forEach(b=>b.onclick=()=>setAgentTab(b.dataset.agentTab));$$('[data-wizard-steps="agent-create"] [data-create-step]').forEach(b=>b.onclick=()=>{if(!b.disabled)setAgentCreateStep(Number(b.dataset.createStep))});bindAgentModalInputs();$$('.agent-close').forEach(b=>b.onclick=()=>$('#agentModal').classList.remove('open')); + $('#agentSearch').oninput=renderAgents;$('#agentPrev').onclick=agentWizardPrev;$('#agentNext').onclick=agentWizardNext;$$('[data-wizard-steps="agent"] [data-agent-tab]').forEach(b=>b.onclick=()=>setAgentTab(b.dataset.agentTab));$$('[data-wizard-steps="agent-create"] [data-create-step]').forEach(b=>b.onclick=()=>{if(!b.disabled)setAgentCreateStep(Number(b.dataset.createStep))});bindAgentModalInputs();$$('.agent-close').forEach(b=>b.onclick=closeAgentWizard); $('#newRunFromRuns')&&($('#newRunFromRuns').onclick=()=>switchView('issues')); $('#runSearch').oninput=e=>{state.runQuery=e.target.value.trim().toLowerCase();resetListPage('runs');renderRuns()}; $('#runWorkflowFilter').onchange=e=>{state.runWorkflowFilter=e.target.value;resetListPage('runs');renderRuns()}; @@ -1307,6 +1320,7 @@ function bind(){ } const open=[...$$('.modal.open')].pop(); if(open?.id==='scheduleModal')return closeScheduleJobModal(); + if(open?.id==='agentModal')return closeAgentWizard(); if(open)return open.classList.remove('open'); const panel=$('#flowSettingsPanel'); if(panel&&!panel.hidden){panel.hidden=true;$('#flowSettingsToggle')?.classList.remove('active');return} @@ -1847,14 +1861,14 @@ function applyAssetRoute(){ } async function applyAgentRoute(){ const id=agentRouteId(); - if(!id)return; + if(!id){$('#agentModal')?.classList.remove('open');return} try{ const agent=await api(`/api/agents/${encodeURIComponent(id)}`); if(agentRouteId()!==id||activeViewName()!=='agents')return; const index=(state.data.agents||[]).findIndex(a=>a.id===id); if(index>=0)state.data.agents[index]=agent;else state.data.agents.push(agent); - openAgentWizard(agent); - }catch(error){toast(error.message,'err')} + openAgentWizard(agent,routePart(2)==='gov'?3:1,{loaded:true}); + }catch(error){if(agentRouteId()===id)toast(error.message,'err')} } // Only SOPs visible in the active project can be restored from the URL or localStorage. function openableWorkflow(id){return id?catalogWorkflows().find(w=>w.id===id)||null:null} @@ -1902,7 +1916,7 @@ function persistView(name,push=false){ if(linked)next=runViewHash(linked); } if(name==='flow')next=flowViewHash(); - if(name==='agents'&&agentRouteId())next=`#/agents/${encodeURIComponent(agentRouteId())}`; + if(name==='agents'&&agentRouteId())next=`#/agents/${encodeURIComponent(agentRouteId())}${routePart(2)==='gov'?'/gov':''}`; if(isProjectSharedAsset(name)&&routePart(0)===name&&assetRouteId())next=`#/${name}/${encodeURIComponent(assetRouteId())}`; if(name==='projects')next=projectAdminHash(state.projectAdminDetailId||'',state.projectAdminTab); if(name==='collaboration'){ @@ -1932,6 +1946,7 @@ function switchView(name){ // 手敲 #/platform 或者从别的账号留下的 localStorage 恢复进来,都要挡住。 if(name==='platform'&&!isPlatformAdmin())name='collaboration'; const previous=activeViewName(); + if(previous==='agents'&&name!=='agents')$('#agentModal')?.classList.remove('open'); if(!settingsRouteApplying){ const crossingSettings=previous!==name&&((previous==='collaboration'&&isSettingsManagementView(name))||(isSettingsManagementView(previous)&&name==='collaboration')); if(crossingSettings&&!settingsRouteMotion.matches){startSettingsRouteTransition(name);return} diff --git a/web/app/agents.js b/web/app/agents.js index aa9b56d4..b1b4005f 100644 --- a/web/app/agents.js +++ b/web/app/agents.js @@ -282,7 +282,11 @@ function setAgentModalMode(mode){ state.agentModalMode=mode==='create'?'create':'edit'; const f=$('#agentForm');if(f)f.dataset.agentMode=state.agentModalMode; } -function openAgentWizard(agent=null,initialStep=1){ +function closeAgentWizard(){ + $('#agentModal').classList.remove('open'); + if(agentRouteId())history.replaceState(null,'','#/agents'); +} +function openAgentWizard(agent=null,initialStep=1,{loaded=false}={}){ const open=a=>{ const presetHost=$('#agentPresetHost');if(presetHost)presetHost.dataset.ready=''; setAgentModalMode(a?.id?'edit':'create'); @@ -295,7 +299,7 @@ function openAgentWizard(agent=null,initialStep=1){ syncAgentTabIndicators();requestAnimationFrame(()=>syncAgentTabIndicators()); if(catalogGeneric(state.workflow))loadMCPMarket().then(()=>{const current=workflowAgent(state.selectedAgent)||state.agentDraft||a;if(current){renderAgentAssetsPanel(current);renderAgentSummary()}}); }; - if(agent?.id && !agent.prompt){ + if(agent?.id && !agent.prompt && !loaded && !catalogGeneric(state.workflow)){ api(`/api/agents/${encodeURIComponent(agent.id)}`).then(full=>{const i=state.data.agents.findIndex(x=>x.id===full.id);if(i>=0)state.data.agents[i]=full;open(full)}).catch(e=>{toast(e.message,'err');open(agent)}); return; } @@ -440,7 +444,7 @@ async function persistAgent(f){ // MR gates are checked by the platform and carry no commands; every other // gate is saved as a command gate and dropped while it has no command. function agentGatesForSave(gates){return (gates||[]).map((gate,i)=>{const base={id:gate.id||`gate-${i+1}`,name:gate.name||`门禁 ${i+1}`,stage:'after_execution',required:true,onFailure:['loop','reject','fail','human'].includes(gate.onFailure)?gate.onFailure:'loop'};return gate.mode==='mr'?{...base,mode:'mr'}:{...base,mode:'command',commands:(gate.commands||[]).map(c=>String(c||'').trim()).filter(Boolean),executionScope:gate.executionScope==='repositories'?'repositories':'run'}}).filter(g=>g.mode==='mr'||g.commands.length)} -async function persistAgentRequest(f,creating){const existing=state.data.agents.find(a=>a.id===f.elements.id.value);if(!catalogGeneric(state.workflow)&&existing&&catalogForeign(existing.projectId))return toast('这是其他项目的共享角色,请先复制到本项目再改');const checked=name=>[...f.querySelectorAll(`input[name="${name}"]:checked`)].map(x=>x.value);const draft=readAgentDraft(f);const artifacts=draft.artifactOutputs.map((x,i)=>({name:x.name||`artifact-${i+1}`,path:x.path||'result.md',mediaType:x.path?.endsWith('.json')?'application/json':(x.mediaType||'text/markdown'),required:!!x.required})),verification=agentGatesForSave(draft.verification),hooks=(draft.hooks||[]).map((h,i)=>({id:String(h.id||`hook-${i+1}`).trim(),name:String(h.name||`Hook ${i+1}`).trim(),event:h.event||'PreToolUse',matcher:String(h.matcher||'').trim(),language:h.language==='python'?'python':'shell',script:String(h.script||'').trim(),timeoutSec:Number(h.timeoutSec)||10,executionScope:h.executionScope==='repositories'?'repositories':'run'})).filter(h=>h.script),interventions=[];if(f.elements.interventionAfter?.checked)interventions.push({id:'human-review',name:'人工结果复核',stage:'after_execution',required:true});if(f.elements.interventionPublish?.checked)interventions.push({id:'publish-approval',name:'产物发布确认',stage:'before_publish',required:true});const a={id:f.elements.id.value.trim(),name:f.elements.name.value.trim(),version:(existing?.version||0)+1,projectId:existing?(existing.projectId||state.projectFilter||''):(state.projectFilter||''),shared:!!f.elements.shared?.checked,description:f.elements.description.value,prompt:draft.prompt,executorId:f.elements.executorId?.value||'',model:agentEffectiveModel(f),effort:f.elements.effort?.value||'',rules:checked('rules'),skills:checked('skills'),mcpServers:checked('mcpServers'),platformMcp:!!f.elements.platformMcp?.checked,knowledgeBase:!!f.elements.knowledgeBase?.checked,hooks,loop:{enabled:!!f.elements.loopEnabled?.checked,maxIterations:Number(f.elements.loopMaxIterations?.value)||1,exitCondition:'all_gates_pass',onExhausted:f.elements.loopOnExhausted?.value||'fail',feedbackPrompt:f.elements.loopFeedbackPrompt?.value||''},interventions,artifactOutputs:artifacts,verification};if(!a.id||!a.name)return toast('标识和名称不能为空');if(catalogGeneric(state.workflow)){if(!isPlatformAdmin())return toast('只有平台管理员可以编辑通用模板角色');const bundled=workflowAgent(a.id);if(!bundled)return toast('该角色不属于当前通用模板');a.projectId='';a.shared=false;a.rules=bundled.rules||[];a.skills=bundled.skills||[];a.mcpServers=f.querySelectorAll('input[name="mcpServers"]').length?checked('mcpServers'):(bundled.mcpServers||[]);a.hooks=Array.isArray(bundled.hooks)?bundled.hooks:a.hooks;a.version=bundled.version||0;try{const saved=await api(`/api/workflows/${encodeURIComponent(state.workflow.id)}/agents`,{method:'PUT',body:JSON.stringify(a)});const list=state.genericTemplateAgents||[];const gi=list.findIndex(x=>x.id===saved.id);if(gi>=0)list[gi]=saved;else list.push(saved);state.genericTemplateAgents=list;state.selectedAgent=saved.id;state.agentDraft=null;$('#agentModal').classList.remove('open');renderCanvas();renderProperties();toast('通用模板角色已保存,所有项目下次运行生效');}catch(err){toast(err.message)}return;}try{await api('/api/agents',{method:'PUT',body:JSON.stringify(a)});const i=state.data.agents.findIndex(x=>x.id===a.id);if(i>=0)state.data.agents[i]=a;else state.data.agents.push(a);if(a.shared){(state.data.rules||[]).forEach(item=>{if(a.rules.includes(item.id)&&item.projectId===a.projectId)item.shared=true});(state.data.skills||[]).forEach(item=>{if(a.skills.includes(item.id)&&item.projectId===a.projectId)item.shared=true})}state.selectedAgent=a.id;state.agentDraft=null;if(creating){state.agentScope='project';renderAgents();renderCanvas();toast('Agent 新版本已保存');showCreatedAgent(a);return a}$('#agentModal').classList.remove('open');renderAgents();renderCanvas();toast('Agent 新版本已保存');return a}catch(err){toast(err.message)}return null} +async function persistAgentRequest(f,creating){const existing=state.data.agents.find(a=>a.id===f.elements.id.value);if(!catalogGeneric(state.workflow)&&existing&&catalogForeign(existing.projectId))return toast('这是其他项目的共享角色,请先复制到本项目再改');const checked=name=>[...f.querySelectorAll(`input[name="${name}"]:checked`)].map(x=>x.value);const draft=readAgentDraft(f);const artifacts=draft.artifactOutputs.map((x,i)=>({name:x.name||`artifact-${i+1}`,path:x.path||'result.md',mediaType:x.path?.endsWith('.json')?'application/json':(x.mediaType||'text/markdown'),required:!!x.required})),verification=agentGatesForSave(draft.verification),hooks=(draft.hooks||[]).map((h,i)=>({id:String(h.id||`hook-${i+1}`).trim(),name:String(h.name||`Hook ${i+1}`).trim(),event:h.event||'PreToolUse',matcher:String(h.matcher||'').trim(),language:h.language==='python'?'python':'shell',script:String(h.script||'').trim(),timeoutSec:Number(h.timeoutSec)||10,executionScope:h.executionScope==='repositories'?'repositories':'run'})).filter(h=>h.script),interventions=[];if(f.elements.interventionAfter?.checked)interventions.push({id:'human-review',name:'人工结果复核',stage:'after_execution',required:true});if(f.elements.interventionPublish?.checked)interventions.push({id:'publish-approval',name:'产物发布确认',stage:'before_publish',required:true});const a={id:f.elements.id.value.trim(),name:f.elements.name.value.trim(),version:(existing?.version||0)+1,projectId:existing?(existing.projectId||state.projectFilter||''):(state.projectFilter||''),shared:!!f.elements.shared?.checked,description:f.elements.description.value,prompt:draft.prompt,executorId:f.elements.executorId?.value||'',model:agentEffectiveModel(f),effort:f.elements.effort?.value||'',rules:checked('rules'),skills:checked('skills'),mcpServers:checked('mcpServers'),platformMcp:!!f.elements.platformMcp?.checked,knowledgeBase:!!f.elements.knowledgeBase?.checked,hooks,loop:{enabled:!!f.elements.loopEnabled?.checked,maxIterations:Number(f.elements.loopMaxIterations?.value)||1,exitCondition:'all_gates_pass',onExhausted:f.elements.loopOnExhausted?.value||'fail',feedbackPrompt:f.elements.loopFeedbackPrompt?.value||''},interventions,artifactOutputs:artifacts,verification};if(!a.id||!a.name)return toast('标识和名称不能为空');if(catalogGeneric(state.workflow)){if(!isPlatformAdmin())return toast('只有平台管理员可以编辑通用模板角色');const bundled=workflowAgent(a.id);if(!bundled)return toast('该角色不属于当前通用模板');a.projectId='';a.shared=false;a.rules=bundled.rules||[];a.skills=bundled.skills||[];a.mcpServers=f.querySelectorAll('input[name="mcpServers"]').length?checked('mcpServers'):(bundled.mcpServers||[]);a.hooks=Array.isArray(bundled.hooks)?bundled.hooks:a.hooks;a.version=bundled.version||0;try{const saved=await api(`/api/workflows/${encodeURIComponent(state.workflow.id)}/agents`,{method:'PUT',body:JSON.stringify(a)});const list=state.genericTemplateAgents||[];const gi=list.findIndex(x=>x.id===saved.id);if(gi>=0)list[gi]=saved;else list.push(saved);state.genericTemplateAgents=list;state.selectedAgent=saved.id;state.agentDraft=null;$('#agentModal').classList.remove('open');renderCanvas();renderProperties();toast('通用模板角色已保存,所有项目下次运行生效');}catch(err){toast(err.message)}return;}try{await api('/api/agents',{method:'PUT',body:JSON.stringify(a)});const i=state.data.agents.findIndex(x=>x.id===a.id);if(i>=0)state.data.agents[i]=a;else state.data.agents.push(a);if(a.shared){(state.data.rules||[]).forEach(item=>{if(a.rules.includes(item.id)&&item.projectId===a.projectId)item.shared=true});(state.data.skills||[]).forEach(item=>{if(a.skills.includes(item.id)&&item.projectId===a.projectId)item.shared=true})}state.selectedAgent=a.id;state.agentDraft=null;if(creating){state.agentScope='project';renderAgents();renderWorkflowMeta();renderCanvas();toast('Agent 新版本已保存');showCreatedAgent(a);return a}closeAgentWizard();renderAgents();renderCanvas();toast('Agent 新版本已保存');return a}catch(err){toast(err.message)}return null} async function deleteAgent(id){ const a=(state.data.agents||[]).find(x=>x.id===id); if(!a)return toast('角色不存在或已删除'); diff --git a/web/app/flow-canvas.css b/web/app/flow-canvas.css index 32ba62c7..5e2fb609 100644 --- a/web/app/flow-canvas.css +++ b/web/app/flow-canvas.css @@ -428,6 +428,8 @@ html[data-theme="dark"] #flowView .fd-toast button{background:rgba(0,0,0,.06);co #aiOrchestrator textarea::placeholder{color:var(--hui-tertiary)} #aiOrchestrator textarea:focus{outline:0;box-shadow:none} #aiOrchestrator .ai-orchestrator-toolbar{display:flex;align-items:center;justify-content:space-between;gap:6px;min-width:0} +/* Keep the floating feedback control clear of the send button. */ +body:has(.fb-fab:not(.gone):not(.is-hidden)) #aiOrchestrator .ai-orchestrator-toolbar{padding-inline-end:52px} #aiOrchestrator .ai-orchestrator-runtime{display:flex;align-items:center;gap:2px;flex:1;min-width:0} #aiOrchestrator .ai-orchestrator-picker{min-width:0;flex:1} #aiOrchestrator #aiOrchestratorCLIPicker{flex:0 1 116px} diff --git a/web/app/flows.js b/web/app/flows.js index a52efd57..a9f28cc1 100644 --- a/web/app/flows.js +++ b/web/app/flows.js @@ -193,12 +193,11 @@ function addNode(type,opts={}){ const at=opts.at?{x:Math.round(opts.at.x/10)*10,y:Math.round(opts.at.y/10)*10}:flowViewport.freeSpot(); if(type==='preview'){ const existing=state.workflow.nodes.find(n=>isPreviewBuildNode(n.id)); - if(existing){state.selectedNode=existing.id;renderCanvas();renderProperties();return toast('预览节点已存在,可拖拽连线调整它的位置')} + if(existing){openNodeDrawer(existing.id);return toast('预览节点已存在,可拖拽连线调整它的位置')} flowHistory.record(); ensurePreviewContract(); state.workflow.nodes.push({id:PREVIEW_BUILD_NODE_ID,name:'构建静态站点',type:'agent',agentId:PREVIEW_BUILD_AGENT_ID,executorId:'codebuddy',executionScope:'run',onFailure:'fail',retryStrategy:'targeted_fix',maxAttempts:2,maxReworks:1,position:at,artifactOutputs:[{name:'frontend-preview',path:'dist/index.html',required:true}]}); - state.selectedNode=PREVIEW_BUILD_NODE_ID; - dirty();renderCanvas();renderProperties(); + dirty();openNodeDrawer(PREVIEW_BUILD_NODE_ID); return; } flowHistory.record(); @@ -207,8 +206,8 @@ function addNode(type,opts={}){ const agentId=type==='agent'?(opts.agentId||workflowAgents()[0]?.id||''):''; const agent=agentId?workflowAgent(agentId):null; const node={id:uid(type),name:firstSOP?.name||(opts.agentId&&agent?.name)||labels[type]||'新节点',type,agentId,sopWorkflowId:firstSOP?.id||'',scriptLanguage:type==='script'?'shell':'',script:type==='script'?"printf 'passed\\n'":'',executionScope:'run',artifactOutputs:firstSOP?sopDeclaredArtifacts(firstSOP):[],rejectTo:'',onFailure:'fail',retryStrategy:'targeted_fix',carryOver:['failed_checks','last_error','upstream_artifacts'],maxAttempts:1,maxReworks:3,position:at}; - state.workflow.nodes.push(node);state.selectedNode=node.id; - dirty();renderCanvas();renderProperties(); + state.workflow.nodes.push(node); + dirty();openNodeDrawer(node.id); } // Removes a node with its edges and any reject routes pointing at it. function removeNode(id){ @@ -235,8 +234,8 @@ function duplicateNode(id){ const copy=clone(n); Object.assign(copy,{id:uid(n.type||'node'),name:`${n.name} 副本`,position:{x:(n.position?.x||0)+40,y:(n.position?.y||0)+40},rejectTo:''}); if(copy.onFailure==='reject')copy.onFailure='fail'; - wf.nodes.push(copy);state.selectedNode=copy.id; - dirty();renderCanvas();renderProperties(); + wf.nodes.push(copy); + dirty();openNodeDrawer(copy.id); flowToast('已复制(不含连线)',{undo:true}); return copy; } @@ -593,6 +592,7 @@ function flowToast(message,opts={}){ } function openNodeDrawer(id){ if(!state.workflow?.nodes.some(n=>n.id===id))return; + if($('#aiOrchestrator')?.hidden===false)setAIOrchestratorOpen(false); if(state.selectedNode!==id)state.flowWantReject=null; state.selectedNode=id;renderCanvas();renderProperties(); } @@ -851,6 +851,14 @@ function effectiveNodeArtifacts(node,agent){ function roleGates(agent){ return [...(agent?.verification||[])].filter(g=>g.mode!=='submit'); } +function boundRoleLink(agent,validation=false){ + if(!agent)return ''; + const id=validation?'openBoundAgentValidation':'openBoundAgent'; + const label=validation?'去角色定义编辑校验清单':'角色配置'; + if(catalogGeneric(state.workflow))return ``; + const href='#/agents/'+encodeURIComponent(agent.id)+(validation?'/gov':''); + return `${label}`; +} function nodeGatePane(n){ const agent=workflowAgent(n.agentId); const artifacts=effectiveNodeArtifacts(n,agent); @@ -860,7 +868,7 @@ function nodeGatePane(n){ const gateRows=gates.length?gates.map(g=>{const cmds=(g.commands||[]).filter(Boolean);return `
${flowPalette.icon('terminal',13)}${escapeHTML(g.name||g.id||'未命名门禁')}${escapeHTML(cmds.join(' && ')||'人工确认')}${g.executionScope==='repositories'?'每个代码仓库':'Run 工作区'} · 失败后 ${escapeHTML({loop:'本节点自修正',reject:'打回上游',human:'转人工确认',fail:'本节点失败'}[g.onFailure]||'按节点策略')}
`}).join(''):'
这个节点没有额外门禁命令。
'; const terminal=n.type==='agent'?step(1,'先提交结构化终态','平台内建',`
${flowPalette.icon('check',13)}pass | rework | fail | humanAgent 完成任务后必须先调用 submit_gate_result 提交终态;缺失时自动恢复同一会话重试。
`):''; const base=n.type==='agent'?1:0; - return `

执行时 Agent 节点先提交结构化终态,随后校验产物,最后执行可选门禁命令。

    ${terminal}${step(base+1,'再校验产物',`${artifacts.length} 项`,artifactRows)}${step(base+2,'最后触发额外门禁',`${gates.length} 项`,gateRows)}
${agent?'':''}`; + return `

执行时 Agent 节点先提交结构化终态,随后校验产物,最后执行可选门禁命令。

    ${terminal}${step(base+1,'再校验产物',`${artifacts.length} 项`,artifactRows)}${step(base+2,'最后触发额外门禁',`${gates.length} 项`,gateRows)}
${boundRoleLink(agent,true)}`; } function renderAgentAssetsPanel(a){ @@ -970,7 +978,7 @@ function agentBindCard(n){ const duty=String(agent.description||'').trim(),taskHint=duty?(duty.length>48?`${duty.slice(0,48)}…`:duty):'还没写职责,可在角色定义里补'; const model=agent.model||exec?.model||exec?.name||'未选模型'; return `

${hint}

-
${escapeHTML(flowPalette.initial(agent.name))}${escapeHTML(agent.name)}${escapeHTML(taskHint)}
${escapeHTML(model)}模型
${arts.length}产物
${gates.length}门禁
${agent.loop?.enabled?`${agent.loop.maxIterations||1} 轮`:'单轮'}Loop
`; +
${escapeHTML(flowPalette.initial(agent.name))}${escapeHTML(agent.name)}${escapeHTML(taskHint)}${boundRoleLink(agent)}
${escapeHTML(model)}模型
${arts.length}产物
${gates.length}门禁
${agent.loop?.enabled?`${agent.loop.maxIterations||1} 轮`:'单轮'}Loop
`; } function flowDrawerHead(n,kind,label){ const agent=kind==='agent'?workflowAgent(n.agentId):null; @@ -1063,8 +1071,11 @@ function bindNodeProperties(host,n){ }; host.querySelector('#addSOPHandoff')?.addEventListener('click',()=>{flowHistory.record();n.artifactOutputs=n.artifactOutputs||[];n.artifactOutputs.push({name:'',path:'',mediaType:'text/markdown',required:true});renderProperties();dirty()}); if(n.type==='sop')bindArtifactRows(host,n); - const openBound=$('#openBoundAgent');if(openBound)openBound.onclick=()=>{const agent=workflowAgent(n.agentId);if(!agent)return;if(!catalogGeneric(state.workflow))switchView('agents');openAgentWizard(agent,2)}; - const openBoundValidation=$('#openBoundAgentValidation');if(openBoundValidation)openBoundValidation.onclick=()=>{const agent=workflowAgent(n.agentId);if(!agent)return;if(!catalogGeneric(state.workflow))switchView('agents');openAgentWizard(agent,3)}; + if(catalogGeneric(state.workflow)){ + const agent=workflowAgent(n.agentId); + host.querySelector('#openBoundAgent')?.addEventListener('click',()=>openAgentWizard(agent)); + host.querySelector('#openBoundAgentValidation')?.addEventListener('click',()=>openAgentWizard(agent,3)); + } host.querySelectorAll('[data-fail]').forEach(b=>b.onclick=()=>{ if(b.dataset.fail==='fail'){state.flowWantReject=false;if(!setRejectTo(n.id,'')&&n.onFailure==='reject'){n.onFailure='fail';dirty()}renderProperties();return} state.flowWantReject=true;renderProperties();host.querySelector('#rejectTarget')?.focus(); diff --git a/web/index.html b/web/index.html index 48d4376d..1350ed02 100644 --- a/web/index.html +++ b/web/index.html @@ -31,7 +31,7 @@ - + @@ -1325,7 +1325,7 @@

确认操作

- + @@ -1350,6 +1350,6 @@

确认操作

- + diff --git a/web/orchestrate.js b/web/orchestrate.js index 7d36327e..ad30e85f 100644 --- a/web/orchestrate.js +++ b/web/orchestrate.js @@ -360,9 +360,14 @@ function openAIOrchestrator() { } function resetAIOrchestrator() { + const build = aiBuild; + const restore = isCurrentAIBuild(build); aiBuildToken++; aiAbort?.abort(); + aiBuild = null; + if (restore) restoreAIBuildFailure(build); finishAIBuildVisuals(); + syncCanvasAIEntry(); if (state.projectFilter) delete aiHistory[state.projectFilter]; const log = $('#aiOrchestratorLog'); const intro = $('#aiOrchestratorIntro'); @@ -503,6 +508,11 @@ function placeAIGhost() { host.append(ghost); } +function isCurrentAIBuild(build) { + return !!build && aiBuild === build && build.token === aiBuildToken + && state.projectFilter === build.projectId && state.workflow?.id === build.workflowId; +} + async function startAIBuild(raw, opts = {}) { const occupied = !!state.workflow && ((state.workflow.nodes || []).length > 0 || state.workflowDirty); if (occupied && !opts.confirmed) { @@ -517,8 +527,15 @@ async function startAIBuild(raw, opts = {}) { const token = ++aiBuildToken; finishAIBuildVisuals(); const previous = state.workflow ? aiClone(state.workflow) : null; - aiBuild = {token, buffer: '', thought: '', placed: new Map(), wired: new Set(), pendingEdges: [], queue: [], draining: null, ghostText: opts.ghost || 'AI 正在理解你的需求…', ghostHidden: false, freePositions: true, mode: 'create', previous, spawned: 0, goal: opts.goal || '', referenced: opts.referenced || []}; + const selectedNode = state.selectedNode; state.workflow = shellForAIWorkflow(raw || {}); + aiBuild = { + token, workflowId: state.workflow.id, projectId: state.projectFilter, selectedNode, + buffer: '', thought: '', placed: new Map(), wired: new Set(), pendingEdges: [], + queue: [], draining: null, ghostText: opts.ghost || 'AI 正在理解你的需求…', + ghostHidden: false, freePositions: true, mode: 'create', previous, + goal: opts.goal || '', referenced: opts.referenced || [] + }; state.selectedNode = null; if ((state.currentView || activeViewName()) !== 'flow') switchView('flow'); renderWorkflowMeta(); @@ -532,7 +549,7 @@ async function startAIBuild(raw, opts = {}) { function ingestStreamingWorkflow(graph) { const build = aiBuild; - if (!build) return; + if (!isCurrentAIBuild(build)) return; if (graph.name && state.workflow && state.workflow.name !== graph.name) { state.workflow.name = graph.name; renderWorkflowMeta(); @@ -560,7 +577,7 @@ function drainAIBuild() { // Yield first so the assignment above lands before the loop can finish and clear it. await Promise.resolve(); try { - while (aiBuild === build && build.token === aiBuildToken) { + while (isCurrentAIBuild(build)) { const ready = build.pendingEdges.findIndex(item => build.placed.has(item.data.source) && build.placed.has(item.data.target)); if (ready >= 0) { const [item] = build.pendingEdges.splice(ready, 1); @@ -582,13 +599,12 @@ async function aiPlaceNode(build, node) { if (!node.position) node.position = aiProvisionalPosition(build.placed.size); state.workflow.nodes.push(node); build.placed.set(node.id, node); - build.spawned = (build.spawned || 0) + 1; - state.selectedNode = node.id; + if (!$('#aiOrchestrator')?.hidden) state.selectedNode = node.id; renderCanvas(); const el = document.querySelector('.flow-node[data-id="' + (CSS.escape ? CSS.escape(node.id) : node.id) + '"]'); el?.classList.add('ai-just-built'); aiCanvasFollow(node.position.x, node.position.y); - const agent = node.agentId ? (state.data?.agents || []).find(a => a.id === node.agentId) : null; + const agent = workflowAgent(node.agentId); appendOrchestratorNote('创建节点「' + node.name + '」' + (agent ? ' · ' + agent.name : ''), 'step'); setAIBuildStatus('已建 ' + build.placed.size + ' 个节点:' + node.name); setAIGhostText('AI 正在写下一个节点…'); @@ -659,6 +675,10 @@ async function completeAIBuild(build, finalRaw) { } if (finalRaw && Array.isArray(finalRaw.nodes)) { ingestStreamingWorkflow({name: finalRaw.name || '', nodes: finalRaw.nodes, edges: finalRaw.edges || []}); + } + await drainAIBuild(); + if (!isCurrentAIBuild(build)) return false; + if (finalRaw && Array.isArray(finalRaw.nodes)) { const finalById = new Map(finalRaw.nodes.filter(n => n.id).map(n => [n.id, n])); state.workflow.nodes.forEach(node => { const fin = finalById.get(node.id); @@ -666,8 +686,7 @@ async function completeAIBuild(build, finalRaw) { }); if (finalRaw.description) state.workflow.description = finalRaw.description; } - await drainAIBuild(); - if (aiBuild !== build || build.token !== aiBuildToken) return false; + if (!await validateAIBuildRoles(build)) return false; build.ghostHidden = true; placeAIGhost(); if (!state.workflow.nodes.length) { @@ -678,6 +697,7 @@ async function completeAIBuild(build, finalRaw) { } setAIBuildStatus('整理布局…'); await aiRelayout(build); + if (!isCurrentAIBuild(build)) return false; const canvas = $('#canvas'); finishAIBuildVisuals(); canvas?.classList.add('ai-done'); @@ -688,16 +708,13 @@ async function completeAIBuild(build, finalRaw) { renderCanvas(); renderProperties(); aiOverview(); - const agentIds = new Set((state.data?.agents || []).map(a => a.id)); - const unbound = state.workflow.nodes.filter(n => n.type === 'agent' && (!n.agentId || !agentIds.has(n.agentId))); - if (unbound.length) appendOrchestratorNote(unbound.length + ' 个 Agent 节点还没绑定有效角色:' + unbound.map(n => n.name).join('、') + ',保存前在右侧属性里选一下', 'warn'); setAIBuildStatus(state.workflow.edges.length ? '节点和连线都已放好,确认后点保存' : '节点已放好,确认后点保存'); return true; } function aiRolesHint() { - const agents = catalogAgents().slice(0, 40); - if (!agents.length) return '当前项目还没有角色,请只用 approval(人工确认)和 script 节点。'; + const agents = workflowAgents().slice(0, 40); + if (!agents.length) return '当前画布没有可绑定的角色。'; return '当前项目可用角色(agentId:名称):\n' + agents.map(a => '- ' + a.id + ':' + a.name + (a.description ? '(' + String(a.description).slice(0, 40) + ')' : '')).join('\n'); } @@ -826,9 +843,9 @@ function aiOrchestratePrompt(goal, canvas, referenced) { editing ? '在当前画布上的这份 SOP 上按要求修改,重新提交完整的 workflows_save 草稿。这是增量修改:用户没点名的节点、连线、id 和脚本都保持原样,不要另起一条流程。' : '请在当前项目搭建一条新的 SOP。', - '只提交一个 workflows_save 草稿,不要发布,也不要调用其它写入工具。', - 'drafts[0].body 必须是 JSON 对象(不要序列化成字符串),字段按 name、description、nodes、edges 的顺序输出;已有节点沿用原来的 id,只有新增节点才用新 id。', - 'agent 节点的 agentId 只能从下面的已有角色里选;没有合适角色时改用 approval(人工确认)或 script 节点。', + '每轮只提交一个待确认草稿,不要发布。通常提交 workflows_save;如果目标需要尚不存在的角色,先提交该新角色的 agents_save 草稿(含 id、name、description、prompt、executorId 和指定的 model)。用户确认创建后再使用实际保存的角色 id 继续编排。', + 'drafts[0].body 必须是 JSON 对象。SOP 字段按 name、description、nodes、edges 的顺序输出;已有节点沿用原来的 id,只有新增节点才用新 id。', + 'agent 节点的 agentId 必须是当前画布能绑定的角色 id。不能用其他项目的私有角色、角色显示名或尚未保存的 id。人工确认用 approval,确定的脚本任务用 script。', '平台节点「构建静态站点」不在角色列表里:id 固定为 af-preview-build,agentId 为 af-preview-builder。复制或修改已有 SOP 时必须保留它、它的连线和 preview 字段,除非用户明确要求去掉前端预览。', 'edges 用 {"source","target","when":"success"} 按成功路径连线,可以并行分支再汇合。', aiRolesHint() @@ -846,12 +863,13 @@ async function beginAIOrchestration(goal) { const token = ++aiBuildToken; finishAIBuildVisuals(); aiBuild = { - token, buffer: '', thought: '', + token, workflowId: state.workflow.id, projectId: state.projectFilter, + selectedNode: state.selectedNode, buffer: '', thought: '', placed: new Map(state.workflow.nodes.map(node => [node.id, node])), wired: new Set((state.workflow.edges || []).map(edge => edge.source + '→' + edge.target)), pendingEdges: [], queue: [], draining: null, ghostText: '', ghostHidden: true, freePositions: false, - mode: 'edit', base: aiClone(state.workflow), spawned: 0, goal, referenced: [] + mode: 'edit', base: aiClone(state.workflow), goal, referenced: [] }; if ((state.currentView || activeViewName()) !== 'flow') switchView('flow'); openAIOrchestrator(); @@ -903,7 +921,7 @@ async function completeAIEdit(build, finalRaw) { ingestStreamingWorkflow({name: merged.name, nodes: newcomers, edges: laterEdges}); await drainAIBuild(); } - if (aiBuild !== build || build.token !== aiBuildToken) return false; + if (!isCurrentAIBuild(build) || !await validateAIBuildRoles(build)) return false; build.ghostHidden = true; placeAIGhost(); finishAIBuildVisuals(); @@ -918,14 +936,51 @@ async function completeAIEdit(build, finalRaw) { function restoreAIBuildFailure(build) { if (!build) return; - const previous = build.mode === 'edit' ? build.base : (build.spawned ? null : build.previous); - if (!previous) return; - state.workflow = previous; + state.workflow = build.mode === 'edit' ? build.base : build.previous; + state.selectedNode = build.selectedNode; renderWorkflowMeta(); renderCanvas(); renderProperties(); } +async function validateAIBuildRoles(build) { + const unavailable = () => state.workflow.nodes.filter(node => (node.type || 'agent') === 'agent' + && !(isPreviewBuildNode(node.id) && node.agentId === PREVIEW_BUILD_AGENT_ID) + && !workflowAgent(node.agentId)); + if (!unavailable().length) return true; + // A role may have been created or shared while the assistant was working. + await refreshWorkflowAgents(); + if (!isCurrentAIBuild(build)) return false; + const missing = unavailable(); + if (missing.length) { + const names = missing.map(n => (n.name || n.id) + '(' + (n.agentId || '未绑定') + ')'); + throw new Error('草稿引用了当前流程不可用的角色:' + names.join('、') + '。请先创建对应角色,或让助手使用节点库中的角色重新编排。'); + } + return true; +} + +function offerAIRoleDraft(role, project) { + const note = appendOrchestratorNote('确认创建「' + role.name + '」后,可以继续编排。'); + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'fd-btn ghost sm'; + button.textContent = '配置并创建角色'; + note.append(' ', button); + button.onclick = () => { + if (state.projectFilter !== project || catalogGeneric(state.workflow)) return toast('请在提出角色草稿的项目中创建角色'); + const {id, name, description, prompt, executorId, model} = role; + if (id && agentIdTaken(id)) return toast('这个角色标识已存在,请使用已保存的角色继续编排'); + // Reuse the create wizard and its validation. The proposal has no effect until confirmed. + openAgentWizard({id: '', name, description, prompt, executorId, model, projectId: project}); + if (id) { + state.agentIdAuto = false; + $('#agentForm').elements.id.value = id; + syncAgentSlug(); + } + setAgentCreateStep(2); + }; +} + async function readAssistantSSE(res, onEvent) { const reader = res.body.getReader(); const decoder = new TextDecoder(); @@ -970,7 +1025,7 @@ async function runAIOrchestrator() { if (!build) return; const model = selectedAIOrchestratorModel(); const previous = aiHistory[project]; - const history = previous && aiOrchestratorEngine(previous.model) === aiOrchestratorEngine(model) ? previous : {sessionId: '', messages: []}; + const sessionId = previous && aiOrchestratorEngine(previous.model) === aiOrchestratorEngine(model) ? previous.sessionId : ''; build.goal = goal; build.referenced = referenced; if (button) button.disabled = true; @@ -981,33 +1036,51 @@ async function runAIOrchestrator() { appendOrchestratorNote(goal, 'mine'); setAIBuildStatus(editing ? '正在按当前流程修改,画布先保持原样' : '正在连接 AI…'); if (!editing) placeAIGhost(); - const messages = history.messages.concat([{role: 'user', content: aiOrchestratePrompt(goal, canvas, referenced)}]); aiAbort = new AbortController(); try { + const [session] = await Promise.all([ + sessionId ? api('/api/assistant/sessions/'+encodeURIComponent(sessionId),{silent:true}) : null, + refreshWorkflowAgents() + ]); + if (!isCurrentAIBuild(build)) return; + renderWorkflowMeta(); + // Project conversations require the stored transcript, including server-stamped metadata. + const messages = [...(session?.messages || []), {role: 'user', content: aiOrchestratePrompt(goal, canvas, referenced)}]; const res = await fetch('/api/assistant/chat', { method: 'POST', headers: {'Content-Type': 'application/json', 'Accept': 'text/event-stream'}, signal: aiAbort.signal, - body: JSON.stringify({projectId: project, sessionId: history.sessionId, model, approvalMode: 'confirm', messages}) + body: JSON.stringify({projectId: project, sessionId, model, requireExactModel: !!model, approvalMode: 'confirm', messages}) }); if (!res.ok) { let msg = 'HTTP ' + res.status; try { msg = (await res.json()).error || msg; } catch {} throw new Error(msg); } - const reply = (res.headers.get('Content-Type') || '').includes('text/event-stream') ? await readAssistantSSE(res, pushAIThought) : await res.json(); - if (build.token !== aiBuildToken) return; - aiHistory[project] = {sessionId: reply.sessionId || history.sessionId, model, messages: messages.concat([{role: 'assistant', model, content: reply.message || '已提交草稿'}]).slice(-8)}; + const reply = (res.headers.get('Content-Type') || '').includes('text/event-stream') + ? await readAssistantSSE(res, event => { if (isCurrentAIBuild(build)) pushAIThought(event); }) + : await res.json(); + if (!isCurrentAIBuild(build)) return; + aiHistory[project] = {sessionId: reply.sessionId || sessionId, model}; document.querySelectorAll('.ai-live-thought.live').forEach(box => box.classList.remove('live')); if (reply.message) appendOrchestratorNote(reply.message, ''); - const draft = (reply.drafts || []).find(item => item.tool === 'workflows_save' && item.body); + const draft = (reply.drafts || []).find(item => ['workflows_save', 'agents_save'].includes(item.tool) && item.body); (draft?.warnings || []).forEach(w => appendOrchestratorNote(w, 'warn')); let body = draft?.body; if (typeof body === 'string') { try { body = JSON.parse(body); } catch { body = null; } } + if (draft?.tool === 'agents_save' && body?.name && !catalogGeneric(state.workflow)) { + aiBuild = null; + restoreAIBuildFailure(build); + finishAIBuildVisuals(); + syncCanvasAIEntry(); + setAIBuildStatus(''); + offerAIRoleDraft(body, project); + return; + } const ok = await completeAIBuild(build, body); if (!ok && build.token === aiBuildToken) setAIBuildStatus(build.mode === 'edit' ? '这轮没有改动画布,当前流程还在' : '这轮没有生成可放置的 SOP,可以换个说法再试'); } catch (error) { - if (build.token !== aiBuildToken) return; + if (!isCurrentAIBuild(build)) return; restoreAIBuildFailure(build); finishAIBuildVisuals(); aiBuild = null; @@ -1018,6 +1091,12 @@ async function runAIOrchestrator() { toast(error.message); } } finally { + if (aiBuild === build) { + aiBuild = null; + finishAIBuildVisuals(); + syncCanvasAIEntry(); + setAIBuildStatus(''); + } if (button) button.disabled = false; modelToggles.forEach(toggle => { toggle.disabled = false; }); aiAbort = null; @@ -1033,9 +1112,19 @@ async function playWorkflowOnCanvas(raw, opts = {}) { } const build = await startAIBuild(raw || {}, {confirmed: opts.confirmed, ghost: 'AI 正在放置节点…'}); if (!build) return false; - const ok = await completeAIBuild(build, raw); - if (ok && opts.source === 'assistant') toast('AI 已在画布上逐个放好节点'); - return ok; + try { + const ok = await completeAIBuild(build, raw); + if (ok && opts.source === 'assistant') toast('AI 已在画布上逐个放好节点'); + return ok; + } catch (error) { + if (isCurrentAIBuild(build)) { + aiBuild = null; + restoreAIBuildFailure(build); + finishAIBuildVisuals(); + toast(error.message); + } + return false; + } } bindOrchestrator(); diff --git a/web/orchestrate_models_test.js b/web/orchestrate_models_test.js index bcb0178b..69a226c9 100644 --- a/web/orchestrate_models_test.js +++ b/web/orchestrate_models_test.js @@ -8,6 +8,7 @@ const html = fs.readFileSync('index.html', 'utf8'); dom.html(html.slice(html.indexOf('