feat(observatory): persist scene profiles and stable device view bindings

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 00:42:56 +03:00
parent b7b5ac9cf0
commit 14c3c7c2b6
33 changed files with 408 additions and 71 deletions
@@ -4,6 +4,8 @@ import {Button,DockHandle,GlassSurface,Icon,IconButton,LoadingRegion,Select,Stat
import {useDevicePluginHost} from '../../../core/device-plugins/DevicePluginHost';
import {createFleetSensorTransport} from '../../../core/fleet/sensorTransport';
import {moveObservation,withObservationTree,orderedObservationIDs,observationTree} from '../../../core/fleet/observationLayout';
import {bindObservationLayout} from '../../../core/fleet/observationBinding';
import {useSpatialDefaults} from '../../../core/observation/useSpatialDefaults';
import {useVehicleObservation} from '../../../core/fleet/useVehicleObservation';
import {observationArrangements,retainDormantObservationTree} from '../../../core/fleet/observationPresets';
import {ObservationLayoutSaveWindow} from '../../../components/observation/ObservationLayoutSaveWindow';
@@ -11,8 +13,9 @@ import {createIsolatedRerunHost} from '../../../components/rerun/isolatedRerunHo
import {CameraObservation} from '../../../../../../packages/sensor-ui/src/CameraObservation';
import {cameraObservationViews,observationKey,type SensorObservationView,type ObservationHeaderTargets} from '../../../../../../packages/sensor-ui/src/observation';
import {unboundObservationViews} from '../../../../../../packages/sensor-ui/src/observationCatalog';
import {sensorContribution} from '../../../../../../packages/sensor-ui/src/extensions';
import {sensorContribution,wirelessContributions} from '../../../../../../packages/sensor-ui/src/extensions';
import {ObservationDeviceSettings} from './ObservationDeviceSettings';
import {ObservationConnectionWindow} from './ObservationConnectionWindow';
import {ObservationPanelHeader} from './ObservationPanelHeader';
import {ObservationDeck,ObservationMount} from './ObservationDeck';
import {ObservationMap} from './ObservationMap';
@@ -25,28 +28,42 @@ import {RoverLogs} from '../../../components/rover/RoverLogs';
import {useRoverDiagnostics} from '../../../core/fleet/useRoverDiagnostics';
import {useRoverControl} from '../../../core/fleet/useRoverControl';
import {roverObservationStatus} from '../../../core/fleet/roverObservation';
import {observationPortal} from '../../../core/observation/observationPortal';
export function BoardObservationCenter({vehicleID,name,enabled,paired,back,configure,headerToolsHost}:{vehicleID:string;name:string;enabled:boolean;paired:boolean;back:()=>void;configure:()=>void;headerToolsHost?:HTMLElement|null}){
const diagnostics=useRoverDiagnostics(vehicleID);
const [devOpen,setDevOpen]=useState(false);
const [primaryCamera,setPrimaryCamera]=useState<string|null>(null),primaryRef=useRef<string|null>(null);
const {registry}=useDevicePluginHost(),transport=useMemo(()=>createFleetSensorTransport(vehicleID),[vehicleID]);
const inventory=useObservationInventory(transport),presets=useVehicleObservation(vehicleID);
const {inventory,refresh}=useObservationInventory(transport),presets=useVehicleObservation(vehicleID);
const {layout,setLayout}=presets;
const spatialDefaults=useSpatialDefaults();
const [saving,setSaving]=useState(false),[editing,setEditing]=useState<string|null>(null);
const edited=presets.presets.find(p=>p.id===editing);
const [settingsView,setSettingsView]=useState('points');
const [settingsDevice,setSettingsDevice]=useState<string|null>(null);
const [connectingKind,setConnectingKind]=useState<string|null>(null);
const wireless=wirelessContributions(registry.sensorContributions);
const connect=(kind:string)=>{setSettingsDevice(null);setConnectingKind(kind);};
const reconnect=(kind:string|undefined)=>kind&&transport.enrollment&&wireless.some(item=>item.kind===kind)?()=>connect(kind):undefined;
const [layersOpen,setLayersOpen]=useState(false);
const [full,setFull]=useState<string|null>(null),[expanded,setExpanded]=useState(false);
const frame=useRef<HTMLDivElement>(null),[portal]=useState(()=>document.createElement('div'));
useLayoutEffect(()=>{(expanded?document.body:frame.current!).append(portal);return()=>portal.remove();},[expanded,portal]);
const portalOwner=useRef<ReturnType<typeof observationPortal>|null>(null);
useLayoutEffect(()=>{const owner=observationPortal(portal,frame.current!,document.body);portalOwner.current=owner;return()=>{portalOwner.current=null;owner.dispose();};},[portal]);
useLayoutEffect(()=>{portalOwner.current?.setExpanded(expanded);},[expanded]);
const mounts=useRef(new Map<string,HTMLElement>()),media=useRef(new Map<string,HTMLElement>()),headers=useRef(new Map<string,ObservationHeaderTargets>());
const groups=(inventory?.items??[]).flatMap(device=>{
const contribution=sensorContribution(registry.sensorContributions,device)?.observation;
const views=contribution?.views(device)??cameraObservationViews(device);
return views.length?[{device,views,independentMediaLiveness:contribution?contribution.independentMediaLiveness===true:true,Session:contribution?.Session??CameraObservation}]:[];
});
const sources:{key:string;deviceID?:string;catalog?:string;view:SensorObservationView}[]=groups.flatMap(group=>group.views.map(view=>({key:observationKey(group.device.id,view.id),deviceID:group.device.id,view})));
const sceneKeys=groups.flatMap(group=>group.views.filter(view=>view.scene).map(view=>observationKey(group.device.id,view.id)));
useEffect(()=>{if(presets.ready&&spatialDefaults)for(const key of sceneKeys)if(!presets.scenes?.[key])presets.setScene(key,spatialDefaults);},[presets.ready,spatialDefaults,JSON.stringify(sceneKeys)]);
const bindings=groups.filter(group=>groups.filter(other=>other.device.kind===group.device.kind).length===1).flatMap(group=>group.views.map(view=>({from:JSON.stringify(['catalog',group.device.kind,view.id]),to:observationKey(group.device.id,view.id)})));
const bindingKey=JSON.stringify(bindings);
useEffect(()=>{if(!presets.ready)return;setLayout(value=>bindObservationLayout(value,bindings));setFull(value=>bindings.find(item=>item.from===value)?.to??value);},[bindingKey,presets.ready,layout]);
const sources:{key:string;deviceID?:string;kind?:string;catalog?:string;view:SensorObservationView}[]=groups.flatMap(group=>group.views.map(view=>({key:observationKey(group.device.id,view.id),deviceID:group.device.id,kind:group.device.kind,view})));
sources.push(...unboundObservationViews(inventory?.items??[],registry.sensorContributions));
sources.push({key:'map',view:{id:'map',label:'Карта'}},{key:'rover',view:{id:'rover',label:'3D View аппарата'}},{key:'telemetry',view:{id:'telemetry',label:'Телеметрия'}});
if(diagnostics.state.id)sources.push({key:'rover-logs',view:{id:'rover-logs',label:'Логи управления'}});
@@ -60,7 +77,7 @@ export function BoardObservationCenter({vehicleID,name,enabled,paired,back,confi
// own this subscription; the rover transport enforces its own freshness.
const rover=useRoverControl(vehicleID,paired&&(visible.includes('rover')||visible.includes('telemetry')));
const roverObservation=roverObservationStatus(rover.state,rover.connection);
const drivingVisible=visible.includes('rover')&&(!effectiveFull||effectiveFull==='rover')&&!layersOpen&&!settingsDevice&&!devOpen;
const drivingVisible=visible.includes('rover')&&(!effectiveFull||effectiveFull==='rover')&&!layersOpen&&!settingsDevice&&!connectingKind&&!devOpen;
useEffect(()=>{if(!drivingVisible)rover.stop();},[drivingVisible,rover.stop]);
const configuredDevice=inventory?.items.find(device=>device.id===settingsDevice);
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(document.querySelector('[data-docking="true"]'))return;if(event.key!=='Escape'||layersOpen||document.querySelector('[role=dialog], [role=listbox]'))return;if(effectiveFull){setFull(null);event.stopImmediatePropagation();}else if(expanded){setExpanded(false);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull,expanded,layersOpen]);
@@ -73,7 +90,7 @@ export function BoardObservationCenter({vehicleID,name,enabled,paired,back,confi
<div className="observation-deck">{!inventory||!presets.ready?<LoadingRegion loading={!presets.error} label="Получение визуальных источников"/>:visible.length?<ObservationDeck minimumSizes={{telemetry:roverTelemetryMinimum(rover.state)}} ids={visible} focusedId={effectiveFull} mounts={mounts.current} layout={layout} labels={Object.fromEntries(sources.map(source=>[source.key,source.view.label]))} onTreeChange={tree=>setLayout(current=>withObservationTree(current,retainDormantObservationTree(current.tree,tree)))}>
{sources.filter(source=>visible.includes(source.key)).map(source=>createPortal(
<div className="observation-panel">
<GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className="observation-panel__surface observation-panel__surface--overlay">
<GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className={`observation-panel__surface observation-panel__surface--${source.view.header==='flow'?'flow':'overlay'}`}>
<ObservationPanelHeader>
<DockHandle id={source.key} label={source.view.label}/>
<div className="observation-panel__title">{source.key!=='rover'&&<h3 title={source.view.label}>{source.view.label}</h3>}<ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.statusTarget}/></div>
@@ -81,7 +98,7 @@ export function BoardObservationCenter({vehicleID,name,enabled,paired,back,confi
{source.view.layers&&<Select className="observation-layer-select" label={`Слой · ${source.view.label}`} value={layerFor(source.key,source.view)} options={source.view.layers} onChange={value=>setLayout(current=>({...current,layers:{...current.layers,[source.key]:value}}))} variant="inline"/>}
<ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.actionsTarget}/>
{source.deviceID&&cameras.some(group=>group.device.id===source.deviceID)&&<IconButton label={`${primaryRef.current===source.deviceID?'Основной видеопоток':'Сделать основным видеопотоком'} · ${source.view.label}`} aria-pressed={primaryRef.current===source.deviceID} onClick={()=>setPrimaryCamera(source.deviceID!)}><Icon name="eye"/></IconButton>}
{source.deviceID&&<IconButton label={`Настройки · ${source.view.label}`} onClick={()=>setSettingsDevice(source.deviceID!)}><Icon name="settings"/></IconButton>}
{source.deviceID&&<IconButton label={`Настройки · ${source.view.label}`} onClick={()=>{setSettingsView(source.view.id==='plan'?'plan':'points');setSettingsDevice(source.deviceID!);}}><Icon name="settings"/></IconButton>}
<IconButton label={`${effectiveFull===source.key?'Восстановить':'Развернуть'} · ${source.view.label}`} onClick={()=>setFull(value=>value===source.key?null:source.key)}><Icon name={effectiveFull===source.key?'minimize':'expand'}/></IconButton>
<IconButton label={`Скрыть · ${source.view.label}`} onClick={()=>setVisible(source.key,false)}><Icon name="close"/></IconButton>
</div>
@@ -90,11 +107,12 @@ export function BoardObservationCenter({vehicleID,name,enabled,paired,back,confi
</GlassSurface>
</div>,mounts.current.get(source.key)!,source.key))}
</ObservationDeck>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>setLayersOpen(true)}>Доступные слои</Button></div>}</div>
{groups.map(({device,views,Session,independentMediaLiveness})=>visible.some(key=>views.some(view=>key===observationKey(device.id,view.id)))&&<Session key={device.id} device={device} transport={transport} presentation={presets.cameras[device.id]} onPresentationChange={presets.ready?value=>presets.setCamera(device.id,value):undefined} enabled={(independentMediaLiveness?paired:enabled&&inventory?.fresh!==false)&&device.online} fresh={enabled&&inventory?.fresh!==false} createRerunHost={createIsolatedRerunHost} views={views.map(view=>({id:view.id,layer:layerFor(observationKey(device.id,view.id),view),target:media.current.get(observationKey(device.id,view.id))!,...headers.current.get(observationKey(device.id,view.id))!}))}/>)}
{sources.filter(source=>source.catalog&&visible.includes(source.key)).map(source=>createPortal(<div className="observation-source"><div className="observation-source__notice"><p>{source.catalog} не подключён к аппарату.</p><Button onClick={configure}>Подключить оборудование</Button></div></div>,media.current.get(source.key)!,source.key))}
{configuredDevice&&<ObservationDeviceSettings key={configuredDevice.id} device={configuredDevice} transport={transport} contributions={registry.sensorContributions} enabled={enabled&&inventory?.fresh!==false&&configuredDevice.online} close={()=>setSettingsDevice(null)} configure={configure}/>}
{presets.ready&&groups.map(({device,views,Session,independentMediaLiveness})=>visible.some(key=>views.some(view=>key===observationKey(device.id,view.id)))&&<Session key={device.id} device={device} transport={transport} configure={view=>{setSettingsView(view==='plan'?'plan':'points');setSettingsDevice(device.id);}} sceneProfiles={Object.fromEntries(views.map(view=>[view.id,presets.scenes?.[observationKey(device.id,view.id)]]).filter(([,value])=>value))} onSceneChange={presets.ready?(view,value)=>presets.setScene(observationKey(device.id,view),value):undefined} reconnect={reconnect(device.kind)} presentation={presets.cameras[device.id]} onPresentationChange={presets.ready?value=>presets.setCamera(device.id,value):undefined} enabled={(independentMediaLiveness?paired:enabled&&inventory?.fresh!==false)&&device.online} fresh={enabled&&inventory?.fresh!==false} createRerunHost={createIsolatedRerunHost} views={views.filter(view=>visible.includes(observationKey(device.id,view.id))).map(view=>({id:view.id,layer:layerFor(observationKey(device.id,view.id),view),target:media.current.get(observationKey(device.id,view.id))!,...headers.current.get(observationKey(device.id,view.id))!}))}/>)}
{sources.filter(source=>source.catalog&&visible.includes(source.key)).map(source=>createPortal(<div className="observation-source"><div className="observation-source__notice"><p>{source.catalog} не подключён к аппарату.</p><Button onClick={reconnect(source.kind)??configure}>Подключить оборудование</Button></div></div>,media.current.get(source.key)!,source.key))}
{connectingKind&&<ObservationConnectionWindow key={`${vehicleID}:${connectingKind}`} kind={connectingKind} transport={transport} contributions={registry.sensorContributions} enabled={enabled} refresh={refresh} close={()=>setConnectingKind(null)} configure={setSettingsDevice}/>}
{configuredDevice&&<ObservationDeviceSettings key={configuredDevice.id+settingsView} sceneProfile={{view:settingsView,settings:presets.scenes?.[observationKey(configuredDevice.id,settingsView)],save:value=>presets.setScene(observationKey(configuredDevice.id,settingsView),value)}} device={configuredDevice} transport={transport} contributions={registry.sensorContributions} enabled={enabled&&inventory?.fresh!==false} close={()=>setSettingsDevice(null)} configure={configure} refresh={async()=>{await refresh();}} reconnect={reconnect(configuredDevice.kind)}/>}
{visible.includes('map')&&createPortal(<ObservationMap vehicleID={vehicleID} header={headers.current.get('map')!}/>,media.current.get('map')!,'map-session')}
{visible.includes('rover')&&createPortal(<RoverView vehicleID={vehicleID} controller={rover} header={headers.current.get('rover')!} active={drivingVisible} observation={roverObservation}/>,media.current.get('rover')!,'rover-session')}
{visible.includes('rover')&&createPortal(<RoverView vehicleID={vehicleID} name={name} controller={rover} header={headers.current.get('rover')!} active={drivingVisible} observation={roverObservation}/>,media.current.get('rover')!,'rover-session')}
{visible.includes('rover-logs')&&createPortal(<RoverLogs capture={diagnostics} header={headers.current.get('rover-logs')!}/>,media.current.get('rover-logs')!,'rover-logs-session')}
{visible.includes('telemetry')&&createPortal(<RoverTelemetry state={rover.state} observation={roverObservation}/>,media.current.get('telemetry')!,'telemetry-session')}
<Window open={layersOpen} onClose={()=>setLayersOpen(false)} title="Доступные слои" size="md"><div className="observation-settings">
@@ -0,0 +1,25 @@
import {useEffect,useRef} from 'react';
import {WirelessEnrollmentWindow} from '../../../../../../packages/sensor-ui/src/WirelessEnrollmentWindow';
import {enrolledDevice,type SensorInventory,type SensorTransport} from '../../../../../../packages/sensor-ui/src/contracts';
import type {SensorUiContribution} from '../../../../../../packages/sensor-ui/src/extensions';
/** One enrollment owner for every view of the selected device kind. */
export function ObservationConnectionWindow({kind,transport,contributions,enabled,refresh,close,configure}:{
kind:string;transport:SensorTransport;contributions:readonly SensorUiContribution[];enabled:boolean;
refresh:()=>Promise<SensorInventory|null>;close:()=>void;configure:(deviceID:string)=>void;
}){
const current=useRef({active:true,enabled});
current.current.enabled=enabled;
useEffect(()=>{current.current.active=true;return()=>{current.current.active=false;};},[]);
async function complete(sessionID:string,signal?:AbortSignal){
if(!current.current.enabled)throw new Error('БК недоступен. Обновите состояние устройства.');
const inventory=await refresh();
if(signal?.aborted||!current.current.active)return;
const device=inventory&&enrolledDevice(inventory,sessionID);
if(!current.current.enabled||!device||device.kind!==kind)throw new Error('Связь с устройством пока не подтверждена. Проверьте его состояние.');
close();configure(device.id);
}
if(!transport.enrollment)return null;
return <WirelessEnrollmentWindow initialKind={kind} contributions={contributions.filter(item=>item.kind===kind)} transport={transport.enrollment}
enabled={enabled} onClose={close} onChange={()=>{void refresh();}} onComplete={complete}/>;
}
@@ -1,17 +1,18 @@
import {useState} from 'react';
import {Button,ToastStack,Window} from '@nodedc/ui-react';
import type {SensorDetailProps} from '../../../../../../packages/sensor-ui/src/extensions';
import {SensorDetail} from '../../../../../../packages/sensor-ui/src/SensorDetail';
import {sensorContribution,type SensorUiContribution} from '../../../../../../packages/sensor-ui/src/extensions';
import type {Sensor,SensorTransport} from '../../../../../../packages/sensor-ui/src/contracts';
import {createIsolatedRerunHost} from '../../../components/rerun/isolatedRerunHost';
export function ObservationDeviceSettings({device,transport,contributions,enabled,close,configure}:{device:Sensor;transport:SensorTransport;contributions:readonly SensorUiContribution[];enabled:boolean;close:()=>void;configure:()=>void}) {
export function ObservationDeviceSettings({device,transport,contributions,enabled,close,configure,refresh,reconnect,sceneProfile}:{sceneProfile?:SensorDetailProps['sceneProfile'];device:Sensor;transport:SensorTransport;contributions:readonly SensorUiContribution[];enabled:boolean;close:()=>void;configure:()=>void;refresh:()=>Promise<void>;reconnect?:()=>void}) {
const [error,setError]=useState('');
const contribution=sensorContribution(contributions,device);
const Detail=contribution?.Detail??SensorDetail;
const content=<Detail key={device.snapshot.context.session_id} device={device} transport={transport} enabled={enabled} back={close} refresh={async()=>{await transport.inventory();}} failure={reason=>setError(reason instanceof Error?reason.message:reason?String(reason):'')} createRerunHost={createIsolatedRerunHost}/>;
const content=<Detail key={device.snapshot.context.session_id} device={device} transport={transport} enabled={enabled} previewEnabled={false} sceneProfile={sceneProfile} back={close} backLabel="Вернуться к наблюдению" refresh={refresh} reconnect={reconnect} failure={reason=>setError(reason instanceof Error?reason.message:reason?String(reason):'')} createRerunHost={createIsolatedRerunHost}/>;
if(contribution?.detailPresentation==='modal')return <>{content}<ToastStack items={error?[{id:'device-settings-error',tone:'error',title:error,durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
return <Window open title={`Настройки · ${device.name}`} size="lg" placement="end" draggable closeOnBackdrop={false} lockBodyScroll={false} trapFocus={false} onClose={close}>
return <Window open title={`Настройки · ${device.name}`} size="lg" placement="center" closeOnBackdrop={false} onClose={close}>
{!enabled&&<p>Нет связи с устройством. Настройки оборудования будут доступны после подключения.</p>}
{!device.prepared&&<Button onClick={configure}>Открыть оборудование аппарата</Button>}
{error&&<p role="alert">{error}</p>}
@@ -1,17 +1,23 @@
import {useEffect,useState} from 'react';
import {useCallback,useEffect,useRef,useState} from 'react';
import type {SensorInventory,SensorTransport} from '../../../../../../packages/sensor-ui/src/contracts';
export function useObservationInventory(transport:SensorTransport){
const [inventory,setInventory]=useState<SensorInventory|null>(null);
const reader=useRef<(()=>Promise<SensorInventory|null>)|null>(null);
const refresh=useCallback(async()=>await reader.current?.()??null,[]);
useEffect(()=>{
let active=true,running=false,revision=0,last=0;
const receive=(value:SensorInventory)=>{if(active){revision++;last=Date.now();setInventory(value);}};
let active=true,running=false,revision=0,last=0,latest:SensorInventory|null=null;
const lifetime=new AbortController();
setInventory(null);
const receive=(value:SensorInventory)=>{if(active){revision++;last=Date.now();latest=value;setInventory(value);}};
// A lost SSE connection is not evidence that a working camera stopped.
// Retain the last inventory for one bounded heartbeat window and verify via HTTP.
const unavailable=()=>{if(active&&Date.now()-last>15000)setInventory(value=>value?{...value,fresh:false}:value);};
const poll=async()=>{if(running||Date.now()-last<4000)return;running=true;const before=revision;try{const value=await transport.inventory();if(before===revision)receive(value);}catch{if(before===revision)unavailable();}finally{running=false;}};
const read=async()=>{const before=revision;try{const value=await transport.inventory(lifetime.signal);if(!active)return null;if(before===revision)receive(value);return latest;}catch{if(before===revision)unavailable();return null;}};
reader.current=read;
const poll=async()=>{if(running||Date.now()-last<4000)return;running=true;try{await read();}finally{running=false;}};
void poll();const unsubscribe=transport.subscribe?.(receive,()=>{unavailable();void poll();});const timer=setInterval(()=>{unavailable();void poll();},5000);
return()=>{active=false;clearInterval(timer);unsubscribe?.();};
return()=>{active=false;lifetime.abort();if(reader.current===read)reader.current=null;clearInterval(timer);unsubscribe?.();};
},[transport]);
return inventory;
return {inventory,refresh};
}