perf: optimize full interface loading and refresh paths

This commit is contained in:
abaishu0730 committed 2026-10-28 09:24:04 +08:00
1 parent 649a0df832
commit f317314a3c
57 files changed
+791 -136

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);
+39
View File
@@ -0,0 +1,39 @@
'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);
});
@@ -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
@@ -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;});
+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, 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('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]);}});
+3 -3
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=>{
@@ -31,10 +31,10 @@ test('field mapping save retains returned version after followup GET fails',{tim
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);});
+6 -2
View File
@@ -48,10 +48,11 @@ async function fixture(t,{user={username:'alice',role:'operator'},connections,ac
});
await page.goto(base);
await page.addStyleTag({path:path.join(__dirname,'../../web/app.css')});
await page.addScriptTag({path:path.join(__dirname,'../../web/modules/navigation/lifecycle.js')});
if(fs.existsSync(source))await page.addScriptTag({path:source});
assert.equal(await page.evaluate(()=>typeof window.BpmLogin?.mount),'function','BPM page exposes a working mount function');
await page.evaluate(async user=>{
const api=async(route,body)=>{const r=await fetch('/api'+route,{method:body===undefined?'GET':'POST',headers:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});return r.json();};
const api=async(route,body,{signal}={})=>{const r=await fetch('/api'+route,{signal,method:body===undefined?'GET':'POST',headers:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});return r.json();};
await window.BpmLogin.mount(document.querySelector('#root'),{api,esc:v=>String(v??'').replaceAll('<','&lt;'),formatDate:v=>v||'—',notify:()=>{},user,isActive:()=>true});
},user);
return {page,calls,releaseOpen,releaseInput,releaseFrame,releaseSave,releaseAccount,releaseFill,releaseAccountSave,maxFrames:()=>maxFrames};
@@ -286,8 +287,9 @@ for(const pendingAction of ['open','save'])test(`document unload sends authentic
const appSource=fs.readFileSync(path.join(__dirname,'../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
const fixtureServer=http.createServer(async(req,res)=>{
const requestPath=new URL(req.url,'http://localhost').pathname;
if(requestPath==='/lifecycle.js'){res.setHeader('Content-Type','application/javascript; charset=utf-8');return res.end(fs.readFileSync(path.join(__dirname,'../../web/modules/navigation/lifecycle.js')));}
if(requestPath==='/bpm.js'||requestPath==='/app.js'){res.setHeader('Content-Type','application/javascript; charset=utf-8');return res.end(requestPath==='/bpm.js'?fs.readFileSync(source):appSource);}
if(!requestPath.startsWith('/api/')){res.setHeader('Content-Type','text/html; charset=utf-8');return res.end('<div id="app"></div><div id="root"></div><script src="/bpm.js"></script><script src="/app.js"></script>');}
if(!requestPath.startsWith('/api/')){res.setHeader('Content-Type','text/html; charset=utf-8');return res.end('<div id="app"></div><div id="root"></div><script src="/lifecycle.js"></script><script src="/bpm.js"></script><script src="/app.js"></script>');}
let body='';for await(const chunk of req)body+=chunk;
calls.push({path:requestPath,body,cookie:req.headers.cookie,origin:req.headers.origin});
res.setHeader('Content-Type','application/json');
@@ -364,3 +366,5 @@ test('UI renders backend conclusions without reinterpreting raw connection flags
assert.equal(await f.page.locator('[data-sync-status] .bpm-status-yellow').count(),1);
await f.page.getByText('后端已核实会话',{exact:true}).waitFor();
});
test('remote login frames pause hidden and resume a single frame without replacing the session',async t=>{const f=await fixture(t);await f.page.getByRole('button',{name:'远程登录',exact:true}).click();await f.page.locator('[data-bpm-frame]').waitFor();await f.page.clock.install();const frames=()=>f.calls.filter(c=>c.path.endsWith('/frame')).length,before=frames();await f.page.evaluate(()=>{Object.defineProperty(document,'hidden',{value:true,configurable:true});document.dispatchEvent(new Event('visibilitychange'));});await f.page.clock.fastForward(10001);await delay(100);assert.equal(frames(),before);const response=f.page.waitForResponse(r=>r.url().endsWith('/login/frame'));await f.page.evaluate(()=>{Object.defineProperty(document,'hidden',{value:false,configurable:true});document.dispatchEvent(new Event('visibilitychange'));});await response;assert.equal(frames(),before+1);assert.equal(f.calls.filter(c=>c.path.endsWith('/open')).length,1);assert.equal(f.calls.filter(c=>c.path.endsWith('/close')).length,0);});
+1 -1
View File
@@ -18,5 +18,5 @@ async function startTestDashboard({stateDir,mailHistory=false,executionFactory})
await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(0,'127.0.0.1',resolve);});
return {server,store,workspace,orderRules,mail,orderExecution,async close(){await orderExecution?.stop();await mail?.stop();server.closeAllConnections();await new Promise(r=>server.close(r));workspace.close();orderRules.close();mailStore?.close();}};
}
async function login(page){await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();}
async function login(page){await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await Promise.all([page.waitForResponse(response=>response.url().endsWith('/api/login')&&response.request().method()==='POST'),page.getByRole('button',{name:'登录',exact:true}).click()]);await page.locator('#logout').waitFor();}
module.exports={startTestDashboard,login};
+24
View File
@@ -0,0 +1,24 @@
'use strict';
const crypto=require('node:crypto');
const {DatabaseSync}=require('node:sqlite');
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
const {BpmVault}=require('../../src/platform/security/vault.cjs');
function fixture(n,{status='pending',huizhou=false}={}){
const db=new DatabaseSync(':memory:');db.exec('CREATE TABLE records(kind TEXT,id TEXT,payload BLOB,PRIMARY KEY(kind,id))');
const vault=Object.assign(Object.create(BpmVault.prototype),{key:crypto.randomBytes(32)}),counts={all:{},get:{},decode:0};let now=new Date('2026-10-26T01:00:00Z');
const store=Object.assign(Object.create(RuleStore.prototype),{db,vault,clock:()=>new Date(now),schedule:()=>({times:['11:00','17:00'],weekends:false}),calendar:()=>[],capabilities:{}});
store.put('settings',{id:'main',version:1,enabled:false,processingEnabled:false,channelId:'',maxMessageBytes:20971520});
for(const draft of require('../../src/modules/order-rules/catalog.cjs').seedRules())store.put('rules',{id:draft.id,draft,published:null});
const rule={id:'bs-change',categoryId:'bs-change',name:'Synthetic',version:1,processNames:['Synthetic'],nodeNames:['Node'],scopes:[{processName:'Synthetic',nodeName:'Node'}],huizhouEnabled:huizhou,to:['fixture@example.invalid']};
for(let i=0;i<n;i++){
const row={connectionId:'a',source:'todo',portalSource:'v4',instanceId:String(i),taskId:String(i),revision:'1',processName:'Synthetic',processVersion:'1',nodeName:'Node',receivedAt:'2026-10-26T00:30:00Z',orderNo:String(i),title:'Synthetic '+i};
store.put('orders',{id:'o'+i,categoryId:rule.categoryId,status,sample:row,event:row,ruleSnapshot:rule,createdAt:row.receivedAt,notifications:huizhou?{huizhou:{status:'pending',orderNos:['H'+i],issues:[]}}:undefined});
store.put('execution-tasks',{id:'t'+i,orderId:'o'+i,connectionId:'a',status,step:'complete',categoryIds:[rule.categoryId],row,createdAt:row.receivedAt});
}
const all=store.all,get=store.get,decode=vault.decode;
store.all=function(kind){counts.all[kind]=(counts.all[kind]||0)+1;return all.call(this,kind);};
store.get=function(kind,id){counts.get[kind]=(counts.get[kind]||0)+1;return get.call(this,kind,id);};
vault.decode=function(...args){counts.decode++;return decode.apply(this,args);};
return {store,counts,context:{orderRules:store,workspace:{recordSources:()=>[{id:'a',owner:'alice'}],businessIssue:()=>null}},actor:{username:'alice',role:'operator'},reset(){counts.all={};counts.get={};counts.decode=0;},setNow(value){now=new Date(value);},close(){db.close();vault.key.fill(0);}};
}
module.exports={fixture};
+1 -1
View File
@@ -2,5 +2,5 @@
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{WorkspaceStore}=require('../../src/modules/workspace/store.cjs'),{BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs'),{BpmScanner}=require('../../src/modules/bpm/scanner.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function setup(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'record-nav-')),store=new Store(path.join(dir,'dashboard')),workspace=new WorkspaceStore(path.join(dir,'workspace')),scan=new BpmScanStore(path.join(dir,'scan')),password='Record-nav-test-123',actor={username:'admin',role:'admin'};store.bootstrap('admin',password);for(const role of ['viewer','operator'])store.addUser({username:role,password,role},'admin');const connection=workspace.createConnection({name:'隔离测试来源',owner:'admin'},actor,store.users());scan.saveConfig({enabled:false,intervalMinutes:9});scan.complete(scan.begin(connection.id,'admin'),connection.id,Array.from({length:105},(_,i)=>({taskId:String(i).padStart(3,'0'),serialNum:'TEST-'+String(i).padStart(3,'0'),source:'portal-v4',processName:'海外运营订单评审',activityName:'通知节点',subject:'订单样例 '+String(i).padStart(3,'0'),arrivalDay:'2026-10-20',arrivedAt:'2026-10-20T01:00:00Z'})),connection);for(let i=0;i<105;i++)store.recordJob({jobId:'job-'+String(i).padStart(3,'0'),status:'error',metadata:{order:'PDF-'+String(i).padStart(3,'0')},error:'隔离导出失败'});const scanner=new BpmScanner({store:scan,workspace,manager:{scanArrivals:async()=>[]},settings:()=>store.settings()}),server=createDashboard({store,workspace,scanner,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));const browser=await loadPlaywright().chromium.launch(browserOptions()),base='http://127.0.0.1:'+server.address().port;
t.after(async()=>{await browser.close();await scanner.stop();server.closeAllConnections();await new Promise(r=>server.close(r));scan.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});return {store,workspace,scan,connection,browser,base,password,async page(route='#records',username='admin',clock=false){const page=await browser.newPage({viewport:{width:1280,height:900}});if(clock)await page.clock.install();await page.goto(base+'/'+route);await page.locator('#username').fill(username);await page.locator('#password').fill(password);await page.locator('#login-form button').click();return page;}};}
t.after(async()=>{await browser.close();await scanner.stop();server.closeAllConnections();await new Promise(r=>server.close(r));scan.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});return {store,workspace,scan,connection,browser,base,password,async page(route='#records',username='admin',clock=false){const page=await browser.newPage({viewport:{width:1280,height:900}});if(clock)await page.clock.install();await page.goto(base+'/'+route);await page.locator('#username').fill(username);await page.locator('#password').fill(password);await Promise.all([page.waitForResponse(response=>response.url().endsWith('/api/login')&&response.request().method()==='POST'),page.locator('#login-form button').click()]);await page.locator('#logout').waitFor();return page;}};}
module.exports={setup};
+1 -1
View File
@@ -6,7 +6,7 @@ test('history UI saves IMAP-only credentials locally, explicitly queries sent ma
t.after(async()=>{await browser?.close();await runtime.close();fs.rmSync(dir,{recursive:true,force:true});});
let connects=0;
const raw=Buffer.from('From: sender@example.test\r\nTo: orders@example.test\r\nSubject: Test notice\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n<img src="https://tracker.example.test/pixel"> Huizhou evidence');
runtime.mail.imapFactory=()=>({mailbox:{uidValidity:1n},on(){},async connect(){connects++;},async list(){return [{path:'Sent',specialUse:'\\Sent'}];},async getMailboxLock(_path,opts){assert.equal(opts.readOnly,true);return {release(){}};},async search(){return [1];},async fetchOne(uid,q){return q.source?{source:raw}:{uid,size:raw.length,envelope:{subject:'Test notice'}};},async logout(){},close(){}});
runtime.mail.imapFactory=()=>({mailbox:{uidValidity:1n},on(){},async connect(){connects++;},async list(){return [{path:'Sent',specialUse:'\\Sent'}];},async getMailboxLock(_path,opts){assert.equal(opts.readOnly,true);return {release(){}};},async search(){return [1];},async *fetch(){yield {uid:1,size:raw.length,envelope:{subject:'Test notice'}};},async fetchOne(uid,q){return q.source?{source:raw}:{uid,size:raw.length,envelope:{subject:'Test notice'}};},async logout(){},close(){}});
browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage();const requests=[];page.on('request',r=>requests.push(r.url()));
await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#mail');await login(page);await page.getByRole('button',{name:'只读查阅已发送邮件',exact:true}).click();
await page.getByRole('button',{name:'添加只读邮箱',exact:true}).click({timeout:5000});
+29
View File
@@ -3,13 +3,42 @@ const {test}=require('node:test');const assert=require('node:assert/strict');
const {MailService}=require('../../src/modules/mail/service.cjs');
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {MailStore}=require('../../src/modules/mail/store.cjs');
const {readHistory}=require('../../src/modules/mail/history.cjs');
const raw=Buffer.from('From: sender@example.test\r\nTo: orders@example.test\r\nCc: factory@example.test\r\nSubject: Order notice\r\nDate: Sun, 18 Oct 2026 10:00:00 +0800\r\nMessage-ID: <notice@example.test>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nOrder body');
function fixture(){
const calls=[],store={channelSecret:()=>({version:1,imap:{}}),guard(){}};
const client={mailbox:{uidValidity:9n},on(){},async connect(){},async logout(){},close(){},async list(){return [{path:'Sent',specialUse:'\\Sent',flags:new Set()},{path:'INBOX',flags:new Set()}];},async getMailboxLock(folder,options){calls.push({folder,...options});return {release(){}};},async search(query,options){calls.push({query,...options});return [1,2,3];},async fetchOne(uid,query,options){calls.push({uid,query,...options});return query.source?{source:raw}:{uid,size:raw.length,envelope:{subject:'Order notice',date:new Date('2026-10-18T02:00:00Z'),to:[{address:'orders@example.test'}]}};}};
client.fetch=async function*(range,query,options){for(const uid of range.split(',').map(Number))yield await client.fetchOne(uid,query,options);};
const service=new MailService({store,imapFactory:()=>client,smtpFactory:()=>{throw Error('SMTP must not be used');}});
return {service,calls,client};
}
test('history batches bounded UID envelopes, keeps descending order and releases its read lock',async()=>{
let locked=false,released=0,batches=0;
const client={mailbox:{uidValidity:42n},list:async()=>[{path:'Sent',specialUse:'\\Sent'}],
async getMailboxLock(folder,options){assert.equal(folder,'Sent');assert.equal(options.readOnly,true);locked=true;return {release(){locked=false;released++;}};},
async search(query,options){assert.equal(locked,true);assert.equal(options.uid,true);return [3,8,5,10,2];},
fetchOne(){assert.fail('search must not fetch each message separately');},
async *fetch(range,query,options){batches++;assert.equal(locked,true);assert.equal(range,'10,8,5');assert.deepEqual(query,{uid:true,envelope:true,size:true});assert.deepEqual(options,{uid:true});
// An expunged UID is absent; sequence order need not equal the requested order.
yield {uid:5,size:100,envelope:{subject:'Five'}};yield {uid:10,envelope:{subject:'Ten'}};
yield {uid:10,size:200};yield {uid:99,size:1,envelope:{subject:'Unrequested'}};yield {seq:1,flags:new Set()};
}
};
const result=await readHistory(client,{action:'search',folder:'Sent',since:'2026-10-01',before:'2026-10-02',limit:3});
assert.deepEqual(result.messages.map(item=>[item.uid,item.subject,item.size]),[[10,'Ten',200],[5,'Five',100]]);assert.equal(result.uidValidity,'42');assert.equal(result.truncated,true);assert.equal(batches,1);assert.equal(released,1);assert.equal(locked,false);
});
test('empty history search never FETCHes and an interrupted batch always releases its lock',async()=>{
let released=0;
const client={mailbox:{uidValidity:9n},list:async()=>[{path:'Sent',specialUse:'\\Sent'}],getMailboxLock:async()=>({release(){released++;}}),search:async()=>[],
fetchOne:()=>assert.fail('no per-message fetch'),async *fetch(){assert.fail('empty results must not become a wildcard fetch');}
};
const input={action:'search',folder:'Sent',since:'2026-10-01',before:'2026-10-02'};
assert.deepEqual((await readHistory(client,input)).messages,[]);assert.equal(released,1);
client.search=async()=>[4];client.fetch=async function*(){throw Error('batch interrupted');};
await assert.rejects(readHistory(client,input),/batch interrupted/);assert.equal(released,2);
});
test('an IMAP-only history account stores no SMTP credential and rejects all sending or template polling',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'history-account-')),store=new MailStore(dir);
const service=new MailService({store,smtpFactory:()=>{throw Error('SMTP should be unreachable');}});
+1 -1
View File
@@ -102,7 +102,7 @@ function dispatchFixture(t,{ready=true,capabilities=true,enabled=true,verify,sen
const record={prepared:0,begun:0,smtp:0,locked:0,status:'prepared',messages:[],sent:[]};
const config={version:1,enabled,channelId:'channel1'};
const caps={liveTodo:capabilities,pdfExport:capabilities,automaticArchive:capabilities};
const store={discoveryBlockers:()=>[],batchIncomplete:()=>false,settings:()=>({...config}),snapshot:()=>({capabilities:{...caps},batches:[structuredClone({...batch,status:record.status})]}),prepare:(date,actor,window)=>{record.prepared++;assert.equal(date,dispatchCutoff);assert.equal(actor,'系统调度');assert.equal(window.start,'2026-10-19T09:00:00.000Z');assert.equal(window.end,dispatchCutoff);assert.equal(window.startInclusive,true);assert.equal(window.endInclusive,false);return [batch];},beginSending:id=>{assert.equal(id,'batch1');record.begun++;record.status='sending';},finishSending:(id,status,message)=>{assert.equal(id,'batch1');record.status=status;record.messages.push(message);}};
const store={discoveryBlockers:()=>[],batchIncomplete:()=>false,settings:()=>({...config}),capabilities:caps,all:kind=>kind==='batches'?[structuredClone({...batch,status:record.status})]:[],prepare:(date,actor,window)=>{record.prepared++;assert.equal(date,dispatchCutoff);assert.equal(actor,'系统调度');assert.equal(window.start,'2026-10-19T09:00:00.000Z');assert.equal(window.end,dispatchCutoff);assert.equal(window.startInclusive,true);assert.equal(window.endInclusive,false);return [batch];},beginSending:id=>{assert.equal(id,'batch1');record.begun++;record.status='sending';},finishSending:(id,status,message)=>{assert.equal(id,'batch1');record.status=status;record.messages.push(message);}};
const mail={exclusive:async(id,fn)=>{assert.equal(id,'channel1');record.locked++;return fn();},store:{channelSecret:id=>({id,version:2,email:'sender@example.com',name:'通知',smtp:{host:'unused.invalid'}}),guard:(id,version)=>{assert.equal(id,'channel1');assert.equal(version,2);}},smtpFactory:()=>{record.smtp++;return {verify:async()=>{if(verify)await verify({batch,config,caps,file});},sendMail:async message=>{record.sent.push(message);if(send)return send(message);return result||{accepted:['2639266652@qq.com'],rejected:[]};},close:()=>{}};}};
const schedule={times:['09:00','17:00'],timezone:'Asia/Shanghai',weekends:false,mode:'product_line',missed:'next_window'};
let now=new Date('2026-10-20T00:59:00.000Z');
+13
View File
@@ -88,6 +88,19 @@ test('status reads only effective settings and in-memory capabilities',async t=>
assert.deepEqual(await response.json(),{settings:{enabled:false},capabilities:{liveTodo:true,pdfExport:false,automaticArchive:false}});
});
test('catalog and notification settings avoid history and unrelated configuration resources',async t=>{
const rules=memoryRules(t);poisonHistory(rules);
for(const kind of ['field-adapters','scope-catalog','scope-process-catalog'])rules.db.prepare('INSERT OR REPLACE INTO records VALUES(?,?,?)').run(kind,'corrupt',Buffer.from('not encrypted'));
const f=await dashboard(t,{rules});
const catalogResponse=await f.request('/api/order-rules/catalog');assert.equal(catalogResponse.status,200);
const catalog=await catalogResponse.json();assert.equal(catalog.rules.length,15);assert.equal(catalog.templateUsage.length,15);
assert.deepEqual(Object.keys(catalog.rules[0]).sort(),['categoryId','name']);assert.equal(catalog.templateUsage[0].status,'draft');
assert.doesNotMatch(JSON.stringify(catalog),/"orders":|"fields":|"adapters":|"draft":/);
const settingsResponse=await f.request('/api/order-rules/notification-settings');assert.equal(settingsResponse.status,200);
assert.deepEqual(await settingsResponse.json(),{settings:rules.settings(),restrictedTest:null});
for(const route of ['/api/order-rules/catalog','/api/order-rules/notification-settings'])assert.equal((await f.request(route,{role:'anonymous'})).status,401);
});
test('rule write receipts retain complete editor versions without historic reads or relaxing stale-version validation',async t=>{
const rules=memoryRules(t),{captured}=activateReferenceMapping(rules,'bs-change',{connectionId:'own',instanceId:'i',taskId:'t',revision:'1'});
const draft=rules.saveRule({...rules.get('rules','bs-change').draft,to:['admin@example.test'],attachPdf:false,archiveDirectory:'\\\\server\\orders',filenameDate:'appDate'},'admin');rules.capturedPreview(captured.id);
@@ -6,7 +6,7 @@ const at='2026-10-27T03:30:00.000Z';
function fixture({verifyError,sendError,result,channelId='mail',expired=false}={}){
const batch={id:'batch',status:'prepared',cutoff:expired?'2026-10-27T02:00:00.000Z':at,channelId,to:['2639266652@qq.com'],cc:[],attachments:[],orderIds:['order'],ruleSnapshot:{}};
const completions=[];let submissions=0,begun=0;
const store={get:()=>null,now:()=>at,settings:()=>({enabled:true,channelId:'mail'}),snapshot:()=>({batches:[batch],capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),discoveryBlockers:()=>[],batchIncomplete:()=>false,beginSending:()=>{begun++;},finishSending:(...args)=>completions.push(args)};
const store={get:()=>null,now:()=>at,settings:()=>({enabled:true,channelId:'mail'}),all:kind=>kind==='batches'?[structuredClone(batch)]:[],capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true},discoveryBlockers:()=>[],batchIncomplete:()=>false,beginSending:()=>{begun++;},finishSending:(...args)=>completions.push(args)};
const mail={store:{channelSecret:()=>({id:'mail',version:1,email:'sender@example.com',smtp:{}}),guard:()=>{}},smtpFactory:()=>({verify:async()=>{if(verifyError)throw verifyError;},sendMail:async()=>{submissions++;if(sendError)throw sendError;return result||{accepted:['2639266652@qq.com'],rejected:[]};},close:()=>{}})};
const dispatcher=new OrderRuleDispatcher({store,mail,settings:()=>({}),clock:()=>new Date(at),providersReady:()=>true});
return {dispatcher,batch,store,completions,counts:()=>({submissions,begun})};
@@ -19,7 +19,7 @@ test('authorized users can explicitly revalidate only the original departed task
});
test('test settings and rule editor name uncovered flows even when all categories are ready',{timeout:90000},async t=>{
const {page}=await orderDrivenUI(t,'#notification-orders'),name='零售国内返工订单更改评审<待适配>';
await page.route('**/api/order-rules?view=summary',async route=>{const response=await route.fetch(),data=await response.json();data.restrictedTest={id:'coverage-test',version:1,enabled:true,ruleCount:15,readyCount:15,recipient:'2639266652@qq.com',archiveRoot:'C:\\isolated',since:'2026-10-26T00:00:00Z',uncovered:[{categoryId:'domestic-change',processName:name}]};await route.fulfill({json:data});});
await page.route(/\/api\/order-rules\/(notification-settings|configuration)$/,async route=>{const response=await route.fetch(),data=await response.json();data.restrictedTest={id:'coverage-test',version:1,enabled:true,ruleCount:15,readyCount:15,recipient:'2639266652@qq.com',archiveRoot:'C:\\isolated',since:'2026-10-26T00:00:00Z',uncovered:[{categoryId:'domestic-change',processName:name}]};await route.fulfill({json:data});});
for(const hash of ['notification-settings','order-rules']){await page.goto(new URL('/#'+hash,page.url()).href);await page.getByText(name,{exact:true}).waitFor();assert.equal(await page.locator('待适配').count(),0);assert.match(await page.locator('#content').innerText(),/domestic-change/);}
});
test('failure modal shows field sources and actionable diagnosis without offering an unsafe immediate retry',{timeout:90000},async t=>{
@@ -0,0 +1,68 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {fixture}=require('../fixtures/query-performance.cjs');
const query=require('../../src/modules/order-rules/query.cjs');
for(const operation of ['queryOrders','queryBatches','summary'])test(operation+' decrypts each task set once per read, including window checks',t=>{
const f=fixture(40);t.after(()=>f.close());
const result=operation==='summary'?query.summary(f.context,f.actor):query[operation](f.context,{},f.actor);
if(operation==='queryOrders'){assert.equal(result.total,40);assert.equal(result.items.length,25);}
if(operation==='queryBatches'){assert.equal(result.total,1);assert.equal(result.items[0].orderCount,40);}
if(operation==='summary'){assert.equal(result.counts.orders,40);assert.equal(result.home.pendingOrders,40);}
assert.ok((f.counts.all['execution-tasks']||0)<=1,JSON.stringify(f.counts));
assert.ok((f.counts.all.orders||0)<=1,JSON.stringify(f.counts));
assert.ok(f.counts.decode<200,JSON.stringify(f.counts));
});
test('completed modes perform no intake eligibility reads',t=>{
const f=fixture(40,{status:'sent'});t.after(()=>f.close());
const groups=require('../../src/modules/order-rules/collecting-batches.cjs').list(f.store);assert.deepEqual(groups,[]);
assert.equal(f.counts.all['execution-tasks']||0,0);
});
test('a frozen normal category excludes eligibility while a pending Hui mode remains independent',t=>{
const f=fixture(1,{status:'sent',huizhou:true});t.after(()=>f.close());
f.store.put('batches',{id:'frozen',categoryId:'bs-change',status:'unknown',cutoff:'2026-10-26T03:00:00.000Z',orderIds:['o0']});
const collecting=require('../../src/modules/order-rules/collecting-batches.cjs');
assert.deepEqual(collecting.list(f.store).map(b=>[b.notificationMode,b.orderIds]),[['huizhou',['o0']]]);
const order=f.store.get('orders','o0');order.status='pending';order.notifications.huizhou.status='unknown';f.store.put('orders',order);f.reset();
assert.deepEqual(collecting.list(f.store),[]);assert.equal(f.counts.all['execution-tasks']||0,0);
});
test('queries see writes even when the connection-local change counter is unchanged',t=>{
const f=fixture(1);t.after(()=>f.close());f.store.queryRevision=()=>1;
assert.equal(query.queryOrders(f.context,{},f.actor).items[0].status,'pending');
const order=f.store.get('orders','o0');order.status='sent';f.store.put('orders',order);
assert.equal(query.queryOrders(f.context,{},f.actor).items[0].status,'sent');
});
test('a later read rechecks window time and returned objects cannot change durable notices',t=>{
const f=fixture(1,{huizhou:true});t.after(()=>f.close());
const first=query.queryOrders(f.context,{},f.actor);assert.equal(first.items[0].collectingBatches.length,2);
first.items[0].notifications.huizhou.status='sent';
assert.equal(f.store.get('orders','o0').notifications.huizhou.status,'pending');
f.setNow('2026-10-26T04:00:00Z');assert.deepEqual(query.queryOrders(f.context,{},f.actor).items[0].collectingBatches,[]);
});
test('identity candidates scale with matching tasks while legacy portal overlap remains ambiguous',()=>{
const identity=require('../../src/modules/order-rules/task-identity.cjs'),{readStore}=require('../../src/modules/order-rules/read-context.cjs');let visits=0;
const tasks=Array.from({length:100},(_,i)=>({id:'t'+i,row:{get source(){visits++;return 'todo';},taskId:String(i),portalSource:'v4'}}));
const store=readStore({all:()=>tasks,get:()=>null});
for(let i=0;i<100;i++)assert.equal(identity.lookup(store,'execution-tasks',{source:'todo',taskId:String(i),portalSource:'v4'}).id,'t'+i);
assert.ok(visits<=400,'identity lookup revisited '+visits+' task sources');
const legacy=readStore({all:()=>[{id:'native',row:{source:'todo',taskId:'1',portalSource:'v4'}},{id:'legacy',row:{source:'todo',taskId:'1'}}],get:()=>null});
assert.throws(()=>identity.lookup(legacy,'execution-tasks',{source:'todo',taskId:'1',portalSource:'v4'}),e=>e.status===409);
assert.deepEqual(identity.records(legacy,'execution-tasks',{source:'todo',taskId:'1',portalSource:'v8'}).map(row=>row.id),['legacy']);
});
for(const status of ['sent','unknown','ignored','failed'])test('intake expiry skips inactive '+status+' history without scanning task eligibility',t=>{
const f=fixture(40,{status});t.after(()=>f.close());const before=f.store.queryRevision();
f.store.expireIntakes();
assert.equal(f.store.queryRevision(),before,'history must remain untouched');
assert.equal(f.counts.all['execution-tasks']||0,0,JSON.stringify(f.counts));
assert.equal(f.counts.get.batches||0,0,JSON.stringify(f.counts));
});
for(const huizhou of [false,true])test('active carry advancement skips eligibility for 300 archived sent orders '+(huizhou?'with disabled Hui records':'without a Hui notice'),t=>{
const f=fixture(300,{status:'sent',huizhou});t.after(()=>f.close());
const settings=f.store.get('settings','main');f.store.put('settings',{...settings,enabled:true,processingEnabled:true});
for(const order of f.store.all('orders'))f.store.put('orders',{...order,ruleSnapshot:{...order.ruleSnapshot,huizhouEnabled:false},archive:{archivedAt:'2026-10-26T00:45:00Z',files:[{name:'notice.pdf',path:'C:\\fixture\\notice.pdf',sha256:'a'.repeat(64),size:128,kind:'pdf'}]}});
const revision=f.store.queryRevision();f.reset();
assert.deepEqual(require('../../src/modules/order-rules/carry-forward.cjs').advance(f.store),{moved:[]});
assert.equal(f.counts.all['execution-tasks']||0,0,JSON.stringify(f.counts));
assert.equal(f.counts.get['capture-samples']||0,0,JSON.stringify(f.counts));
assert.equal(f.store.queryRevision(),revision,'completed and disabled modes must stay untouched');
});
@@ -4,9 +4,9 @@ const {orderDrivenUI}=require('../fixtures/order-driven-ui.cjs');
test('healthy todo without matched orders shows pending verification without loosening capability gates',{timeout:60000},async t=>{
const {page,runtime}=await orderDrivenUI(t,'#notification-settings'),s=runtime.orderRules;
s.put('settings',{...s.get('settings','main'),enabled:true,processingEnabled:true});s.capabilities={liveTodo:true,pdfExport:false,automaticArchive:false};
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByRole('link',{name:'自动通知待验证',exact:true}).waitFor();
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByRole('link',{name:'自动通知待核验',exact:true}).waitFor();
assert.equal(s.providersReady(),false);assert.equal(s.settings().enabled,true);
s.put('execution-scans',{id:'failed-source',status:'failed',error:'fixture failure'});
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByRole('link',{name:'自动通知受阻',exact:true}).waitFor();
await page.getByRole('button',{name:'刷新数据',exact:true}).click();await page.getByRole('link',{name:'自动通知待核验',exact:true}).waitFor();
assert.equal(s.providersReady(),false);
});
+5 -5
View File
@@ -3,11 +3,11 @@ const test=require('node:test'),assert=require('node:assert/strict'),fs=require(
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function setup(t,section,owner='OrderNotificationViews',mailFailure=false){
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();page.setDefaultTimeout(5000);await page.setContent('<main id="root"></main>');
for(const file of ['order-notifications/shared.js','order-rules/view.js','order-notifications/view.js'])await page.addScriptTag({content:await fs.readFile(path.resolve('web/modules',file),'utf8')});
await page.evaluate(async({section,owner,mailFailure})=>{window.calls=[];window.active=true;window.PageLifecycle={requestKey:()=> 'key',dirty:()=>false,onDispose:()=>{},afterSave:async reload=>reload(),guard:fn=>fn()};window.BusinessRecordViews={render:async(host,options,kind)=>{host.textContent='授权分页 '+kind;}};window.OrderExecutionViews={fields:async panel=>{panel.textContent='字段映射';}};const snapshot={rules:[],adapters:[],settings:{enabled:false,processingEnabled:false,version:1},counts:{orders:3,blocked:1,unknown:1,activeBatches:2},capabilities:{},window:{available:true,start:'2026-10-19T00:00:00Z',end:'2026-10-19T11:00:00Z'}};window[owner].configure(window.viewHelpers={api:async(url,body)=>{window.calls.push(url);if(body)return new Promise(r=>window.releaseAction=()=>r({version:2}));if(url==='/mail'&&mailFailure)throw Error('SMTP目录暂不可读');return url==='/mail'?{channels:[]}:snapshot;},esc:value=>String(value??'').replaceAll('&','&amp;').replaceAll('<','&lt;'),formatDate:v=>v||'—',user:{role:'admin'}});await window[owner].render(document.querySelector('#root'),()=>window.active,section);},{section,owner,mailFailure});return page;
for(const file of ['navigation/lifecycle.js','order-notifications/home.js','order-notifications/shared.js','order-rules/view.js','order-notifications/view.js'])await page.addScriptTag({content:await fs.readFile(path.resolve('web/modules',file),'utf8')});
await page.evaluate(async({section,owner,mailFailure})=>{window.calls=[];window.active=true;window.BusinessRecordViews={render:async(host,options,kind)=>{host.textContent='授权分页 '+kind;}};window.OrderExecutionViews={fields:async panel=>{panel.textContent='字段映射';}};const snapshot={rules:[],adapters:[],settings:{enabled:false,processingEnabled:false,version:1},counts:{orders:3,blocked:1,unknown:1,activeBatches:2},capabilities:{},window:{available:true,start:'2026-10-19T00:00:00Z',end:'2026-10-19T11:00:00Z'}};window[owner].configure(window.viewHelpers={api:async(url,body)=>{window.calls.push(url);if(body)return new Promise(r=>window.releaseAction=()=>r({version:2}));if(url==='/mail'&&mailFailure)throw Error('SMTP目录暂不可读');return url==='/mail'?{channels:[]}:snapshot;},esc:value=>String(value??'').replaceAll('&','&amp;').replaceAll('<','&lt;'),formatDate:v=>v||'—',user:{role:'admin'}});await window[owner].render(document.querySelector('#root'),()=>window.active,section);},{section,owner,mailFailure});return page;
}
test('order and batch sections delegate to bounded query views without loading full snapshots',async t=>{const page=await setup(t,'orders');assert.equal(await page.locator('main').innerText(),'授权分页 orders');assert.deepEqual(await page.evaluate(()=>calls),[]);await page.evaluate(()=>OrderNotificationViews.render(document.querySelector('#root'),()=>active,'pending'));assert.equal(await page.locator('main').innerText(),'授权分页 batches');assert.deepEqual(await page.evaluate(()=>calls),[]);});
test('fields delegate their lifecycle without notification runtime reads',async t=>{const page=await setup(t,'fields','OrderRuleViews');await page.getByText('字段映射',{exact:true}).waitFor();assert.deepEqual(await page.evaluate(()=>calls),[]);});
test('business homepage uses bounded summary and concrete remediation links',async t=>{const page=await setup(t,'workbench');assert.match(await page.locator('main').innerText(),/2026-10-19T11:00:00Z/);for(const hash of ['#rule-fields','#bpm','#storage','#notification-orders'])assert.ok(await page.locator('a[href="'+hash+'"]').count());assert.deepEqual(await page.evaluate(()=>calls),['/order-rules?view=summary']);});
test('mailbox failure is explicit and cannot save an empty catalog',async t=>{const page=await setup(t,'settings','OrderNotificationViews',true);assert.match(await page.locator('main').innerText(),/邮箱目录读取失败/);await page.getByRole('button',{name:'保存设置'}).click();assert.deepEqual(await page.evaluate(()=>calls),['/order-rules?view=summary','/mail']);});
test('late settings action after departure starts no readback or saved feedback',async t=>{const page=await setup(t,'settings');await page.getByRole('button',{name:'保存设置'}).click();await page.waitForFunction(()=>typeof releaseAction==='function');await page.evaluate(()=>{active=false;releaseAction();});await page.waitForFunction(()=>!document.querySelector('#order-rule-settings button').disabled);assert.deepEqual(await page.evaluate(()=>calls),['/order-rules?view=summary','/mail','/order-rules/settings']);assert.equal(await page.locator('form [role=alert]').innerText(),'');});
test('business homepage uses bounded summary and concrete remediation links',async t=>{const page=await setup(t,'workbench');assert.equal(await page.locator('[data-home-next-send]').innerText(),'19:00');for(const hash of ['#rule-fields','#bpm','#storage','#notification-orders'])assert.ok(await page.locator('a[href="'+hash+'"]').count());assert.deepEqual(await page.evaluate(()=>calls),['/order-rules?view=summary']);});
test('mailbox failure is explicit and cannot save an empty catalog',async t=>{const page=await setup(t,'settings','OrderNotificationViews',true);assert.match(await page.locator('main').innerText(),/邮箱目录读取失败/);await page.getByRole('button',{name:'保存设置'}).click();assert.deepEqual(await page.evaluate(()=>calls),['/order-rules/notification-settings','/mail']);});
test('late settings action after departure starts no readback or saved feedback',async t=>{const page=await setup(t,'settings');await page.getByRole('button',{name:'保存设置'}).click();await page.waitForFunction(()=>typeof releaseAction==='function');await page.evaluate(()=>{active=false;releaseAction();});await page.waitForFunction(()=>!document.querySelector('#order-rule-settings button').disabled);assert.deepEqual(await page.evaluate(()=>calls),['/order-rules/notification-settings','/mail','/order-rules/settings']);assert.equal(await page.locator('form [role=alert]').innerText(),'');});
+79
View File
@@ -0,0 +1,79 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path');
const {FileArea,SmbClient,MAX_FILE}=require('../../src/modules/storage/files.cjs');
const {StorageService}=require('../../src/modules/storage/service.cjs');
const {storageApi}=require('../../src/modules/storage/api.cjs');
const {validate}=require('../../src/modules/storage/smb-operation.cjs');
const {makePreviewFiles}=require('../fixtures/storage-preview-files.cjs');
async function fixture(t){const root=await fs.mkdtemp(path.join(os.tmpdir(),'storage-range-'));t.after(()=>fs.rm(root,{recursive:true,force:true}));return {root,area:new FileArea(root)};}
async function request(storage,range,{action='file',relative='large.bin',role='operator'}={}){
const headers={},url=new URL('http://localhost/api/storage/servers/local/'+action+'?path='+encodeURIComponent(relative));let status,bytes;
await storageApi({storage,user:{username:'tester',role},url,route:url.pathname,method:'GET',request:{headers:range===undefined?{}:{range}},response:{setHeader(name,value){headers[name]=value;},writeHead(value){status=value;},end(value){bytes=value||Buffer.alloc(0);}}});return {headers,status,bytes};
}
function countReads(t){let bytes=0,opens=0;const original=fs.open;t.mock.method(fs,'open',async(...args)=>{const handle=await original(...args),read=handle.read.bind(handle);opens++;handle.read=async(...args)=>{const value=await read(...args);bytes+=value.bytesRead;return value;};return handle;});return {get bytes(){return bytes;},get opens(){return opens;}};}
for(const preview of [false,true])test(`64 KiB ${preview?'PDF preview':'download'} range reads bounded bytes through the real route, service and FileArea`,async t=>{
const {root,area}=await fixture(t),relative=preview?'large.pdf':'large.bin',source=Buffer.alloc(16*1024*1024,7);if(preview)source.write('%PDF-1.7');await fs.writeFile(path.join(root,relative),source);
const storage=new StorageService({store:{secret:()=>({enabled:true})},client:{area:async()=>area}});t.after(()=>storage.stop());const reads=countReads(t);
const result=await request(storage,'bytes=1048576-1114111',{action:preview?'content':'file',relative});
assert.equal(result.status,206);assert.equal(result.headers['Content-Range'],'bytes 1048576-1114111/16777216');assert.equal(result.bytes.length,65536);assert.deepEqual(result.bytes,source.subarray(1048576,1114112));
assert.ok(reads.bytes<100*1024,`range must not read the full file: ${reads.bytes}`);assert.equal(reads.opens,1,'header and requested content must use the same handle');
});
test('suffixes, open ends, invalid ranges and empty downloads preserve complete-size HTTP metadata',async t=>{
const {root,area}=await fixture(t);await fs.writeFile(path.join(root,'large.bin'),'0123456789');const storage=new StorageService({store:{secret:()=>({enabled:true})},client:{area:async()=>area}});t.after(()=>storage.stop());
for(const [range,want,contentRange] of [['bytes=-3','789','bytes 7-9/10'],['bytes=7-','789','bytes 7-9/10'],['bytes=7-99','789','bytes 7-9/10'],['bytes=-99','0123456789','bytes 0-9/10']]){const result=await request(storage,range);assert.equal(result.status,206);assert.equal(result.bytes.toString(),want);assert.equal(result.headers['Content-Range'],contentRange);}
for(const range of ['bytes=-0','bytes=10-','bytes=9-8','bytes=-','bytes=0-1,3-4','items=0-1','bytes=9007199254740992-','bytes=-9007199254740992']){const result=await request(storage,range);assert.equal(result.status,416,range);assert.equal(result.headers['Content-Range'],'bytes */10');assert.equal(result.bytes.length,0);}
await fs.writeFile(path.join(root,'empty.bin'),'');const empty=await request(storage,undefined,{relative:'empty.bin'});assert.equal(empty.status,200);assert.equal(empty.bytes.length,0);assert.equal((await request(storage,'bytes=0-',{relative:'empty.bin'})).status,416);
});
test('PDF ranges still validate the header and whole-file limits before reading content',async t=>{
const {root,area}=await fixture(t);await fs.writeFile(path.join(root,'fake.pdf'),'Not a PDF body');await assert.rejects(area.readPreview('fake.pdf',{range:'bytes=5-7'}),error=>error.status===415);
await fs.writeFile(path.join(root,'huge.bin'),'');await fs.truncate(path.join(root,'huge.bin'),MAX_FILE+1);await assert.rejects(area.readFile('huge.bin',MAX_FILE,{range:'bytes=0-1'}),error=>error.status===413);
await fs.writeFile(path.join(root,'huge.pdf'),'%PDF-');await fs.truncate(path.join(root,'huge.pdf'),MAX_FILE+1);await assert.rejects(area.readPreview('huge.pdf',{range:'bytes=0-1'}),error=>error.status===413);
});
test('a source that shrinks during range reading is rejected instead of returning partial success',async t=>{
const {root,area}=await fixture(t),file=path.join(root,'large.bin');await fs.writeFile(file,Buffer.alloc(1024,1));const original=fs.open;let changed=false;
t.mock.method(fs,'open',async(...args)=>{const handle=await original(...args),read=handle.read.bind(handle);handle.read=async(...args)=>{if(!changed){changed=true;await fs.truncate(file,100);}return read(...args);};return handle;});
await assert.rejects(area.readFile('large.bin',MAX_FILE,{range:'bytes=512-767'}),error=>error.status===409);
});
for(const change of ['grow','replace'])test(`a source that ${change==='grow'?'grows':'is replaced'} between PDF header and content is rejected`,async t=>{
const {root,area}=await fixture(t),file=path.join(root,'sample.pdf');await fs.writeFile(file,Buffer.from('%PDF-'+'.'.repeat(1019)));const original=fs.open;let changed=false;
t.mock.method(fs,'open',async(...args)=>{const handle=await original(...args),read=handle.read.bind(handle);handle.read=async(...args)=>{const result=await read(...args);if(!changed){changed=true;if(change==='grow')await fs.appendFile(file,'x');else{await fs.rename(file,file+'.old');await fs.writeFile(file,Buffer.alloc(1024,1));}}return result;};return handle;});
await assert.rejects(area.readPreview('sample.pdf',{range:'bytes=100-199'}),error=>error.status===409);
});
test('Office and image ranges retain whole-file validation and text ranges address decoded UTF-8 bytes',async t=>{
const {root,area}=await fixture(t);await makePreviewFiles(root);
for(const relative of ['sample.docx','sample.xlsx','sample.png']){
const full=await area.readPreview(relative),part=await area.readPreview(relative,{range:'bytes=0-7'});
assert.equal(part.total,full.bytes.length);assert.equal(part.status,206);assert.deepEqual(part.bytes,full.bytes.subarray(0,8));
}
const full=await area.readPreview('gbk.txt'),part=await area.readPreview('gbk.txt',{range:'bytes=-3'});assert.equal(part.total,6);assert.deepEqual(part.bytes,full.bytes.subarray(3));assert.equal(part.bytes.toString(),'文');
await assert.rejects(area.readPreview('bad.png',{range:'bytes=0-1'}),error=>error.status===415);
const office=await fs.readFile(path.join(root,'sample.docx')),central=office.indexOf(Buffer.from([0x50,0x4b,0x01,0x02]));office.writeUInt32LE(70*1024*1024,central+24);await fs.writeFile(path.join(root,'bomb.docx'),office);
await assert.rejects(area.readPreview('bomb.docx',{range:'bytes=0-1'}),error=>error.status===413);
});
test('range access keeps relative-path, link, and role restrictions',async t=>{
const {root,area}=await fixture(t),outside=await fs.mkdtemp(path.join(os.tmpdir(),'storage-range-outside-'));t.after(()=>fs.rm(outside,{recursive:true,force:true}));await fs.writeFile(path.join(outside,'secret.bin'),'private');await fs.symlink(outside,path.join(root,'link'),'junction');
for(const relative of ['../secret.bin','link/secret.bin','x:stream'])await assert.rejects(area.readFile(relative,MAX_FILE,{range:'bytes=0-1'}),error=>error.status===400);
const storage={readFile:()=>assert.fail('viewers must not reach storage')};await assert.rejects(request(storage,'bytes=0-1',{role:'viewer'}),error=>error.status===403);
});
test('range metadata and bounded buffers survive real worker IPC while malformed offsets are rejected',async t=>{
const {root}=await fixture(t);await fs.writeFile(path.join(root,'large.bin'),Buffer.alloc(16*1024*1024,8));const server={root,pidFile:path.join(root,'worker.pid'),enabled:true,version:1},client=new SmbClient({workerPath:path.join(__dirname,'worker-fixture.cjs')}),storage=new StorageService({store:{secret:()=>server},client,operationTimeoutMs:5000});t.after(()=>storage.stop());
const result=await storage.readFile('local','large.bin',{range:'bytes=-65536'});assert.equal(result.total,16777216);assert.equal(result.start,16711680);assert.equal(result.end,16777215);assert.equal(result.status,206);assert.equal(result.bytes.length,65536);assert.ok(result.bytes.every(byte=>byte===8));
assert.throws(()=>validate('readFile',{filename:'x',total:10,start:5,end:7,status:206,bytes:Buffer.alloc(1)}),error=>error.status===502);
const invalid=await storage.readFile('local','large.bin',{range:'bytes=16777216-'});assert.equal(invalid.status,416);assert.equal(invalid.total,16777216);assert.equal(invalid.bytes.length,0);
});
test('production worker dispatch preserves range options and returns unsatisfied totals as metadata',async t=>{
const {root,area}=await fixture(t);await fs.writeFile(path.join(root,'sample.pdf'),'%PDF-1.7 data');
let handle,message,exitCode;const vm=require('node:vm'),source=await fs.readFile(path.join(__dirname,'../../src/modules/storage/smb-operation-worker.cjs'),'utf8');
vm.runInNewContext(source,{require:specifier=>specifier==='./files.cjs'?{SmbClient:class{async area(){return area;}}}:{validate},process:{once(event,handler){assert.equal(event,'message');handle=handler;},send(value,callback){message=value;callback();},exit(code){exitCode=code;}}});
await handle({server:{},operation:'readPreview',args:['sample.pdf',{range:'bytes=5-7'}]});assert.equal(message.ok,true);assert.equal(message.value.status,206);assert.equal(message.value.total,13);assert.equal(message.value.bytes.toString(),'1.7');assert.equal(exitCode,0);
await handle({server:{},operation:'readFile',args:['sample.pdf',MAX_FILE,{range:'bytes=99-'}]});assert.equal(message.ok,true);assert.equal(message.value.status,416);assert.equal(message.value.total,13);assert.equal(message.value.bytes.length,0);
});
+22
View File
@@ -65,3 +65,25 @@ test('network timeout returns unavailable and preserves the current version',asy
const checker=createUpdateChecker({currentVersion:'0.1.0',timeoutMs:25,fetchImpl:async(url,{signal})=>new Promise((resolve,reject)=>signal.addEventListener('abort',()=>reject(signal.reason),{once:true}))});
assert.deepEqual(await checker(),{status:'unavailable',currentVersion:'0.1.0',latest:null});
});
test('concurrent update checks share one upstream read and the next manual check is fresh',async()=>{
let requests=0,release;
const gate=new Promise(resolve=>{release=resolve;});
const checker=createUpdateChecker({currentVersion:'0.1.0',fetchImpl:async()=>{requests++;await gate;return new Response(JSON.stringify({tag_name:'v0.2.0'}));}});
const pending=Array.from({length:8},()=>checker());
assert.equal(requests,1,'simultaneous readers must share the in-flight request');
release();const results=await Promise.all(pending);
assert.ok(results.every(result=>result.status==='update-available'));
results[0].latest.version='caller-mutation';assert.equal(results[1].latest.version,'0.2.0');
assert.equal((await checker()).latest.version,'0.2.0');assert.equal(requests,2,'a completed check must not mask a later manual refresh');
});
test('a coalesced failed check clears in-flight state and a new check can recover',async()=>{
let requests=0,reject;
const failed=new Promise((resolve,rejectPromise)=>{reject=rejectPromise;});
const checker=createUpdateChecker({currentVersion:'0.1.0',fetchImpl:async()=>{requests++;if(requests===1)return failed;return new Response('',{status:404});}});
const first=checker(),second=checker();assert.equal(requests,1);
reject(Error('offline'));
assert.deepEqual(await first,{status:'unavailable',currentVersion:'0.1.0',latest:null});assert.equal((await second).status,'unavailable');
assert.equal((await checker()).status,'none');assert.equal(requests,2);
});