Files
order-notification-automation/tests/bpm/bpm-ui.test.cjs
T

367 lines
37 KiB
JavaScript

const {test,before,after}=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const http=require('node:http');
const path=require('node:path');
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
const {setTimeout:delay}=require('node:timers/promises');
async function waitUntil(predicate){const deadline=Date.now()+10000;while(!predicate()){assert.ok(Date.now()<deadline,'expected browser request did not arrive');await delay(25);}}
let browser,server,base,jpeg;
const source=path.join(__dirname,'../../web/modules/bpm/view.js');
const {connectionSnapshot}=require('../../src/modules/bpm/connection-status.cjs');
before(async()=>{
browser=await loadPlaywright().chromium.launch(browserOptions());
const page=await browser.newPage({viewport:{width:1280,height:800}});jpeg=await page.screenshot({type:'jpeg'});await page.close();
server=http.createServer((req,res)=>{res.setHeader('Content-Type','text/html');res.end('<div id="root"></div>');});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));base=`http://127.0.0.1:${server.address().port}`;
});
after(async()=>{await browser?.close();await new Promise(resolve=>server?.close(resolve));});
async function fixture(t,{user={username:'alice',role:'operator'},connections,account={configured:false,username:'',updatedAt:null},savedAccountConnection,holdAccount=false,holdAccountSave=false,holdFill=false,holdOpen=false,holdInput=false,holdFrame=false,holdSave=false}={}){
const page=await browser.newPage();t.after(()=>page.close());
const calls=[];let releaseOpen,releaseInput,releaseFrame,releaseSave,releaseAccount,releaseFill,releaseAccountSave;
const accountSaveGate=holdAccountSave?new Promise(r=>releaseAccountSave=r):Promise.resolve();
const accountGate=holdAccount?new Promise(r=>releaseAccount=r):Promise.resolve();
const fillGate=holdFill?new Promise(r=>releaseFill=r):Promise.resolve();
const openGate=holdOpen?new Promise(r=>releaseOpen=r):Promise.resolve();
const inputGate=holdInput?new Promise(r=>releaseInput=r):Promise.resolve();
const frameGate=holdFrame?new Promise(r=>releaseFrame=r):Promise.resolve();
const saveGate=holdSave?new Promise(r=>releaseSave=r):Promise.resolve();
let frameActive=0,maxFrames=0;
await page.route('**/api/**',async route=>{
const url=new URL(route.request().url()),body=route.request().postDataJSON();calls.push({path:url.pathname,body});
if(url.pathname.endsWith('/frame')){frameActive++;maxFrames=Math.max(maxFrames,frameActive);await frameGate;frameActive--;return route.fulfill({contentType:'image/jpeg',body:jpeg});}
let result={};
if(url.pathname.endsWith('/account')){await accountGate;if(body){await accountSaveGate;account={configured:true,username:body.username,updatedAt:'2026-10-16T00:00:00.000Z'};}result=body&&savedAccountConnection?{...account,connection:savedAccountConnection}:account;}
if(url.pathname.endsWith('/account/clear'))result=account={configured:false,username:'',updatedAt:null};
if(url.pathname.endsWith('/fill-account')){await fillGate;result={filled:true,message:'账号已填入。'};}
if(url.pathname==='/api/workspace')result={members:[{username:'alice',role:'operator'}],capabilities:{remoteLogin:true},connections:connections||[{id:'one',name:'业务连接',owner:'alice',status:'disconnected'}]};
if(url.pathname.endsWith('/open')){await openGate;result={active:true,viewport:{width:1280,height:800},expiresAt:new Date(Date.now()+600000).toISOString(),host:'bpmn.skyworthdigital.com'};}
if(url.pathname.endsWith('/input'))await inputGate;
if(url.pathname.endsWith('/save'))await saveGate;
if(url.pathname.endsWith('/save')||url.pathname.endsWith('/check'))result={connection:{id:'one',name:'业务连接',owner:'alice',status:'connected',identity:'Alice',checkedAt:new Date().toISOString(),checks:{portal:{ok:true,message:'已登录'}}}};
if(url.pathname.endsWith('/account/check'))result={available:body?.username!=='already-used'};
if(url.pathname.endsWith('/enable')||url.pathname.endsWith('/disable')){const id=url.pathname.split('/').at(-2),item=connections.find(c=>c.id===id);item.status=url.pathname.endsWith('/enable')?'unchecked':'disabled';item.version=(item.version||0)+1;result={...item};}
if(result.connections)result.connections=result.connections.map(c=>connectionSnapshot(c));
if(result.connection)result.connection=connectionSnapshot(result.connection);
if(result.id&&result.status)result=connectionSnapshot(result);
await route.fulfill({json:result});
});
await page.goto(base);
await page.addStyleTag({path:path.join(__dirname,'../../web/app.css')});
if(fs.existsSync(source))await page.addScriptTag({path:source});
assert.equal(await page.evaluate(()=>typeof window.BpmLogin?.mount),'function','BPM page exposes a working mount function');
await page.evaluate(async user=>{
const api=async(route,body)=>{const r=await fetch('/api'+route,{method:body===undefined?'GET':'POST',headers:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});return r.json();};
await window.BpmLogin.mount(document.querySelector('#root'),{api,esc:v=>String(v??'').replaceAll('<','&lt;'),formatDate:v=>v||'—',notify:()=>{},user,isActive:()=>true});
},user);
return {page,calls,releaseOpen,releaseInput,releaseFrame,releaseSave,releaseAccount,releaseFill,releaseAccountSave,maxFrames:()=>maxFrames};
}
test('admin can delete only disabled connections after explicit confirmation',async t=>{
const connections=[{id:'one',name:'已停用账号',owner:'alice',status:'disabled'},{id:'active',name:'使用中账号',owner:'alice',status:'connected'}];
const f=await fixture(t,{connections,user:{username:'boss',role:'admin'}});
const remove=f.page.getByRole('button',{name:'删除',exact:true});assert.equal(await remove.count(),1);
f.page.once('dialog',dialog=>dialog.dismiss());await remove.click();
assert.equal(f.calls.some(c=>c.path.endsWith('/delete')),false);
f.page.once('dialog',async dialog=>{assert.match(dialog.message(),/已停用账号/);assert.match(dialog.message(),/Cookie/);await dialog.accept();});
await remove.click();await f.page.getByText('连接已删除。',{exact:true}).waitFor();
assert.equal(await f.page.getByRole('heading',{name:'已停用账号',exact:true}).count(),0);
assert.equal(await f.page.getByRole('heading',{name:'使用中账号',exact:true}).count(),1);
assert.deepEqual(f.calls.filter(c=>c.path.endsWith('/delete')).map(c=>c.body),[{}]);
for(const role of ['operator','viewer']){const other=await fixture(t,{connections,user:{username:'alice',role}});assert.equal(await other.page.getByRole('button',{name:'删除',exact:true}).count(),0);}
});
test('auto-renew setup rejects a duplicate username before sending credentials and clears stale checks',async t=>{
const f=await fixture(t);
await f.page.getByRole('button',{name:'开启自动续登',exact:true}).click();
const username=f.page.getByLabel('BPM 账号',{exact:true}),password=f.page.getByLabel('托管密码',{exact:true});
await username.fill('already-used');await password.fill('not-submitted');
await f.page.getByText('该账号已开启自动续登,请使用已有连接。',{exact:true}).waitFor();
assert.equal(await username.evaluate(el=>el.validity.valid),false);
assert.equal(f.calls.some(c=>c.path.endsWith('/account')&&c.body),false);
await username.fill('available-user');await password.fill('new-secret');
await f.page.getByRole('button',{name:'保存账号',exact:true}).click();
await f.page.getByText('自动续登已开启。',{exact:true}).waitFor();
assert.equal(f.calls.filter(c=>c.path.endsWith('/account')&&c.body).length,1);
assert.equal(await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).count(),1);
});
test('portal login displays session, business and monitoring checks without legacy controls',async t=>{
const f=await fixture(t,{connections:[{id:'one',name:'新版 BPM',owner:'alice',status:'connected',checks:{portal:{ok:true,message:'新版已登录'}}}]});
await f.page.getByText('状态详情',{exact:true}).click();
assert.equal(await f.page.getByText('旧版入口',{exact:true}).count(),0);
assert.equal(await f.page.getByText('bpm.skyworthdigital.com',{exact:true}).count(),0);
assert.match(await f.page.locator('.bpm-checks').innerText(),/登录会话.*新版已登录/);
await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
assert.equal(await f.page.getByRole('button',{name:'旧版入口',exact:true}).count(),0);
await f.page.getByRole('button',{name:'新版门户',exact:true}).click();
await f.page.getByRole('button',{name:'刷新',exact:true}).click();
await f.page.getByRole('button',{name:'检查并保存',exact:true}).click();
await f.page.getByText('连接已检查并保存。',{exact:true}).waitFor();
assert.equal(await f.page.locator('[data-connection-status] .bpm-status-green').count(),1);
assert.match(await f.page.locator('.bpm-checks').innerText(),/登录会话.*已登录/);
assert.deepEqual(f.calls.filter(c=>c.path.endsWith('/navigate')).map(c=>c.body),[{target:'main'},{target:'reload'}]);
});
test('account management loads metadata only for enabled owner or admin connections',async t=>{
const connections=[{id:'mine',name:'我的连接',owner:'alice',status:'unchecked'},{id:'other',name:'其他连接',owner:'bob',status:'connected'},{id:'off',name:'停用连接',owner:'alice',status:'disabled'}];
const f=await fixture(t,{connections});
assert.equal(await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).count(),1);
await f.page.getByText('自动续登未开启',{exact:true}).waitFor();
assert.deepEqual(f.calls.filter(c=>c.path.endsWith('/account')).map(c=>c.path),['/api/connections/mine/account']);
const viewer=await fixture(t,{connections,user:{username:'alice',role:'viewer'}});
assert.equal(await viewer.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).count(),0);
assert.equal(viewer.calls.some(c=>c.path.endsWith('/account')),false);
const admin=await fixture(t,{connections,user:{username:'boss',role:'admin'}});
assert.equal(await admin.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).count(),2);
});
test('account editor saves exact credentials, clears secret input, requires fresh password and explicitly clears custody',async t=>{
const f=await fixture(t,{account:{configured:true,username:'saved-user',updatedAt:'2026-10-16T00:00:00.000Z'}});
await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).click();
const username=f.page.getByLabel('BPM 账号',{exact:true}),password=f.page.getByLabel('托管密码',{exact:true});
await username.waitFor();assert.equal(await username.inputValue(),'saved-user');
assert.equal(await password.getAttribute('type'),'password');assert.equal(await password.getAttribute('autocomplete'),'new-password');assert.equal(await password.inputValue(),'');
await username.fill('new-user');await f.page.getByRole('button',{name:'保存账号',exact:true}).click();
assert.equal(f.calls.filter(c=>c.path.endsWith('/account')&&c.body).length,0);
await password.fill(' secret-value ');await f.page.getByRole('button',{name:'保存账号',exact:true}).click();
await f.page.getByText('自动续登已开启。',{exact:true}).waitFor();
assert.deepEqual(f.calls.find(c=>c.path.endsWith('/account')&&c.body).body,{username:'new-user',password:' secret-value '});
assert.equal(await f.page.locator('input[type=password]').evaluateAll(inputs=>inputs.some(input=>input.value!=='')),false);
assert.equal(await f.page.locator('#root').textContent().then(s=>s.includes('secret-value')),false);
assert.equal(await f.page.evaluate(()=>localStorage.length),0);
await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).click();
assert.equal(await password.inputValue(),'');assert.equal(await password.getAttribute('placeholder'),'输入新密码以更新');
await f.page.getByRole('button',{name:'关闭自动续登',exact:true}).click();await f.page.getByText('自动续登未开启',{exact:true}).waitFor();
assert.deepEqual(f.calls.find(c=>c.path.endsWith('/account/clear')).body,{});
await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
assert.equal(await f.page.getByRole('button',{name:'填入托管账号',exact:true}).count(),0);
});
test('saving a replacement account blocks new remote control and shows the automatically connected identity',async t=>{
const f=await fixture(t,{holdAccountSave:true,savedAccountConnection:{id:'one',name:'业务连接',owner:'alice',status:'connected',identity:'replacement',checkedAt:new Date().toISOString(),checks:{portal:{ok:true,message:'已登录'}}},connections:[{id:'one',name:'业务连接',owner:'alice',status:'connected',identity:'old-user',checkedAt:'2026-10-15T00:00:00.000Z',checks:{portal:{ok:true,message:'已登录'}}}]});
await f.page.setViewportSize({width:360,height:800});await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).click();
await f.page.getByLabel('BPM 账号',{exact:true}).fill('replacement');await f.page.getByLabel('托管密码',{exact:true}).fill('replacement-secret');
assert.equal(await f.page.evaluate(()=>document.documentElement.scrollWidth<=window.innerWidth),true);
await f.page.getByRole('button',{name:'保存账号',exact:true}).click();
assert.equal(await f.page.getByRole('button',{name:'远程登录',exact:true}).isDisabled(),true);
await f.page.locator('[data-account-form]').evaluate(form=>form.dispatchEvent(new Event('submit',{bubbles:true,cancelable:true})));
await f.page.waitForTimeout(50);assert.equal(f.calls.filter(c=>c.path.endsWith('/account')&&c.body).length,1);
f.releaseAccountSave();await f.page.getByText('登录账号 replacement',{exact:true}).waitFor();
assert.equal(await f.page.locator('[data-connection-status] .bpm-status-green').count(),1);
assert.equal(await f.page.getByText('登录账号 old-user',{exact:true}).count(),0);
assert.equal(await f.page.getByText('上次检查 2026-10-15T00:00:00.000Z',{exact:true}).count(),0);
assert.equal(await f.page.getByRole('button',{name:'远程登录',exact:true}).isEnabled(),true);
await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).click();await f.page.getByLabel('托管密码',{exact:true}).fill('unsaved');
await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
assert.equal(await f.page.getByRole('button',{name:'保存账号',exact:true}).count(),0);
assert.equal(await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).isDisabled(),true);
});
test('account fill drains queued input and disposal waits for its operation before closing',async t=>{
const f=await fixture(t,{holdInput:true,holdFill:true,account:{configured:true,username:'saved-user',updatedAt:'2026-10-16T00:00:00.000Z'}});
await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
await f.page.locator('[data-bpm-input]').evaluate(el=>el.dispatchEvent(new InputEvent('input',{data:'x',bubbles:true})));
await f.page.getByRole('button',{name:'填入托管账号',exact:true}).click();
assert.equal(f.calls.some(c=>c.path.endsWith('/fill-account')),false);
assert.equal(await f.page.getByRole('button',{name:'检查并保存',exact:true}).isDisabled(),true);
f.releaseInput();await f.page.waitForFunction(()=>document.querySelector('[data-bpm-input]').disabled);await waitUntil(()=>f.calls.some(c=>c.path.endsWith('/fill-account')));
assert.deepEqual(f.calls.find(c=>c.path.endsWith('/fill-account'))?.body,{});
await f.page.evaluate(()=>{window.BpmLogin.dispose();});
assert.equal(f.calls.some(c=>c.path.endsWith('/close')),false);
f.releaseFill();await waitUntil(()=>f.calls.some(c=>c.path.endsWith('/close')));
assert.equal(f.calls.filter(c=>c.path.endsWith('/close')).length,1);
});
test('late account metadata cannot mount an editor after leaving the BPM page',async t=>{
const f=await fixture(t,{holdAccount:true});await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).click();
await f.page.evaluate(()=>{window.BpmLogin.dispose();document.querySelector('#root').innerHTML='<p>其他页面</p>';});
f.releaseAccount();await f.page.waitForTimeout(100);
assert.equal(await f.page.getByLabel('托管密码',{exact:true}).count(),0);assert.equal(await f.page.locator('#root').textContent(),'其他页面');
});
test('scaled clicks, IME, paste and editing keys reach the remote browser in order before save',async t=>{
const f=await fixture(t,{holdInput:true});await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
const image=f.page.locator('[data-bpm-frame]');await image.waitFor({state:'visible'});
await image.evaluate(el=>{el.style.width='640px';el.style.height='400px';});
await image.click({position:{x:320,y:200}});
await f.page.locator('[data-bpm-input]').evaluate(el=>{
el.dispatchEvent(new CompositionEvent('compositionstart',{bubbles:true}));
el.value='中文';el.dispatchEvent(new InputEvent('input',{data:'中文',inputType:'insertCompositionText',isComposing:true,bubbles:true}));
el.dispatchEvent(new CompositionEvent('compositionend',{data:'中文',bubbles:true}));
el.dispatchEvent(new InputEvent('input',{data:'中文',inputType:'insertText',bubbles:true}));
const clipboardData=new DataTransfer();clipboardData.setData('text/plain','paste secret');el.dispatchEvent(new ClipboardEvent('paste',{clipboardData,bubbles:true,cancelable:true}));
el.dispatchEvent(new KeyboardEvent('keydown',{key:'Backspace',bubbles:true,cancelable:true}));
el.dispatchEvent(new KeyboardEvent('keydown',{key:'Tab',bubbles:true,cancelable:true}));
});
await f.page.getByRole('button',{name:'检查并保存',exact:true}).click();
assert.equal(f.calls.filter(c=>c.path.endsWith('/input')).length,1);
assert.equal(f.calls.some(c=>c.path.endsWith('/save')),false);
f.releaseInput();await f.page.getByText('连接已检查并保存。',{exact:true}).waitFor();
const actions=f.calls.filter(c=>c.path.endsWith('/input')).map(c=>c.body);
// Browser click coordinates round to whole CSS pixels: at half scale, allow two remote pixels.
assert.equal(actions[0].type,'click');assert.ok(Math.abs(actions[0].x-640)<=2,JSON.stringify(actions[0]));assert.ok(Math.abs(actions[0].y-400)<=2,JSON.stringify(actions[0]));
assert.deepEqual(actions.slice(1),[{type:'text',text:'中文'},{type:'text',text:'paste secret'},{type:'key',key:'Backspace'},{type:'key',key:'Tab'}]);
assert.ok(f.calls.findIndex(c=>c.path.endsWith('/save'))>f.calls.map(c=>c.path).lastIndexOf('/api/connections/one/login/input'));
assert.equal(await f.page.locator('[data-bpm-input]').inputValue(),'');
assert.equal(await f.page.evaluate(()=>localStorage.length),0);
});
test('remote surface forwards physical keyboard events without relying on a hidden editable element',async t=>{
const f=await fixture(t);await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
await f.page.locator('[data-bpm-frame]').waitFor({state:'visible'});
const surface=f.page.locator('.bpm-screen');
await surface.focus();await f.page.keyboard.type('Ab-1');await f.page.keyboard.press('Backspace');
await f.page.getByRole('button',{name:'检查并保存',exact:true}).click();await f.page.getByText('连接已检查并保存。',{exact:true}).waitFor();
assert.deepEqual(f.calls.filter(c=>c.path.endsWith('/input')).map(c=>c.body),[{type:'text',text:'A'},{type:'text',text:'b'},{type:'text',text:'-'},{type:'text',text:'1'},{type:'key',key:'Backspace'}]);
const keyboard=f.page.getByLabel('远程登录输入',{exact:true});
const screenBounds=await surface.boundingBox(),bounds=await keyboard.boundingBox();
assert.ok(bounds.y>=screenBounds.y && bounds.y+bounds.height<=screenBounds.y+screenBounds.height,'IME capture stays inside the remote picture, with no input field below it');
assert.equal(await keyboard.evaluate(el=>getComputedStyle(el).opacity),'0','typing must not expose a second editor');
await f.page.locator('[data-bpm-frame]').click({position:{x:110,y:90}});
await f.page.keyboard.type('xy');await f.page.keyboard.press('Tab');await f.page.keyboard.insertText('中文输入');
await f.page.getByRole('button',{name:'检查并保存',exact:true}).click();
await f.page.waitForFunction(()=>document.querySelector('[data-bpm-input]')?.value==='');
assert.equal(f.calls.filter(c=>c.body?.type==='text'&&c.body.text==='中文输入').length,1);
assert.deepEqual(f.calls.filter(c=>c.path.endsWith('/input')).slice(6).map(c=>c.body),[{type:'text',text:'x'},{type:'text',text:'y'},{type:'key',key:'Tab'},{type:'text',text:'中文输入'}]);
});
test('disposal during a pending open closes the late lease without mounting a frame',async t=>{
const f=await fixture(t,{holdOpen:true});await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
await f.page.waitForFunction(()=>document.querySelector('button[data-login]')?.disabled);
await f.page.evaluate(()=>{window.BpmLogin.dispose();});f.releaseOpen();
await f.page.waitForTimeout(150);
assert.equal(f.calls.filter(c=>c.path.endsWith('/close')).length,1);
assert.equal(f.calls.filter(c=>c.path.endsWith('/frame')).length,0);
});
test('frame polling never overlaps and disposal stops polling and revokes the displayed URL',async t=>{
const f=await fixture(t,{holdFrame:true});
await f.page.evaluate(()=>{window.revoked=[];const revoke=URL.revokeObjectURL.bind(URL);URL.revokeObjectURL=u=>{window.revoked.push(u);revoke(u);};});
await f.page.getByRole('button',{name:'远程登录',exact:true}).click();await f.page.waitForTimeout(1200);
assert.equal(f.calls.filter(c=>c.path.endsWith('/frame')).length,1);assert.equal(f.maxFrames(),1);
f.releaseFrame();await f.page.waitForFunction(()=>document.querySelector('[data-bpm-frame]')?.src.startsWith('blob:'));
await f.page.evaluate(()=>window.BpmLogin.dispose());const count=f.calls.filter(c=>c.path.endsWith('/frame')).length;
await f.page.waitForTimeout(800);assert.equal(f.calls.filter(c=>c.path.endsWith('/frame')).length,count);
assert.ok((await f.page.evaluate(()=>window.revoked)).length>=1);
});
test('only the connection owner operator can login and check; admin creation remains separate',async t=>{
const connections=[{id:'mine',name:'我的连接',owner:'alice',status:'unchecked'},{id:'other',name:'其他连接',owner:'bob',status:'connected'},{id:'off',name:'停用连接',owner:'alice',status:'disabled'}];
const f=await fixture(t,{connections});
assert.equal(await f.page.getByRole('button',{name:'远程登录',exact:true}).count(),1);
assert.equal(await f.page.getByRole('button',{name:'检查连接',exact:true}).count(),1);
assert.equal(await f.page.getByRole('button',{name:'创建连接',exact:true}).count(),0);
assert.equal(await f.page.getByRole('button',{name:'停用连接',exact:true}).count(),0);
const viewer=await fixture(t,{connections,user:{username:'alice',role:'viewer'}});
assert.equal(await viewer.page.getByRole('button',{name:'远程登录',exact:true}).count(),0);
});
test('leaving during save waits for verification before releasing the browser',async t=>{
const f=await fixture(t,{holdSave:true});await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
await f.page.getByRole('button',{name:'检查并保存',exact:true}).click();
await f.page.waitForTimeout(70);await f.page.evaluate(()=>{window.BpmLogin.dispose();});
await f.page.waitForTimeout(100);assert.equal(f.calls.filter(c=>c.path.endsWith('/close')).length,0);
f.releaseSave();await f.page.waitForTimeout(150);assert.equal(f.calls.filter(c=>c.path.endsWith('/close')).length,1);
});
test('narrow screens keep the frame inside the page and native typing forwards text once',async t=>{
const f=await fixture(t);await f.page.setViewportSize({width:360,height:800});
await f.page.getByRole('button',{name:'远程登录',exact:true}).click();
const frame=f.page.locator('[data-bpm-frame]');await frame.waitFor({state:'visible'});await frame.click({position:{x:50,y:50}});
await f.page.keyboard.type('abc');await f.page.keyboard.press('Backspace');await f.page.keyboard.press('Tab');
await f.page.getByRole('button',{name:'检查并保存',exact:true}).click();await f.page.getByText('连接已检查并保存。',{exact:true}).waitFor();
assert.deepEqual(f.calls.filter(c=>c.body?.type==='text').map(c=>c.body.text),['a','b','c']);
assert.ok(await f.page.evaluate(()=>document.documentElement.scrollWidth<=window.innerWidth));
});
test('refresh and logout release BPM control before rendering or dropping authentication',async()=>{
const vm=require('node:vm'),events=[],elements=new Map();
const element=id=>{if(!elements.has(id))elements.set(id,{innerHTML:'',textContent:'',classList:{remove(){}},querySelector(){return {disabled:false};}});return elements.get(id);};
const context=vm.createContext({Intl,setTimeout,clearInterval,location:{hash:'#overview'},history:{replaceState(){}},document:{querySelector:element,querySelectorAll:()=>[],addEventListener(){}},window:{addEventListener(){},PageLifecycle:{guard:fn=>fn(),dispose:async()=>{},attach(){},bind(){}},AppNavigation:{primary:[],resolve:id=>id,sectionFor:()=>null,renderTabs(){},isConfiguration:()=>false},BpmLogin:{dispose:async()=>events.push('release')},OrderNotificationViews:{render:async()=>events.push('render')}}});
const source=fs.readFileSync(path.join(__dirname,'../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
vm.runInContext(fs.readFileSync(path.join(__dirname,'../../web/modules/records/state.js'),'utf8'),context);
vm.runInContext(source,context);
await vm.runInContext("currentUser={username:'alice',role:'admin'};renderView()",context);
assert.deepEqual(events,['release','render']);events.length=0;
vm.runInContext("shell();api=async route=>events.push(route);boot=async()=>{}",Object.assign(context,{events}));
await element('#logout').onclick();assert.deepEqual(events,['release','/logout']);
});
test('an expired login request rejects without waiting on its own remote cleanup',async()=>{
const vm=require('node:vm'),events=[];
const context=vm.createContext({Intl,setTimeout,clearTimeout,AbortController,AbortSignal,fetch:async()=>({status:401,ok:false,json:async()=>({error:'请重新登录。'})}),document:{querySelector:()=>({}),addEventListener(){}},window:{addEventListener(){},BpmLogin:{dispose:()=>new Promise(()=>{})}},events});
const source=fs.readFileSync(path.join(__dirname,'../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');vm.runInContext(source,context);
const pending=vm.runInContext("currentUser={username:'alice',role:'operator'};boot=async()=>events.push('login');api('/connections/one/login/open',{}).then(()=> 'resolved',()=> 'rejected')",context);
assert.equal(await Promise.race([pending,new Promise(resolve=>setTimeout(()=>resolve('pending'),100))]),'rejected');assert.deepEqual(events,['login']);
});
for(const pendingAction of ['open','save'])test(`document unload sends authenticated close while ${pendingAction} is pending`,async t=>{
const calls=[];let finishPending=()=>{},pendingStarted;
const started=new Promise(resolve=>pendingStarted=resolve);
const appSource=fs.readFileSync(path.join(__dirname,'../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
const fixtureServer=http.createServer(async(req,res)=>{
const requestPath=new URL(req.url,'http://localhost').pathname;
if(requestPath==='/bpm.js'||requestPath==='/app.js'){res.setHeader('Content-Type','application/javascript; charset=utf-8');return res.end(requestPath==='/bpm.js'?fs.readFileSync(source):appSource);}
if(!requestPath.startsWith('/api/')){res.setHeader('Content-Type','text/html; charset=utf-8');return res.end('<div id="app"></div><div id="root"></div><script src="/bpm.js"></script><script src="/app.js"></script>');}
let body='';for await(const chunk of req)body+=chunk;
calls.push({path:requestPath,body,cookie:req.headers.cookie,origin:req.headers.origin});
res.setHeader('Content-Type','application/json');
if(requestPath.endsWith('/'+pendingAction)){finishPending=()=>res.end('{}');pendingStarted();return;}
if(requestPath.endsWith('/frame')){res.setHeader('Content-Type','image/jpeg');return res.end(jpeg);}
if(requestPath.endsWith('/open'))return res.end(JSON.stringify({active:true,viewport:{width:1280,height:800},expiresAt:new Date(Date.now()+600000).toISOString(),host:'bpmn.skyworthdigital.com'}));
if(requestPath==='/api/workspace')return res.end(JSON.stringify({members:[],capabilities:{remoteLogin:true},connections:[{id:'one',name:'业务连接',owner:'alice',status:'disconnected'}]}));
res.end('{}');
});
await new Promise(resolve=>fixtureServer.listen(0,'127.0.0.1',resolve));
const fixtureBase=`http://127.0.0.1:${fixtureServer.address().port}`;
const page=await browser.newPage();t.after(async()=>{finishPending();await page.close();fixtureServer.closeAllConnections();await new Promise(resolve=>fixtureServer.close(resolve));});
await page.context().addCookies([{name:'session',value:'fixture-session',url:fixtureBase}]);await page.goto(fixtureBase);
await page.evaluate(async()=>window.BpmLogin.mount(document.querySelector('#root'),{api,esc:v=>String(v??''),formatDate:v=>v||'—',notify:()=>{},user:{username:'alice',role:'operator'},isActive:()=>true}));
await page.getByRole('button',{name:'远程登录',exact:true}).click();
if(pendingAction==='save')await page.getByRole('button',{name:'检查并保存',exact:true}).click();
await started;await page.goto(fixtureBase+'/exit');
const deadline=Date.now()+700;while(!calls.some(c=>c.path.endsWith('/close'))&&Date.now()<deadline)await new Promise(resolve=>setTimeout(resolve,20));
const close=calls.find(c=>c.path.endsWith('/close'));assert.ok(close,'unload must dispatch close before the held request completes');
assert.equal(close.body,'{}');assert.match(close.cookie,/session=fixture-session/);assert.equal(close.origin,fixtureBase);
});
test('admin pauses and resumes using explicit buttons and the current version',async t=>{const f=await fixture(t,{user:{username:'admin',role:'admin'},connections:[{id:'toggle',name:'可恢复连接',owner:'alice',status:'connected',version:4,identity:'fixture'}]});await f.page.getByRole('button',{name:'停用连接',exact:true}).click();await f.page.getByRole('button',{name:'启用连接',exact:true}).waitFor();assert.equal(await f.page.getByRole('button',{name:'检查连接',exact:true}).count(),0);assert.deepEqual(f.calls.find(c=>c.path.endsWith('/disable')).body,{version:4});await f.page.getByRole('button',{name:'启用连接',exact:true}).click();await f.page.getByRole('button',{name:'停用连接',exact:true}).waitFor();assert.deepEqual(f.calls.find(c=>c.path.endsWith('/enable')).body,{version:5});assert.equal(await f.page.getByRole('switch').count(),0);});
test('connection cards distinguish authenticated session, todo permission and passive-listener status',async t=>{const f=await fixture(t,{connections:[{id:'one',name:'分层检测',owner:'alice',status:'connected',health:{portal:{status:'healthy',checkedAt:new Date().toISOString()},todo:{status:'forbidden',checkedAt:new Date().toISOString()}},monitoring:{status:'listening',lastSyncAt:new Date().toISOString()}}]});await f.page.getByText('状态详情',{exact:true}).click();await f.page.getByText('订单接口 · 无读取权限',{exact:false}).waitFor();await f.page.getByText('到达监听 · 推送已连接',{exact:false}).waitFor();await f.page.getByRole('button',{name:'开启自动续登',exact:true}).click();await f.page.getByLabel('BPM 账号',{exact:true}).fill('not-yet-saved');await new Promise(r=>setTimeout(r,5200));assert.equal(await f.page.getByLabel('BPM 账号',{exact:true}).inputValue(),'not-yet-saved');});
test('a delayed background snapshot cannot resurrect a connection after deletion',async t=>{
const connection={id:'off',name:'旧连接',owner:'alice',status:'disabled',version:1},f=await fixture(t,{user:{username:'admin',role:'admin'},connections:[connection]});let arrive,release;const arrived=new Promise(r=>arrive=r),gate=new Promise(r=>release=r);
await f.page.route('**/api/workspace',async route=>{arrive();await gate;await route.fulfill({json:{connections:[connection],capabilities:{remoteLogin:true}}});});await arrived;f.page.once('dialog',dialog=>dialog.accept());await f.page.getByRole('button',{name:'删除',exact:true}).click();await f.page.getByText('连接已删除。',{exact:true}).waitFor();const response=f.page.waitForResponse(r=>r.url().endsWith('/api/workspace'));release();await response;await f.page.waitForTimeout(100);assert.equal(await f.page.getByRole('heading',{name:'旧连接',exact:true}).count(),0);
});
test('source read state and local delivery are separate and handover uses connection version',async t=>{
const connection={id:'one',name:'隔离监听连接',owner:'boss',version:7,status:'connected',monitoring:{status:'listening',nextReconcileAt:'2026-10-21T10:00:00Z',sources:{todo:{status:'healthy',lastSuccessAt:'2026-10-21T09:00:00Z'},inform:{status:'failed',lastFailureAt:'2026-10-21T09:01:00Z',retryAt:'2026-10-21T09:02:00Z'}},delivery:{status:'retrying',pending:2,message:'隔离本地投递失败'}}};
const f=await fixture(t,{user:{username:'boss',role:'admin'},connections:[connection]});await f.page.getByText('状态详情',{exact:true}).click();await f.page.getByText(/待办源读取 · healthy/).waitFor();await f.page.getByText(/通知源读取 · failed/).waitFor();await f.page.getByText(/本地执行器投递 · retrying · 待交付 2/).waitFor();let submitted;
await f.page.route('**/api/connections/one/owner',route=>{submitted=route.request().postDataJSON();return route.fulfill({json:{connection:{...connection,owner:'alice',status:'disabled',version:8},cleanupPending:false}});});
await f.page.locator('[data-owner-transfer] select').selectOption('alice');await f.page.getByRole('button',{name:'确认转交',exact:true}).click();await f.page.getByRole('button',{name:'启用连接',exact:true}).waitFor();assert.deepEqual(submitted,{version:7,owner:'alice'});assert.match(await f.page.locator('[data-bpm-feedback]').innerText(),/连接已暂停/);
});
test('account traffic lights summarize errors, warnings and complete health with collapsed diagnostics',async t=>{
const now=new Date().toISOString(),good={status:'connected',health:{portal:{status:'healthy',checkedAt:now},todo:{status:'healthy',checkedAt:now}},monitoring:{status:'listening',sources:{todo:{status:'healthy',lastSuccessAt:now},inform:{status:'healthy',lastSuccessAt:now}},delivery:{status:'healthy',pending:0}}};
const cases=[
['健康',good,'green','green'],
['首次读取',{...good,monitoring:{...good.monitoring,sources:{todo:{status:'pending'},inform:{status:'pending'}}}},'green','yellow'],
['读取失败',{...good,monitoring:{...good.monitoring,sources:{todo:{status:'healthy'},inform:{status:'failed'}}}},'green','red'],
['会话过期',{...good,health:{...good.health,portal:{status:'login_required',checkedAt:now}}},'red','red'],
['检查过期',{...good,health:{...good.health,portal:{status:'healthy',checkedAt:'2020-01-01T00:00:00Z'}}},'yellow','green'],
['重连',{...good,monitoring:{...good.monitoring,status:'reconnecting'}},'green','yellow'],
['投递失败',{...good,monitoring:{...good.monitoring,delivery:{status:'error',pending:1}}},'green','red'],
['未检查',{status:'unchecked'},'yellow','yellow'],
['已停用',{...good,status:'disabled'},'yellow','yellow']
];
const f=await fixture(t,{connections:cases.map(([name,value],i)=>({...value,id:String(i),name,owner:'alice'}))});
for(const [i,[, ,color,syncColor]] of cases.entries()){
const card=f.page.locator('article').nth(i);
assert.equal(await card.locator('[data-connection-status] .bpm-status-'+color).count(),1);
assert.equal(await card.locator('[data-sync-status] .bpm-status-'+syncColor).count(),1);
assert.equal(await card.locator('details').getAttribute('open'),null);
assert.equal(await card.getByText('待办源读取最近失败',{exact:false}).isVisible(),false);
}
const first=f.page.locator('article').first();
await first.getByText('状态详情',{exact:true}).click();
assert.equal(await first.getByText('待办源读取最近失败',{exact:false}).isVisible(),true);
await f.page.waitForTimeout(5300);
assert.notEqual(await first.locator('details').getAttribute('open'),null,'polling preserves expanded diagnostics');
assert.equal(f.calls.some(c=>c.body),false,'status display only reads state');
});
test('UI renders backend conclusions without reinterpreting raw connection flags',async t=>{
const c={id:'one',name:'后端结论',owner:'alice',status:'error',health:{portal:{status:'login_required'}},connectionState:{account:{status:'healthy',color:'green',label:'健康',message:'后端已核实会话'},sync:{status:'pending',color:'yellow',label:'警告',message:'等待后端对账'}}};
const f=await fixture(t,{connections:[]});
await f.page.route('**/api/workspace',route=>route.fulfill({json:{connections:[c],capabilities:{remoteLogin:true},members:[]}}));
await f.page.waitForTimeout(5300);
assert.equal(await f.page.locator('[data-connection-status] .bpm-status-green').count(),1);
assert.equal(await f.page.locator('[data-sync-status] .bpm-status-yellow').count(),1);
await f.page.getByText('后端已核实会话',{exact:true}).waitFor();
});