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

+42
View File
@@ -0,0 +1,42 @@
# BPM 状态统一:第一阶段
本阶段只统一观测结果和页面展示,不改账号托管、密码加密、自动续登提交、人工登录互斥或连接生命周期。
## 状态来源
`src/modules/bpm/connection-status.cjs` 提供纯函数 `projectConnectionStatus`,输出独立的 `account` 与 `sync`,每项包含状态、颜色、原因码、说明及观测时间。`connectionSnapshot` 读取现有会话健康与监听快照,供工作台接口、连接操作响应和健康中心复用。读取状态不会发起登录、BPM 扫描、重试或邮件发送。
- 账号:选取最新的已保存检查或运行时会话观测。明确认证失效为红色;网络不确定、未检查、过期为黄色;有效会话为绿色。
- 同步:独立考虑推送、待办、通知和本地投递。无读取权限、读取失败或投递失败不会把账号标为失效。
- 正常读取进行中:最近成功仍有效且没有未恢复的失败时,保留健康;首次读取保持待核验。
- 过期:完整读取采用配置对账周期的两倍加 30 秒容差;账号采用会话证据缓存周期的两倍加 30 秒容差。这只是观测有效期,不改变原有检查或续登周期。
- 停用覆盖历史结果;暂停自动同步只影响同步状态。
- 会话代次变化:监听快照附带已有的身份代次,新会话不继承旧会话的同步成功;在新订阅完成前显示等待核验。
- 冲突观测:较新的接口错误会使同步降级,较新的完整读取可以覆盖旧错误;登录恢复后显示等待监听重连,不重复提示登录。
- 同步配置读取失败:账号结论仍可展示,同步显示待核验;不把模块读取失败解释为健康。
工作台卡片默认显示账号灯、同步灯及各自说明,技术证据仍在“状态详情”内。设置页不再自行计算五分钟过期。健康中心的“BPM 连接”和“BPM 同步”复用相同投影;原有扫描、监听和投递分项保留诊断证据。
连接操作响应也附加相同状态,避免检查完成后短暂显示旧灯色。缺少后端结论时,页面显示等待更新,不根据原始字段猜测。
为保持操作后状态一致,本阶段除工作台接口外,也在 BPM 操作接口附加只读结论;监听器仅增加快照中的 `sessionEpoch` 字段,原有连接、重试和代次校验流程不变。
## 回归范围
- 新增 `tests/bpm/connection-status.test.cjs`:正常刷新、首次读取、错误隔离、最新观测优先、周期、新旧失败恢复、暂停以及只读边界。
- 新增 `tests/app/connection-status-api.test.cjs`:工作台与健康中心一致、归属过滤和周期生效。
- 更新 BPM 浏览器测试:账号/同步独立、后台结论优先、折叠详情与轮询保留。
- 回归现有账号、权限、自动续登、生命周期、交接、读取恢复及健康页面测试。
第一阶段完成后,第二阶段已接入会话与监听状态机,详见 `docs/bpm-session-state-machine-2026-10-24.md`。本文件保留第一阶段的改动与验收记录。
## 本机验证(2026-10-24)
- 状态、接口、健康、连接生命周期、托管器、监听恢复与账号交接隔离测试:53/53 通过。
- BPM 页面、健康页面及 BPM HTTP 操作回归:36/36 通过;补充的操作响应状态一致性测试 1/1 通过。
- 账号托管测试文件的 14 项均通过,覆盖加密保存、换账号、Cookie 复用、自动续登、验证码、冷却、网络不确定及凭据提交边界。
- 独立代码审查发现的三项问题均补回归并修正,复审无剩余重要问题。
- 桌面与 390px 手机宽度检查通过,手机无横向溢出;示例截图使用合成账号数据。
- 本地服务已重启,通过双端口健康检查;工作台 HTTP 200,实际提供的 BPM 页面脚本使用后端状态结论。
以上为隔离回归及本地服务烟雾检查,不代表真实 BPM 业务链路或真实订单验收已完成。
@@ -0,0 +1,45 @@
# BPM 会话与监听状态机:第二阶段
## 实施范围
`session-state.cjs` 管理会话操作阶段和认证结论,`listener-state.cjs` 管理监听转换;它们只保存状态、票据代次和冷却期限,不保存账号、密码、Cookie 或原始异常。副作用仍由原有 SessionManager、表单白名单、加密 Vault 和 ArrivalMonitor 执行。
| 会话阶段 | 允许操作与退出条件 |
| --- | --- |
| idle | 可以检查或人工登录;明确认证失效且冷却结束才允许自动续登 |
| checking | 检查结果归为有效、失效、暂不可核验;普通刷新保留已有有效证据 |
| renewing | 只允许当前票据的一次密码提交;成功恢复、人工介入或失败后退出 |
| manual | 登录窗口独占;验证不结束窗口,关闭后回到空闲 |
| paused | 拒绝检查与提交;恢复后重新核验 |
| stopped | 终态,旧操作及新请求不能恢复此状态机 |
每次检查、续登和人工窗口都取得票据。暂停、删除、停止与更换账号使票据失效;结果回写和自动提交前再次检查票据与调用者权限。Cookie 身份代次继续用于监听和读取隔离,不与状态机操作序号混用。
并发 `ensure` 在整个检查和浏览器恢复期间共享同一任务,包括已经创建临时浏览器窗口的阶段。每个等待者在返回前分别重新授权;人工窗口没有对应恢复任务时仍返回忙碌。
## 自动续登边界
- 明确登录失效、已有托管账号、已核验的表单与 POST 提交目标是前提。
- 表单检查不消耗提交许可,真正提交只消费一次许可。
- 原有 15 分钟期限仍在密码提交前写入加密账号记录;冷却跨进程重启继续有效。
- 网络不确定、权限不足或工作台权限失效都不构成重新提交密码的依据。
- 修改同账号密码继续保留有效 Cookie 并清除旧冷却;切换账号继续使旧身份失效。
- 关闭自动续登只删除托管凭据;暂停保留数据;删除清除凭据与会话。
Vault 的 SQLite 提交在首次 await 前同步完成;票据在提交前检查。提交后暂停不会撤回已经完成的存储操作,但迟到的结果不会恢复健康、增加身份代次或恢复连接。
## 监听转换
新尝试从 connecting 或 reconnecting 开始,通过事件进入 listening、polling、login_required 或 busy。旧尝试、重复关闭回调及 STOP 之后的成功结果不能恢复监听。原有读取退避、完整对账周期、业务时间窗口和只读限制保留。
认证恢复且会话处于空闲时,监听在下一轮 tick 解除认证/忙碌等待,使用已验证会话重连,不必等待旧五分钟期限。
工作台及健康中心继续复用第一阶段投影:检查中不使正常账号跳黄;续登、人工窗口及冷却显示对应原因;详情显示会话操作和可重试期限。
## 验证范围
新增状态机和实际 manager 隔离测试覆盖:转换、暂停/替换/停止失效、一次提交许可、冷却、人工窗口、整个恢复任务共享、浏览器阶段的共享及等待者权限撤销。监听新增登录恢复后及时重连测试。
现有账号加密、Cookie 复用、验证码、提交目标限制、冷却重启、真实本机浏览器会话、浏览器重建、工作台权限及页面回归一并验证。所有业务端访问使用隔离本机测试环境,不以这些测试代替真实 BPM 订单验收。
2026-10-24 验证结果:后端、状态转换与接口相关测试 77/77;账号、真实本机浏览器会话、运行时、托管器及浏览器重建 30/30;BPM 页面与健康页面 27/27。独立审查发现的临时浏览器阶段并发共享问题已修正并补回归,复审无剩余重要问题。
@@ -0,0 +1,16 @@
# BPM 会话与监听状态机实施计划
**目标:** 第二阶段将实际登录检查、自动续登、人工登录及监听副作用接入明确的转换与失效规则,复用第一阶段状态展示。
**设计:** 会话分为操作阶段(空闲、检查、续登、人工、暂停、停止)和认证结论(未知、有效、失效、暂不可核验),避免把人工操作误当成账号失效。每次异步操作持有状态机票据;停用、恢复、账号切换和停止使旧票据失效。现有 Cookie 身份代次独立保留,继续保护监听与读取。状态机不保存账号、密码或原始错误。
现有功能分支内连续实施,保留第一阶段未提交改动和用户文件;不迁移密钥、不重建账号、不发送邮件、不办理 BPM。
- [x] 新建 `src/modules/bpm/session-state.cjs` 与测试:转换表、暂停/停止优先、旧票据拒绝、单次提交许可、冷却和人工操作。
- [x] 接入 `session-manager.cjs`:检查、续登、手工操作、凭据替换、暂停/删除/停止;并发 ensure 共用一次恢复,但分别重新授权;所有结果在提交前校验票据。
- [x] 通过隔离测试验证真实 manager 的并发、暂停与冷却路径,回归加密账号及人工浏览器控制。
- [x] 新建监听状态转换表并接入 `arrival-monitor.cjs`,保持现有退避、对账和身份检查;停止后旧连接结果不能恢复监听。
- [x] 在已有只读状态快照附加操作阶段,保持正常检查不跳黄、人工与冷却有准确原因;补接口与页面回归。
- [x] 独立审查、相关全量隔离测试、更新交接文档,重启本地服务并检查工作台。
自动续登仍须有明确认证失效证据和已核验登录表单;网络异常及读取权限不足不能触发密码提交。15 分钟冷却继续由现有加密托管记录持久化,状态机只消费并展示该期限。关闭自动续登仍只关闭托管,停用保留数据,删除清除数据。
+1 -1
View File
@@ -99,7 +99,7 @@ async function main(options = {}) {
orderRules.deliveryBlockers=allowed=>scanStore.deliveries.pendingSources().filter(allowed);
bpmMonitor=new BpmArrivalMonitor({workspace,manager:bpmSessions,scanner,provider:orderProvider,settings:()=>store.settings(),onTodoReconciled:payload=>orderExecution.notifyDiscovery(payload)});
assistantStore=new AssistantStore(path.join(stateDir,'assistant'));assistantStore.recover();assistant=new AssistantService({store:assistantStore,runtime:new ZcodeRuntime({stateDir:path.join(stateDir,'assistant','runtime')}),dashboard:store,workspace,scanner,storage,orderRules,orderExecution});
health=new RuntimeHealth({stateDir,startedAt,instanceId:watchdog.instanceId,workspace,scanner,storage,mail,execution:orderExecution,monitor:bpmMonitor});
health=new RuntimeHealth({stateDir,startedAt,instanceId:watchdog.instanceId,workspace,scanner,storage,mail,execution:orderExecution,monitor:bpmMonitor,bpmSessions});
await bpmSessions.migrateAccounts(workspace.snapshot().connections);
workspace.markSessionChecksPending();
server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage,watchdog,renderSnapshot:options.renderSnapshot});
+5 -3
View File
@@ -1,4 +1,5 @@
const fail=(status,message)=>{throw Object.assign(new Error(message),{status});};
const {connectionSnapshot}=require('./connection-status.cjs');
const isLoopback=address=>['127.0.0.1','::1','::ffff:127.0.0.1'].includes(address);
function secureBpmTransport(request,trustedProxy=false){
if(request.socket.encrypted)return true;
@@ -23,6 +24,7 @@ async function bpmApi({workspace,bpmSessions,bpmLifecycle,user,sessionId,route,m
const [,id,login,other,account,suffix]=match;const action=login || other || (suffix==='/clear'?'clear-account':suffix==='/check'?'check-account':account);
if(action==='account'?!['GET','POST'].includes(method):method!==(action==='frame'?'GET':'POST'))fail(405,'此操作不支持当前请求方式。');
const connection=workspace.getConnection(id);authorizeConnection(connection,user);
const describe=value=>connectionSnapshot(value,{manager:bpmSessions,monitor:bpmLifecycle?.monitor});
if(action==='delete'){
if(user.role!=='admin')fail(403,'仅管理员可以删除连接。');emptyBody(body);
if(connection.status!=='disabled')fail(409,'请先停用连接再删除。');
@@ -33,7 +35,7 @@ async function bpmApi({workspace,bpmSessions,bpmLifecycle,user,sessionId,route,m
if(user.role!=='admin')fail(403,'仅管理员可以启用或停用连接。');
if(!body||Array.isArray(body)||Object.keys(body).some(k=>k!=='version'))fail(400,'请提供当前连接版本。');
const input=action==='disable'&&!Object.keys(body).length?{version:connection.version||0}:body;
reply(200,await bpmLifecycle.change(id,action==='enable',input,user));return true;
reply(200,describe(await bpmLifecycle.change(id,action==='enable',input,user)));return true;
}
if(connection.status==='disabled')fail(409,'此连接已停用。');
if(!secureBpmTransport(request,trustedProxy))fail(403,'请在部署机本地或 HTTPS 页面中登录 BPM。');
@@ -54,7 +56,7 @@ async function bpmApi({workspace,bpmSessions,bpmLifecycle,user,sessionId,route,m
try{const result=await managerCall(()=>bpmSessions.ensure(workspace.getConnection(id),principal));checked=workspace.updateConnectionSession(id,result,user);}
catch(error){if(error.status!==409)throw error;checked=workspace.getConnection(id);}
}
reply(200,{configured:value.configured===true,username:typeof value.username==='string'?value.username:'',updatedAt:typeof value.updatedAt==='string'?value.updatedAt:null,...(saving?{connection:checked}:{})});return true;
reply(200,{configured:value.configured===true,username:typeof value.username==='string'?value.username:'',updatedAt:typeof value.updatedAt==='string'?value.updatedAt:null,...(saving?{connection:describe(checked)}:{})});return true;
}
if(action==='fill-account'){
const value=await managerCall(()=>bpmSessions.fillAccount(connection,principal));reply(200,{filled:value.filled===true,message:typeof value.message==='string'?value.message:''});return true;
@@ -65,7 +67,7 @@ async function bpmApi({workspace,bpmSessions,bpmLifecycle,user,sessionId,route,m
response.writeHead(200,{'Content-Type':'image/jpeg'});response.end(bytes);return true;
}
if(action==='save' || action==='check'){
const result=await managerCall(()=>bpmSessions[action](connection,principal));reply(200,workspace.updateConnectionSession(id,result,user));return true;
const result=await managerCall(()=>bpmSessions[action](connection,principal));reply(200,describe(workspace.updateConnectionSession(id,result,user)));return true;
}
const value=await managerCall(()=>bpmSessions[action](action==='open'?connection:id,principal,body));
if(action==='open')reply(200,{active:value.active===true,viewport:{width:value.viewport?.width,height:value.viewport?.height},expiresAt:value.expiresAt,host:value.host});
+13 -10
View File
@@ -3,6 +3,7 @@ const crypto=require('node:crypto');
const {dayPolicy}=require('../../shared/schedule.cjs');
const {normalizeArrival}=require('./list-client.cjs');
const {BpmSignalRClient}=require('./signalr-client.cjs');
const {ListenerState}=require('./listener-state.cjs');
function todoArrival(row){
if(row.source!=='todo'||!['portal-v4','portal-v8'].includes(row.portalSource)||row.instanceId==null)throw Object.assign(new Error('真实待办身份不完整。'),{status:502});
return {...normalizeArrival({taskId:row.taskId,startTime:row.receivedAt,serialNum:row.serialNum,processName:row.processName,activityName:row.nodeName,processInstanceSubject:row.title},'todo:'+row.portalSource),kind:'todo',instanceId:String(row.instanceId),...(row.revision==null?{}:{revision:row.revision}),processVersion:row.processVersion||'',recordKey:String(row.taskId)};
@@ -18,7 +19,7 @@ class BpmArrivalMonitor{
sourceSuccess(entry,kind){if(!entry||!this.active(entry))return;const source=this.source(entry,kind);Object.assign(source,{status:'healthy',failures:0,nextAttempt:0,lastSuccessAt:new Date(this.clock()).toISOString(),message:null});if(['todo','inform'].every(k=>this.source(entry,k).status==='healthy'))entry.lastSyncAt=new Date(this.clock()).toISOString();}
sourceFailure(entry,kind,error){if(!entry||!this.active(entry))return;const source=this.source(entry,kind),delay=this.sourceRetryMs[Math.min(source.failures++,this.sourceRetryMs.length-1)];Object.assign(source,{status:'error',lastFailureAt:new Date(this.clock()).toISOString(),nextAttempt:this.clock()+delay,message:error?.code==='TODO_IDENTITY_AMBIGUOUS'?error.message:error?.status===401?'需要恢复BPM登录。':error?.status===403?'没有读取权限。':error?.status===409?'连接忙碌或已暂停。':'读取失败,等待重试。'});entry.lastFailureAt=source.lastFailureAt;entry.dirty.add(kind);}
deliveryState(id){return this.scanner.store.deliveries?.summary(id)||{status:'healthy',pending:0};}
snapshot(id){const e=this.entries.get(id);if(e)return {status:e.status,lastSignalAt:e.lastSignalAt||null,lastSyncAt:e.lastSyncAt||null,lastFailureAt:e.lastFailureAt||null,nextRetryAt:Number.isFinite(e.nextRetry)?new Date(e.nextRetry).toISOString():null,nextReconcileAt:new Date(e.nextReconcile).toISOString(),delivery:this.deliveryState(id),sources:Object.fromEntries(['todo','inform'].map(kind=>{const s=this.source(e,kind);return [kind,{status:s.status,lastSuccessAt:s.lastSuccessAt,lastFailureAt:s.lastFailureAt,retryAt:s.nextAttempt?new Date(s.nextAttempt).toISOString():null,message:s.message||null}];}))};
snapshot(id){const e=this.entries.get(id);if(e)return {status:e.status,sessionEpoch:e.epoch??null,lastSignalAt:e.lastSignalAt||null,lastSyncAt:e.lastSyncAt||null,lastFailureAt:e.lastFailureAt||null,nextRetryAt:Number.isFinite(e.nextRetry)?new Date(e.nextRetry).toISOString():null,nextReconcileAt:new Date(e.nextReconcile).toISOString(),delivery:this.deliveryState(id),sources:Object.fromEntries(['todo','inform'].map(kind=>{const s=this.source(e,kind);return [kind,{status:s.status,lastSuccessAt:s.lastSuccessAt,lastFailureAt:s.lastFailureAt,retryAt:s.nextAttempt?new Date(s.nextAttempt).toISOString():null,message:s.message||null}];}))};
let status='removed';try{status=this.workspace.getConnection(id).status==='disabled'||!this.scanner.store.config().enabled?'paused':'waiting';}catch{}return {status,lastSignalAt:null,lastSyncAt:null,nextReconcileAt:null,sources:{},delivery:this.deliveryState(id)};
}
updateInterval(entry,config){if(entry.intervalMinutes===config.intervalMinutes)return;entry.intervalMinutes=config.intervalMinutes;entry.nextReconcile=(entry.lastReconcileAt??this.clock())+config.intervalMinutes*60000;}
@@ -30,8 +31,10 @@ class BpmArrivalMonitor{
if(!config.enabled)return;
for(const c of connections){
if(c.status==='disabled'||c.status==='disconnected'&&!c.lastConnectedAt)continue;
let entry=this.entries.get(c.id);if(!entry){entry={id:c.id,status:'connecting',nextRetry:0,nextReconcile:this.clock()+config.intervalMinutes*60000,lastReconcileAt:this.clock(),intervalMinutes:config.intervalMinutes,sources:{},failures:0,dirty:new Set(),controller:new AbortController(),attempt:0};this.entries.set(c.id,entry);}
let entry=this.entries.get(c.id);if(!entry){entry={id:c.id,lifecycle:new ListenerState(),get status(){return this.lifecycle.state;},nextRetry:0,nextReconcile:this.clock()+config.intervalMinutes*60000,lastReconcileAt:this.clock(),intervalMinutes:config.intervalMinutes,sources:{},failures:0,dirty:new Set(),controller:new AbortController(),attempt:0};this.entries.set(c.id,entry);}
this.updateInterval(entry,config);
const session=this.manager.sessionSnapshot?.(c.id);
if(['login_required','busy'].includes(entry.status)&&session?.phase==='idle'&&session.authentication==='valid')entry.nextRetry=0;
if(this.allowed())this.publishPending(c.id,()=>this.active(entry)&&this.allowed()&&entry.epoch===(this.manager.epoch?.(c.id)||0)).catch(()=>{});
if(entry.handle&&entry.epoch!==(this.manager.epoch?.(c.id)||0)){await this.stopConnection(c.id);continue;}
if(!entry.handle&&!entry.connecting&&this.clock()>=entry.nextRetry)this.connect(entry,c);
@@ -39,21 +42,21 @@ class BpmArrivalMonitor{
else if(entry.dirty.size&&!entry.sync&&!entry.debounce)this.queue(entry,[]);
}
}
retry(entry,status='polling',delay){if(!this.active(entry))return;if(entry.connectedAt&&this.clock()-entry.connectedAt>60000)entry.failures=0;entry.status=status;entry.nextRetry=this.clock()+(delay??this.retryMs[Math.min(entry.failures++,this.retryMs.length-1)]);}
retry(entry,status='polling',delay){if(!this.active(entry))return;if(entry.connectedAt&&this.clock()-entry.connectedAt>60000)entry.failures=0;if(!entry.lifecycle.transition(({polling:'NETWORK_FAILED',login_required:'AUTH_REQUIRED',busy:'BUSY'})[status]))return;entry.nextRetry=this.clock()+(delay??this.retryMs[Math.min(entry.failures++,this.retryMs.length-1)]);}
connect(entry,connection){
const attempt=++entry.attempt;let closed=false;entry.status=entry.failures?'reconnecting':'connecting';
const ticket=entry.lifecycle.begin();if(ticket===null)return;const attempt=++entry.attempt;let closed=false;
entry.connecting=(async()=>{
if(this.manager.sessions.has(entry.id))throw Object.assign(new Error('人工登录窗口正在使用。'),{status:409});
const result=await this.manager.ensure(connection,this.principal);if(!this.active(entry))return;
const result=await this.manager.ensure(connection,this.principal);if(!this.active(entry)||!entry.lifecycle.current(ticket))return;
if(result.status!=='connected'){this.retry(entry,result.status==='login_required'?'login_required':'polling',5*60000);return;}
entry.epoch=this.manager.epoch?.(entry.id)||0;const handle=await this.manager.run(entry.id,async()=>{
this.manager.authorize(connection,this.principal);if(this.manager.sessions.has(entry.id))throw Object.assign(new Error('人工登录窗口正在使用。'),{status:409});
const saved=await this.manager.vault().read(entry.id);
return this.hubClient.connect(saved?.storageState,{signal:entry.controller.signal,onEvent:name=>{if(!this.active(entry)||entry.attempt!==attempt||entry.epoch!==(this.manager.epoch?.(entry.id)||0))return;entry.lastSignalAt=new Date(this.clock()).toISOString();this.queue(entry,name==='worklistChanged'?['todo']:name==='informlistChanged'?['inform']:['todo','inform']);},onClose:()=>{closed=true;if(this.active(entry)&&entry.attempt===attempt){entry.handle=null;this.retry(entry);}}});
return this.hubClient.connect(saved?.storageState,{signal:entry.controller.signal,onEvent:name=>{if(!this.active(entry)||!entry.lifecycle.current(ticket)||entry.attempt!==attempt||entry.epoch!==(this.manager.epoch?.(entry.id)||0))return;entry.lastSignalAt=new Date(this.clock()).toISOString();this.queue(entry,name==='worklistChanged'?['todo']:name==='informlistChanged'?['inform']:['todo','inform']);},onClose:()=>{closed=true;if(this.active(entry)&&entry.lifecycle.current(ticket)&&entry.attempt===attempt){entry.handle=null;this.retry(entry);}}});
});
if(!handle)return;if(!this.active(entry)||closed){await handle.stop();return;}
entry.handle=handle;entry.connectedAt=this.clock();entry.status='listening';entry.nextRetry=Infinity;entry.lastReconcileAt=this.clock();entry.nextReconcile=this.clock()+this.scanner.store.config().intervalMinutes*60000;this.queue(entry,['todo','inform']);
})().catch(error=>{if(!this.active(entry))return;if(error.status===401)this.manager.observe?.(entry.id,'portal',error);this.retry(entry,error.status===409?'busy':error.status===401?'login_required':'polling',error.status===409?5000:error.status===401?5*60000:undefined);if(![401,409].includes(error.status))this.queue(entry,['todo','inform']);}).finally(()=>{entry.connecting=null;});
if(!handle)return;if(!this.active(entry)||closed||!entry.lifecycle.transition('CONNECTED',ticket)){await handle.stop();return;}
entry.handle=handle;entry.connectedAt=this.clock();entry.nextRetry=Infinity;entry.lastReconcileAt=this.clock();entry.nextReconcile=this.clock()+this.scanner.store.config().intervalMinutes*60000;this.queue(entry,['todo','inform']);
})().catch(error=>{if(!this.active(entry)||!entry.lifecycle.current(ticket))return;if(error.status===401)this.manager.observe?.(entry.id,'portal',error);this.retry(entry,error.status===409?'busy':error.status===401?'login_required':'polling',error.status===409?5000:error.status===401?5*60000:undefined);if(![401,409].includes(error.status))this.queue(entry,['todo','inform']);}).finally(()=>{entry.connecting=null;});
}
dueKinds(entry){return [...entry.dirty].filter(kind=>this.clock()>=this.source(entry,kind).nextAttempt);}
queue(entry,kinds){if(!this.active(entry))return;for(const kind of kinds)entry.dirty.add(kind);if(entry.sync||entry.debounce||!this.dueKinds(entry).length||!this.allowed()||this.manager.sessions.has(entry.id))return;
@@ -97,7 +100,7 @@ class BpmArrivalMonitor{
catch{const delay=this.sourceRetryMs[Math.min(item.attempts,this.sourceRetryMs.length-1)];this.scanner.store.deliveries.failed(item.id,this.clock()+delay);}
}}).finally(()=>{if(this.deliveryPending.get(id)===task)this.deliveryPending.delete(id);});this.deliveryPending.set(id,task);return task;
}
async stopConnection(id){const entry=this.entries.get(id);if(entry){this.entries.delete(id);entry.controller.abort();clearTimeout(entry.debounce);}await Promise.allSettled([entry?.handle?.stop(),entry?.connecting,entry?.sync,this.todoPending.get(id),this.deliveryPending.get(id)]);}
async stopConnection(id){const entry=this.entries.get(id);if(entry){entry.lifecycle.transition('STOP');this.entries.delete(id);entry.controller.abort();clearTimeout(entry.debounce);}await Promise.allSettled([entry?.handle?.stop(),entry?.connecting,entry?.sync,this.todoPending.get(id),this.deliveryPending.get(id)]);}
async stop(){this.stopped=true;clearInterval(this.timer);this.timer=null;await Promise.all([...this.entries.keys()].map(id=>this.stopConnection(id)));await Promise.allSettled([...this.todoPending.values(),...this.deliveryPending.values()]);}
}
module.exports={BpmArrivalMonitor,todoArrival};
+65
View File
@@ -0,0 +1,65 @@
'use strict';
const time=value=>typeof value==='string'&&Number.isFinite(Date.parse(value))?Date.parse(value):null;
const view=(status,reason,message,checkedAt=null)=>({status,color:status==='healthy'?'green':status==='error'?'red':'yellow',label:status==='healthy'?'健康':status==='error'?'异常':'警告',reason,message,checkedAt});
// A pure projection of observations. It must never authenticate, scan, retry or mutate custody.
function projectConnectionStatus(connection,{now=Date.now(),config={},sessionFreshMs=300000,sessionEpoch}={}){
const health=connection.health||{},monitoring=connection.monitoring||{},activity=connection.sessionActivity||{};
const interval=Number.isFinite(config.intervalMinutes)&&config.intervalMinutes>0?config.intervalMinutes:5;
const sourceFreshMs=Math.max(60000,interval*120000+30000);
const sessionWindow=Math.max(60000,sessionFreshMs*2+30000);
const fresh=(at,window)=>{const value=time(at);return value!==null&&value<=now&&now-value<=window;};
const paused=view('paused','DISABLED','连接已停用');
if(connection.status==='disabled'||['paused','stopped'].includes(activity.phase))return {account:paused,sync:{...paused}};
const savedAt=time(connection.checkedAt),observed=health.portal,observedAt=time(observed?.checkedAt);
const useObserved=observedAt!==null&&(savedAt===null||observedAt>=savedAt);
const session=useObserved?observed:{status:connection.status==='login_required'?'login_required':connection.status==='error'?'error':connection.status==='connected'&&connection.checks?.portal?.ok===true?'healthy':'unknown',checkedAt:connection.checkedAt||null};
let account;
if(session.status==='login_required')account=view('error','AUTH_REQUIRED','登录已失效,请重新登录',session.checkedAt);
else if(session.status==='error'||session.status==='forbidden')account=view('pending','SESSION_UNAVAILABLE','暂时无法核实登录,请检查网络或连接',session.checkedAt);
else if(session.status!=='healthy')account=view('pending','CHECK_PENDING','账号等待检查',session.checkedAt);
else if(!fresh(session.checkedAt,sessionWindow))account=view('pending','SESSION_STALE','最近登录验证已过期,等待后台检查',session.checkedAt);
else account=view('healthy','SESSION_VALID','登录会话有效',session.checkedAt);
if(activity.phase==='renewing')account=view('pending','RENEWING','正在自动恢复登录会话',session.checkedAt);
else if(activity.phase==='manual'&&account.status!=='healthy')account=view('pending','MANUAL_LOGIN','等待人工完成登录验证',session.checkedAt);
else if(activity.authentication==='expired'&&activity.retryAt>now)account=view('pending','RENEWAL_COOLDOWN','自动续登冷却中,请等待或更新托管账号',session.checkedAt);
else if(activity.phase==='checking'&&account.reason==='CHECK_PENDING')account=view('pending','CHECKING','正在检查登录会话',session.checkedAt);
const sync=()=>{
if(config.enabled===false||monitoring.status==='paused')return view('paused','SYNC_PAUSED','自动同步已暂停');
if(activity.phase==='manual')return view('pending','MANUAL_LOGIN','人工登录窗口使用中,同步暂缓');
if(activity.phase==='renewing'||account.reason==='RENEWAL_COOLDOWN')return view('pending',account.reason,account.message);
if(Number.isInteger(sessionEpoch)&&Number.isInteger(monitoring.sessionEpoch)&&sessionEpoch!==monitoring.sessionEpoch)return view('pending','SESSION_CHANGED','登录会话已更新,等待新会话完成监听和读取');
const failures=[],warnings=[];
const delivery=monitoring.delivery||{};
if(['error','failed','retrying'].includes(delivery.status))failures.push(view('error','DELIVERY_FAILED','执行线索投递失败,账号会话单独核验',delivery.lastFailureAt||null));
else if(delivery.pending>0)warnings.push(view('pending','DELIVERY_PENDING','执行线索等待本地投递'));
for(const [kind,label]of [['todo','待办'],['inform','通知']]){
const source=monitoring.sources?.[kind]||{},probe=health[kind];
// A newer successful full read supersedes an older permission probe.
if(probe?.status==='forbidden'&&(time(source.lastSuccessAt)===null||time(probe.checkedAt)===null||time(probe.checkedAt)>=time(source.lastSuccessAt)))failures.push(view('error','READ_FORBIDDEN',label+'接口无读取权限',probe.checkedAt||null));
if(probe?.status==='error'&&(time(source.lastSuccessAt)===null||time(probe.checkedAt)===null||time(probe.checkedAt)>=time(source.lastSuccessAt)))warnings.push(view('pending','READ_UNAVAILABLE',label+'接口暂不可用,等待读取核验',probe.checkedAt||null));
const unresolvedFailure=time(source.lastFailureAt)!==null&&(time(source.lastSuccessAt)===null||time(source.lastFailureAt)>=time(source.lastSuccessAt));
if(['error','failed','forbidden','login_required'].includes(source.status)||source.status==='running'&&unresolvedFailure)failures.push(view('error','SOURCE_FAILED',label+'读取失败,等待核实或重试',source.lastFailureAt||null));
else if(!source.lastSuccessAt)warnings.push(view('pending','SOURCE_PENDING',label+'等待首次完整读取'));
else if(!fresh(source.lastSuccessAt,sourceFreshMs))warnings.push(view('pending','SOURCE_STALE',label+'读取结果已超过对账周期',source.lastSuccessAt));
}
if(account.reason==='AUTH_REQUIRED'||monitoring.status==='login_required'&&account.status!=='healthy')failures.push(view('error','AUTH_REQUIRED','同步需要恢复 BPM 登录'));
if(['error','failed'].includes(monitoring.status))failures.push(view('error','LISTENER_FAILED','到达监听不可用',monitoring.lastFailureAt||null));
else if(monitoring.status!=='listening')warnings.push(view('pending','LISTENER_PENDING',({polling:'推送暂不可用,正在轮询',connecting:'到达监听正在连接',reconnecting:'到达监听正在重连',busy:'人工登录期间同步暂缓',login_required:'登录会话已恢复,等待监听重连'})[monitoring.status]||'到达监听等待就绪'));
return failures[0]||warnings[0]||view('healthy','SYNC_HEALTHY','监听、待办和通知读取正常',monitoring.lastSyncAt||monitoring.sources?.todo?.lastSuccessAt||null);
};
return {account,sync:sync()};
}
function connectionSnapshot(connection,{manager,monitor,config,now,sessionFreshMs}={}){
const health=manager?.health?.snapshot(connection.id)||connection.health||{};
const monitoring=monitor?.snapshot(connection.id)||connection.monitoring||{status:connection.status==='disabled'?'paused':'waiting'};
const sessionActivity=manager?.sessionSnapshot?.(connection.id)||connection.sessionActivity;
const snapshot={...connection,health,monitoring,...(sessionActivity?{sessionActivity}:{})};
let settings={},configUnavailable=false;
try{settings=(typeof config==='function'?config():config)||monitor?.scanner?.store?.config?.()||{};}catch{configUnavailable=true;}
const connectionState=projectConnectionStatus(snapshot,{config:settings,now,sessionFreshMs:sessionFreshMs??manager?.health?.freshMs,sessionEpoch:manager?.epoch?.(connection.id)});
if(configUnavailable&&connection.status!=='disabled')connectionState.sync=view('pending','SYNC_STATE_UNAVAILABLE','暂时无法读取同步配置,等待后台核验');
return {...snapshot,connectionState};
}
module.exports={projectConnectionStatus,connectionSnapshot};
+18
View File
@@ -0,0 +1,18 @@
'use strict';
const transitions={
connecting:{CONNECTED:'listening',NETWORK_FAILED:'polling',AUTH_REQUIRED:'login_required',BUSY:'busy'},
reconnecting:{CONNECTED:'listening',NETWORK_FAILED:'polling',AUTH_REQUIRED:'login_required',BUSY:'busy'},
listening:{NETWORK_FAILED:'polling',AUTH_REQUIRED:'login_required',BUSY:'busy'}
};
class ListenerState{
constructor(){this.state='waiting';this.revision=0;}
begin(){if(!['waiting','polling','login_required','busy'].includes(this.state))return null;this.state=this.state==='waiting'?'connecting':'reconnecting';return ++this.revision;}
current(ticket){return ticket===this.revision&&['connecting','reconnecting','listening'].includes(this.state);}
transition(event,ticket){
if(event==='STOP'){this.state='stopped';this.revision++;return true;}
if(ticket!==undefined&&!this.current(ticket))return false;
const next=transitions[this.state]?.[event];if(!next)return false;
this.state=next;if(event!=='CONNECTED')this.revision++;return true;
}
}
module.exports={ListenerState};
+111 -56
View File
@@ -6,6 +6,7 @@ const { BpmVault } = require('../../platform/security/vault.cjs');
const { loadPlaywright, browserOptions } = require('../../platform/browser.cjs');
const { BpmListClient } = require('./list-client.cjs');
const {BpmConnectionHealth}=require('./connection-health.cjs');
const {SessionState}=require('./session-state.cjs');
const DEFAULT_URLS = { main: 'https://bpmn.skyworthdigital.com/' };
const { LOGIN_FORMS, fillSavedForm, automaticSubmitForm } = require('./login-form.cjs');
const TTL = 10 * 60 * 1000;
@@ -40,6 +41,7 @@ class BpmSessionManager {
this.browserFactory = browserFactory || (() => loadPlaywright().chromium.launch(browserOptions()));
this.probe = probe || this.defaultProbe.bind(this);
this.accessClient=accessClient;this.health=new BpmConnectionHealth();this.accessChecks=new Map();this.sessionEpochs=new Map();
this.sessionState=new SessionState();this.ensureFlights=new Map();
this.sessions = new Map(); this.operations = new Map(); this.disabled = new Set(); this.revokedSessionHashes=new Set(); this.stopped = false;
}
allowed(url) { try { const parsed = new URL(url); return !parsed.username && !parsed.password && this.allowedOrigins.has(parsed.origin); } catch { return false; } }
@@ -63,7 +65,9 @@ class BpmSessionManager {
// A password rotation retains valid cookies. Only an actual account change revokes
// authentication; first custody can reuse a user's already saved manual login.
await this.vault().write('account:'+connection.id,stored);
this.sessionState.clearCooldown(connection.id);
if (previous && previous.username.trim().toLowerCase()!==stored.username.toLowerCase()) {
this.sessionState.lifecycle(connection.id,'replace');
this.health.clear(connection.id);this.sessionEpochs.set(connection.id,this.epoch(connection.id)+1);
try{await this.vault().remove(connection.id);await this.closeLease(connection.id);}
catch(cause){await this.vault().write('account:'+connection.id,previous);throw cause;}
@@ -72,7 +76,7 @@ class BpmSessionManager {
});
}
async clearAccount(connection,principal) {
return this.run(connection?.id,async()=>{ this.authorize(connection,principal); await this.vault().remove('account:'+connection.id); return this.accountMetadata(null); });
return this.run(connection?.id,async()=>{ this.authorize(connection,principal); await this.vault().remove('account:'+connection.id);this.sessionState.clearCooldown(connection.id); return this.accountMetadata(null); });
}
async fillSavedAccount(lease) {
const stored=await this.vault().read('account:'+lease.id);
@@ -83,71 +87,107 @@ class BpmSessionManager {
async fillAccount(connection,principal) {
return this.run(connection?.id,async()=>{ this.authorize(connection,principal); const lease=await this.getLease(connection.id,principal,true); await this.settleNavigation(lease); return this.fillSavedAccount(lease); });
}
async automaticSubmit(lease,stored,submit=false) {
async automaticSubmit(lease,stored,submit=false,ticket) {
if(this.stopped||this.disabled.has(lease.id))throw error('此连接已停止自动登录。',409);
if(submit&&!this.sessionState.consume(ticket))throw error('自动续登许可已失效,请稍后重新检查。',409);
return automaticSubmitForm(lease,stored,submit,this.loginForms);
}
async persistLease(lease) {
async persistLease(lease,ticket=lease.stateTicket) {
if(ticket)this.sessionState.assert(ticket);
await this.captureSessions(lease);
const storageState=await lease.context.storageState({indexedDB:true});
if(ticket)this.sessionState.assert(ticket);
await this.vault().write(lease.id,{storageState,sessionStorage:lease.sessionStorage});
if(ticket)this.sessionState.assert(ticket);
this.sessionEpochs.set(lease.id,this.epoch(lease.id)+1);
}
canPersistVerified(result) {
return result.status==='connected' && result.checks.portal.ok;
}
epoch(id){return this.sessionEpochs.get(id)||0;}
observe(id,source,cause){this.health.observe(id,source,cause?cause.status===401?'login_required':cause.status===403?'forbidden':'error':'healthy');}
sessionSnapshot(id){return this.sessionState.snapshot(id);}
assertGeneration(id,generation){if(this.stopped||this.disabled.has(id)||this.sessionSnapshot(id).generation!==generation)throw error('BPM 会话状态已变化,请刷新后重试。',409);}
observe(id,source,cause){
if(this.stopped||this.disabled.has(id))return;
this.health.observe(id,source,cause?cause.status===401?'login_required':cause.status===403?'forbidden':'error':'healthy');
if(!cause||cause.status===401||source==='portal')this.sessionState.observe(id,!cause?'valid':cause.status===401?'expired':'unavailable');
}
recordSessionResult(id,result){this.observe(id,'portal',result.status==='connected'?null:{status:result.status==='login_required'?401:502});}
async checkAccess(connection,principal){
this.authorize(connection,principal);const id=connection.id;
if(this.accessChecks.has(id)){const result=await this.accessChecks.get(id);this.authorize(connection,principal);return result;}
this.authorize(connection,principal);const id=connection.id,generation=this.sessionSnapshot(id).generation;
const shared=this.accessChecks.get(id);
if(shared){const result=await shared;this.authorize(connection,principal);this.assertGeneration(id,generation);return result;}
const task=this.run(id,async()=>{
this.authorize(connection,principal);if(this.sessions.has(connection.id))throw error('此连接正在登录窗口中使用。',409);
const saved=await this.vault().read(connection.id),result=await this.accessClient.check(saved?.storageState);this.authorize(connection,principal);
this.health.observe(connection.id,'portal',result.status==='connected'?'healthy':result.status==='login_required'?'login_required':'error');
this.health.observe(connection.id,'todo',result.todo||'unknown');
if(result.storageState&&result.status==='connected')await this.vault().write(connection.id,{...saved,storageState:result.storageState});
return {status:result.status,identity:connection.identity||'',checkedAt:result.checkedAt,checks:result.checks};
});this.accessChecks.set(id,task);try{return await task;}finally{if(this.accessChecks.get(id)===task)this.accessChecks.delete(id);}
this.authorize(connection,principal);this.assertGeneration(id,generation);
if(this.sessions.has(id))throw error('此连接正在登录窗口中使用。',409);
const ticket=this.sessionState.begin(id,'checking');
try{
const saved=await this.vault().read(id),result=await this.accessClient.check(saved?.storageState);
this.authorize(connection,principal);this.sessionState.assert(ticket);
if(result.storageState&&result.status==='connected')await this.vault().write(id,{...saved,storageState:result.storageState});
this.authorize(connection,principal);this.sessionState.assert(ticket);
this.recordSessionResult(id,result);this.health.observe(id,'todo',result.todo||'unknown');
this.sessionState.finish(ticket,result.status==='connected'?'valid':result.status==='login_required'?'expired':'unavailable');
return {status:result.status,identity:connection.identity||'',checkedAt:result.checkedAt,checks:result.checks};
}finally{this.sessionState.abort(ticket);}
});
this.accessChecks.set(id,task);try{return await task;}finally{if(this.accessChecks.get(id)===task)this.accessChecks.delete(id);}
}
async ensure(connection,principal) {
if(this.accessClient){
this.authorize(connection,principal);
if(this.health.recent(connection.id))return {status:'connected',identity:connection.identity||'',checkedAt:this.health.snapshot(connection.id).portal.checkedAt,checks:{portal:{ok:true,message:'最近业务请求已验证登录。'}}};
const result=await this.checkAccess(connection,principal);if(result.status!=='login_required')return result;
async ensure(connection,principal){
this.authorize(connection,principal);const id=connection.id,generation=this.sessionSnapshot(id).generation;
let flight=this.ensureFlights.get(id);
if(!flight||flight.generation!==generation){
if(this.sessions.has(id))throw error('此连接正在登录窗口中使用。',409);
flight={generation,promise:this.recoverSession(connection,principal,generation)};this.ensureFlights.set(id,flight);
flight.promise.finally(()=>{if(this.ensureFlights.get(id)===flight)this.ensureFlights.delete(id);}).catch(()=>{});
}
return this.ensureBrowser(connection,principal);
const result=await flight.promise;this.authorize(connection,principal);this.assertGeneration(id,generation);return result;
}
async ensureBrowser(connection,principal) {
async recoverSession(connection,principal,generation){
if(this.accessClient){
if(this.health.recent(connection.id)){this.sessionState.observe(connection.id,'valid');return {status:'connected',identity:connection.identity||'',checkedAt:this.health.snapshot(connection.id).portal.checkedAt,checks:{portal:{ok:true,message:'最近业务请求已验证登录。'}}};}
const result=await this.checkAccess(connection,principal);this.assertGeneration(connection.id,generation);
if(result.status!=='login_required')return result;
}
this.assertGeneration(connection.id,generation);return this.ensureBrowser(connection,principal,generation);
}
async ensureBrowser(connection,principal,generation=this.sessionSnapshot(connection.id).generation){
return this.run(connection?.id,async()=>{
this.authorize(connection,principal);
if (this.sessions.has(connection.id)) throw error('此连接正在登录窗口中使用。',409);
const lease=await this.create(connection,principal);
try {
let result=await this.verify(lease);
this.authorize(connection,principal);
if (this.canPersistVerified(result)) await this.persistLease(lease);
if (result.status==='connected') return result;
// Network failures and a healthy portal never justify submitting credentials again.
if (result.status!=='login_required' || result.checks.portal.message!=='请在此入口完成登录。' || lease.blocked) return result;
const stored=await this.vault().read('account:'+connection.id);
if (!stored) return result;
const manual=message=>{ if (!result.checks.portal.ok) result.checks.portal.message=message; return result; };
if (Date.parse(stored.nextAttemptAt)>Date.now()) return manual('自动登录暂缓,请稍后重试或更新托管账号。');
await this.readOnlyGoto(lease,this.urls.main);
if (lease.blocked || !this.allowed(lease.page.url())) return manual('请人工检查 BPM 登录页面。');
if (!await this.automaticSubmit(lease,stored)) return manual('需要人工完成验证码或登录验证。');
// Persist before a request to avoid repeated retries after a crash or failed password.
await this.vault().write('account:'+connection.id,{...stored,nextAttemptAt:new Date(Date.now()+15*60*1000).toISOString()});
if (!await this.automaticSubmit(lease,stored,true)) return manual('需要人工完成登录验证。');
await this.settleNavigation(lease);
result=await this.verify(lease);this.authorize(connection,principal);
if (this.canPersistVerified(result)) {
await this.persistLease(lease);delete stored.nextAttemptAt;await this.vault().write('account:'+connection.id,stored);
} else if (!result.checks.portal.ok) result.checks.portal.message='自动登录未完成,请检查托管账号或人工完成验证;稍后重试。';
const id=connection.id;this.authorize(connection,principal);this.assertGeneration(id,generation);
if(this.sessions.has(id))throw error('此连接正在登录窗口中使用。',409);
let ticket=this.sessionState.begin(id,'checking');
try{
const lease=await this.create(connection,principal);let result=await this.verify(lease);
this.authorize(connection,principal);this.sessionState.assert(ticket);
if(this.canPersistVerified(result))await this.persistLease(lease,ticket);
this.recordSessionResult(id,result);this.sessionState.finish(ticket,result.status==='connected'?'valid':result.status==='login_required'?'expired':'unavailable');
if(result.status!=='login_required'||result.checks.portal.message!=='请在此入口完成登录。'||lease.blocked)return result;
const stored=await this.vault().read('account:'+id);this.authorize(connection,principal);this.assertGeneration(id,generation);
if(!stored)return result;
const manual=message=>{if(!result.checks.portal.ok)result.checks.portal.message=message;return result;};
const retryAt=Date.parse(stored.nextAttemptAt);
if(retryAt>Date.now()){this.sessionState.defer(id,retryAt);return manual('自动登录暂缓,请稍后重试或更新托管账号。');}
ticket=this.sessionState.begin(id,'renewing');
await this.readOnlyGoto(lease,this.urls.main);this.authorize(connection,principal);this.sessionState.assert(ticket);
if(lease.blocked||!this.allowed(lease.page.url())||!await this.automaticSubmit(lease,stored)){
this.sessionState.finish(ticket,'expired','manual_required');return manual('需要人工完成验证码或登录验证。');
}
const nextAttempt=Date.now()+15*60*1000;
await this.vault().write('account:'+id,{...stored,nextAttemptAt:new Date(nextAttempt).toISOString()});
this.authorize(connection,principal);this.sessionState.reserve(ticket,nextAttempt);
if(!await this.automaticSubmit(lease,stored,true,ticket)){
this.sessionState.finish(ticket,'expired','manual_required');return manual('需要人工完成登录验证。');
}
await this.settleNavigation(lease);result=await this.verify(lease);
this.authorize(connection,principal);this.sessionState.assert(ticket);
if(this.canPersistVerified(result)){
await this.persistLease(lease,ticket);delete stored.nextAttemptAt;await this.vault().write('account:'+id,stored);
}else if(!result.checks.portal.ok)result.checks.portal.message='自动登录未完成,请检查托管账号或人工完成验证;稍后重试。';
this.authorize(connection,principal);this.sessionState.assert(ticket);this.recordSessionResult(id,result);
this.sessionState.finish(ticket,result.status==='connected'?'valid':result.status==='login_required'?'expired':'unavailable',result.status==='connected'?null:'manual_required');
return result;
} finally { await this.closeLease(connection.id); }
}finally{this.sessionState.abort(ticket);await this.closeLease(id);}
});
}
async scanArrivals(connection,principal) {
@@ -235,7 +275,7 @@ class BpmSessionManager {
}
invalidateBrowser(browser,pending) {
if(this.browserPromise===pending)this.browserPromise=null;
for(const [id,lease] of this.sessions)if(lease.browser===browser){clearTimeout(lease.timer);this.sessions.delete(id);lease.context?.close().catch(()=>{});}
for(const [id,lease] of this.sessions)if(lease.browser===browser){clearTimeout(lease.timer);this.sessions.delete(id);this.sessionState.abort(lease.stateTicket);lease.context?.close().catch(()=>{});}
}
async create(connection, principal) {
this.authorize(connection,principal);
@@ -330,9 +370,14 @@ class BpmSessionManager {
async open(connection, principal) {
return this.run(connection?.id,async()=>{
this.authorize(connection,principal);
const lease=this.sessions.has(connection.id) ? await this.getLease(connection.id,principal,true) : await this.create(connection,principal);
this.authorize(connection,principal);
return { active:true,viewport:{width:1280,height:800},expiresAt:new Date(lease.expiresAt).toISOString(),host:new URL(lease.page.url()).host };
let ticket;
try{
if(!this.sessions.has(connection.id))ticket=this.sessionState.begin(connection.id,'manual');
const lease=this.sessions.has(connection.id)?await this.getLease(connection.id,principal,true):await this.create(connection,principal);
if(ticket)lease.stateTicket=ticket;
this.authorize(connection,principal);if(lease.stateTicket)this.sessionState.assert(lease.stateTicket);
return {active:true,viewport:{width:1280,height:800},expiresAt:new Date(lease.expiresAt).toISOString(),host:new URL(lease.page.url()).host};
}catch(cause){this.sessionState.abort(ticket);throw cause;}
});
}
async frame(id,principal) { return this.run(id,async()=>{ const lease=await this.getLease(id,principal); return lease.page.screenshot({type:'jpeg',quality:75,caret:'initial',timeout:10000}); }); }
@@ -426,8 +471,10 @@ class BpmSessionManager {
this.authorize(connection,principal); const lease=await this.getLease(connection.id,principal,true);
const result=await this.verify(lease);
this.authorize(connection,principal);
if(lease.stateTicket)this.sessionState.assert(lease.stateTicket);
// Failed verification never replaces a previously working credential snapshot.
if (this.canPersistVerified(result)) await this.persistLease(lease);
this.authorize(connection,principal);if(lease.stateTicket)this.sessionState.assert(lease.stateTicket);this.recordSessionResult(connection.id,result);
return result;
});
}
@@ -436,14 +483,20 @@ class BpmSessionManager {
return this.run(connection?.id,async()=>{
this.authorize(connection,principal);
const transient=!this.sessions.has(connection.id);
const lease=transient ? await this.create(connection,principal) : await this.getLease(connection.id,principal,true);
try { const result=await this.verify(lease); this.authorize(connection,principal); if(this.canPersistVerified(result))await this.persistLease(lease); return result; }
finally { if (transient) await this.closeLease(connection.id); }
const ticket=transient?this.sessionState.begin(connection.id,'checking'):null;
try {
const lease=transient?await this.create(connection,principal):await this.getLease(connection.id,principal,true),guard=ticket||lease.stateTicket;
const result=await this.verify(lease);this.authorize(connection,principal);if(guard)this.sessionState.assert(guard);
if(this.canPersistVerified(result))await this.persistLease(lease,guard);
this.authorize(connection,principal);if(guard)this.sessionState.assert(guard);this.recordSessionResult(connection.id,result);
if(ticket)this.sessionState.finish(ticket,result.status==='connected'?'valid':result.status==='login_required'?'expired':'unavailable');return result;
} finally {this.sessionState.abort(ticket);if(transient)await this.closeLease(connection.id);}
});
}
async closeLease(id) {
const lease=this.sessions.get(id); if (!lease) return;
clearTimeout(lease.timer); this.sessions.delete(id);
if(lease.stateTicket)this.sessionState.finish(lease.stateTicket,this.sessionSnapshot(id).authentication);
await lease.context?.close().catch(()=>{});
}
async close(id,principal) { return this.run(id,async()=>{ if (!this.sessions.has(id)) return {active:false}; await this.getLease(id,principal,false,true); await this.closeLease(id); return {active:false}; }); }
@@ -453,12 +506,14 @@ class BpmSessionManager {
for(const hash of revoked)this.revokedSessionHashes.add(hash);
await Promise.all([...this.sessions.values()].filter(lease=>revoked.has(crypto.createHash('sha256').update(lease.sessionId).digest('hex'))).map(lease=>this.run(lease.id,()=>this.closeLease(lease.id))));
}
async suspend(id) { this.disabled.add(id);this.health.clear(id);await this.sessions.get(id)?.context?.close().catch(()=>{}); await this.run(id,()=>this.closeLease(id)); }
async resume(id) { await this.run(id,async()=>{this.disabled.delete(id);this.health.clear(id);}); }
async disable(id) { this.disabled.add(id); await this.run(id,async()=>{ await this.closeLease(id); await this.vault().remove(id); await this.vault().remove('account:'+id); }); }
async suspend(id) { this.disabled.add(id);this.sessionState.lifecycle(id,'pause');this.health.clear(id);await this.sessions.get(id)?.context?.close().catch(()=>{}); await this.run(id,()=>this.closeLease(id)); }
async resume(id) { await this.run(id,async()=>{this.disabled.delete(id);this.sessionState.lifecycle(id,'resume');this.health.clear(id);}); }
async disable(id) { this.disabled.add(id);this.sessionState.lifecycle(id,'stop');this.health.clear(id); await this.run(id,async()=>{ await this.closeLease(id); await this.vault().remove(id); await this.vault().remove('account:'+id); }); }
async shutdown() {
this.stopped=true;
for(const id of this.sessionState.values.keys())this.sessionState.lifecycle(id,'stop');
await Promise.allSettled([...this.operations.values()]);
await Promise.allSettled([...this.ensureFlights.values()].map(flight=>flight.promise));
await Promise.all([...this.sessions.keys()].map(id=>this.closeLease(id)));
if (this.browserPromise) await (await this.browserPromise.catch(()=>null))?.close().catch(()=>{});
this._vault?.destroy();
+38
View File
@@ -0,0 +1,38 @@
'use strict';
const conflict=()=>Object.assign(new Error('BPM 会话状态已变化,请刷新后重试。'),{status:409});
const phases=new Set(['checking','renewing','manual']);
const authentication=new Set(['unknown','valid','expired','unavailable']);
class SessionState{
constructor({clock=()=>Date.now()}={}){this.clock=clock;this.values=new Map();}
value(id){if(!this.values.has(id))this.values.set(id,{phase:'idle',authentication:'unknown',generation:0,revision:0,reason:null,retryAt:null});return this.values.get(id);}
snapshot(id){const {phase,authentication,generation,revision,reason,retryAt}=this.value(id);return {phase,authentication,generation,revision,reason,retryAt};}
begin(id,phase){
const state=this.value(id);
if(!phases.has(phase)||state.phase!=='idle')throw conflict();
if(phase==='renewing'&&(state.authentication!=='expired'||state.retryAt>this.clock()))throw conflict();
state.phase=phase;state.revision++;state.reserved=false;state.consumed=false;
return Object.freeze({id,generation:state.generation,revision:state.revision,phase});
}
current(ticket){if(!ticket)return false;const state=this.value(ticket.id);return state.generation===ticket.generation&&state.revision===ticket.revision&&state.phase===ticket.phase;}
assert(ticket){if(!this.current(ticket))throw conflict();}
reserve(ticket,retryAt){this.assert(ticket);const state=this.value(ticket.id);if(state.phase!=='renewing'||state.reserved||!Number.isFinite(retryAt)||retryAt<=this.clock())throw conflict();state.retryAt=retryAt;state.reason='cooldown';state.reserved=true;}
consume(ticket){if(!this.current(ticket))return false;const state=this.value(ticket.id);if(state.phase!=='renewing'||!state.reserved||state.consumed)return false;state.consumed=true;return true;}
finish(ticket,result,reason=null){
if(!this.current(ticket))return false;
if(!authentication.has(result))throw conflict();
const state=this.value(ticket.id);state.phase='idle';state.authentication=result;state.reason=reason;state.revision++;
if(result==='valid')state.retryAt=null;
return true;
}
abort(ticket){if(this.current(ticket)){const state=this.value(ticket.id);state.phase='idle';state.revision++;}}
observe(id,result){const state=this.value(id);if(['paused','stopped'].includes(state.phase)||!authentication.has(result))return false;state.authentication=result;if(result==='valid'){state.retryAt=null;state.reason=null;}return true;}
defer(id,retryAt,reason='cooldown'){const state=this.value(id);if(state.phase!=='idle'||!Number.isFinite(retryAt))throw conflict();state.retryAt=retryAt;state.reason=reason;}
clearCooldown(id){const state=this.value(id);if(!['paused','stopped'].includes(state.phase)){state.retryAt=null;state.reason=null;}}
lifecycle(id,event){
const state=this.value(id);
if(!['pause','resume','replace','stop'].includes(event)||state.phase==='stopped')return false;
state.generation++;state.revision++;state.phase=event==='pause'?'paused':event==='stop'?'stopped':'idle';state.authentication='unknown';state.retryAt=null;state.reason=event;
return true;
}
}
module.exports={SessionState};
+10 -4
View File
@@ -1,6 +1,7 @@
'use strict';
const fs=require('node:fs'),path=require('node:path'),{DatabaseSync}=require('node:sqlite'),{readSupervisor}=require('../../platform/service/control.cjs'),{redact}=require('../../shared/redact.cjs');
const {monitorEventLoopDelay}=require('node:perf_hooks');
const {connectionSnapshot}=require('../bpm/connection-status.cjs');
function timestamp(value){if(typeof value!=='string')return null;const normalized=/^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/.test(value)?value.replace(' ','T')+'Z':value;const n=Date.parse(normalized);return Number.isFinite(n)?new Date(n).toISOString():null;}
const latest=(...values)=>values.map(timestamp).filter(Boolean).sort().at(-1)||null;
const groupStatus=items=>!items.length?'unconfigured':['error','unknown','running','pending','healthy','paused','disabled'].find(s=>items.some(i=>i.status===s))||'pending';
@@ -23,11 +24,16 @@ class RuntimeHealth {
}
collect(){
const groups=[],safe=(key,title,link,read)=>{try{const items=read();groups.push({key,title,link,status:groupStatus(items),items});}catch{groups.push({key,title,link,status:'unknown',items:[],message:'暂时无法读取此模块状态,请到对应页面核实。'});}};
let connections=[];
let connections=[],connectionViews=[];
safe('bpm','BPM 连接','#bpm',()=>{connections=this.sources.workspace?.snapshot().connections||[];return connections.map(c=>{
const checkedAt=timestamp(c.checkedAt),status=c.status==='disabled'?'disabled':c.status==='connected'?'healthy':['error','login_required'].includes(c.status)?'error':'pending';
return {id:c.id,name:redact(c.name||'BPM 连接'),owner:c.owner,status,checkedAt,detail:status==='error'?'上次验证失败或需要重新登录。':status==='healthy'?'上次已验证登录;连接由后台托管检查。':'尚未验证或已停用。',...this.remember('bpm',c.id,{successAt:latest(c.lastConnectedAt,status==='healthy'?checkedAt:null),failureAt:status==='error'?checkedAt:null})};
const config=()=>this.sources.monitor?.scanner?.store?.config?.()||this.sources.scanner?.store.status().config||{};
const snapshot=connectionSnapshot(c,{manager:this.sources.bpmSessions,monitor:this.sources.monitor,config,now:this.clock()});connectionViews.push(snapshot);
const account=snapshot.connectionState.account,checkedAt=timestamp(account.checkedAt),status=account.status;
return {id:c.id,name:redact(c.name||'BPM 连接'),owner:c.owner,status,checkedAt,reason:account.reason,detail:account.message,...this.remember('bpm',c.id,{successAt:latest(c.lastConnectedAt,status==='healthy'?checkedAt:null),failureAt:['AUTH_REQUIRED','SESSION_UNAVAILABLE'].includes(account.reason)?checkedAt:null})};
});});
safe('bpm-sync','BPM 同步','#bpm',()=>connectionViews.map(c=>{
const sync=c.connectionState.sync;return {id:c.id,name:redact(c.name||'BPM 连接'),owner:c.owner,status:sync.status,reason:sync.reason,checkedAt:timestamp(sync.checkedAt),detail:sync.message};
}));
safe('scan','BPM 扫描','#records',()=>{
const {config={},runs=[]}=this.sources.scanner?.store.status()||{};
for(const r of runs)this.remember('scan',r.connectionId+':'+(r.kind||'inform'),{successAt:r.status==='success'?r.finishedAt:null,failureAt:['error','interrupted'].includes(r.status)?r.finishedAt:null});
@@ -63,7 +69,7 @@ class RuntimeHealth {
return groups;
}
snapshot(user){
const now=this.clock(),groups=this.collect().map(g=>{if(!['bpm','scan','listener','handoff','execution'].includes(g.key)||user.role==='admin'||g.status==='unknown')return g;const items=g.items.filter(i=>i.global||i.owner===user.username);return {...g,items,status:groupStatus(items)};});
const now=this.clock(),groups=this.collect().map(g=>{if(!['bpm','bpm-sync','scan','listener','handoff','execution'].includes(g.key)||user.role==='admin'||g.status==='unknown')return g;const items=g.items.filter(i=>i.global||i.owner===user.username);return {...g,items,status:groupStatus(items)};});
let saved;try{saved=readSupervisor(this.stateDir);}catch{saved={state:null,events:[],autostart:null};}
const s=saved.state,managed=Boolean(this.instanceId&&s?.childInstanceId===this.instanceId),fresh=managed&&now-Date.parse(s.updatedAt)<45000;
const guard=managed?{status:fresh?s.status:'stale',heartbeatAt:s.heartbeatAt,updatedAt:s.updatedAt,restartCount:s.restartCount,childStartedAt:s.childStartedAt,reason:s.reason,nextRestartAt:s.nextRestartAt,events:saved.events.map(e=>({at:e.at,kind:e.kind,code:e.detail.code,delayMs:e.detail.delayMs,reason:e.detail.reason}))}:{status:'unmanaged',restartCount:0,events:[]};
+2 -1
View File
@@ -1,9 +1,10 @@
// This router is called only after dashboard authentication and same-origin validation.
const {connectionSnapshot}=require('../bpm/connection-status.cjs');
async function workspaceApi({workspace,store,user,route,method,body,reply,bpmSessions,bpmMonitor,bpmLifecycle,orderRules}){
if(!workspace)return false;
const members=()=>store.users();
if(route==='/api/workspace'||route.startsWith('/api/exceptions'))workspace.syncBusinessIssues?.(orderRules?.all('business-issues')||[],members());
if(route==='/api/workspace' && method==='GET'){const snapshot=workspace.snapshot(members());snapshot.capabilities.remoteLogin=Boolean(bpmSessions);snapshot.connections=snapshot.connections.map(c=>({...c,health:bpmSessions?.health?.snapshot(c.id)||{},monitoring:bpmMonitor?.snapshot(c.id)||{status:c.status==='disabled'?'paused':'waiting'}}));reply(200,snapshot);return true;}
if(route==='/api/workspace' && method==='GET'){const snapshot=workspace.snapshot(members());snapshot.capabilities.remoteLogin=Boolean(bpmSessions);snapshot.connections=snapshot.connections.map(c=>connectionSnapshot(c,{manager:bpmSessions,monitor:bpmMonitor}));reply(200,snapshot);return true;}
if(method!=='POST')return false;
if(route==='/api/calendar'){reply(200,workspace.saveCalendar(body,user));return true;}
if(route==='/api/exceptions'){reply(201,workspace.createException(body,user,members()));return true;}
+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());
});
+2
View File
@@ -58,3 +58,5 @@
.rule-scope-row .ts-wrapper{min-width:0;font-size:.8rem}.rule-scope-node-control>.ts-wrapper{flex:1;min-width:0}.rule-scope-node-control>.ts-wrapper .ts-control{border-top-right-radius:0;border-bottom-right-radius:0}.rule-scope-row .ts-dropdown{z-index:20}.rule-scope-row .ts-dropdown .option{overflow-wrap:anywhere}
.rule-scope-row .ts-wrapper{--bs-body-bg:var(--tblr-bg-surface,#fff);--bs-body-color:var(--tblr-body-color,#182433);--bs-border-radius:var(--tblr-border-radius,6px)}
.bpm-account-status{display:inline-flex;align-items:center;gap:7px;font-size:.8rem;font-weight:600;white-space:nowrap}.bpm-status-light{width:9px;height:9px;border-radius:50%;background:currentColor;flex-shrink:0}.bpm-status-green{color:#23834b}.bpm-status-yellow{color:#996600}.bpm-status-red{color:#c53030}.bpm-status-details>summary{cursor:pointer;font-size:.8rem;color:#657b81}.bpm-status-details>div{display:flex;gap:.75rem;flex-wrap:wrap;align-items:center;margin-top:.65rem}
.bpm-sync-summary{display:flex;align-items:center;gap:.75rem;flex-wrap:wrap}
+9 -6
View File
@@ -1,7 +1,7 @@
'use strict';
window.BpmLogin=(()=>{
let active=null,releasing=null,releasePending=Promise.resolve();
const statuses={disconnected:['未连接','secondary'],unchecked:['待检查','yellow'],login_required:['待登录','yellow'],connected:['已连接','green'],disabled:['已停用','secondary'],error:['检查失败','red']};
const observation=(c,kind)=>c.connectionState?.[kind]||{status:'pending',message:'等待后台更新状态'};
function dispose(options={}){const previous=active||releasing;active=null;if(previous){releasing=previous;releasePending=previous.dispose(options);releasePending.finally(()=>{if(releasing===previous)releasing=null;});}return releasePending;}
async function mount(container,{api,esc,formatDate,notify,user,isActive=()=>true}){
await dispose();
@@ -12,7 +12,7 @@ window.BpmLogin=(()=>{
const $=selector=>container.querySelector(selector);
const authorized=c=>user.role==='admin'||(user.role==='operator'&&c.owner===user.username);
const route=(id,action)=>`/connections/${encodeURIComponent(id)}/${action}`;
const status=c=>{const [label,color]=statuses[c.status]||statuses.error;return `<span class="badge bg-${color}-lt">${label}</span>`;};
const status=(c,kind='account')=>{const state=observation(c,kind),[color,label]=({healthy:['green','健康'],error:['red','异常'],pending:['yellow','警告'],paused:['yellow','已暂停']})[state.status]||['yellow','待确认'];return `<span class="bpm-account-status bpm-status-${color}"><span class="bpm-status-light" aria-hidden="true"></span>${kind==='account'?'账号':'同步'} · ${label}</span>`;};
function feedback(message,type='danger'){if(!live())return;const el=$('[data-bpm-feedback]');if(el){el.hidden=false;el.className=`alert alert-${type}`;el.textContent=message;}notify(message,type);}
function release(r,{unload=false}={}){
r.closed=true;clearTimeout(r.timer);r.controller?.abort();if(r.url){URL.revokeObjectURL(r.url);r.url=null;}
@@ -28,7 +28,7 @@ window.BpmLogin=(()=>{
if(!valid(r)||r.busy)return;
r.queue=r.queue.then(()=>{if(valid(r)&&!r.failed)return api(route(r.id,'login/input'),action);}).catch(()=>{if(valid(r)){r.failed=true;feedback('输入未送达,请关闭后重新打开登录窗口。');}});
}
function update(result,id){++statusRevision;const saved=result.connection||result;connections=connections.map(c=>c.id===id?{...c,...saved,id}:c);drawCards();}
function update(result,id){++statusRevision;const saved=result.connection||result;connections=connections.map(c=>c.id===id?{...c,...saved,id,connectionState:saved.connectionState||null}:c);drawCards();}
function rememberAccount(id,result){const metadata={configured:result.configured===true,username:typeof result.username==='string'?result.username:'',updatedAt:result.updatedAt||null};accounts.set(id,metadata);return metadata;}
function loadAccount(id){
if(accounts.has(id))return Promise.resolve(accounts.get(id));
@@ -84,14 +84,15 @@ window.BpmLogin=(()=>{
return row(label,info.status||'待确认',info.lastSuccessAt)+row(label+'最近失败',info.lastFailureAt?'失败':'无',info.lastFailureAt)+row(label+'重试时间',info.retryAt?formatDate(info.retryAt):'无');
};
const delivery=monitoring.delivery||{};
return row('登录会话',portal?(Date.now()-Date.parse(portal.checkedAt)>300000?'上次检查'+(state[portal.status]||'待确认'):state[portal.status]||'待确认'):legacy?.message||'尚未检查',portal?.checkedAt||c.checkedAt)
return '<p class="small mb-2">'+esc(observation(c,'account').message)+'</p><div class="bpm-sync-summary mb-2"><span data-sync-status>'+status(c,'sync')+'</span><span class="small">'+esc(observation(c,'sync').message)+'</span></div><details class="bpm-status-details"><summary>状态详情</summary>'+row('登录会话',portal?(state[portal.status]||'待确认'):legacy?.message||'尚未检查',portal?.checkedAt||c.checkedAt)
+(c.sessionActivity?row('会话操作',({idle:'空闲',checking:'检查中',renewing:'自动续登中',manual:'人工登录中',paused:'已暂停',stopped:'已停止'})[c.sessionActivity.phase]||'待确认')+(Number.isFinite(c.sessionActivity.retryAt)?row('续登重试',formatDate(new Date(c.sessionActivity.retryAt).toISOString())):''):'')
+row('订单接口',state[health.todo?.status]||'尚未检查',health.todo?.checkedAt)
+row('到达监听',monitor[monitoring.status]||'等待就绪',monitoring.lastSyncAt)
+source('todo','待办源读取')+source('inform','通知源读取')
+row('下一完整对账',monitoring.nextReconcileAt?formatDate(monitoring.nextReconcileAt):'未排队')
+row('本地执行器投递',(delivery.status||'尚无投递')+' · 待交付 '+(delivery.pending||0),delivery.lastSuccessAt)
+row('投递重试',delivery.retryAt?formatDate(delivery.retryAt):'无')
+(delivery.message?row('投递说明',delivery.message):'');
+(delivery.message?row('投递说明',delivery.message):'')+'</details>';
}
async function refreshStatus(){
if(!live())return;
@@ -99,7 +100,7 @@ window.BpmLogin=(()=>{
if(accountBusy||mutationBusy)return;const request=statusRevision,next=await api('/workspace');if(!live()||request!==statusRevision)return;
const rows=next.connections||[],changed=JSON.stringify(connections.map(c=>[c.id,c.status,c.version,c.owner]))!==JSON.stringify(rows.map(c=>[c.id,c.status,c.version,c.owner]));connections=rows;
if(changed&&!remote&&!container.querySelector('[data-account-form]')&&!window.PageLifecycle?.dirty())drawCards();
else for(const c of connections){const badge=container.querySelector('[data-connection-status="'+c.id+'"]'),health=container.querySelector('[data-connection-health="'+c.id+'"]');if(badge)badge.innerHTML=status(c);if(health)health.innerHTML=observations(c);}
else for(const c of connections){const badge=container.querySelector('[data-connection-status="'+c.id+'"]'),health=container.querySelector('[data-connection-health="'+c.id+'"]');if(badge)badge.innerHTML=status(c);if(health){const expanded=health.querySelector('details')?.open;health.innerHTML=observations(c);if(expanded)health.querySelector('details').open=true;}}
}catch{}finally{if(live())statusTimer=setTimeout(refreshStatus,5000);}
}
function ownerForm(c){
@@ -108,8 +109,10 @@ window.BpmLogin=(()=>{
}
function drawCards(){
if(!live())return;
const expanded=new Set([...container.querySelectorAll('[data-connection-health]')].filter(el=>el.querySelector('details')?.open).map(el=>el.dataset.connectionHealth));
container.querySelectorAll('[data-account-form]').forEach(form=>form.reset());
$('#bpm-list').innerHTML=connections.length?connections.map(c=>`<article class="card mb-3"><div class="card-header"><span class="connection-avatar" aria-hidden="true">B</span><div class="flex-fill"><h3 class="card-title mb-1">${esc(c.name)}</h3><span class="text-secondary small">负责人 ${esc(c.owner||'未分配')}</span></div><span data-connection-status="${esc(c.id)}">${status(c)}</span></div><div class="card-body"><div class="connection-url"><span class="text-secondary">新版门户</span><span>bpmn.skyworthdigital.com</span></div>${c.identity?`<div class="small mt-2">登录账号 ${esc(c.identity)}</div>`:''}${c.checkedAt?`<div class="small text-secondary mt-2">上次检查 ${esc(formatDate(c.checkedAt))}</div>`:''}<div class="bpm-checks mt-3" data-connection-health="${esc(c.id)}">${observations(c)}</div></div>${c.status!=='disabled'&&authorized(c)?`<div class="card-footer d-flex gap-2 flex-wrap">${data.capabilities?.remoteLogin?`<button class="btn btn-primary" data-login="${esc(c.id)}" ${remote?'disabled':''}>远程登录</button><button class="btn" data-check="${esc(c.id)}" ${remote?'disabled':''}>检查连接</button>`:'<span class="text-secondary small">远程登录未启用</span>'}<button class="btn" data-account="${esc(c.id)}" ${remote?'disabled':''}>${accounts.get(c.id)?.configured?'管理账号':'开启自动续登'}</button>${user.role==='admin'?`<button class="btn btn-outline-danger ms-auto" data-disable="${esc(c.id)}" ${remote?'disabled':''}>停用连接</button>`:''}</div><div class="bpm-account-summary small text-secondary" data-account-summary="${esc(c.id)}">${esc(accountSummary(c))}</div><div class="bpm-account-panel" data-account-panel hidden></div>`:c.status==='disabled'&&user.role==='admin'?`<div class="card-footer d-flex gap-2"><button class="btn btn-primary" data-enable="${esc(c.id)}" ${remote?'disabled':''}>启用连接</button><span class="small text-secondary align-self-center">账号、会话和历史保留</span><button class="btn btn-outline-danger ms-auto" data-delete="${esc(c.id)}" ${remote?'disabled':''}>删除</button></div>`:''}${ownerForm(c)}</article>`).join(''):'<div class="card"><div class="workspace-empty"><h3>还没有 BPM 连接</h3><p class="text-secondary mb-0">请管理员添加连接并指定负责人。</p></div></div>';
container.querySelectorAll('[data-connection-health]').forEach(el=>{if(expanded.has(el.dataset.connectionHealth))el.querySelector('details').open=true;});
container.querySelectorAll('[data-owner-transfer]').forEach(form=>form.onsubmit=async event=>{
event.preventDefault();if(remote||mutationBusy)return;
const c=connections.find(c=>c.id===form.dataset.ownerTransfer),button=form.querySelector('button');