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(){ 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('
');}); 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};} 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('<','<'),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:'新版已登录'}}}]}); 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.getByText('已连接',{exact:true}).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:'2026-10-16T01:00:00.000Z',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.getByText('已连接',{exact:true}).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='

其他页面

';}); 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')},WorkspaceViews:{overview:async()=>events.push('render')}}}); const source=fs.readFileSync(path.join(__dirname,'../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,''); 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('
');} 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()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: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); });