Compare commits
66
Commits
b0332fa377
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b67d5f7df | ||
|
|
d4ed96f3cd | ||
|
|
43d4916331 | ||
|
|
a50d638ced | ||
|
|
3ff43dd2af | ||
|
|
bed1db3508 | ||
|
|
3d04fa45d3 | ||
|
|
1635299252 | ||
|
|
22f262ca59 | ||
|
|
c45bd6b882 | ||
|
|
bd8af772d9 | ||
|
|
e26582fc75 | ||
|
|
e9527060f6 | ||
|
|
56d89197a8 | ||
|
|
29ef038a43 | ||
|
|
9cbdd4ea5c | ||
|
|
b1533ce0ea | ||
|
|
f4b506d593 | ||
|
|
a3781bcf4b | ||
|
|
a3927ce846 | ||
|
|
0a29522f2f | ||
|
|
7c0dbd4e06 | ||
|
|
9871ae500f | ||
|
|
a80e3a8ff5 | ||
|
|
a5e4fba807 | ||
|
|
996ce7efdf | ||
|
|
0f97f79216 | ||
|
|
8aeb5b3fd2 | ||
|
|
958e9c396d | ||
|
|
778a558a34 | ||
|
|
4a8fffb418 | ||
|
|
6911da71d8 | ||
|
|
87c0c7960a | ||
|
|
b96bea1599 | ||
|
|
136be019af | ||
|
|
e8e450e93a | ||
|
|
28cb2e49a4 | ||
|
|
c6280525ba | ||
|
|
4002ae4c96 | ||
|
|
71705ea862 | ||
|
|
91a18c580a | ||
|
|
8e37ef6968 | ||
|
|
1a0b5b0bd7 | ||
|
|
d88ea2de93 | ||
|
|
c785f1173f | ||
|
|
1c092ff0e3 | ||
|
|
f6e0bab559 | ||
|
|
e8920f56a2 | ||
|
|
9937eb66d8 | ||
|
|
cd27a5e483 | ||
|
|
a49fb00b8e | ||
|
|
58ac9fe3d2 | ||
|
|
800518ea80 | ||
|
|
1317f78672 | ||
|
|
a724a9796a | ||
|
|
4d0306f353 | ||
|
|
40872d3534 | ||
|
|
1472926112 | ||
|
|
e8025bc99f | ||
|
|
ad5a929e06 | ||
|
|
fe5900ff3b | ||
|
|
cd34b6ce1a | ||
|
|
7595bea07c | ||
|
|
ab5766df6a | ||
|
|
43148a8769 | ||
|
|
09c13a5c68 |
@@ -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,
|
||||
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
|
||||
|
||||
The governing Ops record is [MISSIONCOR-50 — Фундаментальная архитектура Mission Core](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-50),
|
||||
@@ -33,6 +44,12 @@ links to that record for monorepo, storage, resource and live-only telemetry rul
|
||||
terminal, close only your own hold with `finish` (pin qualified/rollback
|
||||
outcomes), review its plan and apply it as part of build completion. Never
|
||||
expire active holds by age or declare unknown legacy inputs disposable.
|
||||
- Node/X4 owner installers close out their exact unpacked `.deb` duplicates via
|
||||
`scripts/packaging/qualified_payloads.py` after durable publication and full
|
||||
hash verification. Keep the installer and `PAYLOAD_LOCATION.json`. Register a
|
||||
persistent payload hold before a dependent consumer needs loose files; release
|
||||
it only after that consumer ends. Read retired payloads through the helper,
|
||||
not by leaving another permanent extracted copy. See `docs/STORAGE_RETENTION.md`.
|
||||
- Run local Python validation through `scripts/check_python.py pytest|ruff|mypy`
|
||||
(pass the usual file/selection arguments). It owns temporary caches, disables
|
||||
persistent pytest/Ruff cache output, and cleans its own scratch after child
|
||||
@@ -75,6 +92,55 @@ links to that record for monorepo, storage, resource and live-only telemetry rul
|
||||
retain the immutable algorithm result and human provenance separately.
|
||||
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
|
||||
|
||||
- Default to non-mutating discovery or read-only operations. CoreBluetooth BLE
|
||||
@@ -335,3 +401,24 @@ decoders before BLE/Wi-Fi/data-session evidence exists.
|
||||
unchanged searches or model variants under a new name.
|
||||
- Worker access/power/runtime authority comes from the owner's current session
|
||||
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.
|
||||
|
||||
Generated
+17
-5
@@ -10,6 +10,7 @@
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.2.0",
|
||||
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.86.tgz",
|
||||
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
|
||||
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
|
||||
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
|
||||
@@ -41,9 +42,9 @@
|
||||
},
|
||||
"../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react": {
|
||||
"name": "@nodedc/map-cesium-react",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.4",
|
||||
"dependencies": {
|
||||
"cesium": "1.143.0"
|
||||
"cesium": "1.147.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.1.0",
|
||||
@@ -63,19 +64,19 @@
|
||||
},
|
||||
"../../../NODEDC_DESIGN_GUIDELINE/packages/ui-core": {
|
||||
"name": "@nodedc/ui-core",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.4",
|
||||
"dependencies": {
|
||||
"@nodedc/tokens": "0.6.0"
|
||||
}
|
||||
},
|
||||
"../../../NODEDC_DESIGN_GUIDELINE/packages/ui-react": {
|
||||
"name": "@nodedc/ui-react",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.10",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@nodedc/ui-core": "0.7.0",
|
||||
"@nodedc/ui-core": "0.7.4",
|
||||
"lucide-react": "^0.468.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -882,6 +883,17 @@
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@nodedc/bim-viewer": {
|
||||
"version": "0.2.86",
|
||||
"resolved": "file:../../vendor/bim/nodedc-bim-viewer-0.2.86.tgz",
|
||||
"integrity": "sha512-1yaWhAbEx3Y1V93b+T1HKfra7Z6hGpFL/Fhz/S6Bi+AzFMEJsQ4TpE32uVIARxN6EWJtAx3QuBlmaD8TP499IQ==",
|
||||
"peerDependencies": {
|
||||
"@nodedc/map-cesium-react": ">=0.1.4 <0.2",
|
||||
"@nodedc/ui-react": ">=0.7.10 <0.8",
|
||||
"react": ">=19 <20",
|
||||
"react-dom": ">=19 <20"
|
||||
}
|
||||
},
|
||||
"node_modules/@nodedc/map-cesium-react": {
|
||||
"resolved": "../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
|
||||
"link": true
|
||||
|
||||
@@ -6,14 +6,16 @@
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"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",
|
||||
"preview": "vite preview",
|
||||
"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": {
|
||||
"@noble/hashes": "^2.2.0",
|
||||
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.86.tgz",
|
||||
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
|
||||
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
|
||||
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {SceneDisplayControls} from "../../../packages/spatial-ui/src/SceneDisplayControls";
|
||||
import {SceneLayerControls} from "../../../packages/spatial-ui/src/SceneLayerControls";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
import { Description,
|
||||
AdminNavigationPanel,
|
||||
AppHeader,
|
||||
ApplicationPanel,
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
Button,
|
||||
ControlRow,
|
||||
HeaderNavigation,
|
||||
HeaderProfile,
|
||||
Icon,
|
||||
Inspector,
|
||||
StatusBadge,
|
||||
@@ -51,6 +50,8 @@ import type {
|
||||
import { useRecordedSessionAdmission } from "./core/observation/useRecordedSessionAdmission";
|
||||
import { useWorkspaceLayoutProfile } from "./core/observation/useWorkspaceLayoutProfile";
|
||||
import { useSessionDisplayProfile } from "./core/observation/useSessionDisplayProfile";
|
||||
import { EventPanel } from './components/notifications/NotificationHost';
|
||||
import { useNotifications } from './core/notifications/useNotificationHistory';
|
||||
import { viewerSettingsTargetIdentity } from "./core/observation/viewerSettingsTarget";
|
||||
import { resolvePolygonRunRoute } from "./core/polygon/runArchive";
|
||||
import {
|
||||
@@ -59,6 +60,7 @@ import {
|
||||
type ObservationWorkspaceLayoutProfile,
|
||||
} from "./core/observation/workspaceLayout";
|
||||
import {
|
||||
capabilityStatusLabel,
|
||||
rootById,
|
||||
roots,
|
||||
workspaceById,
|
||||
@@ -233,6 +235,7 @@ export default function App() {
|
||||
);
|
||||
runtimeUpdateViewerSettingsRef.current = runtime.updateViewerSettings;
|
||||
replayActiveRef.current = replayPresented;
|
||||
const notifications = useNotifications();
|
||||
const sessionDisplayProfile = useSessionDisplayProfile(replayPresented ? recordedReplay?.sessionId ?? null : null, (settings) => {
|
||||
sceneSettingsRef.current = settings;
|
||||
displayDraftRef.current = settings;
|
||||
@@ -444,7 +447,7 @@ export default function App() {
|
||||
workspace.openNavigation();
|
||||
if (rootId === "system") {
|
||||
workspace.openView(
|
||||
activeDefinition?.root === "system" ? activeDefinition.id : "modules",
|
||||
activeDefinition?.id === "vps" ? "vps" : "workers",
|
||||
);
|
||||
} else {
|
||||
workspace.closeView();
|
||||
@@ -666,7 +669,7 @@ export default function App() {
|
||||
connectionScenarioResetting: runtime.pendingAction === "mode",
|
||||
saveWorkspaceLayout,
|
||||
workspaceLayoutSaving: workspaceLayoutProfile.state === "saving",
|
||||
systemUtilityActions: computeContourSettings.utilityActions,
|
||||
systemUtilityActions: [...computeContourSettings.utilityActions, {label: "К списку воркеров", icon: "chevron-left", onClick: () => openNavigationView("workers")}],
|
||||
sessionOverview: { ...sessionOverview, available: Boolean(recordedReplay && replayPresented && !sourceSwitchBlocked) },
|
||||
});
|
||||
|
||||
@@ -687,11 +690,11 @@ export default function App() {
|
||||
/>
|
||||
}
|
||||
right={
|
||||
<HeaderProfile>
|
||||
<UserProfileMenu
|
||||
displayName="DC"
|
||||
subtitle="Mission Core"
|
||||
triggerLabel={null}
|
||||
headerAction={{label: notifications.unread ? `Центр событий · непрочитанных: ${notifications.unread}` : 'Центр событий', pressed: notifications.open, controls: 'operator-events', onSelect: () => notifications.setOpen(open => !open)}}
|
||||
actions={[
|
||||
{
|
||||
id: "refresh",
|
||||
@@ -707,7 +710,6 @@ export default function App() {
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</HeaderProfile>
|
||||
}
|
||||
/>
|
||||
);
|
||||
@@ -723,6 +725,8 @@ export default function App() {
|
||||
}
|
||||
contentOpen={workspace.contentOpen && activeDefinition !== null}
|
||||
contentExpanded
|
||||
endPanel={<EventPanel/>}
|
||||
endPanelOpen={notifications.open}
|
||||
header={header}
|
||||
stage={activeDefinition ? null :
|
||||
<LandingStage
|
||||
@@ -738,8 +742,8 @@ export default function App() {
|
||||
navigation={currentRoot && activeRoot === "system" ? (
|
||||
<SystemNavigationPanel
|
||||
title={currentRoot.title}
|
||||
onAdd={computeContourSettings.openCreate}
|
||||
onNavigateRoot={() => openNavigationView("modules")}
|
||||
activeId={activeDefinition?.id ?? "workers"}
|
||||
onNavigate={openNavigationView}
|
||||
onClose={workspace.closeNavigation}
|
||||
/>
|
||||
) : currentRoot ? (
|
||||
@@ -789,7 +793,7 @@ export default function App() {
|
||||
allowFullscreen={activeDefinition.kind === "vehicles"}
|
||||
eyebrow={activeDefinition.eyebrow}
|
||||
title={
|
||||
activeDefinition.kind === "vehicles"
|
||||
(activeDefinition.kind === "vehicles" || activeDefinition.kind === "architectural-projects")
|
||||
? <>{activeDefinition.title}<span className="fleet-header-title" ref={setWorkspaceHeaderTitleHost}/></>
|
||||
: activeDefinition.kind === "recordings"
|
||||
&& replayPresented
|
||||
@@ -836,7 +840,7 @@ export default function App() {
|
||||
/>
|
||||
) : activeDefinition.kind === "missions" ? (
|
||||
<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>
|
||||
) : activeDefinition.kind === "lab-archive" ? (
|
||||
laboratoryAnnotation.control
|
||||
@@ -844,13 +848,15 @@ export default function App() {
|
||||
<StatusBadge tone="neutral">Только наблюдение</StatusBadge>
|
||||
) : activeDefinition.kind === "contour-health" ? (
|
||||
<div ref={setWorkspaceHeaderToolsHost} />
|
||||
) : activeDefinition.kind === "workers" || activeDefinition.kind === "vps" ? (
|
||||
<div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} />
|
||||
) : activeDefinition.root === "system" ? (
|
||||
<SystemWorkspaceSelector
|
||||
value={activeDefinition.id}
|
||||
onChange={openNavigationView}
|
||||
/>
|
||||
) : (
|
||||
<StatusBadge tone="warning">Интерфейс готов</StatusBadge>
|
||||
<StatusBadge tone={activeDefinition.status === "active" ? "success" : "warning"}>{capabilityStatusLabel[activeDefinition.status ?? "contract"]}</StatusBadge>
|
||||
)
|
||||
}
|
||||
utilityActions={contentActions}
|
||||
@@ -1108,7 +1114,7 @@ export default function App() {
|
||||
<i className="api-dot" data-status={effectiveSourceUrl ? "online" : "checking"} aria-hidden="true" />
|
||||
{effectiveSourceUrl ? "Источник назначен" : "Источник не назначен"}
|
||||
</span>
|
||||
<p>Структура повторяет продуктовые сущности, а не внутренние панели визуального движка.</p>
|
||||
<Description>Структура повторяет продуктовые сущности, а не внутренние панели визуального движка.</Description>
|
||||
</div>
|
||||
<SceneLayerControls sceneSettings={sceneSettings} pending={runtime.pendingAction === "viewer"} applyScenePatch={applyScenePatch}/>
|
||||
</Window>
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { EnvironmentSettingsWindow as SharedEnvironmentSettingsWindow } from "@nodedc/ui-react";
|
||||
import { environmentSurfaceIds, type EnvironmentSettings, type EnvironmentSurfaceId, type UploadedEnvironmentMedia } from "../core/environment/environmentSettings";
|
||||
import { NetworkSettings } from "./network/NetworkSettings";
|
||||
import { CesiumServiceSettings } from "./map/CesiumServiceSettings";
|
||||
import { useLabStorageSettings } from "./storage/LabStorageSettings";
|
||||
import { roots, workspaces, workspacesForRoot } from "../productModel";
|
||||
|
||||
interface Props {
|
||||
@@ -16,7 +19,8 @@ const surfaces = environmentSurfaceIds.map(id => ({
|
||||
actions: id === "home" ? workspaces.filter(item => !item.internalOnly) : workspacesForRoot(id),
|
||||
}));
|
||||
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, {id: "network", label: "Сеть", icon: "network", content: props.open ? <NetworkSettings/> : null}, {id: "services", label: "Сервисы", icon: "key", content: props.open ? <CesiumServiceSettings/> : null}]}
|
||||
onSave={draft => props.onSave({ ...draft, pages: Object.fromEntries(environmentSurfaceIds.map(id => [id, draft.pages[id]])) as EnvironmentSettings["pages"] })}
|
||||
onUpload={(id, itemId, file) => {
|
||||
if (!environmentSurfaceIds.includes(id as EnvironmentSurfaceId)) throw new Error("Страница окружения недоступна.");
|
||||
|
||||
@@ -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 { EnvironmentPage } from "../core/environment/environmentSettings";
|
||||
@@ -35,7 +35,7 @@ export function LandingStage({
|
||||
<span className="section-eyebrow">ИСТОЧНИК</span>
|
||||
<StatusBadge tone={phaseTone(phase)}>{phaseLabel(phase)}</StatusBadge>
|
||||
</div>
|
||||
<p>{message || "Выберите архитектурный блок в верхней навигации."}</p>
|
||||
<Description>{message || "Выберите архитектурный блок в верхней навигации."}</Description>
|
||||
</>}
|
||||
footer={<>
|
||||
<span>{root?.accent ?? "НАБЛЮДЕНИЕ · МИССИИ · ДАННЫЕ"}</span>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { GlassSurface } from "@nodedc/ui-react";
|
||||
import { Description, GlassSurface } from "@nodedc/ui-react";
|
||||
|
||||
export interface MetricCardProps {
|
||||
eyebrow: string;
|
||||
@@ -16,7 +16,7 @@ export function MetricCard({ eyebrow, value, unit, detail, featured = false }: M
|
||||
<strong>{value}</strong>
|
||||
{unit ? <span>{unit}</span> : null}
|
||||
</div>
|
||||
<p>{detail}</p>
|
||||
<Description>{detail}</Description>
|
||||
</GlassSurface>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from "react";
|
||||
import { ConfirmationModal, Dropdown, Icon } from "@nodedc/ui-react";
|
||||
import { Description, ConfirmationModal, Dropdown, Icon } from "@nodedc/ui-react";
|
||||
|
||||
import {
|
||||
type ObservationSessionReplayLaunch,
|
||||
@@ -279,16 +279,16 @@ export function ObservationSessionSelect({
|
||||
description={deleteTarget ? <>
|
||||
<strong>{deleteTarget.label}</strong>
|
||||
{deleteTarget.lab ? (
|
||||
<p>
|
||||
<Description>
|
||||
Будут удалены только LAB-запись из каталога и её подготовленный кэш.
|
||||
Исходная запись {deleteTarget.lab.sourceSessionId} и зафиксированный
|
||||
лабораторный результат останутся неизменными.
|
||||
</p>
|
||||
</Description>
|
||||
) : (
|
||||
<p>
|
||||
<Description>
|
||||
Сессия, исходные данные наблюдения, подготовленная Rerun-запись и
|
||||
видеоматериалы будут удалены с этого сервера без возможности восстановления.
|
||||
</p>
|
||||
</Description>
|
||||
)}
|
||||
{sessions.error && sessions.deletingSessionId === null ? (
|
||||
<p className="observation-session-delete-error" role="alert">{sessions.error}</p>
|
||||
@@ -346,11 +346,11 @@ export function ObservationSessionArchive({
|
||||
{labsOnly ? "ВОСПРОИЗВОДИМЫЕ ЛАБОРАТОРНЫЕ ЗАПИСИ" : "АРХИВ НАБЛЮДЕНИЯ"}
|
||||
</span>
|
||||
<h2>{labsOnly ? "Записанные лабораторные работы" : "Сохранённые сессии"}</h2>
|
||||
<p>
|
||||
<Description>
|
||||
{labsOnly
|
||||
? "Каждая запись связана с LAB-конфигурацией и открывается как самостоятельный визуальный результат."
|
||||
: "Выберите запись: сцена и синхронные каналы откроются ниже, не меняя эфир наблюдения."}
|
||||
</p>
|
||||
</Description>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
@@ -457,16 +457,16 @@ export function ObservationSessionArchive({
|
||||
description={deleteTarget ? <>
|
||||
<strong>{deleteTarget.label}</strong>
|
||||
{deleteTarget.lab ? (
|
||||
<p>
|
||||
<Description>
|
||||
Будут удалены только LAB-запись из каталога и её подготовленный кэш.
|
||||
Исходная запись {deleteTarget.lab.sourceSessionId} и зафиксированный
|
||||
лабораторный результат останутся неизменными.
|
||||
</p>
|
||||
</Description>
|
||||
) : (
|
||||
<p>
|
||||
<Description>
|
||||
Сессия, исходные данные наблюдения, подготовленная Rerun-запись и
|
||||
видеоматериалы будут удалены с этого сервера без возможности восстановления.
|
||||
</p>
|
||||
</Description>
|
||||
)}
|
||||
</> : null}
|
||||
confirmLabel="Удалить сессию"
|
||||
|
||||
@@ -2200,7 +2200,7 @@ function RerunViewportInstance({
|
||||
/>
|
||||
) : null}
|
||||
{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" />
|
||||
<div>
|
||||
<strong>
|
||||
@@ -2217,7 +2217,7 @@ function RerunViewportInstance({
|
||||
</div>
|
||||
) : null}
|
||||
{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>
|
||||
<strong>Источник не открыт</strong>
|
||||
<span>Проверьте локальный поток Rerun или повторите подключение.</span>
|
||||
|
||||
@@ -11,13 +11,13 @@ export function BatteryAppearanceSettings({open,onClose,profile,sensor}:{sensor?
|
||||
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 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></>}
|
||||
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&§ion!=='markings'&§ion!=='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>
|
||||
{range('Размер маркировки, %',m.size,50,160,size=>update({...value,markings:{...m,size}}))}
|
||||
</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>;
|
||||
}
|
||||
|
||||
@@ -1,23 +1,24 @@
|
||||
import {useBatteryView} from '../../core/batteryScene/useBatteryView';
|
||||
import type {SensorDetailProps} from '../../../../../packages/sensor-ui/src/extensions';
|
||||
import {BatteryAppearanceSettings} from './BatteryAppearanceSettings';
|
||||
import {useBatteryAppearance} from '../../core/batteryScene/useBatteryAppearance';
|
||||
import type {BatteryAppearance} from '../../core/batteryScene/appearance';
|
||||
import {useEffect,useState,type ReactNode} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {EditorWorkspace,Icon,IconButton,ResizableViewport,ToastStack,useApplicationPanelFullscreen} from '@nodedc/ui-react';
|
||||
import {batteryViewHeight,batteryViewHeightKey,minBatteryViewHeight,maxBatteryViewHeight} from '../../core/batteryScene/viewHeight';
|
||||
import {EditorWorkspace,Icon,IconButton,LoadingRegion,ResizableViewport,ToastStack,useApplicationPanelFullscreen} from '@nodedc/ui-react';
|
||||
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}){
|
||||
const inheritedFull=useApplicationPanelFullscreen(),full=fullscreenControl??inheritedFull,[editing,setEditing]=useState(false),[error,setError]=useState(''),[settings,setSettings]=useState(false);
|
||||
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;
|
||||
useEffect(()=>()=>{setFullscreen?.(false);},[setFullscreen]);
|
||||
useEffect(()=>{const escape=(event:KeyboardEvent)=>{
|
||||
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();
|
||||
};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></>;
|
||||
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,
|
||||
} from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Button,
|
||||
Checker,
|
||||
ControlRow,
|
||||
@@ -35,7 +34,9 @@ import {
|
||||
import type { CanonicalLabReplayDescriptor } from "../../core/laboratory/canonicalLabReplay";
|
||||
import type { ObservationSessionReplayLaunch } from "../../core/observation/sessionArchive";
|
||||
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 {
|
||||
fetchLabViewProfile,
|
||||
@@ -216,6 +217,7 @@ export function CanonicalResultRerunReplay({
|
||||
const [viewerStatus, setViewerStatus] = useState<RerunViewportStatus>("idle");
|
||||
const [launch, setLaunch] = useState<CanonicalReplayLaunch | null>(null);
|
||||
const [launchError, setLaunchError] = useState<string | null>(null);
|
||||
const [preparationProgress, setPreparationProgress] = useState<Progress>({ phase: "checking", fraction: null });
|
||||
const sceneDraftRef = useRef(sceneDraft);
|
||||
const previousSplitViewRef = useRef(splitView);
|
||||
const trackedLaunchSha256Ref = useRef<string | null>(null);
|
||||
@@ -275,15 +277,10 @@ export function CanonicalResultRerunReplay({
|
||||
setPlayback(null);
|
||||
setPlaybackController(null);
|
||||
setViewerStatus("idle");
|
||||
void resolveObservationSessionReplay(sessionId, {
|
||||
signal: controller.signal,
|
||||
maximumWaitMs: 30 * 60 * 1000,
|
||||
onUpdate: () => undefined,
|
||||
}).then(async (value) => ({
|
||||
base: value,
|
||||
replay: await resolveReplay(resultId, value, { signal: controller.signal }),
|
||||
})).then((value) => {
|
||||
if (!controller.signal.aborted) setLaunch(value);
|
||||
void prepareLabReplay(resultId, sessionId, resolveReplay, {
|
||||
signal: controller.signal, onProgress: setPreparationProgress,
|
||||
}).then((value) => {
|
||||
if (!controller.signal.aborted) { setLaunch(value); announceLabStorageChange(); }
|
||||
}).catch((caught: unknown) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setLaunchError(caught instanceof Error ? caught.message : "Сохранённая запись недоступна.");
|
||||
@@ -465,7 +462,9 @@ export function CanonicalResultRerunReplay({
|
||||
emptyMessage="Слои результата недоступны."
|
||||
deckOverlays={presentationState === "loading" ? (
|
||||
<div className="canonical-vegetation-rerun-replay__loading">
|
||||
<ActivityIndicator label="Загружаем синхронизированную запись" />
|
||||
<LabReplayProgress progress={launch
|
||||
? { phase: "opening", fraction: playback?.bufferProgress ?? null }
|
||||
: preparationProgress} />
|
||||
</div>
|
||||
) : undefined}
|
||||
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 {
|
||||
forwardRef,
|
||||
type CSSProperties,
|
||||
@@ -915,7 +916,7 @@ LaboratoryMetricEvidenceSceneHandle,
|
||||
return (
|
||||
<div className="laboratory-metric-evidence-scene">
|
||||
<div ref={hostRef} className="laboratory-metric-evidence-scene__viewport">
|
||||
{renderError ? <p>{renderError}</p> : null}
|
||||
{renderError ? <Description>{renderError}</Description> : null}
|
||||
</div>
|
||||
<div className="laboratory-metric-evidence-scene__legend">
|
||||
{showRenderStats && renderStats ? (
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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> {
|
||||
id: T;
|
||||
@@ -91,7 +91,7 @@ export function LaboratorySelector<T extends string>({
|
||||
<div>
|
||||
<span className="section-eyebrow">{eyebrow}</span>
|
||||
<h2>{title}</h2>
|
||||
<p>{description}</p>
|
||||
<Description>{description}</Description>
|
||||
</div>
|
||||
<div className="laboratory-selector__control">
|
||||
<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 { resolveCanonicalLabReplay } from "../../core/laboratory/canonicalLabReplay";
|
||||
import type { ObservatoryPortableResultReview } from "../../core/observatory/recordedRun";
|
||||
@@ -38,7 +38,7 @@ export function PortableResultReplay({
|
||||
&& (moduleId === "rf-detr" || moduleId === "object-distance");
|
||||
if (!tgs && !semantics && !objects) return (
|
||||
<GlassSurface className="observatory-replay-state" padding="lg">
|
||||
<p role="alert">Сохранённый результат этого профиля пока не поддерживает визуальный разбор.</p>
|
||||
<Description role="alert">Сохранённый результат этого профиля пока не поддерживает визуальный разбор.</Description>
|
||||
</GlassSurface>
|
||||
);
|
||||
return <CanonicalResultRerunReplay key={review.resultId} resultId={review.resultId}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import {useEffect, useState} from "react";
|
||||
import {Description, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField} from "@nodedc/ui-react";
|
||||
import {cesiumServiceMessage, cesiumTokenIndicator, readCesiumService, saveCesiumService, verifyCesiumService,
|
||||
type CesiumRouteMode, type CesiumServiceSettings as Settings, type CesiumVerification} from "../../core/map/cesiumService";
|
||||
import "./cesiumServiceSettings.css";
|
||||
import {serverRequest, type Server} from "../../core/system/servers";
|
||||
|
||||
export function CesiumServiceSettings() {
|
||||
const [service, setService] = useState("");
|
||||
const [pending, setPending] = useState<"verify" | "save" | "remove" | null>(null);
|
||||
const [settings, setSettings] = useState<Settings | null>(null);
|
||||
const [mode, setMode] = useState<CesiumRouteMode>("auto");
|
||||
const [egress, setEgress] = useState("");
|
||||
const [servers, setServers] = useState<Server[]>([]);
|
||||
const [routesError, setRoutesError] = useState("");
|
||||
const [token, setToken] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [checkError, setCheckError] = useState("");
|
||||
const [showVerification, setShowVerification] = useState(false);
|
||||
const [verification, setVerification] = useState<CesiumVerification | null>(null);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
void readCesiumService().then(value => {if (active) {setSettings(value); setMode(value.mode); setEgress(value.egress_id || "");}})
|
||||
.catch(reason => {if (active) setError(reason.message);});
|
||||
void serverRequest<{items:Server[]}>("").then(value => {if(active) setServers(value.items);})
|
||||
.catch(reason => {if(active) setRoutesError(reason.message);});
|
||||
return () => {active = false;};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setVerification(null); setCheckError(""); setShowVerification(false);
|
||||
if (service !== "cesium" || !settings?.token_configured || token.trim() || egress !== (settings.egress_id || "")) {setChecking(false); return;}
|
||||
setChecking(true);
|
||||
void verifyCesiumService().then(value => {if (active) setVerification(value);})
|
||||
.catch(reason => {if (active) setCheckError(reason instanceof Error ? reason.message : cesiumServiceMessage());})
|
||||
.finally(() => {if (active) setChecking(false);});
|
||||
return () => {active = false;};
|
||||
}, [service, settings?.revision, settings?.token_configured, token, egress]);
|
||||
const indicator = cesiumTokenIndicator({configured: !!settings?.token_configured, draft: !!token.trim(),
|
||||
checking: checking || pending === "verify" || pending === "save", error: error || checkError, verification});
|
||||
async function action(kind: "verify" | "save" | "remove") {
|
||||
if (!settings || busy) return;
|
||||
setBusy(true); setPending(kind); setError(""); setCheckError(""); setVerification(null); setShowVerification(kind === "verify");
|
||||
try {
|
||||
if (kind === "verify") setVerification(await verifyCesiumService(token.trim() || undefined, egress));
|
||||
else {
|
||||
const result = await saveCesiumService({revision: settings.revision, mode, egress_id: egress,
|
||||
...(kind === "remove" ? {remove_token: true} : token.trim() ? {token: token.trim()} : {})});
|
||||
setSettings(result); setToken("");
|
||||
}
|
||||
} catch (reason) {setError(reason instanceof Error ? reason.message : cesiumServiceMessage());}
|
||||
finally {setBusy(false); setPending(null);}
|
||||
}
|
||||
return <SettingsCard title="Сервисы" actions={service === "cesium" && <>
|
||||
<IconButton label="Проверить доступ" disabled={busy || checking || !settings || (!token.trim() && !settings.token_configured)}
|
||||
loading={pending === "verify"} onClick={() => void action("verify")}><Icon name="activity"/></IconButton>
|
||||
<IconButton label="Сохранить" disabled={busy || !settings} loading={pending === "save"}
|
||||
onClick={() => void action("save")}><Icon name="save"/></IconButton>
|
||||
{settings?.token_configured && <IconButton label="Удалить токен" disabled={busy} loading={pending === "remove"}
|
||||
onClick={() => void action("remove")}><Icon name="trash"/></IconButton>}
|
||||
</>}>
|
||||
<Select label="Выберите сервис" value={service} disabled={busy} onChange={setService}
|
||||
options={[{value: "", label: "Выберите сервис"}, {value: "cesium", label: "Cesium ion",
|
||||
icon: <StatusBadge variant="indicator" tone={indicator.tone} pulse={indicator.pulse} title={indicator.label} aria-label={indicator.label}/>} ]}/>
|
||||
{service === "cesium" && <>
|
||||
<Description>Общий доступ к спутниковым картам, рельефу и зданиям во всех разделах Mission Core.</Description>
|
||||
{!settings && !error && <Description role="status">Получаем настройки…</Description>}
|
||||
{settings && <>
|
||||
<Select label="Подключение" value={mode} disabled={busy} onChange={value => setMode(value as CesiumRouteMode)}
|
||||
options={[{value: "auto", label: "Автоматически"}, {value: "direct", label: "Напрямую к источнику"},
|
||||
{value: "gateway", label: "Сервер хранения локальных данных"}]}/>
|
||||
<Description>{mode === "auto" ? "Карты используют сервер хранения локальных данных. Если сервер недоступен, подключение переключается на источник через интернет." :
|
||||
mode === "direct" ? "Карты загружаются через интернет без сохранения тайлов на этом компьютере." : "Карты загружаются только через сервер хранения локальных данных. Если сервер недоступен, загрузка приостанавливается."}</Description>
|
||||
<Select label="Маршрутизация" value={egress} disabled={busy} onChange={value=>{setEgress(value);setVerification(null);setError("");}}
|
||||
options={[{value:"",label:"Текущий маршрут"},...servers.flatMap(server=>server.services.filter(item=>item.kind==='egress').map(item=>({value:item.id,label:`${server.name} · ${server.address}`})))]}/>
|
||||
{routesError&&<Description role="alert">{routesError}</Description>}
|
||||
<TextField label={settings.token_configured ? "Новый токен Cesium ion" : "Токен Cesium ion"} type="password" value={token}
|
||||
disabled={busy} autoComplete="off" spellCheck={false} onChange={event => {setToken(event.target.value); setVerification(null); setError("");}}
|
||||
placeholder={settings.token_configured ? "Токен сохранён; заполните для замены" : "Токен"}/>
|
||||
<Description>Токен сохраняется только в Mission Core. Для прямого подключения нужен доступ к рельефу, спутниковой карте и зданиям Cesium ion.</Description>
|
||||
{showVerification && verification && <div className="cesium-service-results" role="status">{Object.entries(verification.assets).map(([id, result]) =>
|
||||
<Description key={id}>{({"1": "Рельеф", "2": "Спутниковая карта", "96188": "Здания"} as Record<string, string>)[id] ?? id}: {result.ok ? "доступ подтверждён" : cesiumServiceMessage(result.code)}</Description>)}</div>}
|
||||
</>}
|
||||
{error && <Description role="alert">{error}</Description>}
|
||||
</>}
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -652,6 +652,7 @@ function CacheHealth({
|
||||
);
|
||||
}
|
||||
const { cache } = health.snapshot;
|
||||
if (!cache) return <ControlRow label="Подключение"><StatusBadge tone="neutral">Источник · без кэша</StatusBadge></ControlRow>;
|
||||
return (
|
||||
<dl className="mission-map__cache-health">
|
||||
<div>
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
.cesium-service-results { display: grid; gap: var(--nodedc-space-2); }
|
||||
@@ -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";
|
||||
export function MissionCheckWindow({ open, onClose, busy, error, report, run }: {
|
||||
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">
|
||||
<p>Проверка сохранённой записи и выбранного участка. Новый проход со сканером для этой проверки не требуется.</p>
|
||||
<Description>Проверка сохранённой записи и выбранного участка. Новый проход со сканером для этой проверки не требуется.</Description>
|
||||
<LoadingRegion loading={busy} label="Проверка исходных данных">
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{error && <Description role="alert">{error}</Description>}
|
||||
{report && <><dl>
|
||||
<div><dt>Исходная запись</dt><dd>{report.source_verified ? "Контрольные суммы совпадают" : "Недоступна"}</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.pose_count.toLocaleString("ru-RU")}</dd></div>
|
||||
<div><dt>Максимальный шаг</dt><dd>{report.max_step_m.toFixed(2)} м</dd></div></dl>
|
||||
{report.warnings.map(w => <p key={w}>{w}</p>)}
|
||||
<p>Совмещение с повторным проходом не выполнялось. Записанная траектория описывает движение сканера; проходимость для аппарата по ней не проверена.</p></>}
|
||||
{report.warnings.map(w => <Description key={w}>{w}</Description>)}
|
||||
<Description>Совмещение с повторным проходом не выполнялось. Записанная траектория описывает движение сканера; проходимость для аппарата по ней не проверена.</Description></>}
|
||||
<Button disabled={busy} onClick={run}>{report ? "Повторить проверку" : "Начать проверку"}</Button>
|
||||
</LoadingRegion>
|
||||
</div></Window>;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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";
|
||||
/** Equal-axis plan projection; the moving marker is an archive pose, not localization. */
|
||||
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" />
|
||||
<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>
|
||||
</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)} />
|
||||
<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>;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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';
|
||||
|
||||
/** 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}</>;
|
||||
return <div className="mission-planner__check">
|
||||
<StatusBadge tone="warning">Исследование ожидает новую запись</StatusBadge>
|
||||
<p>{planning.test!.draft.name}</p>
|
||||
<p>Для самостоятельной съёмки завершите подготовленное исследование. Запись и подключение сканера не будут остановлены.</p>
|
||||
{planning.error && <p role="alert">{planning.error}</p>}
|
||||
<Description>{planning.test!.draft.name}</Description>
|
||||
<Description>Для самостоятельной съёмки завершите подготовленное исследование. Запись и подключение сканера не будут остановлены.</Description>
|
||||
{planning.error && <Description role="alert">{planning.error}</Description>}
|
||||
<div className="mission-planner__actions">
|
||||
<Button loading={planning.busy} onClick={() => void planning.finish()}>Завершить исследование</Button>
|
||||
<Button disabled={planning.busy} onClick={onResume}>Вернуться к исследованию</Button>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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 {planningTestTerminal,usePlanningTest} from '../../core/missions/PlanningTestContext';
|
||||
|
||||
@@ -15,17 +15,17 @@ export function PlanningConnectionWindow({children}:{children:ReactNode}){
|
||||
if(!p.test)return <>{children}</>;
|
||||
const t=p.test, terminal=planningTestTerminal(t);
|
||||
const details=<><StatusBadge tone="neutral">Профиль · Планирование</StatusBadge>
|
||||
<p>{t.draft.name} · эталон {t.draft.zone.label} · {t.draft.route.length_m.toFixed(1)} м</p>
|
||||
<p>Укажите новое имя проекта сканера. Неподвижная калибровка просматривает весь выбранный маршрут; после калибровки сканера оставайтесь на месте до статуса «Сопровождение». Если совпадение не найдено или неоднозначно, сцена сообщит причину и не начнёт сопровождение.</p></>;
|
||||
<Description>{t.draft.name} · эталон {t.draft.zone.label} · {t.draft.route.length_m.toFixed(1)} м</Description>
|
||||
<Description>Укажите новое имя проекта сканера. Неподвижная калибровка просматривает весь выбранный маршрут; после калибровки сканера оставайтесь на месте до статуса «Сопровождение». Если совпадение не найдено или неоднозначно, сцена сообщит причину и не начнёт сопровождение.</Description></>;
|
||||
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>
|
||||
{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>
|
||||
<Window open={open} title="Подключение сканера · Планирование" size="lg" className="planning-connection" onClose={()=>setOpen(false)}>
|
||||
<div className="mission-planner__check">{details}
|
||||
{t.state==='preparing'?<LoadingRegion loading label="Подготовка эталонного участка" />
|
||||
: terminal?<p>{t.message}</p>:children}
|
||||
: terminal?<Description>{t.message}</Description>:children}
|
||||
</div>
|
||||
</Window>
|
||||
</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';
|
||||
|
||||
export function PlanningProjectResult({project:p}:{project:PlanningProjectDetail}) {
|
||||
const r=p.result;
|
||||
return <Inspector variant="panel" defaultOpen={['sources','result']} sections={[
|
||||
{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>
|
||||
<div><dt>Участок эталона</dt><dd>{p.draft.route.length_m.toFixed(2)} м</dd></div></dl>
|
||||
</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>
|
||||
{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>}
|
||||
</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.scene_note&&p.scene_url&&<small>{p.scene_note}</small>}
|
||||
{r?.reasons.map(reason=><small key={reason}>{reason}</small>)}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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';
|
||||
|
||||
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="Удалить совмещённый маршрут?"
|
||||
description={target ? <>
|
||||
<strong>{target.name}</strong>
|
||||
<p>{new Date(target.created_at_utc).toLocaleString('ru-RU')} · {planningProjectStatus(target)}</p>
|
||||
<p>Проект будет удалён из списка совмещённых маршрутов. Эталон, запись прохода и сохранённые отчёты останутся на диске. Другие проекты не изменятся.</p>
|
||||
<Description>{new Date(target.created_at_utc).toLocaleString('ru-RU')} · {planningProjectStatus(target)}</Description>
|
||||
<Description>Проект будет удалён из списка совмещённых маршрутов. Эталон, запись прохода и сохранённые отчёты останутся на диске. Другие проекты не изменятся.</Description>
|
||||
</> : null}
|
||||
confirmLabel="Удалить маршрут" pendingLabel="Удаление…" danger
|
||||
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 type { useMissionPlanner } from '../../core/missions/useMissionPlanner';
|
||||
|
||||
@@ -24,7 +24,7 @@ export function PlanningProjectSettings({p,onStart,starting}:{
|
||||
<div className="inspector-control-stack">
|
||||
{p.source&&!routeReady&&<small>В записи недостаточно перемещения для привязки. Выберите другой эталон.</small>}
|
||||
<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>
|
||||
</>;
|
||||
}
|
||||
|
||||
@@ -2,10 +2,10 @@ import {Fragment,useEffect,useState} from 'react';
|
||||
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
|
||||
|
||||
type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]};
|
||||
export function InstallerCard({kind}:{kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'}){
|
||||
export function InstallerCard({kind,connectionInstruction}:{connectionInstruction?:string;kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'|'vps-librespeed'|'vps-egress'}){
|
||||
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
|
||||
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
|
||||
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((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>
|
||||
</SettingsCard>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import {useState} from 'react';
|
||||
import {Button,Description,Select,SettingsCard} from '@nodedc/ui-react';
|
||||
import {useServers,useServerHealth} from '../../core/system/servers';
|
||||
import {selectedSpeedServer,speedtestServers} from '../../core/system/speedtestServers';
|
||||
import {useCoreSpeedtest} from '../../core/system/networkSpeedtest';
|
||||
import {ServerServiceSetup} from '../system/ServerServiceSetup';
|
||||
import {RouterSpeedGauge} from './RouterSpeedGauge';
|
||||
import './networkSettings.css';
|
||||
|
||||
const format=(value:number)=>`${new Intl.NumberFormat('ru-RU',{maximumFractionDigits:1}).format(value)} мс`;
|
||||
export function NetworkSettings(){
|
||||
const servers=useServers(),health=useServerHealth(servers.items,servers.generation),test=useCoreSpeedtest();
|
||||
const [selected,setSelected]=useState(''),[setup,setSetup]=useState(false);
|
||||
const items=speedtestServers(servers.items,health);
|
||||
const chosen=selectedSpeedServer(items,selected,test.running?test.receipt?.server_id:undefined);
|
||||
const measurement=test.receipt?.measurement;
|
||||
const busy=test.sending||test.running;
|
||||
const ready=test.loaded&&test.fresh&&chosen?.online&&!servers.error;
|
||||
return <>
|
||||
<SettingsCard title="Замер скорости" description="Проверяется интернет компьютера, на котором работает Mission Core. Замер занимает около 30 секунд.">
|
||||
{!servers.items&&!test.receipt?<Description role="status">{servers.error||'Получаем список VPS…'}</Description>:items.length===0&&!test.receipt?<>
|
||||
<Description>Для замера подключите службу LibreSpeed на одном из ваших VPS.</Description>
|
||||
<Button disabled={busy||!!servers.error} onClick={()=>setSetup(true)}>Добавить службу</Button>
|
||||
</>:<>
|
||||
{items.length>0?<Select label="Сервер замера" disabled={busy} value={chosen?.service.id??''} onChange={setSelected}
|
||||
options={[{value:'',label:'Выберите VPS'},...items.map(item=>({value:item.service.id,label:`${item.server.name} · ${item.server.address}${item.online?'':` · ${item.label}`}`}))]}/>:<Description>Служба замера больше не доступна в списке VPS.</Description>}
|
||||
{chosen&&!chosen.online&&<Description role="status">Служба не подтвердила доступность. Список обновляется автоматически.</Description>}
|
||||
{servers.error&&<Description role="alert">{servers.error}</Description>}
|
||||
<RouterSpeedGauge key={test.receipt?.operation_id??'idle'} measurement={measurement} waiting={test.receipt?.state==='queued'} fresh={test.fresh} staleLabel="Обновляем данные замера"/>
|
||||
{test.receipt?.state==='cancelling'&&<Description role="status">Останавливаем замер…</Description>}
|
||||
{measurement?.phase==='complete'&&<>
|
||||
<dl className="network-speed-facts">
|
||||
<div><dt>Задержка HTTP</dt><dd>{format(measurement.latency_ms)}</dd></div>
|
||||
<div><dt>Джиттер HTTP</dt><dd>{format(measurement.jitter_ms)}</dd></div>
|
||||
</dl>
|
||||
<Description>{test.receipt?.server_name} · {new Date((measurement.finished_at??measurement.started_at)*1000).toLocaleString('ru-RU')}</Description>
|
||||
</>}
|
||||
{measurement?.phase==='error'&&<Description role="alert">Замер не завершён. Проверьте соединение и доступность VPS. Возможно, на сервере уже идёт другой замер.</Description>}
|
||||
{test.loaded&&!test.fresh&&<Description role="status">Нет свежих данных от Mission Core. Состояние замера уточняется.</Description>}
|
||||
<div className="network-speed-actions">
|
||||
{test.running?<Button disabled={test.sending||test.receipt?.state==='cancelling'} onClick={()=>void test.cancel()}>Остановить замер</Button>:<Button disabled={test.sending||!ready} loading={test.sending} onClick={()=>chosen&&void test.start(chosen.service.id)}>Начать замер</Button>}
|
||||
<Button disabled={busy} onClick={()=>setSetup(true)}>Добавить службу</Button>
|
||||
</div>
|
||||
<Description>Используется текущее соединение компьютера, включая VPN, если он включён. Результат относится к выбранному VPS и времени замера.</Description>
|
||||
</>}
|
||||
{test.error&&<Description role="alert">{test.error}</Description>}
|
||||
</SettingsCard>
|
||||
{setup&&<ServerServiceSetup fixedKind="librespeed" onClose={()=>setSetup(false)} onSaved={()=>{setSetup(false);servers.refresh();}}/>}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import {Description,StatusBadge} from '@nodedc/ui-react';
|
||||
import {ObservationHeader} from '../../../../../packages/sensor-ui/src/ObservationHeader';
|
||||
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
|
||||
import {metric,type RouterDevice,type RouterSnapshot} from '../../../../../packages/router-ui/src/contracts';
|
||||
import {RouterSignal} from '../../../../../packages/router-ui/src/RouterSignal';
|
||||
import {routerObservation} from '../../core/fleet/routerObservation';
|
||||
import '../../../../../packages/router-ui/src/router.css';
|
||||
import './routerObservation.css';
|
||||
|
||||
export function RouterObservation({device,value,compact=false,header}:{device:RouterDevice;value:RouterSnapshot|null;compact?:boolean;header?:ObservationHeaderTargets}){
|
||||
const view=routerObservation(device,value);
|
||||
return <div className="router-observation" aria-label={`Связь · ${view.name}`}>
|
||||
{header&&<ObservationHeader targets={header} live={view.live} waiting={view.waiting} label={view.status}/>}
|
||||
{!compact&&<div>
|
||||
<div className="router-observation__summary"><strong>{view.mode.current}</strong><StatusBadge variant="indicator" tone={view.ready?'success':'neutral'} aria-label={view.status} title={view.status}/></div>
|
||||
<Description>{view.internet}</Description>
|
||||
{view.ready&&view.mode.message&&<Description role="status">{view.mode.message}</Description>}
|
||||
</div>}
|
||||
{view.channels.map(channel=><section key={channel.slot} className="router-observation__channel" aria-label={`${channel.label} · ${channel.detail} · ${channel.status}`}>
|
||||
<div className="router-observation__summary"><StatusBadge variant="indicator" tone={channel.indicator} aria-label={`${channel.label} · ${channel.indicatorLabel}`} title={`${channel.label} · ${channel.indicatorLabel}`}/><strong>{channel.label}</strong><span>{channel.operator}</span><strong className="router-observation__value">{channel.rsrp==null?'—':metric(channel.rsrp,'dBm')}</strong></div>
|
||||
{!compact&&<RouterSignal rsrp={channel.rsrp} compact/>}
|
||||
</section>)}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
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);
|
||||
const tickLength=12;
|
||||
function markerPoint(fraction:number){
|
||||
const p=speedPoint(fraction);
|
||||
return{x:p.x+p.nx*tickLength/2,y:p.y+p.ny*tickLength/2};
|
||||
}
|
||||
export function RouterSpeedGauge({measurement,waiting,fresh,staleLabel="Ожидаем данные борта"}:{measurement?:SpeedMeasurement;waiting:boolean;fresh:boolean;staleLabel?:string}){
|
||||
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=markerPoint(useMarker(speedFraction(active??0,ceiling)));
|
||||
const secondary=markerPoint(speedFraction(up??0,ceiling));
|
||||
const state=waiting?'Подготовка замера':stale?staleLabel: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*tickLength} y2={p.y+p.ny*tickLength} 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,4 @@
|
||||
.network-speed-facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--nodedc-space-4);margin:0;}
|
||||
.network-speed-facts dt{color:var(--nodedc-text-secondary);font-size:var(--nodedc-font-size-sm);}
|
||||
.network-speed-facts dd{margin:var(--nodedc-space-1) 0 0;font-size:var(--nodedc-font-size-md);}
|
||||
.network-speed-actions{display:flex;flex-wrap:wrap;gap:var(--nodedc-space-2);}
|
||||
@@ -0,0 +1,10 @@
|
||||
.router-observation {height:100%;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:var(--nodedc-space-2);padding:var(--nodedc-space-2);font-size:var(--nodedc-font-size-sm);--nodedc-description-font-size:var(--nodedc-font-size-xs);}
|
||||
.router-observation__channel {display:flex;flex-direction:column;}
|
||||
.router-observation__summary {display:flex;align-items:center;flex-wrap:wrap;gap:var(--nodedc-space-2);}
|
||||
.router-observation__summary strong {font-weight:var(--nodedc-font-weight-medium);}
|
||||
.router-observation__value {margin-inline-start:auto;white-space:nowrap;}
|
||||
|
||||
.router-observation .router-signal-scale {margin-top:0;}
|
||||
.router-observation .router-signal-zone {min-height:24px;}
|
||||
.router-observation .router-signal-track {height:4px;}
|
||||
.router-observation .router-signal-marker {width:8px;height:8px;}
|
||||
@@ -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,54 @@
|
||||
import {useEffect, useState} from 'react';
|
||||
import {Button, Checker, Description, FeatureSettingsWindow, SettingsCard} from '@nodedc/ui-react';
|
||||
import {notificationRequest} from '../../core/notifications/history';
|
||||
|
||||
interface Preference {
|
||||
key: string;
|
||||
section: string;
|
||||
group: string;
|
||||
label: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export function EventSettings({onClose}: {onClose: () => void}) {
|
||||
const [items, setItems] = useState<Preference[]>([]);
|
||||
const [section, setSection] = useState('Сеть');
|
||||
const [error, setError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setError('');
|
||||
notificationRequest<Preference[]>('/preferences').then(result => {
|
||||
if (active) setItems(result);
|
||||
}).catch(() => { if (active) setError('Не удалось загрузить настройки событий.'); });
|
||||
return () => { active = false; };
|
||||
}, [attempt]);
|
||||
|
||||
async function configure(key: string, enabled: boolean) {
|
||||
setSaving(true);
|
||||
setError('');
|
||||
try {
|
||||
setItems(await notificationRequest<Preference[]>('/preferences', 'PATCH', {key, enabled}));
|
||||
} catch {
|
||||
setError('Не удалось подтвердить изменение. Обновите настройки и повторите попытку.');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
const sections = [...new Set(items.map(item => item.section))];
|
||||
const current = items.filter(item => item.section === section);
|
||||
const groups = [...new Set(current.map(item => item.group))];
|
||||
return <FeatureSettingsWindow open title="Настройки центра событий"
|
||||
identity={{title: 'Центр событий', avatarLabel: 'ЦС'}}
|
||||
sections={sections.map(label => ({id: label, label, icon: label === 'Сеть' ? 'network' : 'activity'}))}
|
||||
activeSection={section} onSectionChange={setSection} onClose={onClose}>
|
||||
{error && <><Description role="alert">{error}</Description><Button onClick={() => setAttempt(n => n + 1)}>Обновить настройки</Button></>}
|
||||
{!error && !items.length && <Description role="status">Загружаем настройки…</Description>}
|
||||
{groups.map(group => <SettingsCard key={group} title={group}>
|
||||
{current.filter(item => item.group === group).map(item => <Checker key={item.key}
|
||||
label={item.label} checked={item.enabled} disabled={saving}
|
||||
onChange={enabled => void configure(item.key, enabled)}/>)}
|
||||
</SettingsCard>)}
|
||||
</FeatureSettingsWindow>;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import {useEffect, useRef, useState, type ReactNode} from 'react';
|
||||
import {ApplicationSidePanel, Button, Description, Icon, IconButton, ResourceList, ResourceRow, StatusBadge, ToastStack} from '@nodedc/ui-react';
|
||||
import {NotificationContext, useNotificationHistory, useNotifications} from '../../core/notifications/useNotificationHistory';
|
||||
import type {NotificationTone} from '../../core/notifications/history';
|
||||
import {EventSettings} from './EventSettings';
|
||||
|
||||
const tones = {success: 'success', warning: 'warning', error: 'danger', info: 'neutral'} as const;
|
||||
const labels: Record<NotificationTone, string> = {success: 'Успешно', warning: 'Внимание', error: 'Ошибка', info: 'Информация'};
|
||||
|
||||
export function NotificationHost({children}: {children: ReactNode}) {
|
||||
const state = useNotificationHistory();
|
||||
return <NotificationContext.Provider value={state}>
|
||||
{children}
|
||||
<ToastStack items={state.toasts} onDismiss={state.dismiss} observe={false}/>
|
||||
</NotificationContext.Provider>;
|
||||
}
|
||||
|
||||
export function EventPanel() {
|
||||
const state = useNotifications();
|
||||
const [settings, setSettings] = useState(false);
|
||||
const gear = useRef<HTMLButtonElement>(null);
|
||||
const close = () => {
|
||||
state.setOpen(false);
|
||||
document.querySelector<HTMLButtonElement>('[aria-controls="operator-events"]')?.focus();
|
||||
};
|
||||
useEffect(() => {
|
||||
if (!state.open) return;
|
||||
gear.current?.focus({preventScroll: true});
|
||||
}, [state.open]);
|
||||
return <ApplicationSidePanel id="operator-events" eyebrow="Mission Core" title="Центр событий"
|
||||
inert={!state.open} aria-label="Центр событий" closeLabel="Закрыть центр событий" onClose={close}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Escape' && !settings) { event.stopPropagation(); close(); }
|
||||
}}
|
||||
headerActions={<IconButton ref={gear} label="Настройки центра событий" onClick={() => setSettings(true)}><Icon name="settings"/></IconButton>}>
|
||||
{state.error && <Description role="status">{state.error}</Description>}
|
||||
{!state.items.length && <Description>{state.loading ? 'Получаем события…' : 'Событий пока нет.'}</Description>}
|
||||
<ResourceList aria-label="История событий">{state.items.map(item => <li key={item.identity}>
|
||||
<ResourceRow title={item.title} description={item.description}
|
||||
metadata={new Date(item.at * 1000).toLocaleString('ru-RU')}
|
||||
statusPlacement="leading" status={<StatusBadge variant="indicator" tone={tones[item.tone]}
|
||||
aria-label={labels[item.tone]} title={labels[item.tone]}/>}/>
|
||||
</li>)}</ResourceList>
|
||||
{state.more && <Button loading={state.loading} onClick={() => void state.loadMore()}>Показать ещё</Button>}
|
||||
{settings && state.open && <EventSettings onClose={() => setSettings(false)}/>}
|
||||
</ApplicationSidePanel>;
|
||||
}
|
||||
@@ -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))} />
|
||||
</>;
|
||||
}
|
||||
@@ -3,29 +3,40 @@ import {Button,Description,Select,SettingsCard,Switch,Window,WindowFooterActions
|
||||
import {localDevOptions,type DevOptions,type RoverDiagnostics} from '../../core/fleet/useRoverDiagnostics';
|
||||
import './roverLogs.css';
|
||||
|
||||
export function RoverDevWindow({capture,close,started}:{capture:RoverDiagnostics;close:()=>void;started:()=>void}){
|
||||
export function RoverDevWindow({capture,close}:{capture:RoverDiagnostics;close:()=>void}){
|
||||
const [options,setOptions]=useState<DevOptions>({...localDevOptions});
|
||||
const [local,setLocal]=useState({enabled:true,preview:true});
|
||||
const set=(key:keyof DevOptions,value:boolean|number)=>setOptions(current=>({...current,[key]:value}));
|
||||
const rates=[8,16,32,64].map(value=>({value:String(value),label:`${value} кбит/с`}));
|
||||
const begin=async()=>{if(await capture.toggle(options,local)){started();close();}};
|
||||
return <Window open onClose={close} title="Настройки DEV-записи" size="md" footer={<WindowFooterActions><Button onClick={close}>Отмена</Button><Button variant="primary" loading={capture.pending} disabled={!capture.state.options_supported} onClick={()=>void begin()}>Начать запись</Button></WindowFooterActions>}>
|
||||
const begin=async()=>{if(await capture.toggle({...options,router:!!capture.state.sources_supported&&options.router,system:!!capture.state.sources_supported&&options.system},local)){close();}};
|
||||
return <Window open onClose={close} title="Настройки DEV-записи" size="md" footer={<WindowFooterActions><Button onClick={close}>Отмена</Button><Button variant="primary" loading={capture.pending} disabled={!capture.state.options_supported||(options.passive&&!capture.state.passive_supported)} onClick={()=>void begin()}>Начать запись</Button></WindowFooterActions>}>
|
||||
<div className="rover-dev-options">
|
||||
<Description>Запись сохраняется на борту. После завершения её можно скачать в окне логов. Закрытие окна не останавливает запись.</Description>
|
||||
<SettingsCard title="Что записывать" description="Переходы управления, остановки и ошибки записываются всегда.">
|
||||
<Switch label="Подробные замеры моторов" checked={options.motor_samples} onChange={value=>set('motor_samples',value)}/>
|
||||
<Switch label="Сетевые события и распределение полосы" checked={options.network} onChange={value=>set('network',value)}/>
|
||||
<Switch label="Моторы и CAN" checked={options.motor_samples} onChange={value=>set('motor_samples',value)}/>
|
||||
<Switch label="Связь с Mission Core" checked={options.network} onChange={value=>set('network',value)}/>
|
||||
<Description>Доставка команд и телеметрии, задержки, распределение полосы, сетевой путь и счётчики интерфейсов.</Description>
|
||||
<Switch label="Роутер и SIM-карты" disabled={!capture.state.sources_supported} checked={!!capture.state.sources_supported&&options.router} onChange={value=>set('router',value)}/>
|
||||
<Description>Режим роутера, активный выход, состояние SIM и радиосигнал с временем исходного замера. В пассивном режиме используются обычные обновления роутера.</Description>
|
||||
<Switch label="Состояние борта и оборудования" disabled={!capture.state.sources_supported} checked={!!capture.state.sources_supported&&options.system} onChange={value=>set('system',value)}/>
|
||||
<Description>Сетевые интерфейсы, USB-устройства, нагрузка и задержки выполнения на борту.</Description>
|
||||
{!capture.state.sources_supported&&<Description>Новые источники записи станут доступны после обновления Node.</Description>}
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Замеры на компьютере" description="Задержки команд и события браузера сохраняются отдельно от записи борта. Эти замеры не передаются на борт.">
|
||||
<Switch label="Записать замеры Core и браузера" checked={local.enabled} onChange={enabled=>setLocal(current=>({...current,enabled}))}/>
|
||||
{local.enabled&&<><Switch label="Добавить статистику видео" checked={local.preview} onChange={preview=>setLocal(current=>({...current,preview}))}/><Description>Без записи изображения. Замер хранится в памяти до перезапуска Core: не более 15 минут и последних 6000 событий. После остановки сохраните его отдельной кнопкой в окне логов.</Description></>}
|
||||
{local.enabled&&<><Switch label="Добавить статистику видео" checked={local.preview} onChange={preview=>setLocal(current=>({...current,preview}))}/><Description>Без записи изображения. Замер сохраняется на компьютере до одного часа, не более 32 МБ. Доступны текущий и три предыдущих файла; перезапуск Core их не удаляет.</Description></>}
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Передача во время записи" description={!options.live&&!options.core_trace?'Диагностические события остаются на борту. По сети передаётся только короткое состояние записи.':'Эти потоки используют сеть. На слабом канале их можно отключить и скачать файл позже.'}>
|
||||
<SettingsCard title="Передача во время записи" description={options.passive?'Логи остаются на борту и в Core. Дополнительных сетевых запросов во время записи нет; выгрузка — по вашему запросу.':!options.live&&!options.core_trace?'Диагностические события остаются на борту. По сети передаётся только короткое состояние записи.':'Эти потоки используют сеть. На слабом канале их можно отключить и скачать файл позже.'}>
|
||||
<Switch label="Пассивная запись" checked={options.passive} onChange={passive=>setOptions(current=>({...current,passive,...(passive?{live:false,core_trace:false}:{})}))}/>
|
||||
{options.passive&&<Description>Подтверждения запуска и остановки передаются один раз. Статистика браузера добавляется при остановке или сохранении; до этого она хранится локально в браузере.</Description>}
|
||||
{!options.passive&&<>
|
||||
<Switch label="Показывать события онлайн" checked={options.live} onChange={value=>set('live',value)}/>
|
||||
{options.live&&<Select label="Лимит live-событий" value={String(options.live_kbps)} options={rates} onChange={value=>set('live_kbps',Number(value))}/>}
|
||||
<Switch label="Добавлять события Core и браузера" checked={options.core_trace} onChange={value=>set('core_trace',value)}/>
|
||||
{options.core_trace&&<><Description>Эти события передаются с компьютера оператора на борт. При нехватке полосы пропуски отмечаются в записи.</Description><Select label="Лимит событий на борт" value={String(options.core_kbps)} options={rates} onChange={value=>set('core_kbps',Number(value))}/></>}
|
||||
</>}
|
||||
</SettingsCard>
|
||||
{options.passive&&!capture.state.passive_supported&&<Description>Для пассивной записи требуется обновление Node на борту.</Description>}
|
||||
{!capture.state.options_supported&&<Description>Борт ещё не подтвердил доступность настроек записи. Запуск станет доступен после подключения совместимого борта.</Description>}
|
||||
</div>
|
||||
</Window>;
|
||||
|
||||
@@ -1,21 +1,28 @@
|
||||
import {useState} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {Button,StatusBadge} from '@nodedc/ui-react';
|
||||
import { Description,Button,Select,StatusBadge} from '@nodedc/ui-react';
|
||||
import type {RoverDiagnostics} from '../../core/fleet/useRoverDiagnostics';
|
||||
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
|
||||
import './roverLogs.css';
|
||||
export function RoverLogs({capture,header}:{capture:RoverDiagnostics;header:ObservationHeaderTargets}){
|
||||
const [selected,setSelected]=useState('');
|
||||
const localCaptures=[capture.state.local_capture,...(capture.state.local_history??[])].filter(item=>item?.id);
|
||||
const selectedCapture=localCaptures.find(item=>item?.id===selected)??localCaptures[0];
|
||||
const storage=capture.state.node?.storage,failed=storage?.error||capture.state.node?.transport_error;
|
||||
const passive=capture.state.active&&capture.state.options?.passive===true;
|
||||
const status=failed?'Ошибка записи':capture.state.closing?'Завершение записи':storage?.closed?'Запись завершена':capture.state.node?.active?'Запись на борт':'Ожидание борта';
|
||||
return <>
|
||||
{createPortal(<StatusBadge variant="indicator" tone={failed?'danger':capture.state.node?.active?'success':'warning'} aria-label={status} title={status}/>,header.statusTarget)}
|
||||
|
||||
<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>
|
||||
<p>{status} · {storage?.written??0} записей{storage?.dropped?` · Потеряно при записи: ${storage.dropped}`:''}</p>
|
||||
{storage?.file&&<p title={storage.file}>{storage.file}</p>}
|
||||
{failed&&<p role="alert">Файл может быть неполным: {failed}</p>}
|
||||
<p>{capture.state.options?.live===false?'События записываются локально; live-передача отключена.':'Последние события онлайн.'} «Сохранить с борта» выгружает полный бортовой файл. Закрытие окна не завершает запись.</p>
|
||||
{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>}
|
||||
<div className="rover-logs__actions"><Button disabled={!storage?.file} loading={capture.saving} onClick={()=>void capture.save()}>Сохранить с борта</Button>{selectedCapture?.id&&<Button loading={capture.saving} onClick={()=>void capture.saveLocal(selectedCapture.id!)}>Сохранить с компьютера</Button>}</div>
|
||||
{localCaptures.length>1&&<Select label="Замер компьютера" value={selectedCapture?.id??''} options={localCaptures.map(item=>({value:item!.id!,label:`${item!.started_at?new Date(item!.started_at).toLocaleString('ru-RU'):'Последний замер'} · ${item!.active?'Запись идёт':'Завершён'}`}))} onChange={setSelected}/>}
|
||||
<Description>{status}{passive?' · Пассивная запись':` · ${storage?.written??0} записей`}{storage?.dropped?` · Потеряно при записи: ${storage.dropped}`:''}</Description>
|
||||
{storage?.file&&<Description title={storage.file}>{storage.file}</Description>}
|
||||
{failed&&<Description role="alert">Файл может быть неполным: {failed}</Description>}
|
||||
<Description>{passive?(capture.state.passive_confirmed?'Запуск подтверждён. Состояние файла обновится при остановке или сохранении.':'Ожидаем подтверждение запуска записи на борту.'):capture.state.options?.live===false?'События записываются локально; live-передача отключена.':'Последние события онлайн.'} «Сохранить с борта» выгружает полный бортовой файл. Закрытие окна не завершает запись.</Description>
|
||||
{selectedCapture?.id&&<Description>Замер компьютера: {selectedCapture.active?'идёт запись':'завершён'} · {selectedCapture.storage?.written??selectedCapture.sequence??0} событий{(selectedCapture.storage?.dropped??selectedCapture.dropped)?` · Пропущено: ${selectedCapture.storage?.dropped??selectedCapture.dropped}`:''}. Доступны текущий и три предыдущих файла. Новый запуск постепенно заменяет старые замеры; нужные можно скачать.</Description>}
|
||||
{selectedCapture?.storage?.error&&<Description role="alert">Замер компьютера может быть неполным: {selectedCapture.storage.error}</Description>}
|
||||
<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>;})}
|
||||
</div>
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import {ComparisonTable,Description,StatusBadge} from '@nodedc/ui-react';
|
||||
import type {RoverState} from '../../core/fleet/useRoverControl';
|
||||
import type {RoverObservationStatus} from '../../core/fleet/roverObservation';
|
||||
import {ObservationHeader} from '../../../../../packages/sensor-ui/src/ObservationHeader';
|
||||
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
|
||||
import type {RoverConnection} from '../../core/fleet/roverTransport';
|
||||
import {drivePositions} from '../../../../../plugins/vesc/frontend/src/model';
|
||||
const number=(v:number|undefined,digits=1)=>typeof v==='number'&&Number.isFinite(v)?v.toLocaleString('ru-RU',{maximumFractionDigits:digits}):'—';
|
||||
export function roverTelemetryTable(state:RoverState){
|
||||
export function roverTelemetryTable(state:RoverState,compact=false){
|
||||
const devices=state.snapshot.devices??[],profile=state.snapshot.profile;
|
||||
const positions=drivePositions(profile?.layout??null);
|
||||
const assigned=Object.entries(profile?.bindings??{}).map(([slot,binding])=>({
|
||||
@@ -13,17 +16,24 @@ export function roverTelemetryTable(state:RoverState){
|
||||
const readings=[...assigned,...devices.filter(d=>!assigned.some(a=>a.id===d.id&&a.uuid===d.uuid)).map(d=>({...d,reading:d}))];
|
||||
const fresh=(d:typeof readings[number])=>state.fresh&&!!d.reading&&Number.isFinite(d.reading.age_ms)&&d.reading.age_ms>=0&&d.reading.age_ms<1000;
|
||||
const metrics=[['motor_current_a','Ток мотора','А',1],['input_current_a','Ток батареи','А',1],['input_voltage_v','Напряжение','В',1],['erpm','Обороты, ERPM','',0],['mos_temperature_c','Контроллер','°C',1]] as const;
|
||||
const available=readings.filter(fresh).length;
|
||||
const health=state.snapshot.supported&&available>0&&available===readings.length?'online':available||state.snapshot.observation?.initializing_devices?.length?'partial':'offline';
|
||||
return {
|
||||
columns:readings.map(d=>({id:d.id+':'+d.uuid,label:d.uuid.slice(0,6).toUpperCase()})),
|
||||
health,columns:readings.map(d=>({id:d.id+':'+d.uuid,label:d.uuid.slice(0,6).toUpperCase()})),
|
||||
rows:[{id:'position',label:'Расположение',cells:readings.map(d=>d.label||'Не назначено')},
|
||||
{id:'status',label:'Связь',cells:readings.map(d=>!state.fresh?'Нет данных':!d.reading?'Нет связи':fresh(d)?'В сети':'Нет данных')},
|
||||
...metrics.map(([key,label,unit,digits])=>({id:key,label,cells:readings.map(d=>{const value=fresh(d)?d.reading?.values?.[key]:undefined;return typeof value==='number'&&Number.isFinite(value)?`${number(value,digits)}${unit?' '+unit:''}`:'—';})})),
|
||||
{id:'fault',label:'Ошибка VESC',cells:readings.map(d=>{const code=fresh(d)?d.reading?.values?.fault_code:undefined;return typeof code==='number'?code===0?'Нет':String(code):'—';})}],
|
||||
...(compact?metrics.slice(0,1):metrics).map(([key,label,unit,digits])=>({id:key,label,cells:readings.map(d=>{const value=fresh(d)?d.reading?.values?.[key]:undefined;return typeof value==='number'&&Number.isFinite(value)?`${number(value,digits)}${unit?' '+unit:''}`:'—';})})),
|
||||
...(!compact?[{id:'fault',label:'Ошибка VESC',cells:readings.map(d=>{const code=fresh(d)?d.reading?.values?.fault_code:undefined;return typeof code==='number'?code===0?'Нет':String(code):'—';})}]:[])],
|
||||
};
|
||||
}
|
||||
export function RoverTelemetry({state,observation}:{state:RoverState;observation?:RoverObservationStatus}){
|
||||
const table=roverTelemetryTable(state);
|
||||
return <div className="rover-telemetry">{observation?.label&&<StatusBadge tone="warning" pulse={observation.pulse}>{observation.label}</StatusBadge>}{table.columns.length?<ComparisonTable density="compact" label="Телеметрия VESC" heading="VESC" {...table}/>:!observation?.label&&<Description>{state.fresh?'Получение показаний VESC…':'Нет свежих показаний VESC.'}</Description>}</div>;
|
||||
export function RoverTelemetry({state,observation,compact=false,header,connection='connected'}:{
|
||||
state:RoverState;observation?:RoverObservationStatus;compact?:boolean;header?:ObservationHeaderTargets;connection?:RoverConnection
|
||||
}){
|
||||
const table=roverTelemetryTable(state,compact);
|
||||
const live=connection==='connected' && state.fresh && table.health==='online';
|
||||
const waiting=connection==='connecting'||connection==='reconnecting'||(connection==='connected'&&state.fresh&&table.health==='partial');
|
||||
const label=live?'Телеметрия VESC поступает':waiting?'Ожидание свежей телеметрии VESC':'Телеметрия VESC недоступна';
|
||||
return <div className="rover-telemetry">{header&&<ObservationHeader targets={header} live={live} waiting={waiting} label={label}/>}{observation?.label&&<StatusBadge tone="warning" pulse={observation.pulse}>{observation.label}</StatusBadge>}{table.columns.length?<ComparisonTable density="compact" label="Телеметрия VESC" heading="VESC" {...table}/>:!observation?.label&&<Description>{state.fresh?'Получение показаний VESC…':'Нет свежих показаний VESC.'}</Description>}</div>;
|
||||
}
|
||||
|
||||
export function roverTelemetryMinimum(state:RoverState){return {width:Math.max(288,144+88*roverTelemetryTable(state).columns.length),height:280};}
|
||||
export function roverTelemetryMinimum(state:RoverState,compact=false){return {width:Math.max(288,144+88*roverTelemetryTable(state).columns.length),height:compact?172:280};}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import {useObservationView} from '../../core/observation/useObservationView';
|
||||
import {roverModelID} from '../../core/roverScene/model';
|
||||
import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
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 {roverDevEvent} from '../../core/fleet/roverDevEvents';
|
||||
import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput';
|
||||
import {useRoverTelemetryPolicy} from '../../core/fleet/useRoverTelemetryPolicy';
|
||||
import {bindRoverHoldInput,hasBlockingRoverOverlay} from '../../core/fleet/roverHoldInput';
|
||||
import type {RoverController} from '../../core/fleet/useRoverControl';
|
||||
import {roverObservationStatus,type RoverObservationStatus} from '../../core/fleet/roverObservation';
|
||||
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
|
||||
@@ -15,7 +17,11 @@ const labels:Record<string,string>={observing:'Наблюдение',preparing:'
|
||||
export function RoverView({vehicleID,name,controller:c,header,active,observation}:{vehicleID:string;name:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean;observation?:RoverObservationStatus}){
|
||||
const storage=`missioncore.rover-view.v1:${vehicleID}`;
|
||||
const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}});
|
||||
const presentation=useObservationView('rover-view',vehicleID,()=>({schema:'missioncore.rover-view/v1' as const,model:''}),async()=>{
|
||||
try{const raw=localStorage.getItem(storage);return raw?{schema:'missioncore.rover-view/v1' as const,model:roverSettings(JSON.parse(raw)).model}:null;}catch{return null;}
|
||||
});
|
||||
const [open,setOpen]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
|
||||
const telemetryPolicy=useRoverTelemetryPolicy(vehicleID,open);
|
||||
const [editing,setEditing]=useState(false);
|
||||
const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading');
|
||||
const stage=useRef<HTMLDivElement>(null),input=useRef<ReturnType<typeof bindRoverHoldInput>|null>(null);
|
||||
@@ -25,7 +31,7 @@ export function RoverView({vehicleID,name,controller:c,header,active,observation
|
||||
focusAfterArm.current=false;
|
||||
// Window restores its opener on close. Transfer input after that cleanup,
|
||||
// once only, without taking focus back from another window or dialog.
|
||||
const frame=requestAnimationFrame(()=>{if(active&&!document.hidden&&document.hasFocus()&&!document.querySelector('[role=dialog],[role=listbox]'))stage.current?.focus({preventScroll:true});});
|
||||
const frame=requestAnimationFrame(()=>{if(active&&!document.hidden&&document.hasFocus()&&!hasBlockingRoverOverlay(document))stage.current?.focus({preventScroll:true});});
|
||||
return()=>cancelAnimationFrame(frame);
|
||||
},[open,active]);
|
||||
const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();},[c.stop,c.setInputGuard]);
|
||||
@@ -57,10 +63,10 @@ export function RoverView({vehicleID,name,controller:c,header,active,observation
|
||||
onKeyDown={e=>{if(!c.ready&&(c.armed||c.pending||c.recovering)&&e.isTrusted&&['Space','Escape'].includes(e.code)){e.preventDefault();stop();}}}
|
||||
onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}>
|
||||
<EditorWorkspace editing={editing&&active} title={`Ровер / ${name}`} subtitle="Редактирование сцены" onBack={()=>setEditing(false)}>
|
||||
{settings.model===roverModelID?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
|
||||
{!presentation.ready?<LoadingRegion loading label="Загрузка настроек вида"/>:presentation.document.model===roverModelID?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
|
||||
<Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense>
|
||||
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
|
||||
</LoadingRegion>:<div className="rover-view__empty"><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">
|
||||
<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)}
|
||||
@@ -75,15 +81,18 @@ export function RoverView({vehicleID,name,controller:c,header,active,observation
|
||||
</EditorWorkspace>
|
||||
</div>
|
||||
<Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings">
|
||||
{presentation.error&&<><Description>{presentation.error}</Description><Button onClick={presentation.retry}>Повторить сохранение вида</Button></>}
|
||||
<Select label="Тип управления" value={settings.mode} options={[{value:'arcade',label:'Аркадный · W A S D'},{value:'tank',label:'Танковый · Q A / E D'}]} onChange={mode=>setSettings(v=>({...v,mode:mode as RoverMode}))}/>
|
||||
<Select label="3D-модель" value={settings.model} options={[{value:'',label:'Не выбрана'},{value:roverModelID,label:'DCD-006 · сборка v022'}]} onChange={model=>setSettings(v=>({...v,model}))}/>
|
||||
<Select label="3D-модель" disabled={!presentation.ready} value={presentation.document.model} options={[{value:'',label:'Не выбрана'},{value:roverModelID,label:'DCD-006 · сборка v022'}]} onChange={model=>presentation.update(v=>({...v,model}))}/>
|
||||
{duty?<TextField label="Газ, %" hint="1–100" description="Доля полного газа пульта. Фактическая скорость зависит от нагрузки." type="number" min={1} max={100} step={1} value={Number.isFinite(settings.throttlePercent)?settings.throttlePercent:''} onChange={e=>setSettings(v=>({...v,throttlePercent:roverNumberInput(e.target.value)}))}/>:
|
||||
<TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={Number.isFinite(settings.maxErpm)?settings.maxErpm:''} onChange={e=>setSettings(v=>({...v,maxErpm:roverNumberInput(e.target.value)}))}/>}
|
||||
<TextField label="Предел тока каждого мотора, А" description={currentDescription} type="number" min={.5} step={.5} value={Number.isFinite(settings.currentA)?settings.currentA:''} onChange={e=>setSettings(v=>({...v,currentA:roverNumberInput(e.target.value)}))}/>
|
||||
<TextField label="Максимальный возраст телеметрии, мс" hint="250–5000 · по умолчанию 1000" description="Управление останавливается, если возраст последних данных достигает этого порога. Применяется при следующем включении управления; срок действия команд не меняется." type="number" min={250} max={5000} step={50} disabled={!telemetryPolicy.ready} value={Number.isFinite(telemetryPolicy.value)?telemetryPolicy.value:''} onChange={e=>telemetryPolicy.setValue(roverNumberInput(e.target.value))} onBlur={()=>{if(telemetryPolicy.valid)void telemetryPolicy.save().catch(()=>{});}}/>
|
||||
{telemetryPolicy.error&&<Description>{telemetryPolicy.error}</Description>}
|
||||
{(availability||c.error)&&<StatusBadge tone="warning">{availability||c.error}</StatusBadge>}
|
||||
<p>Включайте управление на остановленном аппарате. Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. После восстановления связи для движения нажмите клавишу заново. Команда с пульта прекращает удалённое управление.</p>
|
||||
<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>
|
||||
<Description>Включайте управление на остановленном аппарате. Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. После восстановления связи для движения нажмите клавишу заново. Команда с пульта прекращает удалённое управление.</Description>
|
||||
<Button variant="primary" tone="neutral" disabled={!c.canArm||!!observing.label||!telemetryPolicy.ready||!telemetryPolicy.valid||!(Number.isFinite(settings.currentA)&&settings.currentA>=.5&&speedValid)} loading={c.pending}
|
||||
onClick={async()=>{try{const threshold=await telemetryPolicy.save();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',telemetry_stop_ms:threshold});const acquired=await c.arm(settings.currentA,duty?settings.throttlePercent:settings.maxErpm,duty?'duty':'rpm',threshold);if(acquired){focusAfterArm.current=true;setOpen(false);}}catch{/* Field retains the save error; no arm is sent. */}}}>Включить управление</Button>
|
||||
</div></Window>
|
||||
<ToastStack onDismiss={c.clearError} items={c.error?[{id:'rover-control-error',tone:'error',title:'Управление остановлено',description:c.error}]:[]}/>
|
||||
</>;
|
||||
|
||||
@@ -23,7 +23,7 @@ export function EnvironmentProfiles({document:doc,update,onError}:{document:Scen
|
||||
<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>Библиотека общая для сцен на этом компьютере. Профиль переносит окружение и поведение камеры; ракурс, материалы и компоновка сцены сохраняются.</Description>
|
||||
<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)}/>
|
||||
|
||||
@@ -44,7 +44,7 @@ export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,o
|
||||
const node=findSceneObject(root,selectedObject),targets=node?objectTargets(node):[];
|
||||
useObjectSelection(sceneApi,targets,editing&&modelPhase==='ready');
|
||||
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[]=[
|
||||
{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},
|
||||
@@ -66,7 +66,7 @@ export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,o
|
||||
{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>
|
||||
{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>
|
||||
</>}
|
||||
</>}/>
|
||||
|
||||
@@ -11,3 +11,5 @@
|
||||
.rover-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-3); }
|
||||
.rover-settings p { font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-secondary); }
|
||||
.rover-telemetry {height:100%; min-height:0; min-width:0; overflow:hidden; padding:var(--nodedc-space-3);}.rover-telemetry > .nodedc-comparison-table {max-height:100%;}
|
||||
|
||||
.rover-telemetry .nodedc-comparison-table table {font-size:var(--nodedc-font-size-xs);}
|
||||
|
||||
@@ -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);}
|
||||
.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 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 {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 { urbanExtent, type UrbanMap, type UrbanClassId } from "../../core/simulation/urbanMap";
|
||||
import { EditorCollisionLayer } from "./EditorCollisionLayer";
|
||||
import { waypointHit } from "../../core/simulation/waypointHit";
|
||||
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 { 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";
|
||||
@@ -37,6 +38,7 @@ export class AiEditorRuntime {
|
||||
private semanticProject: (()=>void)|null = null;
|
||||
private visualBounds:number[][]=[];
|
||||
private urbanVisible=false;
|
||||
private semanticMode=false;
|
||||
private experienceLayer: EditorUrbanMapLayer | null = null;
|
||||
private experiencePoints: number[][] = [];
|
||||
private onExperienceProject: (p: ScreenPoint[])=>void = ()=>undefined;
|
||||
@@ -130,11 +132,14 @@ export class AiEditorRuntime {
|
||||
this.scan.gsplat!.setWorkBufferModifier({ glsl: `
|
||||
uniform float editorClip;
|
||||
uniform float editorFloor;
|
||||
uniform float editorClipEnabled;
|
||||
uniform float editorFloorEnabled;
|
||||
void modifySplatCenter(inout vec3 center) {}
|
||||
void modifySplatRotationScale(vec3 a, vec3 b, inout vec4 rotation, inout vec3 scale) {}
|
||||
void modifySplatColor(vec3 center, inout vec4 color) {
|
||||
// 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);
|
||||
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) {
|
||||
this.urbanBounds=urbanExtent(document);
|
||||
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]};}
|
||||
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;}
|
||||
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;}
|
||||
@@ -202,7 +207,8 @@ export class AiEditorRuntime {
|
||||
return q[2]>=this.clipFloor&&q[2]<=this.clip?q:null;
|
||||
}
|
||||
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}) {
|
||||
this.surfacePicker.invalidate();this.controls.invalidateSurface();this.collisionVisible=collision;
|
||||
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;
|
||||
}
|
||||
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.clip = height; this.clipFloor = floor;
|
||||
this.collisionLayer?.setClip(height,floor);
|
||||
this.urbanLayer?.setClip(height,floor);this.experienceLayer?.setClip(height,floor);
|
||||
if (this.scan.gsplat) {
|
||||
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 1e9);
|
||||
this.scan.gsplat.setParameter("editorFloor", Number.isFinite(floor) ? floor : -1e9);
|
||||
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 0);
|
||||
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.dirty = true;
|
||||
@@ -248,7 +258,10 @@ export class AiEditorRuntime {
|
||||
private syncCamera() {
|
||||
const c=this.controls.camera;
|
||||
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;
|
||||
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"/>}>
|
||||
<SpatialPreview points={selected.points} label={selected.label}/>
|
||||
</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)} с
|
||||
{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}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import {getSimulationLayout,readSceneView,writeSceneView,useSimulationLayout} from "./useSimulationLayout";
|
||||
import {PlannerCameraTools} from "./PlannerCameraTools";
|
||||
import { heightSlice } from "../../core/heightSlice";
|
||||
import { sceneClipRange, sceneClipLabel } from "../../core/simulation/sceneClip";
|
||||
import { InfrastructureAnalysis } from "./InfrastructureAnalysis";
|
||||
import { PlannerLegend } from "./PlannerLegend";
|
||||
import { SemanticEditor } from "./SemanticEditor";
|
||||
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 { ScreenPoint } from "../../core/simulation/aiPolygon";
|
||||
import { editWaypoints, waypointEditing, waypointShortcut } from "../../core/simulation/waypointEditing";
|
||||
@@ -13,7 +13,7 @@ import { SimulationViewTools } from "./SimulationViewTools";
|
||||
import { usePlannerPreferences } from "./usePlannerPreferences";
|
||||
import { useEffect, useReducer, useRef, useState } from "react";
|
||||
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 { AiWaypoint, AiWorld } from "../../core/simulation/aiPolygon";
|
||||
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 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;
|
||||
actionsHost: HTMLElement | null; headerActions: React.ReactNode;
|
||||
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 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 [urbanMap,setUrbanMap]=useState<UrbanMap|null>(null);
|
||||
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 [urbanError,setUrbanError]=useState<string|null>(null);
|
||||
const [markers, setMarkers] = useState<EditorMarker[]>([]);
|
||||
const [mode,setMode] = useState<"view" | "add">("view");
|
||||
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 timer=window.setInterval(remember,1500);window.addEventListener("pagehide",remember);
|
||||
const abort=new AbortController();
|
||||
setUrbanMap(null);setUrbanError(null);
|
||||
setUrbanMap(null);
|
||||
setReady(false); setError(null); setClip(null);
|
||||
let view: AiEditorRuntime;
|
||||
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();
|
||||
void view.load().then(() => { if (active) {
|
||||
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);
|
||||
loaded=true;setReady(true);
|
||||
void loadUrbanMap(cache.world.world_id,cache.world.sha256!,abort.signal).then(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); });
|
||||
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]);
|
||||
@@ -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 });
|
||||
}, [points,cache,ready,sequence,planning]);
|
||||
useEffect(()=>{
|
||||
if(!semantic&&urbanMap){runtime.current?.setUrbanMap(urbanMap);runtime.current?.setUrbanClasses(urbanClasses);runtime.current?.showUrbanMap(urbanVisible);}
|
||||
},[semantic,urbanMap,urbanVisible,urbanClasses]);
|
||||
runtime.current?.setSemanticMode(semantic);
|
||||
},[semantic,ready]);
|
||||
useEffect(()=>{
|
||||
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);
|
||||
if(drag.current){edit({type:"cancel"});drag.current=null;runtime.current?.setNavigation(!busy);}
|
||||
},[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(()=>{runtime.current?.setPreferences(preferences);},[preferences,ready]);
|
||||
useEffect(()=>{runtime.current?.setSelected(selected);},[selected,ready]);
|
||||
@@ -123,12 +118,20 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
|
||||
: cache?.status === "ready" ? "Открываем локальную сцену" : "Готовим локальную копию сцены";
|
||||
const modeLabels={view:"Просмотр",semantic:"Семантика",planning:"Планирование миссии"};
|
||||
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;
|
||||
const header=<>{planning?<FieldFrame label="Выбор задания" labelPlacement="below" className="ai-polygon__task-field">{headerActions}</FieldFrame>:null}
|
||||
onMap={map=>{setUrbanMap(map);runtime.current?.setUrbanMap(map);runtime.current?.showUrbanMap(true);setError(null);}}/>:null;
|
||||
const header=<div className="ai-polygon__scene-actions">
|
||||
<div className="ai-polygon__context-actions">
|
||||
{planning?<FieldFrame label="Выбор задания" labelPlacement="below" className="ai-polygon__task-field">{headerActions}</FieldFrame>:null}
|
||||
{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>{infrastructure}{semantic?<span className="ai-polygon__semantic-actions" ref={setSemanticHeader}/>:null}{planning?routeActions:null}</>;
|
||||
</FieldFrame>
|
||||
<IconButton label="Назад к локациям" disabled={busy} onClick={onBack}><Icon name="chevron-left"/></IconButton>
|
||||
</div>
|
||||
</div>;
|
||||
return <div className="ai-polygon__stage" ref={host}>
|
||||
{expanded ? <>
|
||||
<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">
|
||||
<StatusBadge tone={ready ? "success" : "neutral"}>{ready ? modeLabels[sceneMode] : message}</StatusBadge>
|
||||
{planning?<p>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</p>: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}
|
||||
{planning?<Description>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</Description>:null}
|
||||
</div>
|
||||
<div className="ai-polygon__viewer">
|
||||
<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}
|
||||
</div>
|
||||
<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]}
|
||||
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>)}
|
||||
{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}
|
||||
</SegmentedGroup>
|
||||
{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}
|
||||
</g>:null)}
|
||||
</svg></div>
|
||||
{!semantic?<PlannerLegend map={urbanVisible?urbanMap:null} memory={memoryVisible}
|
||||
selected={urbanClasses} onChange={setUrbanClasses} disabled={busy}/>:null}
|
||||
{planning?<PlannerLegend map={null} memory={memoryVisible}
|
||||
selected={[]} onChange={()=>undefined} disabled={busy}/>: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="Срез"
|
||||
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)}
|
||||
onChange={(v)=>{const next=heightSlice(v,runtime.current!.height);setClip(v);runtime.current!.setClip(next.ceiling??Infinity,next.floor??-Infinity);}}/></div>
|
||||
{error?<div className="ai-route__tools"><p role="alert">{error}</p></div>:null}</>:null}
|
||||
{error && !ready ? <div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>setRetry(retry+1)}>Повторить загрузку</Button></div>:null}
|
||||
formatValue={(v)=>sceneClipLabel(v,runtime.current!.height)} formatLimit={(v)=>sceneClipLabel(v,runtime.current!.height)}
|
||||
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"><Description role="alert">{error}</Description></div>:null}</>: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>;
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
import { useState } from "react";
|
||||
import { useInfrastructureQueue } from "../../core/simulation/infrastructureAnalysis";
|
||||
import { Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow,
|
||||
StatusBadge, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
|
||||
import { Description, Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow,
|
||||
StatusBadge, ProgressBar, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
|
||||
import { updateAiWorld, type AiWorld } from "../../core/simulation/aiPolygon";
|
||||
import {useLocationImports} from "../../core/simulation/locationImports";
|
||||
|
||||
import {deleteLocation,useLocationDeletions} from "../../core/simulation/locationDeletions";
|
||||
import {SimulationOriginalDownload} from "./SimulationOriginalDownload";
|
||||
|
||||
export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused, onOpen, onPlan, canPlan, onChanged}: {
|
||||
worlds: AiWorld[]; removedWorlds: AiWorld[]; activeWorldId?: string; paused: boolean;
|
||||
onOpen: (world: AiWorld) => void; onPlan: (world: AiWorld) => void; canPlan: boolean; onChanged: () => Promise<void>;
|
||||
}) {
|
||||
const queue=useInfrastructureQueue();
|
||||
const deletions=useLocationDeletions(onChanged);
|
||||
const imports=useLocationImports();
|
||||
const uploadingWorlds=new Set(imports.map(task=>task.project?.projectId.replace("sim-","aiworld-")));
|
||||
const [editing, setEditing] = useState<AiWorld | null>(null);
|
||||
const [name, setName] = useState("");
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
@@ -27,16 +34,17 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
|
||||
} finally { setBusy(null); }
|
||||
};
|
||||
return <>
|
||||
<ResourceList>{worlds.map(world => {const queued=queue.jobs.find(j=>j.world_id===world.world_id);return <li key={world.world_id}>
|
||||
<ResourceList>{worlds.filter(world=>!uploadingWorlds.has(world.world_id)).map(world => {const queued=queue.jobs.find(j=>j.world_id===world.world_id);const deletion=deletions.find(d=>d.project_id===world.local_scene?.project_id);return <li key={world.world_id}>
|
||||
<ResourceRow title={world.name} icon={<Icon name="globe"/>}
|
||||
status={activeWorldId === world.world_id ? <StatusBadge tone="neutral">
|
||||
{paused ? "На паузе" : "Сцена открыта"}</StatusBadge> : queued ? <StatusBadge tone={queue.unavailable?"neutral":"warning"}>
|
||||
{queue.unavailable?"Нет обновлений очереди":queued.cancel_requested?"Отмена расчёта":queued.status==="queued"?`В очереди · №${queued.queue?.position??"—"}`:queued.status==="running"?"Расчёт инфраструктуры":"Освобождение Worker"}</StatusBadge> : undefined}
|
||||
actions={<>
|
||||
actions={deletion?<div className="simulation-imports__progress" role="status"><ProgressBar label="Удаление локации"/><Description>{deletion.error??"Удаление локации"}</Description></div>:<>
|
||||
<IconButton label={world.status === "uploading" ? `Продолжить импорт ${world.name}` : `Открыть ${world.name}`}
|
||||
onClick={() => onOpen(world)}><Icon name={world.status === "uploading" ? "upload" : "eye"}/></IconButton>
|
||||
{canPlan&&world.status!=="uploading"&&world.settings.prepared?<IconButton label={`Подготовить маршрут · ${world.name}`}
|
||||
onClick={() => onPlan(world)}><Icon name="plan"/></IconButton>:null}
|
||||
{world.status!=="uploading"?<SimulationOriginalDownload worldId={world.world_id} name={world.name}/>:null}
|
||||
<IconButton label={`Настройки ${world.name}`} onClick={() => {
|
||||
setEditing(world); setName(world.name); setConfirming(false); setError(null);
|
||||
}}><Icon name="settings"/></IconButton>
|
||||
@@ -44,7 +52,7 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
|
||||
</li>;})}</ResourceList>
|
||||
{removedWorlds.length ? <>
|
||||
<Button aria-expanded={showRemoved} onClick={() => setShowRemoved(!showRemoved)}>
|
||||
Удалённые локации · {removedWorlds.length}</Button>
|
||||
Скрытые локации · {removedWorlds.length}</Button>
|
||||
{showRemoved ? <ResourceList>{removedWorlds.map(world => <li key={world.world_id}>
|
||||
<ResourceRow title={world.name} icon={<Icon name="globe"/>} actions={
|
||||
<Button disabled={busy !== null} loading={busy === world.world_id}
|
||||
@@ -55,19 +63,25 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
|
||||
onClose={() => {if (!busy) setEditing(null);}}
|
||||
footer={<WindowFooterActions>
|
||||
<Button icon={<Icon name="trash"/>} disabled={!!busy || editing?.world_id === activeWorldId}
|
||||
onClick={() => setConfirming(true)}>Удалить локацию</Button>
|
||||
onClick={() => setConfirming(true)}>{editing?.local_scene?"Удалить локацию":"Скрыть локацию"}</Button>
|
||||
<Button variant="primary" loading={!!busy} disabled={!name.trim() || name.trim() === editing?.name}
|
||||
onClick={() => {if (editing) void update(editing, {display_name:name.trim()});}}>Сохранить</Button>
|
||||
</WindowFooterActions>}>
|
||||
<TextField label="Название локации" value={name} maxLength={120} disabled={!!busy}
|
||||
onChange={event => setName(event.target.value)}/>
|
||||
{editing?.world_id === activeWorldId ? <p>Удаление станет доступно после завершения симуляции.</p> : null}
|
||||
{editing?.world_id === activeWorldId ? <Description>Удаление станет доступно после завершения симуляции.</Description> : null}
|
||||
</Window>
|
||||
<ConfirmationModal open={!!editing && confirming} title="Удалить локацию?" danger
|
||||
description={<>«{editing?.name}» исчезнет из доступных локаций. Исходный скан, разметка и задания сохранятся.
|
||||
Восстановить её можно в списке удалённых локаций.</>}
|
||||
confirmLabel="Удалить" pendingLabel="Удаляем" onClose={() => {if (!busy) setConfirming(false);}}
|
||||
onConfirm={async () => {if (editing) await update(editing, {removed:true});}}/>
|
||||
<ConfirmationModal open={!!editing && confirming} title={editing?.local_scene?"Удалить локацию полностью?":"Скрыть локацию?"} danger
|
||||
description={editing?.local_scene?<>«{editing.name}»: обработка будет остановлена, исходные файлы и результаты удалены на Worker и на этом компьютере. Общие файлы других локаций сохранятся. Отменить удаление нельзя.</>:<>«{editing?.name}» будет скрыта из каталога. Эта старая локация хранит данные в отдельном контуре симулятора; скрытие не удаляет файлы. Восстановление доступно в списке скрытых локаций.</>}
|
||||
confirmLabel={editing?.local_scene?"Удалить полностью":"Скрыть"} pendingLabel="Удаляем" onClose={() => {if (!busy) setConfirming(false);}}
|
||||
onConfirm={async () => {
|
||||
if(!editing)return;
|
||||
if(!editing.local_scene){await update(editing,{removed:true});return;}
|
||||
setBusy(editing.world_id);setError(null);
|
||||
try{await deleteLocation(editing.local_scene.project_id);setConfirming(false);setEditing(null);await onChanged();}
|
||||
catch(caught){setError(caught instanceof Error?caught.message:"Не удалось начать удаление.");}
|
||||
finally{setBusy(null);}
|
||||
}}/>
|
||||
{error ? <ToastStack items={[{id:"location-settings",tone:"error",title:"Не удалось изменить локацию",description:error}]}
|
||||
onDismiss={() => setError(null)}/> : null}
|
||||
</>;
|
||||
|
||||
@@ -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}: {
|
||||
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()}
|
||||
onClick={onSave}>{launch?"Сохранить и запустить":"Сохранить"}</Button></WindowFooterActions>}>
|
||||
<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)}/>
|
||||
<p>Сохраняются текущие точки маршрута и выбранный ровер. Задание появится в списке над сценой.</p>
|
||||
<Description>Сохраняются текущие точки маршрута и выбранный ровер. Задание появится в списке над сценой.</Description>
|
||||
</div>
|
||||
</Window>;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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 { 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 || !draft?.can_undo} onClick={() => send({ action: "undo" })}>Отменить</Button>
|
||||
<Button disabled={!cameraReady} onClick={() => send({ action: "home" })}>К началу маршрута</Button>
|
||||
<p>Мышь — взгляд · Shift + мышь — сдвиг · Колесо — приближение · WASD / стрелки — полёт · Q / E — вниз / вверх · Shift — быстрее</p>
|
||||
{error || draft?.error ? <p role="alert">{error ?? draft?.error}</p> : null}
|
||||
<Description>Мышь — взгляд · Shift + мышь — сдвиг · Колесо — приближение · WASD / стрелки — полёт · Q / E — вниз / вверх · Shift — быстрее</Description>
|
||||
{error || draft?.error ? <Description role="alert">{error ?? draft?.error}</Description> : null}
|
||||
</div> : null}
|
||||
</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 { 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")}`,
|
||||
icon:<Icon name="trash"/>,disabled:removing!==null || !["completed","stopped","failed"].includes(run.state),
|
||||
onAction:()=>onRemove(run)},
|
||||
}))}/> : <p>В этой локации ещё нет прогонов.</p>}
|
||||
}))}/> : <Description>В этой локации ещё нет прогонов.</Description>}
|
||||
</AiSessionSection>;
|
||||
}
|
||||
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;
|
||||
return <div className="ai-polygon__form ai-polygon__report">
|
||||
<StatusBadge tone={report.mission_outcome === "goal-reached" ? "success" : "neutral"}>
|
||||
@@ -60,8 +60,8 @@ function RunDetails({run}:{run:AiRun}) {
|
||||
<h3>Остановки после начала движения</h3>
|
||||
{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>
|
||||
</div>)}</dl> : <p>Переходов от движения к нулевой команде не записано.</p>}
|
||||
<p>Исходные кадры и телеметрия хранятся на Worker. Архив: {report.evidence_files} файлов, {(report.evidence_bytes / 1024 ** 2).toFixed(1)} МБ.</p>
|
||||
</div>)}</dl> : <Description>Переходов от движения к нулевой команде не записано.</Description>}
|
||||
<Description>Исходные кадры и телеметрия хранятся на Worker. Архив: {report.evidence_files} файлов, {(report.evidence_bytes / 1024 ** 2).toFixed(1)} МБ.</Description>
|
||||
<dl className="ai-polygon__report-identities">
|
||||
<div><dt>Прогон</dt><dd>{report.run_id}</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";
|
||||
|
||||
const STATES: Record<AiRun["state"], string> = {
|
||||
@@ -51,6 +51,6 @@ export function AiRunView({ run }: { run: AiRun }) {
|
||||
<dt>{label}</dt><dd>{value}</dd>
|
||||
</div>)}
|
||||
</dl>
|
||||
{run.state === "failed" && run.message ? <p>{run.message}</p> : null}
|
||||
{run.state === "failed" && run.message ? <Description>{run.message}</Description> : null}
|
||||
</section>;
|
||||
}
|
||||
|
||||
@@ -2,13 +2,16 @@ import { useEffect, useRef, useState } from "react";
|
||||
import { Button, Icon, ProgressBar, TextField, ToastStack, Window } from "@nodedc/ui-react";
|
||||
import { importAiWorld, type AiSource, type AiWorld } from "../../core/simulation/aiPolygon";
|
||||
|
||||
export function AiWorldImport({ source, resume, onClose, onImported }: {
|
||||
source: AiSource | null; resume?: AiWorld; onClose: () => void; onImported: (world: AiWorld) => void;
|
||||
import {locationImports} from "../../core/simulation/locationImports";
|
||||
import {classifySimulationSource} from "../../core/simulation/sourceFiles";
|
||||
|
||||
export function AiWorldImport({ source, resume, initialFile, onClose, onImported }: {
|
||||
source: AiSource | null; resume?: AiWorld; initialFile?: File; onClose: () => void; onImported: (world: AiWorld) => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<AiSource>(source ?? {
|
||||
name: "", author: "", license: "", source_url: "",
|
||||
name: initialFile?.name.replace(/\.ply$/i, "") ?? "", author: "", license: "", source_url: "",
|
||||
});
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [file, setFile] = useState<File | null>(initialFile ?? null);
|
||||
const [pending, setPending] = useState<AiWorld | undefined>(resume);
|
||||
const [progress, setProgress] = useState(0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -18,6 +21,10 @@ export function AiWorldImport({ source, resume, onClose, onImported }: {
|
||||
useEffect(() => () => controller.current?.abort(), []);
|
||||
const submit = async () => {
|
||||
if (!file || busy) return;
|
||||
if (!resume) {
|
||||
locationImports.enqueue(draft.name.trim(), Promise.resolve().then(()=>({...classifySimulationSource([{file,logicalPath:file.name}]), attribution:{author:draft.author,license:draft.license,source_url:draft.source_url}})));
|
||||
onClose(); return;
|
||||
}
|
||||
setBusy(true); setError(null);
|
||||
const abort = new AbortController(); controller.current = abort;
|
||||
try { onImported(await importAiWorld(file, draft, setProgress, abort.signal, pending, setPending)); }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useRef, useState, type ReactNode } from "react";
|
||||
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 { WorkerVideo, type WorkerVideoState } from "./WorkerVideo";
|
||||
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="Управление камерой симуляции">
|
||||
<div className="ai-polygon__stream-picture">
|
||||
{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")}
|
||||
label={run?.state === "disconnected" ? "Восстанавливаем связь с Worker" : !connectable ? "Подготавливаем сцену на Worker" : "Подключаем видео"}>
|
||||
<div className="ai-polygon__video" inert>
|
||||
@@ -69,9 +69,9 @@ export function AiWorldStream({ world, run, onBack, onChange, controls, headerAc
|
||||
</div>
|
||||
</LoadingRegion>
|
||||
{!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">
|
||||
<p>Не удалось получить видео после повторных подключений. Если сцена открыта в другой вкладке, закройте её и подключитесь снова.</p>
|
||||
<Description>Не удалось получить видео после повторных подключений. Если сцена открыта в другой вкладке, закройте её и подключитесь снова.</Description>
|
||||
<Button onClick={() => {setState("connecting");setRevision((value) => value + 1);}}>Подключить видео</Button>
|
||||
</div> : null}
|
||||
</div>
|
||||
|
||||
@@ -27,6 +27,7 @@ export class EditorCamera {
|
||||
private right = new Vector3();
|
||||
private delta = new Vector3();
|
||||
sceneCenter = new Vector3();
|
||||
get focusDepth(){return navigationDepth(this.camera,this.lastAnchor??this.sceneCenter);}
|
||||
pick: ((x:number,y:number)=>number[]|null)|null = null;
|
||||
pickSurface: ((x:number,y:number)=>Promise<number[]|null>)|null = null;
|
||||
constructor(private surface: HTMLElement, private canvas: HTMLCanvasElement) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { SimulationViewTools } from "./SimulationViewTools";
|
||||
import { usePlannerPreferences } from "./usePlannerPreferences";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
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 { RoverSettings } from "../../core/simulation/roverSettings";
|
||||
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}`} />
|
||||
{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}
|
||||
{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>;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {useSimulationLayout} from "./useSimulationLayout";
|
||||
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 { loadExperience, attemptLabel, experienceMap, type SpatialExperience } from "../../core/simulation/spatialExperience";
|
||||
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
|
||||
@@ -33,20 +33,20 @@ export function PlannerExperience({worldId,worldSha,runtime,viewport,onVisibilit
|
||||
aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}>Память</SegmentedButton>}>
|
||||
<div className="ai-polygon__layer-options">
|
||||
<strong>Память локации</strong>
|
||||
<p>Сохраняет посещённые места и попытки проезда между заездами. Новый заезд с той же конфигурацией ровера продолжает эту историю.</p>
|
||||
{error?<p role="alert">{error}</p>:memory?<>
|
||||
<p>Посещено участков: {memory.visits.length}. Попыток проезда: {memory.attempts.length}, из них позже пройдено: {memory.attempts.filter(a=>a.status==="revisited-successfully").length}.</p>
|
||||
<Description>Сохраняет посещённые места и попытки проезда между заездами. Новый заезд с той же конфигурацией ровера продолжает эту историю.</Description>
|
||||
{error?<Description role="alert">{error}</Description>:memory?<>
|
||||
<Description>Посещено участков: {memory.visits.length}. Попыток проезда: {memory.attempts.length}, из них позже пройдено: {memory.attempts.filter(a=>a.status==="revisited-successfully").length}.</Description>
|
||||
<Checker label="Показывать на карте" checked={visible} onChange={setVisible}/>
|
||||
</>:<p>Сохранённых проездов пока нет. Память появится после движения ровера.</p>}
|
||||
<p>Прежние попытки помогают выбрать другой подход. Возможность проезда всегда проверяется заново по текущим данным.</p>
|
||||
<p>Показана накопленная память конфигурации ровера из последнего заезда. Для другой версии локации или конфигурации сохраняется отдельная память.</p>
|
||||
</>:<Description>Сохранённых проездов пока нет. Память появится после движения ровера.</Description>}
|
||||
<Description>Прежние попытки помогают выбрать другой подход. Возможность проезда всегда проверяется заново по текущим данным.</Description>
|
||||
<Description>Показана накопленная память конфигурации ровера из последнего заезда. Для другой версии локации или конфигурации сохраняется отдельная память.</Description>
|
||||
</div>
|
||||
</Dropdown>
|
||||
{visible&&memory?createPortal(<svg className="ai-local-editor__markers" viewBox="0 0 1280 720" preserveAspectRatio="none" aria-label="Память проездов">
|
||||
{memory.attempts.map((attempt,i)=>{const p=projected[i];if(!p)return null;
|
||||
const label=attemptLabel(attempt),color=URBAN_COLORS[attempt.status==="unresolved"?"attempt":"revisited"];
|
||||
return <g key={attempt.id} role="img" aria-label={label} tabIndex={0} style={{pointerEvents:"auto"}}>
|
||||
<title>{label}</title><circle cx={p[0]*1280} cy={p[1]*720} r="7" fill={`rgb(${color.join(",")})`}/>
|
||||
return <g key={attempt.id} role="img" data-nodedc-tooltip={label} aria-label={label} tabIndex={0} style={{pointerEvents:"auto"}}>
|
||||
<circle cx={p[0]*1280} cy={p[1]*720} r="7" fill={`rgb(${color.join(",")})`}/>
|
||||
</g>;
|
||||
})}
|
||||
</svg>,viewport):null}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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 {PlannerCubeSettings} from "./PlannerCubeSettings";
|
||||
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>
|
||||
</> : <>
|
||||
<strong>Сдвиг камеры</strong>
|
||||
<p>Расстояние до поверхности под курсором. Чувствительность плавно меняется между двумя границами.</p>
|
||||
<Description>Расстояние до поверхности под курсором. Чувствительность плавно меняется между двумя границами.</Description>
|
||||
{range("navigation","nearDistance","Ближнее расстояние",.5,50,.5,"м")}
|
||||
{range("navigation","nearPan","Чувствительность вблизи",.1,5,.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>
|
||||
{range("navigation","zoom","Скорость зума",.1,3,.1,"×")}
|
||||
<strong>Центр вращения</strong>
|
||||
<p>Шарик появляется в точке нажатия на время вращения.</p>
|
||||
<Description>Шарик появляется в точке нажатия на время вращения.</Description>
|
||||
{range("navigation","centroidPixels","Размер центра на экране",6,64,1,"px")}
|
||||
<ControlRow label="Цвет центра"><ColorField label="Цвет центра" value={value.navigation.centroidColor} onChange={(v)=>set("navigation","centroidColor",v)}/></ControlRow>
|
||||
{range("navigation","centroidOpacity","Непрозрачность центра",.1,1,.05,"")}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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 { 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("payload_mass_kg","Дополнительный груз, кг",0,500,1)}
|
||||
{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>
|
||||
<p>Груз расположен по центру ровера. Масса и высота влияют на центр тяжести и инерцию; мощность моторов остаётся прежней.</p>
|
||||
{manual?<p>В ручном режиме учитываются скорость и общая масса. Высота груза применяется в заезде на Worker.</p>:null}
|
||||
<p>Изменения применяются к следующему заезду. Его результат сохраняет использованные настройки.</p>
|
||||
{!valid?<p role="status">Допустимо: конечная скорость от 0.05 м/с, масса 10–1000 кг, груз 0–500 кг, высота 0.1–3 м.</p>:null}
|
||||
<Description>Общая масса: {Number.isFinite(draft.base_mass_kg+draft.payload_mass_kg)?draft.base_mass_kg+draft.payload_mass_kg:"—"} кг.</Description>
|
||||
<Description>Груз расположен по центру ровера. Масса и высота влияют на центр тяжести и инерцию; мощность моторов остаётся прежней.</Description>
|
||||
{manual?<Description>В ручном режиме учитываются скорость и общая масса. Высота груза применяется в заезде на Worker.</Description>:null}
|
||||
<Description>Изменения применяются к следующему заезду. Его результат сохраняет использованные настройки.</Description>
|
||||
{!valid?<Description role="status">Допустимо: конечная скорость от 0.05 м/с, масса 10–1000 кг, груз 0–500 кг, высота 0.1–3 м.</Description>:null}
|
||||
</div>
|
||||
</Window>;
|
||||
}
|
||||
|
||||
@@ -38,21 +38,20 @@ export function SemanticEditOverlay(props:SemanticOverlayProps) {
|
||||
{props.editing&&!props.blocked&&base&&g?<g aria-label="Пивот перемещения">
|
||||
{(["x","y","z"] as const).map(axis=>{const end=g[axis];if(!end)return null;const p=[end[0]*rect.width,end[1]*rect.height],d=Math.hypot(p[0]-base[0],p[1]-base[1]);if(d<12)return null;
|
||||
const ux=(p[0]-base[0])/d,uy=(p[1]-base[1])/d;
|
||||
return <g key={axis} data-semantic-axis={axis} style={{pointerEvents:"stroke",cursor:"move"}}>
|
||||
<title>{`Переместить по ${axis.toUpperCase()}`}</title>
|
||||
return <g key={axis} data-nodedc-tooltip={`Переместить по ${axis.toUpperCase()}`} aria-label={`Переместить по ${axis.toUpperCase()}`} data-semantic-axis={axis} style={{pointerEvents:"stroke",cursor:"move"}}>
|
||||
<line x1={base[0]} y1={base[1]} x2={p[0]} y2={p[1]} stroke="transparent" strokeWidth={18}/>
|
||||
<line x1={base[0]} y1={base[1]} x2={p[0]} y2={p[1]} stroke={g.colors[axis]} strokeWidth={3}/>
|
||||
<path d={`M${p[0]},${p[1]} L${p[0]-ux*12-uy*5},${p[1]-uy*12+ux*5} L${p[0]-ux*12+uy*5},${p[1]-uy*12-ux*5} Z`} fill={g.colors[axis]}/>
|
||||
<text x={p[0]+7} y={p[1]-7} fill={g.colors[axis]} fontSize={12}>{axis.toUpperCase()}</text>
|
||||
</g>;
|
||||
})}
|
||||
<rect data-semantic-axis={props.axis} x={base[0]-7} y={base[1]-7} width={14} height={14} fill={color} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}><title>{`Переместить: ${props.axis.toUpperCase()}`}</title></rect>
|
||||
{chosen[0]&&(isRigidMarking(chosen[0])||selected?.object)?<circle data-semantic-axis="rotate" cx={base[0]} cy={base[1]} r={48} fill="none" stroke={color} strokeWidth={3} style={{pointerEvents:"stroke",cursor:"grab"}}><title>Повернуть элемент в плоскости</title></circle>:null}
|
||||
<rect data-nodedc-tooltip={`Переместить: ${props.axis.toUpperCase()}`} aria-label={`Переместить: ${props.axis.toUpperCase()}`} data-semantic-axis={props.axis} x={base[0]-7} y={base[1]-7} width={14} height={14} fill={color} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}/>
|
||||
{chosen[0]&&(isRigidMarking(chosen[0])||selected?.object)?<circle data-nodedc-tooltip="Повернуть элемент в плоскости" aria-label="Повернуть элемент в плоскости" data-semantic-axis="rotate" cx={base[0]} cy={base[1]} r={48} fill="none" stroke={color} strokeWidth={3} style={{pointerEvents:"stroke",cursor:"grab"}}/>:null}
|
||||
</g>:null}
|
||||
{props.editing&&node&&props.selection.length===1?(["incoming","outgoing"] as const).map(key=>{
|
||||
const a=project(node.point),b=project(curveControlPoint(node,key,handleScale));
|
||||
if(!a||!b||!node[key].some(Boolean))return null;
|
||||
return <g key={key} data-semantic-handle-scale={handleScale}><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={4}/><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke={color} strokeWidth={1.5}/><circle data-semantic-handle={key} cx={b[0]} cy={b[1]} r={6} fill="var(--nodedc-text-primary)" stroke={color} strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}><title>Ручка кривой</title></circle></g>;
|
||||
return <g key={key} data-semantic-handle-scale={handleScale}><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={4}/><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke={color} strokeWidth={1.5}/><circle data-nodedc-tooltip="Ручка кривой" aria-label="Ручка кривой" data-semantic-handle={key} cx={b[0]} cy={b[1]} r={6} fill="var(--nodedc-text-primary)" stroke={color} strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}/></g>;
|
||||
}):null}
|
||||
</svg>,viewport);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {
|
||||
import { Description,
|
||||
ActivityIndicator,
|
||||
Button,
|
||||
Icon,
|
||||
@@ -85,7 +85,7 @@ export function SimulationCatalog({
|
||||
<div className="simulation-catalog__empty">
|
||||
<span><Icon name="globe" size={20} /></span>
|
||||
<strong>Перетащите архивы в это окно</strong>
|
||||
<p>Каждый ZIP, RAR или 7z сразу станет отдельным проектом и встанет в очередь.</p>
|
||||
<Description>Каждый ZIP, RAR или 7z сразу станет отдельным проектом и встанет в очередь.</Description>
|
||||
<Button variant="primary" icon={<Icon name="plus" size={16} />} onClick={onCreate}>
|
||||
Новый проект
|
||||
</Button>
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import {useCallback, useEffect, useState} from "react";
|
||||
import {ConfirmationModal, Description, Icon, IconButton, ProgressBar, ResourceList, ResourceRow, StatusBadge} from "@nodedc/ui-react";
|
||||
import {locationImports, useLocationImports} from "../../core/simulation/locationImports";
|
||||
import {deleteLocation, useLocationDeletions} from "../../core/simulation/locationDeletions";
|
||||
import {estimateSimulationProcessing, fetchSimulationProjects, retrySimulationProject, type SimulationProject} from "../../core/simulation/projects";
|
||||
|
||||
type DeletionTarget={name:string;taskId?:string;projectId?:string};
|
||||
|
||||
/** Pending source rows stay visible before the world is admitted to the location catalog. */
|
||||
export function SimulationImports({worldIds}:{worldIds:string[]}) {
|
||||
const tasks=useLocationImports();
|
||||
const [projects,setProjects]=useState<SimulationProject[]>([]), [error,setError]=useState<string|null>(null);
|
||||
const [target,setTarget]=useState<DeletionTarget|null>(null);
|
||||
const refresh=useCallback(async()=>{
|
||||
const started=performance.now(),rows=await fetchSimulationProjects();
|
||||
setProjects(rows);locationImports.reconcile(rows.map(row=>row.projectId),started);
|
||||
},[]);
|
||||
const deletions=useLocationDeletions(refresh);
|
||||
useEffect(()=>{
|
||||
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
|
||||
const poll=async()=>{
|
||||
try {const started=performance.now(),rows=await fetchSimulationProjects(abort.signal);
|
||||
if(!abort.signal.aborted){setProjects(rows);locationImports.reconcile(rows.map(row=>row.projectId),started);setError(null);}}
|
||||
catch(caught){if(!abort.signal.aborted)setError(caught instanceof Error?caught.message:"Нет обновлений импорта.");}
|
||||
if(!abort.signal.aborted)timer=setTimeout(()=>void poll(),2000);
|
||||
};
|
||||
void poll();return()=>{abort.abort();clearTimeout(timer);};
|
||||
},[]);
|
||||
useEffect(()=>{
|
||||
for(const task of tasks)if(task.phase==="submitted" && worldIds.includes(task.project?.projectId.replace("sim-","aiworld-")??""))locationImports.forget(task.id);
|
||||
},[tasks,worldIds]);
|
||||
const taskProjects=new Set(tasks.map(task=>task.project?.projectId));
|
||||
const deletingIds=new Set(deletions.map(row=>row.project_id));
|
||||
const pending=projects.filter(project=>project.status!=="ready"&&!taskProjects.has(project.projectId)&&!deletingIds.has(project.projectId));
|
||||
const pendingDeletions=deletions.filter(row=>!taskProjects.has(row.project_id)&&!worldIds.includes(row.project_id.replace("sim-","aiworld-")));
|
||||
if(!tasks.length&&!pending.length&&!pendingDeletions.length&&!error)return null;
|
||||
const retry=async(project:SimulationProject)=>{
|
||||
try {await retrySimulationProject(project.projectId);setProjects(await fetchSimulationProjects());}
|
||||
catch(caught){setError(caught instanceof Error?caught.message:"Не удалось продолжить обработку.");}
|
||||
};
|
||||
const trash=(item:DeletionTarget)=><IconButton label={"Удалить импорт "+item.name} onClick={()=>setTarget(item)}><Icon name="trash"/></IconButton>;
|
||||
return <section className="simulation-imports" aria-label="Импорт локаций">
|
||||
<ResourceList>
|
||||
{tasks.map(task=>{
|
||||
const project=projects.find(row=>row.projectId===task.project?.projectId)??task.project;
|
||||
const serverPhase=task.phase==="submitted"&&project?projectProgress(project):null;
|
||||
const failure=task.error??serverPhase?.error;
|
||||
const label=failure??(task.phase==="deleting"?(deletions.find(row=>row.project_id===task.project?.projectId)?.error??"Удаление импорта"):task.phase==="checking"?"Проверка файла":task.phase==="waiting"?"В очереди загрузки":task.phase==="uploading"?
|
||||
(task.progress===1?"Проверка и сохранение исходного файла":"Загрузка"):serverPhase?.label??"Обновление каталога");
|
||||
return <li key={task.id}><ImportRow name={task.name} label={label} value={task.deleteRequested?undefined:serverPhase?.value??task.progress} failed={!!failure}
|
||||
actions={task.phase==="deleting"?undefined:<>
|
||||
{failure&&!task.deleteRequested?(locationImports.canRetry(task.id)?
|
||||
<IconButton label={"Повторить импорт "+task.name} onClick={()=>locationImports.retry(task.id)}><Icon name="refresh"/></IconButton>:
|
||||
project?<IconButton label={"Повторить обработку "+task.name} onClick={()=>void retry(project)}><Icon name="refresh"/></IconButton>:null):null}
|
||||
{failure&&!project&&!task.deleteRequested?<IconButton label={"Убрать ошибку "+task.name} onClick={()=>locationImports.forget(task.id)}><Icon name="close"/></IconButton>:
|
||||
trash({name:task.name,taskId:task.id})}
|
||||
</>}/></li>;
|
||||
})}
|
||||
{pending.map(project=>{const progress=projectProgress(project);return <li key={project.projectId}>
|
||||
<ImportRow name={project.name} {...progress} failed={!!progress.error} label={progress.error??progress.label}
|
||||
actions={<>{project.status==="failed"?<IconButton label={`Повторить обработку ${project.name}`} onClick={()=>void retry(project)}><Icon name="refresh"/></IconButton>:null}{trash({name:project.name,projectId:project.projectId})}</>}/>
|
||||
</li>;})}
|
||||
{pendingDeletions.map(row=><li key={row.project_id}><ImportRow name={row.name} label={row.error??"Удаление локации"} failed={false}/></li>)}
|
||||
</ResourceList>
|
||||
{error?<Description role="alert">{error}</Description>:null}
|
||||
<ConfirmationModal open={!!target} title="Удалить импорт полностью?" danger confirmLabel="Удалить полностью" pendingLabel="Останавливаем импорт"
|
||||
description={<>«{target?.name}»: загрузка и обработка будут остановлены. Исходные файлы и результаты этой локации будут удалены на Worker и на этом компьютере. Общие файлы других локаций сохранятся.</>}
|
||||
onClose={()=>setTarget(null)} onConfirm={async()=>{
|
||||
if(!target)return;
|
||||
try {
|
||||
if(target.taskId)await locationImports.remove(target.taskId);
|
||||
else if(target.projectId)await deleteLocation(target.projectId);
|
||||
setTarget(null);await refresh();
|
||||
} catch(caught){setError(caught instanceof Error?caught.message:"Не удалось начать удаление.");}
|
||||
}}/>
|
||||
</section>;
|
||||
}
|
||||
|
||||
function ImportRow({name,label,value,failed,actions}:{name:string;label:string;value?:number;failed:boolean;actions?:React.ReactNode}){
|
||||
return <ResourceRow title={name} icon={<Icon name="globe"/>}
|
||||
status={<StatusBadge tone={failed?"danger":"warning"} pulse={!failed}>{failed?"Ошибка импорта":"Импорт"}</StatusBadge>}
|
||||
actions={<><div className="simulation-imports__progress" role={failed?"alert":"status"}>
|
||||
{!failed?<ProgressBar label={label} value={value}/>:null}<Description>{label}{!failed&&value!==undefined?` · ${Math.floor(value*100)}%`:""}</Description>
|
||||
</div>{actions}</>}/>;
|
||||
}
|
||||
|
||||
function projectProgress(project:SimulationProject):{label:string;value?:number;error?:string}{
|
||||
if(project.status==="failed")return {label:"Ошибка обработки",error:project.error??"Обработка не завершена."};
|
||||
if(project.status==="uploading")return {label:"Загрузка исходника не завершена",value:project.source.uploadedByteLength/project.source.totalByteLength};
|
||||
if(project.status==="queued")return {label:"Ожидание обработки"};
|
||||
if(project.status==="ready")return {label:"Готово",value:1};
|
||||
if(project.status==="importing")return {label:"Получение готовой локации"};
|
||||
const label:Record<string,string>={verifying_source:"Проверка исходника",inspecting:"Анализ локации",building_preview:"Конвертация превью",building_streamed_sog:"Конвертация уровней детализации",building_collision:"Подготовка коллизий"};
|
||||
const estimate=estimateSimulationProcessing(project);
|
||||
const eta=estimate?.estimatedSecondsRemaining;
|
||||
return {label:(label[project.provider.state??""]??"Обработка локации")+(eta?` · осталось ≈ ${Math.max(1,Math.ceil(eta/60))} мин`:""),value:estimate?estimate.percent/100:undefined};
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import {useEffect,useRef,useState,type ReactNode} from 'react';
|
||||
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 {useObservationPresets} from '../../core/fleet/useObservationPresets';
|
||||
import {observationArrangements,retainDormantObservationTree} from '../../core/fleet/observationPresets';
|
||||
@@ -48,7 +48,7 @@ export function SimulationObservationDeck({video,videoActions,toolbar,preview}:{
|
||||
</div></ObservationPanelHeader>
|
||||
<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))}
|
||||
</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}/>}
|
||||
{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}/>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import {useState} from "react";
|
||||
import {Button, Description, Icon, IconButton, ToastStack, Window} from "@nodedc/ui-react";
|
||||
import {polygonRequest} from "../../core/simulation/aiPolygon";
|
||||
|
||||
type OriginalFile={name:string;byte_length:number;url:string};
|
||||
export function SimulationOriginalDownload({worldId,name}:{worldId:string;name:string}){
|
||||
const [files,setFiles]=useState<OriginalFile[]|null>(null),[error,setError]=useState<string|null>(null),[busy,setBusy]=useState(false);
|
||||
const download=(file:OriginalFile)=>{window.location.assign(file.url);setFiles(null);};
|
||||
const open=async()=>{
|
||||
setBusy(true);setError(null);
|
||||
try {const result=await polygonRequest<{files:OriginalFile[]}>(`/worlds/${worldId}/originals`);
|
||||
if(result.files.length===1)download(result.files[0]);else setFiles(result.files);
|
||||
}catch(caught){setError(caught instanceof Error?caught.message:"Исходник недоступен.");}
|
||||
finally{setBusy(false);}
|
||||
};
|
||||
return <><IconButton label={`Скачать исходник ${name}`} disabled={busy} onClick={()=>void open()}><Icon name="download"/></IconButton>
|
||||
<Window open={!!files} title={`Исходные файлы · ${name}`} onClose={()=>setFiles(null)}>
|
||||
<Description>Выберите файл для скачивания.</Description>
|
||||
{files?.map(file=><Button key={file.url} onClick={()=>download(file)}>{file.name}</Button>)}
|
||||
</Window>
|
||||
{error?<ToastStack items={[{id:"original-download",tone:"error",title:"Исходник недоступен",description:error}]} onDismiss={()=>setError(null)}/>:null}
|
||||
</>;
|
||||
}
|
||||
@@ -11,26 +11,29 @@ import {
|
||||
} from "@nodedc/ui-react";
|
||||
|
||||
import {
|
||||
createAndUploadSimulationProject,
|
||||
updateSimulationProject,
|
||||
type SimulationProject,
|
||||
type SimulationSceneType,
|
||||
type SimulationUploadCandidate,
|
||||
type SimulationUploadProgress,
|
||||
} from "../../core/simulation/projects";
|
||||
import {
|
||||
candidatesFromDrop,
|
||||
validateSimulationCandidates,
|
||||
classifySimulationSource,
|
||||
} from "../../core/simulation/sourceFiles";
|
||||
|
||||
import { locationImports } from "../../core/simulation/locationImports";
|
||||
|
||||
export function SimulationProjectWindow({
|
||||
open,
|
||||
project,
|
||||
initialCandidates,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: {
|
||||
open: boolean;
|
||||
project: SimulationProject | null;
|
||||
initialCandidates?: SimulationUploadCandidate[];
|
||||
onClose: () => void;
|
||||
onSaved: (project: SimulationProject) => void;
|
||||
}) {
|
||||
@@ -41,7 +44,6 @@ export function SimulationProjectWindow({
|
||||
const [candidates, setCandidates] = useState<SimulationUploadCandidate[]>([]);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const [pending, setPending] = useState(false);
|
||||
const [progress, setProgress] = useState<SimulationUploadProgress | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -49,10 +51,16 @@ export function SimulationProjectWindow({
|
||||
setName(project?.name ?? "");
|
||||
setSceneType(project?.sceneType ?? "outdoor");
|
||||
setCandidates([]);
|
||||
setProgress(null);
|
||||
setPending(false);
|
||||
setError(null);
|
||||
}, [open, project]);
|
||||
if (!project && initialCandidates?.length) {
|
||||
try {
|
||||
validateSimulationCandidates(initialCandidates);
|
||||
setCandidates(initialCandidates);
|
||||
setName(candidateName(initialCandidates));
|
||||
} catch (caught) {setError(caught instanceof Error ? caught.message : "Источник не принят.");}
|
||||
}
|
||||
}, [open, project, initialCandidates]);
|
||||
|
||||
const sourceSummary = useMemo(() => summarizeCandidates(candidates), [candidates]);
|
||||
const canSubmit = name.trim().length > 0 && (project !== null || candidates.length > 0) && !pending;
|
||||
@@ -63,9 +71,7 @@ export function SimulationProjectWindow({
|
||||
setCandidates(next);
|
||||
setError(null);
|
||||
if (!name.trim() && next.length) {
|
||||
const named = next.find((candidate) => /\.lcc2?$/i.test(candidate.logicalPath)) ?? next[0];
|
||||
const first = named?.logicalPath.split("/").filter(Boolean).at(-1) ?? "Новая сцена";
|
||||
setName(first.replace(/\.(lcc2?|zip|rar|7z)$/i, ""));
|
||||
setName(candidateName(next));
|
||||
}
|
||||
} catch (caught) {
|
||||
setCandidates([]);
|
||||
@@ -75,17 +81,15 @@ export function SimulationProjectWindow({
|
||||
|
||||
const submit = async () => {
|
||||
if (!canSubmit) return;
|
||||
if (!project) {
|
||||
locationImports.enqueue(name, Promise.resolve({...classifySimulationSource(candidates), sceneType}));
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
setPending(true);
|
||||
setError(null);
|
||||
try {
|
||||
const saved = project
|
||||
? await updateSimulationProject(project.projectId, name, sceneType)
|
||||
: await createAndUploadSimulationProject(
|
||||
name,
|
||||
sceneType,
|
||||
candidates,
|
||||
setProgress,
|
||||
);
|
||||
const saved = await updateSimulationProject(project.projectId, name, sceneType);
|
||||
onSaved(saved);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof Error ? caught.message : "Не удалось сохранить проект.");
|
||||
@@ -213,33 +217,15 @@ export function SimulationProjectWindow({
|
||||
</div>
|
||||
</FieldFrame>
|
||||
) : null}
|
||||
{progress ? (
|
||||
<div className="simulation-upload-progress" role="status">
|
||||
<span><i style={{ width: `${Math.min(100, progress.totalBytes ? progress.uploadedBytes / progress.totalBytes * 100 : 0)}%` }} /></span>
|
||||
<div>
|
||||
<strong>
|
||||
{formatBytes(progress.uploadedBytes)} / {formatBytes(progress.totalBytes)}
|
||||
{" · "}{formatUploadEta(progress.estimatedSecondsRemaining)}
|
||||
</strong>
|
||||
<small>{progress.currentPath}</small>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{error ? <p className="simulation-project-window__error" role="alert">{error}</p> : null}
|
||||
</div>
|
||||
</Window>
|
||||
);
|
||||
}
|
||||
|
||||
function formatUploadEta(seconds: number | null): string {
|
||||
if (seconds === 0) return "загружено";
|
||||
if (seconds === null) return "считаем время";
|
||||
if (seconds < 60) return `осталось ≈ ${Math.max(1, seconds)} сек`;
|
||||
const minutes = Math.ceil(seconds / 60);
|
||||
if (minutes < 60) return `осталось ≈ ${minutes} мин`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const remainder = minutes % 60;
|
||||
return `осталось ≈ ${hours} ч${remainder ? ` ${remainder} мин` : ""}`;
|
||||
function candidateName(candidates: SimulationUploadCandidate[]): string {
|
||||
const named = candidates.find(candidate => /\.lcc2?$/i.test(candidate.logicalPath)) ?? candidates[0];
|
||||
return (named?.logicalPath.split("/").filter(Boolean).at(-1) ?? "Новая сцена").replace(/\.(lcc2?|zip|rar|7z)$/i, "");
|
||||
}
|
||||
|
||||
function summarizeCandidates(candidates: SimulationUploadCandidate[]): { title: string; detail: string } {
|
||||
|
||||
@@ -1,15 +1,24 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button, LoadingRegion, Window } from "@nodedc/ui-react";
|
||||
import { fetchSimulationProjects, retrySimulationProject, type SimulationProject } from "../../core/simulation/projects";
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Description, Button, GlassMaterialSurface, Icon, IconButton, LoadingRegion, Window } from "@nodedc/ui-react";
|
||||
import { fetchSimulationProjects, retrySimulationProject, type SimulationProject, type SimulationUploadCandidate } from "../../core/simulation/projects";
|
||||
import { SIMULATION_IMPORT_FORMATS } from "../../core/simulation/sourceFiles";
|
||||
import { useSimulationFileDrop } from "../../core/simulation/useSimulationFileDrop";
|
||||
import { importDroppedLocation } from "../../core/simulation/locationImports";
|
||||
import { SimulationProjectWindow } from "./SimulationProjectWindow";
|
||||
|
||||
/** Reuses the existing resumable Gaussian Pipeline admission workflow. */
|
||||
export function SimulationSourceImport({open,onClose,onPly,onReady}: {
|
||||
open:boolean; onClose:()=>void; onPly:()=>void; onReady:(worldId:string)=>void;
|
||||
export function SimulationSourceImport({children,headerToolsHost,disabled=false,onPly,onReady}: {
|
||||
children:ReactNode; headerToolsHost?:HTMLElement|null; disabled?:boolean;
|
||||
onPly:(file?:File)=>void; onReady:(worldId:string)=>void;
|
||||
}) {
|
||||
const [archive,setArchive]=useState(false), [project,setProject]=useState<SimulationProject|null>(null);
|
||||
const [open,setOpen]=useState(false);
|
||||
const [archive,setArchive]=useState<{candidates?:SimulationUploadCandidate[]}|null>(null), [project,setProject]=useState<SimulationProject|null>(null);
|
||||
const [error,setError]=useState<string|null>(null);
|
||||
const [pending,setPending]=useState<SimulationProject[]>([]);
|
||||
const drop=useSimulationFileDrop(importDroppedLocation,!disabled&&!open&&!archive&&!project);
|
||||
const importAction=<IconButton label="Импорт локации" disabled={disabled||!!archive||open}
|
||||
onClick={()=>setOpen(true)}><Icon name="plus"/></IconButton>;
|
||||
useEffect(()=>{
|
||||
if(!open)return;
|
||||
const abort=new AbortController();setError(null);
|
||||
@@ -33,21 +42,28 @@ export function SimulationSourceImport({open,onClose,onPly,onReady}: {
|
||||
};
|
||||
void poll();return()=>{abort.abort();clearTimeout(timer);};
|
||||
},[project?.projectId,project?.status]);
|
||||
return <>
|
||||
<Window open={open} title="Импорт локации" onClose={onClose}><div className="ai-polygon__actions">
|
||||
<Button onClick={()=>{onClose();onPly();}}>Gaussian PLY</Button>
|
||||
<Button onClick={()=>{onClose();setArchive(true);}}>Архив или папка LCC</Button>
|
||||
return <div className="ai-polygon" {...drop.handlers}>
|
||||
{headerToolsHost?createPortal(importAction,headerToolsHost):<div className="ai-polygon__import-action">{importAction}</div>}
|
||||
{children}
|
||||
{drop.active?<GlassMaterialSurface context="floating" radius="panel" className="simulation-import-overlay" role="status">
|
||||
<Icon name="upload"/><strong>Отпустите файл или папку, чтобы добавить локацию</strong>
|
||||
<Description>{SIMULATION_IMPORT_FORMATS}</Description>
|
||||
<Description>Одна локация за раз. Проверка и импорт начнутся автоматически.</Description>
|
||||
</GlassMaterialSurface>:null}
|
||||
<Window open={open} title="Импорт локации" onClose={()=>setOpen(false)}><div className="ai-polygon__actions">
|
||||
<Button onClick={()=>{setOpen(false);onPly();}}>Gaussian PLY</Button>
|
||||
<Button onClick={()=>{setOpen(false);setArchive({});}}>Архив или папка LCC</Button>
|
||||
</div>
|
||||
{pending.map(p=><div key={p.projectId} className="ai-polygon__row"><p>{p.name}</p>
|
||||
<Button onClick={()=>{onClose();setError(null);setProject(p);}}>Подготовка локации</Button></div>)}
|
||||
{error?<p role="alert">{error}</p>:null}
|
||||
{pending.map(p=><div key={p.projectId} className="ai-polygon__row"><Description>{p.name}</Description>
|
||||
<Button onClick={()=>{setOpen(false);setError(null);setProject(p);}}>Подготовка локации</Button></div>)}
|
||||
{error?<Description role="alert">{error}</Description>:null}
|
||||
</Window>
|
||||
<SimulationProjectWindow open={archive} project={null} onClose={()=>setArchive(false)} onSaved={p=>{setArchive(false);setProject(p);}} />
|
||||
<SimulationProjectWindow open={!!archive} initialCandidates={archive?.candidates} project={null} onClose={()=>setArchive(null)} onSaved={p=>{setArchive(null);setProject(p);}} />
|
||||
{project?<Window open title={`Подготовка ${project.name}`} onClose={()=>setProject(null)}>
|
||||
<LoadingRegion loading={project.status!=='failed'&&!error} label="Подготовка локации">
|
||||
<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}
|
||||
</LoadingRegion>
|
||||
</Window>:null}
|
||||
</>;
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {
|
||||
import { Description,
|
||||
Button,
|
||||
Icon,
|
||||
RangeControl,
|
||||
@@ -44,12 +44,12 @@ export function SimulationUgvSettingsPanel({
|
||||
<strong>Физика UGV</strong>
|
||||
<span>Дифференциальный привод</span>
|
||||
</div>
|
||||
<p>
|
||||
<Description>
|
||||
A/D без W/S разворачивают UGV вокруг собственного центра. Скорость и
|
||||
динамика применяются сразу. Мышь вращает камеру вокруг машины, колесо
|
||||
меняет дистанцию; после паузы камера плавно возвращается назад. Ползунок
|
||||
работает в штатном диапазоне, точное значение можно ввести вручную.
|
||||
</p>
|
||||
</Description>
|
||||
<TextField
|
||||
label="Название пресета"
|
||||
value={value.presetName}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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 { usePlannerPreferences } from "./usePlannerPreferences";
|
||||
|
||||
@@ -22,12 +22,12 @@ export function SimulationViewTools({expanded,toggle,semantic=false,planning=fal
|
||||
{settings?<PlannerSettings boundsRef={boundsRef} onClose={()=>setSettings(false)}/>:null}
|
||||
<Window open={help} onClose={()=>setHelp(false)} title="Управление сценой">
|
||||
<div className="ai-polygon__form">{planning?<>
|
||||
<p>{semantic?"При редактировании Ctrl + перетаскивание ЛКМ — вращение камеры; без Ctrl — выбранный инструмент. Вне редактирования ЛКМ вращает камеру без Ctrl.":"ЛКМ — вращение вокруг точки нажатия."} ПКМ или клик двумя пальцами с движением — сдвиг.</p>
|
||||
<p>{semantic?"При редактировании прокрутка двумя пальцами сдвигает вид; щипок или Ctrl + прокрутка — зум к курсору.":"Прокрутка — зум к курсору, в том числе в режиме добавления точек."}</p>
|
||||
<p>WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.</p>
|
||||
{semantic?<p>Клик по полосе выбирает элемент целиком, по её вершине — точку; рамка или Shift + клик выбирают несколько точек. Shift + перетаскивание пивота копирует целый элемент или продолжает выбранную точку. Escape отменяет действие, Ctrl/Cmd+Z — отменяет правку. Hold закрепляет тулбар.</p>:null}
|
||||
{routeEditing?<p>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</p>:null}
|
||||
</>:<><p>WASD / стрелки — движение. Пробел — тормоз. R — к старту.</p><p>Мышь — обзор.</p></>}</div>
|
||||
<Description>{semantic?"При редактировании Ctrl + перетаскивание ЛКМ — вращение камеры; без Ctrl — выбранный инструмент. Вне редактирования ЛКМ вращает камеру без Ctrl.":"ЛКМ — вращение вокруг точки нажатия."} ПКМ или клик двумя пальцами с движением — сдвиг.</Description>
|
||||
<Description>{semantic?"При редактировании прокрутка двумя пальцами сдвигает вид; щипок или Ctrl + прокрутка — зум к курсору.":"Прокрутка — зум к курсору, в том числе в режиме добавления точек."}</Description>
|
||||
<Description>WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.</Description>
|
||||
{semantic?<Description>Клик по полосе выбирает элемент целиком, по её вершине — точку; рамка или Shift + клик выбирают несколько точек. Shift + перетаскивание пивота копирует целый элемент или продолжает выбранную точку. Escape отменяет действие, Ctrl/Cmd+Z — отменяет правку. Hold закрепляет тулбар.</Description>:null}
|
||||
{routeEditing?<Description>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</Description>:null}
|
||||
</>:<><Description>WASD / стрелки — движение. Пробел — тормоз. R — к старту.</Description><Description>Мышь — обзор.</Description></>}</div>
|
||||
</Window>
|
||||
{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 {
|
||||
import { Description,
|
||||
ActivityIndicator,
|
||||
Button,
|
||||
GlassMaterialSurface,
|
||||
@@ -237,7 +237,7 @@ export function SimulationViewport({
|
||||
data-control-mode={controlMode}
|
||||
aria-label={`Сцена ${project.name}`}
|
||||
>
|
||||
<header className="simulation-viewport__toolbar">
|
||||
<header data-glass-context="scene" className="simulation-viewport__toolbar nodedc-viewport-surface">
|
||||
<div>
|
||||
<StatusBadge tone={state === "failed" || collisionState === "failed" ? "warning" : state === "ready" && collisionState !== "loading" ? "success" : "accent"}>
|
||||
{controlState === "loading"
|
||||
@@ -341,7 +341,7 @@ export function SimulationViewport({
|
||||
role="dialog"
|
||||
aria-label="Настройки сцены"
|
||||
>
|
||||
<div className="simulation-viewport__settings-head">
|
||||
<div data-glass-context="scene" className="simulation-viewport__settings-head nodedc-viewport-surface">
|
||||
<div>
|
||||
<strong>Настройки сцены</strong>
|
||||
<span>Локация, камера и UGV</span>
|
||||
@@ -356,9 +356,9 @@ export function SimulationViewport({
|
||||
<strong>Система координат</strong>
|
||||
<span>Мир сцены · Y вверх</span>
|
||||
</div>
|
||||
<p>
|
||||
<Description>
|
||||
Коррекция слоёв не меняет координаты камеры, навигации и будущей физики.
|
||||
</p>
|
||||
</Description>
|
||||
<div className="simulation-viewport__settings-rotations">
|
||||
<LayerRotationFields
|
||||
label="Гауссовый слой"
|
||||
@@ -450,10 +450,10 @@ export function SimulationViewport({
|
||||
<div className="simulation-viewport__stage">
|
||||
<canvas ref={canvasRef} aria-label={`Сцена ${project.name}`} />
|
||||
{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="Загрузка локации" />}
|
||||
<strong>{state === "failed" ? "Локация не открылась" : "Загружаем локацию"}</strong>
|
||||
<p>{error ?? "LOD-уровни загружаются по мере готовности runtime."}</p>
|
||||
<Description>{error ?? "LOD-уровни загружаются по мере готовности runtime."}</Description>
|
||||
</div>
|
||||
) : null}
|
||||
</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'|'egress'>(fixedKind??'wireguard'),[document,setDocument]=useState(''),[filename,setFilename]=useState('');
|
||||
const catalog=useServers();const [serverId,setServerId]=useState(initialServer?.id??'');
|
||||
const server=initialServer??catalog.items?.find(s=>s.id===serverId);
|
||||
const serviceName=kind==='egress'?'Маршрутизация трафика':kind==='librespeed'?'LibreSpeed':'WireGuard';
|
||||
const [network,setNetwork]=useState(''),[interfaces,setInterfaces]=useState<{id:string;label:string}[]>([]);
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState('');const file=useRef<HTMLInputElement>(null);
|
||||
useEffect(()=>{let active=true;void vpsRequest<{items:{id:string;label:string}[]}>('/interfaces').then(r=>{if(active)setInterfaces(r.items);}).catch(()=>{});return()=>{active=false;};},[]);
|
||||
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'},{value:'egress',label:'Маршрутизация трафика'}]} onChange={value=>{setKind(value as typeof kind);setDocument('');setFilename('');setError('');}}/>
|
||||
<InstallerCard key={kind} connectionInstruction={kind==='librespeed'?undefined:"Вернитесь в это окно и подключите установленную службу с выданным приглашением."} kind={kind==='egress'?'vps-egress':kind==='librespeed'?'vps-librespeed':kind==='wireguard'?'vps-wireguard':'vps-arnavi'}/>
|
||||
<SettingsCard title="Подключение установленной службы" description="Запустите установщик на выбранном VPS. Затем передайте выданное им приглашение — Mission Core проверит сервер и сохранит подключение.">
|
||||
{kind!=='arnavi'?<>
|
||||
<input ref={file} type="file" accept=".json,application/json" hidden onChange={event=>{const chosen=event.target.files?.[0];event.target.value='';if(!chosen)return;setDocument('');setFilename('');void (async()=>{if(chosen.size>16384)throw Error(`Выберите файл приглашения ${serviceName} (до 16 КБ).`);setDocument(await chosen.text());setFilename(chosen.name);})().catch(e=>setError(e.message));}}/>
|
||||
<Button icon={<Icon name="upload"/>} disabled={busy} onClick={()=>file.current?.click()}>Выбрать приглашение {serviceName}</Button>
|
||||
{filename&&<Description>{filename}</Description>}
|
||||
<Description>Файл на VPS: {kind==='egress'?'/var/lib/ndc-egress-vps/mission-core-egress.json':kind==='librespeed'?'/var/lib/ndc-librespeed-vps/mission-core-librespeed.json':'/var/lib/ndc-wireguard-vps/mission-core-wireguard.json'}. Скопируйте его по защищённому соединению (например, SFTP). Приглашение действует 24 часа; новое выпускается командой connection того же установщика. {kind==='wireguard'?'Экспорт .conf из клиента WireGuard не подходит.':''}</Description>
|
||||
</>:<TextAreaField label="Ключ подключения ARNavi" value={document} disabled={busy} rows={4} onChange={e=>setDocument(e.target.value)} hint="Ключ находится на VPS в /opt/nodedc-mission-vps/connect.key. Действует 24 часа и используется один раз."/>}
|
||||
</SettingsCard>
|
||||
{interfaces.length>0&&<Select label="Подключение к VPS" disabled={busy} value={network} options={[{value:'',label:'Через текущую сеть'},...interfaces.map(i=>({value:i.id,label:`Напрямую · ${i.label}`}))]} onChange={setNetwork}/>}
|
||||
</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 {
|
||||
AdminNavigationPanel,
|
||||
Icon,
|
||||
IconButton,
|
||||
} from "@nodedc/ui-react";
|
||||
import {AdminNavigationPanel, Icon} from "@nodedc/ui-react";
|
||||
import {workspacesForRoot} from "../../productModel";
|
||||
|
||||
import { useComputeContours } from "../../core/system/ComputeContourContext";
|
||||
|
||||
interface SystemNavigationPanelProps {
|
||||
title: string;
|
||||
onAdd: () => void;
|
||||
onNavigateRoot: () => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function SystemNavigationPanel({
|
||||
title,
|
||||
onAdd,
|
||||
onNavigateRoot,
|
||||
onClose,
|
||||
}: SystemNavigationPanelProps) {
|
||||
const { contours, selectedContour, selectContour } = useComputeContours();
|
||||
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>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
export function SystemNavigationPanel({title, activeId, onNavigate, onClose}: {
|
||||
title: string; activeId: string; onNavigate: (id: string) => void; onClose: () => void;
|
||||
}) {
|
||||
const categories = workspacesForRoot("system").filter(item => item.kind === "workers" || item.kind === "vps");
|
||||
return <AdminNavigationPanel eyebrow="MISSION CORE" title={title}
|
||||
closeLabel={`Закрыть раздел «${title}»`} navigationLabel="Система" onClose={onClose}
|
||||
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}/>;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { SegmentedControl } from "@nodedc/ui-react";
|
||||
|
||||
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> = {
|
||||
modules: "Модули",
|
||||
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 { useComputeContours } from "../../core/system/ComputeContourContext";
|
||||
import { ComputeContourSettingsWindow } from "./ComputeContourSettingsWindow";
|
||||
import { WorkerConnectionSettings } from "./WorkerConnectionSettings";
|
||||
import { useWorkerPower } from "./useWorkerPower";
|
||||
|
||||
interface ComputeContourSettingsController {
|
||||
canEdit: boolean;
|
||||
@@ -14,6 +15,7 @@ interface ComputeContourSettingsController {
|
||||
|
||||
export function useComputeContourSettings(): ComputeContourSettingsController {
|
||||
const contours = useComputeContours();
|
||||
const power = useWorkerPower(contours.selectedContour);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [mode, setMode] = useState<"create" | "edit">("edit");
|
||||
const openCreate = useCallback(() => {
|
||||
@@ -47,16 +49,16 @@ export function useComputeContourSettings(): ComputeContourSettingsController {
|
||||
canEdit: contours.selectedContour !== null,
|
||||
openCreate,
|
||||
openEdit,
|
||||
utilityActions,
|
||||
utilityActions: [...utilityActions, power.action],
|
||||
window: (
|
||||
<ComputeContourSettingsWindow
|
||||
<><WorkerConnectionSettings
|
||||
open={open}
|
||||
mode={mode}
|
||||
contour={contours.selectedContour}
|
||||
contour={mode === "create" ? null : contours.selectedContour}
|
||||
onClose={() => setOpen(false)}
|
||||
onCreate={contours.createContour}
|
||||
onChanged={() => {contours.refresh(); contours.refreshTelemetry();}}
|
||||
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(),
|
||||
});
|
||||
}
|
||||
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({
|
||||
label: sessionOverview.open ? "Закрыть информацию о записи" : "Информация о записи",
|
||||
icon: "info", pressed: sessionOverview.open, disabled: !sessionOverview.available,
|
||||
|
||||
@@ -4,7 +4,7 @@ export type BatteryPanelAppearance={height:number;radius:number;labelSize: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 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:{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: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 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;
|
||||
@@ -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 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);
|
||||
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,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{
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import {legacyRecord,profileClient} from '../roverScene/profileClient';
|
||||
import {defaultChargeGradient} from '../roverScene/chargeGradient';
|
||||
import r04 from './r04.json';
|
||||
import {defaultScene,parseScene,type SceneDocument} from '../roverScene/sceneDocument';
|
||||
@@ -8,27 +9,16 @@ export function defaultBatteryScene():SceneDocument {
|
||||
return {...defaultScene(),schema:'missioncore.battery-scene/v1',model:'catl-r04/v1',
|
||||
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 {
|
||||
return {defaults:defaultBatteryScene,write:save,filename:'battery-r04-scene.json',read:async id=>{
|
||||
const db=await database();let raw:unknown;try{raw=await new Promise((resolve,reject)=>{
|
||||
const request=db.transaction('scenes').objectStore('scenes').get(id);
|
||||
request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error);
|
||||
});}finally{db.close();}
|
||||
const clients=new Map<string,ReturnType<typeof profileClient<SceneDocument>>>();
|
||||
const client=(id:string)=>{let c=clients.get(id);if(!c){c=profileClient<SceneDocument>('battery',id);clients.set(id,c);}return c;};
|
||||
return {defaults:defaultBatteryScene,write:(id,doc)=>client(id).write(doc),filename:'battery-r04-scene.json',read:async id=>{
|
||||
const raw=await client(id).read(async()=>{const old=await legacyRecord('missioncore-battery-scenes','scenes',id);return old?parseScene(old,defaultBatteryScene):null;});
|
||||
if(raw)return parseScene(raw,defaultBatteryScene);
|
||||
const seed=seedKey?await readScene(seedKey):null;
|
||||
const doc=defaultBatteryScene();
|
||||
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.
|
||||
await save(id,doc);return doc;
|
||||
// Defaults remain in memory until an explicit edit. Never overwrite a failed read.
|
||||
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 {profileClient} from '../roverScene/profileClient';
|
||||
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){
|
||||
const [error,setError]=useState('');
|
||||
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 [value,setValue]=useState(history.present);
|
||||
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 update=useCallback((next:BatteryAppearance)=>{if(JSON.stringify(next)!==JSON.stringify(history.present)){history.update(next);publish();}},[history,publish]);
|
||||
const undo=useCallback(()=>{if(history.undo())publish();},[history,publish]);
|
||||
const redo=useCallback(()=>{if(history.redo())publish();},[history,publish]);
|
||||
const [error,setError]=useState(''),[ready,setReady]=useState(false);
|
||||
const client=useMemo(()=>profileClient<BatteryAppearance>('battery-ui',id),[id]);
|
||||
const history=useMemo(()=>new SceneHistory(defaultBatteryAppearance()),[id]);
|
||||
const [value,setValue]=useState(history.present),loaded=useRef(false);
|
||||
const pending=useRef<BatteryAppearance|null>(null),timer=useRef<ReturnType<typeof setTimeout>|null>(null);
|
||||
const flush=useCallback(()=>{if(timer.current)clearTimeout(timer.current);const next=pending.current;if(!next)return;pending.current=null;
|
||||
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(()=>{
|
||||
if(!active)return;
|
||||
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);
|
||||
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]);
|
||||
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){
|
||||
const [value,setValue]=useState(defaultBatteryAppearance);
|
||||
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 external=(event:StorageEvent)=>{if(!event.key||event.key===(id&&batteryAppearanceKey(id)))read();};
|
||||
read();window.addEventListener('missioncore:battery-ui',local);window.addEventListener('storage',external);
|
||||
return()=>{window.removeEventListener('missioncore:battery-ui',local);window.removeEventListener('storage',external);};
|
||||
read();window.addEventListener('missioncore:battery-ui',local);window.addEventListener('focus',read);
|
||||
return()=>{cancelled=true;window.removeEventListener('missioncore:battery-ui',local);window.removeEventListener('focus',read);};
|
||||
},[id]);
|
||||
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"],
|
||||
missions: ["routes", null],
|
||||
data: ["recordings", "datasets"],
|
||||
system: ["modules", "integrations"],
|
||||
system: ["modules", "network"],
|
||||
polygon: ["observatory", "local-device"],
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
export interface UplinkCandidate {id:string;label:string;interface:string;kind:'wifi'|'ethernet';verified:boolean;available?:boolean;active?:boolean}
|
||||
export interface BoardUplinkView {
|
||||
path_verified?:boolean;available:boolean;reason:string;revision:string;runtime:string;current_id:string;candidates:UplinkCandidate[];
|
||||
operation:{id:string;phase:string;message:string}|null;
|
||||
fallback?:{enabled:boolean;revision:number;operation_id:string}|null;
|
||||
fallback_operation?:{id:string;phase:string;message:string}|null;
|
||||
}
|
||||
export const uplinkPending=(value:BoardUplinkView|null)=>['queued','applying','verifying','rolling_back','recovering','unknown','rollback_failed'].includes(value?.operation?.phase||'');
|
||||
export const fallbackPending=(value:BoardUplinkView|null)=>value?.fallback_operation?.phase==='queued';
|
||||
export const canSetFallback=(value:BoardUplinkView|null)=>Boolean(value?.available&&value.path_verified&&value.fallback&&!uplinkPending(value)&&!fallbackPending(value));
|
||||
export const canSelectUplink=(value:BoardUplinkView|null,target:string)=>Boolean(value?.available&&!uplinkPending(value)&&!fallbackPending(value)&&value.current_id&&(target!==value.current_id||value.path_verified===false)&&value.candidates.some(c=>c.id===target&&(c.available||c.verified)));
|
||||
export const uplinkOptions=(value:BoardUplinkView|null)=>(value?.candidates??[]).map(c=>({value:c.id,label:`${c.kind==='wifi'?'Wi-Fi':'Ethernet'} · ${c.label}`,description:`${c.interface}${c.id===value?.current_id?' · Текущее':''}${!c.verified?(c.active?' · Интернет не подтверждён':' · Не подключено'):''}`,disabled:!(c.available||c.verified)}));
|
||||
export const uplinkStatusMessage=(value:BoardUplinkView|null)=>{
|
||||
if(!value)return '';
|
||||
if(!value.available)return value.reason;
|
||||
if(uplinkPending(value))return value.operation?.message||'Проверяем подключение.';
|
||||
const op=value.operation;
|
||||
if(op?.phase==='applied'||op?.phase==='rolled_back'){
|
||||
if(!value.path_verified)return 'Текущий путь к Core не подтверждён.';
|
||||
const result=op.phase==='applied'?'Подключение выбрано.':'Возвращено прежнее подключение.';
|
||||
return `${result} ${value.path_verified?'Путь к Core подтверждён.':'Текущий путь к Core не подтверждён.'}`;
|
||||
}
|
||||
return op?.message||'';
|
||||
};
|
||||
// Follow observed state unless the operator is deliberately choosing an alternative.
|
||||
export const uplinkReceipt=(value:BoardUplinkView|null)=>value?.operation?`${value.operation.id}:${value.operation.phase}`:'';
|
||||
export const reconcileUplinkSelection=(selected:string,previousCurrent:string,next:BoardUplinkView,previousReceipt='')=>{
|
||||
const settled=Boolean(next.operation&&!uplinkPending(next)&&uplinkReceipt(next)!==previousReceipt);
|
||||
return settled||selected===previousCurrent||!next.candidates.some(c=>c.id===selected&&(c.available||c.verified))?next.current_id:selected;
|
||||
};
|
||||
|
||||
export const uplinkCurrentLabel=(value:BoardUplinkView|null)=>{
|
||||
if(!value?.available)return value?.reason||'Получаем состояние сети с борта.';
|
||||
if(uplinkPending(value))return 'Текущее подключение: проверяется.';
|
||||
const current=value.candidates.find(c=>c.id===value.current_id);
|
||||
if(!current)return 'Основное подключение не определено.';
|
||||
return `Текущее подключение: ${current.kind==='wifi'?'Wi-Fi':'Ethernet'} · ${current.label}${value.path_verified?'':' · путь к Core не подтверждён'}.`;
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
import type {IndependentDevice} from './equipment';
|
||||
import type {TrackerTelemetry} from './vps';
|
||||
|
||||
export function visibleIndependentDevices(devices:IndependentDevice[],telemetry:{items:TrackerTelemetry[];unavailable:boolean;receivedAt:number},now=Date.now()):IndependentDevice[]{
|
||||
if(telemetry.unavailable||!telemetry.receivedAt||now-telemetry.receivedAt>=20000)return [];
|
||||
const online=new Set(telemetry.items.filter(item=>item.online).map(item=>item.instance_id));
|
||||
return devices.filter(device=>online.has(device.id));
|
||||
}
|
||||
@@ -3,5 +3,5 @@ import {fleetRequest} from './useFleet';
|
||||
|
||||
export function routerTransport(vehicleID:string):RouterTransport{
|
||||
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 {openAdmin:device=>fleetRequest(base+'/'+encodeURIComponent(device)+'/admin','POST',{}),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,25 @@
|
||||
import {routerFresh,routerLabel,routerName,simChannels,type RouterDevice,type RouterSnapshot} from '../../../../../packages/router-ui/src/contracts';
|
||||
import {routerMode} from '../../../../../packages/router-ui/src/mode';
|
||||
import {modemLabel} from '../../../../../packages/router-ui/src/overview';
|
||||
|
||||
export const routerObservationKey=(id:string)=>JSON.stringify(['router',id]);
|
||||
export function routerObservation(device:RouterDevice,value:RouterSnapshot|null,now=Date.now()){
|
||||
const ready=device.attached!==false&&device.state==='ready'&&routerFresh(value,device,now);
|
||||
const mode=routerMode(device,ready);
|
||||
const aggregating=ready&&!mode.pending&&!mode.fallback&&['aggregation','proxy'].includes(mode.activeMode);
|
||||
return {ready,mode,live:ready&&!mode.pending,waiting:device.attached!==false&&value?.available===true&&(!ready||mode.pending),name:routerName(device),status:device.attached===false?'Роутер отключён':mode.pending?'Роутер применяет настройки':routerLabel(value,device,now),
|
||||
internet:ready&&device.internet==='verified'?'Интернет подтверждён':ready?'Интернет не подтверждён':'Нет свежих данных',
|
||||
channels:simChannels(device).map(channel=>{
|
||||
const modem=device.modems.find(item=>item.slot===channel.slot);
|
||||
const wan=device.client_api?.wan?.find(item=>item.slot===channel.slot);
|
||||
const radioFresh=ready&&wan?.fresh!==false&&modem?.radio!=='NOSIM'&&(modem?.radio_age_seconds==null||modem.radio_age_seconds<40&&modem.radio_age_seconds>=0);
|
||||
const active=mode.activeSlot===channel.slot;
|
||||
const connected=ready&&modem?.connectivity==='online'&&modem.radio!=='NOSIM'&&wan?.up!==false&&wan?.fresh!==false&&wan?.sim_present!==false&&wan?.modem_present!==false;
|
||||
// An observed aggregation mode has no single activeSlot. Show availability
|
||||
// of its WANs without claiming that registration alone proves aggregation.
|
||||
const aggregateChannel=aggregating&&connected&&wan?.up===true&&wan.fresh===true;
|
||||
return {...channel,indicator:active?(connected?'success' as const:'warning' as const):aggregateChannel?'success' as const:'neutral' as const,indicatorLabel:active?(connected?'Активный канал':'Выбранный канал недоступен'):aggregateChannel?'Канал агрегации доступен':'Не используется',operator:ready?(modem?.operator||'Оператор не определён'):'—',
|
||||
status:modemLabel(modem,ready),active,
|
||||
rsrp:radioFresh?modem?.rsrp:null};
|
||||
})};
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/** Explicit DEV recording only. Persistent browser spool; no network or authority.
|
||||
* Unacknowledged evidence is never evicted. Quota refusal is reported to the owner. */
|
||||
export type BrowserRow=Record<string,unknown>;
|
||||
type Stored={key?:number;capture:string;bytes:number;row:BrowserRow};
|
||||
const CAPTURE_BYTES=32*1024*1024,TOTAL_BYTES=128*1024*1024;
|
||||
let opened:Promise<IDBDatabase>|null=null;
|
||||
function database(){
|
||||
if(!opened)opened=new Promise<IDBDatabase>((resolve,reject)=>{
|
||||
const r=indexedDB.open('missioncore-browser-dev-v1',1);
|
||||
r.onupgradeneeded=()=>{r.result.createObjectStore('rows',{keyPath:'key',autoIncrement:true}).createIndex('capture','capture');r.result.createObjectStore('quota');};
|
||||
r.onsuccess=()=>resolve(r.result);r.onerror=()=>{opened=null;reject(r.error);};
|
||||
});return opened;
|
||||
}
|
||||
export interface BrowserJournalStore {append(rows:BrowserRow[]):Promise<void>;page(limit?:number):Promise<Stored[]>;ack(rows:Stored[]):Promise<void>}
|
||||
export class BrowserJournal implements BrowserJournalStore {
|
||||
constructor(readonly capture:string){}
|
||||
async append(rows:BrowserRow[]){
|
||||
if(!rows.length)return;
|
||||
const db=await database(),entries=rows.map(row=>({capture:this.capture,row,bytes:new TextEncoder().encode(JSON.stringify(row)).length})),bytes=entries.reduce((n,r)=>n+r.bytes,0);
|
||||
await new Promise<void>((resolve,reject)=>{
|
||||
const tx=db.transaction(['rows','quota'],'readwrite'),q=tx.objectStore('quota');let failure:Error|null=null;
|
||||
const total=q.get('total'),capture=q.get(this.capture);
|
||||
capture.onsuccess=()=>{
|
||||
if((total.result??0)+bytes>TOTAL_BYTES||(capture.result??0)+bytes>CAPTURE_BYTES){failure=Error('Локальное хранилище DEV заполнено. Сохраните запись; ранее записанные события сохранены.');tx.abort();return;}
|
||||
for(const r of entries)tx.objectStore('rows').add(r);
|
||||
q.put((total.result??0)+bytes,'total');q.put((capture.result??0)+bytes,this.capture);
|
||||
};
|
||||
tx.oncomplete=()=>resolve();tx.onabort=tx.onerror=()=>reject(failure??tx.error??Error('Не удалось сохранить DEV в браузере.'));
|
||||
});
|
||||
}
|
||||
async page(limit?:number){
|
||||
const db=await database();return new Promise<Stored[]>((resolve,reject)=>{
|
||||
const tx=db.transaction('rows'),r=tx.objectStore('rows').index('capture').getAll(IDBKeyRange.only(this.capture),limit);
|
||||
r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error);
|
||||
});
|
||||
}
|
||||
async ack(rows:Stored[]){
|
||||
if(!rows.length)return;const db=await database();await new Promise<void>((resolve,reject)=>{
|
||||
const tx=db.transaction(['rows','quota'],'readwrite'),q=tx.objectStore('quota');let removed=0;
|
||||
for(const row of rows){const r=tx.objectStore('rows').get(row.key!);r.onsuccess=()=>{if(r.result?.capture===this.capture){removed+=r.result.bytes;tx.objectStore('rows').delete(row.key!);}};}
|
||||
const total=q.get('total'),capture=q.get(this.capture);
|
||||
capture.onsuccess=()=>{q.put(Math.max(0,(total.result??0)-removed),'total');q.put(Math.max(0,(capture.result??0)-removed),this.capture);};
|
||||
tx.oncomplete=()=>resolve();tx.onerror=tx.onabort=()=>reject(tx.error);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Recovery is appended to the same explicit operator download: browsers may
|
||||
* block a second automatic file. Download does not acknowledge Core receipt. */
|
||||
export async function pendingBrowserJournal(url:string,id:string):Promise<Blob|null>{
|
||||
if(typeof indexedDB==='undefined')return null;
|
||||
const rows=await new BrowserJournal(`${url}:${id}`).page();
|
||||
if(!rows.length)return null;
|
||||
return new Blob(['\n',JSON.stringify({schema:'missioncore.browser-capture/v1',capture_id:id,source:'browser',recovered:true})+'\n',...rows.map(r=>JSON.stringify({...r.row,source:'browser',recovered:true})+'\n')],{type:'application/x-ndjson'});
|
||||
}
|
||||
@@ -1,38 +1,76 @@
|
||||
/** Opt-in bounded queues on the operator host. Never awaited by motor transport. */
|
||||
import {BrowserJournal,type BrowserJournalStore} from './roverBrowserJournal';
|
||||
type Row=Record<string,unknown>;
|
||||
type Capture={id:string|null;rows:Row[];bytes:number;dropped:number;journal:BrowserJournalStore|null;pending:Promise<void>|null;error:string|null};
|
||||
const emptyCapture=():Capture=>({id:null,rows:[],bytes:0,dropped:0,journal:null,pending:null,error:null});
|
||||
export class BrowserEvidence {
|
||||
id:string|null=null;rows:Row[]=[];busy=false;dropped=0;
|
||||
constructor(readonly url:string,readonly local=false){}
|
||||
set(id:string|null){if(this.id!==id){this.rows=[];this.dropped=0;this.id=id;}}
|
||||
private capture=emptyCapture();busy=false;
|
||||
get id(){return this.capture.id;}get rows(){return this.capture.rows;}get bytes(){return this.capture.bytes;}
|
||||
get dropped(){return this.capture.dropped;}set dropped(n:number){this.capture.dropped=n;}
|
||||
get storageError(){return this.capture.error;}
|
||||
constructor(readonly url:string,readonly local=false,readonly store=(capture:string):BrowserJournalStore|null=>typeof indexedDB==='undefined'?null:new BrowserJournal(capture)){}
|
||||
set(id:string|null,durable=false){
|
||||
if(this.id===id)return;
|
||||
// Each asynchronous writer owns its capture, even after the UI changes sessions.
|
||||
void this.persistCapture(this.capture).catch(()=>{});
|
||||
this.capture={...emptyCapture(),id,journal:this.local&&id&&durable?this.store(`${this.url}:${id}`):null};
|
||||
if(this.local&&id&&durable&&!this.capture.journal)this.capture.error='Браузер не поддерживает локальное сохранение DEV.';
|
||||
}
|
||||
private restore(c:Capture,rows:Row[]){
|
||||
c.rows=[...rows,...c.rows];c.bytes=c.rows.reduce((n,r)=>n+JSON.stringify(r).length*2,0);
|
||||
while(c.rows.length>6000||c.bytes>2*1024*1024){const r=c.journal?c.rows.pop():c.rows.shift();c.bytes-=JSON.stringify(r).length*2;c.dropped++;}
|
||||
}
|
||||
private async persistCapture(c:Capture):Promise<void>{
|
||||
while(c.pending)await c.pending;
|
||||
if(!c.journal||!c.rows.length)return;
|
||||
const rows=c.rows.splice(0);c.bytes=0;
|
||||
c.pending=c.journal.append(rows).then(()=>{c.error=null;}).catch(e=>{
|
||||
c.error=e instanceof Error?e.message:'Не удалось сохранить DEV в браузере.';this.restore(c,rows);throw e;
|
||||
}).finally(()=>{c.pending=null;});
|
||||
await c.pending;
|
||||
if(c.rows.length)return this.persistCapture(c);
|
||||
}
|
||||
persist(){return this.persistCapture(this.capture);}
|
||||
record(event:string,data:Row={}){
|
||||
if(!this.id)return;
|
||||
const row={event,browser_ms:performance.now(),...data};
|
||||
if(JSON.stringify(row).length>2048){this.dropped++;return;}
|
||||
if(this.rows.length>=256){this.rows.shift();this.dropped++;}
|
||||
this.rows.push(row);
|
||||
const c=this.capture;if(!c.id)return;
|
||||
const row={event,...(this.local?{browser_event_id:crypto.randomUUID()}:{}),browser_ms:performance.now(),browser_time_origin_ms:performance.timeOrigin,...data};
|
||||
const size=JSON.stringify(row).length*2,limit=this.local?6000:256;
|
||||
if(size>4096){c.dropped++;return;}
|
||||
if(c.journal&&(c.rows.length>=limit||c.bytes+size>2*1024*1024)){c.dropped++;c.error='Не удалось дописать события DEV: локальное хранилище занято.';return;}
|
||||
while(c.rows.length&&(c.rows.length>=limit||c.bytes+size>2*1024*1024)){c.bytes-=JSON.stringify(c.rows.shift()).length*2;c.dropped++;}
|
||||
c.rows.push(row);c.bytes+=size;
|
||||
}
|
||||
async flush(){
|
||||
if(this.busy||!this.id||!this.rows.length)return;
|
||||
const id=this.id,rows=this.rows.splice(0,32);this.busy=true;
|
||||
try{const r=await fetch(this.url+(this.local?'/diagnostics/local/events':'/diagnostics/events'),{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({id,events:rows}),signal:AbortSignal.timeout(2000),keepalive:true});
|
||||
if(!r.ok)throw Error('trace');
|
||||
if(this.local&&(await r.json()).accepted!==true&&id===this.id)this.set(null);
|
||||
}
|
||||
catch{if(id===this.id){const pending=[...rows,...this.rows];this.dropped+=Math.max(0,pending.length-256);this.rows=pending.slice(-256);}}
|
||||
if(this.busy||!this.id)return 0;
|
||||
const c=this.capture,id=c.id,journal=c.journal;this.busy=true;
|
||||
let memory:Row[]=[];
|
||||
try{
|
||||
if(journal)await this.persistCapture(c);
|
||||
const stored=journal?await journal.page(256):[];
|
||||
memory=journal?[]:c.rows.splice(0,this.local?256:32);
|
||||
if(!journal)c.bytes-=memory.reduce((n,row)=>n+JSON.stringify(row).length*2,0);
|
||||
const rows=journal?stored.map(r=>r.row):memory;if(!rows.length)return 0;
|
||||
const r=await fetch(this.url+(this.local?'/diagnostics/local/events':'/diagnostics/events'),{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({id,events:rows}),signal:AbortSignal.timeout(5000)});
|
||||
if(!r.ok)throw Error('Не удалось передать события DEV. Локальная запись сохранена.');
|
||||
if(this.local&&(await r.json()).accepted!==true)throw Error('Запись Core уже закрыта. События браузера сохранены локально.');
|
||||
if(journal)await journal.ack(stored);
|
||||
return rows.length;
|
||||
}catch(e){if(memory.length)this.restore(c,memory);throw e;}
|
||||
finally{this.busy=false;}
|
||||
}
|
||||
}
|
||||
const sessions=new Map<string,{remote:BrowserEvidence;local:BrowserEvidence;preview:boolean}>();
|
||||
const sessions=new Map<string,{remote:BrowserEvidence;local:BrowserEvidence;preview:boolean;deferred:boolean}>();
|
||||
export function roverDevEvent(url:string,event:string,data:Row={}){try{const pair=sessions.get(url);pair?.remote.record(event,data);pair?.local.record(event,data);}catch{/* No change to input authority. */}}
|
||||
/** Camera metrics never enter the optional WAN recorder. */
|
||||
export function roverPreviewEvidence(url:string,sample:Row){try{const pair=sessions.get(url);if(pair?.preview)pair.local.record('preview',{sample});}catch{/* No preview/control side effect. */}}
|
||||
export function connectRoverEvidence(url:string){
|
||||
const pair={remote:new BrowserEvidence(url),local:new BrowserEvidence(url,true),preview:true};sessions.set(url,pair);
|
||||
const timer=setInterval(()=>{for(const e of [pair.remote,pair.local]){if(e.dropped){const dropped=e.dropped;e.dropped=0;e.record('lifecycle',{reason:'browser_queue_gap',dropped});}void e.flush();}},250);
|
||||
return {set(id:string|null,localID:string|null=null,preview=true){pair.preview=preview;pair.remote.set(id);const changed=pair.local.id!==localID;pair.local.set(localID);if(changed&&localID)pair.local.record('lifecycle',{reason:'local_capture_attached',foreground:roverEvidenceForeground()});},
|
||||
async flush(){for(const e of [pair.remote,pair.local])for(let n=0;n<9&&e.rows.length;n++){if(e.busy)await new Promise(r=>setTimeout(r,25));else await e.flush();}},
|
||||
close(){clearInterval(timer);for(const e of [pair.remote,pair.local])void e.flush();if(sessions.get(url)===pair)sessions.delete(url);}};
|
||||
const pair={remote:new BrowserEvidence(url),local:new BrowserEvidence(url,true),preview:true,deferred:false};sessions.set(url,pair);
|
||||
const timer=setInterval(()=>{if(pair.deferred){void pair.local.persist().catch(()=>{});return;}for(const e of [pair.remote,pair.local]){if(e.dropped){const dropped=e.dropped;e.dropped=0;e.record('lifecycle',{reason:'browser_queue_gap',dropped});}void e.flush().catch(()=>{});}},250);
|
||||
return {set(id:string|null,localID:string|null=null,preview=true,deferred=false){pair.preview=preview;pair.deferred=deferred;pair.remote.set(id);const changed=pair.local.id!==localID;pair.local.set(localID,deferred);if(changed&&localID)pair.local.record('lifecycle',{reason:'local_capture_attached',foreground:roverEvidenceForeground()});},
|
||||
async flush(){for(const e of [pair.remote,pair.local]){if(e.dropped){const dropped=e.dropped;e.dropped=0;e.record('lifecycle',{reason:'browser_queue_gap',dropped});}let drained=false;for(let n=0;n<4000;n++){if(e.busy){await new Promise(r=>setTimeout(r,25));continue;}if(!await e.flush()){drained=true;break;}}if(!drained)throw Error('Выгрузка DEV ещё не завершена. Повторите сохранение.');}},
|
||||
storageError(){return pair.local.storageError;},
|
||||
close(){clearInterval(timer);if(pair.deferred)void pair.local.persist().catch(()=>{});else for(const e of [pair.remote,pair.local])void e.flush().catch(()=>{});if(sessions.get(url)===pair)sessions.delete(url);}};
|
||||
}
|
||||
|
||||
export function roverEvidenceForeground(){try{return typeof document!=='undefined'&&!document.hidden&&document.hasFocus();}catch{return false;}}
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
import {keyDemand,keysFor,type Demand,type RoverMode} from './roverInput';
|
||||
|
||||
// Some viewers retain closed dialogs in the DOM. Only rendered overlays block
|
||||
// operator input; visible overlays still revoke held keys before a new press.
|
||||
export function hasBlockingRoverOverlay(doc:Document){
|
||||
return Array.from(doc.querySelectorAll<HTMLElement>('[role=dialog],[role=listbox],[role=menu]')).some(element=>{
|
||||
if(!element.getClientRects().length)return false;
|
||||
const visibility=doc.defaultView!.getComputedStyle(element).visibility;
|
||||
return visibility!=='hidden'&&visibility!=='collapse';
|
||||
});
|
||||
}
|
||||
|
||||
// Key state is keydown/keyup, independent of OS autorepeat (which may
|
||||
// stop for the remaining key after releasing the last key in a chord).
|
||||
// Focus/visibility revoke input; Core and Node independently expire heartbeat.
|
||||
@@ -20,7 +30,7 @@ export function bindRoverHoldInput(scope:HTMLElement,mode:RoverMode,callbacks:{
|
||||
const editable='input,textarea,select,[contenteditable]:not([contenteditable="false"]),[role=dialog],[role=listbox],[role=menu]';
|
||||
const focused=()=>!doc.hidden&&doc.hasFocus()
|
||||
&&(scope.contains(doc.activeElement)||doc.activeElement===doc.body)
|
||||
&&!doc.activeElement?.closest(editable)&&!doc.querySelector('[role=dialog],[role=listbox],[role=menu]');
|
||||
&&!doc.activeElement?.closest(editable)&&!hasBlockingRoverOverlay(doc);
|
||||
const valid=()=>{
|
||||
if(closed)return false;
|
||||
if(!focused()){pause("focus_lost");return false;}
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import {pendingBrowserJournal} from './roverBrowserJournal';
|
||||
/** Bounded local diagnostic download. No request to the board or motion API. */
|
||||
export async function saveOperatorCapture(url:string,id:string,beforeSnapshot:()=>Promise<void>=async()=>{}){
|
||||
export async function saveOperatorCapture(url:string,id:string,beforeSnapshot:()=>Promise<void>=async()=>{},pendingSnapshot=pendingBrowserJournal){
|
||||
if(!/^[a-f0-9]{32}$/.test(id))throw Error('Запись изменилась.');
|
||||
await beforeSnapshot();
|
||||
const response=await fetch(url+'/diagnostics/local/export?capture_id='+id,{cache:'no-store',signal:AbortSignal.timeout(5000)});
|
||||
if(!response.ok)throw Error('Не удалось выгрузить замер компьютера. Запись сохранена в Core.');
|
||||
const blob=await response.blob();if(blob.size>4*1024*1024)throw Error('Размер замера превышает допустимый.');
|
||||
const blob=await response.blob();if(blob.size>33*1024*1024)throw Error('Размер замера превышает допустимый.');
|
||||
// The bounded snapshot uses the browser's normal download flow, including fullscreen.
|
||||
const href=URL.createObjectURL(blob),a=document.createElement('a');
|
||||
const pending=await pendingSnapshot(url,id);
|
||||
const download=pending?new Blob([blob,pending],{type:'application/x-ndjson'}):blob;
|
||||
const href=URL.createObjectURL(download),a=document.createElement('a');
|
||||
try{a.href=href;a.download=`rover-operator-${id}.jsonl`;document.body.append(a);a.click();}
|
||||
finally{a.remove();setTimeout(()=>URL.revokeObjectURL(href),1000);}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type {RoverState} from './useRoverControl';
|
||||
|
||||
export interface RoverArmSettings {currentA:number;speed:number;mode:'rpm'|'duty'}
|
||||
export interface RoverArmSettings {currentA:number;speed:number;mode:'rpm'|'duty';telemetryStopMs?:number}
|
||||
const MAX_RETRY_BACKOFF=3;
|
||||
const STABLE_CONNECTION_MS=30000;
|
||||
const MAX_READY_OBSERVATION_GAP_MS=1000;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {fleetRequest} from './useFleet';
|
||||
import {canSelectUplink,canSetFallback,fallbackPending,uplinkPending,uplinkReceipt,reconcileUplinkSelection,type BoardUplinkView} from './boardUplink';
|
||||
|
||||
export function useBoardUplink(vehicleId:string){
|
||||
const [value,setValue]=useState<BoardUplinkView|null>(null),[target,setTarget]=useState(''),[error,setError]=useState(''),[loadError,setLoadError]=useState(''),[busy,setBusy]=useState(false);
|
||||
const selected=useRef(''),previousCurrent=useRef(''),previousReceipt=useRef(''),generation=useRef(0);
|
||||
useEffect(()=>{const epoch=++generation.current;let live=true;let timer:ReturnType<typeof setTimeout>;const abort=new AbortController();
|
||||
selected.current='';previousCurrent.current='';previousReceipt.current='';setTarget('');setValue(null);setError('');setLoadError('');setBusy(false);
|
||||
const poll=async()=>{try{
|
||||
const next=await fleetRequest<BoardUplinkView>(`/${encodeURIComponent(vehicleId)}/uplink`,'GET',undefined,12000,abort.signal);
|
||||
if(!live||generation.current!==epoch)return;
|
||||
setValue(next);setLoadError('');
|
||||
const choice=reconcileUplinkSelection(selected.current,previousCurrent.current,next,previousReceipt.current);
|
||||
previousReceipt.current=uplinkReceipt(next);
|
||||
previousCurrent.current=next.current_id;selected.current=choice;setTarget(choice);
|
||||
}catch(e){if(live){setValue(old=>old?{...old,available:false}:null);setLoadError(e instanceof Error?e.message:'Нет сведений о подключении.');}}
|
||||
finally{if(live)timer=setTimeout(poll,2000);}};
|
||||
void poll();return()=>{live=false;abort.abort();clearTimeout(timer);};
|
||||
},[vehicleId]);
|
||||
const choose=(id:string)=>{selected.current=id;setTarget(id);setError('');};
|
||||
const connect=async()=>{
|
||||
if(busy||!value||!canSelectUplink(value,target))return;
|
||||
const epoch=generation.current;setBusy(true);setError('');
|
||||
try{
|
||||
const operation=await fleetRequest<NonNullable<BoardUplinkView['operation']>>(`/${encodeURIComponent(vehicleId)}/uplink`,'POST',{target,revision:value.revision,runtime:value.runtime,operation_id:crypto.randomUUID().replaceAll('-','')});
|
||||
if(generation.current===epoch)setValue(old=>old?{...old,operation}:old);
|
||||
}catch(e){if(generation.current===epoch)setError(e instanceof Error?e.message:'Нет подтверждения команды. Проверьте состояние подключения.');}
|
||||
finally{if(generation.current===epoch)setBusy(false);}
|
||||
};
|
||||
const setFallback=async(enabled:boolean)=>{
|
||||
if(busy||!canSetFallback(value)||!value?.fallback)return;
|
||||
const epoch=generation.current;setBusy(true);setError('');
|
||||
try{
|
||||
const operation=await fleetRequest<NonNullable<BoardUplinkView['operation']>>(`/${encodeURIComponent(vehicleId)}/uplink/fallback`,'PATCH',{enabled,revision:value.fallback.revision,runtime:value.runtime,operation_id:crypto.randomUUID().replaceAll('-','')});
|
||||
if(generation.current===epoch)setValue(old=>old?{...old,fallback_operation:operation}:old);
|
||||
}catch(e){if(generation.current===epoch)setError(e instanceof Error?e.message:'Настройка не сохранена.');}
|
||||
finally{if(generation.current===epoch)setBusy(false);}
|
||||
};
|
||||
return {value,target,choose,error:error||loadError,busy,connect,setFallback,
|
||||
fallbackPending:fallbackPending(value),canSetFallback:!busy&&canSetFallback(value),
|
||||
pending:uplinkPending(value),canConnect:!busy&&canSelectUplink(value,target)};
|
||||
}
|
||||
@@ -12,7 +12,7 @@ export interface RoverReading {
|
||||
values:{motor_current_a:number;input_current_a:number;input_voltage_v:number;erpm:number;duty:number;mos_temperature_c:number;fault_code:number};
|
||||
}
|
||||
export interface RoverState {
|
||||
fresh:boolean;controlling:boolean;
|
||||
fresh:boolean;controlling:boolean;control_fresh?:boolean;telemetry_age_ms?:number|null;telemetry_stop_ms?:number;
|
||||
snapshot:{supported?:boolean;control_modes?:string[];instance?:string;state?:string;session_id?:string|null;message?:string|null;release_confirmed?:boolean|null;devices?:RoverReading[];
|
||||
observation?:{initializing_devices:string[]};
|
||||
last_stop?:{session_id:string;state:string;message:string|null;recovered_at?:string};
|
||||
@@ -23,6 +23,7 @@ export interface RoverState {
|
||||
// wastes half of the 50 ms carrier opportunities during a network burst.
|
||||
const INTENT_INTERVAL_MS=50;
|
||||
const empty:RoverState={fresh:false,controlling:false,snapshot:{}};
|
||||
export const roverControlFresh=(s:RoverState)=>s.controlling?(s.control_fresh??s.fresh):s.fresh;
|
||||
const retryable=(e:unknown)=>!(e instanceof RoverHttpError)||e.status>=500||[408,429].includes(e.status)||['Управление завершено. Включите его заново.','Команда устарела до передачи на борт.','Канал управления бортом недоступен.','Дождитесь завершения предыдущего управления.'].includes(e.message);
|
||||
async function request<T>(url:string,body?:unknown,_keepalive=false):Promise<T>{
|
||||
const started=performance.now(),kind=url.endsWith('/arm')?'arm':body?'command':'view';let outcome:'ok'|'http'|'transport'='transport';
|
||||
@@ -76,10 +77,10 @@ export function useRoverControl(vehicleID:string,visible:boolean){
|
||||
},[url,stop,interrupt]);
|
||||
const setDemand=useCallback((next:Demand)=>{roverDevEvent(url,"demand",next);demand.current=next;void send();},[send]);
|
||||
const pauseInput=useCallback(()=>{demand.current={left:0,right:0};void send();},[send]);
|
||||
const start=useCallback(async({currentA,speed,mode}:RoverArmSettings)=>{
|
||||
const start=useCallback(async({currentA,speed,mode,telemetryStopMs=1000}:RoverArmSettings)=>{
|
||||
if(document.hidden||!document.hasFocus()||session.current||armPending.current)return false;const g=++generation.current;armPending.current=true;setError(null);setPending(true);
|
||||
try{
|
||||
const result=await request<{session_id:string}>(url+'/arm',{standstill_confirmed:true,current_a:currentA,...(mode==='duty'?{max_duty_percent:speed}:{max_erpm:speed})});
|
||||
const result=await request<{session_id:string}>(url+'/arm',{standstill_confirmed:true,current_a:currentA,telemetry_stop_ms:telemetryStopMs,...(mode==='duty'?{max_duty_percent:speed}:{max_erpm:speed})});
|
||||
if(g!==generation.current){void request(url+'/command',{session_id:result.session_id,sequence:1,left:0,right:0,stop:true},true).catch(()=>{});return false;}
|
||||
// Retire every read started before this acknowledgement, including reads
|
||||
// begun while POST /arm was pending. They describe the previous authority.
|
||||
@@ -91,9 +92,9 @@ export function useRoverControl(vehicleID:string,visible:boolean){
|
||||
}return false;}
|
||||
finally{if(g===generation.current){armPending.current=false;setPending(false);}}
|
||||
},[url,send,interrupt,stop]);
|
||||
const arm=useCallback((currentA:number,speed:number,mode:'rpm'|'duty'='rpm')=>{
|
||||
const arm=useCallback((currentA:number,speed:number,mode:'rpm'|'duty'='rpm',telemetryStopMs=1000)=>{
|
||||
if(session.current||armPending.current||recovery.current.waiting)return Promise.resolve(false);
|
||||
const settings={currentA,speed,mode};recovery.current.remember(settings,latest.current);return start(settings);
|
||||
const settings={currentA,speed,mode,telemetryStopMs};recovery.current.remember(settings,latest.current);return start(settings);
|
||||
},[start]);
|
||||
useEffect(()=>{
|
||||
if(!visible){stop();setState(empty);setError(null);setConnection('closed');return;}
|
||||
@@ -114,7 +115,7 @@ export function useRoverControl(vehicleID:string,visible:boolean){
|
||||
const previousStatus=armPending.current||recovery.current.previousStatus(value,ownedSession);
|
||||
const blocker=armPending.current?null:recovery.current.blocker(value,session.current);
|
||||
if(blocker){stop();setError(blocker);}
|
||||
else if(session.current&&(!value.fresh||!value.controlling||(value.snapshot.session_id===session.current&&value.snapshot.state==='stopping'))){
|
||||
else if(session.current&&(!roverControlFresh(value)||!value.controlling||(value.snapshot.session_id===session.current&&value.snapshot.state==='stopping'))){
|
||||
const reason=value.snapshot.message||(!value.fresh?'Управление прервано: нет свежих данных с борта.':value.snapshot.state==='receiver'?'Управление передано пульту.':'Управление прервано: борт перестал подтверждать команды. Повторите включение.');
|
||||
interrupt(reason);
|
||||
}
|
||||
@@ -132,7 +133,7 @@ export function useRoverControl(vehicleID:string,visible:boolean){
|
||||
window.addEventListener('blur',blur);window.addEventListener('focus',foreground);window.addEventListener('pagehide',stop);document.addEventListener('visibilitychange',hidden);
|
||||
return()=>{alive=false;clearInterval(timer);clearInterval(heartbeat);window.removeEventListener('blur',blur);window.removeEventListener('focus',foreground);window.removeEventListener('pagehide',stop);document.removeEventListener('visibilitychange',hidden);stop();releaseTransport();roverTiming.clear();};
|
||||
},[url,visible,stop,send,pauseInput,start,interrupt]);
|
||||
const ready=armed&&state.fresh&&state.snapshot.session_id===session.current&&['ready','driving'].includes(state.snapshot.state??'');
|
||||
const ready=armed&&roverControlFresh(state)&&state.snapshot.session_id===session.current&&['ready','driving'].includes(state.snapshot.state??'');
|
||||
const canArm=!recovering&&state.fresh&&state.snapshot.supported===true&&!state.controlling&&!['preparing','ready','driving','stopping'].includes(state.snapshot.state??'');
|
||||
return {state,armed,pending,error,connection,connecting:connection==='connecting',controlMode,recovering,canArm,arm,stop,pauseInput,setDemand,setInputGuard,ready,clearError:()=>setError(null)};
|
||||
}
|
||||
|
||||
@@ -3,20 +3,20 @@ import {connectRoverEvidence,roverDevEvent} from './roverDevEvents';
|
||||
import {saveRoverLog} from './roverLogSave';
|
||||
import {saveOperatorCapture} from './roverOperatorCapture';
|
||||
export type LocalCaptureOptions={enabled:boolean;preview:boolean};
|
||||
export type DevOptions={live:boolean;core_trace:boolean;motor_samples:boolean;network:boolean;live_kbps:number;core_kbps:number};
|
||||
export const localDevOptions:DevOptions={live:false,core_trace:false,motor_samples:true,network:true,live_kbps:16,core_kbps:16};
|
||||
export type DevOptions={passive:boolean;live:boolean;core_trace:boolean;motor_samples:boolean;network:boolean;router:boolean;system:boolean;live_kbps:number;core_kbps:number};
|
||||
export const localDevOptions:DevOptions={passive:true,live:false,core_trace:false,motor_samples:true,network:true,router:true,system:true,live_kbps:16,core_kbps:16};
|
||||
export type DevRow={record_sequence:number;source:string;event:string;at_utc:string;record?:DevRow;[key:string]:unknown};
|
||||
export type DevState={local_capture?:{id:string|null;active:boolean;preview?:boolean;dropped?:number;sequence?:number};options?:DevOptions;options_supported?:boolean;id:string|null;active:boolean;closing:boolean;sequence:number;frames:DevRow[];
|
||||
export type LocalCapture={id:string|null;active:boolean;started_at?:string;preview?:boolean;dropped?:number;sequence?:number;storage?:{persistent?:boolean;written?:number;dropped?:number;error?:string|null;closed?:boolean}};
|
||||
export type DevState={local_capture?:LocalCapture;local_history?:LocalCapture[];options?:DevOptions;options_supported?:boolean;sources_supported?:boolean;passive_supported?:boolean;passive_confirmed?:boolean;id:string|null;active:boolean;closing:boolean;sequence:number;frames:DevRow[];
|
||||
node?:{active?:boolean;transport_error?:string;storage?:{file?:string;closed:boolean;written:number;dropped:number;error?:string}}};
|
||||
const empty:DevState={id:null,active:false,closing:false,sequence:0,frames:[]};
|
||||
export function useRoverDiagnostics(vehicleID:string){
|
||||
const url=`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`;
|
||||
const [state,setState]=useState<DevState>(empty),[rows,setRows]=useState<DevRow[]>([]);
|
||||
const [pending,setPending]=useState(false),[saving,setSaving]=useState(false),[error,setError]=useState<string|null>(null);
|
||||
const savedLocal=useRef<string|null>(null);
|
||||
const evidence=useRef<ReturnType<typeof connectRoverEvidence>|null>(null),latest=useRef(empty);
|
||||
const accept=useCallback((value:DevState)=>{
|
||||
const previous=latest.current;latest.current=value;setState(value);evidence.current?.set(value.active&&value.options?.core_trace!==false?value.id:null,value.local_capture?.active?value.local_capture.id:null,value.local_capture?.preview!==false);
|
||||
const previous=latest.current;latest.current=value;setState(value);evidence.current?.set(value.active&&value.options?.core_trace!==false?value.id:null,value.local_capture?.active?value.local_capture.id:null,value.local_capture?.preview!==false,value.options?.passive===true);
|
||||
const failure=value.node?.storage?.error;
|
||||
if(failure&&(previous.id!==value.id||previous.node?.storage?.error!==failure))
|
||||
setError(failure==='CaptureInterrupted'?'DEV-запись прервана перезапуском борта. Сохранившийся файл оставлен на борту. Можно начать новую запись.':failure==='CaptureNotFound'?'Предыдущая DEV-запись на борту не найдена. Можно начать новую запись.':`Запись остановлена: ${failure}. Файл может быть неполным.`);
|
||||
@@ -25,7 +25,7 @@ export function useRoverDiagnostics(vehicleID:string){
|
||||
useEffect(()=>{
|
||||
let alive=true,busy=false;latest.current=empty;setState(empty);setRows([]);
|
||||
const client=connectRoverEvidence(url);evidence.current=client;
|
||||
const poll=async()=>{if(busy)return;busy=true;const started=performance.now();try{
|
||||
const poll=async()=>{const storageError=client.storageError();if(storageError&&alive)setError(storageError);if(busy||(latest.current.active&&latest.current.options?.passive&&latest.current.passive_confirmed&&!latest.current.closing))return;busy=true;const started=performance.now();try{
|
||||
const r=await fetch(url+'/diagnostics?after='+latest.current.sequence,{cache:'no-store',signal:AbortSignal.timeout(3000)});
|
||||
if(!r.ok)throw Error();const value:DevState=await r.json();
|
||||
if(performance.now()-started>=200)roverDevEvent(url,'request',{action:'diagnostics_view',outcome:'slow',elapsed_ms:performance.now()-started});if(alive){accept(value);setError(current=>current==='Нет связи с Mission Core. Файл остаётся на борту.'?null:current);}
|
||||
@@ -39,7 +39,6 @@ export function useRoverDiagnostics(vehicleID:string){
|
||||
try{
|
||||
const enabled=!latest.current.active;if(!enabled)await evidence.current?.flush();
|
||||
const previousID=latest.current.local_capture?.id;
|
||||
if(enabled&&local?.enabled&&previousID&&savedLocal.current!==previousID)throw Error("Сначала сохраните предыдущий замер компьютера в окне логов.");
|
||||
const r=await fetch(url+'/diagnostics',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(enabled?{enabled,options:options??localDevOptions,...(local?{local_options:{...local,previous_id:previousID??null}}:{})}:{enabled})});
|
||||
const value=await r.json();if(!r.ok)throw Error(value.detail??'Не удалось переключить DEV.');accept(value);return enabled;
|
||||
}catch(e){setError(e instanceof Error?e.message:'Не удалось переключить DEV.');return false;}finally{setPending(false);}
|
||||
@@ -50,9 +49,9 @@ export function useRoverDiagnostics(vehicleID:string){
|
||||
catch(e){if(!(e instanceof DOMException&&e.name==='AbortError'))setError(e instanceof Error?e.message:'Не удалось сохранить файл.');}
|
||||
finally{setSaving(false);}
|
||||
},[url,saving]);
|
||||
const saveLocal=useCallback(async()=>{
|
||||
const id=latest.current.local_capture?.id;if(!id||saving)return;setSaving(true);setError(null);
|
||||
try{await saveOperatorCapture(url,id,async()=>{await evidence.current?.flush();});if(latest.current.local_capture?.id===id&&!latest.current.local_capture.active)savedLocal.current=id;}
|
||||
const saveLocal=useCallback(async(captureID?:string)=>{
|
||||
const id=captureID??latest.current.local_capture?.id;if(!id||saving)return;setSaving(true);setError(null);
|
||||
try{await saveOperatorCapture(url,id,async()=>{if(latest.current.local_capture?.active)await evidence.current?.flush();});}
|
||||
catch(e){if(!(e instanceof DOMException&&e.name==='AbortError'))setError(e instanceof Error?e.message:'Не удалось сохранить замер.');}
|
||||
finally{setSaving(false);}
|
||||
},[url,saving]);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user