feat(vesc): extend motor diagnostics, configuration and transport recovery

Add firmware and extension catalogues, configuration transactions, sample review and QML diagnostics. Preserve explicit authority, bounded retries and stop recovery in motor transport.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:09:59 +03:00
parent 115476d2e6
commit f32c7b400b
186 changed files with 21197 additions and 339 deletions
@@ -0,0 +1,20 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
const source=readFileSync(new URL('../../../plugins/vesc/frontend/src/bmsView.ts',import.meta.url),'utf8');
const {bmsCellSummary,bmsCells,bmsTemperature,bmsCanOptions,bmsNumber}=await import('data:text/javascript;base64,'+Buffer.from(ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText).toString('base64'));
test('BMS cell spread preserves missing values and actual balancing state',()=>{
assert.equal(bmsCellSummary({v_cells:[]}),null);
assert.equal(bmsCellSummary({v_cells:[3.7,null]}),null);
const summary=bmsCellSummary({v_cells:[3.7,3.8,3.75]});assert.ok(Math.abs(summary.spreadMv-100)<1e-8);
assert.deepEqual(bmsCells({v_cells:[3.7,NaN],is_balancing:[true]}),[{index:0,voltage:3.7,balancing:true},{index:1,voltage:null,balancing:null}]);
assert.equal(bmsCells({v_cells:Array(200).fill(3.7)}).length,96);
});
test('BMS does not turn missing readings or temperature sentinels into zero',()=>{
assert.equal(bmsNumber(undefined),'Не сообщается');assert.equal(bmsNumber(NaN),'Не сообщается');assert.equal(bmsNumber(0),'0');
assert.equal(bmsTemperature(-280),'Не сообщается');assert.equal(bmsTemperature(-300),'Не сообщается');assert.notEqual(bmsTemperature(0),'Не сообщается');
});
test('BMS CAN target selection cannot broadcast and stays unique',()=>{
assert.deepEqual(bmsCanOptions([253,0,0,255,254,-1,NaN,'12',true,1.5]),[{value:'0',label:'CAN 0'},{value:'253',label:'CAN 253'}]);
});
@@ -0,0 +1,16 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
const source=readFileSync(new URL('../../../plugins/vesc/frontend/src/editorFiles.ts',import.meta.url),'utf8');
const {validateProject,bytesBase64}=await import('data:text/javascript;base64,'+Buffer.from(ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText).toString('base64'));
test('Lisp project export preserves binary imports and UTF-8 source',()=>{
const input={kind:'lisp',source:'(print "проверка")',imports:{'data.bin':bytesBase64(Uint8Array.from([0,255,1]))},fullscreen:false};
assert.deepEqual(validateProject(JSON.parse(JSON.stringify(input)),'lisp'),input);
assert.equal(atob(input.imports['data.bin']).charCodeAt(1),255);
});
test('code import rejects wrong kind, oversized source and unsafe attachment names',()=>{
const p={kind:'lisp',source:'(+ 1 2)',imports:{},fullscreen:false};
for(const value of [{...p,kind:'qml'},{...p,source:'x'.repeat(122881)},{...p,source:'x\0y'}, {...p,imports:{'../secret':'YQ=='}},{...p,imports:{'/secret':'YQ=='}},{...p,imports:{'a.bin':'!'}},{...p,imports:Array(2)}]) assert.throws(()=>validateProject(value,'lisp'));
assert.throws(()=>validateProject({...p,kind:'qml',imports:{'a.bin':'YQ=='}},'qml'));
});
@@ -0,0 +1,63 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const bundled=await build({stdin:{contents:`export {useVescRead} from '../../plugins/vesc/frontend/src/useVescRead';
export {useVescEditor} from '../../plugins/vesc/frontend/src/useVescEditor';`,resolveDir:process.cwd(),loader:'ts'},
bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'react-fixture',setup(b){
b.onResolve({filter:/^react$/},()=>({path:'react',namespace:'fixture'}));
b.onLoad({filter:/.*/,namespace:'fixture'},()=>({contents:`export const useRef=v=>({current:v});
export const useEffect=f=>f();export const useState=v=>{const i=globalThis.vescFixture.index++;
return [i===0&&globalThis.vescFixture.preview?globalThis.vescFixture.preview:v,
next=>globalThis.vescFixture.writes.push(next)];};`}));
}}]});
const {useVescRead,useVescEditor}=await import('data:text/javascript;base64,'+Buffer.from(bundled.outputFiles[0].contents).toString('base64'));
async function fixture(run,{delay=45000,outcome='complete',preview=null}={}){
const oldNow=Date.now,oldTimeout=globalThis.setTimeout,oldFixture=globalThis.vescFixture;
let now=1000000;Date.now=()=>now;globalThis.setTimeout=f=>{now+=1000;queueMicrotask(f);return 0;};
const state={index:0,writes:[],preview};globalThis.vescFixture=state;
const submitted=[],polled=[],errors=[],result={verified:true,preview_id:'cfg_synthetic'};
const props={enabled:true,blocked:false,onBusyChange:()=>{},failure:e=>{if(e)errors.push(e);},refresh:async()=>{},
device:{id:'synthetic',online:true,verified:true,snapshot:{context:{session_id:'attachment'}},
vesc_status:{readable:true,configuration_edit_supported:true}},
transport:{submit:async c=>{submitted.push(c);now+=delay;return {state:'queued'};},
operation:async id=>{polled.push(id);return {state:outcome,result};}}};
try{await run({props,submitted,polled,errors,state,result});}
finally{Date.now=oldNow;globalThis.setTimeout=oldTimeout;
if(oldFixture===undefined)delete globalThis.vescFixture;else globalThis.vescFixture=oldFixture;}
}
test('configuration read survives a paced delivery longer than the former 30 second budget',async()=>fixture(async f=>{
await useVescRead(f.props,'vesc.configuration.read').read();
assert.deepEqual(f.errors,[]);assert.ok(f.state.writes.includes(f.result));
assert.equal(f.submitted.length,1);assert.deepEqual(f.polled,[f.submitted[0].operation_id]);
assert.equal(Date.parse(f.submitted[0].deadline_at)-Date.parse(f.submitted[0].requested_at),180000);
}));
test('ordinary telemetry reads retain their short budget',async()=>fixture(async f=>{
await useVescRead(f.props,'vesc.telemetry.read').read();
assert.equal(f.submitted.length,1);assert.equal(f.errors.length,1);assert.deepEqual(f.polled,[]);
assert.equal(Date.parse(f.submitted[0].deadline_at)-Date.parse(f.submitted[0].requested_at),30000);
}));
test('preview and reconciliation use the configuration delivery budget',async()=>{
for(const method of ['prepare','reconcile'])await fixture(async f=>{
await useVescEditor(f.props)[method]({kind:'motor',changes:{l_current_max:100}});
assert.deepEqual(f.errors,[]);assert.equal(f.submitted.length,1);assert.ok(f.state.writes.includes(f.result));
});
});
test('apply waits for its own late receipt without resending a write',async()=>fixture(async f=>{
await useVescEditor(f.props).apply();
assert.deepEqual(f.errors,[]);assert.equal(f.submitted.length,1);
assert.equal(f.submitted[0].action_id,'vesc.configuration.apply');
assert.deepEqual(f.submitted[0].parameters,{preview_id:'cfg_synthetic',rig_clear:true,inputs_isolated:true});
assert.deepEqual(f.polled,[f.submitted[0].operation_id]);assert.ok(f.state.writes.includes(f.result));
},{delay:75000,preview:{preview_id:'cfg_synthetic'}}));
test('unknown apply result stays unconfirmed and never resubmits the write',async()=>fixture(async f=>{
await useVescEditor(f.props).apply();
assert.equal(f.errors.length,1);assert.equal(f.submitted.length,1);
assert.equal(f.state.writes.includes(f.result),false);
},{outcome:'unknown',preview:{preview_id:'cfg_synthetic'}}));
test('configuration wait is bounded',async()=>fixture(async f=>{
await useVescRead(f.props,'vesc.configuration.read').read();
assert.equal(f.errors.length,1);assert.equal(f.submitted.length,1);assert.deepEqual(f.polled,[]);
},{delay:191000}));
@@ -0,0 +1,24 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
const source=readFileSync(new URL('../../../plugins/vesc/frontend/src/controlTransport.ts',import.meta.url),'utf8');
const {routeError,transportMode}=await import('data:text/javascript;base64,'+Buffer.from(ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText).toString('base64'));
const drive={layout:'1x1',revision:1,bindings:{'left.1':{device_id:'left',uuid:'1'.repeat(24)},'right.1':{device_id:'right',uuid:'2'.repeat(24)}}};
const usb={left:{kind:'usb',uuid:'1'.repeat(24)},right:{kind:'usb',uuid:'2'.repeat(24)}};
const can={...usb,left:{...usb.left,kind:'can',adapter_id:'usbcan_'+'a'.repeat(32),channel:0,can_id:74,bitrate:500000}};
test('selection distinguishes uniform and mixed transport',()=>{
assert.equal(transportMode(usb),'usb');assert.equal(transportMode(can),'mixed');assert.equal(routeError(can,drive),null);
});
test('CAN requires an explicit address and binding',()=>{
assert.ok(routeError({...can,left:{...can.left,can_id:-1}},drive));
assert.ok(routeError({...can,left:{...can.left,can_id:255}},drive));
assert.ok(routeError({...can,left:{...can.left,uuid:'3'.repeat(24)}},drive));
});
test('same address is permitted only on independent channels',()=>{
const both={...can,right:{...can.left,uuid:usb.right.uuid}};
assert.ok(routeError(both,drive));both.right.channel=1;assert.equal(routeError(both,drive),null);assert.equal(transportMode(both),'can');
});
test('one physical CAN bus cannot have two bitrates',()=>{
assert.ok(routeError({...can,right:{...can.left,uuid:usb.right.uuid,can_id:111,bitrate:250000}},drive));
});
@@ -0,0 +1,34 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,diagnostics;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});diagnostics=await server.ssrLoadModule('../../plugins/vesc/frontend/src/diagnosticReview.ts');});
after(async()=>{await server?.close();});
const uuid='00112233445566778899aabb';
const report=(events=1,timeouts=0)=>({device_id:'synthetic-controller',identity:{uuid,version:'5.02',hardware:'SYNTHETIC'},observed_at:'2026-10-18T10:00:00Z',usb:{port:'1-2',serial:'not-unique'},reports:{hw_status:{command:'hw_status',completion:'200ms-print-quiescence',text:`Firmware: 5.2\nHardware: SYNTHETIC\nUUID: 00 11 22 33 44 55 66 77 88 99 AA BB\nFOC Current Offsets: 2048 2049 2050\nUSB config events: ${events}\nUSB write timeouts: ${timeouts}\n `},faults:{command:'faults',completion:'200ms-print-quiescence',text:'No faults registered since startup\n'}}});
const time=Date.parse('2026-10-18T10:00:00Z');
const snap=(r=report(),offset=0,session='usb-1')=>{r.observed_at=new Date(time+offset).toISOString();return diagnostics.diagnosticSnapshot(r,session,time+offset,1000+offset);};
test('native hw_status grammar preserves UUID, counter zero and current offsets',()=>{const s=snap();assert.equal(s.identityMatches,true);assert.equal(s.configEvents,1);assert.equal(s.writeTimeouts,0);assert.deepEqual(s.offsets,[2048,2049,2050]);assert.equal(s.faults.state,'none');});
test('missing, duplicate, signed, overflowing and malformed counters never become zero',()=>{
for(const value of ['', '-1', 'NaN', '1.5', '4294967296', '1 extra']){const r=report(value);assert.equal(snap(r).configEvents,null);}
const r=report();r.reports.hw_status.text+='\nUSB config events: 1';assert.equal(snap(r).configEvents,null);
r.reports.hw_status.text='partial';const s=snap(r);assert.equal(s.configEvents,null);assert.equal(s.writeTimeouts,null);assert.equal(s.offsets,null);assert.equal(s.identityMatches,false);
});
test('comparison uses only matching controller identity, firmware and USB session',()=>{
const a=snap(),b=snap(report(3,2),10000);assert.deepEqual(diagnostics.compareDiagnostics(a,b),{reason:null,configEvents:2,writeTimeouts:2});
for(const mutate of [b=>b.session='usb-2',b=>b.read.device_id='other',b=>b.read.identity.uuid='ff'.repeat(12),b=>b.read.identity.version='6.00',b=>b.read.identity.hardware='other',b=>b.identityMatches=false]){const b=snap(report(3,2),10000);mutate(b);const d=diagnostics.compareDiagnostics(a,b);assert.ok(d.reason);assert.equal(d.configEvents,null);assert.equal(d.writeTimeouts,null);}
});
test('counter decrease invalidates all deltas and never proves a reboot',()=>{const a=snap(report(4,3)),b=snap(report(1,5),10000),d=diagnostics.compareDiagnostics(a,b);assert.match(d.reason,/возможен/);assert.equal(d.configEvents,null);assert.equal(d.writeTimeouts,null);});
test('no subtraction across unordered, expired or next-day snapshots',()=>{
const a=snap();for(const b of [snap(),snap(report(),-1),snap(report(),300000)])assert.ok(diagnostics.compareDiagnostics(a,b).reason);
const r=report();r.observed_at='2026-10-18T23:59:59Z';const a2=diagnostics.diagnosticSnapshot(r,'usb-1',Date.parse(r.observed_at),100);r.observed_at='2026-10-19T00:00:01Z';const b2=diagnostics.diagnosticSnapshot(r,'usb-1',Date.parse(r.observed_at),2100);assert.ok(diagnostics.compareDiagnostics(a2,b2).reason);
});
test('expiry uses both monotonic and wall clocks, UTC day and backward jumps',()=>{const s=snap();assert.equal(diagnostics.diagnosticExpired(s,time+299999,300999),false);for(const [wall,mono] of [[time+300000,301000],[time+1,301000],[time-1,1001],[time+1,999],[time+86400000,1001]])assert.equal(diagnostics.diagnosticExpired(s,wall,mono),true);});
test('fault log keeps separate repeated fault entries and unknown fields, not a current fault',()=>{
const f=diagnostics.parseFaults('The following faults were registered since start:\nFault : FAULT_CODE_ABS_OVER_CURRENT\nMotor : 1\nCurrent : 82.3\nRPM : 140\nFuture field : unknown\n\nFault : FAULT_CODE_ABS_OVER_CURRENT\nCurrent : 90.1\n');
assert.equal(f.state,'reported');assert.equal(f.entries.length,2);assert.equal(f.entries[0].fields.Current,'82.3');assert.equal(f.entries[1].fields.Current,'90.1');assert.equal(f.entries[0].fields['Future field'],'unknown');
});
test('empty, truncated or unknown faults are not a clean bill of health',()=>{for(const text of ['','No faults','Fault : bad','Firmware failure','x'.repeat(65537),'Fault : FAULT_CODE_X\n'.repeat(65)])assert.equal(diagnostics.parseFaults(text).state,'unknown');});
test('bad report envelopes and oversized input are rejected',()=>{
for(const mutate of [r=>delete r.reports.hw_status,r=>r.reports.hw_status.command='faults',r=>r.reports.faults.text='x'.repeat(65537),r=>r.observed_at='bad']){const r=report();mutate(r);assert.throws(()=>diagnostics.diagnosticSnapshot(r,'usb-1'));}
});
@@ -0,0 +1,15 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
const source=readFileSync(new URL('../../../plugins/vesc/frontend/src/firmwareFiles.ts',import.meta.url),'utf8');
const {firmwareFileError}=await import('data:text/javascript;base64,'+Buffer.from(ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText).toString('base64'));
test('older engines do not offer HEX; supported files stay bounded before browser allocation',()=>{
assert.ok(firmwareFileError({name:'firmware.hex',size:1000},'firmware',['bin']));
assert.equal(firmwareFileError({name:'firmware.HEX',size:8*1024*1024},'firmware',['bin','hex']),null);
assert.ok(firmwareFileError({name:'firmware.hex',size:8*1024*1024+1},'firmware',['bin','hex']));
assert.ok(firmwareFileError({name:'firmware.zip',size:1000},'firmware',['bin','hex']));
assert.ok(firmwareFileError({name:'boot.bin',size:65537},'bootloader',['bin','hex']));
assert.equal(firmwareFileError({name:'boot.hex',size:100000},'bootloader',['bin','hex']),null);
assert.ok(firmwareFileError({name:'empty.bin',size:0},'firmware',['bin','hex']));
});
@@ -0,0 +1,20 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,h;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});h=await server.ssrLoadModule('../../plugins/vesc/frontend/src/hallInputs.ts');});
after(async()=>{await server?.close();});
const config=(values)=>({configuration:{motor:{parameters:Object.entries(values).map(([name,value])=>({name,value,type:'integer',editor_scale:1}))}}});
test('Hall selected in FOC is configuration intent, never sensor presence or zero edges',()=>{
const v=h.hallConfiguration(config({motor_type:2,m_sensor_port_mode:0,foc_sensor_mode:2}));
assert.equal(v.use,'Холлы выбраны в настройках FOC');assert.deepEqual(v.inputs,[null,null,null]);assert.deepEqual(v.transitions,[null,null,null]);
});
test('Sensorless and a repaired contact cannot imply either disconnected or working',()=>{
const v=h.hallConfiguration(config({motor_type:2,m_sensor_port_mode:0,foc_sensor_mode:0}));
assert.equal(v.use,'Холлы не выбраны в настройках FOC');assert.deepEqual(v.inputs,[null,null,null]);
});
test('missing config or a different motor/port never confirms Hall use',()=>{
assert.equal(h.hallConfiguration(null).use,'Не прочитано');
assert.equal(h.hallConfiguration(config({motor_type:0,m_sensor_port_mode:0,foc_sensor_mode:2})).use,'См. параметры выбранного типа мотора');
assert.equal(h.hallConfiguration(config({motor_type:2,m_sensor_port_mode:1,foc_sensor_mode:2})).use,'Холлы не выбраны в настройках FOC');
});
@@ -0,0 +1,51 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,log,trends,plot,telemetry;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});log=await server.ssrLoadModule('../../plugins/vesc/frontend/src/logAnalysis.ts');trends=await server.ssrLoadModule('../../plugins/vesc/frontend/src/trends.ts');plot=await server.ssrLoadModule('../../plugins/vesc/frontend/src/SignalPlot.tsx');telemetry=await server.ssrLoadModule('./src/components/rover/RoverTelemetry.tsx');});
after(async()=>{await server?.close();});
const rt=(rows)=>'ms_today;input_voltage;current_motor;duty_cycle;vesc_id;\n'+rows.map(r=>r.join(';')+';').join('\n');
test('original RT CSV preserves measured zero/missing values and converts PWM only once',()=>{
const v=log.parseVescLog(rt([[100,48,0,.5,1],[200,47,'',0,1]]));
assert.equal(v.format,'VESC Tool · RT');assert.equal(v.duration,100);assert.equal(v.points[0].values.duty_cycle,50);assert.equal(v.points[1].values.current_motor,null);
assert.equal(v.uuid,null);assert.equal(v.columns[0].unit,'В');
});
test('original rich Log Analysis headers retain arbitrary columns, units and missing cells',()=>{
const v=log.parseVescLog('t_day:Time:s:3:1:1;custom:Signal:A:2:0:0\n2;1\n2.1;\n2.2;3\n');
assert.equal(v.columns[0].label,'Signal');assert.equal(v.columns[0].unit,'A');assert.equal(v.points[1].values.custom,null);assert.ok(Math.abs(v.duration-200)<1e-8);
});
test('Mission Core exported CSV round-trips measured units, metadata, escaped CSV and session gaps',()=>{
const p=[{at:10,source:'a',session:'one',sample:1,utc:'2026-10-18T01:00:00Z',values:{duty:20,input_voltage_v:48}},{at:20,source:'a',session:'one',sample:2,utc:'',values:null},{at:30,source:'b',session:'two',sample:3,utc:'2026-10-18T01:00:01Z',values:{duty:30}}];
const v=log.parseVescLog(trends.traceCsv(p,{uuid:'abc123',hardware:'board,"quoted"',version:'5.02'}));
assert.equal(v.uuid,'abc123');assert.equal(v.hardware,'board,"quoted"');assert.equal(v.points[0].values['duty [%]'],20);assert.equal(v.points.at(-1).values['duty [%]'],30);assert.ok(v.points.some(p=>p.gap));
});
test('time wraps at midnight with explicit gap, regressions and mixed controllers are rejected',()=>{
const v=log.parseVescLog(rt([[86399900,48,0,0,1],[100,48,0,0,1]]));assert.equal(v.duration,200);assert.equal(v.points[1].gap,true);
assert.throws(()=>log.parseVescLog(rt([[200,48,0,0,1],[100,48,0,0,1]])),/назад/);
assert.throws(()=>log.parseVescLog(rt([[100,48,0,0,1],[200,48,0,0,2]])),/разные контроллеры/);
});
test('parser rejects malformed widths, duplicate keys, formula, nonfinite and oversized input',()=>{
for(const value of ['ms_today;x;x\n1;2;3','ms_today;x\n1;2;3','ms_today;x\n1;=2+2','ms_today;x\n1;NaN','ms_today;x\n1;Infinity','ms_today;x\n1;"broken','ms_today;x\n-1;2','unknown;x\n1;2'])assert.throws(()=>log.parseVescLog(value));
assert.throws(()=>log.parseVescLog('x'.repeat(log.LOG_MAX_BYTES+1)),/размер/);
assert.throws(()=>log.parseVescLog('ms_today;x\n'+Array.from({length:20001},(_,i)=>`${i};1`).join('\n')),/20 000/);
});
test('Hann FFT finds known frequency/amplitude and removes DC without changing source',()=>{
const points=Array.from({length:1024},(_,i)=>({at:i*10,values:{x:5+3*Math.sin(2*Math.PI*12.5*i/100)},gap:false}));
const result=log.spectrum(points,'x',0,10240);assert.equal(result.n,1024);assert.equal(result.rate,100);assert.equal(result.peak.hz,12.5);assert.ok(Math.abs(result.peak.amplitude-3)<.001);assert.ok(result.bins[0].amplitude<.001);assert.equal(points[0].values.x,5);
});
test('FFT refuses gaps, duplicate time, irregular samples, missing values and short intervals',()=>{
const base=Array.from({length:64},(_,i)=>({at:i*10,values:{x:i},gap:false}));
for(const data of [base.slice(0,31),base.map((p,i)=>i===30?{...p,gap:true}:p),base.map((p,i)=>i===30?{...p,at:p.at-10}:p),base.map((p,i)=>i===30?{...p,values:{x:null}}:p)])assert.throws(()=>log.spectrum(data,'x',0,1000));
assert.throws(()=>log.spectrum(base.map((p,i)=>({...p,at:p.at+(i===1?2:0)})),'x',0,1000),/неравномерен/);
});
test('plot reduction retains a one-sample peak and does not join a gap',()=>{
const points=Array.from({length:10000},(_,i)=>({at:i,value:i===5000?100:i===6000?null:0}));
const v=plot.signalView(points,0,10000);assert.equal(v.max,100);assert.equal(v.count,9999);assert.equal(v.segments.length,2);assert.ok(v.segments.flat().length<3000);assert.ok(v.segments[0].some(p=>p.y<40));
});
test('telemetry uses identity columns and never treats stale, wrong UUID, NaN or negative age as live',()=>{
const d=(n,age=20)=>({id:'d'+n,uuid:'uuid'+n,label:'device'+n,age_ms:age,values:{motor_current_a:0,fault_code:0}});
for(const count of [1,2,3,4]){const v=telemetry.roverTelemetryTable({fresh:true,snapshot:{devices:Array.from({length:count},(_,i)=>d(i))}});assert.equal(v.columns.length,count);assert.ok(v.rows.every(row=>row.cells.length===count));}
for(const age of [1000,-1,NaN]){const v=telemetry.roverTelemetryTable({fresh:true,snapshot:{devices:[d(1,age)]}});assert.equal(v.rows.find(r=>r.id==='motor_current_a').cells[0],'—');assert.equal(v.rows.find(r=>r.id==='fault').cells[0],'—');}
const stale=telemetry.roverTelemetryTable({fresh:false,snapshot:{devices:[d(1)]}});assert.equal(stale.columns.length,1);assert.equal(stale.rows.find(r=>r.id==='fault').cells[0],'—');
const mismatch=telemetry.roverTelemetryTable({fresh:true,snapshot:{devices:[d(1)],profile:{bindings:{left:{device_id:'d1',uuid:'other'}}}}});assert.equal(mismatch.columns.length,2);assert.equal(mismatch.rows.find(r=>r.id==='status').cells[0],'Нет связи');
});
@@ -0,0 +1,24 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,m,parse;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});m=await server.ssrLoadModule('../../plugins/vesc/frontend/src/rotorHallReview.ts');parse=(await server.ssrLoadModule('../../plugins/vesc/frontend/src/sampleReview.ts')).parseSampleRecord;});
after(async()=>{await server?.close();});
const points=(states)=>states.map((h,i)=>({at:i,values:{hall:h,phase_deg:(358+i)%360,current:i%2?-3:2},gap:false}));
const review=(p,from=0,to=2000)=>m.reviewRotorHall(p,from,to);
test('six-state sequence and reverse direction are not a winding-order diagnosis',()=>{for(const s of [[1,3,2,6,4,5,1],[1,5,4,6,2,3,1]]){const r=review(points(s));assert.equal(r.transitions,6);assert.equal(r.events.filter(e=>e.kind==='change').length,6);assert.equal(r.counts.slice(1,7).filter(Boolean).length,6);}});
test('repeated state reports observed span, never stall or complete sector dwell',()=>{const r=review(points([1,1,1,1]));assert.equal(r.longest[1],3);assert.equal(r.transitions,0);assert.equal(r.events.length,0);assert.equal(r.peakCurrent,3);});
test('0 and 7 remain separate runs; unknown Hall is not silently zero',()=>{const r=review(points([0,0,7,null,2.5,NaN,8,1]));assert.deepEqual(r.counts,[2,1,0,0,0,0,0,1]);assert.equal(r.missing,4);assert.deepEqual(r.events.filter(e=>e.kind!=='change').map(e=>[e.kind,e.first,e.last]),[['code',0,1],['code',2,2],['missing',3,6]]);});
test('mapped commutation codes never become raw-input edges or a sensor diagnosis',()=>{const r=review(points([1,2,5]));assert.equal(r.transitions,2);assert.equal(r.multi,undefined);assert.equal(r.single,undefined);assert.deepEqual(r.events.map(e=>e.label),['Код Hall: 1 → 2','Код Hall: 2 → 5']);});
test('do not bridge a gap, missing state, missing phase or interval boundary',()=>{
const p=points([1,6,2,5]);p[1].gap=true;const r=review(p);assert.equal(r.transitions,1);assert.equal(r.missing,1);assert.equal(r.phaseCount,3);
assert.equal(review(points([1,2]),1,1).transitions,0);
const q=points([1,null,2]);q[1].values.phase_deg=null;assert.equal(review(q).transitions,0);assert.equal(review(q).phaseStep,null);
});
test('phase wraps across 0 without reporting a 359 degree jump; half turn ambiguous',()=>{assert.equal(m.wrappedPhaseStep(359,1),2);assert.equal(m.wrappedPhaseStep(1,359),-2);const p=points([1,1,1]);p[0].values.phase_deg=0;p[1].values.phase_deg=180;p[2].values.phase_deg=360;const r=review(p);assert.equal(r.halfTurns,2);assert.equal(r.phaseStep,180);});
test('missing and out-of-range phase does not become measured mechanical angle',()=>{const p=points([1,1,1,1]);for(const [i,v] of [null,-1,361,Infinity].entries())p[i].values.phase_deg=v;assert.equal(review(p).phaseCount,0);assert.equal(review(p).phaseStep,null);});
test('event navigation keeps original indices and cursor times with bounded context',()=>{const p=points(Array(20).fill(1));p[12].values.hall=2;const r=review(p,10,15);const w=m.hallEventWindow(p,r.events[0]);assert.deepEqual(w,{from:6,to:17,first:11,second:12});});
test('empty interval and one sample never fabricate movement',()=>{const p=points([1]);assert.equal(review(p,2,3).count,0);const r=review(p);assert.equal(r.phaseStep,null);assert.equal(r.longest[1],0);assert.equal(r.transitions,0);});
test('bounded inputs and ordered finite clock enforced',()=>{for(const p of [Array.from({length:2001},(_,i)=>({...points([1])[0],at:i})),points([1,1]).map(p=>({...p,at:0})),[{at:NaN,values:{},gap:false}]])assert.throws(()=>review(p));assert.throws(()=>review(points([1]),2,1));});
test('old VESC CSV without Hall preserves unavailable channel; no fault claim',()=>{const csv='T;I1;I2;I3;V1;V2;V3;I_tot;V_zero;Phase\n0;0;0;0;0;0;0;0;0;10\n0.01;0;0;0;0;0;0;0;0;20';const r=parse(csv,'synthetic.csv');assert.equal(r.complete,null);const a=review(r.points);assert.equal(a.missing,2);assert.equal(a.counts[0],0);assert.equal(a.transitions,0);});
test('review never mutates source or interpolates skipped transitions',()=>{const p=points([1,6,1]),before=structuredClone(p);const r=review(p);assert.deepEqual(p,before);assert.equal(r.transitions,2);assert.equal(r.count,3);});
@@ -0,0 +1,48 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,review,samples,plot,log;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});review=await server.ssrLoadModule('../../plugins/vesc/frontend/src/sampleReview.ts');samples=await server.ssrLoadModule('../../plugins/vesc/frontend/src/samples.ts');plot=await server.ssrLoadModule('../../plugins/vesc/frontend/src/SignalPlot.tsx');log=await server.ssrLoadModule('../../plugins/vesc/frontend/src/logAnalysis.ts');});
after(async()=>{await server?.close();});
const row=i=>({index:i,i1:Math.sin(2*Math.PI*125*i/2000),i2:0,i3:0,v1:1,v2:2,v3:3,v0:4,current:0,switching_hz:20000,commutation:2,hall:3,phase_deg:180,dt_s:.0005,indexed:false,third_current_measured:false});
const passport=()=>({schema:'missioncore.vesc.sample-data/v1',identity:{uuid:'00112233445566778899AABB',hardware:'SYNTHETIC',version:'5.02'},session:'synthetic-usb-1',state:{capture_id:'synthetic-1',state:'complete',received:128,expected:128,mode:1,count:128,decimation:10,malformed:0},rows:Array.from({length:128},(_,i)=>row(i))});
const parse=v=>review.parseSampleRecord(JSON.stringify(v),'fixture.json');
const filter=extra=>({...review.defaultSampleFilter,...extra});
test('passport preserves source identity, approximate cadence and calculated-current provenance',()=>{const p=parse(passport());assert.equal(p.uuid,'00112233445566778899AABB');assert.equal(p.firmware,'5.02');assert.equal(p.points[1].at,.5);assert.equal(p.complete,true);assert.equal(p.thirdMeasured,false);assert.equal(p.capture,'synthetic-1');});
test('partial/unverified passports cannot be mistaken for full captures',()=>{for(const state of ['incomplete','unverified','timeout','cancelled']){const v=passport();v.state.state=state;v.state.expected=2000;assert.equal(parse(v).complete,false);}});
test('damaged, oversized or contradictory passports fail closed',()=>{
for(const change of [v=>v.schema='other',v=>v.rows[1].index=4,v=>v.rows[1].i1='3',v=>v.rows[1].i1=null,v=>v.rows[1].dt_s=-1,v=>v.rows[1].dt_s=2,v=>v.rows[1].hall=8,v=>v.state.received=100,v=>v.state.expected=2000,v=>v.state.malformed=1,v=>v.identity.uuid='wrong',v=>v.rows=[],v=>v.rows=Array.from({length:2001},(_,i)=>row(i)),v=>v.state.state='constructor']){const v=passport();change(v);assert.throws(()=>parse(v));}
assert.throws(()=>review.parseSampleRecord(' '.repeat(4*1024*1024+1),'huge'));assert.throws(()=>review.parseSampleRecord('{','bad'));
});
test('legacy CSV never borrows connected-controller identity; missing signals stay absent',()=>{
const csv='T;I1;I2;I3;V1;V2;V3;I_tot;V_zero;Phase\n0;1;2;-3;4;5;6;7;8;180;\n0.0001;2;3;-5;4;5;6;7;8;181;';
const p=review.parseSampleRecord(csv,'old.csv');assert.equal(p.uuid,null);assert.equal(p.complete,null);assert.equal(p.thirdMeasured,null);assert.equal(p.points[1].at,.1);assert.equal(p.points[1].values.hall,undefined);assert.equal(p.points[0].values.i3,-3);
assert.equal(review.parseSampleRecord(samples.sampleCsv([row(0),row(1)]),'own.csv').points[1].values.hall,3);
});
test('FIR matches Tool frequency-bin inverse transform and Hamming window',()=>{
const expected=[0,.03661165235168156,.125,.21338834764831843,.25,.21338834764831843,.125,.03661165235168156];
const actual=review.filterCoefficients(filter({kind:'fir',bits:3,cutoff:.125,hamming:false}));actual.forEach((v,i)=>assert.ok(Math.abs(v-expected[i])<1e-12,`${i}: ${v}`));
const windowed=review.filterCoefficients(filter({kind:'fir',bits:3,cutoff:.125,hamming:true}));windowed.forEach((v,i)=>assert.ok(Math.abs(v-expected[i]*(.54-.46*Math.cos(2*Math.PI*i/7)))<1e-12));
assert.deepEqual(review.filterCoefficients(filter({kind:'mean',bits:2})),[.25,.25,.25,.25]);
for(const extra of [{bits:0},{bits:11},{cutoff:NaN},{cutoff:.6}])assert.throws(()=>review.filterCoefficients(filter({kind:'fir',...extra})));
});
test('Tool convolution and delay preserve unsupported edges as gaps, never zeros',()=>{
const points=Array.from({length:12},(_,i)=>({at:i,values:{i1:i,hall:i%8},gap:false}));
const centered=review.filteredSamplePoints(points,'i1',filter({kind:'mean',bits:2}));assert.equal(centered[0].value,null);assert.equal(centered[1].value,null);assert.equal(centered[2].value,1.5);assert.equal(centered[9].value,8.5);assert.equal(centered[10].value,null);
const delayed=review.filteredSamplePoints(points,'i1',filter({kind:'mean',bits:2,compensate:false}));assert.equal(delayed[3].value,null);assert.equal(delayed[4].value,1.5);assert.equal(delayed[11].value,8.5);
assert.equal(review.filteredSamplePoints(points,'hall',filter({kind:'mean',bits:2}))[0].value,0);
const absent=review.filteredSamplePoints(points.slice(0,4),'i1',filter({kind:'mean',bits:2}));assert.ok(absent.every(p=>p.value===null));
points[3].values.i1=null;assert.equal(review.filteredSamplePoints(points,'i1',filter({kind:'mean',bits:2}))[2].value,null);
points[3].values.i1=3;points[3].at=3.2;assert.equal(review.filteredSamplePoints(points,'i1',filter({kind:'mean',bits:2}))[2].value,null);
});
test('cursors use nearest real sample, keep holes and outside-record requests empty',()=>{
const points=[{at:0,value:1},{at:.1,value:null},{at:.2,value:3}];let m=review.sampleMeasurement(points,0,.2,.01,.19);assert.equal(m.first.at,0);assert.equal(m.second.at,.2);assert.equal(m.delta,2);assert.equal(m.dt,.2);assert.equal(m.count,2);assert.equal(m.rms,Math.sqrt(5));
m=review.sampleMeasurement(points,0,1,.1,.8);assert.equal(m.first,null);assert.equal(m.second,null);assert.equal(m.delta,null);
});
test('submillisecond samples occupy full plot width instead of collapsing to the left',()=>{const view=plot.signalView([{at:0,value:1},{at:.01,value:2}],0,.01);assert.equal(view.segments[0][0].x,64);assert.equal(view.segments[0][1].x,780);});
test('filtering keeps frequency and rejects FFT over missing edges',()=>{
const points=samples.samplePoints(Array.from({length:1024},(_,i)=>row(i))),filtered=review.filteredSamplePoints(points,'i1',filter({kind:'mean',bits:3}));
const mapped=filtered.map(p=>({at:p.at,values:{i1:p.value},gap:p.value===null}));assert.throws(()=>log.spectrum(mapped,'i1',0,512));const fft=log.spectrum(mapped,'i1',4,500);assert.ok(Math.abs(fft.peak.hz-125)<1e-8);
});
test('responsive plot uses the measured viewport width without shrinking axis type',()=>{const points=[{at:0,value:1},{at:1,value:2}];for(const width of [320,480,960]){const v=plot.signalView(points,0,1,160,width);assert.equal(v.segments[0][0].x,64);assert.equal(v.segments[0][1].x,width-20);}});
@@ -0,0 +1,25 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,samples,log;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});samples=await server.ssrLoadModule('../../plugins/vesc/frontend/src/samples.ts');log=await server.ssrLoadModule('../../plugins/vesc/frontend/src/logAnalysis.ts');});
after(async()=>{await server?.close();});
const row=i=>({index:i,i1:Math.sin(2*Math.PI*125*i/2000),i2:0,i3:0,v1:1,v2:2,v3:3,v0:4,current:0,switching_hz:20000,commutation:2,hall:3,phase_deg:180,dt_s:.0005,indexed:false,third_current_measured:false});
test('sample time uses decimated cadence and FFT resolves high frequency',()=>{
const points=samples.samplePoints(Array.from({length:1024},(_,i)=>row(i)));
assert.ok(Math.abs(points[1].at-.5)<1e-9);
const fft=log.spectrum(points,'i1',0,512);assert.ok(Math.abs(fft.peak.hz-125)<1e-8);
const csv=samples.sampleCsv([row(0),row(1)]);assert.ok(csv.startsWith('T;I1;I2;I3;'));assert.ok(csv.split('\n')[2].startsWith('0.0005;'));
assert.ok(csv.split('\n')[0].includes('Hall;Commutation;F_sw'));
});
test('malformed samples cannot become false zero traces',()=>{
for(const rows of [[{...row(0),i1:NaN}],[{...row(0),dt_s:0}],[row(1)],Array.from({length:2001},(_,i)=>row(i))])assert.throws(()=>samples.samplePoints(rows));
});
test('native Sample Data CSV imports the original asymmetric trailing delimiter',()=>{
const header='T;I1;I2;I3;V1;V2;V3;I_tot;V_zero;Phase';
const original=header+'\n0;1;2;-3;4;5;6;7;8;180;\n0.0001;2;3;-5;4;5;6;7;8;181;';
const parsed=log.parseVescLog(original);assert.equal(parsed.format,'VESC Tool · Sample Data');assert.equal(parsed.duration,.1);assert.equal(parsed.points[1].values.I3,-5);assert.equal(parsed.uuid,null);
const current=log.parseVescLog(samples.sampleCsv([row(0),row(1)]));assert.equal(current.points[1].values.Hall,3);assert.equal(current.duration,.5);
assert.throws(()=>log.parseVescLog(header+'\n0;1;2;3;4;5;6;7;8;9\n0;1;2;3;4;5;6;7;8;9'));
});
@@ -0,0 +1,45 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,config,editor;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
config=await server.ssrLoadModule('../../plugins/vesc/frontend/src/configuration.ts');
editor=await server.ssrLoadModule('../../plugins/vesc/frontend/src/VescParameterEditor.tsx');
});
after(async()=>{await server?.close();});
const parameter={name:'current_max',title:'Motor current',type:'number',value:0.35,editor_scale:100,decimals:1,suffix:'%',transmittable:true};
test('native editor scale and units display without changing stored values',()=>{
assert.equal(config.parameterValue(parameter),'35 %');assert.equal(parameter.value,0.35);
assert.equal(config.parameterValue({...parameter,type:'enum',value:1,options:['Disabled','FOC']}),'FOC');
assert.equal(config.parameterValue({...parameter,type:'boolean',value:false}),'Выключено');
});
test('search reaches native names across groups and ignores separator pseudo parameters',()=>{
const other={...parameter,name:'app_mode',title:'Application mode'};
const schema={parameters:[parameter,other],groups:[{name:'general',subgroups:[{name:'limits',parameters:['::sep::Motor','current_max']}]}]};
assert.deepEqual(config.groupedParameters(schema,'general',''),[parameter]);
assert.deepEqual(config.groupedParameters(schema,'general','app_mode'),[other]);
assert.deepEqual(config.groupedParameters(schema,'all','missing'),[]);
});
test('unknown upstream groups remain accessible after an engine update',()=>{
assert.equal(config.groupLabel('foc'),'FOC');assert.equal(config.groupLabel('future_device'),'future_device');
});
test('subgroups preserve upstream order and hide unrelated fields by default',()=>{
const first={...parameter,name:'first'},second={...parameter,name:'second'};
const schema={parameters:[first,second],groups:[{name:'general',subgroups:[{name:'current',parameters:['::sep::Current','second','first']},{name:'voltage',parameters:['first']}]}]};
assert.deepEqual(config.groupedParameters(schema,'general','','current'),[second,first]);
assert.deepEqual(config.groupedParameters(schema,'general','','voltage'),[first]);
});
test('typed editor converts display units back to firmware values and rejects invalid input',()=>{
const p={...parameter,min:0,max:1};
assert.equal(editor.initialDraft(p),'35');
assert.deepEqual(editor.parseDraft(p,'42,5'),{value:0.425,error:null});
for(const value of ['', 'Infinity', 'NaN', '101', '-1'])assert.ok(editor.parseDraft(p,value).error);
assert.ok(editor.parseDraft({...p,type:'integer',min:0,max:100},'1.2').error);
assert.ok(editor.parseDraft({...p,type:'enum',options:['a','b']},'2').error);
assert.ok(editor.parseDraft({...p,type:'bitfield'},'256').error);
assert.equal(editor.parseDraft({...p,type:'boolean'},false).value,false);
assert.ok(editor.parseDraft({...p,type:'string',max_length:4},'longer').error);
});
@@ -0,0 +1,79 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
const load=async name=>{
const source=readFileSync(new URL(`../../../plugins/vesc/frontend/src/${name}.ts`,import.meta.url),'utf8');
return import('data:text/javascript;base64,'+Buffer.from(ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText).toString('base64'));
};
const {VescTrace,traceView,traceCsv,TRACE_LIMIT}=await load('trends');
const {TraceObserver}=await load('traceObserver');
const frame=(sample=1000,extra={})=>({fresh:true,instance:'source',devices:[{id:'device',uuid:'ABC',session_id:'session',sample_time_ms:sample,observed_at:'2026-10-18T10:00:00Z',age_ms:0,values:{input_voltage_v:48,input_current_a:2,duty:.25,erpm:0},...extra}]});
test('native values retain units; missing/non-finite measurements never become zero',()=>{
const t=new VescTrace();assert.equal(t.accept(frame(), 'device','abc',1000,0),true);
assert.equal(t.points[0].values.duty,25);assert.equal(t.points[0].values.input_power_w,96);
assert.equal(t.points[0].values.motor_temperature_c,undefined);
const v=traceView(t.points,'motor_temperature_c',0,2000);assert.equal(v.count,0);assert.equal(v.min,null);
t.accept(frame(1100,{values:{input_voltage_v:NaN,erpm:Infinity,duty:false}}),'device','abc',1100,0);
assert.equal(t.points.at(-1).values,null);
});
test('duplicate/reordered samples do not extend freshness or add fake flat-line points',()=>{
const t=new VescTrace();t.accept(frame(),'device','abc',1000,0);
t.accept(frame(),'device','abc',1700,0);t.accept(frame(900),'device','abc',1800,0);
assert.equal(t.points.length,1);assert.equal(t.freshUntil,2500);
t.accept(frame(),'device','abc',2501,0);assert.equal(t.points.at(-1).values,null);
for(let i=0;i<10;i++)t.gap(2600+i);assert.equal(t.points.length,2);
});
test('USB sessions, service restarts and missing frames cannot join plot segments',()=>{
const t=new VescTrace();t.accept(frame(),'device','abc',1000,0);t.accept(frame(1300),'device','abc',1300,0);
t.accept(frame(1600,{session_id:'new-session'}),'device','abc',1600,0);
t.accept({...frame(1,{session_id:'new-session'}),instance:'restarted'},'device','abc',1900,0);
t.gap(2100);t.accept(frame(400,{session_id:'new-session'}),'device','abc',2200,0);
const v=traceView(t.points,'erpm',0,3000);assert.equal(v.segments.length,4);
assert.equal(t.points.filter(p=>p.values===null).length,3);
});
test('identity ambiguity, stale transport, missing timestamps and slow HTTP fail closed',()=>{
const invalid=[{...frame(),fresh:false},{...frame(),instance:''},{...frame(),devices:frame().devices.concat(frame().devices)},
frame(1000,{uuid:'other'}),frame(1000,{session_id:''}),frame(1000,{age_ms:1600}),frame(1000,{age_ms:-1}),
frame(undefined,{sample_time_ms:undefined}),frame(1000,{observed_at:'broken'})];
for(const f of invalid){const t=new VescTrace();assert.equal(t.accept(f,'device','abc',1000,0),false);assert.equal(t.points.length,0);}
const t=new VescTrace();assert.equal(t.accept(frame(),'device','abc',1000,1500),false);
});
test('timestamp gap creates a break even when no explicit disconnect arrived',()=>{
const t=new VescTrace();t.accept(frame(),'device','abc',1000,0);t.accept(frame(3100),'device','abc',3100,0);
assert.equal(traceView(t.points,'erpm',0,4000).segments.length,2);
});
test('rolling trace is bounded by count, time and UTC day; clear resets sample identity',()=>{
const t=new VescTrace();for(let i=0;i<2500;i++)t.accept(frame(i),'device','abc',i,0);
assert.equal(t.points.length,TRACE_LIMIT);t.prune(400000);assert.equal(t.points.length,0);
t.accept(frame(400001),'device','abc',400001,0);t.prune(400002,'2099-01-01');assert.equal(t.points.length,0);
t.accept(frame(400003),'device','abc',400003,0);t.clear();assert.equal(t.accept(frame(1),'device','abc',1,0),true);
});
test('CSV records gaps, session provenance, empty absent fields and escaped spreadsheet text',()=>{
const t=new VescTrace();t.accept(frame(),'device','abc',1000,0);t.gap(2000);
const csv=traceCsv(t.points,{uuid:'abc',hardware:'=cmd,"bad"',version:'5.02'});
assert.match(csv,/duty \[%\]/);assert.match(csv,/"gap"/);assert.match(csv,/"session"/);assert.match(csv,/"'=cmd,""bad"""/);
assert.equal(csv.split('\r\n').length,4);assert.doesNotMatch(csv,/undefined|NaN|Infinity/);
});
test('observer is single-flight, suppresses late results after close and aborts owned read',async t=>{
t.mock.timers.enable({apis:['setInterval','setTimeout']});
let resolve,calls=0,signal;const received=[];
const observer=new TraceObserver(s=>{calls++;signal=s;return new Promise(r=>resolve=r);},v=>received.push(v),()=>{},()=>true,()=>1000);
await Promise.resolve();t.mock.timers.tick(1000);assert.equal(calls,1);
observer.close();assert.equal(signal.aborted,true);resolve(frame());await Promise.resolve();await Promise.resolve();assert.equal(received.length,0);
t.mock.timers.tick(5000);assert.equal(calls,1);
});
test('hidden view starts no requests; aborted/expired read never delivers a stale frame',async t=>{
t.mock.timers.enable({apis:['setInterval','setTimeout']});
let visible=false,calls=0,resolve,signal;const received=[];
const observer=new TraceObserver(s=>{calls++;signal=s;return new Promise(r=>resolve=r);},v=>received.push(v),()=>{},()=>visible,()=>1000);
await Promise.resolve();assert.equal(calls,0);visible=true;t.mock.timers.tick(500);await Promise.resolve();assert.equal(calls,1);
t.mock.timers.tick(1201);assert.equal(signal.aborted,true);resolve(frame());await Promise.resolve();await Promise.resolve();
assert.equal(received.filter(Boolean).length,0);observer.close();
});
test('pause retains the last numeric value as historical and expanded plot uses full height',()=>{
const t=new VescTrace();t.accept(frame(),'device','abc',1000,0);t.gap(1400);
const a=traceView(t.points,'input_voltage_v',0,2000,180),b=traceView(t.points,'input_voltage_v',0,2000,384);
assert.equal(a.last,48);assert.equal(t.freshUntil,-Infinity);assert.ok(b.segments[0][0].y>a.segments[0][0].y);
});