diff --git a/internal/domain/workflow.go b/internal/domain/workflow.go index 4a03e4559..7111cb65f 100644 --- a/internal/domain/workflow.go +++ b/internal/domain/workflow.go @@ -195,6 +195,34 @@ type WorkflowDefinition struct { ExecutorDefaults map[string]AssistantDefaults `json:"executorDefaults,omitempty"` } +// GenericSourceTagPrefix marks a project LOOP adopted from a built-in generic +// template; the suffix is the template id. The server writes it on adoption +// and reads it to let the copied template roles follow the responsible user's +// default executor, so it is provenance, not a user label. +const GenericSourceTagPrefix = "generic-source:" + +// GenericSource returns the template id this LOOP was adopted from, if any. +func (wf WorkflowDefinition) GenericSource() string { + for _, tag := range wf.Tags { + if id, found := strings.CutPrefix(tag, GenericSourceTagPrefix); found && strings.TrimSpace(id) != "" { + return id + } + } + return "" +} + +// KeepGenericSource carries the stored provenance tag over to an edit whose +// tags no longer include one: editors replace the free-form tag list, and +// dropping the marker would silently switch every copied role to its pinned +// CLI instead of the responsible user's default. +func (wf *WorkflowDefinition) KeepGenericSource(previous WorkflowDefinition) { + source := previous.GenericSource() + if source == "" || wf.GenericSource() != "" { + return + } + wf.Tags = append(append([]string(nil), wf.Tags...), GenericSourceTagPrefix+source) +} + // UnmarshalJSON migrates the pre-workflow-sandbox shape while the legacy node // field is still visible. Conflicting node profiles cannot describe one shared // workflow sandbox and are rejected instead of being silently guessed. diff --git a/internal/domain/workflow_test.go b/internal/domain/workflow_test.go new file mode 100644 index 000000000..25f9da87b --- /dev/null +++ b/internal/domain/workflow_test.go @@ -0,0 +1,22 @@ +package domain + +import "testing" + +func TestKeepGenericSourceCarriesOnlyAMissingMarker(t *testing.T) { + previous := WorkflowDefinition{Tags: []string{"public", GenericSourceTagPrefix + "tpl"}} + edited := WorkflowDefinition{Tags: []string{"mine"}} + edited.KeepGenericSource(previous) + if got := edited.GenericSource(); got != "tpl" || len(edited.Tags) != 2 || edited.Tags[0] != "mine" { + t.Fatalf("tags = %v source = %q", edited.Tags, got) + } + retagged := WorkflowDefinition{Tags: []string{GenericSourceTagPrefix + "other"}} + retagged.KeepGenericSource(previous) + if len(retagged.Tags) != 1 || retagged.GenericSource() != "other" { + t.Fatalf("an explicit marker must win: %v", retagged.Tags) + } + untouched := WorkflowDefinition{Tags: []string{"a"}} + untouched.KeepGenericSource(WorkflowDefinition{Tags: []string{"b", GenericSourceTagPrefix}}) + if len(untouched.Tags) != 1 || untouched.GenericSource() != "" { + t.Fatalf("no provenance to keep: %v", untouched.Tags) + } +} diff --git a/internal/engine/sop_executors.go b/internal/engine/sop_executors.go index e37ae74ea..fddbd3f7d 100644 --- a/internal/engine/sop_executors.go +++ b/internal/engine/sop_executors.go @@ -200,13 +200,7 @@ func (a sopExecutorAccess) firstSavedModel(kind string) string { func templateSOPRoleIDs(st *repo.Store, wf domain.WorkflowDefinition) map[string]bool { source := wf.ID if !wf.Generic { - source = "" - for _, tag := range wf.Tags { - if id, found := strings.CutPrefix(tag, "generic-source:"); found { - source = id - break - } - } + source = wf.GenericSource() } template, ok := st.GenericTemplateByWorkflow(source) if !ok { diff --git a/internal/httpapi/catalog.go b/internal/httpapi/catalog.go index 2150cff4d..d14c4b569 100644 --- a/internal/httpapi/catalog.go +++ b/internal/httpapi/catalog.go @@ -1034,6 +1034,7 @@ func (h *catalogHandlers) workflows(c *gin.Context) { previousProjectID := "" if previous, exists := h.repo.Workflow(v.ID); exists { previousProjectID = previous.ProjectID + v.KeepGenericSource(previous) if (needsNotificationAccess || len(previous.Notifications) > 0) && !h.notifications.access(c, previous.ProjectID, true) { return } diff --git a/internal/httpapi/generic_workflows.go b/internal/httpapi/generic_workflows.go index 223a72638..5bf24ef80 100644 --- a/internal/httpapi/generic_workflows.go +++ b/internal/httpapi/generic_workflows.go @@ -37,7 +37,7 @@ func (h *catalogHandlers) adoptGenericWorkflow(template domain.WorkflowDefinitio // shared built-in catalog. adopted.Nodes = append([]domain.WorkflowNode(nil), template.Nodes...) adopted.Edges = append([]domain.WorkflowEdge(nil), template.Edges...) - adopted.Tags = append(append([]string(nil), template.Tags...), "generic-source:"+template.ID) + adopted.Tags = append(append([]string(nil), template.Tags...), domain.GenericSourceTagPrefix+template.ID) adopted.Requirements = append([]domain.WorkflowRequirement(nil), template.Requirements...) adopted.ID, adopted.Name, adopted.Owner = id, name, owner adopted.ProjectID = projectID diff --git a/internal/httpapi/generic_workflows_test.go b/internal/httpapi/generic_workflows_test.go index 8fb8cde90..cbf0146e9 100644 --- a/internal/httpapi/generic_workflows_test.go +++ b/internal/httpapi/generic_workflows_test.go @@ -4,6 +4,7 @@ import ( "net/http" "net/http/httptest" "path/filepath" + "slices" "testing" "time" @@ -810,3 +811,47 @@ func TestProductAndFrontendGenericTemplatesAreListed(t *testing.T) { } } } + +// Editors replace the free-form tag list (the 新建 LOOP wizard with custom tags, +// the designer's tag field). The adoption marker must survive those saves, or +// the copied template roles stop following the responsible user's default CLI. +func TestAdoptedCopyKeepsGenericSourceWhenTagsAreEdited(t *testing.T) { + h, _ := newGenericTemplateServer(t) + marker := "generic-source:" + repo.GenericBackendDeliveryWorkflowID + adopted := requestJSON[domain.WorkflowDefinition](t, h, http.MethodPost, + "/api/workflows/"+repo.GenericBackendDeliveryWorkflowID+"/clone", + map[string]any{"id": "alpha-tagged", "name": "带标签副本", "projectId": "alpha"}, + http.StatusCreated) + if !slices.Contains(adopted.Tags, marker) { + t.Fatalf("adoption must record its template: %v", adopted.Tags) + } + edited := adopted + edited.Tags = []string{"走查", "后端"} + saved := requestJSON[domain.WorkflowDefinition](t, h, http.MethodPut, "/api/workflows", edited, http.StatusOK) + if !slices.Contains(saved.Tags, marker) { + t.Fatalf("user tags dropped the adoption marker: %v", saved.Tags) + } + want := []string{"走查", "后端", marker} + if len(saved.Tags) != len(want) { + t.Fatalf("tags = %v, want %v", saved.Tags, want) + } + for i := range want { + if saved.Tags[i] != want[i] { + t.Fatalf("tags = %v, want %v", saved.Tags, want) + } + } + // Clearing every tag keeps only the marker; a LOOP that was never adopted gets none. + saved.Tags = nil + cleared := requestJSON[domain.WorkflowDefinition](t, h, http.MethodPut, "/api/workflows", saved, http.StatusOK) + if len(cleared.Tags) != 1 || cleared.Tags[0] != marker { + t.Fatalf("cleared tags = %v", cleared.Tags) + } + plain := requestJSON[domain.WorkflowDefinition](t, h, http.MethodPut, "/api/workflows", domain.WorkflowDefinition{ + ID: "alpha-plain", Name: "plain", ProjectID: "alpha", SandboxProfileID: "test-native", Tags: []string{"x"}, + }, http.StatusOK) + plain.Tags = []string{"y"} + plain = requestJSON[domain.WorkflowDefinition](t, h, http.MethodPut, "/api/workflows", plain, http.StatusOK) + if len(plain.Tags) != 1 || plain.Tags[0] != "y" { + t.Fatalf("plain LOOP tags = %v", plain.Tags) + } +} diff --git a/web/app.js b/web/app.js index 9498b27f0..327fba4d3 100644 --- a/web/app.js +++ b/web/app.js @@ -1085,7 +1085,7 @@ function bind(){ $('#workflowOwner').oninput=e=>{if(!state.workflow)return;state.workflow.owner=e.target.value;dirty()}; $('#workflowSandbox').onchange=e=>{if(!state.workflow)return;setSOPSandboxChoice(state.workflow,e.target.value);dirty()}; $('#workflowStatus').onchange=e=>{if(!state.workflow)return;state.workflow.status=e.target.value;dirty()}; - $('#workflowTags').oninput=e=>{if(!state.workflow)return;state.workflow.tags=e.target.value.split(',').map(x=>x.trim()).filter(Boolean);dirty()}; + $('#workflowTags').oninput=e=>{if(!state.workflow)return;state.workflow.tags=withGenericSourceTags(e.target.value.split(',').map(x=>x.trim()).filter(Boolean),state.workflow.tags);dirty()}; $('#workflowMetricCategory').onchange=e=>{if(!state.workflow)return;state.workflow.metricCategory=e.target.value;dirty()}; $('#workflowSOPLane').onchange=e=>{if(!state.workflow)return;state.workflow.sopLane=e.target.value;dirty()}; $('#workflowDescription').oninput=e=>{if(!state.workflow)return;state.workflow.description=e.target.value;dirty()}; diff --git a/web/app/flows.js b/web/app/flows.js index 1c6465809..afe143772 100644 --- a/web/app/flows.js +++ b/web/app/flows.js @@ -180,7 +180,7 @@ function renderWorkflowMeta(){ normalizeWorkflowNotifications(wf); const notificationHost=$('#workflowNotificationEditor');if(notificationHost)mountNotificationEditor(notificationHost,wf.notifications,{sourceType:'run',kind:'sop',projectId:wf.projectId||state.projectFilter},()=>dirty()); $('#workflowName').value=wf.name;$('#workflowDescription').value=wf.description||''; - $('#workflowOwner').value=wf.owner||'';$('#workflowStatus').value=wf.status||'draft';$('#workflowTags').value=(wf.tags||[]).join(', ');$('#workflowMetricCategory').value=wf.metricCategory||'';$('#workflowSOPLane').value=wf.sopLane||''; + $('#workflowOwner').value=wf.owner||'';$('#workflowStatus').value=wf.status||'draft';$('#workflowTags').value=workflowUserTags(wf.tags).join(', ');$('#workflowMetricCategory').value=wf.metricCategory||'';$('#workflowSOPLane').value=wf.sopLane||''; const previewOn=!!wf.preview?.enabled, hasPreviewNode=(wf.nodes||[]).some(n=>isPreviewBuildNode(n.id)); if(previewOn!==hasPreviewNode)syncPreviewBuildGraph(); const sandboxSelect=$('#workflowSandbox'); @@ -1018,7 +1018,7 @@ function agentBindCard(n){ if(!agent)return `

