Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
import {useEffect,useLayoutEffect,useMemo,useRef,useState} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {Button,DragDropRoot,DraggableItem,DropZone,GlassSurface,Icon,IconButton,LoadingRegion,Select,StatusBadge,Switch,Window} from '@nodedc/ui-react';
|
||||
import {Button,DockHandle,GlassSurface,Icon,IconButton,LoadingRegion,Select,StatusBadge,Switch,Window} from '@nodedc/ui-react';
|
||||
import {useDevicePluginHost} from '../../../core/device-plugins/DevicePluginHost';
|
||||
import {createFleetSensorTransport} from '../../../core/fleet/sensorTransport';
|
||||
import {decodeObservationLayout,emptyObservationLayout,moveObservation,orderedObservationIDs} from '../../../core/fleet/observationLayout';
|
||||
import {decodeObservationLayout,emptyObservationLayout,moveObservation,withObservationTree,orderedObservationIDs} from '../../../core/fleet/observationLayout';
|
||||
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';
|
||||
@@ -45,21 +45,19 @@ export function BoardObservationCenter({vehicleID,name,enabled,back,configure,he
|
||||
useEffect(()=>{if(!drivingVisible)rover.stop();},[drivingVisible,rover.stop]);
|
||||
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]);
|
||||
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(document.querySelector('[data-docking="true"]'))return;if(event.key!=='Escape'||layersOpen||document.querySelector('[role=dialog], [role=listbox]'))return;if(effectiveFull){setFull(null);event.stopImmediatePropagation();}else if(expanded){setExpanded(false);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull,expanded,layersOpen]);
|
||||
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;
|
||||
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={()=>{setLayersOpen(true);}}>Доступные слои</Button></div>}</div>
|
||||
<div className="observation-deck">{!inventory?<LoadingRegion loading label="Получение визуальных источников"/>:visible.length?<ObservationDeck ids={visible} focusedId={effectiveFull} mounts={mounts.current} layout={layout} labels={Object.fromEntries(sources.map(source=>[source.key,source.view.label]))} onTreeChange={tree=>setLayout(current=>withObservationTree(current,tree))}>
|
||||
{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})=>
|
||||
<div className="observation-panel">
|
||||
<GlassSurface tone="soft" radius="panel" padding="none" materialRim={false} className="observation-panel__surface observation-panel__surface--overlay">
|
||||
<ObservationPanelHeader>
|
||||
{handle}
|
||||
<DockHandle id={source.key} label={source.view.label}/>
|
||||
<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"/>}
|
||||
@@ -71,9 +69,8 @@ export function BoardObservationCenter({vehicleID,name,enabled,back,configure,he
|
||||
</ObservationPanelHeader>
|
||||
<ObservationMount element={media.current.get(source.key)!}/>
|
||||
</GlassSurface>
|
||||
}</DraggableItem>
|
||||
</DropZone>,mounts.current.get(source.key)!,source.key))}
|
||||
</DragDropRoot>
|
||||
</div>,mounts.current.get(source.key)!,source.key))}
|
||||
</ObservationDeck>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>setLayersOpen(true)}>Доступные слои</Button></div>}</div>
|
||||
{groups.map(({device,views,Session})=>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}/>}
|
||||
@@ -81,9 +78,9 @@ export function BoardObservationCenter({vehicleID,name,enabled,back,configure,he
|
||||
{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="Доступные слои" 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}))}/>
|
||||
<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,tree:undefined,splits:{}}))}/>
|
||||
{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>
|
||||
<Button onClick={()=>{setLayout(current=>({...current,tree:undefined,order:[],splits:{},arrangement:'auto'}));setFull(null);}}>Восстановить расположение</Button>
|
||||
</div></Window>
|
||||
</section>,portal)}</>;
|
||||
}
|
||||
|
||||
@@ -1,18 +1 @@
|
||||
import {useLayoutEffect,useRef} from 'react';
|
||||
import {SplitPane} from '@nodedc/ui-react';
|
||||
import type {ObservationLayout} from '../../../core/fleet/observationLayout';
|
||||
|
||||
/** Moving a mount preserves media elements, peer lifetimes and native renderer state. */
|
||||
export function ObservationMount({element,className='observation-mount'}:{element:HTMLElement;className?:string}){
|
||||
const ref=useRef<HTMLDivElement>(null);
|
||||
useLayoutEffect(()=>{const host=ref.current!;host.append(element);return()=>{if(element.parentElement===host)element.remove();};},[element]);
|
||||
return <div ref={ref} className={className}/>;
|
||||
}
|
||||
export function ObservationDeck({ids,mounts,layout,onSplit,depth=0}:{ids:string[];mounts:Map<string,HTMLElement>;layout:ObservationLayout;onSplit:(key:string,value:number)=>void;depth?:number}){
|
||||
if(!ids.length)return null;
|
||||
if(ids.length===1)return <ObservationMount element={mounts.get(ids[0])!}/>;
|
||||
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 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}/>}/>;
|
||||
}
|
||||
export {ObservationDeck,ObservationMount} from "../../../components/observation/ObservationDeck";
|
||||
|
||||
@@ -1,13 +1 @@
|
||||
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>;
|
||||
}
|
||||
export {ObservationPanelHeader} from "../../../components/observation/ObservationPanelHeader";
|
||||
|
||||
@@ -1,50 +1 @@
|
||||
.observation-center { display:flex; flex-direction:column; gap:var(--nodedc-space-3); padding:var(--nodedc-space-4); min-width:0; height:max(600px, calc(100dvh - 260px)); }
|
||||
.observation-center--expanded { position:fixed; inset:0; z-index:var(--nodedc-layer-overlay); background:var(--nodedc-canvas); height:100dvh; box-sizing:border-box; }
|
||||
.observation-toolbar, .observation-summary, .observation-actions { display:flex; align-items:center; gap:var(--nodedc-space-2); }
|
||||
.observation-toolbar { justify-content:space-between; flex-wrap:wrap; }
|
||||
.observation-toolbar h2, .observation-panel h3 { margin:0; }
|
||||
.observation-toolbar span { color:var(--nodedc-text-muted); font-size:var(--nodedc-font-size-sm); }
|
||||
.observation-actions { flex-shrink:0; }
|
||||
.observation-deck { flex:1; min-height:0; min-width:0; }
|
||||
.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; }
|
||||
.observation-panel__title { display:flex; align-items:center; gap:var(--nodedc-space-2); flex:1; min-width:0; }
|
||||
.observation-header-slot, .observation-header-slot > div { display:flex; align-items:center; gap:var(--nodedc-space-2); flex-shrink:0; }
|
||||
.observation-header-slot:has(> div:empty) { display:none; }
|
||||
.observation-layer-select { min-width:0; max-width:120px; }
|
||||
.observation-layer-select button { max-width:100%; }
|
||||
.observation-layer-select button > span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.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: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); }
|
||||
.observation-layer > * { min-width:0; width:100%; }
|
||||
.observation-layer > .nodedc-switch { text-align:left; }
|
||||
.observation-empty { display:grid; place-content:center; height:100%; text-align:center; }
|
||||
.observation-decoder { position:absolute; width:1px; height:1px; opacity:0; pointer-events:none; }
|
||||
@media(max-width:700px) { .observation-toolbar .observation-actions { flex-wrap:wrap; } .observation-center { height:max(650px, calc(100dvh - 200px)); } .observation-center--expanded { height:100dvh; } }
|
||||
|
||||
.observation-map[data-available="false"] > [data-nodedc-map-renderer] { visibility:hidden; }
|
||||
|
||||
/* Transform the live panel as one item; reveal it across nested split boundaries. */
|
||||
.observation-panel-drag { position:relative; height:100%; min-height:0; }
|
||||
.observation-panel-drag.is-dragging { z-index:var(--nodedc-layer-panel); }
|
||||
.observation-split:has(.observation-panel-drag.is-dragging),
|
||||
.observation-split > .nodedc-split-pane__panel:has(.observation-panel-drag.is-dragging) { position:relative; overflow:visible; z-index:var(--nodedc-layer-panel); }
|
||||
@container (max-width:340px) {
|
||||
.observation-panel__header { flex-wrap:wrap; }
|
||||
.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)); }
|
||||
@import "../../../components/observation/observation.css";
|
||||
|
||||
@@ -1,14 +1,37 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Button, GlassSurface, Icon, IconButton, LoadingRegion, StatusBadge, ToastStack } from "@nodedc/ui-react";
|
||||
import { viewedAiRun } from "../../core/simulation/viewedAiRun";
|
||||
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Button, GlassSurface, Icon, IconButton, LoadingRegion, InspectorSelectField, ResourceList, ResourceRow, StatusBadge, ToastStack } from "@nodedc/ui-react";
|
||||
import { SimulationSourceImport } from "../../components/simulation/SimulationSourceImport";
|
||||
import { AiWorldImport } from "../../components/simulation/AiWorldImport";
|
||||
import { AiWorldStream } from "../../components/simulation/AiWorldStream";
|
||||
import { AiWorldSetup } from "../../components/simulation/AiWorldSetup";
|
||||
import { AiRunView } from "../../components/simulation/AiRunView";
|
||||
import { AiRunActions } from "../../components/simulation/AiRunActions";
|
||||
import { AiCompositionFields } from "../../components/simulation/AiCompositionFields";
|
||||
import { fetchAiCatalog, fetchAiModules, startAiRun, type AiCatalog, type AiSource, type AiWorld, type AiRun, type AiModules, type AiSelection } from "../../core/simulation/aiPolygon";
|
||||
import { AiRunReport } from "../../components/simulation/AiRunReport";
|
||||
import { AiConfiguration } from "../../components/simulation/AiConfiguration";
|
||||
import { AiSessionSection } from "../../components/simulation/AiSessionSection";
|
||||
import { AiTaskSelect } from "../../components/simulation/AiTaskSelect";
|
||||
import { AiPlanSaveWindow } from "../../components/simulation/AiPlanSaveWindow";
|
||||
import { planMatchesDraft } from "../../core/simulation/planDraft";
|
||||
import type { AiPlan, AiWaypoint } from "../../core/simulation/aiPolygon";
|
||||
import { aiPlanName, updateAiPlan, removeAiRun, fetchAiCatalog, fetchAiModules, startAiRun, type AiCatalog, type AiSource, type AiWorld, type AiRun, type AiModules } from "../../core/simulation/aiPolygon";
|
||||
import { useAiSelection } from "../../core/simulation/useAiSelection";
|
||||
import { useRoverSettings } from "../../core/simulation/useRoverSettings";
|
||||
import { RoverSettingsWindow } from "../../components/simulation/RoverSettingsWindow";
|
||||
import { currentSelection } from "../../core/simulation/runConfiguration";
|
||||
|
||||
import { saveLocalPlan } from "../../core/simulation/aiEditor";
|
||||
import type { LocalDraft } from "../../components/simulation/AiLocalPlanner";
|
||||
const LocalManualScene = lazy(() => import("../../components/simulation/LocalManualScene").then((m) => ({ default: m.LocalManualScene })));
|
||||
const AiLocalPlanner = lazy(() => import("../../components/simulation/AiLocalPlanner").then((m) => ({ default: m.AiLocalPlanner })));
|
||||
const EMPTY_POINTS:AiWaypoint[]=[];
|
||||
|
||||
export function AiPolygonWorkspace() {
|
||||
const [mode,setMode] = useState<"manual"|"inference">("inference");
|
||||
const [manual,setManual] = useState(false);
|
||||
const [importChoice,setImportChoice] = useState(false);
|
||||
const [planning, setPlanning] = useState(false);
|
||||
const [draft, setDraft] = useState<LocalDraft | null>(null);
|
||||
const [catalog, setCatalog] = useState<AiCatalog | null>(null);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [runId, setRunId] = useState<string | null>(null);
|
||||
@@ -16,14 +39,49 @@ export function AiPolygonWorkspace() {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [starting, setStarting] = useState(false);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [roverSettingsOpen,setRoverSettingsOpen] = useState(false);
|
||||
const [actionsHost, setActionsHost] = useState<HTMLDivElement | null>(null);
|
||||
const [modules, setModules] = useState<AiModules | null>(null);
|
||||
const [selection, setSelection] = useState<AiSelection | undefined>();
|
||||
const [robotId, setRobotId] = useState<string | null>(null);
|
||||
const [planId, setPlanId] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saveOpen, setSaveOpen] = useState(false);
|
||||
const [launchAfterSave,setLaunchAfterSave] = useState(false);
|
||||
const [editorPlan,setEditorPlan] = useState<AiPlan|null>(null);
|
||||
const [planName, setPlanName] = useState("");
|
||||
const [removing,setRemoving] = useState<string|null>(null);
|
||||
const [removed,setRemoved] = useState<{kind:"plan"|"run";id:string;name:string}[]>([]);
|
||||
const planUpdated = (value:AiPlan) => {
|
||||
setCatalog(prior=>prior?{...prior,plans:value.removed ? prior.plans.filter(p=>p.plan_id!==value.plan_id)
|
||||
: prior.plans.map(p=>p.plan_id===value.plan_id?value:p)}:prior);
|
||||
if(value.removed){
|
||||
setRemoved(prior=>[...prior,{kind:"plan",id:value.plan_id,name:aiPlanName(value)}]);
|
||||
if(plan?.plan_id===value.plan_id)setPlanId("");
|
||||
}
|
||||
};
|
||||
const removeRun = async (value:AiRun) => {
|
||||
setRemoving(value.run_id);
|
||||
try {
|
||||
await removeAiRun(value.run_id,true);
|
||||
setCatalog(prior=>prior?{...prior,runs:prior.runs.filter(r=>r.run_id!==value.run_id)}:prior);
|
||||
setRemoved(prior=>[...prior,{kind:"run",id:value.run_id,name:`Прогон ${new Date(value.created_at??"").toLocaleString("ru-RU")}`}]);
|
||||
} catch(caught) { setError(caught instanceof Error?caught.message:"Не удалось удалить прогон."); }
|
||||
finally {setRemoving(null);}
|
||||
};
|
||||
const undoRemove = async () => {
|
||||
const item=removed.at(-1);if(!item)return;
|
||||
setRemoving(item.id);
|
||||
try {
|
||||
if(item.kind==="plan")await updateAiPlan(item.id,{removed:false});else await removeAiRun(item.id,false);
|
||||
await load();setRemoved(prior=>prior.filter(p=>p.id!==item.id));
|
||||
} catch(caught) {setError(caught instanceof Error?caught.message:"Не удалось восстановить запись.");}
|
||||
finally {setRemoving(null);}
|
||||
};
|
||||
const fast = useRef(false);
|
||||
const load = useCallback(async () => { const result = await fetchAiCatalog(); setCatalog(result); }, []);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
void fetchAiModules().then((value) => { if (active) { setModules(value); setSelection(value.selection); } })
|
||||
void fetchAiModules().then((value) => { if (active) setModules(value); })
|
||||
.catch((caught: Error) => { if (active) setError(caught.message); });
|
||||
return () => { active = false; };
|
||||
}, []);
|
||||
@@ -39,15 +97,17 @@ export function AiPolygonWorkspace() {
|
||||
void poll(); return () => { active = false; clearTimeout(timer); };
|
||||
}, []);
|
||||
const selected = catalog?.worlds.find((world) => world.world_id === selectedId);
|
||||
const activeRun = catalog?.runtime.active_run;
|
||||
useEffect(() => {
|
||||
if (activeRun?.world.world_id === selectedId) setRunId(activeRun.run_id);
|
||||
}, [activeRun?.run_id, activeRun?.world.world_id, selectedId]);
|
||||
const run = selected ? catalog?.runtime.active_run?.world.world_id === selected.world_id
|
||||
? catalog.runtime.active_run : catalog?.runs.find((item) => item.run_id === runId && item.world.world_id === selected.world_id)
|
||||
: undefined;
|
||||
// Catalog observation does not acquire NVIDIA's single video slot. Only Start
|
||||
// or an explicit Open may attach this browser to a running simulation.
|
||||
const run = selected && mode === "inference" ? viewedAiRun(catalog,selected.world_id,runId) : undefined;
|
||||
const shownFailure=useRef<string|null>(null);
|
||||
useEffect(()=>{
|
||||
if(run?.state==='failed'&&shownFailure.current!==run.run_id){
|
||||
shownFailure.current=run.run_id;setError(run.message??'Не удалось запустить симуляцию.');
|
||||
}
|
||||
},[run?.run_id,run?.state,run?.message]);
|
||||
const acceptRun = (value: AiRun) => {
|
||||
setSettingsOpen(false);
|
||||
setSettingsOpen(false);setPlanning(false);setDraft(null);
|
||||
setRunId(value.run_id); fast.current = !["completed", "stopped", "failed"].includes(value.state);
|
||||
setCatalog((prior) => prior ? { ...prior, runs: [value, ...prior.runs.filter((r) => r.run_id !== value.run_id)],
|
||||
runtime: { ...prior.runtime, active_run: fast.current ? value : null } } : prior);
|
||||
@@ -59,21 +119,81 @@ export function AiPolygonWorkspace() {
|
||||
const openWorld = (world: AiWorld) => {
|
||||
if (world.status === "uploading") setImporting({ source: world, resume: world });
|
||||
else {
|
||||
setSelectedId(world.world_id); setRunId(null); setSettingsOpen(!world.settings.prepared);
|
||||
setSelectedId(world.world_id); setRunId(catalog?.runtime.active_run?.world.world_id===world.world_id?catalog.runtime.active_run.run_id:null); setPlanId(null);setEditorPlan(null);setSettingsOpen(!world.settings.prepared);
|
||||
}
|
||||
};
|
||||
const returnToLocations = () => { setSelectedId(null); setRunId(null); };
|
||||
const returnToLocations = () => { setManual(false); setPlanning(false); setDraft(null); setSelectedId(null); setRunId(null); };
|
||||
const running = !!run && !["completed", "stopped", "failed"].includes(run.state);
|
||||
const robot = catalog?.robots?.find((item) => item.robot_id === robotId) ?? catalog?.robots?.[0];
|
||||
const [selection, setSelection] = useAiSelection(selectedId, robot?.robot_id ?? null, modules);
|
||||
const plans = (catalog?.plans ?? []).filter((p) => p.world_id === selectedId
|
||||
&& p.robot_id === robot?.robot_id && p.robot_sha256 === robot?.sha256);
|
||||
const previousPlan = (catalog?.plans ?? []).find((p) => p.world_id === selectedId && p.robot_id === robot?.robot_id);
|
||||
const plan = planId === null ? plans[0] : plans.find((p) => p.plan_id === planId);
|
||||
const [roverSettings,setRoverSettings] = useRoverSettings(robot,
|
||||
plan?.settings?.max_speed_mps ?? selected?.settings.max_speed_mps ?? .15);
|
||||
const start = (purpose: "planning" | "evaluation", task=plan) => {
|
||||
if (!selected || !robot) return;
|
||||
if (purpose === "planning") { setEditorPlan(plan??(planId===null?previousPlan:null)??null);setSettingsOpen(false); setDraft(null); setPlanning(true); return; }
|
||||
setStarting(true);
|
||||
void fetchAiModules().then((fresh) => {
|
||||
setModules(fresh);
|
||||
const composition = currentSelection(selection ?? fresh.selection, fresh);
|
||||
setSelection(composition);
|
||||
return startAiRun(selected, robot, composition, purpose, task, roverSettings);
|
||||
}).then(acceptRun).catch((caught: Error) => setError(caught.message)).finally(() => setStarting(false));
|
||||
};
|
||||
const save = () => {
|
||||
if (!draft || !robot) return;
|
||||
setSaving(true);
|
||||
void saveLocalPlan(draft.cache, robot, draft.points, planName, draft.id, draft.sequence).then(async (saved) => {
|
||||
setPlanId(saved.plan_id);setSaveOpen(false);
|
||||
setCatalog(prior=>prior?{...prior,plans:[saved,...prior.plans.filter(p=>p.plan_id!==saved.plan_id)]}:prior);
|
||||
if(launchAfterSave)start("evaluation",saved);
|
||||
}).catch((caught: Error) => setError(caught.message)).finally(() => setSaving(false));
|
||||
};
|
||||
const openSave = (launch=false) => {
|
||||
setLaunchAfterSave(launch);setPlanName(plan?aiPlanName(plan):`${selected?.name} · маршрут`);setSaveOpen(true);
|
||||
};
|
||||
const launchDraft = () => {
|
||||
if(!draft||!robot)return;
|
||||
if(planMatchesDraft(plan,draft.cache.key,robot.sha256,draft.points))start("evaluation",plan);
|
||||
else openSave(true);
|
||||
};
|
||||
const connection = <StatusBadge tone={catalog?.runtime.available ? "success" : "neutral"}>
|
||||
{catalog?.runtime.available ? "Симулятор подключён" : "Симулятор не подключён"}
|
||||
</StatusBadge>;
|
||||
const sceneActions = selected && catalog ? <>
|
||||
<Button onClick={() => setSettingsOpen(!settingsOpen)}>Старт и масштаб</Button>
|
||||
{!run || ["completed", "stopped", "failed"].includes(run.state) ? <Button variant="primary"
|
||||
icon={<Icon name="play" />} loading={starting}
|
||||
disabled={!catalog.runtime.available || !selected.settings.prepared || !!catalog.runtime.active_run}
|
||||
onClick={() => { setStarting(true); void startAiRun(selected, selection).then(acceptRun)
|
||||
.catch((caught: Error) => setError(caught.message)).finally(() => setStarting(false)); }}>Открыть симуляцию</Button> : null}
|
||||
{run ? <AiRunActions run={run} onChange={acceptRun} /> : null}
|
||||
{!planning&&!manual&&!running&&!starting?<><div className="ai-polygon__robot-select"><InspectorSelectField label="Режим" value={mode}
|
||||
options={[{value:"inference",label:"Inference"},{value:"manual",label:"Ручное управление"}]}
|
||||
disabled={running || planning || manual || starting}
|
||||
onChange={(value)=>{setMode(value);setRunId(null);setSettingsOpen(false);}} /></div>
|
||||
<div className="ai-polygon__rover-row"><div className="ai-polygon__robot-select"><InspectorSelectField label="Ровер"
|
||||
value={running ? run.robot?.robot_id ?? "" : robot?.robot_id ?? ""}
|
||||
options={(catalog.robots ?? []).map((item) => ({ value: item.robot_id, label: item.name }))}
|
||||
disabled={planning || manual || starting || running} onChange={(id)=>{setRobotId(id);setPlanId(null);}} /></div>
|
||||
<IconButton label="Настройки ровера" disabled={!robot || !roverSettings || starting}
|
||||
onClick={()=>setRoverSettingsOpen(true)}><Icon name="settings"/></IconButton>
|
||||
</div>
|
||||
{roverSettings?<p>{roverSettings.max_speed_mps} м/с · {roverSettings.base_mass_kg+roverSettings.payload_mass_kg} кг с грузом</p>:null}</>:null}
|
||||
{mode==="inference"&&!running&&!starting?<AiTaskSelect inspector={!planning} plans={plans} value={plan?.plan_id??""}
|
||||
disabled={running||starting||saving} onUpdated={planUpdated}
|
||||
onChange={(id)=>{setPlanId(id);setEditorPlan(plans.find(p=>p.plan_id===id)??null);setSettingsOpen(false);setPlanning(true);}}/>:null}
|
||||
<div className="ai-polygon__actions">{mode === "manual" ? <Button variant="primary" icon={<Icon name={manual ? "stop" : "play"} />}
|
||||
disabled={!robot || !selected.settings.prepared}
|
||||
onClick={()=>{setSettingsOpen(false);setManual(!manual);}}>{manual ? "Завершить" : "Старт"}</Button> : planning ? <>
|
||||
<Button disabled={starting || saving || !draft || draft.points.length < 2}
|
||||
onClick={()=>openSave()}>Сохранить задание</Button>
|
||||
<Button variant="primary" icon={<Icon name="play"/>} loading={starting}
|
||||
disabled={saving || !draft || draft.points.length<2 || selected.inference_ready===false || !catalog.runtime.available || !!catalog.runtime.active_run}
|
||||
onClick={launchDraft}>Запустить симуляцию</Button>
|
||||
</> : !running ? <>
|
||||
<Button loading={starting} disabled={!robot || !selected.settings.prepared}
|
||||
onClick={() => start("planning")}>Подготовить маршрут</Button>
|
||||
<Button variant="primary" icon={<Icon name="play" />} loading={starting}
|
||||
disabled={!robot || !plan || selected.inference_ready === false || !catalog.runtime.available || !!catalog.runtime.active_run}
|
||||
onClick={() => start("evaluation")}>Запустить симуляцию</Button>
|
||||
</> : <AiRunActions run={run!} onChange={acceptRun} />}</div>
|
||||
</> : null;
|
||||
return <div className="ai-polygon">
|
||||
<header className="ai-polygon__head">
|
||||
@@ -84,34 +204,74 @@ export function AiPolygonWorkspace() {
|
||||
<h2>{selected?.name ?? "Доступные локации"}</h2>
|
||||
</div>
|
||||
<div className="ai-polygon__actions" ref={setActionsHost}>
|
||||
{selected ? !run ? sceneActions : null : <>{connection}
|
||||
<Button icon={<Icon name="upload" />} onClick={() => setImporting({ source: null })}>Импорт локации</Button></>}
|
||||
{selected ? null : <>{connection}
|
||||
<Button icon={<Icon name="upload" />} onClick={() => setImportChoice(true)}>Импорт локации</Button></>}
|
||||
</div>
|
||||
</header>
|
||||
<LoadingRegion className="ai-polygon__content" loading={!catalog && !error} label="Загрузка локаций">
|
||||
<LoadingRegion className={`ai-polygon__content${manual||planning?" ai-polygon__content--local":""}`} loading={!catalog && !error} label="Загрузка локаций">
|
||||
{error ? <ToastStack items={[{ id: "error", tone: "error", title: "Не удалось выполнить действие", description: error }]} onDismiss={() => setError(null)} /> : null}
|
||||
{removed.length?<GlassSurface padding="sm" className="ai-polygon__row">
|
||||
<span>Удалено из списка: {removed.at(-1)?.name}</span>
|
||||
<Button disabled={removing!==null} onClick={()=>void undoRemove()}>Отменить удаление</Button>
|
||||
</GlassSurface>:null}
|
||||
{catalog ? !selected ? <section aria-label="Доступные локации" className="ai-polygon__section">
|
||||
{catalog.worlds.map((world) => <GlassSurface key={world.world_id} padding="md" className="ai-polygon__row">
|
||||
<div><strong>{world.name}</strong><p>{world.author} · {world.license}</p></div>
|
||||
{catalog.runtime.active_run?.world.world_id === world.world_id ? <StatusBadge tone="neutral">
|
||||
{catalog.runtime.active_run.state === "running" && catalog.runtime.active_run.telemetry?.ai_ready
|
||||
? "AI запущен" : catalog.runtime.active_run.state === "paused" ? "На паузе" : "Сцена открыта"}
|
||||
</StatusBadge> : null}
|
||||
<Button onClick={() => openWorld(world)}>{world.status === "uploading" ? "Продолжить импорт" : "Открыть"}</Button>
|
||||
</GlassSurface>)}
|
||||
<ResourceList>{catalog.worlds.map((world) => <li key={world.world_id}>
|
||||
<ResourceRow title={world.name} icon={<Icon name="globe"/>}
|
||||
status={catalog.runtime.active_run?.world.world_id === world.world_id ? <StatusBadge tone="neutral">
|
||||
{catalog.runtime.active_run.state === "paused" ? "На паузе" : "Сцена открыта"}
|
||||
</StatusBadge> : undefined}
|
||||
actions={<IconButton label={world.status === "uploading" ? `Продолжить импорт ${world.name}` : `Открыть ${world.name}`}
|
||||
onClick={() => openWorld(world)}><Icon name={world.status === "uploading" ? "upload" : "eye"}/></IconButton>}/>
|
||||
</li>)}</ResourceList>
|
||||
</section> : <section className="ai-polygon__section" aria-label={`Симуляция ${selected.name}`}>
|
||||
<LoadingRegion loading={starting} label="Открываем симуляцию на Worker">
|
||||
{run ? <AiWorldStream world={selected} run={run} onBack={returnToLocations} onChange={acceptRun}
|
||||
{!running && !planning && !manual ? <AiSessionSection key={`${selected.world_id}:configuration`}
|
||||
scope={`${selected.world_id}:configuration`} title="Конфигурация">
|
||||
<div className="ai-polygon__configuration-columns">
|
||||
<section className="ai-polygon__configuration-column" aria-label="Базовые настройки">
|
||||
<h3>Базовые настройки</h3>
|
||||
<div className="ai-polygon__configuration-fields">
|
||||
<InspectorSelectField label="Локация" value={selected.world_id}
|
||||
options={catalog.worlds.filter(w=>w.status!=="uploading").map(w=>({value:w.world_id,label:w.name}))}
|
||||
disabled={starting} onChange={id=>{const world=catalog.worlds.find(w=>w.world_id===id);if(world)openWorld(world);}} />
|
||||
{sceneActions}
|
||||
</div>
|
||||
{mode === "inference" && !running && !planning ? <div className="ai-polygon__facts">
|
||||
{plan ? <p>{plan.points.length} точек · {plan.length_m.toFixed(1)} м · задание сохранено</p>
|
||||
: <p>{previousPlan && !plans.length && planId===null ? "Сохранённый маршрут использует другую версию ровера. Откройте «Подготовить маршрут» и сохраните задание для выбранного ровера." : "Для запуска выберите задание или сохраните маршрут минимум из двух точек: старт и финиш."}</p>}
|
||||
</div> : null}
|
||||
</section>
|
||||
{mode==='inference'&&modules&&selection?<AiConfiguration key={selected.world_id} modules={modules}
|
||||
selection={selection} disabled={starting||!!catalog.runtime.active_run} onChange={setSelection}/>:null}
|
||||
</div>
|
||||
</AiSessionSection> : null}
|
||||
{mode === "inference" && !planning && !running && catalog.runtime.active_run ? <div className="ai-polygon__facts"><p>Выполняется симуляция «{catalog.runtime.active_run.world.name}».</p>
|
||||
{catalog.runtime.active_run.world.world_id===selected.world_id?<Button onClick={()=>acceptRun(catalog.runtime.active_run!)}>Открыть текущую симуляцию</Button>:null}</div> : null}
|
||||
{manual && robot ? <Suspense fallback={<LoadingRegion loading label="Открываем ручное управление" />}>
|
||||
<LocalManualScene key={selected.world_id} world={selected} robot={robot} settings={roverSettings} actionsHost={actionsHost} headerActions={sceneActions} />
|
||||
</Suspense> : planning ? <Suspense fallback={<LoadingRegion loading label="Открываем редактор" />}>
|
||||
<AiLocalPlanner key={selected.world_id} world={selected} initialPoints={editorPlan?.points ?? EMPTY_POINTS}
|
||||
busy={starting || saving} onDraft={setDraft} actionsHost={actionsHost} headerActions={sceneActions} />
|
||||
</Suspense> : <LoadingRegion loading={starting} label="Открываем симуляцию на Worker">
|
||||
{mode === "inference" && running && run ? <AiWorldStream key={run.run_id} world={selected} run={run} onBack={returnToLocations} onChange={acceptRun}
|
||||
actionsHost={actionsHost} headerActions={sceneActions}
|
||||
controls={<AiRunView run={run} connection={connection} />} /> : <div className="ai-polygon__telemetry-row">{connection}</div>}
|
||||
</LoadingRegion>
|
||||
controls={<AiRunView run={run} />} /> : mode === "inference" ? <div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">{connection}{selected.inference_ready===false?<p>{selected.inference_message}</p>:null}</div> : null}
|
||||
</LoadingRegion>}
|
||||
{mode === "inference" && !planning ? <AiRunReport key={selected.world_id} worldId={selected.world_id} modules={modules} onRemove={removeRun} removing={removing} runs={catalog.runs.filter((item) => item.world.world_id === selected.world_id)} /> : null}
|
||||
{settingsOpen ? <AiWorldSetup key={selected.world_id} world={selected}
|
||||
disabled={!!catalog.runtime.active_run} onSaved={acceptWorld} /> : null}
|
||||
{settingsOpen && modules && selection ? <AiCompositionFields modules={modules}
|
||||
selection={activeRun?.world.world_id === selectedId ? activeRun.request?.composition ?? selection : selection}
|
||||
disabled={!!catalog.runtime.active_run} onChange={setSelection} /> : null}
|
||||
|
||||
</section> : null}
|
||||
</LoadingRegion>
|
||||
{roverSettingsOpen && robot && roverSettings && !running && !manual && !planning && !starting
|
||||
? <RoverSettingsWindow key={robot.sha256} robot={robot} value={roverSettings} manual={mode==="manual"}
|
||||
onClose={()=>setRoverSettingsOpen(false)} onApply={value=>{
|
||||
setRoverSettingsOpen(false);
|
||||
try {setRoverSettings(value);} catch {setError("Настройки применены, но не сохранены в браузере. После перезагрузки их нужно задать снова.");}
|
||||
}}/> : null}
|
||||
{saveOpen?<AiPlanSaveWindow name={planName} onName={setPlanName} busy={saving}
|
||||
launch={launchAfterSave} onClose={()=>setSaveOpen(false)} onSave={save}/>:null}
|
||||
<SimulationSourceImport open={importChoice} onClose={()=>setImportChoice(false)}
|
||||
onPly={()=>setImporting({source:null})} onReady={(id)=>{void load();setSelectedId(id);}} />
|
||||
{importing ? <AiWorldImport source={importing.source} resume={importing.resume}
|
||||
onClose={() => setImporting(null)} onImported={acceptWorld} /> : null}
|
||||
</div>;
|
||||
|
||||
@@ -1,428 +1,6 @@
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type DragEvent,
|
||||
} from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Button,
|
||||
ConfirmationModal,
|
||||
GlassSurface,
|
||||
Icon,
|
||||
StatusBadge,
|
||||
Select,
|
||||
} from "@nodedc/ui-react";
|
||||
|
||||
import { SimulationCatalog } from "../../components/simulation/SimulationCatalog";
|
||||
import { AiPolygonWorkspace } from "./AiPolygonWorkspace";
|
||||
import { SimulationProjectWindow } from "../../components/simulation/SimulationProjectWindow";
|
||||
import { SimulationViewport } from "../../components/simulation/SimulationViewport";
|
||||
import {
|
||||
createSimulationProject,
|
||||
deleteSimulationProject,
|
||||
fetchSimulationProjects,
|
||||
retrySimulationProject,
|
||||
uploadSimulationProjectSource,
|
||||
type SimulationProject,
|
||||
type SimulationProjectStatus,
|
||||
type SimulationUploadProgress,
|
||||
} from "../../core/simulation/projects";
|
||||
import {
|
||||
archiveProjectName,
|
||||
archivesFromDrop,
|
||||
hasDroppedFiles,
|
||||
} from "../../core/simulation/sourceFiles";
|
||||
|
||||
const BUILD_STATUSES = new Set<SimulationProjectStatus>(["queued", "processing", "importing"]);
|
||||
|
||||
interface BrowserUpload {
|
||||
project: SimulationProject;
|
||||
file: File;
|
||||
}
|
||||
|
||||
/** One location library; execution mode is selected inside the location. */
|
||||
export function SimulationWorkspace() {
|
||||
const [profile, setProfile] = useState<"lcc" | "ai">(() => {
|
||||
try { return localStorage.getItem("missioncore.simulation-profile") === "ai" ? "ai" : "lcc"; }
|
||||
catch { return "lcc"; }
|
||||
});
|
||||
return <div className="simulation-profiles" data-simulation-profile={profile}>
|
||||
<Select label="Профиль симуляции" value={profile} options={[
|
||||
{ value: "lcc", label: "LCC Gaussian Mirror" }, { value: "ai", label: "AI-полигон" },
|
||||
]} onChange={(value) => { setProfile(value);
|
||||
try { localStorage.setItem("missioncore.simulation-profile", value); } catch { /* Private browsing. */ }
|
||||
}} />
|
||||
{profile === "lcc" ? <LccGaussianWorkspace /> : <AiPolygonWorkspace />}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function LccGaussianWorkspace() {
|
||||
const [projects, setProjects] = useState<SimulationProject[]>([]);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [windowOpen, setWindowOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<SimulationProject | null>(null);
|
||||
const [deleting, setDeleting] = useState<SimulationProject | null>(null);
|
||||
const [retryingId, setRetryingId] = useState<string | null>(null);
|
||||
const [pendingUploads, setPendingUploads] = useState<BrowserUpload[]>([]);
|
||||
const [uploadProgress, setUploadProgress] = useState<Map<string, SimulationUploadProgress>>(
|
||||
() => new Map(),
|
||||
);
|
||||
const [queueError, setQueueError] = useState<string | null>(null);
|
||||
const [dropping, setDropping] = useState(false);
|
||||
const activeUploadRef = useRef<{ projectId: string; controller: AbortController } | null>(null);
|
||||
const intakeChainRef = useRef<Promise<void>>(Promise.resolve());
|
||||
const dragDepthRef = useRef(0);
|
||||
|
||||
const load = useCallback(async (signal?: AbortSignal) => {
|
||||
try {
|
||||
const next = await fetchSimulationProjects(signal);
|
||||
setProjects(next);
|
||||
setError(null);
|
||||
} catch (caught) {
|
||||
if (signal?.aborted) return;
|
||||
setError(caught instanceof Error ? caught.message : "Каталог симуляций недоступен.");
|
||||
} finally {
|
||||
if (!signal?.aborted) setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
void load(controller.signal);
|
||||
return () => controller.abort();
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!projects.some((project) => BUILD_STATUSES.has(project.status))) return;
|
||||
const timer = window.setInterval(() => void load(), 2_000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [load, projects]);
|
||||
|
||||
useEffect(() => {
|
||||
const next = pendingUploads[0];
|
||||
if (!next || activeUploadRef.current) return;
|
||||
const controller = new AbortController();
|
||||
activeUploadRef.current = { projectId: next.project.projectId, controller };
|
||||
void uploadSimulationProjectSource(
|
||||
next.project,
|
||||
[{ file: next.file, logicalPath: next.file.name }],
|
||||
(progress) => {
|
||||
setUploadProgress((current) => {
|
||||
const updated = new Map(current);
|
||||
updated.set(next.project.projectId, progress);
|
||||
return updated;
|
||||
});
|
||||
setProjects((current) => current.map((project) => (
|
||||
project.projectId === next.project.projectId
|
||||
? {
|
||||
...project,
|
||||
source: { ...project.source, uploadedByteLength: progress.uploadedBytes },
|
||||
}
|
||||
: project
|
||||
)));
|
||||
},
|
||||
controller.signal,
|
||||
).then((queued) => {
|
||||
setProjects((current) => current.map((project) => (
|
||||
project.projectId === queued.projectId ? queued : project
|
||||
)));
|
||||
setQueueError(null);
|
||||
}).catch((caught) => {
|
||||
if (controller.signal.aborted) return;
|
||||
setQueueError(caught instanceof Error
|
||||
? `${next.file.name}: ${caught.message}`
|
||||
: `${next.file.name}: загрузка остановлена.`);
|
||||
}).finally(() => {
|
||||
setPendingUploads((current) => current.filter(
|
||||
(item) => item.project.projectId !== next.project.projectId,
|
||||
));
|
||||
setUploadProgress((current) => {
|
||||
const updated = new Map(current);
|
||||
updated.delete(next.project.projectId);
|
||||
return updated;
|
||||
});
|
||||
activeUploadRef.current = null;
|
||||
});
|
||||
}, [pendingUploads]);
|
||||
|
||||
useEffect(() => () => activeUploadRef.current?.controller.abort(), []);
|
||||
|
||||
const selected = useMemo(
|
||||
() => projects.find((project) => project.projectId === selectedId) ?? null,
|
||||
[projects, selectedId],
|
||||
);
|
||||
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
setWindowOpen(true);
|
||||
};
|
||||
|
||||
const openEdit = (project: SimulationProject) => {
|
||||
setEditing(project);
|
||||
setWindowOpen(true);
|
||||
};
|
||||
|
||||
const acceptSaved = (project: SimulationProject) => {
|
||||
const wasEditing = editing !== null;
|
||||
setProjects((current) => [project, ...current.filter((item) => item.projectId !== project.projectId)]);
|
||||
if (!wasEditing) setSelectedId(project.projectId);
|
||||
setWindowOpen(false);
|
||||
setEditing(null);
|
||||
};
|
||||
|
||||
const acceptViewerProject = useCallback((project: SimulationProject) => {
|
||||
setProjects((current) => current.map((item) => (
|
||||
item.projectId === project.projectId ? project : item
|
||||
)));
|
||||
}, []);
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (!deleting) return;
|
||||
const pending = pendingUploads.find((item) => item.project.projectId === deleting.projectId);
|
||||
if (activeUploadRef.current?.projectId === deleting.projectId) {
|
||||
activeUploadRef.current.controller.abort();
|
||||
}
|
||||
setPendingUploads((current) => current.filter(
|
||||
(item) => item.project.projectId !== deleting.projectId,
|
||||
));
|
||||
try {
|
||||
await deleteSimulationProject(deleting.projectId);
|
||||
setProjects((current) => current.filter((project) => project.projectId !== deleting.projectId));
|
||||
setUploadProgress((current) => {
|
||||
const updated = new Map(current);
|
||||
updated.delete(deleting.projectId);
|
||||
return updated;
|
||||
});
|
||||
if (selectedId === deleting.projectId) setSelectedId(null);
|
||||
setDeleting(null);
|
||||
} catch (caught) {
|
||||
if (pending) setPendingUploads((current) => [pending, ...current]);
|
||||
const message = caught instanceof Error ? caught.message : "Не удалось удалить проект.";
|
||||
setQueueError(message);
|
||||
throw caught;
|
||||
}
|
||||
};
|
||||
|
||||
const enqueueDroppedArchives = useCallback((files: File[]) => {
|
||||
intakeChainRef.current = intakeChainRef.current.then(async () => {
|
||||
for (const file of files) {
|
||||
try {
|
||||
const project = await createSimulationProject(
|
||||
archiveProjectName(file.name),
|
||||
"outdoor",
|
||||
[{ file, logicalPath: file.name }],
|
||||
);
|
||||
setProjects((current) => [
|
||||
project,
|
||||
...current.filter((item) => item.projectId !== project.projectId),
|
||||
]);
|
||||
setPendingUploads((current) => [...current, { project, file }]);
|
||||
} catch (caught) {
|
||||
setQueueError(caught instanceof Error
|
||||
? `${file.name}: ${caught.message}`
|
||||
: `${file.name}: не удалось создать проект.`);
|
||||
}
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleDrop = async (transfer: DataTransfer) => {
|
||||
dragDepthRef.current = 0;
|
||||
setDropping(false);
|
||||
setQueueError(null);
|
||||
try {
|
||||
enqueueDroppedArchives(await archivesFromDrop(transfer));
|
||||
} catch (caught) {
|
||||
setQueueError(caught instanceof Error ? caught.message : "Архивы не приняты.");
|
||||
}
|
||||
};
|
||||
|
||||
const handleDragEnter = (event: DragEvent<HTMLDivElement>) => {
|
||||
if (!hasDroppedFiles(event.dataTransfer)) return;
|
||||
event.preventDefault();
|
||||
dragDepthRef.current += 1;
|
||||
setDropping(true);
|
||||
};
|
||||
|
||||
const handleDragLeave = (event: DragEvent<HTMLDivElement>) => {
|
||||
if (!hasDroppedFiles(event.dataTransfer)) return;
|
||||
event.preventDefault();
|
||||
dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
|
||||
if (dragDepthRef.current === 0) setDropping(false);
|
||||
};
|
||||
|
||||
const retry = async (project: SimulationProject) => {
|
||||
setRetryingId(project.projectId);
|
||||
setError(null);
|
||||
try {
|
||||
const queued = await retrySimulationProject(project.projectId);
|
||||
setProjects((current) => current.map((item) => (
|
||||
item.projectId === queued.projectId ? queued : item
|
||||
)));
|
||||
} catch (caught) {
|
||||
setError(caught instanceof Error ? caught.message : "Не удалось повторить сборку.");
|
||||
} finally {
|
||||
setRetryingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (selected) {
|
||||
return (
|
||||
<div className="simulation-workspace simulation-workspace--scene">
|
||||
<header className="simulation-workspace__scene-head">
|
||||
<Button
|
||||
size="compact"
|
||||
variant="ghost"
|
||||
icon={<Icon name="chevron-left" size={16} />}
|
||||
onClick={() => setSelectedId(null)}
|
||||
>
|
||||
Все проекты
|
||||
</Button>
|
||||
<div>
|
||||
<span className="section-eyebrow">LAB / SIMULATION RUNTIME</span>
|
||||
<h2>{selected.name}</h2>
|
||||
</div>
|
||||
<StatusBadge tone={statusPresentation(selected.status).tone}>
|
||||
{statusPresentation(selected.status).label}
|
||||
</StatusBadge>
|
||||
</header>
|
||||
{selected.status === "ready" && selected.worldManifest ? (
|
||||
<SimulationViewport
|
||||
project={selected}
|
||||
onProjectChange={acceptViewerProject}
|
||||
/>
|
||||
) : (
|
||||
<GlassSurface className="simulation-workspace__processing" padding="lg">
|
||||
{selected.status === "failed" ? <Icon name="alert" size={20} /> : <ActivityIndicator label="Сборка мира" />}
|
||||
<div className="simulation-workspace__processing-copy">
|
||||
<strong>{selected.status === "failed" ? "Сборка остановлена" : "Worker 006 собирает мир"}</strong>
|
||||
<p>{error ?? selected.error ?? processingMessage(selected)}</p>
|
||||
</div>
|
||||
<div className="simulation-workspace__processing-actions">
|
||||
<StatusBadge tone={selected.status === "failed" ? "warning" : "accent"}>
|
||||
{providerStateLabel(selected.provider.state, selected.status)}
|
||||
</StatusBadge>
|
||||
{selected.status === "failed" ? (
|
||||
<Button
|
||||
size="compact"
|
||||
variant="secondary"
|
||||
disabled={retryingId === selected.projectId}
|
||||
icon={retryingId === selected.projectId
|
||||
? <ActivityIndicator size="compact" />
|
||||
: <Icon name="refresh" size={14} />}
|
||||
onClick={() => void retry(selected)}
|
||||
>
|
||||
Повторить сборку
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</GlassSurface>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="simulation-workspace"
|
||||
onDragEnter={handleDragEnter}
|
||||
onDragOver={(event) => {
|
||||
if (!hasDroppedFiles(event.dataTransfer)) return;
|
||||
event.preventDefault();
|
||||
event.dataTransfer.dropEffect = "copy";
|
||||
}}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={(event) => {
|
||||
if (!hasDroppedFiles(event.dataTransfer)) return;
|
||||
event.preventDefault();
|
||||
void handleDrop(event.dataTransfer);
|
||||
}}
|
||||
>
|
||||
<header className="simulation-workspace__head">
|
||||
<div>
|
||||
<span className="section-eyebrow">ТЕСТОВЫЙ КОНТУР / СИМУЛЯЦИИ</span>
|
||||
<h2>Gaussian-миры</h2>
|
||||
<p>Каталог исходников, сборок Worker 006 и полнофункциональных интерактивных сцен.</p>
|
||||
</div>
|
||||
<Button variant="primary" icon={<Icon name="plus" size={16} />} onClick={openCreate}>
|
||||
Новый проект
|
||||
</Button>
|
||||
</header>
|
||||
|
||||
<SimulationCatalog
|
||||
projects={projects}
|
||||
uploadProgress={uploadProgress}
|
||||
loading={loading}
|
||||
loadError={error}
|
||||
queueError={queueError}
|
||||
dropping={dropping}
|
||||
onCreate={openCreate}
|
||||
onRetryLoad={() => void load()}
|
||||
onSelect={(project) => setSelectedId(project.projectId)}
|
||||
onEdit={openEdit}
|
||||
onDelete={setDeleting}
|
||||
/>
|
||||
|
||||
<SimulationProjectWindow
|
||||
open={windowOpen}
|
||||
project={editing}
|
||||
onClose={() => { if (!windowOpen) return; setWindowOpen(false); setEditing(null); }}
|
||||
onSaved={acceptSaved}
|
||||
/>
|
||||
<ConfirmationModal
|
||||
open={deleting !== null}
|
||||
title="Удалить проект симуляции?"
|
||||
description={(
|
||||
<p>
|
||||
Проект <strong>{deleting?.name}</strong>, локальные производные артефакты и job на Worker 006 будут удалены.
|
||||
</p>
|
||||
)}
|
||||
confirmLabel="Удалить проект"
|
||||
pendingLabel="Удаляем…"
|
||||
danger
|
||||
onClose={() => setDeleting(null)}
|
||||
onConfirm={confirmDelete}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function statusPresentation(status: SimulationProjectStatus): {
|
||||
label: string;
|
||||
tone: "success" | "accent" | "warning" | "neutral";
|
||||
} {
|
||||
if (status === "ready") return { label: "Визуал готов", tone: "success" };
|
||||
if (status === "failed") return { label: "Ошибка", tone: "warning" };
|
||||
if (status === "uploading") return { label: "Загрузка", tone: "neutral" };
|
||||
if (status === "importing") return { label: "Импорт", tone: "accent" };
|
||||
return { label: "Сборка", tone: "accent" };
|
||||
}
|
||||
|
||||
function processingMessage(project: SimulationProject): string {
|
||||
const progress = project.provider.progress;
|
||||
const completed = progress?.completed_steps;
|
||||
const total = progress?.total_steps;
|
||||
if (typeof completed === "number" && typeof total === "number") {
|
||||
return `Этап ${completed.toLocaleString("ru-RU")} из ${total.toLocaleString("ru-RU")}. Каталог обновляется автоматически.`;
|
||||
}
|
||||
return "Исходник подтверждён; локация и её LOD-уровни собираются в переносимом контейнере.";
|
||||
}
|
||||
|
||||
function providerStateLabel(
|
||||
state: string | null,
|
||||
projectStatus: SimulationProjectStatus,
|
||||
): string {
|
||||
if (state === "queued") return "Ожидание";
|
||||
if (state === "verifying_source") return "Проверка исходника";
|
||||
if (state === "inspecting") return "Анализ локации";
|
||||
if (state === "building_preview") return "Подготовка локации";
|
||||
if (state === "building_streamed_sog") return "Сборка LOD";
|
||||
if (state === "building_collision") return "Сборка коллизий";
|
||||
if (state === "ready") return "Визуал готов";
|
||||
if (state === "failed") return "Ошибка";
|
||||
return statusPresentation(projectStatus).label;
|
||||
return <AiPolygonWorkspace />;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user