Compare commits

...
Author SHA1 Message Date
DCCONSTRUCTIONS 97614742bb Accept qualified ARNavi VPS 0.2.5 v1 compatibility contract 2026-10-01 14:38:42 +03:00
DCCONSTRUCTIONS a78fdeae66 Accept qualified ARNavi VPS 0.2.4 client contract 2026-10-01 09:13:14 +03:00
DCCONSTRUCTIONS b17ff5554e Preserve ARNavi full settings support through VPS 0.2.3 2026-10-01 01:07:13 +03:00
DCCONSTRUCTIONS 43b63e8eb9 Accept shared B2 VPS 0.2.1 for equipment settings and commands 2026-09-30 22:43:12 +03:00
DCCONSTRUCTIONS df36e92500 Accept ARNavi VPS 0.2.0 through the existing client contract 2026-09-30 15:34:24 +03:00
DCCONSTRUCTIONS 6dd652f71e Keep B2 client fixes and move VPS implementation to its standalone repository 2026-09-29 12:41:21 +03:00
DCCONSTRUCTIONS 03d44d0fb1 docs(handoff): record ARNavi cards, source revisions and closeout checks 2026-09-28 18:52:10 +03:00
DCCONSTRUCTIONS 21f46ac38a docs(arnavi): consolidate server and tracker handoff with qualification evidence 2026-09-28 18:44:50 +03:00
DCCONSTRUCTIONS 67ae1f4d77 feat(map): show independent tracker positions and recover unavailable layers 2026-09-28 18:44:18 +03:00
DCCONSTRUCTIONS 031e01a99b feat(ui): add tracker provisioning, SIM policies, command history and firmware archive 2026-09-28 18:44:18 +03:00
DCCONSTRUCTIONS f3a7592d90 feat(fleet): integrate independent trackers, VPS pairing and recoverable commands 2026-09-28 18:44:12 +03:00
DCCONSTRUCTIONS d684eb7e05 feat(vps): ship durable ARNavi host with reproducible install and recovery 2026-09-28 18:43:39 +03:00
DCCONSTRUCTIONS b6efae3272 feat(arnavi): add qualified B2 protocols, USB provisioning and SIM evidence 2026-09-28 18:43:32 +03:00
DCCONSTRUCTIONS fb33a6d45c fix(ui): label connectivity checks as Проверка состояния 2026-09-25 23:26:51 +03:00
DCCONSTRUCTIONS 0fb117fe7b docs: record worker recovery acceptance and deployment boundaries 2026-09-25 23:25:02 +03:00
DCCONSTRUCTIONS e2cf3078b6 fix(ui): unify connectivity labels and move contour refresh to header 2026-09-25 23:24:45 +03:00
DCCONSTRUCTIONS f3640026cf fix(telemetry): recover worker agent and Tailscale transport automatically 2026-09-25 23:24:27 +03:00
DCCONSTRUCTIONS bd5873ef34 fix(fleet): derive contour status from registered nodes and remove obsolete tabs 2026-09-25 22:28:42 +03:00
DCCONSTRUCTIONS aecae4a986 feat(fleet): edit apparatus name independently of onboard availability 2026-09-25 22:28:22 +03:00
DCCONSTRUCTIONS ee7576b7b4 refactor(fleet-ui): consolidate apparatus header and computer status 2026-09-25 21:58:57 +03:00
DCCONSTRUCTIONS e2b0d839eb feat(fleet-ui): organize apparatus equipment beneath its computer 2026-09-25 21:38:25 +03:00
DCCONSTRUCTIONS d2ec9e95b1 feat(fleet): replace onboard computer without replacing apparatus 2026-09-25 21:38:13 +03:00
DCCONSTRUCTIONS 8283f9ba85 feat(observation): expose offline sources with transparent viewport headers 2026-09-25 19:14:21 +03:00
DCCONSTRUCTIONS db3b1d7b67 fix(navigation): return repeated section selections to their entry view 2026-09-25 19:14:21 +03:00
DCCONSTRUCTIONS a993eda6b8 feat(rover): add live scene and material editing with environment migration 2026-09-25 19:13:52 +03:00
226 changed files with 24880 additions and 1048 deletions
+5
View File
@@ -1,5 +1,10 @@
# NODEDC MISSION CORE
ARNavi B2 VPS server development moved to
[NODEDC_MISSION_CORE_ARNAVI-VPS](https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS).
Mission Core retains its B2 client and existing pairing; see the
[repository boundary](docs/arnavi_b2/VPS_REPOSITORY_SPLIT_20260929.md).
NODEDC MISSION CORE is the vendor-neutral control, observation, mission-planning,
recording, and integration platform for NODEDC autonomous systems. This
repository is the canonical early-stage monorepo: it contains the Mission Core
Binary file not shown.
File diff suppressed because it is too large Load Diff
+26 -10
View File
@@ -152,6 +152,7 @@ export default function App() {
contentExpanded: true,
});
const [navigationRevision, setNavigationRevision] = useState(0);
const [activeRoot, setActiveRoot] = useState<RootId | null>(
polygonDatasetRoute.active ? "data" : null,
);
@@ -159,6 +160,7 @@ export default function App() {
const [launchProfile, setLaunchProfile] = useState<WorkspaceLaunchProfile>('direct');
const [sourceUrl, setSourceUrl] = useState("");
const [workspaceHeaderToolsHost, setWorkspaceHeaderToolsHost] = useState<HTMLDivElement | null>(null);
const [workspaceHeaderTitleHost, setWorkspaceHeaderTitleHost] = useState<HTMLSpanElement | null>(null);
const [recordedReplay, setRecordedReplay] = useState<ObservationSessionReplayLaunch | null>(null);
const [recordedReplayLabel, setRecordedReplayLabel] = useState<string | null>(null);
const [replayTransitioning, setReplayTransitioning] = useState(false);
@@ -457,6 +459,17 @@ export default function App() {
workspace.openView(viewId);
};
// Explicit menu navigation always returns to that workspace's entry screen.
const openNavigationView = (viewId: string) => {
if (!workspaceById(viewId)) return;
setNavigationRevision(value => value + 1);
sessionOverview.close();
setSourceWindowOpen(false);
setDisplayWindowOpen(false);
setLayerInspectorOpen(false);
openView(viewId);
};
const openSource = () => {
if (!sceneWorkspaceActive) return;
setSourceDraft(sourceUrl);
@@ -645,11 +658,8 @@ export default function App() {
return () => window.clearTimeout(timer);
}, [layoutSaveNotice]);
const [fleetCreateRequest, setFleetCreateRequest] = useState(0);
const sessionOverview = useSessionOverviewMode(activeDefinition?.kind === "recordings");
const onAddVehicle = useCallback(() => setFleetCreateRequest(value => value + 1), []);
const contentActions = useApplicationPanelActions({
onAddVehicle,
definition: activeDefinition,
refreshRuntime: runtime.refresh,
resetConnectionScenario: runtime.resetConnectionScenario,
@@ -729,6 +739,7 @@ export default function App() {
<SystemNavigationPanel
title={currentRoot.title}
onAdd={computeContourSettings.openCreate}
onNavigateRoot={() => openNavigationView("modules")}
onClose={workspace.closeNavigation}
/>
) : currentRoot ? (
@@ -755,7 +766,7 @@ export default function App() {
icon: <Icon name={item.icon} />,
}))}
activeId={workspace.activeView ?? undefined}
onItemChange={openView}
onItemChange={openNavigationView}
footer={
<>
<span className="nodedc-admin-panel__nav-icon" aria-hidden="true">
@@ -765,7 +776,8 @@ export default function App() {
{rootWorkspaces.length}{" "}
{rootWorkspaces.length === 1
? "рабочая поверхность"
: "рабочих поверхностей"}
: rootWorkspaces.length >= 2 && rootWorkspaces.length <= 4
? "рабочие поверхности" : "рабочих поверхностей"}
</span>
</>
}
@@ -776,7 +788,9 @@ export default function App() {
key={activeDefinition.id}
eyebrow={activeDefinition.eyebrow}
title={
activeDefinition.kind === "recordings"
activeDefinition.kind === "vehicles"
? <>{activeDefinition.title}<span className="fleet-header-title" ref={setWorkspaceHeaderTitleHost}/></>
: activeDefinition.kind === "recordings"
&& replayPresented
&& recordedReplayLabel
? `${activeDefinition.title}: ${recordedReplayLabel}`
@@ -822,16 +836,18 @@ export default function App() {
/>
) : activeDefinition.kind === "missions" ? (
<div ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.kind === "vehicles" ? <div ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? null : activeDefinition.kind === "datasets" ? (
) : activeDefinition.kind === "vehicles" ? <div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? null : activeDefinition.kind === "datasets" ? (
<StatusBadge tone="neutral">Offline evaluation</StatusBadge>
) : activeDefinition.kind === "lab-archive" ? (
laboratoryAnnotation.control
) : activeDefinition.kind === "observatory" ? (
<StatusBadge tone="neutral">Только наблюдение</StatusBadge>
) : activeDefinition.kind === "contour-health" ? (
<div ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.root === "system" ? (
<SystemWorkspaceSelector
value={activeDefinition.id}
onChange={openView}
onChange={openNavigationView}
/>
) : (
<StatusBadge tone="warning">Интерфейс готов</StatusBadge>
@@ -840,7 +856,7 @@ export default function App() {
utilityActions={contentActions}
onClose={workspace.closeView}
>
<PlanningCaptureGuard
<PlanningCaptureGuard key={`${activeDefinition.id}:${navigationRevision}`}
enabled={launchProfile === 'direct' && (activeDefinition.kind === 'device' || activeDefinition.kind === 'spatial')}
onResume={() => openView('local-device', 'planning')}
>
@@ -860,8 +876,8 @@ export default function App() {
<WorkspaceRenderer
launchProfile={launchProfile}
definition={activeDefinition}
fleetCreateRequest={fleetCreateRequest}
headerToolsHost={workspaceHeaderToolsHost}
headerTitleHost={workspaceHeaderTitleHost}
state={activeRuntimeState}
backendStatus={runtime.backendStatus}
sourceUrl={effectiveSourceUrl}
@@ -0,0 +1,8 @@
import {createPortal} from 'react-dom';
import {Icon,IconButton} from '@nodedc/ui-react';
/** A nested workspace returns through the shared panel header. */
export function WorkspaceBackButton({label,onClick,host}:{label:string;onClick:()=>void;host?:HTMLElement|null}) {
const button=<IconButton label={label} onClick={onClick}><Icon name="chevron-left"/></IconButton>;
return host?createPortal(button,host):button;
}
@@ -6,40 +6,41 @@ import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput';
import type {RoverController} from '../../core/fleet/useRoverControl';
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
import './rover.css';
const Scene=lazy(()=>import('./playcanvas/PlayCanvasViewer'));
const Scene=lazy(()=>import('./editor/RoverScene'));
const labels:Record<string,string>={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление включено',driving:'Команда движения',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выключено',fault:'Управление остановлено'};
export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean}){
const storage=`missioncore.rover-view.v1:${vehicleID}`;
const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}});
const [open,setOpen]=useState(false),[confirmed,setConfirmed]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
const [editing,setEditing]=useState(false);
const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading');
const stage=useRef<HTMLDivElement>(null),input=useRef<ReturnType<typeof bindRoverHoldInput>|null>(null);
const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();setConfirmed(false);},[c.stop,c.setInputGuard]);
useEffect(()=>{try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]);
useEffect(()=>{if(!active)stop();},[active,stop]);
useEffect(()=>{
if(!c.ready||!active||open||!stage.current)return;
if(!c.ready||!active||open||editing||!stage.current)return;
const binding=bindRoverHoldInput(stage.current,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop});
input.current=binding;c.setInputGuard(binding.valid);
return()=>{c.setInputGuard(null);binding.dispose();if(input.current===binding)input.current=null;};
},[c.ready,active,open,settings.mode,c.setDemand,c.setInputGuard,c.pauseInput,stop]);
const showSettings=()=>{stop();setOpen(true);};
},[c.ready,active,open,editing,settings.mode,c.setDemand,c.setInputGuard,c.pauseInput,stop]);
const showSettings=()=>{setEditing(false);stop();setOpen(true);};
const preparing=c.pending||(c.armed&&!c.ready);
const availability=c.connecting?'Синхронизация с бортом':!c.state.fresh?'Нет свежих данных с борта':!c.state.snapshot.supported?'Управление на борту недоступно':c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null;
const tone=preparing||availability?'warning':c.ready?'success':c.state.snapshot.state==='fault'?'warning':'neutral';
const status=preparing?'Подготовка управления':availability??(labels[c.state.snapshot.state??'']??'Наблюдение');
return <>
{createPortal(<IconButton label="Настройки управления ровером" onClick={showSettings}><Icon name="settings"/></IconButton>,header.actionsTarget)}
{createPortal(<><IconButton label={editing?"Завершить редактирование сцены":"Редактировать сцену"} aria-pressed={editing} onClick={()=>{c.pauseInput();setHeld(new Set());setEditing(v=>!v);}}><Icon name="edit"/></IconButton><IconButton label="Настройки управления ровером" onClick={showSettings}><Icon name="settings"/></IconButton></>,header.actionsTarget)}
{createPortal(<StatusBadge variant="indicator" tone={tone} aria-label={status} title={status}/>,header.statusTarget)}
<div className="rover-view" ref={stage} tabIndex={0} aria-label="3D-вид и управление ровером"
onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}>
{settings.model==='dcd006-v020'?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'} label="Загрузка модели ровера">
<Suspense fallback={null}><Scene modelUrl="/rover-scene/dcd006-v020.glb" cameraAutoRotate={false} onModelState={setModelState}/></Suspense>
<Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense>
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
</LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>}
<div className="rover-view__status"><StatusBadge tone={tone}>{status}</StatusBadge></div>
{c.ready&&<div className="rover-view__controls">
<div className="rover-view__status"><StatusBadge tone={editing?'neutral':tone}>{editing?'Редактирование сцены':status}</StatusBadge></div>
{c.ready&&!editing&&<div className="rover-view__controls">
<div className={`rover-keys rover-keys--${settings.mode}`} aria-label={settings.mode==='arcade'?'Аркадное управление':'Танковое управление'}>
{keysFor(settings.mode).map(code=><KeyButton key={code} className={`rover-key-${code}`} label={settings.mode==='arcade'?({KeyW:'Вперёд · W',KeyS:'Назад · S',KeyA:'Налево · A',KeyD:'Направо · D'}[code]??code):({KeyQ:'Левая сторона вперёд · Q',KeyA:'Левая сторона назад · A',KeyE:'Правая сторона вперёд · E',KeyD:'Правая сторона назад · D'}[code]??code)}
disabled={!c.ready||!active} pressed={held.has(code)}
@@ -50,9 +51,9 @@ export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:stri
</div>
<span>{settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп</span>
</div>}
<div className="rover-view__authority">
{!editing&&<div className="rover-view__authority">
{c.armed||c.pending?<Button onClick={stop}>Остановить управление</Button>:<Button onClick={showSettings}>Управлять</Button>}
</div>
</div>}
</div>
<Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings">
<Select label="Тип управления" value={settings.mode} options={[{value:'arcade',label:'Аркадный · W A S D'},{value:'tank',label:'Танковый · Q A / E D'}]} onChange={mode=>setSettings(v=>({...v,mode:mode as RoverMode}))}/>
@@ -0,0 +1,23 @@
import {LutField} from './LutField';
import {useRef} from 'react';
import {Button,ColorField,ControlRow,Inspector,InspectorSelectField,RangeControl,Switch,TextField} from '@nodedc/ui-react';
import {environmentFields,fieldValue,fieldDisabled,type SceneDocument,type SceneField} from '../../../core/roverScene/sceneDocument';
const labels:Record<string,string>={'Камера':'Камера',Lighting:'Освещение',Rendering:'Рендеринг',Grid:'Сетка',SSAO:'Контактное затенение · SSAO',Bloom:'Свечение · Bloom','Chromatic Aberration':'Хроматическая аберрация',TAA:'Временное сглаживание · TAA',Grading:'Цветокоррекция',LUT:'Цветовая таблица · LUT',Vignette:'Виньетка','Environment Atlas':'Карта окружения','Skybox':'Небо','Directional Light':'Направленный свет','Shadow Catcher':'Тень на поверхности'};
export function EnvironmentInspector({document,onChange,onResetCamera,onError}:{document:SceneDocument;onChange:(key:string,value:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
const groups=[...new Set(environmentFields.map(f=>f.group))];
return <Inspector defaultOpen={['Камера','PostProcess/Lighting']} sections={groups.map(group=>({id:group,label:labels[group.split('/').at(-1)!]??group,content:<div className="rover-scene-fields">{environmentFields.filter(f=>f.group===group).map(f=><EnvironmentField key={f.key} field={f} value={fieldValue(document,f.key)} disabled={fieldDisabled(document,f)} onChange={v=>onChange(f.key,v)} onResetCamera={onResetCamera} onError={onError}/>)}</div>}))}/>;
}
function EnvironmentField({field:f,value,disabled,onChange,onResetCamera,onError}:{field:SceneField;value:unknown;disabled:boolean;onChange:(v:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
if(f.type==='texture')return <LutField value={value as string|null} onChange={onChange} onError={onError}/>;
if(f.type==='action')return <Button onClick={onResetCamera}>Сбросить камеру</Button>;
if(f.type==='toggle')return <Switch label={f.label} checked={!!value} disabled={disabled} onChange={onChange}/>;
if(f.type==='color')return <ControlRow label={f.label}><ColorField label={f.label} value={String(value)} disabled={disabled} onChange={onChange}/></ControlRow>;
if(f.type==='select')return <InspectorSelectField label={f.label} value={String(value)} options={f.options??[]} disabled={disabled} onChange={onChange}/>;
if(f.type==='doubleSlider'){const range=value as number[];return <>{['Начало тумана, м','Конец тумана, м'].map((label,i)=><RangeControl key={i} label={label} min={f.min??0} max={f.max??100} step={f.step??1} exactValueBounds={{min:f.min,max:f.max}} value={range[i]} disabled={disabled} onChange={v=>onChange(i?[range[0],v]:[v,range[1]])}/>)}</>;}
if(f.type==='number')return <TextField type="number" label={f.label} min={f.min} max={f.max} step={f.step??.01} value={Number(value)} disabled={disabled} onChange={e=>onChange(Number(e.target.value))}/>;
return <RangeControl label={f.label} value={Number(value)} min={f.min??0} max={f.max??100} step={f.step??.01} exactValueBounds={{min:f.min,max:f.max}} disabled={disabled} onChange={onChange}/>;
}
export function SceneFileActions({onImport,onExport,onReset}:{onImport:(file:File)=>void;onExport:()=>void;onReset:()=>void}){
const input=useRef<HTMLInputElement>(null);
return <div className="rover-scene-actions"><Button size="compact" onClick={onExport}>Экспорт JSON</Button><Button size="compact" onClick={()=>input.current?.click()}>Импорт JSON</Button><Button size="compact" onClick={onReset}>Окружение NodeDC</Button><input ref={input} hidden type="file" accept=".json,application/json" onChange={e=>{const f=e.currentTarget.files?.[0];if(f)onImport(f);e.currentTarget.value='';}}/></div>;
}
@@ -0,0 +1,7 @@
import {useRef,useState} from 'react';
import {Button,Icon,IconButton} from '@nodedc/ui-react';
import {textureFromFile} from '../../../core/roverScene/sceneStorage';
export function LutField({value,onChange,onError}:{value:string|null|undefined;onChange:(value:string|null)=>void;onError:(error:string)=>void}){
const input=useRef<HTMLInputElement>(null),[loading,setLoading]=useState(false);
return <div className="rover-scene-fields"><p className="rover-scene-note">PNG 256 × 16 · горизонтальная таблица 16³</p><div className="rover-scene-actions"><Button loading={loading} onClick={()=>input.current?.click()}>{value?'Заменить LUT':'Загрузить LUT'}</Button>{value&&<IconButton label="Удалить LUT" onClick={()=>onChange(null)}><Icon name="trash"/></IconButton>}</div><input hidden ref={input} type="file" accept="image/png" onChange={async e=>{const file=e.currentTarget.files?.[0];e.currentTarget.value='';if(!file)return;setLoading(true);try{const bitmap=await createImageBitmap(file);const valid=bitmap.width===256&&bitmap.height===16;bitmap.close();if(!valid||file.type!=='image/png')throw new Error('Нужна PNG-таблица LUT размером 256 × 16.');onChange((await textureFromFile(file)).data);}catch(error){onError(error instanceof Error?error.message:'Не удалось прочитать LUT.');}finally{setLoading(false);}}}/></div>;
}
@@ -0,0 +1,17 @@
import {useRef,useState} from 'react';
import {Button,ColorField,ControlRow,Icon,IconButton,Inspector,RangeControl,Switch,TextField} from '@nodedc/ui-react';
import {textureSlots,type TextureSlot,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {textureFromFile} from '../../../core/roverScene/sceneStorage';
const slotLabels:Record<TextureSlot,string>={diffuse:'Базовый цвет',normal:'Нормали',roughness:'Шероховатость',metalness:'Металличность',opacity:'Прозрачность',emissive:'Свечение',ao:'Окклюзия · AO'};
export function MaterialInspector({material,onChange,onReset,onError}:{material:MaterialSpec;onChange:(patch:Partial<MaterialSpec>)=>void;onReset:()=>void;onError:(message:string)=>void}){
const range=(key:keyof MaterialSpec,label:string,max=1)=><RangeControl label={label} value={Number(material[key])} min={0} max={max} step={.01} exactValueBounds={{min:0,max}} onChange={v=>onChange({[key]:v})}/>;
return <><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><p className="rover-scene-note">Изменения применяются ко всем деталям с этим материалом.</p><Inspector defaultOpen={['surface']} sections={[
{id:'surface',label:'Поверхность',content:<div className="rover-scene-fields"><ControlRow label="Базовый цвет"><ColorField label="Базовый цвет" value={material.color} onChange={color=>onChange({color})}/></ControlRow>{range('metalness','Металличность')}{range('roughness','Шероховатость')}{range('reflectivity','Отражение')}{range('opacity','Непрозрачность')}<Switch label="Двусторонняя поверхность" checked={material.doubleSided} onChange={doubleSided=>onChange({doubleSided})}/></div>},
{id:'coat',label:'Лак и свечение',content:<div className="rover-scene-fields">{range('clearCoat','Слой лака')}{range('clearCoatRoughness','Шероховатость лака')}<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={material.emissive} onChange={emissive=>onChange({emissive})}/></ControlRow>{range('emissiveIntensity','Сила свечения',10)}</div>},
{id:'textures',label:'Текстуры',description:'PNG / JPEG / WebP · до 4096 px',content:<div className="rover-scene-fields">{textureSlots.map(slot=><TextureField key={slot} slot={slot} value={material.textures[slot]} onChange={texture=>onChange({textures:{...material.textures,[slot]:texture}})} onError={onError}/>)}{range('normalStrength','Сила нормалей',2)}<RangeControl label="Повторение текстуры" min={.01} max={20} step={.01} exactValueBounds={{min:.01,max:20}} value={material.tiling} onChange={tiling=>onChange({tiling})}/></div>},
]}/><Button onClick={onReset}>Исходный материал</Button></>;
}
function TextureField({slot,value,onChange,onError}:{slot:TextureSlot;value:MaterialSpec['textures'][TextureSlot];onChange:(value:MaterialSpec['textures'][TextureSlot])=>void;onError:(message:string)=>void}){
const input=useRef<HTMLInputElement>(null),[pending,setPending]=useState(false);
return <div className="rover-scene-texture"><ControlRow label={slotLabels[slot]} layout="stack"><div className="rover-scene-texture__row">{value&&<img src={value.data} alt=""/>}<Button size="compact" loading={pending} onClick={()=>input.current?.click()}>{value?.name??'Загрузить текстуру'}</Button>{value&&<IconButton label={`Удалить текстуру: ${slotLabels[slot]}`} onClick={()=>onChange(undefined)}><Icon name="trash"/></IconButton>}</div></ControlRow><input hidden ref={input} type="file" accept="image/png,image/jpeg,image/webp" onChange={async e=>{const file=e.currentTarget.files?.[0];e.currentTarget.value='';if(!file)return;setPending(true);try{onChange(await textureFromFile(file));}catch(error){onError(error instanceof Error?error.message:'Не удалось загрузить текстуру.');}finally{setPending(false);}}}/></div>;
}
@@ -0,0 +1,38 @@
import {useCallback,useEffect,useState,type CSSProperties} from 'react';
import {Button,GlassSurface,Icon,IconButton,LoadingRegion,StatusBadge,ToastStack,Window} from '@nodedc/ui-react';
import {assignMaterial,createMaterial,changeField,defaultScene,textureBytes,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {useSceneDocument} from '../../../core/roverScene/useSceneDocument';
import PlayCanvasViewer from '../playcanvas/PlayCanvasViewer';
import {EnvironmentInspector,SceneFileActions} from './EnvironmentInspector';
import {MaterialInspector} from './MaterialInspector';
import './sceneEditor.css';
export default function RoverScene({vehicleID,editing,onModelState}:{vehicleID:string;editing:boolean;onModelState:(state:'loading'|'ready'|'error')=>void}){
const scene=useSceneDocument(vehicleID),[palette,setPalette]=useState(false),[environment,setEnvironment]=useState(false),[selected,setSelected]=useState<string|null>(null),[materialOpen,setMaterialOpen]=useState(false),[cameraReset,setCameraReset]=useState(0),[textureState,setTextureState]=useState<'loading'|'ready'|'error'>('ready');
const [selectedGroup,setSelectedGroup]=useState<string|null>(null);
const pick=useCallback((id:string,group?:string)=>{setSelected(id);if(group)setSelectedGroup(group);setMaterialOpen(true);},[]);
const addMaterial=()=>{if(Object.keys(scene.document.materials).length>=128){scene.setError('В сцене может быть не больше 128 материалов.');return;}const id=`custom/${crypto.randomUUID()}`;scene.update(doc=>createMaterial(doc,id));pick(id);};
const patchMaterial=(id:string,patch:Partial<MaterialSpec>)=>{const next={...scene.document,materials:{...scene.document.materials,[id]:{...scene.document.materials[id],...patch}}};if(textureBytes(next)>28_000_000){scene.setError('Суммарный объём текстур превышает 20 МБ. Удалите ненужную текстуру.');return;}scene.update(doc=>({...doc,materials:{...doc.materials,[id]:{...doc.materials[id],...patch}}}));};
useEffect(()=>{if(textureState==='error')scene.setError('Не удалось применить текстуру к сцене. Проверьте файл и загрузите его заново.');},[textureState,scene.setError]);
const saved=scene.saveState==='saved',status=textureState==='loading'?'Загрузка текстур':scene.saveState==='loading'?'Загрузка настроек сцены':scene.saveState==='saving'?'Сохранение сцены':scene.saveState==='error'?'Изменения не сохранены':'Сохранено на этом компьютере';
const material=selected?scene.document.materials[selected]:null;
return <>
<LoadingRegion className="rover-view__scene" style={{bottom:editing&&palette?150:0}} loading={!scene.ready} label="Загрузка настроек сцены">
{scene.ready&&<PlayCanvasViewer modelUrl="/rover-scene/dcd006-v020.glb?materials-v2" postFx={scene.document.postFx} cameraAutoRotate={scene.document.cameraAutoRotate} cameraZoomStrength={scene.document.cameraZoomStrength} cameraResetToken={cameraReset} materials={scene.document.materials} assignments={scene.document.assignments} editing={editing} onMaterialPick={pick} onModelState={onModelState} onTextureState={setTextureState}/>}
</LoadingRegion>
{editing&&<>
<div className="rover-scene-tools"><GlassSurface className="rover-scene-tools__surface"><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>setPalette(v=>!v)}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton></GlassSurface></div>
<div className="rover-scene-save"><StatusBadge tone={saved&&textureState!=='loading'?'neutral':'warning'}>{status}</StatusBadge></div>
{palette&&<GlassSurface className="rover-material-palette"><div className="rover-material-palette__header"><span>Материалы · выберите в палитре или на модели</span><IconButton label="Скрыть палитру материалов" onClick={()=>setPalette(false)}><Icon name="close"/></IconButton></div><div className="rover-material-palette__items">{Object.entries(scene.document.materials).map(([id,m])=><Button key={id} variant={selected===id?'primary':'secondary'} tone="neutral" aria-pressed={selected===id} title={m.name} onClick={()=>pick(id)}><span className="rover-material-tile"><span aria-hidden="true" className="rover-material-swatch" style={{'--material-color':m.color,'--material-gloss':1-m.roughness} as CSSProperties}/><span>{m.name}</span></span></Button>)}<Button aria-label="Добавить материал" title="Добавить материал" onClick={addMaterial}><span className="rover-material-tile"><Icon name="plus"/><span>Новый материал</span></span></Button></div></GlassSurface>}
</>}
<Window open={editing&&environment} title="Окружение сцены" placement="end" draggable onClose={()=>setEnvironment(false)} footer={<SceneFileActions onImport={scene.importDocument} onExport={scene.exportDocument} onReset={()=>scene.update(doc=>({...doc,postFx:defaultScene().postFx}))}/>}>
<EnvironmentInspector onError={scene.setError} document={scene.document} onChange={(key,value)=>scene.update(doc=>changeField(doc,key,value))} onResetCamera={()=>setCameraReset(v=>v+1)}/>
</Window>
<Window open={editing&&materialOpen&&!!material} title={material?.name||'Материал'} subtitle="Материал сцены" placement="end" draggable style={{position:'fixed',left:'var(--nodedc-space-4)',top:'6rem',right:'auto'}} onClose={()=>setMaterialOpen(false)}>
{material&&selected&&<>
{selectedGroup?<div className="rover-scene-fields"><p className="rover-scene-note">Выбранная группа: {defaultScene().materials[selectedGroup]?.name}</p><Button disabled={(scene.document.assignments[selectedGroup]??selectedGroup)===selected} onClick={()=>scene.update(doc=>assignMaterial(doc,selectedGroup,selected))}>Назначить выбранной группе</Button></div>:<p className="rover-scene-note">Нажмите на деталь в сцене, затем выберите материал в палитре, чтобы назначить его группе.</p>}
<MaterialInspector key={selected} material={material} onChange={patch=>patchMaterial(selected,patch)} onReset={()=>{const base=defaultScene().materials[selected]??createMaterial(defaultScene(),selected).materials[selected];if(base)patchMaterial(selected,{...base,name:material.name});}} onError={scene.setError}/>
</>}
</Window>
<ToastStack items={scene.error?[{id:'rover-scene-error',tone:'error',title:'Настройки сцены',description:scene.error}]:[]} onDismiss={()=>scene.setError('')}/>
</>;
}
@@ -0,0 +1,17 @@
.rover-scene-tools {position:absolute;right:var(--nodedc-space-3);top:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3));}
.rover-scene-tools__surface,.rover-scene-actions {display:flex;align-items:center;gap:var(--nodedc-space-2);flex-wrap:wrap;}
.rover-scene-tools__surface {padding:var(--nodedc-space-1);}
.rover-scene-save {position:absolute;left:var(--nodedc-space-3);top:calc(var(--observation-overlay-header-space, 0px) + 3rem);pointer-events:none;}
.rover-material-palette {position:absolute;bottom:var(--nodedc-space-3);left:var(--nodedc-space-3);right:var(--nodedc-space-3);padding:var(--nodedc-space-2);}
.rover-material-palette__header {display:flex;align-items:center;justify-content:space-between;gap:var(--nodedc-space-2);font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-secondary);}
.rover-material-palette__items {display:flex;gap:var(--nodedc-space-2);overflow:auto;}
.rover-material-palette__items > * {flex:0 0 auto;}
.rover-material-tile {display:grid;justify-items:center;gap:var(--nodedc-space-1);width:100px;white-space:normal;font-size:var(--nodedc-font-size-xs);}
/* Domain material thumbnail: a swatch, not a replacement control. */
.rover-material-swatch {display:block;width:38px;height:38px;border-radius:50%;background:radial-gradient(ellipse at 35% 25%,#ffffffb0,transparent 45%),radial-gradient(ellipse at 60% 75%,transparent,var(--material-color) 70%),var(--material-color);box-shadow:inset -5px -5px 12px #0008;}
.rover-scene-fields {display:flex;flex-direction:column;gap:var(--nodedc-space-3);}
.rover-scene-note {font-size:var(--nodedc-font-size-sm);color:var(--nodedc-text-secondary);}
.rover-scene-texture__row {display:flex;gap:var(--nodedc-space-2);align-items:center;min-width:0;}
.rover-scene-texture__row img {width:36px;height:36px;object-fit:cover;}
.rover-scene-texture__row .nodedc-button {min-width:0;overflow:hidden;}
@container(max-width:460px){.rover-scene-save{top:calc(var(--observation-overlay-header-space, 0px) + 4.5rem)}.rover-material-tile{width:82px}.rover-material-palette__header>span{max-width:210px}}
@@ -11,6 +11,13 @@
"No fallback to a different vehicle",
"Removed unused node-editor type helper; rendering settings unchanged",
"Observe the host pane on resize; preserve responsive canvas CSS sizing",
"Frame the complete rover using the donor 28-degree FOV and current viewport aspect"
]
"Frame the complete rover using the donor 28-degree FOV and current viewport aspect",
"Scene editing uses canonical modeless Design Guideline inspectors; all 109 donor camera/post-FX fields retained as a versioned field catalog",
"Original NodeDC environment preset restored by owner request; editor reset changes environment only",
"Semantic material groups, UV texture editing, GPU surface picking and bounded texture disposal",
"Live grid step/diameter and ambient fill added; wireframe application and LUT loading corrected",
"Responsive scene framing and palette space without drive authority"
],
"inspector_source_sha256": "8f1df16bd8c12fb1b8481480690ff4ed0e6b2645cb3fba527888c0f9acb59192",
"model_revision": "dcd006-v020-materials-v2"
}
@@ -3,13 +3,16 @@ import * as pc from 'playcanvas'
import { buildSceneTree } from './sceneTree'
import { mergePostFxDefaults, type PostFxSettings } from './playcanvasPostFx'
import {useLutTexture} from './useLutTexture'
import {useSceneMaterials,type SceneMaterialsProps} from './useSceneMaterials'
const DEFAULT_MODEL_URL = ''
const PIXELFORMAT_RGBA8 = (pc as any).PIXELFORMAT_RGBA8 ?? 7
const PIXELFORMAT_111110F = (pc as any).PIXELFORMAT_111110F ?? 18
const PIXELFORMAT_RGBA16F = (pc as any).PIXELFORMAT_RGBA16F ?? 12
const PIXELFORMAT_RGBA32F = (pc as any).PIXELFORMAT_RGBA32F ?? 14
export type PlayCanvasViewerProps = {
export type PlayCanvasViewerProps = SceneMaterialsProps & {
modelUrl: string | null
postFx?: Partial<PostFxSettings> | null
viewportSize?: { width: number; height: number }
@@ -390,16 +393,9 @@ function toColor(value: ColorInput, fallback?: pc.Color): pc.Color {
}
function setWireframeForScene(app: pc.Application, enabled: boolean) {
const renders = app.root.findComponents('render') as any[]
for (const r of renders) {
const meshInstances = r?.meshInstances ?? []
for (const mi of meshInstances) {
const mat = mi.material as any
if (mat && 'wireframe' in mat) {
mat.wireframe = enabled
mat.update?.()
}
}
const root = app.root.findByName('ModelRoot') as pc.Entity | null
for (const mi of collectMeshInstances(root)) {
mi.renderStyle = enabled ? pc.RENDERSTYLE_WIREFRAME : pc.RENDERSTYLE_SOLID
}
}
@@ -805,7 +801,7 @@ function applyPostFx(
}
frame.rendering.renderTargetScale = fx.rendering.renderTargetScale
frame.rendering.samples = Number.isFinite(overrides?.samples) ? Number(overrides?.samples) : fx.rendering.samples
frame.rendering.sceneColorMap = true
frame.rendering.sceneColorMap = !!fx.rendering.sceneColorMap
frame.rendering.sceneDepthMap = !!fx.rendering.sceneDepthMap
frame.rendering.toneMapping = fx.rendering.toneMapping
frame.rendering.sharpness = fx.rendering.sharpness
@@ -882,6 +878,7 @@ function applyPostFx(
export default function PlayCanvasViewer({
modelUrl,
materials, assignments, editing, onMaterialPick, onTextureState,
postFx,
viewportSize,
onSceneReady,
@@ -928,7 +925,11 @@ export default function PlayCanvasViewer({
const [skyboxVersion, setSkyboxVersion] = useState(0)
const [modelVersion, setModelVersion] = useState(0)
useSceneMaterials(appRef,cameraEntityRef,canvasRef,modelVersion,{materials,assignments,editing,onMaterialPick,onTextureState})
const fx = useMemo(() => mergePostFxDefaults(postFx), [postFx])
const lutError = useCallback(()=>onTextureState?.('error'),[onTextureState])
useLutTexture(appRef,cameraFrameRef,lutTextureRef,fx.lut.textureUrl,appReady,lutError)
useEffect(() => {
cameraStateRef.current = cameraState ?? null
@@ -962,7 +963,7 @@ export default function PlayCanvasViewer({
if (bounds && orbit) {
const vertical = (cameraEntityRef.current?.camera?.fov ?? 28) * Math.PI / 360
const horizontal = Math.atan(Math.tan(vertical) * w / h)
orbit.setDistance(Math.max(1.8, bounds.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 1.1))
orbit.setDistance(Math.max(1.8, bounds.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 0.88))
}
}, [])
@@ -1112,6 +1113,8 @@ export default function PlayCanvasViewer({
`,
fragmentGLSL: `
uniform vec2 uHalfExtents;
uniform float uGridStep;
uniform float uGridRadius;
uniform vec3 uColorX;
uniform vec3 uColorZ;
uniform vec3 uColorMain;
@@ -1182,7 +1185,9 @@ export default function PlayCanvasViewer({
void main(void) {
vec2 uv = uv0;
vec2 pos = (uv * 2.0 - 1.0) * uHalfExtents;
vec2 worldPos = (uv * 2.0 - 1.0) * uHalfExtents;
if (length(worldPos) > uGridRadius) discard;
vec2 pos = worldPos / uGridStep;
vec2 ddx = dFdx(pos);
vec2 ddy = dFdy(pos);
@@ -1262,7 +1267,7 @@ export default function PlayCanvasViewer({
float fadeEnd = max(0.0, uFadeEnd);
float fade = 1.0;
if (fadeEnd > fadeStart && fadeEnd > 0.0) {
float d = length(pos);
float d = length(worldPos);
fade = 1.0 - smoothstep(fadeStart, fadeEnd, d);
}
outAlpha *= fade;
@@ -1312,6 +1317,8 @@ export default function PlayCanvasViewer({
gridMaterial.setParameter('uFadeStart', 0)
gridMaterial.setParameter('uFadeEnd', 0)
gridMaterial.setParameter('uResolution', 2)
gridMaterial.setParameter('uGridStep', fx.grid.step)
gridMaterial.setParameter('uGridRadius', fx.grid.diameter / 2)
const gridHalfExtents = new pc.Vec2(500, 500)
gridMaterial.setParameter('uHalfExtents', [gridHalfExtents.x, gridHalfExtents.y])
gridMaterial.update()
@@ -1528,7 +1535,7 @@ export default function PlayCanvasViewer({
const cam = cameraEntityRef.current?.camera
const vertical = (cam?.fov ?? 28) * Math.PI / 360
const horizontal = Math.atan(Math.tan(vertical) * (cam?.aspectRatio ?? 1))
orbit.setDistance(Math.max(1.8, aabb.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 1.1))
orbit.setDistance(Math.max(1.8, aabb.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 0.88))
}
if (exposeSceneGraph || onSceneGraph) {
@@ -1617,7 +1624,7 @@ export default function PlayCanvasViewer({
if (!aabb) return
orbit.setState({
pivot: { x: aabb.center.x, y: aabb.center.y, z: aabb.center.z },
distance: Math.max(1.8, aabb.halfExtents.length() * 2.5),
distance: Math.max(1.8,aabb.halfExtents.length() / Math.sin(Math.min(14*Math.PI/180,Math.atan(Math.tan(14*Math.PI/180)*(cameraEntityRef.current?.camera?.aspectRatio??1))))*.88),
azimuthDeg: 45,
elevationDeg: 10,
})
@@ -1638,6 +1645,9 @@ export default function PlayCanvasViewer({
const gridVisible = !!fx.grid.enabled || !!fx.grid.dotsEnabled || !!fx.grid.crossEnabled
grid.enabled = gridVisible
grid.setLocalScale(fx.grid.diameter,1,fx.grid.diameter)
mat.setParameter('uGridStep',fx.grid.step)
mat.setParameter('uGridRadius',fx.grid.diameter/2)
const cX = toColor(fx.grid.colorX)
const cZ = toColor(fx.grid.colorZ)
const cMain = toColor(fx.grid.colorMain)
@@ -1661,6 +1671,7 @@ export default function PlayCanvasViewer({
mat.setParameter('uFadeEnd', Math.max(0, Number(fx.grid.fadeEnd) || 0))
mat.update()
}, [
fx.grid.step,fx.grid.diameter,
fx.grid.enabled,
fx.grid.colorX,
fx.grid.colorZ,
@@ -1690,7 +1701,7 @@ export default function PlayCanvasViewer({
const app = appRef.current
if (!app) return
setWireframeForScene(app, fx.rendering.wireframe)
}, [fx.rendering.wireframe])
}, [fx.rendering.wireframe,modelVersion])
useEffect(() => {
const frame: any = cameraFrameRef.current
@@ -1703,9 +1714,10 @@ export default function PlayCanvasViewer({
const app = appRef.current
if (!app) return
if (fx.lighting) {
app.scene.ambientLight = new pc.Color(fx.lighting.ambientIntensity,fx.lighting.ambientIntensity,fx.lighting.ambientIntensity)
app.scene.exposure = fx.lighting.exposure
}
}, [fx.lighting?.exposure])
}, [fx.lighting?.exposure,fx.lighting.ambientIntensity])
useEffect(() => {
const app = appRef.current
@@ -1924,6 +1936,8 @@ export default function PlayCanvasViewer({
envAtlasVersion,
skyboxVersion,
modelVersion,
materials,
assignments,
fx.envAtlas.enabled,
fx.envAtlas.background,
fx.envAtlas.reflection,
@@ -1,393 +1,2 @@
export type PostFxSettings = {
lighting: {
exposure: number
skyBoxIntensity: number
}
envAtlas: {
enabled: boolean
background: boolean
reflection: boolean
intensity: number
reflectionIntensity: number
brightness: number
contrast: number
saturation: number
toneMapping: number
mip: number
rotation: number
}
skybox: {
enabled: boolean
background: boolean
reflection: boolean
intensity: number
reflectionIntensity: number
mip: number
rotation: number
colorA: string
colorB: string
}
rendering: {
backgroundColor: string
wireframe: boolean
renderFormat: number
renderFormatFallback0: number
renderFormatFallback1: number
stencil: boolean
renderTargetScale: number
samples: number
sharpness: number
toneMapping: number
sceneColorMap: boolean
sceneDepthMap: boolean
fog: 'none' | 'linear' | 'exp' | 'exp2'
fogColor: string
fogRange: [number, number]
fogDensity: number
fogStart: number
fogEnd: number
}
grid: {
enabled: boolean
colorX: string
colorZ: string
colorMain: string
alphaX: number
alphaZ: number
alphaMain: number
dotsEnabled: boolean
dotsColor: string
dotsAlpha: number
dotsDiameter: number
crossEnabled: boolean
crossColor: string
crossAlpha: number
crossLength: number
crossWidth: number
fadeStart: number
fadeEnd: number
}
ssao: {
type: 'none' | 'lighting' | 'combine'
blurEnabled: boolean
intensity: number
radius: number
samples: number
power: number
minAngle: number
scale: number
}
bloom: {
enabled: boolean
intensity: number
lastMipLevel: number
}
chromaticAberration: {
enabled: boolean
intensity: number
}
taa: {
enabled: boolean
jitter: number
}
grading: {
enabled: boolean
brightness: number
contrast: number
saturation: number
tint: string
}
lut: {
intensity: number
textureUrl?: string | null
}
vignette: {
enabled: boolean
intensity: number
inner: number
outer: number
curvature: number
color: string
}
directionalLight: {
enabled: boolean
color: string
intensity: number
azimuth: number
elevation: number
castShadows: boolean
shadowIntensity: number
shadowDistance: number
shadowResolution: number
shadowBias: number
normalOffsetBias: number
shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3'
vsmBlurSize: number
}
shadowCatcher: {
enabled: boolean
size: number
yOffset: number
lightIntensity: number
lightColor: string
lightAzimuth: number
lightElevation: number
shadowIntensity: number
shadowDistance: number
shadowResolution: number
shadowBias: number
normalOffsetBias: number
shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3'
vsmBlurSize: number
}
}
export const DEFAULT_POSTFX: PostFxSettings = {
lighting: {
exposure: 1.21,
skyBoxIntensity: 0.86,
},
envAtlas: {
enabled: true,
background: false,
reflection: true,
intensity: 0.76,
reflectionIntensity: 0.6,
brightness: 1.65,
contrast: 1,
saturation: 1,
toneMapping: 0,
mip: 1,
rotation: 247,
},
skybox: {
enabled: false,
background: false,
reflection: true,
intensity: 0.62,
reflectionIntensity: 1,
mip: 0,
rotation: 0,
colorA: '#c5bfbf',
colorB: '#c7bcbc',
},
rendering: {
backgroundColor: '#111113',
wireframe: false,
renderFormat: 18,
renderFormatFallback0: 12,
renderFormatFallback1: 14,
stencil: false,
renderTargetScale: 1,
samples: 4,
sharpness: 0,
toneMapping: 4,
sceneColorMap: false,
sceneDepthMap: false,
fog: 'exp',
fogColor: '#dcc2ff',
fogRange: [0, 100],
fogDensity: 0.008,
fogStart: 0,
fogEnd: 100,
},
grid: {
enabled: true,
colorX: '#ffffff',
colorZ: '#ffffff',
colorMain: '#7a3cff',
alphaX: 0.18,
alphaZ: 0.18,
alphaMain: 0.6,
dotsEnabled: false,
dotsColor: '#ffffff',
dotsAlpha: 0.5,
dotsDiameter: 0.06,
crossEnabled: false,
crossColor: '#ffffff',
crossAlpha: 0.5,
crossLength: 0.5,
crossWidth: 0.06,
fadeStart: 0,
fadeEnd: 0,
},
ssao: {
type: 'none',
blurEnabled: true,
intensity: 0.5,
radius: 30,
samples: 12,
power: 6,
minAngle: 10,
scale: 1,
},
bloom: {
enabled: true,
intensity: 0.03,
lastMipLevel: 4,
},
chromaticAberration: {
enabled: true,
intensity: 30,
},
taa: {
enabled: false,
jitter: 1,
},
grading: {
enabled: true,
brightness: 0.837,
contrast: 1.1,
saturation: 1.126,
tint: '#ffffff',
},
lut: {
intensity: 1,
textureUrl: null,
},
vignette: {
enabled: true,
intensity: 1,
inner: 0.25,
outer: 1.52,
curvature: 0.78,
color: '#000000',
},
directionalLight: {
enabled: true,
color: '#ffffff',
intensity: 0.4,
azimuth: 0,
elevation: 0,
castShadows: false,
shadowIntensity: 0.5,
shadowDistance: 16,
shadowResolution: 1024,
shadowBias: 0,
normalOffsetBias: 0,
shadowType: 'vsm16',
vsmBlurSize: 8,
},
shadowCatcher: {
enabled: true,
size: 9,
yOffset: 0.001,
lightIntensity: 0.3,
lightColor: '#ffffff',
lightAzimuth: 20,
lightElevation: 60,
shadowIntensity: 0.29,
shadowDistance: 16,
shadowResolution: 2048,
shadowBias: 0,
normalOffsetBias: 0,
shadowType: 'vsm16',
vsmBlurSize: 8,
},
}
function isObject(value: any): value is Record<string, any> {
return !!value && typeof value === 'object' && !Array.isArray(value)
}
export function mergePostFxDefaults(raw?: Partial<PostFxSettings> | null): PostFxSettings {
if (!raw) return JSON.parse(JSON.stringify(DEFAULT_POSTFX)) as PostFxSettings
const out: any = JSON.parse(JSON.stringify(DEFAULT_POSTFX))
const merge = (target: any, source: any) => {
if (!isObject(source)) return
for (const [key, value] of Object.entries(source)) {
if (isObject(value)) {
if (!isObject(target[key])) target[key] = {}
merge(target[key], value)
} else {
target[key] = value
}
}
}
merge(out, raw)
const legacy: any = raw as any
if (legacy?.hdrLight) {
const src = legacy.hdrLight
const env = legacy?.envAtlas ?? {}
if (env?.enabled === undefined && typeof src.enabled === 'boolean') out.envAtlas.enabled = src.enabled
if (env?.background === undefined && typeof src.showSkybox === 'boolean') out.envAtlas.background = src.showSkybox
if (env?.intensity === undefined && typeof src.intensity === 'number') out.envAtlas.intensity = src.intensity
if (env?.mip === undefined && typeof src.mip === 'number') out.envAtlas.mip = src.mip
if (env?.rotation === undefined && typeof src.rotation === 'number') out.envAtlas.rotation = src.rotation
}
if (legacy?.hdrReflection && (legacy?.envAtlas?.reflection === undefined)) {
if (typeof legacy.hdrReflection.enabled === 'boolean') {
out.envAtlas.reflection = legacy.hdrReflection.enabled
}
}
if (out.envAtlas && typeof out.envAtlas.reflectionIntensity !== 'number') {
out.envAtlas.reflectionIntensity = out.envAtlas.intensity
}
if (out.envAtlas && typeof out.envAtlas.brightness !== 'number') {
out.envAtlas.brightness = 1
}
if (out.envAtlas && typeof out.envAtlas.contrast !== 'number') {
out.envAtlas.contrast = 1
}
if (out.envAtlas && typeof out.envAtlas.saturation !== 'number') {
out.envAtlas.saturation = 1
}
if (out.envAtlas && typeof out.envAtlas.toneMapping !== 'number') {
out.envAtlas.toneMapping = 0
}
if (out.skybox && typeof out.skybox.reflectionIntensity !== 'number') {
out.skybox.reflectionIntensity = out.skybox.intensity
}
if (out.grid && typeof out.grid.enabled !== 'boolean') {
out.grid.enabled = DEFAULT_POSTFX.grid.enabled
}
if (out.grid && typeof out.grid.colorX !== 'string') {
out.grid.colorX = DEFAULT_POSTFX.grid.colorX
}
if (out.grid && typeof out.grid.colorZ !== 'string') {
out.grid.colorZ = DEFAULT_POSTFX.grid.colorZ
}
if (out.grid && typeof out.grid.colorMain !== 'string') {
out.grid.colorMain = DEFAULT_POSTFX.grid.colorMain
}
if (out.grid && typeof out.grid.alphaX !== 'number') {
out.grid.alphaX = DEFAULT_POSTFX.grid.alphaX
}
if (out.grid && typeof out.grid.alphaZ !== 'number') {
out.grid.alphaZ = DEFAULT_POSTFX.grid.alphaZ
}
if (out.grid && typeof out.grid.alphaMain !== 'number') {
out.grid.alphaMain = DEFAULT_POSTFX.grid.alphaMain
}
if (out.grid && typeof out.grid.dotsEnabled !== 'boolean') {
out.grid.dotsEnabled = DEFAULT_POSTFX.grid.dotsEnabled
}
if (out.grid && typeof out.grid.dotsColor !== 'string') {
out.grid.dotsColor = DEFAULT_POSTFX.grid.dotsColor
}
if (out.grid && typeof out.grid.dotsAlpha !== 'number') {
out.grid.dotsAlpha = DEFAULT_POSTFX.grid.dotsAlpha
}
if (out.grid && typeof out.grid.dotsDiameter !== 'number') {
out.grid.dotsDiameter = DEFAULT_POSTFX.grid.dotsDiameter
}
if (out.grid && typeof out.grid.crossEnabled !== 'boolean') {
out.grid.crossEnabled = DEFAULT_POSTFX.grid.crossEnabled
}
if (out.grid && typeof out.grid.crossColor !== 'string') {
out.grid.crossColor = DEFAULT_POSTFX.grid.crossColor
}
if (out.grid && typeof out.grid.crossAlpha !== 'number') {
out.grid.crossAlpha = DEFAULT_POSTFX.grid.crossAlpha
}
if (out.grid && typeof out.grid.crossLength !== 'number') {
out.grid.crossLength = DEFAULT_POSTFX.grid.crossLength
}
if (out.grid && typeof out.grid.crossWidth !== 'number') {
out.grid.crossWidth = DEFAULT_POSTFX.grid.crossWidth
}
return out as PostFxSettings
}
// Shared serializable contract; donor defaults remain available.
export * from '../../../core/roverScene/postFx';
@@ -0,0 +1,17 @@
import {useEffect,type RefObject} from 'react';
import * as pc from 'playcanvas';
export function useLutTexture(appRef:RefObject<pc.Application|null>,frameRef:RefObject<any>,textureRef:RefObject<pc.Texture|null>,url:string|null|undefined,ready:boolean,onError?:()=>void){
useEffect(()=>{
const app=appRef.current;let cancelled=false;
const clear=()=>{if(frameRef.current?.colorLUT){frameRef.current.colorLUT.texture=null;frameRef.current.update?.();}textureRef.current?.destroy();textureRef.current=null;};
clear();if(!app||!ready||!url)return;
const img=new Image();img.onload=()=>{
if(cancelled)return;
if(img.width!==256||img.height!==16){onError?.();return;}
const texture=new pc.Texture(app.graphicsDevice,{name:'Rover color LUT',format:pc.PIXELFORMAT_SRGBA8,mipmaps:false,minFilter:pc.FILTER_LINEAR,magFilter:pc.FILTER_LINEAR,addressU:pc.ADDRESS_CLAMP_TO_EDGE,addressV:pc.ADDRESS_CLAMP_TO_EDGE});
texture.setSource(img);textureRef.current=texture;
if(frameRef.current?.colorLUT){frameRef.current.colorLUT.texture=texture;frameRef.current.update?.();}
};img.onerror=()=>{if(!cancelled)onError?.();};img.src=url;
return()=>{cancelled=true;clear();};
},[appRef,frameRef,textureRef,url,ready,onError]);
}
@@ -0,0 +1,83 @@
import {useEffect,useRef,type RefObject} from 'react';
import * as pc from 'playcanvas';
import type {MaterialSpec,TextureSlot} from '../../../core/roverScene/sceneDocument';
export type SceneMaterialsProps={materials?:Record<string,MaterialSpec>;assignments?:Record<string,string>;editing?:boolean;onMaterialPick?:(id:string,group:string)=>void;onTextureState?:(state:'loading'|'ready'|'error')=>void};
const maps:Record<TextureSlot,string>={diffuse:'diffuseMap',normal:'normalMap',metalness:'metalnessMap',roughness:'glossMap',opacity:'opacityMap',emissive:'emissiveMap',ao:'aoMap'};
export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRef:RefObject<pc.Entity|null>,canvasRef:RefObject<HTMLCanvasElement|null>,modelVersion:number,{materials,assignments,editing,onMaterialPick,onTextureState}:SceneMaterialsProps){
const latest=useRef({materials,onMaterialPick,onTextureState});latest.current={materials,onMaterialPick,onTextureState};
const textures=useRef(new Map<string,{texture?:pc.Texture;promise:Promise<pc.Texture>}>());
const generation=useRef(0);
const originalGroups=useRef(new WeakMap<pc.MeshInstance,{id:string;material:pc.StandardMaterial}>());
const customMaterials=useRef(new Map<string,pc.StandardMaterial>());
useEffect(()=>{
const app=appRef.current;if(!app||!modelVersion||!materials)return;
const current=++generation.current;let pending=0,failed=false;
const map=new Map<string,pc.StandardMaterial>();
for(const component of (app.root.findByName('ModelRoot') as pc.Entity|null)?.findComponents('render')??[])for(const mi of (component as pc.RenderComponent).meshInstances){
if(!(mi.material instanceof pc.StandardMaterial))continue;
if(!originalGroups.current.has(mi))originalGroups.current.set(mi,{id:mi.material.name,material:mi.material});
const source=originalGroups.current.get(mi)!;map.set(source.id,source.material);
}
for(const id of Object.keys(materials))if(id.startsWith('custom/')){
if(!customMaterials.current.has(id)){const m=new pc.StandardMaterial();m.name=id;customMaterials.current.set(id,m);}
map.set(id,customMaterials.current.get(id)!);
}
for(const component of (app.root.findByName('ModelRoot') as pc.Entity|null)?.findComponents('render')??[])for(const mi of (component as pc.RenderComponent).meshInstances){
const source=originalGroups.current.get(mi);if(source)mi.material=map.get(assignments?.[source.id]??source.id)??source.material;
}
for(const [id,m] of customMaterials.current)if(!Object.hasOwn(materials,id)){m.destroy();customMaterials.current.delete(id);}
const applyTexture=(m:pc.StandardMaterial,slot:TextureSlot,texture:pc.Texture|null,spec:MaterialSpec)=>{
(m as any)[maps[slot]]=texture;
const prefix=maps[slot];(m as any)[prefix+'Tiling']=new pc.Vec2(spec.tiling,spec.tiling);
if(['metalness','roughness','opacity','ao'].includes(slot))(m as any)[prefix+'Channel']='r';
m.update();
};
const used=new Set<string>();
for(const [id,spec] of Object.entries(materials)){
const m=map.get(id);if(!m)continue;
m.diffuse.fromString(spec.color);m.useMetalness=true;m.metalness=spec.metalness;
m.glossInvert=true;m.gloss=spec.roughness;m.opacity=spec.opacity;
// Specular factor is independent from the donor's global IBL multiplier.
m.specularityFactor=spec.reflectivity;m.clearCoat=spec.clearCoat;
m.clearCoatGlossInvert=true;m.clearCoatGloss=spec.clearCoatRoughness;
m.emissive.fromString(spec.emissive);m.emissiveIntensity=spec.emissiveIntensity;
m.bumpiness=spec.normalStrength;m.cull=spec.doubleSided?pc.CULLFACE_NONE:pc.CULLFACE_BACK;
m.blendType=spec.opacity<1||spec.textures.opacity?pc.BLEND_NORMAL:pc.BLEND_NONE;
m.depthWrite=m.blendType===pc.BLEND_NONE;
for(const slot of Object.keys(maps) as TextureSlot[]){
const data=spec.textures[slot]?.data;if(!data){applyTexture(m,slot,null,spec);continue;}
const srgb=slot==='diffuse'||slot==='emissive';const key=`${srgb}:${data}`;used.add(key);
let item=textures.current.get(key);
if(!item){
const promise=new Promise<pc.Texture>((resolve,reject)=>{const img=new Image();img.onload=()=>{if(generation.current<0){reject(new Error('Scene disposed'));return;}const tex=new pc.Texture(app.graphicsDevice,{name:spec.textures[slot]?.name,format:srgb?pc.PIXELFORMAT_SRGBA8:pc.PIXELFORMAT_RGBA8,mipmaps:true,addressU:pc.ADDRESS_REPEAT,addressV:pc.ADDRESS_REPEAT});tex.setSource(img);resolve(tex);};img.onerror=()=>reject(new Error('Texture decode failed'));img.src=data;});
item={promise};textures.current.set(key,item);const cached=item;
promise.then(tex=>{cached.texture=tex;if(textures.current.get(key)!==cached){tex.destroy();}}).catch(()=>{if(textures.current.get(key)===cached)textures.current.delete(key);});
}
if(item.texture)applyTexture(m,slot,item.texture,spec);
else{
pending++;item.promise.then(tex=>{if(generation.current===current)applyTexture(m,slot,tex,spec);}).catch(()=>{failed=true;}).finally(()=>{pending--;if(generation.current===current&&!pending)latest.current.onTextureState?.(failed?'error':'ready');});
}
}
m.update();
}
for(const [key,item] of textures.current)if(!used.has(key)){item.texture?.destroy();textures.current.delete(key);}
onTextureState?.(pending?'loading':'ready');
return()=>{generation.current++;};
},[materials,assignments,modelVersion,appRef,onTextureState]);
useEffect(()=>()=>{generation.current=-1;for(const item of textures.current.values())item.texture?.destroy();textures.current.clear();for(const m of customMaterials.current.values())m.destroy();customMaterials.current.clear();},[]);
useEffect(()=>{
const app=appRef.current,canvas=canvasRef.current,camera=cameraRef.current;
if(!editing||!app||!canvas||!camera?.camera||!modelVersion)return;
const picker=new pc.Picker(app,1,1);let start:{x:number;y:number}|null=null;
const down=(e:PointerEvent)=>{start=e.button===0?{x:e.clientX,y:e.clientY}:null;};
const up=(e:PointerEvent)=>{
const p=start;start=null;if(!p||Math.hypot(p.x-e.clientX,p.y-e.clientY)>4)return;
const rect=canvas.getBoundingClientRect();picker.resize(Math.max(1,Math.floor(rect.width)),Math.max(1,Math.floor(rect.height)));
picker.prepare(camera.camera!,app.scene);
const hit=picker.getSelection(e.clientX-rect.left,e.clientY-rect.top).find(mi=>!!latest.current.materials?.[mi.material.name]);
if(hit instanceof pc.MeshInstance){const source=originalGroups.current.get(hit);if(source)latest.current.onMaterialPick?.(hit.material.name,source.id);}
};
canvas.addEventListener('pointerdown',down);canvas.addEventListener('pointerup',up);
return()=>{canvas.removeEventListener('pointerdown',down);canvas.removeEventListener('pointerup',up);picker.destroy();};
},[editing,modelVersion,appRef,cameraRef,canvasRef]);
}
@@ -2,7 +2,7 @@
.rover-view:focus-visible { outline:2px solid var(--nodedc-text-secondary); outline-offset:-2px; }
.rover-view .rover-view__scene { position:absolute; inset:0; }
.rover-view__empty { display:grid; place-content:center; height:100%; text-align:center; font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-muted); }
.rover-view__status { position:absolute; top:var(--nodedc-space-3); left:var(--nodedc-space-3); }
.rover-view__status { position:absolute; top:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)); left:var(--nodedc-space-3); }
.rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; }
.rover-view__controls > span { font-size:var(--nodedc-font-size-xs); color:var(--nodedc-text-secondary); }
.rover-keys { display:grid; gap:var(--nodedc-space-1); grid-template-columns:repeat(3,46px); }
@@ -10,7 +10,7 @@
.rover-key-KeyQ { grid-column:1; }.rover-key-KeyE { grid-column:3; }
.rover-view__authority { position:absolute; left:var(--nodedc-space-3); bottom:var(--nodedc-space-3); }
@container (max-width: 380px) {
.rover-view__authority { top:48px; bottom:auto; }
.rover-view:has(.rover-view__controls) .rover-view__authority { top:calc(var(--observation-overlay-header-space, 0px) + 48px); bottom:auto; }
}
.rover-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-3); }
.rover-settings p { font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-secondary); }
@@ -9,12 +9,14 @@ import { useComputeContours } from "../../core/system/ComputeContourContext";
interface SystemNavigationPanelProps {
title: string;
onAdd: () => void;
onNavigateRoot: () => void;
onClose: () => void;
}
export function SystemNavigationPanel({
title,
onAdd,
onNavigateRoot,
onClose,
}: SystemNavigationPanelProps) {
const { contours, selectedContour, selectContour } = useComputeContours();
@@ -40,7 +42,7 @@ export function SystemNavigationPanel({
description: contour.expected_node_id,
icon: <Icon name="apps" />,
active: selectedContour?.contour_id === contour.contour_id,
onSelect: () => selectContour(contour.contour_id),
onSelect: () => { selectContour(contour.contour_id); onNavigateRoot(); },
}))}
items={[]}
onItemChange={() => undefined}
@@ -5,7 +5,6 @@ import type { WorkspaceDefinition } from "../productModel";
interface ApplicationPanelActionsOptions {
definition: WorkspaceDefinition | null;
onAddVehicle?: () => void;
refreshRuntime: () => void;
resetConnectionScenario?: () => Promise<boolean>;
connectionScenarioResetting: boolean;
@@ -45,7 +44,6 @@ export function deviceRuntimeUtilityAction({
export function useApplicationPanelActions({
definition,
onAddVehicle,
refreshRuntime,
resetConnectionScenario,
connectionScenarioResetting,
@@ -56,7 +54,6 @@ export function useApplicationPanelActions({
}: ApplicationPanelActionsOptions): ApplicationPanelUtilityAction[] {
return useMemo(() => {
const actions: ApplicationPanelUtilityAction[] = [];
if (definition?.kind === "vehicles" && onAddVehicle) actions.push({ label: "Добавить аппарат", icon: "plus", onClick: onAddVehicle });
if (definition?.kind === "device") {
actions.push(deviceRuntimeUtilityAction({
refreshRuntime,
@@ -81,7 +78,6 @@ export function useApplicationPanelActions({
return actions;
}, [
definition,
onAddVehicle,
refreshRuntime,
resetConnectionScenario,
connectionScenarioResetting,
@@ -0,0 +1,62 @@
import type {CellularNetwork,CellularStamp,TrackerTelemetry} from './vps';
export function cellularFresh(value:CellularStamp|undefined,now=Date.now()/1000){
return !!value&&now-value.measured_at>=0&&now-value.measured_at<90;
}
// Public INTERNAL TAG table examples. A serving network never selects an APN.
const networks:Record<string,string>={'250:1':'МТС','250:2':'МегаФон','250:99':'Билайн'};
export function cellularCardOperator(telemetry:TrackerTelemetry|undefined,slot:string){
const card=telemetry?.sim_identity?.slots[slot];
const home=card?.binding_current?card.known_card?.home_network:undefined;
return home?({'25001':'МТС','25002':'МегаФон','25099':'Билайн'} as Record<string,string>)[home]:undefined;
}
export function cellularOperator(value:CellularNetwork|undefined){
return value?.mcc==null?undefined:networks[`${value.mcc}:${value.mnc}`];
}
/** Losing freshness does not prove card removal; retain explicitly labelled history. */
export function cellularSimOptions(telemetry:TrackerTelemetry|undefined,now=Date.now()/1000){
const status=telemetry?.cellular?.status;
if(!status||status.measured_at>now)return [];
const current=!!telemetry?.online&&cellularFresh(status,now);
return (['1','2'] as const).filter(slot=>[1,2,3,5,6].includes(status!.sim_states[slot])).map(slot=>{
const network=telemetry?.cellular?.networks[slot];
const registered=[1,5].includes(status!.sim_states[slot]);
const knownNetwork=network&&network.measured_at<=now&&(current?cellularFresh(network,now):network.measured_at<=status.measured_at);
const operator=cellularCardOperator(telemetry,slot)??(registered&&knownNetwork?cellularOperator(network):undefined);
return {value:slot,label:`SIM ${slot} (${operator??'оператор не определён'})${current?'':' · последние данные'}`};
});
}
export function cellularSimCurrent(telemetry:TrackerTelemetry|undefined,slot:number,now=Date.now()/1000){
return !!telemetry?.online&&cellularFresh(telemetry.cellular?.status,now)&&[1,2,3,5,6].includes(telemetry.cellular!.status!.sim_states[String(slot)]);
}
export function cellularNetworkLabel(value:CellularNetwork|undefined){
if(!value||value.mcc===null)return 'Оператор не определён';
const code=`${String(value.mcc).padStart(3,'0')}-${String(value.mnc).padStart(2,'0')}`;
const name=cellularOperator(value);
return name?`${name} · ${code}`:`Оператор не определён · код ${code}`;
}
export function cellularSlotDescription(telemetry:TrackerTelemetry|undefined,slot:'1'|'2',now=Date.now()/1000){
const view=cellularSlotView(telemetry,slot,now);
if(view.absent)return 'B2 не обнаружил карту. Вставленная резервная SIM может определиться при переходе на неё.';
const operator=cellularCardOperator(telemetry,slot);
if(operator)return operator;
if(view.current&&view.network?.mcc==null)return view.internet?'Интернет подключён. B2 ещё не передал код сети оператора.':'B2 ещё не передал код сети оператора.';
return cellularNetworkLabel(view.network);
}
export function cellularSlotView(telemetry:TrackerTelemetry|undefined,slot:'1'|'2',now=Date.now()/1000){
const status=telemetry?.cellular?.status;
const current=!!telemetry?.online&&cellularFresh(status,now);
const absent=current&&status?.sim_states[slot]===0;
// A fresh removal invalidates the old serving-network reading for this slot.
const network=absent?undefined:telemetry?.cellular?.networks[slot];
const selected=current&&!absent&&status?.active_sim===Number(slot);
const internet=selected&&status?.gsm_state===4;
const role=!current?'Последнее полученное состояние':absent?'SIM не обнаружена':internet?'Используется для интернета':selected?'Выбрана модемом':'Не выбрана для интернета';
return {current,absent,network,internet,role};
}
export function cellularSimLabel(value:number|undefined){
return ({0:'SIM не обнаружена',1:'Регистрация в домашней сети',2:'Поиск сети',3:'Регистрация отклонена',5:'Регистрация в роуминге',6:'Ошибка PIN'} as Record<number,string>)[value??-1]??'Нет сведений';
}
export function cellularModemLabel(value:number|undefined){
return ({0:'Модем выключен',1:'Модем включён',2:'Модем отвечает',3:'Подключение GPRS',4:'GPRS подключён'} as Record<number,string>)[value??-1]??'Нет сведений о модеме';
}
@@ -0,0 +1,29 @@
import type {EquipmentCommand,EquipmentNetworkOperation,IndependentDevice} from './equipment';
export interface CommandPreset {id:string;label:string;command:EquipmentCommand;wire:string;encoding:string;queue_seconds:number;confirmation:string;firmware:string;unavailable:string}
export interface CommandEvent {state:string;attempt?:number;stage?:string;observed_at:number;occurred_at?:number;historical:boolean}
export interface CommandEntry extends Omit<EquipmentNetworkOperation,'scope'> {sequence?:number;delivered_at?:number;delivery_seconds?:number;reconcile_pending?:boolean;received_at?:number;vps_created_at?:number;scope:string;description:Partial<CommandPreset>;firmware?:string;queue_deadline?:number;finished_at?:number;updated_at?:number;reason?:string;events:CommandEvent[]}
export interface CommandRuntime {items:CommandEntry[];tracked_items:CommandEntry[];next_before:number|null;counts:Record<string,number>;catalog:CommandPreset[];device:IndependentDevice;capacity:number|null;durable_kinds?:string[]}
export const commandPending=(state:string)=>['waiting','submitting','queued','dispatched'].includes(state);
export const commandTracked=(entry:CommandEntry)=>commandPending(entry.state)||entry.reconcile_pending===true;
export const commandStatus=(state:string)=>({delivered:'Доставлено',accepted:'Принято B2',stopped:'Повторы остановлены',attempt_started:'Начата попытка',waiting:'В очереди Core',submitting:'Передача на VPS',queued:'В очереди VPS',dispatched:'Отправлено B2',device_accepted:'Принято B2, выполняется',device_confirmed:'Подтверждено B2',device_rejected:'Отклонено B2',reconnected:'Связь после перезапуска подтверждена',expired:'Срок истёк',unconfirmed:'Результат не подтверждён',uncertain:'Результат неизвестен',cancelled:'Отменено до отправки',rejected:'Отклонено',observed:'Прочитано',verified:'Настройки проверены',sim_selected:'SIM подключена',not_applied:'Не применено'} as Record<string,string>)[state]??'Неизвестный статус';
export const commandTone=(state:string):'success'|'warning'|'neutral'=>['accepted','device_confirmed','reconnected','observed','verified','sim_selected'].includes(state)?'success':['unconfirmed','uncertain','device_rejected','rejected','not_applied','expired'].includes(state)?'warning':'neutral';
export const commandDate=(value?:number)=>value===undefined?'—':new Date(value*1000).toLocaleString('ru-RU');
export const commandDuration=(value?:number)=>value===undefined?'—':`${value.toFixed(3)} с`;
export function mergeCommands(current:CommandEntry[],incoming:CommandEntry[]):CommandEntry[]{
const values=new Map(current.map(item=>[item.id,item]));for(const item of incoming){const old=values.get(item.id);if(!old||(item.updated_at??0)>=(old.updated_at??0))values.set(item.id,item);}
return [...values.values()].sort((a,b)=>(b.sequence??0)-(a.sequence??0));
}
export function commandReason(value:CommandEntry):string{
if(value.reason==='pulse_result_unknown')return 'Импульс был отправлен, но доставка не подтверждена. Автоматический повтор может вызвать второй импульс. Проверьте результат перед повторной отправкой.';
if(value.state==='expired'&&value.vps_created_at&&!value.dispatched_at)return 'VPS не дождался готового соединения с B2 до истечения срока. Команда трекеру не отправлена.';
return ({settings_changed:'Настройки изменились после запроса повтора. Команда не отправлена.',queue_deadline:'Время ожидания в Core истекло; передача на VPS не начиналась.',device_changed:'После постановки в очередь изменилось устройство или его привязка.',host_changed:'Изменилась привязка VPS.',operator_cancelled:'Оператор отменил команду до передачи на VPS.',historical_result_missing:'Окончательный результат этой старой операции не сохранился.'} as Record<string,string>)[value.reason??'']??'';
}
export function commandReceipt(value:CommandEntry):string{
if(value.delivered_at!==undefined)return 'Доставка команды подтверждена. Это не подтверждение переключения контактов выхода.';
if(value.device_code===undefined&&value.description?.encoding?.includes('FC'))return 'Текстовый ответ B2 не содержит идентификатора команды. Исполнение по такому ответу подтвердить нельзя.';
if(value.device_code===undefined)return 'Ответ трекера не получен';
return ({0:value.kind==='restart'?'B2 принял команду перезапуска':'B2 подтвердил команду без ошибки',1:'B2 не распознал команду',2:'Недостаточно аргументов',3:'Слишком много аргументов',4:'Некорректное значение аргумента',5:'B2 сообщил об ошибке выполнения',6:'B2 принял команду; требуется время на выполнение',7:'Очередь команд B2 заполнена',8:'Подключённое устройство недоступно',9:'Подключённое устройство не ответило'} as Record<number,string>)[value.device_code]??'Неизвестный ответ B2';
}
export const commandEntryStatus=(value:CommandEntry)=>value.durable&&commandPending(value.state)&&value.stop_requested?'Остановка повторов':value.durable&&commandPending(value.state)&&value.runtime_phase&&value.runtime_phase!=='executing'?({'waiting-link':'Ожидает связи с B2','retry-wait':'Ожидает следующей попытки','checking-result':'Проверка состояния B2',reconciling:'Уточнение результата у VPS'} as Record<string,string>)[value.runtime_phase]??commandStatus(value.state):value.state==='dispatched'&&value.device_accepted_at!==undefined?commandStatus('device_accepted'):commandStatus(value.state);
@@ -0,0 +1,105 @@
/** Independent equipment is owned by Fleet, never by a vehicle's Node transport. */
export interface EquipmentPolicy {
schema_version:1;
endpoint:{host:string;port:number;slot:number}|null;
connectivity:{strategy:'preserve'|'manual'|'operator'|'sim'|'both'|'native';apn1:string;apn2:string;apn?:string|null;preset_id?:string|null;sim_slot?:number;activate?:boolean;automatic?:boolean};
parameters:Record<string,number>;
}
export interface EquipmentField {key:string;label:string;group:string;min:number;max:number}
export interface ConnectivityPreset {id:string;label:string;apn:string}
export interface EquipmentModel {id:string;label:string;fields:EquipmentField[];profile_schema:number;connectivity_presets?:ConnectivityPreset[];usb_write_firmware?:string[]}
export interface EquipmentProfile {id:string;name:string;model_id:string;settings:EquipmentPolicy;created_at:number}
export interface EquipmentObservation {
output_modes?:Record<string,number>;configuration_read_at?:number;configuration_transport?:'vps';
supported_profile_fields?:string[];read_at:number;model:string;device_id:string;imei_suffix:string;firmware:string;
sim1_iccid_reported_suffix:string|null;sim1_iccid_reported_length:number;
sim2_iccid_reported_suffix:string|null;sim2_iccid_reported_length:number;
configuration:{record_count:number;apn1:string;apn2:string;servers:{slot:number;host:string;port:number;protocol_code:number}[]};
provisioned:false;
}
export interface EquipmentCandidate {id:string;model_id:string;observed:EquipmentObservation;settings:EquipmentPolicy;expires_at:number}
export type EquipmentCommand = {kind:'request-position'}|{kind:'restart'}|{kind:'pulse-output';pin:number;seconds:number}|{kind:'set-output';pin:number;enabled:boolean};
export interface EquipmentNetworkOperation {reason?:string;id:string;durable?:boolean;runtime_phase?:string;attempt_count?:number;next_attempt_at?:number;attempt_expires_at?:number;stop_requested?:boolean;reconcile_pending?:boolean;read_only?:boolean;state:string;stage?:string;scope:'server1'|'configuration'|'sim-selection'|'command';sim_policy?:'both';sim_slot?:number;active_sim?:number;command?:EquipmentCommand;kind?:EquipmentCommand['kind']|'read-settings'|'configure-server1'|'read-configuration'|'configure-all'|'select-sim';unchanged?:boolean;record_count?:number;configuration_sha256?:string;created_at?:number;expires_at?:number;dispatched_at?:number;queue_seconds?:number;roundtrip_seconds?:number;device_code?:number;device_accepted_at?:number;reconnected_at?:number;reconnect_seconds?:number;telemetry_measured_at?:number;verified_at?:number;server1?:{host:string;port:number}}
export interface IndependentDevice {network_operation?:EquipmentNetworkOperation;network_server1?:{host:string;port:number};id:string;name:string;model_id:string;vehicle_id:string;revision:number;observed:EquipmentObservation;settings:EquipmentPolicy;profile_id:string|null;policy_state:'saved'|'applied'|'unchanged'|'uncertain'|'rolled_back'|'not_applied'|'not_started';updated_at:number}
export async function equipmentRequest<T>(path:string,method='GET',body?:unknown):Promise<T>{
const response=await fetch(`/api/v1/fleet/equipment${path}`,{method,credentials:'same-origin',cache:'no-store',headers:body===undefined?{}:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body),signal:AbortSignal.timeout(path.endsWith('/apply')?120000:45000)});
if(!response.ok){const value=await response.json().catch(()=>({}));throw new Error(typeof value.detail==='string'?value.detail:'Не удалось выполнить действие с оборудованием.');}
return response.json();
}
export const emptyEquipmentPolicy=():EquipmentPolicy=>({schema_version:1,endpoint:null,connectivity:{strategy:'preserve',apn1:'',apn2:''},parameters:{}});
/** Compare settings by value, including server defaults; JSON key order is not an edit. */
export function equipmentPolicyEqual(a:EquipmentPolicy,b:EquipmentPolicy):boolean{
const canonical=(p:EquipmentPolicy)=>{
const c=p.connectivity;
return JSON.stringify([p.schema_version,p.endpoint?[p.endpoint.host,p.endpoint.port,p.endpoint.slot]:null,[c.strategy,c.apn1,c.apn2,c.apn??null,c.preset_id??null,c.sim_slot??1,c.activate??false,c.automatic??false],Object.entries(p.parameters).sort(([x],[y])=>x.localeCompare(y))]);
};
return canonical(a)===canonical(b);
}
/** A saved SIM target does not itself request another modem restart. */
export function simSelectionIntent(draft:EquipmentPolicy,saved:EquipmentPolicy,selected:boolean):boolean{
return (['both','native'].includes(draft.connectivity.strategy)||draft.connectivity.strategy==='sim'&&draft.connectivity.activate===true)&&(selected||!equipmentPolicyEqual({...draft,endpoint:null,parameters:{}},{...saved,endpoint:null,parameters:{}}));
}
/** Selecting a SIM requests exclusive data service; keep its current APN unless edited. */
export function selectInternetSim(policy:EquipmentPolicy,slot:number):EquipmentPolicy{
if(![1,2].includes(slot))return policy;
const current=policy.connectivity;
const apn=current.strategy==='sim'&&current.sim_slot===slot?current.apn??null:null;
return {...policy,connectivity:{strategy:'sim',sim_slot:slot,activate:true,automatic:apn===null,apn,apn1:'',apn2:'',preset_id:null}};
}
export function allowBothInternetSims(policy:EquipmentPolicy,withoutApn=false):EquipmentPolicy{
return {...policy,connectivity:{strategy:withoutApn?'native':'both',apn1:'',apn2:''}};
}
export function equipmentApplyMessage(state:IndependentDevice['policy_state']):string{
return {saved:'Настройки сохранены в Mission Core.',applied:'Настройки записаны в трекер и проверены чтением.',unchanged:'Настройки трекера уже совпадают с сохранёнными.',uncertain:'Результат записи не подтверждён. Прочитайте настройки повторно перед следующим действием.',rolled_back:'Проверка записи не прошла. Предыдущие настройки восстановлены.',not_applied:'Трекер сохранил прежние настройки. Изменения не применены.',not_started:'Запись не началась. Прочитайте устройство повторно и проверьте настройки.'}[state];
}
export function policyError(policy:EquipmentPolicy,fields:EquipmentField[]):string{
if(policy.endpoint&&(!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/i.test(policy.endpoint.host)||!Number.isInteger(policy.endpoint.port)||policy.endpoint.port<1||policy.endpoint.port>65535))return 'Укажите DNS/IP и порт от 1 до 65535.';
if(policy.connectivity.strategy==='sim'&&(![1,2].includes(policy.connectivity.sim_slot??1)||!/^([A-Za-z0-9.-]{0,29})$/.test(policy.connectivity.apn??'')))return 'Проверьте APN выбранной SIM.';
if(policy.connectivity.strategy==='manual'&&!policy.connectivity.apn1.trim())return 'Укажите APN основной SIM.';
if(policy.connectivity.strategy==='operator'&&(!policy.connectivity.preset_id||![1,2].includes(policy.connectivity.sim_slot??1)))return 'Выберите настройки оператора и SIM.';
for(const [key,value]of Object.entries(policy.parameters)){const field=fields.find(f=>f.key===key);if(!field||!Number.isInteger(value)||value<field.min||value>field.max)return `Проверьте значение: ${field?.label??key}.`;}
for(const [a,b]of [['243','244'],['245','246']])if(policy.parameters[a]!==undefined&&policy.parameters[b]!==undefined&&policy.parameters[a]>policy.parameters[b])return 'Минимальное значение превышает максимальное.';
return '';
}
/** A local deadline ends the spinner, not the VPS operation or the write interlock. */
export function networkOperationProgress(operation?:EquipmentNetworkOperation,now=Date.now()/1000){
const pending=!!operation&&['submitting','queued','dispatched'].includes(operation.state);
const deadline=operation?.durable?undefined:operation?.expires_at??(operation?.created_at!==undefined?operation.created_at+240:undefined);
const overdue=pending&&deadline!==undefined&&now>=deadline;
const remaining=pending&&deadline!==undefined?Math.max(0,Math.ceil(deadline-now)):undefined;
return {pending,overdue,waiting:pending&&!overdue,remaining};
}
export function configurationWriteNotStarted(operation?:EquipmentNetworkOperation):boolean{
return !!operation&&['configuration','sim-selection'].includes(operation.scope)&&!operation.read_only&&operation.stage==='preflight'&&['unconfirmed','expired'].includes(operation.state);
}
export function networkOperationMessage(operation?:EquipmentNetworkOperation):string{
if(operation?.reason==='sim_card_changed')return 'Карта в выбранном слоте изменилась. Выберите SIM заново и сохраните настройки.';
if(!operation)return 'Сохранение профиля и подтверждение трекером отображаются отдельно.';
if(operation.durable){
if(operation.stop_requested&&['submitting','queued','dispatched'].includes(operation.state))return 'Останавливаем дальнейшие повторы. Уже отправленная попытка может завершиться.';
if(operation.state==='stopped')return 'Дальнейшие попытки остановлены. История отправок сохранена.';
if(operation.state==='accepted')return 'B2 подтвердил приём команды перезапуска. Возвращение на связь пока не подтверждено; повторного перезапуска не будет.';
if(['submitting','queued','dispatched'].includes(operation.state))return ({reconciling:'Уточняем сохранённый результат у VPS. Задание остаётся в очереди.', 'waiting-identity':'Ожидаем подтверждение карты в выбранном слоте. Настройки пока не отправляются.', 'waiting-link':'Задание сохранено. Ожидаем свежую связь с B2.', 'retry-wait':'Ответ предыдущей попытки не подтверждён. Задание ожидает следующую попытку.', 'checking-result':'Читаем фактические настройки B2 перед решением о повторной записи.', executing:operation.stage==='preflight'?'Читаем текущую конфигурацию B2…':operation.stage==='write'?'Передаём настройки B2…':operation.stage==='verify'?'Проверяем настройки повторным чтением…':operation.stage==='restart'?'Настройки проверены. Ожидаем свежую связь после перезапуска B2…':'Ожидаем результат текущей попытки от B2.'} as Record<string,string>)[operation.runtime_phase??'']??'Задание сохранено. Передаём его на VPS…';
}
if(operation.scope==='command'&&operation.command?.kind==='restart'){
if(operation.state==='dispatched')return 'Команда перезапуска отправлена. Ожидаем свежие данные по новому соединению.';
if(operation.state==='reconnected')return 'После команды перезапуска трекер прислал свежие данные по новому соединению.';
if(operation.state==='unconfirmed')return 'Команда отправлена, но возвращение трекера на связь не подтверждено. Автоматического повторения не будет.';
}
if(operation.scope==='command')return ({submitting:'Передача команды на VPS…',queued:'VPS ожидает соединение с трекером…',dispatched:'Команда отправлена трекеру. Ожидаем ответ.',device_confirmed:'Трекер подтвердил приём команды.',device_rejected:'Трекер отклонил команду.',expired:'Срок отправки истёк. Команда не отправлена.',unconfirmed:'Команда отправлена, но её выполнение не подтверждено отдельным ответом.',uncertain:'Результат команды неизвестен. Автоматического повторения не будет.'} as Record<string,string>)[operation.state]??'Статус команды недоступен.';
if(configurationWriteNotStarted(operation))return 'Трекер не прислал конфигурацию до истечения срока ожидания. Запись настроек не началась. Прочитайте настройки через VPS перед новой попыткой.';
if(operation.scope==='sim-selection'){
if(operation.sim_policy==='both'){
if(operation.state==='sim_selected')return `Обе SIM разрешены. Связь через SIM ${operation.active_sim} подтверждена свежими данными B2.`;
if(operation.stage==='restart')return ['queued','dispatched'].includes(operation.state)?'Обе SIM разрешены. Перезапускаем B2 и ждём восстановления интернета…':'Настройки записаны, но возвращение B2 на связь пока не подтверждено.';
}
if(operation.state==='sim_selected')return `SIM ${operation.active_sim} подключена к интернету. Получены свежие данные B2 через VPS.`;
if(operation.stage==='restart')return ['queued','dispatched'].includes(operation.state)?`Настройки проверены. Перезапускаем B2 и ждём интернет через SIM ${operation.sim_slot}…`:`Настройки записаны, но интернет через SIM ${operation.sim_slot} не подтверждён. Повторного перезапуска не будет.`;
}
if(['configuration','sim-selection'].includes(operation.scope))return ({submitting:'Передача запроса на VPS…',queued:'Ожидание следующего шага обмена с трекером…',dispatched:operation.stage==='preflight'?'Чтение полной конфигурации трекера…':operation.stage==='write'?'Передача настроек трекеру…':'Повторное чтение и проверка записи…',observed:`Конфигурация прочитана с трекера: ${operation.record_count??'—'} параметров.`,verified:operation.unchanged?'Настройки B2 уже совпадают с сохранённым профилем.':'Настройки записаны в B2 и подтверждены повторным чтением.',rejected:'Запись отменена: конфигурация трекера изменилась либо затронут резервный канал связи. Прочитайте настройки повторно.',not_applied:'Трекер сохранил прежние настройки.',expired:'Срок операции истёк. Начните с повторного чтения.',uncertain:'Результат записи не подтверждён. Автоматического повтора не будет.',unconfirmed:operation.stage==='preflight'?'Выгрузка настроек не получена. Прочитайте устройство повторно.':'Завершение записи не подтверждено. Прочитайте настройки B2 повторно.'} as Record<string,string>)[operation.state]??'Статус операции недоступен.';
if(operation.state==='observed')return `Сервер 1 прочитан с трекера: ${operation.server1?.host}:${operation.server1?.port}.`;
if(operation.state==='verified')return `Сервер 1 подтверждён трекером: ${operation.server1?.host}:${operation.server1?.port}. Проверено ${new Date((operation.verified_at??0)*1000).toLocaleString('ru-RU')}.`;
return ({submitting:'Отправка запроса на VPS…',queued:'Ожидание связи с трекером…',dispatched:operation.stage==='preflight'?'Чтение текущих настроек трекера…':operation.stage==='write'?'Запись адреса сервера…':'Проверка адреса сервера повторным чтением…',rejected:'Запись отменена: текущие настройки трекера отличаются от ожидаемых.',not_applied:'Трекер сохранил прежний адрес сервера.',expired:'Трекер не вышел на связь. Запись не началась.',uncertain:'Результат записи не подтверждён. Повторная запись автоматически не выполняется.',unconfirmed:'Ответ не получен. Результат записи не подтверждён.'} as Record<string,string>)[operation.state]??'Статус операции недоступен.';
}
@@ -0,0 +1,27 @@
export interface FirmwareImage {
id:string;model_id:string;filename:string;bytes:number;sha256:string;added_at:number;
version:string|null;source_url:string|null;source:'manufacturer'|'user';installable:false;
}
export interface FirmwareCatalog {items:FirmwareImage[];update_available:false}
const root='/api/v1/fleet/equipment/firmware';
async function response(url:string,init:RequestInit={}){
const value=await fetch(url,{...init,credentials:'same-origin',cache:'no-store',signal:AbortSignal.timeout(30000)});
if(!value.ok){const error=await value.json().catch(()=>({}));throw new Error(typeof error.detail==='string'?error.detail:'Архив прошивок недоступен. Повторите действие.');}
return value;
}
export async function readFirmware(model:string):Promise<FirmwareCatalog>{
return (await response(`${root}/${encodeURIComponent(model)}`)).json();
}
export async function uploadFirmware(model:string,file:File):Promise<FirmwareImage>{
if(!/\.dfw$/i.test(file.name)||file.size===0||file.size>4*1024*1024)throw new Error('Выберите непустой файл .dfw размером до 4 МБ.');
return (await response(`${root}/${encodeURIComponent(model)}?filename=${encodeURIComponent(file.name)}`,{method:'POST',headers:{'Content-Type':'application/octet-stream'},body:file})).json();
}
export async function downloadFirmware(image:FirmwareImage):Promise<void>{
const value=await response(`${root}/${encodeURIComponent(image.model_id)}/${image.id}/download`);
const data=await value.arrayBuffer();
const digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',data)),b=>b.toString(16).padStart(2,'0')).join('');
if(digest!==image.sha256||data.byteLength!==image.bytes)throw new Error('Контрольная сумма файла не совпала. Скачивание отменено.');
const url=URL.createObjectURL(new Blob([data],{type:'application/octet-stream'}));
const anchor=document.createElement('a');anchor.href=url;anchor.download=image.filename;
document.body.append(anchor);anchor.click();anchor.remove();setTimeout(()=>URL.revokeObjectURL(url),1000);
}
@@ -1,12 +1,13 @@
export interface ObservationLayout {
version:1; order:string[]; hidden:string[]; layers:Record<string,string>;
splits:Record<string,number>; arrangement:'auto'|'columns'|'rows';
catalogVisible?:string[]; splits:Record<string,number>; arrangement:'auto'|'columns'|'rows';
}
export const emptyObservationLayout=():ObservationLayout=>({version:1,order:[],hidden:[],layers:{},splits:{},arrangement:'auto'});
const record=(value:unknown):Record<string,unknown>=>value!==null&&typeof value==='object'&&!Array.isArray(value)?value as Record<string,unknown>:{};
export function decodeObservationLayout(value:unknown):ObservationLayout {
const source=record(value),result=emptyObservationLayout();if(source.version!==1)return result;
const ids=(value:unknown)=>Array.isArray(value)?[...new Set(value.filter((v):v is string=>typeof v==='string'&&v.length<512))].slice(0,128):[];
if(source.catalogVisible!==undefined)result.catalogVisible=ids(source.catalogVisible);
result.order=ids(source.order);result.hidden=ids(source.hidden);
result.layers=Object.fromEntries(Object.entries(record(source.layers)).filter(([k,v])=>k.length<512&&typeof v==='string'&&v.length<128).slice(0,128)) as Record<string,string>;
result.splits=Object.fromEntries(Object.entries(record(source.splits)).filter(([k,v])=>k.length<4096&&typeof v==='number'&&Number.isFinite(v)).slice(0,256).map(([k,v])=>[k,Math.min(80,Math.max(20,v as number))]));
@@ -0,0 +1,17 @@
import {useEffect,useState} from 'react';
import {equipmentRequest} from './equipment';
import {commandPending,type CommandEntry} from './commandRuntime';
export interface CommandAttempt {id:string;number:number;phase:string;state:string;observed_at:number;dispatched_at?:number;received_at?:number;device_accepted_at?:number;device_code?:number;roundtrip_seconds?:number}
interface Page {items:CommandAttempt[];next_before:number|null}
export function useCommandAttempts(identifier:string,entry:CommandEntry){
const [page,setPage]=useState<Page>({items:[],next_before:null}),[error,setError]=useState(''),[working,setWorking]=useState(false),[retry,setRetry]=useState(0);
const path=`/instances/${identifier}/commands/${entry.id}/attempts`;
useEffect(()=>{
if(!entry.durable)return;
let active=true;let timer:ReturnType<typeof setTimeout>;
async function read(){try{const value=await equipmentRequest<Page>(path);if(active){setPage(old=>({items:[...new Map([...old.items,...value.items].map(item=>[item.number,item])).values()].sort((a,b)=>b.number-a.number),next_before:old.items.length>20?old.next_before:value.next_before}));setError('');}}catch(e){if(active)setError(e instanceof Error?e.message:'История попыток недоступна.');}finally{if(active&&commandPending(entry.state))timer=setTimeout(()=>void read(),3000);}}
void read();return()=>{active=false;clearTimeout(timer);};
},[path,entry.durable,entry.state,retry]);
async function more(){if(page.next_before===null||working)return;setWorking(true);try{const value=await equipmentRequest<Page>(`${path}?before=${page.next_before}`);setPage(old=>({items:[...new Map([...old.items,...value.items].map(item=>[item.number,item])).values()].sort((a,b)=>b.number-a.number),next_before:value.next_before}));setError('');}catch(e){setError(e instanceof Error?e.message:'История попыток недоступна.');}finally{setWorking(false);}}
return {...page,error,working,more,refresh:()=>setRetry(n=>n+1)};
}
@@ -0,0 +1,31 @@
import {useCallback,useEffect,useRef,useState} from 'react';
import {equipmentRequest} from './equipment';
import {commandTracked,mergeCommands,type CommandEntry,type CommandRuntime} from './commandRuntime';
type Intent={request_id:string;preset_id?:string;repeat_of?:string};
export function useCommandRuntime(identifier:string){
const path=`/instances/${identifier}/commands`,key=`missioncore.command-intent.${identifier}`;
const [data,setData]=useState<CommandRuntime|null>(null),[items,setItems]=useState<CommandEntry[]>([]),[before,setBefore]=useState<number|null>(null),[error,setError]=useState(''),[activity,setActivity]=useState('');
const alive=useRef(true),sending=useRef(false),first=useRef(true);
const tracked=useRef<string[]>([]);
const [intent,setIntent]=useState<Intent|null>(()=>{try{const v=JSON.parse(localStorage.getItem(key)??'null');return v&&/^[a-f0-9]{32}$/.test(v.request_id)&&(typeof v.preset_id==='string'||typeof v.repeat_of==='string')?v:null;}catch{return null;}});
const accept=useCallback((value:CommandRuntime)=>{if(!alive.current)return;tracked.current=value.tracked_items.filter(commandTracked).map(item=>item.id).slice(0,32);setData(value);setItems(old=>mergeCommands(old,[...value.items,...value.tracked_items]));if(first.current){first.current=false;setBefore(value.next_before);}setError('');},[]);
const refresh=useCallback(async()=>{const query=new URLSearchParams();for(const id of tracked.current)query.append('tracked',id);accept(await equipmentRequest<CommandRuntime>(`${path}?${query}`));},[path,accept]);
useEffect(()=>{alive.current=true;let timer:ReturnType<typeof setTimeout>;async function poll(){try{await refresh();}catch(e){if(alive.current)setError(e instanceof Error?e.message:'Журнал временно недоступен.');}finally{if(alive.current)timer=setTimeout(()=>void poll(),2000);}}void poll();return()=>{alive.current=false;clearTimeout(timer);};},[refresh]);
useEffect(()=>{if(intent&&items.some(item=>item.id===intent.request_id)){localStorage.removeItem(key);setIntent(null);}},[items,intent,key]);
async function send(preset:string,repeatOf?:string){
if(sending.current)return;sending.current=true;setActivity(repeatOf?`repeat:${repeatOf}`:'send');setError('');
const request=intent??{request_id:crypto.randomUUID().replaceAll('-',''),...(repeatOf?{repeat_of:repeatOf}:{preset_id:preset})};
try{
// Persist the request ID before HTTP. A lost reply/reopened window reuses it.
localStorage.setItem(key,JSON.stringify(request));setIntent(request);
const response=await fetch(`/api/v1/fleet/equipment${path}${request.repeat_of?`/${request.repeat_of}/repeat`:''}`,{method:'POST',credentials:'same-origin',cache:'no-store',headers:{'Content-Type':'application/json'},body:JSON.stringify(request.repeat_of?{request_id:request.request_id}:request),signal:AbortSignal.timeout(15000)});
if(!response.ok){const value=await response.json().catch(()=>({}));if(response.status>=400&&response.status<500){localStorage.removeItem(key);if(alive.current)setIntent(null);}throw new Error(value.detail??'Ответ на отправку не получен. Уточните её с тем же ID.');}
localStorage.removeItem(key);if(alive.current)setIntent(null);await refresh();
}catch(e){if(alive.current)setError(e instanceof Error?e.message:'Ответ не получен. Уточните отправку с тем же ID.');}
finally{sending.current=false;if(alive.current)setActivity('');}
}
async function cancel(id:string){setActivity(id);try{await equipmentRequest(`${path}/${id}/cancel`,'POST');await refresh();}catch(e){setError(e instanceof Error?e.message:'Отмена не подтверждена.');}finally{if(alive.current)setActivity('');}}
async function more(){if(before===null)return;setActivity('more');try{const value=await equipmentRequest<CommandRuntime>(`${path}?before=${before}`);if(alive.current){setItems(old=>mergeCommands(old,value.items));setBefore(value.next_before);}}catch(e){setError(e instanceof Error?e.message:'Не удалось прочитать историю.');}finally{if(alive.current)setActivity('');}}
return {data,items,before,error,setError,working:!!activity,activity,intent,send,repeat:(id:string)=>send('',id),cancel,more,refresh};
}
@@ -57,5 +57,8 @@ export function useFleet() {
events.onerror = unavailable;
return () => { active = false; events.close(); if (fallback) clearInterval(fallback); };
}, []);
return { items, error, refresh };
const acceptVehicle = useCallback((vehicle: Vehicle) => {
setItems(current => current?.map(item => item.id === vehicle.id ? vehicle : item) ?? null);
}, []);
return { items, error, refresh, acceptVehicle };
}
@@ -0,0 +1,26 @@
import {useEffect,useState} from 'react';
export interface VPSHost {id:string;name:string;endpoint:string;network_interface?:string|null;vehicle_ids:string[];revision:number;state:'pending'|'paired';last_sync_at:number|null;status:{version:string;tracker:{host:string;port:number};pending_packages:number;devices:number;capabilities:string[]}|null}
export interface TrackerPosition {instance_id:string;host_id:string;latitude:number;longitude:number;measured_at:number;received_at:number;source:'gnss'|'lbs'|'wifi';satellites:number|null;course:number;speed_kmh:number}
export interface TrackerOutputs {pins:Record<string,boolean>;host_id:string;measured_at:number;received_at:number}
export interface CellularStamp {measured_at:number;received_at:number}
export interface CellularStatus extends CellularStamp {gsm_state:number;active_sim:1|2;sim_states:Record<string,number>}
export interface CellularNetwork extends CellularStamp {mcc:number|null;mnc:number;signal:number|null}
export interface TrackerCellular {host_id:string;status?:CellularStatus;networks:Record<string,CellularNetwork>}
export interface InternetAccess {state:'ready'|'waiting_identity'|'unknown_card'|'unsupported_operator';source?:'verified_card'|'carrier_candidate';apn?:string;home_network?:string;card_ref?:string}
export interface TrackerTelemetry {instance_id:string;name:string;vehicle_id:string;position:TrackerPosition|null;last_packet_at:number|null;online:boolean;position_fresh:boolean;outputs?:TrackerOutputs|null;outputs_fresh?:boolean;cellular?:TrackerCellular|null;internet_access?:Record<string,InternetAccess>|null;sim_identity?:{slots:Record<string,{binding_current?:boolean;known_card?:{home_network:string;card_ref:string}|null}>}|null}
export async function vpsRequest<T>(path='',method='GET',body?:unknown):Promise<T>{
const response=await fetch(`/api/v1/fleet/vps-hosts${path}`,{method,cache:'no-store',credentials:'same-origin',headers:body===undefined?{}:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body),signal:AbortSignal.timeout(45000)});
if(!response.ok){const data=await response.json().catch(()=>({}));throw new Error(typeof data.detail==='string'?data.detail:'VPS недоступен. Повторите действие.');}
return response.json();
}
export function hostOnline(host:VPSHost){return !!host.last_sync_at&&Date.now()/1000-host.last_sync_at<30;}
export function telemetryLabel(item:TrackerTelemetry|undefined){return item?.online?'Передаёт данные на VPS':item?.last_packet_at?`Последний пакет: ${new Date(item.last_packet_at*1000).toLocaleString('ru-RU')}`:'Ожидание первого пакета на VPS';}
export function useTrackerTelemetry(vehicleID:string){
const [items,setItems]=useState<TrackerTelemetry[]>([]),[unavailable,setUnavailable]=useState(false);
useEffect(()=>{let active=true;let timer:ReturnType<typeof setTimeout>;setItems([]);
async function poll(){try{const value=await vpsRequest<{items:TrackerTelemetry[]}>(`/telemetry?vehicle_id=${encodeURIComponent(vehicleID)}`);if(active){setItems(value.items);setUnavailable(false);}}catch{if(active)setUnavailable(true);}finally{if(active)timer=setTimeout(()=>void poll(),5000);}}
void poll();return()=>{active=false;clearTimeout(timer);};
},[vehicleID]);
return {items,unavailable};
}
@@ -0,0 +1,21 @@
import {useEffect,useRef} from 'react';
/** Recover the existing renderer only after its own gateway is reachable again. */
export function useMapRecovery(unavailable:boolean,retry:()=>void){
const callback=useRef(retry);callback.current=retry;
useEffect(()=>{
if(!unavailable)return;
let active=true;let timer:ReturnType<typeof setTimeout>;
const abort=new AbortController();
async function check(){
try{
const response=await fetch('/api/v1/map/gateway/health',{credentials:'same-origin',cache:'no-store',signal:AbortSignal.any([abort.signal,AbortSignal.timeout(10000)])});
const value=response.ok?await response.json():null;
if(active&&value?.ok===true){callback.current();return;}
}catch{/* Retain the unavailable state; no public-provider fallback. */}
if(active)timer=setTimeout(()=>void check(),30000);
}
timer=setTimeout(()=>void check(),30000);
return()=>{active=false;abort.abort();clearTimeout(timer);};
},[unavailable]);
}
@@ -37,5 +37,5 @@ export function useSessionOverviewMode(enabled: boolean) {
window.addEventListener("keydown", close, true);
return () => window.removeEventListener("keydown", close, true);
}, [open]);
return { open: enabled && open, toggle: useCallback(() => setOpen(v => !v), []) };
return { open: enabled && open, close: useCallback(() => setOpen(false), []), toggle: useCallback(() => setOpen(v => !v), []) };
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,399 @@
export type PostFxSettings = {
lighting: {
ambientIntensity: number
exposure: number
skyBoxIntensity: number
}
envAtlas: {
enabled: boolean
background: boolean
reflection: boolean
intensity: number
reflectionIntensity: number
brightness: number
contrast: number
saturation: number
toneMapping: number
mip: number
rotation: number
}
skybox: {
enabled: boolean
background: boolean
reflection: boolean
intensity: number
reflectionIntensity: number
mip: number
rotation: number
colorA: string
colorB: string
}
rendering: {
backgroundColor: string
wireframe: boolean
renderFormat: number
renderFormatFallback0: number
renderFormatFallback1: number
stencil: boolean
renderTargetScale: number
samples: number
sharpness: number
toneMapping: number
sceneColorMap: boolean
sceneDepthMap: boolean
fog: 'none' | 'linear' | 'exp' | 'exp2'
fogColor: string
fogRange: [number, number]
fogDensity: number
fogStart: number
fogEnd: number
}
grid: {
step: number
diameter: number
enabled: boolean
colorX: string
colorZ: string
colorMain: string
alphaX: number
alphaZ: number
alphaMain: number
dotsEnabled: boolean
dotsColor: string
dotsAlpha: number
dotsDiameter: number
crossEnabled: boolean
crossColor: string
crossAlpha: number
crossLength: number
crossWidth: number
fadeStart: number
fadeEnd: number
}
ssao: {
type: 'none' | 'lighting' | 'combine'
blurEnabled: boolean
intensity: number
radius: number
samples: number
power: number
minAngle: number
scale: number
}
bloom: {
enabled: boolean
intensity: number
lastMipLevel: number
}
chromaticAberration: {
enabled: boolean
intensity: number
}
taa: {
enabled: boolean
jitter: number
}
grading: {
enabled: boolean
brightness: number
contrast: number
saturation: number
tint: string
}
lut: {
intensity: number
textureUrl?: string | null
}
vignette: {
enabled: boolean
intensity: number
inner: number
outer: number
curvature: number
color: string
}
directionalLight: {
enabled: boolean
color: string
intensity: number
azimuth: number
elevation: number
castShadows: boolean
shadowIntensity: number
shadowDistance: number
shadowResolution: number
shadowBias: number
normalOffsetBias: number
shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3'
vsmBlurSize: number
}
shadowCatcher: {
enabled: boolean
size: number
yOffset: number
lightIntensity: number
lightColor: string
lightAzimuth: number
lightElevation: number
shadowIntensity: number
shadowDistance: number
shadowResolution: number
shadowBias: number
normalOffsetBias: number
shadowType: 'vsm16' | 'vsm32' | 'pcf1' | 'pcf3'
vsmBlurSize: number
}
}
export const DEFAULT_POSTFX: PostFxSettings = {
lighting: {
ambientIntensity: 0,
exposure: 1.21,
skyBoxIntensity: 0.86,
},
envAtlas: {
enabled: true,
background: false,
reflection: true,
intensity: 0.76,
reflectionIntensity: 0.6,
brightness: 1.65,
contrast: 1,
saturation: 1,
toneMapping: 0,
mip: 1,
rotation: 247,
},
skybox: {
enabled: false,
background: false,
reflection: true,
intensity: 0.62,
reflectionIntensity: 1,
mip: 0,
rotation: 0,
colorA: '#c5bfbf',
colorB: '#c7bcbc',
},
rendering: {
backgroundColor: '#111113',
wireframe: false,
renderFormat: 18,
renderFormatFallback0: 12,
renderFormatFallback1: 14,
stencil: false,
renderTargetScale: 1,
samples: 4,
sharpness: 0,
toneMapping: 4,
sceneColorMap: false,
sceneDepthMap: false,
fog: 'exp',
fogColor: '#dcc2ff',
fogRange: [0, 100],
fogDensity: 0.008,
fogStart: 0,
fogEnd: 100,
},
grid: {
step: 1,
diameter: 1000,
enabled: true,
colorX: '#ffffff',
colorZ: '#ffffff',
colorMain: '#7a3cff',
alphaX: 0.18,
alphaZ: 0.18,
alphaMain: 0.6,
dotsEnabled: false,
dotsColor: '#ffffff',
dotsAlpha: 0.5,
dotsDiameter: 0.06,
crossEnabled: false,
crossColor: '#ffffff',
crossAlpha: 0.5,
crossLength: 0.5,
crossWidth: 0.06,
fadeStart: 0,
fadeEnd: 0,
},
ssao: {
type: 'none',
blurEnabled: true,
intensity: 0.5,
radius: 30,
samples: 12,
power: 6,
minAngle: 10,
scale: 1,
},
bloom: {
enabled: true,
intensity: 0.03,
lastMipLevel: 4,
},
chromaticAberration: {
enabled: true,
intensity: 30,
},
taa: {
enabled: false,
jitter: 1,
},
grading: {
enabled: true,
brightness: 0.837,
contrast: 1.1,
saturation: 1.126,
tint: '#ffffff',
},
lut: {
intensity: 1,
textureUrl: null,
},
vignette: {
enabled: true,
intensity: 1,
inner: 0.25,
outer: 1.52,
curvature: 0.78,
color: '#000000',
},
directionalLight: {
enabled: true,
color: '#ffffff',
intensity: 0.4,
azimuth: 0,
elevation: 0,
castShadows: false,
shadowIntensity: 0.5,
shadowDistance: 16,
shadowResolution: 1024,
shadowBias: 0,
normalOffsetBias: 0,
shadowType: 'vsm16',
vsmBlurSize: 8,
},
shadowCatcher: {
enabled: true,
size: 9,
yOffset: 0.001,
lightIntensity: 0.3,
lightColor: '#ffffff',
lightAzimuth: 20,
lightElevation: 60,
shadowIntensity: 0.29,
shadowDistance: 16,
shadowResolution: 2048,
shadowBias: 0,
normalOffsetBias: 0,
shadowType: 'vsm16',
vsmBlurSize: 8,
},
}
function isObject(value: any): value is Record<string, any> {
return !!value && typeof value === 'object' && !Array.isArray(value)
}
export function mergePostFxDefaults(raw?: Partial<PostFxSettings> | null): PostFxSettings {
if (!raw) return JSON.parse(JSON.stringify(DEFAULT_POSTFX)) as PostFxSettings
const out: any = JSON.parse(JSON.stringify(DEFAULT_POSTFX))
const merge = (target: any, source: any) => {
if (!isObject(source)) return
for (const [key, value] of Object.entries(source)) {
if (isObject(value)) {
if (!isObject(target[key])) target[key] = {}
merge(target[key], value)
} else {
target[key] = value
}
}
}
merge(out, raw)
const legacy: any = raw as any
if (legacy?.hdrLight) {
const src = legacy.hdrLight
const env = legacy?.envAtlas ?? {}
if (env?.enabled === undefined && typeof src.enabled === 'boolean') out.envAtlas.enabled = src.enabled
if (env?.background === undefined && typeof src.showSkybox === 'boolean') out.envAtlas.background = src.showSkybox
if (env?.intensity === undefined && typeof src.intensity === 'number') out.envAtlas.intensity = src.intensity
if (env?.mip === undefined && typeof src.mip === 'number') out.envAtlas.mip = src.mip
if (env?.rotation === undefined && typeof src.rotation === 'number') out.envAtlas.rotation = src.rotation
}
if (legacy?.hdrReflection && (legacy?.envAtlas?.reflection === undefined)) {
if (typeof legacy.hdrReflection.enabled === 'boolean') {
out.envAtlas.reflection = legacy.hdrReflection.enabled
}
}
if (out.envAtlas && typeof out.envAtlas.reflectionIntensity !== 'number') {
out.envAtlas.reflectionIntensity = out.envAtlas.intensity
}
if (out.envAtlas && typeof out.envAtlas.brightness !== 'number') {
out.envAtlas.brightness = 1
}
if (out.envAtlas && typeof out.envAtlas.contrast !== 'number') {
out.envAtlas.contrast = 1
}
if (out.envAtlas && typeof out.envAtlas.saturation !== 'number') {
out.envAtlas.saturation = 1
}
if (out.envAtlas && typeof out.envAtlas.toneMapping !== 'number') {
out.envAtlas.toneMapping = 0
}
if (out.skybox && typeof out.skybox.reflectionIntensity !== 'number') {
out.skybox.reflectionIntensity = out.skybox.intensity
}
if (out.grid && typeof out.grid.enabled !== 'boolean') {
out.grid.enabled = DEFAULT_POSTFX.grid.enabled
}
if (out.grid && typeof out.grid.colorX !== 'string') {
out.grid.colorX = DEFAULT_POSTFX.grid.colorX
}
if (out.grid && typeof out.grid.colorZ !== 'string') {
out.grid.colorZ = DEFAULT_POSTFX.grid.colorZ
}
if (out.grid && typeof out.grid.colorMain !== 'string') {
out.grid.colorMain = DEFAULT_POSTFX.grid.colorMain
}
if (out.grid && typeof out.grid.alphaX !== 'number') {
out.grid.alphaX = DEFAULT_POSTFX.grid.alphaX
}
if (out.grid && typeof out.grid.alphaZ !== 'number') {
out.grid.alphaZ = DEFAULT_POSTFX.grid.alphaZ
}
if (out.grid && typeof out.grid.alphaMain !== 'number') {
out.grid.alphaMain = DEFAULT_POSTFX.grid.alphaMain
}
if (out.grid && typeof out.grid.dotsEnabled !== 'boolean') {
out.grid.dotsEnabled = DEFAULT_POSTFX.grid.dotsEnabled
}
if (out.grid && typeof out.grid.dotsColor !== 'string') {
out.grid.dotsColor = DEFAULT_POSTFX.grid.dotsColor
}
if (out.grid && typeof out.grid.dotsAlpha !== 'number') {
out.grid.dotsAlpha = DEFAULT_POSTFX.grid.dotsAlpha
}
if (out.grid && typeof out.grid.dotsDiameter !== 'number') {
out.grid.dotsDiameter = DEFAULT_POSTFX.grid.dotsDiameter
}
if (out.grid && typeof out.grid.crossEnabled !== 'boolean') {
out.grid.crossEnabled = DEFAULT_POSTFX.grid.crossEnabled
}
if (out.grid && typeof out.grid.crossColor !== 'string') {
out.grid.crossColor = DEFAULT_POSTFX.grid.crossColor
}
if (out.grid && typeof out.grid.crossAlpha !== 'number') {
out.grid.crossAlpha = DEFAULT_POSTFX.grid.crossAlpha
}
if (out.grid && typeof out.grid.crossLength !== 'number') {
out.grid.crossLength = DEFAULT_POSTFX.grid.crossLength
}
if (out.grid && typeof out.grid.crossWidth !== 'number') {
out.grid.crossWidth = DEFAULT_POSTFX.grid.crossWidth
}
return out as PostFxSettings
}
@@ -0,0 +1,85 @@
import {mergePostFxDefaults,type PostFxSettings} from './postFx';
import donorFields from './environmentFields.json';
export type SceneField={key:string;type:string;label:string;group:string;default?:unknown;min?:number;max?:number;step?:number;options?:{label:string;value:string}[];disabledIf?:string};
export const environmentFields:SceneField[]=[...donorFields,
{key:'postFx.lut.textureUrl',type:'texture',label:'Таблица LUT',group:'PostProcess/LUT'},
{key:'postFx.lighting.ambientIntensity',type:'sliderNumber',label:'Заполняющий свет',group:'PostProcess/Lighting',min:0,max:1,step:.01},
{key:'postFx.grid.step',type:'sliderNumber',label:'Шаг основной сетки, м',group:'PostProcess/Grid',min:.01,max:10,step:.01},
{key:'postFx.grid.diameter',type:'sliderNumber',label:'Диаметр сетки, м',group:'PostProcess/Grid',min:1,max:1000,step:1},
];
export const textureSlots=['diffuse','normal','metalness','roughness','opacity','emissive','ao'] as const;
export type TextureSlot=typeof textureSlots[number];
export type MaterialSpec={name:string;color:string;metalness:number;roughness:number;opacity:number;reflectivity:number;clearCoat:number;clearCoatRoughness:number;emissive:string;emissiveIntensity:number;normalStrength:number;doubleSided:boolean;tiling:number;textures:Partial<Record<TextureSlot,{name:string;data:string}>>};
export type SceneDocument={schema:'missioncore.rover-scene/v1';model:'dcd006-v020-materials-v2';environmentVersion:2;postFx:PostFxSettings;cameraZoomStrength:number;cameraAutoRotate:boolean;materials:Record<string,MaterialSpec>;assignments:Record<string,string>};
const material=(name:string,color:string,metalness:number,roughness:number):MaterialSpec=>({name,color,metalness,roughness,opacity:1,reflectivity:1,clearCoat:0,clearCoatRoughness:.3,emissive:'#000000',emissiveIntensity:0,normalStrength:1,doubleSided:false,tiling:1,textures:{}});
export function defaultScene():SceneDocument{
const postFx=mergePostFxDefaults();
return {schema:'missioncore.rover-scene/v1',model:'dcd006-v020-materials-v2',environmentVersion:2,postFx,cameraZoomStrength:.04,cameraAutoRotate:false,assignments:{},materials:{
'rover/body':material('Корпус и подвеска','#2c2f31',.12,.53),
'rover/rubber':material('Резина гусениц и катков','#202328',0,.72),
'rover/track-steel':material('Нержавеющие проставки','#c4c8cd',1,.17),
'rover/box':material('Бортовой ящик','#34373a',.08,.4),
'rover/molle':material('MOLLE панель','#52575b',.3,.44),
'rover/motor':material('Алюминий моторов','#95999c',.68,.38),
'rover/hardware':material('Чёрный крепёж','#24272b',.45,.38),
'rover/polymer':material('Пластик и кожухи','#24292d',0,.44),
'rover/drive':material('Ведущие звёзды','#81652f',0,.46),
}};
}
export function createMaterial(doc:SceneDocument,id:string):SceneDocument{
if(!/^custom\/[a-zA-Z0-9-]{1,80}$/.test(id)||Object.hasOwn(doc.materials,id)||Object.keys(doc.materials).length>=128)return doc;
const used=new Set(Object.values(doc.materials).map(m=>m.name));let n=1;while(used.has(`Материал ${n}`))n++;
return {...doc,materials:{...doc.materials,[id]:material(`Материал ${n}`,'#808080',0,.5)}};
}
export function assignMaterial(doc:SceneDocument,group:string,id:string):SceneDocument{
if(!Object.hasOwn(defaultScene().materials,group)||!Object.hasOwn(doc.materials,id))return doc;
return {...doc,assignments:{...doc.assignments,[group]:id}};
}
export function fieldValue(doc:SceneDocument,key:string):unknown{return key.split('.').reduce<unknown>((v,k)=>v&&typeof v==='object'?(v as Record<string,unknown>)[k]:undefined,doc);}
export function fieldDisabled(doc:SceneDocument,f:SceneField):boolean{
const rule=f.disabledIf;if(!rule)return false;
if(rule.startsWith('!'))return !fieldValue(doc,rule.slice(1));
const atlas=doc.postFx.envAtlas.enabled,sky=doc.postFx.skybox.enabled;
return ({ssaoDisabled:doc.postFx.ssao.type==='none',fogDisabled:doc.postFx.rendering.fog==='none',envAtlasBlocked:sky,skyboxBlocked:atlas,envAtlasFieldsDisabled:sky||!atlas,skyboxFieldsDisabled:atlas||!sky,gridDotsDisabled:!doc.postFx.grid.dotsEnabled,gridCrossDisabled:!doc.postFx.grid.crossEnabled} as Record<string,boolean>)[rule]??false;
}
export function changeField(doc:SceneDocument,key:string,value:unknown):SceneDocument{
const f=environmentFields.find(x=>x.key===key);if(!f||f.type==='action')return doc;
if(f.type==='texture'&&value!==null&&(typeof value!=='string'||value.length>1_000_000||!/^data:image\/png;base64,[A-Za-z0-9+/=]+$/.test(value)))return doc;
const old=fieldValue(doc,key);
if(typeof old==='number'){
value=Number(value);if(!Number.isFinite(value))return doc;
if(f.min!==undefined)value=Math.max(f.min,value as number);if(f.max!==undefined)value=Math.min(f.max,value as number);
}else if(typeof old==='boolean'){if(typeof value!=='boolean')return doc;}
else if(f.type==='color'){if(typeof value!=='string'||!/^#[0-9a-f]{6}$/i.test(value))return doc;}
if(f.options&&!f.options.some(o=>o.value===String(value)))return doc;
if(f.type==='doubleSlider'){
if(!Array.isArray(value)||value.length!==2||!value.every(Number.isFinite))return doc;
value=[Math.max(0,Math.min(100,value[0])),Math.max(0,Math.min(100,value[1]))].sort((a,b)=>a-b);
}
const result={...doc,postFx:structuredClone(doc.postFx)};const parts=key.split('.');const tail=parts.pop()!;
const target=parts.reduce((v,k)=>v[k],result as any);target[tail]=value;
if(key==='postFx.rendering.fogRange'){[result.postFx.rendering.fogStart,result.postFx.rendering.fogEnd]=value as [number,number];}
if(key==='postFx.envAtlas.enabled'&&value)result.postFx.skybox.enabled=false;
if(key==='postFx.skybox.enabled'&&value)result.postFx.envAtlas.enabled=false;
return result;
}
export const materialRanges:Record<string,[number,number]>={metalness:[0,1],roughness:[0,1],opacity:[0,1],reflectivity:[0,1],clearCoat:[0,1],clearCoatRoughness:[0,1],emissiveIntensity:[0,10],normalStrength:[0,2],tiling:[.01,20]};
export function textureBytes(doc:SceneDocument):number{return Object.values(doc.materials).reduce((sum,m)=>sum+Object.values(m.textures).reduce((n,t)=>n+(t?.data.length??0),0),0);}
export function parseScene(raw:unknown):SceneDocument{
const r=raw as SceneDocument;if(!r||r.schema!=='missioncore.rover-scene/v1'||r.model!=='dcd006-v020-materials-v2')throw new Error('Файл сцены не подходит к этой модели.');
let doc=defaultScene();
for(const f of environmentFields){const v=fieldValue(r,f.key);if(v!==undefined)doc=changeField(doc,f.key,v);}
if(Object.keys(r.materials??{}).length>128)throw new Error('В сцене может быть не больше 128 материалов.');
for(const id of Object.keys(r.materials??{}))if(id.startsWith('custom/'))doc=createMaterial(doc,id);
for(const [id,base] of Object.entries(doc.materials)){
const m=r.materials?.[id];if(!m)continue;
if(typeof m.name==='string')base.name=m.name.trim().slice(0,120)||base.name;
for(const key of ['color','emissive'] as const)if(/^#[0-9a-f]{6}$/i.test(m[key]))base[key]=m[key];
for(const [key,[lo,hi]] of Object.entries(materialRanges)){const v=m[key as keyof MaterialSpec];if(typeof v==='number'&&Number.isFinite(v))(base as any)[key]=Math.max(lo,Math.min(hi,v));}
if(typeof m.doubleSided==='boolean')base.doubleSided=m.doubleSided;
for(const slot of textureSlots){const t=m.textures?.[slot];if(!t)continue;if(typeof t.name!=='string'||typeof t.data!=='string'||t.data.length>12_000_000||!/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(t.data))throw new Error('Некорректная текстура в файле сцены.');base.textures[slot]={name:t.name.slice(0,200),data:t.data};}
}
for(const [group,id] of Object.entries(r.assignments??{}))if(typeof id==='string')doc=assignMaterial(doc,group,id);
if(textureBytes(doc)>28_000_000)throw new Error('Суммарный объём текстур превышает 20 МБ.');
return doc;
}
@@ -0,0 +1,21 @@
import {defaultScene,parseScene,type SceneDocument} from './sceneDocument';
// Fingerprint of the first editor's withdrawn neutral preset. Match the entire
// environment: independently edited environments must never be reset on load.
function withdrawnEnvironment(){
const fx=defaultScene().postFx;
Object.assign(fx.lighting,{exposure:1.1,skyBoxIntensity:1,ambientIntensity:.22});
Object.assign(fx.envAtlas,{reflectionIntensity:1,brightness:1.2});
Object.assign(fx.rendering,{backgroundColor:'#202227',fog:'none',toneMapping:4});
Object.assign(fx.grid,{colorMain:'#747982',colorX:'#93969c',colorZ:'#93969c',alphaMain:.25,alphaX:.35,alphaZ:.35,fadeStart:2,fadeEnd:5,step:.5,diameter:12});
fx.chromaticAberration.enabled=false;fx.vignette.enabled=false;fx.grading.enabled=false;fx.bloom.enabled=false;
Object.assign(fx.directionalLight,{intensity:1.8,azimuth:135,elevation:45});
Object.assign(fx.shadowCatcher,{size:4,lightIntensity:.5,shadowIntensity:.25});
return fx;
}
export function loadStoredScene(raw:unknown):{document:SceneDocument;updated:boolean;restoredEnvironment:boolean}{
const doc=parseScene(raw);
const updated=(raw as Partial<SceneDocument>).environmentVersion!==2;
const restoredEnvironment=updated&&JSON.stringify(doc.postFx)===JSON.stringify(withdrawnEnvironment());
return {document:restoredEnvironment?{...doc,postFx:defaultScene().postFx}:doc,updated,restoredEnvironment};
}
@@ -0,0 +1,23 @@
import type {SceneDocument} from './sceneDocument';
import {loadStoredScene} from './sceneMigration';
const key=(vehicle:string)=>`${vehicle}:dcd006-v020-materials-v2`;
function database():Promise<IDBDatabase>{return new Promise((resolve,reject)=>{const r=indexedDB.open('missioncore-rover-scenes',1);r.onupgradeneeded=()=>r.result.createObjectStore('scenes');r.onerror=()=>reject(r.error);r.onblocked=()=>reject(new Error('Хранилище сцены занято другим окном.'));r.onsuccess=()=>resolve(r.result);});}
export async function readScene(vehicle:string):Promise<SceneDocument|null>{
const db=await database();try{
const raw=await new Promise<unknown>((resolve,reject)=>{const r=db.transaction('scenes').objectStore('scenes').get(key(vehicle));r.onerror=()=>reject(r.error);r.onsuccess=()=>resolve(r.result);});
if(!raw)return null;
const result=loadStoredScene(raw);
if(result.updated)await new Promise<void>((resolve,reject)=>{
const tx=db.transaction('scenes','readwrite'),store=tx.objectStore('scenes');
if(result.restoredEnvironment)store.put(raw,`${key(vehicle)}:before-environment-v2`);
store.put(result.document,key(vehicle));tx.oncomplete=()=>resolve();tx.onabort=()=>reject(tx.error);tx.onerror=()=>reject(tx.error);
});
return result.document;
}finally{db.close();}
}
export async function saveScene(vehicle:string,document:SceneDocument):Promise<void>{const db=await database();try{await new Promise<void>((resolve,reject)=>{const tx=db.transaction('scenes','readwrite');tx.objectStore('scenes').put(document,key(vehicle));tx.oncomplete=()=>resolve();tx.onabort=()=>reject(tx.error);tx.onerror=()=>reject(tx.error);});}finally{db.close();}}
export async function textureFromFile(file:File):Promise<{name:string;data:string}>{
if(!['image/png','image/jpeg','image/webp'].includes(file.type)||file.size>8_000_000)throw new Error('Выберите PNG, JPEG или WebP до 8 МБ.');
const bitmap=await createImageBitmap(file);try{if(bitmap.width>4096||bitmap.height>4096)throw new Error('Максимальный размер текстуры — 4096 × 4096.');}finally{bitmap.close();}
return new Promise((resolve,reject)=>{const r=new FileReader();r.onerror=()=>reject(r.error);r.onload=()=>resolve({name:file.name,data:String(r.result)});r.readAsDataURL(file);});
}
@@ -0,0 +1,22 @@
import {useCallback,useEffect,useRef,useState} from 'react';
import {defaultScene,parseScene,type SceneDocument} from './sceneDocument';
import {readScene,saveScene} from './sceneStorage';
let writes=Promise.resolve();
const enqueue=(vehicle:string,doc:SceneDocument)=>{const next=writes.catch(()=>{}).then(()=>saveScene(vehicle,doc));writes=next;return next;};
export function useSceneDocument(vehicle:string){
const [document,setDocument]=useState(defaultScene),[ready,setReady]=useState(false),[revision,setRevision]=useState(0);
const [saveState,setSaveState]=useState<'loading'|'saved'|'saving'|'error'>('loading'),[error,setError]=useState('');
const latest=useRef({document,revision,vehicle});latest.current={document,revision,vehicle};
const savedRevision=useRef(0);
useEffect(()=>{let cancelled=false;readScene(vehicle).then(value=>{if(!cancelled){setDocument(value??defaultScene());setSaveState('saved');}}).catch(()=>{if(!cancelled){setError('Не удалось прочитать сохранённую сцену. Изменения можно экспортировать в JSON.');setSaveState('error');}}).finally(()=>{if(!cancelled)setReady(true);});return()=>{cancelled=true;};},[vehicle]);
const update=useCallback((fn:(doc:SceneDocument)=>SceneDocument)=>{setDocument(d=>fn(d));setRevision(v=>v+1);setSaveState('saving');},[]);
useEffect(()=>{
if(!ready||revision===0)return;
let cancelled=false;const timer=setTimeout(()=>{enqueue(vehicle,document).then(()=>{savedRevision.current=revision;if(!cancelled)setSaveState('saved');}).catch(()=>{if(!cancelled){setSaveState('error');setError('Не удалось сохранить сцену на этом компьютере. Экспортируйте JSON, чтобы сохранить изменения.');}});},400);
return()=>{cancelled=true;clearTimeout(timer);};
},[ready,revision,vehicle,document]);
useEffect(()=>()=>{const v=latest.current;if(v.revision>savedRevision.current)void enqueue(v.vehicle,v.document).catch(()=>{});},[]);
const importDocument=async(file:File)=>{try{if(file.size>32_000_000)throw new Error('Файл сцены больше 32 МБ.');const next=parseScene(JSON.parse(await file.text()));update(()=>next);}catch(e){setError(e instanceof Error?e.message:'Не удалось загрузить сцену.');}};
const exportDocument=()=>{const blob=new Blob([JSON.stringify(document,null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=globalThis.document.createElement('a');a.href=url;a.download='rover-scene.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
return {document,ready,saveState,error,setError,update,importDocument,exportDocument};
}
@@ -0,0 +1,70 @@
import {fetchComputeContours,type ComputeContour} from './computeContours';
import {fetchWorkerTelemetry,type WorkerTelemetry} from './workerTelemetry';
import type {Vehicle} from '../fleet/useFleet';
import {workerConnectionStatus} from './workerConnectionStatus';
export interface CoreHealth {
ok:boolean; service:string; version:string;
plugin_runtimes:{ready:number;total:number};
components?:{recording_cache?:{status?:string}};
}
export interface ContourSnapshot {
core:CoreHealth|null; latency:number|null;
workers:{contour:ComputeContour;telemetry:WorkerTelemetry|null}[]|null;
vehicles:Vehicle[]|null; errors:string[]; observedAt:number;
}
async function json(url:string,signal:AbortSignal):Promise<unknown>{
const response=await fetch(url,{signal,cache:'no-store',headers:{Accept:'application/json'}});
if(!response.ok)throw new Error(`HTTP ${response.status}`);
return response.json();
}
export async function readContourSnapshot(signal:AbortSignal):Promise<ContourSnapshot>{
const bounded=AbortSignal.any([signal,AbortSignal.timeout(8000)]);
const errors:string[]=[];
const [coreResult,workersResult,fleetResult]=await Promise.allSettled([
(async()=>{
const start=performance.now();
const data=await json('/api/health',bounded) as CoreHealth;
if(!data||typeof data.ok!=='boolean'||data.service!=='mission-core-control-plane'||typeof data.version!=='string'||!Number.isFinite(data.plugin_runtimes?.ready)||!Number.isFinite(data.plugin_runtimes?.total))throw new Error('Invalid health');
return {data,latency:performance.now()-start};
})(),
(async()=>{
const contours=await fetchComputeContours(bounded);
return Promise.all(contours.map(async contour=>{
try{return {contour,telemetry:await fetchWorkerTelemetry(contour.contour_id,bounded)};}
catch{errors.push(`Не удалось проверить вычислитель «${contour.display_name}».`);return {contour,telemetry:null};}
}));
})(),
(async()=>{
const data=await json('/api/v1/fleet',bounded) as {items:Vehicle[]};
if(!data||!Array.isArray(data.items)||data.items.some(item=>!item||typeof item.id!=='string'||typeof item.name!=='string'||!['online','offline'].includes(item.connectivity)))throw new Error('Invalid fleet');
return data.items;
})(),
]);
if(coreResult.status==='rejected')errors.push('Не удалось проверить Mission Core.');
if(workersResult.status==='rejected')errors.push('Не удалось получить список вычислителей.');
if(fleetResult.status==='rejected')errors.push('Не удалось получить бортовые компьютеры.');
return {
core:coreResult.status==='fulfilled'?coreResult.value.data:null,
latency:coreResult.status==='fulfilled'?coreResult.value.latency:null,
workers:workersResult.status==='fulfilled'?workersResult.value:null,
vehicles:fleetResult.status==='fulfilled'?fleetResult.value:null,
errors,observedAt:Date.now(),
};
}
export function workerAvailable(telemetry:WorkerTelemetry|null):boolean{
return Boolean(telemetry?.connection.reachable&&telemetry.connection.identity_matches&&telemetry.node);
}
export function boardAvailable(vehicle:Vehicle):boolean{
return vehicle.enrollment==='paired'&&vehicle.connectivity==='online';
}
export function contourSummary(snapshot:ContourSnapshot|null){
if(!snapshot)return {tone:'warning' as const,label:'Проверка состояния',online:null,total:null};
const total=snapshot.workers!==null&&snapshot.vehicles!==null?1+snapshot.workers.length+snapshot.vehicles.length:null;
const online=Number(snapshot.core!==null)+(snapshot.workers??[]).filter(item=>workerAvailable(item.telemetry)).length+(snapshot.vehicles??[]).filter(boardAvailable).length;
if(snapshot.errors.length)return {tone:'warning' as const,label:'Проверка неполная',online,total};
if(!snapshot.core)return {tone:'danger' as const,label:'Mission Core не в сети',online,total};
if(!snapshot.core.ok)return {tone:'warning' as const,label:'Mission Core работает с ограничениями',online,total};
if(snapshot.workers?.some(item=>workerConnectionStatus(item.telemetry).state==='unknown'))return {tone:'warning' as const,label:'Состояние части узлов не подтверждено',online,total};
return {tone:online===total?'success' as const:'warning' as const,label:online===total?'Все узлы в сети':'Часть узлов не в сети',online,total};
}
@@ -0,0 +1,13 @@
import type {WorkerTelemetry} from './workerTelemetry';
// Receiver failure is not evidence that the remote host has shut down.
export function workerConnectionStatus(telemetry: WorkerTelemetry | null) {
const connection = telemetry?.connection;
if (!connection) return {state:'unknown', tone:'warning', label:'Не в сети', detail:'Состояние вычислителя пока не подтверждено.'} as const;
if (connection.reachable && !connection.identity_matches) return {state:'unknown', tone:'warning', label:'Не в сети', detail:'Ответивший узел не совпадает с выбранным вычислителем.'} as const;
if (connection.reachable && connection.identity_matches && telemetry.node) return {state:'online', tone:'success', label:'В сети', detail:null} as const;
if (['telemetry-receiver-unavailable','telemetry-agent-unavailable','invalid-telemetry-response'].includes(connection.error_code ?? '')) {
return {state:'unknown', tone:'warning', label:'Не в сети', detail:'Mission Core не получает данные через службу телеметрии. Состояние самого вычислителя не подтверждено.'} as const;
}
return {state:'unknown', tone:'warning', label:'Не в сети', detail:'Последние данные не подтверждают текущее состояние вычислителя.'} as const;
}
+1 -45
View File
@@ -186,7 +186,7 @@ export const workspaces: WorkspaceDefinition[] = [
label: "Состояние контура",
title: "Состояние контура",
eyebrow: "ПАРК / СОСТОЯНИЕ",
description: "Узлы, процессы, сеть и подключённые устройства по данным живого контура.",
description: "Связь с Mission Core, вычислителями и бортовыми компьютерами аппаратов.",
icon: "shield",
kind: "contour-health",
groups: [],
@@ -213,50 +213,6 @@ export const workspaces: WorkspaceDefinition[] = [
kind: "device",
groups: [],
},
{
id: "payload",
root: "fleet",
label: "Сенсоры и каналы",
title: "Сенсоры и каналы",
eyebrow: "ПАРК / ПОЛЕЗНАЯ НАГРУЗКА",
description: "Полезная нагрузка аппарата и каналы данных, которые она публикует.",
icon: "grid",
kind: "catalog",
groups: [
{
title: "Пространственные сенсоры",
description: "Единый контракт для разных источников.",
capabilities: [
active("Облако точек", "Доказанный декодированный поток точек текущего устройства."),
active("Поза и траектория", "Доказанный поток позы и накопление пути."),
contract("Камеры", "Изображение, видео, глубина, внутренние и внешние параметры."),
contract("Навигация", "IMU, GNSS/RTK, одометрия и система координат."),
],
},
],
},
{
id: "configurations",
root: "fleet",
label: "Компоновки",
title: "Компоновки борта",
eyebrow: "ПАРК / КОМПОНОВКИ",
description: "Версионируемые сочетания сенсоров, вычислителей, транспорта и питания.",
icon: "settings",
kind: "catalog",
groups: [
{
title: "Шаблон компоновки",
description: "Повторяемая конфигурация для одинаковых аппаратов.",
capabilities: [
contract("Состав модулей", "Сенсоры, адаптеры, обработчики и зависимости."),
contract("Калибровки", "Системы координат, преобразования, внутренние и внешние параметры."),
contract("Профиль сети", "Локальная сеть, ячеистая сеть, LTE и серверный маршрут."),
later("Развёртывание на борт", "Пакет конфигурации и контролируемое обновление."),
],
},
],
},
{
id: "spatial-scene",
root: "polygon",
@@ -2173,6 +2173,7 @@
.contour-health-summary {
justify-content: space-between;
flex-wrap: wrap;
gap: 1rem;
}
@@ -2203,7 +2204,7 @@
.contour-health-kpis {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
grid-template-columns: repeat(auto-fit, minmax(min(100%, 10rem), 1fr));
gap: 0.45rem;
}
@@ -2235,7 +2236,7 @@
.contour-node-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
grid-template-columns: repeat(auto-fit, minmax(min(100%, 22rem), 1fr));
gap: 0.65rem;
}
@@ -2251,6 +2252,7 @@
.contour-node header {
justify-content: space-between;
flex-wrap: wrap;
gap: 1rem;
}
@@ -2262,7 +2264,7 @@
.contour-node dl {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
grid-template-columns: repeat(2, minmax(0, 1fr));
margin: 0;
border-radius: 0.75rem;
background: rgb(255 255 255 / 0.022);
@@ -2277,11 +2279,10 @@
.contour-node dd {
margin: 0;
overflow: hidden;
overflow-wrap: anywhere;
color: var(--nodedc-text-secondary);
font-size: 0.62rem;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--nodedc-font-size-sm);
white-space: normal;
}
.contour-process-list {
@@ -1,41 +1,10 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { Button, Icon, StatusBadge } from "@nodedc/ui-react";
import type { MissionRuntimeState } from "../core/runtime/contracts";
import {
fetchPolygonWorkerStatus,
type PolygonWorkerStatus,
} from "../core/polygon/liveWorker";
interface ControlPlaneHealth {
ok: boolean;
status: string;
service: string;
version: string;
plugin_runtimes: {
ready: number;
total: number;
};
}
interface PluginRuntimeHealth {
runtime_instance_id: string;
plugin_id: string;
plugin_version: string;
status: string;
observed_at: string;
detail_code: string | null;
}
interface ContourSnapshot {
controlPlane: ControlPlaneHealth | null;
pluginRuntimes: PluginRuntimeHealth[];
simulationWorker: PolygonWorkerStatus | null;
controlPlaneLatencyMs: number | null;
simulationGatewayLatencyMs: number | null;
observedAt: Date;
error: string | null;
}
import {useEffect,useState} from 'react';
import {createPortal} from 'react-dom';
import {workerConnectionStatus} from '../core/system/workerConnectionStatus';
import {IconButton,Icon,StatusBadge} from '@nodedc/ui-react';
import type {MissionRuntimeState} from '../core/runtime/contracts';
import {boardAvailable,contourSummary,readContourSnapshot,type ContourSnapshot} from '../core/system/contourHealth';
import {startSequentialPolling} from '../core/system/sequentialPolling';
export function contourRuntimeAuthorityPresentation(
state: MissionRuntimeState | null,
@@ -56,310 +25,64 @@ export function contourRuntimeAuthorityPresentation(
};
}
function validControlPlaneHealth(value: unknown): value is ControlPlaneHealth {
if (!value || typeof value !== "object") return false;
const item = value as Partial<ControlPlaneHealth>;
return typeof item.ok === "boolean"
&& typeof item.status === "string"
&& typeof item.service === "string"
&& typeof item.version === "string"
&& Boolean(item.plugin_runtimes)
&& typeof item.plugin_runtimes?.ready === "number"
&& typeof item.plugin_runtimes?.total === "number";
function observed(value:number|string|null|undefined){
if(value===null||value===undefined)return '—';
const date=new Date(value);
return Number.isFinite(date.getTime())?date.toLocaleString('ru-RU'):'—';
}
function validPluginRuntime(value: unknown): value is PluginRuntimeHealth {
if (!value || typeof value !== "object") return false;
const item = value as Partial<PluginRuntimeHealth>;
return typeof item.runtime_instance_id === "string"
&& typeof item.plugin_id === "string"
&& typeof item.plugin_version === "string"
&& typeof item.status === "string"
&& typeof item.observed_at === "string";
}
async function timedJson(
url: string,
signal: AbortSignal,
): Promise<{ payload: unknown; latencyMs: number }> {
const started = performance.now();
const response = await fetch(url, {
method: "GET",
headers: { Accept: "application/json" },
signal,
});
const latencyMs = performance.now() - started;
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return { payload: await response.json(), latencyMs };
}
function formatLatency(value: number | null): string {
if (value === null) return "—";
return `${Math.max(1, Math.round(value))} мс`;
}
function formatObservedAt(value: Date | string | null): string {
if (!value) return "—";
const date = value instanceof Date ? value : new Date(value);
if (!Number.isFinite(date.getTime())) return "—";
return new Intl.DateTimeFormat("ru-RU", {
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
}).format(date);
}
export function ContourHealthWorkspace({
state,
}: {
state: MissionRuntimeState | null;
}) {
const [snapshot, setSnapshot] = useState<ContourSnapshot | null>(null);
const [loading, setLoading] = useState(false);
const [generation, setGeneration] = useState(0);
const refresh = useCallback(() => setGeneration((value) => value + 1), []);
useEffect(() => {
const controller = new AbortController();
setLoading(true);
void Promise.allSettled([
timedJson("/api/health", controller.signal),
timedJson("/api/v1/device-plugin-runtimes", controller.signal),
(async () => {
const started = performance.now();
const worker = await fetchPolygonWorkerStatus({ signal: controller.signal });
return { worker, latencyMs: performance.now() - started };
})(),
]).then(([healthResult, runtimesResult, workerResult]) => {
if (controller.signal.aborted) return;
const healthPayload = healthResult.status === "fulfilled"
? healthResult.value.payload
: null;
const runtimesPayload = runtimesResult.status === "fulfilled"
? runtimesResult.value.payload
: null;
const runtimeItems = runtimesPayload
&& typeof runtimesPayload === "object"
&& Array.isArray((runtimesPayload as { items?: unknown }).items)
? (runtimesPayload as { items: unknown[] }).items.filter(validPluginRuntime)
: [];
const failures = [healthResult, runtimesResult, workerResult]
.filter((result) => result.status === "rejected").length;
setSnapshot({
controlPlane: validControlPlaneHealth(healthPayload) ? healthPayload : null,
pluginRuntimes: runtimeItems,
simulationWorker: workerResult.status === "fulfilled"
? workerResult.value.worker
: null,
controlPlaneLatencyMs: healthResult.status === "fulfilled"
? healthResult.value.latencyMs
: null,
simulationGatewayLatencyMs: workerResult.status === "fulfilled"
? workerResult.value.latencyMs
: null,
observedAt: new Date(),
error: failures === 0
? null
: `Не ответили ${failures} из 3 диагностических контрактов.`,
});
}).finally(() => {
if (!controller.signal.aborted) setLoading(false);
});
return () => controller.abort();
}, [generation]);
useEffect(() => {
const timer = window.setInterval(refresh, 5_000);
return () => window.clearInterval(timer);
}, [refresh]);
const {
aiActive,
deviceControlConnectivity,
controlledDevice,
} = contourRuntimeAuthorityPresentation(state);
const simulationWorker = snapshot?.simulationWorker ?? null;
const controlPlaneReady = Boolean(snapshot?.controlPlane?.ok);
const runtimeReady = snapshot?.pluginRuntimes.filter(
(runtime) => runtime.status === "ready",
).length ?? 0;
const processCount = (snapshot?.pluginRuntimes.length ?? 0) + 2;
const readyProcessCount = runtimeReady
+ (controlPlaneReady ? 1 : 0)
+ (simulationWorker?.available ? 1 : 0);
const nodeStatus = useMemo(() => {
if (!snapshot) return "Проверяем";
if (controlPlaneReady && snapshot.error === null) return "Контур отвечает";
if (controlPlaneReady) return "Частично доступен";
return "Нет связи";
}, [controlPlaneReady, snapshot]);
return (
<div className="contour-health-dashboard">
<section className="contour-health-summary">
<div>
<span className="section-eyebrow">ЖИВОЙ ДИАГНОСТИЧЕСКИЙ СРЕЗ</span>
<h2>Локальный вычислительный контур</h2>
<p>
Статусы читаются из Control Plane, plugin runtime и шлюза Simulation Worker.
Пустые значения не подменяются демонстрационными числами.
</p>
</div>
<div className="contour-health-summary__status">
<StatusBadge tone={controlPlaneReady ? "success" : "danger"}>
{nodeStatus}
</StatusBadge>
<Button
size="compact"
variant="secondary"
disabled={loading}
onClick={refresh}
>
<Icon name="refresh" size={14} />
{loading ? "Проверяем" : "Обновить"}
</Button>
</div>
</section>
<section className="contour-health-kpis" aria-label="Сводка состояния контура">
<div>
<span>Узлы</span>
<strong>{snapshot ? 2 : "—"}</strong>
<small>локальный + внешний worker</small>
</div>
<div>
<span>Процессы готовы</span>
<strong>{snapshot ? `${readyProcessCount} / ${processCount}` : "—"}</strong>
<small>по живым health-контрактам</small>
</div>
<div>
<span>Локальный API</span>
<strong>{formatLatency(snapshot?.controlPlaneLatencyMs ?? null)}</strong>
<small>браузер → Control Plane</small>
</div>
<div>
<span>Последняя проверка</span>
<strong>{formatObservedAt(snapshot?.observedAt ?? null)}</strong>
<small>автообновление каждые 5 секунд</small>
</div>
</section>
<section className="contour-node-grid" aria-label="Вычислительные узлы">
<article className="contour-node" data-state={controlPlaneReady ? "online" : "offline"}>
<header>
<div>
<span className="section-eyebrow">УЗЕЛ 01 · ЛОКАЛЬНЫЙ</span>
<h3>Mission Core Control Plane</h3>
</div>
<StatusBadge tone={controlPlaneReady ? "success" : "danger"}>
{controlPlaneReady ? "Доступен" : "Недоступен"}
</StatusBadge>
</header>
<dl>
<div><dt>Версия</dt><dd>{snapshot?.controlPlane?.version ?? "—"}</dd></div>
<div><dt>API latency</dt><dd>{formatLatency(snapshot?.controlPlaneLatencyMs ?? null)}</dd></div>
<div><dt>Plugin runtimes</dt><dd>{snapshot ? `${runtimeReady} / ${snapshot.pluginRuntimes.length}` : "—"}</dd></div>
<div><dt>Активный режим</dt><dd>{state?.sourceMode ?? "idle"}</dd></div>
</dl>
<div className="contour-process-list">
{snapshot?.pluginRuntimes.map((runtime) => (
<div key={runtime.runtime_instance_id}>
<i data-state={runtime.status === "ready" ? "online" : "offline"} />
<span>
<strong>Device runtime · {runtime.plugin_id}</strong>
<small>v{runtime.plugin_version} · {formatObservedAt(runtime.observed_at)}</small>
</span>
<em>{runtime.status}</em>
</div>
))}
<div>
<i data-state={aiActive ? "online" : "idle"} />
<span>
<strong>AI perception</strong>
<small>
{aiActive
? `${Math.round(state?.metrics?.aiFrameRateHz ?? 0)} кадр/с`
: "Нет активного задания"}
</small>
</span>
<em>{aiActive ? "active" : "idle"}</em>
</div>
</div>
</article>
<article
className="contour-node"
data-state={simulationWorker?.available ? "online" : "offline"}
>
<header>
<div>
<span className="section-eyebrow">УЗЕЛ 02 · ВНЕШНИЙ</span>
<h3>{simulationWorker?.workerId ?? "Simulation Worker"}</h3>
</div>
<StatusBadge tone={simulationWorker?.available ? "success" : "neutral"}>
{simulationWorker?.available ? "Доступен" : "Offline"}
</StatusBadge>
</header>
<dl>
<div><dt>Gateway latency</dt><dd>{formatLatency(snapshot?.simulationGatewayLatencyMs ?? null)}</dd></div>
<div><dt>Сеть worker</dt><dd>{simulationWorker?.isolation.network ?? "unavailable"}</dd></div>
<div><dt>Политика данных</dt><dd>{simulationWorker?.isolation.artifactPolicy ?? "d-only"}</dd></div>
<div><dt>Активный прогон</dt><dd>{simulationWorker?.activeRunId ?? "нет"}</dd></div>
</dl>
<div className="contour-process-list">
<div>
<i data-state={simulationWorker?.available ? "online" : "offline"} />
<span>
<strong>Simulation orchestration</strong>
<small>
{simulationWorker?.runState
? `Прогон: ${simulationWorker.runState}`
: "Нет активного прогона"}
</small>
</span>
<em>{simulationWorker?.available ? "ready" : "offline"}</em>
</div>
</div>
</article>
</section>
<section className="contour-network-strip" aria-label="Состояние сети">
<div>
<span className="section-eyebrow">СЕТЬ</span>
<strong>Браузер</strong>
<small>127.0.0.1:8000</small>
</div>
<Icon name="chevron-right" />
<div>
<i data-state={controlPlaneReady ? "online" : "offline"} />
<strong>Control Plane</strong>
<small>{formatLatency(snapshot?.controlPlaneLatencyMs ?? null)}</small>
</div>
<Icon name="chevron-right" />
<div>
<i data-state={simulationWorker?.available ? "online" : "offline"} />
<strong>Worker gateway</strong>
<small>{formatLatency(snapshot?.simulationGatewayLatencyMs ?? null)}</small>
</div>
</section>
{controlledDevice ? (
<section className="contour-connected-device">
<span className="section-eyebrow">ПОДТВЕРЖДЁННАЯ УПРАВЛЯЮЩАЯ СЕССИЯ</span>
<strong>{controlledDevice.displayName}</strong>
<small>
{controlledDevice.endpointLabel ?? controlledDevice.modelId}
{deviceControlConnectivity === "degraded"
? " · управление подтверждено, поток данных нарушен"
: " · управление подтверждено"}
</small>
</section>
) : null}
{snapshot?.error ? (
<p className="contour-health-error" role="status">{snapshot.error}</p>
) : null}
</div>
);
export function ContourHealthWorkspace({state,headerToolsHost}:{state:MissionRuntimeState|null;headerToolsHost?:HTMLElement|null}){
const [snapshot,setSnapshot]=useState<ContourSnapshot|null>(null);
const [loading,setLoading]=useState(true),[generation,setGeneration]=useState(0);
useEffect(()=>{
const controller=new AbortController();
const stop=startSequentialPolling(async()=>{
setLoading(true);
try{const next=await readContourSnapshot(controller.signal);if(!controller.signal.aborted)setSnapshot(next);}
finally{if(!controller.signal.aborted)setLoading(false);}
},5000);
return ()=>{stop();controller.abort();};
},[generation]);
const summary=contourSummary(snapshot);
const core=snapshot?.core;
const {controlledDevice,deviceControlConnectivity}=contourRuntimeAuthorityPresentation(state);
const refresh=<IconButton label={loading?"Проверка состояния":"Обновить состояние контура"} disabled={loading} onClick={()=>setGeneration(value=>value+1)}><Icon name="refresh" size={16}/></IconButton>;
return <div className="contour-health-dashboard">
{headerToolsHost?createPortal(refresh,headerToolsHost):refresh}
<section className="contour-health-summary">
<div><h2>Узлы и связь</h2><p>Mission Core, зарегистрированные вычислители и бортовые компьютеры аппаратов.</p></div>
<div className="contour-health-summary__status"><StatusBadge tone={loading?'warning':summary.tone}>{loading?'Проверка состояния':summary.label}</StatusBadge></div>
</section>
<section className="contour-health-kpis" aria-label="Сводка состояния контура">
<div><span>Узлы в сети</span><strong>{summary.online??'—'} / {summary.total??'—'}</strong><small>Core, вычислители и бортовые ПК</small></div>
<div><span>Вычислители</span><strong>{snapshot?.workers?.length??'—'}</strong><small>из настроек системы</small></div>
<div><span>Бортовые компьютеры</span><strong>{snapshot?.vehicles?.length??'—'}</strong><small>из реестра аппаратов</small></div>
<div><span>Последняя проверка</span><strong>{observed(snapshot?.observedAt)}</strong><small>обновление каждые 5 секунд</small></div>
</section>
<section className="contour-node-grid" aria-label="Узлы контура">
<article className="contour-node" data-state={core?(core.ok?'online':'degraded'):'unknown'}>
<header><div><span className="section-eyebrow">КОМПЬЮТЕР ОПЕРАТОРА</span><h3>Mission Core</h3></div><StatusBadge tone={core?.ok?'success':'warning'}>{core?'В сети':snapshot?'Не в сети':'Проверка состояния'}</StatusBadge></header>
<dl><div><dt>Версия</dt><dd>{core?.version??'—'}</dd></div><div><dt>Время ответа</dt><dd>{snapshot?.latency==null?'—':`${Math.max(1,Math.round(snapshot.latency))} мс`}</dd></div><div><dt>Обработчики устройств готовы</dt><dd>{core?`${core.plugin_runtimes.ready} / ${core.plugin_runtimes.total}`:'—'}</dd></div></dl>
{!core?.ok&&core?.components?.recording_cache?.status==='capacity-pressure'&&<small>Недостаточно свободного места для новых записей.</small>}
</article>
{snapshot?.workers?.map(({contour,telemetry})=>{
const status=workerConnectionStatus(telemetry);
return <article key={contour.contour_id} className="contour-node" data-state={status.state}>
<header><div><span className="section-eyebrow">ВЫЧИСЛИТЕЛЬ</span><h3>{contour.display_name}</h3></div><StatusBadge tone={status.tone}>{status.label}</StatusBadge></header>
<dl><div><dt>Узел</dt><dd>{contour.expected_node_id}</dd></div><div><dt>Телеметрия</dt><dd>{contour.telemetry_mode==='agent-mqtt'?'Агент':'Диагностика SSH'}</dd></div><div><dt>Проверено</dt><dd>{observed(telemetry?.connection.observed_at_utc)}</dd></div><div><dt>Последнее измерение</dt><dd>{observed(telemetry?.node?.observed_at_utc)}</dd></div><div><dt>Операционная система</dt><dd>{telemetry?.node?.os.caption??'—'}</dd></div></dl>
{status.detail&&<small>{status.detail}</small>}
</article>;
})}
{snapshot?.vehicles?.map(vehicle=>{
const online=boardAvailable(vehicle);
const status=vehicle.enrollment==='revoked'?'Привязка отозвана':vehicle.enrollment==='pending'?'Подключение':vehicle.enrollment==='failed'?'Не подключён':online?'В сети':'Не в сети';
return <article key={vehicle.id} className="contour-node" data-state={online?'online':'offline'}>
<header><div><span className="section-eyebrow">БОРТОВОЙ КОМПЬЮТЕР</span><h3>{vehicle.name}</h3></div><StatusBadge tone={online?'success':'neutral'}>{status}</StatusBadge></header>
<dl><div><dt>Имя БК</dt><dd>{vehicle.host?.hostname??'—'}</dd></div><div><dt>Операционная система</dt><dd>{vehicle.host?.os??'—'}</dd></div><div><dt>Последняя связь</dt><dd>{observed(vehicle.last_seen===null?null:vehicle.last_seen*1000)}</dd></div></dl>
{!online&&vehicle.host&&<small>Сведения о БК сохранены с последнего подключения.</small>}
</article>;
})}
</section>
{controlledDevice&&<section className="contour-connected-device"><span className="section-eyebrow">ПОДКЛЮЧЁННОЕ УСТРОЙСТВО ОПЕРАТОРА</span><strong>{controlledDevice.displayName}</strong><small>{deviceControlConnectivity==='degraded'?'Поток данных нарушен':'Управляющая связь подтверждена'}</small></section>}
{snapshot?.errors.map(error=><p key={error} className="contour-health-error" role="status">{error}</p>)}
</div>;
}
@@ -431,12 +431,13 @@ export function WorkspaceRenderer(props: WorkspaceRendererProps) {
case "missions":
return <MissionPlannerWorkspace openView={props.navigation.openView} headerToolsHost={props.headerToolsHost} />;
case "vehicles":
return <VehiclesWorkspace createRequest={props.fleetCreateRequest} headerToolsHost={props.headerToolsHost} />;
return <VehiclesWorkspace headerToolsHost={props.headerToolsHost} headerTitleHost={props.headerTitleHost} />;
case "catalog":
return <CatalogWorkspace {...props} />;
case "contour-health":
return (
<ContourHealthWorkspace
headerToolsHost={props.headerToolsHost}
state={props.state}
/>
);
@@ -37,8 +37,8 @@ export interface LaboratoryViewAction {
export interface WorkspaceRendererProps {
launchProfile?: WorkspaceLaunchProfile;
fleetCreateRequest?: number;
headerToolsHost?: HTMLElement | null;
headerTitleHost?: HTMLElement | null;
definition: WorkspaceDefinition;
state: MissionRuntimeState | null;
backendStatus: BackendStatus;
@@ -0,0 +1,21 @@
import {Button,Icon,IconButton,ResourceRow,StatusBadge,Window} from '@nodedc/ui-react';
import type {Vehicle} from '../../core/fleet/useFleet';
export const boardStatus=(item:Vehicle,available=true)=>item.enrollment==='pending'?'Подтверждаем привязку':item.enrollment==='revoked'?'Не привязан':item.enrollment==='failed'?'Привязка не завершена':item.connectivity==='online'?(available?'В сети':'Не в сети'):'Не в сети';
export function BoardComputerRow({vehicle,enabled,showingSavedDevices,onSettings,onMonitor,onAdd,open,onToggle}:{vehicle:Vehicle;enabled:boolean;showingSavedDevices:boolean;onSettings:()=>void;onMonitor:()=>void;onAdd?:()=>void;open:boolean;onToggle:()=>void}){
const label=boardStatus(vehicle,enabled);
return <ResourceRow icon={<Icon name="apps"/>} title="Бортовой компьютер" description={vehicle.host?.hostname||'Mission Core Node'} metadata={`${label}${showingSavedDevices?' (показаны последние сохранённые устройства)':''}`} statusPlacement="leading"
status={<StatusBadge variant="indicator" tone={enabled?'success':vehicle.enrollment==='pending'?'warning':'neutral'} aria-label={label} title={label}/>}
actions={<>{onAdd&&<IconButton label="Добавить устройство к БК" onClick={onAdd}><Icon name="plus"/></IconButton>}<IconButton label="Настройки бортового компьютера" onClick={onSettings}><Icon name="settings"/></IconButton><IconButton label="Мониторинг системы БК" onClick={onMonitor}><Icon name="activity"/></IconButton><IconButton label={open?'Свернуть устройства БК':'Показать устройства БК'} aria-expanded={open} onClick={onToggle}><Icon name={open?'chevron-down':'chevron-right'}/></IconButton></>}/>;
}
export function BoardComputerSettings({vehicle,enabled,onClose,onRevoke}:{vehicle:Vehicle;enabled:boolean;onClose:()=>void;onRevoke:()=>void}){
return <Window open title="Бортовой компьютер" subtitle={vehicle.host?.hostname||'Mission Core Node'} onClose={onClose}>
<div className="fleet-form"><StatusBadge tone={enabled?'success':vehicle.enrollment==='pending'?'warning':'neutral'}>{boardStatus(vehicle,enabled)}</StatusBadge>
{vehicle.notice&&<p role="status">{vehicle.notice}</p>}
<dl className="fleet-facts"><div><dt>Идентификатор БК</dt><dd>{vehicle.node_id}</dd></div><div><dt>Последняя связь</dt><dd>{vehicle.last_seen?new Date(vehicle.last_seen*1000).toLocaleString('ru-RU'):'Соединение ещё не получено'}</dd></div>
{vehicle.host&&<><div><dt>Имя БК в системе</dt><dd>{vehicle.host.hostname}</dd></div><div><dt>Операционная система</dt><dd>{vehicle.host.os}</dd></div><div><dt>Архитектура</dt><dd>{vehicle.host.architecture}</dd></div><div><dt>Процессоры</dt><dd>{vehicle.host.cpus}</dd></div><div><dt>Память</dt><dd>{vehicle.host.memory_kib?`${(vehicle.host.memory_kib/1048576).toFixed(1)} ГиБ`:'Нет сведений'}</dd></div></>}
</dl>
{vehicle.enrollment!=='revoked'&&<Button onClick={onRevoke}>Отозвать привязку БК</Button>}
</div>
</Window>;
}
@@ -1,5 +1,6 @@
import {WorkspaceBackButton} from '../../components/WorkspaceBackButton';
import {useState} from 'react';
import {ActivityIndicator,Button,Icon,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge,TextField,ToastStack} from '@nodedc/ui-react';
import {ActivityIndicator,Button,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge,TextField,ToastStack} from '@nodedc/ui-react';
import {useBoardMonitor,monitorSeries,monitorValue} from '../../core/fleet/boardMonitor';
import {TelemetrySeries} from '../../components/system/TelemetrySeries';
import '../../styles/system-telemetry.css';
@@ -7,7 +8,7 @@ import './board-monitor.css';
const eventLabels:Record<string,string>={'ui-error':'Ошибка интерфейса','ui-rejection':'Ошибка асинхронной операции','ui-render-error':'Ошибка представления','system-oom':'Нехватка памяти','gpu-reset':'Сброс GPU','disk-error':'Ошибка диска','usb-disconnected':'Отключение USB','usb-error':'Ошибка USB','service-failed':'Сбой службы','ui-process-exit':'Завершение процесса окна','ui-load-failed':'Ошибка загрузки окна'};
const time=(value:number)=>new Date(value*1000).toLocaleString('ru-RU');
export function BoardMonitorView({vehicle,name,back}:{vehicle:string;name:string;back:()=>void}) {
export function BoardMonitorView({vehicle,name,back,headerToolsHost}:{vehicle:string;name:string;back:()=>void;headerToolsHost?:HTMLElement|null}) {
const [metric,setMetric]=useState('cpu.usage'),[group,setGroup]=useState('CPU'),[window,setWindow]=useState(900),[end,setEnd]=useState<number|null>(null),[mode,setMode]=useState<'min'|'max'|'mean'>('max');
const {value,error,dismissError}=useBoardMonitor(vehicle,metric,window,end);
const definitions=value?.definitions??{},definition=definitions[metric];
@@ -15,7 +16,7 @@ export function BoardMonitorView({vehicle,name,back}:{vehicle:string;name:string
const metrics=Object.entries(definitions).filter(([,item])=>item.group===group);
const latest=value?.latest;
return <div className="board-monitor">
<div><Button onClick={back}><Icon name="chevron-left"/>К аппарату</Button></div>
<WorkspaceBackButton label="К аппарату" onClick={back} host={headerToolsHost}/>
<SettingsCard title="Мониторинг системы БК" description={name} actions={<StatusBadge tone={value?.fresh&&!error?'success':'neutral'}>{value?.fresh&&!error?'Данные поступают':'Нет свежих данных'}</StatusBadge>}>
{latest&&<p>Измерено на БК: {time(latest.at)}. {value?.storage==='ready'?'Локальная история записывается.':'Запись локальной истории недоступна.'} {value?.backlog?'История догружается в Mission Core.':''}</p>}
{value?.database_bytes!=null&&<p>Архив на БК: {monitorValue(value.database_bytes,'bytes')} из {monitorValue(value.database_budget_bytes,'bytes')}. {value.archive_since?`Копия в Mission Core с ${time(value.archive_since)}.`:''}</p>}
@@ -0,0 +1,42 @@
import {useId,useState,type FormEvent} from 'react';
import {Button,Select,SettingsCard,TextAreaField,TextField,StatusBadge} from '@nodedc/ui-react';
import {fleetRequest,type FleetPreview,type Vehicle} from '../../core/fleet/useFleet';
import type {SensorEnrollmentProps} from '../../../../../packages/sensor-ui/src/extensions';
import {InstallerCard} from './equipment/InstallerCard';
export const platforms=[{value:'ugv',label:'Наземный (UGV)'},{value:'uav',label:'Воздушный (UAV)'},{value:'stationary',label:'Стационарный'},{value:'other',label:'Другой'}];
export const platformLabel=(value:string)=>platforms.find(item=>item.value===value)?.label??value;
/** The invitation admits a computer; an existing apparatus keeps its identity. */
export function NodeInvitationForm({vehicle,onClose,onComplete,renderWindow}:{vehicle?:Vehicle;onClose:()=>void;onComplete:(vehicle:Vehicle)=>void;renderWindow:SensorEnrollmentProps['renderWindow']}){
const form=useId();
const [revision]=useState(vehicle?.revision);
const [code,setCode]=useState(''),[name,setName]=useState(''),[platform,setPlatform]=useState('ugv');
const [preview,setPreview]=useState<FleetPreview|null>(null),[pending,setPending]=useState(false),[error,setError]=useState('');
async function inspect(event:FormEvent){
event.preventDefault();if(pending)return;setPending(true);setError('');
try{const value=await fleetRequest<FleetPreview>('/preview','POST',{code:code.trim()});setPreview(value);setName(current=>current||value.name);setCode('');}
catch(e){setError(e instanceof Error?e.message:'Не удалось проверить приглашение.');}
finally{setPending(false);}
}
async function attach(){
if(!preview||pending)return;setPending(true);setError('');
try{
const result=vehicle
?await fleetRequest<Vehicle>(`/${encodeURIComponent(vehicle.id)}/computer`,'POST',{preview_id:preview.preview_id,expected_revision:revision})
:await fleetRequest<Vehicle>('','POST',{preview_id:preview.preview_id,name:name.trim(),platform});
onComplete(result);
}catch(e){setError(e instanceof Error?e.message:'Не удалось подключить БК.');}
finally{setPending(false);}
}
const replacing=!!vehicle&&vehicle.enrollment!=='revoked';
return renderWindow({busy:pending,actions:<><Button disabled={pending} onClick={onClose}>Отмена</Button>{preview?<Button loading={pending} disabled={pending||(!vehicle&&!name.trim())} onClick={()=>void attach()}>{vehicle?(replacing?'Заменить БК':'Подключить БК'):'Добавить аппарат'}</Button>:<Button loading={pending} type="submit" form={form} disabled={pending||!code.trim()}>Проверить БК</Button>}</>,content:
<form id={form} className="fleet-form" onSubmit={inspect} aria-busy={pending}>
{!preview&&<InstallerCard kind="node"/>}
{!vehicle&&<><Select label="Класс аппарата" value={platform} options={platforms} onChange={setPlatform} disabled={pending}/><TextField label="Название аппарата" value={name} maxLength={80} onChange={e=>setName(e.target.value)} disabled={pending} autoComplete="off"/></>}
{vehicle&&<SettingsCard title={vehicle.name} description={replacing?'Новый БК заменит текущий. Аппарат, его название и раскладки сохранятся; прежняя привязка будет отозвана.':'Подключите БК к этому аппарату по приглашению Mission Core Node.'}/>}
{preview?<SettingsCard title={preview.name} description="Идентичность БК проверена по приглашению"><dl className="fleet-facts"><div><dt>Идентификатор БК</dt><dd>{preview.node_id}</dd></div><div><dt>Система</dt><dd>{preview.host.os} · {preview.host.architecture}</dd></div><div><dt>Адрес БК</dt><dd>{preview.endpoint}</dd></div></dl><Button disabled={pending} onClick={()=>setPreview(null)}>Другое приглашение</Button></SettingsCard>:<TextAreaField label="Код приглашения из Node" value={code} rows={5} maxLength={4096} spellCheck={false} autoComplete="off" disabled={pending} onChange={e=>setCode(e.target.value)}/>}
{pending&&<StatusBadge tone="warning">{preview?'Подключение БК':'Проверка приглашения БК'}</StatusBadge>}
{error&&<p role="alert">{error}</p>}
</form>});
}
@@ -0,0 +1,30 @@
import {useEffect,useSyncExternalStore} from 'react';
import {Button,Icon,Inspector,LoadingRegion} from '@nodedc/ui-react';
import type {BoardLayoutStore} from '../../../../../packages/sensor-ui/src/boardLayout';
import type {SensorBoardContent} from '../../../../../packages/sensor-ui/src/SensorWorkspace';
import type {Vehicle} from '../../core/fleet/useFleet';
import {VehicleIdentitySettings} from './VehicleIdentitySettings';
import {BoardComputerRow} from './BoardComputer';
import {IndependentEquipment} from './equipment/IndependentEquipment';
export function VehicleEquipment({vehicle,enabled,layout,content,onAddComputer,onSettings,onMonitor,onUpdated}:{vehicle:Vehicle;enabled:boolean;layout:BoardLayoutStore;content:SensorBoardContent;onAddComputer:()=>void;onSettings:()=>void;onMonitor:()=>void;onUpdated:(vehicle:Vehicle)=>void}){
const state=useSyncExternalStore(layout.subscribe,layout.getSnapshot);
useEffect(()=>{void layout.load();},[layout]);
const computerOpen=state.value.open_sections.includes('computer');
// The former computer-section preference now controls its nested device branch.
const changeSections=(ids:string[])=>layout.change([...ids,...(computerOpen?['computer']:[])]);
const toggleComputer=()=>layout.change(computerOpen?state.value.open_sections.filter(id=>id!=='computer'):[...state.value.open_sections,'computer']);
return <div className="sensor-content">
{state.error&&<div role="alert"><p>{state.error}</p><Button onClick={()=>void layout.load()}>Повторить</Button></div>}
<LoadingRegion loading={!state.ready&&!state.error} label="Загрузка раскладки аппарата">
<Inspector variant="panel" openSections={state.value.open_sections.filter(id=>id!=='computer')} onOpenSectionsChange={changeSections} sections={[
{id:'settings',label:'Настройки аппарата',icon:<Icon name="sliders"/>,disabled:!state.ready,content:<div className="sensor-content"><VehicleIdentitySettings key={vehicle.id} vehicle={vehicle} onUpdated={onUpdated}/>{content.settings}</div>},
{id:'devices',label:'Оборудование',icon:<Icon name="apps"/>,disabled:!state.ready,content:<div className="sensor-content">
<IndependentEquipment key={vehicle.id} vehicle={vehicle} onComputer={onAddComputer} onRefresh={()=>void content.refresh()} computer={<div><BoardComputerRow vehicle={vehicle} enabled={enabled} showingSavedDevices={content.showingSavedDevices} open={computerOpen} onToggle={toggleComputer} onSettings={onSettings} onMonitor={onMonitor} onAdd={content.canAddDevice?content.addDevice:undefined}/>
{computerOpen&&<div className="fleet-computer-devices">{content.devices}</div>}
</div>}/>
</div>},
]}/>
</LoadingRegion>
</div>;
}
@@ -0,0 +1,27 @@
import {useEffect,useState} from 'react';
import {Button,SettingsCard,TextField} from '@nodedc/ui-react';
import {fleetRequest,type Vehicle} from '../../core/fleet/useFleet';
export function VehicleIdentitySettings({vehicle,onUpdated}:{vehicle:Vehicle;onUpdated:(vehicle:Vehicle)=>void}){
const [base,setBase]=useState(vehicle),[name,setName]=useState(vehicle.name);
const [saving,setSaving]=useState(false),[message,setMessage]=useState(''),[error,setError]=useState('');
const dirty=name!==base.name;
useEffect(()=>{if(!dirty&&!saving){setBase(vehicle);setName(vehicle.name);}},[vehicle,dirty,saving]);
const reset=()=>{setBase(vehicle);setName(vehicle.name);setError('');setMessage('');};
const save=async()=>{
if(saving||!name.trim()||!dirty)return;
setSaving(true);setError('');setMessage('');
try{
const updated=await fleetRequest<Vehicle>(`/${encodeURIComponent(vehicle.id)}`,'PATCH',{name:name.trim(),expected_revision:base.revision});
onUpdated(updated);setBase(updated);setName(updated.name);setMessage('Название сохранено');
}catch(reason){setError(reason instanceof Error?reason.message:'Не удалось сохранить название.');}
finally{setSaving(false);}
};
return <SettingsCard title="Основные параметры">
<form className="fleet-form" onSubmit={event=>{event.preventDefault();void save();}}>
<TextField label="Название аппарата" value={name} maxLength={80} autoComplete="off" disabled={saving} onChange={event=>{setName(event.target.value);setMessage('');}}/>
<div className="sensor-actions"><Button type="submit" disabled={!dirty||!name.trim()||saving}>{saving?'Сохранение…':'Сохранить'}</Button>{dirty&&<Button type="button" variant="secondary" disabled={saving} onClick={reset}>Отмена</Button>}</div>
{error&&<p role="alert">{error}</p>}{message&&<p role="status">{message}</p>}
</form>
</SettingsCard>;
}
@@ -1,13 +1,16 @@
import {useMemo,type ReactNode} from 'react';
import {useMemo} from 'react';
import {boardLayout} from '../../core/fleet/boardLayout';
import {useDevicePluginHost} from '../../core/device-plugins/DevicePluginHost';
import {createIsolatedRerunHost} from '../../components/rerun/isolatedRerunHost';
import {SensorWorkspace} from '../../../../../packages/sensor-ui/src/SensorWorkspace';
import {createFleetSensorTransport} from '../../core/fleet/sensorTransport';
export function VehicleSensors({vehicleID,enabled,computer,description}:{vehicleID:string;enabled:boolean;computer:ReactNode;description:string}){
import type {Vehicle} from '../../core/fleet/useFleet';
import {VehicleEquipment} from './VehicleEquipment';
export function VehicleSensors({vehicle,enabled,onAddComputer,onSettings,onMonitor,onUpdated}:{vehicle:Vehicle;enabled:boolean;onAddComputer:()=>void;onSettings:()=>void;onMonitor:()=>void;onUpdated:(vehicle:Vehicle)=>void}){
const vehicleID=vehicle.id;
const {registry}=useDevicePluginHost();
const sensorContributions=registry.sensorContributions;
const layout=useMemo(()=>boardLayout(vehicleID),[vehicleID]);
const transport=useMemo(()=>createFleetSensorTransport(vehicleID),[vehicleID]);
return <SensorWorkspace contributions={sensorContributions} createRerunHost={createIsolatedRerunHost} key={vehicleID} transport={transport} enabled={enabled} board={{layout,computer,description}}/>;
return <SensorWorkspace contributions={sensorContributions} createRerunHost={createIsolatedRerunHost} key={`${vehicleID}:${vehicle.node_id}`} transport={transport} enabled={enabled} readOfflineInventory renderBoard={content=><VehicleEquipment vehicle={vehicle} enabled={enabled} layout={layout} content={content} onAddComputer={onAddComputer} onSettings={onSettings} onMonitor={onMonitor} onUpdated={onUpdated}/>}/>;
}
@@ -1,75 +1,41 @@
import {useState} from 'react';
import {createPortal} from 'react-dom';
import {LoadingRegion,ConfirmationModal,Icon,IconButton,ResourceList,ResourceRow,SettingsCard,StatusBadge,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
import {WorkspaceBackButton} from '../../components/WorkspaceBackButton';
import {fleetRequest,useFleet,type Vehicle} from '../../core/fleet/useFleet';
import {BoardObservationCenter} from './observation/BoardObservationCenter';
import {BoardMonitorView} from './BoardMonitorView';
import { useEffect, useRef, useState } from "react";
import { LoadingRegion, Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow, Select, SettingsCard, StatusBadge, TextAreaField, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
import { fleetRequest, useFleet, type FleetPreview, type Vehicle } from "../../core/fleet/useFleet";
import "./fleet.css";
import { VehicleSensors } from "./VehicleSensors";
import {VehicleSensors} from './VehicleSensors';
import {BoardComputerSettings,boardStatus} from './BoardComputer';
import {NodeInvitationForm,platformLabel} from './NodeInvitationForm';
import './fleet.css';
const platforms = [{ value: "ugv", label: "Наземный (UGV)" }, { value: "uav", label: "Воздушный (UAV)" }, { value: "stationary", label: "Стационарный" }, { value: "other", label: "Другой" }];
const platformLabel = (value: string) => platforms.find(item => item.value === value)?.label ?? value;
function statusLabel(item: Vehicle) { return item.enrollment === "pending" ? "Подтверждаем привязку" : item.enrollment === "revoked" ? "Доверие отозвано" : item.enrollment === "failed" ? "Привязка не завершена" : item.connectivity === "online" ? "В сети" : "Нет связи"; }
export function VehiclesWorkspace({ createRequest = 0, headerToolsHost }: { createRequest?: number; headerToolsHost?: HTMLElement|null }) {
const fleet = useFleet();
const [adding, setAdding] = useState(false);
const [code, setCode] = useState("");
const [name, setName] = useState("");
const [platform, setPlatform] = useState("ugv");
const [preview, setPreview] = useState<FleetPreview | null>(null);
const [pending, setPending] = useState(false);
const [error, setError] = useState("");
const [selected, setSelected] = useState<string | null>(null);
const [monitorOpen,setMonitorOpen]=useState(false);
const [observationOpen,setObservationOpen]=useState(false);
const [revoking, setRevoking] = useState<Vehicle | null>(null);
const lastCreateRequest = useRef(createRequest);
useEffect(() => { if (createRequest !== lastCreateRequest.current) { lastCreateRequest.current = createRequest; setAdding(true); setError(""); } }, [createRequest]);
function close() { if (pending) return; setAdding(false); setPreview(null); setCode(""); setName(""); setError(""); }
async function inspect(event: React.FormEvent) {
event.preventDefault(); if (pending) return;
setPending(true); setError("");
try { const value = await fleetRequest<FleetPreview>("/preview", "POST", { code: code.trim() }); setPreview(value); setName(current => current || value.name); setCode(""); }
catch (error) { setError(error instanceof Error ? error.message : "Не удалось проверить приглашение."); }
finally { setPending(false); }
}
async function add() {
if (!preview || pending) return;
setPending(true); setError("");
try {
const item = await fleetRequest<Vehicle>("", "POST", { preview_id: preview.preview_id, name: name.trim(), platform });
await fleet.refresh(); setSelected(item.id); setAdding(false); setPreview(null); setCode(""); setName("");
} catch (error) { setError(error instanceof Error ? error.message : "Не удалось добавить аппарат."); void fleet.refresh().catch(() => undefined); }
finally { setPending(false); }
}
const detail = fleet.items?.find(item => item.id === selected);
if(detail&&observationOpen)return <BoardObservationCenter key={detail.id} vehicleID={detail.id} name={detail.name} enabled={!fleet.error&&detail.enrollment==="paired"&&detail.connectivity==="online"} back={()=>{setObservationOpen(false);setSelected(null);}} configure={()=>setObservationOpen(false)} headerToolsHost={headerToolsHost}/>;
if(detail&&monitorOpen)return <BoardMonitorView vehicle={detail.id} name={detail.name} back={()=>setMonitorOpen(false)}/>;
return <div className="fleet-workspace">
{fleet.error && <p role="alert">{fleet.error}</p>}
{!adding && error && <p role="alert">{error}</p>}
{detail ? <>
<div><Button onClick={() => {setSelected(null);}}>К списку аппаратов</Button></div>
<VehicleSensors vehicleID={detail.id} enabled={!fleet.error && detail.enrollment === "paired" && detail.connectivity === "online"} description={detail.name} computer={<SettingsCard title={detail.name} description={`${platformLabel(detail.platform)} · с бортовым компьютером`} actions={<StatusBadge tone={!fleet.error && detail.enrollment === "paired" && detail.connectivity === "online" ? "success" : "neutral"}>{fleet.error ? "Нет свежих данных" : statusLabel(detail)}</StatusBadge>}>
{detail.notice && <p role="status">{detail.notice}</p>}
<dl className="fleet-facts"><div><dt>Бортовой компьютер</dt><dd>{detail.node_id}</dd></div>
<div><dt>Последняя связь</dt><dd>{detail.last_seen ? new Date(detail.last_seen * 1000).toLocaleString("ru-RU") : "Соединение ещё не получено"}</dd></div>
{detail.host && <><div><dt>Имя БК в системе</dt><dd>{detail.host.hostname}</dd></div><div><dt>Операционная система</dt><dd>{detail.host.os}</dd></div><div><dt>Архитектура</dt><dd>{detail.host.architecture}</dd></div><div><dt>Процессоры</dt><dd>{detail.host.cpus}</dd></div><div><dt>Память</dt><dd>{detail.host.memory_kib ? `${(detail.host.memory_kib / 1024 / 1024).toFixed(1)} ГиБ` : "Нет сведений"}</dd></div></>}
</dl>
<div className="fleet-board-actions"><Button onClick={()=>setMonitorOpen(true)}><Icon name="activity"/>Мониторинг системы БК</Button>
<Button onClick={()=>setObservationOpen(true)}><Icon name="eye"/>Центр наблюдения и управления</Button>
{detail.enrollment !== "revoked" && <Button onClick={() => setRevoking(detail)}>Отозвать привязку БК</Button>}</div>
</SettingsCard>}/>
</> : !fleet.items ? <LoadingRegion loading label="Получение аппаратов" /> : fleet.items.length === 0 ? <SettingsCard title="Аппаратов пока нет" description="Добавьте аппарат по приглашению из Mission Core Node на его бортовом компьютере."><Button onClick={() => setAdding(true)}>Добавить аппарат</Button></SettingsCard> : <ResourceList aria-label="Аппараты">{fleet.items.map(item => <li key={item.id}><ResourceRow icon={<Icon name="apps" />} title={item.name} description={`${platformLabel(item.platform)} · бортовой компьютер`} status={<StatusBadge tone={!fleet.error && item.enrollment === "paired" && item.connectivity === "online" ? "success" : "neutral"}>{fleet.error ? "Нет свежих данных" : statusLabel(item)}</StatusBadge>} actions={<><IconButton label={`Конфигурация: ${item.name}`} onClick={() => setSelected(item.id)}><Icon name="sliders" /></IconButton><IconButton label={`Центр наблюдения и управления: ${item.name}`} onClick={() => {setSelected(item.id);setObservationOpen(true);}}><Icon name="eye" /></IconButton></>} /></li>)}</ResourceList>}
<Window open={adding} title="Добавить аппарат" subtitle="Подключить бортовой компьютер по приглашению Node" size="md" closeOnBackdrop={false} closeOnEscape={!pending} onClose={close} footer={<WindowFooterActions><Button disabled={pending} onClick={close}>Отмена</Button>{preview ? <Button disabled={pending || !name.trim()} onClick={() => void add()}>{pending ? "Добавление…" : "Добавить аппарат"}</Button> : <Button type="submit" form="fleet-invitation" disabled={pending || !code.trim()}>{pending ? "Проверка БК…" : "Проверить БК"}</Button>}</WindowFooterActions>}>
<form id="fleet-invitation" className="fleet-form" onSubmit={inspect} aria-busy={pending}>
<Select label="Способ подключения" value="node" options={[{ value: "node", label: "С бортовым компьютером" }]} onChange={() => undefined} disabled={pending} />
<Select label="Класс аппарата" value={platform} options={platforms} onChange={setPlatform} disabled={pending} />
<TextField label="Название аппарата" value={name} maxLength={80} onChange={event => setName(event.target.value)} disabled={pending} autoComplete="off" />
{preview ? <SettingsCard title={preview.name} description="Идентичность БК проверена по приглашению"><dl className="fleet-facts"><div><dt>Идентификатор БК</dt><dd>{preview.node_id}</dd></div><div><dt>Система</dt><dd>{preview.host.os} · {preview.host.architecture}</dd></div><div><dt>Адрес БК</dt><dd>{preview.endpoint}</dd></div></dl><Button disabled={pending} onClick={() => setPreview(null)}>Другое приглашение</Button></SettingsCard> : <TextAreaField label="Код приглашения из Node" value={code} rows={5} maxLength={4096} spellCheck={false} autoComplete="off" disabled={pending} onChange={event => setCode(event.target.value)} />}
{error && <p role="alert">{error}</p>}
</form>
</Window>
<ConfirmationModal open={revoking !== null} title="Отозвать привязку БК?" description={`Аппарат «${revoking?.name ?? ""}» останется в реестре, а его БК потеряет доступ к Core. БК получит отзыв при следующем соединении.`} confirmLabel="Отозвать" cancelLabel="Отмена" danger onClose={() => setRevoking(null)} onConfirm={async () => { if (!revoking) return; try { await fleetRequest(`/${encodeURIComponent(revoking.id)}`, "DELETE"); await fleet.refresh(); setRevoking(null); } catch (error) { setError(error instanceof Error ? error.message : "Не удалось отозвать привязку."); throw error; } }} />
export function VehiclesWorkspace({headerToolsHost,headerTitleHost}:{headerToolsHost?:HTMLElement|null;headerTitleHost?:HTMLElement|null}){
const fleet=useFleet();
const [selected,setSelected]=useState<string|null>(null);
const [adding,setAdding]=useState(false),[monitorOpen,setMonitorOpen]=useState(false),[observationOpen,setObservationOpen]=useState(false),[settingsOpen,setSettingsOpen]=useState(false);
const [revoking,setRevoking]=useState<Vehicle|null>(null),[error,setError]=useState('');
const detail=fleet.items?.find(item=>item.id===selected);
const enabled=!!detail&&!fleet.error&&detail.enrollment==='paired'&&detail.connectivity==='online';
const refresh=()=>{void fleet.refresh().catch(()=>setError('Не удалось обновить аппарат. Повторите получение сведений.'));};
const complete=(item:Vehicle)=>{setSelected(item.id);setAdding(false);refresh();};
const addButton=<IconButton label="Добавить аппарат" onClick={()=>setAdding(true)}><Icon name="plus"/></IconButton>;
const headerAdd=!detail&&(headerToolsHost?createPortal(addButton,headerToolsHost):addButton);
const titleSuffix=detail?` — ${detail.name} / ${platformLabel(detail.platform)}`:'';
const observationButton=<IconButton label="Центр наблюдения и управления" onClick={()=>setObservationOpen(true)}><Icon name="eye"/></IconButton>;
const headerObservation=detail&&!observationOpen&&!monitorOpen&&(headerToolsHost?createPortal(observationButton,headerToolsHost):observationButton);
const content=detail&&observationOpen?<BoardObservationCenter key={detail.id} vehicleID={detail.id} name={detail.name} enabled={enabled} back={()=>{setObservationOpen(false);setSelected(null);}} configure={()=>setObservationOpen(false)} headerToolsHost={headerToolsHost}/>
:detail&&monitorOpen?<BoardMonitorView vehicle={detail.id} name={detail.name} back={()=>setMonitorOpen(false)} headerToolsHost={headerToolsHost}/>
:<div className="fleet-workspace">
{detail?<>
<WorkspaceBackButton label="К списку аппаратов" onClick={()=>setSelected(null)} host={headerToolsHost}/>
<VehicleSensors onUpdated={fleet.acceptVehicle} vehicle={detail} enabled={enabled} onAddComputer={()=>setAdding(true)} onSettings={()=>setSettingsOpen(true)} onMonitor={()=>setMonitorOpen(true)}/>
</>:!fleet.items?<LoadingRegion loading={!fleet.error} label="Получение аппаратов"/>:fleet.items.length===0?<SettingsCard title="Аппаратов пока нет" description="Создайте аппарат и подключите его бортовой компьютер по приглашению Mission Core Node."/>:<ResourceList aria-label="Аппараты">{fleet.items.map(item=><li key={item.id}><ResourceRow icon={<Icon name="apps"/>} title={item.name} description={platformLabel(item.platform)} status={<StatusBadge tone={!fleet.error&&item.enrollment==='paired'&&item.connectivity==='online'?'success':'neutral'}>{fleet.error?'Нет свежих данных':`БК: ${boardStatus(item)}`}</StatusBadge>} actions={<><IconButton label={`Конфигурация: ${item.name}`} onClick={()=>setSelected(item.id)}><Icon name="sliders"/></IconButton><IconButton label={`Центр наблюдения и управления: ${item.name}`} onClick={()=>{setSelected(item.id);setObservationOpen(true);}}><Icon name="eye"/></IconButton></>}/></li>)}</ResourceList>}
</div>;
return <>{headerTitleHost&&createPortal(titleSuffix,headerTitleHost)}{headerAdd}{headerObservation}{content}
{adding&&<NodeInvitationForm key={detail?.id??'new'} vehicle={detail} onClose={()=>setAdding(false)} onComplete={complete} renderWindow={({content,actions,busy})=><Window open title={detail?'Подключить бортовой компьютер':'Добавить аппарат'} subtitle={detail?detail.name:'Создать аппарат и подключить БК по приглашению Node'} size="md" closeOnBackdrop={false} closeOnEscape={!busy} onClose={()=>{if(!busy)setAdding(false);}} footer={<WindowFooterActions>{actions}</WindowFooterActions>}>{content}</Window>}/>}
{settingsOpen&&detail&&<BoardComputerSettings vehicle={detail} enabled={enabled} onClose={()=>setSettingsOpen(false)} onRevoke={()=>{setSettingsOpen(false);setRevoking(detail);}}/>}
<ConfirmationModal open={revoking!==null} title="Отозвать привязку БК?" description={`Аппарат «${revoking?.name??''}» останется в реестре. БК потеряет доступ к Core и получит отзыв при следующем соединении.`} confirmLabel="Отозвать" cancelLabel="Отмена" danger onClose={()=>setRevoking(null)} onConfirm={async()=>{if(!revoking)return;try{await fleetRequest(`/${encodeURIComponent(revoking.id)}`,'DELETE');await fleet.refresh();setRevoking(null);}catch(e){setError(e instanceof Error?e.message:'Не удалось отозвать привязку.');throw e;}}}/>
<ToastStack items={error||fleet.error?[{id:'fleet-error',title:error||fleet.error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/>
</>;
}
@@ -0,0 +1,33 @@
import {Button,Icon,IconButton,ResourceList,ResourceRow,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {commandPending,commandDate,commandDuration,commandReason,commandReceipt,commandEntryStatus,commandStatus,commandTone,type CommandEntry} from '../../../core/fleet/commandRuntime';
import {useCommandAttempts} from '../../../core/fleet/useCommandAttempts';
export function CommandHistory({identifier,items,selected,onSelect,onCancel,onRepeat,working,cancelling}:{identifier:string;items:CommandEntry[];selected:string;onSelect:(id:string)=>void;onCancel:(id:string)=>void;onRepeat:(id:string)=>void;working:boolean;cancelling:string}){
return <ResourceList aria-label="Журнал команд B2">{items.map(item=><li key={item.id}><ResourceRow title={item.description.label??'Операция B2'} description={commandDate(item.created_at)} metadata={`${item.durable?`Попыток: ${item.attempt_count??0} · `:''}Отправлено: ${commandDate(item.dispatched_at)} · Ответ: ${commandDuration(item.roundtrip_seconds)}`} status={<StatusBadge tone={commandTone(item.state)}>{commandEntryStatus(item)}</StatusBadge>} actions={<><Button aria-pressed={item.id===selected} onClick={()=>onSelect(item.id===selected?'':item.id)}>Подробнее</Button><IconButton label={`Повторить: ${item.description.label??'Операция B2'}`} title={commandPending(item.state)?'Дождитесь завершения операции':'Отправить ещё раз'} loading={cancelling===`repeat:${item.id}`} disabled={working||commandPending(item.state)} onClick={()=>onRepeat(item.id)}><Icon name="refresh"/></IconButton>{(item.state==='waiting'||item.durable&&commandPending(item.state))&&<Button loading={cancelling===item.id} disabled={working||item.stop_requested} onClick={()=>onCancel(item.id)}>{item.state==='waiting'?'Отменить':item.stop_requested?'Остановка повторов':'Остановить повторы'}</Button>}</>}/>{item.id===selected&&<CommandDetails key={item.id} identifier={identifier} current={item}/>}</li>)}</ResourceList>;
}
function CommandDetails({identifier,current}:{identifier:string;current:CommandEntry}){
const attempts=useCommandAttempts(identifier,current);
return <SettingsCard title={current.description.label??'Операция B2'} description={`ID ${current.id} · ПО ${current.firmware??'неизвестно'}`}>
{current.description.wire&&<p><code>{current.description.wire}</code></p>}
<dl className="fleet-facts">
<div><dt>Принято Core</dt><dd>{commandDate(current.created_at)}</dd></div>
{current.durable?<><div><dt>Попыток</dt><dd>{current.attempt_count??0}</dd></div>{current.attempt_expires_at!==undefined&&<div><dt>Срок текущей попытки</dt><dd>{commandDate(current.attempt_expires_at)}</dd></div>}</>:<><div><dt>Срок отправки из Core</dt><dd>{commandDate(current.queue_deadline)}</dd></div><div><dt>Срок ожидания ответа</dt><dd>{commandDate(current.expires_at)}</dd></div></>}
<div><dt>Отправлено B2</dt><dd>{commandDate(current.dispatched_at)}</dd></div><div><dt>Ответ B2</dt><dd>{commandDate(current.received_at)}</dd></div>
{current.delivered_at!==undefined&&<div><dt>Доставка подтверждена</dt><dd>{commandDate(current.delivered_at)} · {commandDuration(current.delivery_seconds)}</dd></div>}
{current.device_accepted_at!==undefined&&<div><dt>Принято B2</dt><dd>{commandDate(current.device_accepted_at)}</dd></div>}
{current.scope==='command'&&<div><dt>Результат B2</dt><dd>{commandReceipt(current)}</dd></div>}
<div><dt>До ответа</dt><dd>{commandDuration(current.roundtrip_seconds)}</dd></div>
{current.reconnected_at!==undefined&&<div><dt>Возвращение на связь</dt><dd>{commandDate(current.reconnected_at)}</dd></div>}
</dl>
{commandReason(current)&&<p>{commandReason(current)}</p>}
<p>{current.description.confirmation}</p>
{current.stop_requested&&<p>Новые попытки остановлены или ожидают остановки на VPS. Уже переданная попытка может завершиться.</p>}
{current.durable&&<>
<ResourceList aria-label="Попытки доставки">{attempts.items.map(item=><li key={item.id}><ResourceRow title={`Попытка ${item.number}${item.phase==='inspect'?' · проверка состояния':''}`} description={`Отправлено: ${commandDate(item.dispatched_at)} · Ответ: ${commandDate(item.received_at)} · ${commandDuration(item.roundtrip_seconds)}`} status={<StatusBadge tone={commandTone(item.state)}>{commandStatus(item.state)}</StatusBadge>} metadata={item.device_code!==undefined?commandReceipt({...current,device_code:item.device_code}):undefined}/></li>)}</ResourceList>
{attempts.error&&<><p>{attempts.error}</p><Button onClick={attempts.refresh}>Повторить чтение попыток</Button></>}
{attempts.next_before!==null&&<Button loading={attempts.working} onClick={()=>void attempts.more()}>Предыдущие попытки</Button>}
</>}
<ResourceList aria-label="Этапы операции">{[...current.events].sort((a,b)=>(a.occurred_at??a.observed_at)-(b.occurred_at??b.observed_at)).map((event,index)=><li key={index}><ResourceRow title={`${commandStatus(event.state)}${event.attempt?` ${event.attempt}`:''}`} description={event.stage?({preflight:'Чтение настроек',write:'Запись',verify:'Проверка',restart:'Ожидание после перезапуска'} as Record<string,string>)[event.stage]:undefined} metadata={`${commandDate(event.occurred_at??event.observed_at)}${event.historical?' · восстановлено из истории':''}`}/></li>)}</ResourceList>
</SettingsCard>;
}
@@ -0,0 +1,26 @@
import {SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {cellularFresh,cellularSlotDescription,cellularSimLabel,cellularSlotView} from '../../../core/fleet/cellular';
import type {EquipmentObservation} from '../../../core/fleet/equipment';
import type {TrackerTelemetry} from '../../../core/fleet/vps';
export function EquipmentCellular({telemetry,observed}:{telemetry?:TrackerTelemetry;observed:EquipmentObservation}){
const status=telemetry?.cellular?.status;
const configTime=observed.configuration_read_at??observed.read_at;
return <div className="fleet-form">
{(['1','2'] as const).map(slot=>{
const view=cellularSlotView(telemetry,slot),network=view.network;
const fresh=!!telemetry?.online&&cellularFresh(network);
const apn=slot==='1'?observed.configuration.apn1:observed.configuration.apn2;
return <SettingsCard key={slot} title={`SIM ${slot}`} description={cellularSlotDescription(telemetry,slot)} actions={<StatusBadge tone={view.internet?'success':'neutral'}>{view.role}</StatusBadge>}>
<dl className="fleet-facts">
<div><dt>Регистрация</dt><dd>{cellularSimLabel(status?.sim_states[slot])}</dd></div>
{!view.absent&&network&&<>
<div><dt>Сигнал</dt><dd>{network.signal===null?'Неизвестен':`${network.signal} из 31`}</dd></div>
<div><dt>{fresh?'Сеть измерена':'Последнее измерение сети'}</dt><dd>{new Date(network.measured_at*1000).toLocaleString('ru-RU')}</dd></div>
</>}
<div><dt>APN из настроек B2</dt><dd>{apn||'Не задан'}<br/>Прочитан {new Date(configTime*1000).toLocaleString('ru-RU')}</dd></div>
</dl>
</SettingsCard>;
})}
</div>;
}
@@ -0,0 +1,37 @@
import {useState} from 'react';
import {Button,LoadingRegion,Select,SettingsCard,StatusBadge,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
import {commandPending} from '../../../core/fleet/commandRuntime';
import {useCommandRuntime} from '../../../core/fleet/useCommandRuntime';
import {telemetryLabel,type TrackerTelemetry} from '../../../core/fleet/vps';
import type {IndependentDevice} from '../../../core/fleet/equipment';
import {CommandHistory} from './CommandHistory';
export function EquipmentCommandWindow({device,telemetry,onClose}:{device:IndependentDevice;telemetry?:TrackerTelemetry;onClose:()=>void}){
const runtime=useCommandRuntime(device.id);
const [preset,setPreset]=useState('position'),[filter,setFilter]=useState('all'),[selected,setSelected]=useState('');
const data=runtime.data,chosen=data?.catalog.find(value=>value.id===(runtime.intent?.preset_id??preset));
const pending=Object.entries(data?.counts??{}).reduce((total,[state,n])=>total+(commandPending(state)?n:0),0);
const items=runtime.items.filter(item=>filter==='all'||(filter==='active'?commandPending(item.state):!commandPending(item.state)));
return <><Window open title="Команды ARNavi B2" subtitle={data?.device.name??device.name} size="lg" onClose={onClose}>
<div className="fleet-form">
<StatusBadge tone={telemetry?.online?'success':'neutral'}>{telemetryLabel(telemetry)}</StatusBadge>
<LoadingRegion loading={!data&&!runtime.error} label="Загрузка команд и журнала">
{data&&<>
<SettingsCard title="Отправить команду" description={`B2 · ПО ${data.device.observed.firmware}`}>
<Select label="Команда" value={runtime.intent?.preset_id??preset} options={data.catalog.map(value=>({value:value.id,label:value.label,disabled:!!value.unavailable}))} disabled={runtime.working||!!runtime.intent} onChange={setPreset}/>
{runtime.intent?.repeat_of&&<p>Повтор: {runtime.items.find(item=>item.id===runtime.intent?.repeat_of)?.description.label??'операция из журнала'}. Уточните отправку, чтобы получить результат принятия команды.</p>}
{chosen&&!runtime.intent?.repeat_of&&<><dl className="fleet-facts"><div><dt>{chosen.encoding} · тело</dt><dd><code>{chosen.wire}</code></dd></div></dl><p>{chosen.confirmation} {data.durable_kinds?.includes(chosen.command.kind)?(chosen.command.kind==='pulse-output'?'Задание ждёт отправки до отмены. После отправки импульс автоматически не повторяется при неизвестном результате.':chosen.command.kind==='set-output'?'Задание ждёт связи и отправки до отмены. При неподтверждённой доставке повторяется установка того же состояния.':'Задание сохраняется до результата или остановки повторов. При потере связи VPS уточняет результат и повторяет неподтверждённые попытки.'):`Ожидание отправки: до ${chosen.queue_seconds} с. Отправленная команда автоматически не повторяется.`}{chosen.encoding.includes('FC')&&' Пароль скрыт.'}</p>{chosen.unavailable&&<p>{chosen.unavailable}</p>}</>}
<WindowFooterActions><Button loading={runtime.activity==='send'} disabled={runtime.working||(!runtime.intent&&(!chosen||!!chosen.unavailable||(data.capacity!==null&&pending>=data.capacity)))} onClick={()=>void runtime.send(preset)}>{runtime.intent?'Уточнить отправку':'Отправить'}</Button></WindowFooterActions>
</SettingsCard>
<SettingsCard title="Журнал операций" description={`Незавершённых: ${pending}${data.capacity===null?' · Задания сохранены':` · Вместимость очереди: ${data.capacity}`}`}>
<Select label="Показать операции" value={filter} onChange={setFilter} options={[{value:'all',label:'Все операции'},{value:'active',label:'В очереди и выполняются'},{value:'finished',label:'Завершённые'}]}/>
{!items.length&&<p>{runtime.items.length?'В загруженной части истории таких операций нет.':'Команд пока нет.'}</p>}
<CommandHistory identifier={device.id} items={items} selected={selected} onSelect={setSelected} onCancel={id=>void runtime.cancel(id)} onRepeat={id=>void runtime.repeat(id)} working={runtime.working||!!runtime.intent} cancelling={runtime.activity}/>
{runtime.before!==null&&<WindowFooterActions><Button loading={runtime.activity==='more'} disabled={runtime.working} onClick={()=>void runtime.more()}>Загрузить предыдущие</Button></WindowFooterActions>}
</SettingsCard>
</>}
</LoadingRegion>
{!data&&runtime.error&&<Button onClick={()=>void runtime.refresh().catch(()=>undefined)}>Повторить чтение</Button>}
</div>
</Window><ToastStack items={runtime.error?[{id:'command-runtime-error',title:runtime.error,tone:'error',durationMs:null}]:[]} onDismiss={()=>runtime.setError('')}/></>;
}
@@ -0,0 +1,29 @@
import {useState} from 'react';
import {Button,Select,SettingsCard,StatusBadge,TextField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
import {equipmentRequest,type EquipmentCandidate,type EquipmentModel,type EquipmentProfile,type IndependentDevice} from '../../../core/fleet/equipment';
import {NodeInvitationForm} from '../NodeInvitationForm';
import {VPSHostSettings} from './VPSHostSettings';
import type {VPSHost} from '../../../core/fleet/vps';
import type {SensorEnrollmentProps} from '../../../../../../packages/sensor-ui/src/extensions';
import type {Vehicle} from '../../../core/fleet/useFleet';
export function EquipmentConnect({vehicle,vehicles,models,profiles,hosts,onComputer,onVPS,onClose,onAdded}:{vehicle:Vehicle;vehicles:Vehicle[];models:EquipmentModel[];profiles:EquipmentProfile[];hosts:VPSHost[];onComputer:()=>void;onVPS:()=>void;onClose:()=>void;onAdded:(item:IndependentDevice)=>void}){
const [type,setType]=useState('computer'),[name,setName]=useState(''),[target,setTarget]=useState(vehicle.id),[profile,setProfile]=useState('');
const [candidate,setCandidate]=useState<EquipmentCandidate|null>(null),[busy,setBusy]=useState(false),[error,setError]=useState('');
const model=models.find(m=>m.id===type),selectedProfile=profiles.find(p=>p.id===profile);
async function inspect(){setBusy(true);setError('');setCandidate(null);try{const value=await equipmentRequest<EquipmentCandidate>('/inspect','POST',{model_id:type});setCandidate(value);setName(current=>current||`${model?.label??''} · ${value.observed.device_id}`);}catch(e){setError(e instanceof Error?e.message:'Не удалось прочитать устройство.');}finally{setBusy(false);}}
async function add(){if(!candidate)return;setBusy(true);setError('');try{onAdded(await equipmentRequest<IndependentDevice>('/instances','POST',{candidate_id:candidate.id,name:name.trim(),vehicle_id:target,profile_id:profile||null}));}catch(e){setError(e instanceof Error?e.message:'Не удалось добавить устройство.');}finally{setBusy(false);}}
const renderWindow:SensorEnrollmentProps['renderWindow']=({content,actions,busy:pending})=><Window open title="Подключить независимое устройство" subtitle={vehicle.name} size="md" closeOnBackdrop={false} closeOnEscape={!pending} onClose={()=>{if(!pending)onClose();}} footer={<WindowFooterActions>{actions}</WindowFooterActions>}><div className="fleet-form"><Select label="Тип устройства" value={type} options={[{value:'computer',label:'Бортовой компьютер'},...models.map(m=>({value:m.id,label:m.label})),{value:'vps-host',label:'VPS Host ARNavi'}]} disabled={pending} onChange={value=>{setType(value);setCandidate(null);setName('');setProfile('');}}/>{content}</div></Window>;
if(type==='computer')return <NodeInvitationForm vehicle={vehicle} onClose={onClose} onComplete={()=>onComputer()} renderWindow={renderWindow}/>;
if(type==='vps-host')return <VPSHostSettings hosts={hosts} vehicle={vehicle} vehicles={vehicles} onClose={onClose} onSaved={onVPS} renderWindow={renderWindow}/>;
return <>{renderWindow({busy,actions:<><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!candidate||!name.trim()||!target} onClick={()=>void add()}>Добавить к аппарату</Button></>,content:<div className="fleet-form">
{model&&<><TextField label="Название" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
<Select label="Аппарат" value={target} options={vehicles.map(v=>({value:v.id,label:v.name}))} onChange={setTarget} disabled={busy}/>
<Select label="Профиль настроек" value={profile} options={[{value:'',label:'Прочитать настройки трекера'},...profiles.filter(p=>p.model_id===type).map(p=>({value:p.id,label:`${p.name} · ${new Date(p.created_at*1000).toLocaleString('ru-RU')}`}))]} onChange={setProfile} disabled={busy}/>
{selectedProfile&&<SettingsCard title={selectedProfile.name} description={selectedProfile.settings.endpoint?`${selectedProfile.settings.endpoint.host}:${selectedProfile.settings.endpoint.port} · сервер ${selectedProfile.settings.endpoint.slot}`:'Адрес сервера сохраняется из трекера'}/>}
<SettingsCard title="USB на этом Mac" description="Подключите один трекер кабелем с передачей данных. Проверка считает модель, идентификатор и настройки."><Button loading={busy} disabled={busy} onClick={()=>void inspect()}>{candidate?'Прочитать повторно':'Проверить USB'}</Button></SettingsCard>
{candidate&&<SettingsCard title={`${candidate.observed.model} · ${candidate.observed.device_id}`} description={`IMEI …${candidate.observed.imei_suffix} · ПО ${candidate.observed.firmware}`}><StatusBadge tone="success">Настройки прочитаны</StatusBadge><p>Устройство будет добавлено в реестр. Передача на ваш сервер ещё не подтверждена; выбранный профиль будет сохранён для настройки.</p></SettingsCard>}
</>}
</div>
})}<ToastStack items={error?[{id:'equipment-connect',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
}
@@ -0,0 +1,44 @@
import {useEffect,useRef,useState} from 'react';
import {Button,Icon,LoadingRegion,Select,SettingsCard,StatusBadge,ToastStack} from '@nodedc/ui-react';
import type {IndependentDevice} from '../../../core/fleet/equipment';
import {downloadFirmware,readFirmware,uploadFirmware,type FirmwareCatalog} from '../../../core/fleet/firmware';
export function EquipmentFirmware({device}:{device:IndependentDevice}){
const [catalog,setCatalog]=useState<FirmwareCatalog|null>(null),[selected,setSelected]=useState('');
const [loading,setLoading]=useState(true),[uploading,setUploading]=useState(false),[downloading,setDownloading]=useState(false);
const [loadError,setLoadError]=useState(''),[error,setError]=useState(''),[notice,setNotice]=useState(''),[reload,setReload]=useState(0);
const picker=useRef<HTMLInputElement>(null);
useEffect(()=>{let active=true;setLoading(true);setLoadError('');
readFirmware(device.model_id).then(value=>{if(active){setCatalog(value);setSelected(current=>value.items.some(item=>item.id===current)?current:value.items[0]?.id??'');}})
.catch(e=>{if(active)setLoadError(e instanceof Error?e.message:'Не удалось прочитать архив прошивок.');})
.finally(()=>{if(active)setLoading(false);});return()=>{active=false;};
},[device.model_id,reload]);
const item=catalog?.items.find(image=>image.id===selected);
async function add(file:File){setUploading(true);setError('');setNotice('');try{
const image=await uploadFirmware(device.model_id,file);setSelected(image.id);setReload(value=>value+1);setNotice('Файл сохранён в Mission Core. Прошивка трекера не изменена.');
}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить файл.');}finally{setUploading(false);}}
async function download(){if(!item)return;setDownloading(true);setError('');try{await downloadFirmware(item);}catch(e){setError(e instanceof Error?e.message:'Не удалось скачать файл.');}finally{setDownloading(false);}}
const recordedVersion=device.observed.firmware;
return <>
<SettingsCard title="Прошивка трекера" description="Последняя считанная версия устройства.">
<dl className="fleet-facts"><div><dt>Версия</dt><dd>{recordedVersion||'Нет сведений'}</dd></div><div><dt>Считана</dt><dd>{device.observed.read_at?new Date(device.observed.read_at*1000).toLocaleString('ru-RU'):'Нет сведений'}</dd></div></dl>
<p>Обновление прошивки через Mission Core недоступно. Файлы ниже хранятся отдельно от настроек трекера.</p>
</SettingsCard>
<SettingsCard title="Файлы прошивок" description="Архив Mission Core. Добавление и выбор файла не запускают установку.">
<input ref={picker} type="file" accept=".dfw" hidden aria-label="Файл прошивки .dfw" onChange={e=>{const file=e.target.files?.[0];e.target.value='';if(file)void add(file);}}/>
<Button icon={<Icon name="upload"/>} loading={uploading} disabled={uploading||downloading} onClick={()=>picker.current?.click()}>Добавить файл .dfw</Button>
<LoadingRegion loading={loading} label="Читаем архив прошивок">
{loadError?<><p>{loadError}</p><Button onClick={()=>setReload(value=>value+1)}>Повторить загрузку</Button></>:catalog?.items.length?<div className="fleet-form">
<Select label="Файл прошивки" value={selected} onChange={setSelected} disabled={uploading||downloading} options={catalog.items.map(image=>({value:image.id,label:image.version?`${image.version} · ${image.filename}`:image.filename}))}/>
{item&&<>
<StatusBadge tone="neutral">{item.source==='manufacturer'?'Файл производителя':'Файл пользователя · совместимость не проверена'}</StatusBadge>
<dl className="fleet-facts"><div><dt>Версия файла</dt><dd>{item.version??'Не определена'}</dd></div><div><dt>Размер</dt><dd>{new Intl.NumberFormat('ru-RU').format(item.bytes)} байт</dd></div><div><dt>Сохранён</dt><dd>{new Date(item.added_at*1000).toLocaleString('ru-RU')}</dd></div></dl>
<Button icon={<Icon name="download"/>} loading={downloading} disabled={uploading||downloading} onClick={()=>void download()}>Скачать файл</Button>
</>}
{recordedVersion&&!catalog.items.some(image=>image.source==='manufacturer'&&image.version===recordedVersion)&&<p>Образ считанной версии {recordedVersion} в архиве не найден. Сохранённые настройки не являются копией прошивки.</p>}
</div>:<p>Файлов прошивок пока нет. Добавьте файл .dfw с компьютера.</p>}
</LoadingRegion>
</SettingsCard>
<ToastStack items={error?[{id:'firmware-error',title:error,tone:'error',durationMs:null}]:notice?[{id:'firmware-saved',title:notice,tone:'success'}]:[]} onDismiss={()=>{setError('');setNotice('');}}/>
</>;
}
@@ -0,0 +1,26 @@
import {Select,SettingsCard,Switch,TextField} from '@nodedc/ui-react';
import {cellularFresh,cellularSimOptions} from '../../../core/fleet/cellular';
import {allowBothInternetSims,selectInternetSim,type ConnectivityPreset,type EquipmentObservation,type EquipmentPolicy} from '../../../core/fleet/equipment';
import type {TrackerTelemetry} from '../../../core/fleet/vps';
export function EquipmentInternet({telemetry,observed,presets,value,onChange,disabled}:{telemetry?:TrackerTelemetry;observed:EquipmentObservation;presets:ConnectivityPreset[];value:EquipmentPolicy;onChange:(value:EquipmentPolicy)=>void;disabled:boolean}){
const options=cellularSimOptions(telemetry);
const preferred=['both','native'].includes(value.connectivity.strategy)?value.connectivity.strategy:value.connectivity.activate?String(value.connectivity.sim_slot??1):'';
const both=['both','native'].includes(preferred);
const slot=both?preferred:options.some(option=>option.value===preferred)?preferred:'';
const current=slot==='1'?observed.configuration.apn1:observed.configuration.apn2;
const connection=value.connectivity;
const automatic=connection.strategy==='sim'&&connection.automatic===true;
const access=telemetry?.internet_access?.[slot];
const targeted=String(connection.sim_slot??1)===slot;
const apn=connection.strategy==='sim'&&targeted?connection.apn??current:connection.strategy==='operator'&&targeted?presets.find(p=>p.id===connection.preset_id)?.apn??current:connection.strategy==='manual'?(slot==='1'?connection.apn1:connection.apn2):current;
return <SettingsCard title="Интернет"><div className="fleet-form">
<Select label="SIM для интернета" value={slot} options={[{value:'',label:'Выберите режим SIM',disabled:true},{value:'native',label:'Автоматический режим — без заданного APN'},{value:'both',label:'Автоматический режим — с сохранением APN'},...options.map(option=>({...option,label:`Только ${option.label}`}))]} disabled={disabled} onChange={next=>onChange(['both','native'].includes(next)?allowBothInternetSims(value,next==='native'):selectInternetSim(value,Number(next)))}/>
<p>{slot==='native'?'Оба слота разрешены: B2 сам выбирает SIM для интернета. APN, логин и пароль обеих SIM будут очищены; подключение возможно, если оператор разрешает доступ без них. После сохранения B2 перезапустится.':slot==='both'?'Оба слота разрешены: B2 сам выбирает SIM для интернета. Текущие APN, логин и пароль каждой SIM сохранятся. Одновременно интернет работает через одну карту. После сохранения B2 перезапустится.':'Выберите одну SIM для принудительного подключения или автоматический режим. При выборе одной интернет на другой запрещается. Если выбранная SIM не подключится, для восстановления может потребоваться USB.'}</p>
{!!options.length&&(!telemetry?.online||!cellularFresh(telemetry.cellular?.status))&&<p>Показаны последние обнаруженные SIM. Ожидаем обновления связи с B2.</p>}
{slot&&!both?<>
<Switch label="Подбирать интернет для этой карты" checked={automatic} disabled={disabled} onChange={checked=>onChange({...value,connectivity:{strategy:'sim',sim_slot:Number(slot),activate:true,automatic:checked,apn:checked?null:apn,apn1:'',apn2:'',preset_id:null}})}/>
{automatic?<p>{access?.state==='ready'?`${access.source==='verified_card'?'Проверенные настройки этой карты':'Стандартные настройки оператора'}: ${access.apn}. После сохранения проверим запись и подключение выбранной SIM.`:access?.state==='unknown_card'?'Карта ещё не распознана. Прочитайте её через USB или отключите автоподбор и задайте APN.':access?.state==='unsupported_operator'?'Для этой карты нет сохранённых настроек. Отключите автоподбор и задайте APN.':'Ожидаем подтверждение карты в выбранном слоте.'}</p>:<TextField label="APN" value={apn} maxLength={29} disabled={disabled} hint={`В B2 прочитан: ${current||'не задан'}. Изменение будет отправлено при сохранении настроек.`} onChange={event=>onChange({...value,connectivity:{strategy:'sim',sim_slot:Number(slot),activate:true,automatic:false,apn:event.target.value,apn1:'',apn2:'',preset_id:null}})}/>}
</>:!both&&!options.length&&<p>Ожидаем актуальные сведения о SIM от трекера.</p>}
</div></SettingsCard>;
}
@@ -0,0 +1,17 @@
import {Select,SettingsCard,Switch,TextField} from '@nodedc/ui-react';
import type {TrackerTelemetry,VPSHost} from '../../../core/fleet/vps';
import type {ConnectivityPreset,EquipmentField,EquipmentObservation,EquipmentPolicy} from '../../../core/fleet/equipment';
import {EquipmentInternet} from './EquipmentInternet';
export function EquipmentPolicyFields({hosts,section,fields,presets,telemetry,observed,value,onChange,disabled}:{telemetry?:TrackerTelemetry;observed:EquipmentObservation;hosts:VPSHost[];section:string;fields:EquipmentField[];presets:ConnectivityPreset[];value:EquipmentPolicy;onChange:(value:EquipmentPolicy)=>void;disabled:boolean}){
if(section==='connection')return <div className="fleet-form">
<EquipmentInternet telemetry={telemetry} observed={observed} presets={presets} value={value} onChange={onChange} disabled={disabled}/>
<SettingsCard title="Сервер мониторинга" description="Используйте постоянное DNS-имя: при переезде VPS можно сохранить адрес в трекерах.">
<div className="fleet-form"><Select label="Зарегистрированный VPS" value={hosts.find(h=>h.status?.tracker.host===value.endpoint?.host&&h.status?.tracker.port===value.endpoint?.port)?.id??''} options={[{value:'',label:'Сохранить адрес или указать вручную'},...hosts.filter(h=>h.status).map(h=>({value:h.id,label:h.name}))]} disabled={disabled} onChange={id=>{const host=hosts.find(h=>h.id===id);if(host?.status)onChange({...value,endpoint:{...host.status.tracker,slot:value.endpoint?.slot??2}});}}/><Switch label="Задать сервер в профиле" checked={value.endpoint!==null} disabled={disabled} onChange={enabled=>onChange({...value,endpoint:enabled?{host:'',port:0,slot:1}:null})}/>
{value.endpoint&&<><TextField label="DNS/IP сервера" value={value.endpoint.host} maxLength={49} disabled={disabled} onChange={e=>onChange({...value,endpoint:{...value.endpoint!,host:e.target.value}})}/><TextField label="Порт" type="number" min={1} max={65535} value={value.endpoint.port||''} disabled={disabled} onChange={e=>onChange({...value,endpoint:{...value.endpoint!,port:Number(e.target.value)}})}/><Select label="Слот сервера" value={String(value.endpoint.slot)} options={[1,2,3,4].map(n=>({value:String(n),label:`Сервер ${n}`}))} disabled={disabled} onChange={slot=>onChange({...value,endpoint:{...value.endpoint!,slot:Number(slot)}})}/><p>Протокол INTERNAL. Остальные серверы сохраняются.</p></>}
</div>
</SettingsCard>
</div>;
return <div className="fleet-form"><p>Пустое поле — сохранить значение конкретного трекера. Ноль — задать нулевое значение.</p>{fields.filter(f=>f.group===section).map(field=><TextField key={field.key} label={field.label} type="number" min={field.min} max={field.max} step={1} hint={`${field.min} … ${field.max}`} value={value.parameters[field.key]??''} disabled={disabled} onChange={e=>{const parameters={...value.parameters};if(e.target.value==='')delete parameters[field.key];else parameters[field.key]=Number(e.target.value);onChange({...value,parameters});}}/>)}</div>;
}
@@ -0,0 +1,55 @@
import {useEffect,useRef,useState} from 'react';
import {Button,FeatureSettingsWindow,Select,SettingsCard,StatusBadge,TextField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
import {configurationWriteNotStarted,simSelectionIntent,equipmentPolicyEqual,equipmentApplyMessage,equipmentRequest,networkOperationMessage,networkOperationProgress,policyError,type EquipmentModel,type EquipmentProfile,type IndependentDevice} from '../../../core/fleet/equipment';
import {cellularSimCurrent} from '../../../core/fleet/cellular';
import type {Vehicle} from '../../../core/fleet/useFleet';
import {telemetryLabel,type TrackerTelemetry,type VPSHost} from '../../../core/fleet/vps';
import {EquipmentPolicyFields} from './EquipmentPolicyFields';
import {EquipmentCellular} from './EquipmentCellular';
import {EquipmentFirmware} from './EquipmentFirmware';
export function EquipmentSettings({device,model,hosts,telemetry,vehicles,profiles,onClose,onObserved,onProfile,onCommands}:{device:IndependentDevice;model:EquipmentModel;hosts:VPSHost[];telemetry?:TrackerTelemetry;vehicles:Vehicle[];profiles:EquipmentProfile[];onClose:()=>void;onObserved:(item:IndependentDevice)=>void;onProfile:()=>void;onCommands:()=>void}){
const [name,setName]=useState(device.name),[target,setTarget]=useState(device.vehicle_id),[settings,setSettings]=useState(device.settings),[section,setSection]=useState('identity');
const [profileName,setProfileName]=useState(''),[profileOpen,setProfileOpen]=useState(false),[working,setBusy]=useState(false),[error,setError]=useState(''),[notice,setNotice]=useState(''),[selectedProfile,setSelectedProfile]=useState('');
const contentRef=useRef<HTMLDivElement>(null);
const [simRequested,setSimRequested]=useState(false);
const selectSim=simSelectionIntent(settings,device.settings,simRequested);
function changeSettings(value:typeof settings){if(value.connectivity!==settings.connectivity)setSimRequested(true);setSettings(value);}
const [now,setNow]=useState(()=>Date.now()/1000);
const progress=networkOperationProgress(device.network_operation,now);
const networkPending=progress.pending;
useEffect(()=>{if(!networkPending)return;setNow(Date.now()/1000);const timer=setInterval(()=>setNow(Date.now()/1000),1000);return()=>clearInterval(timer);},[networkPending,device.network_operation?.id]);
const busy=working||networkPending;
useEffect(()=>{if(!networkPending)return;let active=true;let timer:ReturnType<typeof setTimeout>;async function poll(){try{const value=await equipmentRequest<{items:IndependentDevice[]}>('/instances');const current=value.items.find(d=>d.id===device.id);if(active&&current)onObserved(current);}catch{/* Keep the pending operation visible; the VPS owns its bounded expiry. */}finally{if(active)timer=setTimeout(()=>void poll(),3000);}}timer=setTimeout(()=>void poll(),3000);return()=>{active=false;clearTimeout(timer);};},[device.id,networkPending,onObserved]);
const observed=device.observed;
const secondary=observed.configuration.servers.find(s=>s.slot===2);
const fullSettings=hosts.some(h=>h.state==='paired'&&h.vehicle_ids.includes(device.vehicle_id)&&['0.1.15','0.1.16','0.1.17','0.1.18','0.1.19','0.1.20','0.1.21','0.1.22','0.1.23','0.1.24','0.1.25','0.1.26','0.1.27','0.1.28','0.1.29','0.1.30','0.1.31','0.1.32','0.1.33','0.1.34','0.1.35','0.1.36','0.1.37','0.1.38','0.1.39','0.1.40','0.1.41','0.1.42','0.1.43','0.1.44','0.1.45','0.1.46','0.2.0','0.2.1'].includes(h.status?.version??'')&&h.status?.tracker.host===secondary?.host&&h.status?.tracker.port===secondary?.port);
const supported=observed.supported_profile_fields??Object.keys(device.settings.parameters);
const fields=model.fields.filter(f=>supported.includes(f.key));
const validation=policyError(settings,fields)||(selectSim&&settings.connectivity.strategy==='sim'&&!cellularSimCurrent(telemetry,settings.connectivity.sim_slot??1)?'Ожидаем свежие данные выбранной SIM перед отправкой настроек.':'');
const dirty=name!==device.name||target!==device.vehicle_id||!equipmentPolicyEqual(settings,device.settings);
const writable=model.usb_write_firmware?.includes(observed.firmware)??false;
const [applying,setApplying]=useState(false),[saving,setSaving]=useState(false),[readingUsb,setReadingUsb]=useState(false);
async function applyUsb(){setBusy(true);setApplying(true);setError('');try{onObserved(await equipmentRequest<IndependentDevice>(`/instances/${device.id}/apply`,'POST',{expected_revision:device.revision}));}catch(e){setError(e instanceof Error?e.message:'Результат записи не получен. Прочитайте USB повторно.');}finally{setBusy(false);setApplying(false);}}
const sections=[{id:'identity',label:'Устройство и аппарат'},{id:'connection',label:'Сервер и связь'},{id:'commands',label:'Команды'},{id:'firmware',label:'Прошивка'},...Array.from(new Set(fields.map(f=>f.group))).map(group=>({id:group,label:group,group:'Параметры профиля'}))];
async function readNetwork(){setBusy(true);setError('');try{onObserved(await equipmentRequest<IndependentDevice>(`/instances/${device.id}/inspect-network`,'POST',{expected_revision:device.revision}));}catch(e){setError(e instanceof Error?e.message:'Чтение через VPS не подтверждено.');}finally{setBusy(false);}}
async function applyNetwork(item:IndependentDevice=device,selection=selectSim){setBusy(true);setError('');contentRef.current?.scrollIntoView({block:'start'});try{onObserved(await equipmentRequest<IndependentDevice>(`/instances/${item.id}/apply-network`,'POST',{expected_revision:item.revision,select_sim:selection}));setSimRequested(false);}catch(e){setError(e instanceof Error?e.message:'Отправка через VPS не подтверждена.');}finally{setBusy(false);}}
async function save(){setBusy(true);setSaving(true);setError('');setNotice('');try{const changed=!equipmentPolicyEqual(settings,device.settings);const retrySelection=selectSim;if(!dirty&&!retrySelection){setNotice('Изменений настроек нет. Команда трекеру не отправлена.');return;}const item=dirty?await equipmentRequest<IndependentDevice>(`/instances/${device.id}`,'PUT',{expected_revision:device.revision,name:name.trim(),vehicle_id:target,settings}):device;onObserved(item);if(changed||retrySelection)await applyNetwork(item,selectSim);else setNotice('Изменения сохранены в Mission Core.');}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить настройки.');}finally{setBusy(false);setSaving(false);}}
async function readUsb(){setBusy(true);setReadingUsb(true);setError('');try{onObserved(await equipmentRequest<IndependentDevice>(`/instances/${device.id}/inspect`,'POST',{expected_revision:device.revision}));}catch(e){setError(e instanceof Error?e.message:'Не удалось прочитать USB.');}finally{setBusy(false);setReadingUsb(false);}}
async function saveProfile(){setBusy(true);setError('');try{await equipmentRequest('/profiles','POST',{name:profileName.trim(),model_id:device.model_id,settings});setProfileOpen(false);setNotice('Профиль сохранён и доступен при подключении новых трекеров.');onProfile();}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить профиль.');}finally{setBusy(false);}}
return <><FeatureSettingsWindow open={!profileOpen} title="Настройки устройства" subtitle={device.name} identity={{title:model.label,subtitle:`IMEI …${observed.imei_suffix}`,avatarLabel:model.label}} sections={sections} activeSection={section} onSectionChange={setSection} onClose={()=>{if(!working)onClose();}} footer={section==='firmware'?undefined:<WindowFooterActions><Button loading={saving} disabled={busy||!!validation||!name.trim()||!target} onClick={()=>void save()}>Сохранить настройки</Button><Button disabled={working||!!validation} onClick={()=>{setProfileName(`${model.label} — ${name}`.slice(0,80));setProfileOpen(true);}}>Сохранить профиль</Button></WindowFooterActions>}>
<div className="fleet-form" ref={contentRef}><StatusBadge tone={telemetry?.online?'success':'neutral'}>{telemetryLabel(telemetry)}</StatusBadge>{section!=='commands'&&section!=='firmware'&&<SettingsCard title="Настройки через VPS" description={fullSettings?"Параметры профиля записываются через VPS. Текущие настройки читаются перед записью, а результат проверяется повторным чтением. Адрес резервного сервера сохраняется.":"По сети доступна смена адреса и порта сервера 1. Сервер 2 сохраняет связь с текущим VPS. Для полной конфигурации нужен обновлённый VPS."}><p>{equipmentApplyMessage(configurationWriteNotStarted(device.network_operation)?'not_started':device.policy_state)}</p>{device.network_server1&&<p>Последний подтверждённый сервер 1: {device.network_server1.host}:{device.network_server1.port}.</p>}<p>{networkOperationMessage(device.network_operation?.scope!=='command'?device.network_operation:undefined)}</p>{networkPending&&device.network_operation?.scope!=='command'&&<p>{device.network_operation?.durable?`Попыток: ${device.network_operation.attempt_count??0}. Окно можно закрыть — задание сохранено. Повторы можно остановить в журнале команд.`:progress.overdue?'Срок ожидания истёк. Уточняем результат у VPS; повторная отправка заблокирована до получения результата.':`До окончания ожидания: ${progress.remaining??'—'} с. Окно можно закрыть — операция продолжится на VPS.`}</p>}<Button loading={progress.waiting&&device.network_operation?.scope!=='command'&&!device.network_operation?.read_only} disabled={busy||dirty||!!validation||!writable} onClick={()=>void applyNetwork()}>Отправить через VPS</Button><Button loading={progress.waiting&&device.network_operation?.scope!=='command'&&device.network_operation?.read_only} disabled={busy||dirty} onClick={()=>void readNetwork()}>Прочитать через VPS</Button></SettingsCard>}
{section==='connection'&&<EquipmentCellular telemetry={telemetry} observed={observed}/>}
{section==='firmware'?<EquipmentFirmware device={device}/>:section==='identity'?<>
<TextField label="Название" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
<Select label="Привязка к аппарату" value={target} options={vehicles.map(v=>({value:v.id,label:v.name}))} onChange={setTarget} disabled={busy}/>
<Select label="Загрузить сохранённый профиль" value={selectedProfile} options={[{value:'',label:'Текущие настройки'},...profiles.filter(p=>p.model_id===device.model_id).map(p=>({value:p.id,label:`${p.name} · ${new Date(p.created_at*1000).toLocaleString('ru-RU')}`}))]} disabled={busy} onChange={id=>{setSelectedProfile(id);const p=profiles.find(p=>p.id===id);changeSettings(p?.settings??device.settings);}}/>
<SettingsCard title="Сведения B2" description={`ID ${observed.device_id} · ПО ${observed.firmware} · идентификация по USB ${new Date(observed.read_at*1000).toLocaleString('ru-RU')}`}>{observed.configuration_read_at&&<p>Настройки прочитаны через VPS: {new Date(observed.configuration_read_at*1000).toLocaleString('ru-RU')}.</p>}<dl className="fleet-facts"><div><dt>Основная SIM</dt><dd>{observed.sim1_iccid_reported_suffix?`…${observed.sim1_iccid_reported_suffix} (${observed.sim1_iccid_reported_length} цифр в ответе)`:'Нет сведений'}</dd></div><div><dt>Вторая SIM</dt><dd>{observed.sim2_iccid_reported_suffix?`…${observed.sim2_iccid_reported_suffix} (${observed.sim2_iccid_reported_length} цифр в ответе)`:'Нет сведений'}</dd></div><div><dt>APN основной SIM</dt><dd>{observed.configuration.apn1||'Не задан'}</dd></div><div><dt>APN второй SIM</dt><dd>{observed.configuration.apn2||'Не задан'}</dd></div>{observed.configuration.servers.filter(s=>s.host).map(s=><div key={s.slot}><dt>Сервер {s.slot}</dt><dd>{s.host}:{s.port}</dd></div>)}</dl><Button loading={readingUsb} disabled={busy||dirty} onClick={()=>void readUsb()}>Прочитать USB повторно</Button><Button loading={applying} disabled={busy||dirty||!!validation||!writable} onClick={()=>void applyUsb()}>Первоначальная настройка по USB</Button>{applying&&<p>Запись и проверка настроек. Не отсоединяйте USB.</p>}</SettingsCard>
</>:section==='commands'?<SettingsCard title="Команды и журнал" description="Отправка команд, очередь и история обмена с B2."><Button disabled={working||dirty} onClick={onCommands}>Открыть команды</Button>{dirty&&<p>Сохраните изменения перед переходом к командам.</p>}</SettingsCard>:<EquipmentPolicyFields telemetry={telemetry} observed={observed} hosts={hosts.filter(h=>h.vehicle_ids.includes(target))} section={section} fields={fields} presets={model.connectivity_presets??[]} value={settings} onChange={changeSettings} disabled={busy}/>}
{section!=='firmware'&&validation&&<StatusBadge tone="warning">{validation}</StatusBadge>}
</div>
</FeatureSettingsWindow>
<Window open={profileOpen} title="Сохранить профиль" subtitle="Общие настройки для новых трекеров" onClose={()=>{if(!working)setProfileOpen(false);}} closeOnEscape={!working} closeOnBackdrop={false} footer={<WindowFooterActions><Button disabled={working} onClick={()=>setProfileOpen(false)}>Отмена</Button><Button loading={working} disabled={working||!profileName.trim()||!!validation} onClick={()=>void saveProfile()}>Сохранить профиль</Button></WindowFooterActions>}><div className="fleet-form"><TextField label="Название профиля" value={profileName} maxLength={80} disabled={working} onChange={e=>setProfileName(e.target.value)}/><p>Сохранятся параметры работы, выбранный сервер и настройки связи. IMEI, номера SIM, личные пароли и привязка к аппарату не входят в профиль. Настройки уже добавленных устройств не изменятся.</p></div></Window>
<ToastStack items={error?[{id:'equipment-settings-error',title:error,tone:'error',durationMs:null}]:notice?[{id:'equipment-profile-saved',title:notice,tone:'success'}]:[]} onDismiss={()=>{setError('');setNotice('');}}/>
</>;
}
@@ -0,0 +1,40 @@
import {useCallback,useEffect,useState,type ReactNode} from 'react';
import {Button,Icon,IconButton,LoadingRegion,ResourceList,ResourceRow,StatusBadge,ToastStack} from '@nodedc/ui-react';
import {equipmentRequest,type EquipmentModel,type EquipmentProfile,type IndependentDevice} from '../../../core/fleet/equipment';
import {fleetRequest,type Vehicle} from '../../../core/fleet/useFleet';
import {EquipmentConnect} from './EquipmentConnect';
import {EquipmentSettings} from './EquipmentSettings';
import {EquipmentCommandWindow} from './EquipmentCommandWindow';
import {hostOnline,telemetryLabel,useTrackerTelemetry,vpsRequest,type VPSHost} from '../../../core/fleet/vps';
import {VPSHostSettings} from './VPSHostSettings';
import './equipment.css';
export function IndependentEquipment({vehicle,computer,onRefresh}:{vehicle:Vehicle;computer:ReactNode;onComputer:()=>void;onRefresh:()=>void}){
const [devices,setDevices]=useState<IndependentDevice[]|null>(null),[models,setModels]=useState<EquipmentModel[]>([]),[profiles,setProfiles]=useState<EquipmentProfile[]>([]),[vehicles,setVehicles]=useState<Vehicle[]>([]);
const [hosts,setHosts]=useState<VPSHost[]>([]),[vpsOpen,setVpsOpen]=useState(false),[selectedHost,setSelectedHost]=useState<VPSHost|undefined>();
const telemetry=useTrackerTelemetry(vehicle.id);
const [adding,setAdding]=useState(false),[selected,setSelected]=useState<IndependentDevice|null>(null),[error,setError]=useState('');
const refresh=useCallback(async()=>{
const [items,catalog,policies,fleet,vps]=await Promise.all([equipmentRequest<{items:IndependentDevice[]}>(`/instances?vehicle_id=${encodeURIComponent(vehicle.id)}`),equipmentRequest<{models:EquipmentModel[]}>('/catalog'),equipmentRequest<{items:EquipmentProfile[]}>('/profiles'),fleetRequest<{items:Vehicle[]}>(),vpsRequest<{items:VPSHost[]}>()]);
setHosts(vps.items);setDevices(items.items);setModels(catalog.models);setProfiles(policies.items);setVehicles(fleet.items);setError('');
},[vehicle.id]);
const observe=useCallback((item:IndependentDevice)=>{setSelected(item);void refresh().catch(()=>setError('Не удалось обновить независимое оборудование.'));},[refresh]);
const reload=()=>{void refresh().catch(()=>setError('Не удалось обновить независимое оборудование. Повторите запрос.'));};
useEffect(()=>{let active=true;void refresh().catch(()=>{if(active)setError('Не удалось получить независимое оборудование.');});return()=>{active=false;};},[refresh]);
useEffect(()=>{let active=true;let timer:ReturnType<typeof setTimeout>;async function poll(){try{const value=await vpsRequest<{items:VPSHost[]}>();if(active)setHosts(value.items);}catch{/* Existing timestamps expire when the connection is unavailable. */}finally{if(active)timer=setTimeout(()=>void poll(),5000);}}void poll();return()=>{active=false;clearTimeout(timer);};},[]);
const [commandDevice,setCommandDevice]=useState<IndependentDevice|null>(null);
const model=selected&&models.find(m=>m.id===selected.model_id);
const selectedTelemetry=telemetry.items.find(t=>t.instance_id===selected?.id);
return <>
<div className="sensor-actions sensor-inventory-toolbar"><span className="sensor-note">Бортовой компьютер и независимые устройства</span><div className="sensor-actions"><IconButton label="Подключить независимое устройство" onClick={()=>setAdding(true)}><Icon name="plus"/></IconButton><IconButton label="Обновить оборудование" onClick={()=>{reload();onRefresh();}}><Icon name="refresh"/></IconButton></div></div>
{computer}
{!devices?<LoadingRegion loading={!error} label="Загрузка независимых устройств"/>:<ResourceList aria-label="Независимые устройства">{devices.map(device=><li key={device.id}><ResourceRow icon={<Icon name="network"/>} title={device.name} description={`${models.find(m=>m.id===device.model_id)?.label??device.model_id} · IMEI …${device.observed.imei_suffix}`} metadata={telemetry.unavailable?'Связь с сервером не проверена':telemetryLabel(telemetry.items.find(t=>t.instance_id===device.id))} statusPlacement="leading" status={<StatusBadge variant="indicator" tone={!telemetry.unavailable&&telemetry.items.find(t=>t.instance_id===device.id)?.online?'success':'neutral'} aria-label={telemetryLabel(telemetry.items.find(t=>t.instance_id===device.id))}/>} actions={<><IconButton label={`Команды: ${device.name}`} onClick={()=>setCommandDevice(device)}><Icon name="terminal"/></IconButton><IconButton label={`Настройки: ${device.name}`} onClick={()=>setSelected(device)}><Icon name="settings"/></IconButton></>}/></li>)}</ResourceList>}
<ResourceList aria-label="VPS Host ARNavi">{hosts.filter(h=>h.vehicle_ids.includes(vehicle.id)).map(host=><li key={host.id}><ResourceRow icon={<Icon name="database"/>} title={host.name} description="VPS Host ARNavi" metadata={`${host.endpoint} · Аппаратов: ${host.vehicle_ids.length}`} statusPlacement="leading" status={<StatusBadge variant="indicator" tone={hostOnline(host)?'success':'neutral'} aria-label={hostOnline(host)?'VPS на связи':'Нет связи с VPS'}/>} actions={<IconButton label={`Настройки: ${host.name}`} onClick={()=>{setSelectedHost(host);setVpsOpen(true);}}><Icon name="settings"/></IconButton>}/></li>)}</ResourceList>
{vpsOpen&&<VPSHostSettings host={hosts.find(h=>h.id===selectedHost?.id)} hosts={hosts} vehicle={vehicle} vehicles={vehicles} onClose={()=>setVpsOpen(false)} onSaved={()=>{setVpsOpen(false);reload();}}/>}
{error&&!devices&&<Button onClick={reload}>Повторить</Button>}
{adding&&<EquipmentConnect vehicle={vehicle} vehicles={vehicles} models={models} profiles={profiles} hosts={hosts} onClose={()=>setAdding(false)} onComputer={()=>{setAdding(false);onRefresh();}} onVPS={()=>{setAdding(false);reload();}} onAdded={item=>{setAdding(false);if(item.vehicle_id===vehicle.id)setSelected(item);reload();}}/>}
{selected&&model&&<EquipmentSettings key={selected.id} device={selected} model={model} hosts={hosts} telemetry={telemetry.unavailable&&selectedTelemetry?{...selectedTelemetry,online:false}:selectedTelemetry} vehicles={vehicles} profiles={profiles} onClose={()=>setSelected(null)} onObserved={observe} onProfile={reload} onCommands={()=>{setCommandDevice(selected);setSelected(null);}}/>}
{commandDevice&&<EquipmentCommandWindow key={commandDevice.id} device={commandDevice} telemetry={telemetry.items.find(t=>t.instance_id===commandDevice.id)} onClose={()=>{setCommandDevice(null);reload();}}/>}
<ToastStack items={error?[{id:'independent-equipment-error',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/>
</>;
}
@@ -0,0 +1,11 @@
import {Fragment,useEffect,useState} from 'react';
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]};
export function InstallerCard({kind}:{kind:'node'|'vps-arnavi'}){
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((step,index)=><Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>)}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
<Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button>
</SettingsCard>;
}
@@ -0,0 +1,29 @@
import {useEffect,useState} from 'react';
import {Button,FeatureSettingsWindow,Select,SettingsCard,StatusBadge,Switch,TextAreaField,TextField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
import {hostOnline,vpsRequest,type VPSHost} from '../../../core/fleet/vps';
import type {SensorEnrollmentProps} from '../../../../../../packages/sensor-ui/src/extensions';
import {InstallerCard} from './InstallerCard';
import type {Vehicle} from '../../../core/fleet/useFleet';
export function VPSHostSettings({host,hosts,vehicle,vehicles,onClose,onSaved,renderWindow}:{host?:VPSHost;hosts:VPSHost[];vehicle:Vehicle;vehicles:Vehicle[];onClose:()=>void;onSaved:()=>void;renderWindow?:SensorEnrollmentProps['renderWindow']}){
const [existing,setExisting]=useState(''),[name,setName]=useState(host?.name??'VPS Host ARNavi'),[code,setCode]=useState(''),[selected,setSelected]=useState(host?.vehicle_ids??[vehicle.id]);
const [advanced,setAdvanced]=useState(false),[replaces,setReplaces]=useState('');
const [network,setNetwork]=useState(host?.network_interface??''),[interfaces,setInterfaces]=useState<{id:string;label:string}[]>([]);
useEffect(()=>{let active=true;void vpsRequest<{items:{id:string;label:string}[]}>('/interfaces').then(v=>{if(active)setInterfaces(v.items);}).catch(()=>{});return()=>{active=false;};},[]);
const [busy,setBusy]=useState(false),[error,setError]=useState('');
const current=host??hosts.find(h=>h.id===existing);
async function save(){setBusy(true);setError('');try{if(current){await vpsRequest(`/${current.id}`,'PUT',{name:name.trim(),vehicle_ids:selected,network_interface:network||null,expected_revision:current.revision});}else{await vpsRequest('','POST',{code:code.trim(),name:name.trim(),vehicle_ids:selected,network_interface:network||null,replaces_id:replaces||null});}onSaved();}catch(e){setError(e instanceof Error?e.message:'Не удалось подключить VPS.');}finally{setBusy(false);}}
const actions=<><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!name.trim()||(!current&&!code.trim())} onClick={()=>void save()}>{current?'Применить':'Подключить VPS'}</Button></>;
const footer=<WindowFooterActions>{actions}</WindowFooterActions>;
const content=<div className="fleet-form">
{!host&&<Select label="VPS Host ARNavi" value={existing} options={[{value:'',label:'Подключить новый VPS'},...hosts.filter(h=>h.state==='paired').map(h=>({value:h.id,label:h.name}))]} disabled={busy} onChange={id=>{setExisting(id);const value=hosts.find(h=>h.id===id);setName(value?.name??'VPS Host ARNavi');setNetwork(value?.network_interface??'');setSelected(Array.from(new Set([...(value?.vehicle_ids??[]),vehicle.id])));}}/>}
{!current&&<InstallerCard kind="vps-arnavi"/>}
<TextField label="Название" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
{!current&&<TextAreaField label="Ключ подключения VPS" value={code} rows={5} disabled={busy} onChange={e=>setCode(e.target.value)} hint="После установки VPS Host ARNavi ключ находится в /opt/nodedc-mission-vps/connect.key. Он действует 24 часа и используется один раз."/>}
{!current&&hosts.some(h=>h.state==='paired')&&<Select label="После переустановки" value={replaces} options={[{value:'',label:'Это новый VPS'},...hosts.filter(h=>h.state==='paired').map(h=>({value:h.id,label:`Заменить ${h.name}`}))]} onChange={setReplaces} disabled={busy}/>}
{interfaces.length>0&&<><Button disabled={busy} onClick={()=>setAdvanced(v=>!v)}>{advanced?'Скрыть параметры подключения':'Параметры подключения при использовании VPN'}</Button>{advanced&&<SettingsCard title="Подключение с этого компьютера" description="Если VPN мешает доступу к VPS, выберите прямое подключение. Это влияет только на соединение Mission Core с этим сервером."><Select label="Способ подключения" value={network} options={[{value:'',label:'Обычное подключение (с учётом VPN)'},...interfaces.map(i=>({value:i.id,label:`Напрямую · ${i.label}`}))]} disabled={busy} onChange={setNetwork}/></SettingsCard>}</>}
{current&&<SettingsCard title="Связь с VPS" description={current.endpoint}><StatusBadge tone={hostOnline(current)?'success':'neutral'}>{hostOnline(current)?'На связи':current.state==='pending'?'Подключение не завершено':'Нет связи'}</StatusBadge><dl className="fleet-facts"><div><dt>Версия</dt><dd>{current.status?.version??'Нет сведений'}</dd></div><div><dt>Последняя синхронизация</dt><dd>{current.last_sync_at?new Date(current.last_sync_at*1000).toLocaleString('ru-RU'):'Ещё не было'}</dd></div><div><dt>Приём ARNavi B2</dt><dd>{current.status?`${current.status.tracker.host}:${current.status.tracker.port}`:'Не подтверждён'}</dd></div><div><dt>Трекеры</dt><dd>{current.status?.devices??0}</dd></div></dl></SettingsCard>}
<SettingsCard title="Обслуживаемые аппараты" description="Один VPS может обслуживать несколько аппаратов. Его настройки общие для всех привязок."><div className="fleet-form">{vehicles.map(v=><Switch key={v.id} label={v.name} checked={selected.includes(v.id)} disabled={busy} onChange={checked=>setSelected(ids=>checked?[...ids,v.id]:ids.filter(id=>id!==v.id))}/>)}</div></SettingsCard>
</div>;
return <>{renderWindow?renderWindow({content,actions,busy}):host?<FeatureSettingsWindow open title="Настройки VPS Host ARNavi" subtitle={host.name} identity={{title:'VPS Host ARNavi',subtitle:host.endpoint,avatarLabel:'VPS'}} sections={[{id:'host',label:'Сервер и аппараты'}]} activeSection="host" onSectionChange={()=>{}} onClose={()=>{if(!busy)onClose();}} footer={footer}>{content}</FeatureSettingsWindow>:<Window open title="Подключить VPS Host ARNavi" subtitle={vehicle.name} size="md" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}} footer={footer}>{content}</Window>}<ToastStack items={error?[{id:'vps-host-error',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
}
@@ -0,0 +1 @@
.equipment-settings-title { display:flex; align-items:center; flex-wrap:wrap; gap:var(--nodedc-space-4); }
@@ -1,5 +1,7 @@
.fleet-workspace, .fleet-form { display: flex; flex-direction: column; gap: var(--nodedc-space-4); }
.fleet-workspace { padding: var(--nodedc-space-4); }
.fleet-header-tools { display:flex; align-items:center; gap:var(--nodedc-space-2); }
.nodedc-application-panel__titles h1 > .fleet-header-title { font:inherit; color:inherit; letter-spacing:inherit; text-transform:none; }
.fleet-facts { display: grid; gap: var(--nodedc-space-3); }
.fleet-facts > div { display: grid; grid-template-columns: minmax(120px, 1fr) minmax(0, 2fr); gap: var(--nodedc-space-3); }
.fleet-facts dd { margin: 0; overflow-wrap: anywhere; }
@@ -10,4 +12,6 @@
.fleet-board-actions { display:flex; gap:var(--nodedc-space-3); }
.fleet-board-actions > * { flex:1; }
.fleet-computer-devices { padding-block-start:var(--nodedc-space-4); padding-inline-start:var(--nodedc-space-4); display:grid; gap:var(--nodedc-space-4); }
.fleet-form p { font-size:var(--nodedc-font-size-sm); line-height:1.5; color:var(--nodedc-text-secondary); }
@media(max-width:600px) { .fleet-board-actions { flex-wrap:wrap; } }
@@ -7,6 +7,10 @@ import {decodeObservationLayout,emptyObservationLayout,moveObservation,orderedOb
import {createIsolatedRerunHost} from '../../../components/rerun/isolatedRerunHost';
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 {ObservationDeviceSettings} from './ObservationDeviceSettings';
import {ObservationPanelHeader} from './ObservationPanelHeader';
import {ObservationDeck,ObservationMount} from './ObservationDeck';
import {ObservationMap} from './ObservationMap';
import {useObservationInventory} from './useObservationInventory';
@@ -19,62 +23,66 @@ export function BoardObservationCenter({vehicleID,name,enabled,back,configure,he
const {registry}=useDevicePluginHost(),transport=useMemo(()=>createFleetSensorTransport(vehicleID),[vehicleID]);
const inventory=useObservationInventory(transport),storageKey=`missioncore.observation.v1:${vehicleID}`;
const [layout,setLayout]=useState(()=>{try{return decodeObservationLayout(JSON.parse(localStorage.getItem(storageKey)??'null'));}catch{return emptyObservationLayout();}});
const [layersOpen,setLayersOpen]=useState(false),[focused,setFocused]=useState<string|null>(null);
const [settingsDevice,setSettingsDevice]=useState<string|null>(null);
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 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=registry.sensorContributions.find(item=>item.kind===device.kind)?.observation;
const contribution=sensorContribution(registry.sensorContributions,device)?.observation;
const views=contribution?.views(device)??cameraObservationViews(device);
return views.length?[{device,views,Session:contribution?.Session??CameraObservation}]:[];
});
const sources:{key:string;deviceID?:string;view:SensorObservationView}[]=groups.flatMap(group=>group.views.map(view=>({key:observationKey(group.device.id,view.id),deviceID:group.device.id,view})));
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})));
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:'Телеметрия'}});
for(const source of sources){if(!mounts.current.has(source.key)){mounts.current.set(source.key,document.createElement('div'));media.current.set(source.key,document.createElement('div'));headers.current.set(source.key,{statusTarget:document.createElement('div'),actionsTarget:document.createElement('div')});mounts.current.get(source.key)!.className='observation-panel-mount';media.current.get(source.key)!.className='observation-media-mount';}}
const ids=orderedObservationIDs(layout,sources.map(source=>source.key)),visible=ids.filter(id=>!layout.hidden.includes(id));
const ids=orderedObservationIDs(layout,sources.map(source=>source.key)),visible=ids.filter(id=>!layout.hidden.includes(id)&&(!sources.find(source=>source.key===id)?.catalog||layout.catalogVisible?.includes(id)));
const effectiveFull=full&&visible.includes(full)?full:null;
const rover=useRoverControl(vehicleID,enabled&&(visible.includes('rover')||visible.includes('telemetry')));
const drivingVisible=visible.includes('rover')&&(!effectiveFull||effectiveFull==='rover')&&!layersOpen;
const drivingVisible=visible.includes('rover')&&(!effectiveFull||effectiveFull==='rover')&&!layersOpen&&!settingsDevice;
useEffect(()=>{if(!drivingVisible)rover.stop();},[drivingVisible,rover.stop]);
const active=sources.find(source=>source.key===focused);
const configuredDevice=inventory?.items.find(device=>device.id===settingsDevice);
useEffect(()=>{try{localStorage.setItem(storageKey,JSON.stringify(layout));}catch{/* The workspace remains usable without browser storage. */}},[storageKey,layout]);
useEffect(()=>{const escape=(event:KeyboardEvent)=>{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]);
const setVisible=(id:string,show:boolean)=>setLayout(value=>({...value,hidden:show?value.hidden.filter(key=>key!==id):[...new Set([...value.hidden,id])]}));
const setVisible=(id:string,show:boolean)=>setLayout(value=>({...value,catalogVisible:show?[...new Set([...(value.catalogVisible??[]),...(sources.find(source=>source.key===id)?.catalog?[id]:[])])]:(value.catalogVisible??[]).filter(key=>key!==id),hidden:show?value.hidden.filter(key=>key!==id):[...new Set([...value.hidden,id])]}));
const layerFor=(key:string,view:SensorObservationView)=>view.layers?.find(layer=>layer.value===layout.layers[key])?.value??view.layers?.[0]?.value??view.id;
return <>{headerToolsHost&&createPortal(<IconButton label="К аппаратам" onClick={back}><Icon name="chevron-left"/></IconButton>,headerToolsHost)}<div ref={frame}/>{createPortal(<section className={`observation-center${expanded?' observation-center--expanded':''}`} aria-label={`Центр наблюдения и управления · ${name}`}>
<header className="observation-toolbar"><div><h2>Центр наблюдения и управления</h2><span>{name}</span></div><div className="observation-actions">{(!headerToolsHost||expanded)&&<IconButton label="К аппаратам" onClick={back}><Icon name="chevron-left"/></IconButton>}<Button onClick={configure}><Icon name="sliders"/>Конфигуратор</Button><Button onClick={()=>{setFocused(null);setLayersOpen(true);}}><Icon name="grid"/>Доступные слои</Button><IconButton label={expanded?'Восстановить размер центра':'Развернуть центр наблюдения и управления'} onClick={()=>setExpanded(value=>!value)}><Icon name={expanded?'minimize':'expand'}/></IconButton></div></header>
const navigationActions=<><IconButton label="Конфигуратор" onClick={configure}><Icon name="sliders"/></IconButton><IconButton label="К аппаратам" onClick={back}><Icon name="chevron-left"/></IconButton></>;
return <>{headerToolsHost&&!expanded&&createPortal(navigationActions,headerToolsHost)}<div ref={frame}/>{createPortal(<section className={`observation-center${expanded?' observation-center--expanded':''}`} aria-label={`Центр наблюдения и управления · ${name}`}>
<header className="observation-toolbar"><div><h2>Центр наблюдения и управления</h2><span>{name}</span></div><div className="observation-actions">{(!headerToolsHost||expanded)&&navigationActions}<Button onClick={()=>{setLayersOpen(true);}}><Icon name="grid"/>Доступные слои</Button><IconButton label={expanded?'Восстановить размер центра':'Развернуть центр наблюдения и управления'} onClick={()=>setExpanded(value=>!value)}><Icon name={expanded?'minimize':'expand'}/></IconButton></div></header>
<div className="observation-summary"><StatusBadge tone={enabled&&inventory&&inventory.fresh!==false?'success':'neutral'}>{!inventory?'Получение источников':!enabled||inventory.fresh===false?'Нет свежих данных с БК':`Устройства: ${groups.length} · Окна: ${visible.length}`}</StatusBadge>{effectiveFull&&<Button onClick={()=>setFull(null)}>Все окна</Button>}</div>
<DragDropRoot onDragEnd={({activeId,overId})=>{if(overId)setLayout(value=>moveObservation(value,ids,activeId,overId));}}>
<div className="observation-deck">{!inventory?<LoadingRegion loading label="Получение визуальных источников"/>:visible.length?<ObservationDeck ids={effectiveFull?[effectiveFull]:visible} mounts={mounts.current} layout={layout} onSplit={(key,value)=>setLayout(current=>({...current,splits:{...current.splits,[key]:value}}))}/>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>{setFocused(null);setLayersOpen(true);}}>Доступные слои</Button></div>}</div>
<div className="observation-deck">{!inventory?<LoadingRegion loading label="Получение визуальных источников"/>:visible.length?<ObservationDeck ids={effectiveFull?[effectiveFull]:visible} mounts={mounts.current} layout={layout} onSplit={(key,value)=>setLayout(current=>({...current,splits:{...current.splits,[key]:value}}))}/>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>{setLayersOpen(true);}}>Доступные слои</Button></div>}</div>
{sources.filter(source=>visible.includes(source.key)).map(source=>createPortal(
<DropZone id={source.key} className="observation-panel">
<DraggableItem id={source.key} className="observation-panel-drag">{({handle})=>
<GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className="observation-panel__surface">
<header className="observation-panel__header">
<GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className="observation-panel__surface observation-panel__surface--overlay">
<ObservationPanelHeader>
{handle}
<div className="observation-panel__title"><h3 title={source.view.label}>{source.view.label}</h3><ObservationMount className="observation-header-slot" element={headers.current.get(source.key)!.statusTarget}/></div>
<div className="observation-actions">
{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&&<IconButton label={`Настройки · ${source.view.label}`} onClick={()=>{setFocused(source.key);setLayersOpen(true);}}><Icon name="settings"/></IconButton>}
{source.deviceID&&<IconButton label={`Настройки · ${source.view.label}`} onClick={()=>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>
</header>
</ObservationPanelHeader>
<ObservationMount element={media.current.get(source.key)!}/>
</GlassSurface>
}</DraggableItem>
</DropZone>,mounts.current.get(source.key)!,source.key))}
</DragDropRoot>
{groups.map(({device,views,Session})=>visible.some(key=>views.some(view=>key===observationKey(device.id,view.id)))&&<Session key={device.id} device={device} transport={transport} enabled={enabled&&inventory?.fresh!==false&&device.online} 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}/>}
{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}/>,media.current.get('rover')!,'rover-session')}
{visible.includes('telemetry')&&createPortal(<RoverTelemetry state={rover.state}/>,media.current.get('telemetry')!,'telemetry-session')}
<Window open={layersOpen} onClose={()=>setLayersOpen(false)} title={active?active.view.label:'Доступные слои'} size="md"><div className="observation-settings">
{!active&&<Select label="Расположение окон" value={layout.arrangement} options={[{value:'auto',label:'Автоматически'},{value:'columns',label:'В ряд'},{value:'rows',label:'Друг под другом'}]} onChange={value=>setLayout(current=>({...current,arrangement:value as typeof layout.arrangement}))}/>}
{ids.filter(id=>!active||id===active.key).map(id=>{const source=sources.find(item=>item.key===id)!;return <div className="observation-layer" key={id}><Switch label={source.view.label} checked={visible.includes(id)} onChange={value=>setVisible(id,value)}/><Select label={`Позиция · ${source.view.label}`} value={String(ids.indexOf(id))} options={ids.map((_,i)=>({value:String(i),label:`Окно ${i+1}`}))} onChange={value=>setLayout(current=>moveObservation(current,ids,id,ids[Number(value)]))}/></div>;})}
{active?.view.layers&&<Select label="Слой источника" value={layerFor(active.key,active.view)} options={active.view.layers} onChange={value=>setLayout(current=>({...current,layers:{...current.layers,[active.key]:value}}))}/>}
<Window open={layersOpen} onClose={()=>setLayersOpen(false)} title="Доступные слои" size="md"><div className="observation-settings">
<Select label="Расположение окон" value={layout.arrangement} options={[{value:'auto',label:'Автоматически'},{value:'columns',label:'В ряд'},{value:'rows',label:'Друг под другом'}]} onChange={value=>setLayout(current=>({...current,arrangement:value as typeof layout.arrangement}))}/>
{ids.map(id=>{const source=sources.find(item=>item.key===id)!;return <div className="observation-layer" key={id}><Switch label={source.catalog?`${source.view.label} · Источник не подключён`:source.view.label} checked={visible.includes(id)} onChange={value=>setVisible(id,value)}/><Select label={`Позиция · ${source.view.label}`} value={String(ids.indexOf(id))} options={ids.map((_,i)=>({value:String(i),label:`Окно ${i+1}`}))} onChange={value=>setLayout(current=>moveObservation(current,ids,id,ids[Number(value)]))}/></div>;})}
<Button onClick={()=>{setLayout(emptyObservationLayout());setFull(null);}}>Восстановить расположение</Button>
</div></Window>
</section>,portal)}</>;
@@ -14,5 +14,5 @@ export function ObservationDeck({ids,mounts,layout,onSplit,depth=0}:{ids:string[
const defaultColumns=depth===0&&layout.arrangement==='auto'&&!layout.order.some(id=>id==='rover'||id==='telemetry')&&ids.some(id=>!['map','rover','telemetry'].includes(id));
const cameraCount=ids.filter(id=>!['map','rover','telemetry'].includes(id)).length;
const mid=defaultColumns&&cameraCount<ids.length?cameraCount:layout.arrangement==='auto'&&ids[0]==='map'&&ids.includes('rover')?1:Math.ceil(ids.length/2),key=JSON.stringify(ids),orientation=layout.arrangement==='rows'?'horizontal':layout.arrangement==='columns'?'vertical':depth%2?'horizontal':'vertical';
return <SplitPane className="observation-split" orientation={orientation} primarySize={layout.splits[key]??50} onPrimarySizeChange={value=>onSplit(key,value)} separatorLabel="Изменить размеры окон" primary={<ObservationDeck ids={ids.slice(0,mid)} mounts={mounts} layout={layout} onSplit={onSplit} depth={depth+1}/>} secondary={<ObservationDeck ids={ids.slice(mid)} mounts={mounts} layout={layout} onSplit={onSplit} depth={depth+1}/>}/>;
return <SplitPane separatorAppearance="invisible" className="observation-split" orientation={orientation} primarySize={layout.splits[key]??50} onPrimarySizeChange={value=>onSplit(key,value)} separatorLabel="Изменить размеры окон" primary={<ObservationDeck ids={ids.slice(0,mid)} mounts={mounts} layout={layout} onSplit={onSplit} depth={depth+1}/>} secondary={<ObservationDeck ids={ids.slice(mid)} mounts={mounts} layout={layout} onSplit={onSplit} depth={depth+1}/>}/>;
}
@@ -0,0 +1,17 @@
import {useState} from 'react';
import {Button,Window} from '@nodedc/ui-react';
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}) {
const [error,setError]=useState('');
const Detail=sensorContribution(contributions,device)?.Detail??SensorDetail;
return <Window open title={`Настройки · ${device.name}`} size="lg" placement="end" draggable closeOnBackdrop={false} lockBodyScroll={false} trapFocus={false} onClose={close}>
{!enabled&&<p>Нет связи с устройством. Настройки оборудования будут доступны после подключения.</p>}
{!device.prepared&&<Button onClick={configure}>Подготовить устройство в конфигураторе</Button>}
{error&&<p role="alert">{error}</p>}
<Detail 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}/>
</Window>;
}
@@ -1,23 +1,34 @@
import {useMemo,useRef,useState} from 'react';
import {CesiumMapRenderer,initialMapRuntimeState,type CesiumMapRendererHandle,type MapCamera} from '@nodedc/map-cesium-react';
import {useEffect,useMemo,useRef,useState} from 'react';
import {CesiumMapRenderer,initialMapRuntimeState,type CesiumMapRendererHandle,type MapCamera,type MapGhostPinLayer} from '@nodedc/map-cesium-react';
import {Button,Icon,IconButton,Switch,Window} from '@nodedc/ui-react';
import {ObservationHeader} from '../../../../../../packages/sensor-ui/src/ObservationHeader';
import type {ObservationHeaderTargets} from '../../../../../../packages/sensor-ui/src/observation';
import {defaultMapViewDocument} from '../../../core/map/mapView';
import {useTrackerTelemetry} from '../../../core/fleet/vps';
import {defaultMapViewDocument,encodeMapViewPut} from '../../../core/map/mapView';
import {useMapRecovery} from '../../../core/map/useMapRecovery';
import {mapPresentation} from '../../../components/map/mapPresentation';
export function ObservationMap({vehicleID,header}:{vehicleID:string;header:ObservationHeaderTargets}){
const defaults=useMemo(()=>defaultMapViewDocument().view,[]),renderer=useRef<CesiumMapRendererHandle>(null);
const [settings,setSettings]=useState(false),[state,setState]=useState(initialMapRuntimeState),[generation,setGeneration]=useState(0);
const storageKey=`missioncore.observation-map.v1:${vehicleID}`;
const [camera]=useState(()=>{try{const value=JSON.parse(localStorage.getItem(storageKey)??'null') as MapCamera|null;return value&&['longitude','latitude','height','heading','pitch','roll'].every(key=>Number.isFinite(value[key as keyof MapCamera]))?value:defaults.camera;}catch{return defaults.camera;}});
const [layers,setLayers]=useState({...defaults.layerVisibility,grid:false,targets:false});
const ready=state.phase==='ready';
const available=Object.values(state.providers).some(provider=>provider.phase==='ready');
const [camera,setCamera]=useState(()=>{try{const value=JSON.parse(localStorage.getItem(storageKey)??'null') as MapCamera|null;return value&&['longitude','latitude','height','heading','pitch','roll'].every(key=>Number.isFinite(value[key as keyof MapCamera]))?value:defaults.camera;}catch{return defaults.camera;}});
const [layers,setLayers]=useState({...defaults.layerVisibility,grid:false,targets:true});
const telemetry=useTrackerTelemetry(vehicleID),centered=useRef(false);
const pins=telemetry.items.flatMap(item=>item.position?[{id:item.instance_id,label:`${item.name} · ${item.position_fresh&&!telemetry.unavailable?item.position.source.toUpperCase():new Date(item.position.measured_at*1000).toLocaleTimeString('ru-RU')}`,longitude:item.position.longitude,latitude:item.position.latitude,heading_degrees:item.position.course,speed_meters_per_second:0}]:[]);
const presentation=useMemo(()=>(encodeMapViewPut(defaultMapViewDocument()) as {view:{ghost_pins:MapGhostPinLayer}}).view.ghost_pins.presentation,[]);
const markers:MapGhostPinLayer={anchor:null,radius_meters:0,simulation_enabled:false,pins,presentation:{...presentation,stem_height_meters:20,head_size_px:12,label_mode:'attributes',label_max_length:80}};
function center(){const pin=pins[0];if(pin){setCamera({longitude:pin.longitude,latitude:pin.latitude,height:1200,heading:0,pitch:-90,roll:0});setGeneration(v=>v+1);}}
useEffect(()=>{if(pins.length&&!centered.current){centered.current=true;center();}},[pins.length]);
const latest=telemetry.items.find(item=>item.position);
const positionLabel=telemetry.unavailable?'Обновление координат недоступно':latest?.position?`${latest.position.latitude.toFixed(6)}, ${latest.position.longitude.toFixed(6)} · ${latest.position.source.toUpperCase()} · ${latest.position.satellites??'—'} спутников · ${new Date(latest.position.measured_at*1000).toLocaleTimeString('ru-RU')}`:'Ожидание координат трекера';
const available=state.phase==='ready'||Object.values(state.providers).some(provider=>provider.phase==='ready');
const unavailable=!available&&state.phase!=='loading';
useMapRecovery(unavailable,()=>setGeneration(v=>v+1));
return <div className="observation-source">
<ObservationHeader targets={header} live={ready} label={ready?'Карта доступна':state.phase==='loading'?'Загрузка карты':state.phase==='degraded'?'Часть слоёв недоступна':'Карта недоступна'}><IconButton label="Слои карты" onClick={()=>setSettings(true)}><Icon name="layers"/></IconButton></ObservationHeader>
<div className="observation-source__media observation-map" data-available={available}><CesiumMapRenderer key={generation} ref={renderer} runtimeConfigUrl="/api/v1/map/runtime-config" camera={camera} layers={layers} settings={mapPresentation(defaults.visualSettings)} cacheIntent={{enabled:true,no_overwrite:true}} onRuntimeStateChange={setState} onCameraChange={value=>{try{localStorage.setItem(storageKey,JSON.stringify(value));}catch{/* Browser storage may be unavailable. */}}}/></div>
{!available&&state.phase!=='loading'&&<div className="observation-source__notice"><p>Не удалось загрузить картографические слои.</p><Button onClick={()=>setGeneration(v=>v+1)}>Повторить загрузку карты</Button></div>}
<ObservationHeader targets={header} live={!telemetry.unavailable&&telemetry.items.some(item=>item.online&&item.position_fresh)} label={positionLabel}><IconButton label="Показать аппарат на карте" disabled={!pins.length} onClick={center}><Icon name="globe"/></IconButton><IconButton label="Слои карты" onClick={()=>setSettings(true)}><Icon name="layers"/></IconButton></ObservationHeader>
<div className="observation-source__media observation-map" data-available={available}><CesiumMapRenderer key={generation} ref={renderer} runtimeConfigUrl="/api/v1/map/runtime-config" camera={camera} ghostPins={markers} layers={layers} settings={mapPresentation(defaults.visualSettings)} cacheIntent={{enabled:true,no_overwrite:true}} onRuntimeStateChange={setState} onCameraChange={value=>{try{localStorage.setItem(storageKey,JSON.stringify(value));}catch{/* Browser storage may be unavailable. */}}}/></div>
{unavailable&&<div className="observation-source__notice"><p>Картографические слои недоступны. Проверяем связь с сервером карты.</p><p>{positionLabel}</p><Button onClick={()=>setGeneration(v=>v+1)}>Повторить загрузку карты</Button></div>}
<Window open={settings} onClose={()=>setSettings(false)} title="Слои карты" size="sm">
<div className="observation-settings">{([{id:'imagery',name:'Спутниковые снимки'},{id:'terrain',name:'Рельеф'},{id:'buildings',name:'Здания OSM'}] as const).map(item=><Switch key={item.id} label={item.name} checked={layers[item.id]} onChange={value=>setLayers(current=>({...current,[item.id]:value}))}/>)}
</div>
@@ -0,0 +1,13 @@
import {useLayoutEffect,useRef,type ReactNode} from 'react';
/** Reserve the actual overlay height for text/status content, including wrapped controls. */
export function ObservationPanelHeader({children}:{children:ReactNode}) {
const ref=useRef<HTMLElement>(null);
useLayoutEffect(()=>{
const header=ref.current!;
const measure=()=>header.parentElement?.style.setProperty('--observation-overlay-header-space',`${header.getBoundingClientRect().height}px`);
measure();const observer=new ResizeObserver(measure);observer.observe(header);
return()=>observer.disconnect();
},[]);
return <header ref={ref} className="observation-panel__header">{children}</header>;
}
@@ -9,6 +9,9 @@
.observation-mount, .observation-panel-mount, .observation-media-mount, .observation-panel, .observation-split { height:100%; min-height:0; min-width:0; }
.observation-panel__surface { display:flex; flex-direction:column; height:100%; overflow:hidden; container-type:inline-size; }
.observation-panel__surface > .observation-mount { flex:1; }
.observation-panel__surface--overlay { position:relative; --observation-overlay-header-space:62px; }
.observation-panel__surface--overlay > .observation-panel__header { position:absolute; inset:0 0 auto; z-index:1; background:transparent; pointer-events:none; }
.observation-panel__surface--overlay > .observation-panel__header > * { pointer-events:auto; }
.observation-panel__header { display:flex; align-items:center; gap:var(--nodedc-space-2); padding:var(--nodedc-space-2); flex-shrink:0; }
.observation-panel__header h3 { min-width:0; font-size:var(--nodedc-font-size-sm); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.observation-source { position:relative; display:flex; flex-direction:column; height:100%; min-height:0; }
@@ -21,7 +24,7 @@
.observation-source__media { position:relative; flex:1; min-height:0; overflow:hidden; display:flex; align-items:center; justify-content:center; }
.observation-source__media video, .observation-source__media canvas { width:100%; height:100%; object-fit:contain; }
.observation-source__media[data-live="false"] > *, .observation-source__media [data-live="false"] { visibility:hidden; }
.observation-source__notice { position:absolute; inset:30% var(--nodedc-space-4) auto; text-align:center; color:var(--nodedc-text-secondary); font-size:calc(var(--nodedc-font-size-lg) * .7); }
.observation-source__notice { position:absolute; inset:max(30%, calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3))) var(--nodedc-space-4) auto; text-align:center; color:var(--nodedc-text-secondary); font-size:calc(var(--nodedc-font-size-lg) * .7); }
.observation-rerun, .observation-rerun > div, .observation-map > div { width:100%; height:100%; }
.observation-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-4); }
.observation-layer { display:grid; grid-template-columns:minmax(0, 1fr) 50%; align-items:center; gap:var(--nodedc-space-3); }
@@ -43,3 +46,5 @@
.observation-panel__title { min-width:80px; }
.observation-panel__header > .observation-actions { max-width:100%; flex-wrap:wrap; justify-content:flex-end; margin-left:auto; }
}
.observation-panel__surface--overlay .rover-telemetry { padding-top:calc(var(--observation-overlay-header-space) + var(--nodedc-space-3)); }
@@ -1,3 +1,4 @@
import {workerConnectionStatus} from '../../core/system/workerConnectionStatus';
import {
GlassSurface,
StatusBadge,
@@ -77,9 +78,7 @@ export function ComputeModulesWorkspace() {
const node = telemetry?.node ?? null;
const missionCoreRuntimes = telemetry?.runtimes.filter((runtime) => !runtime.external) ?? [];
const externalRuntimes = telemetry?.runtimes.filter((runtime) => runtime.external) ?? [];
const connected = Boolean(
telemetry?.connection.reachable && telemetry.connection.identity_matches && node,
);
const connectionStatus = workerConnectionStatus(telemetry);
const agentTelemetry = telemetry?.connection.source === "agent-mqtt";
const history = telemetry?.history ?? [];
const cpuPercent = node?.cpu.load_percent;
@@ -105,14 +104,13 @@ export function ComputeModulesWorkspace() {
</p>
</div>
<div className="system-workspace__actions">
<StatusBadge tone={connected ? "success" : "danger"}>
{connected
? agentTelemetry ? "Агент доступен" : "SSH-диагностика"
: "Нет свежих данных"}
<StatusBadge tone={connectionStatus.tone}>
{connectionStatus.label}
</StatusBadge>
</div>
</section>
{connectionStatus.detail && <p role="status">{connectionStatus.detail}</p>}
{error ? (
<GlassSurface className="system-workspace__notice" padding="md" tone="soft">
<StatusBadge tone="warning">{error}</StatusBadge>
@@ -1,3 +1,4 @@
import {workerConnectionStatus} from '../../core/system/workerConnectionStatus';
import {
GlassSurface,
StatusBadge,
@@ -31,6 +32,7 @@ export function NetworkWorkspace() {
const connected = Boolean(
telemetry?.connection.reachable && telemetry.connection.identity_matches,
);
const connectionStatus = workerConnectionStatus(telemetry);
const agentTelemetry = telemetry?.connection.source === "agent-mqtt";
const runtimeOnline = telemetry?.runtimes.some(
(runtime) => !runtime.external && runtime.state === "running",
@@ -43,17 +45,18 @@ export function NetworkWorkspace() {
<span className="section-eyebrow">СИСТЕМА / СЕТЬ</span>
<h2>{selectedContour?.display_name ?? "Контур не выбран"}</h2>
<p>
Фактический локальный маршрут и сетевые счётчики выбранного вычислительного
Фактический маршрут и сетевые счётчики выбранного вычислительного
контура. Адрес, транспорт и установка агента находятся в настройках контура.
</p>
</div>
<div className="system-workspace__actions">
<StatusBadge tone={connected ? "success" : "danger"}>
{connected ? "Маршрут доступен" : "Нет свежих данных"}
<StatusBadge tone={connectionStatus.tone}>
{connectionStatus.label}
</StatusBadge>
</div>
</section>
{connectionStatus.detail && <p role="status">{connectionStatus.detail}</p>}
{error ? (
<GlassSurface className="system-workspace__notice" padding="md" tone="soft">
<StatusBadge tone="warning">{error}</StatusBadge>
@@ -109,7 +112,7 @@ export function NetworkWorkspace() {
<small>127.0.0.1:8000</small>
</div>
<i aria-hidden="true" data-state="online" />
<div data-state={agentTelemetry ? "online" : "offline"}>
<div data-state={connected ? "online" : "unknown"}>
<span>Telemetry plane</span>
<strong>{agentTelemetry ? "Mosquitto + Timescale" : "SSH diagnostic"}</strong>
<small>
@@ -1,11 +1,12 @@
import assert from 'node:assert/strict';
import {after,before,test} from 'node:test';
import {createServer} from 'vite';
let server,layout,source,fanout;
let server,layout,source,fanout,catalog;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
layout=await server.ssrLoadModule('/src/core/fleet/observationLayout.ts');
source=await server.ssrLoadModule('../../packages/sensor-ui/src/observation.ts');
catalog=await server.ssrLoadModule('../../packages/sensor-ui/src/observationCatalog.ts');
({observationRerun:fanout}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/observationRerun.ts'));
});
after(async()=>{await server?.close();});
@@ -41,3 +42,21 @@ test('two Rerun views share bytes, apply independent blueprints once and dispose
assert.equal(sent[0].length,2);assert.deepEqual(started,[0,1]);host.dispose();assert.deepEqual(closed,[0,1]);
}finally{globalThis.fetch=fetchBefore;}
});
test('known offline D455 remains selectable; connected capabilities override the catalog',()=>{
const offline={name:'RealSense D455',model:'RealSense D455',online:false,layers:[]};
assert.deepEqual(source.cameraObservationViews(offline)[0].layers.map(v=>v.value),['color','depth','infrared1','infrared2','points','motion']);
assert.deepEqual(source.cameraObservationViews({...offline,online:true,layers:['depth']})[0].layers.map(v=>v.value),['depth']);
assert.deepEqual(source.cameraObservationViews({...offline,model:'unknown'}),[]);
});
test('unbound catalog views have no device authority; connected instances replace templates without aliasing',()=>{
const plugin={kind:'k1',observation:{catalog:{label:'K1',views:[{id:'points',label:'Points'},{id:'camera',label:'Camera'}]}}};
const entries=catalog.unboundObservationViews([],[plugin]);
assert.equal(entries.length,2);assert.notEqual(entries[0].key,entries[1].key);
assert.equal(entries[0].deviceID,undefined);assert.equal(entries[0].device,undefined);
assert.deepEqual(catalog.unboundObservationViews([{id:'one',kind:'k1'}],[plugin]),[]);
assert.deepEqual(catalog.unboundObservationViews([],[plugin,plugin]),[]);
const persisted=layout.decodeObservationLayout({...layout.emptyObservationLayout(),catalogVisible:[entries[0].key,entries[0].key,null]});
assert.deepEqual(persisted.catalogVisible,[entries[0].key]);
});
@@ -0,0 +1,91 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
const code=ts.transpileModule(readFileSync(new URL('../src/core/fleet/cellular.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText;
const {cellularSlotDescription,cellularFresh,cellularNetworkLabel,cellularSimLabel,cellularModemLabel,cellularSlotView,cellularSimOptions,cellularSimCurrent}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
test('SIM freshness rejects old, future and missing observations independently',()=>{
assert.equal(cellularFresh(undefined,100),false);
assert.equal(cellularFresh({measured_at:11},100),true);
assert.equal(cellularFresh({measured_at:10},100),false);
assert.equal(cellularFresh({measured_at:101},100),false);
});
test('missing country code cannot identify a carrier from MNC alone',()=>{
assert.equal(cellularNetworkLabel({mcc:null,mnc:2}),'Оператор не определён');
assert.equal(cellularNetworkLabel({mcc:250,mnc:2}),'МегаФон · 250-02');
assert.equal(cellularNetworkLabel({mcc:250,mnc:1}),'МТС · 250-01');
assert.equal(cellularNetworkLabel({mcc:310,mnc:260}),'Оператор не определён · код 310-260');
assert.equal(cellularNetworkLabel(undefined),'Оператор не определён');
});
test('unknown registration and modem states never imply data service',()=>{
assert.equal(cellularSimLabel(undefined),'Нет сведений');
assert.equal(cellularSimLabel(0),'SIM не обнаружена');
assert.equal(cellularSimLabel(6),'Ошибка PIN');
assert.equal(cellularSimLabel(7),'Нет сведений');
assert.equal(cellularModemLabel(4),'GPRS подключён');
assert.equal(cellularModemLabel(7),'Нет сведений о модеме');
});
test('registered second SIM is not presented as another internet connection',()=>{
const t={online:true,cellular:{status:{active_sim:1,gsm_state:4,sim_states:{'1':1,'2':1},measured_at:99},networks:{'1':{mcc:250,mnc:2,measured_at:99},'2':{mcc:250,mnc:0,measured_at:99}}}};
assert.equal(cellularSlotView(t,'1',100).role,'Используется для интернета');
assert.equal(cellularSlotView(t,'2',100).role,'Не выбрана для интернета');
assert.equal(cellularNetworkLabel(cellularSlotView(t,'2',100).network),'Оператор не определён · код 250-00');
t.cellular.status.active_sim=2;
assert.equal(cellularSlotView(t,'2',100).internet,true);
assert.equal(cellularSlotView(t,'1',100).internet,false);
t.online=false;
assert.equal(cellularSlotView(t,'2',100).role,'Последнее полученное состояние');
assert.equal(cellularSlotView(t,'2',100).internet,false);
});
test('removed SIM does not retain a current operator or internet badge',()=>{
const t={online:true,cellular:{status:{active_sim:2,gsm_state:4,sim_states:{'1':1,'2':0},measured_at:99},networks:{'2':{mcc:250,mnc:1,measured_at:98}}}};
assert.equal(cellularSlotView(t,'2',100).role,'SIM не обнаружена');
assert.equal(cellularSlotView(t,'2',100).network,undefined);
assert.equal(cellularSlotView(t,'2',100).internet,false);
assert.equal(cellularSlotView(t,'1',200).role,'Последнее полученное состояние');
assert.equal(cellularSlotView(undefined,'1',100).internet,false);
assert.equal(cellularNetworkLabel({mcc:250,mnc:99}),'Билайн · 250-99');
});
test('target selector lists installed SIMs and resolves labels anew after swaps',()=>{
const t={online:true,cellular:{status:{active_sim:1,gsm_state:4,sim_states:{'1':1,'2':0},measured_at:99},networks:{'1':{mcc:250,mnc:2,measured_at:99},'2':{mcc:250,mnc:1,measured_at:99}}}};
assert.deepEqual(cellularSimOptions(t,100),[{value:'1',label:'SIM 1 (МегаФон)'}]);
t.cellular.status.sim_states['2']=1;
assert.deepEqual(cellularSimOptions(t,100),[{value:'1',label:'SIM 1 (МегаФон)'},{value:'2',label:'SIM 2 (МТС)'}]);
[t.cellular.networks['1'],t.cellular.networks['2']]=[t.cellular.networks['2'],t.cellular.networks['1']];
assert.deepEqual(cellularSimOptions(t,100),[{value:'1',label:'SIM 1 (МТС)'},{value:'2',label:'SIM 2 (МегаФон)'}]);
t.cellular.networks['2'].mnc=99;
assert.equal(cellularSimOptions(t,100)[1].label,'SIM 2 (Билайн)');
t.cellular.status.sim_states['1']=0;
assert.deepEqual(cellularSimOptions(t,100),[{value:'2',label:'SIM 2 (Билайн)'}]);
assert.deepEqual(cellularSimOptions(t,200),[{value:'2',label:'SIM 2 (Билайн) · последние данные'}]);
assert.equal(cellularSimCurrent(t,2,200),false);
assert.equal(cellularSimCurrent(t,2,100),true);
t.online=false;assert.deepEqual(cellularSimOptions(t,100),[{value:'2',label:'SIM 2 (Билайн) · последние данные'}]);
assert.equal(cellularSimCurrent(t,2,100),false);
assert.deepEqual(cellularSimOptions(undefined,100),[]);
});
test('target selector never carries an old operator into stale, searching or unknown evidence',()=>{
const t={online:true,cellular:{status:{sim_states:{'1':2,'2':1},measured_at:99},networks:{'1':{mcc:250,mnc:2,measured_at:99},'2':{mcc:250,mnc:0,measured_at:99}}}};
assert.deepEqual(cellularSimOptions(t,100).map(o=>o.label),['SIM 1 (оператор не определён)','SIM 2 (оператор не определён)']);
t.cellular.status.sim_states['1']=1;t.cellular.networks['1'].measured_at=1;
assert.equal(cellularSimOptions(t,100)[0].label,'SIM 1 (оператор не определён)');
});
test('qualified card home operator follows current binding even when serving MNC is unavailable',()=>{
const t={online:true,cellular:{status:{measured_at:100,sim_states:{'1':1,'2':1}},networks:{}},sim_identity:{slots:{'1':{binding_current:true,known_card:{home_network:'25002'}},'2':{binding_current:true,known_card:{home_network:'25001'}}}}};
assert.deepEqual(cellularSimOptions(t,101).map(x=>x.label),['SIM 1 (МегаФон)','SIM 2 (МТС)']);
t.sim_identity.slots['2'].binding_current=false;
assert.equal(cellularSimOptions(t,101)[1].label,'SIM 2 (оператор не определён)');
});
test('connected SIM with missing MCC is distinguished from an absent SIM',()=>{
const telemetry={online:true,cellular:{status:{measured_at:100,active_sim:1,gsm_state:4,sim_states:{1:1,2:1}},networks:{1:{measured_at:100,mcc:null,mnc:1,signal:18}}}};
assert.equal(cellularSlotDescription(telemetry,'1',100),'Интернет подключён. B2 ещё не передал код сети оператора.');
telemetry.cellular.networks[1].mcc=250;
assert.equal(cellularSlotDescription(telemetry,'1',100),'МТС · 250-01');
telemetry.cellular.status.sim_states[1]=0;
assert.match(cellularSlotDescription(telemetry,'1',100),/B2 не обнаружил карту/);
});
@@ -0,0 +1,72 @@
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import test from 'node:test';
import ts from 'typescript';
const code=ts.transpileModule(readFileSync(new URL('../src/core/fleet/commandRuntime.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText;
const {mergeCommands,commandPending,commandTracked,commandStatus,commandTone,commandDate,commandDuration,commandReceipt,commandEntryStatus}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
test('runtime retains loaded history and merges a changing operation by immutable id',()=>{
const a={id:'a',sequence:10,state:'waiting'},b={id:'b',sequence:9,state:'device_confirmed'};
const entries=mergeCommands([a,b],[{...a,state:'dispatched'},{id:'c',sequence:11,state:'queued'}]);
assert.deepEqual(entries.map(x=>[x.id,x.state]),[['c','queued'],['a','dispatched'],['b','device_confirmed']]);
assert.equal(a.state,'waiting');
});
test('a delayed polling response cannot roll a completed command back to pending',()=>{
const current={id:'a',sequence:10,state:'device_confirmed',updated_at:20};
assert.equal(mergeCommands([current],[{...current,state:'dispatched',updated_at:10}])[0].state,'device_confirmed');
});
test('runtime makes expiry, no confirmation and receipt distinct; none claim actuator execution',()=>{
for(const state of ['waiting','submitting','queued','dispatched'])assert.equal(commandPending(state),true);
for(const state of ['expired','cancelled','unconfirmed','uncertain','device_confirmed'])assert.equal(commandPending(state),false);
assert.equal(commandTone('device_confirmed'),'success');
assert.equal(commandTone('unconfirmed'),'warning');
assert.notEqual(commandStatus('expired'),commandStatus('unconfirmed'));
assert.doesNotMatch(commandStatus('device_confirmed'),/исполнено|выполнено/i);
assert.equal(commandDuration(undefined),'—');assert.equal(commandDuration(0.01234),'0.012 с');assert.equal(commandDate(undefined),'—');
});
test('unresolved results remain tracked after timeout without blocking the command queue',()=>{
const unknown={id:'a',sequence:1,state:'uncertain',reconcile_pending:true,updated_at:10};
assert.equal(commandPending(unknown.state),false);
assert.equal(commandTracked(unknown),true);
const final={...unknown,state:'device_confirmed',reconcile_pending:false,updated_at:20};
assert.equal(commandTracked(final),false);
assert.deepEqual(mergeCommands([unknown],[final]),[final]);
});
test('tracker ACK is visible without pretending that execution finished',()=>{
const ack={state:'dispatched',device_code:6,device_accepted_at:10};
assert.equal(commandPending(ack.state),true);
assert.equal(commandEntryStatus(ack),'Принято B2, выполняется');
assert.equal(commandReceipt(ack),'B2 принял команду; требуется время на выполнение');
assert.equal(commandReceipt({device_code:0,kind:'restart'}),'B2 принял команду перезапуска');
assert.equal(commandEntryStatus({...ack,state:'device_confirmed'}),'Подтверждено B2');
assert.equal(commandReceipt({device_code:5}),'B2 сообщил об ошибке выполнения');
assert.equal(commandReceipt({device_code:7}),'Очередь команд B2 заполнена');
});
test('durable jobs show recovery independently of a single attempt and stop request',()=>{
const entry={state:'queued',durable:true,device_accepted_at:10};
assert.equal(commandEntryStatus({...entry,runtime_phase:'retry-wait'}),'Ожидает следующей попытки');
assert.equal(commandEntryStatus({...entry,runtime_phase:'reconciling'}),'Уточнение результата у VPS');
assert.equal(commandEntryStatus({...entry,stop_requested:true}),'Остановка повторов');
assert.equal(commandPending('accepted'),false);
assert.equal(commandPending('stopped'),false);
});
test('text output receipt does not falsely claim no response when it cannot correlate SERV OK',()=>{
const text={kind:'pulse-output',state:'unconfirmed',description:{encoding:'INTERNAL · FC'}};
assert.match(commandReceipt(text),/не содержит идентификатора команды/);
assert.doesNotMatch(commandReceipt(text),/Ответ трекера не получен/);
assert.equal(commandStatus('unconfirmed'),'Результат не подтверждён');
});
test('text transport completion releases queue without claiming execution',()=>{
const delivered={kind:'set-output',state:'delivered',delivered_at:100,delivery_seconds:1.5,description:{encoding:'INTERNAL · FC'}};
assert.equal(commandPending(delivered.state),false);
assert.equal(commandStatus(delivered.state),'Доставлено');
assert.equal(commandTone(delivered.state),'neutral');
assert.match(commandReceipt(delivered),/Доставка команды подтверждена/);
assert.match(commandReceipt(delivered),/не подтверждение переключения/);
});
@@ -0,0 +1,77 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from 'vite';
let server,readContourSnapshot,contourSummary,workerAvailable;
before(async()=>{
server=await createServer({server:{middlewareMode:true,hmr:false},optimizeDeps:{noDiscovery:true,include:[]},appType:'custom'});
({readContourSnapshot,contourSummary,workerAvailable}=await server.ssrLoadModule('/src/core/system/contourHealth.ts'));
});
after(async()=>{await server?.close();});
const core={ok:true,service:'mission-core-control-plane',version:'test',plugin_runtimes:{ready:1,total:1}};
const contour={contour_id:'test-compute',display_name:'Test compute',expected_node_id:'test-node'};
const worker={schema_version:'missioncore.worker-telemetry/v1',profile:{},connection:{reachable:true,identity_matches:true},node:{node_id:'test-node'},runtimes:[],pipeline:{},network:{},history:[]};
const vehicle={id:'test-vehicle',name:'Test rover',enrollment:'paired',connectivity:'offline'};
function installFetch(t,{failed=[],data={}}={}){
const calls=[];
t.mock.method(globalThis,'fetch',async url=>{
calls.push(url);
if(failed.includes(url))throw new Error('unavailable');
const defaults={
'/api/health':core,
'/api/v1/system/contours':{schema_version:'missioncore.compute-contour-catalog/v1',contours:[contour]},
'/api/v1/system/contours/test-compute/telemetry?history=90':worker,
'/api/v1/fleet':{items:[vehicle]},
};
assert.ok(url in defaults,`Unexpected probe: ${url}`);
return new Response(JSON.stringify(url in data?data[url]:defaults[url]));
});
return calls;
}
test('actual registries determine node count and offline boards prevent all-online status',async t=>{
const calls=installFetch(t);
const snapshot=await readContourSnapshot(new AbortController().signal);
assert.equal(snapshot.workers[0].contour.display_name,'Test compute');
assert.deepEqual(contourSummary(snapshot),{tone:'warning',label:'Часть узлов не в сети',online:2,total:3});
assert.equal(calls.length,4);
});
test('failed checks discard previous online data and distinguish unknown from empty',async t=>{
installFetch(t,{failed:['/api/v1/fleet','/api/v1/system/contours/test-compute/telemetry?history=90']});
const snapshot=await readContourSnapshot(new AbortController().signal);
assert.equal(snapshot.vehicles,null);
assert.equal(snapshot.workers[0].telemetry,null);
assert.equal(snapshot.errors.length,2);
assert.deepEqual(contourSummary(snapshot),{tone:'warning',label:'Проверка неполная',online:1,total:null});
});
test('invalid health never becomes reachable; identity mismatch and stale worker are not online',async t=>{
installFetch(t,{data:{'/api/health':{ok:true}}});
const snapshot=await readContourSnapshot(new AbortController().signal);
assert.equal(snapshot.core,null);
assert.equal(workerAvailable({...worker,connection:{reachable:true,identity_matches:false}}),false);
assert.equal(workerAvailable({...worker,connection:{reachable:false,identity_matches:true}}),false);
assert.equal(workerAvailable({...worker,node:null}),false);
});
test('an empty configured contour contains only the operator, with no fabricated worker',async t=>{
installFetch(t,{data:{'/api/v1/system/contours':{schema_version:'missioncore.compute-contour-catalog/v1',contours:[]},'/api/v1/fleet':{items:[]}}});
assert.deepEqual(contourSummary(await readContourSnapshot(new AbortController().signal)),{tone:'success',label:'Все узлы в сети',online:1,total:1});
});
test('receiver failure leaves worker unknown instead of declaring it offline',async t=>{
installFetch(t,{data:{'/api/v1/system/contours/test-compute/telemetry?history=90':{...worker,node:null,connection:{reachable:false,identity_matches:false,error_code:'telemetry-receiver-unavailable'}}}});
const snapshot=await readContourSnapshot(new AbortController().signal);
assert.equal(contourSummary(snapshot).label,'Состояние части узлов не подтверждено');
const {workerConnectionStatus}=await server.ssrLoadModule('/src/core/system/workerConnectionStatus.ts');
const status=workerConnectionStatus(snapshot.workers[0].telemetry);
assert.equal(status.state,'unknown');
assert.equal(status.label,'Не в сети');
assert.equal(workerConnectionStatus({...worker,node:null,connection:{reachable:false,error_code:'telemetry-agent-stale'}}).label,'Не в сети');
assert.equal(workerConnectionStatus(worker).state,'online');
});
test('a responding Core with recording capacity pressure remains reachable',async t=>{
installFetch(t,{data:{'/api/health':{...core,ok:false,components:{recording_cache:{status:'capacity-pressure'}}}}});
const snapshot=await readContourSnapshot(new AbortController().signal);
assert.equal(contourSummary(snapshot).online,2);
assert.equal(contourSummary(snapshot).label,'Mission Core работает с ограничениями');
});
@@ -0,0 +1,157 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
const code=ts.transpileModule(readFileSync(new URL('../src/core/fleet/equipment.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022}}).outputText;
const {emptyEquipmentPolicy,policyError,equipmentRequest,selectInternetSim,networkOperationMessage,equipmentPolicyEqual}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
const fields=[{key:'25',min:0,max:65535,label:'Интервал'}];
test('SIM choice creates explicit activation without copying another APN or legacy preset',()=>{
for(const connectivity of [
{strategy:'operator',sim_slot:2,preset_id:'ru-megafon-public-v1',apn1:'',apn2:''},
{strategy:'sim',sim_slot:1,apn:'test.apn',apn1:'',apn2:''},
{strategy:'preserve',apn1:'',apn2:''},
]){
const policy={...emptyEquipmentPolicy(),parameters:{'25':60},connectivity};
const next=selectInternetSim(policy,2);
assert.deepEqual(next.connectivity,{strategy:'sim',sim_slot:2,activate:true,automatic:true,apn:null,apn1:'',apn2:'',preset_id:null});
assert.equal(next.parameters,policy.parameters);assert.equal(policy.connectivity,connectivity);
}
const current=selectInternetSim(emptyEquipmentPolicy(),2);current.connectivity.apn='custom';
assert.equal(selectInternetSim(current,2).connectivity.apn,'custom');
assert.equal(selectInternetSim(current,1).connectivity.apn,null);
});
test('blank policy preserves settings; explicit zero remains present',()=>{
const value=emptyEquipmentPolicy();assert.equal(policyError(value,fields),'');assert.deepEqual(value.parameters,{});
value.parameters['25']=0;assert.equal(policyError(value,fields),'');
value.parameters['25']=0.5;assert.notEqual(policyError(value,fields),'');
});
test('endpoint and APN must be concrete before saving',()=>{
const value=emptyEquipmentPolicy();value.endpoint={host:'',port:0,slot:1};assert.notEqual(policyError(value,fields),'');
value.endpoint={host:'track.example.test',port:9023,slot:2};assert.equal(policyError(value,fields),'');
value.connectivity.strategy='manual';assert.notEqual(policyError(value,fields),'');
value.connectivity.apn1='iot.example';assert.equal(policyError(value,fields),'');
});
test('equipment request has independent route, no Node identity, and preserves server errors',async()=>{
const original=globalThis.fetch;const calls=[];
try{
globalThis.fetch=async(url,options)=>{calls.push({url,options});return new Response(JSON.stringify({detail:'Конфликт'}),{status:409});};
await assert.rejects(equipmentRequest('/instances','POST',{candidate_id:'synthetic'}),/Конфликт/);
assert.equal(calls[0].url,'/api/v1/fleet/equipment/instances');assert.equal(calls[0].options.cache,'no-store');
}finally{globalThis.fetch=original;}
});
test('operator connectivity requires a selected preset and a valid SIM slot',()=>{
const value=emptyEquipmentPolicy();value.connectivity={strategy:'operator',apn1:'',apn2:'',preset_id:null,sim_slot:2};
assert.notEqual(policyError(value,fields),'');
value.connectivity.preset_id='ru-mts-public-v1';assert.equal(policyError(value,fields),'');
value.connectivity.sim_slot=3;assert.notEqual(policyError(value,fields),'');
});
test('network status distinguishes observed endpoint from verified write and whole profile',async()=>{
const {networkOperationMessage}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
assert.match(networkOperationMessage({id:'x',state:'verified',scope:'server1',verified_at:1,server1:{host:'example.test',port:9922}}),/Сервер 1 подтверждён/);
assert.match(networkOperationMessage({id:'x',state:'uncertain',scope:'server1'}),/не подтверждён/);
assert.match(networkOperationMessage({id:'x',state:'observed',scope:'server1',server1:{host:'example.test',port:9922}}),/прочитан/);
});
test('command receipt never claims a relay transition or a settings write',async()=>{
const {networkOperationMessage}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
for(const state of ['submitting','queued','dispatched','device_confirmed','device_rejected','expired','unconfirmed','uncertain']){
const message=networkOperationMessage({id:'x',scope:'command',state});
assert.doesNotMatch(message,/записи|адреса сервера|реле включено|реле выключено/i);
}
assert.match(networkOperationMessage({id:'x',scope:'command',state:'device_confirmed'}),/подтвердил приём/);
assert.match(networkOperationMessage({id:'x',scope:'command',state:'unconfirmed'}),/не подтверждено/);
assert.match(networkOperationMessage({id:'x',scope:'command',state:'uncertain'}),/повторения не будет/);
});
test('full configuration distinguishes progress, readback and unchanged profile',async()=>{
const {networkOperationMessage}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
for(const state of ['queued','dispatched','uncertain','unconfirmed','expired','rejected'])assert.doesNotMatch(networkOperationMessage({id:'x',scope:'configuration',state,stage:'write'}),/записаны.*подтверждены/);
assert.match(networkOperationMessage({id:'x',scope:'configuration',state:'observed',record_count:207}),/207 параметров/);
assert.match(networkOperationMessage({id:'x',scope:'configuration',state:'verified'}),/повторным чтением/);
assert.match(networkOperationMessage({id:'x',scope:'configuration',state:'verified',unchanged:true}),/уже совпадают/);
});
test('restart status requires fresh reconnection and never claims a hardware reset from ACK',async()=>{
const {networkOperationMessage}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
const op={id:'x',scope:'command',command:{kind:'restart'}};
assert.match(networkOperationMessage({...op,state:'dispatched'}),/Ожидаем свежие данные/);
assert.match(networkOperationMessage({...op,state:'reconnected'}),/свежие данные по новому соединению/);
assert.doesNotMatch(networkOperationMessage({...op,state:'device_confirmed'}),/перезапущен|снова в сети|свежие данные/);
assert.match(networkOperationMessage({...op,state:'unconfirmed'}),/повторения не будет/);
});
test('deadline stops progress without releasing the write interlock or inventing success',async()=>{
const {networkOperationProgress}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
const op={id:'x',scope:'configuration',state:'dispatched',stage:'preflight',created_at:100,expires_at:280};
assert.deepEqual(networkOperationProgress(op,200),{pending:true,overdue:false,waiting:true,remaining:80});
assert.deepEqual(networkOperationProgress(op,280),{pending:true,overdue:true,waiting:false,remaining:0});
assert.equal(networkOperationProgress({...op,state:'unconfirmed'},300).pending,false);
assert.equal(networkOperationProgress({...op,expires_at:undefined},340).overdue,true);
assert.equal(networkOperationProgress(undefined,300).waiting,false);
});
test('only a terminal preflight timeout proves that configuration writing never began',async()=>{
const {networkOperationMessage,configurationWriteNotStarted}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
const op={id:'x',scope:'configuration',state:'unconfirmed',stage:'preflight',read_only:false};
assert.equal(configurationWriteNotStarted(op),true);
assert.match(networkOperationMessage(op),/Запись настроек не началась/);
for(const change of [{state:'dispatched'},{state:'uncertain'},{stage:'write'},{stage:'verify'},{read_only:true},{scope:'command'}]){
assert.equal(configurationWriteNotStarted({...op,...change}),false);
assert.doesNotMatch(networkOperationMessage({...op,...change}),/Запись настроек не началась/);
}
});
test('SIM result requires modem confirmation and exposes restart wait',()=>{
const op={id:'x',scope:'sim-selection',sim_slot:2};
assert.match(networkOperationMessage({...op,state:'dispatched',stage:'restart'}),/ждём интернет через SIM 2/);
assert.match(networkOperationMessage({...op,state:'uncertain',stage:'restart'}),/не подтверждён/);
assert.match(networkOperationMessage({...op,state:'sim_selected',active_sim:2}),/SIM 2 подключена/);
assert.match(networkOperationMessage({...op,state:'unconfirmed',stage:'preflight'}),/Запись настроек не началась/);
});
test('saved settings are clean despite server key ordering and default expansion',()=>{
const draft=selectInternetSim({...emptyEquipmentPolicy(),parameters:{'25':15,'50':7}},2);
const server={schema_version:1,endpoint:null,connectivity:{strategy:'sim',apn1:'',apn2:'',apn:null,preset_id:null,sim_slot:2,activate:true,automatic:true},parameters:{'50':7,'25':15}};
assert.equal(equipmentPolicyEqual(draft,server),true);
assert.equal(equipmentPolicyEqual(emptyEquipmentPolicy(),{...emptyEquipmentPolicy(),connectivity:{strategy:'preserve',apn1:'',apn2:'',apn:null,preset_id:null,sim_slot:1,activate:false}}),true);
assert.equal(equipmentPolicyEqual(draft,selectInternetSim(server,1)),false);
assert.equal(equipmentPolicyEqual(draft,{...server,parameters:{'50':7,'25':16}}),false);
});
test('explicit SIM intent survives unchanged settings but unrelated edits do not reselect',async()=>{
const {simSelectionIntent}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
const saved=selectInternetSim(emptyEquipmentPolicy(),1);
assert.equal(simSelectionIntent(saved,saved,false),false);
assert.equal(simSelectionIntent({...saved,parameters:{'25':16}},saved,false),false);
assert.equal(simSelectionIntent(saved,saved,true),true);
assert.equal(simSelectionIntent(selectInternetSim(saved,2),saved,false),true);
assert.equal(simSelectionIntent({...saved,connectivity:{...saved.connectivity,apn:'new.apn'}},saved,false),true);
assert.equal(simSelectionIntent(emptyEquipmentPolicy(),saved,true),false);
});
for(const withoutApn of [false,true])test(`both-SIM permission (empty APN: ${withoutApn}) remains an explicit intent`,async()=>{
const {allowBothInternetSims,simSelectionIntent}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
const before=selectInternetSim({...emptyEquipmentPolicy(),parameters:{'25':15}},2);
const both=allowBothInternetSims(before,withoutApn);
assert.deepEqual(both.connectivity,{strategy:withoutApn?'native':'both',apn1:'',apn2:''});
assert.equal(both.parameters,before.parameters);
assert.equal(simSelectionIntent(both,before,false),true);
assert.equal(simSelectionIntent(both,both,false),false);
assert.equal(simSelectionIntent({...both,parameters:{'25':16}},both,false),false);
assert.equal(simSelectionIntent(both,both,true),true);
assert.equal(policyError(both,fields),'');
const op={id:'x',scope:'sim-selection',sim_policy:'both',state:'sim_selected',active_sim:2};
assert.match(networkOperationMessage(op),/Обе SIM разрешены/);
assert.match(networkOperationMessage(op),/SIM 2/);
assert.doesNotMatch(networkOperationMessage({...op,state:'dispatched',stage:'restart'}),/undefined/);
});
test('durable SIM restart shows reconnect phase instead of generic command wait',()=>{
assert.match(networkOperationMessage({id:'x',scope:'sim-selection',sim_policy:'both',state:'dispatched',durable:true,runtime_phase:'executing',stage:'restart'}),/свежую связь после перезапуска/);
});
test('automatic internet is an explicit profile choice and waiting identity is not success',()=>{
const policy=selectInternetSim(emptyEquipmentPolicy(),1);
assert.equal(policy.connectivity.automatic,true);
assert.equal(equipmentPolicyEqual(policy,{...policy,connectivity:{...policy.connectivity,automatic:false}}),false);
assert.match(networkOperationMessage({id:'x',scope:'sim-selection',state:'queued',durable:true,runtime_phase:'waiting-identity'}),/Ожидаем подтверждение карты/);
assert.match(networkOperationMessage({id:'x',scope:'sim-selection',state:'rejected',reason:'sim_card_changed'}),/Карта.*изменилась/);
});
@@ -0,0 +1,65 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import {build} from 'esbuild';
const result=await build({entryPoints:[new URL('../src/core/roverScene/sceneDocument.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
const {defaultScene,environmentFields,changeField,fieldDisabled,parseScene,createMaterial,assignMaterial}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
test('all donor camera and environment fields remain exposed, frame styling excluded',t=>{
const source=new URL('../../../../NODEDC_ENGINE_INFRA/nodedc-source/src/driveinspector/nodes/ThreeDAsset.definition.ts',import.meta.url);
if(!fs.existsSync(source)){t.skip('Donor checkout not installed; pinned catalog remains in repo');return;}
const donor=fs.readFileSync(source,'utf8');
const keys=[...donor.matchAll(/key: '(postFx\.[^']+|cameraZoomStrength|cameraAutoRotate|cameraResetTs)'/g)].map(m=>m[1]);
assert.equal(keys.length,109);
for(const key of keys)assert.ok(environmentFields.some(f=>f.key===key),key);
assert.ok(!environmentFields.some(f=>f.key==='nodeName'));
});
test('documents are independent, scene edits preserve material texture references',()=>{
const a=defaultScene(),b=defaultScene();a.materials['rover/body'].color='#123456';assert.notEqual(a.materials['rover/body'].color,b.materials['rover/body'].color);
const edited=changeField(a,'postFx.lighting.exposure',1.5);assert.equal(edited.postFx.lighting.exposure,1.5);assert.equal(a.postFx.lighting.exposure,defaultScene().postFx.lighting.exposure);assert.equal(edited.materials,a.materials);
});
test('numeric enums, bounds, invalid color and unknown paths are validated',()=>{
const a=defaultScene();assert.equal(changeField(a,'postFx.rendering.toneMapping','3').postFx.rendering.toneMapping,3);
assert.equal(changeField(a,'postFx.grid.step',0).postFx.grid.step,.01);
for(const [key,value] of [['__proto__.x',1],['postFx.grid.step',NaN],['postFx.grid.colorMain','red'],['postFx.rendering.fog','invalid']])assert.equal(changeField(a,key,value),a);
});
test('fog interval, atlas/skybox exclusion and field availability stay coherent',()=>{
let a=changeField(defaultScene(),'postFx.rendering.fogRange',[18,3]);assert.deepEqual(a.postFx.rendering.fogRange,[3,18]);assert.equal(a.postFx.rendering.fogStart,3);assert.equal(a.postFx.rendering.fogEnd,18);
a=changeField(a,'postFx.skybox.enabled',true);assert.equal(a.postFx.envAtlas.enabled,false);
assert.equal(fieldDisabled(a,environmentFields.find(f=>f.key==='postFx.envAtlas.enabled')),true);
});
test('scene JSON round trips materials, texture data and environment without authority',()=>{
const a=defaultScene();a.materials['rover/box'].textures.diffuse={name:'test.png',data:'data:image/png;base64,YWJj'};a.materials['rover/box'].roughness=.28;
assert.deepEqual(parseScene(JSON.parse(JSON.stringify(a))),a);
assert.throws(()=>parseScene({schema:'other'}));
assert.throws(()=>parseScene({...a,model:'wrong'}));
assert.equal('armed' in a,false);
});
test('import rejects texture URLs and normalizes out-of-range PBR values',()=>{
const a=defaultScene();a.materials['rover/box'].roughness=20;assert.equal(parseScene(a).materials['rover/box'].roughness,1);
a.materials['rover/box'].textures.normal={name:'remote',data:'https://unknown/texture'};assert.throws(()=>parseScene(a));
});
test('editing excludes drive bindings and key controls without changing arm authority',()=>{
const view=fs.readFileSync(new URL('../src/components/rover/RoverView.tsx',import.meta.url),'utf8');
assert.match(view,/if\(!c.ready\|\|!active\|\|open\|\|editing/);assert.match(view,/c.ready&&!editing/);assert.match(view,/c.pauseInput\(\);setHeld/);
const editor=fs.readFileSync(new URL('../src/components/rover/editor/RoverScene.tsx',import.meta.url),'utf8');assert.doesNotMatch(editor,/\.arm\(|setDemand|\/api\/v1\/fleet/);
});
test('export manifest retains complete geometry and all editable material groups',()=>{
const manifest=JSON.parse(fs.readFileSync(new URL('../public/rover-scene/dcd006-v020.json',import.meta.url),'utf8'));
assert.equal(manifest.source_object_count,1426);assert.equal(manifest.render_mesh_count,9);assert.equal(manifest.source_saved,false);assert.match(manifest.uv,/cube/);
assert.deepEqual(Object.keys(manifest.materials).sort(),Object.keys(defaultScene().materials).map(k=>k.replace('rover/','')).sort());
});
test('named custom materials and assignments survive JSON and reject unknown groups',()=>{
let a=createMaterial(defaultScene(),'custom/example');
a.materials['custom/example'].name='Мой металл';a=assignMaterial(a,'rover/body','custom/example');
assert.deepEqual(parseScene(JSON.parse(JSON.stringify(a))),a);
assert.equal(assignMaterial(a,'unknown','custom/example'),a);
assert.equal(assignMaterial(a,'rover/body','missing'),a);
assert.equal(createMaterial(a,'__proto__'),a);
const legacy=defaultScene();delete legacy.assignments;assert.deepEqual(parseScene(legacy).assignments,{});
});
test('default environment is the original NodeDC preset without neutral overrides',()=>{
const a=defaultScene();assert.equal(a.postFx.chromaticAberration.enabled,true);
assert.equal(a.postFx.rendering.backgroundColor,'#111113');
assert.equal(a.postFx.lighting.ambientIntensity,0);
});
@@ -0,0 +1,43 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const bundle=await build({stdin:{contents:"export * from './src/core/roverScene/sceneDocument'; export * from './src/core/roverScene/sceneMigration';",resolveDir:process.cwd()},bundle:true,write:false,platform:'node',format:'esm'});
const {defaultScene,loadStoredScene,parseScene}=await import('data:text/javascript;base64,'+Buffer.from(bundle.outputFiles[0].contents).toString('base64'));
// Historical settings released by the first editor, independent of migration code.
function savedFirstEditor(){
const d=defaultScene();delete d.environmentVersion;
d.postFx={...d.postFx,
lighting:{exposure:1.1,skyBoxIntensity:1,ambientIntensity:.22},
envAtlas:{...d.postFx.envAtlas,reflectionIntensity:1,brightness:1.2},
rendering:{...d.postFx.rendering,backgroundColor:'#202227',fog:'none',toneMapping:4},
grid:{...d.postFx.grid,colorMain:'#747982',colorX:'#93969c',colorZ:'#93969c',alphaMain:.25,alphaX:.35,alphaZ:.35,fadeStart:2,fadeEnd:5,step:.5,diameter:12},
chromaticAberration:{...d.postFx.chromaticAberration,enabled:false},vignette:{...d.postFx.vignette,enabled:false},grading:{...d.postFx.grading,enabled:false},bloom:{...d.postFx.bloom,enabled:false},
directionalLight:{...d.postFx.directionalLight,intensity:1.8,azimuth:135,elevation:45},shadowCatcher:{...d.postFx.shadowCatcher,size:4,lightIntensity:.5,shadowIntensity:.25}
};
return d;
}
test('previous saved neutral preset migrates to NodeDC while retaining material work',()=>{
const raw=savedFirstEditor();raw.materials['rover/body'].name='Мой корпус';raw.materials['rover/body'].roughness=.73;raw.materials['rover/body'].textures.diffuse={name:'my.png',data:'data:image/png;base64,YWJj'};
raw.assignments['rover/box']='rover/body';raw.cameraZoomStrength=.1;
const original=structuredClone(raw),r=loadStoredScene(raw);
assert.equal(r.restoredEnvironment,true);assert.equal(r.updated,true);
assert.deepEqual(r.document.postFx,defaultScene().postFx);
assert.deepEqual(r.document.materials,raw.materials);assert.deepEqual(r.document.assignments,raw.assignments);assert.equal(r.document.cameraZoomStrength,.1);
assert.deepEqual(raw,original,'backup must retain the exact input');
assert.equal(loadStoredScene(r.document).updated,false,'migration runs once');
});
test('a single custom environment edit prevents a destructive reset',()=>{
const raw=savedFirstEditor();raw.postFx.lighting.exposure=1.3;
const r=loadStoredScene(raw);assert.equal(r.restoredEnvironment,false);assert.deepEqual(r.document.postFx,raw.postFx);
});
test('a deliberate new gray scene and explicit JSON imports retain their appearance',()=>{
const raw=savedFirstEditor();raw.environmentVersion=2;
assert.equal(loadStoredScene(raw).restoredEnvironment,false);
delete raw.environmentVersion;
const imported=parseScene(raw);assert.equal(imported.environmentVersion,2);assert.deepEqual(imported.postFx,raw.postFx);
assert.equal(loadStoredScene(imported).restoredEnvironment,false);
});
test('already restored legacy NodeDC scene is only versioned, not altered',()=>{
const raw=defaultScene();delete raw.environmentVersion;const r=loadStoredScene(raw);
assert.equal(r.updated,true);assert.equal(r.restoredEnvironment,false);assert.deepEqual(r.document.postFx,raw.postFx);
});
+28 -3
View File
@@ -149,9 +149,11 @@ globally unique because Mosquitto ACL ownership is username-based.
## Worker agent
MQTT outputs use `startup_error_behavior="retry"`, with a 2000-metric buffer and
the configured flush interval. A missing broker at agent startup must not end
the service. See [Telegraf's startup policy](https://docs.influxdata.com/telegraf/v1/configuration/plugin-options/).
MQTT outputs request `startup_error_behavior="retry"`, with a 2000-metric buffer
and the configured flush interval. This setting alone does not guarantee
recovery: Telegraf 1.38.4 can exit cleanly when MQTT is unavailable at startup.
The Tailscale profile below therefore also installs a system recovery task.
See [Telegraf's startup policy](https://docs.influxdata.com/telegraf/v1/configuration/plugin-options/).
If Docker lost a published listener while the saved LAN address is unchanged,
the explicit broker Apply action reconciles that listener; a telemetry GET never
restarts infrastructure. Node connectivity does not prove a profile is ready.
@@ -228,3 +230,26 @@ changing the K1 command sequence.
The stack and agent are intentionally not started by repository tests. Provisioning a
machine is a separate, explicit operation.
## Tailscale operator profile and startup recovery
The accepted 2026-09-25 operator profile no longer depends on a shared LAN or
DHCP address. A prepared Windows agent uses `127.0.0.1:1883`; the existing strict
Tailscale SSH identity carries a loopback reverse forward to the operator
broker. Operator deployment is owned by `scripts/manage_telemetry_startup.py`
(plan, hash-bound apply, rollback). This is a macOS **login** profile, not a
pre-login Docker daemon. Preserve the explicit prepared stack root and its
private credentials when moving the Core source checkout.
For this profile the Windows install/update bundle includes and invokes
`Install-NdcMissionCoreTelemetryRecovery.ps1`: boot + once-per-minute SYSTEM
reconciliation for a stopped Telegraf service, independent of login. Its
maintenance/rollback boundary is described in the audit. Do not rely solely on
SCM failure actions or the MQTT `startup_error_behavior` setting: the pinned
1.38.4 release was observed to terminate with a clean service exit when the
broker was unavailable during boot.
See [the measured recovery audit](../../docs/audits/2026-09-25-worker-telemetry-recovery.md)
for exact acceptance, remaining cold-boot/clean-host gates and bounded test
entrypoints. The earlier LAN workflow remains a legacy explicit configuration;
it is not the current Worker 006 transport.
+1
View File
@@ -29,6 +29,7 @@ SAFE_IDENTIFIER: Final = re.compile(
)
SAFE_INTERVAL: Final = re.compile(r"^[1-9][0-9]{0,2}s$")
WINDOWS_BUNDLE_FILES: Final = (
"Install-NdcMissionCoreTelemetryRecovery.ps1",
"Get-NdcMissionCorePipelineTelemetry.ps1",
"Install-NdcMissionCoreTelegraf.ps1",
"Update-NdcMissionCoreTelegraf.ps1",
@@ -33,6 +33,10 @@ foreach ($name in @(
Set-Item -Path "Env:$name" -Value ([string]$value)
}
$recoveryInstaller = Join-Path $PSScriptRoot 'Install-NdcMissionCoreTelemetryRecovery.ps1'
if ($payload.MISSIONCORE_MQTT_HOST -eq '127.0.0.1' -and -not (Test-Path $recoveryInstaller -PathType Leaf)) {
throw 'Telemetry recovery installer missing from bundle'
}
if (Get-Service -Name $serviceName -ErrorAction SilentlyContinue) {
throw "Service '$serviceName' already exists; refusing an implicit replacement"
}
@@ -137,6 +141,10 @@ try {
if ($LASTEXITCODE -ne 0) {
throw "Failed to enable Telegraf recovery for non-crash failures"
}
$recoveryTask = $null
if ($payload.MISSIONCORE_MQTT_HOST -eq '127.0.0.1') {
$recoveryTask = & $recoveryInstaller -ExpectedNodeId $env:COMPUTERNAME -Action Apply | ConvertFrom-Json
}
Start-Service -Name $serviceName
$service = Get-Service -Name $serviceName
$service.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running, [TimeSpan]::FromSeconds(20))
@@ -150,6 +158,7 @@ try {
Status = $service.Status.ToString()
StartType = $service.StartType.ToString()
RecoveryConfigured = $true
RecoveryTask = $recoveryTask
Configuration = $configurationPath
PipelineCollector = $collectorPath
PipelineJournal = $PipelineJournal
@@ -0,0 +1,87 @@
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)][string]$ExpectedNodeId,
[ValidateSet('Plan','Apply','Rollback')][string]$Action = 'Plan',
[string]$BackupDirectory
)
# Telegraf 1.38.4 can report MQTT startup failure as a clean Windows-service exit.
# SCM failure actions alone cannot recover that stopped service.
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
if ($env:COMPUTERNAME -cne $ExpectedNodeId) { throw 'Worker identity mismatch' }
$taskName = 'ndc-mission-core-telemetry-recovery'
$root = Join-Path $env:ProgramFiles 'NDC\Mission Core\TelemetryRecovery'
$guardPath = Join-Path $root 'Resume-Telemetry.ps1'
$service = Get-CimInstance Win32_Service -Filter "Name='telegraf'"
if (-not $service -or $service.PathName -notlike '*NDC\Mission Core\Telegraf\telegraf.exe*') { throw 'Managed Telegraf service required' }
$guard = @'
$ErrorActionPreference = 'Stop'
$service = Get-Service -Name 'telegraf'
if ($service.Status -eq 'Running') { exit 0 }
if ($service.Status -ne 'Stopped') { exit 0 }
$values = @{}
foreach ($entry in (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Services\telegraf').Environment) {
$name, $value = $entry -split '=', 2
if ($name -in @('MISSIONCORE_MQTT_HOST','MISSIONCORE_MQTT_PORT')) { $values[$name] = $value }
}
if ($values['MISSIONCORE_MQTT_HOST'] -ne '127.0.0.1' -or $values['MISSIONCORE_MQTT_PORT'] -ne '1883') { exit 1 }
$client = [Net.Sockets.TcpClient]::new()
try {
$connect = $client.ConnectAsync('127.0.0.1', 1883)
if (-not $connect.Wait(3000) -or -not $client.Connected) { exit 0 }
} catch { exit 0 } finally { $client.Dispose() }
Start-Service -Name 'telegraf'
(Get-Service -Name 'telegraf').WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running, [TimeSpan]::FromSeconds(15))
'@
if ($Action -eq 'Plan') {
[ordered]@{node=$env:COMPUTERNAME;task=$taskName;path=$guardPath;startMode=$service.StartMode;triggers=@('boot','every-minute');scope='Start stopped telemetry service only';requiresInteractiveLogin=$false}|ConvertTo-Json -Compress
exit 0
}
if ($Action -eq 'Rollback') {
if (-not $BackupDirectory) { throw 'BackupDirectory required' }
$receipt = Get-Content (Join-Path $BackupDirectory 'receipt.json') -Raw | ConvertFrom-Json
if ($receipt.node -cne $ExpectedNodeId -or $receipt.task -ne $taskName) { throw 'Backup identity mismatch' }
if ((Get-FileHash $guardPath -Algorithm SHA256).Hash -ne $receipt.installedHash) { throw 'Installed recovery script changed' }
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
if (Test-Path (Join-Path $BackupDirectory 'task.xml')) {
Register-ScheduledTask -TaskName $taskName -Xml (Get-Content (Join-Path $BackupDirectory 'task.xml') -Raw) -Force | Out-Null
}
if (Test-Path (Join-Path $BackupDirectory 'guard.ps1')) {
Copy-Item (Join-Path $BackupDirectory 'guard.ps1') $guardPath -Force
} else { Remove-Item $guardPath }
[ordered]@{restored=$true;task=$taskName}|ConvertTo-Json -Compress
exit 0
}
$principal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Administrative installer required' }
if (Test-Path $root) {
if ((Get-Item $root -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Recovery directory must not be a reparse point' }
}
New-Item -ItemType Directory -Path $root -Force | Out-Null
# SYSTEM executes this file: only SYSTEM and Administrators may modify it.
& icacls.exe $root /inheritance:r /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'Recovery directory ACL failed' }
$backup = Join-Path $root ('backups\' + [Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $backup -Force | Out-Null
$previousTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
if ($previousTask) { Export-ScheduledTask -TaskName $taskName | Set-Content (Join-Path $backup 'task.xml') -Encoding UTF8 }
if (Test-Path $guardPath) { Copy-Item $guardPath (Join-Path $backup 'guard.ps1') }
try {
[IO.File]::WriteAllText($guardPath, $guard, [Text.UTF8Encoding]::new($false))
$exe = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
$run = New-ScheduledTaskAction -Execute $exe -Argument ('-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "' + $guardPath + '"')
$triggers = @((New-ScheduledTaskTrigger -AtStartup), (New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) -RepetitionInterval (New-TimeSpan -Minutes 1)))
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Seconds 45) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
$identity = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
Register-ScheduledTask -TaskName $taskName -Action $run -Trigger $triggers -Settings $settings -Principal $identity -Force | Out-Null
$receipt = [ordered]@{node=$env:COMPUTERNAME;task=$taskName;installedHash=(Get-FileHash $guardPath -Algorithm SHA256).Hash;backup=$backup}
$receipt|ConvertTo-Json|Set-Content (Join-Path $backup 'receipt.json') -Encoding UTF8
Start-ScheduledTask -TaskName $taskName
$receipt|ConvertTo-Json -Compress
} catch {
if ($previousTask) { Register-ScheduledTask -TaskName $taskName -Xml (Get-Content (Join-Path $backup 'task.xml') -Raw) -Force | Out-Null }
else { Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue }
if (Test-Path (Join-Path $backup 'guard.ps1')) { Copy-Item (Join-Path $backup 'guard.ps1') $guardPath -Force }
else { Remove-Item $guardPath -ErrorAction SilentlyContinue }
throw
}
@@ -0,0 +1,26 @@
[CmdletBinding()]
param([Parameter(Mandatory=$true)][string]$ExpectedNodeId)
$ErrorActionPreference='Stop'
$ProgressPreference='SilentlyContinue'
if ($env:COMPUTERNAME -cne $ExpectedNodeId) { throw 'Worker identity mismatch' }
$task=Get-ScheduledTask -TaskName 'ndc-mission-core-telemetry-recovery'
$account=[Security.Principal.NTAccount]::new($task.Principal.UserId)
$sid=$account.Translate([Security.Principal.SecurityIdentifier]).Value
if (-not $task.Settings.Enabled -or $sid -ne 'S-1-5-18') { throw 'Recovery task not enabled as SYSTEM' }
$before=Get-CimInstance Win32_Service -Filter "Name='telegraf'"
if ($before.State -ne 'Running') { throw 'A running baseline is required' }
$started=[DateTime]::UtcNow
Stop-Service telegraf
(Get-Service telegraf).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped,[TimeSpan]::FromSeconds(20))
$automatic=$false
try {
while (([DateTime]::UtcNow-$started).TotalSeconds -lt 80) {
Start-Sleep -Seconds 2
$after=Get-CimInstance Win32_Service -Filter "Name='telegraf'"
if ($after.State -eq 'Running' -and $after.ProcessId -ne $before.ProcessId) { $automatic=$true;break }
}
[ordered]@{node=$ExpectedNodeId;test='clean-service-stop';automaticRecovery=$automatic;elapsedSeconds=[Math]::Round(([DateTime]::UtcNow-$started).TotalSeconds,2);previousPid=$before.ProcessId;newPid=$after.ProcessId;state=$after.State}|ConvertTo-Json -Compress
if (-not $automatic) { throw 'Automatic recovery failed; restoring baseline' }
} finally {
if ((Get-Service telegraf).Status -ne 'Running') { Start-Service telegraf }
}
@@ -67,6 +67,10 @@ if (-not ($serviceEnvironmentCandidate | Where-Object {
)
}
$recoveryInstaller = Join-Path $PSScriptRoot 'Install-NdcMissionCoreTelemetryRecovery.ps1'
if ($env:MISSIONCORE_MQTT_HOST -eq '127.0.0.1' -and -not (Test-Path $recoveryInstaller -PathType Leaf)) {
throw 'Telemetry recovery installer missing from bundle'
}
$temporaryRoot = Join-Path $env:TEMP "ndc-mission-core-telegraf-update-$([Guid]::NewGuid().ToString('N'))"
$validationOutput = Join-Path $temporaryRoot "validation.out.log"
$validationError = Join-Path $temporaryRoot "validation.error.log"
@@ -127,6 +131,10 @@ try {
if ($LASTEXITCODE -ne 0) {
throw "Failed to enable Telegraf recovery for non-crash failures"
}
$recoveryTask = $null
if ($env:MISSIONCORE_MQTT_HOST -eq '127.0.0.1') {
$recoveryTask = & $recoveryInstaller -ExpectedNodeId $env:COMPUTERNAME -Action Apply | ConvertFrom-Json
}
}
catch {
Stop-Service -Name $serviceName -Force -ErrorAction SilentlyContinue
@@ -155,6 +163,7 @@ try {
ServiceName = $serviceName
Status = (Get-Service -Name $serviceName).Status.ToString()
RecoveryConfigured = $true
RecoveryTask = $recoveryTask
Configuration = $configurationPath
Backup = $backupPath
PipelineCollector = $collectorPath
+66
View File
@@ -0,0 +1,66 @@
# Rover scene material and environment editor
Owner request: 2026-09-25. The operator adjusts the appearance of the selected
vehicle without leaving its observation viewport. The pencil in the existing
3D View header enters an editing mode. A bottom material palette and movable,
modeless material/environment inspectors apply changes immediately.
The earlier combined control/design modal was explicitly superseded by the
owner. Driving settings retain their existing modal. A separate workspace
would hide the live scene and duplicate navigation; the admitted surface is an
edit mode of the existing rover view, with no new product root.
The scene document belongs to vehicle + model revision, persists in IndexedDB
on this operator computer, includes imported texture data, and can be exported
or imported as JSON. Loading and persistence failures remain visible; closing
an inspector never waits for saving. This is appearance only, not a firmware,
calibration or hardware profile. Editing pauses local drive input and prevents
new drive input until exit; it never arms a vehicle.
NodeDC ThreeDAsset.definition provides the environment field catalog and
PlayCanvas remains the renderer. The NodeDC inspector chrome is not copied.
Design Guideline Window (modeless, draggable), Inspector, ControlRow,
InspectorSelectField, RangeControl, ColorField, Switch, Button, IconButton and
ToastStack own all controls and surfaces. Canonical edit/layers/globe icons
identify edit, materials and environment. Material thumbnails are domain PBR
previews inside canonical buttons.
The v020 Blender file is an immutable source. Export retains separate semantic
material groups and UVs; clicking a rendered surface selects its shared material.
The palette explicitly states that edits affect every surface using that
material. Appearance groups include chassis, rubber, track steel, enclosure,
MOLLE, motor aluminum, black hardware and accessories.
Acceptance: donor field coverage, scene validation/persistence isolation,
renderer resource cleanup, edit/control exclusion, TypeScript/unit/build and
browser QA for picking, live edits, dragging, normal/expanded layout, keyboard,
texture loading, persistence and return to observation. No physical motion is
part of editor acceptance.
Owner refinement: the 3D header overlays the viewport with no opaque strip.
The original NodeDC environment preset remains the default and is restored
through the environment inspector, preserving materials. Every material has an
editable display name. A permanent final plus tile creates a new PBR material;
explicit assignment applies it to the picked semantic group. IDs remain stable
when renamed. Custom materials and assignments persist in the same document.
Verified on 2026-09-25: TypeScript/production build, all 972 frontend tests,
normal and expanded browser layout, transparent header, the NodeDC reset control,
GPU picking, material naming/creation/assignment, draggable inspector and Escape.
A synthetic checker texture was uploaded, rendered and retained with its custom
material, name and assignment after a page reload. The texture was then removed
and the enclosure's original material reassigned. Browser error/warning log was
empty. No motor commands were sent; the canonical service remains on port 8000.
The inherited renderer still reduces MSAA to one sample. Local scene storage is
not cross-computer synchronization. Both bounds are recorded in MISSIONCOR-85.
Follow-up: the owner still saw the withdrawn gray preset after clearing browser
cache. Changing defaults and using the reset in one browser did not migrate
other saved IndexedDB scene documents. Added environmentVersion 2 and a narrow
load migration: only the exact original neutral environment is replaced with
NodeDC defaults. Material edits, textures, assignments and camera options survive.
An atomic IndexedDB transaction retains the old document under
`:before-environment-v2` before replacing it. Individually edited environments
and explicit JSON imports are preserved; the version prevents future resets.
Regression tests cover the legacy scene, material preservation, idempotence,
custom environments, deliberate gray scenes, imports and already restored scenes.
@@ -0,0 +1,19 @@
# 0049 — Observation overlays, offline source catalog and section navigation
## Decision
All apparatus observation panels place titles/actions over their viewport, without a separate header strip. A ResizeObserver reserves the real header height for status and telemetry content. DG SplitPane owns the invisible separator variant: pointer hit area, keyboard resize and keyboard focus remain available. Ratios still use the existing per-vehicle JSON layout.
The apparatus detail and board monitor return through a shared circular header action. Explicit left-menu navigation remounts the workspace entry view, including repeated selection; persisted configuration and window arrangements are retained. Scene tool windows and recorded-session overview close. System contour selection returns to its default modules view. Leaving rover control invokes its existing cleanup/stop.
## Sources and authority
A known D455 with an empty offline capability list remains available as a camera viewport with its supported layer choices. A published nonempty capability list takes precedence. Detailed camera settings reuse SensorDetail; its capabilities and preview are not requested from an offline board.
Plugins may declare a view catalog independent of physical inventory. K1 declares point cloud (3D), point cloud (top), and camera. These optional windows are listed even before enrollment, start hidden, and display an explicit disconnected-source message when selected. They never fabricate a Sensor, session, device identifier or command authority. The catalog choice is persisted in bounded catalogVisible layout data. Actual devices retain distinct device-ID-based views and replace unbound catalog entries; no ambiguous model-to-instance assignment is inferred. K1 acquisition remains an explicit operator action in its existing configurator.
Source gear actions open the existing device settings in a draggable window. The layers dialog continues to control visibility and order.
## Validation scope
Build and offline UI acceptance cover section reset/back navigation, overlay headers, invisible pointer/keyboard resizing, layer visibility/persistence, disconnected notices and settings access. Unit cases cover D455 capability precedence, ambiguous plugin rejection, template/physical-device separation and bounded catalog persistence. The board was offline during this change: live RealSense/XGRIDS delivery and hardware settings are not claimed as accepted.
@@ -0,0 +1,105 @@
# 0050 — Apparatus composition and its onboard device branch
## Operator job and decision
Owner-approved 25.09.2026: configure the rover as a whole while seeing which
computer owns each device. Keep the apparatus identity above its computer.
The apparatus has a compact name/class summary, apparatus settings, and an
Equipment section. The current single computer is an expandable resource row;
its devices appear beneath it. Host facts and unpairing belong to its settings.
The previously proposed flat peer list of computer and cameras was rejected:
it hides the actual USB/runtime dependency. The present implementation supports
one onboard computer; multiple computers and flight-controller transports are
not claimed. A future controller's placement must follow its actual connection,
not an invented independent link. Actuation role is separate from topology.
## Actions and persistence
The outer plus is owned by the vehicle list and creates an apparatus. Inside a
vehicle it is absent. Equipment has an attach-computer action and inventory
refresh; the computer row has wireless-device enrollment, settings and monitor.
USB devices are discovered by Node. Wireless enrollment reuses plugin-owned
forms, including K1, and cannot run while the owning computer is unavailable.
ResourceRow, Inspector, IconButton, SettingsCard and Window are existing DG
primitives. No new visual primitive or product root is introduced. The stored
v1 board-layout ids remain compatible: settings/devices control the two outer
sections; computer now controls the nested branch. Collapsing an outer section
does not erase the nested preference. Scene and observation layout identities
remain keyed by the apparatus.
Owner refinement later on 25.09: the apparatus name and class are appended to
the shared panel title. The separate summary card is removed; observation and
configuration are opposite header icon actions. Computer branch collapse is
the rightmost row action. When cached devices are shown, their explanation is
inline after the computer status rather than a separate offline card.
Offline Core reads only its cached fleet inventory, never queries the absent
hardware or shows an endless discovery spinner. Cached devices stay visible;
their current connection is unconfirmed, and mutations stay disabled.
Apparatus metadata is an exception to the hardware mutation gate: the name is
editable in Apparatus settings while the board is offline. PATCH /fleet/{id}
accepts only name and expected_revision through the local-operator boundary.
The transaction preserves apparatus/node identity, binding, platform, device
assignments and history. It checks revisions to prevent a stale editor from
overwriting another change, emits the existing fleet snapshot event, and
returns public metadata. Repeating the already-saved name is idempotent.
The list, panel name/type title, monitor and observation center use this same
registry name. No board request or OS configuration is involved.
The Park navigation now contains only Contour status and Vehicles. Sensor and
composition catalog placeholders are removed. Contour status reads local Core
health, the configured compute-contour catalog and its telemetry, plus the
fleet registry. Simulation gateway fallback identifiers are not inventory.
Node counts are derived from these registries; unavailable/invalid checks are
explicitly unknown, not empty or online. Worker availability requires both
reachability and identity match, with backend telemetry freshness checks;
board status uses the authenticated fleet heartbeat expiry. Polling is bounded,
sequential and stopped when the workspace unmounts.
## Computer replacement boundary
POST /fleet/{vehicle}/computer consumes a verified Node invitation and an
expected vehicle revision. The vehicle id/name/class/creation time stay intact.
The prior private binding row is archived transactionally in board_history;
monitor/configuration archives remain keyed by their original node identity.
The new computer does not inherit commands, sensor sessions, calibration or
claims of physical wiring from the previous computer. A new verified inventory
is required. Existing devices bound to another apparatus are not transferred.
Expired previews, stale revisions, pending pairing, active rover control and
unexpired device operations block replacement. Verification/listener failures
before commit leave the original row intact. At explicit replacement commit,
the old binding loses authority; handshake completion of the new binding is
shown separately. Failure does not silently restore or authorize the old one.
Each stream frame rechecks its binding. Command admission resolves the node
under the same fleet lock as replacement. Preview retry is idempotent only for
the exact resulting binding. This is not live hot-swapping acceptance.
## Validation
Synthetic pairing tests cover preserved vehicle identity/layout, archived old
binding, old-certificate rejection, duplicate node rejection, stale/expired
previews, idempotency, active operation rejection and transactional rollback.
Frontend checks and offline browser QA cover both plus scopes, nested folding,
offline inventory, K1 enrollment state, host settings and back navigation.
Acceptance on 25.09.2026: all 69 fleet tests, 978 Control Station tests and
the Node UI contract test passed. Both production builds passed TypeScript.
Browser QA on canonical port 8000 verified normal/expanded presentation,
Escape dismissal, list/computer/device action scopes, cached devices, and
folding persistence across navigation and a full page reload. The existing
LaunchAgent restarted the sole Core process; exact health recovered.
The real board is powered off: new pairing/replacement and live device operation
require subsequent hardware acceptance; no such action is performed here.
Later name/status acceptance on the same date: 44 focused identity, pairing
and replacement tests passed, as did all 982 Control Station unit tests,
TypeScript and the production build. Final presentation refinements passed
the architecture/status checks again (8 tests), typecheck and build. Browser
QA covered normal/expanded views, empty-name rejection, cancellation, a
temporary rename visible in the list/header/observation center, persistence
after reload and restoration of the original name. The live status view
showed Core reachable, a configured worker without fresh telemetry and the
powered-off board without a link. No actuator or device commands were sent.
@@ -0,0 +1,191 @@
# Автоматическая настройка связи B2
Дата: 2026-09-28. Статус: проект полного решения по требованию владельца.
Первый цикл применения уже принят в ограниченной области:
[выбор карты, подбор доступа и проверка результата через VPS 0.1.38](CARD_ACCESS_APPLICATION_20260928.md).
Не следует считать это приёмкой всех пунктов данного проекта.
Последующее уточнение владельца: [обе карты разрешены, выбор задаёт
предпочтение с автоматическим резервом](SIM_PREFERENCE_AND_FALLBACK_20260928.md).
Ранее проверенный выбор через запрет второй SIM этому требованию не
соответствует. Новая семантика не считается реализованной переименованием
существующего селектора; сначала нужен подтверждённый исполнитель в B2 или
независимый локальный канал.
Первый программный этап реализован в
[журнале наблюдений SIM](SIM_OBSERVATION_RUNTIME_20260928.md): источники
идентичности разделены, полные сведения не затираются неполным чтением,
история не выдаётся за текущее положение карты. Широкий каталог, офлайн-подбор
и фоновая реакция на замену карты ниже остаются проектом.
Продолжение: [полные SID двух SIM в стартовых пакетах собственного VPS](NETWORK_SIM_IDENTITY_20260928.md).
Они сопоставлены с USB-наблюдениями двух расстановок; Core хранит их время и
не выдаёт старый пакет за свежий. Это позволяет узнавать известную карту
в другом слоте по сети. В 0.1.38 эта привязка используется при явном сохранении
настроек, с проверкой карты на VPS перед записью и при подтверждении результата.
## Требование
Владелец меняет SIM или переставляет её между слотами; система определяет
доступные данные о карте, выбирает подходящие параметры и проверяет выход на
собственный VPS. Пользователь не должен каждый раз назначать операторов слотам.
Справочник операторов должен обновляться и редактироваться отдельно от прошивки.
План отдельной ручной записи МТС в SIM 1 остановлен до отправки конфигурации
после уточнения владельца. Повторное USB-чтение на том этапе, когда обе SIM
были извлечены, подтвердило исходный образ; записи не было. В последующем
[опыте с МТС в SIM 2](MTS_MODEM_DIAGNOSTIC_20260928.md) связь с собственным VPS
заработала с тем же образом конфигурации и сохранилась после отключения USB.
Это квалификация данного подключения, а не автоматической настройки новой SIM.
## Что уже известно
- Код содержит два неизменяемых публичных пресета: МТС и МегаФон.
- Модель 231/0.01 позволяет читать и задавать APN, логин и пароль отдельно
для слотов (поля 67–69 и 89–91). Наличие этих полей не доказывает встроенный
каталог APN или исполнение собственного кода в B2.
- INTERNAL передаёт коды обслуживающих сетей и состояние SIM. Обслуживающая
сеть не всегда определяет поставщика SIM или тариф; нельзя подменять
неопределённого оператора именем из сохранённого APN.
- Ранние USB-ответы SID содержали неполные идентификаторы. Они не
являются доказанным полным ICCID и не дают оснований угадывать префикс
оператора. `MN` — IMEI модема, не IMSI карты. В последующей пассивной записи
запуска с МТС в SIM 2 (сессия `mts-modem-diagnostic-b0fb46ee12a849ff96fe25db140f4d0f`)
наблюдались ответы внутреннего модема на `AT+CCID` и `AT+CIMI`: полный
20-значный ICCID и 15-значный IMSI с префиксом, согласованным с сетью МТС.
Наш наблюдатель этих AT-команд не отправлял. Это подтверждает доступность
идентификаторов в данном потоке запуска, но ещё не является квалификацией
запроса по требованию, двух SIM одновременно или распознавания всех MVNO.
Последующая [перестановка той же карты](SIM_SLOT_IDENTITY_20260928.md)
подтвердила полный ICCID штатным запросом `I 7` в обоих слотах, в том числе
без интернета. Идентификатор совпал с ответом модема на `AT+CCID`; при возврате
карта снова определилась во втором слоте. Это закрывает запрос ICCID и
привязку к слоту для одной испытанной МТС, установленной без второй карты.
Следующий [опыт с двумя SIM](DUAL_SIM_IDENTITY_20260928.md) подтвердил
распознавание обеих карт и операторов в потоке запуска до и после обмена
слотами, но выявил ограничение `I 7`: для первого слота он возвращал 12 цифр,
для второго — 20, в том числе при повторном чтении. Кроме того, сырой CCID
МегаФона содержит 18 цифр и `ff`, а SID прошивки — отличающееся 20-значное
число. Поэтому ни длина SID, ни его совпадение с номером слота не являются
достаточным основанием для автоматической записи. Запрос IMSI по требованию,
канонизация нестандартного CCID и произвольные операторы ещё не квалифицированы.
- Чтение по USB работает и без SIM/мобильного интернета. При этом нынешний
продуктовый USB-адаптер поддерживает Mac оператора, не бортовой Linux.
- Нативный автоматический подбор APN на B2 пока не подтверждён. В руководстве
описаны явная настройка и очистка APN; семантика `auto` или пустого значения
как автоматического режима для этой прошивки не установлена.
## Предлагаемая структура справочника
Отделить опубликованные параметры доступа от идентичности карты, положения
в слоте и политики выбора активной SIM.
Каждая неизменяемая редакция записи содержит:
- стабильный идентификатор оператора/варианта услуги и номер редакции;
- название, страну и область применения (обычная SIM, корпоративная услуга);
- APN, способ авторизации и публичные данные доступа, если они предусмотрены;
- источник, дату проверки и отдельный статус проверки на физическом B2;
- правила распознавания с указанием необходимого доказательства;
- известные альтернативные параметры того же оператора и порядок проверки;
- ограничения применимости (тариф, регион, тип SIM/устройства).
Публичная документация оператора не означает успешного испытания данного
тарифа на модеме B2. Требуемые оператором параметры, которые наш интерфейс
устройства пока не умеет задавать, должны оставаться явно не квалифицированы.
Редактор в Mission Core должен создавать новую редакцию, позволять добавить
собственную запись и вернуть предыдущую. Пользовательские/корпоративные
пароли хранятся приватно, отдельно от общих переносимых профилей.
Обновление общей базы не затирает собственные настройки организации и не
перезаписывает немедленно работающие трекеры.
Созданная операция содержит снимок выбранных параметров и редакцию каталога.
Редактирование справочника не меняет содержимое уже ожидающей команды.
Изменение назначения SIM делает старую операцию неприменимой к новой карте;
отложенная команда не должна следовать за номером слота на другую SIM.
## Первичные источники для первоначального наполнения
Параметры ниже — кандидаты для справочника; полный цикл на B2 для всех этих
операторов не проверен. Это не перечень автоматически распознаваемых SIM.
| Оператор | Опубликованный APN | Учётные данные | Источник |
| --- | --- | --- | --- |
| МТС | `internet.mts.ru` | публичные `mts` / `mts` | [МТС, настройки интернета](https://support.mts.ru/mts_mobilnyy_internet/nastroiki-mobilnogo-interneta/kak-nastroit-internet-na-telefone) |
| МегаФон | `internet` | действующий пресет: публичные `gdata` / `gdata` | Существующая квалификация и источник в `connectivity.py`; не переопределять по данным других операторов |
| билайн | `internet.beeline.ru` | публичные `beeline` / `beeline`, PAP | [билайн, ручные настройки](https://moskva.beeline.ru/customers/support/mobile/mobilniy-internet/nastrojki/nastrojka-telefona/) |
| t2 | `internet` | пустые | [t2, Android](https://msk.t2.ru/help/article/android-setup) |
| Т-Мобайл | `tt` | без авторизации по инструкции активации | [Т-Мобайл, активация SIM](https://www.tbank.ru/mobile-operator/help/communication/sim-card/start-using/activate-sim/) |
| Yota | `internet.yota` | пустые | [Yota, проверка интернета](https://www.yota.ru/support/mobile/ne-rabotaet-internet-apn) |
В официальных материалах также встречаются `internet.t2.ru` для
[Windows Phone](https://msk.t2.ru/help/article/winphone-setup) и `m.tinkoff` на
[странице eSIM](https://www.tbank.ru/mobile-operator/sim/esim/). Эти различия
нужно сохранить как различия источников/применимости, не объявлять универсальными
резервами для любого тарифа. Приоритет — конкретная актуальная инструкция,
затем подтверждение реальным подключением. Отдельного испытания с этими SIM
в текущем оборудовании не было.
## Кто выполняет подбор
| Размещение исполнителя | Что возможно | Граница |
| --- | --- | --- |
| Прошивка B2 | Автономно восстановить интернет при питании от адаптера | Сначала подтвердить нативную функцию и её точные параметры; загрузка нашего справочника/исполнителя штатным API не установлена |
| Локальный компьютер, USB с данными | Хранить каталог офлайн, читать устройство, применять и проверять кандидатов без мобильного интернета | Нужны достаточные данные о SIM и квалификация полного цикла; Mac-адаптер ещё не означает поддержку Node/Linux |
| Только VPS | Настраивать доступный B2 и выдавать актуальную базу клиентам | Если единственный канал B2 уже не работает, этот же канал не доставит исправление |
| Независимый SMS-канал | Возможный отдельный способ начальной настройки/восстановления | Требует работающих SMS, адресации SIM и отдельного исполнителя; инфраструктура не реализована и не квалифицирована |
USB в блок питания не создаёт исполнителя или канал данных к нашему ПО.
Для основного сценария самостоятельного B2 нельзя скрыто вводить обязательный
бортовой компьютер. Если нативного режима нет, это реальная граница выбранного
железа: необходим независимый канал настройки или изменение прошивки/оборудования.
Коммуникационная архитектура сохраняется: Core обращается к VPS и опрашивает
его; VPS не подключается входящим соединением к Core. B2 сам открывает свой TCP.
Каталог кэшируется на локальном исполнителе до исчезновения мобильной связи.
## Предлагаемый алгоритм
1. Получить свежие сведения о карте, слоте, регистрации и доступном канале
управления. Не считать отсутствие свежей телеметрии доказательством замены SIM.
2. Если доказательств недостаточно, показать неопределённость. Код базовой сети
может сузить кандидатов, но не даёт права уверенно назвать MVNO или тариф.
3. Для подтверждённой той же карты сначала использовать ранее проверенный
вариант. Затем — применимые записи из кэша каталога. Не перебирать всех
операторов подряд; корпоративные параметры не угадывать.
4. До записи сохранить исходную конфигурацию, намерение, редакцию каталога,
сведения о карте и стадии попытки. По устройству работает один исполнитель.
5. Применить только необходимые поля и проверить чтением. Число попыток и
таймеры ограничены; конкретные значения определяются аппаратными испытаниями.
6. Проверить свежую связь именно этого B2 с нашим VPS. Запись APN, регистрация
в сети или индикатор GPRS сами по себе не означают успех. Нет регистрации
в сети — сначала диагностика сети, а не циклическая смена APN.
7. После разрыва/перезапуска прочитать состояние и продолжить журнал. Если
запись могла состояться, сначала сверка факта, затем решение о повторе.
8. При неуспехе сохранить причину и восстановить прежнюю конфигурацию через
доступный независимый канал. Не обещать удалённый откат по исчезнувшей связи.
Кэш успешных настроек переносится вместе с доказанно той же картой, а не с
номером слота. Нельзя строить глобальную идентичность SIM из усечённого SID.
Наблюдения идентичности должны различать сырой ответ модема CCID, SID прошивки,
IMSI, домашний код сети и обслуживающую сеть, а также слот, сеанс запуска,
источник и время. Не подменять один источник другим и не нормализовать `ff`
без квалифицированного правила. При двух SIM короткий ответ `I 7` не должен
затирать полный исходный снимок или подтверждать, что SIM после перестановки
осталась той же. Для разрешения записи нужны согласованные свежие доказательства.
## Порядок реализации и приёмки
Сначала закрыть возможность исполнения и идентификации: нативный режим B2
либо доступная до интернета локальная диагностика. Затем реализовать редактор
и версии справочника, после — автомат состояния и интеграцию с журналом команд.
Не выдавать расширение списка ручных пресетов за завершённый автоподбор.
Аппаратная приёмка: одна известная SIM в обоих слотах, замена на другого
оператора, неизвестный/неполный идентификатор, отказ регистрации, неверный APN,
разрыв после записи, перезапуск во время попытки, обновление каталога при
ожидающей команде и восстановление без связи с VPS. Проверять сохранность
другой SIM, адресов серверов, устройства/ровера и существующих намерений.
Других SIM и массового парка сейчас нет; их физическую приёмку не заявлять.
+937
View File
@@ -0,0 +1,937 @@
# B2 autonomy and command delivery
[Подтверждения B2 и граница рантайма, Host 0.1.31](TRACKER_CONFIRMATIONS_20260927.md)
Owner scope, 2026-09-26: telemetry, complete configuration, device admission and
commands must operate through the owner's VPS, without an ARNavi/Gelios account.
USB is a bootstrap/recovery transport. This includes independently assigned
trackers, several per apparatus, reusable non-identifying profiles and a
reproducible VPS installer. Relay latency is additional scope, not a substitute
for full configuration.
Current qualification, 2026-09-27: telemetry and selected commands work through
the owned VPS, but repeated remote configuration is **not yet reliable**. The
two-SIM regression below verified one write, then failed the network restoration;
USB restored and independently verified the exact baseline. Earlier successful
roundtrips remain bounded evidence, not general reliability acceptance.
The [2026-09-27 coverage and recovery audit](CONFIGURATION_COVERAGE_20260927.md)
adds an offline, value-redacted coverage checker and fixes bootstrap admission
for the shipped VPS 0.1.26. It confirms 78 editable scalars in the 207-record
physical image. Its new write succeeded; power cycling did not resolve the
failed network restoration. USB subsequently restored the exact baseline,
including field 25 = 15, with independent readback. The
[Host 0.1.27 readiness qualification](OUTBOUND_READINESS_20260927.md) adds guarded
session admission, but does not establish full configuration reliability.
The [Host 0.1.29 clock/freshness follow-up](CONFIGURATION_CLOCK_AND_FRESHNESS_20260927.md)
qualifies our own opcode-7 time response and fresh-stream configuration admission.
A subsequent physical write applied, but post-write network verification failed;
USB restored the exact baseline again. Full remote reliability remains open.
The [Host 0.1.30 recovery qualification](RUNTIME_RECOVERY_20260927.md) preserves
verification of an already committed full-image write through VPS process
restart and a new B2 connection. Only readback resumes; effects do not replay.
Linux SIGKILL/loopback qualification passed. Physical modem recovery and
continuous USB-only power remain separate, unaccepted gates.
## Two independent device channels
The qualified B2 231 / 0.01 has four monitoring slots and a separate configuration
service. Moving monitoring slots alone does not remove the manufacturer's
configuration dependency.
- Monitoring: INTERNAL over TCP. The owner's receiver can send an asynchronous
command while the TCP session is open; it need not wait for the next GNSS point.
- Configuration service: ordered binary settings fields 70 (host) and 71 (port),
interval 62 and startup bit in 72. A real redirected request used HTTP
`POST /c/index.php`, a binary body, and a keep-alive connection. It is not the
TLS management API used between Core and VPS.
- Device envelope: `5b 01 LEN:u16be IMEI:u64le 00 01 e7 02 00 00 OP PAYLOAD 5d`.
LEN is the body length minus five. Metadata is admitted only for model 231,
firmware 0.01. OP 6 identifies the exchange, OP 5 uploads the full image,
OP 2 requests a new image.
- Server envelope: `5b LEN:u16be 00 OP PAYLOAD 5d`, LEN = body length minus four.
Captured OP 6 answer is `5b00030006025d`; captured upload acknowledgment is
`5b00030005015d`. The earlier inferred six-byte upload ACK was rejected by
the bench and is not used. OP 2 carries the complete CRC-checked configuration.
Reference framing was captured in three explicitly owner-authorized diagnostic
requests. The last returned the manufacturer's own previously downloaded copy
byte-for-byte; current owner-VPS settings were not uploaded to the manufacturer.
Those reference requests are engineering evidence, not a runtime dependency.
The release has no vendor client, proxy, login or vendor API call.
Initial USB provisioning sets the selected owner VPS in primary monitoring slot
1, recovery slot 2 and configuration fields 70/71 in one backed-up whole-image
transaction. Core admits the device to that paired, assigned VPS first. Firmware,
instance credentials, SIM identity, periodic interval and unknown fields remain intact.
The accepted 0.1.23 bootstrap clears only the startup-check bit, as qualified below.
Existing optional monitoring slots 3/4 are preserved and must be reviewed when
migrating a device that already uses them; the qualified bench has both disabled.
The component operations are physically qualified; the newly composed bootstrap
is covered by synthetic transaction tests, not a factory-fresh physical-device run.
A separate authenticated engineering observation lease remains bounded to 180 s,
four 16-KiB captures and 64 retained leases. It is disabled during normal product
operations and does not expose raw traffic to the browser. No transparent proxy
or guessed response is needed by the production settings path.
## Command contract
The manufacturer INTERNAL specification documents an asynchronous binary frame,
`FF token:u32le command`, with response packet type 09 (code + token). The B2
manual §10 identifies physical outputs as PIN4..PIN6. Older generic INTERNAL
examples use other output indexes and must not override the B2 mapping.
VPS 0.1.8 adds a narrow, authenticated API allowlist:
| Operation | Documented wire definition | Behavior |
| --- | --- | --- |
| Request position | `01 01` | Ask for an immediate telemetry packet |
| Pulse output | `18 PIN 00 seconds` | PIN4..6, 1..5 seconds; no persistent latch |
| Read settings | Password + `*GETP` in FC | Existing read-only evidence path |
| Change server 1 | Documented SETP #1, GETP before/after | Existing endpoint-only transaction |
Binary actions require a currently connected admitted device, expire for dispatch
after three seconds, and can be sent only on a session that existed when queued.
They never wait indefinitely for an offline tracker. Dispatch is committed before
writing the socket. A dispatched action is never replayed; a queued action expires
on service restart. A lost reply is not evidence that the physical action failed.
The response deadline is thirty seconds. Only a matching token on the selected
session is accepted. Code 6 means accepted for later execution, not completion;
code 0 is device confirmation, not independent proof of relay contact state.
The API immediately wakes the sender after durable submission; a one-second
maintenance timer remains for settings stages. Packet acknowledgement, command
confirmation and observed output state are separate evidence. GNSS fix is not a
prerequisite for communicating with an online modem.
## Physical interfaces and limits of inference
Primary source: [B2 manufacturer manual](https://8888.arusnavi.ru/Arnavi%20B2/).
The 16-pin connector exposes power, configurable inputs/outputs, RS232, RS485,
1-WIRE and CAN. CAN2 shares pins with RS485; these are not independent simultaneous
resources. The manual describes three low-side outputs, with mode 1 for command
control, mode 22 for speed/belt/light control and mode 23 for speed-bounded blocking.
A CAN connection and a program number do not establish permission or capability to
command arbitrary vehicle brakes. Device telemetry about an output is not proof
that an external relay/contact/controller actually changed state.
The owner explicitly confirmed that the two relay boards are disconnected from
the former engine/speed-sensor/limiter circuits and can be checked with LEDs.
Bench qualification must record each physical PIN, wire command, receipt, device
state and observed LED/contact response; no live vehicle actuation is implied.
### Bench observation, 2026-09-26
The owner observed no LED transition for a two-second PIN4 binary pulse and a
five-second PIN5 binary pulse. One board LED stayed on and the other stayed off.
Both commands produced code-0 token replies (1.818 s and 5.933 s roundtrip), which
therefore do not prove physical switching. Telemetry before/after reported an
external supply near 12.48 V and discrete mask 0x0041; roughly 15-second sampling
did not cover the pulse interval. The photographs do not establish the boards'
identity, wire-to-PIN mapping, or meaning of each LED.
VPS 0.1.9 permits an explicit FC text encoding of the same bounded pulse, following
manual §10 (`password*SERV*24.PIN.0.seconds`). PIN and duration limits, current
session requirement, dispatch expiry and no-replay rules remain unchanged. Only
this generated text is accepted; credentials never appear in public receipts.
There is no token-confirmation mechanism for FC: unrelated replies cannot turn
it into success. Text delivery remains unconfirmed pending independent evidence.
The text comparison on the same PIN5 subsequently produced an operator-observed
transition: the previously unlit board LED turned on and then off. The requested
duration was five seconds; physical latency/duration were not measured. This
qualifies that one visible board response on model 231 / firmware 0.01, not both
boards, electrical contacts, generic binary control, or arbitrary firmware.
Telemetry still did not sample the pulse interval. A seven-byte text response
arrived, but its interpretation/correlation is not yet qualified, so the API
correctly retained `unconfirmed`. The confirmed physical observation is separate
operator evidence; do not silently promote uncorrelated protocol receipts.
## Camera qualification of the disconnected bench, 2026-09-26
The owner authorized repeated camera-observed tests. MacBook FaceTime video
established the spatial mapping: the upper board LED is controlled by PIN5;
the lower board LED remained lit. No vehicle mechanisms were connected.
- The FC text PIN5 five-second pulse lit the upper LED for 5.0 seconds at
10-frame/s analysis resolution (video positions 19.7–24.7 seconds).
- VPS 0.1.10 adds allowlisted `set-output`, manual section 10
`password*SERV*8.PIN.STATE`, PIN4..6 and strict boolean `enabled`. This is an
explicit persistent state, not a pulse. It keeps active-session binding,
three-second dispatch expiry, no replay and private password handling.
- Explicit PIN5 on and off both changed the upper LED, confirmed on video.
PIN4 and PIN6 on/off changed their corresponding TAG6 bits but produced no
visible transition on either board. In the recorded sequence, masks changed
0x0001 → 0x0041 (PIN6) → 0x0051 (PIN4) → 0x0071 (PIN5). The reverse commands
restored 0x0001. The upper LED was off and the lower LED still on at handoff.
- A `SERV OK` text reply and output-bit change are useful separate evidence;
the generic command receipt still does not invent token correlation or
physical confirmation. The lower board may have a power indicator or a
different wiring path; neither interpretation is established. Close inspection
of its wiring/labels or an electrical measurement is needed before more tests.
- Video timestamps are relative; file creation UTC is rounded and was not
independently synchronized with server dispatch. No precise millisecond
latency or relay contact behavior is claimed.
Both private videos, sampled LED counts, command manifests and redacted
telemetry have recorded SHA-256 evidence outside Git. Firmware and configuration
fields were unchanged during this bench run. The new VPS artifact passed 50
focused VPS tests, was reproduced twice, installed through the shipped installer,
and published in the Core installer catalog. At that release full configuration
was still pending; the later acceptance is recorded below.
## Remaining autonomy acceptance
### Mission Core command surface accepted, 2026-09-26
The existing B2 settings window now contains a Commands section: request position,
explicit output on/off and a five-second pulse. This is domain content in the
existing FeatureSettingsWindow composition (novelty A), using canonical Select,
SettingsCard, StatusBadge, Button and WindowFooterActions. A separate workspace
was rejected: these occasional actions belong to one already enrolled device,
with its identity, assignment and operation lock. No new product root is added.
Only the qualified firmware/host combinations are admitted. Existing enrollment
snapshots provide output modes without reconnecting USB, without altering the
snapshot date or implying a fresh configuration read. Commands are separate from
desired policy and profile application. Pending, disconnected, incompatible and
unsaved-change states explain why actions are unavailable. Lost requests keep the
durable operation ID; output commands never repeat automatically.
TAG6 mode 1 provides PIN4..6 logical states independently of GNSS. The Core decoder
handles repeated TAG6 instances (analog/frequency tags cannot hide discrete
states), stores observations transactionally with the pull cursor, rejects older
state overwrite and hides state outside the currently assigned host contour.
The UI labels stale observations, keeps output feedback separate from command
receipts and never animates a successful output change optimistically.
Acceptance on the real enrolled B2 used the UI's Request position button through
VPS 0.1.10, with USB physically unplugged as confirmed by the owner. The VPS queue
was 0.004319 seconds; matching device code 0 arrived 1.838826 seconds after socket
dispatch. These are VPS-local measurements, not physical actuation latency or a
cross-machine end-to-end benchmark. No output command was sent in this UI run.
All outputs remained logically inactive. The accepted endpoint remains visible
after subsequent commands, even when the last command replaces the operation card.
Validation: architecture checks, full TypeScript checking, 990 frontend tests and
production build; focused backend checks cover strict inputs, output mode gates,
version/offline rejection, no replay, secret projection, late/out-of-order packets,
transaction rollback, assignment scope and legacy enrollment projection. Browser
QA checked real feedback, disabled actions while pending/dirty, dropdown, Escape
and right-aligned footer actions. Private evidence is retained outside Git.
### Whole-configuration path, 2026-09-26
VPS 0.1.15/0.1.16 adds `read-configuration` and `configure-all` through the paired
TLS API. The tracker receives documented `password*SERV*1.9` (upload) and
`password*SERV*1.8` (download) through INTERNAL. The HTTP channel checks admitted
IMEI, model/firmware framing, CRC, size limits and the active modem peer. This is
legacy device identity plus network correlation, not cryptographic device
attestation; a modem using different CGNAT egress for the two sockets is not yet
qualified. Core-to-VPS authentication and certificate pinning remain separate.
Before a write, the VPS obtains the complete current image and compares its hash
with Core's predecessor. Critical password/recovery/configuration-service fields
cannot change in this operation. Core overlays only reviewed portable settings;
record order, missing fields, unknown settings and unique values are preserved.
Only one image reply is sent. A new upload independently verifies the exact image;
SERV OK, TCP acknowledgment and a successful API request are never write success.
Restart or timeout after dispatch produces an explicit uncertain/unconfirmed
outcome and never silently resends the write. Core privately retains the image
and identity-source provenance, and does not pretend SIM identity was refreshed
by a settings upload. The browser receives summaries, not configuration bytes.
Physical bench evidence with USB unplugged:
- Full read returned 207 records / 983 bytes, byte-identical to the USB baseline.
- A change to field 25, stationary interval 15 -> 16 seconds, was verified by a
separate full read. The other 206 records remained byte-identical.
- Return to 15 seconds restored the exact original full image. The same behavior
was exercised through the canonical Core API, not only an engineering helper.
- On 0.1.15 one preflight timed out without an image write; a later write succeeded
in about 29 s. A subsequent download request was TCP-acknowledged but produced
no download, so restoration was not falsely marked successful.
- 0.1.16 adds 15 s between settings stages/adjacent settings operations. The
original image was restored through Core in about 51 s. This pacing applies
only to full settings, not position/output actions. These are individual bench
timings, not a latency guarantee or evidence of thousand-device capacity.
- The final 0.1.16 UI Save settings action repeated 15 -> 16 -> 15 with
independent verification in both directions and an exact restored image. The
downloadable installer bytes match the qualified installed artifact.
- Final 0.1.16 UI Request position regression: queue 0.003744 s, matching
device confirmation 1.662265 s after socket dispatch. This is protocol
confirmation, not physical relay latency.
- Browser acceptance also showed the current B2 GNSS marker in the expanded
Rover observation map with the onboard Node offline; 12 satellites reported.
- Live position, logical output feedback and both own monitoring endpoints stayed
available. Firmware was not updated and no output actuation was needed.
The same deterministic single-file installer is used for qualification and
operator download. The profile editor applies over the network and retains
separate saved/confirmed states; no USB is required for this enrolled device.
The portable catalog intentionally covers reviewed settings, not every raw field
or every accessory shown in the manufacturer's configurator.
### Remaining scope and limits
1. Factory-fresh physical bootstrap and power-cycle persistence, including SIM
provisioning and devices with existing optional monitoring destinations.
2. Controlled migration of the recovery/configuration endpoint to another VPS;
changing server 1 alone deliberately retains the old recovery channel.
3. Mapping and device qualification of remaining configuration fields and
peripheral protocols (CAN/RS485/RS232/1-WIRE/BLE), remote firmware lifecycle
and protected credential rotation. Full-image transport is not proof of all
these device capabilities.
4. Batch enrollment, restart/offline recovery and capacity qualification on a
suitable worker before claiming a thousand-device deployment.
5. Physical relay/contact latency and local speed-limiter behavior remain
separate work; the owner stopped the miswired LED investigation.
A geofence control policy must also define position freshness, out-of-order packet
handling, boundary hysteresis, loss of connectivity, command expiry, priority,
operator cancellation and the actual limiter interface. A cellular roundtrip has
no hard deadline. Do not implement immediate braking by blindly replaying a stale
"inside zone" command after reconnect. Local enforcement is an independent device
capability to qualify, not an assumption from a server polygon.
### Remote restart and return observation, 2026-09-26
VPS 0.1.17 adds a bounded `restart` command for model 231 / firmware 0.01,
using the B2 manual §10 binary `01 07` under the existing token envelope.
The request has the same three-second dispatch deadline and durable no-replay
rule as other actions. Its return-observation window is 180 seconds. A token
code 0 or 6 is recorded as acceptance and does not complete the operation.
Return is observed only after a new TCP session starts after dispatch and sends
valid type-1 telemetry measured after dispatch (at most five seconds ahead of
server time). Both pre-existing monitoring sessions, new headers alone, old
archive points, text replies and unrelated token responses are insufficient.
The final state is `reconnected`, deliberately not a claim of CPU restart or
hardware power-cycle proof. Timeout reports unconfirmed return; VPS restart
reports an uncertain result; neither resends the command.
The existing Commands page uses canonical SettingsCard/Button components and
separates request acknowledgment timing from time to fresh data on reconnection.
Core requires the matching VPS release and preserves the saved profile state.
Synthetic checks cover old/secondary sessions, stale and future timestamps,
unregistered sessions, text-only replies, expiry, service restart, idempotency,
private wire projection and Core/HTTP/frontend state semantics.
Initial restart qualification (before the startup-check correction below):
- A UI-issued restart on 0.1.17 returned fresh telemetry on a new connection
after 53.225900 seconds. No USB, firmware update or output actuation was used.
- The pre-restart configuration was 207 records / 983 bytes. Two subsequent
full reads timed out while telemetry continued. No settings image was sent,
and persistence must not be claimed from the retained Core cache.
- Bounded captures showed settings-upload commands acknowledged with SERV OK,
but the HTTP channel issued empty command-2 requests instead of an upload.
The documented binary 0109 produced the same behavior as SERV 1.9.
- A one-shot empty command-2 response (0.1.19 engineering lease) advanced the
device to an empty command-1 request. A one-shot empty command-1 response
(0.1.20 engineering lease) did not complete the exchange: command 1 repeated.
The empty reply did not establish its meaning. Neither response contains a settings or
firmware image. These hypotheses are not admitted in the product handler.
- Each experiment retains timestamps, private capture bytes and SHA-256 hashes;
the observation leases were explicitly closed. Position reception remained
available. Completion requires a fresh device upload after restart, not a
restore/write of the old image followed by reading it back.
- While this configuration exchange was unresolved, a product-UI position
request on 0.1.20 was token-confirmed after 1.314065 seconds (queue 0.005 s).
The separate monitoring command channel stayed functional. Core compatibility
and the production UI build were updated and the canonical 8000 service was
health-checked. The 0.1.20 artifact remains an engineering qualification
release; the operator download at that point remained 0.1.16.
- Automatic approval review initially rejected a reference command-1 request.
After the owner's separate scoped authorization, exactly one 20-byte
identity/version request ran. It contained no configuration or passwords.
The saved response was not automatically forwarded to the device.
### Startup-check correction and accepted Host 0.1.23
The ten-byte reference reply contains the existing four-byte numeric device ID,
independently observed during USB enrollment. Host admission now carries that
known ID. The host never derives it from the IMEI, generates a replacement ID,
or asks the manufacturer for it. Numeric ID association is immutable per IMEI;
a conflicting admission fails atomically. Old Core callers that omit the ID do
not erase an established mapping. Removal from admission also removes reply
authority, while retaining identity history for later re-enrollment.
A one-shot numeric-ID reply advanced the device from command 1 to command 2.
However, empty command-2 responses produced a repeated 1/2 exchange rather than
completion. The 0.1.22 combined experiment was rejected. Host 0.1.23 retains only
the independently known numeric-ID reply. It serves a settings image only for
an explicit bounded write; it does not rewrite a cached image on startup.
No runtime manufacturer calls exist.
A bounded capture of the first request after another restart showed an empty
settings-download request (command 2). Fresh telemetry returned after 123.9333 s.
The next experiment explicitly wrote the backed-up full configuration with
**only field 72 bit 0 cleared**, the manufacturer's “check at every start” flag.
All other bits and all other 206 records were retained, including field 62's
value 150 (the public schema labels this interval in hours; physical units have
not been calibrated). Its zero-value semantics were not qualified and were not
changed. This recovery write is separate from reading; it does not prove that
the pre-recovery original image survived the preceding restart unchanged.
Physical acceptance, USB unplugged, model 231 / firmware 0.01:
- A separate product read after the flag change returned all 207 records /
983 bytes, exactly matching the target image.
- One new restart returned fresh telemetry on a new connection after
**71.176131 s**. An independent full read after that restart again matched
the target byte for byte. No configuration was written during this restart
qualification and no output was actuated.
- The canonical Mission Core UI then read the same 207 records through VPS;
its newly persisted evidence also matched the target byte for byte.
- A UI-issued coordinate request was token-confirmed **1.456098 s** after
socket dispatch. This measures protocol confirmation, not relay switching
or a guaranteed cellular deadline.
- A final UI Save settings roundtrip changed field 25 from 15 to 16 seconds,
then back to 15. Both operations were independently verified from all 207
records, in 41.410 s and 41.379 s including the deliberate
settings-channel pacing. All other 206 records stayed unchanged, and the
final image exactly matched the accepted post-restart target. Startup checks
stayed disabled throughout; settings writes did not re-enable them.
- Initial USB bootstrap now sets both monitoring destinations and the
configuration endpoint to the selected owned VPS, and clears only the
startup-check bit. Missing/malformed flags reject before any USB write.
Portable profile saves and ordinary remote writes preserve these flags.
Physical factory-fresh USB bootstrap remains a separate acceptance case.
The accepted installer is immutable Host **0.1.23**, SHA-256
`97abb7a869f86debe885e5130dd14791ac7ed0dfea99f9ee75c64bfb229559d0`.
It was reproduced from the source with the same tar, installer and manifest
hashes as the installed release, then published in Mission Core. Node was not
updated. Release README entries are the historical qualification state at build;
this section records subsequent bench acceptance without replacing the artifact.
Private evidence sessions (outside source control):
`startup-pull-disable-ef4f81c06bb549a59d3bf61fe1738884` and
`startup-disabled-restart-d4508839ef4f487ba22301f7f90ce456` retain before/target,
readbacks, operation receipts, UTC/monotonic times and hashes. The original
restart and failed startup exchanges remain retained, not overwritten.
Remaining startup scope: periodic background checks and a safe no-update reply
have not been qualified. The full original image was deliberately changed by
one flag, so this result must not be presented as unchanged-original persistence
or complete device lifecycle autonomy. Factory reset, physical power cycling,
remote firmware, credentials and peripheral protocols remain separate gates.
### Background-check parameter: negative qualification, 2026-09-27 operator time
Exactly one newly owner-approved command-6 reference request returned the same
seven-byte body as the original reference. No configuration or password was
included, no response was automatically forwarded, and this consumed the scoped
authorization. It does not establish a neutral/no-update response. The owned
runtime remained Host 0.1.23 throughout the following tests.
The public type-231 schema exposes field 62 as a two-byte integer with range
0..65535. Three individually backed-up network experiments tried values **1,
151 and 0**, from the same freshly read value 150. The complete CRC-valid target
image was observed leaving the VPS in each case. Each independent command-5
readback returned the exact original 207-record image, including field 62 = 150.
The product reported `not_applied`, not success. No accelerated periodic-check
window started because no candidate interval was actually retained.
A positive control changed field 25 from 15 to 16 and back to 15 using the same
full-image API, peer admission, write/readback sequence and live firmware. Both
directions were verified. This narrows the failure to the tested period changes;
it is not evidence that all field-62 values are unsupported, that zero disables
anything, or that the actual timer uses the units in the current public schema.
The exact firmware restriction and whether USB behaves differently remain open.
Do not add field 62 to portable profiles or clear it in bootstrap on this evidence.
Final canonical Core read returned all 207 records, byte-identical to the accepted
startup-disabled baseline. A Core-issued position request was token-confirmed in
**2.104986 s**, with **0.004595 s** VPS queue time. No output, firmware, Node or
VPS-runtime change occurred. The five explicit configuration-image transmissions
were the three period candidates and the positive control with restoration;
none was an unsolicited background response.
Private evidence session `periodic-check-eb630dc8b6b04b1daf4ece0f597bed71` retains
the baseline/candidates, separate preflight and verification receipts, UTC and
monotonic timestamps, a bounded packet capture and redacted CRC-checked HTTP
event table. Core read evidence is in `core-flow-c3dd8d4cad164ce594aae15e13ab032d`.
The capture completed with no kernel drops and was stopped explicitly. New
synthetic regressions ensure unchanged and partial readbacks cannot become
successful writes or be replayed after a duplicate request or service restart.
Next discriminating experiment requires the owned B2 on USB: compare one fresh
USB field-62 write/readback with the network behavior, preserve all other records,
and restore the exact baseline. Until that or protocol evidence resolves the
background path, complete lifecycle autonomy remains unqualified.
### USB comparison and repeated telemetry, 2026-09-27
After the operator reconnected the cable, macOS enumerated the qualified Artery
CDC interface. The identity-bracketed USB read returned model 231 / firmware
0.01 and the exact accepted 207-record, 983-byte baseline, SHA-256
`a3b52af5900740cce3eae4db31390a2c2887ba59c7fab99e50595f7e3a48b7ae`.
One backed-up USB transaction changed only field 62 from 150 to 1 in the
transmitted image. The device returned `SR=1`, but the transaction's configuration
readback and final identity check established `not_applied`: all original bytes
remained. The immediate separate snapshot timed out during its final identity
read and was retained as failed evidence. A subsequent complete independent
snapshot succeeded and again matched the original image byte for byte. No
restoration write was necessary. Thus this tested rejection also occurs through
USB; it is not confined to the owned VPS transport. It does not establish the
firmware's reason, the accepted range, timer units or zero-value semantics.
A separate 16-second passive capture on the owned receiver port established
that the tracker still completed INTERNAL identification and sent two valid
eight-packet packages, both numbered 39. Each payload exactly matched an earlier
Core receipt. The VPS sent the corresponding package acknowledgments; the trace
also contains acknowledgment retransmissions and reconnects. The Core's old
telemetry timestamp therefore did not mean the tracker made no connections:
these were duplicate stored payloads, not fresh measurements. One canonical
Core position request was dispatched with 0.004706 s queue time and ended
`unconfirmed` after approximately 35 s. No fresh position or successful command
delivery is claimed. This capture alone does not locate the underlying fault
among the cellular path, modem handling and device acknowledgment processing.
Later, additional packages advanced the Core receipt timestamp and temporarily
made the device online. The latest inspected payloads still contained historical
measurements. This new arrival justified one further position request, retained
separately: it also ended `unconfirmed` after approximately 35 s (queue
0.006464 s). Packet arrival is therefore not acceptance of fresh navigation or
reliable bidirectional commands.
Private session `usb-period-compare-0a184b850292413c961163d4b141398d` retains
the before/readback images, the one USB write receipt, the failed and successful
independent reads, the position receipt and the bounded packet capture.
Capture SHA-256:
`9112cc11e8fb51bfcd22fc6fad66623b2b0944a4b5f3297a492a7aa57b0adc3f`.
The capture stopped at its deadline with no kernel drops; no remote file was
created. Settings ended unchanged, including the disabled startup check.
No firmware, outputs, manufacturer requests, Node update or VPS runtime change
occurred. USB communication is available; stable network exchange and the
background-check lifecycle remain unresolved acceptance gates.
### Correlated modem capture and USB recovery restart, 2026-09-27
Simultaneous passive USB diagnostics and a 40-second receiver-port capture
narrowed the stalled exchange. Three distinct nine-byte HEADER2 replies from
the owned VPS appeared byte-for-byte in the modem's `RXGET` diagnostic stream.
The corresponding four-byte acknowledgments for package 45 matched the public
SERVER_COM format, but none appeared in that same diagnostic capture. The VPS
retransmitted those four-byte TCP segments; a read-only `ss -tin` inspection
also showed four unacknowledged bytes on established connections, nonzero
receive windows and repeated retransmissions. This is stronger evidence than
an application command timeout, but does not identify which network component
or modem behavior caused the missing transport acknowledgment. In particular,
absence from a diagnostic stream alone is not proof of modem non-reception.
The server/Mac clock sample had approximately one second of roundtrip
uncertainty; do not use these two capture clocks as a precise latency benchmark.
For a bounded recovery comparison, the official configurator was inspected
statically again, without executing it. The `act_Reboot` registration at
0x77af33..0x77af4f uses literal `>D 1\r\n` at 0x77b558 for the same model range
5..249 as the already qualified SettingsGet action. The existing executable
SHA-256 was verified against the USB bootstrap reference. Exactly one six-byte
USB restart request was issued after a new identity-bracketed backup, exact
baseline comparison and a check that startup configuration pulling remained off.
No configuration, firmware or output command was sent.
The device returned with a new USB session and reset diagnostic uptime.
Independent identity and full configuration reads matched the pre-restart
snapshot exactly. This qualifies the observed USB software restart on model
231 / firmware 0.01; it is not a power-cycle or factory-reset test. Network
observation through approximately 193 seconds after dispatch did not produce
a fresh position. A subsequent simultaneous capture retained modem connection
attempts, while the 25-second VPS capture contained only four outgoing FIN/ACK
segments from older connections: no new incoming handshake or application
payload was observed in that window. No automatic restart retry ran.
Evidence sessions, outside source control:
- `link-correlation-73311b9599a24aa8aca14f592c01c85b`: passive before-restart
USB/network captures and exact reply-byte correlation.
- `usb-restart-recovery-94928ea71d7b4e6b8adb09614a37ec3b`: source qualification,
backup, one-shot transmission receipt, new-session/configuration verification
and bounded network-return observations.
- `post-restart-link-correlation-1d895d107a5c4e508f4bc04c0aaa1f10`: passive
post-restart modem and TCP observations.
Both packet captures stopped at their deadlines with zero kernel drops. Host
0.1.23, Mission Core and the device configuration were retained; no vendor query,
Node update or VPS runtime change occurred. The next independent control is the
current SIM's mobile-data operation or a known-working alternative SIM. Carrier
failure, device firmware failure and complete lifecycle autonomy are not yet
established by this evidence.
### Two installed SIMs and recovered exchange, 2026-09-27
The owner retained the personal MTS SIM, inserted a different MegaFon SIM and
reported disconnecting/reconnecting external power. A fresh identity-bracketed
USB read recognized both reported SIM identifiers; slot 1 changed and slot 2
matched the prior observation. Full configuration remained exactly the accepted
207-record, 983-byte baseline. APNs were `internet` and `internet.mts.ru`; neither
SIM's GPRS-disable flag was set. No settings were written. Reported identifiers
remain device observations, not full independently verified ICCIDs.
Diagnostic uptime advanced through 722–807 seconds, consistent with the earlier
qualified software restart. Therefore this external-power interruption is not
accepted as a full restart or power-cycle persistence test; USB remained attached.
The B2 manual documents two SIM holders and two-operator support, but does not
specify simultaneous independent data sessions or an automatic watchdog policy.
This test does not qualify either behavior.
A new 40-second VPS capture and simultaneous 45-second passive USB capture
recorded 67 valid incoming packages. All 68 captured four-byte outgoing package
acknowledgments had exact byte matches in the USB diagnostic stream, as did the
one captured HEADER2 acknowledgment. Historical package numbers advanced instead
of remaining on the earlier repeated payload. The capture observed one incoming
public peer address; it does not independently identify the active carrier or
establish failover behavior. Three payload retransmissions were still present.
The passive capture stopped at its deadline, with no kernel drops.
The first canonical Core position request, while archive drainage was underway,
was dispatched but remained `unconfirmed` after 36.82 seconds. Subsequently Core
reported online with a fresh position measured approximately nine seconds before
the check. This changed state justified one separately recorded new request.
The second request completed `device_confirmed`, code 0: VPS queue 0.005224 s,
measured device roundtrip 1.135291 s, and locally observed end-to-end operation
completion 8.606640 s. These are different clocks/intervals; UI completion is not
the radio roundtrip. No automatic replay of the first request occurred.
Private evidence sessions:
- `dual-sim-observation-c5c822f9f2c344d2ad21cb2d06de394d`: fresh USB read,
configuration comparison, both separate position receipts and fresh telemetry.
- `link-correlation-5298fe9e87004db3881db8c0c3ab6553`: correlated passive capture;
network SHA-256 `20e5bc63a4d153c2dac4a444e49c928a4486714b74e2c0f1d8fb8f872bb50e8b`,
USB SHA-256 `ff419027c925db29ad34b007bf94b035429a9195d25ce9b1fab9ea4ef2ca5ab2`.
Network telemetry and one confirmed command recovered without configuration,
firmware, manufacturer requests, Node updates or VPS runtime changes. This is a
successful bounded recovery observation, not proof of the earlier fault's cause,
MTS SIM failure, automatic restart or complete autonomous lifecycle acceptance.
### Two-SIM configuration regression and exact USB recovery, 2026-09-27
The canonical Core API performed a new network-only read/write/readback case
through Host 0.1.23. USB remained connected but was not used during these network
operations. The initial read returned the accepted 207-record baseline in
12.57 seconds. Changing only field 25 from 15 to 16 seconds reached `verified`
in 54.795 seconds, including Core polling and settings-channel pacing.
The requested return to 15 passed its preflight but remained `unconfirmed` at
the write stage after 187.41 seconds. An independent new network read completed
in 9.57 seconds and established that the actual value was still 16. A separately
recorded restoration attempt using this newly observed predecessor timed out
in preflight after 181.328 seconds; that attempt did not reach a settings write.
No blind resend or automatic replay ran. Neither timeout proves carrier failure
or establishes which part of the settings exchange stalled.
After both network operations were terminal, identity-bracketed USB inspection
again read 16. A single USB recovery changed only field 25 to 15 after asserting
that the complete prepared image matched the accepted baseline. An independent
read then matched every byte: 207 records, 983 bytes, SHA-256
`a3b52af5900740cce3eae4db31390a2c2887ba59c7fab99e50595f7e3a48b7ae`.
The product's read-only USB refresh subsequently obtained that same image and
updated its observed snapshot. The failed network receipt remains `unconfirmed`;
USB recovery must not be presented as successful remote restoration.
Private evidence sessions outside source control:
- `core-flow-3bada51cd97f4bff83428f82dc4c847a`: initial read, verified write,
failed return, explicit restoration and USB recovery subdirectories.
- `core-flow-95027e95805e4b2b9d44a58b780a6eac`: independent network read proving
the temporary value remained in the device.
- `core-cellular-702f37f2155f4fd58b5b240647366b0f`: subsequent product USB refresh,
exact-baseline comparison and healthy Core restart.
### Cellular observations in Mission Core, 2026-09-27
Operator job: determine which SIM the tracker reports as active, its registration
and signal state, and the age of that evidence while diagnosing field connectivity.
The admitted placement is the existing B2 **Server and connection** section.
A separate diagnostics workspace was rejected because this is supporting state
for the same device and connection lifecycle. This is domain content in an
existing composition, not new navigation or a new shared visual pattern.
Core now projects TAG8, TAG201 and TAG99/DS2 table 6 from the existing durable
INTERNAL journal after the established framing and CRC validator accepts a
packet. Reference: the manufacturer's public
[INTERNAL TAG table](https://docs.google.com/spreadsheets/d/15s-2ZbqOQ1bZvAtFFm9sIEuKy3jbJzxdeynp72sjoYU).
The parser is Core-only; the receiver codec and immutable VPS 0.1.23 artifact
remain unchanged. The observed B2 emits these tags; this does not qualify every
ARNavi hardware/firmware family listed in the generic specification.
Status and each SIM's serving-network observation retain independent measurement
and receive timestamps. Old archive packets do not replace newer observations;
missing tags do not refresh an old component. Conflicting repeated scalar tags
are omitted. Invalid/unknown MCC and signal values remain unknown. Observations
require device admission and the current paired, assigned host; host changes do
not mix previous-host data into the new snapshot. Cellular projection and journal
cursor commit atomically, independently of whether the packet contains GNSS.
The UI reuses `SettingsCard`, `StatusBadge`, `FeatureSettingsWindow` and the
existing facts layout. Its state grammar distinguishes absent information,
current observations and last received observations. Each SIM's network reading
shows its own time. Serving-network codes do not set an APN, reconstruct ICCIDs,
identify a phone number or establish simultaneous data sessions on both SIMs.
Known names are shown only for exact documented MCC/MNC pairs; `250-00` remains
an explicit network code rather than being guessed as the owner's MTS SIM.
Live acceptance through the canonical service on port 8000 showed active SIM 1,
GPRS connected and MegaFon `250-02`, with both SIM registration observations and
signal readings. The second reported network was `250-00`. Values and timestamps
updated in the browser. Normal/expanded fleet compositions, settings scrolling,
Escape, keyboard focus return and right-aligned footer controls were checked;
the real B2 connection view was left open. No new settings-window expansion
control was added; its existing canonical composition was retained.
Validation: architecture/focused UI checks, full typecheck, 995 frontend tests,
production build, Ruff and 130 relevant backend tests passed sequentially. The
initial sandboxed backend pass could not bind a test localhost socket; the same
bounded suite passed with the required host permission. Coverage includes CRC,
partial frames, conflicting tags, legitimate zero values, partial observations,
stale/future timestamps, host reassignment, admission and transaction rollback.
The existing frontend large-chunk build warning remains. Core was restarted
through its managed LaunchAgent after a SQLite backup and passed health
acceptance. No firmware, output actuation, Node update, vendor request or VPS
runtime change occurred in this increment. Remote-write reliability and the
previously listed autonomy gates remain open.
### SIM state versus APN selection: operator clarification, 2026-09-27
The B2 manual's two holders/two operators statement does not document the full
switching algorithm, its deadlines or simultaneous independent data sessions.
The public DS2 contract reports one selected SIM and GPRS OK on that selected
SIM. Two registration statuses must not be rendered as two Internet links or
as physically tested automatic failover. Do not borrow a switching algorithm
from an ARNavi 5 manual and assert it for this B2 firmware.
The owner reported the second installed card is MTS, but the live TAG201 value
contained MCC 250/MNC 0. The configured APN `internet.mts.ru` is configuration
evidence, not detected SIM ownership or proof of the current serving network.
TAG8 also sometimes omitted a valid MCC. Unknown live codes remain unknown;
there is no substitution from a phone number, user declaration, chosen preset,
APN or historical carrier reading. Known exact codes currently map MTS, MegaFon
and Beeline; other codes remain visible without an invented brand name.
The same admitted connection section now places observed mobile state before
editable endpoint/APN settings, with a distinct canonical card for each SIM.
Each card separates the modem's selected Internet SIM, registration, detected
network, signal time and the APN from the last configuration read. A freshly
reported missing SIM suppresses that slot's previous network observation and
cannot receive an Internet badge. Stale/offline data receive last-state wording.
This remains novelty A in the existing settings window. Keeping the previous
single dense facts block was rejected because it obscured the authority of the
operator selector and the difference between registration and Internet use.
The editing group is explicitly named Internet setup (APN). It selects a target
slot first, then a carrier access preset, and previews the APN that will be
written. Selection alone edits a local draft. Save settings persists the policy
and starts the existing remote apply; the preset replaces APN/login/password for
the selected slot and preserves the other slot's access fields. Save profile
stores a portable template without sending it. This UI change does not add
automatic APN provisioning or a command to switch the active SIM. Incorrect
carrier access settings may prevent that slot from establishing Internet access.
Validation: architecture/focused state checks, typecheck, all 997 frontend tests
and production build passed. Cases include two registered SIMs with one selected,
selection of SIM 2, stale/offline state, removal with an old network reading,
unknown network codes and the existing Beeline mapping. Live browser QA changed
the SIM-2 preset from MTS to MegaFon only in a draft: its preview changed to
`internet`, while the observed APN remained `internet.mts.ru` and selected SIM
remained 1. Escape discarded that draft without saving or transmitting. Ordinary
and expanded parent layouts and the canonical footer were checked; the live case
was retained. No device command, USB transaction, backend/VPS change or automatic
carrier write was performed for this clarification. Core serves content-hashed
assets with fresh HTML, so this frontend-only build requires no service restart.
## APN placement and bounded operation feedback — 2026-09-27
Owner feedback: keep the SIM evidence and APN editor together; a saved operator
preset appeared to wait indefinitely while every action was disabled. Existing
connection section retained (novelty A): VPS transaction → SIM 1 → SIM 2 → APN editor → monitoring server.
Follow-up owner feedback removed the redundant mobile-state summary card; the
active Internet badge remains on the SIM card itself. Putting the monitoring server between
SIM evidence and its editor was rejected because it splits one operator task.
No new product root, navigation, shared primitive or styling was introduced.
Read-only inspection of the owner's failed transaction proved a terminal
`configure-all / preflight / unconfirmed` receipt: 180-second VPS deadline, no
configuration upload and no `write_reply_sent_at`. Therefore that transaction
never wrote the selected MegaFon preset to SIM 2. Its desired policy remains
saved in Core; no automatic write retry or policy reversal was performed.
Core now retains the shorter authenticated VPS expiry rather than displaying
only its 240-second fallback. Terminal preflight timeout is distinguished from
an unknown write result. A still-pending reply past Core's bound terminates as
unknown, without resubmission. Frontend shows time remaining, stops the spinner
at expiry while retaining the write interlock until reconciliation, and exposes
the terminal result. Closing the window and saving a local profile remain
possible during a background transaction. This does not fix the underlying
intermittent B2 configuration upload and does not establish autonomous network
configuration acceptance.
Validation: 26 equipment-network backend tests, 19 focused frontend/architecture
checks, full 999 frontend tests, typecheck and production build passed. Synthetic
coverage includes preflight versus write/verify timeout, a reachable VPS stuck
pending, deadline non-extension, and spinner expiry without inventing success
or releasing the write interlock. Real UI verification uses the enrolled B2,
including a single read-only VPS transaction; see private session manifest for
its outcome. No configuration write, USB operation, relay command, firmware
upload or vendor-service request belongs to this increment.
## Explicit Internet SIM selection — 2026-09-27
Owner clarification supersedes the APN-only selector: choosing SIM 2 and saving
must actually request Internet on SIM 2, keep the settings window open, and
report device evidence rather than a local save or command receipt.
Model 231 field 72 bits 10 and 20 prohibit GPRS on SIM 1 and SIM 2 respectively
(manufacturer model schema aliases `231_72_10`, `231_72_20`). A bounded physical
USB experiment established that writing these flags alone did not switch the
selected SIM within 93 seconds. The same flags followed by the documented
0107 restart returned fresh DS2 telemetry with SIM 2/GPRS OK after about 79
seconds. Both experiments independently restored the exact predecessor image.
These are exclusive data-selection flags, not a priority/failover algorithm.
Host 0.1.24 owns one durable `select-sim` operation: fresh image preflight;
exact predecessor check; one image dispatch; independent exact readback;
one restart; then fresh type-1 TAG99 with the requested active SIM and GPRS OK
on a connection opened after restart dispatch. A 360-second deadline bounds
all phases. A matching image alone cannot mark selection successful. Host
restart, missed response or expiry never replays a write or restart. Core also
requires fresh presence evidence from the owning VPS before dispatch.
The existing connection section is retained (novelty A), using canonical
Select, TextField, SettingsCard and window controls. Explicit SIM selection
replaces any legacy carrier-preset intent; APNs and credentials stay unchanged
unless the operator edits the selected card's APN. The form starts with an
explicit selection prompt instead of presenting a passive APN browser as a
command. Save keeps the window open and brings the operation result into view.
Historical installed-card evidence remains labelled as historical during an
outage; stale evidence cannot authorize a new write. A fresh removal excludes
the slot. Unknown network codes remain unnamed. Saving without an edit or an
explicit SIM-selection intent explains that no command was sent.
Synthetic acceptance covers preserved access credentials/other flags, strict
slot/flag agreement, one-time restart including service-crash recovery, wrong
SIM, no GPRS, missing DS2, archived/future measurements, old/unregistered TCP
sessions, expiry, and Core refusing to equate readback with SIM selection.
Frontend architecture, typecheck, 1003 unit tests and production build passed.
Physical end-to-end outcome and limitations follow in the qualification entry.
### Host 0.1.24 physical acceptance
Private session `sim-switch-284dab5fa2d74cdbb0186e9fe421d207/network-check`:
The bench stopped reporting after the USB experiment's exact-image restoration.
A separate, previously qualified USB restart restored SIM 1/GPRS and a new
network session. This recovery is not counted as a remote SIM-selection result.
The operator-facing form then selected detected SIM 2 and clicked Save settings.
The entire subsequent transaction used Core → owned VPS → cellular B2, without
USB writes or vendor services. Exact preflight/readback proved that only field
72 changed, 2072 → 3096; all 206 other fields and both APNs/access credentials
were preserved. A single documented restart was dispatched after verification.
The requested SIM 2/GPRS was independently observed through a new TCP session;
the durable result became `sim_selected` and Core's policy state `applied`.
Total transaction time: **255.097 seconds** from Core creation; restart-to-
confirming-new-session evidence: **210.044 seconds**. The earlier bench result
of about 79 seconds is not a guarantee. Fast or bounded cellular registration,
fallback to the other SIM and repeated bidirectional switching under field
conditions have not been established. The real SIM 2 now reports MCC250/MNC1,
so its MTS label is from fresh network evidence, not the configured APN.
The selected-only data mode remains enabled for SIM 2 on this test B2.
The settings window stayed open throughout and displayed pending and confirmed
results. A further value-comparison fix treats JSON property order and explicit
server defaults as equivalent; completed operations no longer leave read/apply
buttons disabled as though the form were dirty. Saving an unchanged applied
policy does not dispatch another restart. Progress is brought into view on save.
The installer was reproduced byte-for-byte and published for download in Core:
Host **0.1.24**, SHA-256
`c1090551788cda35f7757ee654419f83bb3a3e12d08c8c8e82ce0012e1b2f33a`.
Existing host identity, TLS, bindings and state were preserved by the same
installer used for operator deployment. Node was not modified.
Final acceptance: all **1004** frontend tests, typecheck and production build
passed. Browser QA confirmed normal/expanded parent layouts, Escape, enabled
read controls after completion, and unchanged-save feedback with the operation
ID and device revision unchanged. Canonical Core remains on port 8000; no
Mission Core listener remains on 8765. Fresh SIM 2/GPRS data remained online.
### Communication limits and transport outage, 2026-09-27
See [the communication limits investigation](COMMUNICATION_LIMITS.md) for
manufacturer references, measured phases, capacity limits and remaining gates.
Session `communication-limits-69cdaddac9c74079b059d8115a2d62aa` retained
simultaneous USB/PCAP evidence and all unsuccessful command results.
Before the new experiment, SIM2 stopped advancing telemetry despite repeated
connections. Three identical old packages were each followed by a VPS ACK and
an incoming RST+ACK 9–10 ms later, with a different TTL from regular tracker
traffic. This suggests a transport-path intermediary but does not identify its
owner or establish a firmware defect. A request-position remained unconfirmed.
One explicit USB recovery changed only the exclusive SIM selection to SIM1,
preserved both APNs/all other records, and issued one qualified restart.
Hardware identity, new USB session and exact post-write configuration were
verified. The broader identity comparison failed because the device-reported
SIM1 identifier changed length; that failed check is retained separately.
Core first observed resumed delivery after 80.416 s, and SIM1 telemetry less
than 30 seconds old after 234.371 s; backlog delivery accounts for part of this
gap. This does not qualify reverse switching over the network.
Three SIM1 request-position samples also remained unconfirmed. VPS dispatch
queues were 5.560–6.525 ms. The correlated sample showed kernel retransmissions
without a normal TCP ACK or matching USB receipt. Retransmissions persisted
after the 30-second application result deadline: current timeout does not
guarantee cancellation of bytes already queued in TCP. This is a priority
limitation before claiming bounded remote-output latency.
Final Core policy/USB image were reconciled to SIM1 through a guarded no-op
application (`unchanged`), with fresh SIM1/GPRS observed. No firmware, relay,
onboard Node, vendor-service request or product-runtime update occurred.
Temporary packet captures exited; the canonical Core and VPS services remain.
### Positive command control with USB disconnected, 2026-09-27
Session `network-only-278ac319e262481d971a22cd1b4480ef` observed no B2 USB
enumeration and used only Core/VPS. Fresh SIM1/GPRS continued. One position
request reached `device_confirmed`, code 0: VPS queue 0.004374 s, device
confirmation 1.320071 s after dispatch. PCAP independently matched the command
token in a type-9 response after 1.314112 s; no incoming RST appeared in the
45-second capture. No configuration, outputs, restart or runtime changes.
This proves one working network-only exchange, not that USB caused earlier
failures, not bounded future latency, and not physical-output actuation.
### TCP delivery deadlines, VPS Host 0.1.25, 2026-09-27
Release session `delivery-a8d26be666ec4dd182f46a4db8d0c566` qualifies monotonic
command-byte deadlines across asyncio and Linux kernel queues. Commands are
bounded by the operation deadline and 30 seconds after dispatch; configuration
HTTP replies by the operation deadline and 12 seconds. Abortive close prevents
queued bytes from lingering after disconnect. TCP ACK only releases transport
tracking; durable protocol confirmation remains separate. Idempotent submission
now reports an expired record's current outcome consistently with GET.
The shipped loopback qualifier passed on the supported VPS: healthy TCP stays
open without application confirmation; a blocked 64-KiB stream resets at
0.751091 seconds for a 0.750-second deadline. This is a bounded functional check,
not capacity qualification. No firewall, packages or onboard environment changed.
Physical network-only session `network-only-b5c513eb06da42d599fb515e66b8a83d`
produced an unconfirmed position command: queue 4.791 ms, five on-wire sends,
no TCP ACK, reset at 29.994 seconds after first transmission, no command bytes
after expiry in the 45-second capture and no replay on another connection.
Core's dialog remained open and its actions became available after timeout.
This qualifies failure containment, not reliable mobile delivery. A preceding
unaccepted/uncertain post-update attempt is retained separately, not retried.
154 backend cases and 1004 frontend cases passed; production build and typecheck
passed. The byte-reproducible installer was applied and published as 0.1.25.
Four persistent identity/key files retained their digests. Tracker configuration,
SIM selection, firmware, outputs and onboard Node were untouched. Already
received commands cannot be cancelled by closing a server socket.
+111
View File
@@ -0,0 +1,111 @@
# B2: permission for both SIMs, 2026-09-27
## Decision and evidence boundary
The model-231 configuration schema defines field 72 bit 10 as prohibiting GPRS
on SIM 1, and bit 20 as prohibiting GPRS on SIM 2. Neither flag specifies a
priority or failover interval. The public SIM sections contain APN, credentials,
roaming permission, preferred roaming operator, PIN and balance-query settings.
No documented temporary SIM selection or timed rollback was found there or in
the B2 manual's command table. That is a limit of the reviewed documentation,
not proof that no additional manufacturer command exists.
Sources: [manufacturer model-231 schema](http://webconfigurator.ru:8089/public-api/v1/device-types/231/configuration/with-translations)
and [B2 user manual, sections 9–10](https://8888.arusnavi.ru/Arnavi%20B2/Arnavi%20B2%20%D1%80%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE%20%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8F%20%5B241219%5D.pdf).
## Product behavior
The existing Internet selector adds **Обе SIM разрешены**. Selecting one card
retains explicit exclusive selection and its warning about losing the other
card as a recovery channel. Selecting both clears only the two GPRS prohibition
bits; it preserves both APNs, credentials, other flags, unknown records and
server endpoints. This is not simultaneous Internet on two cards or a promise
of an immediate automatic switchover. No new surface, control or product root.
The portable policy uses `connectivity.strategy=both`. A deliberate save submits
one durable `select-sim` job with `sim_policy=both` and no exclusive `sim_slot`.
VPS 0.1.37 validates that neither prohibition remains. Core rejects the new
request on older VPS versions. Existing exclusive requests remain compatible.
Execution is fresh full read → guarded image write → independent full read →
restart → fresh GPRS data on a new connection. Either real slot may satisfy
the last step. Configuration readback alone, an old connection, or registration
without GPRS cannot. Recovery reads the actual image and fresh modem state
before deciding on a further attempt. Saving unrelated settings with an
already-applied both-SIM policy does not request another restart.
## Physical acceptance on the owner's B2
Private session `dual-sim-policy-e26d3337c21a4a3bbc321fcf67eb0756`; model 231,
firmware 0.01, indoor conditions. USB and firmware were not used.
- Baseline full read succeeded on its first attempt: 207 records, 983 bytes.
- The actual product selector and **Сохранить настройки** submitted the job.
- Exactly field 72 changed; its only difference was clearing SIM 2's GPRS
prohibition. Both APNs and every other record remained byte-identical.
- One attempt completed. Fresh GPRS on SIM 1 was received 62.631 seconds after
restart dispatch; the whole workflow took about 110 seconds.
- Closing the settings window with Escape and opening it again retained the
same running job. The window did not own or cancel the transaction.
- An additional full read after the restart matched the complete target image,
confirming persistence beyond the pre-restart readback.
- A subsequent position request received B2 token confirmation code 0 in
2.435 seconds, one attempt. Core and VPS agreed on the result.
SHA-256 of the baseline: `7e7798a5e2c1909454dfab500dac4cc2d0917555a02f2afac711b167c9ae1ee8`.
SHA-256 after the change: `a3b52af5900740cce3eae4db31390a2c2887ba59c7fab99e50595f7e3a48b7ae`.
The owner then powered down, removed SIM 1 and started B2 with only SIM 2
(MTS), on external power without USB. No new connection was observed for at
least 386 seconds after the owner reported completion. The receiver was active
and had zero established tracker sockets. Stored SIM 2 APN/login/password
matched the public MTS preset, and both GPRS permissions were enabled. The owner
reported one long and three short blue flashes: according to the manual, mobile
network search/registration and more than eight GNSS satellites. This does not
identify the cause (coverage, SIM service or modem); it does not establish a
VPS/APN failure. Later buffered observations qualify this LED-only account:
B2 recorded SIM 2 as registered with network 250-01 and GPRS state 4 while
SIM 1 was absent. Those records arrived only upon recovery, 94–468 seconds
after measurement. They establish what the modem reported during the outage,
not a working application connection to this VPS through MTS. The cause remains
unresolved. Boot through SIM 2 alone is **not accepted**. No claim of seamless
radio failover follows from a powered-off card-removal test.
One position request was queued while the last packet was already 120 seconds
old. Core and VPS kept it in `waiting-link` with zero attempts. The owner then
restored SIM 1 with power off, retained SIM 2, and supplied 12 V without USB.
The same durable job was dispatched once, 442.342 seconds after creation,
and received B2 confirmation code 0 in 0.906 seconds. Total creation-to-reply
time was 443.247 seconds. Core and VPS agreed on `device_confirmed`; no
replacement command or settings write was involved. This proves preservation
and automatic dispatch of this queued command across the observed outage,
not exactly-once execution of every possible command after an ambiguous reply.
Fresh telemetry after recovery reports SIM 1 active, GPRS state 4, and both
SIMs present. The first fresh modem record was measured at 20:47:25 UTC and
received at 20:47:30.513 UTC. Earlier SIM 2 records, measured at
20:39:34–20:45:52 UTC, were received at 20:47:21.715–20:47:26.873 UTC.
Raw packages and decoded timestamps are retained privately. The runtime's
30-second freshness condition prevents those buffered records from confirming
a current SIM-selection operation.
## Release and validation
VPS 0.1.37 was installed using the versioned installer on the existing host.
Its four identity files were preserved, its service is active, and all 28
installed payload files match the release manifest. Installer published in
Mission Core: SHA-256 `140a54c608a6e9c71663cc9435c7ffab12bba6c5277fc78c6d9daa59da19e002`.
No clean-Ubuntu or migration qualification is inferred from this update.
Focused backend coverage includes contradictory policy rejection, APN/flag
preservation, either-slot fresh evidence, recovery without a second restart,
Core version admission and rejection of readback-only success. The pre-existing
TCP test needed a local-socket sandbox exception and then passed, along with
the seven packet-commit tests. Frontend architecture, typecheck, 1,012 tests and
production build passed; a subsequent progress-text change has focused coverage
and a fresh production build. Normal settings, dropdown, save, pending close /
reopen, and persisted selection were checked in the canonical UI on port 8000.
Remaining: automatic switchover timing/conditions and recovery from exclusive
selection of an unusable SIM are not qualified. A disconnected VPS cannot
deliver a recovery command over that same disconnected mobile link.
@@ -0,0 +1,101 @@
# Применение интернета для распознанной SIM
Дата: 2026-09-28. VPS Host ARNavi 0.1.38. B2 model 231, firmware 0.01.
Сессия: `automatic-connectivity-66e3010ea75244c6b5b97c28fad18193`.
## Реализованная граница
В существующем блоке «Интернет» пользователь выбирает SIM и сохраняет настройки.
Для выбранной SIM по умолчанию включается подбор параметров карты. Сначала Core
ищет ранее проверенную тройку APN/логин/пароль этой карты, затем кандидат из
каталога по её подтверждённой домашней сети. Сейчас кандидаты есть для обычных
тарифов МТС и МегаФона. Обслуживающая сеть, номер телефона и APN слота не
используются как доказательство оператора или идентичности карты.
Карты распознаются по полному сетевому SID и ранее квалифицированному соответствию
SID ↔ модемные CCID/IMSI. Новый неизвестный SID не получает имя оператора по
догадке. Применение по сети требует доступного канала к собственному VPS.
Политика хранит только выбор режима. Секреты доступа, идентификаторы SIM и
доказательства успешного подключения не входят в переносимый профиль. Кэш
проверенных настроек находится в частном SQLite-хранилище наблюдений SIM и
переживает перезапуск Core. Он привязан к карте внутри данного трекера, не слоту.
## Цепочка подтверждения
1. Core проверяет актуальную регистрацию и неаннулированное наблюдение карты.
Стартовый SID не объявляется свежим измерением на каждом пакете: сохраняется
привязка при свежем состоянии регистрации. Отсутствие, поиск, конфликт или
неоднозначность делают её непригодной для автоматической записи.
2. В долговечном задании фиксируются карта, слот и точный целевой образ.
VPS проверяет идентичность перед отправкой записи и ещё раз в транзакции
перед выдачей конфигурации по HTTP. При замене карты образ не выдаётся;
недостаток сведений сохраняет задание в ожидании.
3. VPS читает фактический образ, сверяет предшественника, пишет изменения и
независимо читает результат. Для выбора SIM проверяется её эксклюзивное
разрешение GPRS; служебный перезапуск принадлежит тому же заданию.
4. Успех требует свежего GPRS на выбранном слоте по новому соединению и нового
подтверждения ожидаемого SID после перезапуска. Обычный ACK или только
совпадение настроек не закрывает операцию.
5. Core запоминает доступ только после совпадения целевого образа и результата
`sim_selected` с подтверждённой картой. Повторное чтение после потерянного
ответа использует ту же проверку карты. Другие SIM сохраняют свои параметры.
Схема соединений прежняя: Core инициирует API-запросы к VPS; B2 инициирует
соединение с VPS. VPS не подключается к Core. Внешний ARNavi в этом цикле не
участвует. Достоверность ограничена данными прошивки B2; криптографической
аттестации физической SIM это не добавляет.
## Физическая проверка
МегаФон находился в первом слоте, МТС во втором. Питание 12 В, USB отключён.
Оба выбора сделаны кнопками обычного интерфейса Mission Core.
| Выбор | Результат | Попытки | От принятия задания до подтверждения |
| --- | --- | --- | --- |
| SIM 2, МТС | Образ проверен, свежая связь через SIM 2, карта подтверждена | 1 | 114.236 с |
| SIM 1, МегаФон | Образ проверен, свежая связь через SIM 1, карта подтверждена | 1 | 132.964 с |
Это длительность полного цикла настройки и перезапуска, не задержка доставки
одного пакета. APN и реквизиты обеих карт уже совпадали с кандидатами;
в образе менялись разрешения SIM. Исправление заведомо неверных реквизитов
новой карты данным аппаратным опытом не проверялось.
Интерфейс после каждого результата показал «Проверенные настройки этой карты».
Перезапуск Core сохранил оба результата кэша, тот же идентификатор завершённого
задания и одну попытку; повторной отправки не возникло. Итог: SIM 1 активна,
трекер передаёт свежие пакеты на собственный VPS.
Синтетические проверки охватывают перенос настроек вместе с картой между
слотами, замену карты после отправки команды до HTTP-выдачи образа, отсутствие
нового SID при наличии GPRS, восстановление очереди VPS, приватность ответа,
защиту от архивных пакетов и избирательную запись всех трёх полей доступа.
Связанные backend-тесты, архитектура UI, typecheck, 1015 frontend-тестов и
production build прошли. Проверены ручной режим APN без отправки, повторное
открытие, Escape, обычный и развёрнутый контейнер оборудования.
## Поставка
Установлен штатным версионным `.pyz` поверх 0.1.37. Четыре файла идентичности
сохранены, журнал скопирован штатным SQLite backup до обновления; сервис активен.
Проверены все файлы установленного manifest и байты скачивания из Core.
Две независимые сборки дали одинаковый артефакт.
- Installer SHA-256: `952198b0495520536023fc2f675847adb80f37ca1e5a2e61db00a99da1aac767`.
- Manifest SHA-256: `89e8342901dc46b02efe349941cdc96369a4b4352b89c717651267cdd6aa7ab4`.
- База исходников: `fb33a6d45c73e6d458faed586959ba1a12775355` плюс рабочие изменения;
точные хеши исходников и закрытые измерения находятся в каталоге сессии.
## Что ещё не закрыто
- Автоматический запуск настройки сразу после физической перестановки без
«Сохранить настройки» не реализован. Выбор и применение остаются явным действием.
- Сетевой подбор для произвольной ранее неизвестной карты без её квалификации
не заявляется. Универсальная база операторов, редактирование корпоративных
реквизитов и перебор нескольких кандидатов требуют отдельного этапа.
- Если B2 вообще не может выйти в интернет, VPS не сможет по этому отсутствующему
каналу исправить APN. Нужен локальный канал начальной настройки/восстановления.
- Новая физическая перестановка после обучения кэша и реальная коррекция APN
в другом слоте ещё не проверены; программная перестановка проверена тестами.
- Чистая Ubuntu, перенос на другой VPS и масштабная нагрузка остаются отдельной
приёмкой согласно решению владельца.
@@ -0,0 +1,77 @@
# B2: PIN delivery, history repeat and post-boot SIM network codes
Date: 2026-09-28. Core base: `03d44d0`. VPS Host: **0.1.42**.
## Corrected delivery window
VPS sender admission requires device input no older than 5 seconds. The live B2
reported approximately every 15 seconds. Output requests previously expired in
3 seconds, often before the next eligible input. The inspected expired PIN4
request had no dispatch or transport record: it never reached the tracker.
PIN4–6 output/pulse requests now wait up to 30 seconds on their admitted original
connection, with total expiry capped at 60 seconds and the original Core request
deadline. All existing freshness, session, output-mode and firmware guards remain.
A dispatched output is never retried automatically or replayed across reconnect
or process restart. Other action deadlines are unchanged. The 3-second output
windows described in older runtime documents are superseded by this release.
A separate old PIN5 pulse was written to TCP but expired without transport ACK.
This is distinct from queue expiry; neither establishes electrical actuation.
## Explicit repeat
Each history row has a canonical circular refresh action after Details. An
in-flight row is disabled. Each deliberate repeat creates a fresh intent, while
retries after a lost HTTP response reuse the persisted request ID. The normal
Core FIFO, identity/firmware checks and output-mode checks still apply.
Settings/SIM repeats recover their intended target from revision history, not
from the transport outbox (which is deleted after acknowledgement). Changed
settings, device/host identity, card-bound automatic access or missing old
parameters reject the repeat explicitly. Current settings are never silently
substituted for a different historical action. A queued repeat also checks its
plan fingerprint immediately before starting.
## Current physical evidence
A repeat of a historical configuration read succeeded via the product UI, with
one attempt and 207 records returned. After explicit owner authorization, one
PIN4 five-second pulse was dispatched 0.772 seconds after Core acceptance; TCP
acknowledged it in 1.505 seconds. A `SERV OK` text packet was also received.
FC replies have no command token. They do not establish correlated execution or
contact position. Telemetry before/after the pulse showed PIN4 off, but did not
sample the five-second interval. Electrical switching remains unproved. The UI
now says “Результат не подтверждён”; the FC explanation no longer falsely states
that no device reply was received at all.
## SIM evidence and presentation
The owner's complete power cycle changed fresh DS2 to both SIMs registered,
GPRS on SIM1. From 20:18:55 through 20:25:10 Moscow time, raw TAG8 carried MCC=0,
MNC=1 despite registration and working GPRS. At 20:25:25 it became 250-01 (MTS),
before this code/deployment. SIM2 reported 250-02 (MegaFon).
Missing MCC is distinguished from absent SIM and disconnected internet. The UI
states that internet is connected but B2 has not supplied the operator network
code; it never guesses a carrier from MNC alone. The reason for delayed MCC and
hot insertion detection remains a firmware/modem investigation, not a proven
Core decoder defect. Firmware was not changed.
## Validation and release
250 focused backend/VPS tests passed across two non-overlapping test selections;
1017 frontend tests, architecture/type checks and production build passed. After
the FC copy refinement, 16 focused frontend tests and a new build passed. Two
independent VPS builds matched. Core remains healthy on 8000; no backend on 8765.
The exact installer was applied with its reviewed plan and automatic health
rollback, then published to the operator's existing installer catalog. Previous
release, credentials and state were preserved; VPN/routing were unchanged.
- PYZ SHA-256: `b1eac7ccc68f165a26838e8c01cd5ab630087df2783d8c6079dab057a5e98c9e`
- Release SHA-256: `62c4d4cc32f8ed2f20efba5af4c528be6d5ad7d9bd047774c54df139b20635e9`
Private command identities and redacted live receipts are retained in the local
`outputs/arnavi-sim-investigation-20260928` follow-up report/evidence.
+137
View File
@@ -0,0 +1,137 @@
# Команды B2: очередь, журнал и операторское окно
## Принятое размещение
По запросу владельца 27.09.2026 из строки ARNavi B2 в оборудовании открывается
отдельное окно «Команды». В настройках остаётся переход в то же окно. Пользователь
выбирает понятное действие, видит тело для прочитанной прошивки и отправляет его;
здесь же просматривает незавершённые и завершённые операции.
Альтернатива — оставить команды внутри настроек — не выбрана: журнал живёт
дольше редактирования конфигурации и не должен зависеть от сохранения формы.
Нового раздела основного меню или product root нет. Это доменная композиция
канонического `Window size="lg"`, `SettingsCard`, `ResourceList/ResourceRow`,
`Select`, `StatusBadge`, `Button`, `IconButton`, `ToastStack` и `LoadingRegion`.
В реестре нет иконки терминала; используется существующая `activity` с явным
accessible name «Команды». Новая общая визуальная сущность не добавлена.
## Владение и порядок
- **Core** — долговечные намерения, FIFO по устройству, локальная отмена до
передачи, журнал и повтор HTTP с тем же ID при неизвестном результате.
- **VPS** — одна активная операция на B2, соединение с устройством, исходящий
пакет, ожидание ответа и собственный долговечный результат.
- **B2** — выполнение согласно его прошивке, подтверждение по доступной
семантике протокола. GNSS и наличие мобильного соединения — разные условия.
Очередь относится к серверному процессу Core, не к открытой вкладке. Закрытие
окна не останавливает её. Если сам Core выключен, ещё не переданные операции
не передаются до его возвращения и истекают по исходному сроку. Уже принятые
VPS операции продолжаются независимо от Core. Перезапуск не продлевает сроки.
Текущий владелец соединений и исполнения — VPS 0.1.26; этот этап меняет Core,
не firmware трекера или бортовой Node.
На устройство допускается до 32 незавершённых операций. Локальная очередь
передаёт одну операцию после завершения предыдущей; конфигурационные операции
из настроек используют тот же interlock. Переход waiting → submitting и
приватный outbox фиксируются одной SQLite FULL-транзакцией. Отмена конкурирует
с отправкой через эту же транзакционную границу: после начала передачи она
отклоняется, а не выдаётся за отмену физического действия.
Запрос позиции ждёт начала передачи до 30 секунд. Выходы/импульс/restart ждут
начала передачи из Core до 3 секунд. Уже переданная обычная команда имеет
исходный срок до 30 секунд, restart — до 180 секунд для подтверждения возврата.
VPS дополнительно применяет свои ограничения отправки и TCP из 0.1.26.
Эти часы не дают жёсткого real-time: таймер ОС может задержаться, а доставка
на сотовом пути не гарантируется. Просроченное воздействие не накапливается.
После неясного ответа на POST браузер сохраняет ID запроса локально и предлагает
уточнить ту же отправку. Идентичный ID возвращает имеющуюся операцию; другой
preset с тем же ID отклоняется. Новые произвольные команды не принимаются.
Каталог ограничен прошивкой 0.01, режимом выхода и поддержанными действиями:
позиция, restart, PIN4–6 вкл./выкл./импульс 5 секунд. Тело показывается без пароля;
служебные токены и обрамление формирует существующий адаптер VPS.
## Журнал
Отдельная таблица операций с индексами по устройству и состоянию сохраняет
каждую принятую операцию, её параметры без секретов, состояние, события и
доступные времена отправки/ответа. Существующие операции настройки также
попадают сюда. История загружается страницами по стабильному sequence cursor;
повторные обновления объединяются по ID, а не создают новые строки.
Активные записи возвращаются независимо от страницы истории; последнее
состояние известных активных ID запрашивается до завершения. Поздний ответ
опроса не заменяет более свежее состояние в браузере.
Если Core не получил результат команды до своего срока, неизвестный исход
не блокирует очередь. Отдельный долговечный GET-опрос исходного VPS уточняет
эту строку без повторной отправки B2 и без перезаписи более новой операции.
Браузер продолжает следить за такими строками вне первой страницы.
Границы и проверка описаны в [протоколе восстановления](FAULT_RECOVERY_20260927.md).
Состояния различают очередь Core, передачу на VPS, очередь VPS, отправку B2,
подтверждение, неизвестный результат, отсутствие подтверждения, истечение срока
и локальную отмену. «Подтверждено B2» не означает, что измерены контакты реле.
Для restart результат — свежие данные по новому соединению. Текстовые FC
команды без токена не получают выдуманного подтверждения исполнения.
Времена, сообщённые VPS, показаны отдельно от времени, когда Core увидел статус.
Если опрос пропустил промежуточное состояние, известное время отправки/ответа
сохраняется как отдельное свидетельство; неизвестное время не восстанавливается
по предположению. При первом запуске прежние network_operation из истории
Core импортируются. Старые незавершённые записи без действующей операции
получают неизвестный исход; точные времена их переходов не придуманы.
## Обновление и ограничения
Новая команда будит рабочий цикл Core. При активных операциях результаты
проверяются примерно раз в секунду; обычная синхронизация телеметрии сохраняет
интервал около пяти секунд. Выполнение не зависит от открытого окна; окно
читает журнал раз в две секунды и сохраняет последний результат при ошибке.
Время на экране включает задержку наблюдения; отдельное время VPS → B2
показывается по измерению, а не по анимации.
Один имеющийся worker Core последовательно обслуживает подключённые хосты;
длительный сетевой вызов может задержать обработку следующего. Исходные сроки
действия не продлеваются, но малая задержка и тысяча устройств этим этапом
не квалифицированы. VPS сохраняет предел 256 соединений. Масштабирование,
ретенция журнала и автоматический резерв SIM требуют отдельной квалификации.
Условия помещения/улицы не входят в модель устройства, настройки или UI.
## Приёмка 27.09.2026
До обновления сохранены приватные SQLite-копии обеих баз. Миграция проверена
на отдельной копии: целостность БД сохранена, восстановлены 56 прежних операций.
После установки Core журнал доступен из строки B2 и через настройки; Escape
возвращает фокус к кнопке команд. Проверены каталог, маскировка пароля, все три
фильтра, раскрытие этапов рядом со строкой и подгрузка старой истории.
В интерфейсе последовательно отправлены три запроса координат. Результат
третьего сохранён при закрытом окне и показан после повторного открытия.
| Запрос | Ответ B2 по VPS | Ожидание в VPS | Сопоставленный ответ в PCAP |
|---|---:|---:|---:|
| 1 | 1,188 с | 0,0038 с | 1,182 с |
| 2 | 1,995 с | 0,0035 с | 1,989 с |
| 3 | 2,758 с | 0,0044 с | 2,753 с |
PCAP подтверждает три отдельных прикладных кадра, по одному на операцию,
ответы с совпадающими токенами/CRC и кодом 0. Повторов и TCP reset в этой
100-секундной записи нет. Измерения относятся к запросам позиции; исполнение
выходов, аварийный reboot, максимальная пропускная способность и длительный
радиообрыв этой серией не проверялись. USB serial не открывался; настройки,
SIM, прошивка B2, Node и версия VPS не менялись.
Пройдены 215 backend-проверок до заключительных исправлений; после них —
87 целевых проверок очереди, API, журнала, сетевых операций и оборудования,
включая временную ошибку SQLite, потерянный POST, перезапуск, неизменность ID,
отмену при конкурирующей отправке, исходный deadline, перепривязку и полный
размер очереди. Также прошли Ruff, архитектурные проверки, TypeScript,
1007 frontend-тестов и production build. Существующие предупреждения
Starlette/httpx и большого JS chunk сохраняются.
Приватная сессия доказательств:
`command-runtime-0a8b7a08711746f08b55f0e32a4313f6`.
В неё входят исходные пакеты, снимки журнала, резервные копии, UTC/monotonic
отметки, программа анализа и SHA-256 manifest. Это ограниченная приёмка на одном
B2; ровно одно физическое исполнение и масштаб в тысячу устройств не заявляются.
+287
View File
@@ -0,0 +1,287 @@
# B2: границы связи и план квалификации
Состояние исследования: 2026-09-27. Область принятия: один тестовый B2,
модель 231, прошивка 0.01; текущий VPS Host 0.1.26. Исторические результаты
0.1.24/0.1.25 ниже сохраняют собственную область принятия. Это не гарантия для всех B2,
операторов, прошивок или парка из тысячи устройств.
## Источники и граница достоверности
- [Руководство B2 производителя](https://8888.arusnavi.ru/Arnavi%20B2/Arnavi%20B2%20%D1%80%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE%20%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8F%20%5B241219%5D.pdf):
разделы 1–3, 9–10. Имя файла содержит 241219, заголовок PDF — 241220.
- [INTERNAL производителя](https://docs.google.com/spreadsheets/d/15s-2ZbqOQ1bZvAtFFm9sIEuKy3jbJzxdeynp72sjoYU/edit):
SERVER_COM и TAG99/DS2, определения SIM и состояния GPRS.
- Публичная схема конфигуратора модели 231: поле 72, биты 10 и 20 —
запреты GPRS по слотам. Сохранённый первичный материал использовался
при квалификации; неизвестные поля полной конфигурации сохраняются.
- [Каталог прошивок B2](https://8888.arusnavi.ru/Arnavi%20B2/%D0%9F%D1%80%D0%BE%D1%88%D0%B8%D0%B2%D0%BA%D0%B8/)
содержит 0.05. Наличие файла не доказывает исправление обнаруженной проблемы.
Списка изменений и принятия этой версии в нашем тракте пока нет.
- Поиск B2 в форумах Wialon/Gurtam и общедоступных обсуждениях не дал
проверяемого описания точного алгоритма SIM и его таймеров. Описания других
ARNavi и новости об их прошивках нельзя переносить на B2 0.01.
Руководство подтверждает 2G (GSM/GPRS/EDGE), два SIM-держателя, четыре сервера,
внешний Wi-Fi-модуль и SMS/TCP-команды. Устройство имеет совмещённые интерфейсы:
вторая CAN-линия использует ресурс RS485. Подключение всех возможностей сразу
из перечня не следует из наличия разъёма. Детального расписания двух SIM,
гарантированных задержек команд и API выбора приоритетной SIM руководство
не устанавливает.
## Что означает выбор SIM
На принятой прошивке DS2 сообщает одну выбранную SIM для GPRS. Две регистрации
в сети не являются доказательством двух независимых подключений к интернету.
Наш способ выбора включает GPRS целевого слота и запрещает его другому слоту.
Это **исключительный выбор**, а не предпочтение с автоматическим резервом.
Само изменение этих флагов не переключило соединение за 93 секунды предыдущего
USB-опыта. Положительный результат получен после перезапуска. Текущая операция
`select-sim`: свежий снимок → запись → независимое чтение → один restart →
свежая DS2 целевой SIM через новое соединение. Успех записи не равен успеху
подключения. Отсутствие ответа после записи оставляет неопределённый результат;
повтор записи или restart автоматически не запускается.
Оператор определяется по полученным кодам сети. APN и номер телефона не служат
доказательством оператора. Неизвестный код остаётся неизвестным. Замена SIM не
означает, что устройство или Core умеют определить корпоративный APN, пароль
доступа и ограничения тарифа. Пока связи нет, VPS не может доставить по этому же
каналу параметры для её восстановления. Локальный USB или независимо
работающий SMS-канал — отдельные способы восстановления; SMS-инфраструктура
в продукте не квалифицирована.
## Задержка состоит из разных этапов
Для принятого ранее перехода SIM1 → SIM2 исключительно через Core/VPS:
| Этап | Время |
| --- | ---: |
| Создание операции Core → создание на VPS | 0,733 с |
| Создание Core → передача образа настроек | 26,486 с |
| Создание Core → проверка образа и отправка restart | 45,053 с |
| Restart → свежая целевая DS2 на новом соединении | 210,044 с |
| Полная операция | 255,097 с |
Последние 210 секунд нельзя называть временем регистрации модема: туда могут
входить повторные соединения, доставка накопленных сообщений и ожидание свежего
подтверждения. Предыдущий USB-опыт с restart дал около 79 секунд, но это другая
процедура, а не доказательство постоянного ускорения. Набора для p95/p99 нет.
В настройках введены две паузы по 15 секунд между обменами полным образом:
ранние испытания без них теряли последующий запрос. Они не относятся к
обычным командам позиции/выходов. Уменьшение пауз требует отдельного сравнения
долей успешных операций; просто убрать ожидание — не установленная оптимизация.
## Исследование сбоя 27 сентября
Приватная сессия `communication-limits-69cdaddac9c74079b059d8115a2d62aa`.
Исходный обрыв существовал до эксперимента. USB подтвердил ровно принятый
образ SIM2: 207 записей, 983 байта; параметры не потерялись.
Одновременная пассивная запись USB и VPS установила:
- B2 повторно открывал TCP и отправлял одинаковый пакет №13 с семью старыми
измерениями; это не свежая телеметрия, несмотря на новые подключения.
- VPS формировал четырёхбайтовый ответ за 3,123–3,866 мс после получения пакета.
- В трёх случаях после ответа приходил RST+ACK через 9,013–10,370 мс.
TTL обычных входящих пакетов был 117, а RST — 40–42; различался также IP ID.
- Девятибайтовые ответы на заголовок точно найдены в USB-потоке модема.
Подтверждения пакета №13 в этом потоке не найдены. RST+ACK нельзя засчитывать
как нормальное подтверждение доставки данных.
**Вывод ограничен:** видны сбросы на транспортном пути и застрявшая очередь.
Признаки совместимы с вмешательством промежуточного оборудования. Они не
идентифицируют виновника, не доказывают фильтрацию конкретным оператором и
не доказывают ошибку прошивки. Проверка с другим путём/оператором/портом должна
сохранять те же байты протокола и сопоставимые условия.
Один запрос позиции на исходном соединении был отправлен, но не подтверждён.
Затем выполнено отдельное USB-восстановление: изменено только поле 72 на SIM1,
сохранены APN и остальные 206 записей, выполнен один квалифицированный restart.
Это не приёмка обратного переключения через VPS.
После восстановления поток продолжился, сначала выгружая старые измерения SIM2,
затем появились свежие SIM1/GPRS. Поэтому нужно различать время поступления,
время измерения и текущую активную SIM. От USB-restart до первого наблюдаемого
`online` прошло 80,416 с, но возраст последнего измерения тогда составлял
1526,508 с. SIM1 впервые появилась через 213,259 с; свежая SIM1 с возрастом
меньше 30 с — через 234,371 с. Это времена опросного наблюдения Core, а не
точные моменты регистрации в сотовой сети. USB-проверка точного образа прошла;
аппаратные идентификаторы сохранились. Проверка полного объекта identity дала
отказ: сообщаемая строка SIM1 изменилась с 12 на 20 символов. Это наблюдение
модема, а не основание объявлять замену оборудования; исходный отказ сохранён.
На SIM1 выполнены три отдельных запроса позиции: при выгрузке очереди, после
появления свежей DS2 и с одновременной записью USB/PCAP. Все три остались
`unconfirmed`. Очередь VPS составила 6,327; 6,525 и 5,560 мс соответственно.
В последнем опыте двенадцатибайтовый кадр команды виден на выходе VPS и его
TCP-повторы продолжались, однако нормального TCP ACK и точного кадра в
USB-потоке за окно наблюдения не было. Это не измерение времени исполнения
команды: её доставка не подтверждена. Предыдущий успешный ответ за 1,66 с
не превращается в гарантию на основании одной удачной попытки.
В двух пассивных окнах SIM1 после восстановления входящих RST не наблюдалось,
пакеты телеметрии продвигались. Условия и время различались; этого недостаточно
для вывода «МегаФон всегда работает, МТС всегда неисправен».
Обнаружено дополнительное ограничение тайм-аута: 30 с сейчас ограничивают
**ожидание результата в приложении**, а не срок жизни уже переданных ядру TCP
байтов. В PCAP повторная передача была видна и после этого срока. Поэтому
текущая версия не обеспечивает жёсткую отмену запоздавшей команды. Даже
закрытие сокета не отменяет действие, уже принятое устройством. Для дальнейшей
квалификации требуются ограничение неподтверждённых TCP-данных, явная семантика
неопределённого исхода и, где это поддерживает устройство, срок действия самой
команды. Автоматически повторять воздействия после тайм-аута нельзя.
В конце опыта Core прочитал USB-снимок и сохранил соответствующий выбор SIM1.
Перед проверкой применения вычисленный полный образ сравнен с фактическим;
он уже совпадал. Штатная проверка вернула `unchanged`: дополнительной записи
или перезапуска не произошло. Свежая DS2 подтвердила SIM1/GPRS. Настройки
обеих APN остались исходными. Продуктовый код и VPS 0.1.24 не изменялись.
## Контроль без USB
Следующая сессия `network-only-278ac319e262481d971a22cd1b4480ef` выполнялась
после исчезновения USB-интерфейса B2 из системного перечисления Mac. USB-порт
не открывался. На SIM1 продолжали поступать свежие данные. Отправлен один
`request-position`; конфигурация, выходы и перезапуск не затрагивались.
Команда получила `device_confirmed`, код 0. Очередь VPS — 4,374 мс,
от отправки до подтверждения устройства — 1,320 с. Независимая запись TCP
содержит ответ с совпадающим токеном через 1,314 с после кадра команды;
в этом окне входящих RST не было. Это положительный контроль работоспособности
команд без USB. Одна удачная попытка не доказывает, что USB был причиной
предыдущих отказов, и не устанавливает верхнюю границу задержки.
Исправление тайм-аута должно охватывать сокет, а не только статус операции.
[Linux TCP_USER_TIMEOUT](https://man7.org/linux/man-pages/man7/tcp.7.html)
ограничивает время неподтверждённых данных конкретного TCP-соединения.
Обычное [asyncio close](https://docs.python.org/3/library/asyncio-protocol.html#asyncio.BaseTransport.close)
предусматривает отправку буфера при закрытии; его нельзя считать отменой.
Критерии исправления: прекращение передачи на принятой ОС, отсутствие повтора
команды на новом соединении и сохранение честного неопределённого результата.
Проверка выпуска 0.1.25 описана ниже.
Принятое B2 действие закрытием сокета отменить нельзя. В этой сессии настройки
сокетов и продуктовый код не менялись.
## Ограничения нашего сервера
Установлены чтением кода 0.1.25, а не нагрузочным испытанием:
| Механизм | Текущее ограничение | Следствие |
| --- | --- | --- |
| TCP receiver | 256 одновременных соединений | Это не 256 устройств: один B2 может открыть несколько соединений, включая конфигурацию. Тысяча устройств не квалифицирована. |
| Приём пакетов | 180 с без чтения закрывают соединение | Длинная стоянка/сон и интервалы требуют проверки. |
| Диск | Журнал 512 MiB, резерв свободного места 256 MiB | При заполнении применяется обратное давление; нельзя обещать неограниченное хранение. |
| Команды | Одна незавершённая операция на устройство | Массовые изменения должны иметь очередь по устройствам. |
| Обычные действия | 3 с на начало отправки, 30 с на ожидание подтверждения | С 0.1.25 очередь сокета обрывается по сроку. Уже принятые трекером или находящиеся в сети данные отменить нельзя. |
| Полная конфигурация / SIM | 180 / 360 с на VPS | Истечение срока не означает откат уже переданного образа. |
| Проверка образов | Корреляция IMEI, peer IP, модели, CRC | Это не криптографическое удостоверение B2; разные CGNAT-адреса двух сокетов пока не квалифицированы. |
| Core ↔ VPS | Аутентификация и закреплённый TLS-сертификат | Не распространяется автоматически на legacy INTERNAL B2 ↔ VPS. |
## Очерёдность дальнейшей работы
1. Довести наблюдаемость доставки: очередь → запись в сокет → TCP-подтверждение
без RST → подтверждение устройства → наблюдаемый результат. Для выхода
отдельно различать логическое состояние и физический контакт реле.
Граница TCP исправлена в 0.1.25 ниже; физический результат выходов и
гарантированная задержка остаются отдельными вопросами.
2. Сравнить пути связи одинаковыми командами и одновременными USB/PCAP-данными.
Сначала устранить устойчивый сбой обмена; затем измерять серию задержек.
3. Квалифицировать оба направления SIM через сеть и отдельно отсутствие
интернета у выбранной SIM. Возврат с USB не выдавать за автоматический резерв.
До доказанного локального fallback не обещать удалённое восстановление из
полного отсутствия связи.
4. Исследовать ускорение свежего статуса при выгрузке архива и допустимость
более коротких пауз конфигурации, не меняя критерий успешной записи.
5. Проверить точную спецификацию и совместимость следующей прошивки до
отдельного испытания. Обновление не является гарантированным откатом:
сохранённый файл прошивки сам по себе ещё не доказывает рабочий downgrade.
6. Масштабирование выполнять на серверном стенде: лимиты сокетов, несколько
соединений на устройство, очереди, диск, восстановление процесса и массовые
переподключения. На операторском Mac нагрузочные тесты не запускать.
Автономия от кабинета ARNavi для уже принятого тракта связи возможна и частично
проверена. Полная автономия жизненного цикла, надёжный резерв SIM и гарантия
быстрых команд пока не приняты. Если задача требует жёсткого времени реакции
на геозону, проектировать локальную логику на борту; наличие такой произвольной
логики в B2 данным исследованием не подтверждено.
## Проверенная граница доставки в VPS Host 0.1.25
Сессия выпуска `delivery-a8d26be666ec4dd182f46a4db8d0c566`, 27.09.2026.
Командный кадр имеет монотонный срок: не позже завершения операции и не
дольше 30 секунд после отправки. Для HTTP-ответа с настройками предел —
12 секунд, также ограниченный сроком операции. Watchdog учитывает обе очереди:
пользовательский буфер asyncio и неподтверждённые байты Linux `TIOCOUTQ`.
Временная граница снимается с конкретного кадра после TCP-подтверждения;
это **не** меняет результат команды на «выполнено».
При истечении срока соединение закрывается с `SO_LINGER={1,0}` и
`transport.abort()`. Тот же режим действует при разрыве соединения и остановке
обработчика. Поэтому уже закрытый сокет не продолжает отправлять его старую
очередь. Дополнительно включён per-socket `TCP_USER_TIMEOUT=30000`, без
изменения системных настроек Linux. Семантика аварийного закрытия и очистки
очередей проверена по [исходнику Linux TCP](https://github.com/torvalds/linux/blob/v6.8/net/ipv4/tcp.c).
Встроенная в артефакт `qualify_delivery.py` проверка на Linux 6.8.0-137-generic
использовала два локальных соединения, без B2, firewall и изменения служб:
- Подтверждённые TCP 12 байт без ответа приложения: соединение остаётся открытым.
- Заблокированный получатель: перед сроком 2304 байта оставались в ядре,
62080 — в asyncio. При тестовом сроке 0,750 с аварийное закрытие произошло
за 0,751091 с; клиент получил reset, дескриптор сервера закрыт.
На настоящем B2 без USB выполнен отдельный запрос координат — сессия
`network-only-b5c513eb06da42d599fb515e66b8a83d`. Очередь VPS заняла 4,791 мс.
TCP-подтверждения команды не было; запись содержит отправку и повторения на
1,360 / 4,750 / 11,854 / 25,678 секунды. Исходящий reset произошёл на
29,994 секунды после первого кадра, около границы 30 секунд от создания
операции. В 45-секундной записи нет кадров этой команды после срока и нет
её переноса на другое соединение. Результат — `unconfirmed`; интерфейс
снял ожидание и снова разрешил действия. Телеметрия B2 продолжила поступать.
Первый контрольный запрос сразу после обновления не появился в журнале
команд VPS, а Core завершил его как `uncertain`. Он не повторялся. Неудачная
попытка и её частичная запись сохранены в
`network-only-0e6ee734cd8c436eae6e4984e154ba63`; это не измерение успешной доставки.
154 целевых backend-теста (153 общим проходом и один добавленный тест срока
HTTP отдельно), 1004 frontend-теста, архитектурные проверки, typecheck и
production build прошли. Две сборки установщика совпали побайтно. Версия
0.1.25 установлена штатным установщиком, четыре файла идентичности/ключей
сохранили SHA-256, загрузка этой же сборки опубликована в Mission Core.
Настройки B2, SIM и бортовой Node в этом изменении не записывались.
Ограничение: это прекращение **дальнейшей передачи сервером**, а не отмена
команды, уже принятой трекером или находящейся в сети. Это не система жёсткого
реального времени: задержка event loop/ОС остаётся возможной. Работа обратного
мобильного канала и задержка физического исполнения по-прежнему не гарантированы.
## Сравнение помещения и улицы
[Полный отчёт от 27.09.2026](INDOOR_OUTDOOR_COMPARISON_20260927.md): после переноса
и подключения USB спутников стало 14–16 вместо 8, показатель активной SIM1 —
20–22 вместо 16. Пять отдельных запросов позиции на VPS 0.1.25 подтверждены
B2 за 0,519–1,105 с; медиана 0,604 с. Во всех пяти сетевых записях команд
проверены контрольная сумма, токен ответа и код 0; повторных передач не было.
USB serial не использовался, настройки и выходы не менялись. Это совместное
изменение места/USB/возможного питания, а не изолированное доказательство
влияния улицы. Пропускная способность, долговременная надёжность и непрерывность
питания этим опытом не установлены.
## Возврат в помещение и runtime 0.1.26
На той же 0.1.25 после возврата подтверждены 5/5 запросов: 1,191–2,264 с,
медиана 1,677 с; спутники 14–17, SIM1 15–22. Один TCP-повтор команды завершился
подтверждением. После обновления 0.1.26 ещё 3/3 запроса подтверждены за
0,887–2,224 с; повтор каждого запроса к Core сохранил исходный ID и не создал
вторую команду. Уличная медиана 0,604 с меньше комнатной, но роль питания,
времени и радиоканала по этим сериям не разделена.
[Контракт runtime](WEAK_LINK_RUNTIME.md) описывает долговечную исходящую очередь
Core, дедупликацию, исходный срок действия, ожидание соединения для чтения и
отсутствие повтора неопределённых воздействий. Индекс активных операций и
пробуждение по событиям уменьшают работу сервера без команд. Это не расширение
физических возможностей 2G, не автоматический резерв SIM и не приёмка тысячи
трекеров. Все следующие аппаратные испытания — в помещении.
@@ -0,0 +1,132 @@
# B2 configuration clock and session freshness — 2026-09-27
## Current result
VPS Host **0.1.29** is installed and published in Mission Core. The same qualified
installer can reproduce the deployed code. The host now answers the observed
configuration clock request itself and defers configuration dispatch on silent
monitoring streams. This closes two concrete protocol/transport gaps. It does
**not** establish reliable remote configuration or complete vendor independence.
A physical write reached the B2 and changed only field 25 from 15 to 16 seconds.
The device then stopped communicating with the VPS; verification could not be
sent before the operation expired. A fresh USB read established that the change
had actually applied. One qualified USB restoration and an independent full read
restored the exact 207-record / 983-byte baseline at **14:48:32 UTC**. Core's cache
was reconciled without rewriting the failed network history. Network recovery
after this write remains a separate acceptance gate.
## Reference-qualified clock response
Two owner-authorized bounded diagnostic exchanges sent the same captured
20-byte opcode-7 request to the manufacturer's configuration endpoint. They
contained identity/model/firmware/request code, not configuration, passwords,
SIM data or coordinates. The replies were ten bytes:
`5b 0006 00 07 <Unix UTC seconds:u32be> 5d`
The four-byte value fell between each request's wall-clock start/end and advanced
by 36 seconds between exchanges. Host 0.1.28 introduced a dynamic response from
its own synchronized clock. It never replays the reference timestamp. An admitted
model-231/0.01 identity and active matching modem peer are required. This response
cannot advance or confirm a configuration transaction or extend its deadline.
The owned runtime makes no manufacturer calls. Reference queries are engineering
qualification, not a dependency of the product. Two repeated clock exchanges on
one real Linux loopback HTTP connection passed in isolated state. Physical
traffic subsequently showed the B2's opcode-7 request and our matching response.
That observation is not proof that every firmware clock/startup path is covered.
## Physical sequence and remaining limits
| Phase | Observation | What it establishes |
| --- | --- | --- |
| First read on 0.1.28 | Expired after 180.757 s; B2 requested opcode 2 instead of uploading | No settings image was sent by this read |
| Bounded recovery exchange | Fresh USB image matched baseline; one unchanged image served after an explicit download request | One intentional engineering write, not a normal automatic retry |
| Following exchange | Opcode 6, full opcode-5 upload and opcode-7 time exchange | The owned clock response worked on the physical dialogue |
| Independent network read | Exact baseline in 6.022 s | A fresh full read succeeded |
| Repeated 0.1.28 read | No TCP ACK for the command; six TCP transmissions, abort at 29.999 s; operation ended at 180.718 s | A drained old socket was still unusable; retransmission here was TCP, not application replay |
| First 0.1.29 read | Waited for fresh input; exact baseline received in 24.119 s total | Freshness admission worked on one physical read |
| 0.1.29 write | Fresh preflight, one download request, one image response | Three commands individually TCP-acknowledged in 0.657, 0.550 and 1.231 s |
| Image delivery | Complete 989-byte response body TCP-acknowledged after 1.011 s | Transport delivery; not sufficient alone to confirm application |
| Write verification | No fresh monitoring input after download; operation ended uncertain in verify at 180.927 s | No automatic replay and no false successful application |
| Independent USB inspection | Field 25 = 16; other 206 records unchanged | This network write actually applied |
| USB restoration | Field 25 = 15, exact independent readback | Baseline restored; remote restoration did not pass |
Only one physical tracker, model 231 / firmware 0.01, was used indoors with 12 V
and USB connected. No USB serial operation ran during the timed network phases.
These observations do not isolate RF quality, two-SIM behavior, USB electrical
stability, firmware configuration reload or carrier transport. They are not a
latency guarantee or a fleet-scale reliability result. The recovery lease is
explicit engineering tooling and is not an automatic production recovery path.
## Freshness admission in 0.1.29
The previous Linux guard required no queued asyncio/kernel bytes. A silent
connection can satisfy that check while its cellular path has already failed.
Configuration commands now additionally require input from the B2 within five
monotonic seconds. Otherwise they remain queued until new device input arrives
or their original operation deadline expires. Among eligible drained streams,
the most recently active one still wins. The five-second bound is a conservative
admission policy, not a documented modem guarantee. Position/output policy is
unchanged. Dispatched stages and images are never automatically replayed.
The physical three-command sample dispatched about 1.01 seconds after incoming
telemetry and got TCP acknowledgements without retransmission. This is a narrow
positive observation; it did not solve post-write reconnection.
Core also now retains VPS creation and stage-dispatch timestamps for full
configuration operations. Each distinct dispatch timestamp enters the journal
once; repeated status polling does not duplicate it. Confirmed verification time
has its own evidence event. Invalid/non-finite timestamps and private payloads
are excluded. Historical entries without these facts are not fabricated.
## Release validation and evidence
- Installer SHA-256: `c6637e2578c48771b65aae28e2754b5386fa125e2ae416df1c59824f3e62acd7`.
- Two builds produced identical installer/tar/manifest hashes. All 23 installed
manifest files match the artifact. All four identity files were preserved;
state backups precede installation. VPS time synchronization was checked.
- Focused VPS/Core/protocol tests and Ruff passed; frontend typecheck/build
passed. Configuration-timeline regression tests passed separately.
- Artifact-owned isolated Linux delivery, durable runtime, six fault scenarios,
HTTP clock and fresh-packet wakeup checks passed. The new wakeup scenario uses
a real loopback telemetry frame and verifies one command dispatch with an
unchanged expiry. No physical tracker or production journal is used by it.
- An initial 0.1.29 qualifier candidate used the wrong expected package ACK in
its test harness. It failed and was not installed. The corrected final artifact
passed. The same principle applies to the earlier rejected 0.1.28 harness.
- Browser QA on canonical port 8000 showed the real command history and current
pending/terminal operations. No onboard Node update or relay action occurred.
Private sessions: `clock-8a29efb2006e4744a86a5d046839fe81`, its
`reconcile-351ce7ef505b4547a53d3c805415253c` child,
`clock-roundtrip-*`, and `fresh-31bf7b0ede4f4fe1808508c51b56a873`.
Raw traffic, device identity, SIM values, complete images and state backups remain
in ignored owner storage. Hash manifests preserve UTC/monotonic times and scope.
The 0.1.29 capture ended after the failed operation when Core was deliberately
reloaded for the journal fix; it must not be described as a complete 360-second
capture. A separate bounded recording covers the requested hardware recovery.
## Next acceptance gates
1. Explain and qualify post-image-write reconnection, including startup HTTP
exchanges and modem return. Confirm recovery without USB, not merely a write.
2. Repeat complete read → one-field write → readback → restoration → independent
read cycles, including controlled outages and host restart, with honest
uncertain outcomes and no replay of dispatched effects.
3. Separate persisted one-shot SIM activation from reusable desired settings;
verify unchanged APN/identity handling on unrelated edits.
4. Complete the factory-fresh bootstrap and remaining configuration categories
listed in [the coverage audit](CONFIGURATION_COVERAGE_20260927.md).
## Handoff state
The final download checksum matched the installed 0.1.29 artifact. Core remains
on port 8000 with no listener on 8765 and no pending outbox command. The browser
shows VPS 0.1.29 online and the B2 last packet at 14:43:23 UTC. A six-minute bounded
recovery observation ended while awaiting the operator power-cycle confirmation;
no completed physical cycle or network recovery is claimed. The original image
is independently restored and both USB descriptors and temporary captures are
closed. Continue with the operator-confirmed power cycle, then inspect actual
network return and configuration before any further write.
@@ -0,0 +1,137 @@
# B2 configuration coverage and recovery audit — 2026-09-27
The owner's target is independent admission, telemetry, settings and commands
through the owner's VPS. A complete image transport is necessary, but does not
by itself qualify every setting, accessory or firmware operation.
## Evidence and scope
One physical B2, model 231 / firmware 0.01, VPS Host 0.1.26, canonical Mission
Core, indoor operation on 12 V. No USB serial access, manufacturer device
requests, firmware changes or output actuation in this audit.
The initial fresh network read returned **207 records / 983 bytes in 6.018 s**,
identical to the retained baseline. The scalar profile overlay, without edits,
reproduces all bytes exactly. Monitoring slots 1 and 2 and configuration fields
70/71 point to the owner receiver; monitoring slots 3 and 4 are disabled.
These are configuration facts, not a claim about all possible firmware traffic.
The public model-231 configurator schema contains 12 sections. Its newer default
values are not a source of missing device settings. Eight catalogued GNSS filter
parameters (241–248) are absent on this physical firmware. Five present records
(70, 71, 135, 136, 138) are absent from that public UI schema; the configuration
endpoint semantics for 70/71 were qualified separately.
## What is editable today
The portable catalog has 86 scalar definitions; **78 occur with supported widths
in this device image**. There are no incompatible-width catalogued records in
this sample. This count is parser/editor coverage, not 78 physical write tests.
| Manufacturer section | Present records | Portable scalars | Separate handling | Preserved, not fully edited |
| --- | ---: | ---: | ---: | ---: |
| Monitoring servers | 20 | 0 | 12 | 8 |
| Packet composition | 1 | 0 | 0 | 1 |
| Track generation | 13 | 12 | 1 | 0 |
| Inputs and outputs | 12 | 0 | 0 | 12 |
| Digital ports | 22 | 0 | 1 | 21 |
| Modbus | 16 | 0 | 0 | 16 |
| BLE sensors | 22 | 0 | 0 | 22 |
| Driving quality | 68 | 66 | 0 | 2 |
| Phone numbers | 10 | 0 | 0 | 10 |
| SIM settings | 15 | 0 | 7 | 8 |
| Navigation | 1 | 0 | 0 | 1 |
| System modes | 6 | 0 | 1 | 5 |
Rows can overlap a shared bitfield; do not add the columns as unique-record
totals. “Separate handling” means endpoint/APN handling or only selected bits of
record 72. It is not full-section support. Unique identifiers, phone numbers,
device passwords, sensor addresses and SIM credentials must not become generic
portable profile defaults.
The offline checker is
`k1link.device_plugins.arnavi_b2.configuration_audit`. It reports record IDs,
counts, hashes, overlay compatibility and destination classifications. It never
prints configuration values, contacts a service or synthesizes missing fields.
Its reference input is the cached [public model schema](http://webconfigurator.ru:8089/public-api/v1/device-types/231/configuration/with-translations).
The hardware command reference remains the manufacturer's
[B2 documentation directory](https://8888.arusnavi.ru/Arnavi%20B2/), especially
manual sections 9–10. Neither source authorizes unqualified binary writes.
## Physical transaction results
- Field 25, stationary interval: **15 → 16 seconds verified in 48.276 s**.
The other 206 records remained byte-identical.
- First return to 15: expired unconfirmed at the write-request stage after
361.928 s. The VPS never served the target image and never dispatched the
subsequent SIM restart. A separate 6.026 s network read found **16**, not 15.
- An explicit second restoration, with SIM activation removed from that
transaction, expired in preflight after 180.735 s. No image was served.
- A bounded receiver capture shows the preflight command retransmitted by TCP
while other telemetry sessions remained active. Application success cannot
be inferred from online status or from writing bytes into a socket.
- One separate restart request was followed by fresh telemetry on a new TCP
connection after 12.299 s (`reconnected`). This is connection evidence, not
proof of a CPU restart. The subsequent full read expired in preflight after
180.750 s without a new image.
**Recovery completed through USB at 14:03:28 UTC.** The owner confirmed all
indicators off, ten seconds without power, then 12 V only. The first subsequent
network read returned field 25 = 16 in 15.039 s. Two explicit restoration attempts
still expired: 180.824 s in preflight, then 180.889 s at the write-request stage.
Neither served an image. Power cycling did not resolve remote configuration.
The subsequently installed Host 0.1.27 adds outbound transport readiness checks.
Its restoration attempt obtained a fresh predecessor image, but expired after
180.864 s at the write-request stage without serving an image. TCP acknowledged
the download command after 0.723 s; no corresponding image request arrived.
See [the bounded readiness qualification](OUTBOUND_READINESS_20260927.md).
After the owner connected USB, a new identity-bracketed read found exactly the
test image: only field 25 differed from the baseline. One qualified USB write
restored 15. Its readback and a separate full read matched all 207 original
records byte for byte. Core subsequently reread the hardware through its USB
inspection API and retained the failed network receipt. Desired settings remain
original; no operation is pending. This is **USB recovery**, not acceptance of
the remote write/read/restart roundtrip.
## Product findings and next acceptance gates
1. Fixed the USB bootstrap's stale version allowlist: shipped VPS 0.1.26 was
rejected even though its qualified provisioning protocol is unchanged. A
regression checks the shipped artifact version; unknown versions still
fail closed. This is synthetic bootstrap admission acceptance, not a new
factory-fresh hardware run.
2. Saved `connectivity.activate` is persistent intent. Editing an unrelated
profile field can therefore start a `select-sim` transaction and an extra
restart. Separate the one-time activation action from desired configuration,
including live-SIM confirmation and recovery of previously applied flags.
Do not fix this by assuming matching stored flags prove the selected modem
SIM already changed.
3. Settings recovery still needs physical qualification. Distinguish read
request, image served, independent readback and reconnection. Preserve the
original deadline and history. Never turn an uncertain image write into an
automatic repeated write or silently replay actuation on another session.
4. Only after the recovery gate, extend the editor with validated per-field
schemas and readback acceptance for system/packet settings, I/O and digital
ports, then Modbus and BLE. Accessory function needs a known wiring fixture;
image readback cannot prove relay, CAN or sensor behavior.
Evidence session: `configuration-audit-874d3d549dbd41e9a258412c676af6ac` under
ignored private outputs. Raw images, identifiers, traffic and credentials remain
private. Redacted manifests include UTC/monotonic times and artifact SHA-256.
Initial audit validation: 115 focused backend tests passed; Ruff passed for the bootstrap and
audit modules/tests. The canonical Core service was reloaded through its managed
LaunchAgent after consistent SQLite backups; its health was accepted. No VPS
code/installer or frontend change belonged to that initial audit. The subsequent
0.1.27 release and recovery checks are recorded in the linked qualification.
## Subsequent 0.1.29 qualification
The [clock/freshness follow-up](CONFIGURATION_CLOCK_AND_FRESHNESS_20260927.md)
records two reference clock requests, owned time handling, fresh-stream admission
and a further applied physical write with failed post-write network return.
USB independently restored the exact 207-record baseline at 14:48:32 UTC.
This adds protocol coverage, not general remote-configuration acceptance.
@@ -0,0 +1,105 @@
# Две SIM: идентичность, перестановка и связь, 2026-09-28
Сессия: `dual-sim-identity-e81e0384e86d442dbda64636d8dbd563`.
Тот же B2, модель 231, прошивка 0.01; ранее испытанная МТС и предоставленная
владельцем МегаФон. Все перестановки выполнены владельцем при отключённых
12 В и USB, затем подключались 12 В и USB для пассивной записи запуска.
## Результат двух расстановок
| Расстановка | Идентификация в потоке запуска | Свежая связь с VPS |
| --- | --- | --- |
| МегаФон — SIM 1, МТС — SIM 2 | Два различных CCID/IMSI; домашние коды 25002 / 25001 привязаны к соответствующим слотам | SIM 1, МегаФон; в модем передан сохранённый APN `internet` |
| МТС — SIM 1, МегаФон — SIM 2 | Сырые CCID, IMSI и SID из потока запуска совпали с прежними картами и переместились в новые слоты; домашние коды 25001 / 25002 | SIM 2, МегаФон; в модем передан сохранённый APN `internet.mts.ru` |
В обеих расстановках VPS получил свежие коды сетей обеих карт. После обмена
один запрос координат через Core → VPS → B2 подтверждён устройством с первой
попытки: код 0, `device_confirmed`, **0,999 секунды** от отправки VPS до ответа.
Создано 08:14:03.157 UTC, отправлено 08:14:03.198, подтверждено 08:14:04.197.
Это одиночный контрольный запрос, не оценка гарантированной задержки.
Конфигурация оставалась прежней во всех трёх штатных чтениях: 207 записей,
983 байта, SHA-256
`a3b52af5900740cce3eae4db31390a2c2887ba59c7fab99e50595f7e3a48b7ae`.
Мы не записывали APN, прошивку или выходы и не выбирали активную SIM командой.
После обмена карточек B2 не перенёс сохранённые APN вслед за ними.
Успешный выход через эту МегаФон с APN `internet.mts.ru` не означает, что такой
APN подходит всем картам оператора, и не доказывает автоматический подбор APN
прошивкой. Причина допуска этого подключения оператором не установлена.
В этой сессии не проверялся выход МТС через первый слот с её правильным APN.
## Важное ограничение штатного запроса идентичности
В потоке запуска обе карты выдавали SID длиной 20 цифр, а ответы внутреннего
модема на `AT+CIMI` содержали разные 15-значные IMSI. После обмена картами
совпадение подтверждено по хешам исходных ответов и соответствию слотам.
Наш USB-наблюдатель не отправлял эти AT-команды: их посылала прошивка B2.
Однако штатное чтение `I 7`, обрамляющее чтение конфигурации, дало другой результат:
| Карты в слотах | SID0 при `I 7` | SID1 при `I 7` |
| --- | --- | --- |
| МегаФон / МТС | 12 цифр, не совпадает с исходным SID МегаФона | 20 цифр, совпадает с МТС |
| МТС / МегаФон | 12 цифр, не совпадает с исходным SID МТС | 20 цифр, совпадает с SID МегаФона из запуска |
| Повторное чтение без перестановки | Те же 12 цифр для МТС | Те же 20 цифр для МегаФона |
Оба запроса идентичности внутри каждого чтения согласовались друг с другом;
проверены сами байты ответа, не только JSON-проекция. Короткие значения для
разных карт различаются и не являются префиксом/суффиксом полных исходных SID.
Нельзя объявить их полными ICCID или восстанавливать догадкой. Причина
расхождения внутри B2 не установлена; повторное чтение не устранило её.
Ранее [одна МТС без второй карты](SIM_SLOT_IDENTITY_20260928.md) возвращала
полный ICCID через тот же `I 7` в обоих слотах. Это существенная граница приёмки:
успех с одной картой нельзя переносить на две одновременно установленные SIM.
## Разные формы номера МегаФона
Сырой ответ модема `AT+CCID` для этой МегаФон содержит 18 десятичных цифр и
два символа `ff`. Следующий SID, сформированный B2, содержит 20 десятичных цифр:
первые 18 совпадают, окончание отличается. Обе формы повторились после обмена
слотами. У МТС сырой CCID и исходный SID совпадают полностью.
В доказательствах сохранены обе формы отдельно. Никакой нормализации `ff`,
дополнения цифрами или вывода оператора по длине номера не выполнялось.
Совпадение 20-значного SID само по себе не делает его каноническим ICCID.
Данные операторов в этой проверке подтверждались IMSI/домашними кодами и
свежими кодами обслуживающих сетей, независимо от настроенных APN.
## Метод, доказательства и завершение
Пассивная USB-запись: около 130,5 с / 20 205 байт в первой расстановке и
170,1 с / 27 487 байт во второй. Настройки tty и явные линии управления модемом
не менялись, наш наблюдатель в USB не писал. Затем выполнялись штатные
ограниченные чтения продукта; третье чтение повторяло второе для проверки
нового расхождения идентификатора.
Захват VPS ограничен 600 секундами, портом TCP 9922, снимком 96 байт:
262 пакета захвачено, 262 получено фильтром, 0 потерь ядра. Контрольная команда
после перестановки пришлась уже после окончания этого захвата; её доказательство —
журнал операции/попыток VPS и свежая телеметрия, а не этот PCAP.
Сырые CCID, IMSI, SID, координаты, конфигурация, USB-потоки и пакеты сохраняются
только в приватном каталоге сессии под `outputs/arnavi-b2/`, вне Git. Манифест
содержит UTC/монотонные метки, заметки владельца и SHA-256 артефактов.
Оба USB-наблюдателя завершены. Удалённый захват остановлен, хеш локальной копии
сверен, временный каталог VPS удалён. Core на порту 8000 и сервис VPS работают.
Итоговая физическая расстановка: **МТС в первом слоте, МегаФон во втором,
подключены 12 В и USB**. При завершении B2 передаёт свежие данные через SIM 2,
МегаФон; возраст последнего пакета около 15 секунд, измерения — 20 секунд.
## Решение для дальнейшей реализации
Для этих двух карт подтверждены различение и привязка к слоту в потоке запуска,
включая обмен слотами. Повторный штатный опрос не даёт столь же надёжного полного
идентификатора первой SIM при двух картах. Для автоматического применения APN
нельзя использовать правило «SID состоит из цифр — значит идентичность доказана».
Следующий этап должен сохранять источник, исходное представление, полноту,
сеанс запуска и свежесть наблюдения; не позволять неполному отчёту подменять
подтверждённую карту или переносить ожидающую запись на другую SIM. Получение
достоверной идентичности вне потока запуска и канонизация форматов требуют
отдельной квалификации. Автоматический подбор и запись APN этим опытом не
реализованы; MVNO, корпоративные тарифы и другие SIM не испытывались.
@@ -0,0 +1,74 @@
# Durable B2 maintenance runtime — VPS Host 0.1.32
Scope: owner-authorized service operations ending at B2. No physical actuator,
relay, pin-load or downstream sensor acceptance is claimed. The existing bounded
pin-command transport was preserved; it is not automatically retried.
## Job and attempt ownership
Core accepts one immutable request ID into SQLite before HTTP and retains its
outbox across restarts. On uncertain HTTP delivery it reads the VPS result first;
only an absent/unavailable result permits resubmission of the same ID and body.
The VPS owns a persistent job and distinct bounded transport attempts. Restart of
Core or VPS and expiry of one attempt do not discard the job. Per-device FIFO
capacity is 32. No new attempt is admitted without recent B2 input. Another
tracker's job progresses independently. Retry delays grow from 5 to 300 seconds;
idle channels sleep on events. Old completed/uncertain historical jobs are not
silently replayed on upgrade.
Supported durable kinds: position request, restart, full configuration read,
profile configuration write and SIM selection. The capability is negotiated;
older hosts retain their bounded behavior. Device identity/firmware/assignment
changes before dispatch are rejected explicitly. Permanent B2 argument/execution
errors finish with a visible failure; code 7 (full B2 command queue) waits/retries.
Code 6 remains intermediate; matching token/code 0 finishes a position command.
A configuration retry first reads the actual image. Target image = completed;
unchanged predecessor = eligible for a fresh preflight and another write; any
other image = explicit conflict, not overwrite. SIM recovery additionally needs
fresh selected-slot/GPRS telemetry. A confirmed target SIM is not rebooted again.
A restart with known code-0 acceptance and no return evidence finishes as
`accepted`, distinct from `reconnected`; it is not repeated. If no receipt is
available, the owner-authorized maintenance job can retry after recovery.
This is durable delivery with state reconciliation, not a claim of exactly-once
physical execution. B2 has no demonstrated durable client-id deduplication. If
both an effect and its response happened before a disconnect, a lost receipt may
still make an unobservable effect ambiguous. Tracker acknowledgments establish
only the tracker boundary. No network runtime can deliver while hardware has no
power or the mobile network remains unreachable.
Stopping retries is persisted in Core and VPS. A pre-admission stop is a tombstone,
so a delayed POST cannot revive the job. An already handed-off attempt can finish;
the UI does not promise to undo it. Attempt rows are redacted and paged, with
individual tokens retained only privately. UI shows counts, current attempt,
responses, waiting/reconciliation and stop controls.
## Acceptance
Session `durable-operations-a6b9b43aa22342e28d2d91a4afca9e41`.
Installer SHA-256 `29ad94442210b9f6f399e2b2d0a0b9a3b3411a6ccb3cf5f43e922e7863e98eba`.
- 85 focused backend tests: durable and legacy paths, Core outage beyond one day,
lost POST and restart, stale ACK removal, per-tracker isolation, crash before
and after attempt admission, cancellation races, configuration target/old/
divergent images, verified second write and SIM recovery without second reboot.
- 135 VPS/installer checks passed, including loopback tests.
- Shipped Ubuntu `qualify_operations.py` used actual isolated TCP/HTTP and SQLite:
one job, two attempts across SIGKILL; old reply could not finish the new attempt;
terminal result and stop-before-delayed-POST survived further SIGKILLs. All
previous receipt/runtime/fault qualification also passed. No physical tracker
or production database was used in those destructive process tests.
- Versioned installer preserved four identity files, made a SQLite backup, and
all 27 installed manifest files matched the accepted artifact. Core download
carries that same artifact; onboard software was not updated.
- Actual owner B2: two Core-issued position jobs confirmed in 1.136 s and 0.523 s,
each with one persisted attempt. Core/VPS outcomes agreed. No physical settings,
reboot, pin or USB serial commands were issued for this release.
- Frontend architecture/typecheck, 1010 tests and production build passed. Real
command history, per-attempt result and Escape checked on canonical port 8000.
Existing bundle-size warning remains.
These tests do not qualify thousands-device throughput or resolve the separate
USB/power/radio stall observed earlier. Full vendor-feature parity and factory
bootstrap remain separate acceptance scopes; this release does not assert them.
@@ -0,0 +1,124 @@
# Durable manual commands and protocol ACK handoff
Date: 2026-09-28. Installed VPS Host: **0.1.43**. This supersedes the
queue-lifetime conclusions in `COMMAND_DELIVERY_AND_REPLAY_20260928.md`.
## Faults established
The user's second failure was not solved by 0.1.42's 3 → 30 second dispatch
window. Core PIN4-on and PIN6-pulse jobs expired behind another operation and
never reached VPS. Two later off jobs reached VPS but never dispatched. A
separate PIN4-on reached a socket but had no TCP ACK before its transport bound.
These are three distinct failure stages; the earlier fix was incomplete.
A bounded passive VPS capture showed fresh B2 packages followed by our own
four-byte protocol ACK, with TCP acknowledgement sometimes delayed about
17 seconds. The sender checked for an empty queue after writing that ACK,
so this very exchange could exclude itself from command admission. Commands
were additionally bound to the sockets present at submission, although mobile
reconnection could replace them before their first dispatch.
FC output commands have no transaction token. Waiting a minute for a token
receipt that cannot arrive blocked Core's next jobs until their 30-second
queue deadlines expired. Packet size did not explain these application gates.
## New runtime contract
- A manual command is committed to SQLite before acceptance. Its job has no
queue expiry; offline waiting and process restart preserve its identity.
- Scheduler-v2 removes the old 32-job admission ceiling. The backlog stays on
disk; Core prepares up to 16 and polls up to 8 per pass, and history is paged.
This is not a claim of unlimited disk capacity or billion-job throughput.
- Private Core dispatch bodies survive lost HTTP replies unchanged. Multiple
jobs reach VPS independently of the device's current settings/position row.
Terminal jobs remove their private dispatch body while keeping public history.
- Manual jobs have priority over background reads between exchanges. An unsent
background read can yield. A dispatched exchange or settings write is not
interrupted. Each priority class preserves order, independently per tracker.
- Attempts keep bounded TCP lifetimes; an expired **unsent attempt** retries
under the same persistent job. Such expiry does not erase the job.
- Explicit output-level assignments may retry the same desired state. A pulse
with uncertain dispatch is retained as unconfirmed and requires an explicit
repeat; B2's FC protocol cannot deduplicate it or guarantee exactly-once effect.
- An exact freshly generated ACK tail may precede a command for five seconds,
only if its whole predecessor stream was drained. Another write revokes this
handoff. Older blocked prefixes, command bytes, stale input and revoked devices
remain excluded. A never-dispatched attempt may use a new admitted socket.
- A text output finishes as neutral `delivered` when TCP delivery is observed.
It releases the queue without claiming device execution or contact position.
Cancellation records a durable stop/tombstone and cancels an unsent attempt;
it cannot retract bytes already sent to the device.
## Physical check
Through the product's repeat buttons, three new OFF jobs were accepted within
0.544 seconds at 21:23:09 Moscow time. They were dispatched FIFO to the real B2:
| Output | Dispatch (MSK) | TCP ACK latency | Attempts | Final state |
| --- | --- | ---: | ---: | --- |
| PIN4 off | 21:23:19.981 | 8.271 s | 1 | delivered |
| PIN5 off | 21:23:29.271 | 1.253 s | 1 | delivered |
| PIN6 off | 21:23:31.419 | 1.756 s | 1 | delivered |
All three had completed by 21:23:33.177. Subsequent fresh TAG6 samples report
all three outputs false. They establish reported logical OFF states, not a
measured transition or external relay contacts. Old expired history was retained
and was not automatically replayed. No SIM, APN, firmware or device settings write
was performed in this increment.
Automatic approval review initially blocked a further pulse. The owner then
explicitly authorized as many tests as needed on all outputs. Four five-second
pulses (PIN6, PIN5, PIN4, PIN6 again) were dispatched once each and delivered in
2.256, 1.505, 1.504 and 0.752 seconds. Each isolated test interval contains a real
type-3 `SERV OK` response from B2, arriving 2.039, 1.517, 2.047 and 0.667 seconds
after dispatch. This is distinct from TCP ACK. The text lacks a transaction ID
and PIN, so it is observational evidence, not a generic per-job correlation rule.
PIN4 TAG6 samples show false → true → false. PIN5's short active interval was not
sampled; the subsequent state is false. PIN6 remained true beyond five seconds
in both tests and changed to false after explicit OFF. The documented command
was used unchanged (`SERV*24.6.0.5`). PIN6 timer/report behavior is a reproducible
open device-level issue, not successful pulse-duration acceptance. The owner
explicitly retained physical relay/LED verification; no contact claim is made.
One PIN6 OFF lost its first transport receipt; the same durable job retried and
completed on attempt two. Both OFF attempts have observed `SERV OK` responses,
illustrating why a state assignment can safely repeat while a pulse cannot.
All test jobs and subsequent operator OFF jobs finished; the latest sampled
PIN4/5/6 states are false. Raw package hashes, UTC/monotonic snapshot times,
redacted text replies and separate job identities are retained in private evidence.
## Validation and limits
- 262 focused backend/VPS regression cases passed, including new durable output,
cancellation, restart, lost HTTP response and independent job projection tests.
- 80 persisted jobs survive the old 32-job threshold and a simulated week offline.
- 100 synthetic device identities: one offline job stays queued while the other
99 finish independently; these outcomes survive runtime reconstruction.
This is a deterministic functional test, not 100 real cellular links or a
throughput, tail-latency, soak or resource-capacity qualification.
- 30 relevant frontend/architecture cases, TypeScript and production build pass.
- Staged release on the real Ubuntu VPS: three FIFO output frames through
isolated actual Linux loopback sockets in 2.660 seconds, one attempt each;
no production state/devices involved. Transport ACK and blocked-stream abort
qualifiers pass (0.751 s observed abort for a synthetic 0.750 s bound).
- Two independent builder outputs match. Ruff and diff whitespace checks pass.
- Core remains healthy at 8000; real B2 telemetry and VPS connectivity continue.
Further scaling acceptance requires real or representative concurrent sessions,
long-duration operation, backlog/reconnect bursts, resource measurements and
operator latency criteria. A working single-device exchange is not that gate.
## Installed artifact
- TAR: `96d40b3c4f88f4e78084b685c88de2c932c8578157cadb48aff4bfb3c5ac4194`
- PYZ: `0d1134574adf1f118c39ca4568dda556a24a6ab701d7f5c014b542268e3df0bd`
- Manifest/release: `a8aa2779b33315616cc591282d4840983d52c88ffbee7c8ed1d1657b4fb9599b`
- Exact plan: `e13022c830ac1d13f8d9a49a40cdaf20018e4b49c4a4c9511249f0cfc67aa3ec`
The canonical artifact installer returned healthy and retained 0.1.42 for rollback.
The same accepted PYZ is published to Core's operator catalog. VPN routes,
endpoint ports, identity files and firewall ownership are unchanged. Source work
remains uncommitted. Private IDs/timestamps and redacted output evidence are in
`outputs/arnavi-sim-investigation-20260928/command-runtime-evidence.json` outside
this repository.
+107
View File
@@ -0,0 +1,107 @@
# B2: обрывы и восстановление 27.09.2026
Сессия `fault-recovery-775a9eb9cb8d4707a225842eae8f0d5c`: один принадлежащий
владельцу B2, модель 231, ПО 0.01, помещение. VPS 0.1.26 не обновлялся.
Физические команды — только запросы позиции; реле, настройки, прошивка
и бортовой Node не менялись.
## Физическое отключение
Владелец подтвердил снятие 12 В и USB и погасшие индикаторы. После прекращения
пакетов Core показал отсутствие связи, сохранив экземпляр и привязку.
Последняя позиция имела `position_fresh=false`.
Для исключения оставшегося TCP-сеанса запрос отправлен после более 190 секунд
без пакетов (тайм-аут сеанса VPS — 180 секунд). Два HTTP POST с одним ID
возвратили одну операцию. По журналу VPS запрос находился в очереди, истёк
по исходному 30-секундному сроку и не имел `dispatched_at`.
После сигнала владелец включил 12 В без USB. B2 вернулся под прежним
экземпляром, появились свежие данные. Новый запрос получил `device_confirmed`
за **0,664 с** по измерению VPS. Старый остался истёкшим без отправки.
Отдельный PCAP в этой серии не снимался; вывод опирается на журнал и
протокольный результат. Исполнение выходов не проверялось.
Первый сборщик достиг 660-секундного предела в ожидании включения. Отметка
тайм-аута сохранена. Сбор продолжен отдельным запуском с прежним ID и
накопленными образцами; во время разрыва опроса новые команды не создавались.
## Изолированные сбои VPS
`apps/vps-host/qualify_faults.py` использует установленный `ndc_vps` без
изменений, временную SQLite, локальные HTTP/TCP-порты и один синтетический B2
последовательно. SHA-256 установленных модулей сверены с исходниками.
Главный процесс боевого VPS, его база, TLS и firewall не менялись.
Дочерний тестовый процесс аварийно завершается SIGKILL. Временные процессы
и каталог убираются при завершении.
Пройдены шесть сценариев:
1. Потеря запроса до полного HTTP-тела: повтор с тем же ID.
2. Потеря HTTP-ответа после принятия: авария, восстановление очереди,
повтор исходного ID, один прикладной кадр позиции.
3. Истечение срока без подключения: перезапуск не продлевает срок,
поздний синтетический B2 не получает команду.
4. TCP принимает байты, протокольного ответа нет: `unconfirmed`,
после перезапуска и подключения команда не воспроизводится.
5. Синтетическая команда выхода отправлена, затем авария: `uncertain`,
без автоматического повтора.
6. Новая команда после восстановления проходит; идентичность, история
и целостность SQLite сохранены.
Серия заняла 3,972 с; приёмник зарегистрировал пять командных кадров.
Это функциональная проверка с укороченными сроками, не нагрузка и не
измерение радиоканала, TLS или реле. Для повторения на квалифицированном
Ubuntu VPS скопировать инженерный скрипт во временный каталог и выполнить
`PYTHONPATH=/opt/nodedc-mission-vps/current python3 qualify_faults.py`.
Скрипт сам создаёт временную базу; боевую базу ему не передают.
## Найденный дефект Core
VPS мог сохранить подтверждение, но Core не получал его до срока, ставил
`uncertain` и больше не читал этот ID. Перезапуск и новая команда не
исправляли старую строку. Два регрессионных теста сначала падали.
Теперь локальный тайм-аут команды создаёт долговечное намерение прочитать
результат у исходного VPS. Только GET с прежним ID, без POST и физического
повтора. За проход — до двух запросов на хост; интервалы 5, 10, 20… до
300 секунд сохраняются до сетевого вызова. Исходный срок не продлевается.
Неверные ID/тип или незавершённый ответ не заменяют неизвестный исход.
Конечный результат обновляет журнал и завершает опрос. Новая текущая операция
не затирается старой. Ожидающие результата строки продолжают обновляться
в открытом журнале за пределами первой страницы и не блокируют очередь.
Конечный `uncertain` от самого VPS не запускает бесконечный опрос.
Область исправления — `scope=command`. Поздняя конфигурация не применяется
к текущему состоянию через историю. Для настроек и SIM нужен отдельный
контроль версий снимков. Неизвестные результаты, сохранённые до этой версии,
автоматически не переинтерпретируются.
## Приёмка Core
Сохранены SQLite-копии оборудования и VPS. Миграция на отдельной копии
сохранила 61 операцию без изменения состояний; integrity — ok.
Core обновлён штатным LaunchAgent на 8000. Перед обновлением принят запрос
со статусом `waiting`; после обновления тот же ID получил `device_confirmed`,
ответ VPS → B2 **0,505 с**. История выросла ровно с 61 до 62 строк.
Это сохранность принятого намерения/результата через управляемый перезапуск;
точный момент отправки относительно остановки процесса не квалифицирован.
Пройдены Ruff, 95 backend-тестов, архитектурные проверки, TypeScript,
1008 frontend-тестов и production build. Существующие предупреждения
Starlette/httpx и большого JS chunk сохраняются. В заново загруженном
интерфейсе проверены журнал и этапы истёкшей команды.
Приватные результаты, операторские UTC/monotonic отметки, программы сбора,
логи, резервные копии и SHA-256 manifest сохранены под игнорируемым
`outputs/vps-host-20260926/autonomy/` в каталоге сессии.
## Границы результата
При отсутствии связи гарантировать доставку нельзя. Если команда отправлена,
а подтверждение потеряно, неизвестный исход сохраняется без повторного
воздействия. Это не гарантия ровно одного физического исполнения и не
проверка тысячи устройств. Ограничения worker Core, 256 соединений VPS,
длительного радиообрыва и масштабирования остаются. Полный аудит автономной
конфигурации — следующий отдельный этап.

Some files were not shown because too many files have changed in this diff Show More