Make simulation imports background tasks with Worker-owned sources and durable deletion
This commit is contained in:
@@ -1,14 +1,21 @@
|
||||
import { useState } from "react";
|
||||
import { useInfrastructureQueue } from "../../core/simulation/infrastructureAnalysis";
|
||||
import { Description, Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow,
|
||||
StatusBadge, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
|
||||
StatusBadge, ProgressBar, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
|
||||
import { updateAiWorld, type AiWorld } from "../../core/simulation/aiPolygon";
|
||||
import {useLocationImports} from "../../core/simulation/locationImports";
|
||||
|
||||
import {deleteLocation,useLocationDeletions} from "../../core/simulation/locationDeletions";
|
||||
import {SimulationOriginalDownload} from "./SimulationOriginalDownload";
|
||||
|
||||
export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused, onOpen, onPlan, canPlan, onChanged}: {
|
||||
worlds: AiWorld[]; removedWorlds: AiWorld[]; activeWorldId?: string; paused: boolean;
|
||||
onOpen: (world: AiWorld) => void; onPlan: (world: AiWorld) => void; canPlan: boolean; onChanged: () => Promise<void>;
|
||||
}) {
|
||||
const queue=useInfrastructureQueue();
|
||||
const deletions=useLocationDeletions(onChanged);
|
||||
const imports=useLocationImports();
|
||||
const uploadingWorlds=new Set(imports.map(task=>task.project?.projectId.replace("sim-","aiworld-")));
|
||||
const [editing, setEditing] = useState<AiWorld | null>(null);
|
||||
const [name, setName] = useState("");
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
@@ -27,16 +34,17 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
|
||||
} finally { setBusy(null); }
|
||||
};
|
||||
return <>
|
||||
<ResourceList>{worlds.map(world => {const queued=queue.jobs.find(j=>j.world_id===world.world_id);return <li key={world.world_id}>
|
||||
<ResourceList>{worlds.filter(world=>!uploadingWorlds.has(world.world_id)).map(world => {const queued=queue.jobs.find(j=>j.world_id===world.world_id);const deletion=deletions.find(d=>d.project_id===world.local_scene?.project_id);return <li key={world.world_id}>
|
||||
<ResourceRow title={world.name} icon={<Icon name="globe"/>}
|
||||
status={activeWorldId === world.world_id ? <StatusBadge tone="neutral">
|
||||
{paused ? "На паузе" : "Сцена открыта"}</StatusBadge> : queued ? <StatusBadge tone={queue.unavailable?"neutral":"warning"}>
|
||||
{queue.unavailable?"Нет обновлений очереди":queued.cancel_requested?"Отмена расчёта":queued.status==="queued"?`В очереди · №${queued.queue?.position??"—"}`:queued.status==="running"?"Расчёт инфраструктуры":"Освобождение Worker"}</StatusBadge> : undefined}
|
||||
actions={<>
|
||||
actions={deletion?<div className="simulation-imports__progress" role="status"><ProgressBar label="Удаление локации"/><Description>{deletion.error??"Удаление локации"}</Description></div>:<>
|
||||
<IconButton label={world.status === "uploading" ? `Продолжить импорт ${world.name}` : `Открыть ${world.name}`}
|
||||
onClick={() => onOpen(world)}><Icon name={world.status === "uploading" ? "upload" : "eye"}/></IconButton>
|
||||
{canPlan&&world.status!=="uploading"&&world.settings.prepared?<IconButton label={`Подготовить маршрут · ${world.name}`}
|
||||
onClick={() => onPlan(world)}><Icon name="plan"/></IconButton>:null}
|
||||
{world.status!=="uploading"?<SimulationOriginalDownload worldId={world.world_id} name={world.name}/>:null}
|
||||
<IconButton label={`Настройки ${world.name}`} onClick={() => {
|
||||
setEditing(world); setName(world.name); setConfirming(false); setError(null);
|
||||
}}><Icon name="settings"/></IconButton>
|
||||
@@ -44,7 +52,7 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
|
||||
</li>;})}</ResourceList>
|
||||
{removedWorlds.length ? <>
|
||||
<Button aria-expanded={showRemoved} onClick={() => setShowRemoved(!showRemoved)}>
|
||||
Удалённые локации · {removedWorlds.length}</Button>
|
||||
Скрытые локации · {removedWorlds.length}</Button>
|
||||
{showRemoved ? <ResourceList>{removedWorlds.map(world => <li key={world.world_id}>
|
||||
<ResourceRow title={world.name} icon={<Icon name="globe"/>} actions={
|
||||
<Button disabled={busy !== null} loading={busy === world.world_id}
|
||||
@@ -55,7 +63,7 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
|
||||
onClose={() => {if (!busy) setEditing(null);}}
|
||||
footer={<WindowFooterActions>
|
||||
<Button icon={<Icon name="trash"/>} disabled={!!busy || editing?.world_id === activeWorldId}
|
||||
onClick={() => setConfirming(true)}>Удалить локацию</Button>
|
||||
onClick={() => setConfirming(true)}>{editing?.local_scene?"Удалить локацию":"Скрыть локацию"}</Button>
|
||||
<Button variant="primary" loading={!!busy} disabled={!name.trim() || name.trim() === editing?.name}
|
||||
onClick={() => {if (editing) void update(editing, {display_name:name.trim()});}}>Сохранить</Button>
|
||||
</WindowFooterActions>}>
|
||||
@@ -63,11 +71,17 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
|
||||
onChange={event => setName(event.target.value)}/>
|
||||
{editing?.world_id === activeWorldId ? <Description>Удаление станет доступно после завершения симуляции.</Description> : null}
|
||||
</Window>
|
||||
<ConfirmationModal open={!!editing && confirming} title="Удалить локацию?" danger
|
||||
description={<>«{editing?.name}» исчезнет из доступных локаций. Исходный скан, разметка и задания сохранятся.
|
||||
Восстановить её можно в списке удалённых локаций.</>}
|
||||
confirmLabel="Удалить" pendingLabel="Удаляем" onClose={() => {if (!busy) setConfirming(false);}}
|
||||
onConfirm={async () => {if (editing) await update(editing, {removed:true});}}/>
|
||||
<ConfirmationModal open={!!editing && confirming} title={editing?.local_scene?"Удалить локацию полностью?":"Скрыть локацию?"} danger
|
||||
description={editing?.local_scene?<>«{editing.name}»: обработка будет остановлена, исходные файлы и результаты удалены на Worker и на этом компьютере. Общие файлы других локаций сохранятся. Отменить удаление нельзя.</>:<>«{editing?.name}» будет скрыта из каталога. Эта старая локация хранит данные в отдельном контуре симулятора; скрытие не удаляет файлы. Восстановление доступно в списке скрытых локаций.</>}
|
||||
confirmLabel={editing?.local_scene?"Удалить полностью":"Скрыть"} pendingLabel="Удаляем" onClose={() => {if (!busy) setConfirming(false);}}
|
||||
onConfirm={async () => {
|
||||
if(!editing)return;
|
||||
if(!editing.local_scene){await update(editing,{removed:true});return;}
|
||||
setBusy(editing.world_id);setError(null);
|
||||
try{await deleteLocation(editing.local_scene.project_id);setConfirming(false);setEditing(null);await onChanged();}
|
||||
catch(caught){setError(caught instanceof Error?caught.message:"Не удалось начать удаление.");}
|
||||
finally{setBusy(null);}
|
||||
}}/>
|
||||
{error ? <ToastStack items={[{id:"location-settings",tone:"error",title:"Не удалось изменить локацию",description:error}]}
|
||||
onDismiss={() => setError(null)}/> : null}
|
||||
</>;
|
||||
|
||||
@@ -2,13 +2,16 @@ import { useEffect, useRef, useState } from "react";
|
||||
import { Button, Icon, ProgressBar, TextField, ToastStack, Window } from "@nodedc/ui-react";
|
||||
import { importAiWorld, type AiSource, type AiWorld } from "../../core/simulation/aiPolygon";
|
||||
|
||||
export function AiWorldImport({ source, resume, onClose, onImported }: {
|
||||
source: AiSource | null; resume?: AiWorld; onClose: () => void; onImported: (world: AiWorld) => void;
|
||||
import {locationImports} from "../../core/simulation/locationImports";
|
||||
import {classifySimulationSource} from "../../core/simulation/sourceFiles";
|
||||
|
||||
export function AiWorldImport({ source, resume, initialFile, onClose, onImported }: {
|
||||
source: AiSource | null; resume?: AiWorld; initialFile?: File; onClose: () => void; onImported: (world: AiWorld) => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<AiSource>(source ?? {
|
||||
name: "", author: "", license: "", source_url: "",
|
||||
name: initialFile?.name.replace(/\.ply$/i, "") ?? "", author: "", license: "", source_url: "",
|
||||
});
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [file, setFile] = useState<File | null>(initialFile ?? null);
|
||||
const [pending, setPending] = useState<AiWorld | undefined>(resume);
|
||||
const [progress, setProgress] = useState(0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -18,6 +21,10 @@ export function AiWorldImport({ source, resume, onClose, onImported }: {
|
||||
useEffect(() => () => controller.current?.abort(), []);
|
||||
const submit = async () => {
|
||||
if (!file || busy) return;
|
||||
if (!resume) {
|
||||
locationImports.enqueue(draft.name.trim(), Promise.resolve().then(()=>({...classifySimulationSource([{file,logicalPath:file.name}]), attribution:{author:draft.author,license:draft.license,source_url:draft.source_url}})));
|
||||
onClose(); return;
|
||||
}
|
||||
setBusy(true); setError(null);
|
||||
const abort = new AbortController(); controller.current = abort;
|
||||
try { onImported(await importAiWorld(file, draft, setProgress, abort.signal, pending, setPending)); }
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import {useCallback, useEffect, useState} from "react";
|
||||
import {ConfirmationModal, Description, Icon, IconButton, ProgressBar, ResourceList, ResourceRow, StatusBadge} from "@nodedc/ui-react";
|
||||
import {locationImports, useLocationImports} from "../../core/simulation/locationImports";
|
||||
import {deleteLocation, useLocationDeletions} from "../../core/simulation/locationDeletions";
|
||||
import {estimateSimulationProcessing, fetchSimulationProjects, retrySimulationProject, type SimulationProject} from "../../core/simulation/projects";
|
||||
|
||||
type DeletionTarget={name:string;taskId?:string;projectId?:string};
|
||||
|
||||
/** Pending source rows stay visible before the world is admitted to the location catalog. */
|
||||
export function SimulationImports({worldIds}:{worldIds:string[]}) {
|
||||
const tasks=useLocationImports();
|
||||
const [projects,setProjects]=useState<SimulationProject[]>([]), [error,setError]=useState<string|null>(null);
|
||||
const [target,setTarget]=useState<DeletionTarget|null>(null);
|
||||
const refresh=useCallback(async()=>{
|
||||
const started=performance.now(),rows=await fetchSimulationProjects();
|
||||
setProjects(rows);locationImports.reconcile(rows.map(row=>row.projectId),started);
|
||||
},[]);
|
||||
const deletions=useLocationDeletions(refresh);
|
||||
useEffect(()=>{
|
||||
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
|
||||
const poll=async()=>{
|
||||
try {const started=performance.now(),rows=await fetchSimulationProjects(abort.signal);
|
||||
if(!abort.signal.aborted){setProjects(rows);locationImports.reconcile(rows.map(row=>row.projectId),started);setError(null);}}
|
||||
catch(caught){if(!abort.signal.aborted)setError(caught instanceof Error?caught.message:"Нет обновлений импорта.");}
|
||||
if(!abort.signal.aborted)timer=setTimeout(()=>void poll(),2000);
|
||||
};
|
||||
void poll();return()=>{abort.abort();clearTimeout(timer);};
|
||||
},[]);
|
||||
useEffect(()=>{
|
||||
for(const task of tasks)if(task.phase==="submitted" && worldIds.includes(task.project?.projectId.replace("sim-","aiworld-")??""))locationImports.forget(task.id);
|
||||
},[tasks,worldIds]);
|
||||
const taskProjects=new Set(tasks.map(task=>task.project?.projectId));
|
||||
const deletingIds=new Set(deletions.map(row=>row.project_id));
|
||||
const pending=projects.filter(project=>project.status!=="ready"&&!taskProjects.has(project.projectId)&&!deletingIds.has(project.projectId));
|
||||
const pendingDeletions=deletions.filter(row=>!taskProjects.has(row.project_id)&&!worldIds.includes(row.project_id.replace("sim-","aiworld-")));
|
||||
if(!tasks.length&&!pending.length&&!pendingDeletions.length&&!error)return null;
|
||||
const retry=async(project:SimulationProject)=>{
|
||||
try {await retrySimulationProject(project.projectId);setProjects(await fetchSimulationProjects());}
|
||||
catch(caught){setError(caught instanceof Error?caught.message:"Не удалось продолжить обработку.");}
|
||||
};
|
||||
const trash=(item:DeletionTarget)=><IconButton label={"Удалить импорт "+item.name} onClick={()=>setTarget(item)}><Icon name="trash"/></IconButton>;
|
||||
return <section className="simulation-imports" aria-label="Импорт локаций">
|
||||
<ResourceList>
|
||||
{tasks.map(task=>{
|
||||
const project=projects.find(row=>row.projectId===task.project?.projectId)??task.project;
|
||||
const serverPhase=task.phase==="submitted"&&project?projectProgress(project):null;
|
||||
const failure=task.error??serverPhase?.error;
|
||||
const label=failure??(task.phase==="deleting"?(deletions.find(row=>row.project_id===task.project?.projectId)?.error??"Удаление импорта"):task.phase==="checking"?"Проверка файла":task.phase==="waiting"?"В очереди загрузки":task.phase==="uploading"?
|
||||
(task.progress===1?"Проверка и сохранение исходного файла":"Загрузка"):serverPhase?.label??"Обновление каталога");
|
||||
return <li key={task.id}><ImportRow name={task.name} label={label} value={task.deleteRequested?undefined:serverPhase?.value??task.progress} failed={!!failure}
|
||||
actions={task.phase==="deleting"?undefined:<>
|
||||
{failure&&!task.deleteRequested?(locationImports.canRetry(task.id)?
|
||||
<IconButton label={"Повторить импорт "+task.name} onClick={()=>locationImports.retry(task.id)}><Icon name="refresh"/></IconButton>:
|
||||
project?<IconButton label={"Повторить обработку "+task.name} onClick={()=>void retry(project)}><Icon name="refresh"/></IconButton>:null):null}
|
||||
{failure&&!project&&!task.deleteRequested?<IconButton label={"Убрать ошибку "+task.name} onClick={()=>locationImports.forget(task.id)}><Icon name="close"/></IconButton>:
|
||||
trash({name:task.name,taskId:task.id})}
|
||||
</>}/></li>;
|
||||
})}
|
||||
{pending.map(project=>{const progress=projectProgress(project);return <li key={project.projectId}>
|
||||
<ImportRow name={project.name} {...progress} failed={!!progress.error} label={progress.error??progress.label}
|
||||
actions={<>{project.status==="failed"?<IconButton label={`Повторить обработку ${project.name}`} onClick={()=>void retry(project)}><Icon name="refresh"/></IconButton>:null}{trash({name:project.name,projectId:project.projectId})}</>}/>
|
||||
</li>;})}
|
||||
{pendingDeletions.map(row=><li key={row.project_id}><ImportRow name={row.name} label={row.error??"Удаление локации"} failed={false}/></li>)}
|
||||
</ResourceList>
|
||||
{error?<Description role="alert">{error}</Description>:null}
|
||||
<ConfirmationModal open={!!target} title="Удалить импорт полностью?" danger confirmLabel="Удалить полностью" pendingLabel="Останавливаем импорт"
|
||||
description={<>«{target?.name}»: загрузка и обработка будут остановлены. Исходные файлы и результаты этой локации будут удалены на Worker и на этом компьютере. Общие файлы других локаций сохранятся.</>}
|
||||
onClose={()=>setTarget(null)} onConfirm={async()=>{
|
||||
if(!target)return;
|
||||
try {
|
||||
if(target.taskId)await locationImports.remove(target.taskId);
|
||||
else if(target.projectId)await deleteLocation(target.projectId);
|
||||
setTarget(null);await refresh();
|
||||
} catch(caught){setError(caught instanceof Error?caught.message:"Не удалось начать удаление.");}
|
||||
}}/>
|
||||
</section>;
|
||||
}
|
||||
|
||||
function ImportRow({name,label,value,failed,actions}:{name:string;label:string;value?:number;failed:boolean;actions?:React.ReactNode}){
|
||||
return <ResourceRow title={name} icon={<Icon name="globe"/>}
|
||||
status={<StatusBadge tone={failed?"danger":"warning"} pulse={!failed}>{failed?"Ошибка импорта":"Импорт"}</StatusBadge>}
|
||||
actions={<><div className="simulation-imports__progress" role={failed?"alert":"status"}>
|
||||
{!failed?<ProgressBar label={label} value={value}/>:null}<Description>{label}{!failed&&value!==undefined?` · ${Math.floor(value*100)}%`:""}</Description>
|
||||
</div>{actions}</>}/>;
|
||||
}
|
||||
|
||||
function projectProgress(project:SimulationProject):{label:string;value?:number;error?:string}{
|
||||
if(project.status==="failed")return {label:"Ошибка обработки",error:project.error??"Обработка не завершена."};
|
||||
if(project.status==="uploading")return {label:"Загрузка исходника не завершена",value:project.source.uploadedByteLength/project.source.totalByteLength};
|
||||
if(project.status==="queued")return {label:"Ожидание обработки"};
|
||||
if(project.status==="ready")return {label:"Готово",value:1};
|
||||
if(project.status==="importing")return {label:"Получение готовой локации"};
|
||||
const label:Record<string,string>={verifying_source:"Проверка исходника",inspecting:"Анализ локации",building_preview:"Конвертация превью",building_streamed_sog:"Конвертация уровней детализации",building_collision:"Подготовка коллизий"};
|
||||
const estimate=estimateSimulationProcessing(project);
|
||||
const eta=estimate?.estimatedSecondsRemaining;
|
||||
return {label:(label[project.provider.state??""]??"Обработка локации")+(eta?` · осталось ≈ ${Math.max(1,Math.ceil(eta/60))} мин`:""),value:estimate?estimate.percent/100:undefined};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import {useState} from "react";
|
||||
import {Button, Description, Icon, IconButton, ToastStack, Window} from "@nodedc/ui-react";
|
||||
import {polygonRequest} from "../../core/simulation/aiPolygon";
|
||||
|
||||
type OriginalFile={name:string;byte_length:number;url:string};
|
||||
export function SimulationOriginalDownload({worldId,name}:{worldId:string;name:string}){
|
||||
const [files,setFiles]=useState<OriginalFile[]|null>(null),[error,setError]=useState<string|null>(null),[busy,setBusy]=useState(false);
|
||||
const download=(file:OriginalFile)=>{window.location.assign(file.url);setFiles(null);};
|
||||
const open=async()=>{
|
||||
setBusy(true);setError(null);
|
||||
try {const result=await polygonRequest<{files:OriginalFile[]}>(`/worlds/${worldId}/originals`);
|
||||
if(result.files.length===1)download(result.files[0]);else setFiles(result.files);
|
||||
}catch(caught){setError(caught instanceof Error?caught.message:"Исходник недоступен.");}
|
||||
finally{setBusy(false);}
|
||||
};
|
||||
return <><IconButton label={`Скачать исходник ${name}`} disabled={busy} onClick={()=>void open()}><Icon name="download"/></IconButton>
|
||||
<Window open={!!files} title={`Исходные файлы · ${name}`} onClose={()=>setFiles(null)}>
|
||||
<Description>Выберите файл для скачивания.</Description>
|
||||
{files?.map(file=><Button key={file.url} onClick={()=>download(file)}>{file.name}</Button>)}
|
||||
</Window>
|
||||
{error?<ToastStack items={[{id:"original-download",tone:"error",title:"Исходник недоступен",description:error}]} onDismiss={()=>setError(null)}/>:null}
|
||||
</>;
|
||||
}
|
||||
@@ -11,26 +11,29 @@ import {
|
||||
} from "@nodedc/ui-react";
|
||||
|
||||
import {
|
||||
createAndUploadSimulationProject,
|
||||
updateSimulationProject,
|
||||
type SimulationProject,
|
||||
type SimulationSceneType,
|
||||
type SimulationUploadCandidate,
|
||||
type SimulationUploadProgress,
|
||||
} from "../../core/simulation/projects";
|
||||
import {
|
||||
candidatesFromDrop,
|
||||
validateSimulationCandidates,
|
||||
classifySimulationSource,
|
||||
} from "../../core/simulation/sourceFiles";
|
||||
|
||||
import { locationImports } from "../../core/simulation/locationImports";
|
||||
|
||||
export function SimulationProjectWindow({
|
||||
open,
|
||||
project,
|
||||
initialCandidates,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: {
|
||||
open: boolean;
|
||||
project: SimulationProject | null;
|
||||
initialCandidates?: SimulationUploadCandidate[];
|
||||
onClose: () => void;
|
||||
onSaved: (project: SimulationProject) => void;
|
||||
}) {
|
||||
@@ -41,7 +44,6 @@ export function SimulationProjectWindow({
|
||||
const [candidates, setCandidates] = useState<SimulationUploadCandidate[]>([]);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const [pending, setPending] = useState(false);
|
||||
const [progress, setProgress] = useState<SimulationUploadProgress | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -49,10 +51,16 @@ export function SimulationProjectWindow({
|
||||
setName(project?.name ?? "");
|
||||
setSceneType(project?.sceneType ?? "outdoor");
|
||||
setCandidates([]);
|
||||
setProgress(null);
|
||||
setPending(false);
|
||||
setError(null);
|
||||
}, [open, project]);
|
||||
if (!project && initialCandidates?.length) {
|
||||
try {
|
||||
validateSimulationCandidates(initialCandidates);
|
||||
setCandidates(initialCandidates);
|
||||
setName(candidateName(initialCandidates));
|
||||
} catch (caught) {setError(caught instanceof Error ? caught.message : "Источник не принят.");}
|
||||
}
|
||||
}, [open, project, initialCandidates]);
|
||||
|
||||
const sourceSummary = useMemo(() => summarizeCandidates(candidates), [candidates]);
|
||||
const canSubmit = name.trim().length > 0 && (project !== null || candidates.length > 0) && !pending;
|
||||
@@ -63,9 +71,7 @@ export function SimulationProjectWindow({
|
||||
setCandidates(next);
|
||||
setError(null);
|
||||
if (!name.trim() && next.length) {
|
||||
const named = next.find((candidate) => /\.lcc2?$/i.test(candidate.logicalPath)) ?? next[0];
|
||||
const first = named?.logicalPath.split("/").filter(Boolean).at(-1) ?? "Новая сцена";
|
||||
setName(first.replace(/\.(lcc2?|zip|rar|7z)$/i, ""));
|
||||
setName(candidateName(next));
|
||||
}
|
||||
} catch (caught) {
|
||||
setCandidates([]);
|
||||
@@ -75,17 +81,15 @@ export function SimulationProjectWindow({
|
||||
|
||||
const submit = async () => {
|
||||
if (!canSubmit) return;
|
||||
if (!project) {
|
||||
locationImports.enqueue(name, Promise.resolve({...classifySimulationSource(candidates), sceneType}));
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
setPending(true);
|
||||
setError(null);
|
||||
try {
|
||||
const saved = project
|
||||
? await updateSimulationProject(project.projectId, name, sceneType)
|
||||
: await createAndUploadSimulationProject(
|
||||
name,
|
||||
sceneType,
|
||||
candidates,
|
||||
setProgress,
|
||||
);
|
||||
const saved = await updateSimulationProject(project.projectId, name, sceneType);
|
||||
onSaved(saved);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof Error ? caught.message : "Не удалось сохранить проект.");
|
||||
@@ -213,33 +217,15 @@ export function SimulationProjectWindow({
|
||||
</div>
|
||||
</FieldFrame>
|
||||
) : null}
|
||||
{progress ? (
|
||||
<div className="simulation-upload-progress" role="status">
|
||||
<span><i style={{ width: `${Math.min(100, progress.totalBytes ? progress.uploadedBytes / progress.totalBytes * 100 : 0)}%` }} /></span>
|
||||
<div>
|
||||
<strong>
|
||||
{formatBytes(progress.uploadedBytes)} / {formatBytes(progress.totalBytes)}
|
||||
{" · "}{formatUploadEta(progress.estimatedSecondsRemaining)}
|
||||
</strong>
|
||||
<small>{progress.currentPath}</small>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{error ? <p className="simulation-project-window__error" role="alert">{error}</p> : null}
|
||||
</div>
|
||||
</Window>
|
||||
);
|
||||
}
|
||||
|
||||
function formatUploadEta(seconds: number | null): string {
|
||||
if (seconds === 0) return "загружено";
|
||||
if (seconds === null) return "считаем время";
|
||||
if (seconds < 60) return `осталось ≈ ${Math.max(1, seconds)} сек`;
|
||||
const minutes = Math.ceil(seconds / 60);
|
||||
if (minutes < 60) return `осталось ≈ ${minutes} мин`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const remainder = minutes % 60;
|
||||
return `осталось ≈ ${hours} ч${remainder ? ` ${remainder} мин` : ""}`;
|
||||
function candidateName(candidates: SimulationUploadCandidate[]): string {
|
||||
const named = candidates.find(candidate => /\.lcc2?$/i.test(candidate.logicalPath)) ?? candidates[0];
|
||||
return (named?.logicalPath.split("/").filter(Boolean).at(-1) ?? "Новая сцена").replace(/\.(lcc2?|zip|rar|7z)$/i, "");
|
||||
}
|
||||
|
||||
function summarizeCandidates(candidates: SimulationUploadCandidate[]): { title: string; detail: string } {
|
||||
|
||||
@@ -1,15 +1,24 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Description, Button, LoadingRegion, Window } from "@nodedc/ui-react";
|
||||
import { fetchSimulationProjects, retrySimulationProject, type SimulationProject } from "../../core/simulation/projects";
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Description, Button, GlassMaterialSurface, Icon, IconButton, LoadingRegion, Window } from "@nodedc/ui-react";
|
||||
import { fetchSimulationProjects, retrySimulationProject, type SimulationProject, type SimulationUploadCandidate } from "../../core/simulation/projects";
|
||||
import { SIMULATION_IMPORT_FORMATS } from "../../core/simulation/sourceFiles";
|
||||
import { useSimulationFileDrop } from "../../core/simulation/useSimulationFileDrop";
|
||||
import { importDroppedLocation } from "../../core/simulation/locationImports";
|
||||
import { SimulationProjectWindow } from "./SimulationProjectWindow";
|
||||
|
||||
/** Reuses the existing resumable Gaussian Pipeline admission workflow. */
|
||||
export function SimulationSourceImport({open,onClose,onPly,onReady}: {
|
||||
open:boolean; onClose:()=>void; onPly:()=>void; onReady:(worldId:string)=>void;
|
||||
export function SimulationSourceImport({children,headerToolsHost,disabled=false,onPly,onReady}: {
|
||||
children:ReactNode; headerToolsHost?:HTMLElement|null; disabled?:boolean;
|
||||
onPly:(file?:File)=>void; onReady:(worldId:string)=>void;
|
||||
}) {
|
||||
const [archive,setArchive]=useState(false), [project,setProject]=useState<SimulationProject|null>(null);
|
||||
const [open,setOpen]=useState(false);
|
||||
const [archive,setArchive]=useState<{candidates?:SimulationUploadCandidate[]}|null>(null), [project,setProject]=useState<SimulationProject|null>(null);
|
||||
const [error,setError]=useState<string|null>(null);
|
||||
const [pending,setPending]=useState<SimulationProject[]>([]);
|
||||
const drop=useSimulationFileDrop(importDroppedLocation,!disabled&&!open&&!archive&&!project);
|
||||
const importAction=<IconButton label="Импорт локации" disabled={disabled||!!archive||open}
|
||||
onClick={()=>setOpen(true)}><Icon name="plus"/></IconButton>;
|
||||
useEffect(()=>{
|
||||
if(!open)return;
|
||||
const abort=new AbortController();setError(null);
|
||||
@@ -33,21 +42,28 @@ export function SimulationSourceImport({open,onClose,onPly,onReady}: {
|
||||
};
|
||||
void poll();return()=>{abort.abort();clearTimeout(timer);};
|
||||
},[project?.projectId,project?.status]);
|
||||
return <>
|
||||
<Window open={open} title="Импорт локации" onClose={onClose}><div className="ai-polygon__actions">
|
||||
<Button onClick={()=>{onClose();onPly();}}>Gaussian PLY</Button>
|
||||
<Button onClick={()=>{onClose();setArchive(true);}}>Архив или папка LCC</Button>
|
||||
return <div className="ai-polygon" {...drop.handlers}>
|
||||
{headerToolsHost?createPortal(importAction,headerToolsHost):<div className="ai-polygon__import-action">{importAction}</div>}
|
||||
{children}
|
||||
{drop.active?<GlassMaterialSurface context="floating" radius="panel" className="simulation-import-overlay" role="status">
|
||||
<Icon name="upload"/><strong>Отпустите файл или папку, чтобы добавить локацию</strong>
|
||||
<Description>{SIMULATION_IMPORT_FORMATS}</Description>
|
||||
<Description>Одна локация за раз. Проверка и импорт начнутся автоматически.</Description>
|
||||
</GlassMaterialSurface>:null}
|
||||
<Window open={open} title="Импорт локации" onClose={()=>setOpen(false)}><div className="ai-polygon__actions">
|
||||
<Button onClick={()=>{setOpen(false);onPly();}}>Gaussian PLY</Button>
|
||||
<Button onClick={()=>{setOpen(false);setArchive({});}}>Архив или папка LCC</Button>
|
||||
</div>
|
||||
{pending.map(p=><div key={p.projectId} className="ai-polygon__row"><Description>{p.name}</Description>
|
||||
<Button onClick={()=>{onClose();setError(null);setProject(p);}}>Подготовка локации</Button></div>)}
|
||||
<Button onClick={()=>{setOpen(false);setError(null);setProject(p);}}>Подготовка локации</Button></div>)}
|
||||
{error?<Description role="alert">{error}</Description>:null}
|
||||
</Window>
|
||||
<SimulationProjectWindow open={archive} project={null} onClose={()=>setArchive(false)} onSaved={p=>{setArchive(false);setProject(p);}} />
|
||||
<SimulationProjectWindow open={!!archive} initialCandidates={archive?.candidates} project={null} onClose={()=>setArchive(null)} onSaved={p=>{setArchive(null);setProject(p);}} />
|
||||
{project?<Window open title={`Подготовка ${project.name}`} onClose={()=>setProject(null)}>
|
||||
<LoadingRegion loading={project.status!=='failed'&&!error} label="Подготовка локации">
|
||||
<Description>{error??project.error??'Локация появится в общей библиотеке после подготовки.'}</Description>
|
||||
{project.status==='failed'?<Button onClick={()=>void retrySimulationProject(project.projectId).then(setProject).catch(e=>setError(e.message))}>Повторить подготовку</Button>:null}
|
||||
</LoadingRegion>
|
||||
</Window>:null}
|
||||
</>;
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import {useEffect,useState} from "react";
|
||||
import {deleteSimulationProject} from "./projects";
|
||||
export interface LocationDeletion {project_id:string;name:string;state:"deleting"|"waiting";error:string|null}
|
||||
export const deleteLocation=deleteSimulationProject;
|
||||
export function useLocationDeletions(onChanged:()=>Promise<void>){
|
||||
const [rows,setRows]=useState<LocationDeletion[]>([]);
|
||||
useEffect(()=>{
|
||||
let stopped=false,timer:ReturnType<typeof setTimeout>;let previous="";
|
||||
const poll=async()=>{
|
||||
try{const response=await fetch("/api/v1/simulation-worlds/deletions");if(!response.ok)throw Error();
|
||||
const data=await response.json() as {deletions:LocationDeletion[]};
|
||||
if(!stopped){setRows(data.deletions);const key=JSON.stringify(data.deletions);if(key!==previous){previous=key;await onChanged();}}}
|
||||
catch{/* Keep acknowledged deletion visible while disconnected. */}
|
||||
if(!stopped)timer=setTimeout(()=>void poll(),1500);
|
||||
};
|
||||
void poll();return()=>{stopped=true;clearTimeout(timer);};
|
||||
},[onChanged]);
|
||||
return rows;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import type {SimulationImportSource} from "./sourceFiles";
|
||||
import type {SimulationProject, SimulationUploadProgress} from "./projects";
|
||||
|
||||
export interface LocationImportTask {
|
||||
id: string; name: string; phase: "checking" | "waiting" | "uploading" | "submitted" | "failed" | "deleting";
|
||||
project?: SimulationProject; progress?: number; error?: string; deleteRequested?: boolean; deletionAcknowledgedAt?: number;
|
||||
}
|
||||
interface Dependencies {
|
||||
create: (name:string, source:SimulationImportSource)=>Promise<SimulationProject>;
|
||||
upload: (project:SimulationProject, source:SimulationImportSource, progress:(value:SimulationUploadProgress)=>void, signal:AbortSignal)=>Promise<SimulationProject>;
|
||||
delete?: (project:SimulationProject)=>Promise<void>;
|
||||
}
|
||||
|
||||
/** Owns browser File handles independently of any modal/workspace mount. */
|
||||
export function createLocationImportQueue(api:Dependencies) {
|
||||
let rows:LocationImportTask[]=[], running=false;
|
||||
const sources=new Map<string,SimulationImportSource>(), listeners=new Set<()=>void>();
|
||||
const controllers=new Map<string,AbortController>(), settled=new Map<string,Promise<void>>();
|
||||
const publish=()=>{for(const listener of listeners)listener();};
|
||||
const change=(id:string,patch:Partial<LocationImportTask>)=>{rows=rows.map(row=>row.id===id?{...row,...patch}:row);publish();};
|
||||
const fail=(id:string,caught:unknown)=>change(id,{phase:"failed",error:caught instanceof Error?caught.message:"Импорт не завершён."});
|
||||
const next=()=>[...rows].reverse().find(item=>item.phase==="waiting");
|
||||
const pump=async()=>{
|
||||
if(running)return;
|
||||
running=true;
|
||||
try {
|
||||
for(let row=next();row;row=next()) {
|
||||
const {id}=row, source=sources.get(id)!;
|
||||
const controller=new AbortController();controllers.set(id,controller);
|
||||
let finish!:()=>void;settled.set(id,new Promise<void>(resolve=>{finish=resolve;}));
|
||||
change(id,{phase:"uploading",progress:undefined,error:undefined});
|
||||
try {
|
||||
const project=row.project??await api.create(row.name,source);
|
||||
change(id,{project});
|
||||
controller.signal.throwIfAborted();
|
||||
const submitted=await api.upload(project,source,value=>change(id,{progress:value.totalBytes?value.uploadedBytes/value.totalBytes:0}),controller.signal);
|
||||
controller.signal.throwIfAborted();
|
||||
change(id,{project:submitted,phase:"submitted",progress:undefined});
|
||||
sources.delete(id);
|
||||
} catch(caught) {if(!controller.signal.aborted)fail(id,caught);}
|
||||
finally {controllers.delete(id);settled.delete(id);finish();}
|
||||
}
|
||||
} finally {running=false;}
|
||||
};
|
||||
return {
|
||||
getSnapshot:()=>rows,
|
||||
subscribe(listener:()=>void){listeners.add(listener);return()=>{listeners.delete(listener);};},
|
||||
enqueue(name:string,source:Promise<SimulationImportSource>,resume?:SimulationProject) {
|
||||
const id=crypto.randomUUID();
|
||||
rows=[{id,name,phase:"checking",project:resume},...rows];publish();
|
||||
void source.then(value=>{
|
||||
if(!rows.some(row=>row.id===id&&!row.deleteRequested))return;
|
||||
sources.set(id,value);change(id,{phase:"waiting"});void pump();
|
||||
}).catch(caught=>fail(id,caught));
|
||||
return id;
|
||||
},
|
||||
async remove(id:string){
|
||||
const row=rows.find(item=>item.id===id);if(!row)return;
|
||||
change(id,{phase:"deleting",deleteRequested:true,error:undefined});
|
||||
controllers.get(id)?.abort();
|
||||
// Creation is deliberately not aborted: retain its server identity for cleanup.
|
||||
await settled.get(id);
|
||||
try {
|
||||
const project=rows.find(item=>item.id===id)?.project;
|
||||
if(project){
|
||||
if(!api.delete)throw new Error("Удаление импорта недоступно.");
|
||||
await api.delete(project);sources.delete(id);
|
||||
change(id,{deletionAcknowledgedAt:performance.now()});
|
||||
} else {sources.delete(id);rows=rows.filter(item=>item.id!==id);publish();}
|
||||
} catch(caught){fail(id,caught);throw caught;}
|
||||
},
|
||||
reconcile(projectIds:string[],requestStartedAt:number){
|
||||
const retained=rows.filter(row=>!(row.deletionAcknowledgedAt!==undefined &&
|
||||
requestStartedAt>=row.deletionAcknowledgedAt && !projectIds.includes(row.project!.projectId)));
|
||||
if(retained.length!==rows.length){rows=retained;publish();}
|
||||
},
|
||||
retry(id:string){if(sources.has(id)&&!rows.find(row=>row.id===id)?.deleteRequested){change(id,{phase:"waiting",error:undefined});void pump();}},
|
||||
canRetry:(id:string)=>sources.has(id),
|
||||
forget(id:string){const row=rows.find(item=>item.id===id);if(!row||!["failed","submitted"].includes(row.phase))return;
|
||||
sources.delete(id);rows=rows.filter(item=>item.id!==id);publish();},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import {useSyncExternalStore} from "react";
|
||||
import {createLocationImportQueue} from "./locationImportQueue";
|
||||
import {createSimulationProject, deleteSimulationProject, uploadSimulationProjectSource} from "./projects";
|
||||
import {candidatesFromDrop, classifySimulationSource} from "./sourceFiles";
|
||||
|
||||
export const locationImports=createLocationImportQueue({
|
||||
create:(name,source)=>createSimulationProject(name,source.sceneType??"outdoor",source.candidates,source.attribution),
|
||||
upload:(project,source,progress,signal)=>uploadSimulationProjectSource(project,source.candidates,progress,signal),
|
||||
delete:project=>deleteSimulationProject(project.projectId),
|
||||
|
||||
});
|
||||
export function useLocationImports(){return useSyncExternalStore(locationImports.subscribe,locationImports.getSnapshot);}
|
||||
export function importDroppedLocation(transfer:DataTransfer){
|
||||
const name=transfer.files[0]?.name.replace(/\.(zip|rar|7z|ply)$/i,"")??"Новая локация";
|
||||
// Capture drop entries synchronously; the row exists before directory checks finish.
|
||||
const source=candidatesFromDrop(transfer).then(classifySimulationSource);
|
||||
locationImports.enqueue(name,source);
|
||||
}
|
||||
@@ -196,6 +196,7 @@ export async function createSimulationProject(
|
||||
name: string,
|
||||
sceneType: SimulationSceneType,
|
||||
candidates: SimulationUploadCandidate[],
|
||||
attribution?: {author:string;license:string;source_url:string|null},
|
||||
): Promise<SimulationProject> {
|
||||
const sourceKind = sourceKindFor(candidates);
|
||||
const createdResponse = await fetch(API_ROOT, {
|
||||
@@ -206,6 +207,7 @@ export async function createSimulationProject(
|
||||
name,
|
||||
scene_type: sceneType,
|
||||
source_kind: sourceKind,
|
||||
attribution,
|
||||
files: candidates.map((candidate) => ({
|
||||
logical_path: candidate.logicalPath,
|
||||
byte_length: candidate.file.size,
|
||||
|
||||
@@ -23,15 +23,21 @@ export async function candidatesFromDrop(
|
||||
transfer: DataTransfer,
|
||||
): Promise<SimulationUploadCandidate[]> {
|
||||
const candidates: SimulationUploadCandidate[] = [];
|
||||
for (const item of Array.from(transfer.items)) {
|
||||
// The browser revokes DataTransfer access after the drop callback returns.
|
||||
// Capture every entry/file before awaiting directory enumeration.
|
||||
const fallbackFiles = Array.from(transfer.files);
|
||||
const entries = Array.from(transfer.items).map(item => {
|
||||
const file = item.getAsFile();
|
||||
const entry = (item as DataTransferItem & {
|
||||
webkitGetAsEntry?: () => LegacyFileEntry | null;
|
||||
}).webkitGetAsEntry?.();
|
||||
return {entry, file};
|
||||
});
|
||||
for (const {entry, file} of entries) {
|
||||
if (entry?.isDirectory) {
|
||||
await collectEntry(entry, candidates);
|
||||
continue;
|
||||
}
|
||||
const file = item.getAsFile();
|
||||
if (file) {
|
||||
candidates.push({ file, logicalPath: file.name });
|
||||
continue;
|
||||
@@ -39,13 +45,33 @@ export async function candidatesFromDrop(
|
||||
if (entry) await collectEntry(entry, candidates);
|
||||
}
|
||||
if (!candidates.length) {
|
||||
for (const file of Array.from(transfer.files)) {
|
||||
for (const file of fallbackFiles) {
|
||||
candidates.push({ file, logicalPath: file.name });
|
||||
}
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
export type SimulationImportSource = ({sceneType?: import("./projects").SimulationSceneType; attribution?:{author:string;license:string;source_url:string|null}} & (
|
||||
| {kind: "ply"; file: File; candidates: SimulationUploadCandidate[]}
|
||||
| {kind: "lcc"; candidates: SimulationUploadCandidate[]}));
|
||||
|
||||
export const SIMULATION_IMPORT_FORMATS = "Gaussian PLY · ZIP, RAR, 7z или папка с LCC/LCC2";
|
||||
|
||||
export function classifySimulationSource(candidates: SimulationUploadCandidate[]): SimulationImportSource {
|
||||
if (candidates.length === 1 && /\.ply$/i.test(candidates[0].logicalPath)) {
|
||||
const file = candidates[0].file;
|
||||
if (!file.size) throw new Error("Выбранный файл пуст.");
|
||||
if (file.size > 8 * 1024 ** 3) throw new Error("Gaussian PLY превышает лимит 8 ГБ.");
|
||||
return {kind: "ply", file, candidates};
|
||||
}
|
||||
if (candidates.length === 1 && !/\.(zip|rar|7z|lcc2?)$/i.test(candidates[0].logicalPath)) {
|
||||
throw new Error(`Формат не поддерживается. Доступны: ${SIMULATION_IMPORT_FORMATS}.`);
|
||||
}
|
||||
validateSimulationCandidates(candidates);
|
||||
return {kind: "lcc", candidates};
|
||||
}
|
||||
|
||||
export async function archivesFromDrop(transfer: DataTransfer): Promise<File[]> {
|
||||
const candidates = await candidatesFromDrop(transfer);
|
||||
const invalid = candidates.filter((candidate) => !ARCHIVE_PATTERN.test(candidate.logicalPath));
|
||||
@@ -71,6 +97,9 @@ export async function archivesFromDrop(transfer: DataTransfer): Promise<File[]>
|
||||
|
||||
export function validateSimulationCandidates(candidates: SimulationUploadCandidate[]): void {
|
||||
if (!candidates.length) throw new Error("Выберите архив или папку с результатом LCC/LCC2.");
|
||||
if (candidates.length === 1 && /\.ply$/i.test(candidates[0].logicalPath)) {
|
||||
classifySimulationSource(candidates); return;
|
||||
}
|
||||
const archives = candidates.filter((candidate) => ARCHIVE_PATTERN.test(candidate.logicalPath));
|
||||
if (archives.length) {
|
||||
if (candidates.length !== 1) throw new Error("Архив нужно загружать одним файлом.");
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import {useEffect, useRef, useState, type DragEvent} from "react";
|
||||
import {hasDroppedFiles} from "./sourceFiles";
|
||||
|
||||
/** External files only; native window/tree dragging and portal forms are independent. */
|
||||
export function useSimulationFileDrop(onDrop: (transfer: DataTransfer) => void, enabled: boolean) {
|
||||
const [active, setActive] = useState(false);
|
||||
const depth = useRef(0);
|
||||
const reset = () => {depth.current = 0; setActive(false);};
|
||||
useEffect(() => {
|
||||
const escape = (event: KeyboardEvent) => {if (event.key === "Escape") reset();};
|
||||
window.addEventListener("dragend", reset); window.addEventListener("blur", reset); window.addEventListener("keydown", escape);
|
||||
return () => {window.removeEventListener("dragend", reset); window.removeEventListener("blur", reset); window.removeEventListener("keydown", escape);};
|
||||
}, []);
|
||||
useEffect(() => {if (!enabled) reset();}, [enabled]);
|
||||
const accepts = (event: DragEvent<HTMLElement>) => event.currentTarget.contains(event.target as Node) && hasDroppedFiles(event.dataTransfer);
|
||||
const handlers = {
|
||||
onDragEnter(event: DragEvent<HTMLElement>) {
|
||||
if (!accepts(event)) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (enabled) {depth.current++; setActive(true);}
|
||||
},
|
||||
onDragOver(event: DragEvent<HTMLElement>) {
|
||||
if (!accepts(event)) return;
|
||||
event.preventDefault(); event.stopPropagation(); event.dataTransfer.dropEffect = enabled ? "copy" : "none";
|
||||
if (enabled) setActive(true);
|
||||
},
|
||||
onDragLeave(event: DragEvent<HTMLElement>) {
|
||||
if (!accepts(event)) return;
|
||||
event.stopPropagation(); if (--depth.current <= 0) reset();
|
||||
},
|
||||
onDrop(event: DragEvent<HTMLElement>) {
|
||||
if (!accepts(event)) return;
|
||||
event.preventDefault(); event.stopPropagation(); reset();
|
||||
if (enabled) onDrop(event.dataTransfer);
|
||||
},
|
||||
};
|
||||
return {active, handlers};
|
||||
}
|
||||
@@ -1,6 +1,12 @@
|
||||
.simulation-profiles { display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 1rem; height: 100%; min-height: 0; }
|
||||
.simulation-profiles > .nodedc-select-anchor { justify-self: start; }
|
||||
.ai-polygon { display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 1rem; height: 100%; min-width: 0; min-height: 0; overflow: hidden; }
|
||||
.ai-polygon { position: relative; display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 1rem; height: 100%; min-width: 0; min-height: 0; overflow: hidden; }
|
||||
.ai-polygon__import-action { position: absolute; top: 0; right: 0; }
|
||||
.simulation-import-overlay.nodedc-glass-material { position: absolute; inset: 0; z-index: 100; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--nodedc-space-3); padding: var(--nodedc-space-5); text-align: center; pointer-events: none; border-radius: var(--nodedc-radius-panel); }
|
||||
.simulation-imports { flex: 0 0 auto; margin-bottom: var(--nodedc-space-3); }
|
||||
.simulation-imports__progress { display: flex; align-items: center; gap: var(--nodedc-space-3); width: clamp(14rem, 35vw, 32rem); max-width: 100%; min-width: 0; }
|
||||
.simulation-imports__progress .nodedc-progress-bar { flex: 1 1 45%; min-width: 3rem; }
|
||||
.simulation-imports__progress .nodedc-description { flex: 1 1 55%; min-width: 0; }
|
||||
.ai-polygon__content { min-height: 0; overflow: auto; overscroll-behavior: contain; padding-bottom: 1rem; }
|
||||
.ai-polygon__head, .ai-polygon__row { display: flex; justify-content: space-between; align-items: center; gap: 1rem; flex-wrap: wrap; }
|
||||
.ai-polygon__actions, .ai-polygon__facts { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; }
|
||||
|
||||
@@ -4,6 +4,7 @@ import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react"
|
||||
import { Description, Button, GlassSurface, Icon, IconButton, LoadingRegion, InspectorSelectField, StatusBadge, ToastStack } from "@nodedc/ui-react";
|
||||
import { AiLocationCatalog } from "../../components/simulation/AiLocationCatalog";
|
||||
import { SimulationSourceImport } from "../../components/simulation/SimulationSourceImport";
|
||||
import { SimulationImports } from "../../components/simulation/SimulationImports";
|
||||
import { AiWorldImport } from "../../components/simulation/AiWorldImport";
|
||||
import { AiWorldStream } from "../../components/simulation/AiWorldStream";
|
||||
import { AiWorldSetup } from "../../components/simulation/AiWorldSetup";
|
||||
@@ -33,7 +34,6 @@ const EMPTY_POINTS:AiWaypoint[]=[];
|
||||
export function AiPolygonWorkspace({headerToolsHost}:{headerToolsHost?:HTMLElement|null}) {
|
||||
const [mode,setMode] = useState<"manual"|"inference">("inference");
|
||||
const [manual,setManual] = useState(false);
|
||||
const [importChoice,setImportChoice] = useState(false);
|
||||
const [planning, setPlanning] = useState(false);
|
||||
const [layout,updateLayout]=useSimulationLayout();
|
||||
const sceneMode=layout.mode, setSceneMode=(mode:typeof sceneMode)=>updateLayout({mode});
|
||||
@@ -41,7 +41,7 @@ export function AiPolygonWorkspace({headerToolsHost}:{headerToolsHost?:HTMLEleme
|
||||
const [catalog, setCatalog] = useState<AiCatalog | null>(null);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [runId, setRunId] = useState<string | null>(null);
|
||||
const [importing, setImporting] = useState<{ source: AiSource | null; resume?: AiWorld } | null>(null);
|
||||
const [importing, setImporting] = useState<{ source: AiSource | null; resume?: AiWorld; file?: File } | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [starting, setStarting] = useState(false);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
@@ -224,7 +224,8 @@ export function AiPolygonWorkspace({headerToolsHost}:{headerToolsHost?:HTMLEleme
|
||||
{taskSelector}
|
||||
{routeActions}
|
||||
</> : null;
|
||||
return <div className="ai-polygon">
|
||||
return <SimulationSourceImport headerToolsHost={headerToolsHost} disabled={!!importing}
|
||||
onPly={file=>setImporting({source:null,file})} onReady={id=>{void load();setSelectedId(id);}}>
|
||||
<header className="ai-polygon__head">
|
||||
<div className="ai-polygon__title">
|
||||
{selected && !planning ? <IconButton label="Назад к локациям" onClick={returnToLocations}>
|
||||
@@ -234,11 +235,11 @@ export function AiPolygonWorkspace({headerToolsHost}:{headerToolsHost?:HTMLEleme
|
||||
</div>
|
||||
<div className="ai-polygon__actions ai-polygon__location-actions" ref={setActionsHost}>
|
||||
{selected ? !planning&&!manual&&!running&&canEdit?<IconButton label="Подготовить маршрут"
|
||||
onClick={()=>start("planning")}><Icon name="plan"/></IconButton>:null : <>{connection}
|
||||
<Button icon={<Icon name="upload" />} onClick={() => setImportChoice(true)}>Импорт локации</Button></>}
|
||||
onClick={()=>start("planning")}><Icon name="plan"/></IconButton>:null : connection}
|
||||
</div>
|
||||
</header>
|
||||
<LoadingRegion className={`ai-polygon__content${manual||planning?" ai-polygon__content--local":""}`} loading={!catalog && !error} label="Загрузка локаций">
|
||||
<SimulationImports worldIds={catalog?.worlds.map(world=>world.world_id)??[]}/>
|
||||
{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>
|
||||
@@ -297,9 +298,7 @@ export function AiPolygonWorkspace({headerToolsHost}:{headerToolsHost?:HTMLEleme
|
||||
}}/> : null}
|
||||
{saveOpen?<AiPlanSaveWindow error={saveError} 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}
|
||||
{importing ? <AiWorldImport source={importing.source} resume={importing.resume} initialFile={importing.file}
|
||||
onClose={() => setImporting(null)} onImported={acceptWorld} /> : null}
|
||||
</div>;
|
||||
</SimulationSourceImport>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import {test} from 'node:test';
|
||||
import ts from 'typescript';
|
||||
async function load(name){
|
||||
const code=ts.transpileModule(readFileSync(new URL(`../src/core/simulation/${name}.ts`,import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
|
||||
return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
|
||||
}
|
||||
const {createLocationImportQueue}=await load('locationImportQueue');
|
||||
const {classifySimulationSource,candidatesFromDrop}=await load('sourceFiles');
|
||||
const tick=()=>new Promise(resolve=>setImmediate(resolve));
|
||||
const deferred=()=>{let resolve;const promise=new Promise(r=>{resolve=r;});return {promise,resolve};};
|
||||
const archive={kind:'lcc',candidates:[{logicalPath:'scene.zip',file:new File(['source'],'scene.zip')}]};
|
||||
|
||||
test('row precedes validation; unsupported input never creates a server project',async()=>{
|
||||
let created=0;const queue=createLocationImportQueue({create:()=>{created++;}});
|
||||
const input=deferred(),id=queue.enqueue('bad.las',input.promise.then(classifySimulationSource));
|
||||
assert.equal(queue.getSnapshot()[0].phase,'checking');
|
||||
input.resolve([{logicalPath:'bad.las',file:new File(['x'],'bad.las')}]);await tick();
|
||||
assert.equal(created,0);assert.match(queue.getSnapshot()[0].error,/Формат не поддерживается/);
|
||||
queue.forget(id);assert.equal(queue.getSnapshot().length,0);
|
||||
});
|
||||
test('background upload survives loss of all UI subscribers; queued files run sequentially',async()=>{
|
||||
const release=deferred(),order=[];let active=0,maxActive=0;
|
||||
const queue=createLocationImportQueue({create:async name=>({projectId:name}),upload:async project=>{
|
||||
active++;maxActive=Math.max(maxActive,active);order.push(project.projectId);
|
||||
if(project.projectId==='first')await release.promise;active--;return {...project,status:'queued'};
|
||||
}});
|
||||
const unsubscribe=queue.subscribe(()=>{});
|
||||
queue.enqueue('first',Promise.resolve(archive));await tick();unsubscribe();
|
||||
queue.enqueue('second',Promise.resolve(archive));queue.enqueue('third',Promise.resolve(archive));await tick();
|
||||
assert.equal(queue.getSnapshot().find(row=>row.name==='second').phase,'waiting');
|
||||
release.resolve();await tick();await tick();
|
||||
assert.deepEqual(order,['first','second','third']);assert.equal(maxActive,1);
|
||||
assert.ok(queue.getSnapshot().every(row=>row.phase==='submitted'));
|
||||
});
|
||||
test('retry after transfer failure reuses the created project instead of making a duplicate',async()=>{
|
||||
let creates=0,attempts=0;
|
||||
const queue=createLocationImportQueue({create:async()=>{creates++;return {projectId:'same'};},upload:async project=>{
|
||||
if(!attempts++)throw new Error('Связь прервана');return {...project,status:'queued'};
|
||||
}});
|
||||
const id=queue.enqueue('scene',Promise.resolve(archive));await tick();
|
||||
assert.equal(queue.getSnapshot()[0].phase,'failed');queue.retry(id);await tick();
|
||||
assert.equal(creates,1);assert.equal(queue.getSnapshot()[0].phase,'submitted');
|
||||
});
|
||||
test('drop captures file references before asynchronous directory enumeration revokes DataTransfer',async()=>{
|
||||
let live=true;const file=new File(['x'],'scene.lcc');
|
||||
const entry={isDirectory:true,createReader:()=>{let done=false;return {readEntries:callback=>{
|
||||
setImmediate(()=>{callback(done?[]:[{isFile:true,fullPath:'/scan/scene.lcc',file:callback=>callback(file)}]);done=true;});
|
||||
}};}};
|
||||
const second=new File(['mesh'],'mesh.ply');
|
||||
const transfer={files:[],items:[{getAsFile:()=>null,webkitGetAsEntry:()=>entry},{getAsFile:()=>live?second:null}]};
|
||||
const result=candidatesFromDrop(transfer);live=false;
|
||||
assert.deepEqual((await result).map(row=>row.logicalPath),['scan/scene.lcc','mesh.ply']);
|
||||
});
|
||||
test('format dispatch checks emptiness, PLY size limit, archive multiplicity and LCC descriptor count',()=>{
|
||||
const candidate=(name,size=1)=>({logicalPath:name,file:{name,size}});
|
||||
assert.equal(classifySimulationSource([candidate('SCAN.PLY')]).kind,'ply');
|
||||
assert.equal(classifySimulationSource([candidate('scene.7z')]).kind,'lcc');
|
||||
assert.throws(()=>classifySimulationSource([candidate('scene.ply',0)]),/пуст/);
|
||||
assert.throws(()=>classifySimulationSource([candidate('scene.ply',9*1024**3)]),/8 ГБ/);
|
||||
assert.throws(()=>classifySimulationSource([candidate('a.zip'),candidate('b.zip')]),/одним файлом/);
|
||||
assert.throws(()=>classifySimulationSource([candidate('folder/a.lcc'),candidate('folder/b.lcc2')]),/ровно одна/);
|
||||
});
|
||||
|
||||
test('PLY and archive forms share durable project upload and preserve source options',async()=>{
|
||||
const calls=[];
|
||||
const queue=createLocationImportQueue({create:async(name,source)=>{calls.push(source);return {projectId:name};},upload:async project=>({...project,status:'queued'})});
|
||||
const source={...classifySimulationSource([{logicalPath:'world.ply',file:new File(['ply'],'world.ply')}]),sceneType:'interior',attribution:{author:'Owner',license:'Private',source_url:null}};
|
||||
queue.enqueue('ply',Promise.resolve(source));await tick();
|
||||
assert.equal(calls.length,1);assert.equal(calls[0].kind,'ply');assert.equal(calls[0].sceneType,'interior');
|
||||
assert.equal(calls[0].attribution.author,'Owner');assert.equal(queue.getSnapshot()[0].phase,'submitted');
|
||||
});
|
||||
|
||||
test('delete during creation waits for server identity and never starts its upload',async()=>{
|
||||
const created=deferred(),events=[];
|
||||
const queue=createLocationImportQueue({create:()=>created.promise,upload:async()=>events.push('upload'),delete:async p=>events.push('delete:'+p.projectId)});
|
||||
const id=queue.enqueue('late',Promise.resolve(archive));await tick();
|
||||
const removal=queue.remove(id);await tick();assert.equal(queue.getSnapshot()[0].phase,'deleting');
|
||||
created.resolve({projectId:'late'});await removal;
|
||||
assert.deepEqual(events,['delete:late']);assert.equal(queue.getSnapshot()[0].phase,'deleting');
|
||||
queue.reconcile([],0);assert.equal(queue.getSnapshot().length,1);
|
||||
queue.reconcile(['late'],Infinity);assert.equal(queue.getSnapshot().length,1);
|
||||
queue.reconcile([],Infinity);assert.equal(queue.getSnapshot().length,0);
|
||||
});
|
||||
test('delete aborts active upload; failed delete remains retryable without restarting upload',async()=>{
|
||||
let attempts=0,aborted=false,uploads=0;
|
||||
const queue=createLocationImportQueue({create:async()=>({projectId:'active'}),upload:async(p,s,progress,signal)=>{
|
||||
uploads++;await new Promise((resolve,reject)=>signal.addEventListener('abort',()=>{aborted=true;reject(new Error('abort'));}));
|
||||
},delete:async()=>{if(!attempts++)throw new Error('offline');}});
|
||||
const id=queue.enqueue('active',Promise.resolve(archive));await tick();
|
||||
await assert.rejects(queue.remove(id),/offline/);assert.equal(aborted,true);
|
||||
assert.equal(queue.getSnapshot()[0].deleteRequested,true);queue.retry(id);await tick();
|
||||
assert.equal(uploads,1);await queue.remove(id);queue.reconcile([],Infinity);assert.equal(queue.getSnapshot().length,0);
|
||||
});
|
||||
test('deleting a checking row prevents a late validation result from admitting a project',async()=>{
|
||||
const checked=deferred();let creates=0;
|
||||
const queue=createLocationImportQueue({create:async()=>{creates++;}});
|
||||
const id=queue.enqueue('checking',checked.promise);await queue.remove(id);checked.resolve(archive);await tick();
|
||||
assert.equal(creates,0);assert.equal(queue.getSnapshot().length,0);
|
||||
});
|
||||
@@ -65,10 +65,10 @@ test("browser upload remains same-origin, resumable and token-free", async () =>
|
||||
assert.match(sourceFiles, /ровно одна сцена \.lcc или \.lcc2/);
|
||||
assert.match(sourceFiles, /отдельные архивы ZIP, RAR или 7z/);
|
||||
assert.doesNotMatch(window, /Загружаем источник/);
|
||||
assert.match(window, /считаем время/);
|
||||
assert.match(window, /locationImports\.enqueue[\s\S]*onClose\(\)/);
|
||||
});
|
||||
|
||||
test("failed simulation can restart from its retained Mission Core source", async () => {
|
||||
test("failed simulation can request restart from its retained source", async () => {
|
||||
const [core, workspace] = await Promise.all([
|
||||
read("core/simulation/projects.ts"),
|
||||
read("components/simulation/SimulationSourceImport.tsx"),
|
||||
|
||||
Reference in New Issue
Block a user