diff --git a/e2e/unit/flow-designer.test.mjs b/e2e/unit/flow-designer.test.mjs index 63f71ae26..2b1f398d8 100644 --- a/e2e/unit/flow-designer.test.mjs +++ b/e2e/unit/flow-designer.test.mjs @@ -47,6 +47,8 @@ function load({ workflows = [], projectId = 'p1', elements = {}, groups = [], ag workflowAgents: () => agents, workflowAgent: id => agents.find(a => a.id === id) || null, workflowStages: wf => [wf.nodes], + // Mirrors sops.js, which the LOOP switcher calls since #1320. + workflowVersionLabel: w => (w.publishedRevision || w.status === 'published' ? `v${w.version || 1}` : ''), rememberOpenWorkflow: () => {}, renderAll: () => {}, }; diff --git a/internal/engine/core_cases_test.go b/internal/engine/core_cases_test.go index 57d16e696..4a2406dd7 100644 --- a/internal/engine/core_cases_test.go +++ b/internal/engine/core_cases_test.go @@ -511,3 +511,21 @@ func TestObservationIngressWorkspaceStatusAndStateTransitions(t *testing.T) { t.Fatalf("cancelled node = %+v", cancelled.Nodes["script"]) } } + +func TestAgentLoopMessagesDescribeExecutorFailures(t *testing.T) { + if got := agentLoopSkipMessage(""); strings.Contains(got, "策略为 ,") || !strings.Contains(got, "不是门禁未通过") { + t.Fatalf("executor failure skip message = %q", got) + } + if got := agentLoopSkipMessage("human"); got != "门禁失败策略为 human,跳过自修正" { + t.Fatalf("gate policy skip message = %q", got) + } + if got := agentLoopHumanMessage(1, 3, ""); strings.Contains(got, "耗尽") || !strings.Contains(got, "第 1 轮执行失败") { + t.Fatalf("early hand-off message = %q", got) + } + if got := agentLoopHumanMessage(1, 3, "fail"); strings.Contains(got, "执行失败") || !strings.Contains(got, "第 1 轮门禁未通过(失败策略为 fail)") { + t.Fatalf("early gate hand-off message = %q", got) + } + if got := agentLoopHumanMessage(3, 3, "loop"); got != "Agent 自修正次数已耗尽,转人工判断:" { + t.Fatalf("exhausted message = %q", got) + } +} diff --git a/internal/engine/node_execute.go b/internal/engine/node_execute.go index 73dd97748..bc7342a5a 100644 --- a/internal/engine/node_execute.go +++ b/internal/engine/node_execute.go @@ -1163,7 +1163,7 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl break } if failedAction != "loop" { - e.observe(runID, node.ID, domain.TelemetryEvent{Category: "orchestration", Name: "agent.loop", Phase: "finish", Message: "门禁失败策略为 " + failedAction + ",跳过自修正", Attributes: map[string]any{"iteration": iteration, "onFailure": failedAction, "feedback": err.Error()}}) + e.observe(runID, node.ID, domain.TelemetryEvent{Category: "orchestration", Name: "agent.loop", Phase: "finish", Message: agentLoopSkipMessage(failedAction), Attributes: map[string]any{"iteration": iteration, "onFailure": failedAction, "feedback": err.Error()}}) break } loopFeedback = err.Error() @@ -1222,7 +1222,7 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl } nr.Output, nr.Error, nr.Status, nr.FinishedAt = output, err.Error(), "waiting_approval", time.Now().UTC() markKnowledgeReadsCited(nr.KnowledgeReads, executionAttempt, output, frozen) - e.event(r, node.ID, "agent.loop.exhausted", "Agent 自修正次数已耗尽,转人工判断:"+err.Error()) + e.event(r, node.ID, "agent.loop.exhausted", agentLoopHumanMessage(lastIteration, maxIterations, failedAction)+err.Error()) }) e.persistCitedKnowledgeReads(runID, node.ID, executionAttempt) return @@ -1499,3 +1499,28 @@ func joinGateCommands(commands []string, artifacts []domain.ArtifactContract) st } return "set -e\n" + strings.Join(bound, "\n") } + +// agentLoopSkipMessage explains why a failed iteration does not self-correct. +// Only a gate configured with onFailure=loop retries; any other gate policy is +// named, and a failure no gate decided (the executor itself failed) says so +// instead of naming an empty policy. +func agentLoopSkipMessage(failedAction string) string { + if failedAction == "" { + return "本轮执行失败(不是门禁未通过),不进入自修正" + } + return "门禁失败策略为 " + failedAction + ",跳过自修正" +} + +// agentLoopHumanMessage prefixes the hand-off to a person when a looping role +// stops. It claims the self-correction budget is spent only when every +// iteration actually ran, and names the gate policy when a gate (rather than +// the executor) ended the loop early, matching agentLoopSkipMessage. +func agentLoopHumanMessage(iterations, maxIterations int, failedAction string) string { + if iterations >= maxIterations { + return "Agent 自修正次数已耗尽,转人工判断:" + } + if failedAction == "" { + return fmt.Sprintf("Agent 第 %d 轮执行失败,未进入自修正,转人工判断:", iterations) + } + return fmt.Sprintf("Agent 第 %d 轮门禁未通过(失败策略为 %s),未进入自修正,转人工判断:", iterations, failedAction) +} diff --git a/web/app/repo_drawer.js b/web/app/repo_drawer.js index 14ae0561b..7b47844ad 100644 --- a/web/app/repo_drawer.js +++ b/web/app/repo_drawer.js @@ -1,6 +1,6 @@ // Repository add/edit drawer for the project detail page. Saves write straight // to /api/repositories; #repositoryModal stays for its other callers. -const repoDrawerState={projectId:'',repoId:'',nameTouched:false,saving:false,returnFocus:null}; +const repoDrawerState={projectId:'',repoId:'',nameTouched:false,saving:false,returnFocus:null,branchExecutorId:''}; function repoDrawerOpen(){return !!$('#repoDrawer')?.classList.contains('open')} function setRepoDrawerSwitch(on){const sw=$('#repoDrawerDefault');if(!sw)return;sw.classList.toggle('on',!!on);sw.setAttribute('aria-checked',String(!!on))} function repoDrawerError(show){ @@ -28,12 +28,8 @@ function fillRepoBranchNaming(form,naming){ fields.workBranchPrefix.value=preset?prefix:'custom'; fields.workBranchCustomPrefix.value=preset?'':prefix; fields.workBranchPrompt.value=naming?.prompt||''; - const executors=(state.data.executors||[]).filter(executor=>executor.kind); - fields.workBranchExecutorId.replaceChildren( - new Option(lfT('选择 CLI','Choose a CLI'),''), - ...executors.map(executor=>repoBranchOption(executor.id,executor.name||executor.id,window.AgentFlowAssistantModels.cliIcon(executor.kind))), - ); - fields.workBranchExecutorId.value=naming?.executorId||''; + repoDrawerState.branchExecutorId=naming?.mode==='ai'?naming.executorId||'':''; + fillRepoBranchExecutors(form,repoDrawerState.branchExecutorId); fillRepoBranchModels(form,naming?.model||''); syncRepoBranchNaming(form); } @@ -42,6 +38,26 @@ function repoBranchOption(id,name,icon){ if(icon)option.dataset.brand=icon.split('/').at(-1); return option; } +// AI branch naming runs on the dispatching user's credentials, like role +// nodes, so the picker offers the same configured CLIs as the role editor +// (executorConfigured). A saved CLI that is not configured for this user stays +// visible but disabled, so editing other fields keeps the stored setting. +function fillRepoBranchExecutors(form,selected=''){ + const executors=(state.data.executors||[]).filter(executor=>executor.kind); + const usable=executors.filter(executor=>executorConfigured(executor.id)); + const icon=executor=>window.AgentFlowAssistantModels.cliIcon(executor.kind); + const options=[new Option(usable.length||selected?lfT('选择 CLI','Choose a CLI'):executorModelCatalogRequest?lfT('检查配置中…','Checking configuration…'):lfT('无可用 CLI,请先在个人配置中配置','No configured CLI. Configure one in Settings.'),'')]; + if(selected&&!usable.some(executor=>executor.id===selected)){ + const saved=executors.find(executor=>executor.id===selected); + const status=executorModelCatalogRequest?lfT('检查配置中','checking'):lfT('未配置','not configured'); + const option=repoBranchOption(selected,`${saved?.name||selected}(${status})`,saved?icon(saved):''); + option.disabled=true; + options.push(option); + } + options.push(...usable.map(executor=>repoBranchOption(executor.id,executor.name||executor.id,icon(executor)))); + form.elements.workBranchExecutorId.replaceChildren(...options); + form.elements.workBranchExecutorId.value=selected; +} function fillRepoBranchModels(form,model='',custom=false){ const fields=form.elements,executor=fields.workBranchExecutorId.value,choice=fields.workBranchModelChoice; const catalog=window.AgentFlowAssistantModels; @@ -69,10 +85,15 @@ function syncRepoBranchNaming(form){ form.querySelector('[data-work-branch-custom-prefix]').hidden=form.elements.workBranchPrefix.value!=='custom'; if(isAI){ const user=state.currentUser?.id; - loadExecutorModelCatalogs().then(()=>{ + const loading=loadExecutorModelCatalogs(); + // Repaint while the catalog loads so the picker says "checking" instead + // of reporting configured CLIs as missing until the request returns. + fillRepoBranchExecutors(form,form.elements.workBranchExecutorId.value); + loading.then(()=>{ if(repoDrawerOpen()&&state.currentUser?.id===user&&form.elements.workBranchNamingMode.value==='ai'){ const manual=form.elements.workBranchModelChoice.value===AGENT_CUSTOM_MODEL; const model=repoBranchModel(form); + fillRepoBranchExecutors(form,form.elements.workBranchExecutorId.value); fillRepoBranchModels(form,model,manual&&!model); } }); @@ -161,6 +182,11 @@ async function saveRepoDrawer(e){ if(payload.workBranchNaming.mode==='ai'&&(!payload.workBranchNaming.executorId||!payload.workBranchNaming.model)){ return toast(lfT('请选择 AI 分支命名的 CLI 和模型','Choose the CLI and model for AI branch naming'),'warn'); } + const branchExecutor=payload.workBranchNaming.executorId; + if(payload.workBranchNaming.mode==='ai'&&branchExecutor!==repoDrawerState.branchExecutorId&&!executorConfigured(branchExecutor)){ + f.elements.workBranchExecutorId.focus(); + return toast(executorModelCatalogRequest?lfT('正在检查执行器配置,请稍后再试','Checking executor configuration, try again shortly'):lfT('请选用已配置的 CLI','Choose a configured CLI'),'warn'); + } repoDrawerState.saving=true;$('#repoDrawerSave').disabled=true; try{ captureProjectAdminForm(); diff --git a/webtest/tests/projects-repos.test.mjs b/webtest/tests/projects-repos.test.mjs index 1b591f227..e2e5e7772 100644 --- a/webtest/tests/projects-repos.test.mjs +++ b/webtest/tests/projects-repos.test.mjs @@ -136,8 +136,8 @@ test('repository drawer saves AI and prefix naming settings', async (t) => { t.after(app.close); app.router.put('/api/repositories', (call) => call.body); app.router.get('/api/executor-models', { - codebuddy: { models: [{ id: 'hy4std', name: 'Hy4' }] }, - codex: { models: [{ id: 'gpt-5.6-sol', name: 'GPT-5.6 Sol' }] }, + codebuddy: { configured: true, models: [{ id: 'hy4std', name: 'Hy4' }] }, + codex: { configured: true, models: [{ id: 'gpt-5.6-sol', name: 'GPT-5.6 Sol' }] }, claude: { models: [] }, }); app.evaluate(` @@ -212,6 +212,113 @@ test('repository drawer saves AI and prefix naming settings', async (t) => { assert.deepEqual(updates().at(-1).body.workBranchNaming, { mode: 'prefix', prefix: 'bugfix/' }); }); +test('AI branch naming offers only CLIs configured for the user', async (t) => { + const app = await loadApp(); + t.after(app.close); + app.router.put('/api/repositories', (call) => call.body); + app.router.get('/api/executor-models', { + codebuddy: { configured: true, models: [{ id: 'hy4std', name: 'Hy4' }] }, + codex: { configured: false, models: [{ id: 'gpt-5.6-sol', name: 'GPT-5.6 Sol' }] }, + claude: { configured: false, models: [] }, + }); + app.evaluate(` + state.projectAdminDetailId='project-1'; + state.projectDraftFor='project-1'; + state.data.executors=[{id:'codebuddy',kind:'codebuddy',name:'CodeBuddy'},{id:'codex',kind:'codex',name:'Codex'},{id:'claude',kind:'claude-code',name:'Claude Code'}]; + state.data.repositories=[{ + id:'branch-repo', projectId:'project-1', provider:'github', + name:'payments', cloneUrl:'https://github.com/acme/payments.git', defaultBranch:'main', + workBranchNaming:{mode:'prefix',prefix:'feature/'} + }]; + state.data.projects[0].defaultRepositoryId='branch-repo'; + state.projectDraft=projectDraftFrom(state.data.projects[0]); + state.projectDraftBase=clone(state.projectDraft); + openRepoDrawer('branch-repo'); + `); + const form = app.document.querySelector('#repoDrawerForm'); + const fields = form.elements; + const options = () => Array.from(fields.workBranchExecutorId.options, option => [option.value, option.text, option.disabled]); + const updates = () => app.router.calls.filter(c => c.method === 'PUT' && c.path === '/api/repositories'); + fields.workBranchNamingMode.value = 'ai'; + fields.workBranchNamingMode.dispatchEvent(new app.window.Event('change', { bubbles: true })); + await settle(6); + assert.deepEqual(options(), [['', '选择 CLI', false], ['codebuddy', 'CodeBuddy', false]], + 'CLIs the user cannot run are not offered, as in the role editor'); + + // A CLI that is not usable cannot be saved as a new choice. + fields.workBranchExecutorId.add(new app.window.Option('Codex', 'codex')); + fields.workBranchExecutorId.value = 'codex'; + fields.workBranchExecutorId.dispatchEvent(new app.window.Event('change', { bubbles: true })); + fields.workBranchModelChoice.value = 'gpt-5.6-sol'; + form.dispatchEvent(new app.window.Event('submit', { bubbles: true, cancelable: true })); + await settle(8); + assert.equal(updates().length, 0, 'an unconfigured CLI is rejected before saving'); + assert.match(app.document.body.textContent, /请选用已配置的 CLI/); + + // A stored CLI the current editor has not configured stays visible but + // disabled, and saving other fields keeps it. + app.evaluate(` + state.data.repositories[0].workBranchNaming={mode:'ai',executorId:'codex',model:'gpt-5.6-sol',prompt:''}; + openRepoDrawer('branch-repo'); + `); + await settle(6); + assert.deepEqual(options(), [['', '选择 CLI', false], ['codex', 'Codex(未配置)', true], ['codebuddy', 'CodeBuddy', false]]); + assert.equal(fields.workBranchExecutorId.value, 'codex'); + fields.defaultBranch.value = 'trunk'; + form.dispatchEvent(new app.window.Event('submit', { bubbles: true, cancelable: true })); + await settle(8); + assert.equal(updates().length, 1); + assert.equal(updates().at(-1).body.defaultBranch, 'trunk'); + assert.deepEqual(updates().at(-1).body.workBranchNaming, { mode: 'ai', executorId: 'codex', model: 'gpt-5.6-sol', prompt: '' }); +}); + +test('AI branch naming says the CLI list is loading instead of not configured', async (t) => { + const app = await loadApp(); + t.after(app.close); + let release; + app.router.get('/api/executor-models', () => new Promise(resolve => { + release = () => resolve({ codebuddy: { configured: true, models: [{ id: 'hy4std', name: 'Hy4' }] } }); + })); + app.evaluate(` + state.projectAdminDetailId='project-1'; + state.projectDraftFor='project-1'; + state.data.executors=[{id:'codebuddy',kind:'codebuddy',name:'CodeBuddy'},{id:'codex',kind:'codex',name:'Codex'}]; + state.data.repositories=[{ + id:'saved-ai', projectId:'project-1', provider:'github', + name:'payments', cloneUrl:'https://github.com/acme/payments.git', defaultBranch:'main', + workBranchNaming:{mode:'ai',executorId:'codebuddy',model:'hy4std',prompt:''} + },{ + id:'prefix-repo', projectId:'project-1', provider:'github', + name:'ledger', cloneUrl:'https://github.com/acme/ledger.git', defaultBranch:'main', + workBranchNaming:{mode:'prefix',prefix:'feature/'} + }]; + state.projectDraft=projectDraftFrom(state.data.projects[0]); + state.projectDraftBase=clone(state.projectDraft); + openRepoDrawer('saved-ai'); + `); + const fields = app.document.querySelector('#repoDrawerForm').elements; + const options = () => Array.from(fields.workBranchExecutorId.options, option => [option.value, option.text, option.disabled]); + await settle(2); + assert.deepEqual(options(), [['', '选择 CLI', false], ['codebuddy', 'CodeBuddy(检查配置中)', true]], + 'a saved CLI is not reported as unconfigured before the catalog answers'); + assert.equal(fields.workBranchExecutorId.value, 'codebuddy'); + release(); + await settle(6); + assert.deepEqual(options(), [['', '选择 CLI', false], ['codebuddy', 'CodeBuddy', false]]); + assert.equal(fields.workBranchExecutorId.value, 'codebuddy'); + + // Switching a prefix repository to AI while the catalog reloads shows the + // checking placeholder rather than "no configured CLI". + app.evaluate(`closeRepoDrawer({restoreFocus:false});openRepoDrawer('prefix-repo');`); + fields.workBranchNamingMode.value = 'ai'; + fields.workBranchNamingMode.dispatchEvent(new app.window.Event('change', { bubbles: true })); + await settle(2); + assert.deepEqual(options(), [['', '检查配置中…', false]]); + release(); + await settle(6); + assert.deepEqual(options(), [['', '选择 CLI', false], ['codebuddy', 'CodeBuddy', false]]); +}); + test('project owner deletes a project from its danger zone and the list moves on', async (t) => { const app = await loadApp(); t.after(app.close);