${hint}

先选一个已定义的角色。画布只编排顺序和打回,不改编排角色内部的任务。

`; const arts=effectiveNodeArtifacts(n,agent),gates=roleGates(agent); const duty=String(agent.description||'').trim(),taskHint=duty?(duty.length>48?`${duty.slice(0,48)}…`:duty):'还没写职责,可在角色定义里补'; - const source=(state.workflow?.tags||[]).find(tag=>tag.startsWith('generic-source:'))?.slice('generic-source:'.length); + const source=workflowGenericSource(state.workflow); const template=(state.data.workflows||[]).find(w=>w.id===source&&catalogGeneric(w)); const fromTemplate=generic||template?.nodes?.some(node=>node.agentId&&(node.agentId===agent.id||`${node.agentId}-${projectId}`===agent.id)); const legacyTemplate=fromTemplate&&(agent.projectId||'')===(state.workflow?.projectId||'')&&agent.executorId==='codebuddy'; @@ -1303,7 +1303,7 @@ async function createSOPFromWizard(e){ const request={id:uid('sop'),name,owner,projectId:state.projectFilter}; setSOPSandboxChoice(request,sandboxId); saved=await api(`/api/workflows/${encodeURIComponent(template.id)}/clone`,{method:'POST',body:JSON.stringify(request)}); - if(description||owner||tags.length)saved=await api('/api/workflows',{method:'PUT',body:JSON.stringify({...saved,name,description:description||saved.description,owner:owner||saved.owner,tags:tags.length?tags:saved.tags})}); + if(description||owner||tags.length)saved=await api('/api/workflows',{method:'PUT',body:JSON.stringify({...saved,name,description:description||saved.description,owner:owner||saved.owner,tags:tags.length?withGenericSourceTags(tags,saved.tags):saved.tags})}); }else{ const workflow=template?clone(template):{nodes:[],edges:[]}; Object.assign(workflow,{id:uid('sop'),name,description,owner,tags,status:'draft',version:1,revision:0,projectId:state.projectFilter||'',shared:false}); diff --git a/web/app/issue-model.js b/web/app/issue-model.js index 4e752fabc..0b2bba08f 100644 --- a/web/app/issue-model.js +++ b/web/app/issue-model.js @@ -44,14 +44,21 @@ function bindIssueDeletionContext(root){ }); } const issueStatuses=[['backlog','Backlog'],['todo','Todo'],['in_progress','In progress'],['in_review','In review'],['done','Done'],['closed','Closed'],['blocked','Blocked'],['cancelled','Cancelled']]; +function newestTask(tasks){ + return [...tasks].sort((a,b)=>new Date(b.createdAt||0)-new Date(a.createdAt||0)||String(b.id).localeCompare(String(a.id)))[0]||null; +} function latestIssueTask(i){ const tasks=(state.data.tasks||[]).filter(t=>t.issueId===i.id); - if(tasks.length){ - tasks.sort((a,b)=>new Date(b.createdAt||0)-new Date(a.createdAt||0)||String(b.id).localeCompare(String(a.id))); - return tasks[0]; - } + if(tasks.length)return newestTask(tasks); return (state.data.tasks||[]).find(x=>x.id===i.latestTaskId)||null; } +// Newest task of one LOOP lane. The server accepts rerun only for a lane that has already +// run, so every dispatch entry decides "first run vs rerun" per lane, not per requirement. +function latestIssueLaneTask(i,workflowId){ + const id=String(workflowId||'').trim(); + if(!i?.id||!id)return null; + return newestTask((state.data.tasks||[]).filter(t=>t.issueId===i.id&&t.workflowId===id)); +} function latestIssueRun(i, task){ const runs=state.data.runs||[]; if(task){ diff --git a/web/app/issues.js b/web/app/issues.js index 00c7bef2e..ffa4f794a 100644 --- a/web/app/issues.js +++ b/web/app/issues.js @@ -697,7 +697,7 @@ async function persistIssue(issue){ return saved; } async function saveIssue(e){e.preventDefault();const button=e.currentTarget.querySelector('button[type="submit"]');try{button.disabled=true;button.textContent='正在保存…';const saved=await persistIssue(issueFromForm());state.selectedIssue=saved.id;$('#issueModal').classList.remove('open');renderIssues();toast('需求已保存')}catch(err){toast(err.message)}finally{button.disabled=false;button.textContent='保存'}} -async function dispatchIssue(){try{let issue=issueFromForm();const blocked=issueExecutionBlocked(issue);if(blocked)return toast(blocked);const current=latestIssueTask(issue),rerun=!!current;if(current&&!await afConfirm({title:'重新运行确认',message:['queued','dispatched','running'].includes(current.status)?'该需求已有进行中的任务,确定额外发起一次重新运行吗?':'该需求已经处理过,确定整条 LOOP 重新运行吗?',confirmText:'确认重新运行'}))return;const button=$('#dispatchIssue');button.disabled=true;button.textContent='正在调度…';issue=await persistIssue(issue);button.textContent=sopSandboxPendingText(issue.workflowId||defaultSOPForIssue(issue))||'正在调度…';const task=await api(`/api/issues/${issue.id}/dispatch`,{method:'POST',body:JSON.stringify({rerun,workflowId:issue.workflowId||''})});issue.latestTaskId=task.id;issue.status='in_progress';const idx=state.data.issues.findIndex(i=>i.id===issue.id);if(idx>=0)state.data.issues[idx]=issue;if(!state.data.tasks)state.data.tasks=[];const existingTaskIdx=state.data.tasks.findIndex(t=>t.id===task.id);if(existingTaskIdx>=0)state.data.tasks[existingTaskIdx]=task;else state.data.tasks.unshift(task);if(task.runId){startLiveRun(task.runId);try{const run=await api(`/api/runs/${encodeURIComponent(task.runId)}`,{silent:true});if(run?.id){if(!state.data.runs)state.data.runs=[];const rIdx=state.data.runs.findIndex(r=>r.id===run.id);if(rIdx>=0)state.data.runs[rIdx]={...state.data.runs[rIdx],...run};else state.data.runs=sortRunsDescending([run,...state.data.runs]);}}catch(e){}}$('#issueModal').classList.remove('open');renderIssues();await openIssueDetail(issue.id,'sop');toast(rerun?'已创建重新运行':'已创建执行任务并启动工作流','ok');Promise.all([refreshIssues(),refreshRuns(true)]).catch(()=>{});}catch(err){toast(err.message)}finally{const button=$('#dispatchIssue');button.disabled=false;button.textContent='启动 LOOP'}} +async function dispatchIssue(){try{let issue=issueFromForm();const blocked=issueExecutionBlocked(issue);if(blocked)return toast(blocked);const current=latestIssueLaneTask(issue,issue.workflowId),rerun=!!current;if(current&&!await afConfirm({title:'重新运行确认',message:['queued','dispatched','running'].includes(current.status)?'该需求已有进行中的任务,确定额外发起一次重新运行吗?':'该需求已经处理过,确定整条 LOOP 重新运行吗?',confirmText:'确认重新运行'}))return;const button=$('#dispatchIssue');button.disabled=true;button.textContent='正在调度…';issue=await persistIssue(issue);button.textContent=sopSandboxPendingText(issue.workflowId||defaultSOPForIssue(issue))||'正在调度…';const task=await api(`/api/issues/${issue.id}/dispatch`,{method:'POST',body:JSON.stringify({rerun,workflowId:issue.workflowId||''})});issue.latestTaskId=task.id;issue.status='in_progress';const idx=state.data.issues.findIndex(i=>i.id===issue.id);if(idx>=0)state.data.issues[idx]=issue;if(!state.data.tasks)state.data.tasks=[];const existingTaskIdx=state.data.tasks.findIndex(t=>t.id===task.id);if(existingTaskIdx>=0)state.data.tasks[existingTaskIdx]=task;else state.data.tasks.unshift(task);if(task.runId){startLiveRun(task.runId);try{const run=await api(`/api/runs/${encodeURIComponent(task.runId)}`,{silent:true});if(run?.id){if(!state.data.runs)state.data.runs=[];const rIdx=state.data.runs.findIndex(r=>r.id===run.id);if(rIdx>=0)state.data.runs[rIdx]={...state.data.runs[rIdx],...run};else state.data.runs=sortRunsDescending([run,...state.data.runs]);}}catch(e){}}$('#issueModal').classList.remove('open');renderIssues();await openIssueDetail(issue.id,'sop');toast(rerun?'已创建重新运行':'已创建执行任务并启动工作流','ok');Promise.all([refreshIssues(),refreshRuns(true)]).catch(()=>{});}catch(err){toast(err.message)}finally{const button=$('#dispatchIssue');button.disabled=false;button.textContent='启动 LOOP'}} async function dispatchIssueById(issueId,rerun=false,workflowId=''){try{const issue=(state.data.issues||[]).find(i=>i.id===issueId),blocked=issueExecutionBlocked(issue);if(blocked)return toast(blocked);if(clarificationNeedsConfirm(issue)){openIssueDetail(issueId,'clarify');return toast('请先确认澄清结论后再触发 LOOP')} const sandboxStatus=sopSandboxPendingText(workflowId||issue?.workflowId||defaultSOPForIssue(issue)); const dismiss=sandboxStatus?toast(sandboxStatus,'info',0):null; @@ -755,7 +755,7 @@ async function triggerIssue(issueId,workflowId){ const blocked=issueExecutionBlocked(issue);if(blocked)return toast(blocked); if(issueWithoutSOP(issue)&&!String(workflowId||'').trim()){openIssueDetail(issueId,'sop');return toast('这条需求不使用 LOOP,请先选择要运行的 LOOP')} const targetWorkflow=String(workflowId||'').trim()||issue.workflowId||defaultSOPForIssue(issue); - const laneTask=(state.data.tasks||[]).find(t=>t.issueId===issue.id&&t.workflowId===targetWorkflow); + const laneTask=latestIssueLaneTask(issue,targetWorkflow); const latestRun=laneTask?latestIssueRun(issue,laneTask):null; if(laneTask&&['queued','dispatched','running'].includes(laneTask.status)&&!await afConfirm({title:'发起新运行确认',message:'这条 LOOP 已有进行中的任务,确定再次发起一个新运行吗?',confirmText:'确认发起'}))return; if(['failed','cancelled','succeeded'].includes(latestRun?.status)&&!await afConfirm({title:'触发整条 LOOP 确认',message:'「触发」会把这条 LOOP 从头再跑,已完成的步骤也会重做。要从失败节点继续请用「重试」。确定触发?',confirmText:'确认触发'}))return; @@ -823,7 +823,7 @@ async function retriggerIssue(issueId,workflowId){ if(deliveryLocked(target))target=await reopenDeliveredIssueSilent(target.id); const wf=String(workflowId||'').trim()||target.workflowId||defaultSOPForIssue(target); if(!String(target.workflowId||'').trim())target=await persistIssue({...target,workflowId:wf}); - const ran=!!(state.data.tasks||[]).some(t=>t.issueId===target.id&&t.workflowId===wf); + const ran=!!latestIssueLaneTask(target,wf); await dispatchIssueById(target.id,ran,wf); }catch(err){toast(err.message)} } diff --git a/web/app/sops.js b/web/app/sops.js index 6f725f598..45154b31b 100644 --- a/web/app/sops.js +++ b/web/app/sops.js @@ -1,3 +1,11 @@ +// generic-source: