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
30 changes: 30 additions & 0 deletions e2e/unit/flow-designer.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -305,3 +305,33 @@ test('crowded legacy rows are widened so nodes stop overlapping; normal layouts
assert.equal(run('spreadCrowdedNodes(state.workflow)'), true);
assert.equal(ctx.state.workflow.nodes[1].position.y - ctx.state.workflow.nodes[0].position.y, 160);
});

test('arrangeWorkflowNodes is idempotent and arrangeBeforeCommit organizes messy layouts without recording no-ops', () => {
const { ctx, run, json } = withWorkflow({
...graph(),
nodes: [
node('a', { position: { x: 500, y: 300 } }),
node('b', { position: { x: 40, y: 20 } }),
node('c', { position: { x: 120, y: 400 } }),
],
});
ctx.workflowStages = wf => [[wf.nodes[0]], [wf.nodes[1], wf.nodes[2]]];
run('flowHistory.clear()');

assert.equal(run('arrangeBeforeCommit()'), true);
assert.deepEqual(json('state.workflow.nodes.map(n => n.position)'), [
{ x: 80, y: 80 },
{ x: 400, y: 80 },
{ x: 400, y: 270 },
]);
assert.equal(run('flowHistory.canUndo()'), true, 'moving nodes records an undo entry');

assert.equal(run('arrangeBeforeCommit()'), false, 'already-arranged layout is a no-op');
assert.equal(run('flowHistory.undo()'), true);
assert.deepEqual(json('state.workflow.nodes.map(n => n.position)'), [
{ x: 500, y: 300 },
{ x: 40, y: 20 },
{ x: 120, y: 400 },
]);
assert.equal(run('flowHistory.canUndo()'), false, 'the second no-op call did not push an extra undo entry');
});
70 changes: 56 additions & 14 deletions web/app/flows.js
Original file line number Diff line number Diff line change
Expand Up @@ -356,18 +356,52 @@ function duplicateNode(id){
flowToast('已复制(不含连线)',{undo:true});
return copy;
}
let flowNeedsFitId=null;
function arrangeWorkflowNodes(wf=state.workflow,{animate=false}={}){
if(!wf||typeof workflowStages!=='function')return false;
const targets=[];
workflowStages(wf).forEach((column,x)=>column.forEach((node,y)=>{
const pos={x:80+x*320,y:80+y*190};
if(node.position?.x!==pos.x||node.position?.y!==pos.y)targets.push({node,pos});
}));
if(!targets.length)return false;
if(typeof flowHistory!=='undefined'&&flowHistory?.record)flowHistory.record();
targets.forEach(({node,pos})=>{
node.position=pos;
if(animate){
const el=flowNodeEl(node.id);
if(el){el.style.left=pos.x+'px';el.style.top=pos.y+'px'}
}
});
return true;
}
function fitCanvasOrDefer(){
if(typeof flowViewport==='undefined')return;
const canvas=$('#canvas');
if(!canvas||canvas.hidden||!canvas.clientWidth||!canvas.clientHeight){flowNeedsFitId=state.workflow?.id||null;return}
flowNeedsFitId=null;
flowViewport.fit();
}
function arrangeBeforeCommit(){
if(!state.workflow||(typeof flowReadOnly==='function'&&flowReadOnly(state.workflow)))return false;
if(!arrangeWorkflowNodes(state.workflow))return false;
if(typeof renderCanvas==='function')renderCanvas();
fitCanvasOrDefer();
return true;
}
function arrange(){
if(!state.workflow)return;
if(flowReadOnly())return toast(flowReadOnlyReason());
flowHistory.record();
const stage=$('#canvasStage');stage?.classList.add('anim','arranging');
workflowStages(state.workflow).forEach((column,x)=>column.forEach((node,y)=>{
node.position={x:80+x*320,y:80+y*190};
const el=flowNodeEl(node.id);if(el){el.style.left=node.position.x+'px';el.style.top=node.position.y+'px'}
}));
dirty();
setTimeout(()=>{stage?.classList.remove('arranging');renderCanvas();flowViewport.fit()},380);
flowToast('已按依赖层级整理画布',{undo:true});
const stage=$('#canvasStage');
const moved=arrangeWorkflowNodes(state.workflow,{animate:true});
if(moved){
stage?.classList.add('anim','arranging');
dirty();
setTimeout(()=>{stage?.classList.remove('arranging');renderCanvas();fitCanvasOrDefer()},380);
}else{
fitCanvasOrDefer();
}
flowToast('已按依赖层级整理画布',{undo:moved});
}
// Layouts saved for the narrower legacy node, or templates on a 240px column
// pitch, overlap the 244px node: the overlap hides the ports, so no reject
Expand Down Expand Up @@ -555,6 +589,8 @@ function setFlowView(mode){
$('#flowStageWrap')?.classList.toggle('check-mode',checking);
if(!checking){
flowViewport.afterRender();
if(flowNeedsFitId&&flowNeedsFitId===state.workflow?.id){flowNeedsFitId=null;flowViewport.fit({smooth:false})}
else flowNeedsFitId=null;
if($('#flowStageWrap')?.classList.contains('ai-open'))flowViewport.fitAfterDrawerChange();
return;
}
Expand Down Expand Up @@ -1463,6 +1499,7 @@ async function discardWorkflow(){
async function saveWorkflow(){
if(catalogGeneric(state.workflow)&&!isPlatformAdmin()){toast('通用模板为只读,请先「复制到本项目」再修改');throw new Error('generic LOOP is read-only')}
if(catalogForeign(state.workflow?.projectId)){toast('这是其他项目的共享 LOOP,请先复制到本项目再改');throw new Error('shared LOOP is read-only')}
if(state.workflow?.status==='archived'){const message=typeof flowReadOnlyReason==='function'?flowReadOnlyReason(state.workflow):'已归档的 LOOP 为只读';toast(message);throw new Error('archived LOOP is read-only')}
if(state.workflow?.preview?.enabled&&workflowPreviewExecutor(state.workflow)&&state.workflow.preview.model===''){
const workflow=state.workflow;
await loadExecutorModelCatalogs();
Expand All @@ -1478,7 +1515,8 @@ async function saveWorkflow(){
workflow.preview.model=model;
}
}
try{const saved=await api('/api/workflows',{method:'PUT',body:JSON.stringify(state.workflow)});state.workflow=clone(saved);const i=state.data.workflows.findIndex(w=>w.id===saved.id);if(i>=0)state.data.workflows[i]=clone(saved);else state.data.workflows.unshift(clone(saved));markWorkflowClean();renderWorkflowMeta();renderSOPCatalog();renderCanvas();renderProperties();toast('LOOP 草稿已保存');return saved}catch(e){if(e.message.includes('revision conflict')){if(state.workflow?.id)void syncWorkflowFromServer(state.workflow.id,{applyIfClean:false});toast('保存冲突:其他人已更新该 LOOP,请重新选择后合并')}else if(e.message!=='shared LOOP is read-only'&&e.message!=='generic LOOP is read-only')toast(e.message);throw e}}
const arranged=typeof arrangeBeforeCommit==='function'&&arrangeBeforeCommit();
try{const saved=await api('/api/workflows',{method:'PUT',body:JSON.stringify(state.workflow)});state.workflow=clone(saved);const i=state.data.workflows.findIndex(w=>w.id===saved.id);if(i>=0)state.data.workflows[i]=clone(saved);else state.data.workflows.unshift(clone(saved));markWorkflowClean();renderWorkflowMeta();renderSOPCatalog();renderCanvas();renderProperties();toast('LOOP 草稿已保存');return saved}catch(e){if(arranged&&typeof dirty==='function')dirty();if(e.message.includes('revision conflict')){if(state.workflow?.id)void syncWorkflowFromServer(state.workflow.id,{applyIfClean:false});toast('保存冲突:其他人已更新该 LOOP,请重新选择后合并')}else if(e.message!=='shared LOOP is read-only'&&e.message!=='generic LOOP is read-only'&&e.message!=='archived LOOP is read-only')toast(e.message);throw e}}
function sopSandboxChoices(){
return (state.data.sandboxes||[]).filter(s=>s.id&&catalogVisible(s.projectId,s.shared));
}
Expand Down Expand Up @@ -1648,14 +1686,18 @@ async function deleteWorkflow(id){
async function publishWorkflow(){
if(workflowPublishing||!workflowNeedsPublish())return;
if(catalogGeneric(state.workflow)&&!isPlatformAdmin())return toast('通用模板为只读,请先「复制到本项目」再发布');
if(catalogForeign(state.workflow?.projectId))return toast('这是其他项目的共享 LOOP,请先复制到本项目再改');
if(state.workflow?.status==='archived')return toast(typeof flowReadOnlyReason==='function'?flowReadOnlyReason(state.workflow):'已归档的 LOOP 为只读');
workflowPublishing=true;renderFlowHeader();
let arranged=false;
const id=state.workflow.id;
try{
const id=state.workflow.id;
if(state.workflowDirty||!state.workflow.revision)await saveWorkflow();
arranged=typeof arrangeBeforeCommit==='function'&&arrangeBeforeCommit();
if(state.workflowDirty||!state.workflow.revision||arranged)await saveWorkflow();
const published=await api(`/api/workflows/${encodeURIComponent(id)}/publish`,{method:'POST',body:'{}'});
const i=state.data.workflows.findIndex(w=>w.id===published.id);if(i>=0)state.data.workflows[i]=clone(published);
if(state.workflow?.id===id){state.workflow=clone(published);markWorkflowClean();renderWorkflowMeta()}
if(state.workflow?.id===id){state.workflow=clone(published);markWorkflowClean();renderWorkflowMeta();renderCanvas()}
renderSOPCatalog();toast(`已发布 v${published.version}`);
}catch(e){if(!e.message.includes('revision conflict'))toast(e.message)}
}catch(e){if(arranged&&state.workflow?.id===id&&!state.workflowDirty&&typeof dirty==='function')dirty();if(!e.message.includes('revision conflict'))toast(e.message)}
finally{workflowPublishing=false;renderFlowHeader()}
}
163 changes: 163 additions & 0 deletions webtest/tests/flows-editor.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -423,3 +423,166 @@ test('switching a routed script to repository scope clears its conditions after
assert.equal(app.evaluate(`flowHistory.undo()`), true);
assert.equal(app.evaluate(`!!state.workflow.edges[0].condition`), true);
});

test('saving after dragging flowchart nodes forces auto-arrange and fits the canvas before PUT', async (t) => {
const app = await loadApp();
t.after(app.close);
app.evaluate(`
switchView('flow');
Object.defineProperties($('#canvas'), {clientWidth:{value:960}, clientHeight:{value:540}});
state.workflow={id:'drag-save',projectId:'project-1',name:'Drag save',status:'draft',version:1,revision:1,
sandboxProfileId:'sandbox-1',nodes:[
{id:'a',name:'Plan',type:'script',script:'echo a',position:{x:80,y:80}},
{id:'b',name:'Build',type:'script',script:'echo b',position:{x:400,y:80}},
{id:'c',name:'Test',type:'script',script:'echo c',position:{x:400,y:270}}
],edges:[
{id:'e1',source:'a',target:'b',when:'success'},
{id:'e2',source:'a',target:'c',when:'success'}
]};
markWorkflowClean();renderAll();
`);

const nodeA = app.document.querySelector('#nodes .flow-node[data-id="a"]');
nodeA.setPointerCapture = () => {};
nodeA.dispatchEvent(new app.window.MouseEvent('pointerdown', { button: 0, clientX: 100, clientY: 100, bubbles: true }));
nodeA.dispatchEvent(new app.window.MouseEvent('pointermove', { button: 0, clientX: 700, clientY: 460, bubbles: true }));
nodeA.dispatchEvent(new app.window.MouseEvent('pointerup', { button: 0, clientX: 700, clientY: 460, bubbles: true }));
assert.notEqual(app.evaluate('state.workflow.nodes[0].position.x'), 80);
assert.equal(app.evaluate('state.workflowDirty'), true);

// Move b out of alignment as well, then save via the header Save button.
app.evaluate(`state.workflow.nodes[1].position={x:1200,y:900};renderCanvas()`);
app.router.put('/api/workflows', (call) => ({ status: 200, body: { ...call.body, revision: 2 } }));
app.document.querySelector('#saveWorkflow').click();
await new Promise((resolve) => setTimeout(resolve, 30));

const putCall = app.router.calls.find((c) => c.path === '/api/workflows' && c.method === 'PUT');
assert.ok(putCall);
assert.deepEqual(putCall.body.nodes.map((n) => n.position), [
{ x: 80, y: 80 },
{ x: 400, y: 80 },
{ x: 400, y: 270 },
]);
assert.equal(app.evaluate('state.workflowDirty'), false);
assert.equal(app.document.querySelector('#nodes .flow-node[data-id="a"]').style.left, '80px');
assert.equal(app.document.querySelector('#nodes .flow-node[data-id="b"]').style.left, '400px');
assert.ok(app.evaluate(`
state.workflow.nodes.every(node=>{
const {x,y,zoom}=flowViewport;
const left=node.position.x*zoom+x,top=node.position.y*zoom+y;
return left>=0&&left+244*zoom<=$('#canvas').clientWidth&&top>=0&&top+132*zoom<=$('#canvas').clientHeight;
})
`), 'auto-arranged nodes stay inside the visible canvas');
});

test('publishing forces auto-arrange and saves layout even on an unarranged clean draft', async (t) => {
const app = await loadApp();
t.after(app.close);
app.evaluate(`
switchView('flow');
state.workflow={id:'publish-arrange',projectId:'project-1',name:'Publish arrange',status:'draft',version:1,revision:2,
sandboxProfileId:'sandbox-1',nodes:[
{id:'b',name:'Second',type:'approval',position:{x:60,y:260}},
{id:'a',name:'First',type:'script',script:'echo ok',position:{x:580,y:40}}
],edges:[{id:'e1',source:'a',target:'b',when:'success'}]};
markWorkflowClean();renderAll();
`);
assert.equal(app.evaluate('state.workflowDirty'), false);
assert.equal(app.document.querySelector('#publishWorkflow').disabled, false);

app.router.put('/api/workflows', (call) => ({ status: 200, body: { ...call.body, revision: 3 } }));
app.router.post('/api/workflows/publish-arrange/publish', () => {
const lastPut = app.router.calls.filter((c) => c.path === '/api/workflows' && c.method === 'PUT').at(-1);
return { status: 200, body: { ...lastPut.body, status: 'published', version: 1, revision: 4, publishedRevision: 4 } };
});

app.document.querySelector('#publishWorkflow').click();
await new Promise((resolve) => setTimeout(resolve, 40));

const putCalls = app.router.calls.filter((c) => c.path === '/api/workflows' && c.method === 'PUT');
const publishCalls = app.router.calls.filter((c) => c.path === '/api/workflows/publish-arrange/publish');
assert.equal(putCalls.length, 1);
assert.equal(publishCalls.length, 1);
assert.deepEqual(putCalls[0].body.nodes.map((n) => [n.id, n.position]), [
['b', { x: 400, y: 80 }],
['a', { x: 80, y: 80 }],
]);
assert.equal(app.evaluate('state.workflow.status'), 'published');
assert.equal(app.evaluate('state.workflowDirty'), false);
});

test('failed save after auto-arrange preserves arranged canvas, keeps dirty state, and supports undo', async (t) => {
const app = await loadApp();
t.after(app.close);
app.evaluate(`
switchView('flow');
state.workflow={id:'fail-arrange',projectId:'project-1',name:'Fail arrange',status:'draft',version:1,revision:1,
sandboxProfileId:'sandbox-1',nodes:[
{id:'a',name:'First',type:'script',script:'echo 1',position:{x:520,y:320}},
{id:'b',name:'Second',type:'script',script:'echo 2',position:{x:10,y:40}}
],edges:[{id:'e1',source:'a',target:'b',when:'success'}]};
markWorkflowClean();flowHistory.clear();renderAll();
`);
app.router.put('/api/workflows', () => ({ status: 500, body: { error: 'save failed' } }));
await assert.rejects(() => app.evaluate('saveWorkflow()'));
assert.deepEqual(JSON.parse(app.evaluate('JSON.stringify(state.workflow.nodes.map(n=>n.position))')), [
{ x: 80, y: 80 },
{ x: 400, y: 80 },
]);
assert.equal(app.evaluate('state.workflowDirty'), true);
assert.equal(app.evaluate('flowHistory.undo()'), true);
assert.deepEqual(JSON.parse(app.evaluate('JSON.stringify(state.workflow.nodes.map(n=>n.position))')), [
{ x: 520, y: 320 },
{ x: 10, y: 40 },
]);
});

