feat(core): persist viewer state and integrate Cesium services and profiles
This commit is contained in:
Generated
+8
-8
@@ -10,7 +10,7 @@
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.2.0",
|
||||
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.66.tgz",
|
||||
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.74.tgz",
|
||||
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
|
||||
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
|
||||
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
|
||||
@@ -42,7 +42,7 @@
|
||||
},
|
||||
"../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react": {
|
||||
"name": "@nodedc/map-cesium-react",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.4",
|
||||
"dependencies": {
|
||||
"cesium": "1.147.0"
|
||||
},
|
||||
@@ -71,7 +71,7 @@
|
||||
},
|
||||
"../../../NODEDC_DESIGN_GUIDELINE/packages/ui-react": {
|
||||
"name": "@nodedc/ui-react",
|
||||
"version": "0.7.4",
|
||||
"version": "0.7.5",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
@@ -884,12 +884,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@nodedc/bim-viewer": {
|
||||
"version": "0.2.66",
|
||||
"resolved": "file:../../vendor/bim/nodedc-bim-viewer-0.2.66.tgz",
|
||||
"integrity": "sha512-aq8LktWb72/UFSDtYExDh+Eccb1dAoc2oiDg5gC+tvobXyofEBUnAdwzElYOAV2mg3CNgC7k74UnJmdJ5pKhJA==",
|
||||
"version": "0.2.74",
|
||||
"resolved": "file:../../vendor/bim/nodedc-bim-viewer-0.2.74.tgz",
|
||||
"integrity": "sha512-pZOXFqDcypBEFEqUIjOEX9BU+J6qMemYYLPy+PitBF7Rw0pK+daKlhtUT/gW69v1BQW0PVKi209hkgRgpI3/Gg==",
|
||||
"peerDependencies": {
|
||||
"@nodedc/map-cesium-react": ">=0.1.1 <0.2",
|
||||
"@nodedc/ui-react": ">=0.7.4 <0.8",
|
||||
"@nodedc/map-cesium-react": ">=0.1.4 <0.2",
|
||||
"@nodedc/ui-react": ">=0.7.5 <0.8",
|
||||
"react": ">=19 <20",
|
||||
"react-dom": ">=19 <20"
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.2.0",
|
||||
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.66.tgz",
|
||||
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.74.tgz",
|
||||
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
|
||||
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
|
||||
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { EnvironmentSettingsWindow as SharedEnvironmentSettingsWindow } from "@nodedc/ui-react";
|
||||
import { environmentSurfaceIds, type EnvironmentSettings, type EnvironmentSurfaceId, type UploadedEnvironmentMedia } from "../core/environment/environmentSettings";
|
||||
import { CesiumServiceSettings } from "./map/CesiumServiceSettings";
|
||||
import { useLabStorageSettings } from "./storage/LabStorageSettings";
|
||||
import { roots, workspaces, workspacesForRoot } from "../productModel";
|
||||
|
||||
@@ -18,7 +19,7 @@ const surfaces = environmentSurfaceIds.map(id => ({
|
||||
}));
|
||||
export function EnvironmentSettingsWindow(props: Props) {
|
||||
const storage = useLabStorageSettings(props.open);
|
||||
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet" additionalSections={[storage]}
|
||||
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet" additionalSections={[storage, {id: "services", label: "Сервисы", icon: "key", content: props.open ? <CesiumServiceSettings/> : null}]}
|
||||
onSave={draft => props.onSave({ ...draft, pages: Object.fromEntries(environmentSurfaceIds.map(id => [id, draft.pages[id]])) as EnvironmentSettings["pages"] })}
|
||||
onUpload={(id, itemId, file) => {
|
||||
if (!environmentSurfaceIds.includes(id as EnvironmentSurfaceId)) throw new Error("Страница окружения недоступна.");
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import {useEffect, useState} from "react";
|
||||
import {Description, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField} from "@nodedc/ui-react";
|
||||
import {cesiumServiceMessage, cesiumTokenIndicator, readCesiumService, saveCesiumService, verifyCesiumService,
|
||||
type CesiumRouteMode, type CesiumServiceSettings as Settings, type CesiumVerification} from "../../core/map/cesiumService";
|
||||
import "./cesiumServiceSettings.css";
|
||||
import {serverRequest, type Server} from "../../core/system/servers";
|
||||
|
||||
export function CesiumServiceSettings() {
|
||||
const [service, setService] = useState("");
|
||||
const [pending, setPending] = useState<"verify" | "save" | "remove" | null>(null);
|
||||
const [settings, setSettings] = useState<Settings | null>(null);
|
||||
const [mode, setMode] = useState<CesiumRouteMode>("auto");
|
||||
const [egress, setEgress] = useState("");
|
||||
const [servers, setServers] = useState<Server[]>([]);
|
||||
const [routesError, setRoutesError] = useState("");
|
||||
const [token, setToken] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [checkError, setCheckError] = useState("");
|
||||
const [showVerification, setShowVerification] = useState(false);
|
||||
const [verification, setVerification] = useState<CesiumVerification | null>(null);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
void readCesiumService().then(value => {if (active) {setSettings(value); setMode(value.mode); setEgress(value.egress_id || "");}})
|
||||
.catch(reason => {if (active) setError(reason.message);});
|
||||
void serverRequest<{items:Server[]}>("").then(value => {if(active) setServers(value.items);})
|
||||
.catch(reason => {if(active) setRoutesError(reason.message);});
|
||||
return () => {active = false;};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setVerification(null); setCheckError(""); setShowVerification(false);
|
||||
if (service !== "cesium" || !settings?.token_configured || token.trim() || egress !== (settings.egress_id || "")) {setChecking(false); return;}
|
||||
setChecking(true);
|
||||
void verifyCesiumService().then(value => {if (active) setVerification(value);})
|
||||
.catch(reason => {if (active) setCheckError(reason instanceof Error ? reason.message : cesiumServiceMessage());})
|
||||
.finally(() => {if (active) setChecking(false);});
|
||||
return () => {active = false;};
|
||||
}, [service, settings?.revision, settings?.token_configured, token, egress]);
|
||||
const indicator = cesiumTokenIndicator({configured: !!settings?.token_configured, draft: !!token.trim(),
|
||||
checking: checking || pending === "verify" || pending === "save", error: error || checkError, verification});
|
||||
async function action(kind: "verify" | "save" | "remove") {
|
||||
if (!settings || busy) return;
|
||||
setBusy(true); setPending(kind); setError(""); setCheckError(""); setVerification(null); setShowVerification(kind === "verify");
|
||||
try {
|
||||
if (kind === "verify") setVerification(await verifyCesiumService(token.trim() || undefined, egress));
|
||||
else {
|
||||
const result = await saveCesiumService({revision: settings.revision, mode, egress_id: egress,
|
||||
...(kind === "remove" ? {remove_token: true} : token.trim() ? {token: token.trim()} : {})});
|
||||
setSettings(result); setToken("");
|
||||
}
|
||||
} catch (reason) {setError(reason instanceof Error ? reason.message : cesiumServiceMessage());}
|
||||
finally {setBusy(false); setPending(null);}
|
||||
}
|
||||
return <SettingsCard title="Сервисы" actions={service === "cesium" && <>
|
||||
<IconButton label="Проверить доступ" disabled={busy || checking || !settings || (!token.trim() && !settings.token_configured)}
|
||||
loading={pending === "verify"} onClick={() => void action("verify")}><Icon name="activity"/></IconButton>
|
||||
<IconButton label="Сохранить" disabled={busy || !settings} loading={pending === "save"}
|
||||
onClick={() => void action("save")}><Icon name="save"/></IconButton>
|
||||
{settings?.token_configured && <IconButton label="Удалить токен" disabled={busy} loading={pending === "remove"}
|
||||
onClick={() => void action("remove")}><Icon name="trash"/></IconButton>}
|
||||
</>}>
|
||||
<Select label="Выберите сервис" value={service} disabled={busy} onChange={setService}
|
||||
options={[{value: "", label: "Выберите сервис"}, {value: "cesium", label: "Cesium ion",
|
||||
icon: <StatusBadge variant="indicator" tone={indicator.tone} pulse={indicator.pulse} title={indicator.label} aria-label={indicator.label}/>} ]}/>
|
||||
{service === "cesium" && <>
|
||||
<Description>Общий доступ к спутниковым картам, рельефу и зданиям во всех разделах Mission Core.</Description>
|
||||
{!settings && !error && <Description role="status">Получаем настройки…</Description>}
|
||||
{settings && <>
|
||||
<Select label="Подключение" value={mode} disabled={busy} onChange={value => setMode(value as CesiumRouteMode)}
|
||||
options={[{value: "auto", label: "Автоматически"}, {value: "direct", label: "Напрямую к источнику"},
|
||||
{value: "gateway", label: "Сервер хранения локальных данных"}]}/>
|
||||
<Description>{mode === "auto" ? "Карты используют сервер хранения локальных данных. Если сервер недоступен, подключение переключается на источник через интернет." :
|
||||
mode === "direct" ? "Карты загружаются через интернет без сохранения тайлов на этом компьютере." : "Карты загружаются только через сервер хранения локальных данных. Если сервер недоступен, загрузка приостанавливается."}</Description>
|
||||
<Select label="Маршрутизация" value={egress} disabled={busy} onChange={value=>{setEgress(value);setVerification(null);setError("");}}
|
||||
options={[{value:"",label:"Текущий маршрут"},...servers.flatMap(server=>server.services.filter(item=>item.kind==='egress').map(item=>({value:item.id,label:`${server.name} · ${server.address}`})))]}/>
|
||||
{routesError&&<Description role="alert">{routesError}</Description>}
|
||||
<TextField label={settings.token_configured ? "Новый токен Cesium ion" : "Токен Cesium ion"} type="password" value={token}
|
||||
disabled={busy} autoComplete="off" spellCheck={false} onChange={event => {setToken(event.target.value); setVerification(null); setError("");}}
|
||||
placeholder={settings.token_configured ? "Токен сохранён; заполните для замены" : "Токен"}/>
|
||||
<Description>Токен сохраняется только в Mission Core. Для прямого подключения нужен доступ к рельефу, спутниковой карте и зданиям Cesium ion.</Description>
|
||||
{showVerification && verification && <div className="cesium-service-results" role="status">{Object.entries(verification.assets).map(([id, result]) =>
|
||||
<Description key={id}>{({"1": "Рельеф", "2": "Спутниковая карта", "96188": "Здания"} as Record<string, string>)[id] ?? id}: {result.ok ? "доступ подтверждён" : cesiumServiceMessage(result.code)}</Description>)}</div>}
|
||||
</>}
|
||||
{error && <Description role="alert">{error}</Description>}
|
||||
</>}
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -652,6 +652,7 @@ function CacheHealth({
|
||||
);
|
||||
}
|
||||
const { cache } = health.snapshot;
|
||||
if (!cache) return <ControlRow label="Подключение"><StatusBadge tone="neutral">Источник · без кэша</StatusBadge></ControlRow>;
|
||||
return (
|
||||
<dl className="mission-map__cache-health">
|
||||
<div>
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
.cesium-service-results { display: grid; gap: var(--nodedc-space-2); }
|
||||
@@ -2,7 +2,7 @@ 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,connectionInstruction}:{connectionInstruction?:string;kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'|'vps-librespeed'}){
|
||||
export function InstallerCard({kind,connectionInstruction}:{connectionInstruction?:string;kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'|'vps-librespeed'|'vps-egress'}){
|
||||
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((original,index)=>{const step=connectionInstruction&&index===item.instructions.length-1?connectionInstruction:original;return <Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>;})}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import {useObservationView} from '../../core/observation/useObservationView';
|
||||
import {roverModelID} from '../../core/roverScene/model';
|
||||
import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
@@ -15,6 +16,9 @@ const labels:Record<string,string>={observing:'Наблюдение',preparing:'
|
||||
export function RoverView({vehicleID,name,controller:c,header,active,observation}:{vehicleID:string;name:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean;observation?:RoverObservationStatus}){
|
||||
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 presentation=useObservationView('rover-view',vehicleID,()=>({schema:'missioncore.rover-view/v1' as const,model:''}),async()=>{
|
||||
try{const raw=localStorage.getItem(storage);return raw?{schema:'missioncore.rover-view/v1' as const,model:roverSettings(JSON.parse(raw)).model}:null;}catch{return null;}
|
||||
});
|
||||
const [open,setOpen]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
|
||||
const [editing,setEditing]=useState(false);
|
||||
const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading');
|
||||
@@ -57,7 +61,7 @@ export function RoverView({vehicleID,name,controller:c,header,active,observation
|
||||
onKeyDown={e=>{if(!c.ready&&(c.armed||c.pending||c.recovering)&&e.isTrusted&&['Space','Escape'].includes(e.code)){e.preventDefault();stop();}}}
|
||||
onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}>
|
||||
<EditorWorkspace editing={editing&&active} title={`Ровер / ${name}`} subtitle="Редактирование сцены" onBack={()=>setEditing(false)}>
|
||||
{settings.model===roverModelID?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
|
||||
{!presentation.ready?<LoadingRegion loading label="Загрузка настроек вида"/>:presentation.document.model===roverModelID?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
|
||||
<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"><Description>Выберите модель аппарата.</Description><Button onClick={showSettings}>Настройки вида</Button></div>}
|
||||
@@ -75,8 +79,9 @@ export function RoverView({vehicleID,name,controller:c,header,active,observation
|
||||
</EditorWorkspace>
|
||||
</div>
|
||||
<Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings">
|
||||
{presentation.error&&<><Description>{presentation.error}</Description><Button onClick={presentation.retry}>Повторить сохранение вида</Button></>}
|
||||
<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}))}/>
|
||||
<Select label="3D-модель" value={settings.model} options={[{value:'',label:'Не выбрана'},{value:roverModelID,label:'DCD-006 · сборка v022'}]} onChange={model=>setSettings(v=>({...v,model}))}/>
|
||||
<Select label="3D-модель" disabled={!presentation.ready} value={presentation.document.model} options={[{value:'',label:'Не выбрана'},{value:roverModelID,label:'DCD-006 · сборка v022'}]} onChange={model=>presentation.update(v=>({...v,model}))}/>
|
||||
{duty?<TextField label="Газ, %" hint="1–100" description="Доля полного газа пульта. Фактическая скорость зависит от нагрузки." type="number" min={1} max={100} step={1} value={Number.isFinite(settings.throttlePercent)?settings.throttlePercent:''} onChange={e=>setSettings(v=>({...v,throttlePercent:roverNumberInput(e.target.value)}))}/>:
|
||||
<TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={Number.isFinite(settings.maxErpm)?settings.maxErpm:''} onChange={e=>setSettings(v=>({...v,maxErpm:roverNumberInput(e.target.value)}))}/>}
|
||||
<TextField label="Предел тока каждого мотора, А" description={currentDescription} type="number" min={.5} step={.5} value={Number.isFinite(settings.currentA)?settings.currentA:''} onChange={e=>setSettings(v=>({...v,currentA:roverNumberInput(e.target.value)}))}/>
|
||||
|
||||
@@ -5,10 +5,10 @@ import {serverRequest,useServers,type Server} from '../../core/system/servers';
|
||||
import {vpsRequest} from '../../core/fleet/vps';
|
||||
|
||||
export function ServerServiceSetup({server:initialServer,fixedKind,onClose,onSaved}:{server?:Server;fixedKind?:'librespeed';onClose:()=>void;onSaved:()=>void}) {
|
||||
const [kind,setKind]=useState<'wireguard'|'arnavi'|'librespeed'>(fixedKind??'wireguard'),[document,setDocument]=useState(''),[filename,setFilename]=useState('');
|
||||
const [kind,setKind]=useState<'wireguard'|'arnavi'|'librespeed'|'egress'>(fixedKind??'wireguard'),[document,setDocument]=useState(''),[filename,setFilename]=useState('');
|
||||
const catalog=useServers();const [serverId,setServerId]=useState(initialServer?.id??'');
|
||||
const server=initialServer??catalog.items?.find(s=>s.id===serverId);
|
||||
const serviceName=kind==='librespeed'?'LibreSpeed':'WireGuard';
|
||||
const serviceName=kind==='egress'?'Маршрутизация трафика':kind==='librespeed'?'LibreSpeed':'WireGuard';
|
||||
const [network,setNetwork]=useState(''),[interfaces,setInterfaces]=useState<{id:string;label:string}[]>([]);
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState('');const file=useRef<HTMLInputElement>(null);
|
||||
useEffect(()=>{let active=true;void vpsRequest<{items:{id:string;label:string}[]}>('/interfaces').then(r=>{if(active)setInterfaces(r.items);}).catch(()=>{});return()=>{active=false;};},[]);
|
||||
@@ -22,14 +22,14 @@ export function ServerServiceSetup({server:initialServer,fixedKind,onClose,onSav
|
||||
{!initialServer&&<Select label="VPS" value={serverId} disabled={busy} options={[{value:'',label:'Выберите VPS'},...(catalog.items??[]).map(s=>({value:s.id,label:`${s.name} · ${s.address}`}))]} onChange={id=>{setServerId(id);setDocument('');setFilename('');}}/>}
|
||||
{!initialServer&&catalog.items?.length===0&&<Description>Сначала добавьте VPS в разделе «Система → VPS».</Description>}
|
||||
{catalog.error&&!initialServer&&<Description>{catalog.error}</Description>}
|
||||
<Select label="Служба" value={kind} disabled={busy||!!fixedKind} options={[{value:'wireguard',label:'WireGuard'},{value:'arnavi',label:'ARNavi'},{value:'librespeed',label:'LibreSpeed'}]} onChange={value=>{setKind(value as typeof kind);setDocument('');setFilename('');setError('');}}/>
|
||||
<InstallerCard key={kind} connectionInstruction={kind==='librespeed'?undefined:"Вернитесь в это окно и подключите установленную службу с выданным приглашением."} kind={kind==='librespeed'?'vps-librespeed':kind==='wireguard'?'vps-wireguard':'vps-arnavi'}/>
|
||||
<Select label="Служба" value={kind} disabled={busy||!!fixedKind} options={[{value:'wireguard',label:'WireGuard'},{value:'arnavi',label:'ARNavi'},{value:'librespeed',label:'LibreSpeed'},{value:'egress',label:'Маршрутизация трафика'}]} onChange={value=>{setKind(value as typeof kind);setDocument('');setFilename('');setError('');}}/>
|
||||
<InstallerCard key={kind} connectionInstruction={kind==='librespeed'?undefined:"Вернитесь в это окно и подключите установленную службу с выданным приглашением."} kind={kind==='egress'?'vps-egress':kind==='librespeed'?'vps-librespeed':kind==='wireguard'?'vps-wireguard':'vps-arnavi'}/>
|
||||
<SettingsCard title="Подключение установленной службы" description="Запустите установщик на выбранном VPS. Затем передайте выданное им приглашение — Mission Core проверит сервер и сохранит подключение.">
|
||||
{kind!=='arnavi'?<>
|
||||
<input ref={file} type="file" accept=".json,application/json" hidden onChange={event=>{const chosen=event.target.files?.[0];event.target.value='';if(!chosen)return;setDocument('');setFilename('');void (async()=>{if(chosen.size>16384)throw Error(`Выберите файл приглашения ${serviceName} (до 16 КБ).`);setDocument(await chosen.text());setFilename(chosen.name);})().catch(e=>setError(e.message));}}/>
|
||||
<Button icon={<Icon name="upload"/>} disabled={busy} onClick={()=>file.current?.click()}>Выбрать приглашение {serviceName}</Button>
|
||||
{filename&&<Description>{filename}</Description>}
|
||||
<Description>Файл на VPS: {kind==='librespeed'?'/var/lib/ndc-librespeed-vps/mission-core-librespeed.json':'/var/lib/ndc-wireguard-vps/mission-core-wireguard.json'}. Скопируйте его по защищённому соединению (например, SFTP). Приглашение действует 24 часа; новое выпускается командой connection того же установщика. {kind==='wireguard'?'Экспорт .conf из клиента WireGuard не подходит.':''}</Description>
|
||||
<Description>Файл на VPS: {kind==='egress'?'/var/lib/ndc-egress-vps/mission-core-egress.json':kind==='librespeed'?'/var/lib/ndc-librespeed-vps/mission-core-librespeed.json':'/var/lib/ndc-wireguard-vps/mission-core-wireguard.json'}. Скопируйте его по защищённому соединению (например, SFTP). Приглашение действует 24 часа; новое выпускается командой connection того же установщика. {kind==='wireguard'?'Экспорт .conf из клиента WireGuard не подходит.':''}</Description>
|
||||
</>:<TextAreaField label="Ключ подключения ARNavi" value={document} disabled={busy} rows={4} onChange={e=>setDocument(e.target.value)} hint="Ключ находится на VPS в /opt/nodedc-mission-vps/connect.key. Действует 24 часа и используется один раз."/>}
|
||||
</SettingsCard>
|
||||
{interfaces.length>0&&<Select label="Подключение к VPS" disabled={busy} value={network} options={[{value:'',label:'Через текущую сеть'},...interfaces.map(i=>({value:i.id,label:`Напрямую · ${i.label}`}))]} onChange={setNetwork}/>}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
export type CesiumRouteMode = "auto" | "direct" | "gateway";
|
||||
export interface CesiumServiceSettings {
|
||||
revision: number;
|
||||
egress_id: string;
|
||||
mode: CesiumRouteMode;
|
||||
token_configured: boolean;
|
||||
gateway_configured: boolean;
|
||||
gateway_available: boolean | null;
|
||||
active_route: "unknown" | "gateway" | "direct" | "unavailable";
|
||||
}
|
||||
export interface CesiumVerification { ok: boolean; assets: Record<string, {ok: boolean; code?: string}> }
|
||||
const endpoint = "/api/v1/map/services/cesium-ion";
|
||||
export const cesiumServiceChanged = "missioncore:cesium-service-changed";
|
||||
const messages: Record<string, string> = {
|
||||
cesium_egress_region_denied: "Источник карт блокирует страну исходящего IP выбранного VPS. Выберите другой маршрут.",
|
||||
cesium_egress_invalid: "Выберите подключённую службу маршрутизации.",
|
||||
cesium_egress_unavailable: "Служба маршрутизации недоступна. Проверьте подключение VPS.",
|
||||
cesium_egress_gateway_not_ready: "Сервер хранения локальных данных ещё не подключён к выбранному маршруту. Настройки не изменены.",
|
||||
cesium_token_required: "Добавьте токен Cesium ion для подключения к источнику.",
|
||||
cesium_token_invalid: "Проверьте токен: он не должен содержать пробелы.",
|
||||
cesium_provider_unauthorized: "Cesium ion отклонил токен. Проверьте срок действия, доступ к ресурсам и ограничения адресов.",
|
||||
cesium_provider_unavailable: "Источник Cesium недоступен. Проверьте интернет и повторите попытку.",
|
||||
cesium_provider_rate_limited: "Источник временно ограничил запросы. Повторите проверку позже.",
|
||||
cesium_provider_contract_mismatch: "Источник вернул неподдерживаемый тип карты. Настройки не изменены.",
|
||||
cesium_provider_invalid_response: "Не удалось прочитать ответ источника. Настройки не изменены.",
|
||||
cesium_settings_conflict: "Настройки уже изменены в другом окне. Откройте этот раздел заново.",
|
||||
cesium_settings_unreadable: "Не удалось прочитать сохранённые настройки сервиса.",
|
||||
cesium_settings_unwritable: "Не удалось сохранить настройки сервиса. Проверьте доступ и свободное место.",
|
||||
map_gateway_unavailable: "Сервер хранения локальных данных недоступен. Выберите автоматическое подключение или подключение к источнику.",
|
||||
};
|
||||
export function cesiumServiceMessage(code?: string) { return messages[code ?? ""] ?? "Не удалось выполнить запрос к сервису карт. Повторите попытку."; }
|
||||
export function cesiumTokenIndicator(value: {configured: boolean; draft: boolean; checking: boolean; error: string; verification: CesiumVerification | null}) {
|
||||
if (value.checking) return {tone: "warning" as const, pulse: true, label: "Проверка доступа Cesium ion"};
|
||||
if (value.error) return {tone: "warning" as const, pulse: false, label: value.error};
|
||||
if (value.verification?.ok) return {tone: "success" as const, pulse: false, label: "Cesium ion: доступ подтверждён"};
|
||||
if (value.verification) {
|
||||
const failed = Object.values(value.verification.assets).find(asset => !asset.ok);
|
||||
return {tone: "warning" as const, pulse: false, label: cesiumServiceMessage(failed?.code)};
|
||||
}
|
||||
return {tone: "neutral" as const, pulse: false, label: value.draft ? "Новый токен ещё не проверен" :
|
||||
value.configured ? "Токен сохранён; доступ ещё не проверен" : "Токен не задан"};
|
||||
}
|
||||
async function request<T>(path: string, method = "GET", body?: object): Promise<T> {
|
||||
try {
|
||||
const response = await fetch(endpoint + path, {method, credentials: "same-origin", cache: "no-store",
|
||||
headers: {Accept: "application/json", ...(body ? {"Content-Type": "application/json"} : {})},
|
||||
body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(30_000)});
|
||||
const value = await response.json().catch(() => null);
|
||||
if (!response.ok) throw new Error(cesiumServiceMessage(value?.code));
|
||||
if (!value || typeof value !== "object") throw new Error(cesiumServiceMessage());
|
||||
return value as T;
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "Error") throw error;
|
||||
throw new Error("Сервис карт не ответил. Проверьте соединение и повторите попытку.");
|
||||
}
|
||||
}
|
||||
export const readCesiumService = () => request<CesiumServiceSettings>("");
|
||||
export const verifyCesiumService = (token?: string, egress_id?: string) => request<CesiumVerification>("/verify", "POST", {...(token ? {token} : {}), ...(egress_id !== undefined ? {egress_id} : {})});
|
||||
export async function saveCesiumService(value: {revision: number; mode: CesiumRouteMode; egress_id?: string; token?: string; remove_token?: boolean}) {
|
||||
const result = await request<CesiumServiceSettings>("", "PUT", value);
|
||||
window.dispatchEvent(new Event(cesiumServiceChanged));
|
||||
return result;
|
||||
}
|
||||
@@ -11,7 +11,7 @@ export interface MapGatewayHealthSnapshot {
|
||||
maxBytes: number | null;
|
||||
atCapacity: boolean;
|
||||
persistent: boolean;
|
||||
};
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface MapGatewayHealth {
|
||||
@@ -85,8 +85,11 @@ export function useMapGatewayHealth(active: boolean): MapGatewayHealth {
|
||||
return health;
|
||||
}
|
||||
|
||||
function decodeHealth(value: unknown): MapGatewayHealthSnapshot {
|
||||
export function decodeHealth(value: unknown): MapGatewayHealthSnapshot {
|
||||
const document = record(value, "gateway health");
|
||||
if (document.ok === true && document.service === "missioncore-map-direct" && document.route === "direct") {
|
||||
return {ionConfigured: true, assetAllowlist: [1, 2, 96188], cache: null};
|
||||
}
|
||||
if (document.ok !== true || document.service !== "nodedc-map-gateway") {
|
||||
throw new Error("map_gateway_invalid_response");
|
||||
}
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import {useEffect,useRef} from 'react';
|
||||
import {cesiumServiceChanged} from './cesiumService';
|
||||
|
||||
/** Recover the existing renderer only after its own gateway is reachable again. */
|
||||
/** Recover the existing renderer after either admitted route becomes available. */
|
||||
export function useMapRecovery(unavailable:boolean,retry:()=>void){
|
||||
const callback=useRef(retry);callback.current=retry;
|
||||
useEffect(()=>{
|
||||
const changed=()=>callback.current();
|
||||
window.addEventListener(cesiumServiceChanged,changed);
|
||||
return()=>window.removeEventListener(cesiumServiceChanged,changed);
|
||||
},[]);
|
||||
useEffect(()=>{
|
||||
if(!unavailable)return;
|
||||
let active=true;let timer:ReturnType<typeof setTimeout>;
|
||||
@@ -12,7 +18,7 @@ export function useMapRecovery(unavailable:boolean,retry:()=>void){
|
||||
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. */}
|
||||
}catch{/* The server owns route selection; retry only when reachable. */}
|
||||
if(active)timer=setTimeout(()=>void check(),30000);
|
||||
}
|
||||
timer=setTimeout(()=>void check(),30000);
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {observationViewProfile} from './viewProfile';
|
||||
|
||||
/** Operator presentation only. Never stores or restores control/arming state. */
|
||||
export function useObservationView<T>(kind:'observation-map'|'rover-view',owner:string,defaults:()=>T,legacy:()=>Promise<T|null>){
|
||||
const [document,setDocument]=useState(defaults),[ready,setReady]=useState(false),[error,setError]=useState(''),[reload,setReload]=useState(0);
|
||||
const state=useRef({client:observationViewProfile<T>(kind,owner),document,ready:false,active:false,dirty:false});
|
||||
useEffect(()=>{
|
||||
const current={client:observationViewProfile<T>(kind,owner),document:defaults(),ready:false,active:true,dirty:false};state.current=current;setReady(false);setError('');
|
||||
void current.client.read(legacy).then(value=>{if(!current.active)return;current.document=value??defaults();current.ready=true;setDocument(current.document);setReady(true);}).catch(cause=>{if(current.active)setError(cause instanceof Error?cause.message:'Не удалось прочитать настройки вида.');});
|
||||
return()=>{current.active=false;};
|
||||
},[kind,owner,reload]);
|
||||
const save=()=>{
|
||||
const current=state.current;if(!current.ready||!current.dirty)return;
|
||||
const value=current.document;
|
||||
void current.client.write(value).then(()=>{if(current.document===value)current.dirty=false;if(current.active)setError('');}).catch(cause=>{if(current.active)setError(cause instanceof Error?cause.message:'Не удалось сохранить настройки вида.');});
|
||||
};
|
||||
const update=(change:(value:T)=>T)=>{
|
||||
const current=state.current;if(!current.ready)return;
|
||||
const next=change(current.document);if(JSON.stringify(next)===JSON.stringify(current.document))return;
|
||||
current.document=next;current.dirty=true;setDocument(next);save();
|
||||
};
|
||||
return {document,ready,error,update,retry:()=>{if(state.current.ready)save();else setReload(v=>v+1);}};
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import {profileClient,type ProfileKind} from '../roverScene/profileClient';
|
||||
|
||||
// A newly mounted view must read after the previous view's acknowledged writes.
|
||||
const pending=new Map<string,Promise<unknown>>();
|
||||
export function observationViewProfile<T>(kind:ProfileKind,owner:string){
|
||||
const key=JSON.stringify([kind,owner]),client=profileClient<T>(kind,owner);
|
||||
function serial<R>(action:()=>Promise<R>):Promise<R>{
|
||||
const next=(pending.get(key)??Promise.resolve()).catch(()=>{}).then(action);
|
||||
pending.set(key,next);
|
||||
void next.finally(()=>{if(pending.get(key)===next)pending.delete(key);}).catch(()=>{});
|
||||
return next;
|
||||
}
|
||||
return {read:(legacy?:()=>Promise<T|null>)=>serial(()=>client.read(legacy)),write:(value:T)=>serial(()=>client.write(value))};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/** Durable JSON authority. A legacy browser record is only a one-time migration input. */
|
||||
export type ProfileKind='battery'|'rover'|'battery-ui'|'battery-view'|'environments';
|
||||
export type ProfileKind='battery'|'rover'|'battery-ui'|'battery-view'|'environments'|'observation-map'|'rover-view';
|
||||
type Stored<T>={revision:number;document:T|null};
|
||||
export function profileClient<T>(kind:ProfileKind,owner:string){
|
||||
let revision:number|undefined;
|
||||
|
||||
@@ -2,7 +2,7 @@ import {useCallback, useEffect, useState} from 'react';
|
||||
import type {VPSHost} from '../fleet/vps';
|
||||
import {startSequentialPolling} from './sequentialPolling';
|
||||
|
||||
export type ServerService = {kind:'arnavi'|'wireguard'|'librespeed';id:string;name:string;endpoint:string;state:string;last_seen:number|null;details:VPSHost|{id:string;name:string;endpoint:string;boards:number;last_verified:number|null;state:string}};
|
||||
export type ServerService = {kind:'arnavi'|'wireguard'|'librespeed'|'egress';id:string;name:string;endpoint:string;state:string;last_seen:number|null;details:VPSHost|{id:string;name:string;endpoint:string;boards:number;last_verified:number|null;state:string}};
|
||||
export type Server = {id:string;name:string;address:string;revision:number;services:ServerService[]};
|
||||
export type ServerRemovalPlan = {confirmation:string;name:string;blocked:string[];services:string[];vehicle_connections:number;worker_connections:number};
|
||||
export async function serverRequest<T>(path='', method='GET', body?:unknown, signal?:AbortSignal):Promise<T> {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {useObservationView} from '../../../core/observation/useObservationView';
|
||||
import {useEffect,useMemo,useRef,useState} from 'react';
|
||||
import {CesiumMapRenderer,initialMapRuntimeState,type CesiumMapRendererHandle,type MapCamera,type MapGhostPinLayer} from '@nodedc/map-cesium-react';
|
||||
import {CesiumMapRenderer,initialMapRuntimeState,type CesiumMapRendererHandle,type MapCamera,type MapLayerVisibility,type MapGhostPinLayer} from '@nodedc/map-cesium-react';
|
||||
import { Description,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';
|
||||
@@ -11,26 +12,30 @@ 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,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 view=useObservationView('observation-map',vehicleID,()=>({schema:'missioncore.observation-map/v1' as const,camera:null as MapCamera|null,layers:{...defaults.layerVisibility,grid:false,targets:true} as MapLayerVisibility}),async()=>{
|
||||
try{const camera=JSON.parse(localStorage.getItem(`missioncore.observation-map.v1:${vehicleID}`)??'null') as MapCamera|null;
|
||||
return camera&&['longitude','latitude','height','heading','pitch','roll'].every(key=>Number.isFinite(camera[key as keyof MapCamera]))?{schema:'missioncore.observation-map/v1' as const,camera,layers:{...defaults.layerVisibility,grid:false,targets:true}}:null;
|
||||
}catch{return null;}
|
||||
});
|
||||
const {camera,layers}=view.document;
|
||||
const telemetry=useTrackerTelemetry(vehicleID);
|
||||
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]);
|
||||
function center(){const pin=pins[0];if(pin){view.update(value=>({...value,camera:{longitude:pin.longitude,latitude:pin.latitude,height:1200,heading:0,pitch:-90,roll:0}}));setGeneration(v=>v+1);}}
|
||||
useEffect(()=>{if(view.ready&&pins.length&&!camera)center();},[view.ready,pins.length,camera]);
|
||||
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={!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"><Description>Картографические слои недоступны. Проверяем связь с сервером карты.</Description><Description>{positionLabel}</Description><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={!view.ready||!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}>{view.ready&&<CesiumMapRenderer key={generation} ref={renderer} runtimeConfigUrl="/api/v1/map/runtime-config" camera={camera??defaults.camera} ghostPins={markers} layers={layers} settings={mapPresentation(defaults.visualSettings)} cacheIntent={{enabled:true,no_overwrite:true}} onRuntimeStateChange={setState} onCameraChange={camera=>view.update(value=>({...value,camera}))}/> }</div>
|
||||
{view.ready&&unavailable&&<div className="observation-source__notice"><Description>Картографические слои недоступны. Проверяем связь с сервером карты.</Description><Description>{positionLabel}</Description><Button onClick={()=>setGeneration(v=>v+1)}>Повторить загрузку карты</Button></div>}
|
||||
{view.error&&<div className="observation-source__notice"><Description>{view.error}</Description><Button onClick={view.retry}>Повторить сохранение вида</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 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]} disabled={!view.ready} onChange={value=>view.update(current=>({...current,layers:{...current.layers,[item.id]:value}}))}/>)}
|
||||
</div>
|
||||
</Window>
|
||||
</div>;
|
||||
|
||||
@@ -56,6 +56,7 @@ export function ServersWorkspace({headerToolsHost}:{headerToolsHost?:HTMLElement
|
||||
<Description>Подключено бортов: {'boards' in inspecting.details?inspecting.details.boards:0}</Description>
|
||||
</SettingsCard>
|
||||
</Window>}
|
||||
{inspecting?.kind==='egress'&&<Window open title="Маршрутизация трафика" subtitle={inspecting.endpoint} size="md" onClose={()=>setInspecting(null)}><SettingsCard title="Подключение к источникам"><StatusBadge tone={liveState?.tone??'neutral'}>{liveState?.label??'Связь не проверена'}</StatusBadge><Description>Выберите этот VPS в настройках нужного сервиса. Доступность службы и доступность внешнего источника проверяются отдельно.</Description></SettingsCard></Window>}
|
||||
{inspecting?.kind==='librespeed'&&<Window open title="LibreSpeed" subtitle={inspecting.endpoint} size="md" onClose={()=>setInspecting(null)}><SettingsCard title="Замер скорости" description="Служба для проверки соединения борта через роутер."><StatusBadge tone={liveState?.tone??'neutral'}>{liveState?.label??'Связь не проверена'}</StatusBadge><Description>Запускайте замер из вкладки «Замер скорости» в окне роутера. Одновременно выполняется один замер; результаты не сохраняются на VPS.</Description></SettingsCard></Window>}
|
||||
{store.error&&<SettingsCard title="Не удалось получить VPS" description={store.error}/>}
|
||||
</>;
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import assert from "node:assert/strict";
|
||||
import {after, before, test} from "node:test";
|
||||
import {createServer} from "./support/vite-server.mjs";
|
||||
let server, service, health;
|
||||
const fetchOriginal = globalThis.fetch;
|
||||
before(async () => {
|
||||
server = await createServer({appType: "custom", logLevel: "silent", server: {middlewareMode: true}});
|
||||
service = await server.ssrLoadModule("/src/core/map/cesiumService.ts");
|
||||
health = await server.ssrLoadModule("/src/core/map/useMapGatewayHealth.ts");
|
||||
});
|
||||
after(async () => {globalThis.fetch = fetchOriginal; await server?.close();});
|
||||
test("health distinguishes direct provider from an actual NAS cache", () => {
|
||||
const value = health.decodeHealth({ok: true, service: "missioncore-map-direct", route: "direct", cache: null});
|
||||
assert.equal(value.cache, null);
|
||||
assert.equal(value.ionConfigured, true);
|
||||
assert.throws(() => health.decodeHealth({ok: false, service: "missioncore-map-direct", route: "direct"}));
|
||||
const nas = health.decodeHealth({ok: true, service: "nodedc-map-gateway", ionConfigured: true, assetAllowlist: [1, 2, 96188],
|
||||
cache: {mode: "online", writePolicy: "read-through", entries: 12, bytes: 30, maxBytes: null, atCapacity: false, persistent: true}});
|
||||
assert.equal(nas.cache.entries, 12);
|
||||
});
|
||||
test("settings save uses body-only token and revision, then refreshes maps", async () => {
|
||||
const previousWindow = globalThis.window;
|
||||
const events = [];
|
||||
globalThis.window = {dispatchEvent: event => events.push(event.type)};
|
||||
globalThis.fetch = async (url, options) => {
|
||||
assert.equal(url, "/api/v1/map/services/cesium-ion");
|
||||
assert.equal(options.method, "PUT");
|
||||
assert.equal(options.cache, "no-store");
|
||||
assert.deepEqual(JSON.parse(options.body), {revision: 7, mode: "auto", token: "candidate"});
|
||||
return new Response(JSON.stringify({revision: 8, mode: "auto", token_configured: true}));
|
||||
};
|
||||
try {
|
||||
const value = await service.saveCesiumService({revision: 7, mode: "auto", token: "candidate"});
|
||||
assert.equal(value.revision, 8);
|
||||
assert.deepEqual(events, [service.cesiumServiceChanged]);
|
||||
} finally {globalThis.window = previousWindow;}
|
||||
});
|
||||
test("failed settings write neither exposes upstream body nor announces success", async () => {
|
||||
globalThis.fetch = async () => new Response(JSON.stringify({code: "cesium_provider_unauthorized", detail: "private-credential"}), {status: 401});
|
||||
await assert.rejects(service.saveCesiumService({revision: 7, mode: "auto", token: "candidate"}), error =>
|
||||
/отклонил токен/.test(error.message) && !error.message.includes("private-credential"));
|
||||
});
|
||||
test("token lamp distinguishes saved, pending, verified, rejected and new draft", () => {
|
||||
const base = {configured: false, draft: false, checking: false, error: "", verification: null};
|
||||
assert.equal(service.cesiumTokenIndicator(base).tone, "neutral");
|
||||
assert.equal(service.cesiumTokenIndicator({...base, configured: true}).tone, "neutral");
|
||||
assert.deepEqual(service.cesiumTokenIndicator({...base, checking: true}), {
|
||||
tone: "warning", pulse: true, label: "Проверка доступа Cesium ion",
|
||||
});
|
||||
assert.equal(service.cesiumTokenIndicator({...base, verification: {ok: true, assets: {}}}).tone, "success");
|
||||
assert.match(service.cesiumTokenIndicator({...base, verification: {ok: false,
|
||||
assets: {"1": {ok: false, code: "cesium_provider_unauthorized"}}}}).label, /отклонил токен/);
|
||||
assert.equal(service.cesiumTokenIndicator({...base, error: "Нет соединения"}).tone, "warning");
|
||||
assert.match(service.cesiumTokenIndicator({...base, configured: true, draft: true}).label, /ещё не проверен/);
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const b=await build({entryPoints:['src/workspaces/fleet/observation/ObservationMap.tsx'],bundle:true,write:false,platform:'node',format:'esm',jsx:'automatic',plugins:[{name:'fixture',setup(b){
|
||||
const fixtures={
|
||||
react:'export const useState=v=>globalThis.viewUI.state(v),useRef=v=>globalThis.viewUI.ref(v),useEffect=(f,d)=>globalThis.viewUI.effect(f,d),useMemo=(f,d)=>globalThis.viewUI.memo(f,d);',
|
||||
'react/jsx-runtime':'export const jsx=(type,props)=>({type,props}),jsxs=jsx;',
|
||||
'@nodedc/map-cesium-react':'export const CesiumMapRenderer="Map",initialMapRuntimeState={phase:"ready",providers:{}};',
|
||||
'@nodedc/ui-react':'export const Description="Description",Button="Button",Icon="Icon",IconButton="IconButton",Switch="Switch",Window="Window";',
|
||||
'../../../core/fleet/vps':'export const useTrackerTelemetry=()=>globalThis.viewUI.telemetry;',
|
||||
'../../../core/map/mapView':'export const defaultMapViewDocument=()=>({view:{camera:{longitude:0,latitude:0,height:40000,heading:0,pitch:-50,roll:0},layerVisibility:{imagery:true,terrain:true,buildings:true,grid:false,targets:true},visualSettings:{}}}),encodeMapViewPut=()=>({view:{ghost_pins:{presentation:{}}}});',
|
||||
'../../../core/map/useMapRecovery':'export const useMapRecovery=()=>{};',
|
||||
'../../../components/map/mapPresentation':'export const mapPresentation=v=>v;',
|
||||
'../../../../../../packages/sensor-ui/src/ObservationHeader':'export const ObservationHeader="Header";',
|
||||
};
|
||||
b.onResolve({filter:/.*/},a=>fixtures[a.path]?{path:a.path,namespace:'fixture'}:undefined);
|
||||
b.onLoad({filter:/.*/,namespace:'fixture'},a=>({contents:fixtures[a.path]}));
|
||||
}}]});
|
||||
const {ObservationMap}=await import('data:text/javascript;base64,'+Buffer.from(b.outputFiles[0].contents).toString('base64'));
|
||||
const camera={longitude:37,latitude:55,height:600,heading:137,pitch:-28,roll:3};
|
||||
const layers={imagery:true,terrain:true,buildings:false,grid:false,targets:true};
|
||||
const doc=(value=camera)=>({schema:'missioncore.observation-map/v1',camera:value,layers});
|
||||
function find(v,type){if(!v||typeof v!=='object')return null;if(Array.isArray(v)){for(const item of v){const hit=find(item,type);if(hit)return hit;}return null;}return v.type===type?v:find(v.props?.children,type);}
|
||||
async function fixture(initial,run){
|
||||
const old=new Map(['viewUI','localStorage','fetch'].map(k=>[k,globalThis[k]]));let slots=[],effects=[],queue=[],cursor=0,dirty=true,closed=false;
|
||||
const h={value:{revision:initial?1:0,document:initial},puts:[],tree:null,gate:null,fail:false,
|
||||
telemetry:{items:[{instance_id:'b2',name:'Arnavi',position_fresh:true,online:true,position:{longitude:38,latitude:56,measured_at:1,source:'gnss'}}]},
|
||||
state(v){const i=cursor++;if(!(i in slots))slots[i]=typeof v==='function'?v():v;return[slots[i],v=>{slots[i]=typeof v==='function'?v(slots[i]):v;dirty=true;}];},
|
||||
ref(v){const i=cursor++;return slots[i]??={current:v};},
|
||||
memo(f,d){const i=cursor++;if(!slots[i]||d.some((v,j)=>v!==slots[i].d[j]))slots[i]={d,v:f()};return slots[i].v;},
|
||||
effect(f,d){const i=cursor++;if(!effects[i]||d.some((v,j)=>v!==effects[i].d[j])){const before=effects[i];effects[i]={d};queue.push(()=>{before?.cleanup?.();effects[i].cleanup=f();});}},
|
||||
async settle(){for(let i=0;i<100;i++){await Promise.resolve();if(dirty&&!closed){dirty=false;cursor=0;h.tree=ObservationMap({vehicleID:'fixture',header:{}});for(const f of queue.splice(0))f();}}},
|
||||
close(){closed=true;effects.forEach(e=>e?.cleanup?.());},
|
||||
reopen(){h.close();slots=[];effects=[];queue=[];closed=false;dirty=true;},
|
||||
};
|
||||
globalThis.viewUI=h;globalThis.localStorage={getItem:()=>null};
|
||||
globalThis.fetch=async(_url,o)=>{if(h.fail)return new Response('{}',{status:503});if(o.method==='PUT'){const v=JSON.parse(o.body);h.puts.push(v);if(h.gate)await h.gate;if(v.expected_revision!==h.value.revision)return new Response('{"detail":"conflict"}',{status:409});h.value={revision:h.value.revision+1,document:v.document};}return new Response(JSON.stringify(h.value));};
|
||||
try{await run(h);}finally{h.close();await h.settle();for(const[k,v]of old){if(v===undefined)delete globalThis[k];else globalThis[k]=v;}}
|
||||
}
|
||||
test('saved Cesium tilt wins over tracker arrival and browser cache; reopen waits for camera write',()=>fixture(doc(),async h=>{
|
||||
await h.settle();assert.deepEqual(find(h.tree,'Map').props.camera,camera);assert.equal(h.puts.length,0);assert.deepEqual(find(h.tree,'Map').props.layers,layers);
|
||||
let release;h.gate=new Promise(r=>release=r);const moved={...camera,heading:220,pitch:-17};find(h.tree,'Map').props.onCameraChange(moved);await h.settle();h.reopen();await h.settle();assert.equal(find(h.tree,'Map'),null);
|
||||
release();h.gate=null;await h.settle();assert.deepEqual(find(h.tree,'Map').props.camera,moved);assert.deepEqual(h.value.document.camera,moved);
|
||||
}));
|
||||
test('new map centers once; later telemetry and renderer recovery do not reset its angle',()=>fixture(null,async h=>{
|
||||
await h.settle();assert.equal(find(h.tree,'Map').props.camera.latitude,56);assert.equal(h.puts.length,1);
|
||||
find(h.tree,'Map').props.onCameraChange(camera);await h.settle();h.telemetry.items[0].position.latitude=58;h.reopen();await h.settle();assert.deepEqual(find(h.tree,'Map').props.camera,camera);assert.equal(h.puts.length,2);
|
||||
}));
|
||||
test('failed map profile read cannot render or overwrite defaults',()=>fixture(doc(),async h=>{
|
||||
h.fail=true;await h.settle();assert.equal(find(h.tree,'Map'),null);assert.equal(h.puts.length,0);assert.deepEqual(h.value.document,doc());
|
||||
}));
|
||||
@@ -40,6 +40,7 @@ const {BoardObservationCenter}=await component('../src/workspaces/fleet/observat
|
||||
'../../../components/rover/RoverTelemetry':'export const RoverTelemetry="RoverTelemetry",roverTelemetryMinimum=()=>({width:1,height:1});',
|
||||
});
|
||||
const {RoverView}=await component('../src/components/rover/RoverView.tsx',{
|
||||
'../../core/observation/useObservationView':'export const useObservationView=()=>({ready:true,document:{model:""},update:()=>{},retry:()=>{},error:null});',
|
||||
'../../core/fleet/roverObservation':'export const roverObservationStatus=()=>({label:null,pulse:false});',
|
||||
'../../core/fleet/roverInput':'export const keysFor=()=>[],roverSettings=()=>({mode:"tank",model:"",currentA:34.5,throttlePercent:20}),persistableRoverSettings=()=>false,roverNumberInput=Number;',
|
||||
'../../core/fleet/roverDevEvents':'export const roverDevEvent=()=>{};',
|
||||
|
||||
Reference in New Issue
Block a user