Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions internal/httpapi/issue_sop_mode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,53 @@ func TestRequirementBackToSOPRejoinsScheduledClaims(t *testing.T) {
t.Fatalf("an explicit automationState must win: %+v", stay)
}
}

// The page editor echoes the stored sopMode. Saving a no-LOOP requirement with
// a workflowId keeps it without a LOOP, so the audit log must not claim a LOOP
// was bound; sending sopMode=sop with the chosen LOOP binds it and says so.
func TestRequirementWithoutSOPEditAuditMatchesStoredLOOP(t *testing.T) {
st, err := repo.OpenTest()
if err != nil {
t.Fatal(err)
}
t.Cleanup(st.Close)
for _, id := range []string{"sop-audit-default", "sop-audit-chosen"} {
if err := st.PutWorkflow(domain.WorkflowDefinition{ID: id, Name: id, Version: 1, SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{{ID: "approval", Name: "Approval", Type: "approval", MaxAttempts: 1}}}); err != nil {
t.Fatal(err)
}
}
if err := st.PutProject(domain.Project{ID: "sop-audit", Name: "LOOP audit", OwnerID: 1, WorkflowID: "sop-audit-default"}); err != nil {
t.Fatal(err)
}
e := engine.New(st, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces")))
h := New(st, e, tracker.NewService(), "", "")
lastDetail := func(issue domain.Issue) string {
if len(issue.Operations) == 0 {
return ""
}
return issue.Operations[len(issue.Operations)-1].Detail
}

none := requestJSON[domain.Issue](t, h, http.MethodPost, "/api/issues", map[string]any{
"projectId": "sop-audit", "title": "先不走 LOOP", "kind": "requirement", "sopMode": "none",
}, http.StatusOK)
echoed := requestJSON[domain.Issue](t, h, http.MethodPut, "/api/issues", map[string]any{
"id": none.ID, "projectId": "sop-audit", "title": "先不走 LOOP", "sopMode": "none", "workflowId": "sop-audit-chosen", "priority": "high",
}, http.StatusOK)
if echoed.SOPMode != domain.IssueSOPNone || echoed.WorkflowID != "" {
t.Fatalf("an echoed sopMode=none keeps the requirement without a LOOP: %+v", echoed)
}
if detail := lastDetail(echoed); detail != "优先级" {
t.Fatalf("audit must record only what was stored, got %q", detail)
}

bound := requestJSON[domain.Issue](t, h, http.MethodPut, "/api/issues", map[string]any{
"id": none.ID, "projectId": "sop-audit", "title": "先不走 LOOP", "sopMode": "sop", "workflowId": "sop-audit-chosen", "automationState": "", "priority": "high",
}, http.StatusOK)
if bound.SOPMode != "" || bound.WorkflowID != "sop-audit-chosen" || bound.AutomationState != "eligible" {
t.Fatalf("sopMode=sop with a chosen LOOP must bind that LOOP and rejoin scheduled claims: %+v", bound)
}
if detail := lastDetail(bound); detail != "关联 LOOP" {
t.Fatalf("binding a LOOP must be audited, got %q", detail)
}
}
4 changes: 3 additions & 1 deletion internal/httpapi/issues.go
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,9 @@ func issueChangeDetail(before, after domain.Issue) string {
if before.AssigneeUserID != after.AssigneeUserID || before.AssigneeID != after.AssigneeID {
parts = append(parts, "责任人")
}
if before.WorkflowID != after.WorkflowID && after.WorkflowID != "" {
// A requirement that stays without a LOOP drops any workflowId on save,
// so only a write that actually binds a LOOP records one.
if before.WorkflowID != after.WorkflowID && after.WorkflowID != "" && !after.WithoutSOP() {
parts = append(parts, "关联 LOOP")
}
if before.TapdID != after.TapdID {
Expand Down
20 changes: 16 additions & 4 deletions web/app/issues.js
Original file line number Diff line number Diff line change
Expand Up @@ -482,11 +482,15 @@ function openIssue(issue=null){
state.selectedIssue=issue?.id||null;
const f=$('#issueForm'),projects=state.data.projects||[];
f.elements.projectId.innerHTML=projects.map(p=>`<option value="${p.id}">${escapeHTML(p.name)}</option>`).join('');
f.elements.workflowId.innerHTML=`<option value="">使用来源默认流程</option>`+runnableWorkflowOptions().map(w=>`<option value="${w.id}">${escapeHTML(w.name)}</option>`).join('');
const v=issue||{id:'',projectId:state.projectFilter||projects[0]?.id||'',title:'',description:'',priority:'medium',status:'backlog',workflowId:'',repositoryId:'',repositoryIds:[],baseBranch:''};
// A requirement delivered without a LOOP runs no default flow, so the empty
// choice says so; picking a LOOP here switches it to LOOP delivery.
f.elements.workflowId.innerHTML=`<option value="">${issueWithoutSOP(v)?'不使用 LOOP':'使用来源默认流程'}</option>`+runnableWorkflowOptions().map(w=>`<option value="${w.id}">${escapeHTML(w.name)}</option>`).join('');
['id','projectId','title','description','priority','status','workflowId','baseBranch','tapdId'].forEach(k=>f.elements[k].value=v[k]||'');
f.elements.baseBranch.value=storedIssueWorkBranch(v);
f.elements.automationIgnored.checked=v.automationState==='ignored';
delete f.elements.automationIgnored.dataset.touched;
f.elements.automationIgnored.onchange=()=>{f.elements.automationIgnored.dataset.touched='1'};
fillIssueRepositories(v.projectId,(v.repositoryIds&&v.repositoryIds.length)?v.repositoryIds:(v.repositoryId?[v.repositoryId]:null));
fillIssueAssignees(v.projectId,v.assigneeUserId||'');
f.elements.workflowId.disabled=false;
Expand Down Expand Up @@ -533,10 +537,18 @@ function issueFromForm(){
const assigneeUserId=Number(f.elements.assigneeUserId?.value)||0;
const syncTarget=document.querySelector('#issueForm [name="syncTarget"]:checked')?.value||'';
const source=old.source||(id?'local':syncTarget);
const workflowId=f.elements.workflowId.value||defaultSOPForIssue({...old,source});
const pickedWorkflowId=f.elements.workflowId.value;
const workflowId=pickedWorkflowId||defaultSOPForIssue({...old,source});
// Picking a LOOP for a requirement delivered without one is the switch to
// LOOP delivery: "sop" lifts the stored "none" (an echoed "none" would make
// the server drop the LOOP). Its "ignored" came from the no-LOOP mode, so
// unless the checkbox was changed here the server restores scheduling too.
const switchesToSOP=issueWithoutSOP(old)&&!!pickedWorkflowId;
const sopMode=switchesToSOP?'sop':old.sopMode;
const automationState=switchesToSOP&&!f.elements.automationIgnored.dataset.touched?'':(f.elements.automationIgnored.checked?'ignored':'eligible');
const repositoryIds=selectedIssueRepositoryIds(),status=f.elements.status.value;
const closeSource=status==='closed'?(old.status==='closed'?old.closeSource||'manual':'manual'):'';
return {...old,id,projectId:f.elements.projectId.value,title:f.elements.title.value.trim(),description:f.elements.description.value,priority:f.elements.priority.value,status,closeSource,automationState:f.elements.automationIgnored.checked?'ignored':'eligible',source,workflowId,repositoryId:repositoryIds[0]||'',repositoryIds,baseBranch:f.elements.baseBranch.value.trim(),repositoryBranches:selectedIssueRepositoryBranches(f.elements.baseBranch,$('#issueRepositoryBranches')),assigneeUserId,tapdId:source==='local'?f.elements.tapdId.value.trim():'',externalRef:trackerRefOf(old)||old.externalRef||undefined};
return {...old,id,projectId:f.elements.projectId.value,title:f.elements.title.value.trim(),description:f.elements.description.value,priority:f.elements.priority.value,status,closeSource,automationState,sopMode,source,workflowId,repositoryId:repositoryIds[0]||'',repositoryIds,baseBranch:f.elements.baseBranch.value.trim(),repositoryBranches:selectedIssueRepositoryBranches(f.elements.baseBranch,$('#issueRepositoryBranches')),assigneeUserId,tapdId:source==='local'?f.elements.tapdId.value.trim():'',externalRef:trackerRefOf(old)||old.externalRef||undefined};
}

// ParseGongfengRepoURL 与后端 domain.ParseGongfengRepoURL 保持一致:把粘贴的
Expand Down Expand Up @@ -697,7 +709,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);if(issueWithoutSOP(issue)&&!String(issue.workflowId||'').trim())return toast('这条需求不使用 LOOP,请先选择要运行的 LOOP');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 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;
Expand Down
2 changes: 1 addition & 1 deletion web/artifacts.css
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@
.markdown-body tr:hover{background:var(--hover)}

/* 行内与代码块 */
.markdown-body code:not(pre code){padding:2px 6px;border-radius:5px;background:rgba(148,163,184,.14);font:11.5px/1 var(--mono);color:var(--text);border:1px solid var(--line)}
.markdown-body code:not(pre code){padding:2px 6px;border-radius:5px;background:rgba(148,163,184,.14);font:11.5px/1 var(--mono);color:var(--text);border:1px solid var(--line);white-space:break-spaces;overflow-wrap:anywhere}
.md-code-block{position:relative;margin:16px 0;border-radius:10px;background:#0d1117;border:1px solid var(--line);overflow:hidden}
.md-code-header{display:flex;align-items:center;justify-content:space-between;padding:7px 14px;background:rgba(255,255,255,.04);border-bottom:1px solid rgba(255,255,255,.06);font-size:10.5px;color:#8b949e;user-select:none}
.md-code-lang{font-weight:700;text-transform:uppercase;letter-spacing:.05em}
Expand Down
2 changes: 1 addition & 1 deletion web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<link rel="stylesheet" href="/assets.css?v=20260823v1">
<link rel="stylesheet" href="/platform.css?v=20261121settingsrows">
<link rel="stylesheet" href="/observability.css?v=20261031metrics2">
<link rel="stylesheet" href="/artifacts.css?v=20261122artifactfeedback">
<link rel="stylesheet" href="/artifacts.css?v=20261128inlinecodespaces">
<link rel="stylesheet" href="/sops.css?v=20261030cards1">
<link rel="stylesheet" href="/sync.css?v=20261021schedule1">
<link rel="stylesheet" href="/access.css?v=20261031v1">
Expand Down
75 changes: 75 additions & 0 deletions webtest/tests/issue-no-sop.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,78 @@ test('no-LOOP requirements go to the chat and run a LOOP only when one is picked
app.evaluate(`state.data.issues=[noSOPIssue];openIssueInChatById('iss-nosop')`);
assert.equal(app.evaluate(`activeViewName()`), 'collaboration');
});

// The edit modal echoes the stored sopMode; the server keeps an echoed "none"
// and drops the LOOP, so picking a LOOP here must send sopMode=sop. The empty
// choice of a no-LOOP requirement runs nothing, so it must not read as the
// default flow.
test('editing a no-LOOP requirement binds the LOOP the user picks', async (t) => {
const app = await loadApp();
t.after(app.close);
const $ = (s) => app.document.querySelector(s);
const putBodies = [];
app.router.put('/api/issues', (call) => { putBodies.push(call.body); return { ...call.body, sopMode: call.body.sopMode === 'sop' ? '' : call.body.sopMode }; });
app.router.post('/api/issues/iss-edit-nosop/dispatch', (call) => ({ status: 201, body: { id: 'task-edit', issueId: 'iss-edit-nosop', workflowId: call.body.workflowId } }));
const open = () => app.evaluate(`
var pid=state.projectFilter||state.data.projects[0].id;
state.data.issues=[{id:'iss-edit-nosop',projectId:pid,number:62,kind:'requirement',source:'local',status:'backlog',priority:'medium',title:'编辑不走 LOOP',sopMode:'none',automationState:'ignored'}];
state.data.tasks=[];openIssue(state.data.issues[0]);
`);
const save = async () => { await app.evaluate(`saveIssue({preventDefault(){},currentTarget:document.querySelector('#issueForm')})`); await settle(3); };

open();
const select = $('#issueForm [name="workflowId"]');
assert.equal(select.value, '');
assert.equal(select.options[select.selectedIndex].textContent, '不使用 LOOP');
const workflowId = [...select.options].map((o) => o.value).find(Boolean);
assert.ok(workflowId, 'the project has a runnable LOOP to pick');

$('#issueForm [name="priority"]').value = 'high';
await save();
assert.equal(putBodies.at(-1).sopMode, 'none', 'an untouched choice keeps the requirement without a LOOP');
assert.equal(putBodies.at(-1).workflowId, '');
assert.equal(putBodies.at(-1).automationState, 'ignored');

open();
$('#issueForm [name="workflowId"]').value = workflowId;
await save();
assert.equal(putBodies.at(-1).sopMode, 'sop', 'picking a LOOP switches the requirement to LOOP delivery');
assert.equal(putBodies.at(-1).workflowId, workflowId);
assert.equal(putBodies.at(-1).automationState, '', 'the server restores scheduled claims the no-LOOP mode had turned off');

open();
$('#issueForm [name="workflowId"]').value = workflowId;
const ignore = $('#issueForm [name="automationIgnored"]');
ignore.checked = true;
ignore.dispatchEvent(new app.window.Event('change', { bubbles: true }));
await save();
assert.equal(putBodies.at(-1).automationState, 'ignored', 'an explicit 定时忽略 choice is kept');

open();
const before = app.router.calls.length;
await app.evaluate(`dispatchIssue()`);
await settle(2);
assert.ok(!app.router.calls.slice(before).some((c) => c.path.endsWith('/dispatch') || c.method === 'PUT'), 'starting without a picked LOOP neither saves nor dispatches');
assert.match($('#toastContainer').textContent, /请先选择要运行的 LOOP/);

open();
$('#issueForm [name="workflowId"]').value = workflowId;
await app.evaluate(`dispatchIssue()`);
await settle(4);
assert.equal(putBodies.at(-1).sopMode, 'sop');
const dispatch = app.router.calls.filter((c) => c.path === '/api/issues/iss-edit-nosop/dispatch').at(-1);
assert.equal(dispatch.body.workflowId, workflowId, 'the picked LOOP is the one that runs');
});

test('the edit modal keeps the default-flow wording for LOOP requirements', async (t) => {
const app = await loadApp();
t.after(app.close);
app.evaluate(`
var pid=state.projectFilter||state.data.projects[0].id;
openIssue({id:'iss-loop',projectId:pid,number:63,kind:'requirement',source:'local',status:'backlog',priority:'medium',title:'走 LOOP'});
`);
const select = app.document.querySelector('#issueForm [name="workflowId"]');
assert.equal(select.options[0].textContent, '使用来源默认流程');
app.evaluate(`openIssue(null)`);
assert.equal(select.options[0].textContent, '使用来源默认流程');
});
Loading
Loading