feat: unify BPM health and guard session recovery with state machines

This commit is contained in:
阿白叔 committed 2026-10-24 14:49:15 +08:00
1 parent 97e06328c3
commit 42d19c707d
23 files changed
+681 -90

No files matched your search

+27
View File
@@ -0,0 +1,27 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {workspaceApi}=require('../../src/modules/workspace/api.cjs');
const {RuntimeHealth}=require('../../src/modules/health/runtime-health.cjs');
test('workspace and health share independent account and sync conclusions, respect cadence and ownership without probes',async t=>{
const now=Date.now(),at=new Date(now).toISOString(),old=new Date(now-12*60000).toISOString();
const connection={id:'mine',owner:'worker',name:'业务连接',status:'connected',checkedAt:at,checks:{portal:{ok:true}}};
const workspace={snapshot:()=>({connections:[connection,{...connection,id:'other',owner:'other',name:'PRIVATE_OTHER'}],capabilities:{}})};
const manager={health:{freshMs:300000,snapshot:()=>({portal:{status:'healthy',checkedAt:at}})},ensure:()=>assert.fail('status must not authenticate')};
const config={enabled:true,intervalMinutes:10};
const monitoring={status:'listening',sources:{todo:{status:'running',lastSuccessAt:old},inform:{status:'healthy',lastSuccessAt:at}},delivery:{status:'error',pending:1}};
const monitor={snapshot:()=>monitoring,scanner:{store:{config:()=>config}}};
let response;await workspaceApi({workspace,store:{users:()=>[]},user:{username:'worker',role:'operator'},route:'/api/workspace',method:'GET',bpmSessions:manager,bpmMonitor:monitor,reply:(code,value)=>{assert.equal(code,200);response=value;}});
assert.equal(response.connections[0].connectionState.account.status,'healthy');
assert.equal(response.connections[0].connectionState.sync.reason,'DELIVERY_FAILED');
const stateDir=fs.mkdtempSync(path.join(os.tmpdir(),'connection-status-'));
const health=new RuntimeHealth({stateDir,clock:()=>now,workspace,bpmSessions:manager,monitor,scanner:{store:{status:()=>({config,runs:[]})}}});
t.after(()=>{health.close();fs.rmSync(stateDir,{recursive:true,force:true});});
let snapshot=health.snapshot({username:'worker',role:'operator'});
assert.equal(snapshot.groups.find(g=>g.key==='bpm').items[0].status,'healthy');
const sync=snapshot.groups.find(g=>g.key==='bpm-sync');assert.equal(sync.items[0].reason,'DELIVERY_FAILED');assert.equal(sync.items.length,1);
assert.doesNotMatch(JSON.stringify(snapshot),/PRIVATE_OTHER/);
monitoring.delivery={status:'healthy',pending:0};
snapshot=health.snapshot({role:'admin'});assert.equal(snapshot.groups.find(g=>g.key==='bpm-sync').items[0].status,'healthy');
config.intervalMinutes=1;
snapshot=health.snapshot({role:'admin'});assert.equal(snapshot.groups.find(g=>g.key==='bpm-sync').items[0].reason,'SOURCE_STALE');
});
+1 -1
View File
@@ -6,7 +6,7 @@ test('health keeps success/failure history across restart, filters BPM ownership
const connections=[{id:'mine',name:'我的连接',owner:'worker',status:'connected',checkedAt:'2026-10-18T01:00:00Z',lastConnectedAt:'2026-10-18T01:00:00Z',password:'PRIVATE'},{id:'other',name:'PRIVATE_OTHER',owner:'other',status:'connected'}];
const deps={stateDir,workspace:{snapshot:()=>({connections})},scanner:{store:{status:()=>({config:{enabled:false},runs:[{connectionId:'mine',status:'error',finishedAt:'2026-10-18T02:00:00Z'}]})},scan:()=>assert.fail('must not scan')},storage:{store:{servers:()=>[{id:'s',name:'共享',enabled:true,state:{checkedAt:'2026-10-18T01:00:00Z',readable:true,writable:true,message:'password=PRIVATE C:/PRIVATE/file'}}]},check:()=>assert.fail('must not write/check')},mail:{store:{channels:()=>[]},verify:()=>assert.fail('must not verify/send')}};
health=new RuntimeHealth(deps);let data=health.snapshot({username:'worker',role:'operator'});assert.doesNotMatch(JSON.stringify(data),/PRIVATE|OTHER/);assert.equal(data.groups.find(g=>g.key==='bpm').items.length,1);assert.equal(data.groups.find(g=>g.key==='mail').status,'unconfigured');
connections[0].status='error';connections[0].checkedAt='2026-10-18T03:00:00Z';data=health.snapshot({username:'worker',role:'operator'});const item=data.groups.find(g=>g.key==='bpm').items[0];assert.equal(item.status,'error');assert.equal(item.lastSuccessAt,'2026-10-18T01:00:00.000Z');assert.equal(item.lastFailureAt,'2026-10-18T03:00:00.000Z');
connections[0].status='login_required';connections[0].checkedAt='2026-10-18T03:00:00Z';data=health.snapshot({username:'worker',role:'operator'});const item=data.groups.find(g=>g.key==='bpm').items[0];assert.equal(item.status,'error');assert.equal(item.lastSuccessAt,'2026-10-18T01:00:00.000Z');assert.equal(item.lastFailureAt,'2026-10-18T03:00:00.000Z');
health.close();health=new RuntimeHealth(deps);assert.equal(health.snapshot({username:'worker',role:'operator'}).groups.find(g=>g.key==='bpm').items[0].lastSuccessAt,item.lastSuccessAt);
assert.equal(health.snapshot({username:'admin',role:'admin'}).groups.find(g=>g.key==='bpm').items.length,2);
});
+10 -1
View File
@@ -10,7 +10,7 @@ function fixture(t){assert.equal(typeof Monitor,'function');const dir=fs.mkdtemp
const hubClient={connect:async(_,options)=>{connects++;callbacks=options;if(hubFailure)throw Object.assign(Error('hub denied'),{status:hubFailure});return {stop:async()=>{}};}};
const monitor=new Monitor({workspace,manager,scanner,provider,hubClient,settings:()=>({schedule:{weekends:true}}),clock:()=>now,debounceMs:15,pollMs:10,retryMs:[20,40]});
t.after(async()=>{await monitor.stop();await scanner.stop();store.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});
return {workspace,store,monitor,connection,actor,get todoCalls(){return todoCalls;},get connects(){return connects;},hint(name){callbacks.onEvent(name);},disconnect(){callbacks.onClose({reason:'disconnected'});},bumpEpoch:()=>epoch++,setHubFailure:value=>hubFailure=value,setTodo:value=>todo=value,setFailure:value=>failed=value,setHold:value=>hold=value,advance:ms=>now+=ms,until};
return {workspace,store,monitor,manager,connection,actor,get todoCalls(){return todoCalls;},get connects(){return connects;},hint(name){callbacks.onEvent(name);},disconnect(){callbacks.onClose({reason:'disconnected'});},bumpEpoch:()=>epoch++,setHubFailure:value=>hubFailure=value,setTodo:value=>todo=value,setFailure:value=>failed=value,setHold:value=>hold=value,advance:ms=>now+=ms,until};
}
test('initial and reconnected subscriptions reconcile real todo and inform sources separately, including equal-count replacement',async t=>{const f=fixture(t);f.monitor.start();await until(()=>f.store.list({kind:'todo'}).total===1&&f.store.list().total===1);assert.equal(f.monitor.snapshot(f.connection.id).status,'listening');f.setTodo([{source:'todo',portalSource:'portal-v4',taskId:'T2',instanceId:'I2',revision:1,processName:'测试订单评审',nodeName:'通知节点',serialNum:'S2',title:'订单号:TEST-2',receivedAt:'2026-10-20T00:10:00Z'}]);f.disconnect();f.advance(100);await until(()=>f.connects>=2&&f.store.list({kind:'todo'}).total===2);assert.equal(f.store.list().total,1);assert.equal(f.store.list({kind:'todo'}).groups[0].items.some(r=>r.taskId==='T2'),true);});
test('hint bursts coalesce and a hint during synchronization schedules exactly one followup',async t=>{const f=fixture(t);f.monitor.start();await until(()=>f.todoCalls===1&&f.monitor.snapshot(f.connection.id).lastSyncAt);let release;f.setHold(new Promise(r=>release=r));for(let i=0;i<20;i++)f.hint('worklistChanged');await until(()=>f.todoCalls===2);for(let i=0;i<20;i++)f.hint('worklistChanged');release();f.setHold(null);await until(()=>f.todoCalls===3);await new Promise(r=>setTimeout(r,60));assert.equal(f.todoCalls,3);});
@@ -21,3 +21,12 @@ test('company calendar pauses automatic synchronization while retaining the list
test('identity changes retire old hints and establish a fresh subscription before reconciliation',async t=>{const f=fixture(t);await f.monitor.tick();await until(()=>f.todoCalls===1&&f.monitor.snapshot(f.connection.id).lastSyncAt);f.bumpEpoch();f.hint('worklistChanged');await new Promise(r=>setTimeout(r,45));assert.equal(f.todoCalls,1);await f.monitor.tick();await f.monitor.tick();await until(()=>f.connects===2&&f.todoCalls===2);});
test('a denied push channel falls back immediately to authorized readonly lists',async t=>{const f=fixture(t);f.setHubFailure(403);f.monitor.start();await until(()=>f.store.list({kind:'todo'}).total===1);assert.equal(f.monitor.snapshot(f.connection.id).status,'polling');});
test('verified session recovery releases listener auth backoff without waiting five minutes',async t=>{
const f=fixture(t);f.manager.ensure=async()=>({status:'login_required'});
await f.monitor.tick();await until(()=>f.monitor.snapshot(f.connection.id).status==='login_required');
f.manager.ensure=async()=>({status:'connected'});f.manager.sessionSnapshot=()=>({phase:'idle',authentication:'valid'});
f.monitor.start();await until(()=>f.monitor.snapshot(f.connection.id).status==='listening');
assert.equal(f.connects,1);
});
+11
View File
@@ -9,6 +9,17 @@ async function setup(t,options={}){
const login=async(username)=>(await call('/api/login',{username,password:'Test-password-123'})).headers['set-cookie'][0].split(';')[0];const cookie=await login('admin');const connection=(await call('/api/connections',{name:'BPM',owner:'alice'},cookie)).json();const route='/api/connections/'+connection.id;
return {call,login,cookie,workspace,store,manager,connection,route,setResult:value=>{next=value;},counts:()=>({disabled,released,suspended}),jpg};
}
test('connection operation replies share workspace account and sync conclusions immediately',async t=>{
const s=await setup(t),checkedAt=new Date().toISOString();
s.setResult({status:'connected',identity:'fixture',checkedAt,checks:{portal:{ok:true,message:'已验证'}}});
const checked=await s.call(s.route+'/check',{},s.cookie);assert.equal(checked.status,200);
assert.equal(checked.json().connectionState.account.status,'healthy');
const workspace=(await s.call('/api/workspace',undefined,s.cookie)).json();
assert.deepEqual(checked.json().connectionState,workspace.connections[0].connectionState);
const paused=await s.call(s.route+'/disable',{},s.cookie);
assert.equal(paused.json().connectionState.account.status,'paused');assert.equal(paused.json().connectionState.sync.status,'paused');
});
test('deleting a disabled connection enforces admin, cleans custody first, and preserves the entry on cleanup failure',async t=>{
const s=await setup(t);const endpoint=s.route+'/delete';
assert.equal((await s.call(endpoint,{},s.cookie)).status,409);
+53 -7
View File
@@ -8,6 +8,7 @@ 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();
@@ -40,6 +41,9 @@ async function fixture(t,{user={username:'alice',role:'operator'},connections,ac
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);
@@ -83,6 +87,7 @@ test('auto-renew setup rejects a duplicate username before sending credentials a
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(),/登录会话.*新版已登录/);
@@ -92,7 +97,7 @@ test('portal login displays session, business and monitoring checks without lega
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.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'}]);
});
@@ -130,7 +135,7 @@ test('account editor saves exact credentials, clears secret input, requires fres
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:'已登录'}}}]});
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);
@@ -139,7 +144,7 @@ test('saving a replacement account blocks new remote control and shows the autom
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.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);
@@ -185,7 +190,7 @@ test('scaled clicks, IME, paste and editing keys reach the remote browser in ord
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();
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]));
@@ -252,7 +257,7 @@ test('narrow screens keep the frame inside the page and native typing forwards t
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();
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));
});
@@ -307,14 +312,55 @@ for(const pendingAction of ['open','save'])test(`document unload sends authentic
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('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(/待办源读取 · healthy/).waitFor();await f.page.getByText(/通知源读取 · failed/).waitFor();await f.page.getByText(/本地执行器投递 · retrying · 待交付 2/).waitFor();let submitted;
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();
});
+102
View File
@@ -0,0 +1,102 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {projectConnectionStatus,connectionSnapshot}=require('../../src/modules/bpm/connection-status.cjs');
const now=Date.parse('2026-10-24T06:00:00Z'),at=delta=>new Date(now+delta).toISOString();
function connection(){return {id:'c',owner:'worker',status:'connected',checkedAt:at(0),checks:{portal:{ok:true}},health:{portal:{status:'healthy',checkedAt:at(0)},todo:{status:'healthy',checkedAt:at(0)}},monitoring:{status:'listening',sources:{todo:{status:'healthy',lastSuccessAt:at(0)},inform:{status:'healthy',lastSuccessAt:at(0)}},delivery:{status:'healthy',pending:0}}};}
const read=(c,options={})=>projectConnectionStatus(c,{now,...options});
test('normal refresh keeps the last verified result while first reads remain pending',()=>{
const c=connection();assert.equal(read(c).sync.status,'healthy');
c.monitoring.sources.todo.status='running';assert.equal(read(c).sync.status,'healthy');
delete c.monitoring.sources.todo.lastSuccessAt;assert.equal(read(c).sync.status,'pending');
assert.equal(read(c).account.status,'healthy');
});
test('permission and delivery failures affect sync without invalidating a valid account',()=>{
const c=connection();c.health.todo={status:'forbidden',checkedAt:at(0)};
let result=read(c);assert.equal(result.account.status,'healthy');assert.equal(result.sync.reason,'READ_FORBIDDEN');
c.health.todo.status='healthy';c.monitoring.delivery={status:'error',pending:2};
result=read(c);assert.equal(result.account.status,'healthy');assert.equal(result.sync.reason,'DELIVERY_FAILED');
});
test('latest session evidence wins, and transport errors never masquerade as expired credentials',()=>{
const c=connection();c.status='login_required';c.checkedAt=at(-60000);
assert.equal(read(c).account.status,'healthy');
c.health.portal={status:'login_required',checkedAt:at(0)};
assert.equal(read(c).account.reason,'AUTH_REQUIRED');assert.equal(read(c).account.color,'red');
c.health.portal={status:'error',checkedAt:at(0)};
assert.equal(read(c).account.reason,'SESSION_UNAVAILABLE');assert.equal(read(c).account.color,'yellow');
c.status='connected';c.checkedAt=at(1000);c.checks.portal.ok=true;
assert.equal(read(c,{now:now+1000}).account.status,'healthy');
});
test('freshness follows reconciliation cadence and permits a normal session check grace period',()=>{
const c=connection();c.monitoring.sources.todo.lastSuccessAt=at(-12*60000);
assert.equal(read(c,{config:{intervalMinutes:10}}).sync.status,'healthy');
assert.equal(read(c,{config:{intervalMinutes:1}}).sync.reason,'SOURCE_STALE');
c.health.portal.checkedAt=c.checkedAt=at(-300001);
assert.equal(read(c).account.status,'healthy');
assert.equal(read(c,{now:now+330000}).account.reason,'SESSION_STALE');
});
test('pause overrides old failures; automatic-sync pause preserves the account',()=>{
const c=connection();c.monitoring.sources.todo.status='error';c.status='disabled';
let state=read(c);assert.equal(state.account.status,'paused');assert.equal(state.sync.status,'paused');
c.status='connected';state=read(c,{config:{enabled:false}});
assert.equal(state.account.status,'healthy');assert.equal(state.sync.status,'paused');
});
test('new account generation cannot inherit the old listener success',()=>{
const c=connection();c.monitoring.sessionEpoch=1;
const state=read(c,{sessionEpoch:2});
assert.equal(state.account.status,'healthy');assert.equal(state.sync.reason,'SESSION_CHANGED');assert.equal(state.sync.color,'yellow');
assert.equal(read(c,{sessionEpoch:1}).sync.status,'healthy');
});
test('newer read transport errors degrade sync until superseded by a full successful read',()=>{
for(const kind of ['todo','inform']){
const c=connection();c.monitoring.sources[kind].lastSuccessAt=at(-60000);c.health[kind]={status:'error',checkedAt:at(0)};
const state=read(c);assert.equal(state.account.status,'healthy');assert.equal(state.sync.reason,'READ_UNAVAILABLE');assert.equal(state.sync.color,'yellow');
c.monitoring.sources[kind].lastSuccessAt=at(1000);
assert.equal(read(c,{now:now+1000}).sync.status,'healthy');
}
});
test('recovered authentication waits for listener reconnect without asking for login again',()=>{
const c=connection();c.monitoring.status='login_required';
const state=read(c);assert.equal(state.account.status,'healthy');assert.equal(state.sync.reason,'LISTENER_PENDING');
assert.doesNotMatch(state.sync.message,/需要.*登录/);
c.health.portal={status:'login_required',checkedAt:at(0)};
assert.equal(read(c).sync.reason,'AUTH_REQUIRED');
});
test('retry preserves an unresolved failure, recovery clears it, and polling is a warning',()=>{
const c=connection(),source=c.monitoring.sources.todo;source.status='running';source.lastSuccessAt=at(-60000);source.lastFailureAt=at(-1000);
assert.equal(read(c).sync.reason,'SOURCE_FAILED');
source.status='healthy';source.lastSuccessAt=at(0);assert.equal(read(c).sync.status,'healthy');
c.monitoring.status='polling';assert.equal(read(c).sync.color,'yellow');assert.equal(read(c).account.color,'green');
});
test('snapshot only reads observations and derived states expose no credentials or upstream error bodies',()=>{
const c=connection(),before=structuredClone(c);
const manager={health:{freshMs:300000,snapshot:()=>c.health},ensure:()=>assert.fail('must not authenticate')};
const monitor={snapshot:()=>c.monitoring,scanner:{store:{config:()=>({intervalMinutes:10})}},reconfigure:()=>assert.fail('must not scan')};
c.monitoring.sources.todo.message='password=PRIVATE';
const snapshot=connectionSnapshot(c,{manager,monitor,now});
assert.equal(snapshot.connectionState.account.status,'healthy');assert.equal(snapshot.connectionState.sync.status,'healthy');
assert.doesNotMatch(JSON.stringify(snapshot.connectionState),/PRIVATE|password/);
c.monitoring.sessionEpoch=1;manager.epoch=()=>2;
assert.equal(connectionSnapshot(c,{manager,monitor,now}).connectionState.sync.reason,'SESSION_CHANGED');
delete c.monitoring.sessionEpoch;
delete c.monitoring.sources.todo.message;assert.deepEqual(c,before);
});
test('unavailable sync configuration does not hide a verified account or claim sync is healthy',()=>{
const c=connection();
const snapshot=connectionSnapshot(c,{now,config:()=>{throw Error('PRIVATE configuration failure');}});
assert.equal(snapshot.connectionState.account.status,'healthy');assert.equal(snapshot.connectionState.sync.reason,'SYNC_STATE_UNAVAILABLE');
assert.doesNotMatch(JSON.stringify(snapshot.connectionState),/PRIVATE/);
});
test('real session phases distinguish checking, automatic renewal, manual work and cooldown',()=>{
const c=connection();c.sessionActivity={phase:'checking',authentication:'valid'};
assert.equal(read(c).account.status,'healthy');
c.sessionActivity={phase:'renewing',authentication:'expired'};
assert.equal(read(c).account.reason,'RENEWING');assert.equal(read(c).sync.color,'yellow');
c.sessionActivity={phase:'manual',authentication:'valid'};
assert.equal(read(c).account.status,'healthy');assert.equal(read(c).sync.reason,'MANUAL_LOGIN');
c.health.portal={status:'login_required',checkedAt:at(0)};
c.sessionActivity={phase:'idle',authentication:'expired',retryAt:now+60000};
assert.equal(read(c).account.reason,'RENEWAL_COOLDOWN');assert.equal(read(c).account.color,'yellow');
c.sessionActivity={phase:'paused',authentication:'unknown'};
assert.equal(read(c).account.status,'paused');assert.equal(read(c).sync.status,'paused');
});
+15
View File
@@ -0,0 +1,15 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
let ListenerState;try{ListenerState=require('../../src/modules/bpm/listener-state.cjs').ListenerState;}catch(error){if(error.code!=='MODULE_NOT_FOUND')throw error;}
test('listener transitions from connection to fallback and rejects results from its old attempt',()=>{
assert.equal(typeof ListenerState,'function');const m=new ListenerState(),old=m.begin();assert.equal(m.state,'connecting');
assert.equal(m.transition('CONNECTED',old),true);assert.equal(m.state,'listening');m.transition('NETWORK_FAILED',old);assert.equal(m.state,'polling');
const next=m.begin();assert.equal(m.state,'reconnecting');assert.equal(m.transition('CONNECTED',old),false);assert.equal(m.transition('CONNECTED',next),true);
});
test('authentication and busy waits require a new attempt and stop is terminal',()=>{
assert.equal(typeof ListenerState,'function');
for(const [event,state]of [['AUTH_REQUIRED','login_required'],['BUSY','busy']]){
const m=new ListenerState(),ticket=m.begin();assert.equal(m.transition(event,ticket),true);assert.equal(m.state,state);
const next=m.begin();m.transition('STOP');assert.equal(m.transition('CONNECTED',next),false);assert.equal(m.begin(),null);assert.equal(m.state,'stopped');
}
});
@@ -0,0 +1,49 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),crypto=require('node:crypto');
const {BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
const c={id:'c',owner:'owner',status:'connected'},p={user:{username:'owner',role:'operator'},sessionId:'owner-session'};
const result=status=>({status,checkedAt:new Date().toISOString(),identity:'fixture',checks:{portal:{ok:status==='connected',message:status==='connected'?'已验证':'请在此入口完成登录。'}},todo:status==='connected'?'healthy':'login_required'});
function fixture(t,check,browserFactory){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-machine-')),writes=[];
const manager=new BpmSessionManager({stateDir:dir,accessClient:{check},browserFactory:browserFactory||(()=>assert.fail('must not launch browser'))});
manager._vault={read:async()=>({storageState:{cookies:[],origins:[]}}),write:async(key,value)=>writes.push({key,value}),destroy(){}};
t.after(async()=>{await manager.shutdown();fs.rmSync(dir,{recursive:true,force:true});});
assert.equal(typeof manager.sessionSnapshot,'function');return {manager,writes};
}
test('actual checks enter checking and finish with verified or uncertain authentication without launching login',async t=>{
let release,started;const gate=new Promise(r=>release=r),begun=new Promise(r=>started=r);
const {manager}=fixture(t,async()=>{started();await gate;return result('connected');});
const pending=manager.check(c,p);await begun;
const state=manager.sessionSnapshot('c');release();await pending;
assert.equal(state.phase,'checking');assert.equal(manager.sessionSnapshot('c').authentication,'valid');
manager.accessClient.check=async()=>result('error');await manager.check(c,p);
assert.equal(manager.sessionSnapshot('c').authentication,'unavailable');assert.equal(manager.sessionSnapshot('c').phase,'idle');
});
test('pause during a probe discards its result and prevents refreshed-cookie writes',async t=>{
let release,started;const gate=new Promise(r=>release=r),begun=new Promise(r=>started=r);
const {manager,writes}=fixture(t,async()=>{started();await gate;return {...result('connected'),storageState:{cookies:[],origins:[]}};});
const pending=manager.check(c,p);const rejected=assert.rejects(pending,e=>e.status===409);await begun;
const stopping=manager.suspend('c');release();await Promise.all([stopping,rejected]);
assert.equal(writes.length,0);assert.equal(manager.sessionSnapshot('c').phase,'paused');assert.equal(manager.health.recent('c'),false);
await manager.resume('c');assert.equal(manager.sessionSnapshot('c').authentication,'unknown');
});
test('concurrent expired ensures coalesce the entire browser recovery, including a failed launch',async t=>{
let browsers=0,release,started;const gate=new Promise(r=>release=r),begun=new Promise(r=>started=r);
const {manager}=fixture(t,async()=>{started();await gate;return result('login_required');},async()=>{browsers++;throw Error('fixture browser unavailable');});
const a=manager.ensure(c,p),b=manager.ensure(c,p),settled=Promise.allSettled([a,b]);await begun;release();
assert.ok((await settled).every(r=>r.status==='rejected'));assert.equal(browsers,1);assert.equal(manager.sessionSnapshot('c').phase,'idle');
});
test('a coalesced ensure reauthorizes each waiter after its dashboard session was revoked',async t=>{
let release,started;const gate=new Promise(r=>release=r),begun=new Promise(r=>started=r);
const {manager}=fixture(t,async()=>{started();await gate;return result('connected');});
const other={...p,sessionId:'revoked-waiter'},a=manager.ensure(c,p),b=manager.ensure(c,other);const rejected=assert.rejects(b,e=>e.status===401);
await begun;await manager.releaseSessionHashes([crypto.createHash('sha256').update(other.sessionId).digest('hex')]);release();
assert.equal((await a).status,'connected');await rejected;
});
test('ensure joins an ongoing recovery after its transient browser lease has been created',async t=>{
let release,started;const gate=new Promise(r=>release=r),begun=new Promise(r=>started=r);
const {manager}=fixture(t,async()=>result('login_required'),async()=>{started();await gate;throw Error('fixture launch failure');});
const a=manager.ensure(c,p);const first=assert.rejects(a,e=>e.status===503);await begun;
const b=manager.ensure(c,p);const second=Promise.allSettled([b]);release();await first;
const [outcome]=await second;assert.equal(outcome.status,'rejected');assert.equal(outcome.reason.status,503);
});
+36
View File
@@ -0,0 +1,36 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
let SessionState;try{SessionState=require('../../src/modules/bpm/session-state.cjs').SessionState;}catch(error){if(error.code!=='MODULE_NOT_FOUND')throw error;}
function machine(){assert.equal(typeof SessionState,'function');return new SessionState({clock:()=>1000});}
test('checks distinguish authentication failures from transport uncertainty',()=>{
const m=machine(),ticket=m.begin('c','checking');m.finish(ticket,'valid');assert.equal(m.snapshot('c').authentication,'valid');
const retry=m.begin('c','checking');m.finish(retry,'unavailable');assert.equal(m.snapshot('c').authentication,'unavailable');
assert.throws(()=>m.begin('c','renewing'),e=>e.status===409);
const expired=m.begin('c','checking');m.finish(expired,'expired');assert.equal(m.snapshot('c').phase,'idle');
assert.ok(m.begin('c','renewing'));
});
test('pause, account replacement and stop invalidate old operations and block credential permits',()=>{
for(const event of ['pause','replace','stop']){
const m=machine();m.observe('c','expired');const ticket=m.begin('c','renewing');m.reserve(ticket,2000);
m.lifecycle('c',event);assert.equal(m.current(ticket),false);assert.equal(m.consume(ticket),false);assert.equal(m.finish(ticket,'valid'),false);
assert.notEqual(m.snapshot('c').authentication,'valid');
if(event!=='replace')assert.throws(()=>m.begin('c','checking'),e=>e.status===409);
}
});
test('renewal consumes one credential permit, persists cooldown semantics and requires expired authentication',()=>{
const m=machine();m.observe('c','expired');const ticket=m.begin('c','renewing');m.reserve(ticket,2000);
assert.equal(m.consume(ticket),true);assert.equal(m.consume(ticket),false);m.finish(ticket,'expired','manual_required');
assert.throws(()=>m.begin('c','renewing'),e=>e.status===409);assert.equal(m.snapshot('c').retryAt,2000);
const check=m.begin('c','checking');m.finish(check,'valid');assert.equal(m.snapshot('c').retryAt,null);
});
test('manual login owns its phase until close and cannot be overwritten by older results',()=>{
const m=machine(),old=m.begin('c','checking');m.abort(old);
const manual=m.begin('c','manual');assert.throws(()=>m.begin('c','renewing'),e=>e.status===409);assert.throws(()=>m.begin('c','checking'),e=>e.status===409);
m.observe('c','valid');assert.equal(m.snapshot('c').phase,'manual');assert.equal(m.finish(old,'expired'),false);
m.finish(manual,'valid');assert.equal(m.snapshot('c').phase,'idle');
});
test('resume does not resurrect previous validation and metadata never contains credentials',()=>{
const m=machine();m.observe('c','valid');m.lifecycle('c','pause');m.lifecycle('c','resume');
assert.equal(m.snapshot('c').authentication,'unknown');assert.equal(m.snapshot('c').phase,'idle');
assert.deepEqual(Object.keys(m.snapshot('c')).sort(),['authentication','generation','phase','reason','retryAt','revision'].sort());
});