Compare commits

...
Author SHA1 Message Date
DCCONSTRUCTIONS 4a8fffb418 feat(bim): integrate selection sync and flight speed rail 2026-11-15 15:40:33 +03:00
DCCONSTRUCTIONS 6911da71d8 Integrate BIM material labels and canvas context menu fix 2026-11-15 15:10:05 +03:00
DCCONSTRUCTIONS 87c0c7960a Integrate BIM shared coordinates and layer placement tools 2026-11-15 14:44:48 +03:00
DCCONSTRUCTIONS b96bea1599 Integrate BIM 0.2.16 background checks and grouped glass panels 2026-11-15 13:45:17 +03:00
DCCONSTRUCTIONS 136be019af fix(bim): integrate surface picking and stable hierarchy viewer 2026-11-15 12:49:31 +03:00
DCCONSTRUCTIONS e8e450e93a fix(bim): integrate consistent keyboard navigation speed 2026-11-15 12:09:13 +03:00
DCCONSTRUCTIONS 28cb2e49a4 feat(bim): integrate surface pivot navigation and transparent dock resizing 2026-11-15 11:57:14 +03:00
DCCONSTRUCTIONS c6280525ba fix(bim): install keyboard-only viewport navigation 2026-11-15 11:14:36 +03:00
DCCONSTRUCTIONS 4002ae4c96 feat(bim): install source preflight and layout-independent viewport flight 2026-11-15 10:53:57 +03:00
DCCONSTRUCTIONS 71705ea862 Integrate BIM project uniqueness and shared content lifecycle 2026-11-15 10:29:45 +03:00
DCCONSTRUCTIONS 91a18c580a fix(bim): align upload bar and status in catalog and layers 2026-11-15 09:57:52 +03:00
DCCONSTRUCTIONS 8e37ef6968 feat(bim): integrate acknowledged upload pause and converter progress 2026-11-15 09:50:23 +03:00
DCCONSTRUCTIONS 1a0b5b0bd7 fix(bim): integrate whole-surface intake and background uploads 2026-11-15 09:07:23 +03:00
DCCONSTRUCTIONS d88ea2de93 feat(bim): integrate Worker point clouds and format downloads 2026-11-15 01:29:41 +03:00
DCCONSTRUCTIONS c785f1173f docs(bim): record lifecycle audit and multiuser readiness limits 2026-11-15 00:13:46 +03:00
DCCONSTRUCTIONS 1c092ff0e3 feat(bim): integrate portable viewport settings and shared screen picker 2026-11-15 00:01:32 +03:00
DCCONSTRUCTIONS f6e0bab559 Integrate BIM selection, cube settings and shared viewport refinements 2026-11-14 23:16:52 +03:00
DCCONSTRUCTIONS e8920f56a2 Integrate dockable BIM viewer, IFC hierarchy and scene tools 2026-11-14 22:16:11 +03:00
DCCONSTRUCTIONS 9937eb66d8 Integrate BIM entry hierarchy, durable retirement and viewport glass 2026-11-14 20:44:00 +03:00
DCCONSTRUCTIONS cd27a5e483 feat(bim): integrate portable IFC viewer, project map and prepared layers 2026-11-14 18:49:43 +03:00
DCCONSTRUCTIONS a49fb00b8e feat(routers): integrate Banana Pi Client API and onboard LibreSpeed measurements
Discover Ethernet routers under the board, map physical SIM slots, expose vendor controls and real telemetry, and provide packaged VPS speed tests with a live monochrome gauge. Enforce compact typography across Core and Node UI.
2026-11-11 23:53:46 +03:00
DCCONSTRUCTIONS 58ac9fe3d2 Assemble complete modular LAB recordings on Worker before readiness 2026-11-10 04:44:02 +03:00
DCCONSTRUCTIONS 800518ea80 Record cold-cache LAB playback acceptance and remaining producer integration 2026-11-10 03:23:43 +03:00
DCCONSTRUCTIONS 1317f78672 Restore complete LAB recordings from verified Worker publications 2026-11-10 03:23:20 +03:00
DCCONSTRUCTIONS a724a9796a docs(worker): qualify Wi-Fi result transfer and explicit range recovery 2026-11-10 02:29:07 +03:00
DCCONSTRUCTIONS 4d0306f353 docs(worker): record LTE telemetry acceptance and local LAB reuse 2026-11-10 02:07:12 +03:00
DCCONSTRUCTIONS 40872d3534 fix(system): keep network configuration in worker settings 2026-11-10 02:06:41 +03:00
DCCONSTRUCTIONS 1472926112 docs: record Ops reconciliation and remaining network acceptance plan 2026-11-10 01:17:10 +03:00
DCCONSTRUCTIONS e8025bc99f feat(system): add worker and VPS catalogs with guarded local removal 2026-11-10 01:11:24 +03:00
DCCONSTRUCTIONS ad5a929e06 feat(worker): supervise VPN connections and recover batched telemetry 2026-11-10 01:10:37 +03:00
DCCONSTRUCTIONS fe5900ff3b refactor(lab): move execution to Worker and manage replay and transfer lifecycles 2026-11-10 01:09:39 +03:00
DCCONSTRUCTIONS cd34b6ce1a fix(scene): persist editor and battery profiles in Core 2026-11-10 01:08:00 +03:00
DCCONSTRUCTIONS 7595bea07c fix(simulation): isolate semantics and correct clipping and orthographic LOD 2026-11-10 01:05:59 +03:00
DCCONSTRUCTIONS ab5766df6a Bound semantic worker storage and add verified evidence closeout 2026-11-07 18:53:56 +03:00
DCCONSTRUCTIONS 43148a8769 Bound semantic map publication and define experiment storage closeout 2026-11-07 17:31:06 +03:00
DCCONSTRUCTIONS 09c13a5c68 Retain imported originals on Worker before retiring Core staging 2026-11-07 16:45:17 +03:00
DCCONSTRUCTIONS b0332fa377 docs: preserve useful experiment history in Ops 2026-11-04 19:22:04 +03:00
DCCONSTRUCTIONS d5f35e4a74 feat(battery): support compact charge indicators and header offset 2026-11-04 18:18:33 +03:00
DCCONSTRUCTIONS 14e6426cd5 feat(scene-editor): duplicate independent materials with named copies 2026-11-04 18:18:33 +03:00
DCCONSTRUCTIONS f228b20c2b feat(battery): configure observatory indicator geometry and space design controls 2026-11-04 17:46:06 +03:00
DCCONSTRUCTIONS 55e1ab8d1c feat(scene-editor): share environment profiles and separate SOC material surfaces 2026-11-04 17:46:05 +03:00
487 changed files with 26981 additions and 4298 deletions
+96 -6
View File
@@ -5,6 +5,17 @@ real device plugin investigates an owner-controlled XGRIDS/LixelKity K1 as a
black-box sensor. Preserve the device, the host, the working LAN, raw evidence, black-box sensor. Preserve the device, the host, the working LAN, raw evidence,
and the boundary between Mission Core and vendor-specific integration code. and the boundary between Mission Core and vendor-specific integration code.
- Owner clarification (2026-11-08): LAB trash means permanent deletion of that
LAB's admitted files on Core and Worker, followed by removal from history.
Do not replace it with catalog-only hiding or leave unreachable result bytes.
Source recordings and files shared by retained LABs are separate owners.
Worker acknowledgement is mandatory; on failure keep a retryable history row.
Local-copy expiry/delete is a separate action that preserves history and Worker
results. Pin protects against expiry, not explicit full-LAB deletion.
A LAB module/registered component, its model, benchmark and shared inputs are
not disposable run output. Missing UI history alone is never evidence of junk;
establish ownership and dependencies before retiring an old experiment.
## Single working directory — owner requirement, 2026-10-08 ## Single working directory — owner requirement, 2026-10-08
The governing Ops record is [MISSIONCOR-50 — Фундаментальная архитектура Mission Core](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-50), The governing Ops record is [MISSIONCOR-50 — Фундаментальная архитектура Mission Core](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-50),
@@ -75,6 +86,55 @@ links to that record for monorepo, storage, resource and live-only telemetry rul
retain the immutable algorithm result and human provenance separately. retain the immutable algorithm result and human provenance separately.
See `docs/SEMANTIC_EDITOR.md` for the delivered scope and outstanding gates. See `docs/SEMANTIC_EDITOR.md` for the delivered scope and outstanding gates.
## LAB placement — owner clarification, 2026-11-08
All supported laboratory execution, raw inputs, intermediate arrays and heavy
working directories belong to the portable Worker runtime. The operator Core is
a viewport: retain ready visual products, semantic maps/manual edits and bounded
metadata, never a silent local compute fallback. See
`docs/LAB_AND_INSTALLER_STORAGE.md` and `deploy/laboratory/README.md`.
Canonical Ops policy: [MISSIONCOR-97 — Storage rules](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-97).
Read its current rules before a new LAB/AI data producer or storage migration;
keep current implementation distinct from the dated distributed-storage research.
A LAB viewing result means a full playable recording with synchronized
segmentation/camera frames, 3D cuboids and timeline where the experiment provides
those layers. Catalog JSON, a screenshot or a textual report does not establish
playback acceptance. Preserve the current UI; do not add neural/narrative reports
or redesign LAB as part of storage migration. Later owner clarification on
8 November explicitly adds global Storage settings (configurable local LAB-copy
retention), offline pins, actual local availability and removal of local copies.
Run history must remain discoverable independently of replay compatibility or
local cache presence. These are requirements, not features already implemented
by the storage audit; see `outputs/storage-fresh-audit-20261108/REPORT.md`.
Verify real playback before retiring local working data; preserve accepted
recordings, Gaussians, semantic edits and original captures.
The configurable LAB-copy TTL (default 30 days) applies exclusively to unpinned
local viewing copies in Mission Core, never to Worker experiments or their models.
Integrated/experimental model assets, installed executor packages/images, runtime
environments and experimental configurations are retained until a separate owner
decision consolidates the pipeline, even under `cache` or `derived`. Do not apply
LAB-copy TTL or absence-from-UI cleanup to them. A disposable transport package
means job input/output transfer bytes, not an executor/model distribution. Before retiring an intermediate
copy, verify publication/retry readers, shared owners and restoration of its exact
identity. See the 8 November intermediate-store rules in
`docs/STORAGE_RETENTION.md` and `outputs/intermediate-storage-review-20261108/REPORT.md`.
Portable source/result transfer uses shared physical-disk reservations (2 GiB
free reserve), not fixed 8/4 GiB directory ceilings or model-count limits.
Source copies registered by admitted producers retire only after durable queue
consumers finish and exact originals remain available. HTTP reader locks span the
whole response. Preserve unknown paths, changed originals, shared filesystem
owners and pending publication/reconciliation. Source retirement is not a TTL.
Result closeout retains manifest/receipt for archive-backed retries; do not
readmit retired compute definitions merely to retire historical copies.
Use an explicit target allowlist for one-time historical cleanup and verify
unselected files; unknown old copies are not automatically adopted by a scan.
These rules do not change installed model/executor assets or viewing-copy TTL.
See the 9 November transfer lifecycle section of `docs/STORAGE_RETENTION.md`.
## Non-negotiable safety boundaries ## Non-negotiable safety boundaries
- Default to non-mutating discovery or read-only operations. CoreBluetooth BLE - Default to non-mutating discovery or read-only operations. CoreBluetooth BLE
@@ -280,12 +340,21 @@ decoders before BLE/Wi-Fi/data-session evidence exists.
- The compact summary must explain the decision question, immutable source, - The compact summary must explain the decision question, immutable source,
tested method/models/algorithms, experimental mode, principal result, tested method/models/algorithms, experimental mode, principal result,
limitations, and retained authority. It is not the engineering report. limitations, and retained authority. It is not the engineering report.
- Owner reporting rule (2026-10-09): Ops contains concise, verified delivered - Owner reporting rule (2026-10-09), clarified 2026-11-04: keep current Ops
results only: what works, the implementation used, and its accepted scope. summaries concise and evidence-backed: what works, implementation and accepted
Keep intermediate experiments, failed attempts, architecture proposals, scope. Replace or remove obsolete assertions about the current state.
detailed logs and future plans in local engineering evidence, not Ops. Preserve decision-relevant dated experiments: capability/limit findings, tested
Consolidate superseded intermediate blocks instead of appending a run diary. alternatives and consequential failures that explain a decision or prevent
Never present a partial experiment as a completed product result. repeating a dead end. Keep the method/conditions, outcome, limitation, decision
and evidence reference separate from current state. Age alone does not make
useful evidence disposable. Do not retain every attempt, intermediate UI edit,
routine check or duplicate metric merely for history; consolidate nonessential
detail and keep traces local. A local backup alone does not preserve important
experiment findings in Ops. Annotate disproved interpretations without erasing
their observations; never invent why an untested option was rejected.
Raw logs/media, credentials and secret fields remain in private evidence;
proposals remain explicitly unverified. Never present a partial experiment as
a completed product result. Follow the ops-context skill for card updates.
- Spatial evidence uses 3D by default. Image-space reprojection may be offered - Spatial evidence uses 3D by default. Image-space reprojection may be offered
as a 2D diagnostic mode inside the same reusable viewer. Primary evidence as a 2D diagnostic mode inside the same reusable viewer. Primary evidence
viewers must provide the canonical expand/restore action. viewers must provide the canonical expand/restore action.
@@ -326,3 +395,24 @@ decoders before BLE/Wi-Fi/data-session evidence exists.
unchanged searches or model variants under a new name. unchanged searches or model variants under a new name.
- Worker access/power/runtime authority comes from the owner's current session - Worker access/power/runtime authority comes from the owner's current session
instructions, never from the card or an old experiment's training allowance. instructions, never from the card or an old experiment's training allowance.
## Scene profile persistence — owner requirement, 2026-11-09
- Rover/battery materials, imported textures, scene/environment profiles, camera
pose, editor-window layout and battery UI/view settings are durable Core JSON
configuration. Use `data_dir/scene-profiles/.../meta.json`; never make browser
IndexedDB/localStorage their sole authority. Do not classify these files or
their recovery copies as cache or task scratch.
- Legacy browser records may be read once only when the Core document is absent.
A failed read must not save defaults over user settings. Preserve source data
during migration/recovery; use atomic replacement, previous-version backup and
revision checks so a stale tab cannot silently replace a newer profile.
- Recover actual settings from retained JSON/records before considering manual
reconstruction. Distinguish a proven storage defect from an unproven deletion
trigger, and state the timestamp/fidelity limit of any recovered source.
## Enforced compact typography
Operational values/section headings use md (13 px), explanatory/status/error copy uses Description/sm (12 px). Only canonical window/page title roles use title (18 px). Do not add browser-default paragraphs, local larger sizes, font shorthand or inline fontSize. Typography checks are mandatory build gates; never extend the frozen compact legacy baseline or generalize scene/display exceptions to satisfy a feature. Run the typography contract tests and verify computed sizes in centered/floating and narrow windows. See Design Guideline docs/OPERATIONAL_TYPOGRAPHY.md.
+11
View File
@@ -10,6 +10,7 @@
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"@noble/hashes": "^2.2.0", "@noble/hashes": "^2.2.0",
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.22.tgz",
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react", "@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns", "@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens", "@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
@@ -882,6 +883,16 @@
"url": "https://paulmillr.com/funding/" "url": "https://paulmillr.com/funding/"
} }
}, },
"node_modules/@nodedc/bim-viewer": {
"version": "0.2.22",
"resolved": "file:../../vendor/bim/nodedc-bim-viewer-0.2.22.tgz",
"integrity": "sha512-Nl2PffhxaiSAdFZpHR5O2oYqxih/csC3fvIUl7EDnWWlDG7j1xKHtLo65suM9EaeAjx1GMUQsjTmF/I7VeI6Ow==",
"peerDependencies": {
"@nodedc/ui-react": "0.7.0",
"react": ">=19 <20",
"react-dom": ">=19 <20"
}
},
"node_modules/@nodedc/map-cesium-react": { "node_modules/@nodedc/map-cesium-react": {
"resolved": "../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react", "resolved": "../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
"link": true "link": true
+4 -2
View File
@@ -6,14 +6,16 @@
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"postinstall": "node scripts/install-rerun-navigation.mjs", "postinstall": "node scripts/install-rerun-navigation.mjs",
"prebuild": "node scripts/install-rerun-navigation.mjs", "prebuild": "npm run check:typography && node scripts/install-rerun-navigation.mjs",
"build": "tsc -b && vite build", "build": "tsc -b && vite build",
"preview": "vite preview", "preview": "vite preview",
"test:unit": "node --test --test-concurrency=1 test/*.test.mjs", "test:unit": "node --test --test-concurrency=1 test/*.test.mjs",
"typecheck": "tsc -b --pretty false" "typecheck": "tsc -b --pretty false",
"check:typography": "node --test test/operationalTypography.test.mjs"
}, },
"dependencies": { "dependencies": {
"@noble/hashes": "^2.2.0", "@noble/hashes": "^2.2.0",
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.22.tgz",
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react", "@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns", "@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens", "@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
+12 -12
View File
@@ -1,7 +1,7 @@
import {SceneDisplayControls} from "../../../packages/spatial-ui/src/SceneDisplayControls"; import {SceneDisplayControls} from "../../../packages/spatial-ui/src/SceneDisplayControls";
import {SceneLayerControls} from "../../../packages/spatial-ui/src/SceneLayerControls"; import {SceneLayerControls} from "../../../packages/spatial-ui/src/SceneLayerControls";
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { import { Description,
AdminNavigationPanel, AdminNavigationPanel,
AppHeader, AppHeader,
ApplicationPanel, ApplicationPanel,
@@ -9,7 +9,6 @@ import {
Button, Button,
ControlRow, ControlRow,
HeaderNavigation, HeaderNavigation,
HeaderProfile,
Icon, Icon,
Inspector, Inspector,
StatusBadge, StatusBadge,
@@ -59,6 +58,7 @@ import {
type ObservationWorkspaceLayoutProfile, type ObservationWorkspaceLayoutProfile,
} from "./core/observation/workspaceLayout"; } from "./core/observation/workspaceLayout";
import { import {
capabilityStatusLabel,
rootById, rootById,
roots, roots,
workspaceById, workspaceById,
@@ -444,7 +444,7 @@ export default function App() {
workspace.openNavigation(); workspace.openNavigation();
if (rootId === "system") { if (rootId === "system") {
workspace.openView( workspace.openView(
activeDefinition?.root === "system" ? activeDefinition.id : "modules", activeDefinition?.id === "vps" ? "vps" : "workers",
); );
} else { } else {
workspace.closeView(); workspace.closeView();
@@ -666,7 +666,7 @@ export default function App() {
connectionScenarioResetting: runtime.pendingAction === "mode", connectionScenarioResetting: runtime.pendingAction === "mode",
saveWorkspaceLayout, saveWorkspaceLayout,
workspaceLayoutSaving: workspaceLayoutProfile.state === "saving", workspaceLayoutSaving: workspaceLayoutProfile.state === "saving",
systemUtilityActions: computeContourSettings.utilityActions, systemUtilityActions: [...computeContourSettings.utilityActions, {label: "К списку воркеров", icon: "chevron-left", onClick: () => openNavigationView("workers")}],
sessionOverview: { ...sessionOverview, available: Boolean(recordedReplay && replayPresented && !sourceSwitchBlocked) }, sessionOverview: { ...sessionOverview, available: Boolean(recordedReplay && replayPresented && !sourceSwitchBlocked) },
}); });
@@ -687,7 +687,6 @@ export default function App() {
/> />
} }
right={ right={
<HeaderProfile>
<UserProfileMenu <UserProfileMenu
displayName="DC" displayName="DC"
subtitle="Mission Core" subtitle="Mission Core"
@@ -707,7 +706,6 @@ export default function App() {
}, },
]} ]}
/> />
</HeaderProfile>
} }
/> />
); );
@@ -738,8 +736,8 @@ export default function App() {
navigation={currentRoot && activeRoot === "system" ? ( navigation={currentRoot && activeRoot === "system" ? (
<SystemNavigationPanel <SystemNavigationPanel
title={currentRoot.title} title={currentRoot.title}
onAdd={computeContourSettings.openCreate} activeId={activeDefinition?.id ?? "workers"}
onNavigateRoot={() => openNavigationView("modules")} onNavigate={openNavigationView}
onClose={workspace.closeNavigation} onClose={workspace.closeNavigation}
/> />
) : currentRoot ? ( ) : currentRoot ? (
@@ -789,7 +787,7 @@ export default function App() {
allowFullscreen={activeDefinition.kind === "vehicles"} allowFullscreen={activeDefinition.kind === "vehicles"}
eyebrow={activeDefinition.eyebrow} eyebrow={activeDefinition.eyebrow}
title={ title={
activeDefinition.kind === "vehicles" (activeDefinition.kind === "vehicles" || activeDefinition.kind === "architectural-projects")
? <>{activeDefinition.title}<span className="fleet-header-title" ref={setWorkspaceHeaderTitleHost}/></> ? <>{activeDefinition.title}<span className="fleet-header-title" ref={setWorkspaceHeaderTitleHost}/></>
: activeDefinition.kind === "recordings" : activeDefinition.kind === "recordings"
&& replayPresented && replayPresented
@@ -836,7 +834,7 @@ export default function App() {
/> />
) : activeDefinition.kind === "missions" ? ( ) : activeDefinition.kind === "missions" ? (
<div ref={setWorkspaceHeaderToolsHost} /> <div ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.kind === "vehicles" ? <div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? <div className="ai-polygon__actions" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "datasets" ? ( ) : activeDefinition.kind === "vehicles" || activeDefinition.kind === "architectural-projects" ? <div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? <div className="ai-polygon__actions" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "datasets" ? (
<StatusBadge tone="neutral">Offline evaluation</StatusBadge> <StatusBadge tone="neutral">Offline evaluation</StatusBadge>
) : activeDefinition.kind === "lab-archive" ? ( ) : activeDefinition.kind === "lab-archive" ? (
laboratoryAnnotation.control laboratoryAnnotation.control
@@ -844,13 +842,15 @@ export default function App() {
<StatusBadge tone="neutral">Только наблюдение</StatusBadge> <StatusBadge tone="neutral">Только наблюдение</StatusBadge>
) : activeDefinition.kind === "contour-health" ? ( ) : activeDefinition.kind === "contour-health" ? (
<div ref={setWorkspaceHeaderToolsHost} /> <div ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.kind === "workers" || activeDefinition.kind === "vps" ? (
<div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.root === "system" ? ( ) : activeDefinition.root === "system" ? (
<SystemWorkspaceSelector <SystemWorkspaceSelector
value={activeDefinition.id} value={activeDefinition.id}
onChange={openNavigationView} onChange={openNavigationView}
/> />
) : ( ) : (
<StatusBadge tone="warning">Интерфейс готов</StatusBadge> <StatusBadge tone={activeDefinition.status === "active" ? "success" : "warning"}>{capabilityStatusLabel[activeDefinition.status ?? "contract"]}</StatusBadge>
) )
} }
utilityActions={contentActions} utilityActions={contentActions}
@@ -1108,7 +1108,7 @@ export default function App() {
<i className="api-dot" data-status={effectiveSourceUrl ? "online" : "checking"} aria-hidden="true" /> <i className="api-dot" data-status={effectiveSourceUrl ? "online" : "checking"} aria-hidden="true" />
{effectiveSourceUrl ? "Источник назначен" : "Источник не назначен"} {effectiveSourceUrl ? "Источник назначен" : "Источник не назначен"}
</span> </span>
<p>Структура повторяет продуктовые сущности, а не внутренние панели визуального движка.</p> <Description>Структура повторяет продуктовые сущности, а не внутренние панели визуального движка.</Description>
</div> </div>
<SceneLayerControls sceneSettings={sceneSettings} pending={runtime.pendingAction === "viewer"} applyScenePatch={applyScenePatch}/> <SceneLayerControls sceneSettings={sceneSettings} pending={runtime.pendingAction === "viewer"} applyScenePatch={applyScenePatch}/>
</Window> </Window>
@@ -1,5 +1,6 @@
import { EnvironmentSettingsWindow as SharedEnvironmentSettingsWindow } from "@nodedc/ui-react"; import { EnvironmentSettingsWindow as SharedEnvironmentSettingsWindow } from "@nodedc/ui-react";
import { environmentSurfaceIds, type EnvironmentSettings, type EnvironmentSurfaceId, type UploadedEnvironmentMedia } from "../core/environment/environmentSettings"; import { environmentSurfaceIds, type EnvironmentSettings, type EnvironmentSurfaceId, type UploadedEnvironmentMedia } from "../core/environment/environmentSettings";
import { useLabStorageSettings } from "./storage/LabStorageSettings";
import { roots, workspaces, workspacesForRoot } from "../productModel"; import { roots, workspaces, workspacesForRoot } from "../productModel";
interface Props { interface Props {
@@ -16,7 +17,8 @@ const surfaces = environmentSurfaceIds.map(id => ({
actions: id === "home" ? workspaces.filter(item => !item.internalOnly) : workspacesForRoot(id), actions: id === "home" ? workspaces.filter(item => !item.internalOnly) : workspacesForRoot(id),
})); }));
export function EnvironmentSettingsWindow(props: Props) { export function EnvironmentSettingsWindow(props: Props) {
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet" const storage = useLabStorageSettings(props.open);
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet" additionalSections={[storage]}
onSave={draft => props.onSave({ ...draft, pages: Object.fromEntries(environmentSurfaceIds.map(id => [id, draft.pages[id]])) as EnvironmentSettings["pages"] })} onSave={draft => props.onSave({ ...draft, pages: Object.fromEntries(environmentSurfaceIds.map(id => [id, draft.pages[id]])) as EnvironmentSettings["pages"] })}
onUpload={(id, itemId, file) => { onUpload={(id, itemId, file) => {
if (!environmentSurfaceIds.includes(id as EnvironmentSurfaceId)) throw new Error("Страница окружения недоступна."); if (!environmentSurfaceIds.includes(id as EnvironmentSurfaceId)) throw new Error("Страница окружения недоступна.");
@@ -1,4 +1,4 @@
import { LandingStage as SharedLandingStage, StatusBadge } from "@nodedc/ui-react"; import { Description, LandingStage as SharedLandingStage, StatusBadge } from "@nodedc/ui-react";
import type { BackendStatus, RuntimePhase } from "../core/runtime/contracts"; import type { BackendStatus, RuntimePhase } from "../core/runtime/contracts";
import type { EnvironmentPage } from "../core/environment/environmentSettings"; import type { EnvironmentPage } from "../core/environment/environmentSettings";
@@ -35,7 +35,7 @@ export function LandingStage({
<span className="section-eyebrow">ИСТОЧНИК</span> <span className="section-eyebrow">ИСТОЧНИК</span>
<StatusBadge tone={phaseTone(phase)}>{phaseLabel(phase)}</StatusBadge> <StatusBadge tone={phaseTone(phase)}>{phaseLabel(phase)}</StatusBadge>
</div> </div>
<p>{message || "Выберите архитектурный блок в верхней навигации."}</p> <Description>{message || "Выберите архитектурный блок в верхней навигации."}</Description>
</>} </>}
footer={<> footer={<>
<span>{root?.accent ?? "НАБЛЮДЕНИЕ · МИССИИ · ДАННЫЕ"}</span> <span>{root?.accent ?? "НАБЛЮДЕНИЕ · МИССИИ · ДАННЫЕ"}</span>
@@ -1,4 +1,4 @@
import { GlassSurface } from "@nodedc/ui-react"; import { Description, GlassSurface } from "@nodedc/ui-react";
export interface MetricCardProps { export interface MetricCardProps {
eyebrow: string; eyebrow: string;
@@ -16,7 +16,7 @@ export function MetricCard({ eyebrow, value, unit, detail, featured = false }: M
<strong>{value}</strong> <strong>{value}</strong>
{unit ? <span>{unit}</span> : null} {unit ? <span>{unit}</span> : null}
</div> </div>
<p>{detail}</p> <Description>{detail}</Description>
</GlassSurface> </GlassSurface>
); );
} }
@@ -1,5 +1,5 @@
import { useState } from "react"; import { useState } from "react";
import { ConfirmationModal, Dropdown, Icon } from "@nodedc/ui-react"; import { Description, ConfirmationModal, Dropdown, Icon } from "@nodedc/ui-react";
import { import {
type ObservationSessionReplayLaunch, type ObservationSessionReplayLaunch,
@@ -279,16 +279,16 @@ export function ObservationSessionSelect({
description={deleteTarget ? <> description={deleteTarget ? <>
<strong>{deleteTarget.label}</strong> <strong>{deleteTarget.label}</strong>
{deleteTarget.lab ? ( {deleteTarget.lab ? (
<p> <Description>
Будут удалены только LAB-запись из каталога и её подготовленный кэш. Будут удалены только LAB-запись из каталога и её подготовленный кэш.
Исходная запись {deleteTarget.lab.sourceSessionId} и зафиксированный Исходная запись {deleteTarget.lab.sourceSessionId} и зафиксированный
лабораторный результат останутся неизменными. лабораторный результат останутся неизменными.
</p> </Description>
) : ( ) : (
<p> <Description>
Сессия, исходные данные наблюдения, подготовленная Rerun-запись и Сессия, исходные данные наблюдения, подготовленная Rerun-запись и
видеоматериалы будут удалены с этого сервера без возможности восстановления. видеоматериалы будут удалены с этого сервера без возможности восстановления.
</p> </Description>
)} )}
{sessions.error && sessions.deletingSessionId === null ? ( {sessions.error && sessions.deletingSessionId === null ? (
<p className="observation-session-delete-error" role="alert">{sessions.error}</p> <p className="observation-session-delete-error" role="alert">{sessions.error}</p>
@@ -346,11 +346,11 @@ export function ObservationSessionArchive({
{labsOnly ? "ВОСПРОИЗВОДИМЫЕ ЛАБОРАТОРНЫЕ ЗАПИСИ" : "АРХИВ НАБЛЮДЕНИЯ"} {labsOnly ? "ВОСПРОИЗВОДИМЫЕ ЛАБОРАТОРНЫЕ ЗАПИСИ" : "АРХИВ НАБЛЮДЕНИЯ"}
</span> </span>
<h2>{labsOnly ? "Записанные лабораторные работы" : "Сохранённые сессии"}</h2> <h2>{labsOnly ? "Записанные лабораторные работы" : "Сохранённые сессии"}</h2>
<p> <Description>
{labsOnly {labsOnly
? "Каждая запись связана с LAB-конфигурацией и открывается как самостоятельный визуальный результат." ? "Каждая запись связана с LAB-конфигурацией и открывается как самостоятельный визуальный результат."
: "Выберите запись: сцена и синхронные каналы откроются ниже, не меняя эфир наблюдения."} : "Выберите запись: сцена и синхронные каналы откроются ниже, не меняя эфир наблюдения."}
</p> </Description>
</div> </div>
<button <button
type="button" type="button"
@@ -457,16 +457,16 @@ export function ObservationSessionArchive({
description={deleteTarget ? <> description={deleteTarget ? <>
<strong>{deleteTarget.label}</strong> <strong>{deleteTarget.label}</strong>
{deleteTarget.lab ? ( {deleteTarget.lab ? (
<p> <Description>
Будут удалены только LAB-запись из каталога и её подготовленный кэш. Будут удалены только LAB-запись из каталога и её подготовленный кэш.
Исходная запись {deleteTarget.lab.sourceSessionId} и зафиксированный Исходная запись {deleteTarget.lab.sourceSessionId} и зафиксированный
лабораторный результат останутся неизменными. лабораторный результат останутся неизменными.
</p> </Description>
) : ( ) : (
<p> <Description>
Сессия, исходные данные наблюдения, подготовленная Rerun-запись и Сессия, исходные данные наблюдения, подготовленная Rerun-запись и
видеоматериалы будут удалены с этого сервера без возможности восстановления. видеоматериалы будут удалены с этого сервера без возможности восстановления.
</p> </Description>
)} )}
</> : null} </> : null}
confirmLabel="Удалить сессию" confirmLabel="Удалить сессию"
@@ -2200,7 +2200,7 @@ function RerunViewportInstance({
/> />
) : null} ) : null}
{presentationStatus === "loading" ? ( {presentationStatus === "loading" ? (
<div className="rerun-viewport__notice" role="status"> <div data-glass-context="scene" className="rerun-viewport__notice nodedc-viewport-surface" role="status">
<span className="busy-indicator" aria-hidden="true" /> <span className="busy-indicator" aria-hidden="true" />
<div> <div>
<strong> <strong>
@@ -2217,7 +2217,7 @@ function RerunViewportInstance({
</div> </div>
) : null} ) : null}
{presentationStatus === "error" ? ( {presentationStatus === "error" ? (
<div className="rerun-viewport__notice rerun-viewport__notice--error" role="alert"> <div data-glass-context="scene" className="rerun-viewport__notice rerun-viewport__notice--error nodedc-viewport-surface" role="alert">
<div> <div>
<strong>Источник не открыт</strong> <strong>Источник не открыт</strong>
<span>Проверьте локальный поток Rerun или повторите подключение.</span> <span>Проверьте локальный поток Rerun или повторите подключение.</span>
@@ -11,13 +11,13 @@ export function BatteryAppearanceSettings({open,onClose,profile,sensor}:{sensor?
const {value,update}=profile,m=value.markings; const {value,update}=profile,m=value.markings;
const range=(label:string,value:number,min:number,max:number,onChange:(v:number)=>void)=><RangeControl label={label} value={value} min={min} max={max} step={1} exactValueBounds={{min,max}} onChange={onChange}/>; const range=(label:string,value:number,min:number,max:number,onChange:(v:number)=>void)=><RangeControl label={label} value={value} min={min} max={max} step={1} exactValueBounds={{min,max}} onChange={onChange}/>;
const exportJson=()=>{const url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='battery-ui.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}; const exportJson=()=>{const url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='battery-ui.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
return <FeatureSettingsWindow open={open} title="Настройки батареи" identity={{title:'Батарея',subtitle:section==='markings'||section==='panels'?'Локальный профиль':'BMS',avatarLabel:'АКБ'}} sections={[{id:'markings',label:'Маркировка ячеек',icon:'layers'},{id:'panels',label:'Дизайн',icon:'settings'},...(sensor?[{id:'diagnostics' as const,label:'Диагностика BMS',icon:'activity' as const},{id:'protection' as const,label:'Параметры BMS',icon:'sliders' as const},{id:'control' as const,label:'Управление BMS',icon:'power' as const}]:[])]} activeSection={section} onSectionChange={setSection} onClose={onClose} return <FeatureSettingsWindow open={open} title="Настройки батареи" identity={{title:'Батарея',subtitle:section==='markings'||section==='panels'?'Профиль Mission Core':'BMS',avatarLabel:'АКБ'}} sections={[{id:'markings',label:'Маркировка ячеек',icon:'layers'},{id:'panels',label:'Дизайн',icon:'settings'},...(sensor?[{id:'diagnostics' as const,label:'Диагностика BMS',icon:'activity' as const},{id:'protection' as const,label:'Параметры BMS',icon:'sliders' as const},{id:'control' as const,label:'Управление BMS',icon:'power' as const}]:[])]} activeSection={section} onSectionChange={setSection} onClose={onClose}
headerActions={(section==='markings'||section==='panels')&&<><IconButton label="Отменить настройку батареи" disabled={!profile.canUndo} onClick={profile.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить настройку батареи" disabled={!profile.canRedo} onClick={profile.redo}><Icon name="redo"/></IconButton></>} headerActions={(section==='markings'||section==='panels')&&<><IconButton label="Отменить настройку батареи" disabled={!profile.canUndo} onClick={profile.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить настройку батареи" disabled={!profile.canRedo} onClick={profile.redo}><Icon name="redo"/></IconButton></>}
footer={(section==='markings'||section==='panels')&&<><Button onClick={exportJson}>Экспорт JSON</Button><Button onClick={()=>input.current?.click()}>Импорт JSON</Button><input ref={input} type="file" accept="application/json,.json" hidden onChange={async event=>{const file=event.currentTarget.files?.[0];event.currentTarget.value='';if(!file)return;try{if(file.size>32000)throw new Error('Файл настроек слишком большой.');update(parseBatteryAppearance(JSON.parse(await file.text())));}catch(error){profile.setError(error instanceof Error?error.message:'Не удалось прочитать профиль.');}}}/></>}> footer={(section==='markings'||section==='panels')&&<><Button onClick={exportJson}>Экспорт JSON</Button><Button onClick={()=>input.current?.click()}>Импорт JSON</Button><input ref={input} type="file" accept="application/json,.json" hidden onChange={async event=>{const file=event.currentTarget.files?.[0];event.currentTarget.value='';if(!file)return;try{if(file.size>32000)throw new Error('Файл настроек слишком большой.');update(parseBatteryAppearance(JSON.parse(await file.text())));}catch(error){profile.setError(error instanceof Error?error.message:'Не удалось прочитать профиль.');}}}/></>}>
{sensor&&section!=='markings'&&section!=='panels'?<BmsSettings {...sensor} section={section} open={open}/>:section==='markings'?<SettingsCard title="Маркировка ячеек" description="Номер и напряжение на заводских площадках модели. Размер меняет надпись внутри площадки."> {sensor&&section!=='markings'&&section!=='panels'?<BmsSettings {...sensor} section={section} open={open}/>:section==='markings'?<SettingsCard title="Маркировка ячеек" description="Номер и напряжение на заводских площадках модели. Размер меняет надпись внутри площадки.">
<ControlRow label="Цвет маркировки"><ColorField label="Цвет маркировки" value={m.color} onChange={color=>update({...value,markings:{...m,color}})}/></ControlRow> <ControlRow label="Цвет маркировки"><ColorField label="Цвет маркировки" value={m.color} onChange={color=>update({...value,markings:{...m,color}})}/></ControlRow>
{range('Размер маркировки, %',m.size,50,160,size=>update({...value,markings:{...m,size}}))} {range('Размер маркировки, %',m.size,50,160,size=>update({...value,markings:{...m,size}}))}
</SettingsCard>:<BatteryDesignSettings value={value} update={update}/>} </SettingsCard>:<BatteryDesignSettings value={value} update={update}/>}
{(section==='markings'||section==='panels')&&<Description>Сохраняется на этом компьютере для этой батареи. Ctrl Z / ⌘ Z — отмена, Shift Ctrl Z / ⇧ ⌘ Z — повтор.</Description>} {(section==='markings'||section==='panels')&&<Description>Сохраняется в Mission Core для этой батареи. Ctrl Z / ⌘ Z — отмена, Shift Ctrl Z / ⇧ ⌘ Z — повтор.</Description>}
</FeatureSettingsWindow>; </FeatureSettingsWindow>;
} }
@@ -0,0 +1,2 @@
.battery-design-settings{display:grid;gap:var(--nodedc-space-4);min-width:0}
.battery-indicator-previews{display:flex;flex-wrap:wrap;align-items:center;gap:var(--nodedc-space-3)}
@@ -1,6 +1,8 @@
import {BatteryIndicator} from './BatteryIndicator';
import './BatteryDesignSettings.css';
import {useState} from 'react'; import {useState} from 'react';
import {ColorField,ControlRow,Description,LevelButton,RangeControl,Select,SettingsCard} from '@nodedc/ui-react'; import {ColorField,ControlRow,Description,RangeControl,Select,SettingsCard} from '@nodedc/ui-react';
import {batteryIndicatorColor,type BatteryAppearance} from '../../core/batteryScene/appearance'; import type {BatteryAppearance} from '../../core/batteryScene/appearance';
export function BatteryDesignSettings({value,update}:{value:BatteryAppearance;update:(value:BatteryAppearance)=>void}){ export function BatteryDesignSettings({value,update}:{value:BatteryAppearance;update:(value:BatteryAppearance)=>void}){
const [target,setTarget]=useState<'panels'|'indicator'>('panels'); const [target,setTarget]=useState<'panels'|'indicator'>('panels');
const p=value.panels,i=value.indicator; const p=value.panels,i=value.indicator;
@@ -9,7 +11,7 @@ export function BatteryDesignSettings({value,update}:{value:BatteryAppearance;up
const indicator=(patch:Partial<typeof i>)=>update({...value,indicator:{...i,...patch}}); const indicator=(patch:Partial<typeof i>)=>update({...value,indicator:{...i,...patch}});
const range=(label:string,value:number,min:number,max:number,onChange:(v:number)=>void)=><RangeControl label={label} value={value} min={min} max={max} step={1} exactValueBounds={{min,max}} onChange={onChange}/>; const range=(label:string,value:number,min:number,max:number,onChange:(v:number)=>void)=><RangeControl label={label} value={value} min={min} max={max} step={1} exactValueBounds={{min,max}} onChange={onChange}/>;
const color=(label:string,value:string,onChange:(v:string)=>void)=><ControlRow label={label}><ColorField label={label} value={value} onChange={onChange}/></ControlRow>; const color=(label:string,value:string,onChange:(v:string)=>void)=><ControlRow label={label}><ColorField label={label} value={value} onChange={onChange}/></ControlRow>;
return <><Select label="Элемент дизайна" value={target} onChange={setTarget} options={[{value:'panels',label:'Плашки показаний'},{value:'indicator',label:'Индикатор в обсерватории'}]}/> return <div className="battery-design-settings"><Select label="Элемент дизайна" value={target} onChange={setTarget} options={[{value:'panels',label:'Плашки показаний'},{value:'indicator',label:'Индикатор в обсерватории'}]}/>
{target==='panels'?<SettingsCard title="Плашки показаний" description="Общий вид верхних и нижних плашек над моделью."> {target==='panels'?<SettingsCard title="Плашки показаний" description="Общий вид верхних и нижних плашек над моделью.">
{range('Высота плашек, px',p.height,56,160,height=>panel({height}))} {range('Высота плашек, px',p.height,56,160,height=>panel({height}))}
{range('Радиус углов, px',p.radius,0,48,radius=>panel({radius}))} {range('Радиус углов, px',p.radius,0,48,radius=>panel({radius}))}
@@ -19,7 +21,11 @@ export function BatteryDesignSettings({value,update}:{value:BatteryAppearance;up
{color('Цвет стекла',p.glass.tintHex,tintHex=>glass({tintHex}))} {color('Цвет стекла',p.glass.tintHex,tintHex=>glass({tintHex}))}
{range('Прозрачность стекла, %',100-p.glass.tintOpacity,0,100,transparency=>glass({tintOpacity:100-transparency}))} {range('Прозрачность стекла, %',100-p.glass.tintOpacity,0,100,transparency=>glass({tintOpacity:100-transparency}))}
{range('Размытие стекла, px',p.glass.blur,0,60,blur=>glass({blur}))} {range('Размытие стекла, px',p.glass.blur,0,60,blur=>glass({blur}))}
</SettingsCard>:<SettingsCard title="Индикатор в обсерватории" description="Цвет заливки и диапазоны уровня заряда для этой батареи."> </SettingsCard>:<SettingsCard title="Индикатор в обсерватории" description="Размеры, цвет заливки и диапазоны уровня заряда для этой батареи.">
{range('Ширина индикатора, px',i.width,32,320,width=>indicator({width}))}
{range('Высота индикатора, px',i.height,12,96,height=>indicator({height}))}
{range('Радиус углов индикатора, px',i.radius,0,48,radius=>indicator({radius}))}
{range('Отступ от кнопок шапки влево, px',i.offset,0,320,offset=>indicator({offset}))}
<Select label="Режим цвета индикатора" value={i.mode} onChange={mode=>indicator({mode})} options={[{value:'ranges',label:'По уровню заряда'},{value:'mono',label:'Один цвет'}]}/> <Select label="Режим цвета индикатора" value={i.mode} onChange={mode=>indicator({mode})} options={[{value:'ranges',label:'По уровню заряда'},{value:'mono',label:'Один цвет'}]}/>
{i.mode==='mono'?color('Цвет индикатора',i.color,color=>indicator({color})):<> {i.mode==='mono'?color('Цвет индикатора',i.color,color=>indicator({color})):<>
{range('Низкий заряд ниже, %',i.lowUntil,0,99,lowUntil=>indicator({lowUntil,middleUntil:Math.max(i.middleUntil,lowUntil+1)}))} {range('Низкий заряд ниже, %',i.lowUntil,0,99,lowUntil=>indicator({lowUntil,middleUntil:Math.max(i.middleUntil,lowUntil+1)}))}
@@ -29,6 +35,6 @@ export function BatteryDesignSettings({value,update}:{value:BatteryAppearance;up
{color('Высокий заряд',i.highColor,highColor=>indicator({highColor}))} {color('Высокий заряд',i.highColor,highColor=>indicator({highColor}))}
</>} </>}
<Description>Чёрный или белый текст выбирается автоматически по цвету заливки. Предпросмотр:</Description> <Description>Чёрный или белый текст выбирается автоматически по цвету заливки. Предпросмотр:</Description>
<div className="observation-actions">{[10,25,80].map(soc=><LevelButton key={soc} label="Предпросмотр заряда" value={soc/100} valueText={`${soc}%`} fillColor={batteryIndicatorColor(i,soc)} disabled/>)}</div> <div className="battery-indicator-previews">{[10,25,80].map(soc=><BatteryIndicator key={soc} appearance={i} soc={soc} label="Предпросмотр заряда" valueText={`${soc}%`} disabled/>)}</div>
</SettingsCard>}</>; </SettingsCard>}</div>;
} }
@@ -0,0 +1,6 @@
import {LevelButton,type LevelButtonProps} from '@nodedc/ui-react';
import {batteryIndicatorColor,type BatteryIndicatorAppearance} from '../../core/batteryScene/appearance';
type Props=Omit<LevelButtonProps,'value'|'fillColor'>&{appearance:BatteryIndicatorAppearance;soc:number|null};
export function BatteryIndicator({appearance,soc,style,...props}:Props){
return <LevelButton {...props} value={soc===null?null:soc/100} fillColor={batteryIndicatorColor(appearance,soc)} geometry={{width:appearance.width,height:appearance.height,radius:appearance.radius}} style={style}/>;
}
@@ -5,7 +5,7 @@ import {useMemo,useState} from 'react';
import {Description} from '@nodedc/ui-react'; import {Description} from '@nodedc/ui-react';
import {SceneEditor} from '../rover/editor/RoverScene'; import {SceneEditor} from '../rover/editor/RoverScene';
import {useSceneDocument} from '../../core/roverScene/useSceneDocument'; import {useSceneDocument} from '../../core/roverScene/useSceneDocument';
import {batterySceneProfile,defaultBatteryScene} from '../../core/batteryScene/profile'; import {batterySceneProfile} from '../../core/batteryScene/profile';
export function BatteryScene({editing,soc,fresh,deviceId,seedKey,cellVoltages=[],markingAppearance}:{editing:boolean;soc:number|null;fresh:boolean;deviceId:string;seedKey?:string;cellVoltages?:readonly number[];markingAppearance:CellMarkingAppearance}){ export function BatteryScene({editing,soc,fresh,deviceId,seedKey,cellVoltages=[],markingAppearance}:{editing:boolean;soc:number|null;fresh:boolean;deviceId:string;seedKey?:string;cellVoltages?:readonly number[];markingAppearance:CellMarkingAppearance}){
const profile=useMemo(()=>batterySceneProfile(seedKey),[seedKey]); const profile=useMemo(()=>batterySceneProfile(seedKey),[seedKey]);
@@ -13,7 +13,7 @@ export function BatteryScene({editing,soc,fresh,deviceId,seedKey,cellVoltages=[]
const [api,setApi]=useState<Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0]|null>(null); const [api,setApi]=useState<Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0]|null>(null);
const [phase,setPhase]=useState<'loading'|'ready'|'error'>('loading'); const [phase,setPhase]=useState<'loading'|'ready'|'error'>('loading');
return <div className="bms-scene" data-editing={editing} aria-label="3D-модель батареи R05"> return <div className="bms-scene" data-editing={editing} aria-label="3D-модель батареи R05">
<SceneEditor scene={scene} defaults={defaultBatteryScene} editing={editing} modelUrl="/battery-scene/catl-r04.glb?objects-v6-r05" minFitDistance={.6} chargeState={{soc,fresh}} onModelState={setPhase} onSceneReady={setApi}/> <SceneEditor scene={scene} editing={editing} modelUrl="/battery-scene/catl-r04.glb?objects-v6-r05" minFitDistance={.6} chargeState={{soc,fresh}} onModelState={setPhase} onSceneReady={setApi}/>
<BatteryCellLabels api={api} ready={phase==='ready'} values={cellVoltages} appearance={markingAppearance}/> <BatteryCellLabels api={api} ready={phase==='ready'} values={cellVoltages} appearance={markingAppearance}/>
{phase!=='ready'&&<div className="bms-scene-status"><Description role="status">{phase==='error'?'Модель не загрузилась. Показания BMS доступны ниже.':'Загружается модель аккумулятора…'}</Description></div>} {phase!=='ready'&&<div className="bms-scene-status"><Description role="status">{phase==='error'?'Модель не загрузилась. Показания BMS доступны ниже.':'Загружается модель аккумулятора…'}</Description></div>}
</div>; </div>;
@@ -1,23 +1,24 @@
import {useBatteryView} from '../../core/batteryScene/useBatteryView';
import type {SensorDetailProps} from '../../../../../packages/sensor-ui/src/extensions'; import type {SensorDetailProps} from '../../../../../packages/sensor-ui/src/extensions';
import {BatteryAppearanceSettings} from './BatteryAppearanceSettings'; import {BatteryAppearanceSettings} from './BatteryAppearanceSettings';
import {useBatteryAppearance} from '../../core/batteryScene/useBatteryAppearance'; import {useBatteryAppearance} from '../../core/batteryScene/useBatteryAppearance';
import type {BatteryAppearance} from '../../core/batteryScene/appearance'; import type {BatteryAppearance} from '../../core/batteryScene/appearance';
import {useEffect,useState,type ReactNode} from 'react'; import {useEffect,useState,type ReactNode} from 'react';
import {createPortal} from 'react-dom'; import {createPortal} from 'react-dom';
import {EditorWorkspace,Icon,IconButton,ResizableViewport,ToastStack,useApplicationPanelFullscreen} from '@nodedc/ui-react'; import {EditorWorkspace,Icon,IconButton,LoadingRegion,ResizableViewport,ToastStack,useApplicationPanelFullscreen} from '@nodedc/ui-react';
import {batteryViewHeight,batteryViewHeightKey,minBatteryViewHeight,maxBatteryViewHeight} from '../../core/batteryScene/viewHeight'; import {minBatteryViewHeight,maxBatteryViewHeight} from '../../core/batteryScene/viewHeight';
export function BatteryWorkspace({children,deviceId,title,headerActionsTarget,back,sensor,fullscreenControl}:{sensor?:SensorDetailProps;fullscreenControl?:{fullscreen:boolean;setFullscreen:(value:boolean)=>void};deviceId:string;title:string;headerActionsTarget?:HTMLElement|null;back:()=>void;children:(controls:{editing:boolean;appearance:BatteryAppearance;renderViewport:(children:ReactNode)=>ReactNode})=>ReactNode}){ export function BatteryWorkspace({children,deviceId,title,headerActionsTarget,back,sensor,fullscreenControl}:{sensor?:SensorDetailProps;fullscreenControl?:{fullscreen:boolean;setFullscreen:(value:boolean)=>void};deviceId:string;title:string;headerActionsTarget?:HTMLElement|null;back:()=>void;children:(controls:{editing:boolean;appearance:BatteryAppearance;renderViewport:(children:ReactNode)=>ReactNode})=>ReactNode}){
const inheritedFull=useApplicationPanelFullscreen(),full=fullscreenControl??inheritedFull,[editing,setEditing]=useState(false),[error,setError]=useState(''),[settings,setSettings]=useState(false); const inheritedFull=useApplicationPanelFullscreen(),full=fullscreenControl??inheritedFull,[editing,setEditing]=useState(false),[error,setError]=useState(''),[settings,setSettings]=useState(false);
const profile=useBatteryAppearance(deviceId,settings); const profile=useBatteryAppearance(deviceId,settings);
const [height,setHeight]=useState(()=>{try{return batteryViewHeight(localStorage.getItem(batteryViewHeightKey(deviceId)),window.innerHeight);}catch{return batteryViewHeight(null,window.innerHeight);}}); const view=useBatteryView(deviceId);const {height,setHeight,commitHeight}=view;
const fullscreen=full?.fullscreen??false,setFullscreen=full?.setFullscreen; const fullscreen=full?.fullscreen??false,setFullscreen=full?.setFullscreen;
useEffect(()=>()=>{setFullscreen?.(false);},[setFullscreen]); useEffect(()=>()=>{setFullscreen?.(false);},[setFullscreen]);
useEffect(()=>{const escape=(event:KeyboardEvent)=>{ useEffect(()=>{const escape=(event:KeyboardEvent)=>{
if(event.key!=='Escape'||event.defaultPrevented||document.querySelector('[role=dialog],[role=listbox]'))return; if(event.key!=='Escape'||event.defaultPrevented||document.querySelector('[role=dialog],[role=listbox]'))return;
event.preventDefault();if(fullscreen)setFullscreen?.(false);else if(editing)setEditing(false);else back(); event.preventDefault();if(fullscreen)setFullscreen?.(false);else if(editing)setEditing(false);else back();
};window.addEventListener('keydown',escape);return()=>window.removeEventListener('keydown',escape);},[editing,fullscreen,setFullscreen,back]); };window.addEventListener('keydown',escape);return()=>window.removeEventListener('keydown',escape);},[editing,fullscreen,setFullscreen,back]);
const commitHeight=(value:number)=>{try{localStorage.setItem(batteryViewHeightKey(deviceId),JSON.stringify({height:value}));setError('');}catch{setError('Не удалось сохранить высоту окна на этом компьютере.');}};
const actions=<>{full&&<IconButton label={fullscreen?'Восстановить окно батареи':'Развернуть окно батареи'} onClick={()=>setFullscreen?.(!fullscreen)}><Icon name={fullscreen?'minimize':'expand'}/></IconButton>}<IconButton label={editing?'Завершить редактирование сцены':'Редактировать сцену'} aria-pressed={editing} onClick={()=>{setSettings(false);setEditing(value=>!value);}}><Icon name="edit"/></IconButton><IconButton label="Настройки батареи" aria-pressed={settings} onClick={()=>{setEditing(false);setSettings(true);}}><Icon name="settings"/></IconButton></>; const actions=<>{full&&<IconButton label={fullscreen?'Восстановить окно батареи':'Развернуть окно батареи'} onClick={()=>setFullscreen?.(!fullscreen)}><Icon name={fullscreen?'minimize':'expand'}/></IconButton>}<IconButton label={editing?'Завершить редактирование сцены':'Редактировать сцену'} aria-pressed={editing} onClick={()=>{setSettings(false);setEditing(value=>!value);}}><Icon name="edit"/></IconButton><IconButton label="Настройки батареи" aria-pressed={settings} onClick={()=>{setEditing(false);setSettings(true);}}><Icon name="settings"/></IconButton></>;
return <>{headerActionsTarget?createPortal(actions,headerActionsTarget):actions}{children({editing,appearance:profile.value,renderViewport:content=><ResizableViewport resizeIndicator={false} className="bms-stage" height={height} minHeight={minBatteryViewHeight} maxHeight={maxBatteryViewHeight} onHeightChange={setHeight} onHeightCommit={commitHeight}><EditorWorkspace editing={editing} title={title} subtitle="Редактирование сцены аккумулятора" onBack={()=>setEditing(false)}><div className="bms-stage bms-editor-content">{content}</div></EditorWorkspace></ResizableViewport>})}<BatteryAppearanceSettings open={settings} onClose={()=>setSettings(false)} profile={profile} sensor={sensor}/><ToastStack items={(error||profile.error)?[{id:'battery-view-save',title:error||profile.error,tone:'error'}]:[]} onDismiss={()=>{setError('');profile.setError('');}}/></>; return <>{headerActionsTarget?createPortal(actions,headerActionsTarget):actions}<LoadingRegion loading={!profile.ready||!view.ready} label="Загрузка настроек батареи">{profile.ready&&view.ready&&children({editing,appearance:profile.value,renderViewport:content=><ResizableViewport resizeIndicator={false} className="bms-stage" height={height} minHeight={minBatteryViewHeight} maxHeight={maxBatteryViewHeight} onHeightChange={setHeight} onHeightCommit={commitHeight}><EditorWorkspace editing={editing} title={title} subtitle="Редактирование сцены аккумулятора" onBack={()=>setEditing(false)}><div className="bms-stage bms-editor-content">{content}</div></EditorWorkspace></ResizableViewport>})}</LoadingRegion><BatteryAppearanceSettings open={settings} onClose={()=>setSettings(false)} profile={profile} sensor={sensor}/><ToastStack items={(error||profile.error||view.error)?[{id:'battery-view-save',title:error||profile.error||view.error,tone:'error'}]:[]} onDismiss={()=>{setError('');profile.setError('');view.setError('');}}/></>;
} }
@@ -6,7 +6,6 @@ import {
useState, useState,
} from "react"; } from "react";
import { import {
ActivityIndicator,
Button, Button,
Checker, Checker,
ControlRow, ControlRow,
@@ -35,7 +34,9 @@ import {
import type { CanonicalLabReplayDescriptor } from "../../core/laboratory/canonicalLabReplay"; import type { CanonicalLabReplayDescriptor } from "../../core/laboratory/canonicalLabReplay";
import type { ObservationSessionReplayLaunch } from "../../core/observation/sessionArchive"; import type { ObservationSessionReplayLaunch } from "../../core/observation/sessionArchive";
import { laboratoryResultRerunProfile } from "../../core/observation/viewerProfile"; import { laboratoryResultRerunProfile } from "../../core/observation/viewerProfile";
import { resolveObservationSessionReplay } from "../../core/observation/useObservationSessions"; import { prepareLabReplay, type LabReplayProgress as Progress } from "../../core/laboratory/prepareLabReplay";
import { LabReplayProgress } from "./LabReplayProgress";
import { announceLabStorageChange } from "../../core/storage/localLabStorage";
import type { AIViewerLayer } from "../../core/observatory/aiComposition"; import type { AIViewerLayer } from "../../core/observatory/aiComposition";
import { import {
fetchLabViewProfile, fetchLabViewProfile,
@@ -216,6 +217,7 @@ export function CanonicalResultRerunReplay({
const [viewerStatus, setViewerStatus] = useState<RerunViewportStatus>("idle"); const [viewerStatus, setViewerStatus] = useState<RerunViewportStatus>("idle");
const [launch, setLaunch] = useState<CanonicalReplayLaunch | null>(null); const [launch, setLaunch] = useState<CanonicalReplayLaunch | null>(null);
const [launchError, setLaunchError] = useState<string | null>(null); const [launchError, setLaunchError] = useState<string | null>(null);
const [preparationProgress, setPreparationProgress] = useState<Progress>({ phase: "checking", fraction: null });
const sceneDraftRef = useRef(sceneDraft); const sceneDraftRef = useRef(sceneDraft);
const previousSplitViewRef = useRef(splitView); const previousSplitViewRef = useRef(splitView);
const trackedLaunchSha256Ref = useRef<string | null>(null); const trackedLaunchSha256Ref = useRef<string | null>(null);
@@ -275,15 +277,10 @@ export function CanonicalResultRerunReplay({
setPlayback(null); setPlayback(null);
setPlaybackController(null); setPlaybackController(null);
setViewerStatus("idle"); setViewerStatus("idle");
void resolveObservationSessionReplay(sessionId, { void prepareLabReplay(resultId, sessionId, resolveReplay, {
signal: controller.signal, signal: controller.signal, onProgress: setPreparationProgress,
maximumWaitMs: 30 * 60 * 1000, }).then((value) => {
onUpdate: () => undefined, if (!controller.signal.aborted) { setLaunch(value); announceLabStorageChange(); }
}).then(async (value) => ({
base: value,
replay: await resolveReplay(resultId, value, { signal: controller.signal }),
})).then((value) => {
if (!controller.signal.aborted) setLaunch(value);
}).catch((caught: unknown) => { }).catch((caught: unknown) => {
if (!controller.signal.aborted) { if (!controller.signal.aborted) {
setLaunchError(caught instanceof Error ? caught.message : "Сохранённая запись недоступна."); setLaunchError(caught instanceof Error ? caught.message : "Сохранённая запись недоступна.");
@@ -465,7 +462,9 @@ export function CanonicalResultRerunReplay({
emptyMessage="Слои результата недоступны." emptyMessage="Слои результата недоступны."
deckOverlays={presentationState === "loading" ? ( deckOverlays={presentationState === "loading" ? (
<div className="canonical-vegetation-rerun-replay__loading"> <div className="canonical-vegetation-rerun-replay__loading">
<ActivityIndicator label="Загружаем синхронизированную запись" /> <LabReplayProgress progress={launch
? { phase: "opening", fraction: playback?.bufferProgress ?? null }
: preparationProgress} />
</div> </div>
) : undefined} ) : undefined}
transport={transport} transport={transport}
@@ -0,0 +1,10 @@
import { Description, ProgressBar } from "@nodedc/ui-react";
import { labReplayProgressView, type LabReplayProgress as Progress } from "../../core/laboratory/prepareLabReplay";
export function LabReplayProgress({ progress }: { progress: Progress }) {
const view = labReplayProgressView(progress);
return <div className="lab-replay-progress" aria-busy="true">
<Description role="status" aria-live="polite">{view.text}</Description>
<ProgressBar label={view.label} value={view.value} valueText={view.text} />
</div>;
}
@@ -1,3 +1,4 @@
import { Description } from '@nodedc/ui-react';
import { import {
forwardRef, forwardRef,
type CSSProperties, type CSSProperties,
@@ -915,7 +916,7 @@ LaboratoryMetricEvidenceSceneHandle,
return ( return (
<div className="laboratory-metric-evidence-scene"> <div className="laboratory-metric-evidence-scene">
<div ref={hostRef} className="laboratory-metric-evidence-scene__viewport"> <div ref={hostRef} className="laboratory-metric-evidence-scene__viewport">
{renderError ? <p>{renderError}</p> : null} {renderError ? <Description>{renderError}</Description> : null}
</div> </div>
<div className="laboratory-metric-evidence-scene__legend"> <div className="laboratory-metric-evidence-scene__legend">
{showRenderStats && renderStats ? ( {showRenderStats && renderStats ? (
@@ -1,5 +1,5 @@
import { useId, useState, type ReactNode } from "react"; import { useId, useState, type ReactNode } from "react";
import { Icon, IconButton, Select, StatusBadge } from "@nodedc/ui-react"; import { Description, Icon, IconButton, Select, StatusBadge } from "@nodedc/ui-react";
export interface LaboratoryOption<T extends string> { export interface LaboratoryOption<T extends string> {
id: T; id: T;
@@ -91,7 +91,7 @@ export function LaboratorySelector<T extends string>({
<div> <div>
<span className="section-eyebrow">{eyebrow}</span> <span className="section-eyebrow">{eyebrow}</span>
<h2>{title}</h2> <h2>{title}</h2>
<p>{description}</p> <Description>{description}</Description>
</div> </div>
<div className="laboratory-selector__control"> <div className="laboratory-selector__control">
<span>{label}</span> <span>{label}</span>
@@ -1,4 +1,4 @@
import { GlassSurface } from "@nodedc/ui-react"; import { Description, GlassSurface } from "@nodedc/ui-react";
import { CanonicalResultRerunReplay } from "./CanonicalResultRerunReplay"; import { CanonicalResultRerunReplay } from "./CanonicalResultRerunReplay";
import { resolveCanonicalLabReplay } from "../../core/laboratory/canonicalLabReplay"; import { resolveCanonicalLabReplay } from "../../core/laboratory/canonicalLabReplay";
import type { ObservatoryPortableResultReview } from "../../core/observatory/recordedRun"; import type { ObservatoryPortableResultReview } from "../../core/observatory/recordedRun";
@@ -38,7 +38,7 @@ export function PortableResultReplay({
&& (moduleId === "rf-detr" || moduleId === "object-distance"); && (moduleId === "rf-detr" || moduleId === "object-distance");
if (!tgs && !semantics && !objects) return ( if (!tgs && !semantics && !objects) return (
<GlassSurface className="observatory-replay-state" padding="lg"> <GlassSurface className="observatory-replay-state" padding="lg">
<p role="alert">Сохранённый результат этого профиля пока не поддерживает визуальный разбор.</p> <Description role="alert">Сохранённый результат этого профиля пока не поддерживает визуальный разбор.</Description>
</GlassSurface> </GlassSurface>
); );
return <CanonicalResultRerunReplay key={review.resultId} resultId={review.resultId} return <CanonicalResultRerunReplay key={review.resultId} resultId={review.resultId}
@@ -1,20 +1,20 @@
import { Button, LoadingRegion, Window } from "@nodedc/ui-react"; import { Description, Button, LoadingRegion, Window } from "@nodedc/ui-react";
import type { RouteCheck } from "../../core/missions/planner"; import type { RouteCheck } from "../../core/missions/planner";
export function MissionCheckWindow({ open, onClose, busy, error, report, run }: { export function MissionCheckWindow({ open, onClose, busy, error, report, run }: {
open: boolean; onClose: () => void; busy: boolean; error: string | null; report: RouteCheck | null; run: () => void; open: boolean; onClose: () => void; busy: boolean; error: string | null; report: RouteCheck | null; run: () => void;
}) { }) {
return <Window open={open} title="Проверка маршрута" size="md" onClose={onClose}><div className="mission-planner__check"> return <Window open={open} title="Проверка маршрута" size="md" onClose={onClose}><div className="mission-planner__check">
<p>Проверка сохранённой записи и выбранного участка. Новый проход со сканером для этой проверки не требуется.</p> <Description>Проверка сохранённой записи и выбранного участка. Новый проход со сканером для этой проверки не требуется.</Description>
<LoadingRegion loading={busy} label="Проверка исходных данных"> <LoadingRegion loading={busy} label="Проверка исходных данных">
{error && <p role="alert">{error}</p>} {error && <Description role="alert">{error}</Description>}
{report && <><dl> {report && <><dl>
<div><dt>Исходная запись</dt><dd>{report.source_verified ? "Контрольные суммы совпадают" : "Недоступна"}</dd></div> <div><dt>Исходная запись</dt><dd>{report.source_verified ? "Контрольные суммы совпадают" : "Недоступна"}</dd></div>
<div><dt>Версия черновика</dt><dd>{report.revision}</dd></div> <div><dt>Версия черновика</dt><dd>{report.revision}</dd></div>
<div><dt>Длина маршрута</dt><dd>{report.length_m.toFixed(2)} м</dd></div> <div><dt>Длина маршрута</dt><dd>{report.length_m.toFixed(2)} м</dd></div>
<div><dt>Положения сканера</dt><dd>{report.pose_count.toLocaleString("ru-RU")}</dd></div> <div><dt>Положения сканера</dt><dd>{report.pose_count.toLocaleString("ru-RU")}</dd></div>
<div><dt>Максимальный шаг</dt><dd>{report.max_step_m.toFixed(2)} м</dd></div></dl> <div><dt>Максимальный шаг</dt><dd>{report.max_step_m.toFixed(2)} м</dd></div></dl>
{report.warnings.map(w => <p key={w}>{w}</p>)} {report.warnings.map(w => <Description key={w}>{w}</Description>)}
<p>Совмещение с повторным проходом не выполнялось. Записанная траектория описывает движение сканера; проходимость для аппарата по ней не проверена.</p></>} <Description>Совмещение с повторным проходом не выполнялось. Записанная траектория описывает движение сканера; проходимость для аппарата по ней не проверена.</Description></>}
<Button disabled={busy} onClick={run}>{report ? "Повторить проверку" : "Начать проверку"}</Button> <Button disabled={busy} onClick={run}>{report ? "Повторить проверку" : "Начать проверку"}</Button>
</LoadingRegion> </LoadingRegion>
</div></Window>; </div></Window>;
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { RangeControl } from "@nodedc/ui-react"; import { Description, RangeControl } from "@nodedc/ui-react";
import { routeLength, type PlanningPose, type PlanningSource } from "../../core/missions/planner"; import { routeLength, type PlanningPose, type PlanningSource } from "../../core/missions/planner";
/** Equal-axis plan projection; the moving marker is an archive pose, not localization. */ /** Equal-axis plan projection; the moving marker is an archive pose, not localization. */
export function MissionRoutePreview({ source, poses }: { source: PlanningSource; poses: PlanningPose[] }) { export function MissionRoutePreview({ source, poses }: { source: PlanningSource; poses: PlanningPose[] }) {
@@ -22,8 +22,8 @@ export function MissionRoutePreview({ source, poses }: { source: PlanningSource;
<polyline points={projection.selected} className="mission-route-preview__selected" fill="none" /> <polyline points={projection.selected} className="mission-route-preview__selected" fill="none" />
<circle cx={x} cy={y} r="6" className="mission-route-preview__cursor" /> <circle cx={x} cy={y} r="6" className="mission-route-preview__cursor" />
<path d="M40 450h100" className="mission-route-preview__selected" /><text x="40" y="438">{(100 / projection.scale).toFixed(1)} м</text> <path d="M40 450h100" className="mission-route-preview__selected" /><text x="40" y="438">{(100 / projection.scale).toFixed(1)} м</text>
</svg><p>Путь: {routeLength(poses).toFixed(2)} м · {poses.length.toLocaleString("ru-RU")} положений · X/Y, масштаб осей одинаковый</p> </svg><Description>Путь: {routeLength(poses).toFixed(2)} м · {poses.length.toLocaleString("ru-RU")} положений · X/Y, масштаб осей одинаковый</Description>
<RangeControl label="Положение на маршруте" value={Math.min(cursor, poses.length - 1) + 1} min={1} max={poses.length} step={1} formatValue={n => `${n} / ${poses.length}`} onChange={n => setCursor(n - 1)} /> <RangeControl label="Положение на маршруте" value={Math.min(cursor, poses.length - 1) + 1} min={1} max={poses.length} step={1} formatValue={n => `${n} / ${poses.length}`} onChange={n => setCursor(n - 1)} />
<p>Кадр {point.index + 1} · X {point.position[0].toFixed(2)} · Y {point.position[1].toFixed(2)} · Z {point.position[2].toFixed(2)} м</p> <Description>Кадр {point.index + 1} · X {point.position[0].toFixed(2)} · Y {point.position[1].toFixed(2)} · Z {point.position[2].toFixed(2)} м</Description>
</div>; </div>;
} }
@@ -1,5 +1,5 @@
import type {ReactNode} from 'react'; import type {ReactNode} from 'react';
import {Button, StatusBadge} from '@nodedc/ui-react'; import { Description,Button, StatusBadge} from '@nodedc/ui-react';
import {planningAwaitsCapture, usePlanningTest} from '../../core/missions/PlanningTestContext'; import {planningAwaitsCapture, usePlanningTest} from '../../core/missions/PlanningTestContext';
/** Composition-level handoff; never sends a device or acquisition command. */ /** Composition-level handoff; never sends a device or acquisition command. */
@@ -12,9 +12,9 @@ export function PlanningCaptureGuard({enabled, onResume, children}: {
if (!enabled || !planningAwaitsCapture(planning.test)) return <>{children}</>; if (!enabled || !planningAwaitsCapture(planning.test)) return <>{children}</>;
return <div className="mission-planner__check"> return <div className="mission-planner__check">
<StatusBadge tone="warning">Исследование ожидает новую запись</StatusBadge> <StatusBadge tone="warning">Исследование ожидает новую запись</StatusBadge>
<p>{planning.test!.draft.name}</p> <Description>{planning.test!.draft.name}</Description>
<p>Для самостоятельной съёмки завершите подготовленное исследование. Запись и подключение сканера не будут остановлены.</p> <Description>Для самостоятельной съёмки завершите подготовленное исследование. Запись и подключение сканера не будут остановлены.</Description>
{planning.error && <p role="alert">{planning.error}</p>} {planning.error && <Description role="alert">{planning.error}</Description>}
<div className="mission-planner__actions"> <div className="mission-planner__actions">
<Button loading={planning.busy} onClick={() => void planning.finish()}>Завершить исследование</Button> <Button loading={planning.busy} onClick={() => void planning.finish()}>Завершить исследование</Button>
<Button disabled={planning.busy} onClick={onResume}>Вернуться к исследованию</Button> <Button disabled={planning.busy} onClick={onResume}>Вернуться к исследованию</Button>
@@ -1,5 +1,5 @@
import {useEffect,useState,type ReactNode} from 'react'; import {useEffect,useState,type ReactNode} from 'react';
import {Button,LoadingRegion,StatusBadge,Window} from '@nodedc/ui-react'; import { Description,Button,LoadingRegion,StatusBadge,Window} from '@nodedc/ui-react';
import {useDevicePluginHost} from '../../core/device-plugins/DevicePluginHost'; import {useDevicePluginHost} from '../../core/device-plugins/DevicePluginHost';
import {planningTestTerminal,usePlanningTest} from '../../core/missions/PlanningTestContext'; import {planningTestTerminal,usePlanningTest} from '../../core/missions/PlanningTestContext';
@@ -15,17 +15,17 @@ export function PlanningConnectionWindow({children}:{children:ReactNode}){
if(!p.test)return <>{children}</>; if(!p.test)return <>{children}</>;
const t=p.test, terminal=planningTestTerminal(t); const t=p.test, terminal=planningTestTerminal(t);
const details=<><StatusBadge tone="neutral">Профиль · Планирование</StatusBadge> const details=<><StatusBadge tone="neutral">Профиль · Планирование</StatusBadge>
<p>{t.draft.name} · эталон {t.draft.zone.label} · {t.draft.route.length_m.toFixed(1)} м</p> <Description>{t.draft.name} · эталон {t.draft.zone.label} · {t.draft.route.length_m.toFixed(1)} м</Description>
<p>Укажите новое имя проекта сканера. Неподвижная калибровка просматривает весь выбранный маршрут; после калибровки сканера оставайтесь на месте до статуса «Сопровождение». Если совпадение не найдено или неоднозначно, сцена сообщит причину и не начнёт сопровождение.</p></>; <Description>Укажите новое имя проекта сканера. Неподвижная калибровка просматривает весь выбранный маршрут; после калибровки сканера оставайтесь на месте до статуса «Сопровождение». Если совпадение не найдено или неоднозначно, сцена сообщит причину и не начнёт сопровождение.</Description></>;
return <div className="mission-planner__check"> return <div className="mission-planner__check">
{details}<p>{t.message}</p>{p.error&&<p role="alert">{p.error}</p>} {details}<Description>{t.message}</Description>{p.error&&<Description role="alert">{p.error}</Description>}
<div className="mission-planner__actions"><Button onClick={()=>setOpen(true)}>Подключение сканера</Button> <div className="mission-planner__actions"><Button onClick={()=>setOpen(true)}>Подключение сканера</Button>
{t.state==='running'&&t.planning_phase==='lost'&&!t.tracking_established&&<Button loading={p.busy} onClick={()=>void p.retryInitialization()}>Переинициализировать</Button>} {t.state==='running'&&t.planning_phase==='lost'&&!t.tracking_established&&<Button loading={p.busy} onClick={()=>void p.retryInitialization()}>Переинициализировать</Button>}
{!terminal&&<Button loading={p.busy} onClick={()=>void p.finish()}>Завершить исследование</Button>}</div> {!terminal&&<Button loading={p.busy} onClick={()=>void p.finish()}>Завершить исследование</Button>}</div>
<Window open={open} title="Подключение сканера · Планирование" size="lg" className="planning-connection" onClose={()=>setOpen(false)}> <Window open={open} title="Подключение сканера · Планирование" size="lg" className="planning-connection" onClose={()=>setOpen(false)}>
<div className="mission-planner__check">{details} <div className="mission-planner__check">{details}
{t.state==='preparing'?<LoadingRegion loading label="Подготовка эталонного участка" /> {t.state==='preparing'?<LoadingRegion loading label="Подготовка эталонного участка" />
: terminal?<p>{t.message}</p>:children} : terminal?<Description>{t.message}</Description>:children}
</div> </div>
</Window> </Window>
</div>; </div>;
@@ -1,11 +1,11 @@
import { Inspector, Icon, StatusBadge } from '@nodedc/ui-react'; import { Description, Inspector, Icon, StatusBadge } from '@nodedc/ui-react';
import { planningProjectStatus, type PlanningProjectDetail } from '../../core/missions/planningProjects'; import { planningProjectStatus, type PlanningProjectDetail } from '../../core/missions/planningProjects';
export function PlanningProjectResult({project:p}:{project:PlanningProjectDetail}) { export function PlanningProjectResult({project:p}:{project:PlanningProjectDetail}) {
const r=p.result; const r=p.result;
return <Inspector variant="panel" defaultOpen={['sources','result']} sections={[ return <Inspector variant="panel" defaultOpen={['sources','result']} sections={[
{id:'sources',label:'Проект',icon:<Icon name="file"/>,content:<div className="inspector-control-stack"> {id:'sources',label:'Проект',icon:<Icon name="file"/>,content:<div className="inspector-control-stack">
<p>{p.name}</p><small>{new Date(p.created_at_utc).toLocaleString('ru-RU')}</small> <Description>{p.name}</Description><small>{new Date(p.created_at_utc).toLocaleString('ru-RU')}</small>
<dl><div><dt>Эталон</dt><dd>{p.reference_label}</dd></div><div><dt>Повторный проход</dt><dd>{p.query_label??'—'}</dd></div> <dl><div><dt>Эталон</dt><dd>{p.reference_label}</dd></div><div><dt>Повторный проход</dt><dd>{p.query_label??'—'}</dd></div>
<div><dt>Участок эталона</dt><dd>{p.draft.route.length_m.toFixed(2)} м</dd></div></dl> <div><dt>Участок эталона</dt><dd>{p.draft.route.length_m.toFixed(2)} м</dd></div></dl>
</div>}, </div>},
@@ -15,7 +15,7 @@ export function PlanningProjectResult({project:p}:{project:PlanningProjectDetail
<div><dt>Расхождение поверхностей</dt><dd>{r.inlier_rmse_m==null?'—':`${r.inlier_rmse_m.toFixed(3)} м`}</dd></div> <div><dt>Расхождение поверхностей</dt><dd>{r.inlier_rmse_m==null?'—':`${r.inlier_rmse_m.toFixed(3)} м`}</dd></div>
{r.correction_m!=null&&<div><dt>Уточнение привязки</dt><dd>{r.correction_m.toFixed(2)} м · {r.correction_deg.toFixed(1)}°</dd></div>} {r.correction_m!=null&&<div><dt>Уточнение привязки</dt><dd>{r.correction_m.toFixed(2)} м · {r.correction_deg.toFixed(1)}°</dd></div>}
{r.registration_seconds!=null&&<div><dt>Расчёт</dt><dd>{r.registration_seconds.toFixed(2)} с</dd></div>} {r.registration_seconds!=null&&<div><dt>Расчёт</dt><dd>{r.registration_seconds.toFixed(2)} с</dd></div>}
</dl><small>Совпадение поверхностей не является измеренной точностью положения.</small></>:<p>{p.message?`Сохранённое сообщение: ${p.message}`:'Расчёт совмещения ещё не выполнен.'}</p>} </dl><small>Совпадение поверхностей не является измеренной точностью положения.</small></>:<Description>{p.message?`Сохранённое сообщение: ${p.message}`:'Расчёт совмещения ещё не выполнен.'}</Description>}
{p.evidence_relation==='same_recording'&&<small>Оба участка из одной записи: внутренняя проверка общей карты.</small>} {p.evidence_relation==='same_recording'&&<small>Оба участка из одной записи: внутренняя проверка общей карты.</small>}
{p.scene_note&&p.scene_url&&<small>{p.scene_note}</small>} {p.scene_note&&p.scene_url&&<small>{p.scene_note}</small>}
{r?.reasons.map(reason=><small key={reason}>{reason}</small>)} {r?.reasons.map(reason=><small key={reason}>{reason}</small>)}
@@ -1,5 +1,5 @@
import { useState } from 'react'; import { useState } from 'react';
import { ConfirmationModal, Icon, Select, ToastStack } from '@nodedc/ui-react'; import { Description, ConfirmationModal, Icon, Select, ToastStack } from '@nodedc/ui-react';
import { planningProjectDeletable, planningProjectStatus, type PlanningProject } from '../../core/missions/planningProjects'; import { planningProjectDeletable, planningProjectStatus, type PlanningProject } from '../../core/missions/planningProjects';
export function PlanningProjectSelect({items, value, disabled, onChange, onRemove}: { export function PlanningProjectSelect({items, value, disabled, onChange, onRemove}: {
@@ -29,8 +29,8 @@ export function PlanningProjectSelect({items, value, disabled, onChange, onRemov
<ConfirmationModal open={target !== null} title="Удалить совмещённый маршрут?" <ConfirmationModal open={target !== null} title="Удалить совмещённый маршрут?"
description={target ? <> description={target ? <>
<strong>{target.name}</strong> <strong>{target.name}</strong>
<p>{new Date(target.created_at_utc).toLocaleString('ru-RU')} · {planningProjectStatus(target)}</p> <Description>{new Date(target.created_at_utc).toLocaleString('ru-RU')} · {planningProjectStatus(target)}</Description>
<p>Проект будет удалён из списка совмещённых маршрутов. Эталон, запись прохода и сохранённые отчёты останутся на диске. Другие проекты не изменятся.</p> <Description>Проект будет удалён из списка совмещённых маршрутов. Эталон, запись прохода и сохранённые отчёты останутся на диске. Другие проекты не изменятся.</Description>
</> : null} </> : null}
confirmLabel="Удалить маршрут" pendingLabel="Удаление…" danger confirmLabel="Удалить маршрут" pendingLabel="Удаление…" danger
onClose={() => { if (!busy) setTarget(null); }} onClose={() => { if (!busy) setTarget(null); }}
@@ -1,4 +1,4 @@
import { Button, Icon, Inspector, InspectorSelectField, TextField } from '@nodedc/ui-react'; import { Description, Button, Icon, Inspector, InspectorSelectField, TextField } from '@nodedc/ui-react';
import { routeLength, canStartPlanningRoute } from '../../core/missions/planner'; import { routeLength, canStartPlanningRoute } from '../../core/missions/planner';
import type { useMissionPlanner } from '../../core/missions/useMissionPlanner'; import type { useMissionPlanner } from '../../core/missions/useMissionPlanner';
@@ -24,7 +24,7 @@ export function PlanningProjectSettings({p,onStart,starting}:{
<div className="inspector-control-stack"> <div className="inspector-control-stack">
{p.source&&!routeReady&&<small>В записи недостаточно перемещения для привязки. Выберите другой эталон.</small>} {p.source&&!routeReady&&<small>В записи недостаточно перемещения для привязки. Выберите другой эталон.</small>}
<Button variant="primary" loading={starting} disabled={disabled||!p.ready||!routeReady} onClick={onStart}><Icon name="play"/>Начать новый проход</Button> <Button variant="primary" loading={starting} disabled={disabled||!p.ready||!routeReady} onClick={onStart}><Icon name="play"/>Начать новый проход</Button>
{p.error&&<p role="alert">{p.error}</p>} {p.error&&<Description role="alert">{p.error}</Description>}
</div> </div>
</>; </>;
} }
@@ -2,10 +2,10 @@ import {Fragment,useEffect,useState} from 'react';
import {Button,Icon,SettingsCard} from '@nodedc/ui-react'; import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]}; type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]};
export function InstallerCard({kind}:{kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'}){ export function InstallerCard({kind,connectionInstruction}:{connectionInstruction?:string;kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'|'vps-librespeed'}){
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false); const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]); useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((step,index)=><Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>)}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}> return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((original,index)=>{const step=connectionInstruction&&index===item.instructions.length-1?connectionInstruction:original;return <Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>;})}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
<Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button> <Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button>
</SettingsCard>; </SettingsCard>;
} }
@@ -0,0 +1,47 @@
import {useEffect,useRef,useState} from 'react';
import {Description,Icon} from '@nodedc/ui-react';
import type {SpeedMeasurement} from '../../../../../packages/router-ui/src/contracts';
import {speedFraction,speedPoint,speedTrack,speedValues} from './speedGauge';
import './routerSpeedGauge.css';
function useMarker(target:number){
const [position,setPosition]=useState(target),last=useRef(target);
useEffect(()=>{
if(window.matchMedia('(prefers-reduced-motion: reduce)').matches){last.current=target;setPosition(target);return;}
const start=performance.now(),from=last.current;let frame=0;
function animate(now:number){const t=Math.min(1,(now-start)/650),next=from+(target-from)*(1-Math.pow(1-t,3));last.current=next;setPosition(next);if(t<1)frame=requestAnimationFrame(animate);}
frame=requestAnimationFrame(animate);return()=>cancelAnimationFrame(frame);
},[target]);
return position;
}
const format=(n:number|null)=>n===null?'—':new Intl.NumberFormat('ru-RU',{maximumFractionDigits:1}).format(n/1e6);
export function RouterSpeedGauge({measurement,waiting,fresh}:{measurement?:SpeedMeasurement;waiting:boolean;fresh:boolean}){
const {down,up}=speedValues(measurement),phase=measurement?.phase;
const running=phase==='download'||phase==='upload';
const [clock,setClock]=useState(Date.now());
useEffect(()=>{if(!running)return;const timer=setInterval(()=>setClock(Date.now()),1000);return()=>clearInterval(timer);},[running]);
const stale=running&&(!fresh||!!measurement?.sampled_at&&clock-measurement.sampled_at>6000);
const ceiling=Math.max(down??0,up??0)>1e9?1e10:1e9;
const active=phase==='upload'?up:down;
const marker=speedPoint(useMarker(speedFraction(active??0,ceiling)));
const secondary=speedPoint(speedFraction(up??0,ceiling));
const state=waiting?'Подготовка замера':stale?'Ожидаем данные борта':phase==='latency'?'Проверяем задержку':phase==='download'?'Измеряем приём':phase==='upload'?'Измеряем передачу':phase==='complete'?'Замер завершён':phase==='cancelled'?'Замер остановлен':phase==='error'?'Замер не завершён':'Готов к замеру';
const caption=phase==='download'||phase==='upload'?'Текущая средняя · Мбит/с':'Мбит/с';
return <div className="router-speed-visual"><div className="router-speed-state"><Description role="status">{state}</Description></div><figure className="router-speed-gauge" aria-label={`Скорость соединения. ${state}. Приём ${format(down)}, передача ${format(up)} Мбит/с.`}>
<svg viewBox="0 0 720 280" aria-hidden="true" className={stale?'router-speed-instrument is-stale':'router-speed-instrument'}>
<path d={speedTrack} className="router-speed-track"/>
{Array.from({length:121},(_,i)=>{const p=speedPoint(i/120),lit=active!==null&&i/120<=speedFraction(active,ceiling);return <line key={i} x1={p.x} y1={p.y} x2={p.x+p.nx*12} y2={p.y+p.ny*12} className={lit?'router-speed-tick is-lit':'router-speed-tick'}/>;})}
{[0,10,100,1000].map(n=>{const p=speedPoint(speedFraction(n*1e6*(ceiling/1e9),ceiling));return <line key={n} x1={p.x} y1={p.y} x2={p.x+p.nx*22} y2={p.y+p.ny*22} className="router-speed-major"/>;})}
{active!==null&&<g className="router-speed-marker"><circle cx={marker.x} cy={marker.y} r="11" className="router-speed-halo"/><circle cx={marker.x} cy={marker.y} r="4"/></g>}
{phase==='complete'&&up!==null&&<circle cx={secondary.x} cy={secondary.y} r="5" className="router-speed-upload-marker"/>}
</svg>
{[0,10,100,1000].map(n=>{const p=speedPoint(speedFraction(n*1e6*(ceiling/1e9),ceiling));return <span key={n} className="router-speed-scale" style={{left:`${(p.x-p.nx*22)/720*100}%`,top:`${(p.y-p.ny*22)/280*100}%`}}>{n*(ceiling/1e9)}</span>;})}
<figcaption className="router-speed-center">
<div className="router-speed-readings">
<div data-active={phase==='download'}><span><Icon name="download"/> Приём</span><strong>{format(down)}</strong></div>
<div data-active={phase==='upload'}><span><Icon name="upload"/> Передача</span><strong>{format(up)}</strong></div>
</div>
<Description>{caption}</Description>
</figcaption>
</figure></div>;
}
@@ -0,0 +1,20 @@
.router-speed-visual{margin:8px 0}.router-speed-state{text-align:center}
.router-speed-gauge{position:relative;width:100%;max-width:600px;aspect-ratio:18/7;margin:0 auto;isolation:isolate;color:var(--nodedc-text-primary)}
.router-speed-instrument{display:block;width:100%;height:100%;overflow:visible}
.router-speed-track{fill:none;stroke:currentColor;stroke-width:1;opacity:.06}
.router-speed-tick{stroke:currentColor;stroke-width:1.4;stroke-linecap:round;opacity:.18;transition:opacity 450ms ease}
.router-speed-tick.is-lit{opacity:.8}
.router-speed-major{stroke:currentColor;stroke-width:1.5;stroke-linecap:round;opacity:.5}
.router-speed-marker{fill:currentColor}
.router-speed-halo{opacity:.1}
.router-speed-upload-marker{fill:none;stroke:var(--nodedc-text-muted);stroke-width:2}
.router-speed-instrument.is-stale{opacity:.45}
.router-speed-scale{position:absolute;transform:translate(-50%,-50%);font-size:var(--nodedc-font-size-sm);color:var(--nodedc-text-muted);font-variant-numeric:tabular-nums}
.router-speed-center{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:52%;display:grid;gap:12px;text-align:center}
.router-speed-readings{display:grid;grid-template-columns:1fr 1fr;gap:16px}
.router-speed-readings>div{display:grid;gap:8px}
.router-speed-readings span{display:flex;align-items:center;justify-content:center;gap:6px;color:var(--nodedc-text-muted);font-size:var(--nodedc-font-size-sm)}
.router-speed-readings strong{font-size:var(--nodedc-font-size-md);font-weight:600;font-variant-numeric:tabular-nums}
.router-speed-readings [data-active=true] span{color:var(--nodedc-text-primary)}
@media(max-width:600px){.router-speed-gauge{margin:8px auto}.router-speed-center{gap:6px;width:58%}.router-speed-readings{gap:8px}.router-speed-readings>div{gap:4px}.router-speed-scale{font-size:var(--nodedc-font-size-xs)}}
@media(prefers-reduced-motion:reduce){.router-speed-tick{transition:none}}
@@ -0,0 +1,21 @@
/** Geometry of the router speed instrument. Values stay measured, only the marker interpolates. */
export function speedFraction(bps:number,ceiling=1e9){
return Math.log1p(Math.max(0,Math.min(ceiling,bps))/(ceiling/100))/Math.log(101);
}
export function speedPoint(fraction:number){
const radius=95,left=142,right=578,top=45,bottom=235,tail=143,straight=right-left;
let d=Math.max(0,Math.min(1,fraction))*(tail*2+Math.PI*radius*2+straight);
if(d<=tail)return{x:285-d,y:bottom,nx:0,ny:1};d-=tail;
if(d<=Math.PI*radius){const a=Math.PI/2+d/radius;return{x:left+radius*Math.cos(a),y:140+radius*Math.sin(a),nx:Math.cos(a),ny:Math.sin(a)};}d-=Math.PI*radius;
if(d<=straight)return{x:left+d,y:top,nx:0,ny:-1};d-=straight;
if(d<=Math.PI*radius){const a=-Math.PI/2+d/radius;return{x:right+radius*Math.cos(a),y:140+radius*Math.sin(a),nx:Math.cos(a),ny:Math.sin(a)};}d-=Math.PI*radius;
return{x:right-d,y:bottom,nx:0,ny:1};
}
export const speedTrack='M285 235 H142 A95 95 0 0 1 142 45 H578 A95 95 0 0 1 578 235 H435';
export function speedValues(m:{phase:string;current_bps?:number;sampled_at?:number;download_bps:number;upload_bps:number}|undefined){
if(!m)return{down:null,up:null};
if(m.phase==='complete')return{down:m.download_bps,up:m.upload_bps};
if(m.phase==='download')return{down:m.sampled_at?m.current_bps??null:null,up:null};
if(m.phase==='upload')return{down:m.download_bps,up:m.sampled_at?m.current_bps??null:null};
return{down:null,up:null};
}
@@ -0,0 +1,29 @@
import { useState } from "react";
import { Description, ConfirmationModal, Icon, IconButton } from "@nodedc/ui-react";
import type { ObservatoryRecordedJob } from "../../core/observatory/recordedJobs";
import { deleteFailedRunProjection } from "../../core/observatory/failedRunHistory";
export function FailedRunActions({ job, onDeleted }: {
job: ObservatoryRecordedJob;
onDeleted: () => void;
}) {
const [open, setOpen] = useState(false);
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
return <>
<IconButton label="Удалить ошибочную попытку" onClick={() => { setError(null); setOpen(true); }}>
<Icon name="trash" size={16} />
</IconButton>
<ConfirmationModal open={open} title="Удалить ошибочную попытку?"
description={<><Description>Попытка и её рабочие файлы будут удалены с этого устройства и Worker. Исходная запись сохранится.</Description>
{error ? <Description role="alert">{error}</Description> : null}</>}
confirmLabel="Удалить попытку" pendingLabel="Удаляем…" danger
onClose={() => { if (!pending) setOpen(false); }}
onConfirm={async () => {
setPending(true); setError(null);
try { await deleteFailedRunProjection(job); setOpen(false); onDeleted(); }
catch (cause) { setError(cause instanceof Error ? cause.message : "Не удалось удалить попытку."); }
finally { setPending(false); }
}} />
</>;
}
@@ -0,0 +1,71 @@
import { useEffect, useRef, useState } from "react";
import { ConfirmationModal, Icon, IconButton, ToastStack, type ToastItem } from "@nodedc/ui-react";
import { announceLabStorageChange, pinLabCopy, prepareLocalLabCopy, removeLabCopy,
type LocalLabCopy } from "../../core/storage/localLabStorage";
import { formatLocalLabSize } from "../../core/storage/localLabPresentation";
import type { LabReplayProgress } from "../../core/laboratory/prepareLabReplay";
export type LabCopyProgress = LabReplayProgress;
export function LabCopyActions({ id, sourceId, composition = false, copy, available, storageError, onProgress }: {
id: string; sourceId: string; composition?: boolean; copy?: LocalLabCopy;
available: boolean; storageError: string | null;
onProgress?: (value: LabReplayProgress | null) => void;
}) {
const [busy, setBusy] = useState<"download" | "pin" | "remove" | null>(null);
const [toasts, setToasts] = useState<ToastItem[]>([]);
const [confirm, setConfirm] = useState(false);
const request = useRef<AbortController | null>(null);
const progressCallback = useRef(onProgress);
progressCallback.current = onProgress;
useEffect(() => () => { request.current?.abort(); progressCallback.current?.(null); }, []);
const status = storageError ?? (!available ? "Проверяем локальную копию"
: copy?.local ? `На этом устройстве · ${formatLocalLabSize(copy, true)}`
: "Загрузить запись на это устройство");
async function perform(kind: "download" | "pin" | "remove", action: (signal: AbortSignal) => Promise<unknown>) {
if (request.current) return;
const controller = new AbortController(); request.current = controller;
setBusy(kind); setToasts([]);
try {
await action(controller.signal);
if (!controller.signal.aborted) setConfirm(false);
} catch (reason) {
if (!controller.signal.aborted) setToasts([{ id: "lab-copy-error", tone: "error",
title: "Не удалось изменить локальную копию",
description: reason instanceof Error ? reason.message : "Повторите действие." }]);
} finally {
announceLabStorageChange();
progressCallback.current?.(null);
request.current = null;
if (!controller.signal.aborted) setBusy(null);
}
}
const prepare = (signal: AbortSignal) => prepareLocalLabCopy(id, sourceId, composition,
{ signal, onProgress: (value) => progressCallback.current?.(value) });
const unavailable = !available || !!storageError;
return <>
<IconButton label={status} loading={busy === "download"}
disabled={!!busy || unavailable || !!copy?.local}
onClick={() => void perform("download", prepare)}>
<Icon name={copy?.local ? "database" : "download"} size={16} />
</IconButton>
<IconButton label={copy?.pinned ? "Открепить локальную запись" : "Оставить полную запись на этом устройстве"}
aria-pressed={copy?.pinned ?? false} loading={busy === "pin"} disabled={!!busy || unavailable}
onClick={() => void perform("pin", async (signal) => {
if (!copy?.local && !copy?.pinned) await prepare(signal);
signal.throwIfAborted();
await pinLabCopy(id, !copy?.pinned);
})}>
<Icon name="pin" size={16} />
</IconButton>
{copy?.local ? <IconButton label="Удалить только локальную копию" loading={busy === "remove"}
disabled={!!busy || copy.pinned || unavailable} onClick={() => setConfirm(true)}>
<Icon name="minus" size={16} />
</IconButton> : null}
<ToastStack items={toasts} onDismiss={(key) => setToasts((items) => items.filter((item) => item.id !== key))} />
<ConfirmationModal open={confirm} title="Удалить локальную копию?"
description="Результат и история запуска останутся. Копию можно вернуть кнопкой загрузки или открытием просмотра."
confirmLabel="Удалить копию" cancelLabel="Отмена" onClose={() => { if (!busy) setConfirm(false); }}
onConfirm={() => perform("remove", () => removeLabCopy(id))} />
</>;
}
@@ -1,5 +1,5 @@
import {createPortal} from 'react-dom'; import {createPortal} from 'react-dom';
import {Button,StatusBadge} from '@nodedc/ui-react'; import { Description,Button,StatusBadge} from '@nodedc/ui-react';
import type {RoverDiagnostics} from '../../core/fleet/useRoverDiagnostics'; import type {RoverDiagnostics} from '../../core/fleet/useRoverDiagnostics';
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation'; import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
import './roverLogs.css'; import './roverLogs.css';
@@ -11,11 +11,11 @@ export function RoverLogs({capture,header}:{capture:RoverDiagnostics;header:Obse
<div className="rover-logs"> <div className="rover-logs">
<div className="rover-logs__actions"><Button disabled={!storage?.file} loading={capture.saving} onClick={()=>void capture.save()}>Сохранить с борта</Button>{capture.state.local_capture?.id&&<Button loading={capture.saving} onClick={()=>void capture.saveLocal()}>Сохранить с компьютера</Button>}</div> <div className="rover-logs__actions"><Button disabled={!storage?.file} loading={capture.saving} onClick={()=>void capture.save()}>Сохранить с борта</Button>{capture.state.local_capture?.id&&<Button loading={capture.saving} onClick={()=>void capture.saveLocal()}>Сохранить с компьютера</Button>}</div>
<p>{status} · {storage?.written??0} записей{storage?.dropped?` · Потеряно при записи: ${storage.dropped}`:''}</p> <Description>{status} · {storage?.written??0} записей{storage?.dropped?` · Потеряно при записи: ${storage.dropped}`:''}</Description>
{storage?.file&&<p title={storage.file}>{storage.file}</p>} {storage?.file&&<Description title={storage.file}>{storage.file}</Description>}
{failed&&<p role="alert">Файл может быть неполным: {failed}</p>} {failed&&<Description role="alert">Файл может быть неполным: {failed}</Description>}
<p>{capture.state.options?.live===false?'События записываются локально; live-передача отключена.':'Последние события онлайн.'} «Сохранить с борта» выгружает полный бортовой файл. Закрытие окна не завершает запись.</p> <Description>{capture.state.options?.live===false?'События записываются локально; live-передача отключена.':'Последние события онлайн.'} «Сохранить с борта» выгружает полный бортовой файл. Закрытие окна не завершает запись.</Description>
{capture.state.local_capture?.id&&<p>Замер компьютера: {capture.state.local_capture.active?'идёт запись':'завершён'} · {capture.state.local_capture.sequence??0} событий{capture.state.local_capture.dropped?` · Пропущено: ${capture.state.local_capture.dropped}`:''}. Сохраните до перезапуска Core.</p>} {capture.state.local_capture?.id&&<Description>Замер компьютера: {capture.state.local_capture.active?'идёт запись':'завершён'} · {capture.state.local_capture.sequence??0} событий{capture.state.local_capture.dropped?` · Пропущено: ${capture.state.local_capture.dropped}`:''}. Сохраните до перезапуска Core.</Description>}
<div className="rover-logs__entries" role="log" aria-live="off" aria-label="События DEV-сессии"> <div className="rover-logs__entries" role="log" aria-live="off" aria-label="События DEV-сессии">
{[...capture.rows].reverse().map(item=>{const row=item.record??item;return <pre key={item.record_sequence}>{JSON.stringify(row,null,2)}</pre>;})} {[...capture.rows].reverse().map(item=>{const row=item.record??item;return <pre key={item.record_sequence}>{JSON.stringify(row,null,2)}</pre>;})}
</div> </div>
@@ -1,7 +1,7 @@
import {roverModelID} from '../../core/roverScene/model'; import {roverModelID} from '../../core/roverScene/model';
import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react'; import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react';
import {createPortal} from 'react-dom'; import {createPortal} from 'react-dom';
import {Button,EditorWorkspace,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,TextField,ToastStack,Window} from '@nodedc/ui-react'; import { Description,Button,EditorWorkspace,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,TextField,ToastStack,Window} from '@nodedc/ui-react';
import {keysFor,roverSettings,roverNumberInput,persistableRoverSettings,type RoverMode} from '../../core/fleet/roverInput'; import {keysFor,roverSettings,roverNumberInput,persistableRoverSettings,type RoverMode} from '../../core/fleet/roverInput';
import {roverDevEvent} from '../../core/fleet/roverDevEvents'; import {roverDevEvent} from '../../core/fleet/roverDevEvents';
import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput'; import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput';
@@ -60,7 +60,7 @@ export function RoverView({vehicleID,name,controller:c,header,active,observation
{settings.model===roverModelID?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}> {settings.model===roverModelID?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
<Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense> <Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense>
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>} {modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
</LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>} </LoadingRegion>:<div className="rover-view__empty"><Description>Выберите модель аппарата.</Description><Button onClick={showSettings}>Настройки вида</Button></div>}
{c.ready&&!editing&&<div className="rover-view__controls"> {c.ready&&!editing&&<div className="rover-view__controls">
<div className={`rover-keys rover-keys--${settings.mode}`} aria-label={settings.mode==='arcade'?'Аркадное управление':'Танковое управление'}> <div className={`rover-keys rover-keys--${settings.mode}`} aria-label={settings.mode==='arcade'?'Аркадное управление':'Танковое управление'}>
{keysFor(settings.mode).map(code=><KeyButton key={code} className={`rover-key-${code}`} label={settings.mode==='arcade'?({KeyW:'Вперёд · W',KeyS:'Назад · S',KeyA:'Налево · A',KeyD:'Направо · D'}[code]??code):({KeyQ:'Левая сторона вперёд · Q',KeyA:'Левая сторона назад · A',KeyE:'Правая сторона вперёд · E',KeyD:'Правая сторона назад · D'}[code]??code)} {keysFor(settings.mode).map(code=><KeyButton key={code} className={`rover-key-${code}`} label={settings.mode==='arcade'?({KeyW:'Вперёд · W',KeyS:'Назад · S',KeyA:'Налево · A',KeyD:'Направо · D'}[code]??code):({KeyQ:'Левая сторона вперёд · Q',KeyA:'Левая сторона назад · A',KeyE:'Правая сторона вперёд · E',KeyD:'Правая сторона назад · D'}[code]??code)}
@@ -81,7 +81,7 @@ export function RoverView({vehicleID,name,controller:c,header,active,observation
<TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={Number.isFinite(settings.maxErpm)?settings.maxErpm:''} onChange={e=>setSettings(v=>({...v,maxErpm:roverNumberInput(e.target.value)}))}/>} <TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={Number.isFinite(settings.maxErpm)?settings.maxErpm:''} onChange={e=>setSettings(v=>({...v,maxErpm:roverNumberInput(e.target.value)}))}/>}
<TextField label="Предел тока каждого мотора, А" description={currentDescription} type="number" min={.5} step={.5} value={Number.isFinite(settings.currentA)?settings.currentA:''} onChange={e=>setSettings(v=>({...v,currentA:roverNumberInput(e.target.value)}))}/> <TextField label="Предел тока каждого мотора, А" description={currentDescription} type="number" min={.5} step={.5} value={Number.isFinite(settings.currentA)?settings.currentA:''} onChange={e=>setSettings(v=>({...v,currentA:roverNumberInput(e.target.value)}))}/>
{(availability||c.error)&&<StatusBadge tone="warning">{availability||c.error}</StatusBadge>} {(availability||c.error)&&<StatusBadge tone="warning">{availability||c.error}</StatusBadge>}
<p>Включайте управление на остановленном аппарате. Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. После восстановления связи для движения нажмите клавишу заново. Команда с пульта прекращает удалённое управление.</p> <Description>Включайте управление на остановленном аппарате. Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. После восстановления связи для движения нажмите клавишу заново. Команда с пульта прекращает удалённое управление.</Description>
<Button variant="primary" tone="neutral" disabled={!c.canArm||!!observing.label||!(Number.isFinite(settings.currentA)&&settings.currentA>=.5&&speedValid)} loading={c.pending} <Button variant="primary" tone="neutral" disabled={!c.canArm||!!observing.label||!(Number.isFinite(settings.currentA)&&settings.currentA>=.5&&speedValid)} loading={c.pending}
onClick={async()=>{roverDevEvent(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,'settings',{mode:settings.mode,current_a:settings.currentA,speed:duty?settings.throttlePercent:settings.maxErpm,control_mode:duty?'duty':'rpm'});const acquired=await c.arm(settings.currentA,duty?settings.throttlePercent:settings.maxErpm,duty?'duty':'rpm');if(acquired){focusAfterArm.current=true;setOpen(false);}}}>Включить управление</Button> onClick={async()=>{roverDevEvent(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,'settings',{mode:settings.mode,current_a:settings.currentA,speed:duty?settings.throttlePercent:settings.maxErpm,control_mode:duty?'duty':'rpm'});const acquired=await c.arm(settings.currentA,duty?settings.throttlePercent:settings.maxErpm,duty?'duty':'rpm');if(acquired){focusAfterArm.current=true;setOpen(false);}}}>Включить управление</Button>
</div></Window> </div></Window>
@@ -9,9 +9,8 @@ export function ChargeGradientInspector({value,onChange}:{value:ChargeGradient;o
<RangeControl label="Сила свечения градиента" value={value.intensity} min={0} max={10} step={.05} exactValueBounds={{min:0,max:10}} onChange={intensity=>patch({intensity})}/> <RangeControl label="Сила свечения градиента" value={value.intensity} min={0} max={10} step={.05} exactValueBounds={{min:0,max:10}} onChange={intensity=>patch({intensity})}/>
<RangeControl label="Скорость переливания" value={value.speed} min={0} max={3} step={.01} exactValueBounds={{min:0,max:3}} onChange={speed=>patch({speed})}/> <RangeControl label="Скорость переливания" value={value.speed} min={0} max={3} step={.01} exactValueBounds={{min:0,max:3}} onChange={speed=>patch({speed})}/>
<RangeControl label="Масштаб рисунка" value={value.scale} min={1} max={50} step={.1} exactValueBounds={{min:1,max:50}} onChange={scale=>patch({scale})}/> <RangeControl label="Масштаб рисунка" value={value.scale} min={1} max={50} step={.1} exactValueBounds={{min:1,max:50}} onChange={scale=>patch({scale})}/>
<Description>Материал без данных · используется, когда сохранённого заряда нет. Без свечения.</Description> <RangeControl label="Контраст градиента" value={value.contrast} min={.1} max={4} step={.01} exactValueBounds={{min:.1,max:4}} onChange={contrast=>patch({contrast})}/>
<ControlRow label="Цвет без данных"><ColorField label="Цвет без данных" value={value.fallbackColor} onChange={fallbackColor=>patch({fallbackColor})}/></ControlRow> <RangeControl label="Насыщенность градиента" value={value.saturation} min={0} max={2} step={.01} exactValueBounds={{min:0,max:2}} onChange={saturation=>patch({saturation})}/>
{([['fallbackMetalness','Металличность без данных'],['fallbackRoughness','Шероховатость без данных'],['fallbackReflectivity','Отражение без данных'],['fallbackOpacity','Непрозрачность без данных']] as const).map(([key,label])=><RangeControl key={key} label={label} value={value[key]} min={0} max={1} step={.01} exactValueBounds={{min:0,max:1}} onChange={v=>patch({[key]:v})}/>)}
<Description>Ореол свечения настраивается в окружении → Bloom. При временном обрыве связи сохраняются последние цвет и яркость; движение возобновится с новыми показаниями.</Description> <Description>Ореол свечения настраивается в окружении → Bloom. При временном обрыве связи сохраняются последние цвет и яркость; движение возобновится с новыми показаниями.</Description>
</div>; </div>;
} }
@@ -0,0 +1,10 @@
import {useState} from 'react';
import {Button,Description,TextField,Window,WindowFooterActions} from '@nodedc/ui-react';
export function DuplicateMaterialDialog({initialName,onDuplicate,onClose}:{initialName:string;onDuplicate:(name:string)=>void;onClose:()=>void}){
const [name,setName]=useState(initialName),[error,setError]=useState('');
const save=()=>{try{onDuplicate(name);onClose();}catch(e){setError(e instanceof Error?e.message:'Не удалось создать копию материала.');}};
return <Window open title="Дублировать материал" size="sm" onClose={onClose} footer={<WindowFooterActions><Button onClick={onClose}>Отмена</Button><Button variant="primary" tone="neutral" disabled={!name.trim()} onClick={save}>Создать дубликат</Button></WindowFooterActions>}>
<TextField label="Название дубликата" autoFocus maxLength={120} value={name} onChange={e=>{setName(e.target.value);setError('');}} onKeyDown={e=>{if(e.key==='Enter'&&!e.nativeEvent.isComposing&&name.trim()){e.preventDefault();save();}}}/>
{error&&<Description role="alert">{error}</Description>}
</Window>;
}
@@ -1,11 +1,13 @@
import {EnvironmentProfiles} from './EnvironmentProfiles';
import type {ReactNode} from 'react';
import {LutField} from './LutField'; import {LutField} from './LutField';
import {useRef} from 'react'; import {useRef} from 'react';
import {Button,ColorField,ControlRow,Inspector,InspectorSelectField,RangeControl,Switch,TextField} from '@nodedc/ui-react'; import {Button,ColorField,ControlRow,Inspector,InspectorSelectField,RangeControl,Switch,TextField} from '@nodedc/ui-react';
import {environmentFields,fieldValue,fieldDisabled,type SceneDocument,type SceneField} from '../../../core/roverScene/sceneDocument'; import {environmentFields,fieldValue,fieldDisabled,type SceneDocument,type SceneField} from '../../../core/roverScene/sceneDocument';
const labels:Record<string,string>={'Камера':'Камера',Lighting:'Освещение',Rendering:'Рендеринг',Grid:'Сетка',SSAO:'Контактное затенение · SSAO',Bloom:'Свечение · Bloom','Chromatic Aberration':'Хроматическая аберрация',TAA:'Временное сглаживание · TAA',Grading:'Цветокоррекция',LUT:'Цветовая таблица · LUT',Vignette:'Виньетка','Environment Atlas':'Карта окружения','Skybox':'Небо','Directional Light':'Направленный свет','Shadow Catcher':'Тень на поверхности'}; const labels:Record<string,string>={'Камера':'Камера',Lighting:'Освещение',Rendering:'Рендеринг',Grid:'Сетка',SSAO:'Контактное затенение · SSAO',Bloom:'Свечение · Bloom','Chromatic Aberration':'Хроматическая аберрация',TAA:'Временное сглаживание · TAA',Grading:'Цветокоррекция',LUT:'Цветовая таблица · LUT',Vignette:'Виньетка','Environment Atlas':'Карта окружения','Skybox':'Небо','Directional Light':'Направленный свет','Shadow Catcher':'Тень на поверхности'};
export function EnvironmentInspector({document,onChange,onResetCamera,onError}:{document:SceneDocument;onChange:(key:string,value:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){ export function EnvironmentInspector({document,onChange,onResetCamera,onError,update,sceneFiles}:{document:SceneDocument;update:(fn:(doc:SceneDocument)=>SceneDocument)=>void;sceneFiles:ReactNode;onChange:(key:string,value:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
const groups=[...new Set(environmentFields.map(f=>f.group))]; const groups=[...new Set(environmentFields.map(f=>f.group))];
return <Inspector defaultOpen={['Камера','PostProcess/Lighting']} sections={groups.map(group=>({id:group,label:labels[group.split('/').at(-1)!]??group,content:<div className="rover-scene-fields">{environmentFields.filter(f=>f.group===group).map(f=><EnvironmentField key={f.key} field={f} value={fieldValue(document,f.key)} disabled={fieldDisabled(document,f)} onChange={v=>onChange(f.key,v)} onResetCamera={onResetCamera} onError={onError}/>)}</div>}))}/>; return <Inspector defaultOpen={['profiles']} sections={[{id:'profiles',label:'Профили',content:<><EnvironmentProfiles document={document} update={update} onError={onError}/><Inspector sections={[{id:'scene-json',label:'Вся сцена · JSON',content:sceneFiles}]}/></>},...groups.map(group=>({id:group,label:labels[group.split('/').at(-1)!]??group,content:<div className="rover-scene-fields">{environmentFields.filter(f=>f.group===group).map(f=><EnvironmentField key={f.key} field={f} value={fieldValue(document,f.key)} disabled={fieldDisabled(document,f)} onChange={v=>onChange(f.key,v)} onResetCamera={onResetCamera} onError={onError}/>)}</div>}))]}/>;
} }
function EnvironmentField({field:f,value,disabled,onChange,onResetCamera,onError}:{field:SceneField;value:unknown;disabled:boolean;onChange:(v:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){ function EnvironmentField({field:f,value,disabled,onChange,onResetCamera,onError}:{field:SceneField;value:unknown;disabled:boolean;onChange:(v:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
if(f.type==='texture')return <LutField value={value as string|null} onChange={onChange} onError={onError}/>; if(f.type==='texture')return <LutField value={value as string|null} onChange={onChange} onError={onError}/>;
@@ -17,7 +19,7 @@ function EnvironmentField({field:f,value,disabled,onChange,onResetCamera,onError
if(f.type==='number')return <TextField type="number" label={f.label} min={f.min} max={f.max} step={f.step??.01} value={Number(value)} disabled={disabled} onChange={e=>onChange(Number(e.target.value))}/>; if(f.type==='number')return <TextField type="number" label={f.label} min={f.min} max={f.max} step={f.step??.01} value={Number(value)} disabled={disabled} onChange={e=>onChange(Number(e.target.value))}/>;
return <RangeControl label={f.label} value={Number(value)} min={f.min??0} max={f.max??100} step={f.step??.01} exactValueBounds={{min:f.min,max:f.max}} disabled={disabled} onChange={onChange}/>; return <RangeControl label={f.label} value={Number(value)} min={f.min??0} max={f.max??100} step={f.step??.01} exactValueBounds={{min:f.min,max:f.max}} disabled={disabled} onChange={onChange}/>;
} }
export function SceneFileActions({onImport,onExport,onReset}:{onImport:(file:File)=>void;onExport:()=>void;onReset:()=>void}){ export function SceneFileActions({onImport,onExport}:{onImport:(file:File)=>void;onExport:()=>void}){
const input=useRef<HTMLInputElement>(null); const input=useRef<HTMLInputElement>(null);
return <div className="rover-scene-actions"><Button size="compact" onClick={onExport}>Экспорт JSON</Button><Button size="compact" onClick={()=>input.current?.click()}>Импорт JSON</Button><Button size="compact" onClick={onReset}>Окружение NodeDC</Button><input ref={input} hidden type="file" accept=".json,application/json" onChange={e=>{const f=e.currentTarget.files?.[0];if(f)onImport(f);e.currentTarget.value='';}}/></div>; return <div className="rover-scene-actions"><Button size="compact" onClick={onExport}>Экспорт всей сцены</Button><Button size="compact" onClick={()=>input.current?.click()}>Импорт всей сцены</Button><input ref={input} hidden type="file" accept=".json,application/json" onChange={e=>{const f=e.currentTarget.files?.[0];if(f)onImport(f);e.currentTarget.value='';}}/></div>;
} }
@@ -0,0 +1,33 @@
import {useEffect,useRef,useState} from 'react';
import {Button,Description,InspectorSelectField,TextField,Window,WindowFooterActions} from '@nodedc/ui-react';
import {applyEnvironment,builtinEnvironment,environmentMatches,parseEnvironmentProfile,sceneEnvironment,type EnvironmentProfile,type StoredEnvironmentProfile} from '../../../core/roverScene/environmentProfiles';
import {readEnvironmentProfiles,saveEnvironmentProfile,watchEnvironmentProfiles} from '../../../core/roverScene/environmentProfileStorage';
import type {SceneDocument} from '../../../core/roverScene/sceneDocument';
export function EnvironmentProfiles({document:doc,update,onError}:{document:SceneDocument;update:(fn:(doc:SceneDocument)=>SceneDocument)=>void;onError:(message:string)=>void}){
const [profiles,setProfiles]=useState<StoredEnvironmentProfile[]>([]),[ready,setReady]=useState(false),[pending,setPending]=useState(false),[draft,setDraft]=useState<EnvironmentProfile|null>(null),[name,setName]=useState('');
const input=useRef<HTMLInputElement>(null),mounted=useRef(true);
useEffect(()=>{mounted.current=true;let generation=0;const refresh=()=>{const current=++generation;readEnvironmentProfiles().then(value=>{if(mounted.current&&current===generation){setProfiles(value);setReady(true);}}).catch(e=>{if(mounted.current&&current===generation)onError(e instanceof Error?e.message:'Не удалось прочитать профили.');});};refresh();const stop=watchEnvironmentProfiles(refresh);return()=>{mounted.current=false;stop();};},[onError]);
const builtin=builtinEnvironment(),all=[builtin,...profiles],id=doc.environmentProfileId??(environmentMatches(doc,builtin.environment)?builtin.id:'current'),selected=all.find(p=>p.id===id);
const dirty=!selected||!environmentMatches(doc,selected.environment);
const current=():EnvironmentProfile=>({schema:'missioncore.environment-profile/v1',name:selected?.name??'Мой профиль',environment:sceneEnvironment(doc)});
const begin=(value=current())=>{setDraft(value);setName(value.name==='NodeDC'?'Мой профиль':value.name);};
const save=async(copy:boolean)=>{
const source=copy?draft:current();if(!source||(!copy&&!selected))return;setPending(true);
try{const saved=await saveEnvironmentProfile({...source,name:copy?name:source.name,id:copy?`env/${crypto.randomUUID()}`:selected!.id,revision:0},copy?null:selected!.revision);
if(mounted.current){setProfiles(previous=>[...previous.filter(p=>p.id!==saved.id),saved]);if(copy){update(d=>applyEnvironment(d,saved));setDraft(null);}else update(d=>d.environmentProfileId===saved.id?d:{...d,environmentProfileId:saved.id});}
}catch(e){onError(e instanceof Error?e.message:'Не удалось сохранить профиль.');}finally{if(mounted.current)setPending(false);}
};
const exportJson=()=>{const value=current(),url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));const a=globalThis.document.createElement('a');a.href=url;a.download='environment-profile.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
return <div className="rover-scene-fields">
<InspectorSelectField label="Профиль окружения" value={id} disabled={!ready||pending} options={[...(!selected?[{value:id,label:'Текущие настройки · без сохранённого профиля'}]:[]),...all.map(p=>({value:p.id,label:p.name}))]} onChange={value=>{const profile=all.find(p=>p.id===value);if(profile)update(d=>applyEnvironment(d,profile));}}/>
<Description>{dirty?'Есть изменения относительно профиля. Настройки сцены сохраняются автоматически.':'Настройки совпадают с профилем.'}</Description>
<div className="rover-scene-actions"><Button size="compact" disabled={!ready||!selected||selected.id===builtin.id||pending||!dirty} loading={pending&&!draft} onClick={()=>void save(false)}>Пересохранить профиль</Button><Button size="compact" disabled={!ready||pending} onClick={()=>begin()}>Сохранить как…</Button></div>
<div className="rover-scene-actions"><Button size="compact" onClick={exportJson}>Экспорт JSON</Button><Button size="compact" disabled={!ready||pending} onClick={()=>input.current?.click()}>Импорт JSON</Button></div>
<Description>Библиотека общая для сцен в Mission Core. Профиль переносит окружение и поведение камеры; ракурс, материалы и компоновка сцены сохраняются.</Description>
<input ref={input} type="file" hidden accept=".json,application/json" onChange={async e=>{const f=e.currentTarget.files?.[0];e.currentTarget.value='';if(!f)return;try{if(f.size>2_000_000)throw new Error('Профиль больше 2 МБ.');const value=parseEnvironmentProfile(JSON.parse(await f.text()));if(mounted.current)begin(value);}catch(error){onError(error instanceof Error?error.message:'Не удалось импортировать профиль.');}}}/>
<Window open={!!draft} onClose={()=>{if(!pending)setDraft(null);}} title="Сохранить профиль окружения" size="sm" footer={<WindowFooterActions><Button disabled={pending} onClick={()=>setDraft(null)}>Отмена</Button><Button variant="primary" loading={pending} disabled={!name.trim()} onClick={()=>void save(true)}>Сохранить</Button></WindowFooterActions>}>
<TextField label="Название профиля" value={name} maxLength={80} disabled={pending} onChange={e=>setName(e.target.value)}/>
<Description>Профиль будет доступен для батареи, ровера и других сцен.</Description>
</Window>
</div>;
}
@@ -1,19 +1,20 @@
import {useState} from 'react';
import {DuplicateMaterialDialog} from './DuplicateMaterialDialog';
import {Description,Inspector,InspectorSelectField,TextField,Button} from '@nodedc/ui-react';
import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {ChargeGradientInspector} from './ChargeGradientInspector'; import {ChargeGradientInspector} from './ChargeGradientInspector';
import {useRef,useState} from 'react'; import {MaterialSurfaceInspector} from './MaterialSurfaceInspector';
import {Button,ColorField,ControlRow,Icon,IconButton,Inspector,RangeControl,Switch,TextField} from '@nodedc/ui-react'; export type MaterialPreview='auto'|'active'|'inactive';
import {textureSlots,type TextureSlot,type MaterialSpec} from '../../../core/roverScene/sceneDocument'; export function MaterialInspector({material,onChange,onDuplicate,copyName,selectionDescription,onError,preview='auto',onPreview}:{material:MaterialSpec;onChange:(patch:Partial<MaterialSpec>)=>void;onDuplicate:(name:string)=>void;copyName:string;selectionDescription:string;onError:(message:string)=>void;preview?:MaterialPreview;onPreview?:(value:MaterialPreview)=>void}){
import {textureFromFile} from '../../../core/roverScene/sceneStorage'; const gradient=material.chargeGradient,[duplicate,setDuplicate]=useState(false);
const slotLabels:Record<TextureSlot,string>={diffuse:'Базовый цвет',normal:'Нормали',roughness:'Шероховатость',metalness:'Металличность',opacity:'Прозрачность',emissive:'Свечение',ao:'Окклюзия · AO'}; const header=<><Description>{selectionDescription}</Description><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><Description>Изменения применяются ко всем деталям с этим материалом.</Description>
export function MaterialInspector({material,onChange,onReset,onError}:{material:MaterialSpec;onChange:(patch:Partial<MaterialSpec>)=>void;onReset:()=>void;onError:(message:string)=>void}){ {gradient&&<InspectorSelectField label="Предпросмотр материала" value={preview} options={[{value:'auto',label:'По данным BMS'},{value:'active',label:'Активный · градиент'},{value:'inactive',label:'Неактивный · без данных'}]} onChange={v=>onPreview?.(v as MaterialPreview)}/>}
const range=(key:keyof MaterialSpec,label:string,max=1)=><RangeControl label={label} value={Number(material[key])} min={0} max={max} step={.01} exactValueBounds={{min:0,max}} onChange={v=>onChange({[key]:v})}/>; {gradient&&preview==='active'&&<Description>Предпросмотр градиента: текущий заряд, а при отсутствии показаний — 50%.</Description>}</>;
return <><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><p className="rover-scene-note">Изменения применяются ко всем деталям с этим материалом.</p><Inspector defaultOpen={material.chargeGradient?['charge']:['surface']} sections={[ const footer=<Button variant="primary" tone="neutral" onClick={()=>setDuplicate(true)}>Дублировать материал</Button>;
...(material.chargeGradient?[{id:'charge',label:'Градиент заряда',content:<ChargeGradientInspector value={material.chargeGradient} onChange={chargeGradient=>onChange({chargeGradient})}/>}]:[]), return <>{gradient?
{id:'surface',label:'Поверхность',content:<div className="rover-scene-fields">{!material.chargeGradient?.enabled&&<ControlRow label="Базовый цвет"><ColorField label="Базовый цвет" value={material.color} onChange={color=>onChange({color})}/></ControlRow>}{range('metalness','Металличность')}{range('roughness','Шероховатость')}{range('reflectivity','Отражение')}{range('opacity','Непрозрачность')}<Switch label="Двусторонняя поверхность" checked={material.doubleSided} onChange={doubleSided=>onChange({doubleSided})}/></div>}, <Inspector header={header} footer={footer} defaultOpen={['active']} sections={[
{id:'coat',label:'Лак и свечение',content:<div className="rover-scene-fields">{range('clearCoat','Слой лака')}{range('clearCoatRoughness','Шероховатость лака')}<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={material.emissive} onChange={emissive=>onChange({emissive})}/></ControlRow>{range('emissiveIntensity','Сила свечения',10)}</div>}, {id:'active',label:'Активный материал · градиент',content:<><ChargeGradientInspector value={gradient} onChange={chargeGradient=>onChange({chargeGradient})}/><MaterialSurfaceInspector material={material} onChange={onChange} onError={onError}/></>},
{id:'textures',label:'Текстуры',description:'PNG / JPEG / WebP · до 4096 px',content:<div className="rover-scene-fields">{textureSlots.map(slot=><TextureField key={slot} slot={slot} value={material.textures[slot]} onChange={texture=>onChange({textures:{...material.textures,[slot]:texture}})} onError={onError}/>)}{range('normalStrength','Сила нормалей',2)}<RangeControl label="Повторение текстуры" min={.01} max={20} step={.01} exactValueBounds={{min:.01,max:20}} value={material.tiling} onChange={tiling=>onChange({tiling})}/></div>}, {id:'inactive',label:'Неактивный материал · без данных',content:<><Description>Самостоятельный материал, когда сохранённого заряда нет. Свои поверхность, текстуры и свечение.</Description><MaterialSurfaceInspector material={gradient.inactive} onChange={patch=>onChange({chargeGradient:{...gradient,inactive:{...gradient.inactive,...patch}}})} onError={onError}/></>}
]}/><Button onClick={onReset}>Исходный материал</Button></>; ]}/>:<MaterialSurfaceInspector header={header} footer={footer} material={material} onChange={onChange} onError={onError}/>}
} {duplicate&&<DuplicateMaterialDialog initialName={copyName} onDuplicate={onDuplicate} onClose={()=>setDuplicate(false)}/>}</>;
function TextureField({slot,value,onChange,onError}:{slot:TextureSlot;value:MaterialSpec['textures'][TextureSlot];onChange:(value:MaterialSpec['textures'][TextureSlot])=>void;onError:(message:string)=>void}){
const input=useRef<HTMLInputElement>(null),[pending,setPending]=useState(false);
return <div className="rover-scene-texture"><ControlRow label={slotLabels[slot]} layout="stack"><div className="rover-scene-texture__row">{value&&<img src={value.data} alt=""/>}<Button size="compact" loading={pending} onClick={()=>input.current?.click()}>{value?.name??'Загрузить текстуру'}</Button>{value&&<IconButton label={`Удалить текстуру: ${slotLabels[slot]}`} onClick={()=>onChange(undefined)}><Icon name="trash"/></IconButton>}</div></ControlRow><input hidden ref={input} type="file" accept="image/png,image/jpeg,image/webp" onChange={async e=>{const file=e.currentTarget.files?.[0];e.currentTarget.value='';if(!file)return;setPending(true);try{onChange(await textureFromFile(file));}catch(error){onError(error instanceof Error?error.message:'Не удалось загрузить текстуру.');}finally{setPending(false);}}}/></div>;
} }
@@ -0,0 +1,18 @@
import {useRef,useState,type ReactNode} from 'react';
import {Button,ColorField,ControlRow,Icon,IconButton,Inspector,RangeControl,Switch} from '@nodedc/ui-react';
import {textureSlots,type TextureSlot,type MaterialSurface} from '../../../core/roverScene/materialSurface';
import {textureFromFile} from '../../../core/roverScene/sceneStorage';
const slotLabels:Record<TextureSlot,string>={diffuse:'Базовый цвет',normal:'Нормали',roughness:'Шероховатость',metalness:'Металличность',opacity:'Прозрачность',emissive:'Свечение',ao:'Окклюзия · AO'};
export function MaterialSurfaceInspector({material,onChange,onError,header,footer}:{header?:ReactNode;footer?:ReactNode;material:MaterialSurface;onChange:(patch:Partial<MaterialSurface>)=>void;onError:(message:string)=>void}){
const range=(key:keyof MaterialSurface,label:string,max=1)=><RangeControl label={label} value={Number(material[key])} min={0} max={max} step={.01} exactValueBounds={{min:0,max}} onChange={v=>onChange({[key]:v})}/>;
return <Inspector header={header} footer={footer} defaultOpen={['surface']} sections={[
{id:'surface',label:'Поверхность',content:<div className="rover-scene-fields"><ControlRow label="Базовый цвет"><ColorField label="Базовый цвет" value={material.color} onChange={color=>onChange({color})}/></ControlRow>{range('metalness','Металличность')}{range('roughness','Шероховатость')}{range('reflectivity','Отражение')}{range('opacity','Непрозрачность')}<Switch label="Двусторонняя поверхность" checked={material.doubleSided} onChange={doubleSided=>onChange({doubleSided})}/></div>},
{id:'coat',label:'Лак и свечение',content:<div className="rover-scene-fields">{range('clearCoat','Слой лака')}{range('clearCoatRoughness','Шероховатость лака')}<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={material.emissive} onChange={emissive=>onChange({emissive})}/></ControlRow>{range('emissiveIntensity','Сила свечения',10)}</div>},
{id:'textures',label:'Текстуры',description:'PNG / JPEG / WebP · до 4096 px',content:<div className="rover-scene-fields">{textureSlots.map(slot=><TextureField key={slot} slot={slot} value={material.textures[slot]} onChange={texture=>onChange({textures:{...material.textures,[slot]:texture}})} onError={onError}/>)}{range('normalStrength','Сила нормалей',2)}<RangeControl label="Повторение текстуры" min={.01} max={20} step={.01} exactValueBounds={{min:.01,max:20}} value={material.tiling} onChange={tiling=>onChange({tiling})}/></div>},
]}/>;
}
function TextureField({slot,value,onChange,onError}:{slot:TextureSlot;value:MaterialSurface['textures'][TextureSlot];onChange:(value:MaterialSurface['textures'][TextureSlot])=>void;onError:(message:string)=>void}){
const input=useRef<HTMLInputElement>(null),[pending,setPending]=useState(false);
return <div className="rover-scene-texture"><ControlRow label={slotLabels[slot]} layout="stack"><div className="rover-scene-texture__row">{value&&<img src={value.data} alt=""/>}<Button size="compact" loading={pending} onClick={()=>input.current?.click()}>{value?.name??'Загрузить текстуру'}</Button>{value&&<IconButton label={`Удалить текстуру: ${slotLabels[slot]}`} onClick={()=>onChange(undefined)}><Icon name="trash"/></IconButton>}</div></ControlRow><input hidden ref={input} type="file" accept="image/png,image/jpeg,image/webp" onChange={async e=>{const file=e.currentTarget.files?.[0];e.currentTarget.value='';if(!file)return;setPending(true);try{onChange(await textureFromFile(file));}catch(error){onError(error instanceof Error?error.message:'Не удалось загрузить текстуру.');}finally{setPending(false);}}}/></div>;
}
@@ -1,14 +1,15 @@
import {duplicateMaterial,materialCopyName} from '../../../core/roverScene/materialActions';
import {editorDockLayout,materialTileSizes} from '../../../core/roverScene/editorLayout'; import {editorDockLayout,materialTileSizes} from '../../../core/roverScene/editorLayout';
import {roverModelURL} from '../../../core/roverScene/model'; import {roverModelURL} from '../../../core/roverScene/model';
import {useCallback,useEffect,useRef,useState} from 'react'; import {useCallback,useEffect,useRef,useState} from 'react';
import {Description,DragDropRoot,DropZone,EditorDockLayout,GlassSurface,Icon,IconButton,LoadingRegion,StatusBadge,ToastStack,type EditorDockTool} from '@nodedc/ui-react'; import {DragDropRoot,DropZone,EditorDockLayout,GlassSurface,Icon,IconButton,LoadingRegion,StatusBadge,ToastStack,type EditorDockTool} from '@nodedc/ui-react';
import {createMaterial,changeField,defaultScene,maxSceneMaterials,textureBytes,type MaterialSpec} from '../../../core/roverScene/sceneDocument'; import {createMaterial,changeField,maxSceneMaterials,textureBytes,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {assignObjectMaterial,findSceneObject,objectTargets,type SceneObject} from '../../../core/roverScene/sceneObjects'; import {assignObjectMaterial,findSceneObject,objectTargets,type SceneObject} from '../../../core/roverScene/sceneObjects';
import {useSceneDocument} from '../../../core/roverScene/useSceneDocument'; import {useSceneDocument} from '../../../core/roverScene/useSceneDocument';
import PlayCanvasViewer,{type PlayCanvasViewerProps} from '../playcanvas/PlayCanvasViewer'; import PlayCanvasViewer,{type PlayCanvasViewerProps} from '../playcanvas/PlayCanvasViewer';
import type {ScenePicker,ScenePick} from '../playcanvas/useSceneMaterials'; import type {ScenePicker,ScenePick} from '../playcanvas/useSceneMaterials';
import {EnvironmentInspector,SceneFileActions} from './EnvironmentInspector'; import {EnvironmentInspector,SceneFileActions} from './EnvironmentInspector';
import {MaterialInspector} from './MaterialInspector'; import {MaterialInspector,type MaterialPreview} from './MaterialInspector';
import {MaterialPalette,MaterialPaletteActions,MaterialTile} from './MaterialPalette'; import {MaterialPalette,MaterialPaletteActions,MaterialTile} from './MaterialPalette';
import {SceneObjectTree} from './SceneObjectTree'; import {SceneObjectTree} from './SceneObjectTree';
import {useSceneUndo} from './useSceneUndo'; import {useSceneUndo} from './useSceneUndo';
@@ -18,10 +19,11 @@ import './sceneEditor.css';
export default function RoverScene({vehicleID,...props}:{vehicleID:string;editing:boolean;onModelState:(state:'loading'|'ready'|'error')=>void}){ export default function RoverScene({vehicleID,...props}:{vehicleID:string;editing:boolean;onModelState:(state:'loading'|'ready'|'error')=>void}){
const scene=useSceneDocument(vehicleID);return <SceneEditor {...props} scene={scene}/>; const scene=useSceneDocument(vehicleID);return <SceneEditor {...props} scene={scene}/>;
} }
export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,defaults=defaultScene,onSceneReady,minFitDistance,chargeState}:{scene:ReturnType<typeof useSceneDocument>;editing:boolean;onModelState:NonNullable<PlayCanvasViewerProps['onModelState']>;modelUrl?:string;defaults?:typeof defaultScene;onSceneReady?:PlayCanvasViewerProps['onSceneReady'];minFitDistance?:number;chargeState?:ChargeState}){ export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,onSceneReady,minFitDistance,chargeState}:{scene:ReturnType<typeof useSceneDocument>;editing:boolean;onModelState:NonNullable<PlayCanvasViewerProps['onModelState']>;modelUrl?:string;onSceneReady?:PlayCanvasViewerProps['onSceneReady'];minFitDistance?:number;chargeState?:ChargeState}){
useSceneUndo(scene,editing); useSceneUndo(scene,editing);
const layout=scene.document.editorLayout; const layout=scene.document.editorLayout;
const docking=editorDockLayout(layout),tileSize=layout?.materialTileSize??materialTileSizes.default; const docking=editorDockLayout(layout),tileSize=layout?.materialTileSize??materialTileSizes.default;
const [materialPreview,setMaterialPreview]=useState<MaterialPreview>('auto');
const [palette,setPalette]=useState(true),[environment,setEnvironment]=useState(false),[selected,setSelected]=useState<string|null>(null),[materialOpen,setMaterialOpen]=useState(false),[cameraReset,setCameraReset]=useState(0),[textureState,setTextureState]=useState<'loading'|'ready'|'error'>('ready'); const [palette,setPalette]=useState(true),[environment,setEnvironment]=useState(false),[selected,setSelected]=useState<string|null>(null),[materialOpen,setMaterialOpen]=useState(false),[cameraReset,setCameraReset]=useState(0),[textureState,setTextureState]=useState<'loading'|'ready'|'error'>('ready');
const [objectsOpen,setObjectsOpen]=useState(true),[root,setRoot]=useState<SceneObject|null>(null),[selectedObject,setSelectedObject]=useState<string|null>(null); const [objectsOpen,setObjectsOpen]=useState(true),[root,setRoot]=useState<SceneObject|null>(null),[selectedObject,setSelectedObject]=useState<string|null>(null);
const [selectionVersion,setSelectionVersion]=useState(0); const [selectionVersion,setSelectionVersion]=useState(0);
@@ -33,7 +35,7 @@ export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,d
const sceneReady=useCallback((api:Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0])=>{setSceneApi(api);onSceneReady?.(api);},[onSceneReady]); const sceneReady=useCallback((api:Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0])=>{setSceneApi(api);onSceneReady?.(api);},[onSceneReady]);
const modelState=useCallback((value:'loading'|'ready'|'error')=>{setModelPhase(value);onModelState(value);},[onModelState]); const modelState=useCallback((value:'loading'|'ready'|'error')=>{setModelPhase(value);onModelState(value);},[onModelState]);
const pick=useCallback((id:string)=>{setSelected(id);setMaterialOpen(true);setObjectsOpen(true);},[]); const pick=useCallback((id:string)=>{setMaterialPreview('auto');setSelected(id);setMaterialOpen(true);setObjectsOpen(true);},[]);
const objectPick=useCallback((hit:ScenePick|null)=>{setSelectionVersion(v=>v+1);if(!hit){setSelectedObject(null);setSelected(null);setMaterialOpen(false);return;}setSelectedObject(hit.objectId);setPalette(true);pick(hit.materialId);},[pick]); const objectPick=useCallback((hit:ScenePick|null)=>{setSelectionVersion(v=>v+1);if(!hit){setSelectedObject(null);setSelected(null);setMaterialOpen(false);return;}setSelectedObject(hit.objectId);setPalette(true);pick(hit.materialId);},[pick]);
const selectObject=(id:string)=>{setSelectionVersion(v=>v+1);setSelectedObject(id);const item=findSceneObject(root,id),source=item?.materialIds?.[0];const material=scene.document.objectAssignments?.[id]??(source?(scene.document.assignments[source]??source):null);if(material){setPalette(true);pick(material);}}; const selectObject=(id:string)=>{setSelectionVersion(v=>v+1);setSelectedObject(id);const item=findSceneObject(root,id),source=item?.materialIds?.[0];const material=scene.document.objectAssignments?.[id]??(source?(scene.document.assignments[source]??source):null);if(material){setPalette(true);pick(material);}};
const addMaterial=()=>{if(Object.keys(scene.document.materials).length>=maxSceneMaterials){scene.setError(`В сцене может быть не больше ${maxSceneMaterials} материалов.`);return;}const id=`custom/${crypto.randomUUID()}`;scene.update(doc=>createMaterial(doc,id));pick(id);}; const addMaterial=()=>{if(Object.keys(scene.document.materials).length>=maxSceneMaterials){scene.setError(`В сцене может быть не больше ${maxSceneMaterials} материалов.`);return;}const id=`custom/${crypto.randomUUID()}`;scene.update(doc=>createMaterial(doc,id));pick(id);};
@@ -42,15 +44,15 @@ export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,d
const node=findSceneObject(root,selectedObject),targets=node?objectTargets(node):[]; const node=findSceneObject(root,selectedObject),targets=node?objectTargets(node):[];
useObjectSelection(sceneApi,targets,editing&&modelPhase==='ready'); useObjectSelection(sceneApi,targets,editing&&modelPhase==='ready');
const material=selected?scene.document.materials[selected]:null; const material=selected?scene.document.materials[selected]:null;
const saved=scene.saveState==='saved',status=textureState==='loading'?'Загрузка текстур':scene.saveState==='loading'?'Загрузка настроек сцены':scene.saveState==='saving'?'Сохранение сцены':scene.saveState==='error'?'Изменения не сохранены':'Сохранено на этом компьютере'; const saved=scene.saveState==='saved',status=textureState==='loading'?'Загрузка текстур':scene.saveState==='loading'?'Загрузка настроек сцены':scene.saveState==='saving'?'Сохранение сцены':scene.saveState==='error'?'Изменения не сохранены':'Сохранено в Mission Core';
const tools:EditorDockTool[]=[ const tools:EditorDockTool[]=[
{id:'objects',title:'Объекты сцены',label:'Объекты сцены',open:objectsOpen,onClose:()=>setObjectsOpen(false),className:'scene-object-window',initialRect:{left:16,top:16,width:380,height:600},content:<SceneObjectTree revealVersion={selectionVersion} root={root} selected={selectedObject} visibility={scene.document.objectVisibility} legacyVisibility={scene.document.objects} onSelect={selectObject} onVisibility={(id,value)=>scene.update(doc=>({...doc,objectVisibility:{...doc.objectVisibility,[id]:value}}))}/>}, {id:'objects',title:'Объекты сцены',label:'Объекты сцены',open:objectsOpen,onClose:()=>setObjectsOpen(false),className:'scene-object-window',initialRect:{left:16,top:16,width:380,height:600},content:<SceneObjectTree revealVersion={selectionVersion} root={root} selected={selectedObject} visibility={scene.document.objectVisibility} legacyVisibility={scene.document.objects} onSelect={selectObject} onVisibility={(id,value)=>scene.update(doc=>({...doc,objectVisibility:{...doc.objectVisibility,[id]:value}}))}/>},
{id:'palette',title:'Материалы сцены',label:'Материалы сцены',open:palette,onClose:()=>setPalette(false),className:'rover-material-palette',initialRect:{left:400,top:420,width:640,height:340},minimumSize:{width:280,height:180}, {id:'palette',title:'Материалы сцены',label:'Материалы сцены',open:palette,onClose:()=>setPalette(false),className:'rover-material-palette',initialRect:{left:400,top:420,width:640,height:340},minimumSize:{width:280,height:180},
actions:<MaterialPaletteActions tileSize={tileSize} onTileSize={size=>scene.update(doc=>({...doc,editorLayout:{windows:{},...doc.editorLayout,materialTileSize:size}}))}/>,content:<MaterialPalette tileSize={tileSize} revealVersion={selectionVersion} materials={scene.document.materials} selected={selected} pick={pick} add={addMaterial}/>}, actions:<MaterialPaletteActions tileSize={tileSize} onTileSize={size=>scene.update(doc=>({...doc,editorLayout:{windows:{},...doc.editorLayout,materialTileSize:size}}))}/>,content:<MaterialPalette tileSize={tileSize} revealVersion={selectionVersion} materials={scene.document.materials} selected={selected} pick={pick} add={addMaterial}/>},
{id:'environment',title:'Окружение сцены',label:'Окружение сцены',open:environment,onClose:()=>setEnvironment(false),footer:<SceneFileActions onImport={scene.importDocument} onExport={scene.exportDocument} onReset={()=>scene.update(doc=>({...doc,postFx:defaults().postFx}))}/>,content:<EnvironmentInspector onError={scene.setError} document={scene.document} onChange={(key,value)=>scene.update(doc=>changeField(doc,key,value))} onResetCamera={()=>setCameraReset(v=>v+1)}/>}, {id:'environment',title:'Окружение сцены',label:'Окружение сцены',open:environment,onClose:()=>setEnvironment(false),content:<EnvironmentInspector update={scene.update} sceneFiles={<SceneFileActions onImport={scene.importDocument} onExport={scene.exportDocument}/>} onError={scene.setError} document={scene.document} onChange={(key,value)=>scene.update(doc=>changeField(doc,key,value))} onResetCamera={()=>setCameraReset(v=>v+1)}/>},
{id:'material',title:material?.name||'Материал',label:'Материал',activationKey:`${selectionVersion}:${selected}`,subtitle:node?`Назначить: ${node.name}`:'Выберите объект в дереве',open:materialOpen&&!!material,onClose:()=>setMaterialOpen(false), {id:'material',title:material?.name||'Материал',label:'Материал',activationKey:`${selectionVersion}:${selected}`,subtitle:node?`Назначить: ${node.name}`:'Выберите объект в дереве',open:materialOpen&&!!material,onClose:()=>setMaterialOpen(false),
actions:<IconButton label="Назначить материал выбранному объекту" disabled={!selected||!targets.length} onClick={()=>selected&&scene.update(doc=>assignObjectMaterial(doc,targets,selected))}><Icon name="chevron-right"/></IconButton>, actions:<IconButton label="Назначить материал выбранному объекту" disabled={!selected||!targets.length} onClick={()=>selected&&scene.update(doc=>assignObjectMaterial(doc,targets,selected))}><Icon name="chevron-right"/></IconButton>,
content:material&&selected?<><Description>{node?`Выбран объект: ${node.name}${targets.length>1?` · деталей: ${targets.length}`:''}`:'Выберите деталь в дереве объектов. Назначение доступно стрелкой рядом с крестиком.'}</Description><MaterialInspector key={selected} material={material} onChange={patch=>patchMaterial(selected,patch)} onReset={()=>{const base=defaults().materials[selected]??createMaterial(defaults(),selected).materials[selected];if(base)patchMaterial(selected,{...base,name:material.name});}} onError={scene.setError}/></>:null} content:material&&selected?<MaterialInspector key={selected} selectionDescription={node?`Выбран объект: ${node.name}${targets.length>1?` · деталей: ${targets.length}`:''}`:'Выберите деталь в дереве объектов. Назначение доступно стрелкой рядом с крестиком.'} copyName={materialCopyName(scene.document,selected)} onDuplicate={name=>{const id=`custom/${crypto.randomUUID()}`,next=duplicateMaterial(scene.document,selected,id,name);scene.update(()=>next);setPalette(true);setSelectionVersion(v=>v+1);pick(id);}} preview={materialPreview} onPreview={setMaterialPreview} material={material} onChange={patch=>patchMaterial(selected,patch)} onError={scene.setError}/>:null}
]; ];
return <DragDropRoot renderOverlay={({data})=>{const m=scene.document.materials[String(data?.materialId)];return m?<GlassSurface padding="sm"><MaterialTile material={m}/></GlassSurface>:null;}} onDragEnd={({activeData,pointer})=>{ return <DragDropRoot renderOverlay={({data})=>{const m=scene.document.materials[String(data?.materialId)];return m?<GlassSurface padding="sm"><MaterialTile material={m}/></GlassSurface>:null;}} onDragEnd={({activeData,pointer})=>{
const id=String(activeData?.materialId??'');if(!editing||!pointer||!Object.hasOwn(scene.document.materials,id))return; const id=String(activeData?.materialId??'');if(!editing||!pointer||!Object.hasOwn(scene.document.materials,id))return;
@@ -61,10 +63,10 @@ export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,d
}}> }}>
<EditorDockLayout value={docking} enabled={editing} tools={tools} onChange={next=>scene.update(doc=>({...doc,editorLayout:{windows:{},materialTileSize:materialTileSizes.default,...doc.editorLayout,docking:next}}))} primary={<> <EditorDockLayout value={docking} enabled={editing} tools={tools} onChange={next=>scene.update(doc=>({...doc,editorLayout:{windows:{},materialTileSize:materialTileSizes.default,...doc.editorLayout,docking:next}}))} primary={<>
<DropZone id="scene-model" className="rover-scene-drop"><LoadingRegion className="rover-view__scene" loading={!scene.ready} label="Загрузка настроек сцены"> <DropZone id="scene-model" className="rover-scene-drop"><LoadingRegion className="rover-view__scene" loading={!scene.ready} label="Загрузка настроек сцены">
{scene.ready&&<PlayCanvasViewer modelUrl={modelUrl} onSceneReady={sceneReady} onSceneGraph={sceneGraph} minFitDistance={minFitDistance} postFx={scene.document.postFx} cameraAutoRotate={scene.document.cameraAutoRotate} cameraZoomStrength={scene.document.cameraZoomStrength} cameraResetToken={cameraReset} cameraState={scene.document.camera} onCameraChange={scene.recordCamera} materials={scene.document.materials} assignments={scene.document.assignments} objectAssignments={scene.document.objectAssignments} objectVisibility={scene.document.objectVisibility} legacyObjectVisibility={scene.document.objects} editing={editing} chargeState={chargeState} onObjectPick={objectPick} onPickerReady={pickerReady} onModelState={modelState} onTextureState={setTextureState}/>} {scene.ready&&<PlayCanvasViewer modelUrl={modelUrl} onSceneReady={sceneReady} onSceneGraph={sceneGraph} minFitDistance={minFitDistance} postFx={scene.document.postFx} cameraAutoRotate={scene.document.cameraAutoRotate} cameraZoomStrength={scene.document.cameraZoomStrength} cameraResetToken={cameraReset} cameraState={scene.document.camera} onCameraChange={scene.recordCamera} materials={scene.document.materials} assignments={scene.document.assignments} objectAssignments={scene.document.objectAssignments} objectVisibility={scene.document.objectVisibility} legacyObjectVisibility={scene.document.objects} editing={editing} chargeState={chargeState} materialPreview={editing&&materialOpen&&selected&&materialPreview!=='auto'?{id:selected,mode:materialPreview}:undefined} onObjectPick={objectPick} onPickerReady={pickerReady} onModelState={modelState} onTextureState={setTextureState}/>}
</LoadingRegion></DropZone> </LoadingRegion></DropZone>
{editing&&<> {editing&&<>
<div className="rover-scene-tools"><GlassSurface className="rover-scene-tools__surface nodedc-viewport-controls"><IconButton label="Отменить изменение · Ctrl/Cmd+Z" disabled={!scene.canUndo} onClick={scene.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить изменение · Ctrl/Cmd+Shift+Z" disabled={!scene.canRedo} onClick={scene.redo}><Icon name="redo"/></IconButton><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>{setPalette(v=>!v);setObjectsOpen(true);}}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton><IconButton label="Объекты сцены" aria-pressed={objectsOpen} onClick={()=>setObjectsOpen(v=>!v)}><Icon name="list"/></IconButton></GlassSurface></div> <div className="rover-scene-tools"><div className="rover-scene-tools__surface nodedc-viewport-controls"><IconButton label="Отменить изменение · Ctrl/Cmd+Z" disabled={!scene.canUndo} onClick={scene.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить изменение · Ctrl/Cmd+Shift+Z" disabled={!scene.canRedo} onClick={scene.redo}><Icon name="redo"/></IconButton><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>{setPalette(v=>!v);setObjectsOpen(true);}}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton><IconButton label="Объекты сцены" aria-pressed={objectsOpen} onClick={()=>setObjectsOpen(v=>!v)}><Icon name="list"/></IconButton></div></div>
<div className="rover-scene-save"><StatusBadge tone={saved&&textureState!=='loading'?'neutral':'warning'}>{status}</StatusBadge></div> <div className="rover-scene-save"><StatusBadge tone={saved&&textureState!=='loading'?'neutral':'warning'}>{status}</StatusBadge></div>
</>} </>}
</>}/> </>}/>
@@ -882,7 +882,7 @@ function applyPostFx(
export default function PlayCanvasViewer({ export default function PlayCanvasViewer({
minFitDistance = 1.8, minFitDistance = 1.8,
modelUrl, modelUrl,
materials, assignments, objectAssignments, objectVisibility, legacyObjectVisibility, editing, onObjectPick, onPickerReady, onTextureState, chargeState, materials, assignments, objectAssignments, objectVisibility, legacyObjectVisibility, editing, onObjectPick, onPickerReady, onTextureState, chargeState, materialPreview,
postFx, postFx,
viewportSize, viewportSize,
onSceneReady, onSceneReady,
@@ -930,7 +930,7 @@ export default function PlayCanvasViewer({
const [skyboxVersion, setSkyboxVersion] = useState(0) const [skyboxVersion, setSkyboxVersion] = useState(0)
const [modelVersion, setModelVersion] = useState(0) const [modelVersion, setModelVersion] = useState(0)
useSceneMaterials(appRef,cameraEntityRef,canvasRef,modelVersion,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState}) useSceneMaterials(appRef,cameraEntityRef,canvasRef,modelVersion,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState,materialPreview})
const fx = useMemo(() => mergePostFxDefaults(postFx), [postFx]) const fx = useMemo(() => mergePostFxDefaults(postFx), [postFx])
const lutError = useCallback(()=>onTextureState?.('error'),[onTextureState]) const lutError = useCallback(()=>onTextureState?.('error'),[onTextureState])
@@ -1,8 +1,15 @@
import * as pc from 'playcanvas'; import * as pc from 'playcanvas';
import {chargePair,type ChargeGradient} from '../../../core/roverScene/chargeGradient'; import {chargePair,type ChargeGradient} from '../../../core/roverScene/chargeGradient';
import type {MaterialSpec} from '../../../core/roverScene/sceneDocument'; import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
const surfaces=new WeakMap<pc.StandardMaterial,{known:boolean;spec:MaterialSpec;gradient:ChargeGradient}>(); import type {MaterialSurface} from '../../../core/roverScene/materialSurface';
import {applyMaterialSurface} from './materialSurface';
const surfaces=new WeakMap<pc.StandardMaterial,{surface:MaterialSurface;gradient:ChargeGradient}>();
export type ChargeState={soc:number|null;fresh:boolean}; export type ChargeState={soc:number|null;fresh:boolean};
export type ChargePreview={id:string;mode:'active'|'inactive'};
export function previewChargeState(state:ChargeState|undefined,preview?:ChargePreview):ChargeState|undefined{
return preview?.mode==='inactive'?{soc:null,fresh:false}:preview?.mode==='active'?{soc:Number.isFinite(state?.soc)?state!.soc:50,fresh:true}:state;
}
export function chargeSurface(spec:MaterialSpec,state:ChargeState|undefined):MaterialSurface{return spec.chargeGradient&&!Number.isFinite(state?.soc)?spec.chargeGradient.inactive:spec;}
const emission=` const emission=`
uniform vec3 chargeColorA; uniform vec3 chargeColorA;
uniform vec3 chargeColorB; uniform vec3 chargeColorB;
@@ -10,38 +17,42 @@ uniform float chargeTime;
uniform float chargeScale; uniform float chargeScale;
uniform float chargeIntensity; uniform float chargeIntensity;
uniform float chargeSaturation; uniform float chargeSaturation;
uniform float chargeContrast;
uniform vec3 material_emissive;
uniform float material_emissiveIntensity;
void getEmission() { void getEmission() {
vec3 p=vPositionW*chargeScale; vec3 p=vPositionW*chargeScale;
float wave=sin(p.x*0.77+sin(p.y*0.91+chargeTime)*1.2+chargeTime*0.43); float wave=sin(p.x*0.77+sin(p.y*0.91+chargeTime)*1.2+chargeTime*0.43);
wave+=sin(p.z*0.71-p.y*0.48+sin(p.x*0.57-chargeTime*0.61)); wave+=sin(p.z*0.71-p.y*0.48+sin(p.x*0.57-chargeTime*0.61));
float blend=smoothstep(-1.6,1.6,wave); float blend=clamp((smoothstep(-1.6,1.6,wave)-0.5)*chargeContrast+0.5,0.0,1.0);
vec3 color=mix(chargeColorA,chargeColorB,blend); vec3 color=mix(chargeColorA,chargeColorB,blend);
color=mix(vec3(dot(color,vec3(0.2126,0.7152,0.0722))),color,chargeSaturation); color=mix(vec3(dot(color,vec3(0.2126,0.7152,0.0722))),color,chargeSaturation);
dEmission=color*chargeIntensity; vec3 baseEmission=material_emissive*material_emissiveIntensity;
#ifdef STD_EMISSIVE_TEXTURE
baseEmission *= {STD_EMISSIVE_TEXTURE_DECODE}(texture2DBias({STD_EMISSIVE_TEXTURE_NAME}, {STD_EMISSIVE_TEXTURE_UV}, textureBias)).{STD_EMISSIVE_TEXTURE_CHANNEL};
#endif
#ifdef STD_EMISSIVE_VERTEX
baseEmission *= saturate(vVertexColor.{STD_EMISSIVE_VERTEX_CHANNEL});
#endif
dEmission=baseEmission+max(color,vec3(0.0))*chargeIntensity;
}`; }`;
export function configureChargeMaterial(material:pc.StandardMaterial,gradient?:ChargeGradient){ export function configureChargeMaterial(material:pc.StandardMaterial,gradient?:ChargeGradient){
const chunks=material.getShaderChunks(pc.SHADERLANGUAGE_GLSL); const chunks=material.getShaderChunks(pc.SHADERLANGUAGE_GLSL);
if(gradient?.enabled){chunks.set('emissivePS',emission);material.emissive.set(1,1,1);material.emissiveIntensity=1;material.diffuse.set(.02,.02,.02);} if(gradient)chunks.set('emissivePS',emission);else chunks.delete('emissivePS');
else chunks.delete('emissivePS'); surfaces.delete(material);
} }
export function updateChargeMaterial(material:pc.StandardMaterial,gradient:ChargeGradient,state:ChargeState|undefined,time:number,spec:MaterialSpec){ export function updateChargeMaterial(material:pc.StandardMaterial,gradient:ChargeGradient,state:ChargeState|undefined,time:number,spec:MaterialSpec,bindTextures?:(surface:MaterialSurface)=>void){
const known=typeof state?.soc==='number'&&Number.isFinite(state.soc); const known=typeof state?.soc==='number'&&Number.isFinite(state.soc),surface=known?spec:gradient.inactive;
const applied=surfaces.get(material); const applied=surfaces.get(material);
if(!applied||applied.known!==known||applied.spec!==spec||applied.gradient!==gradient){ if(!applied||applied.surface!==surface||applied.gradient!==gradient){
if(known)material.diffuse.set(.02,.02,.02);else material.diffuse.fromString(gradient.fallbackColor); applyMaterialSurface(material,surface);bindTextures?.(surface);material.update();surfaces.set(material,{surface,gradient});
material.metalness=known?spec.metalness:gradient.fallbackMetalness;
material.gloss=known?spec.roughness:gradient.fallbackRoughness;
material.specularityFactor=known?spec.reflectivity:gradient.fallbackReflectivity;
material.opacity=known?spec.opacity:gradient.fallbackOpacity;
material.blendType=material.opacity<1||spec.textures.opacity?pc.BLEND_NORMAL:pc.BLEND_NONE;
material.depthWrite=material.blendType===pc.BLEND_NONE;
material.update();surfaces.set(material,{known,spec,gradient});
} }
const colors=known?chargePair(gradient,state!.soc):[[0,0,0],[0,0,0]]; const colors=known?chargePair(gradient,state!.soc):[[0,0,0],[0,0,0]];
material.setParameter('chargeColorA',colors[0].map(value=>value**2.2)); material.setParameter('chargeColorA',colors[0].map(value=>value**2.2));
material.setParameter('chargeColorB',colors[1].map(value=>value**2.2)); material.setParameter('chargeColorB',colors[1].map(value=>value**2.2));
material.setParameter('chargeTime',time*gradient.speed); material.setParameter('chargeTime',time*gradient.speed);
material.setParameter('chargeScale',gradient.scale); material.setParameter('chargeScale',gradient.scale);
material.setParameter('chargeIntensity',known?gradient.intensity:0); material.setParameter('chargeIntensity',known&&gradient.enabled?gradient.intensity:0);
material.setParameter('chargeSaturation',known?1:0); material.setParameter('chargeSaturation',gradient.saturation);
material.setParameter('chargeContrast',gradient.contrast);
} }
@@ -0,0 +1,13 @@
import * as pc from 'playcanvas';
import type {MaterialSurface,TextureSlot} from '../../../core/roverScene/materialSurface';
export const surfaceMaps:Record<TextureSlot,string>={diffuse:'diffuseMap',normal:'normalMap',metalness:'metalnessMap',roughness:'glossMap',opacity:'opacityMap',emissive:'emissiveMap',ao:'aoMap'};
export function applyMaterialSurface(m:pc.StandardMaterial,spec:MaterialSurface){
m.diffuse.fromString(spec.color);m.useMetalness=true;m.metalness=spec.metalness;
m.glossInvert=true;m.gloss=spec.roughness;m.opacity=spec.opacity;
m.specularityFactor=spec.reflectivity;m.clearCoat=spec.clearCoat;
m.clearCoatGlossInvert=true;m.clearCoatGloss=spec.clearCoatRoughness;
m.emissive.fromString(spec.emissive);m.emissiveIntensity=spec.emissiveIntensity;
m.bumpiness=spec.normalStrength;m.cull=spec.doubleSided?pc.CULLFACE_NONE:pc.CULLFACE_BACK;
m.blendType=spec.opacity<1||spec.textures.opacity?pc.BLEND_NORMAL:pc.BLEND_NONE;
m.depthWrite=m.blendType===pc.BLEND_NONE;
}
@@ -1,14 +1,16 @@
import {useEffect,useRef,type RefObject} from 'react'; import {useEffect,useRef,type RefObject} from 'react';
import * as pc from 'playcanvas'; import * as pc from 'playcanvas';
import {configureChargeMaterial,updateChargeMaterial,type ChargeState} from './chargeMaterial'; import {configureChargeMaterial,updateChargeMaterial,chargeSurface,previewChargeState,type ChargePreview,type ChargeState} from './chargeMaterial';
import {sceneObjectId} from './sceneTree'; import {sceneObjectId} from './sceneTree';
export type ScenePick={objectId:string;materialId:string}; export type ScenePick={objectId:string;materialId:string};
export type ScenePicker={pick:(x:number,y:number)=>ScenePick|null}; export type ScenePicker={pick:(x:number,y:number)=>ScenePick|null};
import type {MaterialSpec,TextureSlot} from '../../../core/roverScene/sceneDocument'; import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
export type SceneMaterialsProps={materials?:Record<string,MaterialSpec>;assignments?:Record<string,string>;objectAssignments?:Record<string,string>;objectVisibility?:Record<string,boolean>;legacyObjectVisibility?:Record<string,boolean>;editing?:boolean;onObjectPick?:(hit:ScenePick|null)=>void;chargeState?:ChargeState;onPickerReady?:(picker:ScenePicker|null)=>void;onTextureState?:(state:'loading'|'ready'|'error')=>void}; import type {MaterialSurface,TextureSlot} from '../../../core/roverScene/materialSurface';
const maps:Record<TextureSlot,string>={diffuse:'diffuseMap',normal:'normalMap',metalness:'metalnessMap',roughness:'glossMap',opacity:'opacityMap',emissive:'emissiveMap',ao:'aoMap'}; import {applyMaterialSurface,surfaceMaps as maps} from './materialSurface';
export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRef:RefObject<pc.Entity|null>,canvasRef:RefObject<HTMLCanvasElement|null>,modelVersion:number,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState}:SceneMaterialsProps){ export type SceneMaterialsProps={materials?:Record<string,MaterialSpec>;assignments?:Record<string,string>;objectAssignments?:Record<string,string>;objectVisibility?:Record<string,boolean>;legacyObjectVisibility?:Record<string,boolean>;editing?:boolean;onObjectPick?:(hit:ScenePick|null)=>void;chargeState?:ChargeState;materialPreview?:ChargePreview;onPickerReady?:(picker:ScenePicker|null)=>void;onTextureState?:(state:'loading'|'ready'|'error')=>void};
const latest=useRef({materials,onObjectPick,onTextureState,chargeState});latest.current={materials,onObjectPick,onTextureState,chargeState}; export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRef:RefObject<pc.Entity|null>,canvasRef:RefObject<HTMLCanvasElement|null>,modelVersion:number,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState,materialPreview}:SceneMaterialsProps){
const latest=useRef({materials,onObjectPick,onTextureState,chargeState,materialPreview});latest.current={materials,onObjectPick,onTextureState,chargeState,materialPreview};
const bindings=useRef(new Map<string,(surface:MaterialSurface)=>void>());
const animated=useRef(new Map<string,pc.StandardMaterial>()); const animated=useRef(new Map<string,pc.StandardMaterial>());
const textures=useRef(new Map<string,{texture?:pc.Texture;promise:Promise<pc.Texture>}>()); const textures=useRef(new Map<string,{texture?:pc.Texture;promise:Promise<pc.Texture>}>());
const generation=useRef(0); const generation=useRef(0);
@@ -32,40 +34,36 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
const source=originalGroups.current.get(mi);if(source)mi.material=map.get(objectAssignments?.[sceneObjectId(mi.node)]??assignments?.[source.id]??source.id)??source.material; const source=originalGroups.current.get(mi);if(source)mi.material=map.get(objectAssignments?.[sceneObjectId(mi.node)]??assignments?.[source.id]??source.id)??source.material;
} }
for(const [id,m] of customMaterials.current)if(!Object.hasOwn(materials,id)){m.destroy();customMaterials.current.delete(id);} for(const [id,m] of customMaterials.current)if(!Object.hasOwn(materials,id)){m.destroy();customMaterials.current.delete(id);}
const applyTexture=(m:pc.StandardMaterial,slot:TextureSlot,texture:pc.Texture|null,spec:MaterialSpec)=>{ const applyTexture=(m:pc.StandardMaterial,slot:TextureSlot,texture:pc.Texture|null,spec:MaterialSurface)=>{
(m as any)[maps[slot]]=texture; (m as any)[maps[slot]]=texture;
const prefix=maps[slot];(m as any)[prefix+'Tiling']=new pc.Vec2(spec.tiling,spec.tiling); const prefix=maps[slot];(m as any)[prefix+'Tiling']=new pc.Vec2(spec.tiling,spec.tiling);
if(['metalness','roughness','opacity','ao'].includes(slot))(m as any)[prefix+'Channel']='r'; if(['metalness','roughness','opacity','ao'].includes(slot))(m as any)[prefix+'Channel']='r';
m.update(); m.update();
}; };
const used=new Set<string>();animated.current.clear(); const used=new Set<string>();animated.current.clear();bindings.current.clear();
for(const [id,spec] of Object.entries(materials)){ for(const [id,spec] of Object.entries(materials)){
const m=map.get(id);if(!m)continue; const m=map.get(id);if(!m)continue;
m.diffuse.fromString(spec.color);m.useMetalness=true;m.metalness=spec.metalness; const state=()=>previewChargeState(latest.current.chargeState,latest.current.materialPreview?.id===id?latest.current.materialPreview:undefined);
m.glossInvert=true;m.gloss=spec.roughness;m.opacity=spec.opacity; const selectedSurface=()=>chargeSurface(spec,state());
// Specular factor is independent from the donor's global IBL multiplier. const bind=(surface:MaterialSurface)=>{for(const slot of Object.keys(maps) as TextureSlot[]){const data=surface.textures[slot]?.data;applyTexture(m,slot,data?textures.current.get(`${slot==='diffuse'||slot==='emissive'}:${data}`)?.texture??null:null,surface);}};
m.specularityFactor=spec.reflectivity;m.clearCoat=spec.clearCoat; bindings.current.set(id,bind);
m.clearCoatGlossInvert=true;m.clearCoatGloss=spec.clearCoatRoughness; for(const surface of [spec,...(spec.chargeGradient?[spec.chargeGradient.inactive]:[])]){
m.emissive.fromString(spec.emissive);m.emissiveIntensity=spec.emissiveIntensity;
m.bumpiness=spec.normalStrength;m.cull=spec.doubleSided?pc.CULLFACE_NONE:pc.CULLFACE_BACK;
m.blendType=spec.opacity<1||spec.textures.opacity?pc.BLEND_NORMAL:pc.BLEND_NONE;
m.depthWrite=m.blendType===pc.BLEND_NONE;
for(const slot of Object.keys(maps) as TextureSlot[]){ for(const slot of Object.keys(maps) as TextureSlot[]){
const data=spec.textures[slot]?.data;if(!data){applyTexture(m,slot,null,spec);continue;} const data=surface.textures[slot]?.data;if(!data)continue;
const srgb=slot==='diffuse'||slot==='emissive';const key=`${srgb}:${data}`;used.add(key); const srgb=slot==='diffuse'||slot==='emissive';const key=`${srgb}:${data}`;used.add(key);
let item=textures.current.get(key); let item=textures.current.get(key);
if(!item){ if(!item){
const promise=new Promise<pc.Texture>((resolve,reject)=>{const img=new Image();img.onload=()=>{if(generation.current<0){reject(new Error('Scene disposed'));return;}const tex=new pc.Texture(app.graphicsDevice,{name:spec.textures[slot]?.name,format:srgb?pc.PIXELFORMAT_SRGBA8:pc.PIXELFORMAT_RGBA8,mipmaps:true,addressU:pc.ADDRESS_REPEAT,addressV:pc.ADDRESS_REPEAT});tex.setSource(img);resolve(tex);};img.onerror=()=>reject(new Error('Texture decode failed'));img.src=data;}); const promise=new Promise<pc.Texture>((resolve,reject)=>{const img=new Image();img.onload=()=>{if(generation.current<0){reject(new Error('Scene disposed'));return;}const tex=new pc.Texture(app.graphicsDevice,{name:surface.textures[slot]?.name,format:srgb?pc.PIXELFORMAT_SRGBA8:pc.PIXELFORMAT_RGBA8,mipmaps:true,addressU:pc.ADDRESS_REPEAT,addressV:pc.ADDRESS_REPEAT});tex.setSource(img);resolve(tex);};img.onerror=()=>reject(new Error('Texture decode failed'));img.src=data;});
item={promise};textures.current.set(key,item);const cached=item; item={promise};textures.current.set(key,item);const cached=item;
promise.then(tex=>{cached.texture=tex;if(textures.current.get(key)!==cached){tex.destroy();}}).catch(()=>{if(textures.current.get(key)===cached)textures.current.delete(key);}); promise.then(tex=>{cached.texture=tex;if(textures.current.get(key)!==cached){tex.destroy();}}).catch(()=>{if(textures.current.get(key)===cached)textures.current.delete(key);});
} }
if(item.texture)applyTexture(m,slot,item.texture,spec); if(!item.texture){
else{ pending++;item.promise.then(tex=>{if(generation.current===current&&selectedSurface()===surface)applyTexture(m,slot,tex,surface);}).catch(()=>{failed=true;}).finally(()=>{pending--;if(generation.current===current&&!pending)latest.current.onTextureState?.(failed?'error':'ready');});
pending++;item.promise.then(tex=>{if(generation.current===current)applyTexture(m,slot,tex,spec);}).catch(()=>{failed=true;}).finally(()=>{pending--;if(generation.current===current&&!pending)latest.current.onTextureState?.(failed?'error':'ready');});
} }
} }
}
configureChargeMaterial(m,spec.chargeGradient); configureChargeMaterial(m,spec.chargeGradient);
if(spec.chargeGradient?.enabled){animated.current.set(id,m);updateChargeMaterial(m,spec.chargeGradient,latest.current.chargeState,0,spec);} if(spec.chargeGradient){animated.current.set(id,m);updateChargeMaterial(m,spec.chargeGradient,state(),0,spec,bind);}else{applyMaterialSurface(m,spec);bind(spec);}
m.update(); m.update();
} }
for(const [key,item] of textures.current)if(!used.has(key)){item.texture?.destroy();textures.current.delete(key);} for(const [key,item] of textures.current)if(!used.has(key)){item.texture?.destroy();textures.current.delete(key);}
@@ -75,7 +73,7 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
useEffect(()=>{ useEffect(()=>{
const app=appRef.current;if(!app||!modelVersion)return; const app=appRef.current;if(!app||!modelVersion)return;
let time=0;const motion=window.matchMedia('(prefers-reduced-motion: reduce)'); let time=0;const motion=window.matchMedia('(prefers-reduced-motion: reduce)');
const update=(dt:number)=>{const live=latest.current;if(live.chargeState?.fresh&&!motion.matches)time+=Math.min(dt,.1);for(const [id,material] of animated.current){const gradient=live.materials?.[id]?.chargeGradient;if(gradient?.enabled)updateChargeMaterial(material,gradient,live.chargeState,time,live.materials![id]);}}; const update=(dt:number)=>{const live=latest.current;if(live.chargeState?.fresh&&!motion.matches)time+=Math.min(dt,.1);for(const [id,material] of animated.current){const gradient=live.materials?.[id]?.chargeGradient;if(gradient)updateChargeMaterial(material,gradient,previewChargeState(live.chargeState,live.materialPreview?.id===id?live.materialPreview:undefined),time,live.materials![id],bindings.current.get(id));}};
app.on('update',update);return()=>{app.off('update',update);}; app.on('update',update);return()=>{app.off('update',update);};
},[appRef,modelVersion]); },[appRef,modelVersion]);
useEffect(()=>()=>{generation.current=-1;for(const item of textures.current.values())item.texture?.destroy();textures.current.clear();for(const m of customMaterials.current.values())m.destroy();customMaterials.current.clear();},[]); useEffect(()=>()=>{generation.current=-1;for(const item of textures.current.values())item.texture?.destroy();textures.current.clear();for(const m of customMaterials.current.values())m.destroy();customMaterials.current.clear();},[]);
@@ -1,6 +1,6 @@
.nodedc-icon-button > .rover-dev-label {color:inherit;font-size:var(--nodedc-font-size-xs);font-weight:var(--nodedc-font-weight-medium);} .nodedc-icon-button > .rover-dev-label {color:inherit;font-size:var(--nodedc-font-size-xs);font-weight:var(--nodedc-font-weight-medium);}
.rover-logs {height:100%;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:var(--nodedc-space-2);padding:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)) var(--nodedc-space-3) var(--nodedc-space-3);} .rover-logs {height:100%;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:var(--nodedc-space-2);padding:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)) var(--nodedc-space-3) var(--nodedc-space-3);}
.rover-logs > p {margin:0;font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-secondary);overflow-wrap:anywhere;} .rover-logs > p {margin:0;font-size:var(--nodedc-font-size-sm);color:var(--nodedc-text-secondary);overflow-wrap:anywhere;}
.rover-logs__entries {flex:1;min-height:0;overflow:auto;} .rover-logs__entries {flex:1;min-height:0;overflow:auto;}
.rover-logs__entries pre {white-space:pre-wrap;overflow-wrap:anywhere;font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-primary);} .rover-logs__entries pre {white-space:pre-wrap;overflow-wrap:anywhere;font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-primary);}
@@ -1,12 +1,13 @@
import type {SceneView} from "../../core/simulation/simulationLayout"; import type {SceneView} from "../../core/simulation/simulationLayout";
import {isOrthographic,screenSpan,type EditorProjection} from "../../core/simulation/editorProjection"; import {isOrthographic,screenSpan,type EditorProjection} from "../../core/simulation/editorProjection";
import { sceneClipBounds } from "../../core/simulation/sceneClip"; import { heightSlice } from "../../core/heightSlice";
import { sceneClipBounds, sceneClipRange } from "../../core/simulation/sceneClip";
import { EditorUrbanMapLayer } from "./EditorUrbanMapLayer"; import { EditorUrbanMapLayer } from "./EditorUrbanMapLayer";
import { urbanExtent, type UrbanMap, type UrbanClassId } from "../../core/simulation/urbanMap"; import { urbanExtent, type UrbanMap, type UrbanClassId } from "../../core/simulation/urbanMap";
import { EditorCollisionLayer } from "./EditorCollisionLayer"; import { EditorCollisionLayer } from "./EditorCollisionLayer";
import { waypointHit } from "../../core/simulation/waypointHit"; import { waypointHit } from "../../core/simulation/waypointHit";
import { PlannerMarkers } from "./PlannerMarkers"; import { PlannerMarkers } from "./PlannerMarkers";
import { QUALITY_PROFILES } from "../../core/simulation/gaussianQuality"; import { QUALITY_PROFILES, orthographicLodFov } from "../../core/simulation/gaussianQuality";
import { DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences"; import { DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
import { Application, Asset, BoundingBox, Color, Entity, FILLMODE_NONE, Mat4, Quat, PROJECTION_ORTHOGRAPHIC, PROJECTION_PERSPECTIVE, RESOLUTION_AUTO, Vec3, WORKBUFFER_UPDATE_ONCE } from "playcanvas"; import { Application, Asset, BoundingBox, Color, Entity, FILLMODE_NONE, Mat4, Quat, PROJECTION_ORTHOGRAPHIC, PROJECTION_PERSPECTIVE, RESOLUTION_AUTO, Vec3, WORKBUFFER_UPDATE_ONCE } from "playcanvas";
import { toEditor, toMission, type EditorCache } from "../../core/simulation/aiEditor"; import { toEditor, toMission, type EditorCache } from "../../core/simulation/aiEditor";
@@ -37,6 +38,7 @@ export class AiEditorRuntime {
private semanticProject: (()=>void)|null = null; private semanticProject: (()=>void)|null = null;
private visualBounds:number[][]=[]; private visualBounds:number[][]=[];
private urbanVisible=false; private urbanVisible=false;
private semanticMode=false;
private experienceLayer: EditorUrbanMapLayer | null = null; private experienceLayer: EditorUrbanMapLayer | null = null;
private experiencePoints: number[][] = []; private experiencePoints: number[][] = [];
private onExperienceProject: (p: ScreenPoint[])=>void = ()=>undefined; private onExperienceProject: (p: ScreenPoint[])=>void = ()=>undefined;
@@ -130,11 +132,14 @@ export class AiEditorRuntime {
this.scan.gsplat!.setWorkBufferModifier({ glsl: ` this.scan.gsplat!.setWorkBufferModifier({ glsl: `
uniform float editorClip; uniform float editorClip;
uniform float editorFloor; uniform float editorFloor;
uniform float editorClipEnabled;
uniform float editorFloorEnabled;
void modifySplatCenter(inout vec3 center) {} void modifySplatCenter(inout vec3 center) {}
void modifySplatRotationScale(vec3 a, vec3 b, inout vec4 rotation, inout vec3 scale) {} void modifySplatRotationScale(vec3 a, vec3 b, inout vec4 rotation, inout vec3 scale) {}
void modifySplatColor(vec3 center, inout vec4 color) { void modifySplatColor(vec3 center, inout vec4 color) {
// Unified work-buffer modifiers receive the calibrated world center. // Unified work-buffer modifiers receive the calibrated world center.
if (center.y > editorClip || center.y < editorFloor) color.a = 0.0; if ((editorClipEnabled > 0.5 && center.y > editorClip) ||
(editorFloorEnabled > 0.5 && center.y < editorFloor)) color.a = 0.0;
}` }); }` });
this.setPreferences(this.preferences); this.setPreferences(this.preferences);
if (terrain.isEmpty()) this.controls.sceneCenter.set(bounds.center.x,bounds.center.y,bounds.center.z); if (terrain.isEmpty()) this.controls.sceneCenter.set(bounds.center.x,bounds.center.y,bounds.center.z);
@@ -151,10 +156,10 @@ export class AiEditorRuntime {
setUrbanMap(document: UrbanMap) { setUrbanMap(document: UrbanMap) {
this.urbanBounds=urbanExtent(document); this.urbanBounds=urbanExtent(document);
this.urbanLayer?.dispose(); this.urbanLayer?.dispose();
this.urbanLayer=new EditorUrbanMapLayer(this.app,this.camera,document);this.urbanLayer.setClip(this.clip,this.clipFloor);this.urbanLayer.setVisible(this.urbanVisible);this.dirty=true; this.urbanLayer=new EditorUrbanMapLayer(this.app,this.camera,document);this.urbanLayer.setClip(this.clip,this.clipFloor);this.urbanLayer.setVisible(this.semanticMode&&this.urbanVisible);this.dirty=true;
} }
snapshotView():SceneView{return {...this.controls.snapshot(),clip:[Number.isFinite(this.clipFloor)?this.clipFloor:null,Number.isFinite(this.clip)?this.clip:null]};} snapshotView():SceneView{return {...this.controls.snapshot(),clip:[Number.isFinite(this.clipFloor)?this.clipFloor:null,Number.isFinite(this.clip)?this.clip:null]};}
restoreView(view:SceneView){this.setClip(view.clip[1]??Infinity,view.clip[0]??-Infinity);this.controls.restore(view);this.syncCamera();this.dirty=true;} restoreView(view:SceneView){const [floor,ceiling]=sceneClipRange(view.clip,this.height);this.setClip(ceiling,floor);this.controls.restore(view);this.syncCamera();this.dirty=true;}
watchCamera(callback:((q:[number,number,number,number])=>void)|null) {this.cameraProject=callback;this.dirty=true;} watchCamera(callback:((q:[number,number,number,number])=>void)|null) {this.cameraProject=callback;this.dirty=true;}
setProjection(mode:EditorProjection){this.surfacePicker.invalidate();this.controls.setProjection(mode);this.syncCamera();this.dirty=true;} setProjection(mode:EditorProjection){this.surfacePicker.invalidate();this.controls.setProjection(mode);this.syncCamera();this.dirty=true;}
view(direction:number[]){this.surfacePicker.invalidate();this.controls.view(direction);this.syncCamera();this.dirty=true;} view(direction:number[]){this.surfacePicker.invalidate();this.controls.view(direction);this.syncCamera();this.dirty=true;}
@@ -202,7 +207,8 @@ export class AiEditorRuntime {
return q[2]>=this.clipFloor&&q[2]<=this.clip?q:null; return q[2]>=this.clipFloor&&q[2]<=this.clip?q:null;
} }
setUrbanClasses(selected:readonly UrbanClassId[]) {this.urbanLayer?.setClasses(selected);this.dirty=true;} setUrbanClasses(selected:readonly UrbanClassId[]) {this.urbanLayer?.setClasses(selected);this.dirty=true;}
showUrbanMap(visible: boolean) { this.urbanVisible=visible;this.urbanLayer?.setVisible(visible);this.dirty=true; } setSemanticMode(active: boolean) { this.semanticMode=active;this.urbanLayer?.setVisible(active&&this.urbanVisible);this.dirty=true; }
showUrbanMap(visible: boolean) { this.urbanVisible=visible;this.urbanLayer?.setVisible(this.semanticMode&&visible);this.dirty=true; }
setSceneLayers({gaussian,collision}:{gaussian:boolean;collision:boolean}) { setSceneLayers({gaussian,collision}:{gaussian:boolean;collision:boolean}) {
this.surfacePicker.invalidate();this.controls.invalidateSurface();this.collisionVisible=collision; this.surfacePicker.invalidate();this.controls.invalidateSurface();this.collisionVisible=collision;
if (collision && !this.collisionLayer && !this.terrain.bounds.isEmpty()) { if (collision && !this.collisionLayer && !this.terrain.bounds.isEmpty()) {
@@ -229,13 +235,17 @@ export class AiEditorRuntime {
this.app.resizeCanvas(this.canvas.clientWidth,this.canvas.clientHeight);this.dirty=true; this.app.resizeCanvas(this.canvas.clientWidth,this.canvas.clientHeight);this.dirty=true;
} }
setClip(height: number, floor = -Infinity) { setClip(height: number, floor = -Infinity) {
const slice=heightSlice(sceneClipRange([floor,height],this.height),this.height);
height=slice.ceiling??Infinity;floor=slice.floor??-Infinity;
this.surfacePicker.invalidate();this.controls.invalidateSurface(); this.surfacePicker.invalidate();this.controls.invalidateSurface();
this.clip = height; this.clipFloor = floor; this.clip = height; this.clipFloor = floor;
this.collisionLayer?.setClip(height,floor); this.collisionLayer?.setClip(height,floor);
this.urbanLayer?.setClip(height,floor);this.experienceLayer?.setClip(height,floor); this.urbanLayer?.setClip(height,floor);this.experienceLayer?.setClip(height,floor);
if (this.scan.gsplat) { if (this.scan.gsplat) {
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 1e9); this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 0);
this.scan.gsplat.setParameter("editorFloor", Number.isFinite(floor) ? floor : -1e9); this.scan.gsplat.setParameter("editorFloor", Number.isFinite(floor) ? floor : 0);
this.scan.gsplat.setParameter("editorClipEnabled", Number.isFinite(height) ? 1 : 0);
this.scan.gsplat.setParameter("editorFloorEnabled", Number.isFinite(floor) ? 1 : 0);
this.scan.gsplat.workBufferUpdate = WORKBUFFER_UPDATE_ONCE; this.scan.gsplat.workBufferUpdate = WORKBUFFER_UPDATE_ONCE;
} }
this.dirty = true; this.dirty = true;
@@ -248,7 +258,10 @@ export class AiEditorRuntime {
private syncCamera() { private syncCamera() {
const c=this.controls.camera; const c=this.controls.camera;
this.camera.camera!.projection=isOrthographic(c)?PROJECTION_ORTHOGRAPHIC:PROJECTION_PERSPECTIVE; this.camera.camera!.projection=isOrthographic(c)?PROJECTION_ORTHOGRAPHIC:PROJECTION_PERSPECTIVE;
if(isOrthographic(c))this.camera.camera!.orthoHeight=c.top; if(isOrthographic(c)){
this.camera.camera!.orthoHeight=screenSpan(c,1)/2;
this.camera.camera!.fov=orthographicLodFov(screenSpan(c,1)/2,this.controls.focusDepth);
}else this.camera.camera!.fov=c.fov;
const { position:p, quaternion:q } = c; const { position:p, quaternion:q } = c;
this.camera.setPosition(p.x,p.y,p.z); this.camera.setRotation(q.x,q.y,q.z,q.w); this.camera.setPosition(p.x,p.y,p.z); this.camera.setRotation(q.x,q.y,q.z,q.w);
} }
@@ -23,7 +23,7 @@ export function AiInferencePreview({preview,layer}:{preview:InferencePreview;lay
{selected.kind==="points3d"?<Suspense fallback={<LoadingRegion loading label="Открываем 3D"/>}> {selected.kind==="points3d"?<Suspense fallback={<LoadingRegion loading label="Открываем 3D"/>}>
<SpatialPreview points={selected.points} label={selected.label}/> <SpatialPreview points={selected.points} label={selected.label}/>
</Suspense>:<img src={`data:image/jpeg;base64,${selected.jpeg}`} alt={`${selected.label}, кадр ${preview.frame_id}`}/>} </Suspense>:<img src={`data:image/jpeg;base64,${selected.jpeg}`} alt={`${selected.label}, кадр ${preview.frame_id}`}/>}
<div className="ai-inference-preview__caption"> <div data-glass-context="scene" className="ai-inference-preview__caption nodedc-viewport-surface">
Кадр {preview.frame_id} · Время мира {(preview.simulation_time_ns/1e9).toFixed(1)} с Кадр {preview.frame_id} · Время мира {(preview.simulation_time_ns/1e9).toFixed(1)} с
{selected.legend?.length?<span className="ai-inference-preview__legend">{selected.legend.map(c=><span key={c.class_id}><i style={{background:c.color}}/>{c.label}</span>)}</span>:null} {selected.legend?.length?<span className="ai-inference-preview__legend">{selected.legend.map(c=><span key={c.class_id}><i style={{background:c.color}}/>{c.label}</span>)}</span>:null}
{selected.kind==="points3d"?<span>{selected.points.length} из {selected.source_count} точек · Система координат ровера · метры</span>:null} {selected.kind==="points3d"?<span>{selected.points.length} из {selected.source_count} точек · Система координат ровера · метры</span>:null}
@@ -1,11 +1,11 @@
import {getSimulationLayout,readSceneView,writeSceneView,useSimulationLayout} from "./useSimulationLayout"; import {getSimulationLayout,readSceneView,writeSceneView,useSimulationLayout} from "./useSimulationLayout";
import {PlannerCameraTools} from "./PlannerCameraTools"; import {PlannerCameraTools} from "./PlannerCameraTools";
import { heightSlice } from "../../core/heightSlice"; import { sceneClipRange, sceneClipLabel } from "../../core/simulation/sceneClip";
import { InfrastructureAnalysis } from "./InfrastructureAnalysis"; import { InfrastructureAnalysis } from "./InfrastructureAnalysis";
import { PlannerLegend } from "./PlannerLegend"; import { PlannerLegend } from "./PlannerLegend";
import { SemanticEditor } from "./SemanticEditor"; import { SemanticEditor } from "./SemanticEditor";
import { PlannerExperience } from "./PlannerExperience"; import { PlannerExperience } from "./PlannerExperience";
import { loadUrbanMap, type UrbanClassId, type UrbanMap } from "../../core/simulation/urbanMap"; import { loadUrbanMap, type UrbanMap } from "../../core/simulation/urbanMap";
import type { PreparedRoute } from "../../core/simulation/routePreparation"; import type { PreparedRoute } from "../../core/simulation/routePreparation";
import type { ScreenPoint } from "../../core/simulation/aiPolygon"; import type { ScreenPoint } from "../../core/simulation/aiPolygon";
import { editWaypoints, waypointEditing, waypointShortcut } from "../../core/simulation/waypointEditing"; import { editWaypoints, waypointEditing, waypointShortcut } from "../../core/simulation/waypointEditing";
@@ -13,7 +13,7 @@ import { SimulationViewTools } from "./SimulationViewTools";
import { usePlannerPreferences } from "./usePlannerPreferences"; import { usePlannerPreferences } from "./usePlannerPreferences";
import { useEffect, useReducer, useRef, useState } from "react"; import { useEffect, useReducer, useRef, useState } from "react";
import { createPortal } from "react-dom"; import { createPortal } from "react-dom";
import { Button, FieldFrame, Icon, IconButton, LoadingRegion, RangeControl, Select, SegmentedControl, SegmentedGroup, SegmentedButton, StatusBadge } from "@nodedc/ui-react"; import { Description, Button, FieldFrame, Icon, IconButton, LoadingRegion, RangeControl, Select, SegmentedControl, SegmentedGroup, SegmentedButton, StatusBadge } from "@nodedc/ui-react";
import { type EditorCache } from "../../core/simulation/aiEditor"; import { type EditorCache } from "../../core/simulation/aiEditor";
import type { AiWaypoint, AiWorld } from "../../core/simulation/aiPolygon"; import type { AiWaypoint, AiWorld } from "../../core/simulation/aiPolygon";
import { AiEditorRuntime, type EditorMarker } from "./AiEditorRuntime"; import { AiEditorRuntime, type EditorMarker } from "./AiEditorRuntime";
@@ -23,11 +23,11 @@ import { useSimulationFullscreen } from "./useSimulationFullscreen";
export interface LocalDraft { cache: EditorCache; points: AiWaypoint[]; id: string; sequence: number } export interface LocalDraft { cache: EditorCache; points: AiWaypoint[]; id: string; sequence: number }
export type LocationMode = "view" | "semantic" | "planning"; export type LocationMode = "view" | "semantic" | "planning";
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, routeActions, sceneMode, onSceneMode, busy=false, preparedRoute=null }: { export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, routeActions, sceneMode, onSceneMode, onBack, busy=false, preparedRoute=null }: {
world: AiWorld; initialPoints: AiWaypoint[]; onDraft: (draft: LocalDraft | null) => void; world: AiWorld; initialPoints: AiWaypoint[]; onDraft: (draft: LocalDraft | null) => void;
actionsHost: HTMLElement | null; headerActions: React.ReactNode; actionsHost: HTMLElement | null; headerActions: React.ReactNode;
routeActionsHost: HTMLElement | null; routeActions: React.ReactNode; busy?: boolean; preparedRoute?:PreparedRoute|null; routeActionsHost: HTMLElement | null; routeActions: React.ReactNode; busy?: boolean; preparedRoute?:PreparedRoute|null;
sceneMode:LocationMode; onSceneMode:(mode:LocationMode)=>void; sceneMode:LocationMode; onSceneMode:(mode:LocationMode)=>void; onBack:()=>void;
}) { }) {
const [semanticHeader,setSemanticHeader]=useState<HTMLSpanElement|null>(null); const [semanticHeader,setSemanticHeader]=useState<HTMLSpanElement|null>(null);
const markerSvg=useRef<SVGSVGElement>(null); const markerSvg=useRef<SVGSVGElement>(null);
@@ -46,10 +46,7 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
const sceneLayers=layout.sceneLayers,setSceneLayers=(sceneLayers:typeof layout.sceneLayers)=>updateLayout({sceneLayers}); const sceneLayers=layout.sceneLayers,setSceneLayers=(sceneLayers:typeof layout.sceneLayers)=>updateLayout({sceneLayers});
const [urbanMap,setUrbanMap]=useState<UrbanMap|null>(null); const [urbanMap,setUrbanMap]=useState<UrbanMap|null>(null);
const semantic=sceneMode==="semantic", planning=sceneMode==="planning"; const semantic=sceneMode==="semantic", planning=sceneMode==="planning";
const urbanVisible=layout.infrastructure,setUrbanVisible=(infrastructure:boolean)=>updateLayout({infrastructure});
const urbanClasses=layout.urbanLayers,setUrbanClasses=(urbanLayers:UrbanClassId[])=>updateLayout({urbanLayers});
const [memoryVisible,setMemoryVisible]=useState(false); const [memoryVisible,setMemoryVisible]=useState(false);
const [urbanError,setUrbanError]=useState<string|null>(null);
const [markers, setMarkers] = useState<EditorMarker[]>([]); const [markers, setMarkers] = useState<EditorMarker[]>([]);
const [mode,setMode] = useState<"view" | "add">("view"); const [mode,setMode] = useState<"view" | "add">("view");
const [clip,setClip] = useState<[number,number]|null>(null); const [clip,setClip] = useState<[number,number]|null>(null);
@@ -62,7 +59,7 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
const sceneKey=cache.world.sha256!,remember=()=>{if(loaded&&runtime.current)writeSceneView(sceneKey,runtime.current.snapshotView());}; const sceneKey=cache.world.sha256!,remember=()=>{if(loaded&&runtime.current)writeSceneView(sceneKey,runtime.current.snapshotView());};
const timer=window.setInterval(remember,1500);window.addEventListener("pagehide",remember); const timer=window.setInterval(remember,1500);window.addEventListener("pagehide",remember);
const abort=new AbortController(); const abort=new AbortController();
setUrbanMap(null);setUrbanError(null); setUrbanMap(null);
setReady(false); setError(null); setClip(null); setReady(false); setError(null); setClip(null);
let view: AiEditorRuntime; let view: AiEditorRuntime;
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers,setRouteProjection); } try { view = new AiEditorRuntime(canvas.current,cache,setMarkers,setRouteProjection); }
@@ -71,12 +68,12 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
view.setPreferences(preferences);view.setPoints(initialPoints); view.home(); view.setPreferences(preferences);view.setPoints(initialPoints); view.home();
void view.load().then(() => { if (active) { void view.load().then(() => { if (active) {
const remembered=readSceneView(sceneKey),settings=getSimulationLayout(); const remembered=readSceneView(sceneKey),settings=getSimulationLayout();
if(remembered){view.restoreView(remembered);setClip([remembered.clip[0]??view.height[0],remembered.clip[1]??view.height[1]]);} if(remembered){view.restoreView(remembered);setClip(sceneClipRange(view.snapshotView().clip,view.height));}
view.setProjection(settings.projection);view.setSceneLayers(settings.sceneLayers); view.setProjection(settings.projection);view.setSceneLayers(settings.sceneLayers);
loaded=true;setReady(true); loaded=true;setReady(true);
void loadUrbanMap(cache.world.world_id,cache.world.sha256!,abort.signal).then(map=>{ void loadUrbanMap(cache.world.world_id,cache.world.sha256!,abort.signal).then(map=>{
if(active && map){view.setUrbanMap(map);setUrbanMap(map);} if(active && map){view.setUrbanMap(map);setUrbanMap(map);}
}).catch((e:Error)=>{if(active)setUrbanError(e.message);}); }).catch((e:Error)=>{if(active)setError(e.message);});
} }).catch((e: Error) => { if (active) setError(e.message); }); } }).catch((e: Error) => { if (active) setError(e.message); });
return () => { remember();clearInterval(timer);window.removeEventListener("pagehide",remember);active=false; abort.abort(); runtime.current=null; view.dispose(); callback.current(null); }; return () => { remember();clearInterval(timer);window.removeEventListener("pagehide",remember);active=false; abort.abort(); runtime.current=null; view.dispose(); callback.current(null); };
}, [cache?.key,cache?.status,retry]); }, [cache?.key,cache?.status,retry]);
@@ -85,8 +82,8 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
if (cache?.status === "ready" && ready) callback.current({ cache,points,id:draftId.current,sequence }); if (cache?.status === "ready" && ready) callback.current({ cache,points,id:draftId.current,sequence });
}, [points,cache,ready,sequence,planning]); }, [points,cache,ready,sequence,planning]);
useEffect(()=>{ useEffect(()=>{
if(!semantic&&urbanMap){runtime.current?.setUrbanMap(urbanMap);runtime.current?.setUrbanClasses(urbanClasses);runtime.current?.showUrbanMap(urbanVisible);} runtime.current?.setSemanticMode(semantic);
},[semantic,urbanMap,urbanVisible,urbanClasses]); },[semantic,ready]);
useEffect(()=>{ useEffect(()=>{
runtime.current?.setRoute(planning?preparedRoute?.preview_xyz??[]:[]); runtime.current?.setRoute(planning?preparedRoute?.preview_xyz??[]:[]);
@@ -95,8 +92,6 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
setMode("view");press.current=null;runtime.current?.setAddMode(false); setMode("view");press.current=null;runtime.current?.setAddMode(false);
if(drag.current){edit({type:"cancel"});drag.current=null;runtime.current?.setNavigation(!busy);} if(drag.current){edit({type:"cancel"});drag.current=null;runtime.current?.setNavigation(!busy);}
},[sceneMode,ready]); },[sceneMode,ready]);
// SemanticEditor owns both the edited map and its layer mask in semantic mode.
useEffect(()=>{if(!semantic)runtime.current?.setUrbanClasses(urbanClasses);},[semantic,urbanClasses,urbanMap,ready]);
useEffect(()=>{if(ready)try{runtime.current?.setSceneLayers(sceneLayers);}catch(e){setError((e as Error).message);}},[sceneLayers,ready]); useEffect(()=>{if(ready)try{runtime.current?.setSceneLayers(sceneLayers);}catch(e){setError((e as Error).message);}},[sceneLayers,ready]);
useEffect(()=>{runtime.current?.setPreferences(preferences);},[preferences,ready]); useEffect(()=>{runtime.current?.setPreferences(preferences);},[preferences,ready]);
useEffect(()=>{runtime.current?.setSelected(selected);},[selected,ready]); useEffect(()=>{runtime.current?.setSelected(selected);},[selected,ready]);
@@ -123,12 +118,20 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
: cache?.status === "ready" ? "Открываем локальную сцену" : "Готовим локальную копию сцены"; : cache?.status === "ready" ? "Открываем локальную сцену" : "Готовим локальную копию сцены";
const modeLabels={view:"Просмотр",semantic:"Семантика",planning:"Планирование миссии"}; const modeLabels={view:"Просмотр",semantic:"Семантика",planning:"Планирование миссии"};
const infrastructure=semantic?<InfrastructureAnalysis worldId={world.world_id} worldSha={world.sha256!} busy={busy} hasMap={!!urbanMap} const infrastructure=semantic?<InfrastructureAnalysis worldId={world.world_id} worldSha={world.sha256!} busy={busy} hasMap={!!urbanMap}
onMap={map=>{setUrbanMap(map);runtime.current?.setUrbanMap(map);runtime.current?.showUrbanMap(true);setUrbanError(null);}}/>:null; onMap={map=>{setUrbanMap(map);runtime.current?.setUrbanMap(map);runtime.current?.showUrbanMap(true);setError(null);}}/>:null;
const header=<>{planning?<FieldFrame label="Выбор задания" labelPlacement="below" className="ai-polygon__task-field">{headerActions}</FieldFrame>:null} const header=<div className="ai-polygon__scene-actions">
<FieldFrame label="Режим" labelPlacement="below" className="ai-polygon__mode-field"> <div className="ai-polygon__context-actions">
<Select label="Режим" value={sceneMode} onChange={onSceneMode} disabled={busy} {planning?<FieldFrame label="Выбор задания" labelPlacement="below" className="ai-polygon__task-field">{headerActions}</FieldFrame>:null}
options={([{value:"view",label:modeLabels.view},{value:"semantic",label:modeLabels.semantic},{value:"planning",label:modeLabels.planning}] as const).map(o=>({...o}))}/> {infrastructure}{semantic?<span className="ai-polygon__semantic-actions" ref={setSemanticHeader}/>:null}{planning?routeActions:null}
</FieldFrame>{infrastructure}{semantic?<span className="ai-polygon__semantic-actions" ref={setSemanticHeader}/>:null}{planning?routeActions:null}</>; </div>
<div className="ai-polygon__mode-actions">
<FieldFrame label="Режим" labelPlacement="below" className="ai-polygon__mode-field">
<Select label="Режим" value={sceneMode} onChange={onSceneMode} disabled={busy}
options={([{value:"view",label:modeLabels.view},{value:"semantic",label:modeLabels.semantic},{value:"planning",label:modeLabels.planning}] as const).map(o=>({...o}))}/>
</FieldFrame>
<IconButton label="Назад к локациям" disabled={busy} onClick={onBack}><Icon name="chevron-left"/></IconButton>
</div>
</div>;
return <div className="ai-polygon__stage" ref={host}> return <div className="ai-polygon__stage" ref={host}>
{expanded ? <> {expanded ? <>
<div className="ai-polygon__actions ai-polygon__planner-actions">{header}</div> <div className="ai-polygon__actions ai-polygon__planner-actions">{header}</div>
@@ -137,8 +140,7 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
</>} </>}
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local"> <div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
<StatusBadge tone={ready ? "success" : "neutral"}>{ready ? modeLabels[sceneMode] : message}</StatusBadge> <StatusBadge tone={ready ? "success" : "neutral"}>{ready ? modeLabels[sceneMode] : message}</StatusBadge>
{planning?<p>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</p>:null} {planning?<Description>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</Description>:null}
{!semantic && urbanVisible && urbanMap ? <p>Инфраструктура · {urbanMap.coverage.kind === "objects-only" ? `${urbanMap.schema_version === "missioncore.urban-map/v3" ? "по скану" : urbanMap.analysis?.scope === "whole-scene" ? `обследовано ${urbanMap.analysis.tiles_total} участков · данные в ${urbanMap.analysis.tiles_mapped}` : "участок"} · ${urbanMap.features.length} объектов · распознано автоматически` : `${(urbanMap.coverage.accepted_cells * urbanMap.coverage.cell_m ** 2).toFixed(0)} м² · неполное покрытие`}</p> : null}
</div> </div>
<div className="ai-polygon__viewer"> <div className="ai-polygon__viewer">
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()} <div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}
@@ -158,13 +160,10 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
}}><Icon name="trash"/></IconButton>:null} }}><Icon name="trash"/></IconButton>:null}
</div> </div>
<SegmentedGroup label="Слои сцены" className="ai-local-editor__layers"> <SegmentedGroup label="Слои сцены" className="ai-local-editor__layers">
{!semantic&&urbanMap?<SegmentedButton title={urbanError??"Карта дорожной инфраструктуры"}
active={urbanVisible} aria-pressed={urbanVisible}
onClick={()=>{const visible=!urbanVisible;setUrbanVisible(visible);runtime.current?.showUrbanMap(visible);}}>Инфраструктура</SegmentedButton>:null}
{(["gaussian","collision"] as const).map(key=><SegmentedButton key={key} active={sceneLayers[key]} aria-pressed={sceneLayers[key]} {(["gaussian","collision"] as const).map(key=><SegmentedButton key={key} active={sceneLayers[key]} aria-pressed={sceneLayers[key]}
onClick={()=>{try {const next={...sceneLayers,[key]:!sceneLayers[key]};runtime.current?.setSceneLayers(next);setSceneLayers(next);setError(null);} onClick={()=>{try {const next={...sceneLayers,[key]:!sceneLayers[key]};runtime.current?.setSceneLayers(next);setSceneLayers(next);setError(null);}
catch(e){setError(e instanceof Error?e.message:"Не удалось показать слой коллизий.");}}}>{key==="gaussian"?"Gaussian":"Коллизии"}</SegmentedButton>)} catch(e){setError(e instanceof Error?e.message:"Не удалось показать слой коллизий.");}}}>{key==="gaussian"?"Gaussian":"Коллизии"}</SegmentedButton>)}
{runtime.current && viewport.current ? <PlannerExperience worldId={world.world_id} worldSha={world.sha256!} {sceneMode!=="view" && runtime.current && viewport.current ? <PlannerExperience worldId={world.world_id} worldSha={world.sha256!}
runtime={runtime.current} viewport={viewport.current} onVisibilityChange={setMemoryVisible}/> : null} runtime={runtime.current} viewport={viewport.current} onVisibilityChange={setMemoryVisible}/> : null}
</SegmentedGroup> </SegmentedGroup>
{urbanMap&&urbanMap.schema_version!=="missioncore.urban-map/v1"&&runtime.current&&viewport.current?<SemanticEditor key={world.sha256} worldId={world.world_id} worldSha={world.sha256!} {urbanMap&&urbanMap.schema_version!=="missioncore.urban-map/v1"&&runtime.current&&viewport.current?<SemanticEditor key={world.sha256} worldId={world.world_id} worldSha={world.sha256!}
@@ -223,15 +222,15 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
<text x={m[axis]![0]*1280+16} y={m[axis]![1]*720-12}>{axis.toUpperCase()}</text></g>:null):null} <text x={m[axis]![0]*1280+16} y={m[axis]![1]*720-12}>{axis.toUpperCase()}</text></g>:null):null}
</g>:null)} </g>:null)}
</svg></div> </svg></div>
{!semantic?<PlannerLegend map={urbanVisible?urbanMap:null} memory={memoryVisible} {planning?<PlannerLegend map={null} memory={memoryVisible}
selected={urbanClasses} onChange={setUrbanClasses} disabled={busy}/>:null} selected={[]} onChange={()=>undefined} disabled={busy}/>:null}
{!ready && !error ? <LoadingRegion className="ai-local-editor__loading" loading label={message} />:null} {!ready && !error ? <LoadingRegion className="ai-local-editor__loading" loading label={message} />:null}
{ready ? <><div className="ai-route__height"><RangeControl orientation="vertical" limitSide="right" label="Срез" {ready ? <><div className="ai-route__height"><RangeControl orientation="vertical" limitSide="right" label="Срез"
min={runtime.current!.height[0]} max={runtime.current!.height[1]} step="any" value={clip??runtime.current!.height} min={runtime.current!.height[0]} max={runtime.current!.height[1]} step="any" value={clip??runtime.current!.height}
formatValue={(v)=>`${v.toFixed(1)} м`} formatLimit={(v)=>v.toFixed(1)} formatValue={(v)=>sceneClipLabel(v,runtime.current!.height)} formatLimit={(v)=>sceneClipLabel(v,runtime.current!.height)}
onChange={(v)=>{const next=heightSlice(v,runtime.current!.height);setClip(v);runtime.current!.setClip(next.ceiling??Infinity,next.floor??-Infinity);}}/></div> onChange={(v)=>{const view=runtime.current!;view.setClip(v[1],v[0]);setClip(sceneClipRange(view.snapshotView().clip,view.height));}}/></div>
{error?<div className="ai-route__tools"><p role="alert">{error}</p></div>:null}</>:null} {error?<div className="ai-route__tools"><Description role="alert">{error}</Description></div>:null}</>:null}
{error && !ready ? <div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>setRetry(retry+1)}>Повторить загрузку</Button></div>:null} {error && !ready ? <div className="ai-polygon__preview-error"><Description role="alert">{error}</Description><Button onClick={()=>setRetry(retry+1)}>Повторить загрузку</Button></div>:null}
</div> </div>
</div> </div>
</div>; </div>;
@@ -1,6 +1,6 @@
import { useState } from "react"; import { useState } from "react";
import { useInfrastructureQueue } from "../../core/simulation/infrastructureAnalysis"; import { useInfrastructureQueue } from "../../core/simulation/infrastructureAnalysis";
import { Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow, import { Description, Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow,
StatusBadge, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react"; StatusBadge, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
import { updateAiWorld, type AiWorld } from "../../core/simulation/aiPolygon"; import { updateAiWorld, type AiWorld } from "../../core/simulation/aiPolygon";
@@ -61,7 +61,7 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
</WindowFooterActions>}> </WindowFooterActions>}>
<TextField label="Название локации" value={name} maxLength={120} disabled={!!busy} <TextField label="Название локации" value={name} maxLength={120} disabled={!!busy}
onChange={event => setName(event.target.value)}/> onChange={event => setName(event.target.value)}/>
{editing?.world_id === activeWorldId ? <p>Удаление станет доступно после завершения симуляции.</p> : null} {editing?.world_id === activeWorldId ? <Description>Удаление станет доступно после завершения симуляции.</Description> : null}
</Window> </Window>
<ConfirmationModal open={!!editing && confirming} title="Удалить локацию?" danger <ConfirmationModal open={!!editing && confirming} title="Удалить локацию?" danger
description={<>«{editing?.name}» исчезнет из доступных локаций. Исходный скан, разметка и задания сохранятся. description={<>«{editing?.name}» исчезнет из доступных локаций. Исходный скан, разметка и задания сохранятся.
@@ -1,4 +1,4 @@
import { Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react"; import { Description, Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
export function AiPlanSaveWindow({name,onName,busy,launch,onClose,onSave,error}: { export function AiPlanSaveWindow({name,onName,busy,launch,onClose,onSave,error}: {
error:string|null;name:string;onName:(name:string)=>void;busy:boolean;launch:boolean; error:string|null;name:string;onName:(name:string)=>void;busy:boolean;launch:boolean;
@@ -9,9 +9,9 @@ export function AiPlanSaveWindow({name,onName,busy,launch,onClose,onSave,error}:
footer={<WindowFooterActions><Button variant="primary" loading={busy} disabled={!name.trim()} footer={<WindowFooterActions><Button variant="primary" loading={busy} disabled={!name.trim()}
onClick={onSave}>{launch?"Сохранить и запустить":"Сохранить"}</Button></WindowFooterActions>}> onClick={onSave}>{launch?"Сохранить и запустить":"Сохранить"}</Button></WindowFooterActions>}>
<div className="ai-polygon__form"> <div className="ai-polygon__form">
{error?<p role="alert">{error}</p>:null} {error?<Description role="alert">{error}</Description>:null}
<TextField label="Название задания" value={name} maxLength={120} disabled={busy} onChange={(e)=>onName(e.target.value)}/> <TextField label="Название задания" value={name} maxLength={120} disabled={busy} onChange={(e)=>onName(e.target.value)}/>
<p>Сохраняются текущие точки маршрута и выбранный ровер. Задание появится в списке над сценой.</p> <Description>Сохраняются текущие точки маршрута и выбранный ровер. Задание появится в списке над сценой.</Description>
</div> </div>
</Window>; </Window>;
} }
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState, type PointerEvent } from "react"; import { useEffect, useRef, useState, type PointerEvent } from "react";
import { Button, RangeControl, SegmentedControl } from "@nodedc/ui-react"; import { Description, Button, RangeControl, SegmentedControl } from "@nodedc/ui-react";
import { type AiRun, type ScreenPoint } from "../../core/simulation/aiPolygon"; import { type AiRun, type ScreenPoint } from "../../core/simulation/aiPolygon";
import { useAiPlanningControls } from "./useAiPlanningControls"; import { useAiPlanningControls } from "./useAiPlanningControls";
@@ -133,8 +133,8 @@ export function AiRouteOverlay({ run, onChange, videoReady, visible = true }: {
<Button disabled={!ready || !data?.markers.some((m) => m.id === selected)} onClick={() => send({ action: "delete", point_id: selected! })}>Удалить точку</Button> <Button disabled={!ready || !data?.markers.some((m) => m.id === selected)} onClick={() => send({ action: "delete", point_id: selected! })}>Удалить точку</Button>
<Button disabled={!ready || !draft?.can_undo} onClick={() => send({ action: "undo" })}>Отменить</Button> <Button disabled={!ready || !draft?.can_undo} onClick={() => send({ action: "undo" })}>Отменить</Button>
<Button disabled={!cameraReady} onClick={() => send({ action: "home" })}>К началу маршрута</Button> <Button disabled={!cameraReady} onClick={() => send({ action: "home" })}>К началу маршрута</Button>
<p>Мышь — взгляд · Shift + мышь — сдвиг · Колесо — приближение · WASD / стрелки — полёт · Q / E — вниз / вверх · Shift — быстрее</p> <Description>Мышь — взгляд · Shift + мышь — сдвиг · Колесо — приближение · WASD / стрелки — полёт · Q / E — вниз / вверх · Shift — быстрее</Description>
{error || draft?.error ? <p role="alert">{error ?? draft?.error}</p> : null} {error || draft?.error ? <Description role="alert">{error ?? draft?.error}</Description> : null}
</div> : null} </div> : null}
</div>; </div>;
} }
@@ -1,4 +1,4 @@
import { Inspector, Icon, GlassSurface, StatusBadge } from "@nodedc/ui-react"; import { Description, Inspector, Icon, GlassSurface, StatusBadge } from "@nodedc/ui-react";
import type { AiModules, AiRun } from "../../core/simulation/aiPolygon"; import type { AiModules, AiRun } from "../../core/simulation/aiPolygon";
import { AiSessionSection, useSessionLayout } from "./AiSessionSection"; import { AiSessionSection, useSessionLayout } from "./AiSessionSection";
@@ -32,11 +32,11 @@ export function AiRunReport({ runs, modules, onRemove, removing, worldId }: { wo
action:{label:`Удалить прогон ${new Date(run.created_at ?? "").toLocaleString("ru-RU")}`, action:{label:`Удалить прогон ${new Date(run.created_at ?? "").toLocaleString("ru-RU")}`,
icon:<Icon name="trash"/>,disabled:removing!==null || !["completed","stopped","failed"].includes(run.state), icon:<Icon name="trash"/>,disabled:removing!==null || !["completed","stopped","failed"].includes(run.state),
onAction:()=>onRemove(run)}, onAction:()=>onRemove(run)},
}))}/> : <p>В этой локации ещё нет прогонов.</p>} }))}/> : <Description>В этой локации ещё нет прогонов.</Description>}
</AiSessionSection>; </AiSessionSection>;
} }
function RunDetails({run}:{run:AiRun}) { function RunDetails({run}:{run:AiRun}) {
if(!run.report)return <p>{run.message ?? "Отчёт появится после завершения прогона."}</p>; if(!run.report)return <Description>{run.message ?? "Отчёт появится после завершения прогона."}</Description>;
const report=run.report; const report=run.report;
return <div className="ai-polygon__form ai-polygon__report"> return <div className="ai-polygon__form ai-polygon__report">
<StatusBadge tone={report.mission_outcome === "goal-reached" ? "success" : "neutral"}> <StatusBadge tone={report.mission_outcome === "goal-reached" ? "success" : "neutral"}>
@@ -60,8 +60,8 @@ function RunDetails({run}:{run:AiRun}) {
<h3>Остановки после начала движения</h3> <h3>Остановки после начала движения</h3>
{report.stops.length ? <dl>{report.stops.map((stop) => <div key={stop.reason}> {report.stops.length ? <dl>{report.stops.map((stop) => <div key={stop.reason}>
<dt>{reasons[stop.reason] ?? stop.reason}</dt><dd>{stop.events} · {stop.seconds.toFixed(1)} с</dd> <dt>{reasons[stop.reason] ?? stop.reason}</dt><dd>{stop.events} · {stop.seconds.toFixed(1)} с</dd>
</div>)}</dl> : <p>Переходов от движения к нулевой команде не записано.</p>} </div>)}</dl> : <Description>Переходов от движения к нулевой команде не записано.</Description>}
<p>Исходные кадры и телеметрия хранятся на Worker. Архив: {report.evidence_files} файлов, {(report.evidence_bytes / 1024 ** 2).toFixed(1)} МБ.</p> <Description>Исходные кадры и телеметрия хранятся на Worker. Архив: {report.evidence_files} файлов, {(report.evidence_bytes / 1024 ** 2).toFixed(1)} МБ.</Description>
<dl className="ai-polygon__report-identities"> <dl className="ai-polygon__report-identities">
<div><dt>Прогон</dt><dd>{report.run_id}</dd></div> <div><dt>Прогон</dt><dd>{report.run_id}</dd></div>
<div><dt>Профиль ровера</dt><dd>{report.robot_sha256 ?? "Не записан"}</dd></div> <div><dt>Профиль ровера</dt><dd>{report.robot_sha256 ?? "Не записан"}</dd></div>
@@ -1,4 +1,4 @@
import { StatusBadge } from "@nodedc/ui-react"; import { Description, StatusBadge } from "@nodedc/ui-react";
import { type AiRun } from "../../core/simulation/aiPolygon"; import { type AiRun } from "../../core/simulation/aiPolygon";
const STATES: Record<AiRun["state"], string> = { const STATES: Record<AiRun["state"], string> = {
@@ -51,6 +51,6 @@ export function AiRunView({ run }: { run: AiRun }) {
<dt>{label}</dt><dd>{value}</dd> <dt>{label}</dt><dd>{value}</dd>
</div>)} </div>)}
</dl> </dl>
{run.state === "failed" && run.message ? <p>{run.message}</p> : null} {run.state === "failed" && run.message ? <Description>{run.message}</Description> : null}
</section>; </section>;
} }
@@ -1,6 +1,6 @@
import { useCallback, useRef, useState, type ReactNode } from "react"; import { useCallback, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom"; import { createPortal } from "react-dom";
import { Button, Checker, Dropdown, Icon, IconButton, LoadingRegion, Select, StatusBadge } from "@nodedc/ui-react"; import { Description, Button, Checker, Dropdown, Icon, IconButton, LoadingRegion, Select, StatusBadge } from "@nodedc/ui-react";
import { setAiCamera, type AiCamera, type AiRun, type AiWorld } from "../../core/simulation/aiPolygon"; import { setAiCamera, type AiCamera, type AiRun, type AiWorld } from "../../core/simulation/aiPolygon";
import { WorkerVideo, type WorkerVideoState } from "./WorkerVideo"; import { WorkerVideo, type WorkerVideoState } from "./WorkerVideo";
import { AiRouteOverlay } from "./AiRouteOverlay"; import { AiRouteOverlay } from "./AiRouteOverlay";
@@ -60,7 +60,7 @@ export function AiWorldStream({ world, run, onBack, onChange, controls, headerAc
video={<div className="ai-polygon__viewport ai-polygon__stream-bounds" ref={surface} tabIndex={0} aria-label="Управление камерой симуляции"> video={<div className="ai-polygon__viewport ai-polygon__stream-bounds" ref={surface} tabIndex={0} aria-label="Управление камерой симуляции">
<div className="ai-polygon__stream-picture"> <div className="ai-polygon__stream-picture">
{connectable ? <span className="ai-polygon__stream-fps">{state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : state === "failed" ? "Видео недоступно" : "Подключаем видео"}</span> : null} {connectable ? <span className="ai-polygon__stream-fps">{state === "live" ? `Видео · ${fps?.toFixed(0) ?? "—"} FPS` : state === "failed" ? "Видео недоступно" : "Подключаем видео"}</span> : null}
{cameraError ? <p role="alert">Не удалось переключить камеру.</p> : null} {cameraError ? <Description role="alert">Не удалось переключить камеру.</Description> : null}
<LoadingRegion loading={!terminal && (!connectable || state === "connecting")} <LoadingRegion loading={!terminal && (!connectable || state === "connecting")}
label={run?.state === "disconnected" ? "Восстанавливаем связь с Worker" : !connectable ? "Подготавливаем сцену на Worker" : "Подключаем видео"}> label={run?.state === "disconnected" ? "Восстанавливаем связь с Worker" : !connectable ? "Подготавливаем сцену на Worker" : "Подключаем видео"}>
<div className="ai-polygon__video" inert> <div className="ai-polygon__video" inert>
@@ -69,9 +69,9 @@ export function AiWorldStream({ world, run, onBack, onChange, controls, headerAc
</div> </div>
</LoadingRegion> </LoadingRegion>
{!terminal && run && run.telemetry?.route_overlay ? <AiRouteOverlay key={run.run_id} run={run} onChange={onChange} videoReady={state === "live"} visible={routeVisible} /> : null} {!terminal && run && run.telemetry?.route_overlay ? <AiRouteOverlay key={run.run_id} run={run} onChange={onChange} videoReady={state === "live"} visible={routeVisible} /> : null}
{terminal ? <div className="ai-polygon__preview-error"><p>{run?.state === "failed" ? run.message ?? "Симуляция прервана." : "Симуляция завершена."}</p></div> {terminal ? <div className="ai-polygon__preview-error"><Description>{run?.state === "failed" ? run.message ?? "Симуляция прервана." : "Симуляция завершена."}</Description></div>
: connectable && state === "failed" ? <div className="ai-polygon__preview-error" role="status"> : connectable && state === "failed" ? <div className="ai-polygon__preview-error" role="status">
<p>Не удалось получить видео после повторных подключений. Если сцена открыта в другой вкладке, закройте её и подключитесь снова.</p> <Description>Не удалось получить видео после повторных подключений. Если сцена открыта в другой вкладке, закройте её и подключитесь снова.</Description>
<Button onClick={() => {setState("connecting");setRevision((value) => value + 1);}}>Подключить видео</Button> <Button onClick={() => {setState("connecting");setRevision((value) => value + 1);}}>Подключить видео</Button>
</div> : null} </div> : null}
</div> </div>
@@ -27,6 +27,7 @@ export class EditorCamera {
private right = new Vector3(); private right = new Vector3();
private delta = new Vector3(); private delta = new Vector3();
sceneCenter = new Vector3(); sceneCenter = new Vector3();
get focusDepth(){return navigationDepth(this.camera,this.lastAnchor??this.sceneCenter);}
pick: ((x:number,y:number)=>number[]|null)|null = null; pick: ((x:number,y:number)=>number[]|null)|null = null;
pickSurface: ((x:number,y:number)=>Promise<number[]|null>)|null = null; pickSurface: ((x:number,y:number)=>Promise<number[]|null>)|null = null;
constructor(private surface: HTMLElement, private canvas: HTMLCanvasElement) { constructor(private surface: HTMLElement, private canvas: HTMLCanvasElement) {
@@ -2,7 +2,7 @@ import { SimulationViewTools } from "./SimulationViewTools";
import { usePlannerPreferences } from "./usePlannerPreferences"; import { usePlannerPreferences } from "./usePlannerPreferences";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom"; import { createPortal } from "react-dom";
import { Button, GlassSurface, LoadingRegion, StatusBadge } from "@nodedc/ui-react"; import { Description, Button, GlassSurface, LoadingRegion, StatusBadge } from "@nodedc/ui-react";
import type { AiRobot, AiWorld } from "../../core/simulation/aiPolygon"; import type { AiRobot, AiWorld } from "../../core/simulation/aiPolygon";
import type { RoverSettings } from "../../core/simulation/roverSettings"; import type { RoverSettings } from "../../core/simulation/roverSettings";
import { toEditor } from "../../core/simulation/aiEditor"; import { toEditor } from "../../core/simulation/aiEditor";
@@ -48,7 +48,7 @@ export function LocalManualScene({world,robot,settings,actionsHost,headerActions
<canvas ref={canvas} aria-label={`Ручное управление ${robot.name}`} /> <canvas ref={canvas} aria-label={`Ручное управление ${robot.name}`} />
{ready?<div className="ai-simulation__speed"><GlassSurface tone="strong" radius="pill" padding="sm">Скорость: {Math.abs(speed).toFixed(2)} м/с</GlassSurface></div>:null} {ready?<div className="ai-simulation__speed"><GlassSurface tone="strong" radius="pill" padding="sm">Скорость: {Math.abs(speed).toFixed(2)} м/с</GlassSurface></div>:null}
{!ready&&!error?<div className="ai-polygon__preview-error"><LoadingRegion loading label="Открываем локальную сцену"/></div>:null} {!ready&&!error?<div className="ai-polygon__preview-error"><LoadingRegion loading label="Открываем локальную сцену"/></div>:null}
{error?<div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>{setError(null);setRetry(retry+1);}}>Повторить</Button></div>:null} {error?<div className="ai-polygon__preview-error"><Description role="alert">{error}</Description><Button onClick={()=>{setError(null);setRetry(retry+1);}}>Повторить</Button></div>:null}
</div> </div>
</div> </div>
</div>; </div>;
@@ -1,6 +1,6 @@
import {useSimulationLayout} from "./useSimulationLayout"; import {useSimulationLayout} from "./useSimulationLayout";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Checker, Dropdown, SegmentedButton } from "@nodedc/ui-react"; import { Description, Checker, Dropdown, SegmentedButton } from "@nodedc/ui-react";
import { createPortal } from "react-dom"; import { createPortal } from "react-dom";
import { loadExperience, attemptLabel, experienceMap, type SpatialExperience } from "../../core/simulation/spatialExperience"; import { loadExperience, attemptLabel, experienceMap, type SpatialExperience } from "../../core/simulation/spatialExperience";
import type { ScreenPoint } from "../../core/simulation/aiPolygon"; import type { ScreenPoint } from "../../core/simulation/aiPolygon";
@@ -33,13 +33,13 @@ export function PlannerExperience({worldId,worldSha,runtime,viewport,onVisibilit
aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}>Память</SegmentedButton>}> aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}>Память</SegmentedButton>}>
<div className="ai-polygon__layer-options"> <div className="ai-polygon__layer-options">
<strong>Память локации</strong> <strong>Память локации</strong>
<p>Сохраняет посещённые места и попытки проезда между заездами. Новый заезд с той же конфигурацией ровера продолжает эту историю.</p> <Description>Сохраняет посещённые места и попытки проезда между заездами. Новый заезд с той же конфигурацией ровера продолжает эту историю.</Description>
{error?<p role="alert">{error}</p>:memory?<> {error?<Description role="alert">{error}</Description>:memory?<>
<p>Посещено участков: {memory.visits.length}. Попыток проезда: {memory.attempts.length}, из них позже пройдено: {memory.attempts.filter(a=>a.status==="revisited-successfully").length}.</p> <Description>Посещено участков: {memory.visits.length}. Попыток проезда: {memory.attempts.length}, из них позже пройдено: {memory.attempts.filter(a=>a.status==="revisited-successfully").length}.</Description>
<Checker label="Показывать на карте" checked={visible} onChange={setVisible}/> <Checker label="Показывать на карте" checked={visible} onChange={setVisible}/>
</>:<p>Сохранённых проездов пока нет. Память появится после движения ровера.</p>} </>:<Description>Сохранённых проездов пока нет. Память появится после движения ровера.</Description>}
<p>Прежние попытки помогают выбрать другой подход. Возможность проезда всегда проверяется заново по текущим данным.</p> <Description>Прежние попытки помогают выбрать другой подход. Возможность проезда всегда проверяется заново по текущим данным.</Description>
<p>Показана накопленная память конфигурации ровера из последнего заезда. Для другой версии локации или конфигурации сохраняется отдельная память.</p> <Description>Показана накопленная память конфигурации ровера из последнего заезда. Для другой версии локации или конфигурации сохраняется отдельная память.</Description>
</div> </div>
</Dropdown> </Dropdown>
{visible&&memory?createPortal(<svg className="ai-local-editor__markers" viewBox="0 0 1280 720" preserveAspectRatio="none" aria-label="Память проездов"> {visible&&memory?createPortal(<svg className="ai-local-editor__markers" viewBox="0 0 1280 720" preserveAspectRatio="none" aria-label="Память проездов">
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState, type RefObject } from "react"; import { useEffect, useRef, useState, type RefObject } from "react";
import { ColorField, ControlRow, RangeControl, Select, ToastStack, WorkspaceWindow } from "@nodedc/ui-react"; import { Description, ColorField, ControlRow, RangeControl, Select, ToastStack, WorkspaceWindow } from "@nodedc/ui-react";
import type { PlannerPreferences } from "../../core/simulation/plannerPreferences"; import type { PlannerPreferences } from "../../core/simulation/plannerPreferences";
import {PlannerCubeSettings} from "./PlannerCubeSettings"; import {PlannerCubeSettings} from "./PlannerCubeSettings";
import {PlannerToolbarSettings} from "./PlannerToolbarSettings"; import {PlannerToolbarSettings} from "./PlannerToolbarSettings";
@@ -79,7 +79,7 @@ export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<H
<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={value.waypoint.emissionColor} onChange={(v)=>set("waypoint","emissionColor",v)}/></ControlRow> <ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={value.waypoint.emissionColor} onChange={(v)=>set("waypoint","emissionColor",v)}/></ControlRow>
</> : <> </> : <>
<strong>Сдвиг камеры</strong> <strong>Сдвиг камеры</strong>
<p>Расстояние до поверхности под курсором. Чувствительность плавно меняется между двумя границами.</p> <Description>Расстояние до поверхности под курсором. Чувствительность плавно меняется между двумя границами.</Description>
{range("navigation","nearDistance","Ближнее расстояние",.5,50,.5,"м")} {range("navigation","nearDistance","Ближнее расстояние",.5,50,.5,"м")}
{range("navigation","nearPan","Чувствительность вблизи",.1,5,.1,"×")} {range("navigation","nearPan","Чувствительность вблизи",.1,5,.1,"×")}
{range("navigation","farDistance","Дальнее расстояние",Math.max(2,value.navigation.nearDistance+1),500,1,"м")} {range("navigation","farDistance","Дальнее расстояние",Math.max(2,value.navigation.nearDistance+1),500,1,"м")}
@@ -87,7 +87,7 @@ export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<H
<strong>Зум</strong> <strong>Зум</strong>
{range("navigation","zoom","Скорость зума",.1,3,.1,"×")} {range("navigation","zoom","Скорость зума",.1,3,.1,"×")}
<strong>Центр вращения</strong> <strong>Центр вращения</strong>
<p>Шарик появляется в точке нажатия на время вращения.</p> <Description>Шарик появляется в точке нажатия на время вращения.</Description>
{range("navigation","centroidPixels","Размер центра на экране",6,64,1,"px")} {range("navigation","centroidPixels","Размер центра на экране",6,64,1,"px")}
<ControlRow label="Цвет центра"><ColorField label="Цвет центра" value={value.navigation.centroidColor} onChange={(v)=>set("navigation","centroidColor",v)}/></ControlRow> <ControlRow label="Цвет центра"><ColorField label="Цвет центра" value={value.navigation.centroidColor} onChange={(v)=>set("navigation","centroidColor",v)}/></ControlRow>
{range("navigation","centroidOpacity","Непрозрачность центра",.1,1,.05,"")} {range("navigation","centroidOpacity","Непрозрачность центра",.1,1,.05,"")}
@@ -1,5 +1,5 @@
import { useState } from "react"; import { useState } from "react";
import { Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react"; import { Description, Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
import type { AiRobot } from "../../core/simulation/aiPolygon"; import type { AiRobot } from "../../core/simulation/aiPolygon";
import { defaultRoverSettings, validRoverSettings, type RoverSettings } from "../../core/simulation/roverSettings"; import { defaultRoverSettings, validRoverSettings, type RoverSettings } from "../../core/simulation/roverSettings";
@@ -23,11 +23,11 @@ export function RoverSettingsWindow({robot,value,manual,onApply,onClose}:{
{field("base_mass_kg","Масса ровера без груза, кг",10,1000,1)} {field("base_mass_kg","Масса ровера без груза, кг",10,1000,1)}
{field("payload_mass_kg","Дополнительный груз, кг",0,500,1)} {field("payload_mass_kg","Дополнительный груз, кг",0,500,1)}
{field("payload_height_m","Высота центра груза над грунтом, м",.1,3,.01)} {field("payload_height_m","Высота центра груза над грунтом, м",.1,3,.01)}
<p>Общая масса: {Number.isFinite(draft.base_mass_kg+draft.payload_mass_kg)?draft.base_mass_kg+draft.payload_mass_kg:"—"} кг.</p> <Description>Общая масса: {Number.isFinite(draft.base_mass_kg+draft.payload_mass_kg)?draft.base_mass_kg+draft.payload_mass_kg:"—"} кг.</Description>
<p>Груз расположен по центру ровера. Масса и высота влияют на центр тяжести и инерцию; мощность моторов остаётся прежней.</p> <Description>Груз расположен по центру ровера. Масса и высота влияют на центр тяжести и инерцию; мощность моторов остаётся прежней.</Description>
{manual?<p>В ручном режиме учитываются скорость и общая масса. Высота груза применяется в заезде на Worker.</p>:null} {manual?<Description>В ручном режиме учитываются скорость и общая масса. Высота груза применяется в заезде на Worker.</Description>:null}
<p>Изменения применяются к следующему заезду. Его результат сохраняет использованные настройки.</p> <Description>Изменения применяются к следующему заезду. Его результат сохраняет использованные настройки.</Description>
{!valid?<p role="status">Допустимо: конечная скорость от 0.05 м/с, масса 10–1000 кг, груз 0–500 кг, высота 0.1–3 м.</p>:null} {!valid?<Description role="status">Допустимо: конечная скорость от 0.05 м/с, масса 10–1000 кг, груз 0–500 кг, высота 0.1–3 м.</Description>:null}
</div> </div>
</Window>; </Window>;
} }
@@ -1,4 +1,4 @@
import { import { Description,
ActivityIndicator, ActivityIndicator,
Button, Button,
Icon, Icon,
@@ -85,7 +85,7 @@ export function SimulationCatalog({
<div className="simulation-catalog__empty"> <div className="simulation-catalog__empty">
<span><Icon name="globe" size={20} /></span> <span><Icon name="globe" size={20} /></span>
<strong>Перетащите архивы в это окно</strong> <strong>Перетащите архивы в это окно</strong>
<p>Каждый ZIP, RAR или 7z сразу станет отдельным проектом и встанет в очередь.</p> <Description>Каждый ZIP, RAR или 7z сразу станет отдельным проектом и встанет в очередь.</Description>
<Button variant="primary" icon={<Icon name="plus" size={16} />} onClick={onCreate}> <Button variant="primary" icon={<Icon name="plus" size={16} />} onClick={onCreate}>
Новый проект Новый проект
</Button> </Button>
@@ -1,6 +1,6 @@
import {useEffect,useRef,useState,type ReactNode} from 'react'; import {useEffect,useRef,useState,type ReactNode} from 'react';
import {createPortal} from 'react-dom'; import {createPortal} from 'react-dom';
import {Button,Checker,DockHandle,Dropdown,GlassSurface,Icon,IconButton,Select,ToastStack} from '@nodedc/ui-react'; import { Description,Button,Checker,DockHandle,Dropdown,GlassSurface,Icon,IconButton,Select,ToastStack} from '@nodedc/ui-react';
import {withObservationTree,orderedObservationIDs,observationTree} from '../../core/fleet/observationLayout'; import {withObservationTree,orderedObservationIDs,observationTree} from '../../core/fleet/observationLayout';
import {useObservationPresets} from '../../core/fleet/useObservationPresets'; import {useObservationPresets} from '../../core/fleet/useObservationPresets';
import {observationArrangements,retainDormantObservationTree} from '../../core/fleet/observationPresets'; import {observationArrangements,retainDormantObservationTree} from '../../core/fleet/observationPresets';
@@ -48,7 +48,7 @@ export function SimulationObservationDeck({video,videoActions,toolbar,preview}:{
</div></ObservationPanelHeader> </div></ObservationPanelHeader>
<div className="observation-mount">{source.id==='video'?video:preview&&<AiInferencePreview preview={preview} layer={source.id}/>}</div> <div className="observation-mount">{source.id==='video'?video:preview&&<AiInferencePreview preview={preview} layer={source.id}/>}</div>
</GlassSurface></div>,mounts.current.get(source.id)!,source.id))} </GlassSurface></div>,mounts.current.get(source.id)!,source.id))}
</ObservationDeck>:<div className="observation-empty"><p>Все окна скрыты.</p><Button onClick={()=>show('video',true)}>Показать симуляцию</Button></div>}</div> </ObservationDeck>:<div className="observation-empty"><Description>Все окна скрыты.</Description><Button onClick={()=>show('video',true)}>Показать симуляцию</Button></div>}</div>
{saving&&<ObservationLayoutSaveWindow onClose={()=>setSaving(false)} onSave={presets.save}/>} {saving&&<ObservationLayoutSaveWindow onClose={()=>setSaving(false)} onSave={presets.save}/>}
{edited&&<ObservationLayoutSaveWindow key={edited.id} initialName={edited.name} onClose={()=>setEditing(null)} onSave={name=>presets.rename(edited.id,name)} onRemove={()=>presets.remove(edited.id)}/>} {edited&&<ObservationLayoutSaveWindow key={edited.id} initialName={edited.name} onClose={()=>setEditing(null)} onSave={name=>presets.rename(edited.id,name)} onRemove={()=>presets.remove(edited.id)}/>}
<ToastStack items={presets.error?[{id:"layout-save",tone:"error",title:"Раскладка не сохранена",description:presets.error}]:[]} onDismiss={presets.clearError}/> <ToastStack items={presets.error?[{id:"layout-save",tone:"error",title:"Раскладка не сохранена",description:presets.error}]:[]} onDismiss={presets.clearError}/>
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Button, LoadingRegion, Window } from "@nodedc/ui-react"; import { Description, Button, LoadingRegion, Window } from "@nodedc/ui-react";
import { fetchSimulationProjects, retrySimulationProject, type SimulationProject } from "../../core/simulation/projects"; import { fetchSimulationProjects, retrySimulationProject, type SimulationProject } from "../../core/simulation/projects";
import { SimulationProjectWindow } from "./SimulationProjectWindow"; import { SimulationProjectWindow } from "./SimulationProjectWindow";
@@ -38,14 +38,14 @@ export function SimulationSourceImport({open,onClose,onPly,onReady}: {
<Button onClick={()=>{onClose();onPly();}}>Gaussian PLY</Button> <Button onClick={()=>{onClose();onPly();}}>Gaussian PLY</Button>
<Button onClick={()=>{onClose();setArchive(true);}}>Архив или папка LCC</Button> <Button onClick={()=>{onClose();setArchive(true);}}>Архив или папка LCC</Button>
</div> </div>
{pending.map(p=><div key={p.projectId} className="ai-polygon__row"><p>{p.name}</p> {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={()=>{onClose();setError(null);setProject(p);}}>Подготовка локации</Button></div>)}
{error?<p role="alert">{error}</p>:null} {error?<Description role="alert">{error}</Description>:null}
</Window> </Window>
<SimulationProjectWindow open={archive} project={null} onClose={()=>setArchive(false)} onSaved={p=>{setArchive(false);setProject(p);}} /> <SimulationProjectWindow open={archive} project={null} onClose={()=>setArchive(false)} onSaved={p=>{setArchive(false);setProject(p);}} />
{project?<Window open title={`Подготовка ${project.name}`} onClose={()=>setProject(null)}> {project?<Window open title={`Подготовка ${project.name}`} onClose={()=>setProject(null)}>
<LoadingRegion loading={project.status!=='failed'&&!error} label="Подготовка локации"> <LoadingRegion loading={project.status!=='failed'&&!error} label="Подготовка локации">
<p>{error??project.error??'Локация появится в общей библиотеке после подготовки.'}</p> <Description>{error??project.error??'Локация появится в общей библиотеке после подготовки.'}</Description>
{project.status==='failed'?<Button onClick={()=>void retrySimulationProject(project.projectId).then(setProject).catch(e=>setError(e.message))}>Повторить подготовку</Button>:null} {project.status==='failed'?<Button onClick={()=>void retrySimulationProject(project.projectId).then(setProject).catch(e=>setError(e.message))}>Повторить подготовку</Button>:null}
</LoadingRegion> </LoadingRegion>
</Window>:null} </Window>:null}
@@ -1,4 +1,4 @@
import { import { Description,
Button, Button,
Icon, Icon,
RangeControl, RangeControl,
@@ -44,12 +44,12 @@ export function SimulationUgvSettingsPanel({
<strong>Физика UGV</strong> <strong>Физика UGV</strong>
<span>Дифференциальный привод</span> <span>Дифференциальный привод</span>
</div> </div>
<p> <Description>
A/D без W/S разворачивают UGV вокруг собственного центра. Скорость и A/D без W/S разворачивают UGV вокруг собственного центра. Скорость и
динамика применяются сразу. Мышь вращает камеру вокруг машины, колесо динамика применяются сразу. Мышь вращает камеру вокруг машины, колесо
меняет дистанцию; после паузы камера плавно возвращается назад. Ползунок меняет дистанцию; после паузы камера плавно возвращается назад. Ползунок
работает в штатном диапазоне, точное значение можно ввести вручную. работает в штатном диапазоне, точное значение можно ввести вручную.
</p> </Description>
<TextField <TextField
label="Название пресета" label="Название пресета"
value={value.presetName} value={value.presetName}
@@ -1,5 +1,5 @@
import { useState, type ReactNode, type RefObject } from "react"; import { useState, type ReactNode, type RefObject } from "react";
import { Icon, IconButton, Select, ToastStack, Window } from "@nodedc/ui-react"; import { Description, Icon, IconButton, Select, ToastStack, Window } from "@nodedc/ui-react";
import { PlannerSettings } from "./PlannerSettings"; import { PlannerSettings } from "./PlannerSettings";
import { usePlannerPreferences } from "./usePlannerPreferences"; import { usePlannerPreferences } from "./usePlannerPreferences";
@@ -22,12 +22,12 @@ export function SimulationViewTools({expanded,toggle,semantic=false,planning=fal
{settings?<PlannerSettings boundsRef={boundsRef} onClose={()=>setSettings(false)}/>:null} {settings?<PlannerSettings boundsRef={boundsRef} onClose={()=>setSettings(false)}/>:null}
<Window open={help} onClose={()=>setHelp(false)} title="Управление сценой"> <Window open={help} onClose={()=>setHelp(false)} title="Управление сценой">
<div className="ai-polygon__form">{planning?<> <div className="ai-polygon__form">{planning?<>
<p>{semantic?"При редактировании Ctrl + перетаскивание ЛКМ — вращение камеры; без Ctrl — выбранный инструмент. Вне редактирования ЛКМ вращает камеру без Ctrl.":"ЛКМ — вращение вокруг точки нажатия."} ПКМ или клик двумя пальцами с движением — сдвиг.</p> <Description>{semantic?"При редактировании Ctrl + перетаскивание ЛКМ — вращение камеры; без Ctrl — выбранный инструмент. Вне редактирования ЛКМ вращает камеру без Ctrl.":"ЛКМ — вращение вокруг точки нажатия."} ПКМ или клик двумя пальцами с движением — сдвиг.</Description>
<p>{semantic?"При редактировании прокрутка двумя пальцами сдвигает вид; щипок или Ctrl + прокрутка — зум к курсору.":"Прокрутка — зум к курсору, в том числе в режиме добавления точек."}</p> <Description>{semantic?"При редактировании прокрутка двумя пальцами сдвигает вид; щипок или Ctrl + прокрутка — зум к курсору.":"Прокрутка — зум к курсору, в том числе в режиме добавления точек."}</Description>
<p>WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.</p> <Description>WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.</Description>
{semantic?<p>Клик по полосе выбирает элемент целиком, по её вершине — точку; рамка или Shift + клик выбирают несколько точек. Shift + перетаскивание пивота копирует целый элемент или продолжает выбранную точку. Escape отменяет действие, Ctrl/Cmd+Z — отменяет правку. Hold закрепляет тулбар.</p>:null} {semantic?<Description>Клик по полосе выбирает элемент целиком, по её вершине — точку; рамка или Shift + клик выбирают несколько точек. Shift + перетаскивание пивота копирует целый элемент или продолжает выбранную точку. Escape отменяет действие, Ctrl/Cmd+Z — отменяет правку. Hold закрепляет тулбар.</Description>:null}
{routeEditing?<p>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</p>:null} {routeEditing?<Description>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</Description>:null}
</>:<><p>WASD / стрелки — движение. Пробел — тормоз. R — к старту.</p><p>Мышь — обзор.</p></>}</div> </>:<><Description>WASD / стрелки — движение. Пробел — тормоз. R — к старту.</Description><Description>Мышь — обзор.</Description></>}</div>
</Window> </Window>
{error?<ToastStack items={[{id:"quality",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null} {error?<ToastStack items={[{id:"quality",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
</>; </>;
@@ -1,5 +1,5 @@
import { useEffect, useId, useRef, useState } from "react"; import { useEffect, useId, useRef, useState } from "react";
import { import { Description,
ActivityIndicator, ActivityIndicator,
Button, Button,
GlassMaterialSurface, GlassMaterialSurface,
@@ -237,7 +237,7 @@ export function SimulationViewport({
data-control-mode={controlMode} data-control-mode={controlMode}
aria-label={`Сцена ${project.name}`} aria-label={`Сцена ${project.name}`}
> >
<header className="simulation-viewport__toolbar"> <header data-glass-context="scene" className="simulation-viewport__toolbar nodedc-viewport-surface">
<div> <div>
<StatusBadge tone={state === "failed" || collisionState === "failed" ? "warning" : state === "ready" && collisionState !== "loading" ? "success" : "accent"}> <StatusBadge tone={state === "failed" || collisionState === "failed" ? "warning" : state === "ready" && collisionState !== "loading" ? "success" : "accent"}>
{controlState === "loading" {controlState === "loading"
@@ -341,7 +341,7 @@ export function SimulationViewport({
role="dialog" role="dialog"
aria-label="Настройки сцены" aria-label="Настройки сцены"
> >
<div className="simulation-viewport__settings-head"> <div data-glass-context="scene" className="simulation-viewport__settings-head nodedc-viewport-surface">
<div> <div>
<strong>Настройки сцены</strong> <strong>Настройки сцены</strong>
<span>Локация, камера и UGV</span> <span>Локация, камера и UGV</span>
@@ -356,9 +356,9 @@ export function SimulationViewport({
<strong>Система координат</strong> <strong>Система координат</strong>
<span>Мир сцены · Y вверх</span> <span>Мир сцены · Y вверх</span>
</div> </div>
<p> <Description>
Коррекция слоёв не меняет координаты камеры, навигации и будущей физики. Коррекция слоёв не меняет координаты камеры, навигации и будущей физики.
</p> </Description>
<div className="simulation-viewport__settings-rotations"> <div className="simulation-viewport__settings-rotations">
<LayerRotationFields <LayerRotationFields
label="Гауссовый слой" label="Гауссовый слой"
@@ -450,10 +450,10 @@ export function SimulationViewport({
<div className="simulation-viewport__stage"> <div className="simulation-viewport__stage">
<canvas ref={canvasRef} aria-label={`Сцена ${project.name}`} /> <canvas ref={canvasRef} aria-label={`Сцена ${project.name}`} />
{state !== "ready" ? ( {state !== "ready" ? (
<div className="simulation-viewport__state" role={state === "failed" ? "alert" : "status"}> <div data-glass-context="scene" className="simulation-viewport__state nodedc-viewport-surface" role={state === "failed" ? "alert" : "status"}>
{state === "failed" ? null : <ActivityIndicator label="Загрузка локации" />} {state === "failed" ? null : <ActivityIndicator label="Загрузка локации" />}
<strong>{state === "failed" ? "Локация не открылась" : "Загружаем локацию"}</strong> <strong>{state === "failed" ? "Локация не открылась" : "Загружаем локацию"}</strong>
<p>{error ?? "LOD-уровни загружаются по мере готовности runtime."}</p> <Description>{error ?? "LOD-уровни загружаются по мере готовности runtime."}</Description>
</div> </div>
) : null} ) : null}
</div> </div>
@@ -0,0 +1,32 @@
import { useEffect, useState } from "react";
import { Description, Button, SettingsCard, TextField, WindowFooterActions } from "@nodedc/ui-react";
import { announceLabStorageChange, saveLabRetention, useLocalLabStorage } from "../../core/storage/localLabStorage";
export function useLabStorageSettings(open: boolean) {
const { data, error: loadError, refresh } = useLocalLabStorage(open);
const [days, setDays] = useState("30");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
useEffect(() => { if (data) setDays(String(data.retention_days)); }, [data?.retention_days]);
const number = Number(days);
const valid = Number.isInteger(number) && number >= 1 && number <= 365;
const content = <SettingsCard eyebrow="ХРАНИЛИЩЕ" title="Локальные записи лабораторий"
description="Срок хранения готовых записей просмотра после последнего открытия. Закреплённые записи остаются на этом устройстве до снятия булавки.">
<TextField label="Срок временного хранения, дней" type="number" min={1} max={365}
value={days} disabled={busy || !data} onChange={event => { setDays(event.target.value); setSaved(false); }} />
<Description>После снятия булавки срок начинается заново. История запусков и результаты на Worker сохраняются.</Description>
<Description>Правило применяется к учтённым записям просмотра AI Inference. Исходные записи, Gaussian-сцены и разметка сохраняются отдельно.</Description>
{loadError || error ? <Description role="alert">{error ?? loadError}</Description> : saved ? <Description role="status">Настройки сохранены.</Description> : null}
</SettingsCard>;
const footer = <WindowFooterActions>
<Button variant="secondary" disabled={busy || !data || days === String(data.retention_days)}
onClick={() => { setDays(String(data!.retention_days)); setError(null); }}>Сбросить изменения</Button>
<Button variant="primary" tone="neutral" disabled={busy || !data || !valid || days === String(data.retention_days)}
onClick={() => { setBusy(true); setError(null); void saveLabRetention(number).then(async () => {
await refresh(); setSaved(true); announceLabStorageChange();
}).catch(reason => setError(reason instanceof Error ? reason.message : "Не удалось сохранить срок хранения."))
.finally(() => setBusy(false)); }}>{busy ? "Сохраняем…" : "Сохранить"}</Button>
</WindowFooterActions>;
return { id: "storage", label: "Хранилище", icon: "database" as const, content, footer };
}
@@ -1,579 +0,0 @@
import { useEffect, useMemo, useState } from "react";
import {
Button,
FeatureSettingsWindow,
FieldFrame,
Icon,
Select,
SettingsCard,
StatusBadge,
TextField,
WindowFooterActions,
} from "@nodedc/ui-react";
import {
applyComputeContourNetwork,
fetchComputeContourAgentInstall,
fetchComputeContourNetwork,
type ComputeContour,
type ComputeContourAgentInstall,
type ComputeContourDraft,
type ComputeContourNetworkStatus,
type ComputeContourPlatform,
} from "../../core/system/computeContours";
import {
DEFAULT_TELEMETRY_POLL_INTERVAL_SECONDS,
parseTelemetryPollIntervalDraft,
resolveTelemetryPollIntervalDraft,
} from "../../core/system/telemetryPollInterval";
interface ComputeContourSettingsWindowProps {
open: boolean;
contour: ComputeContour | null;
mode: "create" | "edit";
onClose: () => void;
onCreate: (draft: ComputeContourDraft) => Promise<ComputeContour>;
onUpdate: (
contour: ComputeContour,
draft: ComputeContourDraft,
) => Promise<ComputeContour>;
}
const platformOptions = [
{ value: "windows", label: "Windows", description: "Worker с Windows service" },
{ value: "linux", label: "Linux", description: "Worker с systemd service" },
{ value: "unknown", label: "Не определено", description: "Платформа будет уточнена" },
] satisfies Array<{
value: ComputeContourPlatform;
label: string;
description: string;
}>;
function emptyDraft(): ComputeContourDraft {
return {
display_name: "",
expected_node_id: "",
platform: "unknown",
telemetry_mode: "agent-mqtt",
address: "",
ssh_port: 22,
mqtt_host: "127.0.0.1",
mqtt_port: 1883,
mqtt_bind_address: "127.0.0.1",
telemetry_poll_interval_seconds: DEFAULT_TELEMETRY_POLL_INTERVAL_SECONDS,
mqtt_publish_interval_seconds: 2,
};
}
function draftFromContour(contour: ComputeContour | null): ComputeContourDraft {
if (!contour) return emptyDraft();
return {
display_name: contour.display_name,
expected_node_id: contour.expected_node_id,
platform: contour.platform,
telemetry_mode: contour.telemetry_mode,
address: contour.address,
ssh_port: contour.ssh_port,
mqtt_host: contour.mqtt_host,
mqtt_port: contour.mqtt_port,
mqtt_bind_address: contour.mqtt_bind_address,
telemetry_poll_interval_seconds: contour.telemetry_poll_interval_seconds,
mqtt_publish_interval_seconds: contour.mqtt_publish_interval_seconds,
};
}
export function ComputeContourSettingsWindow({
open,
contour,
mode,
onClose,
onCreate,
onUpdate,
}: ComputeContourSettingsWindowProps) {
const [draft, setDraft] = useState<ComputeContourDraft>(() => draftFromContour(contour));
const [telemetryPollIntervalDraft, setTelemetryPollIntervalDraft] = useState(
() => String(draftFromContour(contour).telemetry_poll_interval_seconds),
);
const [mqttPublishIntervalDraft, setMqttPublishIntervalDraft] = useState(
() => String(draftFromContour(contour).mqtt_publish_interval_seconds),
);
const [activeSection, setActiveSection] = useState<"connection" | "agent">("connection");
const [install, setInstall] = useState<ComputeContourAgentInstall | null>(null);
const [network, setNetwork] = useState<ComputeContourNetworkStatus | null>(null);
const [networkAction, setNetworkAction] = useState<
"refresh" | "broker" | "worker" | null
>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!open) return;
const nextDraft = draftFromContour(mode === "edit" ? contour : null);
setDraft(nextDraft);
setTelemetryPollIntervalDraft(String(nextDraft.telemetry_poll_interval_seconds));
setMqttPublishIntervalDraft(String(nextDraft.mqtt_publish_interval_seconds));
setActiveSection("connection");
setInstall(null);
setNetwork(null);
setNetworkAction(null);
setError(null);
}, [contour, mode, open]);
useEffect(() => {
if (!open || mode !== "edit" || !contour) return;
const controller = new AbortController();
setNetworkAction("refresh");
void fetchComputeContourNetwork(contour.contour_id, controller.signal)
.then((document) => {
if (!controller.signal.aborted) setNetwork(document);
})
.catch((reason: unknown) => {
if (!controller.signal.aborted) {
setError(reason instanceof Error ? reason.message : "Сетевая проверка недоступна.");
}
})
.finally(() => {
if (!controller.signal.aborted) setNetworkAction(null);
});
return () => controller.abort();
}, [contour, mode, open]);
useEffect(() => {
if (!open || mode !== "edit" || !contour) return;
const controller = new AbortController();
void fetchComputeContourAgentInstall(contour.contour_id, controller.signal)
.then((document) => {
if (!controller.signal.aborted) setInstall(document);
})
.catch((reason: unknown) => {
if (!controller.signal.aborted) {
setError(reason instanceof Error ? reason.message : "Инструкция агента недоступна.");
}
});
return () => controller.abort();
}, [contour, mode, open]);
const telemetryPollIntervalSeconds = useMemo(
() => parseTelemetryPollIntervalDraft(telemetryPollIntervalDraft),
[telemetryPollIntervalDraft],
);
const mqttPublishIntervalSeconds = useMemo(
() => parseTelemetryPollIntervalDraft(mqttPublishIntervalDraft),
[mqttPublishIntervalDraft],
);
const valid = useMemo(() => (
Boolean(draft.display_name.trim())
&& Boolean(draft.expected_node_id.trim())
&& Boolean(draft.mqtt_host.trim())
&& Boolean(draft.mqtt_bind_address.trim())
&& Number.isInteger(draft.ssh_port)
&& draft.ssh_port > 0
&& Number.isInteger(draft.mqtt_port)
&& draft.mqtt_port > 0
&& telemetryPollIntervalSeconds !== null
&& mqttPublishIntervalSeconds !== null
), [draft, mqttPublishIntervalSeconds, telemetryPollIntervalSeconds]);
const networkProfileDirty = Boolean(
contour
&& (
draft.mqtt_host !== contour.mqtt_host
|| draft.mqtt_port !== contour.mqtt_port
|| draft.mqtt_bind_address !== contour.mqtt_bind_address
|| draft.mqtt_publish_interval_seconds !== contour.mqtt_publish_interval_seconds
),
);
const commitTelemetryPollInterval = () => {
const resolution = resolveTelemetryPollIntervalDraft(
telemetryPollIntervalDraft,
draft.telemetry_poll_interval_seconds,
);
setTelemetryPollIntervalDraft(resolution.draft);
if (!resolution.accepted) return;
setDraft((current) => (
current.telemetry_poll_interval_seconds === resolution.seconds
? current
: {
...current,
telemetry_poll_interval_seconds: resolution.seconds,
}
));
};
const commitMqttPublishInterval = () => {
const resolution = resolveTelemetryPollIntervalDraft(
mqttPublishIntervalDraft,
draft.mqtt_publish_interval_seconds,
);
setMqttPublishIntervalDraft(resolution.draft);
if (!resolution.accepted) return;
setDraft((current) => (
current.mqtt_publish_interval_seconds === resolution.seconds
? current
: {
...current,
mqtt_publish_interval_seconds: resolution.seconds,
}
));
};
const save = async () => {
if (
!valid
|| busy
|| telemetryPollIntervalSeconds === null
|| mqttPublishIntervalSeconds === null
) return;
const committedDraft = {
...draft,
telemetry_poll_interval_seconds: telemetryPollIntervalSeconds,
mqtt_publish_interval_seconds: mqttPublishIntervalSeconds,
};
setBusy(true);
setError(null);
try {
if (mode === "edit" && contour) {
await onUpdate(contour, committedDraft);
} else {
await onCreate(committedDraft);
}
onClose();
} catch (reason) {
setError(reason instanceof Error ? reason.message : "Контур не сохранён.");
} finally {
setBusy(false);
}
};
const refreshNetwork = async () => {
if (!contour || networkAction) return;
setNetworkAction("refresh");
setError(null);
try {
setNetwork(await fetchComputeContourNetwork(contour.contour_id));
} catch (reason) {
setError(reason instanceof Error ? reason.message : "Сетевая проверка недоступна.");
} finally {
setNetworkAction(null);
}
};
const applyNetwork = async (target: "broker" | "worker") => {
if (!contour || networkAction || networkProfileDirty) return;
setNetworkAction(target);
setError(null);
try {
await applyComputeContourNetwork(contour.contour_id, target);
setNetwork(await fetchComputeContourNetwork(contour.contour_id));
} catch (reason) {
setError(
reason instanceof Error ? reason.message : "Сетевой профиль не применён.",
);
} finally {
setNetworkAction(null);
}
};
return (
<FeatureSettingsWindow
open={open}
title={mode === "create" ? "Добавить вычислительный контур" : "Настройки контура"}
subtitle="Локальная переносимая конфигурация"
identity={{
title: contour?.display_name ?? "Новый контур",
subtitle: contour?.expected_node_id ?? "Node ID не назначен",
avatarLabel: contour?.display_name.slice(0, 2).toUpperCase() ?? "WC",
}}
sections={[
{
id: "connection",
label: "Подключение",
group: "ВЫЧИСЛИТЕЛЬНЫЙ КОНТУР",
icon: "network",
},
{
id: "agent",
label: "Агент",
group: "ТЕЛЕМЕТРИЯ",
icon: "activity",
disabled: mode === "create",
},
]}
activeSection={activeSection}
onSectionChange={setActiveSection}
onClose={onClose}
footer={(
<WindowFooterActions>
<Button variant="secondary" onClick={onClose}>Отмена</Button>
<Button variant="primary" disabled={!valid || busy} onClick={() => void save()}>
{busy ? "Сохраняем…" : mode === "create" ? "Добавить контур" : "Сохранить"}
</Button>
</WindowFooterActions>
)}
>
<div className="compute-contour-settings">
{activeSection === "connection" ? (
<>
<SettingsCard
eyebrow="КОНТУР"
title="Идентичность и локальная сеть"
description="Node ID проверяется независимо от IP-адреса. Адрес можно менять при переносе комплекта в другую локальную сеть."
>
<div className="compute-contour-settings__form">
<TextField
label="Название"
value={draft.display_name}
placeholder="Worker 006"
onChange={(event) => setDraft((current) => ({
...current,
display_name: event.currentTarget.value,
}))}
/>
<TextField
label="Ожидаемый Node ID"
value={draft.expected_node_id}
placeholder="DESKTOP-OPJ8J04"
onChange={(event) => setDraft((current) => ({
...current,
expected_node_id: event.currentTarget.value,
}))}
/>
<FieldFrame label="Операционная система">
<Select
label="Операционная система"
value={draft.platform}
options={platformOptions}
variant="split"
menuWidth="anchor"
onChange={(platform) => setDraft((current) => ({ ...current, platform }))}
/>
</FieldFrame>
<TextField
label="Адрес узла"
hint="IP или hostname в текущей LAN"
value={draft.address}
onChange={(event) => setDraft((current) => ({
...current,
address: event.currentTarget.value,
}))}
/>
<TextField
label="MQTT broker"
hint="Стабильный hostname рекомендуется вместо выдаваемого DHCP IP"
value={draft.mqtt_host}
onChange={(event) => setDraft((current) => ({
...current,
mqtt_host: event.currentTarget.value,
}))}
/>
<TextField
label="MQTT port"
type="number"
min={1}
max={65535}
value={String(draft.mqtt_port)}
onChange={(event) => setDraft((current) => ({
...current,
mqtt_port: Number(event.currentTarget.value),
}))}
/>
<TextField
label="Публикация broker"
hint="IP текущего Mac в разрешённой LAN · 0.0.0.0 запрещён"
value={draft.mqtt_bind_address}
onChange={(event) => setDraft((current) => ({
...current,
mqtt_bind_address: event.currentTarget.value,
}))}
/>
<TextField
label="Обновление интерфейса"
hint="1–60 с"
type="text"
inputMode="numeric"
autoComplete="off"
aria-invalid={telemetryPollIntervalSeconds === null}
value={telemetryPollIntervalDraft}
onChange={(event) => setTelemetryPollIntervalDraft(event.currentTarget.value)}
onBlur={commitTelemetryPollInterval}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
commitTelemetryPollInterval();
} else if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
setTelemetryPollIntervalDraft(
String(draft.telemetry_poll_interval_seconds),
);
}
}}
/>
<TextField
label="Интервал MQTT агента"
hint="1–60 с · применяется конфигурацией агента"
type="text"
inputMode="numeric"
autoComplete="off"
aria-invalid={mqttPublishIntervalSeconds === null}
value={mqttPublishIntervalDraft}
onChange={(event) => setMqttPublishIntervalDraft(event.currentTarget.value)}
onBlur={commitMqttPublishInterval}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
commitMqttPublishInterval();
} else if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
setMqttPublishIntervalDraft(
String(draft.mqtt_publish_interval_seconds),
);
}
}}
/>
{draft.telemetry_mode === "legacy-ssh" ? (
<TextField
label="SSH port"
type="number"
min={1}
max={65535}
value={String(draft.ssh_port)}
onChange={(event) => setDraft((current) => ({
...current,
ssh_port: Number(event.currentTarget.value),
}))}
/>
) : null}
</div>
</SettingsCard>
<SettingsCard
eyebrow="СЕТЕВОЙ ПРОФИЛЬ"
title="MQTT · Mac ↔ Worker"
description="Mesh-точки одной LAN не закрепляются по отдельности. Профиль хранит стабильное имя Mac и адрес публикации broker в текущей сети."
actions={(
<StatusBadge tone={network?.broker.ready ? "success" : "warning"}>
{network?.broker.ready ? "Broker доступен" : "Нужна проверка"}
</StatusBadge>
)}
>
<div className="compute-contour-settings__network">
<dl>
<div>
<dt>Endpoint Worker</dt>
<dd>{network
? `${network.broker.configured_host}:${network.broker.configured_port}`
: "—"}</dd>
</div>
<div>
<dt>Текущий IP</dt>
<dd>{network?.broker.resolved_addresses.join(", ") || "—"}</dd>
</div>
<div>
<dt>Публикация Mac</dt>
<dd>{network?.broker.bind_address ?? "—"}</dd>
</div>
<div>
<dt>{contour?.display_name ?? "Worker"}</dt>
<dd>{network?.worker.reachable
? `${network.worker.mqtt_host ?? "—"}:${network.worker.mqtt_port ?? "—"}`
: "Недоступен"}</dd>
</div>
</dl>
<div className="compute-contour-settings__network-statuses">
<StatusBadge tone={network?.broker.bind_reachable ? "success" : "danger"}>
{network?.broker.bind_reachable
? "Listener Mac доступен"
: "Listener Mac недоступен"}
</StatusBadge>
<StatusBadge tone={network?.worker.broker_reachable ? "success" : "danger"}>
{network?.worker.broker_reachable
? "Worker видит broker"
: "Worker не видит broker"}
</StatusBadge>
<StatusBadge tone={network?.worker.matches_profile ? "success" : "warning"}>
{network?.worker.matches_profile
? "Профиль синхронизирован"
: "Профиль отличается"}
</StatusBadge>
</div>
<div className="compute-contour-settings__network-actions">
<Button
size="compact"
variant="secondary"
disabled={Boolean(networkAction)}
icon={<Icon name="refresh" size={14} />}
onClick={() => void refreshNetwork()}
>
{networkAction === "refresh" ? "Проверяем…" : "Проверить"}
</Button>
<Button
size="compact"
variant="secondary"
disabled={Boolean(networkAction) || networkProfileDirty}
onClick={() => void applyNetwork("broker")}
>
{networkAction === "broker" ? "Применяем…" : "Применить на Mac"}
</Button>
<Button
size="compact"
variant="secondary"
disabled={Boolean(networkAction) || networkProfileDirty}
onClick={() => void applyNetwork("worker")}
>
{networkAction === "worker" ? "Применяем…" : "Применить на Worker"}
</Button>
</div>
{networkProfileDirty ? (
<p>Сначала сохраните изменённый сетевой профиль, затем примените его.</p>
) : null}
{error ? <StatusBadge tone="danger">{error}</StatusBadge> : null}
</div>
</SettingsCard>
</>
) : null}
{activeSection === "agent" ? (
<SettingsCard
eyebrow="АГЕНТ"
title="Telegraf · универсальный сборщик"
description="Hardware и runtime собирает готовый агент. Mission Core нормализует только контур, LAB/run и стадии обработки."
actions={(
<StatusBadge tone={install?.ready ? "success" : "warning"}>
{install?.ready ? "Готов к установке" : "Нужен scoped MQTT credential"}
</StatusBadge>
)}
>
{install ? (
<div className="compute-contour-settings__install">
<dl>
<div><dt>Шаблон</dt><dd>{install.agent.configuration_template}</dd></div>
<div><dt>Секрет</dt><dd>интерактивный ввод · не хранится в UI</dd></div>
</dl>
<code>{install.command}</code>
<Button
size="compact"
variant="secondary"
icon={<Icon name="copy" size={14} />}
onClick={() => void navigator.clipboard.writeText(install.command)}
>
Копировать команду
</Button>
{install.blocked_reason ? <p>{install.blocked_reason}</p> : null}
</div>
) : (
<p className="compute-contour-settings__empty">
Сохраните контур, чтобы получить платформенную инструкцию установки.
</p>
)}
{error ? <StatusBadge tone="danger">{error}</StatusBadge> : null}
</SettingsCard>
) : null}
</div>
</FeatureSettingsWindow>
);
}
@@ -0,0 +1,38 @@
import {useEffect,useRef,useState} from 'react';
import {Button,Description,Icon,Select,SettingsCard,TextAreaField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
import {InstallerCard} from '../network/InstallerCard';
import {serverRequest,useServers,type Server} from '../../core/system/servers';
import {vpsRequest} from '../../core/fleet/vps';
export function ServerServiceSetup({server:initialServer,fixedKind,onClose,onSaved}:{server?:Server;fixedKind?:'librespeed';onClose:()=>void;onSaved:()=>void}) {
const [kind,setKind]=useState<'wireguard'|'arnavi'|'librespeed'>(fixedKind??'wireguard'),[document,setDocument]=useState(''),[filename,setFilename]=useState('');
const catalog=useServers();const [serverId,setServerId]=useState(initialServer?.id??'');
const server=initialServer??catalog.items?.find(s=>s.id===serverId);
const serviceName=kind==='librespeed'?'LibreSpeed':'WireGuard';
const [network,setNetwork]=useState(''),[interfaces,setInterfaces]=useState<{id:string;label:string}[]>([]);
const [busy,setBusy]=useState(false),[error,setError]=useState('');const file=useRef<HTMLInputElement>(null);
useEffect(()=>{let active=true;void vpsRequest<{items:{id:string;label:string}[]}>('/interfaces').then(r=>{if(active)setInterfaces(r.items);}).catch(()=>{});return()=>{active=false;};},[]);
async function connect(){if(!server)return;setBusy(true);setError('');try{
await serverRequest(`/${server.id}/services`,'POST',{kind,document:document.trim(),expected_revision:server.revision,network_interface:network||null});
setDocument('');onSaved();
}catch(e){setError(e instanceof Error?e.message:'Не удалось подключить службу.');}finally{setBusy(false);}}
return <><Window open title="Добавить службу" subtitle={server?`${server.name} · ${server.address}`:'Выберите зарегистрированный VPS'} size="lg" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}}
footer={<WindowFooterActions><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!server||!document.trim()} onClick={()=>void connect()}>Подключить службу</Button></WindowFooterActions>}>
<div className="system-catalog-form">
{!initialServer&&<Select label="VPS" value={serverId} disabled={busy} options={[{value:'',label:'Выберите VPS'},...(catalog.items??[]).map(s=>({value:s.id,label:`${s.name} · ${s.address}`}))]} onChange={id=>{setServerId(id);setDocument('');setFilename('');}}/>}
{!initialServer&&catalog.items?.length===0&&<Description>Сначала добавьте VPS в разделе «Система → VPS».</Description>}
{catalog.error&&!initialServer&&<Description>{catalog.error}</Description>}
<Select label="Служба" value={kind} disabled={busy||!!fixedKind} options={[{value:'wireguard',label:'WireGuard'},{value:'arnavi',label:'ARNavi'},{value:'librespeed',label:'LibreSpeed'}]} onChange={value=>{setKind(value as typeof kind);setDocument('');setFilename('');setError('');}}/>
<InstallerCard key={kind} connectionInstruction={kind==='librespeed'?undefined:"Вернитесь в это окно и подключите установленную службу с выданным приглашением."} kind={kind==='librespeed'?'vps-librespeed':kind==='wireguard'?'vps-wireguard':'vps-arnavi'}/>
<SettingsCard title="Подключение установленной службы" description="Запустите установщик на выбранном VPS. Затем передайте выданное им приглашение — Mission Core проверит сервер и сохранит подключение.">
{kind!=='arnavi'?<>
<input ref={file} type="file" accept=".json,application/json" hidden onChange={event=>{const chosen=event.target.files?.[0];event.target.value='';if(!chosen)return;setDocument('');setFilename('');void (async()=>{if(chosen.size>16384)throw Error(`Выберите файл приглашения ${serviceName} (до 16 КБ).`);setDocument(await chosen.text());setFilename(chosen.name);})().catch(e=>setError(e.message));}}/>
<Button icon={<Icon name="upload"/>} disabled={busy} onClick={()=>file.current?.click()}>Выбрать приглашение {serviceName}</Button>
{filename&&<Description>{filename}</Description>}
<Description>Файл на VPS: {kind==='librespeed'?'/var/lib/ndc-librespeed-vps/mission-core-librespeed.json':'/var/lib/ndc-wireguard-vps/mission-core-wireguard.json'}. Скопируйте его по защищённому соединению (например, SFTP). Приглашение действует 24 часа; новое выпускается командой connection того же установщика. {kind==='wireguard'?'Экспорт .conf из клиента WireGuard не подходит.':''}</Description>
</>:<TextAreaField label="Ключ подключения ARNavi" value={document} disabled={busy} rows={4} onChange={e=>setDocument(e.target.value)} hint="Ключ находится на VPS в /opt/nodedc-mission-vps/connect.key. Действует 24 часа и используется один раз."/>}
</SettingsCard>
{interfaces.length>0&&<Select label="Подключение к VPS" disabled={busy} value={network} options={[{value:'',label:'Через текущую сеть'},...interfaces.map(i=>({value:i.id,label:`Напрямую · ${i.label}`}))]} onChange={setNetwork}/>}
</div>
</Window><ToastStack items={error?[{id:'server-connect',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
}
@@ -0,0 +1,33 @@
import {useState} from 'react';
import {Button, Description, Icon, IconButton, LoadingRegion, SettingsCard, TextField, ToastStack, Window, WindowFooterActions} from '@nodedc/ui-react';
import {serverRequest,type Server,type ServerRemovalPlan} from '../../core/system/servers';
export function ServerSettings({server,onClose,onSaved,onRemoved}:{server?:Server;onClose:()=>void;onSaved:(server:Server)=>void;onRemoved?:()=>void}) {
const [name,setName]=useState(server?.name??''),[address,setAddress]=useState(server?.address??'');
const [busy,setBusy]=useState(false),[error,setError]=useState('');
const [removing,setRemoving]=useState(false),[plan,setPlan]=useState<ServerRemovalPlan|null>(null);
async function prepareRemoval(){if(!server)return;setRemoving(true);setPlan(null);setBusy(true);setError('');try{
setPlan(await serverRequest<ServerRemovalPlan>(`/${server.id}/removal`,'POST',{expected_revision:server.revision}));
}catch(e){setError(e instanceof Error?e.message:'Не удалось проверить подключения VPS.');}finally{setBusy(false);}}
async function remove(){if(!server||!plan||plan.blocked.length)return;setBusy(true);setError('');try{
await serverRequest(`/${server.id}`,'DELETE',{expected_revision:server.revision,confirmation:plan.confirmation});
onRemoved?.();
}catch(e){setPlan(null);setError(e instanceof Error?e.message:'Удаление не завершено. Повторите проверку.');}finally{setBusy(false);}}
async function save(){setBusy(true);setError('');try{
const item=await serverRequest<Server>(server?`/${server.id}`:'',server?'PUT':'POST',{name:name.trim(),address:address.trim(),...(server?{expected_revision:server.revision}:{})});
onSaved(item);
}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить VPS.');}finally{setBusy(false);}}
return <><Window open title={removing?'Удалить VPS?':server?'Настройки VPS':'Добавить VPS'} subtitle={server?.name}
size="md" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}}
headerActionsPlacement="before-close" headerActions={server&&!removing&&<IconButton label="Удалить VPS" disabled={busy} onClick={()=>void prepareRemoval()}><Icon name="trash"/></IconButton>}
footer={<WindowFooterActions>{removing?<><Button disabled={busy} onClick={()=>{setRemoving(false);setPlan(null);setError('');}}>Отменить</Button>{plan?<Button loading={busy} disabled={busy||!!plan.blocked.length} onClick={()=>void remove()}>Удалить</Button>:<Button loading={busy} disabled={busy} onClick={()=>void prepareRemoval()}>Повторить проверку</Button>}</>:<><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!name.trim()||!address.trim()} onClick={()=>void save()}>{server?'Сохранить':'Добавить VPS'}</Button></>}</WindowFooterActions>}>
{removing?<LoadingRegion loading={busy&&!plan} label="Проверка подключений"><SettingsCard title={`Удалить «${server?.name}» из Mission Core?`} description="Это действие нельзя отменить.">
<Description>Будут удалены карточка VPS, сохранённые подключения его служб и локальные туннели WireGuard. Для повторного подключения понадобятся новые приглашения.</Description>
<Description>Сам VPS, установленные на нём службы и данные останутся на сервере.</Description>
{plan&&<><Description>Подключения служб: {plan.services.join(', ')||'нет'}. Связанные подключения аппаратов: {plan.vehicle_connections}; воркеров: {plan.worker_connections}.</Description>{plan.blocked.map(message=><Description key={message}>{message}</Description>)}</>}
</SettingsCard></LoadingRegion>:<div className="system-catalog-form">
<TextField label="Название" placeholder="Например, Макхост · сеть парка" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
<TextField label="Адрес сервера" hint={server?.services.length?'Адрес используется подключёнными службами.':'Публичный IP-адрес или DNS-имя, без протокола и порта.'} value={address} maxLength={253} disabled={busy||!!server?.services.length} onChange={e=>setAddress(e.target.value)}/>
</div>}
</Window><ToastStack items={error?[{id:'server-save',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
}
@@ -0,0 +1,27 @@
import {useRef, useState} from "react";
import {Button, Description, Icon, StatusBadge} from "@nodedc/ui-react";
import {fleetRequest} from "../../core/fleet/useFleet";
export function ImportNetworkProfile({onImported, disabled = false}: {onImported: () => Promise<unknown>; disabled?: boolean}) {
const input = useRef<HTMLInputElement>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
return <>
<input ref={input} type="file" accept=".json,application/json" hidden onChange={event => {
const file = event.currentTarget.files?.[0]; event.currentTarget.value = "";
if (!file || busy) return;
setBusy(true); setError(null);
void (async () => {
if (file.size > 16384) throw Error("Выберите файл подключения, выданный установщиком VPS.");
await fleetRequest("/network-profiles/import", "POST", {document: await file.text()}, 240000);
await onImported();
})().catch(e => setError(e instanceof Error ? e.message : "Не удалось добавить профиль."))
.finally(() => setBusy(false));
}}/>
<Button icon={<Icon name="upload"/>} disabled={disabled || busy} loading={busy} onClick={() => input.current?.click()}>
Импортировать подключение к серверу
</Button>
<Description>Файл mission-core-wireguard.json выдаёт установщик NODE.DC на вашем VPS. Получите его у администратора этого сервера и выберите здесь. Приглашение действует 24 часа; затем администратор выпускает новое. Экспорт туннеля из приложения WireGuard (.conf) не подходит.</Description>
{error && <Description role="alert"><StatusBadge tone="warning">{error}</StatusBadge></Description>}
</>;
}
@@ -1,59 +1,13 @@
import { import {AdminNavigationPanel, Icon} from "@nodedc/ui-react";
AdminNavigationPanel, import {workspacesForRoot} from "../../productModel";
Icon,
IconButton,
} from "@nodedc/ui-react";
import { useComputeContours } from "../../core/system/ComputeContourContext"; export function SystemNavigationPanel({title, activeId, onNavigate, onClose}: {
title: string; activeId: string; onNavigate: (id: string) => void; onClose: () => void;
interface SystemNavigationPanelProps { }) {
title: string; const categories = workspacesForRoot("system").filter(item => item.kind === "workers" || item.kind === "vps");
onAdd: () => void; return <AdminNavigationPanel eyebrow="MISSION CORE" title={title}
onNavigateRoot: () => void; closeLabel={`Закрыть раздел «${title}»`} navigationLabel="Система" onClose={onClose}
onClose: () => void; contexts={categories.map(item => ({id: item.id, label: item.label, icon: <Icon name={item.icon}/>,
} active: item.id === (activeId === "vps" ? "vps" : "workers"),
onSelect: () => onNavigate(item.id)}))} items={[]} onItemChange={() => undefined}/>;
export function SystemNavigationPanel({
title,
onAdd,
onNavigateRoot,
onClose,
}: SystemNavigationPanelProps) {
const { contours, selectedContour, selectContour } = useComputeContours();
const contourCountLabel = contours.length === 1
? "1 конфигурация"
: `${contours.length} конфигураций`;
return (
<AdminNavigationPanel
eyebrow="MISSION CORE"
title={title}
closeLabel={`Закрыть раздел «${title}»`}
navigationLabel="Вычислительные контуры"
onClose={onClose}
headerActions={(
<IconButton label="Добавить вычислительный контур" onClick={onAdd}>
<Icon name="plus" size={16} strokeWidth={1.6} />
</IconButton>
)}
contexts={contours.map((contour) => ({
id: contour.contour_id,
label: contour.display_name,
description: contour.expected_node_id,
icon: <Icon name="apps" />,
active: selectedContour?.contour_id === contour.contour_id,
onSelect: () => { selectContour(contour.contour_id); onNavigateRoot(); },
}))}
items={[]}
onItemChange={() => undefined}
footer={(
<>
<span className="nodedc-admin-panel__nav-icon" aria-hidden="true">
<Icon name="activity" />
</span>
<span>{contourCountLabel}</span>
</>
)}
/>
);
} }
@@ -2,7 +2,7 @@ import { SegmentedControl } from "@nodedc/ui-react";
import { workspacesForRoot } from "../../productModel"; import { workspacesForRoot } from "../../productModel";
const systemWorkspaces = workspacesForRoot("system"); const systemWorkspaces = workspacesForRoot("system").filter(item => item.kind === "compute-modules" || item.kind === "network-monitor");
const compactLabels: Record<string, string> = { const compactLabels: Record<string, string> = {
modules: "Модули", modules: "Модули",
integrations: "Интеграции", integrations: "Интеграции",
@@ -0,0 +1,26 @@
import {useState} from "react";
import {Button, Description, Icon} from "@nodedc/ui-react";
import {connectionRequest, type TailscaleClient} from "../../core/system/workerConnections";
export function TailscaleClientStatus({client, disabled, onOpened}: {
client: TailscaleClient; disabled: boolean; onOpened: () => Promise<unknown>;
}) {
const [opening, setOpening] = useState(false);
const [error, setError] = useState<string | null>(null);
if (client.state === "connected") return null;
return <>
<Description>{client.message}</Description>
{client.state === "not_installed" ? <Button icon={<Icon name="download"/>}
onClick={() => window.open("https://tailscale.com/download", "_blank", "noopener,noreferrer")}>
Скачать Tailscale
</Button> : client.can_open ? <Button disabled={disabled || opening} loading={opening}
onClick={() => {
setOpening(true); setError(null);
void connectionRequest("/tailscale/open", {}).then(onOpened)
.catch(reason => setError(reason instanceof Error ? reason.message : "Не удалось открыть Tailscale."))
.finally(() => setOpening(false));
}}>{client.state === "needs_login" ? "Авторизироваться" : "Открыть Tailscale"}</Button>
: <Description>Откройте установленный клиент Tailscale на этом компьютере и проверьте подключение.</Description>}
{error && <Description role="alert">{error}</Description>}
</>;
}
@@ -0,0 +1,146 @@
import {useEffect, useState} from "react";
import {Button, Description, FeatureSettingsWindow, FieldFrame, Icon, IconButton,
Select, SettingsCard, StatusBadge, TextField, WindowFooterActions} from "@nodedc/ui-react";
import {connectionRequest, keepAvailableSelection, workerCandidate, type ConnectionCheck} from "../../core/system/workerConnections";
import {useConnectionCatalog} from "../../core/system/useConnectionCatalog";
import type {ComputeContour, ComputeContourDraft} from "../../core/system/computeContours";
import {ImportNetworkProfile} from "./SharedNetworkProfiles";
import {TailscaleClientStatus} from "./TailscaleClientStatus";
interface Props {open: boolean; mode: "create" | "edit"; contour: ComputeContour | null;
onClose: () => void; onChanged: () => void;
onUpdate: (contour: ComputeContour, draft: ComputeContourDraft) => Promise<ComputeContour>}
export function WorkerConnectionSettings({open, mode, contour, onClose, onChanged, onUpdate}: Props) {
const [section, setSection] = useState("connections");
const [name, setName] = useState("");
const [poll, setPoll] = useState("3");
const [provider, setProvider] = useState("tailscale");
const [profileId, setProfileId] = useState("");
const [peerId, setPeerId] = useState("");
const [selectedPath, setSelectedPath] = useState("");
const [adding, setAdding] = useState(false);
const [acting, setBusy] = useState(false);
const {catalog, refresh, discoveryError, initializing} = useConnectionCatalog(open, acting);
const busy = acting || initializing;
const [error, setError] = useState<string | null>(null);
const [check, setCheck] = useState<ConnectionCheck | null>(null);
const worker = mode === "edit" ? catalog?.workers.find(x => x.contour_id === contour?.contour_id) : null;
const enroll = !worker;
const profiles = catalog?.profiles.filter(x => x.provider === provider
&& catalog.available_profile_ids.includes(x.id)
&& !worker?.connections.some(c => c.profile_id === x.id)) ?? [];
const profile = profiles.find(x => x.id === profileId);
const peers = catalog?.peers.filter(x => x.profile_id === profileId) ?? [];
const candidate = workerCandidate(catalog, profileId, peerId);
useEffect(() => {
if (!open) return;
setError(null); setCheck(null); setAdding(false); setSelectedPath("");
setSection("connections"); setName(contour?.display_name ?? "");
setPoll(String(contour?.telemetry_poll_interval_seconds ?? 3));
}, [open, contour?.contour_id, mode]);
useEffect(() => {setSelectedPath(worker?.active_connection_id ?? "");}, [worker?.active_connection_id]);
useEffect(() => {setProfileId(current => keepAvailableSelection(current, profiles.map(x => x.id), profiles[0]?.id));}, [provider, catalog, worker?.revision]);
useEffect(() => {setPeerId(current => keepAvailableSelection(current, peers.map(x => x.id)));}, [profileId, catalog]);
const availableNetworks = catalog?.available_profile_ids.join(",");
useEffect(() => {setCheck(null);}, [availableNetworks, catalog?.tailscale_client?.state]);
async function action(fn: () => Promise<void>) {
setBusy(true); setError(null);
try {await fn();} catch (e) {setError(e instanceof Error ? e.message : "Операция не выполнена.");}
finally {setBusy(false);}
}
async function add() {
if (!catalog || !profile || !peerId) return;
await connectionRequest(enroll ? "/enroll" : `/${worker!.contour_id}/attach`, {
profile_id: profile.id, peer_id: peerId, revision: enroll ? catalog.revision : worker!.revision,
...(enroll ? {binding_id: candidate.binding?.id} : {}),
});
await refresh(); onChanged(); setAdding(false); setCheck(null);
if (mode === "create") onClose();
}
return <FeatureSettingsWindow open={open} title={mode === "create" ? "Подключить воркер" : "Настройки воркера"}
subtitle="Сетевые подключения" identity={{title: contour?.display_name ?? "Новый воркер",
subtitle: contour?.expected_node_id ?? "Подключение к Mission Core", avatarLabel: "WC"}}
sections={[{id: "connections", label: "Подключения", icon: "network", group: "ВОРКЕР"},
...(mode === "edit" ? [{id: "agent", label: "Агент", icon: "activity" as const, group: "ВОРКЕР"}] : [])]}
activeSection={section} onSectionChange={setSection} onClose={busy ? () => {} : onClose}
headerActions={<IconButton label="Обновить подключения" disabled={busy} onClick={() => void action(async () => {await refresh(); setCheck(null);})}><Icon name="refresh"/></IconButton>}
footer={<WindowFooterActions><Button onClick={onClose} disabled={busy}>Готово</Button></WindowFooterActions>}>
<div className="compute-contour-settings">
{section === "agent" && contour && <SettingsCard title="Устройство и телеметрия"
description={`Идентичность: ${contour.expected_node_id}. Платформа: ${contour.platform}.`}>
<div className="compute-contour-settings__form">
<TextField label="Название" value={name} onChange={event => setName(event.currentTarget.value)}/>
<TextField label="Обновление интерфейса, с" type="number" min={1} max={60} value={poll} onChange={event => setPoll(event.currentTarget.value)}/>
</div>
<Button disabled={busy || !name.trim() || !Number.isInteger(Number(poll)) || Number(poll) < 1 || Number(poll) > 60}
onClick={() => void action(async () => {await onUpdate(contour, {
display_name: name, expected_node_id: contour.expected_node_id, platform: contour.platform,
telemetry_mode: contour.telemetry_mode, address: contour.address, ssh_port: contour.ssh_port,
mqtt_host: contour.mqtt_host, mqtt_port: contour.mqtt_port, mqtt_bind_address: contour.mqtt_bind_address,
mqtt_publish_interval_seconds: contour.mqtt_publish_interval_seconds,
telemetry_poll_interval_seconds: Number(poll),
});})}>Сохранить</Button>
</SettingsCard>}
{section === "connections" && worker && <SettingsCard eyebrow="ПОДКЛЮЧЕНИЯ" title="Активное подключение"
description="Выбор сети относится только к этому воркеру. Другие устройства сохраняют свои подключения.">
<div className="compute-contour-settings__form compute-contour-settings__connection-row">
<FieldFrame label="Подключение"><Select label="Подключение" value={selectedPath} disabled={busy}
options={worker.connections.map(x => ({value: x.id, label: catalog?.profiles.find(p => p.id === x.profile_id)?.name ?? x.profile_id,
description: x.id === worker.active_connection_id ? "Активное" : "Подготовлено"}))}
onChange={value => {setSelectedPath(value); setCheck(null);}}/></FieldFrame>
<div className="system-workspace__actions">
<Button disabled={busy || !selectedPath} onClick={() => void action(async () => {
setCheck(await connectionRequest<ConnectionCheck>(`/${worker.contour_id}/check`, {connection_id: selectedPath, revision: worker.revision}));
})}>Проверить</Button>
<Button disabled={busy || !selectedPath || selectedPath === worker.active_connection_id} onClick={() => void action(async () => {
await connectionRequest(`/${worker.contour_id}/activate`, {connection_id: selectedPath, revision: worker.revision});
await refresh(); onChanged(); setCheck(null);
})}>Использовать</Button>
<IconButton label="Добавить подключение" disabled={busy} onClick={() => setAdding(!adding)}><Icon name="plus"/></IconButton>
</div>
</div>
{catalog?.tailscale_client && worker.connections.some(path => path.id === selectedPath
&& catalog.profiles.some(p => p.id === path.profile_id && p.provider === "tailscale"))
&& <TailscaleClientStatus client={catalog.tailscale_client} disabled={busy} onOpened={refresh}/>}
{catalog?.tailscale_client?.state === "connected" && worker.connections.some(path => path.id === selectedPath
&& !catalog.available_profile_ids.includes(path.profile_id))
&& <Description>Выбранная сеть сейчас недоступна. Подключите её в VPN-клиенте.</Description>}
{check && <><StatusBadge tone="success">Устройство подтверждено · {check.identity.hostname}</StatusBadge>
{check.active && check.channels.map(x => <Description key={x.id}><StatusBadge tone={x.connected ? "success" : "warning"}>{x.label} · {x.connected ? "соединение установлено" : "ожидает подключения"}</StatusBadge></Description>)}
{check.active && <Description>Проверка подтверждает соединения. Свежие показатели и состояние сервисов отображаются в «Модулях».</Description>}
{check.active && check.channels.length === 0 && <Description>Рабочие каналы ещё не установлены.</Description>}</>}
</SettingsCard>}
{section === "connections" && catalog && (enroll || adding) && <SettingsCard eyebrow="НОВОЕ ПОДКЛЮЧЕНИЕ" title={enroll ? "Выберите устройство" : "Добавить резервную сеть"}
description="Выберите VPN, общую сеть и компьютер. Устройства в сети могут быть воркерами, бортами или другими компьютерами.">
<div className="compute-contour-settings__form">
<FieldFrame label="Тип VPN"><Select label="Тип VPN" value={provider} disabled={busy}
options={[{value: "tailscale", label: "Tailscale"}, {value: "wireguard", label: "WireGuard"}]} onChange={setProvider}/></FieldFrame>
<FieldFrame label="Сеть"><Select label="Сеть" value={profileId} disabled={busy || !profiles.length}
options={profiles.map(x => ({value: x.id, label: x.name}))} onChange={setProfileId}/></FieldFrame>
<FieldFrame label="Устройство в сети"><Select label="Устройство в сети" value={peerId} disabled={busy || !peers.length}
options={[{value: "", label: "Выберите устройство"}, ...peers.map(x => ({value: x.id, label: x.name,
description: workerCandidate(catalog, profileId, x.id).enrolled ? "Уже подключён к Mission Core" : x.online === false ? "Не в сети" : "Доступен в VPN"}))]} onChange={setPeerId}/></FieldFrame>
</div>
{provider === "tailscale" && catalog.tailscale_client
&& <TailscaleClientStatus client={catalog.tailscale_client} disabled={busy} onOpened={refresh}/>}
{enroll && candidate.enrolled && <Description>Этот воркер уже подключён. Его сети можно изменить через настройки в разделе «Система».</Description>}
{enroll && candidate.peer && !candidate.enrolled && !candidate.binding && <Description>Устройство найдено в VPN, но доступ Mission Core к нему ещё не настроен. Сначала требуется подготовка агента и доступа на самом компьютере. Одного подключения к VPN недостаточно.</Description>}
{enroll && candidate.binding && <Description>Доступ к {candidate.binding.name} подготовлен. При добавлении проверим устройство и его ключ.</Description>}
{provider === "tailscale" && <Description>Сеть берётся из приложения Tailscale на этом Mac. Чтобы увидеть новый компьютер, подключите его к той же сети Tailscale.</Description>}
{provider === "wireguard" && <Description>Здесь перечислены серверы WireGuard, добавленные в Mission Core. Адрес в названии относится к серверу VPN, а не к воркеру.</Description>}
{provider === "wireguard" && !peers.length && <Description>Сервер не сообщает о зарегистрированных воркерах. Здесь показан его реестр устройств; поиск остальных компьютеров в туннеле не выполняется.</Description>}
{provider === "wireguard" && <ImportNetworkProfile disabled={busy} onImported={refresh}/>}
{!profiles.length && <Description>Доступных новых профилей этого типа нет.</Description>}
<Button variant="primary" disabled={busy || !profile || !peerId || candidate.peer?.online === false || (enroll && (!candidate.binding || Boolean(candidate.enrolled)))} onClick={() => void action(add)}>
{busy ? "Проверяем…" : "Проверить и добавить"}</Button>
</SettingsCard>}
{busy && <Description>Проверяем подключение…</Description>}
{error && <Description role="alert"><StatusBadge tone="warning">{error}</StatusBadge></Description>}
{discoveryError && <Description role="alert">{discoveryError}</Description>}
{catalog?.notice && catalog.notice !== catalog.tailscale_client?.message && <Description>{catalog.notice}</Description>}
</div>
</FeatureSettingsWindow>;
}
@@ -2,7 +2,8 @@ import { useCallback, useMemo, useState, type ReactNode } from "react";
import type { ApplicationPanelUtilityAction } from "@nodedc/ui-react"; import type { ApplicationPanelUtilityAction } from "@nodedc/ui-react";
import { useComputeContours } from "../../core/system/ComputeContourContext"; import { useComputeContours } from "../../core/system/ComputeContourContext";
import { ComputeContourSettingsWindow } from "./ComputeContourSettingsWindow"; import { WorkerConnectionSettings } from "./WorkerConnectionSettings";
import { useWorkerPower } from "./useWorkerPower";
interface ComputeContourSettingsController { interface ComputeContourSettingsController {
canEdit: boolean; canEdit: boolean;
@@ -14,6 +15,7 @@ interface ComputeContourSettingsController {
export function useComputeContourSettings(): ComputeContourSettingsController { export function useComputeContourSettings(): ComputeContourSettingsController {
const contours = useComputeContours(); const contours = useComputeContours();
const power = useWorkerPower(contours.selectedContour);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [mode, setMode] = useState<"create" | "edit">("edit"); const [mode, setMode] = useState<"create" | "edit">("edit");
const openCreate = useCallback(() => { const openCreate = useCallback(() => {
@@ -47,16 +49,16 @@ export function useComputeContourSettings(): ComputeContourSettingsController {
canEdit: contours.selectedContour !== null, canEdit: contours.selectedContour !== null,
openCreate, openCreate,
openEdit, openEdit,
utilityActions, utilityActions: [...utilityActions, power.action],
window: ( window: (
<ComputeContourSettingsWindow <><WorkerConnectionSettings
open={open} open={open}
mode={mode} mode={mode}
contour={contours.selectedContour} contour={mode === "create" ? null : contours.selectedContour}
onClose={() => setOpen(false)} onClose={() => setOpen(false)}
onCreate={contours.createContour} onChanged={() => {contours.refresh(); contours.refreshTelemetry();}}
onUpdate={contours.updateContour} onUpdate={contours.updateContour}
/> />{power.window}</>
), ),
}; };
} }
@@ -0,0 +1,42 @@
import {useState} from "react";
import { Description,Button, ConfirmationModal, Window, WindowFooterActions, type ApplicationPanelUtilityAction} from "@nodedc/ui-react";
import {connectionRequest} from "../../core/system/workerConnections";
import type {ComputeContour} from "../../core/system/computeContours";
export function useWorkerPower(contour: ComputeContour | null) {
const [busy, setBusy] = useState(false);
const [pending, setPending] = useState<{id: string; name: string; confirmation: string} | null>(null);
const [message, setMessage] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const action: ApplicationPanelUtilityAction = {
label: "Выключить воркер", icon: "power", disabled: !contour || busy,
onClick: () => {if (!contour) return; setBusy(true); setError(null);
const selected = contour;
void connectionRequest<{confirmation: string}>(`/${selected.contour_id}/power/prepare`, {})
.then(value => setPending({id: selected.contour_id, name: selected.display_name, confirmation: value.confirmation}))
.catch(e => setMessage(e instanceof Error ? e.message : "Воркер недоступен."))
.finally(() => setBusy(false));
},
};
const window = <>
<ConfirmationModal open={pending !== null} title="Выключить воркер?" danger
confirmLabel="Да, выключить" pendingLabel="Передаём команду…" onClose={() => {if (!busy) setPending(null);}}
description={<><Description>Воркер «{pending?.name}» завершит работу. Выполняемые на нём задачи будут прерваны. Для включения потребуется доступ к компьютеру.</Description>
{error && <Description role="alert">{error}</Description>}</>}
onConfirm={async () => {
if (!pending || busy) return;
setBusy(true); setError(null);
try {
const result = await connectionRequest<{message: string}>(`/${pending.id}/power/shutdown`, {confirmation: pending.confirmation});
setPending(null); setMessage(result.message);
} catch (e) {
setPending(null); setMessage(e instanceof Error ? e.message : "Ответ не получен. Автоматического повтора нет.");
} finally {setBusy(false);}
}}/>
<Window open={message !== null} title="Питание воркера" size="sm" onClose={() => setMessage(null)}
footer={<WindowFooterActions><Button onClick={() => setMessage(null)}>Понятно</Button></WindowFooterActions>}>
<Description role="status">{message}</Description>
</Window>
</>;
return {action, window};
}
@@ -69,7 +69,7 @@ export function useApplicationPanelActions({
onClick: () => void saveWorkspaceLayout(), onClick: () => void saveWorkspaceLayout(),
}); });
} }
if (definition?.root === "system") actions.push(...systemUtilityActions); if (definition && ["compute-modules", "network-monitor"].includes(definition.kind)) actions.push(...systemUtilityActions);
if (definition?.kind === "recordings" && sessionOverview) actions.push({ if (definition?.kind === "recordings" && sessionOverview) actions.push({
label: sessionOverview.open ? "Закрыть информацию о записи" : "Информация о записи", label: sessionOverview.open ? "Закрыть информацию о записи" : "Информация о записи",
icon: "info", pressed: sessionOverview.open, disabled: !sessionOverview.available, icon: "info", pressed: sessionOverview.open, disabled: !sessionOverview.available,
@@ -1,10 +1,10 @@
import {defaultGlassMaterial,type GlassMaterialSettings} from '@nodedc/ui-core'; import {defaultGlassMaterial,type GlassMaterialSettings} from '@nodedc/ui-core';
export type CellMarkingAppearance={color:string;size:number}; export type CellMarkingAppearance={color:string;size:number};
export type BatteryPanelAppearance={height:number;radius:number;labelSize:number;valueSize:number;textColor:string;glass:GlassMaterialSettings}; export type BatteryPanelAppearance={height:number;radius:number;labelSize:number;valueSize:number;textColor:string;glass:GlassMaterialSettings};
export type BatteryIndicatorAppearance={mode:'ranges'|'mono';color:string;lowColor:string;middleColor:string;highColor:string;lowUntil:number;middleUntil:number}; export type BatteryIndicatorAppearance={offset:number;width:number;height:number;radius:number;mode:'ranges'|'mono';color:string;lowColor:string;middleColor:string;highColor:string;lowUntil:number;middleUntil:number};
export type BatteryAppearance={schema:'missioncore.battery-ui/v1';markings:CellMarkingAppearance;panels:BatteryPanelAppearance;indicator:BatteryIndicatorAppearance}; export type BatteryAppearance={schema:'missioncore.battery-ui/v1';markings:CellMarkingAppearance;panels:BatteryPanelAppearance;indicator:BatteryIndicatorAppearance};
export const batteryAppearanceKey=(id:string)=>`missioncore.battery-ui/v1:${id}`; export const batteryAppearanceKey=(id:string)=>`missioncore.battery-ui/v1:${id}`;
export function defaultBatteryAppearance():BatteryAppearance{return {schema:'missioncore.battery-ui/v1',markings:{color:'#ffffff',size:100},indicator:{mode:'ranges',color:'#f1f1ef',lowColor:'#ff7474',middleColor:'#ffd166',highColor:'#b5ff5a',lowUntil:15,middleUntil:30},panels:{height:76,radius:24,labelSize:12,valueSize:18,textColor:'#f1f1ef',glass:{...defaultGlassMaterial,tintOpacity:52,blur:18}}};} export function defaultBatteryAppearance():BatteryAppearance{return {schema:'missioncore.battery-ui/v1',markings:{color:'#ffffff',size:100},indicator:{offset:0,width:115,height:46,radius:23,mode:'ranges',color:'#f1f1ef',lowColor:'#ff7474',middleColor:'#ffd166',highColor:'#b5ff5a',lowUntil:15,middleUntil:30},panels:{height:76,radius:24,labelSize:12,valueSize:13,textColor:'#f1f1ef',glass:{...defaultGlassMaterial,tintOpacity:52,blur:18}}};}
const object=(v:unknown):Record<string,unknown>=>v!==null&&typeof v==='object'?v as Record<string,unknown>:{}; const object=(v:unknown):Record<string,unknown>=>v!==null&&typeof v==='object'?v as Record<string,unknown>:{};
const number=(v:unknown,fallback:number,min:number,max:number)=>typeof v==='number'&&Number.isFinite(v)?Math.min(max,Math.max(min,v)):fallback; const number=(v:unknown,fallback:number,min:number,max:number)=>typeof v==='number'&&Number.isFinite(v)?Math.min(max,Math.max(min,v)):fallback;
const color=(v:unknown,fallback:string)=>typeof v==='string'&&/^#[0-9a-f]{6}$/i.test(v)?v.toLowerCase():fallback; const color=(v:unknown,fallback:string)=>typeof v==='string'&&/^#[0-9a-f]{6}$/i.test(v)?v.toLowerCase():fallback;
@@ -12,7 +12,7 @@ export function parseBatteryAppearance(raw:unknown):BatteryAppearance{
const source=object(raw);if(source.schema!=='missioncore.battery-ui/v1')throw new Error('Это не профиль интерфейса батареи.'); const source=object(raw);if(source.schema!=='missioncore.battery-ui/v1')throw new Error('Это не профиль интерфейса батареи.');
const d=defaultBatteryAppearance(),m=object(source.markings),p=object(source.panels),g=object(p.glass),i=object(source.indicator); const d=defaultBatteryAppearance(),m=object(source.markings),p=object(source.panels),g=object(p.glass),i=object(source.indicator);
const lowUntil=number(i.lowUntil,15,0,99),middleUntil=number(i.middleUntil,30,lowUntil+1,100); const lowUntil=number(i.lowUntil,15,0,99),middleUntil=number(i.middleUntil,30,lowUntil+1,100);
return {schema:d.schema,indicator:{mode:i.mode==='mono'?'mono':'ranges',color:color(i.color,d.indicator.color),lowColor:color(i.lowColor,d.indicator.lowColor),middleColor:color(i.middleColor,d.indicator.middleColor),highColor:color(i.highColor,d.indicator.highColor),lowUntil,middleUntil},markings:{color:color(m.color,d.markings.color),size:number(m.size,100,50,160)},panels:{height:number(p.height,76,56,160),radius:number(p.radius,24,0,48),labelSize:number(p.labelSize,12,10,20),valueSize:number(p.valueSize,18,12,30),textColor:color(p.textColor,d.panels.textColor),glass:{...d.panels.glass,tintHex:color(g.tintHex,d.panels.glass.tintHex),tintOpacity:number(g.tintOpacity,52,0,100),blur:number(g.blur,18,0,60)}}}; return {schema:d.schema,indicator:{offset:number(i.offset,0,0,320),width:number(i.width,115,32,320),height:number(i.height,46,12,96),radius:number(i.radius,23,0,48),mode:i.mode==='mono'?'mono':'ranges',color:color(i.color,d.indicator.color),lowColor:color(i.lowColor,d.indicator.lowColor),middleColor:color(i.middleColor,d.indicator.middleColor),highColor:color(i.highColor,d.indicator.highColor),lowUntil,middleUntil},markings:{color:color(m.color,d.markings.color),size:number(m.size,100,50,160)},panels:{height:number(p.height,76,56,160),radius:number(p.radius,24,0,48),labelSize:number(p.labelSize,12,10,20),valueSize:number(p.valueSize,13,12,30),textColor:color(p.textColor,d.panels.textColor),glass:{...d.panels.glass,tintHex:color(g.tintHex,d.panels.glass.tintHex),tintOpacity:number(g.tintOpacity,52,0,100),blur:number(g.blur,18,0,60)}}};
} }
export function batteryIndicatorColor(value:BatteryIndicatorAppearance,soc:number|null):string|undefined{ export function batteryIndicatorColor(value:BatteryIndicatorAppearance,soc:number|null):string|undefined{
@@ -1,3 +1,4 @@
import {legacyRecord,profileClient} from '../roverScene/profileClient';
import {defaultChargeGradient} from '../roverScene/chargeGradient'; import {defaultChargeGradient} from '../roverScene/chargeGradient';
import r04 from './r04.json'; import r04 from './r04.json';
import {defaultScene,parseScene,type SceneDocument} from '../roverScene/sceneDocument'; import {defaultScene,parseScene,type SceneDocument} from '../roverScene/sceneDocument';
@@ -6,29 +7,18 @@ import type {SceneDocumentProfile} from '../roverScene/useSceneDocument';
export function defaultBatteryScene():SceneDocument { export function defaultBatteryScene():SceneDocument {
return {...defaultScene(),schema:'missioncore.battery-scene/v1',model:'catl-r04/v1', return {...defaultScene(),schema:'missioncore.battery-scene/v1',model:'catl-r04/v1',
materials:{...structuredClone(r04.materials),'bms/cells':{...structuredClone(r04.materials['bms/cells']),chargeGradient:defaultChargeGradient()}},assignments:{},objects:{...r04.objects}}; materials:{...structuredClone(r04.materials),'bms/cells':{...structuredClone(r04.materials['bms/cells']),color:'#050505',emissiveIntensity:0,chargeGradient:defaultChargeGradient()}},assignments:{},objects:{...r04.objects}};
} }
function database():Promise<IDBDatabase>{return new Promise((resolve,reject)=>{
const request=indexedDB.open('missioncore-battery-scenes',1);
request.onupgradeneeded=()=>request.result.createObjectStore('scenes');
request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error);
request.onblocked=()=>reject(new Error('Хранилище батареи занято другим окном.'));
});}
async function save(id:string,document:SceneDocument){const db=await database();try{await new Promise<void>((resolve,reject)=>{
const tx=db.transaction('scenes','readwrite');tx.objectStore('scenes').put(document,id);
tx.oncomplete=()=>resolve();tx.onerror=()=>reject(tx.error);tx.onabort=()=>reject(tx.error);
});}finally{db.close();}}
export function batterySceneProfile(seedKey?:string):SceneDocumentProfile { export function batterySceneProfile(seedKey?:string):SceneDocumentProfile {
return {defaults:defaultBatteryScene,write:save,filename:'battery-r04-scene.json',read:async id=>{ const clients=new Map<string,ReturnType<typeof profileClient<SceneDocument>>>();
const db=await database();let raw:unknown;try{raw=await new Promise((resolve,reject)=>{ const client=(id:string)=>{let c=clients.get(id);if(!c){c=profileClient<SceneDocument>('battery',id);clients.set(id,c);}return c;};
const request=db.transaction('scenes').objectStore('scenes').get(id); return {defaults:defaultBatteryScene,write:(id,doc)=>client(id).write(doc),filename:'battery-r04-scene.json',read:async id=>{
request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error); const raw=await client(id).read(async()=>{const old=await legacyRecord('missioncore-battery-scenes','scenes',id);return old?parseScene(old,defaultBatteryScene):null;});
});}finally{db.close();}
if(raw)return parseScene(raw,defaultBatteryScene); if(raw)return parseScene(raw,defaultBatteryScene);
const seed=seedKey?await readScene(seedKey):null; const seed=seedKey?await readScene(seedKey):null;
const doc=defaultBatteryScene(); const doc=defaultBatteryScene();
if(seed){doc.postFx=structuredClone(seed.postFx);doc.cameraAutoRotate=seed.cameraAutoRotate;doc.cameraZoomStrength=seed.cameraZoomStrength;} if(seed){doc.postFx=structuredClone(seed.postFx);doc.cameraAutoRotate=seed.cameraAutoRotate;doc.cameraZoomStrength=seed.cameraZoomStrength;}
// Copy once. Subsequent rover edits and battery edits have separate owners. // Defaults remain in memory until an explicit edit. Never overwrite a failed read.
await save(id,doc);return doc; return doc;
}}; }};
} }
@@ -1,14 +1,23 @@
import {useCallback,useEffect,useState} from 'react'; import {useCallback,useEffect,useMemo,useRef,useState} from 'react';
import {SceneHistory,historyCommand} from '../roverScene/sceneHistory'; import {SceneHistory,historyCommand} from '../roverScene/sceneHistory';
import {profileClient} from '../roverScene/profileClient';
import {batteryAppearanceKey,defaultBatteryAppearance,parseBatteryAppearance,type BatteryAppearance} from './appearance'; import {batteryAppearanceKey,defaultBatteryAppearance,parseBatteryAppearance,type BatteryAppearance} from './appearance';
async function legacy(id:string){const raw=localStorage.getItem(batteryAppearanceKey(id));return raw?parseBatteryAppearance(JSON.parse(raw)):null;}
export function useBatteryAppearance(id:string,active:boolean){ export function useBatteryAppearance(id:string,active:boolean){
const [error,setError]=useState(''); const [error,setError]=useState(''),[ready,setReady]=useState(false);
const [history]=useState(()=>{let profile=defaultBatteryAppearance();try{const raw=localStorage.getItem(batteryAppearanceKey(id));if(raw)profile=parseBatteryAppearance(JSON.parse(raw));}catch{/* Keep the usable default if the local profile is unavailable. */}return new SceneHistory(profile);}); const client=useMemo(()=>profileClient<BatteryAppearance>('battery-ui',id),[id]);
const [value,setValue]=useState(history.present); const history=useMemo(()=>new SceneHistory(defaultBatteryAppearance()),[id]);
const publish=useCallback(()=>{setValue(history.present);try{localStorage.setItem(batteryAppearanceKey(id),JSON.stringify(history.present));window.dispatchEvent(new CustomEvent('missioncore:battery-ui',{detail:id}));setError('');}catch{setError('Не удалось сохранить настройки батареи на этом компьютере.');}},[history,id]); const [value,setValue]=useState(history.present),loaded=useRef(false);
const update=useCallback((next:BatteryAppearance)=>{if(JSON.stringify(next)!==JSON.stringify(history.present)){history.update(next);publish();}},[history,publish]); const pending=useRef<BatteryAppearance|null>(null),timer=useRef<ReturnType<typeof setTimeout>|null>(null);
const undo=useCallback(()=>{if(history.undo())publish();},[history,publish]); const flush=useCallback(()=>{if(timer.current)clearTimeout(timer.current);const next=pending.current;if(!next)return;pending.current=null;
const redo=useCallback(()=>{if(history.redo())publish();},[history,publish]); void client.write(next).then(()=>{window.dispatchEvent(new CustomEvent('missioncore:battery-ui',{detail:id}));setError('');}).catch(e=>setError(e instanceof Error?e.message:'Не удалось сохранить оформление батареи.'));
},[client,id]);
useEffect(()=>{let cancelled=false;loaded.current=false;setReady(false);setError('');client.read(()=>legacy(id)).then(raw=>{if(!cancelled){const next=raw?parseBatteryAppearance(raw):defaultBatteryAppearance();history.reset(next);setValue(next);loaded.current=true;setReady(true);}}).catch(e=>{if(!cancelled)setError(e instanceof Error?e.message:'Не удалось прочитать оформление батареи.');});return()=>{cancelled=true;loaded.current=false;flush();};},[client,history,id,flush]);
useEffect(()=>{window.addEventListener('pagehide',flush);return()=>window.removeEventListener('pagehide',flush);},[flush]);
const publish=useCallback(()=>{setValue(history.present);pending.current=history.present;if(timer.current)clearTimeout(timer.current);timer.current=setTimeout(flush,300);},[history,flush]);
const update=useCallback((next:BatteryAppearance)=>{if(!loaded.current){setError('Дождитесь загрузки профиля.');return;}if(JSON.stringify(next)!==JSON.stringify(history.present)){history.update(next);publish();}},[history,publish]);
const undo=useCallback(()=>{if(loaded.current&&history.undo())publish();},[history,publish]);
const redo=useCallback(()=>{if(loaded.current&&history.redo())publish();},[history,publish]);
useEffect(()=>{ useEffect(()=>{
if(!active)return; if(!active)return;
const begin=()=>history.begin(),end=()=>history.end(); const begin=()=>history.begin(),end=()=>history.end();
@@ -17,18 +26,18 @@ export function useBatteryAppearance(id:string,active:boolean){
window.addEventListener('keydown',key,true);window.addEventListener('keyup',up,true);window.addEventListener('pointerdown',begin,true);window.addEventListener('pointerup',end);window.addEventListener('pointercancel',end);window.addEventListener('blur',end); window.addEventListener('keydown',key,true);window.addEventListener('keyup',up,true);window.addEventListener('pointerdown',begin,true);window.addEventListener('pointerup',end);window.addEventListener('pointercancel',end);window.addEventListener('blur',end);
return()=>{end();window.removeEventListener('keydown',key,true);window.removeEventListener('keyup',up,true);window.removeEventListener('pointerdown',begin,true);window.removeEventListener('pointerup',end);window.removeEventListener('pointercancel',end);window.removeEventListener('blur',end);}; return()=>{end();window.removeEventListener('keydown',key,true);window.removeEventListener('keyup',up,true);window.removeEventListener('pointerdown',begin,true);window.removeEventListener('pointerup',end);window.removeEventListener('pointercancel',end);window.removeEventListener('blur',end);};
},[active,history,undo,redo]); },[active,history,undo,redo]);
return {value,update,undo,redo,canUndo:history.canUndo,canRedo:history.canRedo,error,setError}; return {value,ready,update,undo,redo,canUndo:history.canUndo,canRedo:history.canRedo,error,setError};
} }
/** Read-only subscribers update immediately when this battery's design is edited. */ /** Read-only subscribers share the persistent Core profile, across browsers. */
export function useBatteryAppearanceValue(id:string|undefined){ export function useBatteryAppearanceValue(id:string|undefined){
const [value,setValue]=useState(defaultBatteryAppearance); const [value,setValue]=useState(defaultBatteryAppearance);
useEffect(()=>{ useEffect(()=>{
const read=()=>{try{const raw=id&&localStorage.getItem(batteryAppearanceKey(id));setValue(raw?parseBatteryAppearance(JSON.parse(raw)):defaultBatteryAppearance());}catch{setValue(defaultBatteryAppearance());}}; let cancelled=false;
const read=()=>{if(!id){setValue(defaultBatteryAppearance());return;}void profileClient<BatteryAppearance>('battery-ui',id).read(()=>legacy(id)).then(raw=>{if(!cancelled)setValue(raw?parseBatteryAppearance(raw):defaultBatteryAppearance());}).catch(()=>{/* Retain the current indicator on a temporary Core disconnect. */});};
const local=(event:Event)=>{if((event as CustomEvent).detail===id)read();}; const local=(event:Event)=>{if((event as CustomEvent).detail===id)read();};
const external=(event:StorageEvent)=>{if(!event.key||event.key===(id&&batteryAppearanceKey(id)))read();}; read();window.addEventListener('missioncore:battery-ui',local);window.addEventListener('focus',read);
read();window.addEventListener('missioncore:battery-ui',local);window.addEventListener('storage',external); return()=>{cancelled=true;window.removeEventListener('missioncore:battery-ui',local);window.removeEventListener('focus',read);};
return()=>{window.removeEventListener('missioncore:battery-ui',local);window.removeEventListener('storage',external);};
},[id]); },[id]);
return value; return value;
} }
@@ -0,0 +1,14 @@
import {useEffect,useMemo,useState} from 'react';
import {profileClient} from '../roverScene/profileClient';
import {batteryViewHeight,batteryViewHeightKey} from './viewHeight';
type View={schema:'missioncore.battery-view/v1';height:number};
export function useBatteryView(id:string){
const client=useMemo(()=>profileClient<View>('battery-view',id),[id]);
const [height,setHeight]=useState(()=>batteryViewHeight(null,window.innerHeight));
const [ready,setReady]=useState(false),[error,setError]=useState('');
useEffect(()=>{let cancelled=false;setReady(false);setError('');void client.read(async()=>{
const raw=localStorage.getItem(batteryViewHeightKey(id));return raw?{schema:'missioncore.battery-view/v1',height:batteryViewHeight(raw,window.innerHeight)}:null;
}).then(value=>{if(!cancelled){setHeight(batteryViewHeight(JSON.stringify(value),window.innerHeight));setReady(true);}}).catch(e=>{if(!cancelled)setError(e.message);});return()=>{cancelled=true;};},[client,id]);
const commitHeight=(value:number)=>{if(!ready)return;void client.write({schema:'missioncore.battery-view/v1',height:value}).then(()=>setError('')).catch(e=>setError(e.message));};
return {height,setHeight,commitHeight,ready,error,setError};
}
@@ -42,7 +42,7 @@ const defaultQuickActions: Record<
observation: ["cameras", "world-map"], observation: ["cameras", "world-map"],
missions: ["routes", null], missions: ["routes", null],
data: ["recordings", "datasets"], data: ["recordings", "datasets"],
system: ["modules", "integrations"], system: ["modules", "network"],
polygon: ["observatory", "local-device"], polygon: ["observatory", "local-device"],
}; };
@@ -3,5 +3,5 @@ import {fleetRequest} from './useFleet';
export function routerTransport(vehicleID:string):RouterTransport{ export function routerTransport(vehicleID:string):RouterTransport{
const base=`/${encodeURIComponent(vehicleID)}/routers`; const base=`/${encodeURIComponent(vehicleID)}/routers`;
return {control:value=>fleetRequest(base+'/control','POST',value),read:()=>fleetRequest(base),authorize:value=>fleetRequest(base+'/access','POST',value),operation:id=>fleetRequest(base+'/access/'+encodeURIComponent(id))}; return {inspect:value=>fleetRequest(base+'/inspect','POST',value),control:value=>fleetRequest(base+'/control','POST',value),read:()=>fleetRequest(base),authorize:value=>fleetRequest(base+'/access','POST',value),operation:id=>fleetRequest(base+'/access/'+encodeURIComponent(id))};
} }
@@ -0,0 +1,57 @@
import { resolveObservationSessionReplay } from "../observation/useObservationSessions";
import type { ObservationSessionReplayLaunch } from "../observation/sessionArchive";
import type { CanonicalLabReplayDescriptor } from "./canonicalLabReplay";
export interface LabReplayProgress {
phase: "checking" | "preparing" | "opening";
fraction: number | null;
}
export type LabReplayResolver = (id: string, base: ObservationSessionReplayLaunch,
options: { signal: AbortSignal }) => Promise<CanonicalLabReplayDescriptor>;
/** Shared preparation for the eye, download and offline pin. Never runs inference. */
export async function prepareLabReplay(id: string, sourceId: string, resolve: LabReplayResolver,
{ signal, onProgress, fetcher }: {
signal: AbortSignal;
onProgress?: (progress: LabReplayProgress) => void;
fetcher?: typeof fetch;
}) {
const request = new AbortController();
const abort = () => request.abort();
signal.addEventListener("abort", abort, { once: true });
const timer = globalThis.setTimeout(abort, 30 * 60 * 1000);
const publish = (progress: LabReplayProgress) => {
request.signal.throwIfAborted();
onProgress?.(progress);
};
try {
signal.throwIfAborted();
publish({ phase: "checking", fraction: null });
const base = await resolveObservationSessionReplay(sourceId, {
signal: request.signal, fetcher, maximumWaitMs: 30 * 60 * 1000,
onUpdate: (state) => publish({ phase: "preparing", fraction: state.progress }),
});
publish({ phase: "preparing", fraction: null });
const replay = await resolve(id, base, { signal: request.signal });
request.signal.throwIfAborted();
return { base, replay };
} catch (error) {
if (request.signal.aborted && !signal.aborted) {
throw new Error("Подготовка записи заняла слишком много времени. Повторите загрузку.");
}
throw error;
} finally {
globalThis.clearTimeout(timer);
signal.removeEventListener("abort", abort);
}
}
export function labReplayProgressView(progress: LabReplayProgress) {
const labels = { checking: "Проверка доступности записи", preparing: "Подготовка записи",
opening: "Открытие записи" };
const value = progress.fraction === null || !Number.isFinite(progress.fraction)
? undefined : Math.min(1, Math.max(0, progress.fraction));
return { label: labels[progress.phase], value,
text: value === undefined ? labels[progress.phase]
: `${labels[progress.phase]} · ${Math.round(value * 100)}%` };
}
@@ -170,9 +170,8 @@ function evidenceFromSession(
`LAB-каталог вернул сессию ${session.id} без типизированной связи с источником.`, `LAB-каталог вернул сессию ${session.id} без типизированной связи с источником.`,
); );
} }
// Historical LABs retain their archive and replay adapters. Observatory is // History follows source identity. Playback admission remains independently
// the portable-profile product; a familiar LAB label is not admission. // validated below; an unavailable viewer must never erase a completed run.
if (session.lab.replayCapability?.kind !== "portable-result-review") return null;
const recordedRun = observatoryRecordedRunBinding(session.id, session.lab); const recordedRun = observatoryRecordedRunBinding(session.id, session.lab);
return { return {
sessionId: session.id, sessionId: session.id,
@@ -303,12 +302,10 @@ async function readCatalogPages(
throw new ObservatoryCatalogContractError("Каталог повторил сессию между страницами."); throw new ObservatoryCatalogContractError("Каталог повторил сессию между страницами.");
} }
seenIds.add(item.id); seenIds.add(item.id);
// Do not accumulate legacy provenance while walking the shared catalog. if (scope === "laboratory" && !item.lab) {
if (scope === "source" || item.lab?.replayCapability?.kind === "portable-result-review") {
items.push(item);
} else if (!item.lab) {
throw new ObservatoryCatalogContractError("LAB-каталог вернул исходную сессию."); throw new ObservatoryCatalogContractError("LAB-каталог вернул исходную сессию.");
} }
items.push(item);
} }
cursor = page.nextCursor; cursor = page.nextCursor;
if (cursor === null) return { items, hasMore: false }; if (cursor === null) return { items, hasMore: false };
@@ -1,3 +1,4 @@
import type { ObservatoryEvidence } from "./catalog";
import type { ObservatoryRecordedRunBinding } from "./recordedRun"; import type { ObservatoryRecordedRunBinding } from "./recordedRun";
const SAFE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; const SAFE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
@@ -26,7 +27,7 @@ export class ObservatoryCatalogMutationError extends Error {
} }
export async function renameObservatoryLabProjection( export async function renameObservatoryLabProjection(
binding: ObservatoryRecordedRunBinding, binding: ObservatoryRecordedRunBinding | Pick<ObservatoryEvidence, "sessionId" | "lab">,
displayName: string, displayName: string,
{ {
signal, signal,
@@ -78,7 +79,7 @@ export async function renameObservatoryLabProjection(
} }
export async function deleteObservatoryLabProjection( export async function deleteObservatoryLabProjection(
binding: ObservatoryRecordedRunBinding, binding: ObservatoryRecordedRunBinding | Pick<ObservatoryEvidence, "sessionId" | "lab">,
{ {
signal, signal,
fetcher = globalThis.fetch, fetcher = globalThis.fetch,
@@ -113,7 +114,16 @@ export async function deleteObservatoryLabProjection(
} }
} }
function admittedProjectionId(binding: ObservatoryRecordedRunBinding): string { function admittedProjectionId(binding: ObservatoryRecordedRunBinding | Pick<ObservatoryEvidence, "sessionId" | "lab">): string {
// Catalog ownership is independent of whether this client supports replay.
// The server verifies the typed LAB projection against its source rows.
if ("lab" in binding) {
if (!SAFE_SESSION_ID.test(binding.sessionId) || !binding.lab.labId
|| !binding.lab.resultId || binding.lab.sourceSessionId === binding.sessionId) {
throw new ObservatoryCatalogMutationError("Выбранный результат не допущен к изменению каталога AI Inference.");
}
return binding.sessionId;
}
const sessionId = binding.evidenceSessionId; const sessionId = binding.evidenceSessionId;
const admittedViewer = ( const admittedViewer = (
binding.kind === "canonical-recorded-rerun" binding.kind === "canonical-recorded-rerun"
@@ -0,0 +1,24 @@
import type { ObservatoryRecordedJob, ObservatoryRecordedJobFetch } from "./recordedJobs";
export function failedRunDetail(job: Pick<ObservatoryRecordedJob, "terminalMessage">): string {
const message = job.terminalMessage ?? "";
if (/source-member|source transport|Content-Length|camera-source/i.test(message)) {
return "Не удалось подготовить исходную запись";
}
if (/assemble|export|presentation/i.test(message)) return "Не удалось собрать запись результата";
if (/Docker Engine|container.*start|start.*container/i.test(message)) return "Не удалось запустить вычислительный контейнер";
if (/exit 143|exit=143|cancel|interrupted/i.test(message)) return "Расчёт прерван до получения результата";
if (/prepare/i.test(message)) return "Ошибка подготовки расчёта";
return "Расчёт завершился ошибкой; готового результата нет";
}
export async function deleteFailedRunProjection(
job: Pick<ObservatoryRecordedJob, "jobId" | "state" | "resultId">,
fetcher: ObservatoryRecordedJobFetch = globalThis.fetch,
): Promise<void> {
if (!/^observatory-run-[a-f0-9]{32}$/.test(job.jobId) || job.state !== "failed" || job.resultId !== null) {
throw new Error("Удалить можно только ошибочную попытку без результата.");
}
const response = await fetcher(`/api/v1/observatory/ai-runs/${encodeURIComponent(job.jobId)}`, { method: "DELETE" });
if (response.status !== 204) throw new Error("Не удалось удалить попытку из истории. Обновите список и повторите.");
}
@@ -1,132 +0,0 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
fetchObservatoryPortableLaboratorySetups,
preflightObservatoryLaboratorySetup,
selectableObservatorySetups,
type ObservatoryLaboratoryRunPreflight,
type ObservatoryLaboratorySetupCatalog,
} from "./laboratorySetups";
type SetupCatalogState = "idle" | "loading" | "ready" | "refreshing" | "error";
export type SetupPreflightState =
| { readonly kind: "idle" }
| { readonly kind: "checking" }
| { readonly kind: "ready"; readonly value: ObservatoryLaboratoryRunPreflight }
| { readonly kind: "error"; readonly message: string };
export function useObservatoryLaboratorySetups(sourceSessionId: string) {
const [catalog, setCatalog] = useState<ObservatoryLaboratorySetupCatalog | null>(null);
const [state, setState] = useState<SetupCatalogState>("idle");
const [error, setError] = useState<string | null>(null);
const [selectedSetupId, setSelectedSetupId] = useState("");
const [revision, setRevision] = useState(0);
const [preflight, setPreflight] = useState<SetupPreflightState>({ kind: "idle" });
const requestSequence = useRef(0);
const preflightRequest = useRef<AbortController | null>(null);
const activeCatalog = catalog?.sourceSessionId === sourceSessionId ? catalog : null;
const selectableSetups = useMemo(() => selectableObservatorySetups(activeCatalog), [activeCatalog]);
const selectedSetup = selectableSetups.find((setup) => setup.setupId === selectedSetupId) ?? null;
const selectedDefinitionSha256 = selectedSetup?.runDefinition?.definitionSha256 ?? null;
useEffect(() => {
preflightRequest.current?.abort();
preflightRequest.current = null;
if (!sourceSessionId) {
setCatalog(null);
setState("idle");
setError(null);
setSelectedSetupId("");
setPreflight({ kind: "idle" });
return;
}
const sequence = ++requestSequence.current;
const request = new AbortController();
setState((current) => activeCatalog && current !== "idle" ? "refreshing" : "loading");
setError(null);
setPreflight({ kind: "idle" });
// Archived definitions belong to evidence, not to the calculation selector.
void fetchObservatoryPortableLaboratorySetups(sourceSessionId, { signal: request.signal })
.then((next) => {
if (request.signal.aborted || requestSequence.current !== sequence) return;
setCatalog(next);
const selectable = selectableObservatorySetups(next);
setSelectedSetupId((current) => (
selectable.some((setup) => setup.setupId === current)
? current
: selectable[0]?.setupId ?? ""
));
setState("ready");
})
.catch((caught: unknown) => {
if (request.signal.aborted || requestSequence.current !== sequence) return;
setState("error");
setError(caught instanceof Error && caught.message.trim()
? caught.message
: "Каталог профилей недоступен.");
});
return () => request.abort();
}, [revision, sourceSessionId]);
useEffect(() => () => preflightRequest.current?.abort(), []);
useEffect(() => {
preflightRequest.current?.abort();
preflightRequest.current = null;
setPreflight((current) => current.kind === "idle" ? current : { kind: "idle" });
}, [selectedSetupId, sourceSessionId, selectedDefinitionSha256]);
const selectSetup = useCallback((setupId: string) => {
preflightRequest.current?.abort();
preflightRequest.current = null;
setSelectedSetupId(setupId);
setPreflight({ kind: "idle" });
}, []);
const refresh = useCallback(() => setRevision((value) => value + 1), []);
const check = useCallback(async () => {
if (!sourceSessionId || !selectedSetup || preflight.kind === "checking") return;
preflightRequest.current?.abort();
const request = new AbortController();
preflightRequest.current = request;
setPreflight({ kind: "checking" });
try {
const value = await preflightObservatoryLaboratorySetup(
sourceSessionId,
selectedSetup,
{ signal: request.signal },
);
if (request.signal.aborted || preflightRequest.current !== request) return;
setPreflight({ kind: "ready", value });
} catch (caught) {
if (request.signal.aborted || preflightRequest.current !== request) return;
setPreflight({
kind: "error",
message: caught instanceof Error && caught.message.trim()
? caught.message
: "Не удалось проверить возможность запуска.",
});
} finally {
if (preflightRequest.current === request) preflightRequest.current = null;
}
}, [preflight.kind, selectedSetup, sourceSessionId]);
useEffect(() => {
if (state !== "ready" || !selectedSetup || preflight.kind !== "idle") return;
void check();
}, [check, preflight.kind, selectedSetup, state]);
return {
catalog: activeCatalog,
selectableSetups,
state,
error,
selectedSetupId: selectedSetup?.setupId ?? "",
selectedSetup,
selectSetup,
refresh,
preflight,
check,
};
}
@@ -1,207 +0,0 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { fetchRecordedProgress, type RecordedProgressView } from "./recordedProgress";
import {
fetchObservatoryRecordedJobs,
retryObservatoryRecordedJobPublication,
submitObservatoryRecordedJob,
type ObservatoryRecordedJob,
} from "./recordedJobs";
type RecordedJobsState =
| "idle"
| "loading"
| "ready"
| "refreshing"
| "submitting"
| "retrying-publication"
| "error";
interface JobSnapshot {
readonly selectionKey: string;
readonly jobs: readonly ObservatoryRecordedJob[];
readonly state: RecordedJobsState;
readonly error: string | null;
readonly progress?: RecordedProgressView | null;
}
const EMPTY_JOBS = [] as const;
const OPEN_STATES = new Set([
"accepted", "queued", "claimed", "running", "paused", "preemption-pending",
"reconciliation-required",
]);
const POLL_INTERVAL_MS = 1_500;
export function useObservatoryRecordedJobs(
sourceSessionId: string,
setupId: string,
definitionSha256: string,
) {
const selectionKey = JSON.stringify([sourceSessionId, setupId, definitionSha256]);
const [snapshot, setSnapshot] = useState<JobSnapshot>({
selectionKey: "", jobs: EMPTY_JOBS, state: "idle", error: null,
});
const [revision, setRevision] = useState(0);
const requestRef = useRef<AbortController | null>(null);
const requestSequence = useRef(0);
const idempotencyKeys = useRef(new Map<string, string>());
const observedJobId = useRef<string | null>(null);
const hasSelection = Boolean(sourceSessionId && setupId && definitionSha256);
// A source/profile change must not display even one render of the previous queue.
const current = snapshot.selectionKey === selectionKey ? snapshot : null;
const jobs = current?.jobs ?? EMPTY_JOBS;
const state = current?.state ?? (hasSelection ? "loading" : "idle");
const error = current?.error ?? null;
useEffect(() => {
requestRef.current?.abort();
requestRef.current = null;
if (!hasSelection) {
setSnapshot({ selectionKey, jobs: EMPTY_JOBS, state: "idle", error: null });
return;
}
const sequence = ++requestSequence.current;
const request = new AbortController();
requestRef.current = request;
setSnapshot({
selectionKey, jobs,
state: jobs.length > 0 ? "refreshing" : "loading", error: null,
progress: current?.progress ?? null,
});
void fetchObservatoryRecordedJobs(sourceSessionId, setupId, {
definitionSha256, signal: request.signal,
}).then(async (next) => {
if (request.signal.aborted || requestSequence.current !== sequence) return;
const pending = next.find((job) => OPEN_STATES.has(job.state));
const progress = pending
? await fetchRecordedProgress(pending, { signal: request.signal }).catch(() => null)
: null;
if (request.signal.aborted || requestSequence.current !== sequence) return;
if (pending) observedJobId.current = pending.jobId;
setSnapshot({ selectionKey, jobs: next, state: "ready", error: null, progress });
}).catch((caught: unknown) => {
if (request.signal.aborted || requestSequence.current !== sequence) return;
setSnapshot({
selectionKey, jobs, state: "error",
error: caught instanceof Error && caught.message.trim()
? caught.message
: "Очередь расчётов недоступна.",
});
}).finally(() => {
if (requestRef.current === request) requestRef.current = null;
});
return () => request.abort();
}, [revision, selectionKey]);
useEffect(() => () => requestRef.current?.abort(), []);
const latestJob = jobs[0] ?? null;
const activeJob = jobs.find((job) => OPEN_STATES.has(job.state)) ?? null;
const publicationPending = jobs.some((job) => job.publication.state === "pending");
// Do not promote historical terminal logs to a new operator action's error.
const computationFailed = latestJob?.state === "failed"
&& latestJob.jobId === observedJobId.current;
useEffect(() => {
if ((state !== "ready" && state !== "error") || (!activeJob && !publicationPending)) return;
const timer = globalThis.setTimeout(
() => setRevision((value) => value + 1),
POLL_INTERVAL_MS,
);
return () => globalThis.clearTimeout(timer);
}, [activeJob, publicationPending, revision, state]);
useEffect(() => {
if (!latestJob || activeJob) return;
idempotencyKeys.current.delete(selectionKey);
}, [activeJob, latestJob, selectionKey]);
const refresh = useCallback(() => setRevision((value) => value + 1), []);
const submit = useCallback(async (
portableBinding: {
readonly definitionSha256: string;
readonly checkSha256: string;
} | null = null,
): Promise<ObservatoryRecordedJob | null> => {
if (!hasSelection || state !== "ready"
|| portableBinding?.definitionSha256 !== definitionSha256
|| publicationPending || latestJob?.publication.state === "failed") return null;
if (activeJob) return activeJob;
requestRef.current?.abort();
const request = new AbortController();
requestRef.current = request;
const key = idempotencyKeys.current.get(selectionKey) ?? createIdempotencyKey();
idempotencyKeys.current.set(selectionKey, key);
setSnapshot({ selectionKey, jobs, state: "submitting", error: null });
try {
const job = await submitObservatoryRecordedJob(
sourceSessionId, setupId, key, portableBinding, { signal: request.signal },
);
if (request.signal.aborted || requestRef.current !== request) return null;
observedJobId.current = job.jobId;
setSnapshot({
selectionKey, jobs: [job, ...jobs.filter((candidate) => candidate.jobId !== job.jobId)],
state: "ready", error: null,
});
return job;
} catch (caught) {
if (request.signal.aborted || requestRef.current !== request) return null;
setSnapshot({
selectionKey, jobs, state: "error",
error: caught instanceof Error && caught.message.trim()
? caught.message
: "Не удалось поставить расчёт в очередь.",
});
return null;
} finally {
if (requestRef.current === request) requestRef.current = null;
}
}, [activeJob, definitionSha256, hasSelection, jobs, latestJob,
publicationPending, selectionKey, setupId, sourceSessionId, state]);
const retryPublication = useCallback(async (): Promise<ObservatoryRecordedJob | null> => {
if (!latestJob || latestJob.publication.state !== "failed"
|| state === "retrying-publication") return null;
requestRef.current?.abort();
const request = new AbortController();
requestRef.current = request;
setSnapshot({ selectionKey, jobs, state: "retrying-publication", error: null });
try {
const job = await retryObservatoryRecordedJobPublication(latestJob.jobId, {
signal: request.signal,
});
if (request.signal.aborted || requestRef.current !== request) return null;
setSnapshot({
selectionKey, jobs: [job, ...jobs.filter((candidate) => candidate.jobId !== job.jobId)],
state: "ready", error: null,
});
return job;
} catch (caught) {
if (request.signal.aborted || requestRef.current !== request) return null;
setSnapshot({
selectionKey, jobs, state: "error",
error: caught instanceof Error && caught.message.trim()
? caught.message
: "Не удалось повторить публикацию результата.",
});
return null;
} finally {
if (requestRef.current === request) requestRef.current = null;
}
}, [jobs, latestJob, selectionKey, state]);
return {
jobs, latestJob, activeJob, publicationPending, computationFailed,
progress: current?.progress ?? null,
state, error, refresh, submit, retryPublication,
};
}
function createIdempotencyKey(): string {
const entropy = typeof globalThis.crypto?.randomUUID === "function"
? globalThis.crypto.randomUUID()
: `${Date.now().toString(36)}-${Math.random().toString(16).slice(2)}`;
return `observatory-ui:${entropy}`;
}
export type ObservatoryRecordedJobsController = ReturnType<typeof useObservatoryRecordedJobs>;
@@ -1,11 +1,14 @@
export type ChargeGradient={enabled:boolean;lowA:string;lowB:string;highA:string;highB:string;speed:number;scale:number;intensity:number;fallbackColor:string;fallbackMetalness:number;fallbackRoughness:number;fallbackOpacity:number;fallbackReflectivity:number}; import {parseMaterialSurface,defaultMaterialSurface,type MaterialSurface} from './materialSurface';
export const defaultChargeGradient=():ChargeGradient=>({enabled:true,lowA:'#ef2815',lowB:'#ff9b23',highA:'#20db62',highB:'#6cffe0',speed:.45,scale:12,intensity:2.5,fallbackColor:'#737b80',fallbackMetalness:.1,fallbackRoughness:.65,fallbackOpacity:1,fallbackReflectivity:.5}); export type ChargeGradient={surfaceVersion:1;enabled:boolean;lowA:string;lowB:string;highA:string;highB:string;speed:number;scale:number;intensity:number;contrast:number;saturation:number;inactive:MaterialSurface};
export const defaultChargeGradient=():ChargeGradient=>({surfaceVersion:1,enabled:true,lowA:'#ef2815',lowB:'#ff9b23',highA:'#20db62',highB:'#6cffe0',speed:.45,scale:12,intensity:2.5,contrast:1,saturation:1,inactive:defaultMaterialSurface()});
export function parseChargeGradient(raw:unknown):ChargeGradient{ export function parseChargeGradient(raw:unknown):ChargeGradient{
const result=defaultChargeGradient(),value=raw as Partial<ChargeGradient>|undefined; const result=defaultChargeGradient(),value=raw as Partial<ChargeGradient>&Record<string,unknown>;
if(!value)return result; if(!value||typeof value!=='object')return result;
if(typeof value.enabled==='boolean')result.enabled=value.enabled; if(typeof value.enabled==='boolean')result.enabled=value.enabled;
for(const key of ['lowA','lowB','highA','highB','fallbackColor'] as const)if(typeof value[key]==='string'&&/^#[0-9a-f]{6}$/i.test(value[key]))result[key]=value[key]; for(const key of ['lowA','lowB','highA','highB'] as const)if(typeof value[key]==='string'&&/^#[0-9a-f]{6}$/i.test(value[key]))result[key]=value[key];
for(const [key,min,max] of [['speed',0,3],['scale',1,50],['intensity',0,10],['fallbackMetalness',0,1],['fallbackRoughness',0,1],['fallbackOpacity',0,1],['fallbackReflectivity',0,1]] as const)if(typeof value[key]==='number'&&Number.isFinite(value[key]))result[key]=Math.max(min,Math.min(max,value[key])); for(const [key,min,max] of [['speed',0,3],['scale',1,50],['intensity',0,10],['contrast',.1,4],['saturation',0,2]] as const)if(typeof value[key]==='number'&&Number.isFinite(value[key]))result[key]=Math.max(min,Math.min(max,value[key]));
// Preserve pre-split fallback edits; inactive textures and coat start independently.
result.inactive=parseMaterialSurface(value.inactive??{color:value.fallbackColor,metalness:value.fallbackMetalness,roughness:value.fallbackRoughness,opacity:value.fallbackOpacity,reflectivity:value.fallbackReflectivity});
return result; return result;
} }
/** Interpolate each end of the gradient; no individual-cell SOC is inferred. */ /** Interpolate each end of the gradient; no individual-cell SOC is inferred. */
@@ -0,0 +1,23 @@
import {parseEnvironmentProfile,prepareEnvironmentSave,validEnvironmentId,type StoredEnvironmentProfile} from './environmentProfiles';
import {legacyRecord,profileClient} from './profileClient';
const eventName='missioncore:environment-profiles';
type Library={schema:'missioncore.environment-library/v1';profiles:StoredEnvironmentProfile[]};
function records(raw:unknown[]):StoredEnvironmentProfile[]{return raw.map((r:any)=>{if(!validEnvironmentId(r?.id)||r.id==='nodedc'||!Number.isInteger(r.revision)||r.revision<1)throw new Error('Не удалось прочитать библиотеку профилей.');return {...parseEnvironmentProfile(r),id:r.id,revision:r.revision};});}
async function library(){
const client=profileClient<Library>('environments','shared');
const value=await client.read(async()=>{const raw=await legacyRecord('missioncore-environment-profiles','profiles');return Array.isArray(raw)&&raw.length?{schema:'missioncore.environment-library/v1',profiles:records(raw)}:null;});
return {client,profiles:records(value?.profiles??[])};
}
export async function readEnvironmentProfiles():Promise<StoredEnvironmentProfile[]>{return (await library()).profiles;}
export async function saveEnvironmentProfile(profile:StoredEnvironmentProfile,expectedRevision:number|null):Promise<StoredEnvironmentProfile>{
const {client,profiles}=await library(),saved=prepareEnvironmentSave(profiles,profile,expectedRevision);
await client.write({schema:'missioncore.environment-library/v1',profiles:[...profiles.filter(p=>p.id!==saved.id),saved]});
window.dispatchEvent(new Event(eventName));
if(typeof BroadcastChannel!=='undefined'){const channel=new BroadcastChannel(eventName);channel.postMessage('changed');channel.close();}
return saved;
}
export function watchEnvironmentProfiles(refresh:()=>void):()=>void{
window.addEventListener(eventName,refresh);window.addEventListener('focus',refresh);
const channel=typeof BroadcastChannel!=='undefined'?new BroadcastChannel(eventName):null;if(channel)channel.onmessage=refresh;
return()=>{window.removeEventListener(eventName,refresh);window.removeEventListener('focus',refresh);channel?.close();};
}
@@ -0,0 +1,31 @@
import {changeField,defaultScene,environmentFields,fieldValue,type SceneDocument} from './sceneDocument';
export type EnvironmentSettings=Pick<SceneDocument,'postFx'|'cameraZoomStrength'|'cameraAutoRotate'>;
export type EnvironmentProfile={schema:'missioncore.environment-profile/v1';name:string;environment:EnvironmentSettings};
export type StoredEnvironmentProfile=EnvironmentProfile&{id:string;revision:number};
export const builtinEnvironmentId='nodedc';
export const validEnvironmentId=(id:unknown):id is string=>typeof id==='string'&&(id===builtinEnvironmentId||/^env\/[a-zA-Z0-9-]{1,80}$/.test(id));
export function sceneEnvironment(doc:EnvironmentSettings):EnvironmentSettings{return structuredClone({postFx:doc.postFx,cameraZoomStrength:doc.cameraZoomStrength,cameraAutoRotate:doc.cameraAutoRotate});}
export const builtinEnvironment=():StoredEnvironmentProfile=>({schema:'missioncore.environment-profile/v1',id:builtinEnvironmentId,revision:0,name:'NodeDC',environment:sceneEnvironment(defaultScene())});
export function parseEnvironmentProfile(raw:unknown):EnvironmentProfile{
const r=raw as any;
if(!r||!['missioncore.environment-profile/v1','missioncore.rover-scene/v1','missioncore.battery-scene/v1'].includes(r.schema))throw new Error('Выберите профиль окружения или JSON сцены Mission Core.');
const value=r.schema==='missioncore.environment-profile/v1'?r.environment:r;
if(!value?.postFx||typeof value.postFx!=='object'||Array.isArray(value.postFx))throw new Error('В файле нет настроек окружения.');
let doc=defaultScene();for(const f of environmentFields){const v=fieldValue(value,f.key);if(v!==undefined)doc=changeField(doc,f.key,v);}
return {schema:'missioncore.environment-profile/v1',name:typeof r.name==='string'?r.name.trim().slice(0,80)||'Импортированный профиль':'Импортированный профиль',environment:sceneEnvironment(doc)};
}
export function applyEnvironment(doc:SceneDocument,profile:StoredEnvironmentProfile):SceneDocument{
return {...doc,...sceneEnvironment(profile.environment),environmentProfileId:profile.id};
}
export const environmentMatches=(a:EnvironmentSettings,b:EnvironmentSettings)=>JSON.stringify(sceneEnvironment(a))===JSON.stringify(sceneEnvironment(b));
export function prepareEnvironmentSave(records:StoredEnvironmentProfile[],profile:StoredEnvironmentProfile,expectedRevision:number|null):StoredEnvironmentProfile{
if(!validEnvironmentId(profile.id)||profile.id===builtinEnvironmentId)throw new Error('Сохраните встроенный профиль под новым именем.');
const existing=records.find(p=>p.id===profile.id);
if((existing?.revision??null)!==expectedRevision)throw new Error('Профиль изменился в другом окне. Выберите его заново или сохраните копию.');
const name=profile.name.trim().slice(0,80);if(!name)throw new Error('Введите название профиля.');
if(records.some(p=>p.id!==profile.id&&p.name.toLocaleLowerCase()===name.toLocaleLowerCase())||name.toLocaleLowerCase()==='nodedc')throw new Error('Это имя уже занято. Выберите другое название.');
const next={...parseEnvironmentProfile(profile),id:profile.id,name,revision:(expectedRevision??0)+1};
const all=[...records.filter(p=>p.id!==profile.id),next];
if(all.length>64||JSON.stringify(all).length>16_000_000)throw new Error('Библиотека профилей заполнена. Пересохраните существующий профиль или экспортируйте JSON.');
return next;
}
@@ -0,0 +1,14 @@
import {maxSceneMaterials,textureBytes,type SceneDocument} from './sceneDocument';
export function materialCopyName(doc:SceneDocument,id:string):string{
const base=doc.materials[id]?.name??'Материал',used=new Set(Object.values(doc.materials).map(m=>m.name));
for(let n=1;;n++){const suffix=` · копия${n===1?'':` ${n}`}`,name=base.slice(0,120-suffix.length)+suffix;if(!used.has(name))return name;}
}
export function duplicateMaterial(doc:SceneDocument,sourceId:string,id:string,name:string):SceneDocument{
const source=doc.materials[sourceId];if(!source)throw new Error('Исходный материал больше не существует.');
if(!/^custom\/[a-zA-Z0-9-]{1,80}$/.test(id)||Object.hasOwn(doc.materials,id))throw new Error('Не удалось создать идентификатор копии.');
if(!name.trim()||name.trim().length>120)throw new Error('Введите название длиной до 120 символов.');
if(Object.keys(doc.materials).length>=maxSceneMaterials)throw new Error(`В сцене может быть не больше ${maxSceneMaterials} материалов.`);
const next={...doc,materials:{...doc.materials,[id]:{...structuredClone(source),name:name.trim()}}};
if(textureBytes(next)>28_000_000)throw new Error('Копия превышает общий объём текстур сцены — 20 МБ.');
return next;
}
@@ -0,0 +1,14 @@
export const textureSlots=['diffuse','normal','metalness','roughness','opacity','emissive','ao'] as const;
export type TextureSlot=typeof textureSlots[number];
export type MaterialSurface={color:string;metalness:number;roughness:number;opacity:number;reflectivity:number;clearCoat:number;clearCoatRoughness:number;emissive:string;emissiveIntensity:number;normalStrength:number;doubleSided:boolean;tiling:number;textures:Partial<Record<TextureSlot,{name:string;data:string}>>};
export const materialRanges:Record<string,[number,number]>={metalness:[0,1],roughness:[0,1],opacity:[0,1],reflectivity:[0,1],clearCoat:[0,1],clearCoatRoughness:[0,1],emissiveIntensity:[0,10],normalStrength:[0,2],tiling:[.01,20]};
export const defaultMaterialSurface=():MaterialSurface=>({color:'#737b80',metalness:.1,roughness:.65,opacity:1,reflectivity:.5,clearCoat:0,clearCoatRoughness:.3,emissive:'#000000',emissiveIntensity:0,normalStrength:1,doubleSided:false,tiling:1,textures:{}});
export function parseMaterialSurface(raw:unknown,defaults:MaterialSurface=defaultMaterialSurface()):MaterialSurface{
const result=structuredClone(defaults),m=raw as Partial<MaterialSurface>|undefined;if(!m||typeof m!=='object')return result;
for(const key of ['color','emissive'] as const)if(typeof m[key]==='string'&&/^#[0-9a-f]{6}$/i.test(m[key]))result[key]=m[key];
for(const [key,[lo,hi]] of Object.entries(materialRanges)){const v=m[key as keyof MaterialSurface];if(typeof v==='number'&&Number.isFinite(v))(result as any)[key]=Math.max(lo,Math.min(hi,v));}
if(typeof m.doubleSided==='boolean')result.doubleSided=m.doubleSided;
for(const slot of textureSlots){const t=m.textures?.[slot];if(!t)continue;if(typeof t.name!=='string'||typeof t.data!=='string'||t.data.length>12_000_000||!/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(t.data))throw new Error('Некорректная текстура в файле сцены.');result.textures[slot]={name:t.name.slice(0,200),data:t.data};}
return result;
}
export const surfaceTextureBytes=(s:MaterialSurface)=>Object.values(s.textures).reduce((sum,t)=>sum+(t?.data.length??0),0);
@@ -0,0 +1,35 @@
/** Durable JSON authority. A legacy browser record is only a one-time migration input. */
export type ProfileKind='battery'|'rover'|'battery-ui'|'battery-view'|'environments';
type Stored<T>={revision:number;document:T|null};
export function profileClient<T>(kind:ProfileKind,owner:string){
let revision:number|undefined;
let queue=Promise.resolve();
const url=`/api/v1/scene-profiles/${kind}?owner=${encodeURIComponent(owner)}`;
async function request(method='GET',body?:unknown):Promise<Stored<T>>{
const response=await fetch(url,{method,cache:'no-store',headers:{'Content-Type':'application/json'},...(body?{body:JSON.stringify(body),keepalive:JSON.stringify(body).length<60000}:{})});
if(!response.ok){let message='Не удалось загрузить или сохранить профиль в Mission Core.';try{const value=await response.json();if(typeof value.detail==='string')message=value.detail;}catch{}throw new Error(message);}
const result=await response.json();if(!Number.isInteger(result.revision)||!Object.hasOwn(result,'document'))throw new Error('Неверный ответ хранилища профилей.');return result;
}
async function read(legacy?:()=>Promise<T|null>):Promise<T|null>{
let value=await request();
if(value.document===null&&legacy){const old=await legacy();if(old!==null){
try{value=await request('PUT',{document:old,expected_revision:0});}
catch(error){const winner=await request();if(winner.document===null)throw error;value=winner;}
}}
revision=value.revision;return value.document;
}
function write(document:T):Promise<void>{
const next=queue.catch(()=>{}).then(async()=>{
if(revision===undefined)throw new Error('Профиль ещё не загружен. Сохранение отменено.');
const value=await request('PUT',{document,expected_revision:revision});revision=value.revision;
});queue=next;return next;
}
return {read,write};
}
export async function legacyRecord(database:string,store:string,key?:string):Promise<unknown>{
if(typeof indexedDB==='undefined'||typeof indexedDB.databases!=='function')return null;
const databases=await indexedDB.databases();if(!databases.some(d=>d.name===database))return null;
const db=await new Promise<IDBDatabase>((resolve,reject)=>{const r=indexedDB.open(database);r.onupgradeneeded=()=>{r.transaction?.abort();reject(new Error('Старое хранилище исчезло.'));};r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error);});
try{if(!db.objectStoreNames.contains(store))return null;return await new Promise((resolve,reject)=>{const s=db.transaction(store,'readonly').objectStore(store),r=key===undefined?s.getAll():s.get(key);r.onsuccess=()=>resolve(r.result??null);r.onerror=()=>reject(r.error);});}finally{db.close();}
}
@@ -1,3 +1,5 @@
import {parseMaterialSurface,surfaceTextureBytes,type MaterialSurface} from './materialSurface';
export {textureSlots,materialRanges,type TextureSlot} from './materialSurface';
import {parseEditorLayout,type SceneEditorLayout} from './editorLayout'; import {parseEditorLayout,type SceneEditorLayout} from './editorLayout';
import {parseCameraState,type CameraState} from './cameraState'; import {parseCameraState,type CameraState} from './cameraState';
import {parseChargeGradient,type ChargeGradient} from './chargeGradient'; import {parseChargeGradient,type ChargeGradient} from './chargeGradient';
@@ -13,10 +15,8 @@ export const environmentFields:SceneField[]=[...donorFields,
{key:'postFx.grid.step',type:'sliderNumber',label:'Шаг основной сетки, м',group:'PostProcess/Grid',min:.01,max:10,step:.01}, {key:'postFx.grid.step',type:'sliderNumber',label:'Шаг основной сетки, м',group:'PostProcess/Grid',min:.01,max:10,step:.01},
{key:'postFx.grid.diameter',type:'sliderNumber',label:'Диаметр сетки, м',group:'PostProcess/Grid',min:1,max:1000,step:1}, {key:'postFx.grid.diameter',type:'sliderNumber',label:'Диаметр сетки, м',group:'PostProcess/Grid',min:1,max:1000,step:1},
]; ];
export const textureSlots=['diffuse','normal','metalness','roughness','opacity','emissive','ao'] as const; export type MaterialSpec=MaterialSurface&{chargeGradient?:ChargeGradient;name:string};
export type TextureSlot=typeof textureSlots[number]; export type SceneDocument={schema:'missioncore.rover-scene/v1'|'missioncore.battery-scene/v1';model:string;environmentVersion:2;environmentProfileId?:string;camera?:CameraState;editorLayout?:SceneEditorLayout;postFx:PostFxSettings;cameraZoomStrength:number;cameraAutoRotate:boolean;materials:Record<string,MaterialSpec>;assignments:Record<string,string>;objectAssignments?:Record<string,string>;objectVisibility?:Record<string,boolean>;objects?:Record<string,boolean>};
export type MaterialSpec={chargeGradient?:ChargeGradient;name:string;color:string;metalness:number;roughness:number;opacity:number;reflectivity:number;clearCoat:number;clearCoatRoughness:number;emissive:string;emissiveIntensity:number;normalStrength:number;doubleSided:boolean;tiling:number;textures:Partial<Record<TextureSlot,{name:string;data:string}>>};
export type SceneDocument={schema:'missioncore.rover-scene/v1'|'missioncore.battery-scene/v1';model:string;environmentVersion:2;camera?:CameraState;editorLayout?:SceneEditorLayout;postFx:PostFxSettings;cameraZoomStrength:number;cameraAutoRotate:boolean;materials:Record<string,MaterialSpec>;assignments:Record<string,string>;objectAssignments?:Record<string,string>;objectVisibility?:Record<string,boolean>;objects?:Record<string,boolean>};
// Reserve the added equipment slots without consuming the legacy custom-material budget. // Reserve the added equipment slots without consuming the legacy custom-material budget.
export const maxSceneMaterials=128+Object.keys(equipmentMaterials).length; export const maxSceneMaterials=128+Object.keys(equipmentMaterials).length;
const material=(name:string,color:string,metalness:number,roughness:number):MaterialSpec=>({name,color,metalness,roughness,opacity:1,reflectivity:1,clearCoat:0,clearCoatRoughness:.3,emissive:'#000000',emissiveIntensity:0,normalStrength:1,doubleSided:false,tiling:1,textures:{}}); const material=(name:string,color:string,metalness:number,roughness:number):MaterialSpec=>({name,color,metalness,roughness,opacity:1,reflectivity:1,clearCoat:0,clearCoatRoughness:.3,emissive:'#000000',emissiveIntensity:0,normalStrength:1,doubleSided:false,tiling:1,textures:{}});
@@ -73,11 +73,11 @@ export function changeField(doc:SceneDocument,key:string,value:unknown):SceneDoc
if(key==='postFx.skybox.enabled'&&value)result.postFx.envAtlas.enabled=false; if(key==='postFx.skybox.enabled'&&value)result.postFx.envAtlas.enabled=false;
return result; return result;
} }
export const materialRanges:Record<string,[number,number]>={metalness:[0,1],roughness:[0,1],opacity:[0,1],reflectivity:[0,1],clearCoat:[0,1],clearCoatRoughness:[0,1],emissiveIntensity:[0,10],normalStrength:[0,2],tiling:[.01,20]}; export function textureBytes(doc:SceneDocument):number{return Object.values(doc.materials).reduce((sum,m)=>sum+surfaceTextureBytes(m)+(m.chargeGradient?surfaceTextureBytes(m.chargeGradient.inactive):0),0);}
export function textureBytes(doc:SceneDocument):number{return Object.values(doc.materials).reduce((sum,m)=>sum+Object.values(m.textures).reduce((n,t)=>n+(t?.data.length??0),0),0);}
export function parseScene(raw:unknown,defaults:()=>SceneDocument=defaultScene):SceneDocument{ export function parseScene(raw:unknown,defaults:()=>SceneDocument=defaultScene):SceneDocument{
const base=defaults(),r=raw as SceneDocument;const models=base.schema==='missioncore.rover-scene/v1'?[roverModelRevision,legacyRoverModelRevision,previousRoverModelRevision]:[base.model];if(!r||r.schema!==base.schema||!models.includes(r.model))throw new Error('Файл сцены не подходит к этой модели.'); const base=defaults(),r=raw as SceneDocument;const models=base.schema==='missioncore.rover-scene/v1'?[roverModelRevision,legacyRoverModelRevision,previousRoverModelRevision]:[base.model];if(!r||r.schema!==base.schema||!models.includes(r.model))throw new Error('Файл сцены не подходит к этой модели.');
let doc=base; let doc=base;
if(typeof r.environmentProfileId==='string'&&/^(nodedc|env\/[a-zA-Z0-9-]{1,80})$/.test(r.environmentProfileId))doc.environmentProfileId=r.environmentProfileId;
const layout=parseEditorLayout(r.editorLayout);if(layout)doc.editorLayout=layout; const layout=parseEditorLayout(r.editorLayout);if(layout)doc.editorLayout=layout;
const camera=parseCameraState(r.camera);if(camera)doc.camera=camera; const camera=parseCameraState(r.camera);if(camera)doc.camera=camera;
if(doc.objects)for(const id of Object.keys(doc.objects)){const legacy=Object.keys(r.objects??{}).filter(key=>id===key||id.startsWith(key+'/')).sort((a,b)=>b.length-a.length)[0];if(legacy&&typeof r.objects?.[legacy]==='boolean')doc.objects[id]=r.objects[legacy];} if(doc.objects)for(const id of Object.keys(doc.objects)){const legacy=Object.keys(r.objects??{}).filter(key=>id===key||id.startsWith(key+'/')).sort((a,b)=>b.length-a.length)[0];if(legacy&&typeof r.objects?.[legacy]==='boolean')doc.objects[id]=r.objects[legacy];}
@@ -87,11 +87,8 @@ export function parseScene(raw:unknown,defaults:()=>SceneDocument=defaultScene):
for(const [id,base] of Object.entries(doc.materials)){ for(const [id,base] of Object.entries(doc.materials)){
const m=r.materials?.[id];if(!m)continue; const m=r.materials?.[id];if(!m)continue;
if(typeof m.name==='string')base.name=m.name.trim().slice(0,120)||base.name; if(typeof m.name==='string')base.name=m.name.trim().slice(0,120)||base.name;
for(const key of ['color','emissive'] as const)if(/^#[0-9a-f]{6}$/i.test(m[key]))base[key]=m[key]; Object.assign(base,parseMaterialSurface(m,base));
for(const [key,[lo,hi]] of Object.entries(materialRanges)){const v=m[key as keyof MaterialSpec];if(typeof v==='number'&&Number.isFinite(v))(base as any)[key]=Math.max(lo,Math.min(hi,v));} if(m.chargeGradient){base.chargeGradient=parseChargeGradient(m.chargeGradient);if(m.chargeGradient.enabled){if(!m.chargeGradient.inactive)base.color='#050505';if(m.chargeGradient.surfaceVersion!==1)base.emissiveIntensity=0;}}
if(typeof m.doubleSided==='boolean')base.doubleSided=m.doubleSided;
if(m.chargeGradient)base.chargeGradient=parseChargeGradient(m.chargeGradient);
for(const slot of textureSlots){const t=m.textures?.[slot];if(!t)continue;if(typeof t.name!=='string'||typeof t.data!=='string'||t.data.length>12_000_000||!/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(t.data))throw new Error('Некорректная текстура в файле сцены.');base.textures[slot]={name:t.name.slice(0,200),data:t.data};}
} }
for(const [group,id] of Object.entries(r.assignments??{}))if(typeof id==='string')doc=assignMaterial(doc,group,id); for(const [group,id] of Object.entries(r.assignments??{}))if(typeof id==='string')doc=assignMaterial(doc,group,id);
for(const key of ['objectAssignments','objectVisibility'] as const){ for(const key of ['objectAssignments','objectVisibility'] as const){
@@ -1,22 +1,13 @@
import type {SceneDocument} from './sceneDocument'; import type {SceneDocument} from './sceneDocument';
import {loadStoredScene} from './sceneMigration'; import {loadStoredScene} from './sceneMigration';
// Retain the original storage slot so upgrades preserve operator materials and environment. import {legacyRecord,profileClient} from './profileClient';
const key=(vehicle:string)=>`${vehicle}:dcd006-v020-materials-v2`; const key=(vehicle:string)=>`${vehicle}:dcd006-v020-materials-v2`;
function database():Promise<IDBDatabase>{return new Promise((resolve,reject)=>{const r=indexedDB.open('missioncore-rover-scenes',1);r.onupgradeneeded=()=>r.result.createObjectStore('scenes');r.onerror=()=>reject(r.error);r.onblocked=()=>reject(new Error('Хранилище сцены занято другим окном.'));r.onsuccess=()=>resolve(r.result);});} export function roverSceneProfile(){
export async function readScene(vehicle:string):Promise<SceneDocument|null>{ const clients=new Map<string,ReturnType<typeof profileClient<SceneDocument>>>();
const db=await database();try{ const client=(id:string)=>{let c=clients.get(id);if(!c){c=profileClient<SceneDocument>('rover',id);clients.set(id,c);}return c;};
const raw=await new Promise<unknown>((resolve,reject)=>{const r=db.transaction('scenes').objectStore('scenes').get(key(vehicle));r.onerror=()=>reject(r.error);r.onsuccess=()=>resolve(r.result);}); return {read:async(id:string)=>{const value=await client(id).read(async()=>{const raw=await legacyRecord('missioncore-rover-scenes','scenes',key(id));return raw?loadStoredScene(raw).document:null;});return value?loadStoredScene(value).document:null;},write:(id:string,doc:SceneDocument)=>client(id).write(doc)};
if(!raw)return null;
const result=loadStoredScene(raw);
if(result.updated)await new Promise<void>((resolve,reject)=>{
const tx=db.transaction('scenes','readwrite'),store=tx.objectStore('scenes');
if(result.restoredEnvironment)store.put(raw,`${key(vehicle)}:before-environment-v2`);
store.put(result.document,key(vehicle));tx.oncomplete=()=>resolve();tx.onabort=()=>reject(tx.error);tx.onerror=()=>reject(tx.error);
});
return result.document;
}finally{db.close();}
} }
export async function saveScene(vehicle:string,document:SceneDocument):Promise<void>{const db=await database();try{await new Promise<void>((resolve,reject)=>{const tx=db.transaction('scenes','readwrite');tx.objectStore('scenes').put(document,key(vehicle));tx.oncomplete=()=>resolve();tx.onabort=()=>reject(tx.error);tx.onerror=()=>reject(tx.error);});}finally{db.close();}} export async function readScene(vehicle:string):Promise<SceneDocument|null>{return roverSceneProfile().read(vehicle);}
export async function textureFromFile(file:File):Promise<{name:string;data:string}>{ export async function textureFromFile(file:File):Promise<{name:string;data:string}>{
if(!['image/png','image/jpeg','image/webp'].includes(file.type)||file.size>8_000_000)throw new Error('Выберите PNG, JPEG или WebP до 8 МБ.'); if(!['image/png','image/jpeg','image/webp'].includes(file.type)||file.size>8_000_000)throw new Error('Выберите PNG, JPEG или WebP до 8 МБ.');
const bitmap=await createImageBitmap(file);try{if(bitmap.width>4096||bitmap.height>4096)throw new Error('Максимальный размер текстуры — 4096 × 4096.');}finally{bitmap.close();} const bitmap=await createImageBitmap(file);try{if(bitmap.width>4096||bitmap.height>4096)throw new Error('Максимальный размер текстуры — 4096 × 4096.');}finally{bitmap.close();}
@@ -1,32 +1,44 @@
import type {CameraState} from './cameraState'; import type {CameraState} from './cameraState';
import {useCallback,useEffect,useRef,useState} from 'react'; import {useCallback,useEffect,useMemo,useRef,useState} from 'react';
import {defaultScene,parseScene,type SceneDocument} from './sceneDocument'; import {defaultScene,parseScene,type SceneDocument} from './sceneDocument';
import {SceneHistory} from './sceneHistory'; import {SceneHistory} from './sceneHistory';
import {readScene,saveScene} from './sceneStorage'; import {roverSceneProfile} from './sceneStorage';
let writes=Promise.resolve(); let writes=Promise.resolve();
const enqueue=(vehicle:string,doc:SceneDocument,write=saveScene)=>{const next=writes.catch(()=>{}).then(()=>write(vehicle,doc));writes=next;return next;}; type Write=(id:string,doc:SceneDocument)=>Promise<void>;
export type SceneDocumentProfile={defaults:()=>SceneDocument;read:(id:string)=>Promise<SceneDocument|null>;write:typeof saveScene;filename:string}; const enqueue=(id:string,doc:SceneDocument,write:Write)=>{const next=writes.catch(()=>{}).then(()=>write(id,doc));writes=next;return next;};
export type SceneDocumentProfile={defaults:()=>SceneDocument;read:(id:string)=>Promise<SceneDocument|null>;write:Write;filename:string};
export function useSceneDocument(vehicle:string,profile?:SceneDocumentProfile){ export function useSceneDocument(vehicle:string,profile?:SceneDocumentProfile){
const defaults=profile?.defaults??defaultScene,read=profile?.read??readScene,write=profile?.write??saveScene; const storage=useMemo(()=>profile??{...roverSceneProfile(),defaults:defaultScene,filename:'rover-scene.json'},[profile]);
const {defaults,read,write}=storage;
const [document,setDocument]=useState(defaults),[ready,setReady]=useState(false),[revision,setRevision]=useState(0); const [document,setDocument]=useState(defaults),[ready,setReady]=useState(false),[revision,setRevision]=useState(0);
const [saveState,setSaveState]=useState<'loading'|'saved'|'saving'|'error'>('loading'),[error,setError]=useState(''); const [saveState,setSaveState]=useState<'loading'|'saved'|'saving'|'error'>('loading'),[error,setError]=useState('');
const latest=useRef({document,revision,vehicle,write});latest.current={document,revision,vehicle,write}; const loaded=useRef(false),savedRevision=useRef(0),history=useRef(new SceneHistory(document));
const pendingCamera=useRef<CameraState|null>(null); const pendingCamera=useRef<CameraState|null>(null);
const savedRevision=useRef(0),history=useRef(new SceneHistory(document)); const latest=useRef({document,revision,vehicle,write,ready});latest.current={document,revision,vehicle,write,ready};
const publish=useCallback(()=>{setDocument(history.current.present);setRevision(v=>v+1);setSaveState('saving');},[]); const publish=useCallback(()=>{setDocument(history.current.present);setRevision(v=>v+1);setSaveState('saving');},[]);
const undo=useCallback(()=>{pendingCamera.current=null;if(history.current.undo())publish();},[publish]); const undo=useCallback(()=>{if(!loaded.current)return;pendingCamera.current=null;if(history.current.undo())publish();},[publish]);
const redo=useCallback(()=>{pendingCamera.current=null;if(history.current.redo())publish();},[publish]); const redo=useCallback(()=>{if(!loaded.current)return;pendingCamera.current=null;if(history.current.redo())publish();},[publish]);
const beginGesture=useCallback(()=>history.current.begin(),[]),endGesture=useCallback(()=>history.current.end(),[]); const beginGesture=useCallback(()=>{if(loaded.current)history.current.begin();},[]),endGesture=useCallback(()=>history.current.end(),[]);
useEffect(()=>{let cancelled=false;read(vehicle).then(value=>{if(!cancelled){const doc=value??defaults();history.current.reset(doc);setDocument(doc);setSaveState('saved');}}).catch(()=>{if(!cancelled){setError('Не удалось прочитать сохранённую сцену. Изменения можно экспортировать в JSON.');setSaveState('error');}}).finally(()=>{if(!cancelled)setReady(true);});return()=>{cancelled=true;};},[vehicle,profile]); useEffect(()=>{
const update=useCallback((fn:(doc:SceneDocument)=>SceneDocument)=>{if(history.current.update(fn(history.current.present)))publish();},[publish]); let cancelled=false;loaded.current=false;pendingCamera.current=null;savedRevision.current=0;
const recordCamera=useCallback((camera:CameraState,commit=false)=>{pendingCamera.current=camera;if(commit){pendingCamera.current=null;update(doc=>JSON.stringify(doc.camera)===JSON.stringify(camera)?doc:{...doc,camera});}},[update]); setReady(false);setRevision(0);setSaveState('loading');setError('');
read(vehicle).then(value=>{if(!cancelled){const doc=value??defaults();history.current.reset(doc);setDocument(doc);loaded.current=true;setReady(true);setSaveState('saved');}}).catch(e=>{if(!cancelled){setError(e instanceof Error?e.message:'Не удалось прочитать сохранённую сцену.');setSaveState('error');}});
return()=>{cancelled=true;loaded.current=false;};
},[vehicle,storage,read,defaults]);
const update=useCallback((fn:(doc:SceneDocument)=>SceneDocument)=>{if(loaded.current&&history.current.update(fn(history.current.present)))publish();},[publish]);
const recordCamera=useCallback((camera:CameraState,commit=false)=>{if(!loaded.current)return;pendingCamera.current=camera;if(commit){pendingCamera.current=null;update(doc=>JSON.stringify(doc.camera)===JSON.stringify(camera)?doc:{...doc,camera});}},[update]);
useEffect(()=>{ useEffect(()=>{
if(!ready||revision===0)return; if(!ready||revision===0)return;
let cancelled=false;const timer=setTimeout(()=>{enqueue(vehicle,document,write).then(()=>{savedRevision.current=revision;if(!cancelled)setSaveState('saved');}).catch(()=>{if(!cancelled){setSaveState('error');setError('Не удалось сохранить сцену на этом компьютере. Экспортируйте JSON, чтобы сохранить изменения.');}});},400); let cancelled=false;const timer=setTimeout(()=>{enqueue(vehicle,document,write).then(()=>{savedRevision.current=revision;if(!cancelled)setSaveState('saved');}).catch(e=>{if(!cancelled){setSaveState('error');setError(e instanceof Error?e.message:'Не удалось сохранить сцену. Экспортируйте JSON, чтобы сохранить изменения.');}});},400);
return()=>{cancelled=true;clearTimeout(timer);}; return()=>{cancelled=true;clearTimeout(timer);};
},[ready,revision,vehicle,document,write]); },[ready,revision,vehicle,document,write]);
useEffect(()=>()=>{const v=latest.current;if(pendingCamera.current||v.revision>savedRevision.current)void enqueue(v.vehicle,pendingCamera.current?{...v.document,camera:pendingCamera.current}:v.document,v.write).catch(()=>{});},[]); useEffect(()=>{
const importDocument=async(file:File)=>{try{if(file.size>32_000_000)throw new Error('Файл сцены больше 32 МБ.');const next=parseScene(JSON.parse(await file.text()),defaults);pendingCamera.current=null;update(()=>next);}catch(e){setError(e instanceof Error?e.message:'Не удалось загрузить сцену.');}}; const flush=()=>{const v=latest.current;if(v.ready&&(pendingCamera.current||v.revision>savedRevision.current))void enqueue(v.vehicle,pendingCamera.current?{...v.document,camera:pendingCamera.current}:v.document,v.write).catch(()=>{});};
const exportDocument=()=>{const blob=new Blob([JSON.stringify(pendingCamera.current?{...document,camera:pendingCamera.current}:document,null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=globalThis.document.createElement('a');a.href=url;a.download=profile?.filename??'rover-scene.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}; const hidden=()=>{if(globalThis.document.visibilityState==='hidden')flush();};
window.addEventListener('pagehide',flush);globalThis.document.addEventListener('visibilitychange',hidden);
return()=>{flush();window.removeEventListener('pagehide',flush);globalThis.document.removeEventListener('visibilitychange',hidden);};
},[]);
const importDocument=async(file:File)=>{try{if(!ready)throw new Error('Дождитесь загрузки профиля.');if(file.size>32_000_000)throw new Error('Файл сцены больше 32 МБ.');const next=parseScene(JSON.parse(await file.text()),defaults);pendingCamera.current=null;update(()=>next);}catch(e){setError(e instanceof Error?e.message:'Не удалось загрузить сцену.');}};
const exportDocument=()=>{const blob=new Blob([JSON.stringify(pendingCamera.current?{...document,camera:pendingCamera.current}:document,null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=globalThis.document.createElement('a');a.href=url;a.download=storage.filename;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
return {document,recordCamera,ready,saveState,error,setError,update,undo,redo,canUndo:history.current.canUndo,canRedo:history.current.canRedo,beginGesture,endGesture,importDocument,exportDocument}; return {document,recordCamera,ready,saveState,error,setError,update,undo,redo,canUndo:history.current.canUndo,canRedo:history.current.canRedo,beginGesture,endGesture,importDocument,exportDocument};
} }

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