diff --git a/internal/httpapi/issue_sop_mode_test.go b/internal/httpapi/issue_sop_mode_test.go index 26c774bbb..317831f16 100644 --- a/internal/httpapi/issue_sop_mode_test.go +++ b/internal/httpapi/issue_sop_mode_test.go @@ -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) + } +} diff --git a/internal/httpapi/issues.go b/internal/httpapi/issues.go index fe8206ec2..93439b2cc 100644 --- a/internal/httpapi/issues.go +++ b/internal/httpapi/issues.go @@ -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 { diff --git a/web/app/issues.js b/web/app/issues.js index 00c7bef2e..34f4ef38e 100644 --- a/web/app/issues.js +++ b/web/app/issues.js @@ -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=>``).join(''); - f.elements.workflowId.innerHTML=``+runnableWorkflowOptions().map(w=>``).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=``+runnableWorkflowOptions().map(w=>``).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; @@ -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 保持一致:把粘贴的 @@ -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; diff --git a/web/artifacts.css b/web/artifacts.css index e864207a2..6e27a2de8 100644 --- a/web/artifacts.css +++ b/web/artifacts.css @@ -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} diff --git a/web/index.html b/web/index.html index 1b1ddc193..302a4986d 100644 --- a/web/index.html +++ b/web/index.html @@ -14,7 +14,7 @@ - + diff --git a/webtest/tests/issue-no-sop.test.mjs b/webtest/tests/issue-no-sop.test.mjs index 196348238..7991f5b78 100644 --- a/webtest/tests/issue-no-sop.test.mjs +++ b/webtest/tests/issue-no-sop.test.mjs @@ -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, '使用来源默认流程'); +}); diff --git a/webtest/tests/markdown-inline-code.test.mjs b/webtest/tests/markdown-inline-code.test.mjs new file mode 100644 index 000000000..8c4106f5e --- /dev/null +++ b/webtest/tests/markdown-inline-code.test.mjs @@ -0,0 +1,48 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile, readdir } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { loadApp } from '../lib/load-app.mjs'; + +const WEB = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../web'); + +function inlineCodeRules(css) { + return [...css.matchAll(/([^{}]*\.markdown-body[^{}]*\bcode\b[^{}]*)\{([^}]*)\}/g)] + .filter(([, selector]) => !/\bpre\s+code\b/.test(selector.replace(/:not\(pre code\)/g, ''))) + .map(([, selector, body]) => ({ selector: selector.replace(/\/\*[\s\S]*?\*\//g, '').trim(), body })); +} + +// Requirement descriptions, artifact previews and skill docs render Markdown +// in .markdown-body. Inline code is literal: `slugify("a b")` must keep both +// spaces, as the chat does (chatbot/src/styles.css .markdown code), or a +// whitespace bug report reads as if the input had one space. +test('inline code in .markdown-body keeps consecutive spaces', async () => { + const css = await readFile(path.join(WEB, 'artifacts.css'), 'utf8'); + const base = inlineCodeRules(css).find((rule) => rule.selector === '.markdown-body code:not(pre code)'); + assert.ok(base, 'the shared inline code rule exists'); + assert.match(base.body, /white-space:\s*break-spaces/); + assert.match(base.body, /overflow-wrap:\s*anywhere/, 'long unbroken code still wraps'); + + const overrides = []; + for (const dir of ['', 'app']) { + for (const name of await readdir(path.join(WEB, dir))) { + if (!name.endsWith('.css')) continue; + const file = path.join(dir, name); + for (const rule of inlineCodeRules(await readFile(path.join(WEB, file), 'utf8'))) { + if (/white-space:\s*(normal|nowrap)/.test(rule.body)) overrides.push(`${file}: ${rule.selector}`); + } + } + } + assert.deepEqual(overrides, [], 'no stylesheet collapses inline code whitespace again'); +}); + +test('the requirement Markdown keeps the spaces inside inline code', async (t) => { + const app = await loadApp(); + t.after(app.close); + const html = app.evaluate(`renderRequirementMarkdown('现状:\`slugify("Hello, World!")\` 返回 \`"hello,--world!"\`')`); + const box = app.document.createElement('div'); + box.className = 'markdown-body'; + box.innerHTML = html; + assert.equal(box.querySelector('code').textContent, 'slugify("Hello, World!")'); +});