feat(k1): add USB networking, device management and acquisition recovery

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 00:42:57 +03:00
parent 14c3c7c2b6
commit 038337783f
78 changed files with 4612 additions and 384 deletions
@@ -4,10 +4,11 @@ import {createElement} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {createServer} from './support/vite-server.mjs';
let server,Detail,presentation,enrolledDevice;
let server,Detail,presentation,enrolledDevice,ObservationAction;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
({K1Detail:Detail}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/K1Detail.tsx'));
({K1ObservationAction:ObservationAction}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/K1ObservationAction.tsx'));
presentation=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/presentation.ts');
({enrolledDevice}=await server.ssrLoadModule('../../packages/sensor-ui/src/contracts.ts'));
});
@@ -88,3 +89,47 @@ test('completed scan with healthy control remains connected and permits a named
assert.doesNotMatch(markup,/Проверить состояние K1|Подключить устройство|Устройство остановлено/);
assert.equal(presentation.k1Status(stopped,false).tone,'neutral');
});
test('observation Play only opens configuration; active acquisition offers its existing controls',()=>{
let opened=0;
const action=ObservationAction({device,fresh:true,configure:()=>opened++});
assert.equal(action.props.label,'Начать сканирование K1');assert.equal(action.props.children.props.name,'play');
action.props.onClick();assert.equal(opened,1);
assert.equal(ObservationAction({device,fresh:false,configure:()=>opened++}),null);
const active={...device,snapshot:{...device.snapshot,acquisition:'streaming'}};
let stopped=0;const stop=ObservationAction({device:{...active,control:{...active.control,can_stop:true}},fresh:true,stop:()=>stopped++});
assert.equal(stop.props.label,'Остановить сканирование K1');stop.props.onClick();assert.equal(stopped,1);assert.equal(opened,1);
});
test('observation configuration preserves START fields and STOP without a duplicate media viewer',()=>{
for(const acquisition of ['idle','starting','streaming','stopping']){
const value={...device,snapshot:{...device.snapshot,acquisition}};
const markup=renderToStaticMarkup(createElement(Detail,{device:value,enabled:true,previewEnabled:false,backLabel:'Вернуться к наблюдению',transport:{},back:()=>{},refresh:async()=>{},failure:()=>{},createRerunHost:()=>assert.fail('must not allocate another viewer')}));
assert.match(markup,/Вернуться к наблюдению/);assert.doesNotMatch(markup,/rerun-viewport__canvas|Открыть пространственную сцену/);
if(acquisition==='idle')assert.match(markup,/Название проекта/);
if(acquisition==='streaming')assert.match(markup,/Остановить устройство/);
}
});
test('observation gear contains only acquisition controls, including before START',()=>{
for(const acquisition of ['idle','streaming']){
const value={...device,snapshot:{...device.snapshot,acquisition}};
const markup=renderToStaticMarkup(createElement(Detail,{device:value,enabled:true,previewEnabled:false,sceneProfile:{view:'plan',save:()=>{}},transport:{},back:()=>{},refresh:async()=>{},failure:()=>{}}));
assert.doesNotMatch(markup,/Размер точки|Атрибут цвета|Палитра|rerun-viewport__canvas/);
if(acquisition==='idle')assert.match(markup,/Название проекта/);
else assert.match(markup,/Остановить устройство/);
}
});
test('K1 storage shows used percentage and expires independently of a fresh inventory',()=>{
const now=Date.now(),observed_at=new Date(now-1000).toISOString();
const almostFull={...device,storage_status:{used_percent:98.99,observed_at}};
assert.equal(presentation.k1StorageStatus(almostFull,true,now+18000).tone,'warning');
const status=presentation.k1StorageStatus(almostFull,true,now);
assert.equal(status.tone,'warning');assert.match(status.label,/занято 99 %.*мало свободного места/);
assert.match(render(almostFull),/Хранилище K1: занято 99 %/);
for(const [value,fresh,at] of [[almostFull,false,now],[{...almostFull,online:false},true,now],[almostFull,true,now+20000],[{...device,storage_status:null},true,now]]){
const unavailable=presentation.k1StorageStatus(value,fresh,at);
assert.equal(unavailable.tone,'neutral');assert.match(unavailable.label,/нет свежих данных/);assert.doesNotMatch(unavailable.label,/99/);
}
assert.equal(presentation.k1StorageStatus({...device,storage_status:{used_percent:0,observed_at}},true,now).tone,'neutral');
});
@@ -0,0 +1,46 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createElement} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {createServer} from './support/vite-server.mjs';
let server,Observation;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',plugins:[{
name:'inline-observation-portals-for-ssr',enforce:'pre',
transform(code,id){
if(id.endsWith('/K1Observation.tsx')||id.endsWith('/ObservationHeader.tsx'))
return code.replace("import {createPortal} from 'react-dom';","import {cloneElement as portalChild} from 'react'; const createPortal=(child: any,_target: unknown,key?: string)=>child&&key?portalChild(child,{key}):child;");
},
}]});
({K1Observation:Observation}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/K1Observation.tsx'));
});
after(async()=>{await server?.close();});
const render=(acquisition,enabled)=>renderToStaticMarkup(createElement(Observation,{
device:{id:'synthetic-k1',name:'K1',online:enabled,verified:enabled,
control:{can_stop:true,acquisition_id:'same-acquisition'},
snapshot:{acquisition,context:{session_id:'same-session'}}},
transport:{},enabled,fresh:enabled,views:[{id:'points',target:{},statusTarget:{},actionsTarget:{}}],
createRerunHost:()=>assert.fail('server rendering must not allocate a viewer'),
}));
test('an ongoing acquisition retains the spatial surface during a link gap while STOP is disabled',()=>{
const online=render('streaming',true),offline=render('streaming',false);
for(const markup of [online,offline]){
assert.match(markup,/rerun-viewport__canvas/);
assert.match(markup,/Окно накопления облака точек/);
assert.match(markup,/Позиция воспроизведения/);
assert.match(markup,/ЭФИР/);
assert.doesNotMatch(markup,/буфер не включён/);
assert.match(markup,/Следовать за K1/);
assert.doesNotMatch(markup,/data-viewer-controls/);
assert.match(markup,/data-pulse="true"/);
}
const stop=offline.match(/<button\b[^>]*aria-label="Остановить сканирование K1"[^>]*>/)?.[0];
assert.ok(stop);assert.match(stop,/disabled=""/);
assert.doesNotMatch(offline,/Инициировать запуск/);
});
test('completed or never-started acquisitions do not retain an active spatial surface',()=>{
for(const acquisition of ['idle','failed'])
assert.doesNotMatch(render(acquisition,false),/rerun-viewport__canvas/);
});
@@ -49,7 +49,7 @@ test('source age expires even when metadata repeats, old frames never look live'
assert.equal(gate.fresh,false);
gate.receive({type:'lidar-state',sequence:1,age_ms:250,points:3});
assert.equal(gate.fresh,true);assert.equal(gate.points,3);
now+=1800;gate.receive({type:'lidar-state',sequence:1,age_ms:0,points:3});
now+=4800;gate.receive({type:'lidar-state',sequence:1,age_ms:0,points:3});
assert.equal(gate.fresh,false);
gate.receive({type:'lidar-state',sequence:2,age_ms:9000,points:3});
assert.equal(gate.fresh,false);
@@ -58,6 +58,19 @@ test('source age expires even when metadata repeats, old frames never look live'
assert.throws(()=>gate.receive({type:'lidar-state',sequence:4,age_ms:-1,points:4}));
});
test('budgeted cloud accepts a three-second delivery without making an old frame live forever',()=>{
let now=10000;const gate=previewFreshness(()=>now);
gate.receive({type:'lidar-state',sequence:1,age_ms:3000,points:394});
assert.equal(gate.fresh,true);
now+=1999;assert.equal(gate.fresh,true);
gate.receive({type:'lidar-state',sequence:1,age_ms:0,points:394});
now++;assert.equal(gate.fresh,false);
gate.receive({type:'lidar-state',sequence:2,age_ms:null,points:394});
assert.equal(gate.fresh,false);
gate.receive({type:'lidar-state',sequence:3,age_ms:5000,points:394});
assert.equal(gate.fresh,false);
});
test('onboard camera admits immediate sourceopen and ignores callbacks after close',()=>{
const saved={media:globalThis.MediaSource,create:URL.createObjectURL,revoke:URL.revokeObjectURL};
let source,buffer,appended=0,ready=0,failed=0;
@@ -0,0 +1,20 @@
import assert from 'node:assert/strict';
import {readdir,readFile} from 'node:fs/promises';
import test from 'node:test';
import ts from 'typescript';
test('K1 sensor surfaces cannot introduce browser-default explanatory paragraphs',async()=>{
const root=new URL('../../../plugins/xgrids-k1/frontend/src/sensors/',import.meta.url);
const files=(await readdir(root)).filter(name=>name.endsWith('.tsx'));
for(const name of files){
const text=await readFile(new URL(name,root),'utf8');
const source=ts.createSourceFile(name,text,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);
function inspect(node){
if((ts.isJsxOpeningElement(node)||ts.isJsxSelfClosingElement(node))&&node.tagName.getText(source)==='p'){
assert.ok(node.attributes.properties.some(p=>ts.isJsxAttribute(p)&&p.name.text==='className'),`${name}: explanatory copy must use Description; only explicitly styled viewport/data paragraphs may remain`);
}
ts.forEachChild(node,inspect);
}
inspect(source);
}
});
@@ -232,3 +232,74 @@ test('legacy resolution failure invalidates the form before a second stale submi
assert.equal(api.enrollmentBluetoothFailure(state),true);
assert.match(api.enrollmentNotice(state),/Найдите K1 ещё раз/);
});
test('saved Bridge recovery needs no BLE candidate and dispatches exactly one existing Verify',async()=>{
const before={...initial,selected_device_id:null,candidates:[],discovery_generation:0,mode_revision:3,
reconnect_target:{device_id:'saved-k1',source:'durable-configured-state'},
allowed_actions:['observe-configured-device-network'],acquisition_recovery:{state:'active'}};
const commands=[];
const transport={submit:async command=>{commands.push(command);return {state:'complete',operation_id:command.operation_id,
result:{...before,snapshot_revision:2,selected_device_id:'saved-k1',connected:true,
device_session:{device_id:'saved-k1',device_session_id:'new-live-session'},
command_result:{operation_id:command.operation_id,status:'succeeded',action:'verify'}}};}};
const result=await api.enroll(transport,before,'verify',{device_id:before.reconnect_target.device_id,discovery_generation:0,mode_revision:3});
assert.equal(api.enrollmentAllowed(before,'verify'),true);
assert.equal(api.enrollmentAllowed(before,'connect'),false);
assert.equal(commands.length,1);assert.equal(commands[0].action,'verify');
assert.deepEqual(commands[0].parameters,{device_id:'saved-k1',discovery_generation:0,mode_revision:3});
assert.equal(api.enrollmentProof(result,'saved-k1').session,'new-live-session');
});
test('unreachable K1 reports power and network checks without claiming power-off or live scanning',()=>{
const before={...initial,connected:false,acquisition_recovery:{state:'active'}};
assert.match(api.enrollmentRecoveryNotice(before),/не подтверждена/);
for(const code of ['connection-verify-device-not-rediscovered','connection-verify-mqtt-unreachable','connection-verify-status-read-timeout']){
const value={...before,verification:{status:'failed',error_code:code}};
const message=api.enrollmentRecoveryNotice(value);
assert.match(message,/Проверьте питание/);assert.match(message,/сети/);
assert.doesNotMatch(message,/K1 выключен|съёмка продолжается|съёмка завершена/);
assert.equal(api.enrollmentRecoveryNotice(JSON.parse(JSON.stringify(value))),message);
}
assert.match(api.enrollmentRecoveryNotice({...before,connected:true,acquisition_recovery:{state:'ceased'}}),/Предыдущая съёмка завершена/);
assert.match(api.enrollmentRecoveryNotice({...before,fresh:false}),/Нет свежих сведений с БК/);
});
test('onboard reset uses the existing CAS outcome without automatic Scan, Verify or provisioning',async()=>{
const before={...initial,can_reset:true,supported_actions:['reset'],mode_revision:4};const commands=[];
assert.equal(api.enrollmentAllowed(before,'reset'),true);
assert.equal(api.enrollmentAllowed({...before,supported_actions:undefined},'reset'),false);
assert.equal(api.enrollmentAllowed({...before,can_reset:undefined},'reset'),false);
const transport={submit:async command=>{commands.push(command);return {state:'complete',operation_id:command.operation_id,result:{...before,mode_revision:5,snapshot_revision:2,connected:false,command_result:{operation_id:command.operation_id,action:'reset',status:'succeeded'}}};}};
const result=await api.enroll(transport,before,'reset',{mode_revision:4});
assert.equal(result.mode_revision,5);assert.equal(commands.length,1);assert.equal(commands[0].action,'reset');
assert.deepEqual(commands[0].parameters,{mode_revision:4});
transport.submit=async command=>({state:'complete',operation_id:command.operation_id,result:before});
await assert.rejects(api.enroll(transport,before,'reset',{mode_revision:4}),/не подтверждён/);
});
test('terminal enrollment without a driver result releases the observer without waiting or replay',async()=>{
for(const action of ['connect','verify']){
for(const state of ['unknown','failed','rejected']){
let posts=0,reads=0,pauses=0,clock=Date.now();
const transport={
submit:async command=>{posts++;return {operation_id:command.operation_id,state,error:'Действие K1 не подтверждено.'};},
operation:async()=>{throw new Error('terminal delivery must not be polled again');},
state:async()=>{reads++;return {...initial,connected:true};},
};
const parameters={device_id:'synthetic-ble',...(action==='connect'?{password:crypto.randomUUID()}: {})};
await assert.rejects(api.enroll(transport,initial,action,parameters,{
now:()=>clock,pause:async()=>{pauses++;clock+=100000;},
}),/Действие K1 не подтверждено/);
assert.deepEqual({posts,reads,pauses},{posts:1,reads:0,pauses:0});
assert.equal('password' in parameters,false);
}
}
});
test('unknown delivery with a correlated running result still observes the owned bootstrap',async()=>{
const f=fixture(),submit=f.transport.submit;
f.transport.submit=async command=>({...await submit(command),state:'unknown'});
const result=await api.enroll(f.transport,initial,'connect',f.parameters,f.observer);
assert.equal(result.connected,true);
assert.deepEqual(f.counts(),{posts:1,reads:1});
});