test('read-only workflows are not rearranged or mutated on save or publish attempts', async (t) => {
const app = await loadApp();
t.after(app.close);
app.evaluate(`
switchView('flow');
state.workflow={id:'ro-flow',projectId:'other-project',shared:true,name:'Shared RO',status:'draft',version:1,revision:1,
sandboxProfileId:'sandbox-1',nodes:[
{id:'a',name:'First',type:'script',script:'echo 1',position:{x:520,y:320}},
{id:'b',name:'Second',type:'script',script:'echo 2',position:{x:10,y:40}}
],edges:[{id:'e1',source:'a',target:'b',when:'success'}]};
markWorkflowClean();renderAll();
`);
await assert.rejects(() => app.evaluate('saveWorkflow()'), /shared LOOP is read-only/);
await app.evaluate('publishWorkflow()');
assert.deepEqual(JSON.parse(app.evaluate('JSON.stringify(state.workflow.nodes.map(n=>n.position))')), [
{ x: 520, y: 320 },
{ x: 10, y: 40 },
]);
assert.equal(app.router.calls.some((c) => c.path.includes('/api/workflows')), false);
});

test('saving from check view avoids clearing check panel and fits canvas on return', async (t) => {
const app = await loadApp();
t.after(app.close);
app.router.post('/api/runs/preflight', () => ({ workflowId: 'check-arrange', responsibleUser: 'Tester', repositories: [] }));
app.evaluate(`
switchView('flow');
Object.defineProperties($('#canvas'), {clientWidth:{value:900}, clientHeight:{value:500}});
state.workflow={id:'check-arrange',projectId:'project-1',name:'Check arrange',status:'draft',version:1,revision:1,
sandboxProfileId:'sandbox-1',nodes:[
{id:'a',name:'First',type:'script',script:'echo 1',position:{x:2000,y:1200}},
{id:'b',name:'Second',type:'script',script:'echo 2',position:{x:100,y:40}}
],edges:[{id:'e1',source:'a',target:'b',when:'success'}]};
state.workflowDirty=true;setFlowView('check');
`);
await new Promise((resolve) => setTimeout(resolve, 30));
const checkHeading = app.document.querySelector('#flowCheckPanel .flow-check-heading');
app.router.put('/api/workflows', (call) => ({ status: 200, body: { ...call.body, revision: 2 } }));
await app.evaluate('saveWorkflow()');
assert.equal(app.document.querySelector('#flowCheckPanel .flow-check-heading'), checkHeading);
app.evaluate(`setFlowView('canvas')`);
assert.ok(app.evaluate(`
state.workflow.nodes.every(node=>{
const {x,y,zoom}=flowViewport;
const left=node.position.x*zoom+x,top=node.position.y*zoom+y;
return left>=0&&left+244*zoom<=$('#canvas').clientWidth&&top>=0&&top+132*zoom<=$('#canvas').clientHeight;
})
`), 'returning to canvas fits the newly arranged nodes');
});
Loading