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: is provenance the server writes when a generic template is
+// adopted (domain.GenericSourceTagPrefix), not a user label: editors only show and replace
+// the user's tags and always carry the marker along.
+const GENERIC_SOURCE_TAG='generic-source:';
+function isGenericSourceTag(tag){return String(tag||'').startsWith(GENERIC_SOURCE_TAG)}
+function workflowGenericSource(w){const tag=(w?.tags||[]).find(isGenericSourceTag);return tag?String(tag).slice(GENERIC_SOURCE_TAG.length):''}
+function workflowUserTags(tags){return (tags||[]).filter(tag=>!isGenericSourceTag(tag))}
+function withGenericSourceTags(userTags,current){return [...workflowUserTags(userTags),...(current||[]).filter(isGenericSourceTag)]}
function renderCatalogScopes(){
const workflows=state.data?.workflows||[],agents=state.data?.agents||[];
const sopProject=workflows.filter(w=>!catalogGeneric(w)&&catalogOwned(w.projectId)).length;
@@ -89,7 +97,7 @@ function genericRequirementChips(w){
function sopResourceRequirements(w){
const project=(state.data?.projects||[]).find(p=>p.id===(w?.projectId||state.projectFilter))||(state.data?.projects||[]).find(p=>p.id===state.projectFilter);
const driver=((state.data?.sandboxes||[]).find(sb=>sb.id===w?.sandboxProfileId)||{}).driver||(/docker/i.test(w?.sandboxProfileId||'')?'docker':'');
- const usesRepo=(catalogGeneric(w)||(w?.tags||[]).some(t=>String(t).startsWith('generic-source:')))&&!!project?.defaultRepositoryId;
+ const usesRepo=(catalogGeneric(w)||!!workflowGenericSource(w))&&!!project?.defaultRepositoryId;
const rows=[];
if(usesRepo)rows.push({key:'run-repo',label:'GitHub 仓库(已绑定)',ok:true,hint:'使用项目已绑定的仓库。访问私有仓库或推送代码时需要在个人配置中配置 GitHub Token;未绑定仓库时可在任务工作区直接运行。'});
if(w?.autoSelectSandbox)rows.push({key:'run-sandbox',label:'由 Agent 选择沙箱',ok:true,hint:'启动时按项目和任务选择运行沙箱。'});
@@ -99,7 +107,7 @@ function sopResourceRequirements(w){
function sopRunRequirements(w){
const nodes=w?.nodes||[],user=userById(state.currentUser?.id)||{};
const resources=sopResourceRequirements(w);
- if(catalogGeneric(w)||(w?.tags||[]).some(tag=>tag.startsWith('generic-source:')))return resources;
+ if(catalogGeneric(w)||workflowGenericSource(w))return resources;
const rows=[];
const executorIds=nodes.filter(n=>n.type==='agent'&&!isPreviewBuildNode(n.id)).map(node=>{
const role=(state.data?.agents||[]).find(a=>a.id===node.agentId);
@@ -165,14 +173,14 @@ function sharedSOPCard(w,m={},liveCount=0){
const meta=[w.owner,workflowVersionLabel(w)].filter(Boolean).join(' · ');
return `${sopRunCardBody(w,m,liveCount)}`;
}
-function genericProjectCopy(w){return (state.data?.workflows||[]).find(x=>!catalogGeneric(x)&&x.projectId===state.projectFilter&&(x.tags||[]).includes(`generic-source:${w.id}`))}
+function genericProjectCopy(w){return (state.data?.workflows||[]).find(x=>!catalogGeneric(x)&&x.projectId===state.projectFilter&&workflowGenericSource(x)===w.id)}
function genericSOPCard(w){
const nodes=w.nodes||[],agentCount=nodes.filter(n=>n.type==='agent').length,gates=nodes.filter(n=>n.type==='approval').length;
const copy=genericProjectCopy(w);
const primary=copy
?sopCardPrimary('data-open-sop',copy.id,'查看项目副本','eye')
:sopCardPrimary('data-adopt-generic',w.id,'复制到本项目','copy','复制后归本项目所有、可自由修改,不再跟随平台更新');
- const tags=(w.tags||[]).filter(t=>!t.startsWith('generic-source:')).join(' · ')||'通用模板';
+ const tags=workflowUserTags(w.tags).join(' · ')||'通用模板';
return `${sopCardHead(sopStatusBadge(w),'平台维护 · 与项目无关',sopBadge(`v${w.version||1}`,'neutral',''))}${sopCardTitle(w)}${escapeHTML(w.description||'平台提供的通用流程模板')}
${sopRunRequirementChips(w)}${genericRequirementChips(w)}${nodes.length}节点${agentCount}角色节点${gates}人工门禁v${w.version||1}版本
`;
}
function sopCatalogCard(w,metrics,live){
diff --git a/web/index.html b/web/index.html
index 1b1ddc193..704b3f5d6 100644
--- a/web/index.html
+++ b/web/index.html
@@ -1421,7 +1421,7 @@ 确认操作
-
+
@@ -1446,7 +1446,7 @@ 确认操作
-
+
diff --git a/webtest/tests/issue-dispatch-lane.test.mjs b/webtest/tests/issue-dispatch-lane.test.mjs
new file mode 100644
index 000000000..28e308ce3
--- /dev/null
+++ b/webtest/tests/issue-dispatch-lane.test.mjs
@@ -0,0 +1,84 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { loadApp, settle } from '../lib/load-app.mjs';
+
+// The server accepts `rerun` only for a LOOP lane that has already run on the requirement.
+// Every dispatch entry (issue modal, list trigger, drawer retrigger) must decide
+// "first run vs rerun" for the LOOP being started, not for the requirement as a whole.
+async function setup(t) {
+ const app = await loadApp();
+ t.after(app.close);
+ app.evaluate(`
+ var base=state.data.workflows[0];
+ state.data.workflows=[base,{...base,id:'flow-2',name:'Fix Flow'}];
+ var lane={id:'issue-1',projectId:'project-1',number:7,kind:'requirement',source:'local',status:'blocked',title:'Lane switch',workflowId:'flow-1',repositoryIds:['repo-1']};
+ state.data.issues=[lane];
+ state.data.tasks=[
+ {id:'task-old',issueId:'issue-1',workflowId:'flow-1',runId:'run-old',status:'succeeded',createdAt:'2026-10-20T10:00:00Z'},
+ {id:'task-new',issueId:'issue-1',workflowId:'flow-1',runId:'run-new',status:'failed',createdAt:'2026-10-21T10:00:00Z'}];
+ state.data.runs=[];
+ `);
+ // Background refreshes after a dispatch must see the same history.
+ const tasks = JSON.parse(app.evaluate(`JSON.stringify(state.data.tasks)`));
+ const issues = JSON.parse(app.evaluate(`JSON.stringify(state.data.issues)`));
+ app.router.get('/api/tasks', () => tasks);
+ app.router.get('/api/issues', () => issues);
+ app.router.get('/api/runs', () => []);
+ app.router.put('/api/issues', (call) => ({ status: 200, body: call.body }));
+ app.router.post('/api/issues/issue-1/dispatch', (call) => ({ status: 201, body: { id: 'task-x', issueId: 'issue-1', workflowId: call.body.workflowId, status: 'running' } }));
+ return app;
+}
+const dispatches = (app) => app.router.calls.filter((c) => c.method === 'POST' && c.path === '/api/issues/issue-1/dispatch');
+const confirmOpen = (app) => app.document.querySelector('#confirmModal')?.classList.contains('open');
+
+test('lane task helper returns the newest task of that LOOP only', async (t) => {
+ const app = await setup(t);
+ const out = JSON.parse(app.evaluate(`JSON.stringify({
+ same:latestIssueLaneTask(state.data.issues[0],'flow-1')?.id,
+ other:latestIssueLaneTask(state.data.issues[0],'flow-2'),
+ blank:latestIssueLaneTask(state.data.issues[0],''),
+ any:latestIssueTask(state.data.issues[0])?.id})`));
+ assert.deepEqual(out, { same: 'task-new', other: null, blank: null, any: 'task-new' });
+});
+
+test('issue modal: switching to a LOOP that never ran starts it as a first run', async (t) => {
+ const app = await setup(t);
+ app.evaluate(`openIssue(state.data.issues[0])`);
+ const form = app.document.querySelector('#issueForm');
+ assert.ok([...form.elements.workflowId.options].some((o) => o.value === 'flow-2'));
+ form.elements.workflowId.value = 'flow-2';
+ app.document.querySelector('#dispatchIssue').click();
+ await settle(6);
+ assert.equal(confirmOpen(app), false, 'a new LOOP lane needs no rerun confirmation');
+ const [call] = dispatches(app);
+ assert.ok(call, 'dispatch was sent');
+ assert.deepEqual(call.body, { rerun: false, workflowId: 'flow-2' });
+});
+
+test('issue modal: starting the LOOP that already ran asks first and sends rerun', async (t) => {
+ const app = await setup(t);
+ app.evaluate(`openIssue(state.data.issues[0])`);
+ app.document.querySelector('#dispatchIssue').click();
+ await settle(4);
+ assert.equal(confirmOpen(app), true);
+ assert.match(app.document.querySelector('#confirmModal').textContent, /已经处理过/);
+ assert.equal(dispatches(app).length, 0, 'nothing is sent before confirming');
+ app.document.querySelector('#confirmOkBtn').click();
+ await settle(6);
+ const [call] = dispatches(app);
+ assert.deepEqual(call.body, { rerun: true, workflowId: 'flow-1' });
+});
+
+test('list trigger and drawer retrigger keep deciding rerun per lane', async (t) => {
+ const app = await setup(t);
+ await app.evaluate(`triggerIssue('issue-1','flow-2')`);
+ await settle(6);
+ assert.deepEqual(dispatches(app).at(-1).body, { rerun: false, workflowId: 'flow-2' });
+
+ const retrigger = app.evaluate(`retriggerIssue('issue-1','flow-1')`);
+ await settle(4);
+ app.document.querySelector('#confirmOkBtn').click();
+ await retrigger;
+ await settle(6);
+ assert.deepEqual(dispatches(app).at(-1).body, { rerun: true, workflowId: 'flow-1' });
+});
diff --git a/webtest/tests/loop-generic-source.test.mjs b/webtest/tests/loop-generic-source.test.mjs
new file mode 100644
index 000000000..fd976f705
--- /dev/null
+++ b/webtest/tests/loop-generic-source.test.mjs
@@ -0,0 +1,65 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { loadApp, settle } from '../lib/load-app.mjs';
+
+// `generic-source:` is the provenance the server writes when a generic
+// template is adopted. It decides whether copied roles follow the responsible
+// user's default CLI, so user tag edits must never drop it.
+const MARKER = 'generic-source:tpl-backend';
+
+function withTemplate(app) {
+ app.evaluate(`
+ state.data.sandboxes=[{id:'project-native',name:'Native',projectId:'project-1',driver:'native'}];
+ state.data.workflows=[{id:'tpl-backend',name:'Backend template',generic:true,tags:['public'],nodes:[],edges:[]}];
+ `);
+}
+
+test('wizard keeps the adoption marker when the user enters tags', async (t) => {
+ const app = await loadApp();
+ t.after(app.close);
+ withTemplate(app);
+ app.router.post('/api/workflows/tpl-backend/clone', (call) => ({
+ status: 201, body: { id: call.body.id, name: call.body.name, projectId: 'project-1', revision: 1, status: 'draft', sandboxProfileId: 'project-native', tags: ['public', MARKER], nodes: [], edges: [] },
+ }));
+ app.router.put('/api/workflows', (call) => ({ status: 200, body: { ...call.body, revision: 2 } }));
+ app.evaluate(`openSOPWizard()`);
+ const form = app.document.querySelector('#sopCreateForm');
+ form.elements.name.value = 'Tagged copy';
+ form.elements.tags.value = '走查, 后端';
+ app.evaluate(`state.sopTemplate='tpl-backend';setSOPWizardStep(2)`);
+ app.document.querySelector('#sopCreateSandbox').value = 'project-native';
+ await app.evaluate('createSOPFromWizard').call(null, { preventDefault() {}, currentTarget: form });
+ await settle(2);
+ const put = app.router.calls.find((c) => c.path === '/api/workflows' && c.method === 'PUT');
+ assert.ok(put, 'the wizard saved the entered tags');
+ assert.deepEqual(put.body.tags, ['走查', '后端', MARKER]);
+});
+
+test('designer tag field hides the marker and keeps it on edit', async (t) => {
+ const app = await loadApp();
+ t.after(app.close);
+ app.evaluate(`state.workflow={id:'copy',name:'Copy',projectId:'project-1',status:'draft',tags:['public','${MARKER}'],nodes:[],edges:[]};renderWorkflowMeta()`);
+ const input = app.document.querySelector('#workflowTags');
+ assert.equal(input.value, 'public');
+ input.value = '';
+ input.dispatchEvent(new app.window.Event('input', { bubbles: true }));
+ assert.deepEqual(JSON.parse(app.evaluate(`JSON.stringify(state.workflow.tags)`)), [MARKER]);
+ input.value = '前端, 回归';
+ input.dispatchEvent(new app.window.Event('input', { bubbles: true }));
+ assert.deepEqual(JSON.parse(app.evaluate(`JSON.stringify(state.workflow.tags)`)), ['前端', '回归', MARKER]);
+ // Typing a marker by hand is ignored: provenance only comes from adoption.
+ input.value = 'x, generic-source:other';
+ input.dispatchEvent(new app.window.Event('input', { bubbles: true }));
+ assert.deepEqual(JSON.parse(app.evaluate(`JSON.stringify(state.workflow.tags)`)), ['x', MARKER]);
+});
+
+test('catalog reads provenance through one helper', async (t) => {
+ const app = await loadApp();
+ t.after(app.close);
+ const out = JSON.parse(app.evaluate(`JSON.stringify({
+ source:workflowGenericSource({tags:['a','${MARKER}']}),
+ none:workflowGenericSource({tags:['a']}),
+ user:workflowUserTags(['a','${MARKER}','b']),
+ })`));
+ assert.deepEqual(out, { source: 'tpl-backend', none: '', user: ['a', 'b'] });
+});