merge: preserve main lazy loading and scoped refresh with DSH

This commit is contained in:
abaishu0730 committed 2026-10-29 09:42:00 +08:00
commit fb7a195186
113 files changed
+2675 -212

No files matched your search

+1 -1
View File
@@ -50,7 +50,7 @@ test('password version rejects old sessions even if eager session cleanup fails'
test('password change closes only the target account BPM login windows',async t=>{
const crypto=require('node:crypto'),{BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs');
const f=await fixture(t),first=await f.login('viewer'),second=await f.login('viewer'),admin=await f.login();
const cookies=[first,second,admin],manager={revokedSessionHashes:new Set(),sessions:new Map(cookies.map((cookie,i)=>[String(i),{id:String(i),sessionId:cookie.split('=')[1]}])),run:async(id,work)=>work(),async closeLease(id){this.sessions.delete(id);}};
const cookies=[first,second,admin],manager={sessionState:new (require('../../src/modules/bpm/session-state.cjs').SessionState)(),revokedSessionHashes:new Set(),sessions:new Map(cookies.map((cookie,i)=>[String(i),{id:String(i),sessionId:cookie.split('=')[1]}])),run:async(id,work)=>work(),async closeLease(id){this.sessions.delete(id);}};
const hashes=new SessionStore(f.dir);const targetHashes=hashes.userSessionHashes(f.viewer.id);hashes.close();
assert.equal(targetHashes.length,2);await BpmSessionManager.prototype.releaseSessionHashes.call(manager,targetHashes);assert.deepEqual([...manager.sessions.keys()],['2']);
assert.equal(targetHashes.includes(crypto.createHash('sha256').update(admin.split('=')[1]).digest('hex')),false);
+81
View File
@@ -0,0 +1,81 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict');
const fs=require('node:fs'),os=require('node:os'),path=require('node:path'),http=require('node:http'),zlib=require('node:zlib');
const {Store}=require('../../src/modules/dashboard/store.cjs');
const {createDashboard}=require('../../src/app/dashboard.cjs');
const {createAssetDelivery}=require('../../src/app/asset-delivery.cjs');
async function fixture(t){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'asset-delivery-')),store=new Store(dir),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});});
return (route,headers={},method='GET')=>new Promise((resolve,reject)=>{const request=http.request({hostname:'127.0.0.1',port:server.address().port,path:route,headers,method},response=>{const parts=[];response.on('data',part=>parts.push(part));response.on('end',()=>resolve({status:response.statusCode,headers:response.headers,bytes:Buffer.concat(parts)}));});request.on('error',reject);request.end();});
}
test('public assets compress losslessly and conditional reload sends no body while APIs stay private',async t=>{
const get=await fixture(t),plain=await get('/app.js'),compressed=await get('/app.js',{'Accept-Encoding':'br, gzip'});
assert.equal(compressed.status,200);assert.equal(compressed.headers['content-encoding'],'br');
assert.deepEqual(zlib.brotliDecompressSync(compressed.bytes),plain.bytes);assert.ok(compressed.bytes.length<plain.bytes.length/2);
assert.match(compressed.headers.vary,/Accept-Encoding/i);assert.ok(plain.headers.etag);assert.match(plain.headers['cache-control'],/must-revalidate/);
const unchanged=await get('/app.js',{'If-None-Match':plain.headers.etag,'Accept-Encoding':'gzip'});
assert.equal(unchanged.status,304);assert.equal(unchanged.bytes.length,0);
const api=await get('/api/me',{'Accept-Encoding':'br'});assert.equal(api.status,401);assert.equal(api.headers['cache-control'],'no-store');assert.equal(api.headers.etag,undefined);
const html=await get('/');assert.match(html.headers['cache-control'],/must-revalidate/);assert.ok(html.bytes.includes(Buffer.from('<!doctype html>')));
});
test('asset encoding negotiation honors q=0 and HEAD returns metadata without payload',async t=>{
const get=await fixture(t),gzip=await get('/app.css',{'Accept-Encoding':'br;q=0, gzip;q=0.7'});
assert.equal(gzip.headers['content-encoding'],'gzip');assert.ok(zlib.gunzipSync(gzip.bytes).length>gzip.bytes.length);
const plain=await get('/app.css',{'Accept-Encoding':'br;q=0, gzip;q=0'});assert.equal(plain.headers['content-encoding'],undefined);
const preferred=await get('/app.css',{'Accept-Encoding':'gzip;q=0.1, identity;q=1'});assert.equal(preferred.headers['content-encoding'],undefined);
const head=await get('/app.css',{'Accept-Encoding':'gzip'},'HEAD');assert.equal(head.status,200);assert.equal(head.bytes.length,0);assert.equal(Number(head.headers['content-length']),gzip.bytes.length);
const none=await get('/app.css',{'Accept-Encoding':'br;q=0,gzip;q=0,identity;q=0,*;q=0'});assert.equal(none.status,406);
const preview=await get('/storage-preview.js',{'Accept-Encoding':'gzip'});assert.match(preview.headers['content-security-policy'],/frame-ancestors 'self'/);assert.equal(preview.headers['access-control-allow-origin'],'*');
});
test('public asset cache revalidates changed files and concurrent reloads agree',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'asset-edit-')),file=path.join(dir,'app.js'),deliver=createAssetDelivery({maxBytes:4096});fs.writeFileSync(file,'old application');t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
async function get(etag){const headers={};let status,bytes;await deliver({method:'GET',headers:{'if-none-match':etag}},{setHeader:(key,value)=>headers[key]=value,writeHead:value=>status=value,end:value=>bytes=value},{path:file,type:'text/javascript'});return {headers,status,bytes};}
const first=await get();fs.writeFileSync(file,'new application with changed size');
const results=await Promise.all(Array.from({length:8},()=>get(first.headers.ETag)));
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>0&&urls.length<20,'core shell stays below twenty eager assets');
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('HTML publishes fingerprint URLs for lazy modules without eagerly loading optional pages',async t=>{
const get=await fixture(t),page=await get('/'),html=page.bytes.toString();
const encoded=/<meta name="app-modules" content="([^"]+)"/.exec(html)?.[1];assert.ok(encoded,'lazy module manifest must be available in the document');
const manifest=JSON.parse(encoded.replaceAll('&quot;','"').replaceAll('&lt;','<').replaceAll('&gt;','>').replaceAll('&amp;','&'));
for(const route of ['/assistant.js','/business-home.js','/order-rules.js']){
assert.ok(manifest.urls[route]);assert.equal(html.includes('<script src="'+manifest.urls[route]+'"'),false);
const asset=await get(manifest.urls[route]);assert.equal(asset.status,200);assert.match(asset.headers['cache-control'],/immutable/);assert.equal(new URL(manifest.urls[route],'http://local').searchParams.get('v'),asset.headers['x-asset-version']);
}
});
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);
});
@@ -0,0 +1,26 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),crypto=require('node:crypto'),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');
function fixture(t,cleanup=true){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'async-auth-')),store=new Store(dir),admin=store.bootstrap('admin','Test-password-123');if(cleanup)t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));return {store,dir,admin};}
test('HTTP login validates real stored credentials without synchronous password hashing',async t=>{
const {store,dir}=fixture(t,false),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 call=async(username,password)=>{const response=await fetch(base+'/api/login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:JSON.stringify({username,password})});return {status:response.status,body:await response.json(),cookie:response.headers.get('set-cookie')};};
t.mock.method(crypto,'scryptSync',()=>{throw Error('synchronous password computation blocks other pages');});
const good=await call('ADMIN','Test-password-123');assert.equal(good.status,200);assert.equal(good.body.user.username,'admin');assert.ok(good.cookie);
assert.equal((await call('missing','Test-password-123')).status,401);assert.equal((await call('admin','Wrong-password-123')).status,401);
const authenticate=store.authenticateAsync.bind(store);store.authenticateAsync=async(...args)=>{const user=await authenticate(...args);store.updateUser(user.id,{version:user.version,enabled:true,role:user.role},user);return user;};
const stale=await call('admin','Test-password-123');assert.equal(stale.status,401,'account revocation between validation and session issuance must win');assert.equal(stale.cookie,null);
});
test('a disabled or changed account cannot complete a queued asynchronous login',async t=>{
const {store,admin}=fixture(t),worker=store.addUser({username:'worker',password:'Test-password-123',role:'operator'},'admin');
assert.equal(typeof store.authenticateAsync,'function');
const pending=store.authenticateAsync('worker','Test-password-123');store.updateUser(worker.id,{version:1,enabled:false,role:'operator'},admin);assert.equal(await pending,null);
const reset=store.authenticateAsync('admin','Test-password-123');store.updatePassword(admin.id,'New-password-456',admin);assert.equal(await reset,null);
});
test('asynchronous password jobs yield to the event loop and reject excessive queued work',async t=>{
const {store}=fixture(t);assert.equal(typeof store.authenticateAsync,'function');
let completed=0;const jobs=Array.from({length:60},()=>store.authenticateAsync('admin','Test-password-123').finally(()=>completed++));
const settled=Promise.allSettled(jobs);await new Promise(r=>setImmediate(r));assert.ok(completed<60,'HTTP/event loop must run while scrypt works');
const results=await settled;assert.ok(results.some(item=>item.status==='fulfilled'&&item.value?.username==='admin'));assert.ok(results.some(item=>item.status==='rejected'&&item.reason.status===429));
});
@@ -0,0 +1,48 @@
'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 {RuntimeHealth}=require('../../src/modules/health/runtime-health.cjs');
const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs');
const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');
test('health reads execution progress without field evidence, candidates, scans or provider probes',t=>{
const stateDir=fs.mkdtempSync(path.join(os.tmpdir(),'lean-health-'));
const tasks=[
{id:'blocked',connectionId:'mine',row:{processName:'Current process'},status:'blocked',orderId:'o1',error:'Capture blocked',updatedAt:'2026-10-27T01:00:00Z'},
{id:'complete',connectionId:'mine',row:{processName:'Completed process'},status:'archived',orderId:'o2',reason:'Archived progress',updatedAt:'2026-10-27T02:00:00Z'},
{id:'private',connectionId:'other',row:{processName:'PRIVATE_OTHER'},status:'failed',updatedAt:'2026-10-27T03:00:00Z'}
];
const execution=Object.create(OrderExecutionCoordinator.prototype);
execution.store={capabilities:{liveTodo:true,pdfExport:false,automaticArchive:true},
all(kind){assert.equal(kind,'execution-tasks','health must only enumerate execution tasks');return structuredClone(tasks);},
get(kind,id){assert.equal(kind,'orders');return {status:id==='o1'?'pending':'sent',error:'Order detail'};},
fields(){assert.fail('health must not decrypt captured fields');}
};
execution.snapshot=()=>assert.fail('full execution snapshot is not a health read');
execution.provider={capabilities:()=>assert.fail('must not probe')};
const health=new RuntimeHealth({stateDir,execution,workspace:{snapshot:()=>({connections:[{id:'mine',owner:'worker'},{id:'other',owner:'other'}]})}});
t.after(()=>{health.close();fs.rmSync(stateDir,{recursive:true,force:true});});
const group=health.snapshot({username:'worker',role:'operator'}).groups.find(group=>group.key==='execution');
assert.equal(group.status,'error');
assert.deepEqual(group.items.filter(item=>!item.global).map(item=>[item.id,item.status,item.detail]),[['complete','healthy','Order detail'],['blocked','error','Capture blocked']]);
assert.doesNotMatch(JSON.stringify(group),/PRIVATE_OTHER/);
const first=execution.healthSnapshot();first.capabilities.liveTodo=false;first.tasks.find(task=>task.id==='complete').status='unknown';
assert.equal(execution.healthSnapshot().capabilities.liveTodo,true);
assert.equal(execution.healthSnapshot().tasks.find(task=>task.id==='complete').status,'sent');
});
test('paused dispatcher expires prepared automatic queues without assembling rules or execution snapshots',async()=>{
const now=new Date('2026-10-27T04:00:00Z'),finished=[],batches=[
{id:'expired',status:'prepared',cutoff:'2026-10-27T03:00:00Z'},
{id:'boundary',status:'prepared',cutoff:'2026-10-27T03:30:00Z'},
{id:'manual',status:'prepared',manual:true,cutoff:'2026-10-27T03:00:00Z'},
{id:'unknown',status:'unknown',cutoff:'2026-10-27T03:00:00Z'}
];let intakeChecks=0;
const dispatcher=new OrderRuleDispatcher({clock:()=>now,store:{
capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true},settings:()=>({enabled:false}),
expireIntakes(){intakeChecks++;},all(kind){assert.equal(kind,'batches');return structuredClone(batches);},
snapshot(){assert.fail('polling must not assemble a full rule snapshot');},finishSending(...args){finished.push(args);}
},mail:{exclusive:()=>assert.fail('paused dispatcher must not send')},providersReady:()=>true});
await dispatcher.tick();
assert.equal(intakeChecks,1);assert.equal(finished.length,1);assert.equal(finished[0][0],'expired');assert.equal(finished[0][1],'failed');
assert.deepEqual(finished[0][3],{outcome:'not_submitted',phase:'queue_expired',at:'2026-10-27T04:00:00.000Z'});
});
+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();const failedRefresh=page.waitForResponse(response=>response.url().includes('/api/order-rules?view=summary')&&response.status()===503);await page.getByRole('button',{name:'刷新业务首页',exact:true}).click();await failedRefresh;await page.getByText('刷新失败:暂时不可用',{exact:false}).waitFor();await page.waitForFunction(()=>{const button=[...document.querySelectorAll('[data-business-updates] button')].find(item=>item.textContent.includes('刷新业务首页'));return button&&!button.disabled;});assert.equal(await page.locator('[data-home-metric="pending"]').innerText(),'7');fail=false;const successfulRefresh=page.waitForResponse(response=>response.url().includes('/api/order-rules?view=summary')&&response.status()===200);await page.getByRole('button',{name:'刷新业务首页',exact:true}).click();await successfulRefresh;await page.locator('[data-business-updates]').waitFor({state:'hidden'});assert.equal(await page.locator('[data-home-metric="pending"]').innerText(),'7');});
+1 -1
View File
@@ -1,7 +1,7 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm');
const source=fs.readFileSync('web/app.js','utf8');
function fixture(){let resolve,requests=0,disposed=0,booted=0;const context={AbortController,AbortSignal,setTimeout:(fn,ms)=>{const timer=setTimeout(fn,ms);timer.unref();return timer;},clearTimeout,fetch:()=>{requests++;return new Promise(r=>resolve=r);},window:{PageLifecycle:{revision:1,dispose:async()=>{disposed++;},succeeded(){},failed(){}},BpmLogin:{dispose(){}}}};vm.createContext(context);vm.runInContext("let currentUser={username:'old'},viewGeneration=1;const pendingWrites=new Map();async function boot(){booted++;}",context);context.booted=0;vm.runInContext(source.slice(source.indexOf('async function api('),source.indexOf('async function verifyUncertainWrite(')),context);return {context,run:s=>vm.runInContext(s,context),resolve:r=>resolve(r),requests:()=>requests,disposed:()=>disposed};}
function fixture(){let resolve,requests=0,disposed=0,booted=0;const context={AbortController,AbortSignal,structuredClone,DOMException,setTimeout:(fn,ms)=>{const timer=setTimeout(fn,ms);timer.unref();return timer;},clearTimeout,fetch:()=>{requests++;return new Promise(r=>resolve=r);},window:{PageLifecycle:{revision:1,dispose:async()=>{disposed++;},succeeded(){},failed(){}},BpmLogin:{dispose(){}}}};vm.createContext(context);vm.runInContext("let currentUser={username:'old'},viewGeneration=1;async function boot(){booted++;}",context);context.booted=0;vm.runInContext(source.slice(source.indexOf('const pendingWrites='),source.indexOf('async function verifyUncertainWrite(')),context);return {context,run:s=>vm.runInContext(s,context),resolve:r=>resolve(r),requests:()=>requests,disposed:()=>disposed};}
for(const change of ['viewGeneration++;window.PageLifecycle.revision++;','currentUser={username:"new"};viewGeneration++;window.PageLifecycle.revision++;'])test('obsolete 401 has no auth effects after '+change,async()=>{const f=fixture(),request=f.run("api('/old')");f.run(change);f.resolve({ok:false,status:401,json:async()=>({error:'expired'})});await assert.rejects(request,/expired/);assert.equal(f.run('currentUser!==null'),true);assert.equal(f.disposed(),0);assert.equal(f.context.booted,0);});
test('owned session 401 still disposes expired session',async()=>{const f=fixture(),request=f.run("api('/current')");f.resolve({ok:false,status:401,json:async()=>({error:'expired'})});await assert.rejects(request,/expired/);assert.equal(f.run('currentUser'),null);assert.equal(f.disposed(),1);assert.equal(f.context.booted,1);});
test('identical writes from a newer session never join old pending work',async()=>{const f=fixture();f.run("api('/write',{a:1})");f.run('currentUser={username:"new"};viewGeneration++;');const current=f.run("api('/write',{a:1})");assert.equal(f.requests(),2);f.resolve({ok:true,json:async()=>({version:2})});await current;});
+48
View File
@@ -0,0 +1,48 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {orderDrivenUI}=require('../fixtures/order-driven-ui.cjs');
test('cold home omits optional pages, routes load dependencies on demand and reuse completed scripts',{timeout:120000},async t=>{
const {page}=await orderDrivenUI(t,'#overview'),errors=[];page.on('pageerror',e=>errors.push(e.message));
await page.route('**/api/mail',r=>r.fulfill({json:{channels:[],templates:[],receipts:[],sends:[]}}));
await page.route('**/api/assistant',r=>r.fulfill({json:{settings:{version:1,enabled:false,model:'fixture',runtimePath:'',apiBase:'',timeoutSeconds:90,dailyLimit:100,allowActions:false},conversations:[],skills:[],usage:{calls:0,limit:100}}}));
await page.route('**/api/assistant/providers',r=>r.fulfill({json:{version:1,providers:[],defaultSelection:null,catalog:{protocols:['openai-completions','openai-responses','anthropic-messages'],presets:[]}}}));
await page.route('**/api/assistant/context',r=>r.fulfill({json:{at:'2026-10-29T00:00:00Z',role:'admin',connections:[],runs:[],servers:[],archives:[],jobs:[],exceptions:[],configuration:[],business:{blockers:[]}}}));
await page.route('**/api/assistant/conversations?*',r=>r.fulfill({json:{items:[],total:0,page:1}}));
await page.route('**/api/assistant/operations*',r=>r.fulfill({json:{events:[]}}));
await page.route('**/api/storage',r=>r.fulfill({json:{servers:[],archives:[],settings:{version:1,enabled:false,defaultServerId:''}}}));
await page.route('**/api/health',r=>r.fulfill({json:{runtime:{uptimeSeconds:0,startedAt:'2026-10-28T00:00:00Z',autostart:{enabled:false},guard:{status:'unmanaged',events:[]}},groups:[]}}));
await page.locator('[data-business-home]').waitFor();const reads=[];
page.on('request',r=>{if(r.resourceType()==='script')reads.push(new URL(r.url()).pathname);});
await page.reload();await page.locator('[data-business-home]').waitFor();
for(const route of ['/assistant.js','/bpm.js','/mail.js','/storage.js','/order-rules.js'])assert.equal(reads.includes(route),false,route);
const screens=[['notification-orders','[data-arrival-list]'],['notification-batches','[data-arrival-list]'],['rule-fields','#fm-count'],['order-rules','#order-rules-panel'],['mail','#mail-add'],['assistant','#assistant-input'],['assistant-settings','#assistant-settings-form'],['storage','#storage-add'],['health','#health-refresh'],['records-pdf','[data-pdf-list]'],['records','[data-arrival-list]'],['bpm','[data-bpm-feedback]'],['account','#account-password-form'],['calendar','#day-form'],['exceptions','#exception-new'],['templates','#mail-templates'],['schedule','#schedule-form'],['audit','.audit-detail,.empty-state,.card']];
for(const [route,ready] of screens){await page.evaluate(hash=>location.hash=hash,route);try{await page.locator(ready).first().waitFor({state:'attached'});}catch(e){t.diagnostic(JSON.stringify({route,text:await page.locator('#content').innerText(),errors}));throw e;}assert.equal(await page.locator('[data-module-retry]').count(),0,route+' module load');}
const before=reads.filter(r=>r==='/assistant.js').length;
await page.evaluate(()=>location.hash='assistant');await page.locator('#assistant-input').waitFor();
assert.equal(reads.filter(r=>r==='/assistant.js').length,before);assert.deepEqual(errors,[]);
});
test('failed route scripts offer retry and an abandoned route cannot mount after a slow dependency',{timeout:60000},async t=>{
const {page}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();let fail=true;
await page.route('**/health.js?*',route=>fail?route.abort():route.continue());
await page.evaluate(()=>location.hash='health');await page.locator('[data-module-retry]').waitFor();fail=false;
await page.locator('[data-module-retry]').click();await page.locator('#health-refresh').waitFor();
let release;const held=new Promise(resolve=>release=resolve);await page.route('**/assistant.js?*',async route=>{await held;await route.continue();});
try{await page.evaluate(()=>location.hash='assistant');await page.waitForFunction(()=>document.querySelector('#view-title')?.textContent==='DSH 助手');await page.evaluate(()=>location.hash='overview');await page.locator('[data-business-home]').waitFor();}finally{release();}
await page.waitForTimeout(200);assert.equal(await page.locator('[data-business-home]').count(),1);assert.equal(await page.locator('#assistant-input').count(),0);
});
test('an unopened home can execute while a cold assistant script is stalled',{timeout:60000},async t=>{
const {page,base}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();
let release;const held=new Promise(resolve=>release=resolve);await page.route('**/assistant.js?*',async route=>{await held;await route.continue();});
try{await page.goto('about:blank');await page.goto(base+'/#assistant',{waitUntil:'domcontentloaded'});await page.waitForFunction(()=>document.querySelector('#view-title')?.textContent==='DSH 助手');await page.evaluate(()=>location.hash='overview');await page.locator('[data-business-home]').waitFor();}finally{release();}
await page.waitForTimeout(100);assert.equal(await page.locator('#assistant-input').count(),0);
});
test('a lazy script whose bytes differ from the document fingerprint cannot execute',{timeout:60000},async t=>{
const {page}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();let corrupt=true;
await page.route('**/health.js?*',async route=>{if(!corrupt)return route.continue();const response=await route.fetch();await route.fulfill({response,headers:{...response.headers(),'cache-control':'no-store'},body:(await response.text())+'\nwindow.staleModuleExecuted=true;'});});
await page.evaluate(()=>location.hash='health');await page.locator('[data-module-retry]').waitFor();assert.equal(await page.evaluate(()=>window.staleModuleExecuted),undefined);
corrupt=false;await page.locator('[data-module-retry]').click();await page.locator('#health-refresh').waitFor({state:'attached'});
});
+36
View File
@@ -0,0 +1,36 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm');
function fixture(){
const groups=JSON.parse(fs.readFileSync('web/modules/navigation/module-manifest.json','utf8')),urls=Object.fromEntries(Object.values(groups).flat().filter(file=>!file.startsWith('$')).map(file=>['/'+file,'/'+file+'?v='+'a'.repeat(64)]));
const appended=[],context=vm.createContext({btoa,document:{querySelector:()=>({content:JSON.stringify({groups,urls})}),head:{appendChild(script){if(script.tagName!=='script')return;appended.push(script.src.split('?')[0]);queueMicrotask(()=>script.onload());}},createElement(tagName){return {tagName,remove(){}};}},window:{}});
vm.runInContext(fs.readFileSync('web/modules/navigation/module-loader.js','utf8'),context);
return {context,appended};
}
test('route loader requests only the selected page group and deduplicates dependencies',async()=>{
const f=fixture();
await f.context.window.AppModules.load('overview');
const first=[...f.appended];
assert.ok(first.includes('/order-notifications.js'));
assert.ok(first.includes('/business-home.js'));
assert.equal(first.includes('/assistant.js'),false);
await f.context.window.AppModules.load('overview');
assert.deepEqual(f.appended,first);
});
test('route loader keeps shared modules before route modules and reports script failures',async()=>{
const f=fixture();await f.context.window.AppModules.load('assistant');
const modules=f.appended;
assert.ok(modules.indexOf('/assistant-operations.js')<modules.indexOf('/assistant.js'));
const bad=fixture();bad.context.document.head.appendChild=script=>{if(script.tagName==='script')queueMicrotask(()=>script.onerror(new Error('missing')));};
await assert.rejects(bad.context.window.AppModules.load('assistant'),/无法加载页面资源/);
});
test('failed modules can be retried without executing successful dependencies twice',async()=>{
const f=fixture();let fail=true;
f.context.document.head.appendChild=script=>{if(script.tagName!=='script')return;f.appended.push(script.src.split('?')[0]);queueMicrotask(()=>fail&&script.src.startsWith('/assistant.js')?script.onerror():script.onload());};
await assert.rejects(f.context.window.AppModules.load('assistant'),/无法加载页面资源/);fail=false;
await f.context.window.AppModules.load('assistant');
assert.equal(f.appended.filter(src=>src==='/assistant.js').length,2);assert.equal(f.appended.filter(src=>src==='/assistant-operations.js').length,1);
});
+14
View File
@@ -0,0 +1,14 @@
'use strict';
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, 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();});
test('cold authentication reads bootstrap once and an authenticated reload skips bootstrap',{timeout:60000},async t=>{const {page,browser,base}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();const context=await browser.newContext();try{const cold=await context.newPage(),bootstrap=[];cold.on('request',r=>{if(r.url().endsWith('/api/bootstrap/status'))bootstrap.push(r.url());});await cold.goto(base);await cold.locator('#login-form').waitFor();assert.equal(bootstrap.length,1);}finally{await context.close();}let bootstrap=0;page.on('request',r=>{if(r.url().endsWith('/api/bootstrap/status'))bootstrap++;});await page.reload();await page.locator('[data-business-home]').waitFor();assert.equal(bootstrap,0);});
test('field mapping directory starts while the independent connection catalog is still loading',{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 fieldRead=false;await page.route('**/api/workspace',async route=>{await held;await route.continue();});await page.route('**/api/order-rules/fields?view=scopes',route=>{fieldRead=true;return route.continue();});try{await page.evaluate(()=>location.hash='rule-fields');await page.waitForFunction(()=>document.querySelector('#view-title').textContent==='字段映射');await new Promise(r=>setTimeout(r,250));assert.equal(fieldRead,true);}finally{release();}await page.locator('#fm-count').waitFor();});
test('running assistant polling pauses hidden and resumes without clearing the next message draft',{timeout:60000},async t=>{const {page}=await orderDrivenUI(t,'#overview');await page.locator('[data-business-home]').waitFor();const conversation={id:'c1',title:'隔离会话',version:1,turns:[{id:'t1',status:'running',text:'只读检查',actions:[]}]};await page.route('**/api/assistant',r=>r.fulfill({json:{settings:{enabled:true,model:'fixture'},conversations:[conversation],usage:{calls:1,limit:30}}}));await page.route('**/api/assistant/conversations?*',r=>r.fulfill({json:{items:[conversation],total:1,page:1}}));await page.route('**/api/assistant/operations*',r=>r.fulfill({json:{events:[]}}));await page.route('**/api/assistant/conversations/c1',r=>r.fulfill({json:conversation}));await page.evaluate(()=>location.hash='assistant');await page.getByRole('button',{name:'停止回复',exact:true}).waitFor();await page.clock.install();await page.locator('#assistant-input').fill('保留下一条草稿');let reads=0;page.on('request',r=>{if(r.url().endsWith('/api/assistant/conversations/c1'))reads++;});await visibility(page,true);await page.clock.fastForward(10001);await new Promise(r=>setTimeout(r,100));assert.equal(reads,0);const response=page.waitForResponse(r=>r.url().endsWith('/api/assistant/conversations/c1'));await visibility(page,false);await response;assert.equal(reads,1);assert.equal(await page.locator('#assistant-input').inputValue(),'保留下一条草稿');});
@@ -0,0 +1,11 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm');
function apiFixture(){const requests=[],context=vm.createContext({document:{querySelector:()=>null},window:{PageLifecycle:{revision:1,succeeded(){},failed(){}}},AbortController,AbortSignal,DOMException,structuredClone,setTimeout,clearTimeout,fetch:(url,options)=>new Promise((resolve,reject)=>{const row={url,options,reply:(data)=>resolve({ok:true,status:200,json:async()=>data})};requests.push(row);options.signal.addEventListener('abort',()=>reject(new DOMException('Aborted','AbortError')),{once:true});})});vm.runInContext(fs.readFileSync('web/app.js','utf8').split('async function verifyUncertainWrite')[0],context);vm.runInContext("currentUser={id:'one'}",context);return {requests,run:code=>vm.runInContext(code,context),context};}
test('same-user in-flight reads share transport but retain independent abort and result objects',async()=>{const f=apiFixture();f.run('globalThis.a=new AbortController();globalThis.b=new AbortController()');const first=f.run("api('/test',undefined,{signal:a.signal})"),second=f.run("api('/test',undefined,{signal:b.signal})");const rejected=assert.rejects(first,{name:'AbortError'});f.run('a.abort()');await rejected;assert.equal(f.requests.length,1);assert.equal(f.requests[0].options.signal.aborted,false);f.requests[0].reply({rows:[1]});assert.deepEqual(await second,{rows:[1]});const third=f.run("api('/next')"),fourth=f.run("api('/next')");f.requests[1].reply({rows:[1]});const [x,y]=await Promise.all([third,fourth]);x.rows.push(2);assert.deepEqual(y,{rows:[1]});});
test('mutations and identity changes prevent joining an older read',async()=>{const f=apiFixture();const old=f.run("api('/test')"),write=f.run("api('/settings',{})");f.requests[1].reply({ok:true});await write;const next=f.run("api('/test')");assert.equal(f.requests.length,3);f.run("currentUser={id:'two'}");const other=f.run("api('/test')");assert.equal(f.requests.length,4);for(const row of f.requests)row.reply({ok:true});await Promise.all([old,next,other]);});
function pollFixture(){const listeners={},timers=new Map();let seq=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(){}},crypto,AbortController,DOMException,setTimeout:(fn)=>{timers.set(++seq,fn);return seq;},clearTimeout:id=>timers.delete(id)});vm.runInContext(fs.readFileSync('web/modules/navigation/lifecycle.js','utf8'),context);return {context,document,listeners,timers,run:code=>vm.runInContext(code,context),tick:async()=>{const rows=[...timers.values()];timers.clear();for(const fn of rows)fn();await Promise.resolve();}};}
test('background pollers pause hidden, resume once visible, serialize work and dispose',async()=>{const f=pollFixture();f.run('globalThis.calls=0;globalThis.finish=null;globalThis.poll=window.PageLifecycle.poll(()=>{calls++;return new Promise(resolve=>finish=resolve);},1000)');await f.tick();assert.equal(f.run('calls'),1);f.run('poll.run()');assert.equal(f.run('calls'),1);f.document.hidden=true;f.listeners.visibilitychange();await f.tick();assert.equal(f.run('calls'),1);f.document.hidden=false;f.listeners.visibilitychange();f.run('finish()');await new Promise(r=>setImmediate(r));await f.tick();assert.equal(f.run('calls'),2);f.run('poll.dispose();finish()');await new Promise(r=>setImmediate(r));assert.equal(f.timers.size,0);assert.equal(f.listeners.visibilitychange,undefined);});
test('manual poll refresh cancels an older request and waits for a fresh response',async()=>{const f=pollFixture();f.run("globalThis.calls=0;globalThis.poll=window.PageLifecycle.poll(signal=>{calls++;return new Promise((resolve,reject)=>signal.addEventListener('abort',()=>reject(new DOMException('Aborted','AbortError')),{once:true}));},1000)");await f.tick();assert.equal(f.run('calls'),1);const fresh=f.run('poll.refresh()');await new Promise(r=>setImmediate(r));assert.equal(f.run('calls'),2);f.run('poll.dispose()');await assert.rejects(fresh,{name:'AbortError'});});
test('a new navigation generation cannot join an older page read',async()=>{const f=apiFixture();const old=f.run("api('/test')");f.run('viewGeneration++;window.PageLifecycle.revision++');const fresh=f.run("api('/test')");try{assert.equal(f.requests.length,2);}finally{for(const row of f.requests)row.reply({ok:true});await Promise.all([old,fresh]);}});
+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);
});
+4 -4
View File
@@ -3,7 +3,7 @@ const {test}=require('node:test'),assert=require('node:assert/strict'),fs=requir
const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function fixture(t,hash='schedule'){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'closure-review-')),runtime=await startTestDashboard({stateDir:dir,mailHistory:true}),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(async()=>{await browser.close();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(6000);await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#'+hash);await login(page);return {page,runtime};}
test('a successful delayed save commits only submitted inputs and later edits remain dirty',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();let release,arrive;const arrived=new Promise(r=>arrive=r),gate=new Promise(r=>release=r);await page.route('**/api/settings',async route=>{if(route.request().method()==='GET')return route.continue();const response=await route.fetch();arrive();await gate;return route.fulfill({response});});await page.locator('#time-first').fill('09:11');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await arrived;await page.locator('#time-first').fill('09:12');release();await page.getByText('发送计划已保存。',{exact:true}).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),true);await page.getByRole('link',{name:'业务日历',exact:true}).first().click();await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();assert.equal(await page.locator('#time-first').inputValue(),'09:12');});
for(const destination of ['internal','route'])test('Save and Continue preserves currentTarget for rule settings: '+destination,{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await openRuleRoute(page,'notification-settings');await page.locator('#order-rule-settings').waitFor();const input=page.locator('#order-rule-settings [name=maxSize]');await input.fill('12');const posts=[];await page.route('**/api/order-rules/settings',async route=>{posts.push(route.request().postDataJSON());return route.continue();});if(destination==='internal')await openRuleRoute(page,'order-notifications');else await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();if(destination==='internal')await page.getByRole('heading',{name:'连续业务窗口',exact:true}).waitFor();else await page.locator('#schedule-form').waitFor();assert.equal(posts.length,1);assert.equal(posts[0].maxMessageBytes,12582912);});
for(const destination of ['internal','route'])test('Save and Continue preserves currentTarget for rule settings: '+destination,{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await openRuleRoute(page,'notification-settings');await page.locator('#order-rule-settings').waitFor();const input=page.locator('#order-rule-settings [name=maxSize]');await input.fill('12');const posts=[];await page.route('**/api/order-rules/settings',async route=>{posts.push(route.request().postDataJSON());return route.continue();});if(destination==='internal')await openRuleRoute(page,'order-notifications');else await page.getByRole('link',{name:'发送计划',exact:true}).first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();if(destination==='internal')await page.locator('[data-business-home]').waitFor();else await page.locator('#schedule-form').waitFor();assert.equal(posts.length,1);assert.equal(posts[0].maxMessageBytes,12582912);});
async function mailFixture(page){const drafts=['t1','t2'].map((id,i)=>({id,version:1,status:'pending',subject:'模板'+(i+1),scope:'',channelId:'mail1',sender:'fixture@example.test',attachmentCount:0,attachments:[],text:'正文'}));await page.route('**/api/mail',route=>route.fulfill({json:{channels:[],templates:drafts,receipts:[],sends:[]}}));await page.route('**/api/mail/templates/categories',route=>route.fulfill({json:{categories:[],bindings:[]}}));await page.route(/\/api\/mail\/templates\/t[12]$/,route=>route.fulfill({json:drafts.find(d=>route.request().url().endsWith('/'+d.id))}));await page.route('**/api/mail/templates/*/preview',route=>route.fulfill({contentType:'text/html',body:'<p>正文</p>'}));return drafts;}
test('switching a template immediately retires its old editable form while the next detail loads',{timeout:45000},async t=>{
@@ -24,17 +24,17 @@ test('rerendering rule saves lock editable fields until the saved response has r
test('invalid readback payload is rejected even when HTTP succeeds',{timeout:45000},async t=>{const {page}=await fixture(t);await page.locator('#schedule-form').waitFor();await page.route('**/api/settings',route=>route.request().method()==='POST'?route.abort('timedout'):route.fulfill({json:{schedule:'not a schedule'}}));await page.locator('#time-first').fill('10:03');await page.getByRole('button',{name:'保存发送计划',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#operation-uncertain')?.textContent.includes('查询失败'));assert.doesNotMatch(await page.locator('#operation-uncertain').innerText(),/已查询最新状态/);});
test('uncertain calendar write reads its workspace calendar rather than overview',{timeout:45000},async t=>{const {page}=await fixture(t,'calendar');await page.locator('#day-note').waitFor();let reads=0;await page.route('**/api/calendar',route=>route.abort('timedout'));await page.route('**/api/workspace',route=>{reads++;return route.fulfill({json:{calendar:{version:8,overrides:[]}}});});await page.locator('#day-note').fill('隔离测试日历安排');await page.getByRole('button',{name:'应用到此日期',exact:true}).click();await page.getByRole('button',{name:'保存日历',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#operation-uncertain')?.textContent.includes('配置版本 8'));assert.equal(reads,1);});
test('rule durable save survives refresh failure, retains version and permits Save and Continue',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await openRuleRoute(page,'order-rules');let failRead=false;const versions=[];await page.route('**/api/order-rules?view=summary',route=>failRead?route.fulfill({status:503,json:{error:'refresh unavailable'}}):route.continue());await page.route('**/api/order-rules/rules',async route=>{versions.push(route.request().postDataJSON().version);const response=await route.fetch();failRead=true;return route.fulfill({response});});await page.getByLabel('规则名称',{exact:true}).fill('首次持久保存');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText(/已保存.*刷新失败/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);await page.getByLabel('规则名称',{exact:true}).fill('再次持久保存');await page.locator('a[href="#system-settings"]').first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();assert.deepEqual(versions,[1,2]);});
test('rule durable save retains returned version and permits Save and Continue without a refresh',{timeout:45000},async t=>{const {page}=await fixture(t,'order-rules');await openRuleRoute(page,'order-rules');let failRead=false;const versions=[];await page.route('**/api/order-rules?view=summary',route=>failRead?route.fulfill({status:503,json:{error:'refresh unavailable'}}):route.continue());await page.route('**/api/order-rules/rules',async route=>{versions.push(route.request().postDataJSON().version);const response=await route.fetch();failRead=true;return route.fulfill({response});});await page.getByLabel('规则名称',{exact:true}).fill('首次持久保存');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);await page.getByLabel('规则名称',{exact:true}).fill('再次持久保存');await page.locator('a[href="#system-settings"]').first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.getByRole('heading',{name:'BPM 连接',exact:true}).first().waitFor();assert.deepEqual(versions,[1,2]);});
test('field mapping save retains returned version after followup GET fails',{timeout:45000},async t=>{
const {page}=await fixture(t,'order-rules');let saved=false;const versions=[];
await page.route('**/api/order-rules/fields*',route=>saved?route.fulfill({status:503,json:{error:'fields unavailable'}}):route.fulfill({json:{samples:[{id:'s1',processName:'测试流程',processVersion:'1',sample:{title:'订单号:A1'},fields:[{path:'order',label:'订单号',value:'A1'},{path:'brief',label:'摘要',value:'摘要'}]}],adapters:[]}}));
await page.route('**/api/order-rules/field-mappings/draft',route=>{const input=route.request().postDataJSON();versions.push(input.version);saved=true;return route.fulfill({json:{...input,id:'a1',version:versions.length,sources:{...input.sources,receivedAt:{type:'metadata',key:'receivedAt'}}}});});
await openRuleRoute(page,'rule-fields');await page.locator('#fm-manual').evaluate(e=>e.open=true);await page.locator('#fm-orderNo').selectOption('order');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText(/已保存.*刷新失败/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);
await page.getByText(/可选业务信息 ·/).evaluate(e=>e.parentElement.open=true);await page.locator('#fm-customer').selectOption('brief');await page.locator('a[href="#overview"]').first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.getByRole('heading',{name:'连续业务窗口',exact:true}).waitFor();assert.deepEqual(versions,[0,1]);
await page.getByText(/可选业务信息 ·/).evaluate(e=>e.parentElement.open=true);await page.locator('#fm-customer').selectOption('brief');await page.locator('a[href="#overview"]').first().click();await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.locator('[data-business-home]').waitFor();assert.deepEqual(versions,[0,1]);
});
test('template usage read failure never enables an alternate binding writer',{timeout:45000},async t=>{const {page}=await fixture(t);await mailFixture(page);await page.route('**/api/order-rules?view=summary',route=>route.fulfill({status:503,json:{error:'使用情况读取失败'}}));await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.locator('#content').getByText('使用情况读取失败',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'保存关联'}).count(),0);assert.equal(await page.getByRole('button',{name:'预览并确认',exact:true}).count(),2);await page.locator('[data-template=t1]').click();await page.getByLabel('发信标题',{exact:true}).waitFor();assert.equal(await page.getByLabel('发信标题',{exact:true}).inputValue(),'模板1');});
test('template usage read failure never enables an alternate binding writer',{timeout:45000},async t=>{const {page}=await fixture(t);await mailFixture(page);await page.route('**/api/order-rules/catalog',route=>route.fulfill({status:503,json:{error:'使用情况读取失败'}}));await page.getByRole('link',{name:'邮件模板',exact:true}).click();await page.locator('#content').getByText('使用情况读取失败',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'保存关联'}).count(),0);assert.equal(await page.getByRole('button',{name:'预览并确认',exact:true}).count(),2);await page.locator('[data-template=t1]').click();await page.getByLabel('发信标题',{exact:true}).waitFor();assert.equal(await page.getByLabel('发信标题',{exact:true}).inputValue(),'模板1');});
test('unknown and conflicted task details cannot offer ordinary retry',{timeout:45000},async t=>{const {page,runtime}=await fixture(t,'order-rules');runtime.orderRules.put('execution-tasks',{id:'unknown',connectionId:'c1',status:'unknown',version:1,row:{orderNo:'UNKNOWN'}});await openRuleRoute(page,'notification-execution');await page.getByRole('button',{name:'查看详情'}).click();await page.getByRole('heading',{name:'处理进度'}).waitFor();assert.equal(await page.getByRole('button',{name:'重试失败任务',exact:true}).count(),0);});