From 30688b3531a78d610c48ca15d1a48333a5dd7183 Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 28 Nov 2026 03:06:52 +0000 Subject: [PATCH 1/2] =?UTF-8?q?fix(web):=20=E9=9C=80=E6=B1=82=E7=BC=96?= =?UTF-8?q?=E8=BE=91=E6=A1=86=E6=8D=A2=E4=B8=80=E6=9D=A1=20LOOP=20?= =?UTF-8?q?=E5=90=8E=E7=82=B9=E3=80=8C=E5=90=AF=E5=8A=A8=20LOOP=E3=80=8D?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E6=8A=A5=E3=80=8C=E4=B8=8D=E8=83=BD=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E9=87=8D=E6=96=B0=E8=BF=90=E8=A1=8C=E3=80=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 需求跑过 LOOP A 后,在编辑框里改成 LOOP B 再点「启动 LOOP」,前端按「这条需求 有没有跑过任何 LOOP」决定 rerun,弹出「重新运行确认」并发送 rerun:true;后端按 LOOP 判断,B 没跑过,返回 400「该需求尚未运行这条 LOOP,不能使用重新运行」, 用户无法从编辑框启动新 LOOP。 列表「触发」和抽屉「重新触发」早已按 LOOP 判断,只有编辑框例外。新增 latestIssueLaneTask,三个入口共用同一条规则:所选 LOOP 跑过才是重新运行 (并确认),没跑过就是首次运行。 Co-Authored-By: Claude Code --- web/app/issue-model.js | 15 ++-- web/app/issues.js | 6 +- webtest/tests/issue-dispatch-lane.test.mjs | 84 ++++++++++++++++++++++ 3 files changed, 98 insertions(+), 7 deletions(-) create mode 100644 webtest/tests/issue-dispatch-lane.test.mjs 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/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' }); +}); From f26ff23b70f8215782e1cf714c66955ff8251d2a Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 28 Nov 2026 03:06:52 +0000 Subject: [PATCH 2/2] =?UTF-8?q?fix(loop):=20=E6=96=B0=E5=BB=BA=20LOOP=20?= =?UTF-8?q?=E6=97=B6=E5=A1=AB=E5=86=99=E6=A0=87=E7=AD=BE=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E4=B8=A2=E5=A4=B1=E6=A8=A1=E6=9D=BF=E6=9D=A5=E6=BA=90=EF=BC=8C?= =?UTF-8?q?=E8=8A=82=E7=82=B9=E7=BB=A7=E7=BB=AD=E8=B7=9F=E9=9A=8F=E8=B4=A3?= =?UTF-8?q?=E4=BB=BB=E4=BA=BA=E7=9A=84=E9=BB=98=E8=AE=A4=E6=89=A7=E8=A1=8C?= =?UTF-8?q?=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 从通用模板新建 LOOP 时在向导里填了标签,前端用用户标签整体替换了 clone 接口 写入的 generic-source:<模板> 标记;设计器的标签输入框也把这个内部标记当普通 标签展示,删掉就丢。标记丢失后: - 引擎不再把复制来的模板角色当模板角色,节点不跟随责任人的默认执行器, 改为固定用 CodeBuddy(不带模型)运行,没配 CodeBuddy 的用户直接跑不了; - LOOP 卡片的运行依赖从「GitHub 仓库(已绑定)」变成「CodeBuddy API Key」, 设计器把「跟随责任人」显示成「CodeBuddy」; - 「内置」里对应模板又显示「复制到本项目」。 修复: - 后端:domain 增加 GenericSourceTagPrefix / GenericSource / KeepGenericSource, PUT /api/workflows 在新标签里没有来源标记时沿用已存记录的标记,任何客户端 (向导、设计器、API、AI 工具)都改不掉;引擎和 clone 共用同一常量与读取方法。 - 前端:标签输入框只展示、只替换用户标签,保存时带回来源标记;向导合并用户 标签与来源标记;目录页统一用 workflowGenericSource 读取。 - 已经丢失标记的旧 LOOP 无法可靠反推来源,不做迁移。 Co-Authored-By: Claude Code --- internal/domain/workflow.go | 28 ++++++++++ internal/domain/workflow_test.go | 22 ++++++++ internal/engine/sop_executors.go | 8 +-- internal/httpapi/catalog.go | 1 + internal/httpapi/generic_workflows.go | 2 +- internal/httpapi/generic_workflows_test.go | 45 +++++++++++++++ web/app.js | 2 +- web/app/flows.js | 6 +- web/app/sops.js | 16 ++++-- web/index.html | 4 +- webtest/tests/loop-generic-source.test.mjs | 65 ++++++++++++++++++++++ 11 files changed, 181 insertions(+), 18 deletions(-) create mode 100644 internal/domain/workflow_test.go create mode 100644 webtest/tests/loop-generic-source.test.mjs 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/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: