perf: cache static assets and validate only requested refresh regions

This commit is contained in:
abaishu0730 committed 2026-10-28 12:11:19 +08:00
1 parent f317314a3c
commit 73773f9526
31 files changed
+554 -41

No files matched your search

+8
View File
@@ -1,5 +1,13 @@
# 开发交接(2026-10-23)
## 2026-10-28 缓存刷新收尾与按需区域校验
- 接续 `codex/system-update` 上一轮中断前的静态指纹缓存、后端 revision 与前端区域刷新改动。新增 `GET /api/refresh/revisions?regions=assistant` 等按需校验,旧的无参数八区域响应兼容;校验区域白名单、重复/空参数,保持认证、账号隔离与 `no-store`。助手频繁轮询不再访问订单、BPM、存储或 PDF 台账等无关模块。
- 修复审查复现的手动刷新空操作:取消并等待旧请求后清除消费者的已应用 token,强制本次重读取;定时检查继续跳过未变化区域。并发手动刷新仍合并,草稿、筛选、权限及时间边界保持。
- 合成内存 SQLite、5 万订单、每项 300 次采样:全八区域校验中位 5.44 ms / 635 B / 21 次 SQL,助手单区域 0.135 ms / 104 B / 1 次 SQL;首页加顶栏合计 4.37 ms / 204 B / 11 次 SQL。不是生产 CPU、内存或网络 SLA;夹具与边界见 [缓存与区域刷新](cache-region-refresh-2026-10-28.md)。
- 最新 `npm test` 404/404 通过,无失败或跳过;28 个改动脚本语法检查、依赖树与 `git diff --check` 通过,独立审查发现的手动刷新 P2 已修复复核。未运行历史 `test:full`。测试前基线曾遇一次 Windows ACL 子进程超时,最终完整业务回归未复现;保留原始日志,不降低存储保护。
- 开发与验证使用原目标工作区 `C:/Users/ABS/.codex/worktrees/system-update/Order Notification Automation`,桌面应用直接关联该既有目录时无法核实归属。提交范围仅为源码、测试与文档,诊断日志及基准夹具留在忽略的 `output` 中。未部署服务、修改真实业务配置或调用真实 BPM/SMTP/SMB;主目录 `dsh` 的独立改动保持。
## 2026-10-27 分类规则设置响应优化
- 规则页改用专用configuration读取,只返回编辑元数据和资源摘要;顶栏用轻状态接口。首次进入不再读取业务summary或完整执行/字段快照,样本在第04步点击“读取已采集订单”时按当前流程和连接权限读取。
+76
View File
@@ -0,0 +1,76 @@
# 静态缓存与分区域刷新验证
本轮把缓存和动态刷新拆成两个边界:公共静态文件允许长期缓存,业务数据只使用用户隔离的短小 revision 验证。没有把订单、邮件正文、凭据或 BPM 证据放进浏览器缓存,也没有改变业务匹配、发送、冻结、未知结果或权限规则。
## 静态资源
根 HTML 响应在服务端读取自身引用的脚本、样式和公开预览资源,按实际内容生成 SHA-256 指纹并改写为 `?v=<64hex>`。只有指纹与当前文件内容完全一致时,资源才返回:
```text
Cache-Control: public, max-age=31536000, immutable
```
HTML 自身始终使用 ETag 和 `max-age=0, must-revalidate`,因此新版本可以在下一次打开时重新验证并获得新的依赖指纹。没有指纹或指纹错误的资源仍然使用 ETag 重新验证策略。压缩、HEAD、预览隔离 CSP、资源变化检测和并发读取行为保留。
隔离 Chromium 测量(基线为 `f317314`,相同 44 个静态请求):
| 场景 | 基线 | 当前 |
| --- | ---: | ---: |
| 再次加载的静态资源网络请求 | 44 个 304 | 0 个 |
| 再次加载的静态资源响应正文 | 0 B | 0 B |
| HTML | 每次条件验证 | 每次条件验证 |
冷打开静态正文约 297 KiB;当前指纹 HTML 会增加少量首屏计算和文档字节,换取后续刷新不再往返 44 个资源。API 保持请求且 `no-store`。
## 动态区域
`GET /api/refresh/revisions` 返回:
```json
{
"version": 1,
"regions": {
"home": "…",
"orderRules": "…",
"records": "…",
"health": "…",
"bpm": "…",
"assistant": "…",
"storage": "…",
"mail": "…"
}
}
```
每个 token 是服务实例密钥生成的 HMAC,包含账号身份、角色、账号版本和可见连接归属。各 SQLite 数据库通过事务触发器维护按表或按业务类型的计数,外部连接写入、回滚和同一状态内容变更均有测试覆盖;验证接口不读取订单/邮件正文,也不构造完整快照。助手只读取当前账号的会话/操作元数据,存储不存在的可选模块返回稳定的 disabled 标记,已配置但暂时读取失败的区域返回随机 token 和安全错误。
### 后续资源优化:按需计算区域
接口增加可选 `regions` 参数,例如 `GET /api/refresh/revisions?regions=assistant`。只计算并返回指定区域;不传参数仍返回原来的八个区域。允许逗号分隔的已知区域,空值、重复区域、重复参数和未知区域返回 400;认证、账号隔离及 `no-store` 保持。各页面传入自身区域,顶栏请求 `orderRules`,不再让每次助手轮询打开 PDF 台账数据库或访问无关模块。
同时修复上一轮遗留的手动刷新问题:取消并等待旧请求后清除该消费者已应用的 token,再读取当前区域与业务数据。手动刷新不再因 token 相同而被跳过,后续定时检查仍可跳过重读取。
同一实现的全区域旧调用与按需调用对比:内存 SQLite、单个合成连接、五万条每条 512 B 的合成订单;每项预热 30 次、采样 300 次,中位数如下。首页与 PDF 台账项目包含独立顶栏检查,因此每周期是两次接口调用。
| 校验工作负载 | 中位耗时 | 每周期响应正文 | 每周期 SQL 读取 |
| --- | ---: | ---: | ---: |
| 原八区域校验 | 5.44 ms | 635 B | 21 |
| 助手区域 | 0.135 ms | 104 B | 1 |
| 首页与顶栏合计 | 4.37 ms | 204 B | 11 |
| PDF 台账与顶栏合计 | 4.50 ms | 207 B | 11 |
此夹具没有操作审计库;配置该库后助手还需读取其最新事件元数据。SQL 计数不包括应用认证;内存数据库与固定时钟用于隔离选择逻辑,不代表生产 HTTP 延迟、磁盘 I/O、CPU 或内存使用降幅。原始脚本及聚合结果在忽略目录 `output/performance-refresh-20261028/resource-selection-benchmark.*`。
前端区域 poller 在隐藏页面暂停,恢复后先验证 token;token 未变化时跳过重数据请求,变化时读取对应页面数据。手动刷新不因 token 相同跳过重读取;校验失败明确报错并可重试。后台订单/批次列表只显示“有更新”提示,保留当前列表、筛选、草稿和详情;PDF 台账每 60 秒仍会检查文件可用性,避免外部文件变化长期不被发现。写操作会使相关区域失效,旧导航或旧账号的结果不能确认新页面状态。
## 验证
- 区域 revision 单测:10/10;HTTP 权限、`no-store`、跨账号 token:1/1。
- 生命周期/区域 poller VM 测试:11/11。
- 区域浏览器测试:3/3;覆盖 token 未变跳过摘要、token 变化后更新、健康和记录筛选保留、初次 revision 失败仍能打开页面。
- 静态资源、压缩、指纹、HTML 依赖变化、预览和 dashboard HTTP 测试:9/9。
- 区域 revision 隔离基准:8 区域响应约 635 B;空历史中位约 6.5 ms,5 万订单约 5.7 ms,再加 5 万旧助手轮次约 6.8 ms;正文枚举/解密守卫触发 0 次。
这些数据来自本地隔离数据库和浏览器,不能作为生产网络 SLA。revision 只证明本地持久状态或权限相关元数据变化;它不能证明 BPM、SMTP、SMB 或模型服务当前外部连通。
本轮最终 `npm test` 为 404/404 通过,0 失败、0 跳过,包含区域选择 4 项、生命周期区域 poller 8 项、区域浏览器 3 项,以及带区域参数的真实 HTTP 鉴权与错误响应。28 个改动脚本语法检查、依赖树和 `git diff --check` 通过;未运行历史 `test:full`。独立复核已验证手动刷新并发合并、取消等待和校验失败后可重试,没有剩余具体 P1/P2。初次基线 16/17 通过,失败来自 Windows ACL 子进程超时,最终完整业务回归没有该失败;日志保留在忽略目录 `output/performance-refresh-20261028/resource-*.log`。
+1 -1
View File
@@ -13,7 +13,7 @@
"service:stop": "node scripts/service.cjs stop",
"service:restart": "node scripts/service.cjs restart",
"test": "npm run test:business",
"test:business": "node --test --test-concurrency=1 tests/app/business-home-ui.test.cjs tests/order-rules/home-summary.test.cjs tests/order-rules/carry-forward-core.test.cjs tests/order-rules/carry-forward-integration.test.cjs tests/order-rules/dispatch-unsent-proof.test.cjs tests/order-rules/dismiss-task.test.cjs tests/app/carry-dismiss-ui.test.cjs tests/workspace/business-issues.test.cjs tests/mail/unified-account.test.cjs tests/mail/unified-account-ui.test.cjs tests/assistant/assistant.test.cjs tests/assistant/assistant-http-ui.test.cjs tests/assistant/controlled-operations.test.cjs tests/assistant/dsh-runtime.test.cjs tests/assistant/dsh-runtime-installer.test.cjs tests/assistant/repair-runner.test.cjs tests/app/automatic-pdf-ledger.test.cjs tests/app/job-records.test.cjs tests/order-rules/version-compatibility.test.cjs tests/bpm-display-policy.test.cjs tests/bpm-dynamicarea.test.cjs tests/bpm-readonly-form.test.cjs tests/bpm-form-contracts.test.cjs tests/bpm-obsolete-display-fields.test.cjs tests/order-rules/snapshot-read-context.test.cjs tests/order-rules/summary.test.cjs tests/order-rules/execution-single-flight.test.cjs tests/order-rules/execution-responsiveness.test.cjs tests/order-rules/readiness-pending-ui.test.cjs tests/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/collecting-batches.test.cjs tests/order-rules/collecting-batches-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs tests/system-update/checker.test.cjs tests/system-update/system-update.test.cjs tests/order-rules/configuration.test.cjs tests/order-rules/configuration-ui.test.cjs tests/order-rules/workbench-ui.test.cjs tests/app/asset-delivery.test.cjs tests/app/authentication-responsiveness.test.cjs tests/app/backend-refresh-performance.test.cjs tests/app/read-refresh-performance.test.cjs tests/app/polling-performance-ui.test.cjs tests/order-rules/query-read-performance.test.cjs tests/mail/history.test.cjs tests/storage/storage-range.test.cjs",
"test:business": "node --test --test-concurrency=1 tests/app/business-home-ui.test.cjs tests/order-rules/home-summary.test.cjs tests/order-rules/carry-forward-core.test.cjs tests/order-rules/carry-forward-integration.test.cjs tests/order-rules/dispatch-unsent-proof.test.cjs tests/order-rules/dismiss-task.test.cjs tests/app/carry-dismiss-ui.test.cjs tests/workspace/business-issues.test.cjs tests/mail/unified-account.test.cjs tests/mail/unified-account-ui.test.cjs tests/assistant/assistant.test.cjs tests/assistant/assistant-http-ui.test.cjs tests/assistant/controlled-operations.test.cjs tests/assistant/dsh-runtime.test.cjs tests/assistant/dsh-runtime-installer.test.cjs tests/assistant/repair-runner.test.cjs tests/app/automatic-pdf-ledger.test.cjs tests/app/job-records.test.cjs tests/order-rules/version-compatibility.test.cjs tests/bpm-display-policy.test.cjs tests/bpm-dynamicarea.test.cjs tests/bpm-readonly-form.test.cjs tests/bpm-form-contracts.test.cjs tests/bpm-obsolete-display-fields.test.cjs tests/order-rules/snapshot-read-context.test.cjs tests/order-rules/summary.test.cjs tests/order-rules/execution-single-flight.test.cjs tests/order-rules/execution-responsiveness.test.cjs tests/order-rules/readiness-pending-ui.test.cjs tests/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/collecting-batches.test.cjs tests/order-rules/collecting-batches-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs tests/system-update/checker.test.cjs tests/system-update/system-update.test.cjs tests/order-rules/configuration.test.cjs tests/order-rules/configuration-ui.test.cjs tests/order-rules/workbench-ui.test.cjs tests/app/asset-delivery.test.cjs tests/app/authentication-responsiveness.test.cjs tests/app/backend-refresh-performance.test.cjs tests/app/read-refresh-performance.test.cjs tests/app/polling-performance-ui.test.cjs tests/order-rules/query-read-performance.test.cjs tests/mail/history.test.cjs tests/storage/storage-range.test.cjs tests/app/region-revisions.test.cjs tests/app/region-revisions-http.test.cjs tests/app/region-refresh.test.cjs tests/app/region-refresh-ui.test.cjs tests/app/region-selection.test.cjs",
"test:full": "node --test --test-concurrency=2 \"tests/**/*.test.cjs\""
},
"engines": {
+22 -4
View File
@@ -8,20 +8,37 @@ function encodingFor(header=''){
if(weights.has('identity')&&weight('identity')>(choices[0]?.q||0))return 'identity';
return choices[0]?.name||(weight('identity')>0?'identity':null);
}
function requestedFingerprint(request){
try {
const url=new URL(request.url||'http://localhost/','http://localhost');
const values=url.searchParams.getAll('v');
return values.length===1&&/^[0-9a-f]{64}$/.test(values[0])?values[0]:null;
}catch{return null;}
}
// Only public assets from createAssets enter this bounded cache; APIs and managed
// files retain no-store. Stat validation allows an edited installation to update.
function createAssetDelivery({maxBytes=32*1024*1024}={}){
function createAssetDelivery({maxBytes=32*1024*1024,resolveAsset}={}){
const cache=new Map(),pending=new Map();let size=0;
let documentValue=null,documentKey=null;
const valueFor=(bytes,version)=>{const fingerprint=crypto.createHash('sha256').update(bytes).digest('hex');return {version,bytes,fingerprint,etag:'W/"'+fingerprint+'"',encodings:new Map()};};
async function load(asset){
const stat=await fs.stat(asset.path),version=[stat.size,stat.mtimeMs,stat.ctimeMs].join(':'),saved=cache.get(asset.path);
if(saved?.version===version){cache.delete(asset.path);cache.set(asset.path,saved);return saved;}
const key=asset.path+':'+version;if(pending.has(key))return pending.get(key);
const work=(async()=>{
const bytes=await fs.readFile(asset.path),value={version,bytes,etag:'W/"'+crypto.createHash('sha256').update(bytes).digest('hex')+'"',encodings:new Map()};
const bytes=await fs.readFile(asset.path),value=valueFor(bytes,version);
if(bytes.length<=maxBytes/2){const current=cache.get(asset.path);if(current){size-=current.size;cache.delete(asset.path);}value.size=bytes.length;cache.set(asset.path,value);size+=value.size;trim();}
return value;
})();pending.set(key,work);try{return await work;}finally{pending.delete(key);}
}
async function documentWithVersions(asset,value){
if(asset.type!=='text/html'||asset.preview||!resolveAsset)return value;
const source=value.bytes.toString('utf8'),urls=[...new Set([...source.matchAll(/(?:src|href)="(\/(?!\/)[^"#]+)"/g)].map(match=>match[1]))];
const versions=await Promise.all(urls.map(async route=>{const url=new URL(route,'http://localhost'),dependency=resolveAsset(url.pathname);if(!dependency||dependency.type==='text/html')return [route,route];const content=await load(dependency);url.searchParams.set('v',content.fingerprint);return [route,url.pathname+url.search];}));
const key=JSON.stringify([asset.path,value.fingerprint,versions]);if(key===documentKey)return documentValue;
const replacements=new Map(versions),bytes=Buffer.from(source.replace(/((?:src|href)=")(\/(?!\/)[^"#]+)(")/g,(_,prefix,route,suffix)=>prefix+(replacements.get(route)||route)+suffix));
documentKey=key;documentValue=valueFor(bytes,key);return documentValue;
}
function trim(){while(size>maxBytes&&cache.size){const [key,value]=cache.entries().next().value;size-=value.size;cache.delete(key);}}
async function compressed(asset,value,encoding){
if(!value.encodings.has(encoding))value.encodings.set(encoding,(async()=>{
@@ -31,8 +48,9 @@ function createAssetDelivery({maxBytes=32*1024*1024}={}){
return value.encodings.get(encoding);
}
return async function deliver(request,response,asset){
const value=await load(asset),encoding=encodingFor(request.headers['accept-encoding']);
response.setHeader('Cache-Control','public, max-age=0, must-revalidate');response.setHeader('ETag',value.etag);response.setHeader('Vary','Accept-Encoding');
const value=await documentWithVersions(asset,await load(asset)),encoding=encodingFor(request.headers['accept-encoding']);
const immutable=asset.type!=='text/html'&&requestedFingerprint(request)===value.fingerprint;
response.setHeader('Cache-Control',immutable?'public, max-age=31536000, immutable':'public, max-age=0, must-revalidate');response.setHeader('ETag',value.etag);response.setHeader('X-Asset-Version',value.fingerprint);response.setHeader('Vary','Accept-Encoding');
if(!encoding){response.writeHead(406);response.end();return;}
const tags=String(request.headers['if-none-match']||'').split(',').map(tag=>tag.trim().replace(/^W\//,''));
if(tags.includes('*')||tags.includes(value.etag.replace(/^W\//,''))){response.writeHead(304);response.end();return;}
+4 -1
View File
@@ -14,6 +14,7 @@ const {assistantApi}=require('../modules/assistant/api.cjs');
const {respondToPing}=require('../platform/service/ping.cjs');
const {createAssets,PREVIEW_CSP}=require('./assets.cjs');
const {createAssetDelivery}=require('./asset-delivery.cjs');
const {createRegionRevisions}=require('./region-revisions.cjs');
const {createAuth}=require('../modules/dashboard/auth.cjs');
const {prepareRequest,readBody}=require('./request.cjs');
const {BpmConnectionLifecycle}=require('../modules/bpm/connection-lifecycle.cjs');
@@ -22,7 +23,8 @@ function createDashboard({store,outputDir,workspace,bpmSessions,bpmMonitor,mail,
const bpmLifecycle=workspace?new BpmConnectionLifecycle({workspace,manager:bpmSessions,monitor:bpmMonitor}):null;
const auth=createAuth({store,workspace,bpmSessions,bpmMonitor,bpmLifecycle});
let assetFor;try{assetFor=createAssets();}catch(error){auth.close();throw error;}
const deliverAsset=createAssetDelivery();
const deliverAsset=createAssetDelivery({resolveAsset:assetFor});
const regionRevisions=createRegionRevisions({store,workspace,bpmSessions,bpmMonitor,mail,scanner,storage,orderRules,orderExecution,assistant,health});
const server=http.createServer(async(request,response)=>{
if(respondToPing(request,response,watchdog))return;
const {encryptedTransport,reply,fail}=prepareRequest(request,response,trustedProxy);
@@ -38,6 +40,7 @@ function createDashboard({store,outputDir,workspace,bpmSessions,bpmMonitor,mail,
const authResult=await auth.authenticate({request,response,route,body,reply,fail,encryptedTransport});
if(authResult.handled)return;
const {user,token}=authResult;
if(regionRevisions.api({route,url,method:request.method,user,response,reply}))return;
if(route==='/api/update' && request.method==='GET') {
const result=await (updateChecker|| (async()=>({status:'unavailable',currentVersion:require('../../package.json').version,latest:null})))();
return reply(200,result);
+76
View File
@@ -0,0 +1,76 @@
'use strict';
const crypto=require('node:crypto');
const {readRevisions}=require('../shared/refresh-revisions.cjs');
const {upcomingWindow}=require('../modules/order-rules/window.cjs');
const {connectionSnapshot}=require('../modules/bpm/connection-status.cjs');
const REGION_NAMES=Object.freeze(['home','orderRules','records','health','bpm','assistant','storage','mail']);
const fail=()=>{throw Object.assign(Error('请先登录。'),{status:401});};
function createRegionRevisions(context){
// A new server always invalidates browser validators, including restored DBs.
// These are change validators only: a changed token requests a fresh bounded
// resource read; it never authorizes a write or claims that an external BPM,
// SMB, SMTP, or model provider is reachable. External side effects are folded
// in only through their persisted local observation/revision metadata.
const key=crypto.randomBytes(32);
const token=value=>crypto.createHmac('sha256',key).update(JSON.stringify(value)).digest('hex');
function snapshot(user,selection=REGION_NAMES){
if(!user||!user.id||!user.username||!['admin','operator','viewer'].includes(user.role)||user.enabled===false)fail();
if(!Array.isArray(selection)||!selection.length||selection.length>REGION_NAMES.length||new Set(selection).size!==selection.length||selection.some(name=>!REGION_NAMES.includes(name)))throw Object.assign(Error('刷新区域无效。'),{status:400});
const identity=[user.id,user.username,user.role,user.version||0,user.enabled!==false],now=new Date(context.clock?context.clock():Date.now()),memo=new Map();
const once=(name,read)=>{if(!memo.has(name)){try{memo.set(name,{value:read()});}catch(error){memo.set(name,{error});}}const result=memo.get(name);if(result.error)throw result.error;return result.value;};
const database=(name,store,scopes)=>once(name,()=>{if(!store)return {disabled:true};if(!store.db)throw Error('Revision source unavailable');return readRevisions(store.db,scopes);});
const workspace=scopes=>database('workspace:'+scopes.join(','),context.workspace,scopes);
const ownership=()=>once('ownership',()=>{
if(!context.workspace)return [];const db=context.workspace.db;if(!db)throw Error('Ownership source unavailable');
return db.prepare("SELECT id,json_extract(value,'$.owner') AS owner,'current' AS status,json_extract(value,'$.status')!='disabled' AS enabled FROM connections WHERE ?='admin' OR json_extract(value,'$.owner')=? UNION ALL SELECT id,json_extract(value,'$.owner') AS owner,'archived' AS status,0 AS enabled FROM connection_archives WHERE ?='admin' OR json_extract(value,'$.owner')=? ORDER BY id").all(user.role,user.username,user.role,user.username).map(c=>[c.id,c.owner,c.status,c.enabled]);
});
const rules=()=>database('rules',context.orderRules);
const configuration=()=>once('configuration',()=>Object.fromEntries(Object.entries(rules()).filter(([scope])=>!['orders','batches','execution-tasks','business-issues','audit'].some(kind=>scope==='records:'+kind)&&!scope.endsWith('-history'))));
const dashboard=()=>once('dashboard',()=>{if(!context.store?.database)throw Error('Export revision source unavailable');return context.store.database(db=>readRevisions(db,['pdf_jobs']));});
const mail=scopes=>database('mail:'+scopes.join(','),context.mail?.store,scopes);
const storage=scopes=>database('storage:'+scopes.join(','),context.storage?.store,scopes);
const scan=scopes=>database('scan:'+scopes.join(','),context.scanner?.store,scopes);
const timing=()=>once('timing',()=>{
if(!context.orderRules)return {disabled:true};
const schedule=context.store.settings().schedule,calendar=context.workspace?context.workspace.meta('calendar'):{version:0,overrides:[]},settings=context.orderRules.get('settings','main'),test=context.orderRules.get('stability-test','main');
const window=upcomingWindow(now,schedule,calendar.overrides),started=Date.parse(test?.startedAt),end=Date.parse(test?.endsAt),expired=test?.enabled===true&&(!Number.isFinite(started)||!Number.isFinite(end)||end<=started||+now>=end);
return {settingsVersion:settings?.version,schedule,calendarVersion:calendar.version,window,collection:window?(+now<Date.parse(window.collectionStart)?'before':+now<Date.parse(window.collectionEnd)?'open':'closed'):null,expired,day:new Date(+now+28800000).toISOString().slice(0,10)};
});
const bpm=()=>once('bpm',()=>{
if(!context.workspace)return [];
const ids=new Set(ownership().map(row=>row[0]));
const connections=context.workspace.db.prepare('SELECT value FROM connections ORDER BY id').all().map(row=>JSON.parse(row.value)).filter(c=>ids.has(c.id));
const config=context.scanner?context.scanner.store.config():{};
return connections.map(c=>connectionSnapshot(c,{manager:context.bpmSessions,monitor:context.bpmMonitor,config,now:+now}));
});
const readers={
home:()=>[rules(),ownership(),workspace(['connections','connection_archives','exceptions','metadata:calendar']),mail(['channels','templates']),storage(['servers','settings']),scan(['config','runs']),context.orderRules?.capabilities,timing()],
orderRules:()=>[configuration(),ownership(),workspace(['connections','connection_archives','metadata:calendar']),mail(['channels','templates','meta']),storage(['servers','settings']),context.orderRules?.capabilities,timing()],
records:()=>[rules(),ownership(),workspace(['connections','connection_archives']),dashboard(),scan(['arrivals','runs','config']),storage(['archives','servers']),mail(['channels','templates','meta']),timing()],
// Health contains uptime/event-loop/supervisor observations without a revision
// API. Its ten-second bucket preserves the existing maximum polling interval.
health:()=>context.health?[rules(),ownership(),workspace(['connections','exceptions']),mail(['channels']),storage(['servers','archives']),scan(['config','runs','execution_deliveries']),bpm(),context.health.instanceId,context.health.startedAt,Math.floor(+now/10000)]:['disabled'],
bpm:()=>[ownership(),workspace(['connections','connection_archives','exceptions']),scan(['config','runs','execution_deliveries']),bpm()],
assistant:()=>{
if(!context.assistant)return ['disabled'];const db=context.assistant.store?.db;if(!db)throw Error('Assistant revision source unavailable');
const day=new Date(+now+28800000).toISOString().slice(0,10);
const journal=context.assistant.journal?.db,operations=journal?journal.prepare('SELECT MAX(id) AS latest FROM operation_events'+(user.role==='admin'?'':' WHERE actor=?')).get(...(user.role==='admin'?[]:[user.id])).latest:null;
return [database('assistant',context.assistant.store,['config','owner:'+user.id,'usage:'+day]),day,operations];
},
storage:()=>[storage(['servers','settings','archives'])],
mail:()=>[mail(['channels','templates','receipts','sends','meta'])]
};
const regions={},errors={};
for(const name of selection){try{regions[name]=token([1,name,identity,readers[name]()]);}catch{regions[name]=crypto.randomBytes(32).toString('hex');errors[name]='暂时无法核实此区域是否更新,请重新读取并核对。';}}
return {version:1,regions,...(Object.keys(errors).length?{errors}:{})};
}
function api({route,url,method,user,response,reply}){
if(route!=='/api/refresh/revisions'||method!=='GET')return false;
response?.setHeader?.('Cache-Control','no-store');
const selections=url?.searchParams.getAll('regions')||[];
if(selections.length>1)throw Object.assign(Error('刷新区域无效。'),{status:400});
reply(200,snapshot(user,selections.length?selections[0].split(','):undefined));return true;
}
return {snapshot,api};
}
module.exports={createRegionRevisions,REGION_NAMES};
+1
View File
@@ -14,6 +14,7 @@ class AssistantStore{
CREATE TABLE IF NOT EXISTS turns(id TEXT PRIMARY KEY,conversation_id TEXT NOT NULL,status TEXT NOT NULL,payload BLOB NOT NULL,day TEXT NOT NULL,created_at TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS conversation_turns ON turns(conversation_id,created_at);`);
this.conversationHistory=new ConversationHistory(this);
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db,['config',['conversations',"'owner:' || $row.owner"],['turns',"'owner:' || (SELECT owner FROM conversations WHERE id=$row.conversation_id)"],['turns',"'usage:' || $row.day",'OLD.day IS NOT NEW.day']]);
} catch(error) {
try { this.db?.close(); } catch {}
try { this.vault?.destroy(); } catch {}
+1
View File
@@ -14,6 +14,7 @@ class BpmScanStore{
UPDATE runs SET status='error',message='服务重启,扫描未完成。',finished_at=CURRENT_TIMESTAMP WHERE status='running';`);
if(!this.db.prepare('PRAGMA table_info(runs)').all().some(c=>c.name==='kind'))this.db.exec("ALTER TABLE runs ADD COLUMN kind TEXT NOT NULL DEFAULT 'inform'");
this.deliveries=new ScanDeliveries({db:this.db,dir});
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db,['config','arrivals','runs','execution_deliveries']);
} catch(error) {
try { this.db?.close(); } catch {}
throw error;
+1
View File
@@ -43,6 +43,7 @@ class Store {
return JSON.parse(db.prepare('SELECT value FROM dashboard_state WHERE id=1').get().value);
});
this.jobStore=new JobStore(this);
this.database(db=>require('../../shared/refresh-revisions.cjs').installRevisionTracking(db,['pdf_jobs','dashboard_state']));
}
database(work){
const db=new DatabaseSync(this.file);
+1
View File
@@ -20,6 +20,7 @@ class MailStore{
if(columns!=='channel_id,scope,notification_mode')this.db.exec("DROP INDEX IF EXISTS active_template; CREATE UNIQUE INDEX active_template ON templates(channel_id,scope,notification_mode) WHERE status='active'");
});
for(const r of this.db.prepare("SELECT id,payload FROM templates WHERE summary='{}'").all()){const p=this.decode(r.id,r.payload);this.db.prepare('UPDATE templates SET summary=? WHERE id=?').run(this.summary(p),r.id);}
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db,['channels','templates','receipts','sends','meta']);
} catch(error) {
try { this.db?.close(); } catch {}
try { this.vault?.destroy(); } catch {}
+1
View File
@@ -46,6 +46,7 @@ class RuleStore{
}
}
});
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db,[['records',"'records:' || $row.kind"]]);
}catch(error){try{this.db?.close();}catch{}this.vault?.destroy();throw error;}
}
now(){return this.clock().toISOString();}
+1
View File
@@ -18,6 +18,7 @@ class StorageStore{
INSERT OR IGNORE INTO settings VALUES(1,'{"serverId":"","enabled":false,"since":null}');
CREATE TABLE IF NOT EXISTS archives(id TEXT PRIMARY KEY,server_id TEXT NOT NULL,job_id TEXT NOT NULL,status TEXT NOT NULL,value TEXT NOT NULL,UNIQUE(server_id,job_id));
UPDATE archives SET status='interrupted' WHERE status='running';`);
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db,['servers','settings','archives']);
} catch(error) {
try { this.db?.close(); } catch {}
try { this.vault?.destroy(); } catch {}
+1
View File
@@ -24,6 +24,7 @@ class WorkspaceStore {
delete item.detailUrl;if(item.checks)delete item.checks.detail;if(item.status==='partial')item.status='unchecked';
this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),row.id);
}});
require('../../shared/refresh-revisions.cjs').installRevisionTracking(this.db,['connections','connection_archives','exceptions',['metadata',"'metadata:' || $row.key"]]);
} catch(error) {
try { this.db?.close(); } catch {}
throw error;
+21
View File
@@ -0,0 +1,21 @@
'use strict';
const crypto=require('node:crypto');
// Transactional metadata only: triggers never copy/decrypt a business payload.
// Existing rows start at zero; the HTTP validator has a fresh key per server.
function installRevisionTracking(db,specs){
db.exec('CREATE TABLE IF NOT EXISTS refresh_revisions(scope TEXT PRIMARY KEY,revision INTEGER NOT NULL)');
for(const spec of specs){
const [table,expression,updateWhen]=Array.isArray(spec)?spec:[spec,"'"+spec+"'"];
if(!/^[a-z_]+$/.test(table))throw Error('Invalid revision table');
const scope=row=>expression.replaceAll('$row',row),bump=value=>`INSERT INTO refresh_revisions(scope,revision) SELECT ${value},1 WHERE ${value} IS NOT NULL ON CONFLICT(scope) DO UPDATE SET revision=revision+1;`;
const name=table+'_'+crypto.createHash('sha256').update(expression+(updateWhen||'')).digest('hex').slice(0,12);
db.exec(`CREATE TRIGGER IF NOT EXISTS refresh_${name}_insert AFTER INSERT ON ${table} BEGIN ${bump(scope('NEW'))} END;
CREATE TRIGGER IF NOT EXISTS refresh_${name}_update AFTER UPDATE ON ${table}${updateWhen?' WHEN '+updateWhen:''} BEGIN ${bump(scope('OLD'))} ${bump(scope('NEW'))} END;
CREATE TRIGGER IF NOT EXISTS refresh_${name}_delete AFTER DELETE ON ${table} BEGIN ${bump(scope('OLD'))} END;`);
}
}
function readRevisions(db,scopes){
const rows=scopes?db.prepare('SELECT scope,revision FROM refresh_revisions WHERE scope IN (SELECT value FROM json_each(?)) ORDER BY scope').all(JSON.stringify(scopes)):db.prepare('SELECT scope,revision FROM refresh_revisions ORDER BY scope').all();
return {...Object.fromEntries((scopes||[]).map(scope=>[scope,0])),...Object.fromEntries(rows.map(row=>[row.scope,Number(row.revision)]))};
}
module.exports={installRevisionTracking,readRevisions};
+32
View File
@@ -37,3 +37,35 @@ test('public asset cache revalidates changed files and concurrent reloads agree'
for(const result of results){assert.equal(result.status,200);assert.equal(result.bytes.toString(),'new application with changed size');assert.notEqual(result.headers.ETag,first.headers.ETag);}
assert.equal((await get(results[0].headers.ETag)).status,304);
});
test('asset URLs become immutable only when their content fingerprint is verified',async t=>{
const get=await fixture(t),plain=await get('/app.js');
const fingerprint=plain.headers['x-asset-version'];
assert.match(fingerprint,/^[0-9a-f]{64}$/);
assert.equal(plain.headers['cache-control'],'public, max-age=0, must-revalidate');
const versioned=await get('/app.js?v='+fingerprint);
assert.equal(versioned.status,200);
assert.equal(versioned.headers['x-asset-version'],fingerprint);
assert.equal(versioned.headers['cache-control'],'public, max-age=31536000, immutable');
const untrusted=await get('/app.js?v=not-the-content-fingerprint');
assert.equal(untrusted.status,200);
assert.equal(untrusted.headers['cache-control'],'public, max-age=0, must-revalidate');
});
test('HTML uses actual fingerprint URLs while the document itself always revalidates',async t=>{
const get=await fixture(t),page=await get('/'),html=page.bytes.toString();
const urls=[...html.matchAll(/(?:src|href)="(\/[^"#]+)"/g)].map(match=>match[1]);assert.ok(urls.length>=44);
for(const url of urls){assert.match(url,/\?v=[a-f0-9]{64}$/);const asset=await get(url);assert.equal(asset.status,200);assert.match(asset.headers['cache-control'],/immutable/);assert.equal(new URL(url,'http://local').searchParams.get('v'),asset.headers['x-asset-version']);}
const versioned=await get('/?v='+page.headers['x-asset-version']);assert.match(versioned.headers['cache-control'],/must-revalidate/);assert.doesNotMatch(versioned.headers['cache-control'],/immutable/);
});
test('changing one dependency changes its URL and HTML ETag without invalidating other assets',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'asset-dependency-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
const documentPath=path.join(dir,'index.html'),one=path.join(dir,'one.js'),two=path.join(dir,'two.css');fs.writeFileSync(documentPath,'<!doctype html><link href="/two.css" rel="stylesheet"><script src="/one.js" defer></script>');fs.writeFileSync(one,'old()');fs.writeFileSync(two,'body{}');
const assets={'/one.js':{path:one,type:'text/javascript'},'/two.css':{path:two,type:'text/css'}},deliver=createAssetDelivery({resolveAsset:url=>assets[url]});
async function get(tag){const headers={};let bytes,status;await deliver({url:'/',method:'GET',headers:{'if-none-match':tag}},{setHeader:(key,value)=>headers[key]=value,writeHead:value=>status=value,end:value=>bytes=value},{path:documentPath,type:'text/html'});return {headers,status,bytes};}
const first=await get();fs.writeFileSync(one,'updated()');const second=await get(first.headers.ETag);assert.equal(second.status,200);assert.notEqual(second.headers.ETag,first.headers.ETag);
const refs=value=>[...value.bytes.toString().matchAll(/(?:src|href)="([^"]+)"/g)].map(match=>match[1]);const a=refs(first),b=refs(second);assert.equal(a[0],b[0]);assert.notEqual(a[1],b[1]);assert.equal((await get(second.headers.ETag)).status,304);
});
+1 -1
View File
@@ -5,4 +5,4 @@ async function setup(t){const f=await orderDrivenUI(t,'#overview'),data=summary(
test('business home presents actual next window and deduplicated work, keeps mobile layout and reduced motion',{timeout:60000},async t=>{const {page}=await setup(t);await page.locator('[data-business-home]').waitFor();assert.equal(await page.locator('[data-home-metric="pending"]').innerText(),'7');assert.equal(await page.locator('[data-home-next-send]').innerText(),'17:00');assert.match(await page.locator('[data-home-cutoff]').innerText(),/16:55/);assert.equal(await page.locator('[data-home-batch]').count(),2);assert.match(await page.locator('[data-home-batch]').first().innerText(),/6.*顺延/s);assert.equal(await page.getByRole('link',{name:'查看全部批次',exact:true}).getAttribute('href'),'#notification-batches');await require('node:fs/promises').mkdir('output/business-flow-test/home-visual',{recursive:true});await page.screenshot({path:'output/business-flow-test/home-visual/desktop.png',fullPage:true});await page.setViewportSize({width:674,height:1000});await page.screenshot({path:'output/business-flow-test/home-visual/compact.png',fullPage:true});await page.emulateMedia({reducedMotion:'reduce'});assert.equal(await page.locator('.home-live .status-dot').evaluate(e=>getComputedStyle(e,'::before').animationName),'none');await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await page.screenshot({path:'output/business-flow-test/home-visual/mobile.png',fullPage:true});});
test('paused and blocked states remain honest and the clock never claims delivery at the deadline',{timeout:60000},async t=>{const {page,data}=await setup(t);await page.locator('[data-business-home]').waitFor();await page.clock.fastForward(5*3600000+1000);assert.match(await page.locator('[data-home-countdown]').innerText(),/刷新.*发送结果/);data.settings.enabled=false;data.capabilities.liveTodo=false;data.issues=[{id:'i',error:'<img src=x onerror=alert(1)>',status:'open'}];await page.reload();await page.getByText('自动邮件已暂停',{exact:true}).waitFor();assert.equal(await page.locator('.home-live .status-dot-animated').count(),0);assert.equal(await page.locator('.home-issues img').count(),0);assert.match(await page.locator('.home-issues').innerText(),/img src/);});
test('failed summary loading never displays invented zero counts or healthy state',{timeout:60000},async t=>{const {page}=await setup(t);await page.unroute('**/api/order-rules?view=summary');await page.route('**/api/order-rules?view=summary',r=>r.fulfill({status:503,json:{error:'首页数据暂不可用'}}));await page.reload();await page.getByText('首页数据暂不可用',{exact:false}).first().waitFor();assert.equal(await page.locator('[data-business-home]').count(),0);});
test('failed internal refresh retains the last home and offers a working retry',{timeout:60000},async t=>{const {page,data}=await setup(t);await page.locator('[data-business-home]').waitFor();await page.unroute('**/api/order-rules?view=summary');let fail=true;await page.route('**/api/order-rules?view=summary',r=>fail?r.fulfill({status:503,json:{error:'暂时不可用'}}):r.fulfill({json:data}));await page.clock.fastForward(15001);await page.locator('[data-business-updates]').waitFor();await page.getByRole('button',{name:'刷新业务首页',exact:true}).click();await page.getByText('刷新失败:暂时不可用',{exact:false}).waitFor();assert.equal(await page.locator('[data-home-metric="pending"]').innerText(),'7');fail=false;await page.getByRole('button',{name:'刷新业务首页',exact:true}).click();await page.locator('[data-business-updates]').waitFor({state:'hidden'});assert.equal(await page.locator('[data-home-metric="pending"]').innerText(),'7');});
test('failed internal refresh retains the last home and offers a working retry',{timeout:60000},async t=>{const {page,data}=await setup(t);await page.locator('[data-business-home]').waitFor();await page.unroute('**/api/order-rules?view=summary');let fail=true;await page.route('**/api/refresh/revisions*',r=>r.fulfill({json:{regions:{home:'a'.repeat(64),orderRules:'b'.repeat(64)}}}));await page.route('**/api/order-rules?view=summary',r=>fail?r.fulfill({status:503,json:{error:'暂时不可用'}}):r.fulfill({json:data}));await page.clock.fastForward(15001);await page.locator('[data-business-updates]').waitFor();await page.getByRole('button',{name:'刷新业务首页',exact:true}).click();await page.getByText('刷新失败:暂时不可用',{exact:false}).waitFor();assert.equal(await page.locator('[data-home-metric="pending"]').innerText(),'7');fail=false;await page.getByRole('button',{name:'刷新业务首页',exact:true}).click();await page.locator('[data-business-updates]').waitFor({state:'hidden'});assert.equal(await page.locator('[data-home-metric="pending"]').innerText(),'7');});
+1 -1
View File
@@ -2,7 +2,7 @@
const test=require('node:test'),assert=require('node:assert/strict');
const {orderDrivenUI}=require('../fixtures/order-driven-ui.cjs');
async function visibility(page,hidden){await page.evaluate(value=>{Object.defineProperty(document,'hidden',{configurable:true,value});document.dispatchEvent(new Event('visibilitychange'));},hidden);}
test('home opens with one summary and lightweight topbar, pauses hidden reads and checks once on return',{timeout:60000},async t=>{const {page}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();await page.clock.install();const requests=[];page.on('request',r=>{if(r.url().includes('/api/'))requests.push(new URL(r.url()).pathname+new URL(r.url()).search);});await page.reload();await page.locator('[data-business-home]').waitFor();assert.equal(requests.filter(r=>r==='/api/order-rules?view=summary').length,1);assert.equal(requests.filter(r=>r==='/api/order-rules/status').length,1);requests.length=0;await page.clock.fastForward(15001);await new Promise(r=>setTimeout(r,150));assert.equal(requests.filter(r=>r==='/api/order-rules?view=summary').length,1);assert.equal(requests.filter(r=>r==='/api/order-rules/status').length,1);requests.length=0;await visibility(page,true);await page.clock.fastForward(60001);await page.waitForTimeout(100);assert.deepEqual(requests,[]);await visibility(page,false);await page.waitForResponse(r=>r.url().endsWith('/api/order-rules?view=summary'));await page.waitForTimeout(100);assert.equal(requests.filter(r=>r==='/api/order-rules?view=summary').length,1);assert.equal(requests.filter(r=>r==='/api/order-rules/status').length,1);});
test('home opens with one summary and lightweight topbar, validates unchanged tokens and checks once on return',{timeout:60000},async t=>{const {page}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();await page.clock.install();const requests=[];page.on('request',r=>{if(r.url().includes('/api/'))requests.push(new URL(r.url()).pathname+new URL(r.url()).search);});await page.reload();await page.locator('[data-business-home]').waitFor();assert.equal(requests.filter(r=>r==='/api/order-rules?view=summary').length,1);assert.equal(requests.filter(r=>r==='/api/order-rules/status').length,1);requests.length=0;await page.clock.fastForward(15001);await new Promise(r=>setTimeout(r,150));assert.equal(requests.filter(r=>r==='/api/order-rules?view=summary').length,0);assert.equal(requests.filter(r=>r==='/api/order-rules/status').length,0);assert.ok(requests.some(r=>r==='/api/refresh/revisions?regions=home'));requests.length=0;await visibility(page,true);await page.clock.fastForward(60001);await page.waitForTimeout(100);assert.deepEqual(requests,[]);const validated=page.waitForResponse(r=>r.url().includes('/api/refresh/revisions?regions=home'));await visibility(page,false);await validated;await page.waitForTimeout(100);assert.equal(requests.filter(r=>r==='/api/order-rules?view=summary').length,0);assert.equal(requests.filter(r=>r==='/api/order-rules/status').length,0);});
test('health, BPM, ledger and business records stop background requests without replacing draft inputs',{timeout:60000},async t=>{const {page}=await orderDrivenUI(t,'#health');await page.clock.install();for(const [route,ready,endpoint] of [['health','#health-refresh','/api/health'],['bpm','[data-bpm-feedback]','/api/workspace'],['records-pdf','[data-pdf-list]','/api/jobs?'],['notification-orders','[data-arrival-list]','/api/order-rules/orders?'],['notification-batches','[data-arrival-list]','/api/order-rules/batches?']]){await visibility(page,false);await page.evaluate(hash=>location.hash=hash,route);await page.locator(ready).waitFor({state:'attached'});await page.waitForTimeout(200);const seen=[];const listen=r=>{if(r.url().includes(endpoint))seen.push(r.url());};const draft=page.locator('[name=q],#record-search').first();if(await draft.count())await draft.fill('未提交过滤词');page.on('request',listen);await visibility(page,true);await page.clock.fastForward(31001);await page.waitForTimeout(100);assert.equal(seen.length,0,route+' should not poll hidden');await visibility(page,false);if(await draft.count())assert.equal(await draft.inputValue(),'未提交过滤词');page.off('request',listen);} });
test('notification settings request only configuration and fetch mailbox in parallel',{timeout:60000},async t=>{const {page}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();let release;const held=new Promise(resolve=>release=resolve);let mailRead=false,settingsRead=false,heavy=0;await page.route('**/api/order-rules/notification-settings',async route=>{settingsRead=true;await held;await route.fulfill({json:{settings:{enabled:false,processingEnabled:false,version:1}}});});await page.route('**/api/mail',route=>{mailRead=true;return route.fulfill({json:{channels:[]}});});page.on('request',r=>{if(r.url().endsWith('/api/order-rules?view=summary'))heavy++;});try{await page.evaluate(()=>location.hash='notification-settings');await page.waitForFunction(()=>document.querySelector('#view-title').textContent==='发送设置');await new Promise(r=>setTimeout(r,250));assert.equal(settingsRead,true);assert.equal(mailRead,true);assert.equal(heavy,0);}finally{release();}await page.locator('#order-rule-settings').waitFor();});
+27
View File
@@ -0,0 +1,27 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {orderDrivenUI}=require('../fixtures/order-driven-ui.cjs');
const regions=()=>({home:'1'.repeat(64),orderRules:'2'.repeat(64),records:'3'.repeat(64),health:'4'.repeat(64),bpm:'5'.repeat(64),assistant:'6'.repeat(64),storage:'7'.repeat(64),mail:'8'.repeat(64)});
test('unchanged home tokens skip heavy reads, changed token offers local apply, validation failure is visible',{timeout:60000},async t=>{
const {page}=await orderDrivenUI(t,'#overview');page.on('pageerror',error=>t.diagnostic(error.message));let tokens=regions(),valid=true,summary=0,status=0,validations=0;
await page.route('**/api/refresh/revisions*',route=>{validations++;return route.fulfill(valid?{json:{regions:tokens}}:{status:503,json:{error:'版本读取暂不可用'}});});
page.on('request',r=>{if(r.url().endsWith('/api/order-rules?view=summary'))summary++;if(r.url().endsWith('/api/order-rules/status'))status++;});
await page.clock.install();await page.reload();await page.locator('[data-business-home]').waitFor();summary=status=validations=0;
await page.clock.fastForward(15001);await page.waitForTimeout(150);assert.ok(validations>0);assert.equal(summary,0);assert.equal(status,0);
tokens={...tokens,home:'a'.repeat(64)};await page.clock.fastForward(15001);await page.waitForTimeout(150);assert.equal(summary,1);
await page.locator('#refresh').click();await page.waitForTimeout(150);assert.equal(summary,2,'manual refresh always rereads the current summary');assert.equal(new URL(page.url()).hash,'#overview');
valid=false;await page.clock.fastForward(15001);await page.getByText(/刷新失败:版本读取暂不可用/).waitFor();assert.equal(summary,2);
});
test('health and record pages validate unchanged tokens while preserving unsubmitted filters',{timeout:60000},async t=>{
const {page}=await orderDrivenUI(t,'#overview');page.on('pageerror',error=>t.diagnostic(error.message));const tokens=regions();await page.route('**/api/refresh/revisions*',r=>r.fulfill({json:{regions:tokens}}));
await page.route('**/api/health',r=>r.fulfill({json:{at:'2026-10-28T01:00:00Z',runtime:{uptimeSeconds:1,startedAt:'2026-10-28T01:00:00Z',autostart:{enabled:false},guard:{status:'unmanaged',events:[]}},groups:[]}}));await page.clock.install();await page.evaluate(()=>location.hash='health');await page.locator('#health-access').waitFor();let health=0,jobs=0;
page.on('request',r=>{if(r.url().endsWith('/api/health'))health++;if(r.url().includes('/api/jobs?'))jobs++;});
await page.clock.fastForward(10001);await page.waitForTimeout(150);assert.equal(health,0);
await page.locator('#health-refresh').click();await page.waitForTimeout(150);assert.equal(health,1,'manual health refresh bypasses an unchanged token');
await page.evaluate(()=>location.hash='records-pdf');await page.locator('[data-pdf-list] table,[data-pdf-list] .empty').waitFor();await page.locator('#record-search').fill('未提交过滤词');jobs=0;
await page.clock.fastForward(10001);await page.waitForTimeout(150);assert.equal(jobs,0);assert.equal(await page.locator('#record-search').inputValue(),'未提交过滤词');
tokens.records='b'.repeat(64);await page.clock.fastForward(10001);await page.waitForTimeout(150);assert.equal(jobs,1);assert.equal(await page.locator('#record-search').inputValue(),'未提交过滤词');
});
test('initial revision failure still loads home data and exposes the failed validation',{timeout:60000},async t=>{
const {page}=await orderDrivenUI(t,'#overview');await page.route('**/api/refresh/revisions*',route=>route.fulfill({status:503,json:{error:'版本服务暂不可用'}}));await page.reload();await page.locator('[data-business-home]').waitFor();await page.getByText(/刷新失败:版本服务暂不可用/).waitFor();assert.equal(await page.locator('[data-business-home]').count(),1);
});
+60
View File
@@ -0,0 +1,60 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm');
function fixture(){
const listeners={},timers=new Map();let sequence=0;
const document={hidden:false,addEventListener:(name,fn)=>{listeners[name]=fn;},removeEventListener:(name,fn)=>{if(listeners[name]===fn)delete listeners[name];}};
const context=vm.createContext({document,window:{addEventListener(){}},AbortController,DOMException,setTimeout:(fn)=>{const id=++sequence;timers.set(id,fn);return id;},clearTimeout:id=>timers.delete(id)});
vm.runInContext(fs.readFileSync('web/modules/navigation/lifecycle.js','utf8'),context);
context.PageLifecycle=context.window.PageLifecycle;
return {context,document,listeners,timers,run:code=>vm.runInContext(code,context),tick:async()=>{const work=[...timers.values()];timers.clear();for(const fn of work)fn();await new Promise(resolve=>setImmediate(resolve));}};
}
const token=letter=>String(letter).repeat(64);function revisions(regions){return {regions:{home:token('a'),orderRules:token('b'),records:token('c'),health:token('d'),bpm:token('e'),assistant:token('f'),storage:token('1'),mail:token('2'),...regions},version:'v1'};}
test('region poll validates revisions before running a heavy read and only reloads after token change',async()=>{
const f=fixture();f.run(`globalThis.revision=${JSON.stringify(revisions())};globalThis.validations=0;globalThis.loads=0;globalThis.poll=PageLifecycle.regionPoll('home',{validate:async()=>{validations++;return revision;},refresh:async()=>{loads++;}},1000)`);
await f.tick();assert.equal(f.run('validations'),1);assert.equal(f.run('loads'),1);
await f.tick();assert.equal(f.run('validations'),2);assert.equal(f.run('loads'),1);
f.run("revision=JSON.parse(JSON.stringify(revision));revision.regions.home='3'.repeat(64)");await f.tick();assert.equal(f.run('validations'),3);assert.equal(f.run('loads'),2);
});
test('manual refresh and mutation invalidation validate immediately without replacing navigation state',async()=>{
const f=fixture();f.run(`globalThis.revision=${JSON.stringify(revisions())};globalThis.loads=0;globalThis.poll=PageLifecycle.regionPoll('orderRules',{validate:async()=>revision,refresh:async()=>{loads++;}},1000)`);await f.tick();
f.run('PageLifecycle.invalidateRegion(\'orderRules\')');const manual=f.run('poll.refresh()');await manual;assert.equal(f.run('loads'),2);
assert.equal(f.run('PageLifecycle.revision'),0);f.run('globalThis.navigation=\'#order-rules\'');assert.equal(f.run('navigation'),'#order-rules');
});
test('an aborted heavy read leaves the token pending and visibility resume retries it',async()=>{
const f=fixture();f.run(`globalThis.revision=${JSON.stringify(revisions())};globalThis.loads=0;globalThis.started=0;globalThis.release=null;globalThis.poll=PageLifecycle.regionPoll('records',{validate:async()=>revision,refresh:signal=>{started++;return new Promise((resolve,reject)=>{release=resolve;signal.addEventListener('abort',()=>reject(new DOMException('Aborted','AbortError')),{once:true});});}},1000)`);
const pending=f.run('poll.run()');await new Promise(resolve=>setImmediate(resolve));assert.equal(f.run('started'),1);f.document.hidden=true;f.listeners.visibilitychange();await assert.rejects(pending,{name:'AbortError'});
f.document.hidden=false;f.listeners.visibilitychange();await new Promise(resolve=>setImmediate(resolve));assert.equal(f.run('started'),2);f.run('release()');await new Promise(resolve=>setImmediate(resolve));
});
test('failed reads, invalid revisions and a mutation during a read cannot acknowledge the region',async()=>{
const f=fixture();f.run(`globalThis.revision=${JSON.stringify(revisions())};globalThis.loads=0;globalThis.errors=0;globalThis.fail=true;globalThis.poll=PageLifecycle.regionPoll('home',{validate:async()=>revision,onError:()=>errors++,refresh:async()=>{loads++;if(fail)throw Error('read failed');PageLifecycle.invalidateRegion('home');}},1000)`);
await assert.rejects(f.run('poll.run()'),/read failed/);f.run('fail=false');await f.run('poll.run()');await f.run('poll.run()');assert.equal(f.run('loads'),3);
f.run('revision.regions.home=null');await assert.rejects(f.run('poll.run()'),/区域版本/);assert.equal(f.run('loads'),3);assert.equal(f.run('errors'),2);
});
test('tokens never carry over between authenticated users',async()=>{
const f=fixture();f.run(`globalThis.user={id:'one'};globalThis.revision=${JSON.stringify(revisions())};globalThis.loads=0;PageLifecycle.configureRegions({read:async()=>revision,user:()=>user});globalThis.poll=PageLifecycle.regionPoll('home',{refresh:async()=>{loads++;}},1000)`);
await f.run('poll.run()');await f.run('poll.run()');assert.equal(f.run('loads'),1);f.run("user={id:'two'}");await f.run('poll.run()');assert.equal(f.run('loads'),2);
});
test('file-backed regions can bound staleness even when database tokens remain unchanged',async()=>{
const f=fixture();f.run(`globalThis.now=0;Date.now=()=>now;globalThis.revision=${JSON.stringify(revisions())};globalThis.loads=0;globalThis.poll=PageLifecycle.regionPoll('records',{validate:async()=>revision,refresh:async()=>{loads++;}},1000,{forceAfter:60000})`);
await f.run('poll.run()');f.run('now=59999');await f.run('poll.run()');assert.equal(f.run('loads'),1);f.run('now=60000');await f.run('poll.run()');assert.equal(f.run('loads'),2);
});
test('each mounted consumer requests only its own region with the original cancellation signal',async()=>{
const f=fixture();f.run(`globalThis.requested=[];globalThis.revision=${JSON.stringify(revisions())};PageLifecycle.configureRegions({read:async(signal,region)=>{requested.push([region,signal instanceof AbortSignal]);return revision;},user:()=>null});globalThis.poll=PageLifecycle.regionPoll('assistant',{refresh:async()=>{}},1200)`);
f.context.AbortSignal=AbortSignal;
await f.run('poll.run()');assert.deepEqual(JSON.parse(f.run('JSON.stringify(requested)')),[['assistant',true]]);
});
test('manual refresh rereads unchanged regions once and periodic checks remain lightweight afterwards',async()=>{
const f=fixture();f.run(`globalThis.revision=${JSON.stringify(revisions())};globalThis.loads=0;globalThis.poll=PageLifecycle.regionPoll('health',{validate:async()=>revision,refresh:async()=>{loads++;}},1000)`);
await f.run('poll.run()');await f.run('poll.run()');assert.equal(f.run('loads'),1);
await f.run('poll.refresh()');assert.equal(f.run('loads'),2);
await f.run('poll.run()');assert.equal(f.run('loads'),2);
});
+14
View File
@@ -0,0 +1,14 @@
'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 {Store}=require('../../src/modules/dashboard/store.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs');
test('region revision route authenticates every read, keeps tokens private and separates users',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'region-http-')),store=new Store(dir);store.bootstrap('admin','Test-password-123');store.addUser({username:'viewer',role:'viewer',password:'Test-password-123'},'admin');
const server=createDashboard({store,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r));fs.rmSync(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port;
const get=cookie=>fetch(base+'/api/refresh/revisions',{headers:cookie?{Cookie:cookie}:{}}),login=async username=>{const response=await fetch(base+'/api/login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:JSON.stringify({username,password:'Test-password-123'})});assert.equal(response.status,200);return response.headers.get('set-cookie').split(';')[0];};
assert.equal((await get()).status,401);const admin=await login('admin'),viewer=await login('viewer'),response=await get(admin);assert.equal(response.status,200);assert.equal(response.headers.get('cache-control'),'no-store');assert.equal(response.headers.get('etag'),null);
const a=await response.json(),b=await(await get(viewer)).json();assert.equal(a.version,1);assert.ok(a.regions.home);assert.notEqual(a.regions.home,b.regions.home);assert.doesNotMatch(JSON.stringify(a),/passwordHash|Test-password|order_session|"admin"/);
const selected=await fetch(base+'/api/refresh/revisions?regions=mail,storage',{headers:{Cookie:admin}});assert.equal(selected.status,200);assert.equal(selected.headers.get('cache-control'),'no-store');assert.deepEqual(await selected.json(),{version:1,regions:{mail:a.regions.mail,storage:a.regions.storage}});
for(const query of ['unknown','','mail&regions=storage','mail,mail','__proto__']){const invalid=await fetch(base+'/api/refresh/revisions?regions='+query,{headers:{Cookie:admin}});assert.equal(invalid.status,400);assert.equal(invalid.headers.get('cache-control'),'no-store');}
assert.equal((await fetch(base+'/api/refresh/revisions?regions=mail')).status,401);
await fetch(base+'/api/logout',{method:'POST',headers:{Origin:base,'Content-Type':'application/json',Cookie:admin},body:'{}'});assert.equal((await get(admin)).status,401);
});
+74
View File
@@ -0,0 +1,74 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),{DatabaseSync}=require('node:sqlite');
let installRevisionTracking,readRevisions,createRegionRevisions;
try{({installRevisionTracking,readRevisions}=require('../../src/shared/refresh-revisions.cjs'));({createRegionRevisions}=require('../../src/app/region-revisions.cjs'));}catch(error){if(error.code!=='MODULE_NOT_FOUND')throw error;}
test('table and kind revision metadata follows committed external writes and rolls back atomically',t=>{
assert.equal(typeof installRevisionTracking,'function');
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'region-counters-')),file=path.join(dir,'state.sqlite'),a=new DatabaseSync(file),b=new DatabaseSync(file);t.after(()=>{a.close();b.close();fs.rmSync(dir,{recursive:true,force:true});});
a.exec('CREATE TABLE records(kind TEXT,id TEXT,payload BLOB,PRIMARY KEY(kind,id)); CREATE TABLE channels(id TEXT)');installRevisionTracking(a,[['records',"'records:' || $row.kind"],'channels']);
const read=()=>readRevisions(a,['records:orders','records:rules','channels']);const before=read();
b.prepare('INSERT INTO records VALUES(?,?,?)').run('orders','o',Buffer.from('PRIVATE_ORDER_BODY'));
assert.notDeepEqual(read(),before);assert.equal(read()['records:rules'],before['records:rules']);assert.equal(read().channels,before.channels);
const committed=read();b.exec('BEGIN');b.prepare('UPDATE records SET payload=?').run(Buffer.from('PRIVATE_NEW_BODY'));b.exec('ROLLBACK');assert.deepEqual(read(),committed);
b.exec("UPDATE records SET kind='rules'");assert.ok(read()['records:orders']>committed['records:orders']);assert.ok(read()['records:rules']>committed['records:rules']);
});
function fixture(t){
assert.equal(typeof createRegionRevisions,'function');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{WorkspaceStore}=require('../../src/modules/workspace/store.cjs'),{RuleStore}=require('../../src/modules/order-rules/store.cjs'),{MailStore}=require('../../src/modules/mail/store.cjs'),{StorageStore}=require('../../src/modules/storage/store.cjs'),{BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs'),{AssistantStore}=require('../../src/modules/assistant/store.cjs');
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'region-contract-')),store=new Store(path.join(dir,'dashboard')),workspace=new WorkspaceStore(path.join(dir,'workspace')),orderRules=new RuleStore(path.join(dir,'rules'));
const mail={store:new MailStore(path.join(dir,'mail'))},storage={store:new StorageStore(path.join(dir,'storage'))},scanner={store:new BpmScanStore(path.join(dir,'scan'))},assistant={store:new AssistantStore(path.join(dir,'assistant'))};
const user={id:'alice-id',username:'alice',role:'operator',version:1},admin={id:'admin-id',username:'admin',role:'admin',version:1},members=[user,admin,{id:'bob-id',username:'bob',role:'operator'}];
const connection=workspace.createConnection({name:'connection',owner:'alice'},admin,members);let now=new Date('2026-10-28T00:00:00Z');orderRules.clock=()=>new Date(now);
const context={store,workspace,orderRules,mail,storage,scanner,assistant,clock:()=>new Date(now),health:{startedAt:now.toISOString(),instanceId:'fixture'}};
const revisions=createRegionRevisions(context);t.after(()=>{workspace.close();orderRules.close();mail.store.close();storage.store.close();scanner.store.close();assistant.store.close();fs.rmSync(dir,{recursive:true,force:true});});
return {context,revisions,user,admin,members,connection,setNow(value){now=new Date(value);},get(userOverride=user){return revisions.snapshot(userOverride);}};
}
test('opaque tokens are stable, independently invalidated, and never assemble or decrypt business payloads',t=>{
const f=fixture(t),first=f.get();assert.equal(first.version,1);assert.deepEqual(Object.keys(first.regions),['home','orderRules','records','health','bpm','assistant','storage','mail']);assert.equal(first.errors,undefined);assert.deepEqual(f.get(),first);
for(const key of Object.keys(first.regions))assert.match(first.regions[key],/^[a-f0-9]{64}$/);
for(const object of [f.context.orderRules,f.context.mail.store,f.context.storage.store,f.context.scanner.store,f.context.assistant.store]){object.snapshot=()=>assert.fail('must not build snapshots');object.all=()=>assert.fail('must not enumerate business records');if(object.vault)object.vault.decode=(function(decode){return function(id,...args){assert.match(id,/^(settings|stability-test):main$/,'must not decrypt business payloads');return decode.call(this,id,...args);};})(object.vault.decode);}
f.context.orderRules.db.prepare('INSERT INTO records VALUES(?,?,?)').run('orders','private-order',Buffer.from('PRIVATE_ORDER_BODY'));
const changed=f.get();assert.notEqual(changed.regions.home,first.regions.home);assert.notEqual(changed.regions.records,first.regions.records);assert.equal(changed.regions.orderRules,first.regions.orderRules);assert.equal(changed.regions.mail,first.regions.mail);assert.equal(changed.regions.storage,first.regions.storage);assert.equal(changed.errors,undefined);assert.doesNotMatch(JSON.stringify(changed),/PRIVATE|alice|connection/);
});
test('roles and connection ownership invalidate business and record tokens without a rule write',t=>{
const f=fixture(t),before=f.get();f.context.workspace.transferConnection(f.connection.id,{version:0,owner:'bob'},f.admin,f.members);const after=f.get();
for(const key of ['home','orderRules','records','health','bpm'])assert.notEqual(after.regions[key],before.regions[key],key);
const role=f.get({...f.user,role:'viewer',version:2});for(const key of Object.keys(role.regions))assert.notEqual(role.regions[key],after.regions[key]);
const bob=f.get({id:'bob-id',username:'bob',role:'operator'});for(const key of Object.keys(bob.regions))assert.notEqual(bob.regions[key],after.regions[key]);
assert.throws(()=>f.get(null),error=>error.status===401);assert.throws(()=>f.get({...f.user,enabled:false}),error=>error.status===401);
});
test('assistant turn revisions stay private to their owner and include same-status payload changes',t=>{
const f=fixture(t),a=f.context.assistant.store,own=a.create(f.user.id),other=a.create('bob-id'),before=f.get();
a.db.prepare('UPDATE conversations SET payload=? WHERE id=?').run(Buffer.from('PRIVATE_BOB_BODY'),other.id);assert.equal(f.get().regions.assistant,before.regions.assistant);
a.db.prepare('INSERT INTO turns VALUES(?,?,?,?,?,?)').run('own-turn',own.id,'success',Buffer.from('PRIVATE_ALICE_BODY'),'2026-10-28','2026-10-28T00:00:00Z');const turned=f.get();assert.notEqual(turned.regions.assistant,before.regions.assistant);
a.db.prepare('UPDATE turns SET payload=? WHERE id=?').run(Buffer.from('PRIVATE_ALICE_UPDATED_BODY'),'own-turn');assert.notEqual(f.get().regions.assistant,turned.regions.assistant);
});
test('effective stability expiry and collection/send boundaries invalidate at the exact instant',t=>{
const f=fixture(t);f.context.orderRules.put('stability-test',{id:'main',enabled:true,startedAt:'2026-10-27T00:00:00Z',endsAt:'2026-10-28T00:00:00.500Z'});
f.setNow('2026-10-28T00:00:00.499Z');let before=f.get();f.setNow('2026-10-28T00:00:00.500Z');let after=f.get();assert.notEqual(after.regions.home,before.regions.home);assert.notEqual(after.regions['orderRules'],before.regions['orderRules']);
for(const boundary of ['2026-10-28T00:55:00.000Z','2026-10-28T01:00:00.000Z','2026-10-28T01:01:00.001Z']){f.setNow(new Date(Date.parse(boundary)-1));before=f.get();f.setNow(boundary);after=f.get();assert.notEqual(after.regions.home,before.regions.home,boundary);}
});
test('the authenticated GET API preserves no-store and source failures force a new token with a safe error',t=>{
const f=fixture(t);let result;const headers={},response={setHeader(key,value){headers[key]=value;}},reply=(status,value)=>result={status,value};
assert.equal(f.revisions.api({route:'/api/refresh/revisions',method:'GET',user:f.user,response,reply}),true);assert.equal(result.status,200);assert.equal(headers['Cache-Control'],'no-store');assert.deepEqual(result.value,f.get());
assert.equal(f.revisions.api({route:'/other',method:'GET',user:f.user,response,reply}),false);
const db=f.context.orderRules.db;f.context.orderRules.db={prepare(){throw Error('PRIVATE_DATABASE_FAILURE');}};try{const one=f.get(),two=f.get();assert.ok(one.errors.home);assert.notEqual(one.regions.home,two.regions.home);assert.doesNotMatch(JSON.stringify(one),/PRIVATE_DATABASE_FAILURE/);}finally{f.context.orderRules.db=db;}
});
test('intentionally absent services expose stable disabled markers without hiding broken initialized sources',()=>{
assert.equal(typeof createRegionRevisions,'function');const revisions=createRegionRevisions({store:{database:()=>({pdf_jobs:0}),settings:()=>({schedule:{times:['09:00','17:00'],weekends:false}})},clock:()=>new Date('2026-10-28T00:00:00Z')}),user={id:'u',username:'worker',role:'operator'};
const first=revisions.snapshot(user);assert.equal(first.errors,undefined);assert.deepEqual(revisions.snapshot(user),first);
});
test('mail template changes invalidate configuration and rendered business records without touching storage',t=>{
const f=fixture(t),before=f.get();f.context.mail.store.db.prepare('INSERT INTO templates(id,channel_id,source_key,scope,status,version,payload,created_at) VALUES(?,?,?,?,?,?,?,?)').run('template','channel','source','scope','pending',1,Buffer.from('PRIVATE_MAIL_BODY'),'2026-10-28T00:00:00Z');
const after=f.get();for(const key of ['home','orderRules','records','mail'])assert.notEqual(after.regions[key],before.regions[key],key);assert.equal(after.regions.storage,before.regions.storage);
});
test('assistant usage and operation metadata follow exactly the aggregates visible to the actor',t=>{
const f=fixture(t),a=f.context.assistant.store,other=a.create('bob-id'),journal=new DatabaseSync(':memory:');t.after(()=>journal.close());journal.exec('CREATE TABLE operation_events(id INTEGER PRIMARY KEY,actor TEXT,payload TEXT)');f.context.assistant.journal={db:journal};
let before=f.get();a.db.prepare('INSERT INTO turns VALUES(?,?,?,?,?,?)').run('bob-turn',other.id,'success',Buffer.from('PRIVATE_BOB_TURN'),'2026-10-28','2026-10-28T00:00:00Z');let after=f.get();assert.notEqual(after.regions.assistant,before.regions.assistant,'global public usage changed');
before=after;journal.prepare('INSERT INTO operation_events VALUES(?,?,?)').run(1,'bob-id','PRIVATE_BOB_EVENT');after=f.get();assert.equal(after.regions.assistant,before.regions.assistant,'operator cannot see other actor operations');
journal.prepare('INSERT INTO operation_events VALUES(?,?,?)').run(2,f.user.id,'PRIVATE_ALICE_EVENT');assert.notEqual(f.get().regions.assistant,after.regions.assistant);
const admin=f.get(f.admin);journal.prepare('INSERT INTO operation_events VALUES(?,?,?)').run(3,'bob-id','PRIVATE_BOB_LATER_EVENT');assert.notEqual(f.get(f.admin).regions.assistant,admin.regions.assistant,'admin operation aggregate includes all actors');
});
test('source catalogue edits invalidate records, and validators need no immediate write transaction',t=>{
const f=fixture(t),before=f.get(),db=f.context.workspace.db;db.prepare("UPDATE connections SET value=json_set(value,'$.name',?) WHERE id=?").run('renamed source',f.connection.id);assert.notEqual(f.get().regions.records,before.regions.records);
});
+47
View File
@@ -0,0 +1,47 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {DatabaseSync}=require('node:sqlite');
const {createRegionRevisions,REGION_NAMES}=require('../../src/app/region-revisions.cjs');
const {installRevisionTracking}=require('../../src/shared/refresh-revisions.cjs');
const user={id:'operator-id',username:'operator',role:'operator',version:1};
function assistantFixture(t){
const db=new DatabaseSync(':memory:');t.after(()=>db.close());
db.exec('CREATE TABLE config(id INTEGER); CREATE TABLE conversations(owner TEXT);');
installRevisionTracking(db,['config',['conversations',"'owner:' || $row.owner"]]);
const reads=[];
const context={assistant:{store:{db}},clock:()=>new Date('2026-10-28T00:00:00Z')};
for(const name of ['store','workspace','orderRules','mail','storage','scanner','health','bpmSessions','bpmMonitor'])Object.defineProperty(context,name,{get(){reads.push(name);throw Error('Unrelated module must not be read');}});
return {revisions:createRegionRevisions(context),db,reads};
}
test('assistant-only validation never opens or reads unrelated modules and follows committed metadata',t=>{
const f=assistantFixture(t),before=f.revisions.snapshot(user,['assistant']);
assert.deepEqual(Object.keys(before.regions),['assistant']);assert.equal(before.errors,undefined);assert.deepEqual(f.reads,[]);
assert.deepEqual(f.revisions.snapshot(user,['assistant']),before);
f.db.exec("BEGIN; INSERT INTO conversations VALUES('operator-id'); ROLLBACK;");assert.deepEqual(f.revisions.snapshot(user,['assistant']),before);
f.db.exec("INSERT INTO conversations VALUES('operator-id')");assert.notEqual(f.revisions.snapshot(user,['assistant']).regions.assistant,before.regions.assistant);
const other=f.revisions.snapshot({...user,id:'other-id'},['assistant']);assert.notEqual(other.regions.assistant,before.regions.assistant);
});
test('selected tokens match the legacy full response and only the selected failure is returned',()=>{
const context={clock:()=>new Date('2026-10-28T00:00:00Z')},revisions=createRegionRevisions(context);
const full=revisions.snapshot(user);assert.deepEqual(Object.keys(full.regions),REGION_NAMES);
const selected=revisions.snapshot(user,['mail','storage']);
assert.deepEqual(selected,{version:1,regions:{mail:full.regions.mail,storage:full.regions.storage}});
const failed=revisions.snapshot(user,['records']);assert.deepEqual(Object.keys(failed.regions),['records']);assert.deepEqual(Object.keys(failed.errors),['records']);
});
test('invalid selections are rejected before any source access and authentication still applies',t=>{
const f=assistantFixture(t);
for(const selection of [[],['unknown'],['toString'],['__proto__'],['assistant','assistant'],'assistant',null,Array(9).fill('home')])assert.throws(()=>f.revisions.snapshot(user,selection),error=>error.status===400);
assert.deepEqual(f.reads,[]);assert.throws(()=>f.revisions.snapshot(null,['assistant']),error=>error.status===401);
});
test('HTTP region selection is explicit, bounded and backwards compatible',t=>{
const f=assistantFixture(t);let result;const headers={},response={setHeader:(name,value)=>headers[name]=value},reply=(status,value)=>result={status,value};
const call=query=>f.revisions.api({route:'/api/refresh/revisions',url:new URL('http://localhost/api/refresh/revisions'+query),method:'GET',user,response,reply});
assert.equal(call('?regions=assistant'),true);assert.equal(result.status,200);assert.deepEqual(Object.keys(result.value.regions),['assistant']);assert.deepEqual(f.reads,[]);assert.equal(headers['Cache-Control'],'no-store');
for(const query of ['?regions=','?regions=unknown','?regions=assistant&regions=mail','?regions=assistant,assistant'])assert.throws(()=>call(query),error=>error.status===400);
call('');assert.deepEqual(Object.keys(result.value.regions),REGION_NAMES);
});
+17 -7
View File
@@ -8,6 +8,16 @@ let currentUser=null,settings=null,currentView='overview',overview=null,refreshT
let updateState={status:'unavailable',currentVersion:'—',latest:null};
const views={tools:['工具','手工导出、文件查看与助手'],'records-pdf':['订单与导出记录','查询PDF导出结果、文件可用性与存储归档记录'],'order-notifications':['通知总览','查看当前发送时段、待发订单及接入阻塞'],'notification-execution':['订单执行','扫描真实待办,查看归档进度与受控恢复'],'notification-orders':['订单中心','查看订单分类、归档证据及所属邮件批次'],'notification-batches':['邮件批次','按发送时段检查分类汇总和冻结内容'],'notification-history':['发送记录','核对发送结果、冻结内容和人工恢复记录'],'notification-settings':['发送设置','维护发件邮箱、邮件限制与自动通知开关'],'rule-fields':['字段映射','采集BPM流程和节点,供分类规则选择匹配项'],'assistant-settings':['助手设置','配置 DSH 运行包、模型与受控操作权限'],'business-settings':['业务设置','维护Excel分类规则、收件人和BPM流程节点目录'],'system-settings':['系统设置','集中管理服务连接、运行维护和团队权限'],account:['个人账号','维护自己的登录密码与访问安全'],'order-rules':['分类通知规则','按 Excel 类别维护匹配、归档、收件人与通知正文'],health:['系统健康','查看服务守护、登录自启和各模块最近检查结果'],assistant:['DSH 助手','对话查询运行状态、分析异常与执行受控恢复'],storage:['存储服务器','配置 SMB 共享目录、检查连接与管理 PDF 归档'],notifications:['兼容业务通知','原来源映射、产业接口人与通知队列'],overview:['业务首页','订单处理、邮件窗口、业务阻塞与待核验'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['分类通知规则','按 Excel 类别维护匹配、归档、收件人与通知正文'],schedule:['发送计划','设置每日两个发送时间及周末安排'],templates:['邮件模板','管理模板及 Excel 类别关联;收件名单在分类规则维护'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']};
const pendingWrites=new Map(),pendingReads=new Map();
function mutationRegions(route){
if(route.startsWith('/assistant'))return ['assistant','health'];
if(route.startsWith('/storage'))return ['storage','records','home','orderRules','health'];
if(route.startsWith('/mail'))return ['mail','orderRules','home','health'];
if(route.startsWith('/connections')||route.startsWith('/bpm'))return ['bpm','records','orderRules','home','health'];
if(route.startsWith('/order-')||route==='/settings'||route==='/calendar'||route.startsWith('/exceptions'))return ['orderRules','home','records','bpm','health'];
if(route.startsWith('/jobs'))return ['records','storage','home','health'];
if(route.startsWith('/users'))return ['home','orderRules','records','health','bpm','assistant','storage','mail'];
return [];
}
// Share transport only while a read is pending; each caller owns cancellation and its result.
function readRequest(route,signal,user,scope){
if(signal?.aborted)return Promise.reject(signal.reason||new DOMException('Aborted','AbortError'));
@@ -29,12 +39,12 @@ function readRequest(route,signal,user,scope){
}
async function api(route,body,{signal,ownerCheck,managedOutcome=false}={}) {
const originGeneration=viewGeneration,originUser=currentUser,originRevision=window.PageLifecycle?.revision;const originActive=()=>viewGeneration===originGeneration&&currentUser===originUser&&window.PageLifecycle?.revision===originRevision;const submission=window.PageLifecycle?.submission,hasBody=body!==undefined,write=hasBody&&route!=='/order-rules/field-mappings/propose',key=originGeneration+':'+originRevision+':'+route+':'+JSON.stringify(body);const pending=pendingWrites.get(key);if(write&&pending?.user===originUser)return pending.work;
if(write)pendingReads.clear();
if(write){pendingReads.clear();if(originUser)window.PageLifecycle?.invalidateRegion?.(mutationRegions(route));}
const work=(async()=>{const controller=new AbortController(),timeout=setTimeout(()=>controller.abort(),30000);const combined=signal?AbortSignal.any([signal,controller.signal]):controller.signal;
try {const response=hasBody?await fetch('/api'+route,{signal:combined,credentials:'same-origin',keepalive:route.endsWith('/login/close'),method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}):await readRequest(route,combined,originUser,originGeneration+':'+originRevision);const result=hasBody?await response.json():response.result;
if(!response.ok){if(response.status===401&&currentUser&&originActive()&&(!ownerCheck||ownerCheck())){window.RecordState?.clear();currentUser=null;++viewGeneration;await window.PageLifecycle?.dispose();window.BpmLogin?.dispose();await boot();}throw Object.assign(Error(result.error||'操作失败,请核对输入。'),{status:response.status,outcome:'rejected'});}if(write&&originActive())window.PageLifecycle?.succeeded(submission);return result;
}catch(error){if(write&&originActive())window.PageLifecycle?.failed(submission);if(write&&(error.name==='AbortError'||error instanceof TypeError)){if(originActive()&&!managedOutcome)void verifyUncertainWrite(route,originActive);throw Object.assign(Error('结果待核实:请求超时或连接中断,正在查询状态;不会自动重试。'),{outcome:'uncertain'});}throw error;
}finally{clearTimeout(timeout);if(write)pendingReads.clear();}})();if(write)pendingWrites.set(key,{user:originUser,work});try{return await work;}finally{if(write&&pendingWrites.get(key)?.work===work)pendingWrites.delete(key);}
}finally{clearTimeout(timeout);if(write){pendingReads.clear();if(currentUser===originUser&&originUser)window.PageLifecycle?.invalidateRegion?.(mutationRegions(route));}}})();if(write)pendingWrites.set(key,{user:originUser,work});try{return await work;}finally{if(write&&pendingWrites.get(key)?.work===work)pendingWrites.delete(key);}
}
async function verifyUncertainWrite(route,isActive){
@@ -87,7 +97,7 @@ function shell() {
renderUpdateStatus(updateState);
document.querySelector('#logout').onclick=()=>window.PageLifecycle.guard(async()=>{++viewGeneration;await window.BpmLogin?.dispose();await api('/logout',{});window.RecordState.clear();currentUser=null;refreshTimer?.dispose();await window.PageLifecycle.dispose();await boot();});
document.querySelector('#check-updates').onclick=()=>checkSystemUpdate(()=>!!currentUser,{manual:true});
document.querySelector('#refresh').onclick=()=>window.PageLifecycle.guard(()=>{const generation=viewGeneration;void updateAutomationStatus(()=>generation===viewGeneration&&!!currentUser);return window.RecordTable?.active?window.RecordTable.active.refresh():renderView();}).catch(error=>notify(error.message,'danger'));
document.querySelector('#refresh').onclick=()=>window.PageLifecycle.guard(async()=>{void refreshTimer?.refresh().catch(()=>{});const region=({overview:'home','order-notifications':'home',health:'health',bpm:'bpm',assistant:'assistant',records:'records','records-pdf':'records','notification-orders':'records','notification-batches':'records','notification-execution':'records','notification-history':'records'})[currentView];if(region&&await window.PageLifecycle.refreshRegions(region))return;return window.RecordTable?.active?window.RecordTable.active.refresh():renderView();}).catch(error=>notify(error.message,'danger'));
document.querySelectorAll('[data-view]').forEach(link=>link.onclick=()=>{const menu=document.querySelector('#sidebar-menu');menu.classList.remove('show');if(menu.classList.contains('collapsing'))menu.addEventListener('shown.bs.collapse',()=>menu.classList.remove('show'),{once:true});document.querySelector('.navbar-toggler').setAttribute('aria-expanded','false');});
}
function empty(title,text){return `<div class="empty-state"><div class="avatar avatar-lg bg-blue-lt mb-3">▤</div><h3>${title}</h3><p class="text-secondary">${text}</p></div>`;}
@@ -133,7 +143,7 @@ async function updateAutomationStatus(isActive,{signal}={}){
if(!data.settings.enabled)apply('自动通知已暂停','secondary','自动发信保持暂停;请完成类别字段、目录、邮箱与预览核验。'+(missing.length?' 待检查:'+missing.join('、'):' 点击查看发送设置。'));
else if(missing.length)apply('自动通知待核验','yellow','部分接入能力尚待核验,请到通知总览查看实际订单和阻塞详情。');
else apply('自动通知已启用','green','通知开关已启用;实际任务、类别及批次仍按各自检查结果执行。');
}catch(error){if(signal?.aborted)return;apply('通知状态待确认','yellow',error.message+';请刷新重试。');}
}catch(error){if(signal?.aborted)throw error;apply('通知状态待确认','yellow',error.message+';请刷新重试。');throw error;}
}
function configurationHost(container){
container.innerHTML='<section class="card notification-configuration"><div class="card-header"><nav id="notification-config-tabs" class="nav nav-segmented settings-tabs configuration-tabs" aria-label="通知配置导航"></nav></div><div class="card-body" id="notification-config-content"></div></section>';
@@ -148,7 +158,7 @@ async function renderView() {
history.replaceState(history.state,'',window.RecordState.serialize(resolved,Object.fromEntries(params)));
}
if(window.RecordState.isRecord(location.hash)&&currentView===resolved&&window.RecordTable?.active?.view===resolved){historyIndex=Number.isInteger(history.state?.appIndex)?history.state.appIndex:historyIndex;void updateAutomationStatus(()=>!!currentUser&&currentView===resolved);return window.RecordTable.active.navigate();}
if(window.RecordState.isRecord(location.hash)&&currentView===resolved&&window.RecordTable?.active?.view===resolved){historyIndex=Number.isInteger(history.state?.appIndex)?history.state.appIndex:historyIndex;void refreshTimer?.run().catch(()=>{});return window.RecordTable.active.navigate();}
const wasRecord=['records','records-pdf'].includes(currentView);
const generation=++viewGeneration;const isActive=()=>generation===viewGeneration && !!currentUser;
await window.PageLifecycle?.dispose();
@@ -166,7 +176,7 @@ async function renderView() {
const notificationSections={'order-notifications':'workbench','notification-execution':'execution','notification-orders':'orders','notification-batches':'pending','notification-history':'history','notification-settings':'settings'};
const fn={'rule-fields':(host,active)=>window.OrderRuleViews.render(host,active,'fields'),...Object.fromEntries(Object.entries(notificationSections).map(([route,section])=>[route,(host,active)=>window.OrderNotificationViews.render(host,active,section)])),'assistant-settings':window.AssistantViews?.settings,account:window.AccountViews?.account,'order-rules':window.OrderRuleViews?.render,health:window.HealthViews?.render,assistant:window.AssistantViews?.render,storage:window.StorageViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,records:viewRecords,'records-pdf':viewPdfRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,users:window.AccountViews?.users,audit:viewAudit,rules:viewRules}[currentView];
void updateAutomationStatus(isActive);
void refreshTimer?.run().catch(()=>{});
try{window.PageLifecycle?.attach(container);const host=window.AppNavigation.isConfiguration(currentView)?configurationHost(container):container;await fn(host,isActive);if(isActive())window.PageLifecycle?.bind();}catch(error){if(isActive())container.innerHTML=`<div class="alert alert-danger">${esc(error.message)}</div>`;}
}
async function authScreen() {
@@ -176,7 +186,7 @@ async function authScreen() {
}
async function passwordChanged(actorId){if(currentUser&&currentUser.id!==actorId)return false;currentUser=null;++viewGeneration;refreshTimer?.dispose();await window.PageLifecycle?.dispose();await window.BpmLogin?.dispose().catch(()=>{});await boot();return true;}
function enter(){window.RecordState.configure(currentUser,({hash,push})=>{if(push&&location.hash!==hash)history.pushState({appIndex:++historyIndex},'',hash);else history.replaceState({...history.state,appIndex:historyIndex},'',hash);});window.PdfRecordViews?.configure({api,esc,formatDate,notify,user:currentUser});window.AccountViews?.configure({api,esc,formatDate,notify,user:currentUser,onPasswordChanged:passwordChanged});window.OrderRuleViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderNotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.HealthViews?.configure({api,esc,formatDate,user:currentUser});window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();renderView();void checkSystemUpdate(()=>!!currentUser);refreshTimer?.dispose();refreshTimer=window.PageLifecycle.poll(signal=>{const statusGeneration=viewGeneration,statusUser=currentUser;return updateAutomationStatus(()=>statusGeneration===viewGeneration&&statusUser===currentUser,{signal});},15000,{isActive:()=>!!currentUser,owned:false});}
function enter(){window.PageLifecycle.configureRegions({read:(signal,region)=>api('/refresh/revisions?regions='+encodeURIComponent(region),undefined,{signal}),user:()=>currentUser});window.RecordState.configure(currentUser,({hash,push})=>{if(push&&location.hash!==hash)history.pushState({appIndex:++historyIndex},'',hash);else history.replaceState({...history.state,appIndex:historyIndex},'',hash);});window.PdfRecordViews?.configure({api,esc,formatDate,notify,user:currentUser});window.AccountViews?.configure({api,esc,formatDate,notify,user:currentUser,onPasswordChanged:passwordChanged});window.OrderRuleViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderNotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.HealthViews?.configure({api,esc,formatDate,user:currentUser});window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();refreshTimer?.dispose();const statusUser=currentUser;refreshTimer=window.PageLifecycle.regionPoll('orderRules',{refresh:signal=>updateAutomationStatus(()=>currentUser===statusUser,{signal}),onError:error=>{const node=document.querySelector('#automation-status');if(node&&currentUser===statusUser){node.textContent='通知状态待确认';node.className='badge bg-yellow-lt text-decoration-none';node.title=error.message+';请刷新重试。';}}},15000,{isActive:()=>!!currentUser&&currentUser===statusUser,owned:false});renderView();void checkSystemUpdate(()=>!!currentUser);}
async function boot(){try{currentUser=(await api('/me')).user;enter();}catch{await authScreen();}}
window.addEventListener('page-operation-error',event=>notify(event.detail.message,'danger'));
window.addEventListener('pagehide',()=>{window.BpmLogin?.dispose({unload:true});});
+1 -1
View File
@@ -23,7 +23,7 @@
if(running||[...pendingActions.values()].includes(currentId)||turns.some(t=>t.actions?.some(a=>a.status==='running')))watch();
}
async function loadCurrent(signal){if(!currentId)return;const id=currentId,at=revision,c=await api('/assistant/conversations/'+id,undefined,{signal,ownerCheck:live});if(!live()||id!==currentId||at!==revision)return;conversation=c;drawMessages();}
const watcher=window.PageLifecycle.poll(async signal=>{if(!polling)return;polling=false;try{await loadCurrent(signal);}catch(e){if(signal.aborted)polling=true;else showError(e);}},1200,{isActive:live});
const watcher=window.PageLifecycle.regionPoll('assistant',{refresh:async signal=>{if(!polling)return false;polling=false;try{await loadCurrent(signal);}catch(e){polling=true;throw e;}},onError:showError},1200,{isActive:live,enabled:()=>polling});watcher.refreshRegion=async()=>{await window.PageLifecycle.validateRegion('assistant').catch(showError);await refreshList();await loadCurrent();};
function watch(){polling=true;watcher.schedule();}
async function select(id){currentId=id;conversation=null;revision++;sessionStorage.setItem(key,id);drawList();if(id)await loadCurrent();else drawMessages();}
function drawPager(){container.querySelector('#assistant-page').textContent=listPage+' / '+Math.max(1,Math.ceil(listTotal/25));container.querySelector('#assistant-prev').disabled=listPage<=1;container.querySelector('#assistant-next').disabled=listPage*25>=listTotal;}
+3 -3
View File
@@ -16,10 +16,10 @@ window.OrderViews=(()=>{
function open(row,trigger){const f=(label,value)=>window.RecordUi.field(esc,label,value);detail.show('<dl class="record-detail-grid">'+f('流水号',row.serialNum)+f('流程',row.processName)+f('流程版本',row.processVersion)+f('节点',row.activityName)+f('到达类型',row.kind==='todo'?'待办到达记录':'待阅到达记录')+f('到达时间',formatDate(row.arrivedAt))+f('来源连接',row.origin.name)+f('来源账号',row.origin.identity||'账号未记录')+f('负责人',row.origin.owner)+f('来源状态',row.origin.status==='archived'?'历史归档':row.origin.enabled?'现有连接':'现有连接 · 已停用')+f('来源归档时间',row.origin.archivedAt?formatDate(row.origin.archivedAt):row.origin.status==='archived'?'未记录':'—')+(row.origin.missing?f('来源说明','来源信息缺失,保留原连接标识:'+row.connectionId):'')+f('首次采集',formatDate(row.firstSeenAt))+f('最近观察',formatDate(row.lastSeenAt))+f('任务标识',row.taskId)+f('完整标题',row.subject)+'</dl>',trigger);}
function draw(data){const host=container.querySelector('[data-arrival-list]');host.innerHTML=data.items.length?'<div class="table-responsive"><table class="table table-vcenter table-hover card-table record-ledger"><thead><tr><th scope="col">流水号/流程</th><th scope="col" class="record-node">节点/类型</th><th scope="col">标题摘要</th><th scope="col" class="record-source">来源</th><th scope="col" class="record-time">到达时间</th><th scope="col">详情</th></tr></thead><tbody>'+data.items.map((row,index)=>'<tr data-arrival-row><td class="record-identity"><strong>'+esc(row.serialNum||'—')+'</strong><div class="small text-secondary">'+esc(row.processName)+'</div><div class="record-inline-source small text-secondary">'+esc(row.origin.name)+(row.origin.status==='archived'?' · 历史归档':row.origin.enabled?'':' · 已停用')+'</div><div class="record-inline-time small text-secondary">'+esc(formatDate(row.arrivedAt))+'</div><div class="record-inline-summary record-summary small">'+esc(row.subject||'—')+'</div></td><td class="record-node">'+esc(row.activityName==='sysInform'?'知会':row.activityName||'—')+'<div class="small text-secondary">'+(row.kind==='todo'?'待办到达':'待阅到达')+'</div></td><td class="record-summary-cell"><div class="record-summary">'+esc(row.subject||'—')+'</div></td><td class="record-source"><div>'+esc(row.origin.name)+'</div><span class="badge bg-'+(row.origin.status==='archived'?'secondary':row.origin.enabled?'green':'yellow')+'-lt">'+(row.origin.status==='archived'?'历史归档':row.origin.enabled?'现有连接':'已停用')+'</span></td><td class="record-time small text-secondary text-nowrap">'+esc(formatDate(row.arrivedAt))+'</td><td class="record-action"><button type="button" class="btn btn-sm" data-arrival-detail="'+index+'">查看详情</button></td></tr>').join('')+'</tbody></table></div>':'<div class="empty py-5"><p class="empty-title">暂无匹配的到达记录</p><p class="empty-subtitle text-secondary">可调整日期、业务范围或查看历史归档。</p></div>';host.querySelectorAll('[data-arrival-detail]').forEach(button=>button.onclick=()=>open(data.items[Number(button.dataset.arrivalDetail)],button));sourceOptions(data.sources);monitor();}
const table=window.RecordTable.mount({view:'records',container,isActive:live,api,onCommit:next=>{filters=next;},render:draw,readDraft(){const scope=get('arrival-scope').value;return {q:get('arrival-query').value.trim(),scope,business:get('arrival-business').value,kind:get('arrival-kind').value,connectionId:filters.scope!==scope?'':get('arrival-connection').value,from:get('arrival-from').value,to:get('arrival-to').value};},writeDraft(next){for(const [field,id]of Object.entries({q:'arrival-query',scope:'arrival-scope',business:'arrival-business',kind:'arrival-kind',connectionId:'arrival-connection',from:'arrival-from',to:'arrival-to'}))get(id).value=next[field];}});
async function refresh(signal){try{statusController?.abort();statusController=new AbortController();const next=await api('/bpm-scan',undefined,{signal:AbortSignal.any([signal,statusController.signal]),ownerCheck:live});if(!live())return;status=next;monitor();const runs=status.runs.filter(r=>(filters.kind==='all'||(r.kind||'inform')===filters.kind)&&(!filters.connectionId||r.connectionId===filters.connectionId));if(runs[0]?.status==='error')container.querySelector('[data-monitor]').textContent+=' · 最近同步失败:'+runs[0].message;else if(runs[0]?.status==='success')container.querySelector('[data-monitor]').textContent+=' · 同步完成 '+formatDate(runs[0].finishedAt);}catch(e){if(!signal.aborted&&live())error('监听状态读取失败:'+e.message);}}
const polling=window.PageLifecycle.poll(refresh,10000,{isActive:live});
async function refresh(signal){try{statusController?.abort();statusController=new AbortController();const next=await api('/bpm-scan',undefined,{signal:AbortSignal.any([signal,statusController.signal]),ownerCheck:live});if(!live())return;status=next;monitor();const runs=status.runs.filter(r=>(filters.kind==='all'||(r.kind||'inform')===filters.kind)&&(!filters.connectionId||r.connectionId===filters.connectionId));if(runs[0]?.status==='error')container.querySelector('[data-monitor]').textContent+=' · 最近同步失败:'+runs[0].message;else if(runs[0]?.status==='success')container.querySelector('[data-monitor]').textContent+=' · 同步完成 '+formatDate(runs[0].finishedAt);}catch(e){throw e;}}
const polling=window.PageLifecycle.regionPoll('bpm',{refresh,onError:e=>{if(live())error('监听状态读取失败:'+e.message);}},10000,{isActive:live});
if(get('scan-now'))get('scan-now').onclick=async()=>{const button=get('scan-now');button.disabled=true;try{for(const c of candidates())for(const kind of filters.kind==='all'?['todo','inform']:[filters.kind])await api('/bpm-scan/run',{connectionId:c.id,kind});if(live()){notify('只读同步已启动。');await polling.refresh();}}catch(e){if(live())error(e.message+';已接受的同步请查看最新结果。');}finally{if(live())monitor();}};
await Promise.all([table.ready,polling.run()]);
await Promise.all([table.ready,polling.run().catch(async()=>{await refresh(new AbortController().signal).catch(e=>{if(live())error('监听状态读取失败:'+e.message);});})]);
}
return {configure,records};
})();
+4 -4
View File
@@ -97,11 +97,11 @@ window.BpmLogin=(()=>{
async function refreshStatus(signal){
if(!live())return;
try{
if(accountBusy||mutationBusy)return;const request=statusRevision,next=await api('/workspace',undefined,{signal,ownerCheck:live});if(!live()||request!==statusRevision)return;
if(accountBusy||mutationBusy)return false;const request=statusRevision,next=await api('/workspace',undefined,{signal,ownerCheck:live});if(!live()||request!==statusRevision)return false;
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){const expanded=health.querySelector('details')?.open;health.innerHTML=observations(c);if(expanded)health.querySelector('details').open=true;}}
}catch{}
}catch(error){throw error;}
}
function ownerForm(c){
if(user.role!=='admin')return '';
@@ -194,12 +194,12 @@ window.BpmLogin=(()=>{
input.onkeydown=keydown;surface.onkeydown=event=>{if(event.target!==input)keydown(event);};surface.onpaste=event=>{if(event.target!==input)input.onpaste(event);};
}
try{
data=await api('/workspace');if(!live())return;connections=data.connections||[];
let initial,initialError;try{initial=await window.PageLifecycle.validateRegion('bpm');}catch(error){initialError=error;}data=await api('/workspace');if(!live())return;connections=data.connections||[];
container.innerHTML=`<div data-bpm-feedback hidden role="alert"></div><div class="connection-layout bpm-layout"><div><div id="bpm-list"></div></div>${user.role==='admin'?`<form class="card" id="connection-create"><div class="card-header"><h2 class="card-title">添加 BPM 连接</h2></div><div class="card-body"><div class="mb-3"><label class="form-label required" for="connection-name">连接名称</label><input class="form-control" id="connection-name" required maxlength="100" placeholder="例如:业务团队 BPM"></div><div><label class="form-label required" for="connection-owner">负责人</label><select class="form-select" id="connection-owner" required><option value="">请选择负责人</option>${(data.members||[]).filter(m=>m.role!=='viewer').map(m=>`<option value="${esc(m.username)}">${esc(m.username)}</option>`).join('')}</select></div></div><div class="card-footer text-end"><button class="btn btn-primary" type="submit">创建连接</button></div></form>`:''}</div><div id="bpm-remote" aria-live="polite"></div><div id="bpm-sync-settings"></div>`;
if(user.role==='admin')$('#connection-create').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button[type=submit]');button.disabled=true;try{const result=await api('/connections',{name:$('#connection-name').value.trim(),owner:$('#connection-owner').value});if(!live())return;++statusRevision;connections.unshift(result.connection||result);event.target.reset();drawCards();feedback('连接已创建。','success');}catch(error){feedback(error.message);}finally{if(live())button.disabled=false;}};
drawCards();
connections.filter(c=>c.status!=='disabled'&&authorized(c)).forEach(c=>loadAccount(c.id).then(refreshAccountSummary).catch(error=>feedback(error.message)));
statusTimer=window.PageLifecycle.poll(refreshStatus,5000,{isActive:live});
statusTimer=window.PageLifecycle.regionPoll('bpm',{refresh:refreshStatus,onError:error=>feedback('状态读取失败:'+error.message+';保留上次状态,请刷新重试。')},5000,{isActive:live,initial});if(initialError)feedback('状态读取失败:'+initialError.message+';正在显示已读取的连接,请刷新重试。');
await window.BpmSyncSettings?.mount($('#bpm-sync-settings'),{api,user,notify,isActive:live});
}catch(error){if(live())throw error;}
}
+6 -3
View File
@@ -18,13 +18,16 @@
container.querySelector('#health-events').innerHTML=`<section class="card"><div class="card-header"><h3 class="card-title">最近守护事件</h3></div><div class="card-body">${guard.events?.length?guard.events.slice(0,12).map(event=>`<div class="d-flex flex-wrap gap-2 mb-2 small"><span class="text-secondary">${esc(formatDate(event.at))}</span><span>${esc(events[event.kind]||'运行状态变化')}${event.code!==undefined&&event.code!==null?'(退出码 '+esc(event.code)+')':''}${event.delayMs?','+Math.ceil(event.delayMs/1000)+' 秒后尝试':''}</span></div>`).join(''):'<span class="text-secondary small">暂无守护事件。</span>'}</div><div class="card-footer small text-secondary">模块状态来自已保存的检查结果;成功与失败时间会持续记录。此页面每 10 秒更新,不触发外部连接检查。</div></section>`;
}
async function refresh(signal){
if(pending||!live())return;pending=true;button.disabled=true;
if(pending||!live())return false;pending=true;button.disabled=true;
try{const data=await api('/health',undefined,{signal:AbortSignal.any([signal,AbortSignal.timeout(8000)]),ownerCheck:live});if(!live())return;draw(data);notice.className='card-footer small text-secondary';notice.innerHTML=`<span>健康状态已更新</span><span class="ms-2">${esc(formatDate(data.at))}</span>`;}
catch{if(!signal.aborted&&live()){const access=container.querySelector('#health-access');if(access){access.className='badge bg-red-lt ms-auto';access.textContent='连接中断';}notice.className='card-footer small text-danger';notice.textContent='暂时无法连接服务,保留上次状态;恢复后会自动更新。';}}
catch(error){throw error;}
finally{pending=false;if(live()){button.disabled=false;}}
}
if(user?.role==='admin'){const box=container.querySelector('#health-maintenance');box.innerHTML='<section class="card"><div class="card-header"><h3 class="card-title">数据容量与保留</h3><button class="btn btn-sm ms-auto" type="button" id="capacity-refresh">刷新容量</button></div><div class="card-body" id="capacity-content">正在读取…</div></section>';const load=async()=>{const b=container.querySelector('#capacity-refresh');b.disabled=true;try{const d=await api('/maintenance');if(live())container.querySelector('#capacity-content').innerHTML='<p>默认永久保留;会话归档及异常退役保留原证据。</p><p>状态数据 '+(d.state.bytes/1048576).toFixed(2)+' MiB · PDF '+d.pdf.files+' 份 / '+(d.pdf.bytes/1048576).toFixed(2)+' MiB · 导出台账 '+d.jobs.total+' 条</p><a class="btn" href="/api/jobs/export">导出 PDF 历史</a><p class="small text-secondary mt-3 mb-0">备份与恢复按停服操作指南执行;只恢复到新空目录。</p>';}catch(e){if(live())container.querySelector('#capacity-content').textContent=e.message;}finally{if(live())b.disabled=false;}};container.querySelector('#capacity-refresh').onclick=load;void load();}
const polling=window.PageLifecycle.poll(refresh,10000,{isActive:live});button.onclick=()=>polling.run();await polling.run();
const failed=error=>{if(!live())return;const access=container.querySelector('#health-access');if(access){access.className='badge bg-red-lt ms-auto';access.textContent='连接中断';}notice.className='card-footer small text-danger';notice.textContent='状态读取失败:'+error.message+';保留上次状态,请刷新重试。';};
let initial,initialError;try{initial=await window.PageLifecycle.validateRegion('health');}catch(error){initialError=error;}
await refresh(new AbortController().signal).catch(failed);
const polling=window.PageLifecycle.regionPoll('health',{refresh,onError:failed},10000,{isActive:live,initial});button.onclick=()=>polling.refresh().catch(()=>{});if(initialError)failed(initialError);await polling.run().catch(()=>{});
}
window.HealthViews={configure:options=>({api,esc,formatDate,user}=options),render};
})();
+33 -1
View File
@@ -48,6 +48,38 @@ window.PageLifecycle=(()=>{
const handle={run,schedule,cancel,async refresh(){await cancel();return run();},dispose(){if(disposed)return;disposed=true;clearTimeout(timer);controller?.abort();document.removeEventListener('visibilitychange',visibility);}};
document.addEventListener('visibilitychange',visibility);if(owned)onDispose(()=>handle.dispose());schedule();return handle;
}
// Revisions identify server state, never response bodies. Each mounted consumer owns
// its applied token so one view cannot acknowledge another view's unfinished read.
let regionSettings={read:null,user:()=>null},regionConfiguration=0;
const regionEpochs=new Map(),regionHandles=new Set();
function configureRegions(options){regionSettings=options;regionConfiguration++;regionEpochs.clear();}
function invalidateRegion(...regions){for(const region of regions.flat())regionEpochs.set(region,(regionEpochs.get(region)||0)+1);}
async function validateRegion(region,{signal,validate=regionSettings.read}={}){
if(typeof validate!=='function')throw Error('刷新状态读取未配置,请刷新页面重试。');
const user=regionSettings.user?.(),configuration=regionConfiguration,epoch=regionEpochs.get(region)||0;
const response=await validate(signal,region),token=response?.regions?.[region];
if(signal?.aborted)throw signal.reason||new DOMException('Aborted','AbortError');
if(typeof token!=='string'||!/^[0-9a-f]{64}$/i.test(token))throw Error('刷新状态响应缺少有效区域版本,请重试。');
return {token,error:typeof response?.errors?.[region]==='string'?response.errors[region]:'',user,configuration,epoch};
}
function regionPoll(region,{refresh,validate,onError=()=>{}},interval,options={}){
let applied=options.initial,appliedAt=Date.now();
const current=state=>state&&state.configuration===regionConfiguration&&state.user===regionSettings.user?.()&&state.epoch===(regionEpochs.get(region)||0);
const handle=poll(async signal=>{
try{
if(options.enabled&&!options.enabled())return;
const next=await validateRegion(region,{signal,validate});
if(!current(next))return;
if(current(applied)&&applied.token===next.token&&(!options.forceAfter||Date.now()-appliedAt<options.forceAfter))return;
const result=await refresh(signal,next);
if(next.error)onError(Object.assign(Error(next.error),{regionError:true}));
if(result!==false&&!signal.aborted&&current(next)&&(!options.isActive||options.isActive())){applied=next;appliedAt=Date.now();}
}catch(error){if(!signal.aborted)onError(error);throw error;}
},interval,options);
handle.refresh=async()=>{await handle.cancel();applied=undefined;return handle.run();};
handle.accept=state=>{if(current(state)){applied=state;appliedAt=Date.now();}};const dispose=handle.dispose;handle.dispose=()=>{regionHandles.delete(handle);dispose();};handle.region=region;handle.owned=options.owned!==false;regionHandles.add(handle);return handle;
}
async function refreshRegions(region){const handles=[...regionHandles].filter(handle=>handle.owned&&handle.region===region);await Promise.all(handles.map(handle=>(handle.refreshRegion||handle.refresh)()));return handles.length>0;}
const requestKey=()=>typeof crypto.randomUUID==='function'?crypto.randomUUID():'request-'+[...crypto.getRandomValues(new Uint8Array(16))].map(v=>v.toString(16).padStart(2,'0')).join('');
return {poll,afterSave,requestKey,attach,bind,register,onDispose,dispose,guard,dirty,failed,succeeded,get submission(){return activeSubmission;},get revision(){return revision;}};
return {poll,regionPoll,refreshRegions,configureRegions,validateRegion,invalidateRegion,afterSave,requestKey,attach,bind,register,onDispose,dispose,guard,dirty,failed,succeeded,get submission(){return activeSubmission;},get revision(){return revision;}};
})();
+9 -5
View File
@@ -1,18 +1,22 @@
'use strict';
window.OrderNotificationViews=(()=>{
let helpers,homeDispose;
async function render(container,isActive=()=>true,section='workbench',prepared=null){
async function render(container,isActive=()=>true,section='workbench',prepared=null,initial=null){
homeDispose?.();homeDispose=null;
const {api,esc,formatDate,user}=helpers;
if(['execution','orders','pending','history'].includes(section))return window.BusinessRecordViews.render(container,{...helpers,isActive},['execution','orders'].includes(section)?'orders':'batches');
if(section!=='settings')container.innerHTML=window.BusinessHome.loading();
let initialError;if(section!=='settings'&&!prepared)try{initial=await window.PageLifecycle.validateRegion('home');}catch(error){initialError=error;}
const [data,mail]=section==='settings'?await Promise.all([api('/order-rules/notification-settings'),api('/mail').catch(error=>({channels:[],error:error.message}))]):[prepared||await api('/order-rules?view=summary')];if(!isActive())return;
if(section==='settings')return settings(container,data,isActive,mail);
const home=window.BusinessHome.mount(container,data,{esc,formatDate,isActive});
let disposed=false,refreshController;const notice=container.querySelector('[data-business-updates]'),signature=JSON.stringify(data);
notice.querySelector('button').onclick=async event=>{const button=event.currentTarget;if(button.disabled)return;button.disabled=true;refreshController=new AbortController();try{await polling.cancel();const fresh=await api('/order-rules?view=summary',undefined,{signal:refreshController.signal});if(!disposed&&isActive())await render(container,isActive,'workbench',fresh);}catch(error){if(!disposed&&isActive()){notice.hidden=false;notice.querySelector('[data-update-text]').textContent='刷新失败:'+error.message+';仍显示上次结果。';home.setStale(true,true);}}finally{if(button.isConnected)button.disabled=false;}};
async function poll(signal){if(disposed||!isActive())return;try{const fresh=await api('/order-rules?view=summary',undefined,{signal,ownerCheck:isActive});if(!disposed&&isActive()){const changed=JSON.stringify(fresh)!==signature;notice.hidden=!changed;notice.querySelector('[data-update-text]').textContent='业务状态有更新。';home.setStale(changed);}}catch{if(!signal.aborted&&!disposed&&isActive()){notice.hidden=false;notice.querySelector('[data-update-text]').textContent='状态读取失败,仍显示上次结果。';home.setStale(true,true);}}}
const polling=window.PageLifecycle.poll(poll,15000,{isActive:()=>!disposed&&isActive()});homeDispose=()=>{disposed=true;polling.dispose();refreshController?.abort();home.dispose();};window.PageLifecycle.onDispose(homeDispose);
let disposed=false,pending;const notice=container.querySelector('[data-business-updates]'),signature=JSON.stringify(data);
const failed=error=>{if(!disposed&&isActive()){notice.hidden=false;notice.querySelector('[data-update-text]').textContent='刷新失败:'+error.message+';仍显示上次结果。';home.setStale(true,true);}};
async function refresh(){try{await polling.refresh();if(!disposed&&isActive()&&pending)await render(container,isActive,'workbench',pending.data,pending.initial);}catch(error){failed(error);}}
notice.querySelector('button').onclick=async event=>{const button=event.currentTarget;if(button.disabled)return;button.disabled=true;try{await refresh();}finally{if(button.isConnected)button.disabled=false;}};
async function poll(signal,validation){if(disposed||!isActive())return false;const fresh=await api('/order-rules?view=summary',undefined,{signal,ownerCheck:isActive});if(disposed||!isActive())return false;pending={data:fresh,initial:validation};const changed=JSON.stringify(fresh)!==signature;notice.hidden=!changed;notice.querySelector('[data-update-text]').textContent='业务状态有更新。';home.setStale(changed);}
const polling=window.PageLifecycle.regionPoll('home',{refresh:poll,onError:failed},15000,{initial,isActive:()=>!disposed&&isActive()});polling.refreshRegion=refresh;homeDispose=()=>{disposed=true;polling.dispose();home.dispose();};window.PageLifecycle.onDispose(homeDispose);
if(initialError)failed(initialError);
}
async function settings(container,data,isActive,mail){
const {api,esc,user,formatDate}=helpers,config=data.settings,admin=user.role==='admin';if(!isActive())return;
+9 -8
View File
@@ -12,19 +12,20 @@ window.RecordTable=(()=>{
function pager(){if(!data)return;window.RecordUi.pager(container,{...data,change:page=>{if(!busy)void load({...applied,page},{push:true,scroll:'top'});},resize:pageSize=>{if(!busy)void load({...applied,page:1,pageSize},{push:true,scroll:'top'});}});controls();}
async function load(filters,options={}){
if(!live())return;const id=++requestId;controller?.abort();pollController?.abort();controller=new AbortController();if(data)window.RecordState.capture(view,applied);busy=true;retry=null;feedback('');controls();const next=window.RecordState.normalize(view,filters);
try{const result=await api((endpoint|| (view==='records'?'/arrivals':'/jobs'))+'?'+new URLSearchParams({...(!endpoint?{view:'ledger'}:{}),...next}),undefined,{signal:controller.signal});if(!live()||id!==requestId)return;
applied={...next,page:result.page,pageSize:result.pageSize};onCommit(applied);render(result);data=result;signature=snapshot(result);notice.hidden=true;window.RecordState.commit(view,applied,{push:!!options.push});if(options.draft)writeDraft(applied);busy=false;pager();
await new Promise(resolve=>requestAnimationFrame(resolve));if(!live()||id!==requestId)return;if(options.scroll==='restore')window.scrollTo(0,options.y??window.RecordState.position(view));else if(options.scroll==='top')list.scrollIntoView({block:'start'});window.RecordState.capture(view,applied);
}catch(e){if(!live()||id!==requestId)return;busy=false;retry={filters:next,options};if(data&&options.draft)window.RecordState.commit(view,applied);feedback('读取失败:'+e.message+(data?';仍显示上次成功的记录。':''));pager();controls();}
try{const validation=options.validation||await window.PageLifecycle.validateRegion('records',{signal:controller.signal}).catch(()=>null);const result=await api((endpoint|| (view==='records'?'/arrivals':'/jobs'))+'?'+new URLSearchParams({...(!endpoint?{view:'ledger'}:{}),...next}),undefined,{signal:controller.signal});if(!live()||id!==requestId)return false;
applied={...next,page:result.page,pageSize:result.pageSize};onCommit(applied);render(result);data=result;signature=snapshot(result);polling.accept(validation);notice.hidden=true;window.RecordState.commit(view,applied,{push:!!options.push});if(options.draft)writeDraft(applied);busy=false;pager();
await new Promise(resolve=>requestAnimationFrame(resolve));if(!live()||id!==requestId)return false;if(options.scroll==='restore')window.scrollTo(0,options.y??window.RecordState.position(view));else if(options.scroll==='top')list.scrollIntoView({block:'start'});window.RecordState.capture(view,applied);return true;
}catch(e){if(!live()||id!==requestId)return false;busy=false;retry={filters:next,options};if(data&&options.draft)window.RecordState.commit(view,applied);feedback('读取失败:'+e.message+(data?';仍显示上次成功的记录。':''));pager();controls();return false;}
}
function apply(){if(busy)return;void load({...applied,...readDraft(),page:1},{push:true,scroll:'top'});}
container.querySelectorAll('[data-record-query]').forEach(button=>button.onclick=apply);
const inputs=container.querySelectorAll('.record-filters input,.record-filters select,#record-search,#record-status');for(const input of inputs)input.addEventListener('keydown',event=>{if(event.key==='Enter'){event.preventDefault();apply();}});
async function check(signal){if(!live())return;try{if(data&&!busy){pollController=new AbortController();const result=await api((endpoint|| (view==='records'?'/arrivals':'/jobs'))+'?'+new URLSearchParams({...(!endpoint?{view:'ledger'}:{}),...applied}),undefined,{signal:AbortSignal.any([signal,pollController.signal]),ownerCheck:live});if(!signal.aborted&&live()&&!busy)notice.hidden=snapshot(result)===signature;}}catch{}}
const polling=window.PageLifecycle.poll(check,10000,{isActive:live});
refresh.onclick=notice.querySelector('button').onclick=()=>{if(!busy)void load(applied,{scroll:'keep'});};
async function check(signal){if(!live()||busy||!data)return false;const id=requestId;pollController=new AbortController();const result=await api((endpoint|| (view==='records'?'/arrivals':'/jobs'))+'?'+new URLSearchParams({...(!endpoint?{view:'ledger'}:{}),...applied}),undefined,{signal:AbortSignal.any([signal,pollController.signal]),ownerCheck:live});if(signal.aborted||!live()||busy||id!==requestId)return false;notice.hidden=snapshot(result)===signature;}
const polling=window.PageLifecycle.regionPoll('records',{refresh:check,onError:error=>{if(live())feedback('状态读取失败:'+error.message+';保留上次记录,请刷新重试。');}},10000,{isActive:live,forceAfter:view==='records-pdf'?60000:0});
const manualRefresh=()=>load(applied,{scroll:'keep'});polling.refreshRegion=manualRefresh;
refresh.onclick=notice.querySelector('button').onclick=()=>{if(!busy)void manualRefresh();};
const scroll=()=>{clearTimeout(scrollTimer);scrollTimer=setTimeout(()=>{if(live()&&data&&!busy)window.RecordState.capture(view,applied);},150);},pagehide=()=>{if(data)window.RecordState.capture(view,applied);};window.addEventListener('scroll',scroll,{passive:true});window.addEventListener('pagehide',pagehide);
const handle={view,refresh:()=>load(applied,{scroll:'keep'}),navigate(){return load(window.RecordState.read(view),{draft:true,scroll:'restore',y:window.RecordState.position(view)});},get busy(){return busy;},dispose(){if(disposed)return;disposed=true;controller?.abort();pollController?.abort();polling.dispose();clearTimeout(scrollTimer);window.removeEventListener('scroll',scroll);window.removeEventListener('pagehide',pagehide);if(data)window.RecordState.capture(view,applied);if(window.RecordTable.active===handle)window.RecordTable.active=null;}};
const handle={view,refresh:manualRefresh,navigate(){return load(window.RecordState.read(view),{draft:true,scroll:'restore',y:window.RecordState.position(view)});},get busy(){return busy;},dispose(){if(disposed)return;disposed=true;controller?.abort();pollController?.abort();polling.dispose();clearTimeout(scrollTimer);window.removeEventListener('scroll',scroll);window.removeEventListener('pagehide',pagehide);if(data)window.RecordState.capture(view,applied);if(window.RecordTable.active===handle)window.RecordTable.active=null;}};
window.RecordTable.active=handle;window.PageLifecycle?.onDispose(()=>handle.dispose());handle.ready=load(applied,{scroll:'restore',y:initialScroll}).finally(()=>{if(live())polling.schedule();});return handle;
}
return {mount,active:null};
+1 -1
View File
@@ -32,7 +32,7 @@
const submission=window.PageLifecycle?.submission,controller=new AbortController(),cancel=()=>controller.abort(signal.reason);let timedOut=false;
if(signal?.aborted)cancel();else signal?.addEventListener('abort',cancel,{once:true});
const timer=setTimeout(()=>{timedOut=true;controller.abort();},timeout);
try{const response=await fetch('/api/storage/servers'+route,{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(input),signal:controller.signal});const body=await response.json();if(!response.ok)throw new Error(body.error||'存储操作失败。');if(route==='')window.PageLifecycle?.succeeded(submission);return body;}
try{window.PageLifecycle?.invalidateRegion?.('storage','orderRules','records','health','home');const response=await fetch('/api/storage/servers'+route,{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(input),signal:controller.signal});const body=await response.json();if(!response.ok)throw new Error(body.error||'存储操作失败。');window.PageLifecycle?.invalidateRegion?.('storage','orderRules','records','health','home');if(route==='')window.PageLifecycle?.succeeded(submission);return body;}
catch(error){if(route===''){window.PageLifecycle?.failed(submission);if(timedOut||error instanceof TypeError){api('/storage').then(()=>{if(alive())status.textContent='结果待核实:已查询服务器列表,请核对保存结果;不会自动重试。';}).catch(()=>{});throw new Error('结果待核实:保存响应超时或连接中断,正在查询状态;不会自动重试。');}}if(timedOut)throw new Error('连接超时,请检查网络后重试。');throw error;}
finally{clearTimeout(timer);signal?.removeEventListener('abort',cancel);}
}