Skip to content
Merged
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
14 changes: 14 additions & 0 deletions web/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -1598,6 +1598,20 @@ function openIssueInChat(issue,opts){
function reloadShellProjects(){
return api('/api/bootstrap',{silent:true}).then(shell=>{Object.assign(state.data,shell);renderAll();return state.data.projects||[]});
}
// Adopting a built-in template copies its roles, rules, skills and default MCPs
// into the project on the server. Reload the catalog lists the designer and the
// role editor read from: otherwise every node of the new SOP shows an
// unavailable role, and saving one of the new roles drops the project rules it
// cannot see. The adopted SOP is kept even if the reload fails.
async function reloadCatalogAfterAdoption(adopted){
try{
const shell=await api('/api/bootstrap',{silent:true});
for(const key of ['workflows','agents','rules','skills','mcpServers'])if(Array.isArray(shell?.[key]))state.data[key]=shell[key];
}catch{}
const workflows=state.data.workflows||(state.data.workflows=[]);
const index=workflows.findIndex(w=>w.id===adopted?.id);
if(index>=0)workflows[index]=adopted;else if(adopted?.id)workflows.unshift(adopted);
}
function mountNativeChat(){
const frame=$('#chatNextFrame');
if(!frame)return;
Expand Down
2 changes: 1 addition & 1 deletion web/app/approvals.js
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ function approvalCardHTML(r){
const sideButton=issue?`<button class="button ghost small" data-open-issue="${escapeHTML(issue.id)}">打开需求</button>`:`<button class="button ghost small" data-open-logs="${escapeHTML(r.id)}">${alignRun?'查看对齐详情':'排查日志'}</button>`;
const more=canDecideRun(r)?`<div class="ap-more"><button type="button" class="ap-more-toggle" data-ap-more title="更多操作" aria-label="更多操作" aria-haspopup="menu" aria-expanded="false">${huiIcon('more-horizontal')}</button><div class="ap-more-menu" role="menu" hidden><button type="button" class="ap-menu-item danger" role="menuitem" data-cancel-run="${escapeHTML(r.id)}">${huiIcon('close')}<span>取消流程</span></button></div></div>`:'';
const decision=r.pauseRequested?(canDecideRun(r)?pausedRunPanelHTML(r):humanDecisionPanelHTML(r.id,nodeId,r.nodes?.[nodeId],node,r.workflowSnapshot?.nodes||[],r)):humanDecisionPanelHTML(r.id,nodeId,r.nodes?.[nodeId],node,r.workflowSnapshot?.nodes||[],r);
return `<div class="ap-card${approvalSelectable(r)&&approvalSelection().has(approvalKey(r.id,waitingNodeId(r)))?' is-selected':''}"><div class="ap-card-head">${approvalSelectBoxHTML(r)}<div class="ap-main"><div class="ap-head"><b>${escapeHTML(title)}</b>${approvalStatusBadgeHTML(r.pauseRequested)}</div><div class="ap-meta">${keyHTML}${sep}${r.pauseRequested?'暂停于':'卡在'}「${escapeHTML(node?.name||nodeId||'确认')}」${sep}${waitingForText(r,nodeId)}</div></div><div class="ap-side">${sideButton}${!r.pauseRequested?refreshRunSOPButtonHTML(r):''}${more}</div></div>${decision?`<div class="ap-body">${decision}</div>`:''}</div>`;
return `<div class="ap-card${approvalSelectable(r)&&approvalSelection().has(approvalKey(r.id,waitingNodeId(r)))?' is-selected':''}"><div class="ap-card-head">${approvalSelectBoxHTML(r)}<div class="ap-main"><div class="ap-head"><b${alignRun?'':' data-i18n-data'}>${escapeHTML(title)}</b>${approvalStatusBadgeHTML(r.pauseRequested)}</div><div class="ap-meta">${keyHTML}${sep}${r.pauseRequested?'暂停于':'卡在'}「${escapeHTML(node?.name||nodeId||'确认')}」${sep}${waitingForText(r,nodeId)}</div></div><div class="ap-side">${sideButton}${!r.pauseRequested?refreshRunSOPButtonHTML(r):''}${more}</div></div>${decision?`<div class="ap-body">${decision}</div>`:''}</div>`;
}
function closeApprovalMoreMenus(except){
document.querySelectorAll('#approvalsView .ap-more.is-open').forEach(more=>{
Expand Down
6 changes: 4 additions & 2 deletions web/app/flows.js
Original file line number Diff line number Diff line change
Expand Up @@ -1311,7 +1311,9 @@ async function createSOPFromWizard(e){
delete workflow.createdAt;delete workflow.updatedAt;
saved=await api('/api/workflows',{method:'PUT',body:JSON.stringify(workflow)});
}
state.data.workflows.unshift(saved);state.workflow=clone(saved);state.selectedNode=null;markWorkflowClean();
if(catalogGeneric(template))await reloadCatalogAfterAdoption(saved);
else state.data.workflows.unshift(saved);
state.workflow=clone(saved);state.selectedNode=null;markWorkflowClean();
$('#sopCreateModal').classList.remove('open');renderAll();switchView('flow');
const missing=catalogGeneric(template)?genericRequirementRows(saved).filter(r=>!r.ok):[];
toast(missing.length?`LOOP 草稿已创建;${missing.length} 项运行依赖未配置(${missing.map(r=>r.label).join('、')})`:'LOOP 草稿已创建,请继续设计节点',missing.length?'':'ok')
Expand All @@ -1320,7 +1322,7 @@ async function createSOPFromWizard(e){
?lfT('所选运行沙箱已不可用,请点击「刷新沙箱」后重新选择。','The selected sandbox is no longer available. Refresh sandboxes and select another one.')
:err.message);
}}
async function cloneWorkflow(id){const src=id?(state.data.workflows||[]).find(w=>w.id===id):state.workflow;if(!src?.id)return toast('先选择一条 LOOP');const name=await afPrompt({title:'复制 LOOP',message:'请输入复制后的 LOOP 名称:',defaultValue:`${src.name} - 副本`});if(!name)return;const owner=await afPrompt({title:'LOOP 负责人',message:'请输入负责人(可留空):',defaultValue:src.owner||''})??'';try{const copied=await api(`/api/workflows/${encodeURIComponent(src.id)}/clone`,{method:'POST',body:JSON.stringify({id:uid('sop'),name,owner,projectId:state.projectFilter||''})});state.data.workflows.unshift(copied);state.workflow=clone(copied);state.selectedNode=null;state.sopScope='project';markWorkflowClean();renderAll();toast('已复制到本项目')}catch(e){toast(e.message)}}
async function cloneWorkflow(id){const src=id?(state.data.workflows||[]).find(w=>w.id===id):state.workflow;if(!src?.id)return toast('先选择一条 LOOP');const name=await afPrompt({title:'复制 LOOP',message:'请输入复制后的 LOOP 名称:',defaultValue:`${src.name} - 副本`});if(!name)return;const owner=await afPrompt({title:'LOOP 负责人',message:'请输入负责人(可留空):',defaultValue:src.owner||''})??'';try{const copied=await api(`/api/workflows/${encodeURIComponent(src.id)}/clone`,{method:'POST',body:JSON.stringify({id:uid('sop'),name,owner,projectId:state.projectFilter||''})});if(catalogGeneric(src))await reloadCatalogAfterAdoption(copied);else state.data.workflows.unshift(copied);state.workflow=clone(copied);state.selectedNode=null;state.sopScope='project';markWorkflowClean();renderAll();toast('已复制到本项目')}catch(e){toast(e.message)}}

async function deleteWorkflow(id){
const w=(state.data.workflows||[]).find(x=>x.id===id);
Expand Down
2 changes: 1 addition & 1 deletion web/app/issues.js
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ function issueKanbanCard(i){
const cardTone=needsConfirm?' needs-confirm':(isFailed?' needs-attention':'');
return `<article class="kanban-card${cardTone}" draggable="true" data-id="${escapeHTML(i.id)}">
<div class="kanban-card-top"><b>${escapeHTML(key)}</b>${issueSelectionCheckbox(i)}</div>
<h4 title="${escapeHTML(i.title)}">${issueTitleMarkup(i.title)}</h4>
<h4 title="${escapeHTML(i.title)}" data-i18n-data>${issueTitleMarkup(i.title)}</h4>
<div class="kanban-card-meta">
${issuePriorityMarkup(i.priority)}
<span class="kanban-stage ${stage.key}" title="${escapeHTML(stage.hint||'')}">${issueStageBadge(stage)}</span>
Expand Down
8 changes: 4 additions & 4 deletions web/app/runs.js

Large diffs are not rendered by default.

5 changes: 1 addition & 4 deletions web/app/sops.js
Original file line number Diff line number Diff line change
Expand Up @@ -476,11 +476,8 @@ async function adoptGenericTemplate(){
const button=$('#confirmGenericTemplate');button.disabled=true;button.textContent='复制中…';
try{
const copied=await api(`/api/workflows/${encodeURIComponent(src.id)}/clone`,{method:'POST',body:JSON.stringify({id:uid('sop'),name:src.name.replace(/^通用/,''),owner:src.owner||'',projectId:state.projectFilter})});
state.data.workflows.unshift(copied);
await reloadCatalogAfterAdoption(copied);
state.workflow=clone(copied);state.selectedNode=null;state.sopScope='project';markWorkflowClean();
// The clone endpoint also copies the template roles into the project; the
// canvas resolves node roles from this list, so refresh it before drawing.
try{const agents=await api('/api/agents',{silent:true});if(Array.isArray(agents))state.data.agents=agents}catch{}
$('#genericTemplateModal').classList.remove('open');
renderAll();switchView('flow');
const missing=genericRequirementRows(copied).filter(r=>!r.ok);
Expand Down
12 changes: 10 additions & 2 deletions web/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ const $ = id => document.getElementById(id);
const t = window.lfT || ((zh) => zh);
let mode = 'login', signup = false;

// The password endpoints answer a wrong password and the rate limit in English
// only; show them in the page language like every other message here.
function authErrorMessage(status, payload, creating) {
if (status === 429) return t('尝试次数过多,请一分钟后再试', 'Too many attempts. Try again in a minute.');
if (!creating && status === 401) return t('用户名或密码错误', 'Invalid username or password');
return payload?.error || t('操作失败', 'Request failed');
}

function render() {
const creating = mode !== 'login';
$('loginSubtitle').textContent = mode === 'setup' ? t('创建管理员账号', 'Create the administrator account') : creating ? t('创建你的账号', 'Create your account') : t('登录你的交付工作台', 'Sign in to your delivery workspace');
Expand Down Expand Up @@ -55,8 +63,8 @@ $('loginForm').onsubmit = async event => {
method: 'POST', headers: {'Content-Type': 'application/json'},
body: JSON.stringify({login: form.elements.login.value.trim(), password: form.elements.password.value}),
});
const payload = await response.json();
if (!response.ok) throw new Error(payload.error || t('操作失败', 'Request failed'));
const payload = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(authErrorMessage(response.status, payload, creating));
location.replace('/');
} catch (err) { error.textContent = err.message; button.disabled = false; }
};
91 changes: 91 additions & 0 deletions webtest/tests/generic-adoption-catalog.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {loadApp, sampleBootstrap} from '../lib/load-app.mjs';

// Adopting a built-in template makes the server copy the template's roles and
// rules into the project. The designer and the role editor read those from
// state.data, so the page has to reload them instead of only adding the SOP.
const template = {
id: 'generic-delivery', name: '通用交付 SOP', generic: true, sandboxProfileId: 'project-box',
nodes: [{id: 'build', name: '开发实现', type: 'agent', agentId: 'generic-delivery-build'}], edges: [],
};
const adoptedRole = {id: 'generic-delivery-build', projectId: 'project-1', name: '开发实现', executorId: 'codebuddy', rules: ['generic-delivery-rule']};
const adoptedRule = {id: 'generic-delivery-rule', projectId: 'project-1', name: '工程约束', content: '# rules'};

function adoptedCopy(body) {
return {...template, ...body, generic: false, nodes: template.nodes, tags: ['generic-source:generic-delivery']};
}

async function adoptionApp(t) {
const app = await loadApp();
t.after(app.close);
app.evaluate(`state.projectFilter='project-1';state.data.workflows=[${JSON.stringify(template)}];
state.data.sandboxes=[{id:'project-box',name:'Project box',projectId:'project-1',driver:'bwrap'}];`);
let copy = null;
app.router.post('/api/workflows/generic-delivery/clone', call => (copy = adoptedCopy(call.body)));
app.router.put('/api/workflows', call => (copy = {...copy, ...call.body}));
// Reloading after the clone returns what the server holds by then.
app.router.get('/api/bootstrap', () => {
const shell = sampleBootstrap();
return {...shell, workflows: [template, copy], agents: [...shell.agents, adoptedRole], rules: [...shell.rules, adoptedRule]};
});
return app;
}

function assertAdoptedRolesResolve(app) {
const id = app.evaluate('state.workflow.id');
assert.equal(app.evaluate(`state.data.workflows.filter(w=>w.id==='${id}').length`), 1, 'the adopted SOP is listed once');
assert.equal(app.evaluate(`workflowAgent('generic-delivery-build')?.name`), '开发实现');
assert.equal(app.evaluate(`state.data.rules.some(r=>r.id==='generic-delivery-rule')`), true);
assert.doesNotMatch(app.document.querySelector('#canvas')?.textContent || '', /角色不可用/);
}

test('copying a built-in template from the SOP catalog reloads the roles and rules it brought', async t => {
const app = await adoptionApp(t);
app.evaluate(`state.genericTemplateId='generic-delivery';`);
await app.evaluate('adoptGenericTemplate()');
assert.ok(app.router.calls.some(c => c.method === 'GET' && c.path === '/api/bootstrap'));
assertAdoptedRolesResolve(app);
});

test('creating an SOP from a built-in template in the wizard reloads the roles and rules it brought', async t => {
const app = await adoptionApp(t);
app.evaluate('openSOPWizard()');
const form = app.document.querySelector('#sopCreateForm');
form.elements.name.value = '交付 SOP';
form.elements.description.value = '带说明';
await app.evaluate('createSOPFromWizard').call(null, {preventDefault() {}, currentTarget: form});
assert.ok(app.router.calls.some(c => c.method === 'POST' && c.path === '/api/workflows/generic-delivery/clone'));
assert.equal(app.evaluate('state.workflow.description'), '带说明');
assertAdoptedRolesResolve(app);
});

test('duplicating a built-in template from the designer reloads the roles and rules it brought', async t => {
const app = await adoptionApp(t);
app.evaluate(`afPrompt=async({defaultValue}={})=>defaultValue||'交付 SOP - 副本'`);
await app.evaluate(`cloneWorkflow('generic-delivery')`);
assert.ok(app.router.calls.some(c => c.method === 'POST' && c.path === '/api/workflows/generic-delivery/clone'));
assertAdoptedRolesResolve(app);
});

test('copying a project SOP keeps the catalog as it is and lists the copy once', async t => {
const app = await loadApp();
t.after(app.close);
app.evaluate(`state.projectFilter='project-1';afPrompt=async({defaultValue}={})=>defaultValue||'Delivery copy'`);
app.router.post('/api/workflows/flow-1/clone', call => ({...call.body, nodes: [], edges: [], status: 'draft'}));
await app.evaluate(`cloneWorkflow('flow-1')`);
const id = app.evaluate('state.workflow.id');
assert.notEqual(id, 'flow-1');
assert.equal(app.evaluate(`state.data.workflows.filter(w=>w.id==='${id}').length`), 1);
assert.equal(app.router.calls.filter(c => c.path === '/api/bootstrap').length, 1, 'only the boot load fetched the shell');
});

test('the adopted SOP stays open when the catalog reload fails', async t => {
const app = await adoptionApp(t);
app.router.get('/api/bootstrap', {status: 500, body: {error: 'boom'}});
app.evaluate(`state.genericTemplateId='generic-delivery';`);
await app.evaluate('adoptGenericTemplate()');
const id = app.evaluate('state.workflow.id');
assert.match(id, /^sop/);
assert.equal(app.evaluate(`state.data.workflows.filter(w=>w.id==='${id}').length`), 1);
});
78 changes: 78 additions & 0 deletions webtest/tests/i18n-user-titles.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { loadApp, WEB_ROOT } from '../lib/load-app.mjs';

// In English mode i18n.js rewrites Chinese copy fragment by fragment. Text a
// person typed — a requirement title or description — may only be replaced as
// a whole dictionary entry, otherwise "修复 X 的两个缺陷" turns into
// "Fix X 的两个缺陷" wherever the title is shown.
async function englishPage() {
const dom = new JSDOM('<html data-lang="en"><body></body></html>', { runScripts: 'outside-only', url: 'http://127.0.0.1/' });
for (const file of ['i18n-en.js', 'i18n.js']) {
new vm.Script(await readFile(path.join(WEB_ROOT, file), 'utf8'), { filename: file }).runInContext(dom.getInternalVMContext());
}
return dom.window;
}

async function rendered(window, html) {
const host = window.document.createElement('div');
host.innerHTML = html;
window.document.body.append(host);
await new Promise((resolve) => window.setTimeout(resolve, 0));
return host;
}

const TITLE = '修复 Inventory.remove 的两个缺陷';
const DESCRIPTION = `${TITLE}\n\n- 对不存在的 SKU 调用 remove 时直接抛 KeyError\n- qty <= 0 也要拒绝\n\n验收:补充 pytest 单测,全部通过。`;

async function fixture(t) {
const app = await loadApp();
t.after(app.close);
const window = await englishPage();
t.after(() => window.close());
// The dictionary does rewrite these fragments in UI copy, so the assertions
// below are only meaningful while that stays true.
assert.notEqual(window.lfTranslate(TITLE), TITLE);
app.evaluate(`
state.data.issues=[{id:'iss-1',projectId:'project-1',number:7,title:${JSON.stringify(TITLE)},description:${JSON.stringify(DESCRIPTION)},status:'in_progress'}];
state.data.tasks=[{id:'task-1',issueId:'iss-1',runId:'run-9'}];
`);
return { app, window };
}

const run = { id: 'run-9', status: 'waiting', workflowId: 'flow-1', executionContext: { issueId: 'iss-1', projectId: 'project-1' },
workflowSnapshot: { id: 'flow-1', name: 'Delivery Flow', nodes: [{ id: 'gate', name: 'Review', type: 'approval' }] },
nodes: { gate: { status: 'waiting_approval' } }, createdAt: '2026-11-26T02:32:06Z' };

test('English mode keeps a requirement title as typed in the run list, the kanban board and the approval queue', async (t) => {
const { app, window } = await fixture(t);
const row = await rendered(window, app.evaluate(`runRowHTML(${JSON.stringify(run)},state.data.workflows)`));
assert.equal(row.querySelector('.run-row-title').textContent, TITLE);
assert.equal(row.querySelector('.run-row-title').getAttribute('title'), TITLE);
const card = await rendered(window, app.evaluate(`issueKanbanCard(state.data.issues[0])`));
assert.equal(card.querySelector('h4').textContent, TITLE);
const approval = await rendered(window, app.evaluate(`approvalCardHTML(${JSON.stringify(run)})`));
assert.equal(approval.querySelector('.ap-head b').textContent, TITLE);
});

test('English mode keeps the requirement description as typed in the run header', async (t) => {
const { app, window } = await fixture(t);
const header = await rendered(window, app.evaluate(`runHeaderDescription(${JSON.stringify(DESCRIPTION)},${JSON.stringify(TITLE)},false)`));
assert.equal(header.querySelector('.run-header-copy').textContent, DESCRIPTION.slice(TITLE.length).trim());
const short = await rendered(window, app.evaluate(`runHeaderDescription('验收:补充单测',${JSON.stringify(TITLE)},false)`));
assert.equal(short.querySelector('.run-header-copy').textContent, '验收:补充单测');
});

test('English mode still translates a requirement title that is a whole dictionary entry and the scheduled baseline title', async (t) => {
const { app, window } = await fixture(t);
const align = { ...run, workflowId: 'scheduled-baseline-align', workflowSnapshot: { id: 'scheduled-baseline-align', name: 'align', nodes: [] }, repository: { name: 'atlas' } };
const approval = await rendered(window, app.evaluate(`approvalCardHTML(${JSON.stringify(align)})`));
assert.doesNotMatch(approval.querySelector('.ap-head b').textContent, /[㐀-鿿]/);
app.evaluate(`state.data.issues[0].title='自由协作'`);
const row = await rendered(window, app.evaluate(`runRowHTML(${JSON.stringify(run)},state.data.workflows)`));
assert.doesNotMatch(row.querySelector('.run-row-title').textContent, /[㐀-鿿]/);
});
Loading
Loading