Compare commits

...
48 Commits
Author SHA1 Message Date
DCCONSTRUCTIONS 7e257275ab Record X4 checkpoint and Ops implementation report
Link the committed Core/Design Guideline pair to MISSIONCOR-77 and preserve
MISSIONCOR-76 baseline through an appended report. Record successful MCP
readback, qualified source comparison and remaining hardware acceptance.
2026-09-10 09:25:12 +03:00
DCCONSTRUCTIONS a3c15e11e9 Add packaged Insta360 X4 integration and recover paired Node channels
Discover independent camera instances and prepare their versioned runtime
from Node or remote Core. Add isolated SDK workers, camera controls, raw
dual-fisheye WebRTC preview, and shared action/region loading states.

Recover existing Node bindings over known Tailscale addresses after a Core
LAN address change. Preserve identities and trust, pin both peers, migrate
endpoints with revision checks, and require real heartbeats for online status.
Fix the Python client certificate profile for Go X509 verification.

Pin Design Guideline 8c53f73 and retain installer/build/acceptance history.
Node 0.8.19 is installed; X4 0.1.3-3 is bundled but hardware activation is pending.

Validation: qualified DG/Node builds and Go race tests; 31 fleet tests;
Python-to-Go certificate interoperability and live tailnet recovery with five
fresh heartbeats; prior 38 X4 tests and bounded remote WebRTC acceptance.
Clean-OS, replug/power autonomy, local X4 video and long-run stability remain open.
2026-09-10 09:21:24 +03:00
DCCONSTRUCTIONS 54a85fdf50 Record installed R19 recovery and onboard K1 acceptance 2026-09-08 11:01:59 +03:00
DCCONSTRUCTIONS 14f8375713 Repair monitor cluster upgrade without blocking K1 package configuration 2026-09-08 10:44:27 +03:00
DCCONSTRUCTIONS 6492ebcdee Record R18 evidence and retain signed telemetry values in plots 2026-09-08 01:53:30 +03:00
DCCONSTRUCTIONS e57511f975 Keep K1 runtime payload manifest in canonical order 2026-09-08 01:41:27 +03:00
DCCONSTRUCTIONS f0802d2713 Fix onboard WebKit preview and archive board telemetry locally 2026-09-08 01:37:52 +03:00
DCCONSTRUCTIONS d8afb61229 Record successful Node R17 installation on owner Ubuntu board 2026-09-07 23:28:46 +03:00
DCCONSTRUCTIONS 421a8c515a Record R17 package validation and pending onboard transfer 2026-09-07 23:03:11 +03:00
DCCONSTRUCTIONS a23c5b2005 Reuse canonical home and settings on Node and admit local K1 viewer 2026-09-07 22:55:13 +03:00
DCCONSTRUCTIONS 1832943558 Record verified Ops publication of onboard K1 laboratory checkpoint 2026-09-07 21:50:38 +03:00
DCCONSTRUCTIONS cc90709919 Record owner-confirmed onboard K1 Bridge laboratory checkpoint 2026-09-07 21:43:19 +03:00
DCCONSTRUCTIONS ee5d760c30 Verify R16 onboard installation and service health 2026-09-07 21:27:40 +03:00
DCCONSTRUCTIONS 0e9faa6824 Record inspected R16 artifacts and pending onboard acceptance 2026-09-07 21:22:41 +03:00
DCCONSTRUCTIONS c6693d6f44 Retain K1 connection between scans and admit the next named acquisition 2026-09-07 21:13:17 +03:00
DCCONSTRUCTIONS ed9a77ba73 Record verified R15 installation after owner restart 2026-09-07 20:16:42 +03:00
DCCONSTRUCTIONS 7dd2c1c836 Record verified R15 packages and pending onboard acceptance 2026-09-07 20:13:37 +03:00
DCCONSTRUCTIONS 762d77ef95 Unify K1 discovery ownership and verification across enrollment paths 2026-09-07 20:04:46 +03:00
DCCONSTRUCTIONS 9c4d70b0e9 Record R14 public artifacts and staged installation scope 2026-09-07 19:04:52 +03:00
DCCONSTRUCTIONS eed53dbc0b Fix onboard K1 enrollment continuity and share named acquisition preparation 2026-09-07 18:53:38 +03:00
DCCONSTRUCTIONS 4f333fc11c Record verified R13 installation on onboard computer 2026-09-07 17:59:36 +03:00
DCCONSTRUCTIONS 35a517f921 Record R13 artifact provenance and pending installation acceptance 2026-09-07 17:54:13 +03:00
DCCONSTRUCTIONS 9bba44f7c4 Preserve onboard preview recordings across backpressure and share the complete spatial scene 2026-09-07 17:47:10 +03:00
DCCONSTRUCTIONS 9b6534287a Record R12 update artifacts and pending clean-cache acceptance 2026-09-07 16:53:32 +03:00
DCCONSTRUCTIONS 9e03404f23 Admit onboard camera preview only after its acquisition producer is ready 2026-09-07 16:44:38 +03:00
DCCONSTRUCTIONS fa8ac760a1 Share the K1 live scene template and preserve idle media channels 2026-09-07 16:38:39 +03:00
DCCONSTRUCTIONS 309bdf759e Confirm installed K1 R11 runtime and authority availability 2026-09-07 15:57:53 +03:00
DCCONSTRUCTIONS ff00851216 Record staged K1 R11 artifact and acceptance gate 2026-09-07 15:54:38 +03:00
DCCONSTRUCTIONS ad24518b71 Refresh selected BlueZ path before K1 GATT operations 2026-09-07 15:50:06 +03:00
DCCONSTRUCTIONS 7ce09eabcd Record R10 release hashes and remaining acceptance gates 2026-09-07 15:32:56 +03:00
DCCONSTRUCTIONS 92b60de945 Preserve RRD preview frames and clarify onboard K1 status 2026-09-07 15:27:13 +03:00
DCCONSTRUCTIONS 67398fef10 Record staged R9 packages and pending installed acceptance 2026-09-07 14:55:28 +03:00
DCCONSTRUCTIONS a93f1f1b8b Accept systemd credential delivery and clarify manual K1 control 2026-09-07 14:44:46 +03:00
DCCONSTRUCTIONS 102e93796b Record staged K1 causal diagnostics release R8 2026-09-07 14:16:18 +03:00
DCCONSTRUCTIONS 4f715e41d2 Preserve native K1 error causes and distinguish Wi-Fi actions 2026-09-07 14:11:34 +03:00
DCCONSTRUCTIONS 8f17a7e282 Confirm installed Linux route contract fix R7 2026-09-07 13:55:50 +03:00
DCCONSTRUCTIONS 7187fd86bd Record prepared Linux route contract fix release R7 2026-09-07 13:53:03 +03:00
DCCONSTRUCTIONS e6521e855a Fix Linux route probe contract and expose K1 verification after Wi-Fi apply 2026-09-07 13:46:01 +03:00
DCCONSTRUCTIONS 06d216ac4a Record installed wireless steps and diagnostic release R6 2026-09-07 13:35:25 +03:00
DCCONSTRUCTIONS d7986cb62f Group onboard wireless steps and trace journalled Bluetooth failures 2026-09-07 13:27:21 +03:00
DCCONSTRUCTIONS a0732386f1 docs(node): record R5 package and pending Ubuntu authentication 2026-09-07 13:08:01 +03:00
DCCONSTRUCTIONS 5c4546a2a6 fix(node): clarify wireless enrollment and restore active K1 after upgrade 2026-09-07 13:02:28 +03:00
DCCONSTRUCTIONS ef1c1f50de docs(k1): record successful onboard Bluetooth discovery 2026-09-07 12:46:14 +03:00
DCCONSTRUCTIONS 2f80507bc0 docs(k1): record R4 onboard installation and pending hardware acceptance 2026-09-07 12:44:22 +03:00
DCCONSTRUCTIONS d2dbfc9c85 fix(k1): translate onboard operation identities at plugin boundary 2026-09-07 12:34:48 +03:00
DCCONSTRUCTIONS 3dffe39c89 Record installation of the onboard discovery fix 2026-09-07 12:20:27 +03:00
DCCONSTRUCTIONS 77acb377e2 Fix onboard BLE admission and stage wireless device enrollment 2026-09-07 12:11:48 +03:00
DCCONSTRUCTIONS 2fdf1d3cc4 Record private K1 installer release and Mini installation acceptance 2026-09-07 11:56:32 +03:00
287 changed files with 23631 additions and 4388 deletions
+34
View File
@@ -62,6 +62,40 @@ and the boundary between Mission Core and vendor-specific integration code.
- Synthetic or explicitly redacted fixtures may be committed under - Synthetic or explicitly redacted fixtures may be committed under
`tests/fixtures/`. `tests/fixtures/`.
## Insta360 and clean-host installation — owner requirement, 2026-09-08
- The current X4 starting point is USB enumeration only. SDK installation,
camera initialization and live video have not been accepted.
- Every Ubuntu change needed for Insta360 must execute through the shipped
installer or the application's versioned device-preparation workflow from
the first board experiment. Do not repair the board with an ad-hoc apt/pip
install, copied library, chmod, environment override, service edit or root
invocation and promise to package it later. Fix the product artifact first,
then rerun that artifact. Read-only engineering inspection remains allowed.
- Document every relevant action and its before/after evidence in
`docs/node/07_INSTA360_X4_INSTALLATION_LEDGER.md`; record the artifact version,
owning installer step, dependencies, idempotency, failure behavior and rollback.
Keep private logs/identifiers/media out of Git and redact their public summary.
- A working prepared Mini is not clean-Ubuntu acceptance. Qualify dependency
closure on the declared clean OS image and actual USB operation separately;
installer, preparation and GUI acceptance must use the same shipped code.
- X4 is operator live video and camera control (settings, photo, recording
start/stop and file access), per the owner’s subsequent scope expansion.
Preview and recording are separate operations. No stitching, AI, navigation
or vehicle-control integration is admitted. Model support and physical device instances are separate: several
cameras of the same model must retain independent identity and lifecycle.
- Follow the scoped implementation plan in
`docs/node/06_INSTA360_X4_AND_MULTI_CAMERA_PLAN.md`. It is a proposed plan,
not evidence that SDK compatibility, hardware capacity or installation passed.
- Subsequent owner direction: the existing Ubuntu Mini is the available build
and qualification machine; do not depend on Worker 006 or another host for
this X4 work. Its existing GCC may compile through a versioned build artifact
in bounded temporary staging. This is a build step, not runtime installation:
no system changes, SDK execution or camera access during compilation. The
final installer must carry the compiled payload so a clean operator Ubuntu
does not inherit an undeclared compiler/build-cache prerequisite. All board
staging/build/install/test actions remain documented and artifact-owned.
## Implementation order ## Implementation order
Follow the gates in `docs/01_IMPLEMENTATION_PLAN.md`. Do not build heavy Follow the gates in `docs/01_IMPLEMENTATION_PLAN.md`. Do not build heavy
+5 -206
View File
@@ -1,3 +1,5 @@
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 { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { import {
AdminNavigationPanel, AdminNavigationPanel,
@@ -5,15 +7,11 @@ import {
ApplicationPanel, ApplicationPanel,
ApplicationShell, ApplicationShell,
Button, Button,
Checker,
ColorField,
ControlRow, ControlRow,
HeaderNavigation, HeaderNavigation,
HeaderProfile, HeaderProfile,
Icon, Icon,
Inspector, Inspector,
RangeControl,
Select,
StatusBadge, StatusBadge,
TextField, TextField,
UserProfileMenu, UserProfileMenu,
@@ -66,8 +64,6 @@ import {
import { backendLabel, localConnectionPhaseLabel, phaseTone } from "./presentation"; import { backendLabel, localConnectionPhaseLabel, phaseTone } from "./presentation";
import { import {
defaultSceneSettings, defaultSceneSettings,
type PointColorMode,
type PointPalette,
type SceneSettings, type SceneSettings,
} from "./sceneSettings"; } from "./sceneSettings";
import { DeviceWorkspace } from "./workspaces/DeviceWorkspace"; import { DeviceWorkspace } from "./workspaces/DeviceWorkspace";
@@ -77,22 +73,6 @@ import "./styles/scene-windows.css";
type SceneToolWindowId = "sources" | "display" | "layers"; type SceneToolWindowId = "sources" | "display" | "layers";
const viewerSettingsQuietPeriodMs = 750; const viewerSettingsQuietPeriodMs = 750;
const colorModeOptions: Array<{ value: PointColorMode; label: string; description: string }> = [
{ value: "intensity", label: "Интенсивность", description: "Значение отражённого сигнала" },
{ value: "height", label: "Высота Z", description: "Градиент по вертикальной координате" },
{ value: "distance", label: "Расстояние", description: "Дальность точки от сенсора" },
{ value: "rgb", label: "RGB", description: "Цвет, если он присутствует в данных" },
{ value: "class", label: "Класс", description: "Категория внешнего модуля восприятия" },
];
const paletteOptions: Array<{ value: PointPalette; label: string; description: string }> = [
{ value: "turbo", label: "Turbo", description: "Контрастный спектральный градиент" },
{ value: "viridis", label: "Viridis", description: "Равномерный перцептивный градиент" },
{ value: "plasma", label: "Plasma", description: "Тёплый контрастный градиент" },
{ value: "grayscale", label: "Серый", description: "Монохромное отображение" },
{ value: "custom", label: "Свой цвет", description: "Один назначенный цвет" },
];
interface LivePerceptionLayers { interface LivePerceptionLayers {
detections2d: boolean; detections2d: boolean;
segmentation: boolean; segmentation: boolean;
@@ -1029,132 +1009,8 @@ export default function App() {
onPointerDown={() => activateSceneWindow("display")} onPointerDown={() => activateSceneWindow("display")}
onClose={() => closeSceneWindow("display")} onClose={() => closeSceneWindow("display")}
> >
<Inspector <SceneDisplayControls displayDraft={displayDraft} stageDisplayPatch={stageDisplayPatch}
defaultOpen={["points"]} commitDisplayPatch={commitDisplayPatch} flushDisplaySettings={flushDisplaySettings} replayPresented={replayPresented}/>
singleOpen
sections={[
{
id: "points",
label: "Облако точек",
description: "Размер и способ окрашивания",
content: (
<div className="inspector-control-stack">
<div
className="scene-settings-commit-field"
onPointerUp={flushDisplaySettings}
onKeyUp={flushDisplaySettings}
onBlur={flushDisplaySettings}
>
<RangeControl
label="Размер точки"
value={displayDraft.pointSize}
min={0.5}
max={12}
step={0.5}
formatValue={(value) => `${value.toFixed(1)} пкс`}
onChange={(pointSize) => stageDisplayPatch({ pointSize })}
/>
</div>
<div className="scene-settings-commit-field" onBlur={flushDisplaySettings}>
<ControlRow label="Атрибут цвета">
<Select
variant="split"
label="Атрибут цвета"
value={displayDraft.colorMode}
options={colorModeOptions}
onChange={(colorMode) => stageDisplayPatch({ colorMode })}
/>
</ControlRow>
</div>
<div className="scene-settings-commit-field" onBlur={flushDisplaySettings}>
<ControlRow label="Палитра">
<Select
variant="split"
label="Палитра"
value={displayDraft.palette}
options={paletteOptions}
onChange={(palette) => stageDisplayPatch({ palette })}
/>
</ControlRow>
</div>
{displayDraft.palette === "custom" || displayDraft.colorMode === "class" ? (
<div
className="scene-settings-commit-field"
onPointerUp={flushDisplaySettings}
onKeyUp={flushDisplaySettings}
onBlur={flushDisplaySettings}
>
<ControlRow label="Цвет точек">
<ColorField
label="Цвет точек"
value={displayDraft.customColor}
onChange={(customColor) => stageDisplayPatch({ customColor })}
/>
</ControlRow>
</div>
) : null}
{replayPresented ? (
<p className="scene-window-note">
Первый новый режим читает индекс архивных точек. Следующие палитры
переключаются из подготовленного цветового кэша без переэкспорта геометрии.
</p>
) : null}
</div>
),
},
{
id: "history",
label: "Накопление и время",
description: "История облака и траектория",
content: (
<div className="inspector-control-stack">
<div
className="scene-settings-commit-field"
onPointerUp={flushDisplaySettings}
onKeyUp={flushDisplaySettings}
onBlur={flushDisplaySettings}
>
<RangeControl
label="Окно накопления"
value={displayDraft.accumulationSeconds}
min={0}
max={120}
step={1}
formatValue={(value) => (value === 0 ? "Только кадр" : `${value} с`)}
onChange={(accumulationSeconds) => stageDisplayPatch({ accumulationSeconds })}
/>
</div>
<div className="nodedc-field">
<span className="nodedc-field__description">Линия пути устройства в координатах сцены</span>
<Checker
checked={displayDraft.showTrajectory}
label="Показывать траекторию"
onChange={(showTrajectory) => commitDisplayPatch({ showTrajectory })}
/>
</div>
</div>
),
},
{
id: "scene",
label: "Окружение сцены",
description: "Сетка, подписи и камеры",
content: (
<div className="inspector-control-stack">
<Checker checked={displayDraft.showGrid} label="Сетка и оси" onChange={(showGrid) => commitDisplayPatch({ showGrid })} />
<div className="nodedc-field">
<span className="nodedc-field__description">Появятся после подключения семантических сущностей</span>
<Checker checked={false} disabled label="Подписи сущностей" onChange={() => undefined} />
</div>
<div className="nodedc-field">
<span className="nodedc-field__description">Камерный канал пока не подключён</span>
<Checker checked={false} disabled label="Области обзора камер" onChange={() => undefined} />
</div>
</div>
),
},
]}
/>
</Window> </Window>
<Window <Window
@@ -1180,64 +1036,7 @@ export default function App() {
</span> </span>
<p>Структура повторяет продуктовые сущности, а не внутренние панели визуального движка.</p> <p>Структура повторяет продуктовые сущности, а не внутренние панели визуального движка.</p>
</div> </div>
<Inspector <SceneLayerControls sceneSettings={sceneSettings} pending={runtime.pendingAction === "viewer"} applyScenePatch={applyScenePatch}/>
defaultOpen={["geometry"]}
singleOpen
sections={[
{
id: "geometry",
label: "Геометрия",
description: "Облако точек и путь",
content: (
<div className="inspector-control-stack">
<div className="nodedc-field">
<span className="nodedc-field__description">Основной поток геометрии лидара</span>
<Checker disabled={runtime.pendingAction === "viewer"} checked={sceneSettings.showPoints} label="Облако точек" onChange={(showPoints) => void applyScenePatch({ showPoints })} />
</div>
<div className="nodedc-field">
<span className="nodedc-field__description">Положение и ориентация устройства во времени</span>
<Checker disabled={runtime.pendingAction === "viewer"} checked={sceneSettings.showTrajectory} label="Траектория" onChange={(showTrajectory) => void applyScenePatch({ showTrajectory })} />
</div>
</div>
),
},
{
id: "frames",
label: "Координаты и камеры",
description: "Преобразования и области обзора",
content: (
<div className="inspector-control-stack">
<Checker disabled={runtime.pendingAction === "viewer"} checked={sceneSettings.showGrid} label="Сетка и оси" onChange={(showGrid) => void applyScenePatch({ showGrid })} />
<div className="nodedc-field">
<span className="nodedc-field__description">Камерный канал пока не подключён</span>
<Checker checked={false} disabled label="Области обзора камер" onChange={() => undefined} />
</div>
</div>
),
},
{
id: "perception",
label: "Объекты и маски",
description: "Ожидают внешние обработчики",
content: (
<div className="inspector-control-stack">
<div className="nodedc-field">
<span className="nodedc-field__description">Внешний обработчик не подключён</span>
<Checker checked={false} disabled label="Рамки 2D и 3D" onChange={() => undefined} />
</div>
<div className="nodedc-field">
<span className="nodedc-field__description">Внешний обработчик не подключён</span>
<Checker checked={false} disabled label="Маски сегментации" onChange={() => undefined} />
</div>
<div className="nodedc-field">
<span className="nodedc-field__description">Внешний обработчик не подключён</span>
<Checker checked={false} disabled label="Ключевые точки и треки" onChange={() => undefined} />
</div>
</div>
),
},
]}
/>
</Window> </Window>
</> </>
); );
@@ -1,92 +1 @@
import { useEffect, useMemo, useState } from "react"; export { EnvironmentBackgroundMedia } from "@nodedc/ui-react";
import type {
EnvironmentBackground,
EnvironmentMediaItem,
} from "../core/environment/environmentSettings";
type ReadyEnvironmentMediaItem = EnvironmentMediaItem & {
url: string;
mediaKind: "image" | "video";
};
function isReadyMediaItem(
item: EnvironmentMediaItem,
): item is ReadyEnvironmentMediaItem {
return Boolean(item.url && item.mediaKind);
}
export function EnvironmentBackgroundMedia({
background,
}: {
background: EnvironmentBackground;
}) {
const items = useMemo(
() => background.items.filter(isReadyMediaItem),
[background.items],
);
const playlistIdentity = items.map((item) => `${item.id}:${item.url}`).join("|");
const [activeIndex, setActiveIndex] = useState(0);
const [failedIds, setFailedIds] = useState<Set<string>>(new Set());
const playableItems = items.filter((item) => !failedIds.has(item.id));
const activeItem = playableItems[activeIndex] ?? playableItems[0] ?? null;
useEffect(() => {
setActiveIndex(0);
setFailedIds(new Set());
}, [playlistIdentity]);
useEffect(() => {
if (
!background.enabled
|| !activeItem
|| activeItem.mediaKind !== "image"
|| playableItems.length < 2
) {
return;
}
const timer = window.setTimeout(() => {
setActiveIndex((current) => (current + 1) % playableItems.length);
}, background.imageDurationSeconds * 1_000);
return () => window.clearTimeout(timer);
}, [
activeItem,
background.enabled,
background.imageDurationSeconds,
playableItems.length,
]);
if (!background.enabled || !activeItem) return null;
return (
<div className="landing-stage__media" aria-hidden="true">
{activeItem.mediaKind === "video" ? (
<video
key={activeItem.url}
src={activeItem.url}
autoPlay
muted
loop={playableItems.length === 1}
playsInline
onEnded={() => setActiveIndex((current) => (
(current + 1) % playableItems.length
))}
onError={() => {
setFailedIds((current) => new Set(current).add(activeItem.id));
setActiveIndex(0);
}}
/>
) : (
<img
key={activeItem.url}
src={activeItem.url}
alt=""
onError={() => {
setFailedIds((current) => new Set(current).add(activeItem.id));
setActiveIndex(0);
}}
/>
)}
</div>
);
}
@@ -1,248 +1 @@
import { useEffect, useMemo, useRef, useState } from "react"; export { EnvironmentMediaPlaylistEditor } from "@nodedc/ui-react";
import {
Icon,
IconButton,
MediaSourceField,
RangeControl,
SortableList,
} from "@nodedc/ui-react";
import {
appendEnvironmentMediaItem,
inferEnvironmentMediaKind,
maxEnvironmentMediaItems,
removeEnvironmentMediaItem,
type EnvironmentBackground,
type EnvironmentMediaItem,
type EnvironmentSurfaceId,
type UploadedEnvironmentMedia,
} from "../core/environment/environmentSettings";
interface EnvironmentMediaPlaylistEditorProps {
surfaceId: EnvironmentSurfaceId;
background: EnvironmentBackground;
disabled: boolean;
error: string | null;
onChange: (background: EnvironmentBackground) => void;
onBusyChange: (busy: boolean) => void;
onUpload: (
surfaceId: EnvironmentSurfaceId,
itemId: string,
file: File,
) => Promise<UploadedEnvironmentMedia>;
}
const acceptedEnvironmentMedia = [
"image/png",
"image/jpeg",
"image/gif",
"image/webp",
"image/avif",
"video/mp4",
"video/webm",
"video/quicktime",
".png",
".jpg",
".jpeg",
".gif",
".webp",
".avif",
".mp4",
".webm",
".mov",
].join(",");
function patchItem(
background: EnvironmentBackground,
itemId: string,
patch: Partial<EnvironmentMediaItem>,
): EnvironmentBackground {
return {
...background,
items: background.items.map((item) => (
item.id === itemId ? { ...item, ...patch } : item
)),
};
}
export function EnvironmentMediaPlaylistEditor({
surfaceId,
background,
disabled,
error,
onChange,
onBusyChange,
onUpload,
}: EnvironmentMediaPlaylistEditorProps) {
const [uploadingIds, setUploadingIds] = useState<Set<string>>(new Set());
const [itemErrors, setItemErrors] = useState<Record<string, string>>({});
const backgroundRef = useRef(background);
backgroundRef.current = background;
const displayedItems = useMemo(
() => [...background.items].reverse(),
[background.items],
);
useEffect(() => {
onBusyChange(uploadingIds.size > 0);
}, [onBusyChange, uploadingIds.size]);
useEffect(() => () => onBusyChange(false), [onBusyChange]);
const setItemError = (itemId: string, message?: string) => {
setItemErrors((current) => {
const next = { ...current };
if (message) next[itemId] = message;
else delete next[itemId];
return next;
});
};
const uploadFile = async (itemId: string, file?: File) => {
if (!file) return;
setUploadingIds((current) => new Set(current).add(itemId));
setItemError(itemId);
try {
const uploaded = await onUpload(surfaceId, itemId, file);
onChange(patchItem(backgroundRef.current, itemId, {
source: "file",
url: uploaded.url,
mediaKind: uploaded.mediaKind,
fileName: uploaded.fileName,
}));
} catch (reason) {
setItemError(
itemId,
reason instanceof Error
? reason.message
: "Не удалось загрузить медиаконтент.",
);
} finally {
setUploadingIds((current) => {
const next = new Set(current);
next.delete(itemId);
return next;
});
}
};
return (
<div className="environment-media-playlist">
<div className="environment-media-playlist__head">
<div>
<span>Видео / картинка</span>
<p>MP4, WebM, MOV, PNG, JPEG, GIF, WebP или AVIF · до 256 МБ.</p>
</div>
<IconButton
label="Добавить медиаконтент"
disabled={disabled || background.items.length >= maxEnvironmentMediaItems}
onClick={() => onChange(appendEnvironmentMediaItem(background))}
>
<Icon name="plus" />
</IconButton>
</div>
{displayedItems.length ? (
<SortableList
items={displayedItems}
getId={(item) => item.id}
className="environment-media-playlist__items"
onReorder={(items) => onChange({
...background,
items: [...items].reverse(),
})}
>
{(item, { handle }) => {
const playbackIndex = background.items.findIndex(
(candidate) => candidate.id === item.id,
);
return (
<div className="environment-media-playlist__item">
<MediaSourceField
label={`Медиаконтент ${String(playbackIndex + 1).padStart(2, "0")}`}
kindLabel={item.mediaKind ?? "media"}
source={item.source}
url={item.url ?? ""}
fileName={item.fileName}
uploading={uploadingIds.has(item.id)}
previewSrc={item.url}
previewKind={item.mediaKind}
accept={acceptedEnvironmentMedia}
path={`${surfaceId}.background.items[${playbackIndex}] → server environment media`}
hint="Файл сохраняется в Mission Core data root. URL должен вести прямо на media по HTTP(S)."
error={itemErrors[item.id] ?? (
playbackIndex === background.items.length - 1 ? error : null
)}
onSourceChange={(source) => {
if (source === item.source) return;
setItemError(item.id);
onChange(patchItem(background, item.id, {
source,
url: null,
mediaKind: null,
fileName: null,
}));
}}
onUrlChange={(url) => {
setItemError(item.id);
onChange(patchItem(background, item.id, {
source: "url",
url: url || null,
mediaKind: url ? inferEnvironmentMediaKind(url) : null,
fileName: null,
}));
}}
onFileChange={(file) => void uploadFile(item.id, file)}
/>
<div className="environment-media-playlist__item-actions">
<IconButton
label={`Удалить медиаконтент ${playbackIndex + 1}`}
disabled={disabled || uploadingIds.has(item.id)}
onClick={() => {
setItemError(item.id);
onChange(removeEnvironmentMediaItem(background, item.id));
}}
>
<Icon name="trash" />
</IconButton>
{handle}
</div>
</div>
);
}}
</SortableList>
) : (
<>
<p className="environment-media-playlist__empty">
Добавьте первый файл или прямую ссылку на медиаконтент.
</p>
{error ? (
<p className="environment-media-playlist__error" role="alert">
{error}
</p>
) : null}
</>
)}
<div className="environment-media-playlist__timing">
<RangeControl
label="Показывать изображение"
value={background.imageDurationSeconds}
min={1}
max={60}
step={1}
disabled={disabled}
formatValue={(value) => `${value} с`}
onChange={(imageDurationSeconds) => onChange({
...background,
imageDurationSeconds,
})}
/>
<span>
Новые элементы появляются сверху. Воспроизведение начинается снизу;
перетаскивание меняет порядок.
</span>
</div>
</div>
);
}
@@ -1,358 +1,25 @@
import { useEffect, useMemo, useState } from "react"; import { EnvironmentSettingsWindow as SharedEnvironmentSettingsWindow } from "@nodedc/ui-react";
import { import { environmentSurfaceIds, type EnvironmentSettings, type EnvironmentSurfaceId, type UploadedEnvironmentMedia } from "../core/environment/environmentSettings";
Button, import { roots, workspaces, workspacesForRoot } from "../productModel";
FeatureSettingsWindow,
Select,
SettingsCard,
Switch,
TextAreaField,
TextField,
WindowFooterActions,
} from "@nodedc/ui-react";
import { interface Props {
cloneEnvironmentSettings,
type EnvironmentBackground,
type EnvironmentPage,
type EnvironmentSettings,
type EnvironmentSurfaceId,
type UploadedEnvironmentMedia,
} from "../core/environment/environmentSettings";
import { EnvironmentMediaPlaylistEditor } from "./EnvironmentMediaPlaylistEditor";
import {
roots,
workspaces,
workspacesForRoot,
} from "../productModel";
interface EnvironmentSettingsWindowProps {
open: boolean; open: boolean;
settings: EnvironmentSettings; settings: EnvironmentSettings;
state: "loading" | "ready" | "saving" | "error"; state: "loading" | "ready" | "saving" | "error";
error: string | null; error: string | null;
onClose: () => void; onClose: () => void;
onSave: (settings: EnvironmentSettings) => Promise<EnvironmentSettings>; onSave: (settings: EnvironmentSettings) => Promise<EnvironmentSettings>;
onUpload: ( onUpload: (surfaceId: EnvironmentSurfaceId, itemId: string, file: File) => Promise<UploadedEnvironmentMedia>;
surfaceId: EnvironmentSurfaceId,
itemId: string,
file: File,
) => Promise<UploadedEnvironmentMedia>;
} }
const surfaces = environmentSurfaceIds.map(id => ({
function patchPage( id, home: id === "home", description: id === "home" ? "Главная страница продукта" : `Стартовая страница раздела «${roots.find(root => root.id === id)?.label}»`,
draft: EnvironmentSettings, actions: id === "home" ? workspaces.filter(item => !item.internalOnly) : workspacesForRoot(id),
surfaceId: EnvironmentSurfaceId, }));
patch: Partial<EnvironmentPage>, export function EnvironmentSettingsWindow(props: Props) {
): EnvironmentSettings { return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet"
return { onSave={draft => props.onSave({ ...draft, pages: Object.fromEntries(environmentSurfaceIds.map(id => [id, draft.pages[id]])) as EnvironmentSettings["pages"] })}
...draft, onUpload={(id, itemId, file) => {
pages: { if (!environmentSurfaceIds.includes(id as EnvironmentSurfaceId)) throw new Error("Страница окружения недоступна.");
...draft.pages, return props.onUpload(id as EnvironmentSurfaceId, itemId, file);
[surfaceId]: { }} />;
...draft.pages[surfaceId],
...patch,
},
},
};
}
function patchBackground(
draft: EnvironmentSettings,
surfaceId: EnvironmentSurfaceId,
patch: Partial<EnvironmentBackground>,
): EnvironmentSettings {
const page = draft.pages[surfaceId];
return patchPage(draft, surfaceId, {
background: {
...page.background,
...patch,
},
});
}
export function EnvironmentSettingsWindow({
open,
settings,
state,
error,
onClose,
onSave,
onUpload,
}: EnvironmentSettingsWindowProps) {
const [draft, setDraft] = useState(() => cloneEnvironmentSettings(settings));
const [surfaceId, setSurfaceId] = useState<EnvironmentSurfaceId>("fleet");
const [uploading, setUploading] = useState(false);
const [localError, setLocalError] = useState<string | null>(null);
useEffect(() => {
if (!open) return;
setDraft(cloneEnvironmentSettings(settings));
setLocalError(null);
}, [open, settings]);
const selectedPage = draft.pages[surfaceId];
const selectedBackground = selectedPage.background;
const pageOptions = useMemo(() => [
{
value: "home" as const,
label: draft.pages.home.headerLabel,
description: "Главная страница продукта",
},
...roots.map((root) => ({
value: root.id,
label: draft.pages[root.id].headerLabel,
description: `Стартовая страница раздела «${draft.pages[root.id].title}»`,
})),
], [draft.pages]);
const quickActionWorkspaces = useMemo(
() => surfaceId === "home"
? workspaces.filter((workspace) => !workspace.internalOnly)
: workspacesForRoot(surfaceId),
[surfaceId],
);
const quickActionOptions = useMemo(() => [
{
value: "none",
label: "Не показывать",
description: "Кнопка скрыта на стартовом экране",
},
...quickActionWorkspaces.map((workspace) => ({
value: workspace.id,
label: workspace.label,
description: workspace.description,
})),
], [quickActionWorkspaces]);
const dirty = useMemo(
() => JSON.stringify(draft) !== JSON.stringify(settings),
[draft, settings],
);
const busy = state === "saving" || uploading;
const updatePage = (patch: Partial<EnvironmentPage>) => {
setDraft((current) => patchPage(current, surfaceId, patch));
};
const save = async () => {
const invalid = Object.entries(draft.pages).find(([, page]) => (
!page.headerLabel.trim()
|| !page.eyebrow.trim()
|| !page.title.trim()
|| !page.description.trim()
));
if (invalid) {
setLocalError("Название, надзаголовок, заголовок и описание не могут быть пустыми.");
return;
}
if (
selectedPage.primaryWorkspaceId
&& selectedPage.primaryWorkspaceId === selectedPage.secondaryWorkspaceId
) {
setLocalError("Быстрые кнопки должны вести на разные рабочие поверхности.");
return;
}
const invalidMedia = Object.entries(draft.pages).find(([, page]) => (
(page.background.enabled && !page.background.items.length)
|| page.background.items.some((item) => {
if (!item.url || !item.mediaKind) return true;
if (item.source !== "url") return false;
try {
const parsed = new URL(item.url);
return !["http:", "https:"].includes(parsed.protocol);
} catch {
return true;
}
})
));
if (invalidMedia) {
setSurfaceId(invalidMedia[0] as EnvironmentSurfaceId);
setLocalError(
"Каждый элемент фона должен содержать загруженный файл или прямой HTTP(S) URL.",
);
return;
}
setLocalError(null);
try {
await onSave({
...draft,
pages: Object.fromEntries(
Object.entries(draft.pages).map(([id, page]) => [id, {
...page,
headerLabel: page.headerLabel.trim(),
eyebrow: page.eyebrow.trim(),
title: page.title.trim(),
description: page.description.trim(),
}]),
) as EnvironmentSettings["pages"],
});
onClose();
} catch (reason) {
setLocalError(reason instanceof Error
? reason.message
: "Не удалось сохранить настройки окружения.");
}
};
return (
<FeatureSettingsWindow
open={open}
title="Настройки Mission Core"
subtitle="Локальное операторское окружение"
identity={{
title: "DC",
subtitle: "Mission Core",
avatarLabel: "DC",
}}
sections={[
{
id: "environment",
label: "Окружение",
group: "MISSION CORE",
icon: "settings",
},
]}
activeSection="environment"
onSectionChange={() => undefined}
onClose={onClose}
footer={(
<WindowFooterActions>
<Button
variant="secondary"
disabled={!dirty || busy}
onClick={() => {
setDraft(cloneEnvironmentSettings(settings));
setLocalError(null);
}}
>
Сбросить изменения
</Button>
<Button
variant="primary"
disabled={!dirty || busy}
onClick={() => void save()}
>
{state === "saving" ? "Сохраняем…" : "Сохранить"}
</Button>
</WindowFooterActions>
)}
>
<div className="environment-settings">
<SettingsCard
eyebrow="ОКРУЖЕНИЕ"
title="Основные элементы управления"
description="Выберите страницу и настройте её название в шапке, содержание стартового экрана, подложку и быстрые переходы."
actions={(
<Switch
checked={selectedBackground.enabled}
label="Показывать фон"
onChange={(enabled) => {
if (enabled && !selectedBackground.items.length) {
setLocalError("Сначала добавьте медиаконтент.");
return;
}
setLocalError(null);
setDraft((current) =>
patchBackground(current, surfaceId, { enabled }));
}}
/>
)}
>
<div className="environment-settings__editor">
<div className="environment-settings__surface">
<span>Страница</span>
<Select
label="Выбрать страницу окружения"
value={surfaceId}
options={pageOptions}
variant="split"
menuWidth="anchor"
onChange={(value) => {
setSurfaceId(value);
setLocalError(null);
}}
/>
</div>
<div className="environment-settings__copy">
<TextField
label={surfaceId === "home" ? "Название продукта" : "Название в шапке"}
value={selectedPage.headerLabel}
maxLength={40}
onChange={(event) => updatePage({
headerLabel: event.currentTarget.value,
})}
/>
<TextField
label="Надзаголовок"
value={selectedPage.eyebrow}
maxLength={80}
onChange={(event) => updatePage({
eyebrow: event.currentTarget.value,
})}
/>
<TextField
label="Основной заголовок"
value={selectedPage.title}
maxLength={120}
onChange={(event) => updatePage({
title: event.currentTarget.value,
})}
/>
<TextAreaField
label="Описание"
value={selectedPage.description}
maxLength={500}
rows={3}
onChange={(event) => updatePage({
description: event.currentTarget.value,
})}
/>
</div>
<div className="environment-settings__quick-actions">
<div>
<span>Кнопка 1</span>
<Select
label="Выбрать первую быструю кнопку"
value={selectedPage.primaryWorkspaceId ?? "none"}
options={quickActionOptions}
variant="split"
menuWidth="anchor"
onChange={(value) => updatePage({
primaryWorkspaceId: value === "none" ? null : value,
})}
/>
</div>
<div>
<span>Кнопка 2</span>
<Select
label="Выбрать вторую быструю кнопку"
value={selectedPage.secondaryWorkspaceId ?? "none"}
options={quickActionOptions}
variant="split"
menuWidth="anchor"
onChange={(value) => updatePage({
secondaryWorkspaceId: value === "none" ? null : value,
})}
/>
</div>
</div>
<EnvironmentMediaPlaylistEditor
surfaceId={surfaceId}
background={selectedBackground}
disabled={busy}
error={localError ?? error}
onBusyChange={setUploading}
onChange={(background) => {
setLocalError(null);
setDraft((current) =>
patchBackground(current, surfaceId, background));
}}
onUpload={onUpload}
/>
</div>
</SettingsCard>
</div>
</FeatureSettingsWindow>
);
} }
@@ -1,5 +1,6 @@
import { useLayoutEffect, useState, type RefObject } from "react"; import type {RefObject} from "react";
import { WorkspaceWindow } from "@nodedc/ui-react"; import {FloatingMediaWindow} from "../../../../packages/spatial-ui/src/FloatingMediaWindow";
export {initialObservationWindowRect,shouldCaptureWorkspacePointer} from "../../../../packages/spatial-ui/src/FloatingMediaWindow";
import type { ObservationWindowRect } from "../core/observation/useObservationLayout"; import type { ObservationWindowRect } from "../core/observation/useObservationLayout";
import type { ObservationSourceDescriptor } from "../core/runtime/contracts"; import type { ObservationSourceDescriptor } from "../core/runtime/contracts";
@@ -10,60 +11,6 @@ import type {
RecordedCameraAdmissionState, RecordedCameraAdmissionState,
} from "../core/observation/recordedSessionAdmission"; } from "../core/observation/recordedSessionAdmission";
const WINDOW_WIDTH = 336;
const WINDOW_HEIGHT = 210;
const WINDOW_GAP = 16;
const WINDOW_INSET = 18;
const TIMELINE_CLEARANCE = 64;
type ClosestTarget = { closest: (selectors: string) => unknown };
export function shouldCaptureWorkspacePointer(
button: number,
target: ClosestTarget | null,
): boolean {
if (button !== 0 || !target) return false;
if (target.closest(".nodedc-workspace-window__resize")) return true;
if (!target.closest(".nodedc-workspace-window__head")) return false;
return !target.closest("button, input, select, textarea, a");
}
export function initialObservationWindowRect(
index: number,
count = 1,
bounds: { width: number; height: number } = { width: 1280, height: 720 },
): ObservationWindowRect {
const availableWidth = Math.max(0, bounds.width - WINDOW_INSET * 2);
const width = Math.max(1, Math.min(WINDOW_WIDTH, availableWidth || WINDOW_WIDTH));
const availableHeight = Math.max(0, bounds.height - WINDOW_INSET - TIMELINE_CLEARANCE);
const maxColumns = Math.max(
1,
Math.floor((availableWidth + WINDOW_GAP) / (width + WINDOW_GAP)),
);
const columns = Math.max(1, Math.min(Math.max(1, count), maxColumns));
const rows = Math.max(1, Math.ceil(Math.max(1, count) / columns));
const rowHeight = Math.max(
1,
(availableHeight - Math.max(0, rows - 1) * WINDOW_GAP) / rows,
);
const height = Math.max(1, Math.min(WINDOW_HEIGHT, rowHeight));
const row = Math.floor(index / columns);
const column = index % columns;
const rowItemCount = Math.min(columns, Math.max(1, count - row * columns));
const rowWidth = rowItemCount * width + Math.max(0, rowItemCount - 1) * WINDOW_GAP;
const rowStart = Math.max(0, bounds.width - WINDOW_INSET - rowWidth);
return {
x: rowStart + Math.min(column, rowItemCount - 1) * (width + WINDOW_GAP),
y: Math.max(
0,
bounds.height - TIMELINE_CLEARANCE - height - row * (height + WINDOW_GAP),
),
width,
height,
};
}
export function FloatingObservationWindow({ export function FloatingObservationWindow({
source, source,
index, index,
@@ -104,76 +51,12 @@ export function FloatingObservationWindow({
state: RecordedCameraAdmissionState, state: RecordedCameraAdmissionState,
) => void; ) => void;
}) { }) {
const [bounds, setBounds] = useState<{ width: number; height: number } | null>(null); return <FloatingMediaWindow title={source.label} subtitle={source.description}
index={index} count={count} boundsRef={boundsRef} rect={rect} maximized={maximized}
useLayoutEffect(() => { active={active} hidden={hidden} onRectChange={onRectChange} onMaximizedChange={onMaximizedChange}
const element = boundsRef.current; onActivate={onActivate} onClose={onClose} resizable={source.capabilities.resizable}
if (!element) return; status={<span className="floating-observation-window__status"><i data-availability={source.availability} aria-hidden="true"/>{observationSourceStatusLabel(source)}</span>}
footer={<span className="floating-observation-window__footer"><span>{source.endpointLabel || source.transport}</span><span>{source.capabilities.timelineMode === "live-only" ? "Эфир без буфера" : "Временная шкала"}</span></span>}>
const measure = () => {
const next = { width: element.clientWidth, height: element.clientHeight };
setBounds((current) => (
current?.width === next.width && current.height === next.height ? current : next
));
};
measure();
const observer = new ResizeObserver(measure);
observer.observe(element);
return () => observer.disconnect();
}, [boundsRef]);
// Camera media admission must not wait for the viewport observer. A source
// can arrive in the same commit as a workspace transition; mounting it with
// the canonical fallback geometry keeps the browser transport alive until
// the real bounds are measured immediately afterward.
const initialRect = initialObservationWindowRect(index, count, bounds ?? undefined);
const windowRect = rect ?? initialRect;
return (
<WorkspaceWindow
boundsRef={boundsRef}
rect={windowRect}
onRectChange={onRectChange}
maximized={maximized}
onMaximizedChange={onMaximizedChange}
onActivate={onActivate}
onClose={onClose}
title={source.label}
subtitle={source.description}
status={(
<span className="floating-observation-window__status">
<i data-availability={source.availability} aria-hidden="true" />
{observationSourceStatusLabel(source)}
</span>
)}
footer={(
<span className="floating-observation-window__footer">
<span>{source.endpointLabel || source.transport}</span>
<span>{source.capabilities.timelineMode === "live-only" ? "Эфир без буфера" : "Временная шкала"}</span>
</span>
)}
minWidth={Math.min(280, windowRect.width)}
minHeight={Math.min(190, windowRect.height)}
resizable={source.capabilities.resizable}
active={active}
zIndex={maximized ? 15 : active ? 9 : 7}
className={`floating-observation-window${hidden ? " floating-observation-window--hidden" : ""}`}
onPointerDownCapture={(event) => {
if (!shouldCaptureWorkspacePointer(event.button, event.target as HTMLElement)) return;
try {
event.currentTarget.setPointerCapture(event.pointerId);
} catch {
// Pointer capture can fail if the browser ended the pointer between
// dispatch and capture. The donor's window listeners remain fallback.
}
}}
closeLabel={`Закрыть ${source.label}`}
maximizeLabel={`Развернуть ${source.label}`}
restoreLabel={`Восстановить ${source.label}`}
moveLabel={`Переместить ${source.label}`}
resizeLabel={`Изменить размер ${source.label}`}
>
<ObservationMedia <ObservationMedia
source={source} source={source}
playback={playback} playback={playback}
@@ -182,6 +65,5 @@ export function FloatingObservationWindow({
recordedAdmissionKey={recordedAdmissionKey} recordedAdmissionKey={recordedAdmissionKey}
onRecordedAdmissionChange={onRecordedAdmissionChange} onRecordedAdmissionChange={onRecordedAdmissionChange}
/> />
</WorkspaceWindow> </FloatingMediaWindow>;
);
} }
@@ -1,10 +1,9 @@
import { Button, Icon, StatusBadge } from "@nodedc/ui-react"; import { LandingStage as SharedLandingStage, StatusBadge } from "@nodedc/ui-react";
import type { BackendStatus, RuntimePhase } from "../core/runtime/contracts"; import type { BackendStatus, RuntimePhase } from "../core/runtime/contracts";
import type { EnvironmentPage } from "../core/environment/environmentSettings"; import type { EnvironmentPage } from "../core/environment/environmentSettings";
import type { RootDefinition, WorkspaceDefinition } from "../productModel"; import type { RootDefinition, WorkspaceDefinition } from "../productModel";
import { backendLabel, backendTone, phaseLabel, phaseTone } from "../presentation"; import { backendLabel, backendTone, phaseLabel, phaseTone } from "../presentation";
import { EnvironmentBackgroundMedia } from "./EnvironmentBackgroundMedia";
export interface LandingStageProps { export interface LandingStageProps {
root: RootDefinition | null; root: RootDefinition | null;
@@ -25,40 +24,10 @@ export function LandingStage({
quickActions, quickActions,
onOpenWorkspace, onOpenWorkspace,
}: LandingStageProps) { }: LandingStageProps) {
const { background } = page; return <SharedLandingStage page={page} pageId={root?.id ?? "home"}
const hasMedia = background.enabled && background.items.some( actions={quickActions.map(workspace => ({ id: workspace.id, label: workspace.label, icon: workspace.icon, onSelect: () => onOpenWorkspace(workspace.id) }))}
(item) => item.url && item.mediaKind, status={<>
); <div>
return (
<section
className="landing-stage"
data-root={root?.id ?? "home"}
data-has-media={hasMedia ? "true" : undefined}
>
<EnvironmentBackgroundMedia background={background} />
<div className="landing-stage__shade" aria-hidden="true" />
<div className="landing-stage__copy">
<span className="section-eyebrow">{page.eyebrow}</span>
<h1>{page.title}</h1>
<p>{page.description}</p>
{quickActions.length ? (
<div className="landing-stage__actions">
{quickActions.map((workspace, index) => (
<Button
key={workspace.id}
variant={index === 0 ? "primary" : "secondary"}
icon={<Icon name={workspace.icon} />}
onClick={() => onOpenWorkspace(workspace.id)}
>
{workspace.label}
</Button>
))}
</div>
) : null}
</div>
<div className="landing-stage__status">
<div>
<span className="section-eyebrow">ЛОКАЛЬНЫЙ КОНТУР</span> <span className="section-eyebrow">ЛОКАЛЬНЫЙ КОНТУР</span>
<StatusBadge tone={backendTone(backendStatus)}>{backendLabel(backendStatus)}</StatusBadge> <StatusBadge tone={backendTone(backendStatus)}>{backendLabel(backendStatus)}</StatusBadge>
</div> </div>
@@ -67,12 +36,9 @@ export function LandingStage({
<StatusBadge tone={phaseTone(phase)}>{phaseLabel(phase)}</StatusBadge> <StatusBadge tone={phaseTone(phase)}>{phaseLabel(phase)}</StatusBadge>
</div> </div>
<p>{message || "Выберите архитектурный блок в верхней навигации."}</p> <p>{message || "Выберите архитектурный блок в верхней навигации."}</p>
</div> </>}
footer={<>
<footer className="landing-stage__footer"> <span>{root?.accent ?? "НАБЛЮДЕНИЕ · МИССИИ · ДАННЫЕ"}</span>
<span>{root?.accent ?? "НАБЛЮДЕНИЕ · МИССИИ · ДАННЫЕ"}</span>
<span>01 / ЛОКАЛЬНЫЙ СТЕНД</span> <span>01 / ЛОКАЛЬНЫЙ СТЕНД</span>
</footer> </>} />;
</section>
);
} }
@@ -1,9 +1,9 @@
import { Dropdown, Icon, type IconName } from "@nodedc/ui-react"; import {sourceIcon,observationSourceStatusLabel} from "../../../../packages/spatial-ui/src/ObservationSourcePicker";
export {ObservationSourcePicker,observationSourceStatusLabel} from "../../../../packages/spatial-ui/src/ObservationSourcePicker";
import { Icon } from "@nodedc/ui-react";
import type { import type {
ObservationSourceAvailability,
ObservationSourceDescriptor, ObservationSourceDescriptor,
ObservationSourceModality,
} from "../core/runtime/contracts"; } from "../core/runtime/contracts";
import { MseFmp4WebSocketPlayer } from "./MseFmp4WebSocketPlayer"; import { MseFmp4WebSocketPlayer } from "./MseFmp4WebSocketPlayer";
import { import {
@@ -16,28 +16,6 @@ import type {
} from "../core/observation/recordedSessionAdmission"; } from "../core/observation/recordedSessionAdmission";
import { liveCameraPlaybackAuthorityIdentity } from "../core/observation/liveCameraRecovery"; import { liveCameraPlaybackAuthorityIdentity } from "../core/observation/liveCameraRecovery";
const sourceIcon: Record<ObservationSourceModality, IconName> = {
"point-cloud": "globe",
video: "video",
image: "image",
depth: "image",
};
const availabilityCopy: Record<ObservationSourceAvailability, string> = {
unverified: "Не подтверждён",
declared: "Канал объявлен",
available: "Доступен",
connecting: "Подключение",
streaming: "Эфир",
degraded: "Нестабильно",
unavailable: "Недоступен",
error: "Ошибка",
};
export function observationSourceStatusLabel(source: ObservationSourceDescriptor): string {
return availabilityCopy[source.availability];
}
export function ObservationMedia({ export function ObservationMedia({
source, source,
playback, playback,
@@ -159,105 +137,3 @@ export function ObservationMedia({
</div> </div>
); );
} }
export function ObservationSourcePicker({
sources,
visibleSourceIds,
pendingSourceIds,
onToggle,
}: {
sources: readonly ObservationSourceDescriptor[];
visibleSourceIds: ReadonlySet<string>;
pendingSourceIds?: ReadonlySet<string>;
onToggle: (sourceId: string) => void | Promise<boolean>;
}) {
const visibleCount = sources.filter((source) => visibleSourceIds.has(source.id)).length;
return (
<Dropdown
className="scene-source-picker"
placement="bottom-start"
width={340}
offset={10}
surfaceRole="dialog"
surfaceClassName="observation-source-menu"
trigger={({ open, toggle, setAnchorRef, setTriggerRef, surfaceId }) => (
<button
ref={(node) => {
setAnchorRef(node);
setTriggerRef(node);
}}
type="button"
className="scene-source-picker__trigger"
data-active={open || visibleCount > 0 ? "true" : undefined}
aria-label="Источники данных сцены"
aria-haspopup="dialog"
aria-expanded={open}
aria-controls={surfaceId}
onClick={toggle}
>
<Icon name="database" size={17} />
{sources.length > 0 ? <span>{visibleCount}</span> : null}
</button>
)}
>
<header className="observation-source-menu__head">
<div>
<span className="section-eyebrow">НАБЛЮДЕНИЕ</span>
<strong>Источники данных</strong>
</div>
<small>{sources.length ? `${visibleCount} из ${sources.length}` : "нет источников"}</small>
</header>
{sources.length ? (
<div className="observation-source-menu__list">
{sources.map((source) => {
const selected = visibleSourceIds.has(source.id);
const pending = pendingSourceIds?.has(source.id) ?? false;
const canOpen = Boolean(
selected ||
source.modality === "point-cloud" ||
source.previewUrl ||
source.delivery ||
source.activation?.controllable,
);
return (
<button
key={source.id}
type="button"
className="nodedc-dropdown-option observation-source-option"
data-selected={selected ? "true" : undefined}
aria-pressed={selected}
disabled={pending || !canOpen}
onClick={() => void onToggle(source.id)}
>
<span className="nodedc-dropdown-option__icon">
<Icon name={sourceIcon[source.modality]} size={16} />
</span>
<span className="nodedc-dropdown-option__body">
<span className="nodedc-dropdown-option__label">{source.label}</span>
<span className="nodedc-dropdown-option__description">
<i data-availability={source.availability} aria-hidden="true" />
{pending ? "Переключение" : observationSourceStatusLabel(source)} · {source.endpointLabel || source.transport}
</span>
</span>
<span className="nodedc-dropdown-option__check">
{selected ? <Icon name="check" size={15} /> : null}
</span>
</button>
);
})}
</div>
) : (
<div className="observation-source-menu__empty">
<Icon name="database" size={18} />
<strong>Каталог пока пуст</strong>
<span>Выберите профиль устройства — его плагин опубликует доступные каналы.</span>
</div>
)}
<footer className="observation-source-menu__foot">
Каналы приходят из активного контура или выбранной сохранённой сессии; сцена не знает
модель оборудования.
</footer>
</Dropdown>
);
}
@@ -1,197 +1 @@
import { Button, Icon, Select } from "@nodedc/ui-react"; export * from "../../../../packages/spatial-ui/src/ObservationTimeline";
import type { ObservationTimelineMode } from "../core/runtime/contracts";
export function ObservationTimeline({
active,
sourceCount,
mode = "live-only",
seekable = false,
synchronization = "host-arrival-best-effort",
rangeNs = null,
currentNs = null,
playing = false,
onSeek,
onPlayingChange,
onJumpToEnd,
showJumpToEnd = true,
playbackRate,
onPlaybackRateChange,
accumulationSeconds,
onAccumulationChange,
onAccumulationCommit,
className = "",
}: {
active: boolean;
sourceCount: number;
mode?: ObservationTimelineMode;
seekable?: boolean;
synchronization?: "host-arrival-best-effort" | "shared-clock" | "frame-accurate";
rangeNs?: { min: number; max: number } | null;
currentNs?: number | null;
playing?: boolean;
onSeek?: (timeNs: number) => void;
onPlayingChange?: (playing: boolean) => void;
onJumpToEnd?: () => void;
showJumpToEnd?: boolean;
playbackRate?: number;
onPlaybackRateChange?: (rate: number) => void;
accumulationSeconds?: number;
onAccumulationChange?: (value: number) => void;
onAccumulationCommit?: () => void;
className?: string;
}) {
const playbackRange = normalizeTimelineRange(rangeNs);
const buffered = Boolean(
seekable &&
(mode === "buffered" || mode === "recorded") &&
playbackRange,
);
const elapsedSeconds = playbackRange
? timelineOffsetSeconds(playbackRange, currentNs ?? playbackRange.min)
: 0;
const durationSeconds = playbackRange
? Math.max(0, (playbackRange.max - playbackRange.min) / 1_000_000_000)
: 0;
const synchronizationLabel = {
"host-arrival-best-effort": "Синхронизация по приходу",
"shared-clock": "Общие часы",
"frame-accurate": "Покадровая синхронизация",
}[synchronization];
const accumulationValue = accumulationSeconds === undefined
? null
: normalizeAccumulationSeconds(accumulationSeconds);
return (
<div
className={`observation-timeline ${className}`.trim()}
data-active={active ? "true" : undefined}
data-mode={mode}
data-accumulation={accumulationValue !== null ? "true" : undefined}
>
{accumulationValue !== null ? (
<div className="observation-timeline__accumulation">
<span>Накопление</span>
<input
className="observation-timeline__track"
type="range"
min={0}
max={120}
step={1}
value={accumulationValue}
aria-label="Окно накопления облака точек"
aria-valuetext={formatAccumulationDuration(accumulationValue)}
onChange={(event) =>
onAccumulationChange?.(normalizeAccumulationSeconds(Number(event.target.value)))}
onPointerUp={onAccumulationCommit}
onTouchEnd={onAccumulationCommit}
onKeyUp={onAccumulationCommit}
onBlur={onAccumulationCommit}
/>
<code>{formatAccumulationDuration(accumulationValue)}</code>
</div>
) : null}
<div className="observation-timeline__playback">
<Button
size="compact"
variant="ghost"
disabled={!buffered || !onSeek}
aria-label="Перейти к началу"
onClick={() => playbackRange && onSeek?.(playbackRange.min)}
>
<Icon name="chevron-left" />
</Button>
<Button
className="observation-timeline__transport"
size="compact"
variant="ghost"
disabled={!buffered || !onPlayingChange}
aria-label={buffered ? (playing ? "Пауза" : "Воспроизвести") : "Только эфир"}
icon={<Icon name={playing ? "stop" : "play"} />}
onClick={() => onPlayingChange?.(!playing)}
/>
{buffered && playbackRate !== undefined && onPlaybackRateChange ? (
<Select
label="Скорость воспроизведения"
value={String(playbackRate)}
options={[
{ value: "0.5", label: "0,5×" },
{ value: "1", label: "1×" },
{ value: "2", label: "2×" },
]}
variant="inline"
menuWidth="anchor"
onChange={(value) => onPlaybackRateChange(Number(value))}
/>
) : null}
<input
className="observation-timeline__track"
type="range"
min={0}
max={Math.max(durationSeconds, 0.001)}
step={0.01}
value={Math.min(elapsedSeconds, durationSeconds)}
disabled={!buffered || !onSeek}
aria-label="Позиция воспроизведения"
onChange={(event) => {
if (!playbackRange) return;
onSeek?.(playbackRange.min + Number(event.target.value) * 1_000_000_000);
}}
/>
<div className="observation-timeline__meta">
<code>
{buffered
? `${formatTimelineDuration(elapsedSeconds)} / ${formatTimelineDuration(durationSeconds)}`
: active ? "LIVE" : "—:—:—.———"}
</code>
<small>
{buffered ? `${sourceCount} каналов` : `${synchronizationLabel} · буфер не включён`}
</small>
</div>
{showJumpToEnd ? (
<button
type="button"
className="observation-timeline__follow"
data-active={!buffered && active ? "true" : undefined}
disabled={buffered ? !onJumpToEnd : true}
onClick={onJumpToEnd}
>
{buffered ? "К КОНЦУ" : "ЭФИР"}
</button>
) : null}
</div>
</div>
);
}
export function normalizeAccumulationSeconds(value: number): number {
if (!Number.isFinite(value)) return 0;
return Math.min(120, Math.max(0, Math.round(value)));
}
export function formatAccumulationDuration(value: number): string {
const seconds = normalizeAccumulationSeconds(value);
return seconds === 0 ? "Кадр" : `${seconds} с`;
}
export function normalizeTimelineRange(
range: { min: number; max: number } | null | undefined,
): { min: number; max: number } | null {
if (!range || !Number.isFinite(range.min) || !Number.isFinite(range.max)) return null;
if (range.max <= range.min) return null;
return range;
}
export function timelineOffsetSeconds(
range: { min: number; max: number },
currentNs: number,
): number {
const clamped = Math.min(Math.max(currentNs, range.min), range.max);
return Math.max(0, (clamped - range.min) / 1_000_000_000);
}
export function formatTimelineDuration(seconds: number): string {
if (!Number.isFinite(seconds) || seconds < 0) return "00:00.000";
const wholeMinutes = Math.floor(seconds / 60);
const remaining = seconds - wholeMinutes * 60;
return `${String(wholeMinutes).padStart(2, "0")}:${remaining.toFixed(3).padStart(6, "0")}`;
}
@@ -6,19 +6,18 @@ interface TelemetrySeriesProps {
ceiling?: number; ceiling?: number;
} }
function linePoints(values: Array<number | null>, ceiling?: number): string { export function lineSegments(values: Array<number | null>, ceiling?: number): string[] {
const finite = values.filter((value): value is number => const finite = values.filter((value): value is number => value !== null && Number.isFinite(value));
value !== null && Number.isFinite(value), if (!finite.length) return [];
); const maximum = Math.max(ceiling ?? 0, ...finite, 1), denominator = Math.max(1, values.length - 1);
if (finite.length === 0) return ""; const minimum = Math.min(0, ...finite), span = maximum - minimum;
const maximum = Math.max(ceiling ?? 0, ...finite, 1); const segments:string[]=[];let segment:string[]=[];
const denominator = Math.max(1, values.length - 1); values.forEach((value,index)=>{
return values.map((value, index) => { if(value===null||!Number.isFinite(value)){if(segment.length)segments.push(segment.join(' '));segment=[];return;}
const x = index / denominator * 100; segment.push(`${(index/denominator*100).toFixed(2)},${(36-(Math.min(maximum,value)-minimum)/span*34).toFixed(2)}`);
const normalized = value === null ? 0 : Math.max(0, Math.min(maximum, value)); });
const y = 36 - normalized / maximum * 34; if(segment.length)segments.push(segment.join(' '));
return `${x.toFixed(2)},${y.toFixed(2)}`; return segments;
}).join(" ");
} }
export function TelemetrySeries({ export function TelemetrySeries({
@@ -28,7 +27,7 @@ export function TelemetrySeries({
resource, resource,
ceiling, ceiling,
}: TelemetrySeriesProps) { }: TelemetrySeriesProps) {
const points = linePoints(values, ceiling); const segments = lineSegments(values, ceiling);
return ( return (
<div className="system-telemetry-series"> <div className="system-telemetry-series">
<div> <div>
@@ -45,7 +44,7 @@ export function TelemetrySeries({
aria-label={`${label}: ${value}`} aria-label={`${label}: ${value}`}
> >
<path d="M0 37 H100" /> <path d="M0 37 H100" />
{points ? <polyline points={points} /> : null} {segments.map((points,index)=><polyline key={index} points={points} />)}
</svg> </svg>
</div> </div>
); );
@@ -1,8 +1,13 @@
import type { DeviceUiPlugin } from "../core/device-plugins/contracts"; import type { DeviceUiPlugin } from "../core/device-plugins/contracts";
import { xgridsK1Plugin } from "@xgrids-k1/frontend/plugin"; import { xgridsK1Plugin } from "@xgrids-k1/frontend/plugin";
import {insta360X4SensorUi} from '../../../../plugins/insta360-x4/frontend/src/plugin';
// Composition root: this is the only place where Mission Core chooses which // Composition root: this is the only place where Mission Core chooses which
// statically reviewed device plugins are shipped in the current build. // statically reviewed device plugins are shipped in the current build.
export const installedDevicePlugins: readonly DeviceUiPlugin[] = Object.freeze([ export const installedDevicePlugins: readonly DeviceUiPlugin[] = Object.freeze([
xgridsK1Plugin, xgridsK1Plugin,
]); ]);
// Node-executed camera controls use the existing sensor contribution contract;
// they do not register a desktop capture/AI runtime or a new product workspace.
export const installedNodeSensorContributions = Object.freeze([insta360X4SensorUi]);
@@ -11,6 +11,8 @@ import {
import { IdleMissionRuntimeProvider } from "../runtime/MissionRuntimeContext"; import { IdleMissionRuntimeProvider } from "../runtime/MissionRuntimeContext";
import type { DeviceUiPlugin, RegisteredDeviceModel } from "./contracts"; import type { DeviceUiPlugin, RegisteredDeviceModel } from "./contracts";
import { createDevicePluginRegistry, type DevicePluginRegistry } from "./registry"; import { createDevicePluginRegistry, type DevicePluginRegistry } from "./registry";
import type {SensorUiContribution} from '../../../../../packages/sensor-ui/src/extensions';
const NO_NODE_SENSORS: readonly SensorUiContribution[] = Object.freeze([]);
interface DevicePluginHostValue { interface DevicePluginHostValue {
registry: DevicePluginRegistry; registry: DevicePluginRegistry;
@@ -83,12 +85,14 @@ export function commitPersistedDeviceModelId(
export function DevicePluginHostProvider({ export function DevicePluginHostProvider({
plugins, plugins,
nodeSensorContributions = NO_NODE_SENSORS,
children, children,
}: { }: {
plugins: readonly DeviceUiPlugin[]; plugins: readonly DeviceUiPlugin[];
nodeSensorContributions?: readonly SensorUiContribution[];
children: ReactNode; children: ReactNode;
}) { }) {
const registry = useMemo(() => createDevicePluginRegistry(plugins), [plugins]); const registry = useMemo(() => createDevicePluginRegistry(plugins, nodeSensorContributions), [plugins, nodeSensorContributions]);
const selectionStorage = useMemo(browserDeviceModelSelectionStorage, []); const selectionStorage = useMemo(browserDeviceModelSelectionStorage, []);
const [selectedModelId, setSelectedModelId] = useState<string | null>(() => const [selectedModelId, setSelectedModelId] = useState<string | null>(() =>
restorePersistedDeviceModelId(registry, selectionStorage) restorePersistedDeviceModelId(registry, selectionStorage)
@@ -105,7 +105,6 @@ export interface DevicePluginConnectionProps {
export interface DeviceUiPlugin { export interface DeviceUiPlugin {
sensorUi?: { sensorUi?: {
contributions: readonly import('../../../../../packages/sensor-ui/src/extensions').SensorUiContribution[]; contributions: readonly import('../../../../../packages/sensor-ui/src/extensions').SensorUiContribution[];
Enrollment?: ComponentType<import('../../../../../packages/sensor-ui/src/extensions').SensorEnrollmentProps>;
}; };
manifest: DevicePluginManifest; manifest: DevicePluginManifest;
RuntimeProvider: ComponentType<{ RuntimeProvider: ComponentType<{
@@ -6,8 +6,10 @@ import {
type DeviceUiPlugin, type DeviceUiPlugin,
type RegisteredDeviceModel, type RegisteredDeviceModel,
} from "./contracts"; } from "./contracts";
import type {SensorUiContribution} from '../../../../../packages/sensor-ui/src/extensions';
export interface DevicePluginRegistry { export interface DevicePluginRegistry {
readonly sensorContributions: readonly SensorUiContribution[];
readonly plugins: readonly DeviceUiPlugin[]; readonly plugins: readonly DeviceUiPlugin[];
readonly models: readonly RegisteredDeviceModel[]; readonly models: readonly RegisteredDeviceModel[];
resolveModel: (modelId: string) => RegisteredDeviceModel | null; resolveModel: (modelId: string) => RegisteredDeviceModel | null;
@@ -15,6 +17,7 @@ export interface DevicePluginRegistry {
export function createDevicePluginRegistry( export function createDevicePluginRegistry(
installedPlugins: readonly DeviceUiPlugin[], installedPlugins: readonly DeviceUiPlugin[],
nodeSensorContributions: readonly SensorUiContribution[] = [],
): DevicePluginRegistry { ): DevicePluginRegistry {
const pluginIds = new Set<string>(); const pluginIds = new Set<string>();
const modelIds = new Set<string>(); const modelIds = new Set<string>();
@@ -133,7 +136,15 @@ export function createDevicePluginRegistry(
} }
const modelById = new Map(models.map((registered) => [registered.model.id, registered])); const modelById = new Map(models.map((registered) => [registered.model.id, registered]));
const sensorContributions = [
...installedPlugins.flatMap(plugin => plugin.sensorUi?.contributions ?? []),
...nodeSensorContributions,
];
if (new Set(sensorContributions.map(value => value.kind)).size !== sensorContributions.length) {
throw new Error('Плагины повторяют модель устройства БК.');
}
return { return {
sensorContributions: Object.freeze(sensorContributions),
plugins: Object.freeze([...installedPlugins]), plugins: Object.freeze([...installedPlugins]),
models: Object.freeze(models), models: Object.freeze(models),
resolveModel: (modelId) => modelById.get(modelId) ?? null, resolveModel: (modelId) => modelById.get(modelId) ?? null,
@@ -1,32 +1,9 @@
import { roots, type RootId } from "../../productModel"; import { roots, type RootId } from "../../productModel";
export type EnvironmentSurfaceId = "home" | RootId; export type EnvironmentSurfaceId = "home" | RootId;
export type EnvironmentMediaKind = "image" | "video"; import { defaultEnvironmentImageDurationSeconds, maxEnvironmentMediaItems, type EnvironmentBackground, type EnvironmentMediaItem, type EnvironmentMediaKind, type EnvironmentMediaSource, type EnvironmentPage } from "@nodedc/ui-core";
export type EnvironmentMediaSource = "file" | "url"; export { createEnvironmentMediaItem, appendEnvironmentMediaItem, removeEnvironmentMediaItem, inferEnvironmentMediaKind, defaultEnvironmentImageDurationSeconds, maxEnvironmentMediaItems } from "@nodedc/ui-core";
export type { EnvironmentBackground, EnvironmentMediaItem, EnvironmentMediaKind, EnvironmentMediaSource, EnvironmentPage } from "@nodedc/ui-core";
export interface EnvironmentMediaItem {
id: string;
source: EnvironmentMediaSource;
url: string | null;
mediaKind: EnvironmentMediaKind | null;
fileName: string | null;
}
export interface EnvironmentBackground {
enabled: boolean;
imageDurationSeconds: number;
items: EnvironmentMediaItem[];
}
export interface EnvironmentPage {
headerLabel: string;
eyebrow: string;
title: string;
description: string;
primaryWorkspaceId: string | null;
secondaryWorkspaceId: string | null;
background: EnvironmentBackground;
}
export interface EnvironmentSettings { export interface EnvironmentSettings {
revision: number; revision: number;
@@ -54,60 +31,7 @@ const surfaceIds: readonly EnvironmentSurfaceId[] = [
"polygon", "polygon",
]; ];
export const defaultEnvironmentImageDurationSeconds = 10; function emptyBackground(): EnvironmentBackground { return { enabled: false, imageDurationSeconds: defaultEnvironmentImageDurationSeconds, items: [] }; }
export const maxEnvironmentMediaItems = 24;
function emptyBackground(): EnvironmentBackground {
return {
enabled: false,
imageDurationSeconds: defaultEnvironmentImageDurationSeconds,
items: [],
};
}
export function createEnvironmentMediaItem(): EnvironmentMediaItem {
return {
id: `media-${crypto.randomUUID()}`,
source: "file",
url: null,
mediaKind: null,
fileName: null,
};
}
export function appendEnvironmentMediaItem(
background: EnvironmentBackground,
item: EnvironmentMediaItem = createEnvironmentMediaItem(),
): EnvironmentBackground {
if (
background.items.length >= maxEnvironmentMediaItems
|| background.items.some((candidate) => candidate.id === item.id)
) {
return background;
}
return {
...background,
enabled: background.items.length === 0 ? true : background.enabled,
items: [...background.items, item],
};
}
export function removeEnvironmentMediaItem(
background: EnvironmentBackground,
itemId: string,
): EnvironmentBackground {
const items = background.items.filter((item) => item.id !== itemId);
if (items.length === background.items.length) return background;
return {
...background,
enabled: items.length > 0 && background.enabled,
items,
};
}
export function inferEnvironmentMediaKind(url: string): EnvironmentMediaKind {
return /\.(mp4|webm|mov)(?:[?#].*)?$/i.test(url) ? "video" : "image";
}
const defaultQuickActions: Record< const defaultQuickActions: Record<
EnvironmentSurfaceId, EnvironmentSurfaceId,
@@ -0,0 +1,49 @@
import {useEffect,useState} from 'react';
export interface MetricDefinition {label:string;group:string;resource:string;unit:string;reason:string|null}
export interface BoardMonitor {
available:boolean;fresh:boolean;storage:string;source_id:string;
latest:{seq:number;at:number;boot_id:string;values:Record<string,number|null>}|null;
definitions:Record<string,MetricDefinition>;received_at:number;backlog:number;
database_bytes:number|null;database_budget_bytes:number;archive_since:number|null;
start:number;end:number;bucket_seconds:number;
series:{at:number;min:number|null;max:number|null;mean:number|null;count:number}[];
events:{at:number;code:string;kind:string;locations:string[]}[];
}
export function useBoardMonitor(vehicle:string,metric:string,window:number,end:number|null){
const [value,setValue]=useState<BoardMonitor|null>(null),[error,setError]=useState('');
useEffect(()=>{
let active=true;let pending:AbortController|undefined;let timer:ReturnType<typeof setTimeout>|undefined;
setValue(null);setError('');
const read=async()=>{
const controller=new AbortController();pending=controller;
const deadline=setTimeout(()=>controller.abort(),12000);
try {
const query=new URLSearchParams({metric,window:String(window),...(end===null?{}:{end:String(end)})});
const response=await fetch(`/api/v1/fleet/${encodeURIComponent(vehicle)}/monitor?${query}`,{credentials:'same-origin',cache:'no-store',signal:controller.signal});
if(!response.ok)throw new Error('Мониторинг БК недоступен.');
const next=await response.json() as BoardMonitor;
if(active){setValue(next);setError('');}
}catch {if(active)setError('Не удалось обновить мониторинг БК.');}
finally {clearTimeout(deadline);if(active)timer=setTimeout(()=>void read(),5000);}
};
void read();return()=>{active=false;pending?.abort();clearTimeout(timer);};
},[vehicle,metric,window,end]);
return {value,error,dismissError:()=>setError('')};
}
export function monitorSeries(value:BoardMonitor,mode:'min'|'max'|'mean') {
const count=Math.ceil((value.end-value.start)/value.bucket_seconds)+1;
const values:Array<number|null>=Array(Math.min(count,302)).fill(null);
const first=Math.floor(value.start/value.bucket_seconds)*value.bucket_seconds;
for(const point of value.series){const index=Math.round((point.at-first)/value.bucket_seconds);if(index>=0&&index<values.length)values[index]=point[mode];}
return values;
}
export function monitorValue(value:number|null|undefined,unit=''){
if(value==null||!Number.isFinite(value))return 'Нет измерения';
if(unit==='bytes'||unit==='bytes/s'){
const labels=unit==='bytes'?['Б','КиБ','МиБ','ГиБ']:['Б/с','КиБ/с','МиБ/с','ГиБ/с'];let index=0;
while(value>=1024&&index<3){value/=1024;index++;}
return `${value.toLocaleString('ru-RU',{maximumFractionDigits:1})} ${labels[index]}`;
}
return `${value.toLocaleString('ru-RU',{maximumFractionDigits:1})}${unit?' '+unit:''}`;
}
+2 -2
View File
@@ -6,7 +6,7 @@ import "@nodedc/tokens/themes.css";
import "@nodedc/ui-core/styles.css"; import "@nodedc/ui-core/styles.css";
import App from "./App"; import App from "./App";
import { installedDevicePlugins } from "./composition/devicePlugins"; import { installedDevicePlugins, installedNodeSensorContributions } from "./composition/devicePlugins";
import { DevicePluginHostProvider } from "./core/device-plugins/DevicePluginHost"; import { DevicePluginHostProvider } from "./core/device-plugins/DevicePluginHost";
import { ComputeContourProvider } from "./core/system/ComputeContourContext"; import { ComputeContourProvider } from "./core/system/ComputeContourContext";
import "./styles.css"; import "./styles.css";
@@ -23,7 +23,7 @@ applyNodedcTheme(rootElement, { theme: "dark" });
createRoot(rootElement).render( createRoot(rootElement).render(
<StrictMode> <StrictMode>
<DevicePluginHostProvider plugins={installedDevicePlugins}> <DevicePluginHostProvider plugins={installedDevicePlugins} nodeSensorContributions={installedNodeSensorContributions}>
<ComputeContourProvider> <ComputeContourProvider>
<App /> <App />
</ComputeContourProvider> </ComputeContourProvider>
+1 -31
View File
@@ -1,31 +1 @@
export type SceneProjection = "3d" | "2d" | "map"; export * from "../../../packages/spatial-ui/src/sceneSettings";
export type PointColorMode = "intensity" | "height" | "distance" | "rgb" | "class";
export type PointPalette = "turbo" | "viridis" | "plasma" | "grayscale" | "custom";
export interface SceneSettings {
projection: SceneProjection;
pointSize: number;
colorMode: PointColorMode;
palette: PointPalette;
customColor: string;
accumulationSeconds: number;
showPoints: boolean;
showTrajectory: boolean;
showGrid: boolean;
showLabels: boolean;
showCameraFrustums: boolean;
}
export const defaultSceneSettings: SceneSettings = {
projection: "3d",
pointSize: 2.5,
colorMode: "intensity",
palette: "turbo",
customColor: "#35d7c1",
accumulationSeconds: 12,
showPoints: true,
showTrajectory: true,
showGrid: true,
showLabels: false,
showCameraFrustums: true,
};
-1
View File
@@ -22,7 +22,6 @@
@import "./styles/responsive.css"; @import "./styles/responsive.css";
@import "./styles/observation.css"; @import "./styles/observation.css";
@import "./styles/observatory.css"; @import "./styles/observatory.css";
@import "./styles/environment-settings.css";
@import "./styles/system-telemetry.css"; @import "./styles/system-telemetry.css";
@import "./styles/artifact-health.css"; @import "./styles/artifact-health.css";
@import "./styles/map.css"; @import "./styles/map.css";
@@ -1,141 +0,0 @@
.environment-settings {
display: grid;
gap: 1rem;
}
.environment-settings__copy {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.85rem;
}
.environment-settings__editor {
display: grid;
gap: 1rem;
}
.environment-settings__surface {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(18rem, 24rem);
align-items: center;
gap: 1rem;
}
.environment-settings__surface > span {
color: var(--nodedc-text-secondary);
font-size: 0.74rem;
font-weight: 650;
}
.environment-settings__surface .nodedc-select-anchor,
.environment-settings__surface .nodedc-select {
width: 100%;
}
.environment-settings__quick-actions {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.85rem;
}
.environment-settings__quick-actions > div {
display: grid;
gap: 0.4rem;
}
.environment-settings__quick-actions span {
color: var(--nodedc-text-secondary);
font-size: 0.68rem;
font-weight: 650;
}
.environment-settings__quick-actions .nodedc-select-anchor,
.environment-settings__quick-actions .nodedc-select {
width: 100%;
}
.environment-media-playlist {
display: grid;
min-width: 0;
gap: 0.85rem;
}
.environment-media-playlist__head {
display: flex;
min-width: 0;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
.environment-media-playlist__head > div {
display: grid;
min-width: 0;
gap: 0.22rem;
}
.environment-media-playlist__head span {
color: var(--nodedc-text-secondary);
font-size: var(--nodedc-font-size-sm);
font-weight: var(--nodedc-font-weight-medium);
}
.environment-media-playlist__head p,
.environment-media-playlist__empty,
.environment-media-playlist__timing > span,
.environment-media-playlist__error {
margin: 0;
color: var(--nodedc-text-muted);
font-size: var(--nodedc-font-size-xs);
line-height: 1.4;
}
.environment-media-playlist__error {
color: rgb(var(--nodedc-danger-rgb));
}
.environment-media-playlist__items {
display: grid;
min-width: 0;
gap: 0.7rem;
}
.environment-media-playlist__item {
display: grid;
min-width: 0;
grid-template-columns: minmax(0, 1fr) auto;
align-items: start;
gap: 0.4rem;
}
.environment-media-playlist__item-actions {
display: flex;
align-items: center;
gap: 0.1rem;
padding-top: 1.65rem;
}
.environment-media-playlist__timing {
display: grid;
gap: 0.42rem;
}
@media (max-width: 760px) {
.environment-settings__copy,
.environment-settings__quick-actions {
grid-template-columns: 1fr;
}
.environment-settings__surface {
grid-template-columns: 1fr;
}
.environment-media-playlist__item {
grid-template-columns: minmax(0, 1fr);
}
.environment-media-playlist__item-actions {
justify-self: end;
padding-top: 0;
}
}
+1 -659
View File
@@ -1,659 +1 @@
.scene-source-controls { @import "../../../../packages/spatial-ui/src/observation.css";
position: absolute;
z-index: 12;
top: 0.85rem;
left: 0.85rem;
display: flex;
align-items: center;
gap: 0.45rem;
}
.scene-device-controls {
position: absolute;
z-index: 30;
top: 0.85rem;
left: 50%;
max-width: calc(100% - 9rem);
transform: translateX(-50%);
}
.scene-source-picker__trigger,
.scene-source-control,
.scene-focus-exit {
display: inline-grid;
width: 2.75rem;
height: 2.75rem;
place-items: center;
border: 1px solid rgb(255 255 255 / 0.09);
border-radius: 50%;
background: rgb(12 13 16 / 0.82);
color: var(--nodedc-text-secondary);
cursor: pointer;
backdrop-filter: blur(18px);
}
.scene-navigation-hint {
position: absolute;
z-index: 11;
right: 0.85rem;
bottom: 4.9rem;
display: flex;
align-items: center;
gap: 0.75rem;
border: 1px solid rgb(255 255 255 / 0.07);
border-radius: 999px;
background: rgb(9 10 13 / 0.7);
color: var(--nodedc-text-muted);
padding: 0.42rem 0.65rem;
font-size: 0.52rem;
font-weight: 680;
pointer-events: none;
backdrop-filter: blur(14px);
}
.scene-source-picker__trigger {
position: relative;
}
.scene-source-picker__trigger:hover,
.scene-source-control:hover,
.scene-focus-exit:hover,
.scene-source-picker__trigger[data-active="true"] {
border-color: rgb(255 255 255 / 0.18);
color: var(--nodedc-text-primary);
}
.scene-source-picker__trigger > span {
position: absolute;
top: -0.2rem;
right: -0.2rem;
display: grid;
min-width: 1.05rem;
height: 1.05rem;
place-items: center;
border-radius: 999px;
background: var(--nodedc-text-primary);
color: #090a0c;
padding: 0 0.25rem;
font-size: 0.5rem;
font-weight: 800;
}
.scene-focus-exit {
position: absolute;
z-index: 20;
top: 0.85rem;
right: 0.85rem;
}
.scene-status--top-left {
left: 7.1rem;
}
.scene-status[aria-hidden="true"],
.scene-metrics[aria-hidden="true"] {
display: none;
}
.observation-source-menu {
overflow: hidden;
font-family: var(--nodedc-font-family);
}
.observation-source-menu__head,
.observation-source-menu__foot {
padding: 0.85rem 0.9rem;
}
.observation-source-menu__head {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 1rem;
}
.observation-source-menu__head strong,
.observation-source-menu__head span {
display: block;
}
.observation-source-menu__head strong {
margin-top: 0.34rem;
color: var(--nodedc-text-primary);
font-size: var(--nodedc-font-size-md);
}
.observation-source-menu__head small,
.observation-source-menu__foot {
color: var(--nodedc-text-muted);
font-size: var(--nodedc-font-size-xs);
line-height: 1.4;
}
.observation-source-menu__list {
display: grid;
max-height: min(28rem, 60vh);
overflow: auto;
padding: 0.35rem;
}
.observation-source-option .nodedc-dropdown-option__description {
display: flex;
align-items: center;
gap: 0.35rem;
}
.observation-source-option i,
.floating-observation-window i,
.camera-slot__status i {
width: 0.42rem;
height: 0.42rem;
flex: 0 0 0.42rem;
border-radius: 50%;
background: var(--nodedc-text-muted);
}
i[data-availability="available"],
i[data-availability="streaming"] {
background: rgb(var(--nodedc-success-rgb));
}
i[data-availability="connecting"],
i[data-availability="declared"] {
background: rgb(var(--nodedc-warning-rgb));
}
i[data-availability="unverified"] {
background: var(--nodedc-text-muted);
}
i[data-availability="degraded"],
i[data-availability="error"] {
background: rgb(var(--nodedc-danger-rgb));
}
.observation-source-menu__empty,
.camera-grid__empty,
.observation-media__empty {
display: grid;
place-items: center;
align-content: center;
gap: 0.5rem;
color: var(--nodedc-text-muted);
text-align: center;
}
.observation-source-menu__empty {
min-height: 10rem;
padding: 1rem;
}
.observation-source-menu__empty strong,
.observation-media__empty strong,
.camera-grid__empty strong {
color: var(--nodedc-text-secondary);
font-size: 0.7rem;
}
.observation-source-menu__empty span,
.observation-media__empty span,
.camera-grid__empty span {
max-width: 24rem;
font-size: 0.59rem;
line-height: 1.45;
}
.observation-source-menu__foot {
border-top: 0;
}
.observation-media__asset,
.observation-media__empty {
width: 100%;
height: 100%;
}
.observation-media__asset {
display: block;
object-fit: contain;
background: #050608;
}
.recorded-media-player {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
background: #070809;
}
.recorded-media-player:not([data-state="ready"]) .observation-media__asset {
visibility: hidden;
}
.recorded-media-player__notice {
position: absolute;
inset: 0;
display: grid;
place-items: center;
padding: 18px;
color: rgba(247, 248, 244, 0.72);
background: #070809;
font: inherit;
font-size: 11px;
text-align: center;
pointer-events: none;
}
.mse-fmp4-player {
position: relative;
width: 100%;
height: 100%;
min-height: 9rem;
overflow: hidden;
background: #050608;
}
.mse-fmp4-player__status {
position: absolute;
inset: 0;
display: grid;
place-items: center;
align-content: center;
gap: 0.5rem;
padding: 1rem;
background: rgb(5 6 8 / 0.88);
color: var(--nodedc-text-muted);
text-align: center;
}
.mse-fmp4-player__status strong {
color: var(--nodedc-text-secondary);
font-size: 0.7rem;
}
.mse-fmp4-player__status span {
max-width: 24rem;
font-size: 0.59rem;
line-height: 1.45;
}
.mse-fmp4-player__status button {
display: inline-flex;
align-items: center;
gap: 0.4rem;
margin-top: 0.25rem;
border: 1px solid rgb(255 255 255 / 0.12);
border-radius: 999px;
background: rgb(255 255 255 / 0.06);
color: var(--nodedc-text-primary);
padding: 0.48rem 0.72rem;
font: inherit;
font-size: 0.58rem;
font-weight: 760;
cursor: pointer;
}
.mse-fmp4-player__status button:hover {
background: rgb(255 255 255 / 0.11);
}
.observation-media__empty {
min-height: 9rem;
background: #07080a;
}
.floating-observation-window__status,
.floating-observation-window__footer {
display: flex;
align-items: center;
gap: 0.45rem;
}
.camera-slot__head-actions button {
display: grid;
width: 1.9rem;
height: 1.9rem;
place-items: center;
border: 0;
border-radius: 50%;
background: rgb(255 255 255 / 0.05);
color: var(--nodedc-text-secondary);
cursor: pointer;
}
.camera-slot__head-actions button:hover {
background: rgb(255 255 255 / 0.1);
color: var(--nodedc-text-primary);
}
.camera-slot__head-actions .camera-slot__activation {
width: auto;
min-width: 5.6rem;
height: 1.9rem;
border: 1px solid rgb(255 255 255 / 0.09);
border-radius: 999px;
padding: 0 0.65rem;
font: inherit;
font-size: 0.53rem;
font-weight: 760;
white-space: nowrap;
}
.camera-slot__head-actions .camera-slot__activation:disabled {
cursor: wait;
opacity: 0.48;
}
.floating-observation-window__status {
color: var(--nodedc-text-secondary);
font-size: 0.54rem;
}
.floating-observation-window__footer {
width: 100%;
justify-content: space-between;
color: var(--nodedc-text-muted);
font-size: 0.53rem;
}
.floating-observation-window .nodedc-workspace-window__body {
background: #06070a;
}
.floating-observation-window.nodedc-material-rim::after {
display: none;
}
.floating-observation-window[data-active="true"] {
box-shadow: 0 1.5rem 4rem rgb(0 0 0 / 0.34);
}
.floating-observation-window--hidden {
visibility: hidden;
pointer-events: none;
}
.observation-timeline {
display: block;
min-width: 0;
border: 0;
border-radius: 0.9rem;
background: rgb(9 10 13 / 0.78);
padding: 0.4rem;
backdrop-filter: blur(16px);
}
.observation-timeline[data-accumulation="true"] {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
align-items: center;
gap: 0.8rem;
}
.observation-timeline__playback {
display: grid;
min-width: 0;
grid-template-columns: auto auto minmax(0, 1fr) auto auto;
align-items: center;
gap: 0.6rem;
}
.observation-timeline__playback > .nodedc-select-anchor {
display: inline-flex;
width: auto;
flex: none;
}
.observation-timeline__transport {
width: var(--nodedc-control-height-compact);
padding: 0;
border-radius: var(--nodedc-radius-circle);
}
.observation-timeline__accumulation {
display: grid;
min-width: 0;
grid-template-columns: auto minmax(0, 1fr) auto;
align-items: center;
gap: 0.7rem;
padding: 0 0.45rem;
}
.observation-timeline__accumulation span,
.observation-timeline__accumulation code {
color: var(--nodedc-text-muted);
font-size: 0.55rem;
white-space: nowrap;
}
.observation-timeline__accumulation code {
min-width: 2.65rem;
color: var(--nodedc-text-primary);
text-align: right;
}
.observation-timeline__track {
width: 100%;
height: 0.3rem;
appearance: none;
border: 0;
border-radius: 999px;
background: rgb(255 255 255 / 0.08);
cursor: pointer;
}
.observation-timeline__track::-webkit-slider-thumb {
width: 0.72rem;
height: 0.72rem;
appearance: none;
border: 0;
border-radius: 50%;
background: var(--nodedc-text-primary);
}
.observation-timeline__track::-moz-range-thumb {
width: 0.72rem;
height: 0.72rem;
border: 0;
border-radius: 50%;
background: var(--nodedc-text-primary);
}
.observation-timeline__track:disabled {
opacity: 0.46;
cursor: default;
}
.observation-timeline__meta {
display: grid;
justify-items: end;
gap: 0.12rem;
}
.observation-timeline__meta code,
.observation-timeline__meta small {
color: var(--nodedc-text-muted);
font-size: 0.52rem;
white-space: nowrap;
}
.observation-timeline__follow {
display: inline-flex;
align-items: center;
gap: 0.38rem;
color: var(--nodedc-text-muted);
border: 0;
background: transparent;
padding: 0.3rem 0.45rem;
font-size: 0.52rem;
font-weight: 820;
}
.observation-timeline__follow:not(:disabled) {
cursor: pointer;
}
.observation-timeline__follow::before {
width: 0.4rem;
height: 0.4rem;
border-radius: 50%;
background: var(--nodedc-text-muted);
content: "";
}
.observation-timeline__follow[data-active="true"] {
color: var(--nodedc-text-primary);
}
.observation-timeline__follow[data-active="true"]::before {
background: rgb(var(--nodedc-success-rgb));
}
.scene-timeline {
position: absolute;
z-index: 10;
right: 0.75rem;
bottom: 0.75rem;
left: 0.75rem;
}
.spatial-workspace[data-focused="true"] {
min-height: 0;
grid-template-rows: minmax(0, 1fr);
gap: 0;
}
.spatial-workspace[data-focused="true"] > .spatial-toolbar,
.spatial-workspace[data-focused="true"] > .spatial-contract-strip {
display: none;
}
.cameras-workspace {
height: 100%;
min-height: 0;
grid-template-rows: auto auto minmax(0, 1fr) auto;
overflow: hidden;
padding-bottom: 0;
}
.camera-workspace__catalog {
display: flex;
min-width: 0;
align-items: center;
justify-content: flex-end;
gap: 0.8rem;
color: var(--nodedc-text-muted);
font-size: 0.6rem;
}
.camera-grid {
display: grid;
min-height: 0;
grid-template-columns: repeat(auto-fit, minmax(min(24rem, 100%), 1fr));
grid-template-rows: none;
grid-auto-rows: minmax(16rem, 1fr);
gap: 0.75rem;
overflow: auto;
}
.camera-grid[data-count="1"] {
grid-template-columns: minmax(0, 1fr);
}
.camera-grid__empty {
min-height: 18rem;
border-radius: 1rem;
background: #07080a;
box-shadow: none;
}
.camera-slot {
grid-template-rows: auto minmax(0, 1fr) auto;
}
.camera-slot header,
.camera-slot footer {
z-index: 2;
}
.camera-slot__head-actions,
.camera-slot__status {
display: flex;
align-items: center;
gap: 0.45rem;
}
.camera-slot__status {
color: var(--nodedc-text-muted);
font-size: 0.56rem;
}
.camera-slot__body {
position: relative;
z-index: 1;
min-width: 0;
min-height: 0;
overflow: hidden;
}
.camera-slot footer {
align-items: flex-end;
}
.camera-slot footer span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.camera-slot footer small {
flex: 0 0 auto;
color: var(--nodedc-text-secondary);
font-size: 0.53rem;
}
.camera-timeline {
position: relative;
}
.cameras-workspace[data-focused="true"] {
height: 100%;
grid-template-rows: minmax(0, 1fr) auto;
padding-bottom: 0;
}
.cameras-workspace[data-focused="true"] > .workspace-lead,
.cameras-workspace[data-focused="true"] > .camera-workspace__catalog {
display: none;
}
.cameras-workspace[data-focused="true"] .camera-grid {
min-height: 0;
overflow: hidden;
}
@media (max-width: 760px) {
.scene-status--top-left {
top: 4.2rem;
left: 0.6rem;
}
.observation-timeline[data-accumulation="true"] {
grid-template-columns: minmax(0, 1fr);
}
.observation-timeline__playback {
grid-template-columns: auto minmax(0, 1fr) auto;
}
.observation-timeline__playback > .nodedc-button:first-child,
.observation-timeline__meta {
display: none;
}
.camera-grid {
grid-template-columns: 1fr;
grid-auto-rows: minmax(14rem, 1fr);
}
}
@@ -3,9 +3,6 @@
grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-columns: repeat(2, minmax(0, 1fr));
} }
.landing-stage__copy {
width: min(35rem, 54%);
}
} }
@media (max-width: 1280px) { @media (max-width: 1280px) {
@@ -190,15 +187,6 @@
text-align: left; text-align: left;
} }
.landing-stage__status {
width: 20rem;
max-width: 36vw;
}
.landing-stage__copy h1 {
font-size: clamp(2.7rem, 7vw, 5.6rem);
}
.scene-metrics { .scene-metrics {
display: none; display: none;
} }
@@ -424,36 +412,6 @@
display: none; display: none;
} }
.landing-stage__copy {
top: 42%;
right: 1.2rem;
left: 1.2rem;
width: auto;
}
.landing-stage__copy h1 {
font-size: clamp(2.8rem, 14vw, 5rem);
}
.landing-stage__status {
top: auto;
right: 1rem;
bottom: 3.3rem;
left: 1rem;
width: auto;
max-width: none;
}
.landing-stage__footer {
right: 1rem;
bottom: 1.1rem;
left: 1rem;
}
.landing-stage__footer span:first-child {
display: none;
}
.metrics-grid, .metrics-grid,
.capability-summary, .capability-summary,
.camera-grid, .camera-grid,
@@ -645,20 +603,5 @@
} }
@media (max-height: 720px) and (min-width: 761px) { @media (max-height: 720px) and (min-width: 761px) {
.landing-stage__copy h1 {
font-size: clamp(2.7rem, 6vw, 5rem);
}
.landing-stage__copy p {
font-size: 0.76rem;
}
.landing-stage__actions {
margin-top: 1rem;
}
.landing-stage__status {
top: 1.2rem;
right: 1.2rem;
}
} }
@@ -1,83 +1 @@
.scene-tool-window { @import "../../../../packages/spatial-ui/src/scene-windows.css";
--scene-tool-window-top: 5.75rem;
--scene-tool-window-right: 27rem;
position: fixed;
top: var(--scene-tool-window-top);
right: var(--scene-tool-window-right);
max-height: calc(100vh - var(--scene-tool-window-top) - 1.5rem);
}
.scene-tool-window--display {
--scene-tool-window-top: 7.75rem;
--scene-tool-window-right: 28.5rem;
}
.scene-tool-window--layers {
--scene-tool-window-top: 9.75rem;
--scene-tool-window-right: 30rem;
}
.scene-tool-window--layout {
--scene-tool-window-top: 11.75rem;
--scene-tool-window-right: 31.5rem;
}
.nodedc-overlay:has(> .scene-tool-window[data-scene-active="true"]) {
z-index: calc(var(--nodedc-layer-overlay) + 1);
}
.nodedc-overlay[data-placement="center"] {
z-index: calc(var(--nodedc-layer-overlay) + 2);
}
.scene-window-state {
display: inline-flex;
min-width: 0;
align-items: center;
gap: 0.5rem;
color: var(--nodedc-text-secondary);
font-size: var(--nodedc-font-size-sm);
line-height: 1.3;
}
.scene-window-code {
display: block;
overflow: hidden;
border-radius: var(--nodedc-radius-control-compact);
background: var(--nodedc-field-bg);
color: var(--nodedc-text-secondary);
padding: 0.72rem 0.8rem;
font-size: var(--nodedc-font-size-xs);
line-height: 1.35;
text-overflow: ellipsis;
white-space: nowrap;
}
.scene-window-note {
margin: 0;
color: var(--nodedc-text-muted);
font-size: var(--nodedc-font-size-xs);
line-height: 1.5;
}
@media (max-width: 44rem) {
.scene-tool-window,
.scene-tool-window--display,
.scene-tool-window--layers,
.scene-tool-window--layout {
--scene-tool-window-top: 4.75rem;
--scene-tool-window-right: 0.875rem;
max-height: calc(100vh - 5.625rem);
}
}
@media (min-width: 44.01rem) and (max-width: 70rem) {
.scene-tool-window,
.scene-tool-window--display,
.scene-tool-window--layers,
.scene-tool-window--layout {
--scene-tool-window-top: 13.5rem;
--scene-tool-window-right: 1.5rem;
max-height: calc(100vh - 15rem);
}
}
-113
View File
@@ -48,116 +48,3 @@
height: 100%; height: 100%;
overflow: hidden; overflow: hidden;
} }
.landing-stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
border-radius: var(--nodedc-radius-card);
background: var(--station-stage);
}
.landing-stage__media,
.landing-stage__shade {
position: absolute;
inset: 0;
}
.landing-stage__media img,
.landing-stage__media video {
width: 100%;
height: 100%;
display: block;
object-fit: cover;
}
.landing-stage__shade {
z-index: 1;
background:
linear-gradient(90deg, rgb(5 6 8 / 0.82) 0%, rgb(5 6 8 / 0.54) 46%, rgb(5 6 8 / 0.24) 100%),
linear-gradient(0deg, rgb(5 6 8 / 0.58), transparent 38%);
pointer-events: none;
}
.landing-stage:not([data-has-media="true"]) .landing-stage__shade {
background:
radial-gradient(circle at 68% 42%, rgb(255 255 255 / 0.035), transparent 34%),
linear-gradient(90deg, rgb(5 6 8 / 0.2), transparent 62%);
}
.landing-stage__copy {
position: absolute;
z-index: 2;
top: 50%;
left: clamp(2rem, 5vw, 6rem);
width: min(39rem, 50%);
transform: translateY(-55%);
}
.landing-stage__copy h1 {
margin: 0.75rem 0 1rem;
color: var(--nodedc-text-primary);
font-size: clamp(3rem, 7vw, 7.6rem);
font-weight: 600;
letter-spacing: -0.072em;
line-height: 0.87;
}
.landing-stage__copy p {
max-width: 34rem;
margin: 0;
color: var(--nodedc-text-secondary);
font-size: clamp(0.8rem, 1vw, 1rem);
line-height: 1.6;
}
.landing-stage__actions {
display: flex;
flex-wrap: wrap;
gap: 0.65rem;
margin-top: 1.6rem;
}
.landing-stage__status {
position: absolute;
z-index: 2;
top: 2.4rem;
right: 2.4rem;
display: grid;
width: min(24rem, 30vw);
gap: 0.6rem;
border-radius: 1.25rem;
background: rgb(10 10 12 / 0.58);
padding: 1rem;
backdrop-filter: blur(18px);
}
.landing-stage__status > div {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
.landing-stage__status p {
margin: 0.15rem 0 0;
color: var(--nodedc-text-muted);
font-size: 0.66rem;
line-height: 1.45;
}
.landing-stage__footer {
position: absolute;
z-index: 2;
right: 2.4rem;
bottom: 1.8rem;
left: 2.4rem;
display: flex;
justify-content: space-between;
gap: 1rem;
color: var(--nodedc-text-muted);
font-size: 0.57rem;
font-weight: 780;
letter-spacing: 0.12em;
}
+1 -484
View File
@@ -1,484 +1 @@
.spatial-workspace { @import "../../../../packages/spatial-ui/src/spatial.css";
display: grid;
width: 100%;
height: 100%;
min-width: 0;
min-height: 34rem;
grid-template-rows: auto minmax(0, 1fr) auto;
gap: 0.65rem;
overflow: hidden;
}
.spatial-toolbar {
display: flex;
min-width: 0;
align-items: center;
justify-content: flex-start;
gap: 1rem;
}
.spatial-toolbar__actions {
display: flex;
min-width: 0;
align-items: center;
gap: 0.45rem;
}
.spatial-toolbar__view-switch {
display: inline-flex;
align-items: center;
gap: 0.25rem;
border: 1px solid rgb(255 255 255 / 0.07);
border-radius: 999px;
background: rgb(255 255 255 / 0.025);
padding: 0.2rem;
}
.spatial-toolbar__view-switch .nodedc-button {
border-radius: 999px;
}
.spatial-viewport-shell {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
border-radius: 1rem;
background: #06070a;
box-shadow: none;
}
.rerun-viewport,
.rerun-viewport__canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
}
.rerun-viewport__canvas[data-presented="false"] {
visibility: hidden;
}
.recorded-session-preloaders {
position: fixed;
left: -10000px;
top: -10000px;
width: 1px;
height: 1px;
overflow: hidden;
opacity: 0;
pointer-events: none;
}
.rerun-viewport {
--rerun-native-chrome-height: 72px;
overflow: hidden;
}
/* The upstream Rerun canvas keeps three fixed 24px rows even after its
panels are overridden: the native top row, recording tab and view tab.
They are drawn inside WASM and cannot be styled independently, so crop the
fixed native chrome while keeping the actual 3D viewport full-height. */
.rerun-viewport__canvas {
top: calc(-1 * var(--rerun-native-chrome-height));
bottom: auto;
height: calc(100% + var(--rerun-native-chrome-height));
}
.rerun-viewport__runtime {
display: block;
width: 100%;
height: 100%;
border: 0;
}
.rerun-viewport__canvas canvas {
display: block;
width: 100% !important;
height: 100% !important;
}
.rerun-viewport__camera-lock {
position: absolute;
z-index: 2;
top: 0;
bottom: 0;
left: 0;
width: calc(46% - 2px);
cursor: default;
touch-action: none;
}
.rerun-viewport:is([data-status="loading"], [data-status="error"])
.rerun-viewport__canvas {
visibility: hidden;
pointer-events: none;
}
.rerun-viewport__notice {
position: absolute;
top: 50%;
left: 50%;
display: flex;
align-items: center;
gap: 0.8rem;
border: 0;
border-radius: 1rem;
background: rgb(10 11 14 / 0.82);
padding: 0.9rem 1rem;
transform: translate(-50%, -50%);
backdrop-filter: blur(18px);
}
.rerun-viewport__notice strong,
.rerun-viewport__notice span {
display: block;
}
.rerun-viewport__notice strong {
font-size: 0.72rem;
}
.rerun-viewport__notice span {
margin-top: 0.18rem;
color: var(--nodedc-text-muted);
font-size: 0.61rem;
}
.rerun-viewport__notice--error {
background: rgb(10 11 14 / 0.9);
}
.rerun-viewport__retry {
margin-top: 0.65rem;
border: 1px solid var(--station-hairline-strong);
border-radius: 999px;
background: rgb(255 255 255 / 0.08);
padding: 0.42rem 0.7rem;
color: var(--nodedc-text-primary);
font: inherit;
font-size: 0.61rem;
cursor: pointer;
}
.rerun-viewport__retry:hover,
.rerun-viewport__retry:focus-visible {
background: rgb(255 255 255 / 0.14);
outline: none;
}
.busy-indicator {
width: 1rem;
height: 1rem;
flex: 0 0 1rem;
border: 2px solid rgb(255 255 255 / 0.12);
border-top-color: var(--nodedc-text-primary);
border-radius: 50%;
animation: viewer-spin 900ms linear infinite;
}
@keyframes viewer-spin {
to { transform: rotate(360deg); }
}
.empty-spatial-stage {
position: absolute;
inset: 0;
overflow: hidden;
background: #06070a;
}
.empty-spatial-stage__grid {
display: none;
}
.spatial-axis {
position: absolute;
right: 2rem;
bottom: 5.2rem;
width: 4.4rem;
height: 4.4rem;
color: var(--nodedc-text-muted);
font-size: 0.53rem;
}
.spatial-axis::before,
.spatial-axis::after {
position: absolute;
bottom: 0.65rem;
left: 0.75rem;
width: 2.7rem;
height: 1px;
background: rgb(255 255 255 / 0.2);
content: "";
transform-origin: left center;
}
.spatial-axis::before { transform: rotate(-24deg); }
.spatial-axis::after { transform: rotate(-90deg); }
.spatial-axis span { position: absolute; }
.spatial-axis span[data-axis="x"] { right: 0; bottom: 0; color: var(--nodedc-text-muted); }
.spatial-axis span[data-axis="y"] { top: 0; left: 0.55rem; color: var(--nodedc-text-muted); }
.spatial-axis span[data-axis="z"] { right: 0.55rem; bottom: 2.2rem; color: var(--nodedc-text-muted); }
.empty-spatial-stage__message {
position: absolute;
top: 50%;
left: 50%;
display: grid;
max-width: 25rem;
justify-items: center;
gap: 0.62rem;
transform: translate(-50%, -58%);
text-align: center;
}
.empty-spatial-stage__icon {
display: grid;
width: 3.4rem;
height: 3.4rem;
place-items: center;
border: 0;
border-radius: 50%;
background: rgb(255 255 255 / 0.035);
color: var(--nodedc-text-secondary);
}
.empty-spatial-stage__message strong {
color: var(--nodedc-text-primary);
font-size: 0.82rem;
}
.empty-spatial-stage__message p {
margin: 0;
color: var(--nodedc-text-muted);
font-size: 0.67rem;
line-height: 1.5;
}
.scene-status,
.scene-metrics,
.scene-adapter-note,
.scene-selection,
.scene-timeline {
position: absolute;
z-index: 3;
border: 0;
background: rgb(9 10 13 / 0.74);
backdrop-filter: blur(16px);
}
.scene-status--top-left {
top: 0.85rem;
left: 0.85rem;
display: grid;
justify-items: start;
gap: 0.42rem;
border-radius: 0.9rem;
padding: 0.7rem;
}
.scene-status small {
max-width: 18rem;
color: var(--nodedc-text-muted);
font-size: 0.57rem;
line-height: 1.35;
}
.scene-metrics {
top: 0.85rem;
right: 0.85rem;
display: grid;
min-width: 10rem;
border-radius: 0.9rem;
padding: 0.35rem 0.75rem;
}
.scene-metrics > div {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 1rem;
border-bottom: 0;
padding: 0.38rem 0;
}
.scene-metrics > div:last-child { border-bottom: 0; }
.scene-metrics span { color: var(--nodedc-text-muted); font-size: 0.56rem; }
.scene-metrics strong { color: var(--nodedc-text-primary); font-size: 0.72rem; }
.scene-metrics small { color: var(--nodedc-text-muted); font-size: 0.52rem; font-weight: 500; }
.scene-adapter-note {
top: 50%;
left: 50%;
display: flex;
max-width: 34rem;
align-items: center;
gap: 0.65rem;
border-radius: 0.9rem;
color: var(--nodedc-text-secondary);
padding: 0.75rem 0.9rem;
font-size: 0.63rem;
line-height: 1.4;
transform: translate(-50%, 5.2rem);
}
.scene-adapter-note > svg { flex: 0 0 auto; color: var(--nodedc-text-secondary); }
.scene-selection {
right: 0.85rem;
bottom: 4.6rem;
display: grid;
max-width: 19rem;
gap: 0.2rem;
border-radius: 0.85rem;
padding: 0.65rem 0.75rem;
}
.scene-selection span,
.scene-selection small { color: var(--nodedc-text-muted); font-size: 0.55rem; }
.scene-selection strong { overflow: hidden; font-size: 0.66rem; text-overflow: ellipsis; white-space: nowrap; }
.scene-operation-status-stack {
position: absolute;
z-index: 11;
left: 0.85rem;
bottom: 7.15rem;
display: grid;
justify-items: start;
gap: 0.3rem;
}
.scene-operation-status {
display: inline-flex;
max-width: min(24rem, calc(100% - 1.7rem));
align-items: center;
gap: 0.42rem;
border: 1px solid rgb(255 255 255 / 0.07);
border-radius: 999px;
background: rgb(9 10 13 / 0.7);
color: var(--nodedc-text-muted);
padding: 0.42rem 0.65rem;
font: inherit;
font-size: 0.52rem;
font-weight: 680;
line-height: 1;
white-space: nowrap;
backdrop-filter: blur(14px);
}
.scene-operation-status .busy-indicator {
width: 0.66rem;
height: 0.66rem;
flex-basis: 0.66rem;
border-width: 1px;
}
.scene-operation-status--action {
color: var(--nodedc-text-secondary);
cursor: pointer;
}
.scene-operation-status--action:hover,
.scene-operation-status--action:focus-visible {
border-color: rgb(255 255 255 / 0.14);
background: rgb(20 21 25 / 0.82);
color: var(--nodedc-text-primary);
outline: none;
}
.scene-operation-status--error {
color: rgb(var(--nodedc-danger-rgb));
}
.scene-timeline {
right: 0.75rem;
bottom: 0.75rem;
left: 0.75rem;
display: grid;
min-width: 0;
grid-template-columns: auto auto minmax(0, 1fr) auto auto;
align-items: center;
gap: 0.6rem;
border-radius: 0.9rem;
padding: 0.4rem;
}
.scene-timeline__track {
height: 0.3rem;
overflow: hidden;
border-radius: 999px;
background: rgb(255 255 255 / 0.08);
}
.scene-timeline__track span {
display: block;
height: 100%;
border-radius: inherit;
background: var(--nodedc-text-primary);
}
.scene-timeline__track[data-disabled="true"] { opacity: 0.46; }
.scene-timeline code { color: var(--nodedc-text-muted); font-size: 0.57rem; }
.scene-timeline__follow {
display: inline-flex;
align-items: center;
gap: 0.38rem;
border-radius: var(--nodedc-radius-circle);
background: transparent;
color: var(--nodedc-text-muted);
padding: 0.3rem 0.45rem;
font-size: 0.52rem;
font-weight: 820;
}
.scene-timeline__follow::before {
width: 0.4rem;
height: 0.4rem;
border-radius: 50%;
background: var(--nodedc-text-muted);
content: "";
}
.scene-timeline__follow[data-active="true"] {
background: transparent;
color: var(--nodedc-text-primary);
}
.scene-timeline__follow[data-active="true"]::before {
background: rgb(var(--nodedc-success-rgb));
}
.spatial-contract-strip {
display: flex;
min-width: 0;
flex-wrap: wrap;
align-items: center;
gap: 0.45rem 1rem;
color: var(--nodedc-text-muted);
font-size: 0.57rem;
}
.spatial-contract-strip span {
display: inline-flex;
align-items: center;
gap: 0.38rem;
}
.spatial-contract-strip i {
width: 0.42rem;
height: 0.42rem;
border-radius: 50%;
background: var(--nodedc-text-muted);
}
.spatial-contract-strip i[data-state="ready"] { background: var(--nodedc-text-primary); }
.spatial-contract-strip i[data-state="contract"] { background: rgb(var(--nodedc-warning-rgb)); }
@media (prefers-reduced-motion: reduce) {
.busy-indicator { animation: none; }
}
@@ -1,3 +1,5 @@
import {SpatialScene, EmptySpatialStage} from '../../../../packages/spatial-ui/src';
import {SpatialToolbarActions} from "../../../../packages/spatial-ui/src/SpatialToolbarActions";
import { VehiclesWorkspace } from "./fleet/VehiclesWorkspace"; import { VehiclesWorkspace } from "./fleet/VehiclesWorkspace";
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Button, GlassSurface, Icon, StatusBadge } from "@nodedc/ui-react"; import { Button, GlassSurface, Icon, StatusBadge } from "@nodedc/ui-react";
@@ -32,7 +34,6 @@ import {
type WorkspaceDefinition, type WorkspaceDefinition,
} from "../productModel"; } from "../productModel";
import { finiteMetric, formatNumber, pipelineLatency, sourceModeLabel } from "../presentation"; import { finiteMetric, formatNumber, pipelineLatency, sourceModeLabel } from "../presentation";
import type { SceneSettings } from "../sceneSettings";
import type { WorkspaceRendererProps } from "./contracts"; import type { WorkspaceRendererProps } from "./contracts";
import { DatasetGatewayWorkspace } from "./DatasetGatewayWorkspace"; import { DatasetGatewayWorkspace } from "./DatasetGatewayWorkspace";
import { ArtifactHealthWorkspace } from "./data/ArtifactHealthWorkspace"; import { ArtifactHealthWorkspace } from "./data/ArtifactHealthWorkspace";
@@ -90,26 +91,6 @@ function WorkspaceLead({ definition, note }: { definition: WorkspaceDefinition;
</section> </section>
); );
} }
function EmptySpatialStage({ settings }: { settings: SceneSettings }) {
return (
<div className="empty-spatial-stage" data-grid={settings.showGrid ? "true" : undefined}>
<div className="empty-spatial-stage__grid" aria-hidden="true" />
<div className="spatial-axis" aria-hidden="true">
<span data-axis="x">X</span>
<span data-axis="z">Z</span>
</div>
<div className="empty-spatial-stage__message">
<span className="empty-spatial-stage__icon"><Icon name="globe" size={20} /></span>
<strong>Визуальный источник не назначен</strong>
<p>
Область сцены не подставляет демонстрационные точки. Назначьте RRD или Rerun gRPC, чтобы
открыть реальные данные.
</p>
</div>
</div>
);
}
function SpatialWorkspace({ function SpatialWorkspace({
state, state,
sourceUrl, sourceUrl,
@@ -411,14 +392,9 @@ function SpatialWorkspace({
: null, : null,
}); });
return ( return <SpatialScene viewportRef={viewportRef} focused={pointCloudFocused||floatingSourceMaximized}
<div primaryFocused={pointCloudFocused} mediaMaximized={floatingSourceMaximized}
className="spatial-workspace" toolbar={<> {recordedPerceptionSupported || livePerceptionAvailable ? (
data-focused={pointCloudFocused || floatingSourceMaximized ? "true" : undefined}
>
<div className="spatial-toolbar" data-viewer-controls="v1">
<div className="spatial-toolbar__actions">
{recordedPerceptionSupported || livePerceptionAvailable ? (
<div className="spatial-toolbar__view-switch" role="group" aria-label="Слои распознавания сцены"> <div className="spatial-toolbar__view-switch" role="group" aria-label="Слои распознавания сцены">
<Button <Button
size="compact" size="compact"
@@ -498,25 +474,7 @@ function SpatialWorkspace({
Сброс вида Сброс вида
</Button> </Button>
) : null} ) : null}
<Button size="compact" variant="secondary" icon={<Icon name="network" />} onClick={navigation.openSource}> <SpatialToolbarActions openSource={navigation.openSource} openLayers={navigation.openLayers} openDisplay={navigation.openDisplay}/></>} renderer={<> {sourceUrl.trim() && pointCloudVisible && !intentionalSourceEnd ? (
Движок
</Button>
<Button size="compact" variant="secondary" icon={<Icon name="list" />} onClick={navigation.openLayers}>
Слои
</Button>
<Button size="compact" variant="secondary" icon={<Icon name="sliders" />} onClick={navigation.openDisplay}>
Отображение
</Button>
</div>
</div>
<div
ref={viewportRef}
className="spatial-viewport-shell"
data-primary-focused={pointCloudFocused ? "true" : undefined}
data-media-maximized={floatingSourceMaximized ? "true" : undefined}
>
{sourceUrl.trim() && pointCloudVisible && !intentionalSourceEnd ? (
<RerunViewport <RerunViewport
profile={rerunViewerProfile} profile={rerunViewerProfile}
sceneSettings={sceneSettings} sceneSettings={sceneSettings}
@@ -530,20 +488,15 @@ function SpatialWorkspace({
) : ( ) : (
<EmptySpatialStage settings={sceneSettings} /> <EmptySpatialStage settings={sceneSettings} />
)} )}
</>}
{spatialControls && !recordedSource ? ( deviceControls={spatialControls&&!recordedSource?( <spatialControls.View
<div className="scene-device-controls">
<spatialControls.View
model={spatialControls.model} model={spatialControls.model}
host={{ host={{
openSpatialScene: () => navigation.openView("spatial-scene"), openSpatialScene: () => navigation.openView("spatial-scene"),
activateAutomaticSpatialSource: navigation.activateAutomaticSpatialSource, activateAutomaticSpatialSource: navigation.activateAutomaticSpatialSource,
}} }}
/> />):null}
</div> sourceControls={<> {pointCloudFocused ? (
) : null}
{pointCloudFocused ? (
<button <button
type="button" type="button"
className="scene-focus-exit" className="scene-focus-exit"
@@ -574,22 +527,9 @@ function SpatialWorkspace({
) : null} ) : null}
</div> </div>
) : null} ) : null}
</>}
<div status={{label:viewerStatusLabel,tone:viewerStatusTone,message:!intentionalSourceEnd?viewerMessage:undefined}}
className="scene-status scene-status--top-left" metrics={<> <div>
aria-hidden={pointCloudFocused || floatingSourceMaximized}
>
<span className="section-eyebrow">ВИЗУАЛЬНЫЙ ДВИЖОК</span>
<StatusBadge tone={viewerStatusTone}>{viewerStatusLabel}</StatusBadge>
{!intentionalSourceEnd && viewerMessage ? <small>{viewerMessage}</small> : null}
</div>
<div
className="scene-metrics"
aria-label="Метрики пространственной сцены"
aria-hidden={pointCloudFocused || floatingSourceMaximized}
>
<div>
<span>КАДР/С</span> <span>КАДР/С</span>
<strong>{formatNumber(frameRate)}</strong> <strong>{formatNumber(frameRate)}</strong>
</div> </div>
@@ -610,10 +550,7 @@ function SpatialWorkspace({
{aiFrameRate === null ? null : <small> · {formatNumber(aiFrameRate)} Гц</small>} {aiFrameRate === null ? null : <small> · {formatNumber(aiFrameRate)} Гц</small>}
</strong> </strong>
</div> </div>
) : null} ) : null}</>} overlays={<> {!pointCloudFocused && !floatingSourceMaximized && state?.sourceMode && state.sourceMode !== "idle" && !sourceUrl.trim() ? (
</div>
{!pointCloudFocused && !floatingSourceMaximized && state?.sourceMode && state.sourceMode !== "idle" && !sourceUrl.trim() ? (
<div className="scene-adapter-note"> <div className="scene-adapter-note">
<Icon name="alert" /> <Icon name="alert" />
<span> <span>
@@ -668,14 +605,8 @@ function SpatialWorkspace({
</div> </div>
) : null} ) : null}
{presentedViewerStatus === "ready" && !floatingSourceMaximized ? ( </>}
<div className="scene-navigation-hint" aria-label="Навигация по 3D-сцене"> navigationReady={presentedViewerStatus==='ready'} timeline={<> {!pointCloudFocused && !floatingSourceMaximized && recordedPlaybackReady ? (
<span>Колесо · зум к курсору</span>
<span>WASD · свободный проход</span>
</div>
) : null}
{!pointCloudFocused && !floatingSourceMaximized && recordedPlaybackReady ? (
<ObservationTimeline <ObservationTimeline
active={presentedViewerStatus === "ready"} active={presentedViewerStatus === "ready"}
sourceCount={Math.max(1, (unifiedPerception ? 2 : 1) + presentedMediaSourceCount)} sourceCount={Math.max(1, (unifiedPerception ? 2 : 1) + presentedMediaSourceCount)}
@@ -698,8 +629,8 @@ function SpatialWorkspace({
className="scene-timeline" className="scene-timeline"
/> />
) : null} ) : null}
</>}
{visibleMediaSources.map((source, index) => ( media={<> {visibleMediaSources.map((source, index) => (
<FloatingObservationWindow <FloatingObservationWindow
key={source.id} key={source.id}
source={source} source={source}
@@ -750,10 +681,7 @@ function SpatialWorkspace({
/> />
))} ))}
</div> </div>
) : null} ) : null}</>} footer={ <div className="spatial-contract-strip">
</div>
<div className="spatial-contract-strip">
<span><i data-state="ready" />Облако точек</span> <span><i data-state="ready" />Облако точек</span>
<span><i data-state="ready" />Траектория</span> <span><i data-state="ready" />Траектория</span>
<span><i data-state="ready" />Преобразования</span> <span><i data-state="ready" />Преобразования</span>
@@ -762,9 +690,7 @@ function SpatialWorkspace({
<span><i data-state={segmentationActive ? "ready" : "contract"} />Сегментация</span> <span><i data-state={segmentationActive ? "ready" : "contract"} />Сегментация</span>
<span><i data-state={cuboids3dActive ? "ready" : "contract"} />Кубы 3D</span> <span><i data-state={cuboids3dActive ? "ready" : "contract"} />Кубы 3D</span>
<span><i data-state="contract" />Компоновка</span> <span><i data-state="contract" />Компоновка</span>
</div> </div>}/>;
</div>
);
} }
function CameraSourceCard({ function CameraSourceCard({
@@ -0,0 +1,45 @@
import {useState} from 'react';
import {ActivityIndicator,Button,Icon,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge,TextField,ToastStack} from '@nodedc/ui-react';
import {useBoardMonitor,monitorSeries,monitorValue} from '../../core/fleet/boardMonitor';
import {TelemetrySeries} from '../../components/system/TelemetrySeries';
import '../../styles/system-telemetry.css';
import './board-monitor.css';
const eventLabels:Record<string,string>={'ui-error':'Ошибка интерфейса','ui-rejection':'Ошибка асинхронной операции','ui-render-error':'Ошибка представления','system-oom':'Нехватка памяти','gpu-reset':'Сброс GPU','disk-error':'Ошибка диска','usb-disconnected':'Отключение USB','usb-error':'Ошибка USB','service-failed':'Сбой службы','ui-process-exit':'Завершение процесса окна','ui-load-failed':'Ошибка загрузки окна'};
const time=(value:number)=>new Date(value*1000).toLocaleString('ru-RU');
export function BoardMonitorView({vehicle,name,back}:{vehicle:string;name:string;back:()=>void}) {
const [metric,setMetric]=useState('cpu.usage'),[group,setGroup]=useState('CPU'),[window,setWindow]=useState(900),[end,setEnd]=useState<number|null>(null),[mode,setMode]=useState<'min'|'max'|'mean'>('max');
const {value,error,dismissError}=useBoardMonitor(vehicle,metric,window,end);
const definitions=value?.definitions??{},definition=definitions[metric];
const groups=[...new Set(Object.values(definitions).map(item=>item.group))];
const metrics=Object.entries(definitions).filter(([,item])=>item.group===group);
const latest=value?.latest;
return <div className="board-monitor">
<div><Button onClick={back}><Icon name="chevron-left"/>К аппарату</Button></div>
<SettingsCard title="Мониторинг системы БК" description={name} actions={<StatusBadge tone={value?.fresh&&!error?'success':'neutral'}>{value?.fresh&&!error?'Данные поступают':'Нет свежих данных'}</StatusBadge>}>
{latest&&<p>Измерено на БК: {time(latest.at)}. {value?.storage==='ready'?'Локальная история записывается.':'Запись локальной истории недоступна.'} {value?.backlog?'История догружается в Mission Core.':''}</p>}
{value?.database_bytes!=null&&<p>Архив на БК: {monitorValue(value.database_bytes,'bytes')} из {monitorValue(value.database_budget_bytes,'bytes')}. {value.archive_since?`Копия в Mission Core с ${time(value.archive_since)}.`:''}</p>}
</SettingsCard>
{!value?<ActivityIndicator label="Получаем мониторинг БК"/>:!value.available?<SettingsCard title="История БК пока не получена" description="Данные появятся после подключения бортового сборщика телеметрии."/>:<>
<SettingsCard title="История нагрузки">
<div className="board-monitor-controls">
<Select label="Ресурс" value={group} options={groups.map(label=>({value:label,label}))} onChange={next=>{setGroup(next);const first=Object.entries(definitions).find(([,item])=>item.group===next);if(first)setMetric(first[0]);}}/>
<Select label="Показатель" value={metric} options={metrics.map(([key,item])=>({value:key,label:`${item.resource} · ${item.label}`}))} onChange={setMetric}/>
<Select label="Период" value={String(window)} options={[{value:'900',label:'15 минут'},{value:'3600',label:'1 час'},{value:'21600',label:'6 часов'},{value:'86400',label:'24 часа'},{value:'604800',label:'7 дней'}]} onChange={next=>setWindow(Number(next))}/>
<Select label="Значение в интервале" value={mode} options={[{value:'max',label:'Максимум'},{value:'mean',label:'Среднее'},{value:'min',label:'Минимум'}]} onChange={next=>setMode(next as typeof mode)}/>
</div>
<div className="board-monitor-controls"><Button onClick={()=>setEnd(end===null?Date.now()/1000:null)}>{end===null?'Зафиксировать время':'В реальном времени'}</Button>{end!==null&&<TextField label="Конец периода" type="datetime-local" step="1" value={new Date((end-new Date(end*1000).getTimezoneOffset()*60)*1000).toISOString().slice(0,19)} onChange={event=>{const next=new Date(event.target.value).getTime()/1000;if(Number.isFinite(next))setEnd(next);}}/>}</div>
<TelemetrySeries label={definition?`${definition.resource} · ${definition.label}`:'Загрузка CPU'} resource="Последний интервал периода" value={monitorValue(value.series.at(-1)?.[mode],definition?.unit)} values={monitorSeries(value,mode)} ceiling={definition?.unit==='%'?100:undefined}/>
<p>{time(value.start)} — {time(value.end)} · интервал {value.bucket_seconds} с. Разрывы означают отсутствие измерений.</p>
{!value.series.length&&<p>За выбранный период измерений нет.</p>}
</SettingsCard>
<SettingsCard title={`Последние измерения · ${group}`} description={latest?time(latest.at):'Ожидаем измерения'}>
<ResourceList aria-label="Показатели системы">{metrics.map(([key,item])=><li key={key}><ResourceRow title={`${item.resource} · ${item.label}`} description={latest?.values[key]==null?item.reason??'Счётчик недоступен':undefined} metadata={monitorValue(latest?.values[key],item.unit)}/></li>)}</ResourceList>
</SettingsCard>
<SettingsCard title="События системы и приложения" description="За выбранный период">
{value.events.length?<ResourceList aria-label="События БК">{value.events.map((event,index)=><li key={`${event.at}-${index}`}><ResourceRow title={eventLabels[event.code]??'Событие системы'} description={time(event.at)}/></li>)}</ResourceList>:<p>Событий не получено.</p>}
</SettingsCard>
</>}
<ToastStack items={error?[{id:'monitor-error',title:error,tone:'error',durationMs:null}]:[]} onDismiss={dismissError}/>
</div>;
}
@@ -6,9 +6,7 @@ import type {SensorInventory,SensorTransport} from '../../../../../packages/sens
import {fleetRequest} from '../../core/fleet/useFleet'; import {fleetRequest} from '../../core/fleet/useFleet';
export function VehicleSensors({vehicleID,enabled,onDetailChange}:{vehicleID:string;enabled:boolean;onDetailChange:(open:boolean)=>void}){ export function VehicleSensors({vehicleID,enabled,onDetailChange}:{vehicleID:string;enabled:boolean;onDetailChange:(open:boolean)=>void}){
const {registry}=useDevicePluginHost(); const {registry}=useDevicePluginHost();
const sensorContributions=useMemo(()=>registry.plugins.flatMap(plugin=>plugin.sensorUi?.contributions??[]),[registry]); const sensorContributions=registry.sensorContributions;
const enrollmentViews=registry.plugins.flatMap(plugin=>plugin.sensorUi?.Enrollment?[plugin.sensorUi.Enrollment]:[]);
const SensorEnrollmentView=enrollmentViews.length===1?enrollmentViews[0]:undefined;
const transport=useMemo<SensorTransport>(()=>({ const transport=useMemo<SensorTransport>(()=>({
enrollment:{ enrollment:{
state:()=>fleetRequest(`/${encodeURIComponent(vehicleID)}/devices/enrollment`), state:()=>fleetRequest(`/${encodeURIComponent(vehicleID)}/devices/enrollment`),
@@ -20,5 +18,5 @@ export function VehicleSensors({vehicleID,enabled,onDetailChange}:{vehicleID:str
submit:value=>fleetRequest(`/${encodeURIComponent(vehicleID)}/devices/operations`,'POST',value), submit:value=>fleetRequest(`/${encodeURIComponent(vehicleID)}/devices/operations`,'POST',value),
operation:id=>fleetRequest(`/${encodeURIComponent(vehicleID)}/devices/operations/${encodeURIComponent(id)}`), operation:id=>fleetRequest(`/${encodeURIComponent(vehicleID)}/devices/operations/${encodeURIComponent(id)}`),
}),[vehicleID]); }),[vehicleID]);
return <SensorWorkspace contributions={sensorContributions} EnrollmentView={SensorEnrollmentView} createRerunHost={createIsolatedRerunHost} key={vehicleID} transport={transport} enabled={enabled} onDetailChange={onDetailChange}/>; return <SensorWorkspace contributions={sensorContributions} createRerunHost={createIsolatedRerunHost} key={vehicleID} transport={transport} enabled={enabled} onDetailChange={onDetailChange}/>;
} }
@@ -1,5 +1,6 @@
import {BoardMonitorView} from './BoardMonitorView';
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { ActivityIndicator, Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow, Select, SettingsCard, StatusBadge, TextAreaField, TextField, Window, WindowFooterActions } from "@nodedc/ui-react"; import { LoadingRegion, Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow, Select, SettingsCard, StatusBadge, TextAreaField, TextField, Window, WindowFooterActions } from "@nodedc/ui-react";
import { fleetRequest, useFleet, type FleetPreview, type Vehicle } from "../../core/fleet/useFleet"; import { fleetRequest, useFleet, type FleetPreview, type Vehicle } from "../../core/fleet/useFleet";
import "./fleet.css"; import "./fleet.css";
import { VehicleSensors } from "./VehicleSensors"; import { VehicleSensors } from "./VehicleSensors";
@@ -19,6 +20,7 @@ export function VehiclesWorkspace({ createRequest = 0 }: { createRequest?: numbe
const [error, setError] = useState(""); const [error, setError] = useState("");
const [selected, setSelected] = useState<string | null>(null); const [selected, setSelected] = useState<string | null>(null);
const [sensorOpen, setSensorOpen] = useState(false); const [sensorOpen, setSensorOpen] = useState(false);
const [monitorOpen,setMonitorOpen]=useState(false);
const [revoking, setRevoking] = useState<Vehicle | null>(null); const [revoking, setRevoking] = useState<Vehicle | null>(null);
const lastCreateRequest = useRef(createRequest); const lastCreateRequest = useRef(createRequest);
useEffect(() => { if (createRequest !== lastCreateRequest.current) { lastCreateRequest.current = createRequest; setAdding(true); setError(""); } }, [createRequest]); useEffect(() => { if (createRequest !== lastCreateRequest.current) { lastCreateRequest.current = createRequest; setAdding(true); setError(""); } }, [createRequest]);
@@ -40,6 +42,7 @@ export function VehiclesWorkspace({ createRequest = 0 }: { createRequest?: numbe
finally { setPending(false); } finally { setPending(false); }
} }
const detail = fleet.items?.find(item => item.id === selected); const detail = fleet.items?.find(item => item.id === selected);
if(detail&&monitorOpen)return <BoardMonitorView vehicle={detail.id} name={detail.name} back={()=>setMonitorOpen(false)}/>;
return <div className="fleet-workspace"> return <div className="fleet-workspace">
{fleet.error && <p role="alert">{fleet.error}</p>} {fleet.error && <p role="alert">{fleet.error}</p>}
{!adding && error && <p role="alert">{error}</p>} {!adding && error && <p role="alert">{error}</p>}
@@ -51,10 +54,11 @@ export function VehiclesWorkspace({ createRequest = 0 }: { createRequest?: numbe
<div><dt>Последняя связь</dt><dd>{detail.last_seen ? new Date(detail.last_seen * 1000).toLocaleString("ru-RU") : "Соединение ещё не получено"}</dd></div> <div><dt>Последняя связь</dt><dd>{detail.last_seen ? new Date(detail.last_seen * 1000).toLocaleString("ru-RU") : "Соединение ещё не получено"}</dd></div>
{detail.host && <><div><dt>Имя БК в системе</dt><dd>{detail.host.hostname}</dd></div><div><dt>Операционная система</dt><dd>{detail.host.os}</dd></div><div><dt>Архитектура</dt><dd>{detail.host.architecture}</dd></div><div><dt>Процессоры</dt><dd>{detail.host.cpus}</dd></div><div><dt>Память</dt><dd>{detail.host.memory_kib ? `${(detail.host.memory_kib / 1024 / 1024).toFixed(1)} ГиБ` : "Нет сведений"}</dd></div></>} {detail.host && <><div><dt>Имя БК в системе</dt><dd>{detail.host.hostname}</dd></div><div><dt>Операционная система</dt><dd>{detail.host.os}</dd></div><div><dt>Архитектура</dt><dd>{detail.host.architecture}</dd></div><div><dt>Процессоры</dt><dd>{detail.host.cpus}</dd></div><div><dt>Память</dt><dd>{detail.host.memory_kib ? `${(detail.host.memory_kib / 1024 / 1024).toFixed(1)} ГиБ` : "Нет сведений"}</dd></div></>}
</dl> </dl>
<Button onClick={()=>setMonitorOpen(true)}><Icon name="activity"/>Мониторинг системы БК</Button>
{detail.enrollment !== "revoked" && <Button onClick={() => setRevoking(detail)}>Отозвать привязку БК</Button>} {detail.enrollment !== "revoked" && <Button onClick={() => setRevoking(detail)}>Отозвать привязку БК</Button>}
</SettingsCard>} </SettingsCard>}
<SettingsCard title="Устройства аппарата"><VehicleSensors onDetailChange={setSensorOpen} vehicleID={detail.id} enabled={!fleet.error && detail.enrollment === "paired" && detail.connectivity === "online"} /></SettingsCard> <SettingsCard title="Устройства аппарата"><VehicleSensors onDetailChange={setSensorOpen} vehicleID={detail.id} enabled={!fleet.error && detail.enrollment === "paired" && detail.connectivity === "online"} /></SettingsCard>
</> : !fleet.items ? <ActivityIndicator label="Получаем аппараты" /> : fleet.items.length === 0 ? <SettingsCard title="Аппаратов пока нет" description="Добавьте аппарат по приглашению из Mission Core Node на его бортовом компьютере."><Button onClick={() => setAdding(true)}>Добавить аппарат</Button></SettingsCard> : <ResourceList aria-label="Аппараты">{fleet.items.map(item => <li key={item.id}><ResourceRow icon={<Icon name="apps" />} title={item.name} description={`${platformLabel(item.platform)} · бортовой компьютер`} status={<StatusBadge tone={!fleet.error && item.enrollment === "paired" && item.connectivity === "online" ? "success" : "neutral"}>{fleet.error ? "Нет свежих данных" : statusLabel(item)}</StatusBadge>} actions={<IconButton label={`Конфигурация: ${item.name}`} onClick={() => setSelected(item.id)}><Icon name="eye" /></IconButton>} /></li>)}</ResourceList>} </> : !fleet.items ? <LoadingRegion loading label="Получаем аппараты" /> : fleet.items.length === 0 ? <SettingsCard title="Аппаратов пока нет" description="Добавьте аппарат по приглашению из Mission Core Node на его бортовом компьютере."><Button onClick={() => setAdding(true)}>Добавить аппарат</Button></SettingsCard> : <ResourceList aria-label="Аппараты">{fleet.items.map(item => <li key={item.id}><ResourceRow icon={<Icon name="apps" />} title={item.name} description={`${platformLabel(item.platform)} · бортовой компьютер`} status={<StatusBadge tone={!fleet.error && item.enrollment === "paired" && item.connectivity === "online" ? "success" : "neutral"}>{fleet.error ? "Нет свежих данных" : statusLabel(item)}</StatusBadge>} actions={<IconButton label={`Конфигурация: ${item.name}`} onClick={() => setSelected(item.id)}><Icon name="eye" /></IconButton>} /></li>)}</ResourceList>}
<Window open={adding} title="Добавить аппарат" subtitle="Подключить бортовой компьютер по приглашению Node" size="md" closeOnBackdrop={false} closeOnEscape={!pending} onClose={close} footer={<WindowFooterActions><Button disabled={pending} onClick={close}>Отмена</Button>{preview ? <Button disabled={pending || !name.trim()} onClick={() => void add()}>{pending ? "Добавляем…" : "Добавить аппарат"}</Button> : <Button type="submit" form="fleet-invitation" disabled={pending || !code.trim()}>{pending ? "Проверяем БК…" : "Проверить БК"}</Button>}</WindowFooterActions>}> <Window open={adding} title="Добавить аппарат" subtitle="Подключить бортовой компьютер по приглашению Node" size="md" closeOnBackdrop={false} closeOnEscape={!pending} onClose={close} footer={<WindowFooterActions><Button disabled={pending} onClick={close}>Отмена</Button>{preview ? <Button disabled={pending || !name.trim()} onClick={() => void add()}>{pending ? "Добавляем…" : "Добавить аппарат"}</Button> : <Button type="submit" form="fleet-invitation" disabled={pending || !code.trim()}>{pending ? "Проверяем БК…" : "Проверить БК"}</Button>}</WindowFooterActions>}>
<form id="fleet-invitation" className="fleet-form" onSubmit={inspect} aria-busy={pending}> <form id="fleet-invitation" className="fleet-form" onSubmit={inspect} aria-busy={pending}>
<Select label="Способ подключения" value="node" options={[{ value: "node", label: "С бортовым компьютером" }]} onChange={() => undefined} disabled={pending} /> <Select label="Способ подключения" value="node" options={[{ value: "node", label: "С бортовым компьютером" }]} onChange={() => undefined} disabled={pending} />
@@ -0,0 +1,3 @@
.board-monitor { display: grid; gap: var(--nodedc-space-4); min-width: 0; }
.board-monitor-controls { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: var(--nodedc-space-3); align-items: end; margin-bottom: var(--nodedc-space-3); }
.board-monitor p { font-size: var(--nodedc-font-size-sm); color: var(--nodedc-text-secondary); }
@@ -0,0 +1,53 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createServer} from 'vite';
let server,series,segments,frames,localPreview,MEDIA_PROTOCOL;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
({monitorSeries:series}=await server.ssrLoadModule('/src/core/fleet/boardMonitor.ts'));
({lineSegments:segments}=await server.ssrLoadModule('/src/components/system/TelemetrySeries.tsx'));
({MEDIA_PROTOCOL}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/previewFrames.ts'));
({localPreviewFrames:frames,localPreview}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/localPreview.ts'));
});
after(async()=>{await server?.close();});
test('archive gaps break the plot instead of manufacturing zero or connecting missing time',()=>{
const values=series({start:0,end:20,bucket_seconds:5,series:[{at:0,max:80},{at:5,max:90},{at:20,max:10}]},'max');
assert.deepEqual(values,[80,90,null,null,10]);
const result=segments(values,100);
assert.equal(result.length,2);
assert.match(result[0],/^0.00,8.80 25.00,5.40$/);
assert.deepEqual(segments([null,NaN,null]),[]);
assert.notEqual(segments([-10,0,10])[0].split(' ')[0].split(',')[1],segments([-10,0,10])[0].split(' ')[1].split(',')[1]);
});
test('HTTP media framing survives every byte boundary and refuses oversized frames',()=>{
const output=[],receive=frames((kind,bytes)=>output.push([kind,[...bytes]]));
const encoded=Uint8Array.of(2,0,0,0,3,4,5,6,3,0,0,0,2,7,8);
for(const byte of encoded)receive(Uint8Array.of(byte));
assert.deepEqual(output,[[2,[4,5,6]],[3,[7,8]]]);
assert.throws(()=>frames(()=>{})(Uint8Array.of(2,0,1,0,0)));
assert.throws(()=>frames(()=>{})(Uint8Array.of(7,0,0,0,0)));
});
test('local carrier delivers registered channels and ACKs through completed responses',async()=>{
const encode=(kind,data)=>{const bytes=typeof data==='string'?new TextEncoder().encode(data):Uint8Array.from(data);const out=new Uint8Array(bytes.length+5);out[0]=kind;new DataView(out.buffer).setUint32(1,bytes.length);out.set(bytes,5);return out;};
const peer='peer_'+ 'a'.repeat(32), received=[], closed=[];let preview;
const device={id:'synthetic-k1',snapshot:{context:{session_id:'synthetic-session'}}};
const transport={
submit:async request=>{closed.push(request);return {state:'complete'};},
localPreview:{
open:async request=>{assert.equal(request.action_id,'offer');return new Response(encode(0,JSON.stringify({peer_id:peer,media_protocol:MEDIA_PROTOCOL})));},
read:async(id,after)=>{
assert.equal(id,peer);
if(after===0)return new Response(new Uint8Array([...encode(2,[8,9]),...encode(3,'camera-ready')]));
assert.equal(after,7);preview.close();return new Response();
}
}
};
preview=localPreview(device,transport,{},()=>assert.fail('carrier failed'));
preview.rrd.onmessage=event=>{received.push([...new Uint8Array(event.data)]);preview.rrd.send(JSON.stringify({ack:7}));};
preview.camera.onmessage=event=>received.push(event.data);
await preview.start();
assert.deepEqual(received,[[8,9],'camera-ready']);
assert.equal(preview.rrd.readyState,'closed');assert.equal(closed.length,1);
assert.equal(closed[0].action_id,'close-peer');assert.equal(closed[0].parameters.peer_id,peer);
});
@@ -1991,7 +1991,7 @@ test("observed SCANNING recovery is a successful STOP-only connection outcome",
); );
assert.ok( assert.ok(
acquisitionSource.indexOf("terminalPhysicalStopObserved ? (") acquisitionSource.indexOf("terminalPhysicalStopObserved ? (")
< acquisitionSource.indexOf("<div className=\"scan-configuration-grid\">"), < acquisitionSource.indexOf("<K1AcquisitionFields"),
"recovered SCANNING must render the STOP-only branch before project/START controls", "recovered SCANNING must render the STOP-only branch before project/START controls",
); );
}); });
@@ -191,11 +191,13 @@ test("XGRIDS frontend is physically plugin-owned and split by operator pipeline"
assert.match(spatialControls, /role="alert"/); assert.match(spatialControls, /role="alert"/);
assert.doesNotMatch(spatialControls, /Повторить остановку/); assert.doesNotMatch(spatialControls, /Повторить остановку/);
assert.match(spatialControls, /stopLocalReceiver/); assert.match(spatialControls, /stopLocalReceiver/);
assert.match(spatialControls, /<ActivityIndicator size="compact"/); assert.match(spatialControls, /<K1SpatialSession/);
assert.match(spatialControls, /aria-busy=\{phase\.busy\}/); const spatialSession = readFileSync(join(pluginFrontendRoot, "components/K1SpatialSession.tsx"), "utf8");
assert.match(spatialControls, /K1 калибруется и готовит облако точек/); assert.match(spatialSession, /<ActivityIndicator size="compact"/);
assert.match(spatialControls, /Первые данные могут появиться через десятки секунд/); assert.match(spatialSession, /aria-busy=\{phase\.busy\}/);
assert.match(spatialControls, /Не перемещайте устройство/); assert.match(spatialSession, /K1 калибруется и готовит облако точек/);
assert.match(spatialSession, /Первые данные могут появиться через десятки секунд/);
assert.match(spatialSession, /Не перемещайте устройство/);
const styles = readFileSync(join(pluginFrontendRoot, "styles.css"), "utf8"); const styles = readFileSync(join(pluginFrontendRoot, "styles.css"), "utf8");
assert.doesNotMatch(styles, /@keyframes xgrids-k1-spin/); assert.doesNotMatch(styles, /@keyframes xgrids-k1-spin/);
@@ -258,7 +260,8 @@ test("K1 connection surface enforces one scan, local selection, and one Apply",
assert.doesNotMatch(provisioning, /allow_host_wifi_switch/); assert.doesNotMatch(provisioning, /allow_host_wifi_switch/);
assert.doesNotMatch(provisioning, /(?:color|background(?:-color)?):\s*(?:#[0-9a-f]{3,8}|rgba?\()/i); assert.doesNotMatch(provisioning, /(?:color|background(?:-color)?):\s*(?:#[0-9a-f]{3,8}|rgba?\()/i);
for (const sharedControl of ["Button", "IconButton", "TextField", "ActivityIndicator", "StatusBadge"]) { for (const sharedControl of ["Button", "IconButton", "TextField", "ActivityIndicator", "StatusBadge"]) {
assert.match(provisioning, new RegExp(`<${sharedControl}\\b`), sharedControl); const password = readFileSync(join(pluginFrontendRoot, "components/K1WifiPasswordField.tsx"), "utf8");
assert.match(provisioning + password, new RegExp(`<${sharedControl}\\b`), sharedControl);
} }
assert.doesNotMatch( assert.doesNotMatch(
provisioning, provisioning,
@@ -734,7 +737,7 @@ test("K1 provisioning keeps the operator draft separate from the backend lease",
assert.match(provisioning, /scanWithResult\(\{ durationSeconds: BLE_DISCOVERY_TIMEOUT_SECONDS \}\)/); assert.match(provisioning, /scanWithResult\(\{ durationSeconds: BLE_DISCOVERY_TIMEOUT_SECONDS \}\)/);
assert.match( assert.match(
provisioning, provisioning,
/onChange=\{\(event\) => setPassword\(event\.target\.value\)\}/, /<K1WifiPasswordField[\s\S]*?onChange=\{setPassword\}/,
); );
}); });
@@ -0,0 +1,29 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
const source=readFileSync(new URL('../../../plugins/insta360-x4/frontend/src/model.ts',import.meta.url),'utf8');
const code=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
const {cameraLabel,cameraStatus,resolutionLabel}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
const camera={id:'instax4_synthetic_a',online:true,configured:true,prepared:true,snapshot:{enrollment:'enrolled'},camera_status:{connected:true,recording:0,preview:0,function_mode:7}};
test('SD recording remains visible after preview closes, independently for each camera',()=>{
const recording={...camera,camera_status:{...camera.camera_status,recording:1}};
assert.equal(cameraLabel(recording,true).label,'Запись на карту камеры');
assert.equal(cameraLabel({...camera,id:'instax4_synthetic_b'},true).label,'Подключена');
assert.equal(cameraStatus(recording).preview,0);
});
test('stale and unconfirmed camera state never appears ready or actively recording',()=>{
assert.equal(cameraLabel({...camera,camera_status:{...camera.camera_status,recording:1}},false).tone,'neutral');
assert.equal(cameraLabel({...camera,camera_status:{}},true).tone,'warning');
assert.equal(cameraLabel({...camera,camera_status:{...camera.camera_status,preview:-1}},true).tone,'warning');
assert.equal(cameraStatus({...camera,camera_status:{preview:true,recording:'1',connected:1}}).preview,null);
});
test('installed model support does not enroll a new physical camera',()=>{
assert.equal(cameraLabel({...camera,configured:false},true).label,'Требуется подготовка');
assert.equal(cameraLabel({...camera,initializable:false},true).tone,'warning');
});
test('SDK resolution names are presented with their actual dimensions and frame rate',()=>{
assert.equal(resolutionLabel('3840_1920_30'),'3840 × 1920 · 30 кадр/с');
});
@@ -0,0 +1,90 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {createElement} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {createServer} from 'vite';
let server,Detail,presentation,enrolledDevice;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
({K1Detail:Detail}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/K1Detail.tsx'));
presentation=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/presentation.ts');
({enrolledDevice}=await server.ssrLoadModule('../../packages/sensor-ui/src/contracts.ts'));
});
after(async()=>{await server?.close();});
const device={id:'synthetic',kind:'k1',name:'K1 test',online:true,verified:true,prepared:true,
control:{can_start:true,can_stop:false,can_verify:true,generation:1,revision:1,acquisition_id:null},
snapshot:{context:{session_id:'exact-session',execution:{node_id:'test'}},acquisition:'idle'}};
const render=(value,enabled=true)=>renderToStaticMarkup(createElement(Detail,{device:value,enabled,
transport:{},back:()=>{},refresh:async()=>{},failure:()=>{},createRerunHost:()=>assert.fail('SSR must not start a viewer or hardware')}));
test('manual K1 surface admits one START only after current control proof',()=>{
const markup=render(device);
assert.match(markup,/Инициировать запуск/);
const start=(markup.match(/<button\b[\s\S]*?<\/button>/g)??[]).filter(button=>button.replace(/<[^>]+>/g,'')==='Инициировать запуск');
assert.equal(start.length,1);
assert.match(start[0],/<button[^>]*disabled=""/);
for(const label of ['Тип установки / носитель','Режим GNSS','Название проекта'])assert.ok(markup.includes(label));
assert.match(markup,/Настройки устройства/);
assert.doesNotMatch(markup,/Остановить устройство|Обновить просмотр|sensor-live-layout/);
const waiting={...device,online:false,verified:false,control:{...device.control,can_start:false,network_applied:true,reason_code:'application_authority_unavailable'}};
const pending=render(waiting);
assert.doesNotMatch(pending,/Инициировать запуск|Настройки устройства|sensor-live-layout/);
assert.match(pending,/Проверить состояние K1/);
assert.match(pending,/авторизовать/);
assert.equal(presentation.k1Status(waiting,true).label,'Нет связи с K1');
assert.equal(presentation.k1ManualState(device,false).canStart,false);
});
test('active acquisition exposes STOP and Rerun without another START',()=>{
const active={...device,control:{...device.control,can_start:false,can_stop:true},snapshot:{...device.snapshot,acquisition:'streaming'}};
const markup=render(active);
assert.match(markup,/Остановить устройство/);
assert.match(markup,/rerun-viewport__canvas/);
assert.doesNotMatch(markup,/>Статус</);
assert.match(markup,/>Пространственная сцена</);
for(const label of ['Движок','Слои','Отображение','Камера K1','Окно накопления облака точек'])assert.ok(markup.includes(label));
assert.ok(markup.includes('data-presented="false"'));
assert.ok(!markup.includes('Loading Rerun'));
assert.ok(!markup.includes('The data layer'));
assert.ok(!markup.includes('data-align="center"'));
assert.doesNotMatch(markup,/Восстановить просмотр|nodedc-activity-indicator/);
assert.doesNotMatch(markup,/Инициировать запуск|Обновить просмотр/);
assert.equal(presentation.k1ManualState(active,false).canStart,false);
assert.equal(presentation.k1ManualState(active,false).showStop,true);
});
test('calibration loader stays inside the primary action',()=>{
const starting={...device,control:{...device.control,can_start:false},snapshot:{...device.snapshot,acquisition:'starting'}};
const markup=render(starting);
const start=(markup.match(/<button\b[\s\S]*?<\/button>/g)??[]).filter(button=>button.replace(/<[^>]+>/g,'')==='Запускаем устройство');
assert.equal(start.length,1);
assert.match(start[0],/<button[^>]*aria-busy="true"/);
assert.equal((start[0].match(/class="nodedc-activity-indicator"/g)??[]).length,1);
assert.match(markup,/K1 калибруется и готовит облако точек/);
assert.doesNotMatch(markup,/Обновить просмотр/);
});
test('connection loss is visible independently of completed STOP',()=>{
const stopped={...device,online:false,verified:false,control:{...device.control,phase:'completed',can_start:false,network_applied:true}};
const markup=render(stopped);
assert.match(markup,/Нет связи с K1/);
assert.match(markup,/Проверить состояние K1/);
assert.doesNotMatch(markup,/Инициировать запуск|нет управления/);
});
test('enrollment handoff opens only the verified current session',()=>{
const inventory={fresh:true,items:[device],operations:[]};
assert.equal(enrolledDevice(inventory,'exact-session'),device);
assert.equal(enrolledDevice(inventory,'other-session'),null);
assert.equal(enrolledDevice({...inventory,fresh:false},'exact-session'),null);
assert.equal(enrolledDevice({...inventory,items:[{...device,verified:false}]},'exact-session'),null);
assert.equal(enrolledDevice({...inventory,items:[device,device]},'exact-session'),null);
});
test('completed scan with healthy control remains connected and permits a named next scan',()=>{
const stopped={...device,control:{...device.control,phase:'completed'}};
const markup=render(stopped);
assert.equal(presentation.k1Status(stopped,true).label,'Подключён');
assert.equal(presentation.k1ManualState(stopped,true).canStart,true);
assert.match(markup,/Инициировать запуск/);
assert.doesNotMatch(markup,/Проверить состояние K1|Подключить устройство|Устройство остановлено/);
assert.equal(presentation.k1Status(stopped,false).tone,'neutral');
});
@@ -0,0 +1,93 @@
import assert from 'node:assert/strict';
import {before,after,test} from 'node:test';
import {execFileSync} from 'node:child_process';
import {createServer} from 'vite';
let server,previewFrames,assertRrd,previewFreshness,previewCamera;
before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
({previewCamera}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/previewCamera.ts'));
({previewFreshness}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/previewFreshness.ts'));
({previewFrames,assertRrd}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/previewFrames.ts'));
});
after(async()=>{await server?.close();});
const array=bytes=>Uint8Array.from(bytes).buffer;
const header=size=>{const value=new Uint8Array(8);value.set([77,67,70,49]);new DataView(value.buffer).setUint32(4,size);return value.buffer;};
test('native RRD crosses many RTC fragments and reaches decoder once, byte-for-byte',()=>{
const payload=execFileSync('../../.venv/bin/python',['-c',`import rerun as rr, numpy as np, sys
r=rr.RecordingStream('synthetic-r10-js'); b=r.binary_stream()
r.log('points',rr.Points3D(np.random.default_rng(42).random((5000,3))))
sys.stdout.buffer.write(b.read())`]);
assert.ok(payload.length>16384);
const calls=[];
const receiver=previewFrames(value=>{assertRrd(value);calls.push(value);});
for(let record=0;record<2;record++){
receiver.push(header(payload.length));
for(let offset=0;offset<payload.length;offset+=16384){
receiver.push(array(payload.subarray(offset,offset+16384)));
if(offset+16384<payload.length)assert.equal(calls.length,record);
}
assert.deepEqual(Buffer.from(calls[record]),payload);
}
assert.equal(calls.length,2);
receiver.close();
});
test('partial, oversized, unframed and invalid records never enter the decoder',()=>{
let calls=0;
const receiver=previewFrames(value=>{assertRrd(value);calls++;});
assert.throws(()=>receiver.push(array([1,2,3])));
assert.throws(()=>receiver.push(header(8*1024*1024+1)));
assert.throws(()=>receiver.push(header(0)));
receiver.push(header(20));receiver.push(array([1,2]));receiver.close();
assert.equal(calls,0);
receiver.push(header(12));assert.throws(()=>receiver.push(array(new Uint8Array(13))));receiver.close();
receiver.push(header(12));assert.throws(()=>receiver.push(array(new Uint8Array(12))));
assert.equal(calls,0);
});
test('source age expires even when metadata repeats, old frames never look live',()=>{
let now=10000;const gate=previewFreshness(()=>now);
assert.equal(gate.fresh,false);
gate.receive({type:'lidar-state',sequence:1,age_ms:250,points:3});
assert.equal(gate.fresh,true);assert.equal(gate.points,3);
now+=1800;gate.receive({type:'lidar-state',sequence:1,age_ms:0,points:3});
assert.equal(gate.fresh,false);
gate.receive({type:'lidar-state',sequence:2,age_ms:9000,points:3});
assert.equal(gate.fresh,false);
gate.receive({type:'lidar-state',sequence:3,age_ms:0,points:4});
assert.equal(gate.fresh,true);assert.equal(gate.points,4);
assert.throws(()=>gate.receive({type:'lidar-state',sequence:4,age_ms:-1,points:4}));
});
test('onboard camera admits immediate sourceopen and ignores callbacks after close',()=>{
const saved={media:globalThis.MediaSource,create:URL.createObjectURL,revoke:URL.revokeObjectURL};
let source,buffer,appended=0,ready=0,failed=0;
class Buffer extends EventTarget {updating=false;buffered={length:0};appendBuffer(){appended++;}}
class Media extends EventTarget {
readyState='open';static isTypeSupported(){return true;}
constructor(){super();source=this;}
addSourceBuffer(){buffer=new Buffer();return buffer;}
}
class Video extends EventTarget {currentTime=0;set src(_){source.dispatchEvent(new Event('sourceopen'));}pause(){}load(){}removeAttribute(){}play(){return Promise.resolve();}}
globalThis.MediaSource=Media;URL.createObjectURL=()=> 'blob:synthetic';URL.revokeObjectURL=()=>{};
try{
const video=new Video(),decoder=previewCamera(video,()=>ready++,()=>failed++);
decoder.open('video/mp4');decoder.push(new Uint8Array([1,2,3]));
assert.equal(appended,1);
video.dispatchEvent(new Event('loadeddata'));assert.equal(ready,1);
decoder.close();video.dispatchEvent(new Event('loadeddata'));buffer.dispatchEvent(new Event('error'));
assert.equal(ready,1);assert.equal(failed,0);
}finally{globalThis.MediaSource=saved.media;URL.createObjectURL=saved.create;URL.revokeObjectURL=saved.revoke;}
});
test('a recovered media peer resumes a recording without reinserting old RRD batches',async()=>{
const {previewRecording}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/previewFrames.ts');
const sent=[];const cursor=previewRecording(value=>sent.push(value));
const payload=new Uint8Array(12);payload.set([82,82,70,50]);
assert.equal(cursor.accept(1,payload),true);
// The ACK was lost, so the new peer resends the exact complete batch.
assert.equal(cursor.accept(1,payload),false);
assert.equal(cursor.after,1);
assert.throws(()=>cursor.accept(3,payload),/cursor gap/);
assert.equal(cursor.accept(2,payload),true);
assert.equal(sent.length,2);
});
@@ -16,6 +16,7 @@ let K1ConnectionPipelines;
let physicalRecoveryConnectionDetail; let physicalRecoveryConnectionDetail;
let shouldRenderK1OperationalPanels; let shouldRenderK1OperationalPanels;
let K1ProvisioningPipeline; let K1ProvisioningPipeline;
let K1WifiPasswordField;
let RuntimeActionFenceTestContext; let RuntimeActionFenceTestContext;
let LOCAL_OPERATION_PROGRESS_DELAY_MILLISECONDS; let LOCAL_OPERATION_PROGRESS_DELAY_MILLISECONDS;
let emptySearchPresentation; let emptySearchPresentation;
@@ -102,6 +103,9 @@ before(async () => {
logLevel: "silent", logLevel: "silent",
server: { middlewareMode: true }, server: { middlewareMode: true },
}); });
({K1WifiPasswordField} = await server.ssrLoadModule(
"@xgrids-k1/frontend/components/K1WifiPasswordField.tsx",
));
({ normalizeXgridsK1MissionState } = await server.ssrLoadModule( ({ normalizeXgridsK1MissionState } = await server.ssrLoadModule(
"@xgrids-k1/frontend/runtimeContext.tsx", "@xgrids-k1/frontend/runtimeContext.tsx",
)); ));
@@ -277,7 +281,7 @@ test("K1 one-intent source contract makes mode reset explicit and keeps device I
assert.match(resultRows, /onSelect=\{\(\) => selectCandidate\(device\)\}/); assert.match(resultRows, /onSelect=\{\(\) => selectCandidate\(device\)\}/);
assert.doesNotMatch(resultRows, /Переподключиться|reopen|verifyConnection/); assert.doesNotMatch(resultRows, /Переподключиться|reopen|verifyConnection/);
assert.match(source, /onChange=\{\(event\) => setSsid\(event\.target\.value\)\}/); assert.match(source, /onChange=\{\(event\) => setSsid\(event\.target\.value\)\}/);
assert.match(source, /onChange=\{\(event\) => setPassword\(event\.target\.value\)\}/); assert.match(source, /<K1WifiPasswordField[\s\S]*?onChange=\{setPassword\}/);
assert.equal((apply.match(/await connect\(/g) ?? []).length, 1); assert.equal((apply.match(/await connect\(/g) ?? []).length, 1);
assert.doesNotMatch( assert.doesNotMatch(
@@ -290,9 +294,13 @@ test("K1 one-intent source contract makes mode reset explicit and keeps device I
source, source,
/(?:color|background(?:-color)?):\s*(?:#[0-9a-f]{3,8}|rgba?\()/i, /(?:color|background(?:-color)?):\s*(?:#[0-9a-f]{3,8}|rgba?\()/i,
); );
const passwordSource = readFileSync(new URL(
"../../../plugins/xgrids-k1/frontend/src/components/K1WifiPasswordField.tsx", import.meta.url,
), "utf8");
for (const sharedControl of ["Button", "IconButton", "TextField", "ActivityIndicator", "StatusBadge"]) { for (const sharedControl of ["Button", "IconButton", "TextField", "ActivityIndicator", "StatusBadge"]) {
assert.match(source, new RegExp(`<${sharedControl}\\b`), sharedControl); assert.match(source + passwordSource, new RegExp(`<${sharedControl}\\b`), sharedControl);
} }
assert.doesNotMatch(passwordSource, /<(?:button|input)\b/);
assert.equal((source.match(/buttonLabel:\s*"Применить"/g) ?? []).length, 3); assert.equal((source.match(/buttonLabel:\s*"Применить"/g) ?? []).length, 3);
assert.match(source, /устарел|stale/i); assert.match(source, /устарел|stale/i);
assert.match(source, /network_outcome_unknown|safe_to_retry/i); assert.match(source, /network_outcome_unknown|safe_to_retry/i);
@@ -1181,7 +1189,7 @@ function elementByProp(node, propName, expectedValue) {
return elementByProp(node.props.children, propName, expectedValue); return elementByProp(node.props.children, propName, expectedValue);
} }
function createStatefulProvisioningHarness(initialProps) { function createStatefulProvisioningHarness(initialProps, Component = K1ProvisioningPipeline) {
const hookSlots = []; const hookSlots = [];
let currentProps = initialProps; let currentProps = initialProps;
let capturedTree = null; let capturedTree = null;
@@ -1296,7 +1304,7 @@ function createStatefulProvisioningHarness(initialProps) {
}; };
try { try {
capturedTree = K1ProvisioningPipeline(currentProps); capturedTree = Component(currentProps);
} finally { } finally {
dispatcher.useState = originals.useState; dispatcher.useState = originals.useState;
dispatcher.useRef = originals.useRef; dispatcher.useRef = originals.useRef;
@@ -2848,8 +2856,9 @@ test("compact connection error can expose only its contextual recovery path", ()
})); }));
assert.match(markup, /Подключение не завершено/); assert.match(markup, /Подключение не завершено/);
assert.match(markup, />Подключить новый K1<\/button>/); assert.equal(buttonMarkupWithText(markup, "Подключить новый K1").length, 1);
assert.doesNotMatch(markup, /Проверить состояние|>Закрыть<\/button>/); assert.doesNotMatch(markup, /Проверить состояние/);
assert.equal(buttonMarkupWithText(markup, "Закрыть").length, 0);
}); });
test("connection attempt network phase copy distinguishes absent, applied and unknown outcomes", () => { test("connection attempt network phase copy distinguishes absent, applied and unknown outcomes", () => {
@@ -4348,16 +4357,16 @@ test("fresh Scan keeps retired audit rows selectable without recovery I/O", () =
assert.match(markup, /Повторить поиск Bluetooth/); assert.match(markup, /Повторить поиск Bluetooth/);
assert.doesNotMatch(markup, /old-stop-operation/); assert.doesNotMatch(markup, /old-stop-operation/);
const priorAction = deviceRowActionButton(markup, "ble-k1-001"); const priorAction = deviceRowActionButton(markup, "ble-k1-001");
assert.match(priorAction, />Выбрать<\/button>/); assert.equal(priorAction.replace(/<[^>]+>/g, ""), "Выбрать");
assert.doesNotMatch(priorAction, /\bdisabled(?:=|\s|>)/); assert.doesNotMatch(priorAction, /\bdisabled(?:=|\s|>)/);
const replacementAction = deviceRowActionButton(markup, "ble-k1-new"); const replacementAction = deviceRowActionButton(markup, "ble-k1-new");
assert.match(replacementAction, />Выбрать<\/button>/); assert.equal(replacementAction.replace(/<[^>]+>/g, ""), "Выбрать");
assert.doesNotMatch(replacementAction, /\bdisabled(?:=|\s|>)/); assert.doesNotMatch(replacementAction, /\bdisabled(?:=|\s|>)/);
assert.equal( assert.equal(
buttonMarkupWithText(markup, "Подключить новый K1").length, buttonMarkupWithText(markup, "Подключить новый K1").length,
0, 0,
); );
assert.doesNotMatch(markup, /<button[^>]*disabled[^>]*>Недоступно<\/button>/); assert.equal(buttonMarkupWithText(markup, "Недоступно").filter(button => /<button[^>]*disabled/.test(button)).length, 0);
assert.doesNotMatch( assert.doesNotMatch(
markup, markup,
/Попытка настройки завершена|Проверить подключение без изменения сети|Управление не подтверждено/, /Попытка настройки завершена|Проверить подключение без изменения сети|Управление не подтверждено/,
@@ -4380,7 +4389,7 @@ test("fresh Scan keeps retired audit rows selectable without recovery I/O", () =
/Подходящих K1 не найдено\. Повторите поиск\./, /Подходящих K1 не найдено\. Повторите поиск\./,
); );
const onlyPriorAction = deviceRowActionButton(onlyPriorMarkup, "ble-k1-001"); const onlyPriorAction = deviceRowActionButton(onlyPriorMarkup, "ble-k1-001");
assert.match(onlyPriorAction, />Выбрать<\/button>/); assert.equal(onlyPriorAction.replace(/<[^>]+>/g, ""), "Выбрать");
assert.doesNotMatch(onlyPriorAction, /\bdisabled(?:=|\s|>)/); assert.doesNotMatch(onlyPriorAction, /\bdisabled(?:=|\s|>)/);
assert.match(onlyPriorMarkup, /Результатов: 1/); assert.match(onlyPriorMarkup, /Результатов: 1/);
assert.doesNotMatch(onlyPriorMarkup, />Недоступно|Переподключиться/); assert.doesNotMatch(onlyPriorMarkup, />Недоступно|Переподключиться/);
@@ -4407,7 +4416,7 @@ test("fresh Scan keeps retired audit rows selectable without recovery I/O", () =
historicalAuditMarkup, historicalAuditMarkup,
"ble-k1-001", "ble-k1-001",
); );
assert.match(historicallyRetiredAction, />Выбрать<\/button>/); assert.equal(historicallyRetiredAction.replace(/<[^>]+>/g, ""), "Выбрать");
assert.doesNotMatch( assert.doesNotMatch(
historicallyRetiredAction, historicallyRetiredAction,
/\bdisabled(?:=|\s|>)/, /\bdisabled(?:=|\s|>)/,
@@ -4497,7 +4506,7 @@ test("an exact prior CoreBluetooth UUID remains a normal fresh selection across
markup, markup,
"f89438fa-55ed-85ad-eed7-734ac84746d8", "f89438fa-55ed-85ad-eed7-734ac84746d8",
); );
assert.match(priorDeviceAction, />Выбрать<\/button>/); assert.equal(priorDeviceAction.replace(/<[^>]+>/g, ""), "Выбрать");
assert.doesNotMatch(priorDeviceAction, /\bdisabled(?:=|\s|>)/); assert.doesNotMatch(priorDeviceAction, /\bdisabled(?:=|\s|>)/);
assert.equal(buttonMarkupWithText(markup, "Переподключиться").length, 0); assert.equal(buttonMarkupWithText(markup, "Переподключиться").length, 0);
assertCanonicalConnectionCopy(markup); assertCanonicalConnectionCopy(markup);
@@ -4669,23 +4678,11 @@ test("post-reset Scan selects the exact prior UUID locally and opens network fie
"local selection must not manufacture a backend Apply attempt", "local selection must not manufacture a backend Apply attempt",
); );
const passwordField = elementByProp(tree, "label", "Пароль Wi‑Fi"); const passwordField = elementByProp(tree, "placeholder", "Введите пароль");
assert.ok(passwordField); assert.ok(passwordField);
assert.equal(passwordField.props.type, "password"); passwordField.props.onChange("test-only-password");
passwordField.props.onChange({ target: { value: "test-only-password" } });
tree = harness.render(props()); tree = harness.render(props());
harness.flushEffects(); harness.flushEffects();
const showPassword = elementByProp(tree, "label", "Показать пароль");
assert.ok(showPassword);
assert.equal(showPassword.props.disabled, false);
showPassword.props.onClick();
tree = harness.render(props());
harness.flushEffects();
assert.equal(
elementByProp(tree, "label", "Пароль Wi‑Fi").props.type,
"text",
);
assert.ok(elementByProp(tree, "label", "Скрыть пароль"));
const chooseAnother = actionByLabel(tree, "Выбрать другое"); const chooseAnother = actionByLabel(tree, "Выбрать другое");
assert.ok(chooseAnother); assert.ok(chooseAnother);
@@ -6116,7 +6113,7 @@ test("an explicit network action keeps one disabled Step-2 form with an in-place
assert.match(markup, /Пароль передан/); assert.match(markup, /Пароль передан/);
assert.doesNotMatch(markup, /secret/); assert.doesNotMatch(markup, /secret/);
assert.equal((markup.match(/<input[^>]*disabled=""/g) ?? []).length, 2); assert.equal((markup.match(/<input[^>]*disabled=""/g) ?? []).length, 2);
assert.doesNotMatch(markup, />Применить<\/button>/); assert.equal(buttonMarkupWithText(markup, "Применить").length, 0);
assertCanonicalConnectionCopy(markup); assertCanonicalConnectionCopy(markup);
}); });
@@ -6301,8 +6298,8 @@ test("current Bridge bootstrap stays visible over an older unresolved STOP check
assert.match(markup, /<span>02<\/span>/); assert.match(markup, /<span>02<\/span>/);
assert.match(markup, /nodedc-activity-indicator/); assert.match(markup, /nodedc-activity-indicator/);
assert.doesNotMatch(markup, /Прежнее подключение не подтверждено/); assert.doesNotMatch(markup, /Прежнее подключение не подтверждено/);
assert.doesNotMatch(markup, />Переподключиться<\/button>/); assert.equal(buttonMarkupWithText(markup, "Переподключиться").length, 0);
assert.doesNotMatch(markup, />Подключить новый K1<\/button>/); assert.equal(buttonMarkupWithText(markup, "Подключить новый K1").length, 0);
assert.equal(isConnectionControlBootstrapSettling({ assert.equal(isConnectionControlBootstrapSettling({
...state, ...state,
@@ -6458,7 +6455,8 @@ test("correlated terminal recovery resets before exposing a separate clean Scan"
buttonMarkupWithText(markup, "Проверить прежнее подключение").length, buttonMarkupWithText(markup, "Проверить прежнее подключение").length,
0, 0,
); );
assert.doesNotMatch(markup, /Проверить состояние|>Закрыть<\/button>/); assert.doesNotMatch(markup, /Проверить состояние/);
assert.equal(buttonMarkupWithText(markup, "Закрыть").length, 0);
assert.doesNotMatch(markup, /Выбрать другое|Пароль Wi‑Fi|Пароль передан|>Применить</); assert.doesNotMatch(markup, /Выбрать другое|Пароль Wi‑Fi|Пароль передан|>Применить</);
assert.doesNotMatch(markup, /<span>02<\/span>|private transport exception/); assert.doesNotMatch(markup, /<span>02<\/span>|private transport exception/);
@@ -7142,7 +7140,7 @@ test("a stale reopen settlement cannot own the current wizard surface", () => {
assert.match(markup, /<span>01<\/span>/); assert.match(markup, /<span>01<\/span>/);
assert.doesNotMatch(markup, /Подключение…|aria-busy="true"/); assert.doesNotMatch(markup, /Подключение…|aria-busy="true"/);
assert.doesNotMatch(markup, /<span>02<\/span>|<span>03<\/span>/); assert.doesNotMatch(markup, /<span>02<\/span>|<span>03<\/span>/);
assert.match(markup, />Найти по Bluetooth<\/button>/); assert.equal(buttonMarkupWithText(markup, "Найти по Bluetooth").length, 1);
const modeToggle = markup.match( const modeToggle = markup.match(
/<button[^>]*aria-label="Способ подключения"[^>]*>/, /<button[^>]*aria-label="Способ подключения"[^>]*>/,
)?.[0]; )?.[0];
@@ -7262,7 +7260,7 @@ test("stale raw Bluetooth results stay hidden until an explicit search", () => {
assert.match(markup, /<span>01<\/span>/); assert.match(markup, /<span>01<\/span>/);
assert.doesNotMatch(markup, /Replacement K1/); assert.doesNotMatch(markup, /Replacement K1/);
assert.match(markup, />Найти по Bluetooth<\/button>/); assert.equal(buttonMarkupWithText(markup, "Найти по Bluetooth").length, 1);
assert.doesNotMatch(markup, /aria-busy="true"/); assert.doesNotMatch(markup, /aria-busy="true"/);
assert.doesNotMatch(markup, /<span>02<\/span>|<span>03<\/span>/); assert.doesNotMatch(markup, /<span>02<\/span>|<span>03<\/span>/);
assert.doesNotMatch(markup, /Завершаем предыдущее действие|Завершаем ранее начатое действие/); assert.doesNotMatch(markup, /Завершаем предыдущее действие|Завершаем ранее начатое действие/);
@@ -7333,7 +7331,7 @@ test("Step-2 credentials and Apply share one canonical field stack", () => {
assert.match( assert.match(
form, form,
/:\s*\(\s*<div className="field-stack"[\s\S]*?label="Пароль Wi‑Fi"[\s\S]*?\{applyAction\}\s*<\/div>/, /:\s*\(\s*<div className="field-stack"[\s\S]*?<K1WifiPasswordField[\s\S]*?\{applyAction\}\s*<\/div>/,
); );
assert.match(form, /disabled=\{provisioningFieldsDisabled\}/); assert.match(form, /disabled=\{provisioningFieldsDisabled\}/);
assert.match(form, /value=\{connectionAttemptOwnsDraft \? "" : password\}/); assert.match(form, /value=\{connectionAttemptOwnsDraft \? "" : password\}/);
@@ -7769,3 +7767,26 @@ test("a failed Connect after completed Bluetooth search exposes recovery instead
assert.match(markup, /K1 ответил ошибкой Bluetooth/); assert.match(markup, /K1 ответил ошибкой Bluetooth/);
assert.doesNotMatch(markup, /Подключение не выполнено|дождитесь, пока система|private transport exception|Пароль передан/); assert.doesNotMatch(markup, /Подключение не выполнено|дождитесь, пока система|private transport exception|Пароль передан/);
}); });
test("shared K1 password field reveals on demand and hides after clearing", () => {
let value = "";
const props = () => ({value, onChange:next=>{value=next;}, disabled:false});
const harness = createStatefulProvisioningHarness(props(), K1WifiPasswordField);
try {
let tree = harness.render(props());
assert.equal(elementByProp(tree, "label", "Показать пароль").props.disabled, true);
elementByProp(tree, "label", "Пароль Wi‑Fi").props.onChange({target:{value:"test-only-value"}});
tree = harness.render(props()); harness.flushEffects();
elementByProp(tree, "label", "Показать пароль").props.onClick();
tree = harness.render(props());
assert.equal(elementByProp(tree, "label", "Пароль Wi‑Fi").props.type, "text");
assert.equal(elementByProp(tree, "label", "Скрыть пароль").props['aria-pressed'], true);
value = "";
tree = harness.render(props()); harness.flushEffects();
tree = harness.render(props());
assert.equal(elementByProp(tree, "label", "Пароль Wi‑Fi").props.type, "password");
assert.equal(elementByProp(tree, "label", "Показать пароль").props.disabled, true);
assert.equal(elementByProp(tree, "label", "Пароль Wi‑Fi").props.autoComplete, "off");
} finally { harness.dispose(); }
});
@@ -414,7 +414,7 @@ test("data recordings keep the compact session dropdown and laboratory results s
test("recording preparation statuses share the viewer's left alignment", async () => { test("recording preparation statuses share the viewer's left alignment", async () => {
const spatialStyles = await readFile( const spatialStyles = await readFile(
new URL("../src/styles/spatial.css", import.meta.url), new URL("../../../packages/spatial-ui/src/spatial.css", import.meta.url),
"utf8", "utf8",
); );
const statusStack = spatialStyles.slice( const statusStack = spatialStyles.slice(
@@ -280,7 +280,7 @@ test("recorded player skips only a proven buffered corrupt timestamp interval",
test("loading and error overlays fully conceal recorded camera pixels", async () => { test("loading and error overlays fully conceal recorded camera pixels", async () => {
const css = await readFile( const css = await readFile(
new URL("../src/styles/observation.css", import.meta.url), new URL("../../../packages/spatial-ui/src/observation.css", import.meta.url),
"utf8", "utf8",
); );
assert.match( assert.match(
@@ -382,7 +382,7 @@ test("the spatial header reports raw replay as an active source", async () => {
}); });
test("the complete vendor canvas host is hidden during partial and failed admission", async () => { test("the complete vendor canvas host is hidden during partial and failed admission", async () => {
const css = await readFile(new URL("../src/styles/spatial.css", import.meta.url), "utf8"); const css = await readFile(new URL("../../../packages/spatial-ui/src/spatial.css", import.meta.url), "utf8");
assert.match( assert.match(
css, css,
/\.rerun-viewport:is\(\[data-status="loading"\], \[data-status="error"\]\)\s+\.rerun-viewport__canvas\s*\{[^}]*visibility:\s*hidden;[^}]*pointer-events:\s*none;/s, /\.rerun-viewport:is\(\[data-status="loading"\], \[data-status="error"\]\)\s+\.rerun-viewport__canvas\s*\{[^}]*visibility:\s*hidden;[^}]*pointer-events:\s*none;/s,
@@ -2,11 +2,13 @@ import assert from 'node:assert/strict';
import {before,after,test} from 'node:test'; import {before,after,test} from 'node:test';
import {readFileSync,readdirSync} from 'node:fs'; import {readFileSync,readdirSync} from 'node:fs';
import {createServer} from 'vite'; import {createServer} from 'vite';
let server,api,resolveContribution; let server,api,resolveContribution,wirelessContributions,revealEnrollment;
before(async()=>{ before(async()=>{
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}}); server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
api=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/enrollment.ts'); api=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/enrollment.ts');
({revealEnrollment}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/revealEnrollment.ts'));
({sensorContribution:resolveContribution}=await server.ssrLoadModule('../../packages/sensor-ui/src/extensions.ts')); ({sensorContribution:resolveContribution}=await server.ssrLoadModule('../../packages/sensor-ui/src/extensions.ts'));
({wirelessContributions}=await server.ssrLoadModule('../../packages/sensor-ui/src/extensions.ts'));
}); });
after(async()=>{await server?.close();}); after(async()=>{await server?.close();});
const initial={node_id:'node-one',available:true,fresh:true,runtime_id:'runtime-one',snapshot_revision:1,runtime_started_at:'2026-09-06T00:00:00Z',selected_device_id:'synthetic-ble'}; const initial={node_id:'node-one',available:true,fresh:true,runtime_id:'runtime-one',snapshot_revision:1,runtime_started_at:'2026-09-06T00:00:00Z',selected_device_id:'synthetic-ble'};
@@ -77,6 +79,44 @@ test('station refusal is the same message in onboard and LAB presentations',()=>
assert.match(api.enrollmentNotice(state),/Проверьте название сети и пароль/); assert.match(api.enrollmentNotice(state),/Проверьте название сети и пароль/);
assert.doesNotMatch(api.enrollmentNotice(state),/Bluetooth.*ошиб/); assert.doesNotMatch(api.enrollmentNotice(state),/Bluetooth.*ошиб/);
}); });
test('Bluetooth failure before dispatch asks for discovery without blaming Wi-Fi',()=>{
const state={...initial,connection_attempt:{schema_version:'missioncore.xgrids-k1-connection-attempt/v1',attempt_id:'test',status:'failed',stage:'connect-failed',phase:'network_not_applied',public_error_code:'BleakError',side_effect_status:'none'}};
assert.equal(api.enrollmentBluetoothFailure(state),true);
assert.match(api.enrollmentNotice(state),/Bluetooth.*не были отправлены/s);
assert.doesNotMatch(api.enrollmentNotice(state),/Проверьте.*пароль/);
const unknown={...state,connection_attempt:{...state.connection_attempt,phase:'network_outcome_unknown',side_effect_status:'unknown'}};
assert.equal(api.enrollmentBluetoothFailure(unknown),false);
assert.doesNotMatch(api.enrollmentNotice(unknown),/не были отправлены/);
});
test('applied and restored network states admit read-only verification without credentials',async()=>{
const f=fixture();
const applied={...initial,allowed_actions:['observe-configured-device-network'],connection_attempt:{schema_version:'missioncore.xgrids-k1-connection-attempt/v1',attempt_id:'previous',status:'failed',stage:'control-bootstrap-failed',phase:'network_applied',side_effect_status:'applied',public_error_code:'TypeError'}};
assert.equal(api.enrollmentAllowed(applied,'verify'),true);
assert.match(api.enrollmentNotice(applied),/Проверить состояние K1/);
assert.equal(api.enrollmentAllowed({...applied,connection_attempt:null},'verify'),true);
await api.enroll(f.transport,applied,'verify',{device_id:'synthetic-ble'},f.observer);
assert.equal(f.request().action,'verify');
assert.deepEqual(f.request().parameters,{device_id:'synthetic-ble'});
assert.equal(f.counts().posts,1);
});
test('new workflow content scrolls only the containing viewport without stealing focus',()=>{
const original={document:globalThis.document,window:globalThis.window,getComputedStyle:globalThis.getComputedStyle};
const calls=[];let reduced=false;
const body={};
const scroller={parentElement:body,scrollHeight:1600,clientHeight:500,scrollTop:100,
getBoundingClientRect:()=>({top:100,bottom:600}),scrollTo:value=>calls.push(value)};
globalThis.document={body,documentElement:{}};
globalThis.window={matchMedia:()=>({matches:reduced})};
globalThis.getComputedStyle=element=>({overflowY:element===scroller?'auto':'visible'});
const target=(top,height)=>({parentElement:scroller,getBoundingClientRect:()=>({top,bottom:top+height,height}),focus:()=>assert.fail('focus must remain with the operator')});
try{
revealEnrollment(target(120,250));assert.equal(calls.length,0);
revealEnrollment(target(620,100));assert.deepEqual(calls.pop(),{top:220,behavior:'smooth'});
reduced=true;
revealEnrollment(target(620,800));assert.deepEqual(calls.pop(),{top:620,behavior:'instant'});
revealEnrollment({...target(700,100),parentElement:body});assert.equal(calls.length,0);
}finally{Object.assign(globalThis,original);}
});
test('sensor host can resolve zero or unrelated integrations and rejects ambiguity',()=>{ test('sensor host can resolve zero or unrelated integrations and rejects ambiguity',()=>{
const alpha={kind:'alpha',Detail:()=>null},beta={kind:'beta',Detail:()=>null}; const alpha={kind:'alpha',Detail:()=>null},beta={kind:'beta',Detail:()=>null};
assert.equal(resolveContribution([],{kind:'alpha'}),undefined); assert.equal(resolveContribution([],{kind:'alpha'}),undefined);
@@ -87,6 +127,14 @@ test('sensor host can resolve zero or unrelated integrations and rejects ambigui
assert.doesNotMatch(readFileSync(new URL('../../../packages/sensor-ui/src/'+name,import.meta.url),'utf8'),/xgrids|lixel|\bk1\b|K1Detail/,'vendor dependency in '+name); assert.doesNotMatch(readFileSync(new URL('../../../packages/sensor-ui/src/'+name,import.meta.url),'utf8'),/xgrids|lixel|\bk1\b|K1Detail/,'vendor dependency in '+name);
} }
}); });
test('wireless device choices come from installed contributions without a single-vendor slot',()=>{
const wired={kind:'wired',Detail:()=>null};
const alpha={kind:'alpha',wirelessEnrollment:{label:'Device alpha',View:()=>null}};
const beta={kind:'beta',wirelessEnrollment:{label:'Device beta',View:()=>null}};
assert.deepEqual(wirelessContributions([]),[]);
assert.deepEqual(wirelessContributions([wired,alpha,beta]),[alpha,beta]);
assert.deepEqual(wirelessContributions([alpha,{...alpha},beta]),[beta]);
});
test('onboard actions use current server policy and never infer authority from readiness',()=>{ test('onboard actions use current server policy and never infer authority from readiness',()=>{
const state={...initial,connected:true,allowed_actions:['verify-control-read-only']}; const state={...initial,connected:true,allowed_actions:['verify-control-read-only']};
assert.equal(api.enrollmentAllowed(state,'connect'),false); assert.equal(api.enrollmentAllowed(state,'connect'),false);
@@ -100,3 +148,87 @@ test('delayed operation result cannot clear an observed board outage',()=>{
assert.equal(result.fresh,false); assert.equal(result.fresh,false);
assert.equal(api.mergeEnrollmentState(result,{...initial,fresh:true,snapshot_revision:3}).fresh,true); assert.equal(api.mergeEnrollmentState(result,{...initial,fresh:true,snapshot_revision:3}).fresh,true);
}); });
test('failed or unknown Bluetooth search is never presented as an empty successful scan',async()=>{
for(const state of ['failed','rejected','unknown']){
let posts=0;
const transport={submit:async command=>{posts++;return {
operation_id:command.operation_id,state:state==='unknown'?'unknown':'complete',
error:'unconfirmed device command',
result:{...initial,candidates:[],command_result:{operation_id:command.operation_id,action:'scan',status:state}},
};}};
await assert.rejects(api.enroll(transport,initial,'scan'),/Не удалось выполнить поиск Bluetooth на БК/);
assert.equal(posts,1);
}
assert.equal(api.enrollmentNotice({...initial,command_result:{action:'scan',status:'failed'}}),'');
});
test('a confirmed scan with zero candidates remains a valid empty result',async()=>{
const transport={submit:async command=>({operation_id:command.operation_id,state:'complete',
result:{...initial,candidates:[],command_result:{operation_id:command.operation_id,action:'scan',status:'succeeded'}},
})};
assert.deepEqual((await api.enroll(transport,initial,'scan')).candidates,[]);
});
test('finishing enrollment requires a verified current device session and survives no stale fence',()=>{
const connected={...initial,connected:true,discovery_generation:3,mode_revision:2,
device_session:{device_session_id:'session-one'},command_result:{status:'succeeded'}};
assert.equal(api.enrollmentProof(initial,'synthetic-ble'),null);
const proof=api.enrollmentProof(connected,'synthetic-ble');
assert.ok(proof);
assert.equal(api.enrollmentProofCurrent(proof,connected,'synthetic-ble'),true);
for(const patch of [{fresh:false},{available:false},{connected:false},{runtime_id:'other-runtime'},
{discovery_generation:4},{mode_revision:3},{selected_device_id:'other-device'},
{device_session:{device_session_id:'other-session'}},{command_result:{status:'rejected'}}]){
assert.equal(api.enrollmentProofCurrent(proof,{...connected,...patch},'synthetic-ble'),false);
}
assert.equal(api.enrollmentProofCurrent(null,connected,'synthetic-ble'),false);
assert.equal(api.enrollmentProofCurrent(proof,connected,'other-device'),false);
});
test('lost BLE candidate tells the operator to rescan without blaming Ethernet or Wi-Fi credentials',()=>{
const notice=api.enrollmentNotice({...initial,connection_attempt:{
schema_version:'missioncore.xgrids-k1-connection-attempt/v1',attempt_id:'test',status:'failed',
public_error_code:'network-provision-candidate-not-fresh',
}});
assert.match(notice,/Найдите K1 ещё раз/);
assert.match(notice,/Настройки Wi-Fi не были отправлены/);
assert.doesNotMatch(notice,/пароль|Ethernet/);
});
test('pending enrollment is presented by its action button without a second notice',()=>{
for(const phase of ['connecting','network_applied']){
assert.equal(api.enrollmentNotice({...initial,connection_attempt:{
schema_version:'missioncore.xgrids-k1-connection-attempt/v1',attempt_id:'test',status:'running',phase,
}}),'');
}
});
test('discovery errors preserve their cause and never imply a Wi-Fi refusal',()=>{
for(const [code,text,requiresScan] of [
['ble-discovery-busy',/поиск уже выполняется/i,false],
['ble-adapter-unavailable',/Bluetooth недоступен/,false],
['ble-discovery-failed',/Служба Bluetooth/,false],
['ble-selected-device-unavailable',/Выбранный K1 не найден/,true],
]){
const state={...initial,connection_attempt:{schema_version:'missioncore.xgrids-k1-connection-attempt/v1',
attempt_id:'test',status:'failed',stage:'resolution-failed',phase:'network_not_applied',
public_error_code:code,side_effect_status:'none'}};
assert.match(api.enrollmentNotice(state),text);
assert.match(api.enrollmentNotice(state),/Настройки Wi-Fi не были отправлены/);
assert.doesNotMatch(api.enrollmentNotice(state),/Проверьте.*пароль/);
assert.equal(api.enrollmentBluetoothFailure(state),requiresScan);
state.connection_attempt.side_effect_status='unknown';
state.connection_attempt.phase='network_outcome_unknown';
assert.doesNotMatch(api.enrollmentNotice(state),/не были отправлены/);
}
});
test('legacy resolution failure invalidates the form before a second stale submission',()=>{
const state={...initial,connection_attempt:{schema_version:'missioncore.xgrids-k1-connection-attempt/v1',
attempt_id:'test',status:'failed',stage:'resolution-failed',public_error_code:'BleakDBusError',side_effect_status:'none'}};
assert.equal(api.enrollmentBluetoothFailure(state),true);
assert.match(api.enrollmentNotice(state),/Найдите K1 ещё раз/);
});
@@ -0,0 +1,34 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import ts from 'typescript';
const source=readFileSync(new URL('../../../packages/sensor-ui/src/preparation.ts',import.meta.url),'utf8');
const code=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
const {devicePreparation,preparationProgress}=await import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
const device={id:'instax4_a'};
const operation={operation_id:'op_a',device_id:device.id,action_id:'prepare',state:'running',requested_at:'2026-09-08T12:00:00Z'};
const preparation={operation_id:'op_a',device_id:device.id,model_id:'insta360.x4',state:'running',phase:'verify',steps:[{id:'profile',label:'Драйвер',state:'complete'},{id:'verify',label:'Выбранная камера',state:'running'}]};
test('progress belongs to the exact operation and physical camera in either UI',()=>{
const inventory={items:[device],operations:[operation],preparations:[{...preparation,device_id:'instax4_b'},preparation]};
assert.deepEqual(devicePreparation(inventory,device),preparation);
assert.equal(devicePreparation({...inventory,preparations:[{...preparation,operation_id:'op_old'}]},device),undefined);
assert.equal(devicePreparation({...inventory,preparations:[preparation,preparation]},device),undefined);
});
test('a shared installation success still leaves instance verification outstanding',()=>{
assert.deepEqual(preparationProgress(preparation,'Подготовка'),{label:'Подготовка',value:.5,valueText:'Выбранная камера'});
assert.equal(preparationProgress(undefined,'Команда').value,undefined);
});
test('legacy RealSense progress cannot appear on an Insta360 row',()=>{
const legacy={items:[device],operations:[operation],preparation:{state:'complete',started_at:Date.parse(operation.requested_at)/1000,steps:[{id:'service',label:'Служба',state:'complete'}]}};
assert.equal(devicePreparation(legacy,device),undefined);
const rs={id:'rsd455_a'};
const value=devicePreparation({...legacy,operations:[{...operation,device_id:rs.id}]},rs);
assert.equal(value.state,'running');
assert.equal(value.steps.at(-1).state,'running');
});
test('new Nodes do not fall back to stale global preparation reports',()=>{
const rs={id:'rsd455_a'};
assert.equal(devicePreparation({items:[rs],operations:[{...operation,device_id:rs.id}],preparations:[],preparation:{started_at:Date.now()/1000,state:'complete',steps:[]}},rs),undefined);
});
+4
View File
@@ -69,11 +69,14 @@ func run() error {
return err return err
} }
app := &node.Server{Store: store, Assets: assets, Origin: "http://" + *listen, Version: version, Inventory: func() node.Inventory { return node.Host("/") }} app := &node.Server{Store: store, Assets: assets, Origin: "http://" + *listen, Version: version, Inventory: func() node.Inventory { return node.Host("/") }}
app.Monitor = node.NewMonitor()
app.Presentation = node.NewPresentationStore(*dir)
pairing, err := node.OpenPairing(store, *dir, version, app.Inventory) pairing, err := node.OpenPairing(store, *dir, version, app.Inventory)
if err != nil { if err != nil {
return err return err
} }
app.Pairing = pairing app.Pairing = pairing
pairing.Monitor = app.Monitor
nodeID, _ := store.Public() nodeID, _ := store.Public()
app.Sensors, err = node.OpenSensors(*dir, nodeID) app.Sensors, err = node.OpenSensors(*dir, nodeID)
if err != nil { if err != nil {
@@ -121,6 +124,7 @@ func run() error {
go func() { errs <- private.Serve(unix) }() go func() { errs <- private.Serve(unix) }()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop() defer stop()
go app.Monitor.Run(ctx)
go app.Sensors.WatchUSB(ctx) go app.Sensors.WatchUSB(ctx)
go pairing.Run(ctx) go pairing.Run(ctx)
log.Print("Mission Core Node " + version + " listening on loopback") log.Print("Mission Core Node " + version + " listening on loopback")
@@ -0,0 +1,73 @@
package node
import (
"bytes"
"encoding/json"
"io"
"net/http"
"strings"
"time"
)
// Local WebKit requires completed bounded HTTP responses. The same plugin
// delivery owns RRD/fMP4 framing, backpressure, resume and acquisition isolation.
func (s *Server) localPreviewRoutes(mux *http.ServeMux) {
capacity := make(chan struct{}, 2)
for _, route := range []string{"/api/devices/preview", "/api/devices/preview/read"} {
mux.HandleFunc("POST "+route, func(w http.ResponseWriter, r *http.Request) {
if !s.authorized(w, r) {
return
}
var value json.RawMessage
if !decode(w, r, &value) {
return
}
if s.DeviceEnrollment == nil {
http.Error(w, "Preview unavailable", 503)
return
}
path := "/local-preview/read"
if r.URL.Path == "/api/devices/preview" {
var command SensorCommand
if json.Unmarshal(value, &command) != nil || command.Action != "offer" || !sensorID.MatchString(command.Session.DeviceID) || !strings.HasPrefix(command.Session.DeviceID, "k1_") {
http.Error(w, "Invalid preview", 400)
return
}
path = "/local-preview"
}
select {
case capacity <- struct{}{}:
defer func() { <-capacity }()
default:
http.Error(w, "Close another viewer", 429)
return
}
request, err := http.NewRequestWithContext(r.Context(), "POST", "http://k1"+path, bytes.NewReader(value))
if err != nil {
http.Error(w, "Invalid preview", 400)
return
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("X-Node-Id", s.DeviceEnrollment.nodeID)
client := &http.Client{Transport: s.DeviceEnrollment.client.Transport, Timeout: 5 * time.Second}
response, err := client.Do(request)
if err != nil {
http.Error(w, "Preview unavailable", 503)
return
}
defer response.Body.Close()
if response.StatusCode != 200 {
http.Error(w, "Preview unavailable", response.StatusCode)
return
}
data, err := io.ReadAll(io.LimitReader(response.Body, 196609))
if err != nil || len(data) > 196608 {
http.Error(w, "Preview unavailable", 503)
return
}
w.Header().Set("Content-Type", "application/vnd.missioncore.preview")
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(data)
})
}
}
+159
View File
@@ -0,0 +1,159 @@
package node
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"strconv"
"sync"
"time"
)
// The collector owns sampling/storage. This bounded cache keeps monitoring I/O
// out of the paired control heartbeat and out of acquisition lifecycles.
type Monitor struct {
mu sync.Mutex
client *http.Client
source string
after int64
sent int64
value map[string]any
}
func NewMonitor() *Monitor {
return &Monitor{client: &http.Client{Timeout: 3 * time.Second, Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, "unix", "/run/mission-core-monitor/monitor.sock")
}}}}
}
func (m *Monitor) read(ctx context.Context, path string, body []byte) (map[string]any, error) {
method := "GET"
if body != nil {
method = "POST"
}
r, e := http.NewRequestWithContext(ctx, method, "http://monitor"+path, bytes.NewReader(body))
if e != nil {
return nil, e
}
r.Header.Set("Content-Type", "application/json")
response, e := m.client.Do(r)
if e != nil {
return nil, e
}
defer response.Body.Close()
if response.StatusCode != 200 {
return nil, errors.New("monitor unavailable")
}
data, e := io.ReadAll(io.LimitReader(response.Body, 262145))
if e != nil || len(data) > 262144 {
return nil, errors.New("monitor response budget")
}
var value map[string]any
e = json.Unmarshal(data, &value)
return value, e
}
func (m *Monitor) Run(ctx context.Context) {
defer m.client.CloseIdleConnections()
timer := time.NewTicker(2 * time.Second)
defer timer.Stop()
for {
status, e := m.read(ctx, "/status", nil)
if e == nil {
source, _ := status["source_id"].(string)
m.mu.Lock()
if source != m.source {
m.source = source
m.after = 0
m.sent = 0
}
after := m.after
m.mu.Unlock()
batch, be := m.read(ctx, "/batch?after="+strconv.FormatInt(after, 10), nil)
if be == nil && batch["source_id"] == source {
status["batch"] = batch
}
m.mu.Lock()
m.value = status
m.mu.Unlock()
}
select {
case <-ctx.Done():
return
case <-timer.C:
}
}
}
func (m *Monitor) Snapshot() map[string]any {
m.mu.Lock()
defer m.mu.Unlock()
if m.value == nil {
return map[string]any{"storage": "unavailable"}
}
if batch, ok := m.value["batch"].(map[string]any); ok {
if rows, ok := batch["samples"].([]any); ok {
for _, raw := range rows {
if row, ok := raw.(map[string]any); ok {
if seq, ok := row["seq"].(float64); ok && int64(seq) > m.sent {
m.sent = int64(seq)
}
}
}
}
}
return m.value
}
func (m *Monitor) Acknowledge(raw json.RawMessage) {
var ack struct {
Source string `json:"source_id"`
After int64 `json:"after"`
}
if json.Unmarshal(raw, &ack) != nil {
return
}
m.mu.Lock()
defer m.mu.Unlock()
// A receiver may already have a later cursor from before the Node restarted.
// Its authenticated ACK is bounded by the collector's durable latest record.
latest := m.sent
if row, ok := m.value["latest"].(map[string]any); ok {
if seq, ok := row["seq"].(float64); ok {
latest = int64(seq)
}
}
if ack.Source == m.source && ack.After >= m.after && ack.After <= latest {
m.after = ack.After
}
}
func (s *Server) monitorRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/monitor", func(w http.ResponseWriter, r *http.Request) {
if !s.authorized(w, r) {
return
}
if s.Monitor == nil {
reply(w, 503, map[string]string{"error": "Мониторинг недоступен"})
return
}
reply(w, 200, s.Monitor.Snapshot())
})
mux.HandleFunc("POST /api/monitor/events", func(w http.ResponseWriter, r *http.Request) {
if !s.authorized(w, r) {
return
}
var value json.RawMessage
if !decode(w, r, &value) {
return
}
if len(value) > 2048 || s.Monitor == nil {
http.Error(w, "Monitoring unavailable", 503)
return
}
if _, e := s.Monitor.read(r.Context(), "/events", value); e != nil {
http.Error(w, "Monitoring unavailable", 503)
return
}
reply(w, 200, map[string]bool{"ok": true})
})
}
@@ -0,0 +1,50 @@
package node
import (
"encoding/json"
"testing"
)
func TestMonitorAcknowledgementsRequireSameArchiveAndDurableBounds(t *testing.T) {
m := NewMonitor()
m.source = "archive-one"
m.value = map[string]any{"latest": map[string]any{"seq": float64(100)}}
for _, raw := range []string{`{"source_id":"another","after":50}`, `{"source_id":"archive-one","after":101}`, `{"source_id":"archive-one","after":-1}`} {
m.Acknowledge(json.RawMessage(raw))
if m.after != 0 {
t.Fatal("accepted invalid cursor")
}
}
m.Acknowledge(json.RawMessage(`{"source_id":"archive-one","after":80}`))
if m.after != 80 {
t.Fatal("did not restore committed receiver cursor after restart")
}
m.Acknowledge(json.RawMessage(`{"source_id":"archive-one","after":10}`))
if m.after != 80 {
t.Fatal("regressed cursor")
}
}
func TestMonitorAndPreviewCannotBypassNodeSession(t *testing.T) {
s := newTestServer(t)
for _, path := range []string{"/api/devices/preview", "/api/devices/preview/read", "/api/monitor/events"} {
if got := call(s, "POST", path, `{}`, nil).Code; got != 401 {
t.Fatalf("%s: %d", path, got)
}
}
if got := call(s, "GET", "/api/monitor", "", nil).Code; got != 401 {
t.Fatal(got)
}
cookie := login(t, s)
if got := call(s, "POST", "/api/devices/preview", `{}`, cookie).Code; got != 503 {
t.Fatal(got)
}
s.Monitor = NewMonitor()
if got := call(s, "GET", "/api/monitor", "", cookie).Code; got != 200 {
t.Fatal(got)
}
// An unavailable collector remains independent from the authenticated UI.
if got := call(s, "GET", "/api/status", "", cookie).Code; got != 200 {
t.Fatal(got)
}
}
+18 -9
View File
@@ -10,6 +10,7 @@ import (
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
"sort"
"sync" "sync"
"time" "time"
) )
@@ -21,15 +22,16 @@ type Invitation struct {
SecretHash string `json:"secret_hash,omitempty"` SecretHash string `json:"secret_hash,omitempty"`
} }
type CoreBinding struct { type CoreBinding struct {
BindingID string `json:"binding_id"` EndpointRevision uint64 `json:"endpoint_revision,omitempty"`
CoreID string `json:"core_id"` BindingID string `json:"binding_id"`
CoreName string `json:"core_name"` CoreID string `json:"core_id"`
Endpoint string `json:"endpoint"` CoreName string `json:"core_name"`
CAPEM string `json:"ca_pem"` Endpoint string `json:"endpoint"`
ClientPEM string `json:"client_pem"` CAPEM string `json:"ca_pem"`
Receipt string `json:"receipt,omitempty"` ClientPEM string `json:"client_pem"`
OfferHash string `json:"offer_hash,omitempty"` Receipt string `json:"receipt,omitempty"`
ExpiresAt int64 `json:"expires_at"` OfferHash string `json:"offer_hash,omitempty"`
ExpiresAt int64 `json:"expires_at"`
} }
type PairState struct { type PairState struct {
Schema string `json:"schema"` Schema string `json:"schema"`
@@ -39,6 +41,7 @@ type PairState struct {
Revocations []CoreBinding `json:"revocations,omitempty"` Revocations []CoreBinding `json:"revocations,omitempty"`
} }
type Pairing struct { type Pairing struct {
Monitor *Monitor
Sensors *Sensors Sensors *Sensors
DeviceEnrollment *DeviceEnrollment DeviceEnrollment *DeviceEnrollment
mu sync.Mutex mu sync.Mutex
@@ -170,6 +173,12 @@ func (p *Pairing) addresses() []string {
} }
} }
} }
sort.SliceStable(result, func(i, j int) bool {
if tailnetAddress(result[i]) != tailnetAddress(result[j]) {
return tailnetAddress(result[i])
}
return result[i] < result[j]
})
return result return result
} }
func (p *Pairing) invite(address string) (map[string]any, error) { func (p *Pairing) invite(address string) (map[string]any, error) {
@@ -0,0 +1,112 @@
package node
import (
"crypto/ed25519"
"crypto/tls"
"errors"
"net"
"net/http"
"net/url"
)
const recoverySchema = "missioncore.node-channel-recovery/v1"
// Address preference is transport policy, never proof of peer identity.
func tailnetAddress(address string) bool {
ip := net.ParseIP(address).To4()
return ip != nil && ip[0] == 100 && ip[1] >= 64 && ip[1] <= 127
}
func recoveryTLS(b CoreBinding, key ed25519.PrivateKey, address string) (*tls.Config, error) {
config, err := bindingTLS(b, key)
if err != nil {
return nil, err
}
cert, err := bootstrapCertificate(key, address)
if err != nil {
return nil, err
}
return &tls.Config{
MinVersion: tls.VersionTLS13, Certificates: []tls.Certificate{cert},
ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: config.RootCAs,
VerifyConnection: func(state tls.ConnectionState) error {
if !recoveryPeer(state, b.CoreID) {
return errors.New("recovery requires the bound Core identity")
}
return nil
},
}, nil
}
func recoveryPeer(state tls.ConnectionState, coreID string) bool {
if len(state.VerifiedChains) == 0 || len(state.PeerCertificates) == 0 {
return false
}
key, ok := state.PeerCertificates[0].PublicKey.(ed25519.PublicKey)
return ok && keyID("core_", key) == coreID
}
func (p *Pairing) recoveryHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil || !tailnetAddress(host) || r.TLS == nil {
http.Error(w, "Private authenticated channel required", 403)
return
}
var body struct {
Schema string `json:"schema"`
BindingID string `json:"binding_id"`
ExpectedEndpoint string `json:"expected_endpoint,omitempty"`
ExpectedRevision uint64 `json:"expected_revision,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
}
if !pairDecode(w, r, &body) {
return
}
p.mu.Lock()
defer p.mu.Unlock()
b := p.state.Binding
// Recheck durable authority on every request, including existing TLS sessions.
if p.state.Phase != "paired" || b == nil || !recoveryPeer(*r.TLS, b.CoreID) || body.BindingID != b.BindingID {
http.Error(w, "Binding unavailable", 403)
return
}
if body.Schema != recoverySchema {
http.Error(w, "Incompatible recovery protocol", 400)
return
}
switch r.URL.Path {
case "/v1/channel/inspect":
case "/v1/channel/migrate":
u, err := url.Parse(body.Endpoint)
if err != nil || !privateEndpoint(body.Endpoint, CorePort) || !tailnetAddress(u.Hostname()) || u.Hostname() != host {
http.Error(w, "Endpoint must address the authenticated Core transport", 400)
return
}
if body.ExpectedEndpoint != b.Endpoint || body.ExpectedRevision != b.EndpointRevision || b.EndpointRevision >= 1000000000 {
http.Error(w, "Endpoint changed; inspect again", 409)
return
}
if body.Endpoint != b.Endpoint {
next := p.state
copy := *b
copy.Endpoint = body.Endpoint
copy.EndpointRevision++
next.Binding = &copy
if p.save(next) != nil {
http.Error(w, "State unavailable", 503)
return
}
p.connection = "offline"
p.lastSeen = 0
b = p.state.Binding
}
default:
http.NotFound(w, r)
return
}
id, _ := p.store.Public()
reply(w, 200, map[string]any{"schema": recoverySchema, "node_id": id, "core_id": b.CoreID, "binding_id": b.BindingID, "endpoint": b.Endpoint, "endpoint_revision": b.EndpointRevision})
})
}
@@ -0,0 +1,197 @@
package node
import (
"context"
"crypto/ed25519"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"io"
"log"
"math/big"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
)
func recoveryFixture(t *testing.T) (*Pairing, tls.Certificate) {
t.Helper()
p, _ := testPairing(t)
pub, key, _ := ed25519.GenerateKey(rand.Reader)
ca := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "synthetic Core"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature}
der, err := x509.CreateCertificate(rand.Reader, ca, ca, pub, key)
if err != nil {
t.Fatal(err)
}
ca, _ = x509.ParseCertificate(der)
leaf := func(serial int64, public any) []byte {
spec := &x509.Certificate{SerialNumber: big.NewInt(serial), NotBefore: ca.NotBefore, NotAfter: ca.NotAfter, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, KeyUsage: x509.KeyUsageDigitalSignature}
value, e := x509.CreateCertificate(rand.Reader, spec, ca, public, key)
if e != nil {
t.Fatal(e)
}
return value
}
b := CoreBinding{BindingID: token(), CoreID: keyID("core_", pub), CoreName: "Test", Endpoint: "https://192.168.10.5:8782", CAPEM: string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})), ClientPEM: string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: leaf(2, p.store.pairingKey().Public())}))}
if err := p.save(PairState{Schema: PairSchema, Phase: "paired", Binding: &b}); err != nil {
t.Fatal(err)
}
return p, tls.Certificate{Certificate: [][]byte{leaf(3, pub)}, PrivateKey: key}
}
func recoveryCall(p *Pairing, client tls.Certificate, path string, body map[string]any) *httptest.ResponseRecorder {
raw, _ := json.Marshal(body)
r := httptest.NewRequest("POST", path, strings.NewReader(string(raw)))
r.RemoteAddr = "100.64.10.5:42000"
r.Header.Set("Content-Type", "application/json")
cert, _ := x509.ParseCertificate(client.Certificate[0])
r.TLS = &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{cert}}, PeerCertificates: []*x509.Certificate{cert}}
w := httptest.NewRecorder()
p.recoveryHandler().ServeHTTP(w, r)
return w
}
func TestRecoveryMigrationPreservesTrustAndSurvivesRestart(t *testing.T) {
p, client := recoveryFixture(t)
old := *p.state.Binding
body := map[string]any{"schema": recoverySchema, "binding_id": old.BindingID, "expected_endpoint": old.Endpoint, "expected_revision": 0, "endpoint": "https://100.64.10.5:8782"}
if out := recoveryCall(p, client, "/v1/channel/migrate", body); out.Code != 200 {
t.Fatal(out.Code, out.Body.String())
}
got := *p.state.Binding
if got.BindingID != old.BindingID || got.CoreID != old.CoreID || got.CAPEM != old.CAPEM || got.ClientPEM != old.ClientPEM || got.EndpointRevision != 1 {
t.Fatal("migration replaced authority")
}
if out := recoveryCall(p, client, "/v1/channel/migrate", body); out.Code != 409 {
t.Fatal("stale request accepted")
}
reopened, err := OpenPairing(p.store, filepath.Dir(p.path), "test", p.inventory)
if err != nil || reopened.state.Binding.Endpoint != got.Endpoint || reopened.state.Binding.EndpointRevision != 1 {
t.Fatal("migration not durable", err)
}
inspect := map[string]any{"schema": recoverySchema, "binding_id": old.BindingID}
out := recoveryCall(reopened, client, "/v1/channel/inspect", inspect)
if out.Code != 200 || !strings.Contains(out.Body.String(), got.Endpoint) || strings.Contains(out.Body.String(), "PEM") {
t.Fatal("lost ack not recoverable")
}
if err := reopened.cancel(); err != nil {
t.Fatal(err)
}
if recoveryCall(reopened, client, "/v1/channel/inspect", inspect).Code != 403 {
t.Fatal("revocation bypass")
}
}
func TestRecoveryRejectsForeignAuthorityAndWrongDestination(t *testing.T) {
p, client := recoveryFixture(t)
b := *p.state.Binding
body := map[string]any{"schema": recoverySchema, "binding_id": b.BindingID, "expected_endpoint": b.Endpoint, "endpoint": "https://100.64.10.5:8782"}
_, foreign := recoveryFixture(t)
if recoveryCall(p, foreign, "/v1/channel/migrate", body).Code != 403 {
t.Fatal("foreign Core accepted")
}
for _, destination := range []string{"https://100.64.10.6:8782", "https://8.8.8.8:8782", "https://192.168.10.5:8782", "https://100.64.10.5:443", "https://100.64.10.5:8782/path"} {
body["endpoint"] = destination
if recoveryCall(p, client, "/v1/channel/migrate", body).Code != 400 {
t.Fatal("wrong destination accepted", destination)
}
}
if *p.state.Binding != b {
t.Fatal("rejection mutated binding")
}
// A valid Node credential signed by this same CA is not Core authority.
block, _ := pem.Decode([]byte(b.ClientPEM))
otherNode := tls.Certificate{Certificate: [][]byte{block.Bytes}, PrivateKey: p.store.pairingKey()}
if recoveryCall(p, otherNode, "/v1/channel/inspect", body).Code != 403 {
t.Fatal("Node impersonated Core")
}
}
func TestRecoveryTLSRequiresBoundCoreCertificate(t *testing.T) {
p, core := recoveryFixture(t)
config, err := recoveryTLS(*p.state.Binding, p.store.pairingKey(), "127.0.0.1")
if err != nil {
t.Fatal(err)
}
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) }))
server.Config.ErrorLog = log.New(io.Discard, "", 0)
server.TLS = config
server.StartTLS()
defer server.Close()
_, foreign := recoveryFixture(t)
block, _ := pem.Decode([]byte(p.state.Binding.ClientPEM))
node := tls.Certificate{Certificate: [][]byte{block.Bytes}, PrivateKey: p.store.pairingKey()}
for _, item := range []struct {
name string
certificates []tls.Certificate
accepted bool
}{
{"Core", []tls.Certificate{core}, true}, {"missing", nil, false}, {"foreign", []tls.Certificate{foreign}, false}, {"Node", []tls.Certificate{node}, false},
} {
t.Run(item.name, func(t *testing.T) {
transport := &http.Transport{TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS13, InsecureSkipVerify: true, Certificates: item.certificates}}
defer transport.CloseIdleConnections()
client := &http.Client{Transport: transport, Timeout: 2 * time.Second}
response, e := client.Get(server.URL)
if e == nil {
response.Body.Close()
}
if (e == nil) != item.accepted {
t.Fatal("TLS admission", e)
}
})
}
}
func TestTailnetIsFirstInvitationAddress(t *testing.T) {
p, _ := testPairing(t)
p.inventory = func() Inventory {
return Inventory{Networks: []Network{
{Up: true, Addresses: []string{"192.168.10.4/24", "100.64.10.4/32"}},
{Up: false, Addresses: []string{"100.64.1.1/32"}},
}}
}
addresses := p.addresses()
if len(addresses) != 2 || addresses[0] != "100.64.10.4" {
t.Fatal(addresses)
}
}
func TestOldHeartbeatCannotRevokeMigratedBinding(t *testing.T) {
p, core := recoveryFixture(t)
old := *p.state.Binding
entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{})
p.clients[old.BindingID+old.Endpoint+digest(old.ClientPEM)] = &http.Client{
Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
close(entered)
<-release
return &http.Response{StatusCode: 410, Body: io.NopCloser(strings.NewReader(`{}`)), Header: make(http.Header)}, nil
}),
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() { defer close(done); p.channel(ctx) }()
select {
case <-entered:
case <-time.After(2 * time.Second):
t.Fatal("heartbeat did not start")
}
body := map[string]any{"schema": recoverySchema, "binding_id": old.BindingID, "expected_endpoint": old.Endpoint, "endpoint": "https://100.64.10.5:8782"}
response := recoveryCall(p, core, "/v1/channel/migrate", body)
cancel()
close(release)
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("heartbeat did not stop")
}
if response.Code != 200 || p.state.Phase != "paired" || p.state.Binding.EndpointRevision != 1 || p.connection != "offline" {
t.Fatal("old heartbeat changed new binding")
}
}
@@ -97,7 +97,7 @@ func (p *Pairing) remoteHandler() http.Handler {
return return
} }
b := *body.Binding b := *body.Binding
if len(b.BindingID) != 43 || len(b.CoreName) < 1 || len(b.CoreName) > 128 || len(b.CoreID) != 69 || len(b.CAPEM) > 8192 || len(b.ClientPEM) > 8192 || b.Receipt != "" || b.OfferHash != "" || b.ExpiresAt != 0 { if len(b.BindingID) != 43 || len(b.CoreName) < 1 || len(b.CoreName) > 128 || len(b.CoreID) != 69 || len(b.CAPEM) > 8192 || len(b.ClientPEM) > 8192 || b.Receipt != "" || b.OfferHash != "" || b.ExpiresAt != 0 || b.EndpointRevision != 0 {
http.Error(w, "Invalid binding", 400) http.Error(w, "Invalid binding", 400)
return return
} }
@@ -154,6 +154,8 @@ func (p *Pairing) Run(ctx context.Context) {
go p.channel(ctx) go p.channel(ctx)
var server *http.Server var server *http.Server
endpoint := "" endpoint := ""
serverIdentity := ""
var refreshAt time.Time
closeServer := func() { closeServer := func() {
if server != nil { if server != nil {
timeout, cancel := context.WithTimeout(context.Background(), time.Second) timeout, cancel := context.WithTimeout(context.Background(), time.Second)
@@ -162,6 +164,7 @@ func (p *Pairing) Run(ctx context.Context) {
server = nil server = nil
} }
endpoint = "" endpoint = ""
serverIdentity = ""
} }
defer closeServer() defer closeServer()
ticker := time.NewTicker(time.Second) ticker := time.NewTicker(time.Second)
@@ -170,29 +173,50 @@ func (p *Pairing) Run(ctx context.Context) {
p.mu.Lock() p.mu.Lock()
_ = p.expire() _ = p.expire()
desired := "" desired := ""
var recovery *CoreBinding
identity := "bootstrap"
if (p.state.Phase == "inviting" || p.state.Phase == "pending") && p.state.Invitation != nil { if (p.state.Phase == "inviting" || p.state.Phase == "pending") && p.state.Invitation != nil {
desired = p.state.Invitation.Endpoint desired = p.state.Invitation.Endpoint
} }
if p.state.Phase == "paired" && p.state.Binding != nil {
for _, address := range p.addresses() {
if tailnetAddress(address) {
desired = "https://" + address + ":" + PairPort
copy := *p.state.Binding
recovery = &copy
identity = copy.BindingID + copy.CoreID
break
}
}
}
p.mu.Unlock() p.mu.Unlock()
if desired != endpoint { if desired != endpoint || (desired != "" && (identity != serverIdentity || time.Now().After(refreshAt))) {
closeServer() closeServer()
if desired != "" { if desired != "" {
u, _ := url.Parse(desired) u, _ := url.Parse(desired)
cert, e := bootstrapCertificate(p.store.pairingKey(), u.Hostname()) cert, e := bootstrapCertificate(p.store.pairingKey(), u.Hostname())
config := &tls.Config{MinVersion: tls.VersionTLS13, Certificates: []tls.Certificate{cert}}
handler := p.remoteHandler()
if recovery != nil {
config, e = recoveryTLS(*recovery, p.store.pairingKey(), u.Hostname())
handler = p.recoveryHandler()
}
var listener net.Listener var listener net.Listener
if e == nil { if e == nil {
listener, e = net.Listen("tcp4", u.Host) listener, e = net.Listen("tcp4", u.Host)
} }
p.mu.Lock() p.mu.Lock()
if e != nil { if e != nil {
p.listenError = "Не удалось открыть частное подключение. Проверьте адрес и создайте приглашение повторно." p.listenError = "Не удалось открыть частное подключение. Проверьте доступность выбранной сети."
} else { } else {
p.listenError = "" p.listenError = ""
} }
p.mu.Unlock() p.mu.Unlock()
if e == nil { if e == nil {
server = &http.Server{Handler: p.remoteHandler(), ReadHeaderTimeout: 3 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 5 * time.Second, MaxHeaderBytes: 8192, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS13, Certificates: []tls.Certificate{cert}}} server = &http.Server{Handler: handler, ReadHeaderTimeout: 3 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 5 * time.Second, MaxHeaderBytes: 8192, TLSConfig: config}
endpoint = desired endpoint = desired
serverIdentity = identity
refreshAt = time.Now().Add(12 * time.Hour)
go func(s *http.Server, l net.Listener) { _ = s.Serve(tls.NewListener(l, s.TLSConfig)) }(server, &pairingListener{Listener: listener, slots: make(chan struct{}, 16), done: make(chan struct{})}) go func(s *http.Server, l net.Listener) { _ = s.Serve(tls.NewListener(l, s.TLSConfig)) }(server, &pairingListener{Listener: listener, slots: make(chan struct{}, 16), done: make(chan struct{})})
} }
} }
@@ -209,7 +233,7 @@ func (p *Pairing) send(ctx context.Context, b CoreBinding, path string, payload
if e != nil { if e != nil {
return nil, 0, e return nil, 0, e
} }
cacheKey := b.BindingID + digest(b.ClientPEM) cacheKey := b.BindingID + b.Endpoint + digest(b.ClientPEM)
client := p.clients[cacheKey] client := p.clients[cacheKey]
if client == nil { if client == nil {
transport := &http.Transport{TLSClientConfig: config, Proxy: nil, MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1, IdleConnTimeout: 15 * time.Second, TLSHandshakeTimeout: 4 * time.Second, DialContext: (&net.Dialer{Timeout: 4 * time.Second}).DialContext} transport := &http.Transport{TLSClientConfig: config, Proxy: nil, MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1, IdleConnTimeout: 15 * time.Second, TLSHandshakeTimeout: 4 * time.Second, DialContext: (&net.Dialer{Timeout: 4 * time.Second}).DialContext}
@@ -262,10 +286,10 @@ func (p *Pairing) channel(ctx context.Context) {
p.mu.Unlock() p.mu.Unlock()
wanted := make(map[string]bool) wanted := make(map[string]bool)
if binding != nil { if binding != nil {
wanted[binding.BindingID+digest(binding.ClientPEM)] = true wanted[binding.BindingID+binding.Endpoint+digest(binding.ClientPEM)] = true
} }
for _, b := range revocations { for _, b := range revocations {
wanted[b.BindingID+digest(b.ClientPEM)] = true wanted[b.BindingID+b.Endpoint+digest(b.ClientPEM)] = true
} }
for key, c := range p.clients { for key, c := range p.clients {
if !wanted[key] { if !wanted[key] {
@@ -276,6 +300,8 @@ func (p *Pairing) channel(ctx context.Context) {
if binding != nil { if binding != nil {
id, name := p.store.Public() id, name := p.store.Public()
payload := map[string]any{"schema": PairSchema, "binding_id": binding.BindingID, "node_id": id, "name": name, "version": p.version, "execution_binding": map[string]string{"node_id": id, "agent_instance_id": instance, "platform": "linux"}, "host": p.inventory(), "devices": []any{}} payload := map[string]any{"schema": PairSchema, "binding_id": binding.BindingID, "node_id": id, "name": name, "version": p.version, "execution_binding": map[string]string{"node_id": id, "agent_instance_id": instance, "platform": "linux"}, "host": p.inventory(), "devices": []any{}}
payload["core_endpoint"] = binding.Endpoint
payload["endpoint_revision"] = binding.EndpointRevision
if p.Sensors != nil { if p.Sensors != nil {
inv := p.Sensors.Inventory() inv := p.Sensors.Inventory()
payload["devices"] = inv["items"] payload["devices"] = inv["items"]
@@ -286,10 +312,16 @@ func (p *Pairing) channel(ctx context.Context) {
payload["device_enrollment"] = p.DeviceEnrollment.Status() payload["device_enrollment"] = p.DeviceEnrollment.Status()
payload["enrollment_results"] = p.DeviceEnrollment.RemoteResults() payload["enrollment_results"] = p.DeviceEnrollment.RemoteResults()
} }
if p.Monitor != nil {
payload["monitor"] = p.Monitor.Snapshot()
}
result, status, e := p.send(ctx, *binding, "/v1/node/heartbeat", payload) result, status, e := p.send(ctx, *binding, "/v1/node/heartbeat", payload)
p.mu.Lock() p.mu.Lock()
if p.state.Phase == "paired" && p.state.Binding != nil && p.state.Binding.BindingID == binding.BindingID { if p.state.Phase == "paired" && p.state.Binding != nil && p.state.Binding.BindingID == binding.BindingID && p.state.Binding.Endpoint == binding.Endpoint && p.state.Binding.EndpointRevision == binding.EndpointRevision {
if e == nil && status == 200 { if e == nil && status == 200 {
if p.Monitor != nil {
p.Monitor.Acknowledge(result["monitor_ack"])
}
p.connection = "online" p.connection = "online"
p.lastSeen = p.now().Unix() p.lastSeen = p.now().Unix()
if p.DeviceEnrollment != nil { if p.DeviceEnrollment != nil {
@@ -0,0 +1,237 @@
package node
import (
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"unicode"
"unicode/utf8"
)
const presentationSchema = "missioncore.node.presentation/v1"
type PresentationMedia struct {
ID string `json:"id"`
Source string `json:"source"`
URL string `json:"url"`
MediaKind string `json:"mediaKind"`
FileName *string `json:"fileName"`
}
type PresentationBackground struct {
Enabled bool `json:"enabled"`
ImageDurationSeconds int `json:"imageDurationSeconds"`
Items []PresentationMedia `json:"items"`
}
type PresentationPage struct {
HeaderLabel string `json:"headerLabel"`
Eyebrow string `json:"eyebrow"`
Title string `json:"title"`
Description string `json:"description"`
PrimaryWorkspaceID *string `json:"primaryWorkspaceId"`
SecondaryWorkspaceID *string `json:"secondaryWorkspaceId"`
Background PresentationBackground `json:"background"`
}
type PresentationSettings struct {
Schema string `json:"schema"`
Revision int64 `json:"revision"`
Pages map[string]PresentationPage `json:"pages"`
}
// Presentation is local product state, separate from identity and device authority.
type PresentationStore struct {
mu sync.Mutex
dir string
uploadMu sync.Mutex
}
func NewPresentationStore(dir string) *PresentationStore { return &PresentationStore{dir: dir} }
func defaultPresentation() PresentationSettings {
primary, secondary := "sensors", "environment"
return PresentationSettings{Schema: presentationSchema, Pages: map[string]PresentationPage{"home": {
HeaderLabel: "Mission Core Node", Eyebrow: "NODEDC / MISSION CORE NODE", Title: "Mission Core Node",
Description: "Подключение устройств, запись и просмотр данных на бортовом компьютере.",
PrimaryWorkspaceID: &primary, SecondaryWorkspaceID: &secondary,
Background: PresentationBackground{ImageDurationSeconds: 10, Items: []PresentationMedia{}},
}}}
}
func (p *PresentationStore) read() (PresentationSettings, error) {
file, err := os.Open(filepath.Join(p.dir, "presentation.json"))
if errors.Is(err, os.ErrNotExist) {
return defaultPresentation(), nil
}
if err != nil {
return PresentationSettings{}, err
}
defer file.Close()
var value PresentationSettings
decoder := json.NewDecoder(io.LimitReader(file, 128*1024+1))
decoder.DisallowUnknownFields()
if err = decoder.Decode(&value); err != nil {
return value, err
}
if decoder.Decode(new(any)) != io.EOF || value.Schema != presentationSchema {
return value, errors.New("invalid presentation document")
}
return value, p.validate(&value)
}
var presentationMediaID = regexp.MustCompile(`^media-[a-z0-9-]{1,58}$`)
var presentationAssetName = regexp.MustCompile(`^[a-f0-9]{64}\.(png|jpg|gif|webp|avif|mp4|webm|mov)$`)
func cleanPresentationText(value *string, limit int, multiline bool) bool {
*value = strings.TrimSpace(*value)
return *value != "" && utf8.ValidString(*value) && utf8.RuneCountInString(*value) <= limit &&
!strings.ContainsFunc(*value, func(r rune) bool { return unicode.IsControl(r) && !(multiline && (r == '\n' || r == '\t')) })
}
func (p *PresentationStore) validate(value *PresentationSettings) error {
invalid := errors.New("Проверьте текст, быстрые переходы и медиаконтент главной страницы.")
page, ok := value.Pages["home"]
if !ok || len(value.Pages) != 1 || value.Revision < 0 || value.Revision >= 1<<53-1 ||
!cleanPresentationText(&page.HeaderLabel, 40, false) || !cleanPresentationText(&page.Eyebrow, 80, false) ||
!cleanPresentationText(&page.Title, 120, false) || !cleanPresentationText(&page.Description, 500, true) {
return invalid
}
actions := map[string]bool{"sensors": true, "environment": true, "overview": true, "network": true, "diagnostics": true, "usb": true, "tailscale": true, "ssh": true, "core": true}
for _, action := range []*string{page.PrimaryWorkspaceID, page.SecondaryWorkspaceID} {
if action != nil && !actions[*action] {
return invalid
}
}
if page.PrimaryWorkspaceID != nil && page.SecondaryWorkspaceID != nil && *page.PrimaryWorkspaceID == *page.SecondaryWorkspaceID {
return invalid
}
bg := page.Background
if bg.ImageDurationSeconds < 1 || bg.ImageDurationSeconds > 60 || bg.Items == nil || len(bg.Items) > 24 || (bg.Enabled && len(bg.Items) == 0) {
return invalid
}
ids := map[string]bool{}
for _, item := range bg.Items {
if !presentationMediaID.MatchString(item.ID) || ids[item.ID] || len(item.URL) > 2048 ||
(item.MediaKind != "image" && item.MediaKind != "video") {
return invalid
}
ids[item.ID] = true
if item.FileName != nil && !cleanPresentationText(item.FileName, 255, false) {
return invalid
}
switch item.Source {
case "url":
u, err := url.Parse(item.URL)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil {
return invalid
}
case "file":
name := strings.TrimPrefix(item.URL, "/api/presentation/media/")
if item.URL != "/api/presentation/media/"+name || !presentationAssetName.MatchString(name) {
return invalid
}
info, err := os.Lstat(filepath.Join(p.dir, "presentation-media", name))
if err != nil || !info.Mode().IsRegular() || mediaKindForExtension(filepath.Ext(name)) != item.MediaKind {
return invalid
}
default:
return invalid
}
}
value.Pages["home"] = page
return nil
}
func (p *PresentationStore) save(value PresentationSettings) error {
data, err := json.Marshal(value)
if err != nil {
return err
}
file, err := os.CreateTemp(p.dir, ".presentation-*")
if err != nil {
return err
}
defer os.Remove(file.Name())
if _, err = file.Write(data); err == nil {
err = file.Sync()
}
closeErr := file.Close()
if err != nil {
return err
}
if closeErr != nil {
return closeErr
}
if err = os.Rename(file.Name(), filepath.Join(p.dir, "presentation.json")); err != nil {
return err
}
dir, err := os.Open(p.dir)
if err != nil {
return err
}
defer dir.Close()
return dir.Sync()
}
func (s *Server) presentationRoutes(mux *http.ServeMux) {
p := s.Presentation
mux.HandleFunc("GET /api/presentation/settings", func(w http.ResponseWriter, r *http.Request) {
if !s.authorized(w, r) {
return
}
p.mu.Lock()
defer p.mu.Unlock()
value, err := p.read()
if err != nil {
reply(w, 500, map[string]string{"error": "Не удалось прочитать оформление главной. Сохранённые настройки не изменены."})
return
}
reply(w, 200, value)
})
mux.HandleFunc("PUT /api/presentation/settings", func(w http.ResponseWriter, r *http.Request) {
if !s.authorized(w, r) {
return
}
if r.Header.Get("Content-Type") != "application/json" {
reply(w, 415, map[string]string{"error": "Ожидался JSON"})
return
}
var value PresentationSettings
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 128*1024))
d.DisallowUnknownFields()
if d.Decode(&value) != nil || d.Decode(new(any)) != io.EOF || (value.Schema != "" && value.Schema != presentationSchema) {
reply(w, 400, map[string]string{"error": "Некорректные настройки оформления"})
return
}
p.mu.Lock()
defer p.mu.Unlock()
current, err := p.read()
if err != nil {
reply(w, 500, map[string]string{"error": "Не удалось прочитать сохранённые настройки"})
return
}
if value.Revision != current.Revision {
reply(w, 409, map[string]string{"error": "Настройки изменены в другом окне. Обновите их перед сохранением."})
return
}
if err = p.validate(&value); err != nil {
reply(w, 400, map[string]string{"error": err.Error()})
return
}
value.Schema, value.Revision = presentationSchema, current.Revision+1
if err = p.save(value); err != nil {
reply(w, 500, map[string]string{"error": "Не удалось сохранить оформление главной"})
return
}
reply(w, 200, value)
})
p.mediaRoutes(mux, s)
}
@@ -0,0 +1,182 @@
package node
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
)
const maxPresentationMediaBytes = 256 * 1024 * 1024
var presentationMediaTypes = map[string]string{
".png": "image/png", ".jpg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".avif": "image/avif",
".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime",
}
func mediaKindForExtension(extension string) string {
if strings.HasPrefix(presentationMediaTypes[extension], "image/") {
return "image"
}
if strings.HasPrefix(presentationMediaTypes[extension], "video/") {
return "video"
}
return ""
}
func matchesPresentationMedia(head []byte, extension string) bool {
typ := http.DetectContentType(head)
if typ == presentationMediaTypes[extension] {
return true
}
if len(head) >= 12 && string(head[4:8]) == "ftyp" {
brand := string(head[8:12])
switch extension {
case ".avif":
return brand == "avif" || brand == "avis"
case ".mov":
return brand == "qt "
}
}
return extension == ".webm" && bytes.HasPrefix(head, []byte{0x1a, 0x45, 0xdf, 0xa3}) && bytes.Contains(head, []byte("webm"))
}
func (p *PresentationStore) mediaRoutes(mux *http.ServeMux, s *Server) {
mux.HandleFunc("PUT /api/presentation/media/{surface}/{item}", func(w http.ResponseWriter, r *http.Request) {
if !s.authorized(w, r) {
return
}
if r.PathValue("surface") != "home" || !presentationMediaID.MatchString(r.PathValue("item")) {
reply(w, 400, map[string]string{"error": "Страница или медиаконтент недоступны"})
return
}
name, err := url.PathUnescape(r.Header.Get("X-NODEDC-File-Name"))
if err != nil || !cleanPresentationText(&name, 255, false) || strings.ContainsAny(name, `/\`) {
reply(w, 400, map[string]string{"error": "Некорректное имя файла"})
return
}
extension := strings.ToLower(filepath.Ext(name))
if extension == ".jpeg" {
extension = ".jpg"
}
if presentationMediaTypes[extension] == "" {
reply(w, 415, map[string]string{"error": "Поддерживаются MP4, WebM, MOV, PNG, JPEG, GIF, WebP и AVIF."})
return
}
if r.ContentLength > maxPresentationMediaBytes {
reply(w, 413, map[string]string{"error": "Размер файла не должен превышать 256 МБ."})
return
}
if !p.uploadMu.TryLock() {
reply(w, 409, map[string]string{"error": "Дождитесь завершения текущей загрузки файла."})
return
}
defer p.uploadMu.Unlock()
controller := http.NewResponseController(w)
_ = controller.SetReadDeadline(time.Now().Add(5 * time.Minute))
_ = controller.SetWriteDeadline(time.Now().Add(5 * time.Minute))
dir := filepath.Join(p.dir, "presentation-media")
if os.MkdirAll(dir, 0700) != nil {
reply(w, 500, map[string]string{"error": "Хранилище фонов недоступно"})
return
}
// Local media storage is bounded independently of device recordings.
entries, err := os.ReadDir(dir)
if err != nil {
reply(w, 500, map[string]string{"error": "Хранилище фонов недоступно"})
return
}
var total int64
for _, entry := range entries {
if info, e := entry.Info(); e == nil {
total += info.Size()
}
}
if total > 8*1024*1024*1024-maxPresentationMediaBytes {
reply(w, 413, map[string]string{"error": "Хранилище фонов заполнено. Используйте прямую ссылку на медиаконтент."})
return
}
file, err := os.CreateTemp(dir, ".upload-*")
if err != nil {
reply(w, 500, map[string]string{"error": "Не удалось создать файл фона"})
return
}
defer os.Remove(file.Name())
defer file.Close()
body := http.MaxBytesReader(w, r.Body, maxPresentationMediaBytes)
head := make([]byte, 512)
n, err := io.ReadFull(body, head)
if err != nil && err != io.ErrUnexpectedEOF && err != io.EOF {
reply(w, 400, map[string]string{"error": "Загрузка файла прервана"})
return
}
head = head[:n]
if !matchesPresentationMedia(head, extension) {
reply(w, 415, map[string]string{"error": "Содержимое файла не соответствует поддерживаемому изображению или видео."})
return
}
hash := sha256.New()
written, err := io.Copy(io.MultiWriter(file, hash), io.MultiReader(bytes.NewReader(head), body))
if err != nil {
reply(w, 413, map[string]string{"error": "Загрузка прервана или файл превышает 256 МБ."})
return
}
if err = file.Sync(); err != nil {
reply(w, 500, map[string]string{"error": "Не удалось сохранить файл фона"})
return
}
if err = file.Close(); err != nil {
reply(w, 500, map[string]string{"error": "Не удалось сохранить файл фона"})
return
}
digest := hex.EncodeToString(hash.Sum(nil))
asset := digest + extension
if err = os.Rename(file.Name(), filepath.Join(dir, asset)); err != nil {
reply(w, 500, map[string]string{"error": "Не удалось сохранить файл фона"})
return
}
directory, err := os.Open(dir)
if err != nil {
reply(w, 500, map[string]string{"error": "Не удалось подтвердить сохранение файла"})
return
}
err = directory.Sync()
directory.Close()
if err != nil {
reply(w, 500, map[string]string{"error": "Не удалось подтвердить сохранение файла"})
return
}
reply(w, 200, map[string]any{"url": "/api/presentation/media/" + asset, "fileName": name, "mediaKind": mediaKindForExtension(extension), "sha256": digest, "byteLength": written})
})
mux.HandleFunc("GET /api/presentation/media/{asset}", func(w http.ResponseWriter, r *http.Request) {
if !s.authorized(w, r) {
return
}
asset := r.PathValue("asset")
if !presentationAssetName.MatchString(asset) {
http.NotFound(w, r)
return
}
path := filepath.Join(p.dir, "presentation-media", asset)
info, err := os.Lstat(path)
if err != nil || !info.Mode().IsRegular() {
http.NotFound(w, r)
return
}
file, err := os.Open(path)
if err != nil {
http.NotFound(w, r)
return
}
defer file.Close()
_ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(5 * time.Minute))
w.Header().Set("Content-Type", presentationMediaTypes[filepath.Ext(asset)])
http.ServeContent(w, r, asset, info.ModTime(), file)
})
}
@@ -0,0 +1,238 @@
package node
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"image"
"image/png"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
)
func presentationServer(t *testing.T) (*Server, *http.Cookie) {
t.Helper()
s := newTestServer(t)
s.Presentation = NewPresentationStore(t.TempDir())
return s, login(t, s)
}
func presentationJSON(t *testing.T, value PresentationSettings) string {
t.Helper()
b, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
return string(b)
}
func TestPresentationPersistsAndConcurrentWindowsConflict(t *testing.T) {
s, cookie := presentationServer(t)
value := defaultPresentation()
page := value.Pages["home"]
page.Title = " Главная борта "
value.Pages["home"] = page
body := presentationJSON(t, value)
codes := make(chan int, 2)
var wg sync.WaitGroup
for range 2 {
wg.Add(1)
go func() { defer wg.Done(); codes <- call(s, "PUT", "/api/presentation/settings", body, cookie).Code }()
}
wg.Wait()
close(codes)
counts := map[int]int{}
for code := range codes {
counts[code]++
}
if counts[200] != 1 || counts[409] != 1 {
t.Fatal(counts)
}
reopened := NewPresentationStore(s.Presentation.dir)
got, err := reopened.read()
if err != nil || got.Revision != 1 || got.Pages["home"].Title != "Главная борта" {
t.Fatal(got, err)
}
info, err := os.Stat(filepath.Join(reopened.dir, "presentation.json"))
if err != nil || info.Mode().Perm() != 0600 {
t.Fatal(info, err)
}
files, _ := os.ReadDir(reopened.dir)
if len(files) != 1 {
t.Fatal("temporary files survived", files)
}
}
func TestPresentationRejectsInvalidChangesWithoutReplacingSavedState(t *testing.T) {
s, cookie := presentationServer(t)
initial := defaultPresentation()
if w := call(s, "PUT", "/api/presentation/settings", presentationJSON(t, initial), cookie); w.Code != 200 {
t.Fatal(w.Body.String())
}
path := filepath.Join(s.Presentation.dir, "presentation.json")
before, _ := os.ReadFile(path)
for name, mutate := range map[string]func(*PresentationSettings){
"extra page": func(v *PresentationSettings) { v.Pages["system"] = v.Pages["home"] },
"blank title": func(v *PresentationSettings) { p := v.Pages["home"]; p.Title = " "; v.Pages["home"] = p },
"unknown action": func(v *PresentationSettings) {
p := v.Pages["home"]
action := "start-device"
p.PrimaryWorkspaceID = &action
v.Pages["home"] = p
},
"duplicate action": func(v *PresentationSettings) {
p := v.Pages["home"]
p.SecondaryWorkspaceID = p.PrimaryWorkspaceID
v.Pages["home"] = p
},
"script URL": func(v *PresentationSettings) {
p := v.Pages["home"]
p.Background.Items = []PresentationMedia{{ID: "media-test", Source: "url", URL: "javascript:alert(1)", MediaKind: "image"}}
v.Pages["home"] = p
},
"foreign local file": func(v *PresentationSettings) {
p := v.Pages["home"]
p.Background.Items = []PresentationMedia{{ID: "media-test", Source: "file", URL: "/etc/passwd", MediaKind: "image"}}
v.Pages["home"] = p
},
} {
t.Run(name, func(t *testing.T) {
value := defaultPresentation()
value.Revision = 1
mutate(&value)
if w := call(s, "PUT", "/api/presentation/settings", presentationJSON(t, value), cookie); w.Code != 400 {
t.Fatal(w.Code, w.Body.String())
}
after, _ := os.ReadFile(path)
if !bytes.Equal(before, after) {
t.Fatal("saved state changed")
}
})
}
corrupt := []byte(`{"schema":"broken"}`)
if err := os.WriteFile(path, corrupt, 0600); err != nil {
t.Fatal(err)
}
if w := call(s, "GET", "/api/presentation/settings", "", cookie); w.Code != 500 {
t.Fatal(w.Code)
}
if w := call(s, "PUT", "/api/presentation/settings", presentationJSON(t, initial), cookie); w.Code != 500 {
t.Fatal(w.Code)
}
after, _ := os.ReadFile(path)
if !bytes.Equal(corrupt, after) {
t.Fatal("corrupt evidence was replaced")
}
}
func presentationUpload(s *Server, cookie *http.Cookie, name string, data []byte) *httptest.ResponseRecorder {
r := httptest.NewRequest("PUT", s.Origin+"/api/presentation/media/home/media-test", bytes.NewReader(data))
r.Header.Set("Origin", s.Origin)
r.Header.Set("X-NODEDC-File-Name", name)
r.Header.Set("Content-Type", "application/octet-stream")
if cookie != nil {
r.AddCookie(cookie)
}
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
return w
}
func TestPresentationUploadSurvivesReopenAndSupportsRange(t *testing.T) {
s, cookie := presentationServer(t)
var data bytes.Buffer
if err := png.Encode(&data, image.NewRGBA(image.Rect(0, 0, 2, 2))); err != nil {
t.Fatal(err)
}
w := presentationUpload(s, cookie, "background.png", data.Bytes())
if w.Code != 200 {
t.Fatal(w.Code, w.Body.String())
}
var asset struct {
URL, FileName, MediaKind string
ByteLength int64
SHA256 string
}
if err := json.Unmarshal(w.Body.Bytes(), &asset); err != nil {
t.Fatal(err)
}
digest := sha256.Sum256(data.Bytes())
if asset.SHA256 != hex.EncodeToString(digest[:]) || asset.ByteLength != int64(data.Len()) || asset.MediaKind != "image" {
t.Fatal(asset)
}
value := defaultPresentation()
page := value.Pages["home"]
page.Background.Enabled = true
page.Background.Items = []PresentationMedia{{ID: "media-test", Source: "file", URL: asset.URL, FileName: &asset.FileName, MediaKind: asset.MediaKind}}
value.Pages["home"] = page
if w := call(s, "PUT", "/api/presentation/settings", presentationJSON(t, value), cookie); w.Code != 200 {
t.Fatal(w.Code, w.Body.String())
}
s.Presentation = NewPresentationStore(s.Presentation.dir)
if got, err := s.Presentation.read(); err != nil || got.Pages["home"].Background.Items[0].URL != asset.URL {
t.Fatal(got, err)
}
r := httptest.NewRequest("GET", s.Origin+asset.URL, nil)
r.AddCookie(cookie)
r.Header.Set("Range", "bytes=0-7")
w = httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
if w.Code != 206 || !bytes.Equal(w.Body.Bytes(), data.Bytes()[:8]) || w.Header().Get("Content-Type") != "image/png" {
t.Fatal(w.Code, w.Header(), w.Body.String())
}
if w := call(s, "GET", asset.URL, "", nil); w.Code != 401 {
t.Fatal("anonymous media access", w.Code)
}
if w := presentationUpload(s, cookie, "fake.png", []byte("<html>not an image</html>")); w.Code != 415 {
t.Fatal(w.Code)
}
files, _ := os.ReadDir(filepath.Join(s.Presentation.dir, "presentation-media"))
if len(files) != 1 {
t.Fatal("rejected upload left files", files)
}
}
func TestPresentationRequiresSessionAndSameOrigin(t *testing.T) {
s, cookie := presentationServer(t)
for _, method := range []string{"GET", "PUT"} {
if w := call(s, method, "/api/presentation/settings", presentationJSON(t, defaultPresentation()), nil); w.Code != 401 {
t.Fatal(method, w.Code)
}
}
if w := presentationUpload(s, nil, "x.png", nil); w.Code != 401 {
t.Fatal(w.Code)
}
r := httptest.NewRequest("PUT", s.Origin+"/api/presentation/settings", strings.NewReader(presentationJSON(t, defaultPresentation())))
r.AddCookie(cookie)
r.Header.Set("Origin", "https://unrelated.invalid")
r.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
if w.Code != 403 {
t.Fatal(w.Code)
}
}
func TestLocalViewerCSPAdmitsOnlyItsOwnRuntimeFrame(t *testing.T) {
s := newTestServer(t)
for _, path := range []string{"/", "/rerun-runtime.html", "/assets/runtime.js"} {
w := call(s, "GET", path, "", nil)
csp := w.Header().Get("Content-Security-Policy")
if path == "/rerun-runtime.html" {
if !strings.Contains(csp, "frame-ancestors 'self'") || !strings.Contains(csp, "'wasm-unsafe-eval'") {
t.Fatal(path, csp)
}
} else if !strings.Contains(csp, "frame-ancestors 'none'") || strings.Contains(csp, "'wasm-unsafe-eval'") {
t.Fatal(path, csp)
}
if strings.Contains(csp, "'unsafe-eval'") || strings.Contains(csp, "script-src *") {
t.Fatal(csp)
}
}
}
@@ -30,6 +30,7 @@ func TestUSBEventsAreHintsAndDoNotMultiplyInterfaces(t *testing.T) {
func TestSensorEventStreamRequiresLocalSession(t *testing.T) { func TestSensorEventStreamRequiresLocalSession(t *testing.T) {
s := newTestServer(t) s := newTestServer(t)
s.Sensors, _ = OpenSensors(t.TempDir(), "node_test") s.Sensors, _ = OpenSensors(t.TempDir(), "node_test")
isolateSensorHost(t, s.Sensors)
if response := call(s, "GET", "/api/devices/events", "", nil); response.Code != 401 { if response := call(s, "GET", "/api/devices/events", "", nil); response.Code != 401 {
t.Fatal("unauthenticated device stream", response.Code) t.Fatal("unauthenticated device stream", response.Code)
} }
@@ -0,0 +1,137 @@
package node
import (
"context"
"crypto/sha256"
"encoding/hex"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
// Model bindings are shipped code, never executables or paths supplied by a
// browser. A model owns its driver/profile; a physical device owns its session.
type sensorModel struct {
ID, Name, Prefix, Kind, Plugin, Version string
Vendor, Product, USBName string
Socket, PrepareUnit, Report string
Actions map[string]bool
}
func actions(names ...string) map[string]bool {
out := map[string]bool{}
for _, name := range names {
out[name] = true
}
return out
}
var sensorModels = []sensorModel{
{ID: "realsense.d455", Name: "RealSense D455", Prefix: "rsd455", Plugin: "missioncore.realsense", Version: "0.6.6",
Vendor: "8086", Product: "0b5c", Socket: "/run/mission-core-sensors/driver.sock",
PrepareUnit: "mission-core-node-realsense-prepare.service", Report: "/var/lib/mission-core-node-drivers/preparation.json",
Actions: actions("prepare", "details", "rename", "verify", "start", "replay", "stop", "option", "offer", "close-peer")},
{ID: "xgrids.k1", Name: "XGRIDS K1", Prefix: "k1", Kind: "k1",
Actions: actions("details", "rename", "verify", "start", "stop", "option", "offer", "close-peer")},
{ID: "insta360.x4", Name: "Insta360 X4", Prefix: "instax4", Kind: "insta360.x4", Plugin: "missioncore.insta360", Version: "0.1.3",
// 2e1a:0002 is shared with other Insta360 models. Require the exact
// OS product descriptor as well; SDK identity is verified after prepare.
Vendor: "2e1a", Product: "0002", USBName: "Insta360 X4", Socket: "/run/mission-core-insta360/driver.sock",
PrepareUnit: "mission-core-node-insta360-x4-profile.service", Report: "/var/lib/mission-core-node-profiles/insta360-x4/preparation.json",
Actions: actions("prepare", "details", "rename", "verify", "preview.start", "preview.stop", "record.start", "record.stop", "photo.capture", "settings.read", "settings.apply", "files.list", "offer", "close-peer")},
}
func modelForDevice(id string) *sensorModel {
if !sensorID.MatchString(id) {
return nil
}
for i := range sensorModels {
if strings.HasPrefix(id, sensorModels[i].Prefix+"_") {
return &sensorModels[i]
}
}
return nil
}
func currentCameraSnapshot(item map[string]any, model *sensorModel) bool {
snapshot, _ := item["snapshot"].(map[string]any)
context, _ := snapshot["context"].(map[string]any)
device, _ := context["device"].(map[string]any)
installed, _ := device["model"].(map[string]any)
_, revision := snapshot["revision"].(float64) // Decoded driver JSON.
observed, _ := snapshot["observed_at"].(string)
_, err := time.Parse(time.RFC3339Nano, observed)
return revision && err == nil && installed["plugin_version"] == model.Version && installed["model_id"] == model.ID
}
func modelDeviceID(model *sensorModel, serial string) string {
h := sha256.Sum256([]byte(serial))
return model.Prefix + "_" + hex.EncodeToString(h[:])[:32]
}
func sensorClient(socket string) *http.Client {
return &http.Client{Timeout: 25 * time.Second, Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, "unix", socket)
}}}
}
type usbSensor struct {
model *sensorModel
id, speed, binding string
stable bool
}
// Read-only OS discovery works before any vendor runtime has been installed.
// An absent or duplicated serial is not enough authority to initialize a unit.
func discoverSensors(root string) []usbSensor {
paths, _ := filepath.Glob(filepath.Join(root, "*"))
items := []usbSensor{}
counts := map[string]int{}
for _, path := range paths {
read := func(name string) string {
data, _ := os.ReadFile(filepath.Join(path, name))
return strings.TrimSpace(string(data))
}
for i := range sensorModels {
model := &sensorModels[i]
if model.Vendor == "" || read("idVendor") != model.Vendor || read("idProduct") != model.Product || (model.USBName != "" && read("product") != model.USBName) {
continue
}
serial := read("serial")
id := modelDeviceID(model, serial)
counts[id]++
items = append(items, usbSensor{model: model, id: id, speed: read("speed") + " Мбит/с", binding: filepath.Base(path) + ":" + read("devnum"), stable: serial != ""})
}
}
unique := []usbSensor{}
for _, item := range items {
if !item.stable || counts[item.id] != 1 {
item.stable = false
item.id = modelDeviceID(item.model, "provisional:"+item.binding)
}
unique = append(unique, item)
}
return unique
}
type discoverySession struct {
binding, session string
stable bool
}
func (s *Sensors) reconcileDiscovery(devices []usbSensor) {
s.mu.Lock()
defer s.mu.Unlock()
live := map[string]discoverySession{}
for _, device := range devices {
previous := s.discoverySessions[device.id]
if previous.binding != device.binding || previous.session == "" {
previous = discoverySession{device.binding, "discovery_" + digest(token())[:24] + "_" + device.id, device.stable}
}
live[device.id] = previous
}
s.discoverySessions = live
}
@@ -0,0 +1,351 @@
package node
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
func fakeUSB(t *testing.T, root, port, serial, product, number string) {
t.Helper()
dir := filepath.Join(root, port)
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
for key, value := range map[string]string{"idVendor": "2e1a", "idProduct": "0002", "product": product, "serial": serial, "devnum": number, "speed": "5000"} {
if err := os.WriteFile(filepath.Join(dir, key), []byte(value), 0600); err != nil {
t.Fatal(err)
}
}
}
func testSensorReply(value any) *http.Response {
data, _ := json.Marshal(value)
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(data))), Header: http.Header{}}
}
func isolatedSensors(t *testing.T) *Sensors {
t.Helper()
s, err := OpenSensors(t.TempDir(), "node_test")
if err != nil {
t.Fatal(err)
}
s.usbRoot = t.TempDir()
for _, client := range s.clients {
client.Transport = sensorRoundTrip(func(*http.Request) (*http.Response, error) {
return testSensorReply(map[string]any{"items": []any{}}), nil
})
}
return s
}
func TestModelDiscoveryIdentityAndHotplug(t *testing.T) {
s := isolatedSensors(t)
fakeUSB(t, s.usbRoot, "3-2", "synthetic-a", "Insta360 X4", "2")
fakeUSB(t, s.usbRoot, "3-3", "synthetic-b", "Insta360 X4", "3")
fakeUSB(t, s.usbRoot, "3-4", "synthetic-other", "Insta360 OneR", "4")
items := s.Inventory()["items"].([]any)
if len(items) != 2 {
t.Fatalf("wrong models admitted: %d", len(items))
}
first := items[0].(map[string]any)
id := first["id"].(string)
if id == items[1].(map[string]any)["id"] || first["prepared"] != false || first["configured"] != false {
t.Fatal("instances collapsed or discovery claimed readiness")
}
session := sensorSessionID(first)
if sensorSessionID(s.Inventory()["items"].([]any)[0].(map[string]any)) != session {
t.Fatal("refresh changed session")
}
if err := os.RemoveAll(filepath.Join(s.usbRoot, "3-2")); err != nil {
t.Fatal(err)
}
s.Inventory()
fakeUSB(t, s.usbRoot, "3-2", "synthetic-a", "Insta360 X4", "7")
again := s.Inventory()["items"].([]any)[0].(map[string]any)
if again["id"] != id || sensorSessionID(again) == session {
t.Fatal("replug did not retain identity and renew session")
}
// D455 IDs use the original unnamespaced serial hash, preserving archives.
if got := modelDeviceID(&sensorModels[0], "abc"); got != "rsd455_ba7816bf8f01cfea414140de5dae2223" {
t.Fatal(got)
}
if sensorModels[1].Kind != "k1" {
t.Fatal("K1 contribution binding changed")
}
}
func TestDuplicateSerialCannotAcquireCameraAuthority(t *testing.T) {
root := t.TempDir()
fakeUSB(t, root, "3-2", "duplicate", "Insta360 X4", "2")
fakeUSB(t, root, "3-3", "duplicate", "Insta360 X4", "3")
items := discoverSensors(root)
if len(items) != 2 || items[0].id == items[1].id || items[0].stable || items[1].stable {
t.Fatal("ambiguous USB devices disappeared or acquired stable authority")
}
}
func TestLegacyCameraProfileKeepsRemoteInitializationAvailable(t *testing.T) {
s := isolatedSensors(t)
fakeUSB(t, s.usbRoot, "3-2", "synthetic-legacy", "Insta360 X4", "2")
model := &sensorModels[2]
id := modelDeviceID(model, "synthetic-legacy")
legacy := s.discovery(id, "5000", true)
legacy["prepared"] = true
snapshot := legacy["snapshot"].(map[string]any)
delete(snapshot, "observed_at")
delete(snapshot, "revision")
s.clients[model.ID].Transport = sensorRoundTrip(func(*http.Request) (*http.Response, error) {
return testSensorReply(map[string]any{"items": []any{legacy}}), nil
})
for _, state := range []string{"idle", "live", "unknown"} {
snapshot["acquisition"] = state
items := s.Inventory()["items"].([]any)
if len(items) != 1 {
t.Fatal("legacy runtime hid or duplicated the USB camera")
}
item := items[0].(map[string]any)
fresh := item["snapshot"].(map[string]any)
if item["prepared"] != false || fresh["observed_at"] == nil || fresh["revision"] == nil || sensorSessionID(item) == "" {
t.Fatal("legacy snapshot escaped the discovery fallback")
}
if (state != "idle") != (item["preparation_safe"] == false) {
t.Fatal("legacy acquisition safety was lost")
}
}
}
func awaitSensor(t *testing.T, predicate func() bool) {
t.Helper()
deadline := time.Now().Add(4 * time.Second)
for time.Now().Before(deadline) {
if predicate() {
return
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("sensor operation timed out")
}
func TestNewCameraUsesReadyProfileWithoutInterruptingAnotherInstance(t *testing.T) {
s := isolatedSensors(t)
fakeUSB(t, s.usbRoot, "3-2", "synthetic-active", "Insta360 X4", "2")
fakeUSB(t, s.usbRoot, "3-3", "synthetic-new", "Insta360 X4", "3")
active := modelDeviceID(&sensorModels[2], "synthetic-active")
newDevice := modelDeviceID(&sensorModels[2], "synthetic-new")
var runs atomic.Int32
var stopped atomic.Bool
release := make(chan struct{})
var releaseOnce sync.Once
defer releaseOnce.Do(func() { close(release) })
s.runPreparation = func(context.Context, string) error {
runs.Add(1)
return errors.New("must not redeploy a ready shared profile")
}
s.clients["insta360.x4"].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/inventory" {
items := []any{}
for _, id := range []string{active, newDevice} {
item := s.discovery(id, "5000", true)
item["prepared"] = true
item["preparation_safe"] = id != active
snapshot := item["snapshot"].(map[string]any)
snapshot["context"].(map[string]any)["session_id"] = "sdk_" + id
if id == active { snapshot["acquisition"] = "streaming" }
items = append(items, item)
}
return testSensorReply(map[string]any{"items": items}), nil
}
var command SensorCommand
_ = json.NewDecoder(r.Body).Decode(&command)
if command.Action == "verify" && command.Session.DeviceID == newDevice {
<-release
} else if command.Action == "preview.stop" && command.Session.DeviceID == active {
stopped.Store(true)
} else {
return nil, errors.New("cross-camera command")
}
return testSensorReply(map[string]any{"state": "complete", "result": map[string]bool{"ok": true}}), nil
})
s.Inventory()
command := sensorTestCommand()
command.Action = "prepare"
command.Session = SensorSession{DeviceID: newDevice, SessionID: "sdk_" + newDevice}
if _, err := s.Submit(command, true); err != nil { t.Fatal(err) }
awaitSensor(t, func() bool { op := s.Get(command.ID); return op.Preparation != nil && op.Preparation.Phase == "verify" })
stop := sensorTestCommand()
stop.ID = "op_" + strings.Repeat("b", 32)
stop.Idempotency = stop.ID
stop.Action = "preview.stop"
stop.Session = SensorSession{DeviceID: active, SessionID: "sdk_" + active}
if _, err := s.Submit(stop, false); err != nil { t.Fatal(err) }
awaitSensor(t, func() bool { return stopped.Load() })
if runs.Load() != 0 { t.Fatal("new-camera preparation redeployed the shared profile") }
releaseOnce.Do(func() { close(release) })
awaitSensor(t, func() bool { return s.Get(command.ID).State == "complete" })
}
func TestLocalAndRemotePrepareShareProfileButVerifyEachInstance(t *testing.T) {
s := isolatedSensors(t)
fakeUSB(t, s.usbRoot, "3-2", "synthetic-a", "Insta360 X4", "2")
fakeUSB(t, s.usbRoot, "3-3", "synthetic-b", "Insta360 X4", "3")
initial := s.Inventory()["items"].([]any)
var installed atomic.Bool
var runs atomic.Int32
var mu sync.Mutex
verified := []string{}
release := make(chan struct{})
s.runPreparation = func(ctx context.Context, unit string) error {
if unit != "mission-core-node-insta360-x4-profile.service" {
return errors.New("wrong unit")
}
runs.Add(1)
select {
case <-ctx.Done():
return ctx.Err()
case <-release:
}
installed.Store(true)
return nil
}
s.clients["insta360.x4"].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
if r.URL.Path == "/inventory" {
items := []any{}
if installed.Load() {
for _, raw := range initial {
old := raw.(map[string]any)
id := old["id"].(string)
item := s.discovery(id, "5000", true)
item["prepared"] = true
item["snapshot"].(map[string]any)["context"].(map[string]any)["session_id"] = "sdk_" + id
items = append(items, item)
}
}
return testSensorReply(map[string]any{"items": items}), nil
}
var c SensorCommand
_ = json.NewDecoder(r.Body).Decode(&c)
if c.Action != "verify" || c.Session.SessionID != "sdk_"+c.Session.DeviceID {
return nil, errors.New("wrong instance session")
}
mu.Lock()
verified = append(verified, c.Session.DeviceID)
mu.Unlock()
if c.Session.DeviceID == initial[1].(map[string]any)["id"] {
return testSensorReply(map[string]any{"state": "error", "error": "no frames"}), nil
}
return testSensorReply(map[string]any{"state": "complete", "result": map[string]any{"device_id": c.Session.DeviceID}}), nil
})
// An active camera of another model must not block X4 installation.
s.client.Transport = sensorRoundTrip(func(*http.Request) (*http.Response, error) {
item := s.discovery(sensorTestCommand().Session.DeviceID, "5000", true)
item["snapshot"].(map[string]any)["acquisition"] = "streaming"
return testSensorReply(map[string]any{"items": []any{item}}), nil
})
commands := []SensorCommand{}
for i, raw := range initial {
item := raw.(map[string]any)
c := sensorTestCommand()
c.Action = "prepare"
c.ID = "op_" + strings.Repeat(string(rune('a'+i)), 32)
c.Idempotency = c.ID
c.Session = SensorSession{DeviceID: item["id"].(string), SessionID: sensorSessionID(item)}
commands = append(commands, c)
if _, err := s.Submit(c, i == 1); err != nil {
t.Fatal(err)
}
}
awaitSensor(t, func() bool {
return s.Get(commands[0].ID).Preparation != nil && s.Get(commands[1].ID).Preparation != nil
})
close(release)
awaitSensor(t, func() bool {
return s.Get(commands[0].ID).State != "running" && s.Get(commands[1].ID).State != "running"
})
if runs.Load() != 1 {
t.Fatalf("deployed %d times", runs.Load())
}
if s.Get(commands[0].ID).State != "complete" || s.Get(commands[1].ID).State != "error" {
t.Fatal("instance outcomes mixed")
}
s.mu.Lock()
a, b := s.initialized[commands[0].Session.DeviceID], s.initialized[commands[1].Session.DeviceID]
s.mu.Unlock()
if !a || b {
t.Fatal("success initialized a different camera")
}
mu.Lock()
defer mu.Unlock()
if len(verified) != 2 || verified[0] == verified[1] {
t.Fatal("verification routed to same instance")
}
if len(s.RemoteResults()) != 1 {
t.Fatal("remote result was lost")
}
}
func TestStalePrepareAndCrossModelActionsCannotMutate(t *testing.T) {
s := isolatedSensors(t)
fakeUSB(t, s.usbRoot, "3-2", "synthetic-a", "Insta360 X4", "2")
item := s.Inventory()["items"].([]any)[0].(map[string]any)
var calls atomic.Int32
s.runPreparation = func(context.Context, string) error { calls.Add(1); return nil }
c := sensorTestCommand()
c.Action = "prepare"
c.Session.DeviceID = item["id"].(string)
if _, err := s.Submit(c, true); err != nil {
t.Fatal(err)
}
awaitSensor(t, func() bool { return s.Get(c.ID).State != "running" })
if calls.Load() != 0 || s.Get(c.ID).State != "error" {
t.Fatal("stale session initialized a camera")
}
c = sensorTestCommand()
c.Action = "record.start"
if _, err := s.Submit(c, false); err == nil {
t.Fatal("X4 recording command admitted for D455")
}
c.Session.DeviceID = item["id"].(string)
c.Action = "start"
if _, err := s.Submit(c, false); err == nil {
t.Fatal("legacy ambiguous start admitted for X4")
}
c.Action = "prepare"
c.Parameters = map[string]any{"unit": "unrelated.service"}
if _, err := s.Submit(c, false); err == nil {
t.Fatal("caller chose privileged profile")
}
}
func TestRecordingWithoutPreviewBlocksModelPreparation(t *testing.T) {
s := isolatedSensors(t)
fakeUSB(t, s.usbRoot, "3-2", "synthetic-a", "Insta360 X4", "2")
item := s.Inventory()["items"].([]any)[0].(map[string]any)
// The camera's SD recording is independent from acquisition/preview.
item["prepared"] = true
item["preparation_safe"] = false
s.clients["insta360.x4"].Transport = sensorRoundTrip(func(*http.Request) (*http.Response, error) {
return testSensorReply(map[string]any{"items": []any{item}}), nil
})
var calls atomic.Int32
s.runPreparation = func(context.Context, string) error { calls.Add(1); return nil }
c := sensorTestCommand()
c.Action = "prepare"
c.Session = SensorSession{DeviceID: item["id"].(string), SessionID: sensorSessionID(item)}
if _, err := s.Submit(c, true); err != nil {
t.Fatal(err)
}
awaitSensor(t, func() bool { return s.Get(c.ID).State != "running" })
if s.Get(c.ID).State != "error" || calls.Load() != 0 {
t.Fatal("preparation changed a model with active camera recording")
}
}
@@ -0,0 +1,277 @@
package node
import (
"context"
"encoding/json"
"errors"
"os"
"os/exec"
"time"
)
var errPreparationUncertain = errors.New("Результат подготовки неизвестен. Обновите состояние устройства.")
type preparationStep struct {
ID string `json:"id"`
Label string `json:"label"`
State string `json:"state"`
Message string `json:"message,omitempty"`
}
type sensorPreparation struct {
OperationID string `json:"operation_id"`
DeviceID string `json:"device_id"`
ModelID string `json:"model_id"`
StartedAt float64 `json:"started_at"`
ProfileStartedAt float64 `json:"profile_started_at"`
State string `json:"state"`
Phase string `json:"phase"`
Steps []preparationStep `json:"steps"`
}
type profilePreparation struct {
done chan struct{}
started float64
err error
users int
finished bool
}
func runModelPreparation(ctx context.Context, unit string) error {
cmd := exec.CommandContext(ctx, "/usr/bin/systemctl", "start", unit)
cmd.Env = []string{"PATH=/usr/bin:/bin", "LANG=C", "DBUS_SYSTEM_BUS_ADDRESS=unix:path=/run/dbus/system_bus_socket"}
if cmd.Run() != nil {
if ctx.Err() != nil {
return errPreparationUncertain
}
return errors.New("Подготовка драйвера не завершена. Проверьте этапы и повторите действие.")
}
return nil
}
func sensorSessionID(item map[string]any) string {
snapshot, _ := item["snapshot"].(map[string]any)
context, _ := snapshot["context"].(map[string]any)
session, _ := context["session_id"].(string)
return session
}
func (s *Sensors) preparationPhase(c SensorCommand, model *sensorModel, job *profilePreparation, phase, state string) error {
s.mu.Lock()
defer s.mu.Unlock()
op := s.operations[c.ID]
if op == nil {
return errors.New("Операция подготовки не найдена.")
}
started, _ := time.Parse(time.RFC3339Nano, c.Requested)
deploy, verify := "running", "pending"
if phase == "verify" {
deploy, verify = "complete", "running"
}
if state != "running" {
if phase == "profile" {
deploy, verify = state, "blocked"
} else {
verify = state
}
}
op.Preparation = &sensorPreparation{OperationID: c.ID, DeviceID: c.Session.DeviceID, ModelID: model.ID,
StartedAt: float64(started.UnixMilli()) / 1000, ProfileStartedAt: job.started, State: state, Phase: phase,
Steps: []preparationStep{{ID: "profile", Label: "Подготовка драйвера", State: deploy}, {ID: "verify", Label: "Проверка выбранной камеры", State: verify}}}
op.Updated = time.Now().Unix()
err := s.write(c.ID+".json", op)
s.events.notify()
return err
}
// A concurrent prepare for another instance of this model joins the same
// deployment. Each command subsequently verifies only its own physical unit.
func (s *Sensors) profileJob(model *sensorModel) *profilePreparation {
s.mu.Lock()
defer s.mu.Unlock()
if job := s.preparing[model.ID]; job != nil {
job.users++
return job
}
job := &profilePreparation{done: make(chan struct{}), started: float64(time.Now().UnixMilli()) / 1000, users: 1}
s.preparing[model.ID] = job
go func() {
// Only this profile's devices can be affected by its service activation.
for _, raw := range s.Inventory()["items"].([]any) {
item := raw.(map[string]any)
id, _ := item["id"].(string)
if modelForDevice(id) != model {
continue
}
snapshot, _ := item["snapshot"].(map[string]any)
if state := snapshot["acquisition"]; (state != "idle" && state != "failed") || item["preparation_safe"] == false {
job.err = errors.New("Остановите захват устройств этой модели перед подготовкой драйвера.")
break
}
}
if job.err == nil {
ctx, cancel := context.WithTimeout(context.Background(), 310*time.Second)
job.err = s.runPreparation(ctx, model.PrepareUnit)
cancel()
}
s.mu.Lock()
job.finished = true
if job.users == 0 {
delete(s.preparing, model.ID)
}
close(job.done)
s.mu.Unlock()
s.events.notify()
}()
return job
}
func reusableCameraProfile(item map[string]any, model *sensorModel) bool {
if item["configured"] == true || item["prepared"] != true || item["preparation_safe"] == false {
return false
}
snapshot, _ := item["snapshot"].(map[string]any)
if snapshot["acquisition"] != "idle" {
return false
}
context, _ := snapshot["context"].(map[string]any)
device, _ := context["device"].(map[string]any)
installed, _ := device["model"].(map[string]any)
return installed["plugin_version"] == model.Version && installed["model_id"] == model.ID
}
func (s *Sensors) prepare(c SensorCommand, selected map[string]any) (result any, err error) {
model := modelForDevice(c.Session.DeviceID)
if model == nil || model.PrepareUnit == "" {
return nil, errors.New("Подготовка этой модели не поддерживается.")
}
deadline, _ := time.Parse(time.RFC3339Nano, c.Deadline)
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
if ctx.Err() != nil {
return nil, errors.New("Срок команды истёк. Устройство не изменено.")
}
s.mu.Lock()
initialBinding := s.discoverySessions[c.Session.DeviceID].binding
s.mu.Unlock()
// A newly attached camera can use the already running admitted profile.
// Verification belongs to this camera and need not stop other instances.
reuse := reusableCameraProfile(selected, model)
s.mu.Lock()
if active := s.preparing[model.ID]; active != nil && !active.finished {
reuse = false
}
s.mu.Unlock()
var job *profilePreparation
if reuse {
job = &profilePreparation{done: make(chan struct{}), started: float64(time.Now().UnixMilli()) / 1000, users: 1, finished: true}
close(job.done)
} else {
job = s.profileJob(model)
}
defer func() {
s.mu.Lock()
job.users--
if job.users == 0 && job.finished && s.preparing[model.ID] == job {
delete(s.preparing, model.ID)
}
s.mu.Unlock()
}()
phase := "profile"
defer func() {
state := "complete"
if err != nil {
state = "error"
}
if errors.Is(err, errPreparationUncertain) {
state = "unknown"
}
if e := s.preparationPhase(c, model, job, phase, state); e != nil {
err = errPreparationUncertain
}
}()
if s.preparationPhase(c, model, job, phase, "running") != nil {
return nil, errPreparationUncertain
}
select {
case <-ctx.Done():
return nil, errPreparationUncertain
case <-job.done:
if job.err != nil {
return nil, job.err
}
}
phase = "verify"
if s.preparationPhase(c, model, job, phase, "running") != nil {
return nil, errPreparationUncertain
}
// X4 bounds vendor Open at 40 seconds; allow that startup window without
// treating an active unit as a verified device. The command deadline still
// bounds the observer independently of the root preparation transaction.
for attempt := 0; attempt < 50; attempt++ {
if ctx.Err() != nil {
return nil, errPreparationUncertain
}
inventory := s.Inventory()
s.mu.Lock()
binding := s.discoverySessions[c.Session.DeviceID].binding
s.mu.Unlock()
if initialBinding != "" && binding != initialBinding {
return nil, errors.New("Камера переподключена во время подготовки. Повторите проверку устройства.")
}
for _, raw := range inventory["items"].([]any) {
item := raw.(map[string]any)
if item["id"] != c.Session.DeviceID || item["online"] != true || item["prepared"] != true {
continue
}
verify := c
verify.Action = "verify"
verify.Session.SessionID = sensorSessionID(item)
if verify.Session.SessionID == "" {
return nil, errors.New("Драйвер не подтвердил сеанс камеры.")
}
response, e := s.modelDriver(ctx, model, "/operation", verify)
if e != nil || response["state"] == "unknown" {
return nil, errPreparationUncertain
}
if response["state"] != "complete" {
message, _ := response["error"].(string)
if message == "" {
message = "Не удалось проверить изображение выбранной камеры."
}
return nil, errors.New(message)
}
return response["result"], nil
}
select {
case <-ctx.Done():
return nil, errPreparationUncertain
case <-time.After(time.Second):
}
}
return nil, errors.New("Драйвер установлен, но камера не открылась. Проверьте USB-подключение.")
}
// Project only the matching model run. A previous success or another model's
// report cannot become the progress of the selected device's verification.
func preparationView(value *sensorPreparation) *sensorPreparation {
copy := *value
model := modelForDevice(value.DeviceID)
if model == nil || len(value.Steps) == 0 {
return &copy
}
data, err := os.ReadFile(model.Report)
if err != nil || len(data) > 32768 {
return &copy
}
var report struct {
ModelID string `json:"model_id"`
StartedAt float64 `json:"started_at"`
Steps []preparationStep `json:"steps"`
}
if json.Unmarshal(data, &report) != nil || report.ModelID != value.ModelID || report.StartedAt < value.ProfileStartedAt || len(report.Steps) == 0 || len(report.Steps) > 32 {
return &copy
}
copy.Steps = append(report.Steps, value.Steps[len(value.Steps)-1])
return &copy
}
+159 -154
View File
@@ -3,15 +3,11 @@ package node
import ( import (
"bytes" "bytes"
"context" "context"
"crypto/sha256"
"encoding/hex"
"encoding/json" "encoding/json"
"errors" "errors"
"io" "io"
"net"
"net/http" "net/http"
"os" "os"
"os/exec"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strings" "strings"
@@ -37,28 +33,34 @@ type SensorCommand struct {
Parameters map[string]any `json:"parameters"` Parameters map[string]any `json:"parameters"`
} }
type SensorOperation struct { type SensorOperation struct {
Command SensorCommand `json:"command"` Command SensorCommand `json:"command"`
State string `json:"state"` State string `json:"state"`
Error string `json:"error,omitempty"` Error string `json:"error,omitempty"`
Result any `json:"result,omitempty"` Result any `json:"result,omitempty"`
Remote bool `json:"remote,omitempty"` Remote bool `json:"remote,omitempty"`
Updated int64 `json:"updated_at"` Updated int64 `json:"updated_at"`
Preparation *sensorPreparation `json:"preparation,omitempty"`
} }
type Sensors struct { type Sensors struct {
events sensorEvents events sensorEvents
mu sync.Mutex mu sync.Mutex
prepareMu sync.Mutex inventoryMu sync.Mutex
root string root string
nodeID string nodeID string
instance string instance string
client *http.Client client *http.Client
NetworkDevices *DeviceEnrollment clients map[string]*http.Client
operations map[string]*SensorOperation usbRoot string
names map[string]string discoverySessions map[string]discoverySession
initialized map[string]bool preparing map[string]*profilePreparation
runPreparation func(context.Context, string) error
NetworkDevices *DeviceEnrollment
operations map[string]*SensorOperation
names map[string]string
initialized map[string]bool
} }
var sensorID = regexp.MustCompile(`^(rsd455|k1)_[0-9a-f]{32}$`) var sensorID = regexp.MustCompile(`^[a-z][a-z0-9]{1,31}_[0-9a-f]{32}$`)
var operationID = regexp.MustCompile(`^op_[0-9a-f]{32}$`) var operationID = regexp.MustCompile(`^op_[0-9a-f]{32}$`)
func OpenSensors(root, nodeID string) (*Sensors, error) { func OpenSensors(root, nodeID string) (*Sensors, error) {
@@ -66,10 +68,13 @@ func OpenSensors(root, nodeID string) (*Sensors, error) {
if e := os.MkdirAll(dir, 0700); e != nil { if e := os.MkdirAll(dir, 0700); e != nil {
return nil, e return nil, e
} }
s := &Sensors{root: dir, nodeID: nodeID, instance: "discovery_" + digest(token())[:24], operations: map[string]*SensorOperation{}, names: map[string]string{}, initialized: map[string]bool{}} s := &Sensors{root: dir, nodeID: nodeID, instance: "discovery_" + digest(token())[:24], operations: map[string]*SensorOperation{}, names: map[string]string{}, initialized: map[string]bool{}, clients: map[string]*http.Client{}, usbRoot: "/sys/bus/usb/devices", discoverySessions: map[string]discoverySession{}, preparing: map[string]*profilePreparation{}, runPreparation: runModelPreparation}
s.client = &http.Client{Timeout: 25 * time.Second, Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { for _, model := range sensorModels {
return (&net.Dialer{}).DialContext(ctx, "unix", "/run/mission-core-sensors/driver.sock") if model.Socket != "" {
}}} s.clients[model.ID] = sensorClient(model.Socket)
}
}
s.client = s.clients["realsense.d455"]
files, _ := filepath.Glob(filepath.Join(dir, "op_*.json")) files, _ := filepath.Glob(filepath.Join(dir, "op_*.json"))
for _, p := range files { for _, p := range files {
data, e := os.ReadFile(p) data, e := os.ReadFile(p)
@@ -83,11 +88,17 @@ func OpenSensors(root, nodeID string) (*Sensors, error) {
if v.State == "running" { if v.State == "running" {
v.State = "unknown" v.State = "unknown"
v.Error = "Результат операции неизвестен после перезапуска. Проверьте состояние устройства." v.Error = "Результат операции неизвестен после перезапуска. Проверьте состояние устройства."
if v.Preparation != nil {
v.Preparation.State = "unknown"
}
} }
s.operations[v.Command.ID] = &v s.operations[v.Command.ID] = &v
} }
data, _ := os.ReadFile(filepath.Join(dir, "names.json")) data, _ := os.ReadFile(filepath.Join(dir, "names.json"))
_ = json.Unmarshal(data, &s.names) _ = json.Unmarshal(data, &s.names)
if s.names == nil {
s.names = map[string]string{}
}
data, _ = os.ReadFile(filepath.Join(dir, "initialized.json")) data, _ = os.ReadFile(filepath.Join(dir, "initialized.json"))
_ = json.Unmarshal(data, &s.initialized) _ = json.Unmarshal(data, &s.initialized)
if s.initialized == nil { if s.initialized == nil {
@@ -133,6 +144,25 @@ func (s *Sensors) write(name string, value any) error {
return d.Sync() return d.Sync()
} }
func (s *Sensors) driver(path string, body any) (map[string]any, error) { func (s *Sensors) driver(path string, body any) (map[string]any, error) {
return s.modelDriver(context.Background(), &sensorModels[0], path, body)
}
func (s *Sensors) modelDriver(ctx context.Context, model *sensorModel, path string, body any) (map[string]any, error) {
if model.Prefix == "k1" {
if s.NetworkDevices == nil {
return nil, errors.New("Служба устройства недоступна.")
}
if path == "/operation" {
path = "/sensor-operation"
}
return s.NetworkDevices.call(ctx, path, body)
}
client := s.clients[model.ID]
if model.ID == "realsense.d455" {
client = s.client
}
if client == nil {
return nil, errors.New("Интеграция устройства не установлена.")
}
method := "GET" method := "GET"
var reader io.Reader var reader io.Reader
if body != nil { if body != nil {
@@ -143,7 +173,7 @@ func (s *Sensors) driver(path string, body any) (map[string]any, error) {
} }
reader = bytes.NewReader(data) reader = bytes.NewReader(data)
} }
req, e := http.NewRequest(method, "http://driver"+path, reader) req, e := http.NewRequestWithContext(ctx, method, "http://driver"+path, reader)
if e != nil { if e != nil {
return nil, e return nil, e
} }
@@ -151,13 +181,14 @@ func (s *Sensors) driver(path string, body any) (map[string]any, error) {
if body != nil { if body != nil {
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
} }
response, e := s.client.Do(req) response, e := client.Do(req)
if e != nil { if e != nil {
return nil, errors.New("Служба камеры недоступна. Подготовьте устройство.") return nil, errors.New("Служба камеры недоступна. Подготовьте устройство.")
} }
defer response.Body.Close() defer response.Body.Close()
var result map[string]any var result map[string]any
if json.NewDecoder(io.LimitReader(response.Body, 1024*1024)).Decode(&result) != nil { data, readErr := io.ReadAll(io.LimitReader(response.Body, 2*1024*1024+1))
if readErr != nil || len(data) > 2*1024*1024 || json.Unmarshal(data, &result) != nil {
return nil, errors.New("Не удалось прочитать результат драйвера.") return nil, errors.New("Не удалось прочитать результат драйвера.")
} }
if response.StatusCode != 200 { if response.StatusCode != 200 {
@@ -167,78 +198,69 @@ func (s *Sensors) driver(path string, body any) (map[string]any, error) {
return result, nil return result, nil
} }
func (s *Sensors) Inventory() map[string]any { func (s *Sensors) Inventory() map[string]any {
// Concurrent local/remote refreshes must observe the same hotplug generation.
s.inventoryMu.Lock()
defer s.inventoryMu.Unlock()
usb := discoverSensors(s.usbRoot)
s.reconcileDiscovery(usb)
items := []any{} items := []any{}
seen := map[string]bool{} seen := map[string]bool{}
if s.NetworkDevices != nil { unsafePreparation := map[string]bool{}
for idx := range sensorModels {
model := &sensorModels[idx]
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
result, e := s.NetworkDevices.call(ctx, "/inventory", nil) result, err := s.modelDriver(ctx, model, "/inventory", nil)
cancel() cancel()
if e == nil { if err != nil {
if found, ok := result["items"].([]any); ok { continue
for _, raw := range found {
item, ok := raw.(map[string]any)
if !ok {
continue
}
id, _ := item["id"].(string)
if !strings.HasPrefix(id, "k1_") || !sensorID.MatchString(id) {
continue
}
s.mu.Lock()
if name := s.names[id]; name != "" {
item["name"] = name
}
s.mu.Unlock()
seen[id] = true
items = append(items, item)
}
}
} }
} found, _ := result["items"].([]any)
if result, e := s.driver("/inventory", nil); e == nil { for _, raw := range found {
if found, ok := result["items"].([]any); ok { item, ok := raw.(map[string]any)
for _, v := range found { if !ok {
item, ok := v.(map[string]any) continue
if !ok { }
continue id, _ := item["id"].(string)
} if modelForDevice(id) != model || seen[id] {
id, _ := item["id"].(string) continue
seen[id] = true }
s.mu.Lock() if model.ID == "insta360.x4" && !currentCameraSnapshot(item, model) {
// Older installed profiles must not break the paired inventory.
// USB discovery still exposes their initialization action, while
// preserving a legacy runtime's refusal to interrupt acquisition.
snapshot, _ := item["snapshot"].(map[string]any)
unsafePreparation[id] = item["preparation_safe"] == false || snapshot["acquisition"] != "idle"
continue
}
s.mu.Lock()
if model.PrepareUnit != "" {
item["configured"] = s.initialized[id] item["configured"] = s.initialized[id]
if n := s.names[id]; n != "" {
item["name"] = n
}
s.mu.Unlock()
items = append(items, item)
} }
if name := s.names[id]; name != "" {
item["name"] = name
}
s.mu.Unlock()
if model.Kind != "" {
item["kind"] = model.Kind
}
seen[id] = true
items = append(items, item)
} }
} }
paths, _ := filepath.Glob("/sys/bus/usb/devices/*") for _, device := range usb {
for _, path := range paths { if !seen[device.id] {
read := func(n string) string { seen[device.id] = true
b, _ := os.ReadFile(filepath.Join(path, n)) item := s.discovery(device.id, device.speed, true)
return strings.TrimSpace(string(b)) if unsafePreparation[device.id] {
item["preparation_safe"] = false
}
items = append(items, item)
} }
if read("idVendor") != "8086" || read("idProduct") != "0b5c" {
continue
}
serial := read("serial")
if serial == "" {
continue
}
h := sha256.Sum256([]byte(serial))
id := "rsd455_" + hex.EncodeToString(h[:])[:32]
if seen[id] {
continue
}
seen[id] = true
items = append(items, s.discovery(id, read("speed")+" Мбит/с", true))
} }
s.mu.Lock() s.mu.Lock()
configured := []string{} configured := []string{}
for id, ready := range s.initialized { for id, ready := range s.initialized {
if ready && sensorID.MatchString(id) && !seen[id] { if model := modelForDevice(id); ready && model != nil && model.PrepareUnit != "" && !seen[id] {
configured = append(configured, id) configured = append(configured, id)
} }
} }
@@ -246,28 +268,41 @@ func (s *Sensors) Inventory() map[string]any {
for _, id := range configured { for _, id := range configured {
items = append(items, s.discovery(id, "—", false)) items = append(items, s.discovery(id, "—", false))
} }
var preparation any var preparation any
if data, e := os.ReadFile("/var/lib/mission-core-node-drivers/preparation.json"); e == nil && len(data) < 32768 { if data, err := os.ReadFile(sensorModels[0].Report); err == nil && len(data) < 32768 {
_ = json.Unmarshal(data, &preparation) _ = json.Unmarshal(data, &preparation)
} }
s.mu.Lock() s.mu.Lock()
operations := []any{} operations := []any{}
preparations := []*sensorPreparation{}
for _, v := range s.operations { for _, v := range s.operations {
if time.Now().Unix()-v.Updated < 600 { if time.Now().Unix()-v.Updated < 600 || v.State == "running" {
operations = append(operations, map[string]any{"operation_id": v.Command.ID, "device_id": v.Command.Session.DeviceID, "action_id": v.Command.Action, "requested_at": v.Command.Requested, "state": v.State, "error": v.Error}) operations = append(operations, map[string]any{"operation_id": v.Command.ID, "device_id": v.Command.Session.DeviceID, "action_id": v.Command.Action, "requested_at": v.Command.Requested, "state": v.State, "error": v.Error})
if v.Preparation != nil {
copy := *v.Preparation
preparations = append(preparations, &copy)
}
} }
} }
s.mu.Unlock() s.mu.Unlock()
return map[string]any{"schema": "missioncore.node.devices/v1", "items": items, "preparation": preparation, "operations": operations} for i, value := range preparations {
preparations[i] = preparationView(value)
}
return map[string]any{"schema": "missioncore.node.devices/v1", "items": items, "preparation": preparation, "preparations": preparations, "operations": operations}
} }
func (s *Sensors) discovery(id, speed string, online bool) map[string]any { func (s *Sensors) discovery(id, speed string, online bool) map[string]any {
now := time.Now().UTC().Format(time.RFC3339Nano) now := time.Now().UTC().Format(time.RFC3339Nano)
model := modelForDevice(id)
s.mu.Lock() s.mu.Lock()
name, configured := s.names[id], s.initialized[id] name, configured := s.names[id], s.initialized[id]
identity, identityPresent := s.discoverySessions[id]
session := s.discoverySessions[id].session
if session == "" {
session = s.instance + "_" + id
}
s.mu.Unlock() s.mu.Unlock()
if name == "" { if name == "" {
name = "RealSense D455" name = model.Name
} }
connectivity, enrollment := "offline", "empty" connectivity, enrollment := "offline", "empty"
if online { if online {
@@ -276,24 +311,30 @@ func (s *Sensors) discovery(id, speed string, online bool) map[string]any {
if configured { if configured {
enrollment = "enrolled" enrollment = "enrolled"
} }
return map[string]any{"id": id, "name": name, "model": "RealSense D455", "configured": configured, "prepared": false, "verified": false, "online": online, "usb": speed, "layers": []any{}, "snapshot": map[string]any{ stability, basis := "stable", "hardware-identifier"
"context": map[string]any{"session_id": s.instance + "_" + id, "device": map[string]any{"device_id": id, "model": map[string]string{"plugin_id": "missioncore.realsense", "plugin_version": "0.6.6", "model_id": "realsense.d455"}, "stability": "stable", "basis": "hardware-identifier"}, "execution": map[string]string{"node_id": s.nodeID, "agent_instance_id": s.instance, "platform": "linux"}, "opened_at": now}, initializable := !identityPresent || identity.stable
if !initializable {
stability, basis = "provisional", "transport-local"
}
return map[string]any{"id": id, "name": name, "model": model.Name, "kind": model.Kind, "initializable": initializable, "configured": configured, "prepared": false, "verified": false, "online": online, "usb": speed, "layers": []any{}, "snapshot": map[string]any{
"context": map[string]any{"session_id": session, "device": map[string]any{"device_id": id, "model": map[string]string{"plugin_id": model.Plugin, "plugin_version": model.Version, "model_id": model.ID}, "stability": stability, "basis": basis}, "execution": map[string]string{"node_id": s.nodeID, "agent_instance_id": s.instance, "platform": "linux"}, "opened_at": now},
"revision": 0, "enrollment": enrollment, "connectivity": connectivity, "acquisition": "idle", "observed_at": now}} "revision": 0, "enrollment": enrollment, "connectivity": connectivity, "acquisition": "idle", "observed_at": now}}
} }
func sensorViewAction(action string) bool { func sensorViewAction(action string) bool {
return action == "details" || action == "offer" || action == "close-peer" return action == "details" || action == "offer" || action == "close-peer" || action == "settings.read" || action == "files.list"
} }
func (s *Sensors) Submit(c SensorCommand, remote bool) (*SensorOperation, error) { func (s *Sensors) Submit(c SensorCommand, remote bool) (*SensorOperation, error) {
if strings.HasPrefix(c.Session.DeviceID, "k1_") && (c.Action == "prepare" || c.Action == "replay") { model := modelForDevice(c.Session.DeviceID)
return nil, errors.New("Эта операция не поддерживается K1.") if c.APIVersion != SensorSchema || c.Kind != "OperationRequest" || !operationID.MatchString(c.ID) || c.Idempotency != c.ID || model == nil || c.Session.SessionID == "" || len(c.Session.SessionID) > 192 {
}
if c.APIVersion != SensorSchema || c.Kind != "OperationRequest" || !operationID.MatchString(c.ID) || c.Idempotency != c.ID || !sensorID.MatchString(c.Session.DeviceID) || len(c.Session.SessionID) > 192 {
return nil, errors.New("Некорректная команда устройства.") return nil, errors.New("Некорректная команда устройства.")
} }
if !map[string]bool{"prepare": true, "details": true, "rename": true, "verify": true, "start": true, "replay": true, "stop": true, "option": true, "offer": true, "close-peer": true}[c.Action] { if !model.Actions[c.Action] {
return nil, errors.New("Операция не поддерживается.") return nil, errors.New("Операция не поддерживается этой моделью.")
}
if c.Action == "prepare" && len(c.Parameters) != 0 {
return nil, errors.New("Подготовка использует встроенный профиль устройства.")
} }
deadline, e := time.Parse(time.RFC3339Nano, c.Deadline) deadline, e := time.Parse(time.RFC3339Nano, c.Deadline)
requested, e2 := time.Parse(time.RFC3339Nano, c.Requested) requested, e2 := time.Parse(time.RFC3339Nano, c.Requested)
@@ -315,7 +356,7 @@ func (s *Sensors) Submit(c SensorCommand, remote bool) (*SensorOperation, error)
return nil, errors.New("Срок команды истёк. Устройство не изменено.") return nil, errors.New("Срок команды истёк. Устройство не изменено.")
} }
for _, v := range s.operations { for _, v := range s.operations {
if v.State == "running" && v.Command.Action == "prepare" { if v.State == "running" && v.Command.Action == "prepare" && (v.Preparation == nil || v.Preparation.Phase == "profile") && c.Action != "prepare" && !sensorViewAction(c.Action) && modelForDevice(v.Command.Session.DeviceID) == model {
return nil, errors.New("Подготовка модели ещё выполняется.") return nil, errors.New("Подготовка модели ещё выполняется.")
} }
if v.State == "running" && v.Command.Session.DeviceID == c.Session.DeviceID && !sensorViewAction(c.Action) && !sensorViewAction(v.Command.Action) { if v.State == "running" && v.Command.Session.DeviceID == c.Session.DeviceID && !sensorViewAction(c.Action) && !sensorViewAction(v.Command.Action) {
@@ -357,10 +398,20 @@ func (s *Sensors) execute(c SensorCommand) {
break break
} }
} }
if item == nil { deadline, _ := time.Parse(time.RFC3339Nano, c.Deadline)
if !deadline.After(time.Now()) {
err = errors.New("Срок команды истёк. Устройство не изменено.")
} else if item == nil {
err = errors.New("Камера не обнаружена. Проверьте подключение.") err = errors.New("Камера не обнаружена. Проверьте подключение.")
} else if c.Action == "prepare" && item["online"] != true {
err = errors.New("Камера отключена. Проверьте подключение.")
} else if c.Action == "prepare" && item["initializable"] == false {
err = errors.New("Не удалось однозначно определить камеру. Проверьте её идентификатор и подключение.")
} else if (c.Action == "prepare" || c.Action == "rename") && sensorSessionID(item) != c.Session.SessionID {
err = errors.New("Сеанс устройства изменился. Обновите сведения.")
} else if c.Action == "prepare" { } else if c.Action == "prepare" {
result, err = s.prepare(c) result, err = s.prepare(c, item)
uncertain = errors.Is(err, errPreparationUncertain)
} else if c.Action == "rename" { } else if c.Action == "rename" {
name, ok := c.Parameters["name"].(string) name, ok := c.Parameters["name"].(string)
if !ok || strings.TrimSpace(name) == "" || len([]rune(name)) > 80 || strings.ContainsAny(name, "\n\r\t") { if !ok || strings.TrimSpace(name) == "" || len([]rune(name)) > 80 || strings.ContainsAny(name, "\n\r\t") {
@@ -374,14 +425,10 @@ func (s *Sensors) execute(c SensorCommand) {
} }
} else { } else {
var v map[string]any var v map[string]any
if strings.HasPrefix(c.Session.DeviceID, "k1_") && s.NetworkDevices != nil { deadline, _ := time.Parse(time.RFC3339Nano, c.Deadline)
deadline, _ := time.Parse(time.RFC3339Nano, c.Deadline) ctx, cancel := context.WithDeadline(context.Background(), deadline)
ctx, cancel := context.WithDeadline(context.Background(), deadline) v, err = s.modelDriver(ctx, modelForDevice(c.Session.DeviceID), "/operation", c)
v, err = s.NetworkDevices.call(ctx, "/sensor-operation", c) cancel()
cancel()
} else {
v, err = s.driver("/operation", c)
}
uncertain = err != nil || v["state"] == "unknown" uncertain = err != nil || v["state"] == "unknown"
if err == nil { if err == nil {
if v["state"] == "complete" { if v["state"] == "complete" {
@@ -418,48 +465,6 @@ func (s *Sensors) execute(c SensorCommand) {
v.Error = "Не удалось сохранить результат операции. Обновите состояние устройства." v.Error = "Не удалось сохранить результат операции. Обновите состояние устройства."
} }
} }
func (s *Sensors) prepare(c SensorCommand) (any, error) {
s.prepareMu.Lock()
defer s.prepareMu.Unlock()
for _, raw := range s.Inventory()["items"].([]any) {
item := raw.(map[string]any)
snap := item["snapshot"].(map[string]any)
if state := snap["acquisition"]; state != "idle" && state != "failed" {
return nil, errors.New("Остановите захват камер перед подготовкой модели.")
}
}
ctx, cancel := context.WithTimeout(context.Background(), 310*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "/usr/bin/systemctl", "start", "mission-core-node-realsense-prepare.service")
cmd.Env = []string{"PATH=/usr/bin:/bin", "LANG=C", "DBUS_SYSTEM_BUS_ADDRESS=unix:path=/run/dbus/system_bus_socket"}
if cmd.Run() != nil {
return nil, errors.New("Подготовка драйвера не завершена. Проверьте этапы и повторите действие.")
}
for i := 0; i < 12; i++ {
inv := s.Inventory()
for _, v := range inv["items"].([]any) {
item := v.(map[string]any)
if item["id"] == c.Session.DeviceID && item["prepared"] == true {
snap := item["snapshot"].(map[string]any)
sc := snap["context"].(map[string]any)
verify := c
verify.Action = "verify"
verify.Session.SessionID = sc["session_id"].(string)
result, e := s.driver("/operation", verify)
if e != nil {
return nil, e
}
if result["state"] != "complete" {
message, _ := result["error"].(string)
return nil, errors.New(message)
}
return result["result"], nil
}
}
time.Sleep(time.Second)
}
return nil, errors.New("Драйвер установлен, но камера не открылась. Проверьте USB-подключение.")
}
func (s *Sensors) Get(id string) *SensorOperation { func (s *Sensors) Get(id string) *SensorOperation {
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
@@ -9,6 +9,17 @@ import (
"time" "time"
) )
// Synthetic tests own both USB discovery and every model transport.
func isolateSensorHost(t *testing.T, s *Sensors) {
t.Helper()
s.usbRoot = t.TempDir()
for _, client := range s.clients {
client.Transport = sensorRoundTrip(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"items":[]}`)), Header: http.Header{}}, nil
})
}
}
func sensorTestCommand() SensorCommand { func sensorTestCommand() SensorCommand {
now := time.Now() now := time.Now()
id := "op_01234567890123456789012345678901" id := "op_01234567890123456789012345678901"
@@ -16,6 +27,7 @@ func sensorTestCommand() SensorCommand {
} }
func TestSensorRejectsAuthorityAndExpiredRequests(t *testing.T) { func TestSensorRejectsAuthorityAndExpiredRequests(t *testing.T) {
s, e := OpenSensors(t.TempDir(), "node_test") s, e := OpenSensors(t.TempDir(), "node_test")
isolateSensorHost(t, s)
if e != nil { if e != nil {
t.Fatal(e) t.Fatal(e)
} }
@@ -39,12 +51,16 @@ func TestSensorRejectsAuthorityAndExpiredRequests(t *testing.T) {
func TestSensorUncertainCrashDoesNotReplay(t *testing.T) { func TestSensorUncertainCrashDoesNotReplay(t *testing.T) {
root := t.TempDir() root := t.TempDir()
s, _ := OpenSensors(root, "node_test") s, _ := OpenSensors(root, "node_test")
isolateSensorHost(t, s)
isolateSensorHost(t, s)
c := sensorTestCommand() c := sensorTestCommand()
old := &SensorOperation{Command: c, State: "running", Updated: time.Now().Unix()} old := &SensorOperation{Command: c, State: "running", Updated: time.Now().Unix()}
if e := s.write(c.ID+".json", old); e != nil { if e := s.write(c.ID+".json", old); e != nil {
t.Fatal(e) t.Fatal(e)
} }
s, e := OpenSensors(root, "node_test") s, e := OpenSensors(root, "node_test")
isolateSensorHost(t, s)
isolateSensorHost(t, s)
if e != nil { if e != nil {
t.Fatal(e) t.Fatal(e)
} }
@@ -65,6 +81,7 @@ func TestSensorPreservesUncertainDriverOutcome(t *testing.T) {
for _, response := range []string{`{"state":"unknown","error":"uncertain"}`, "transport-failure"} { for _, response := range []string{`{"state":"unknown","error":"uncertain"}`, "transport-failure"} {
t.Run(response, func(t *testing.T) { t.Run(response, func(t *testing.T) {
s, _ := OpenSensors(t.TempDir(), "node_test") s, _ := OpenSensors(t.TempDir(), "node_test")
isolateSensorHost(t, s)
c := sensorTestCommand() c := sensorTestCommand()
s.operations[c.ID] = &SensorOperation{Command: c, State: "running"} s.operations[c.ID] = &SensorOperation{Command: c, State: "running"}
s.client = &http.Client{Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) { s.client = &http.Client{Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
@@ -88,12 +105,16 @@ func TestSensorPreservesUncertainDriverOutcome(t *testing.T) {
func TestSensorConfiguredIdentitySurvivesRestartAndDisconnect(t *testing.T) { func TestSensorConfiguredIdentitySurvivesRestartAndDisconnect(t *testing.T) {
root := t.TempDir() root := t.TempDir()
s, _ := OpenSensors(root, "node_test") s, _ := OpenSensors(root, "node_test")
isolateSensorHost(t, s)
isolateSensorHost(t, s)
c := sensorTestCommand() c := sensorTestCommand()
s.initialized[c.Session.DeviceID] = true s.initialized[c.Session.DeviceID] = true
if e := s.write("initialized.json", s.initialized); e != nil { if e := s.write("initialized.json", s.initialized); e != nil {
t.Fatal(e) t.Fatal(e)
} }
s, e := OpenSensors(root, "node_test") s, e := OpenSensors(root, "node_test")
isolateSensorHost(t, s)
isolateSensorHost(t, s)
if e != nil { if e != nil {
t.Fatal(e) t.Fatal(e)
} }
+12 -1
View File
@@ -13,6 +13,7 @@ import (
) )
type Server struct { type Server struct {
Monitor *Monitor
Store *Store Store *Store
Pairing *Pairing Pairing *Pairing
Sensors *Sensors Sensors *Sensors
@@ -24,6 +25,7 @@ type Server struct {
Access *AccessStore Access *AccessStore
Tailscale func() TailscaleStatus Tailscale func() TailscaleStatus
Environment func() EnvironmentStatus Environment func() EnvironmentStatus
Presentation *PresentationStore
mu sync.Mutex mu sync.Mutex
logins map[string]time.Time logins map[string]time.Time
sessions map[string]time.Time sessions map[string]time.Time
@@ -80,6 +82,11 @@ func reply(w http.ResponseWriter, status int, v any) {
func (s *Server) Handler() http.Handler { func (s *Server) Handler() http.Handler {
mux := http.NewServeMux() mux := http.NewServeMux()
s.localPreviewRoutes(mux)
s.monitorRoutes(mux)
if s.Presentation != nil {
s.presentationRoutes(mux)
}
if s.Sensors != nil { if s.Sensors != nil {
s.Sensors.Routes(mux, s) s.Sensors.Routes(mux, s)
} }
@@ -165,7 +172,11 @@ func (s *Server) Handler() http.Handler {
w.Header().Set("Cache-Control", "no-store") w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Referrer-Policy", "no-referrer") w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'") ancestor, scripts := "'none'", "'self'"
if r.URL.Path == "/rerun-runtime.html" {
ancestor, scripts = "'self'", "'self' 'wasm-unsafe-eval'"
}
w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src "+scripts+"; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https: http:; media-src 'self' blob: https: http:; connect-src 'self'; frame-src 'self'; worker-src 'self' blob:; frame-ancestors "+ancestor+"; base-uri 'none'; form-action 'self'")
if "http://"+r.Host != s.Origin { if "http://"+r.Host != s.Origin {
http.Error(w, "Invalid host", http.StatusForbidden) http.Error(w, "Invalid host", http.StatusForbidden)
return return
+201
View File
@@ -0,0 +1,201 @@
#!/usr/bin/python3
"""Independent one-second collector, local archive and private Node read adapter."""
import json
import logging
import os
import re
import signal
import socketserver
import threading
import time
from collections import deque
from http.server import BaseHTTPRequestHandler
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
from linux_metrics import LinuxMetrics
from storage import SCHEMA, Archive
SOCKET = Path("/run/mission-core-monitor/monitor.sock")
class Collector:
def __init__(self):
self.stop = threading.Event()
self.lock = threading.Lock()
self.latest = None
self.definitions = {}
self.events = deque(maxlen=64)
self.storage = "starting"
self.database_bytes = None
self.archive = None
self.boot = Path("/proc/sys/kernel/random/boot_id").read_text().strip()
def event(self, value):
if (
not isinstance(value, dict)
or set(value) - {"code", "kind", "locations"}
or value.get("code") not in {"ui-error", "ui-rejection", "ui-render-error"}
or not isinstance(value.get("kind"), str)
or not re.fullmatch("[A-Za-z]{1,48}", value["kind"])
or not isinstance(value.get("locations", []), list)
or len(value.get("locations", [])) > 8
or any(
not isinstance(v, str)
or not re.fullmatch(r"[A-Za-z0-9_-]{1,96}\.js:[0-9]{1,9}:[0-9]{1,9}", v)
for v in value.get("locations", [])
)
):
raise ValueError("invalid-event")
with self.lock:
if len(self.events) < 64:
self.events.append({**value, "at": time.time()})
def run(self):
metrics = LinuxMetrics()
maintenance = 0
while not self.stop.is_set():
started = time.monotonic()
try:
values = metrics.sample()
with self.lock:
events = list(self.events)
sample = dict(
at=time.time(), boot_id=self.boot, uptime=started, values=values, events=events
)
if self.archive is None:
self.archive = Archive()
# Maintenance also runs while writes are paused by a disk budget.
if started - maintenance > 60:
self.database_bytes = self.archive.maintain()
maintenance = started
record = self.archive.append(sample, metrics.definitions)
with self.lock:
for _ in events:
self.events.popleft()
self.latest = record
self.definitions = metrics.definitions
self.storage = "ready"
except Exception as error:
logging.warning("monitor sample failed class=%s", type(error).__name__)
with self.lock:
self.storage = (
str(error)
if str(error) in {"disk-reserve", "archive-budget"}
else "unavailable"
)
self.stop.wait(max(0.05, 1 - (time.monotonic() - started)))
def status(self):
with self.lock:
return dict(
schema=SCHEMA,
source_id=self.archive.source if self.archive else None,
latest=self.latest,
definitions=self.definitions,
storage=self.storage,
database_bytes=self.database_bytes,
sample_interval_seconds=1,
retention_days=7,
database_budget_bytes=2 * 1024**3,
free_reserve_bytes=2 * 1024**3,
)
class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
daemon_threads = True
block_on_close = False
def __init__(self, collector):
self.collector = collector
self.capacity = threading.BoundedSemaphore(6)
super().__init__(str(SOCKET), Handler)
def process_request(self, request, address):
if not self.capacity.acquire(False):
request.close()
return
request.settimeout(5)
super().process_request(request, address)
def process_request_thread(self, request, address):
try:
super().process_request_thread(request, address)
finally:
self.capacity.release()
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def reply(self, value, status=200):
payload = json.dumps(value, allow_nan=False, separators=(",", ":")).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def do_GET(self):
path = urlsplit(self.path)
try:
if path.path == "/status":
self.reply(self.server.collector.status())
elif path.path == "/batch":
after = int(parse_qs(path.query).get("after", ["0"])[0])
if not 0 <= after <= 2**53 - 1:
raise ValueError()
archive = self.server.collector.archive
if archive is None:
self.reply({"error": "Archive unavailable"}, 503)
else:
self.reply(archive.batch(after))
else:
self.reply({"error": "Unknown request"}, 404)
except Exception:
self.reply({"error": "Archive unavailable"}, 503)
def do_POST(self):
try:
size = int(self.headers.get("Content-Length", "0"))
if self.path != "/events" or not 0 < size <= 2048:
raise ValueError()
self.server.collector.event(json.loads(self.rfile.read(size)))
self.reply({"ok": True})
except (ValueError, TypeError):
self.reply({"error": "Invalid event"}, 400)
def main():
logging.basicConfig(level=logging.WARNING)
os.umask(0o007)
collector = Collector()
from journal_events import watch
threading.Thread(
target=watch, args=(collector,), name="node-system-events", daemon=True
).start()
SOCKET.unlink(missing_ok=True)
server = Server(collector)
worker = threading.Thread(target=collector.run, name="node-system-sampler", daemon=True)
worker.start()
def stop(*_):
collector.stop.set()
threading.Thread(target=server.shutdown, daemon=True).start()
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
try:
server.serve_forever(poll_interval=0.5)
finally:
collector.stop.set()
server.server_close()
worker.join(5)
SOCKET.unlink(missing_ok=True)
if __name__ == "__main__":
main()
+103
View File
@@ -0,0 +1,103 @@
"""Classify bounded journal records; never persist free-form messages or payloads."""
import json
import re
import subprocess
import threading
RULES = (
("system-oom", r"out of memory|oom-kill|killed process"),
("gpu-reset", r"GPU HANG|GPU reset|Resetting.*(gpu|chip)|i915.*(hang|reset|error)"),
("disk-error", r"I/O error|EXT4-fs error|nvme.*(timeout|reset)|ata.*failed command"),
("usb-disconnected", r"USB disconnect"),
("usb-error", r"usb.*(error -|unable to enumerate|reset.*device)"),
("service-failed", r"Failed with result|Main process exited|Failed to start"),
("ui-process-exit", r"node-ui-process-terminated"),
("ui-load-failed", r"node-ui-load-failed"),
)
def classify(record):
message = record.get("MESSAGE")
if not isinstance(message, str):
return None
code = next((code for code, pattern in RULES if re.search(pattern, message, re.I)), None)
if code is None:
return None
try:
at = int(record["__REALTIME_TIMESTAMP"]) / 1_000_000
except (KeyError, ValueError, TypeError):
return None
return dict(
code=code,
kind="Kernel" if record.get("_TRANSPORT") == "kernel" else "System",
at=at,
locations=[],
)
def watch(collector):
args = [
"/usr/bin/journalctl",
"--follow",
"--lines=0",
"--output=json",
"--no-pager",
"_TRANSPORT=kernel",
"+",
"SYSLOG_IDENTIFIER=mission-core-node-ui",
"+",
"_SYSTEMD_UNIT=mission-core-node.service",
"+",
"_SYSTEMD_UNIT=mission-core-k1.service",
"+",
"_SYSTEMD_UNIT=mission-core-node-monitor.service",
"+",
"_SYSTEMD_UNIT=postgresql@16-ndcmonitor.service",
]
for unit in (
"mission-core-node.service",
"mission-core-k1.service",
"mission-core-node-monitor.service",
"postgresql@16-ndcmonitor.service",
):
args.extend(["+", "UNIT=" + unit])
while not collector.stop.is_set():
process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
def retire(process=process):
while process.poll() is None:
if collector.stop.wait(1):
if process.poll() is None:
process.terminate()
return
guard = threading.Thread(target=retire, daemon=True)
guard.start()
try:
while not collector.stop.is_set():
line = process.stdout.readline(65537)
if not line:
break
if len(line) > 65536:
while line and not line.endswith(b"\n"):
line = process.stdout.readline(65537)
continue
try:
event = classify(json.loads(line))
except (ValueError, TypeError):
continue
if event:
with collector.lock:
if len(collector.events) < 64:
collector.events.append(event)
finally:
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=3)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
process.stdout.close()
collector.stop.wait(10)
+353
View File
@@ -0,0 +1,353 @@
"""Read-only Linux counters. Missing or reset counters never manufacture zero."""
import os
import re
import time
from pathlib import Path
class LinuxMetrics:
def __init__(self, root=Path("/"), clock=time.monotonic):
self.root, self.clock = Path(root), clock
self.previous = {}
self.previous_time = None
self.definitions = {}
def text(self, path):
try:
return (self.root / str(path).lstrip("/")).read_text()[:262144].strip()
except (OSError, UnicodeError):
return None
def number(self, path):
try:
return float(self.text(path))
except (ValueError, TypeError):
return None
def paths(self, pattern):
return sorted(self.root.glob(pattern))[:128]
def sample(self):
now = self.clock()
elapsed = None if self.previous_time is None else now - self.previous_time
self.previous_time = now
values, definitions, counters = {}, {}, {}
def metric(
key, label, group, resource, unit, value, reason="Счётчик недоступен в этой системе"
):
values[key] = None if value is None else round(value, 3)
definitions[key] = dict(
label=label,
group=group,
resource=resource,
unit=unit,
reason=reason if value is None else None,
)
def delta(key, value):
if value is None:
return None
counters[key] = value
previous = self.previous.get(key)
return (
None
if previous is None or value < previous or not elapsed or elapsed > 10
else (value - previous) / elapsed
)
stat = self.text("proc/stat") or ""
cpus = 0
for line in stat.splitlines():
parts = line.split()
if not re.fullmatch(r"cpu\d*", parts[0]):
continue
if parts[0] != "cpu":
cpus += 1
data = [int(v) for v in parts[1:9]]
total = delta(parts[0] + ".total", sum(data))
idle = delta(parts[0] + ".idle", data[3] + data[4])
wait = delta(parts[0] + ".iowait", data[4])
for name, label, value in [
(
"usage",
"Загрузка",
None if not total or idle is None else 100 * (1 - idle / total),
),
(
"iowait",
"Ожидание диска",
None if not total or wait is None else 100 * wait / total,
),
]:
metric(
parts[0] + "." + name,
label,
"CPU",
parts[0],
"%",
value,
"Ожидаем два последовательных измерения",
)
if not cpus:
metric("cpu.usage", "Загрузка", "CPU", "CPU", "%", None)
memory = {}
for line in (self.text("proc/meminfo") or "").splitlines():
parts = line.replace(":", "").split()
if len(parts) > 1:
memory[parts[0]] = int(parts[1]) * 1024
for key, label in [
("MemTotal", "Всего"),
("MemAvailable", "Доступно"),
("SwapTotal", "Swap всего"),
("SwapFree", "Swap свободно"),
("Dirty", "Ожидает записи"),
("Writeback", "Записывается"),
]:
metric("memory." + key, label, "RAM", "Память", "bytes", memory.get(key))
total, available = memory.get("MemTotal"), memory.get("MemAvailable")
metric(
"memory.usage",
"Использовано",
"RAM",
"Память",
"%",
None if not total or available is None else 100 * (1 - available / total),
)
for index, load in enumerate((self.text("proc/loadavg") or "").split()[:3]):
metric(
"load." + str(index),
["За 1 минуту", "За 5 минут", "За 15 минут"][index],
"CPU",
"Load average",
"",
float(load),
)
for resource in ["cpu", "memory", "io"]:
for line in (self.text("proc/pressure/" + resource) or "").splitlines():
parts = line.split()
fields = dict(v.split("=") for v in parts[1:])
metric(
"pressure." + resource + "." + parts[0],
"Задержка за 10 секунд",
"Ожидание ресурсов",
resource + " · " + parts[0],
"%",
float(fields["avg10"]),
)
for interface in self.paths("sys/class/net/*"):
name = interface.name
for field, label in [
("rx_bytes", "Приём"),
("tx_bytes", "Передача"),
("rx_errors", "Ошибки приёма"),
("tx_errors", "Ошибки передачи"),
("rx_dropped", "Потери приёма"),
("tx_dropped", "Потери передачи"),
]:
raw = self.number(interface.relative_to(self.root) / "statistics" / field)
metric(
"net." + name + "." + field,
label,
"Сеть",
name,
"bytes/s" if field.endswith("bytes") else "1/s",
delta("net." + name + "." + field, raw),
)
speed = self.number(interface.relative_to(self.root) / "speed")
metric(
"net." + name + ".speed",
"Скорость соединения",
"Сеть",
name,
"Mbit/s",
speed if speed is not None and speed > 0 else None,
)
diskstats = (self.text("proc/diskstats") or "").splitlines()
for line in diskstats:
p = line.split()
if (
len(p) < 14
or p[2].startswith(("loop", "ram"))
or not (self.root / "sys/block" / p[2]).exists()
):
continue
name = p[2]
for index, label, unit, multiplier in [
(5, "Чтение", "bytes/s", 512),
(9, "Запись", "bytes/s", 512),
(3, "Операции чтения", "1/s", 1),
(7, "Операции записи", "1/s", 1),
(12, "Занятость", "%", 0.1),
]:
key = "disk." + name + "." + str(index)
rate = delta(key, int(p[index]))
metric(key, label, "Диски", name, unit, None if rate is None else rate * multiplier)
if self.root == Path("/"):
mounts = set()
for line in (self.text("proc/mounts") or "").splitlines():
p = line.split()
if len(p) < 3 or not p[0].startswith("/dev/") or p[1] in mounts:
continue
mount = p[1].replace("\\040", " ")
mounts.add(mount)
try:
st = os.statvfs(mount)
key = "fs." + str(len(mounts))
metric(
key + ".free",
"Свободно",
"Хранилище",
mount,
"bytes",
st.f_bavail * st.f_frsize,
)
metric(
key + ".usage",
"Использовано",
"Хранилище",
mount,
"%",
100 * (1 - st.f_bfree / st.f_blocks) if st.f_blocks else None,
)
metric(
key + ".inodes",
"Использовано inode",
"Хранилище",
mount,
"%",
100 * (1 - st.f_ffree / st.f_files) if st.f_files else None,
)
except OSError:
metric(
"fs." + str(len(mounts)) + ".free",
"Свободно",
"Хранилище",
mount,
"bytes",
None,
)
for path in self.paths("sys/class/hwmon/hwmon*/temp*_input"):
relative = path.relative_to(self.root)
name = self.text(path.parent.relative_to(self.root) / "name") or path.parent.name
raw = self.number(relative)
metric(
"temperature." + path.parent.name + "." + path.stem,
"Температура",
"Температура",
name + " · " + path.stem,
"°C",
None if raw is None else raw / 1000,
)
for card in self.paths("sys/class/drm/card[0-9]"):
base = card.relative_to(self.root)
metric(
"gpu." + card.name + ".usage",
"Загрузка",
"GPU",
card.name,
"%",
self.number(base / "device/gpu_busy_percent"),
"Драйвер не публикует общий счётчик загрузки GPU",
)
metric(
"gpu." + card.name + ".frequency",
"Частота",
"GPU",
card.name,
"MHz",
self.number(base / "gt_cur_freq_mhz"),
)
for field, label in [
("mem_info_vram_used", "Видеопамять занята"),
("mem_info_vram_total", "Видеопамять всего"),
]:
metric(
"gpu." + card.name + "." + field,
label,
"GPU",
card.name,
"bytes",
self.number(base / "device" / field),
"Выделенная видеопамять или её счётчик недоступны",
)
for usb in self.paths("sys/bus/usb/devices/*"):
if not (usb / "idVendor").exists():
continue
base = usb.relative_to(self.root)
name = usb.name
metric(
"usb." + name + ".speed",
"Скорость соединения",
"USB",
name,
"Mbit/s",
self.number(base / "speed"),
)
metric(
"usb." + name + ".traffic",
"Трафик",
"USB",
name,
"bytes/s",
None,
"USB-драйвер не публикует счётчик трафика порта",
)
groups = self.paths("sys/fs/cgroup/system.slice/mission-core*.service")
groups += self.paths(
"sys/fs/cgroup/system.slice/system-postgresql.slice/postgresql@16-ndcmonitor.service"
)
groups += self.paths(
"sys/fs/cgroup/user.slice/user-*.slice/user@*.service/app.slice/app-gnome-org.nodedc.MissionCoreNode-*.scope"
)
for path in groups:
base = path.relative_to(self.root)
name = path.name
key = "service." + re.sub("[^A-Za-z0-9_.-]", "_", name)
metric(
key + ".memory",
"Память",
"Приложения",
name,
"bytes",
self.number(base / "memory.current"),
)
metric(
key + ".peak",
"Пик памяти",
"Приложения",
name,
"bytes",
self.number(base / "memory.peak"),
)
fields = dict(
line.split() for line in (self.text(base / "cpu.stat") or "").splitlines()
)
rate = delta(
key + ".cpu", float(fields["usage_usec"]) if "usage_usec" in fields else None
)
metric(
key + ".cpu",
"Загрузка CPU",
"Приложения",
name,
"%",
None if rate is None else rate / 10000 / max(cpus, 1),
)
fields = dict(
line.split() for line in (self.text(base / "memory.events") or "").splitlines()
)
metric(
key + ".oom",
"Убийств из-за нехватки памяти",
"Приложения",
name,
"",
float(fields["oom_kill"]) if "oom_kill" in fields else None,
)
self.previous = counters
# A bounded hardware inventory protects the control-plane payload budget.
keys = list(values)[:384]
self.definitions = {key: definitions[key] for key in keys}
return {key: values[key] for key in keys}
+13
View File
@@ -0,0 +1,13 @@
CREATE EXTENSION IF NOT EXISTS timescaledb;
CREATE TABLE IF NOT EXISTS monitor_identity (singleton boolean PRIMARY KEY DEFAULT true CHECK(singleton), source_id text NOT NULL);
INSERT INTO monitor_identity(singleton,source_id) VALUES(true,gen_random_uuid()::text) ON CONFLICT DO NOTHING;
CREATE TABLE IF NOT EXISTS monitor_samples (
seq bigint GENERATED ALWAYS AS IDENTITY,
observed_at timestamptz NOT NULL,
payload jsonb NOT NULL,
PRIMARY KEY(observed_at,seq)
);
SELECT create_hypertable('monitor_samples',by_range('observed_at',INTERVAL '1 hour'),if_not_exists=>true);
CREATE INDEX IF NOT EXISTS monitor_samples_cursor ON monitor_samples(seq);
CREATE TABLE IF NOT EXISTS monitor_definitions(singleton boolean PRIMARY KEY DEFAULT true CHECK(singleton),payload jsonb NOT NULL);
REVOKE ALL ON DATABASE mission_core_monitor FROM PUBLIC;
+118
View File
@@ -0,0 +1,118 @@
"""Bounded local Timescale archive; transport acknowledgements never delete data."""
import json
import shutil
from contextlib import contextmanager
from datetime import UTC, datetime
SCHEMA = "missioncore.node-system-monitor/v1"
MAX_BATCH_BYTES = 196608
DATABASE_BUDGET = 2 * 1024**3
class Archive:
def __init__(self):
from psycopg2.pool import ThreadedConnectionPool
self.pool = ThreadedConnectionPool(
1,
4,
host="/run/mission-core-monitor-db",
port=5433,
dbname="mission_core_monitor",
user="mission-core-monitor",
connect_timeout=3,
options="-c statement_timeout=3000",
)
try:
with self.connection() as db, db.cursor() as cursor:
cursor.execute("SELECT source_id FROM monitor_identity")
self.source = cursor.fetchone()[0]
except Exception:
self.pool.closeall()
raise
self.definitions = None
self.database_bytes = None
@contextmanager
def connection(self):
db = self.pool.getconn()
try:
yield db
db.commit()
except BaseException:
db.rollback()
raise
finally:
self.pool.putconn(db)
def append(self, sample, definitions):
# This reserve belongs to telemetry, never to acquisition storage.
if shutil.disk_usage("/var/lib/mission-core-monitor").free < 2 * 1024**3:
raise RuntimeError("disk-reserve")
if self.database_bytes is None or self.database_bytes >= DATABASE_BUDGET:
raise RuntimeError("archive-budget")
payload = json.dumps(sample, separators=(",", ":"), allow_nan=False)
if len(payload.encode()) > 32768:
raise ValueError("sample-budget")
with self.connection() as db, db.cursor() as cursor:
if definitions != self.definitions:
cursor.execute(
"INSERT INTO monitor_definitions VALUES(true,%s) ON CONFLICT(singleton) "
"DO UPDATE SET payload=excluded.payload",
(json.dumps(definitions),),
)
cursor.execute(
"INSERT INTO monitor_samples(observed_at,payload) VALUES(%s,%s) RETURNING seq",
(datetime.fromtimestamp(sample["at"], UTC), payload),
)
seq = cursor.fetchone()[0]
self.definitions = definitions
return {**sample, "seq": seq}
def batch(self, after):
with self.connection() as db, db.cursor() as cursor:
cursor.execute(
"SELECT seq,payload FROM monitor_samples WHERE seq>%s ORDER BY seq LIMIT 32",
(after,),
)
rows = []
size = 0
for seq, payload in cursor.fetchall():
record = {**payload, "seq": seq}
size += len(json.dumps(record).encode())
if size > MAX_BATCH_BYTES:
break
rows.append(record)
cursor.execute("SELECT min(seq),max(seq),min(observed_at) FROM monitor_samples")
first, last, oldest = cursor.fetchone()
return dict(
schema=SCHEMA,
source_id=self.source,
samples=rows,
first_seq=first,
last_seq=last,
retained_since=oldest.timestamp() if oldest else None,
)
def maintain(self):
with self.connection() as db, db.cursor() as cursor:
cursor.execute("SELECT drop_chunks('monitor_samples',INTERVAL '7 days')")
cursor.execute("SELECT pg_database_size(current_database())")
size = cursor.fetchone()[0]
if size >= DATABASE_BUDGET:
# Drop one oldest completed chunk per pass, retaining the live hour.
cursor.execute(
"SELECT min(range_end) FROM timescaledb_information.chunks "
"WHERE hypertable_name='monitor_samples' AND range_end<NOW()"
)
boundary = cursor.fetchone()[0]
if boundary:
cursor.execute(
"SELECT drop_chunks('monitor_samples',older_than=>%s::timestamptz)",
(boundary,),
)
cursor.execute("SELECT pg_database_size(current_database())")
size = cursor.fetchone()[0]
self.database_bytes = size
return size
@@ -1,6 +1,7 @@
// An authenticated Node action may start only this fixed model job. // An authenticated Node action may start only this fixed model job.
polkit.addRule(function(action, subject) { polkit.addRule(function(action, subject) {
if (subject.user === "mission-core-node" && action.id === "org.freedesktop.systemd1.manage-units" && action.lookup("unit") === "mission-core-node-realsense-prepare.service" && action.lookup("verb") === "start") { var unit = action.lookup("unit");
if (subject.user === "mission-core-node" && action.id === "org.freedesktop.systemd1.manage-units" && (unit === "mission-core-node-realsense-prepare.service" || unit === "mission-core-node-insta360-x4-profile.service") && action.lookup("verb") === "start") {
return polkit.Result.YES; return polkit.Result.YES;
} }
}); });
+4 -1
View File
@@ -11,13 +11,15 @@ import sys
from build_deb import build, VERSION, BRAND_SHA256 from build_deb import build, VERSION, BRAND_SHA256
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
DG_COMMIT = "1bdfc6c24072d38cc1068086ea271c444f2524ad" DG_COMMIT = "8c53f73ee521561a1cc7944a7f7cf113702f40b5"
def guideline_sources(): def guideline_sources():
dg = ROOT.parents[2] / "NODEDC_DESIGN_GUIDELINE" dg = ROOT.parents[2] / "NODEDC_DESIGN_GUIDELINE"
paths = list((dg / "packages/ui-react/src").glob("*")) paths = list((dg / "packages/ui-react/src").glob("*"))
paths += list((dg / "packages/ui-react/dist").glob("*")) paths += list((dg / "packages/ui-react/dist").glob("*"))
paths += list((dg / "packages/ui-core/src").glob("*"))
paths += list((dg / "packages/ui-core/dist").glob("*"))
paths += [dg / "packages/ui-core/styles.css", dg / "packages/tokens/tokens.css", dg / "packages/tokens/themes.css"] paths += [dg / "packages/ui-core/styles.css", dg / "packages/tokens/tokens.css", dg / "packages/tokens/themes.css"]
return {str(p.relative_to(dg)): hashlib.sha256(p.read_bytes()).hexdigest() return {str(p.relative_to(dg)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in sorted(paths) if p.is_file()} for p in sorted(paths) if p.is_file()}
@@ -33,6 +35,7 @@ def provenance():
"design_guideline_commit": DG_COMMIT, "design_guideline_commit": DG_COMMIT,
"design_guideline_files": guideline_sources(), "design_guideline_files": guideline_sources(),
"shared_sensor_ui_files": {str(p.relative_to(ROOT.parents[1])): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((ROOT.parents[1] / "packages/sensor-ui/src").rglob("*")) if p.is_file()}, "shared_sensor_ui_files": {str(p.relative_to(ROOT.parents[1])): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((ROOT.parents[1] / "packages/sensor-ui/src").rglob("*")) if p.is_file()},
"shared_spatial_ui_files": {str(p.relative_to(ROOT.parents[1])): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((ROOT.parents[1] / "packages/spatial-ui/src").rglob("*")) if p.is_file()},
"k1_frontend_files": {str(p.relative_to(ROOT.parents[1])): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((ROOT.parents[1] / "plugins/xgrids-k1/frontend/src").rglob("*")) if p.is_file()}, "k1_frontend_files": {str(p.relative_to(ROOT.parents[1])): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((ROOT.parents[1] / "plugins/xgrids-k1/frontend/src").rglob("*")) if p.is_file()},
"toolchain": json.loads((ROOT / "toolchain.json").read_text()), "files": files} "toolchain": json.loads((ROOT / "toolchain.json").read_text()), "files": files}
+23 -2
View File
@@ -11,7 +11,8 @@ import sys
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
VERSION = "0.8.0" BINARY_VERSION = "0.8.19"
VERSION = "0.8.19"
sys.path.insert(0, str(ROOT.parents[1] / "scripts/packaging")) sys.path.insert(0, str(ROOT.parents[1] / "scripts/packaging"))
from debian import package from debian import package
@@ -43,7 +44,7 @@ Architecture: amd64
Maintainer: NODE.DC local build <noreply@example.invalid> Maintainer: NODE.DC local build <noreply@example.invalid>
Section: admin Section: admin
Priority: optional Priority: optional
Depends: adduser, systemd, python3, python3-gi, gir1.2-gtk-3.0, gir1.2-webkit2-4.1, pkexec, polkitd, ca-certificates, hicolor-icon-theme, network-manager, iproute2 Depends: adduser, systemd (>= 255), python3 (>= 3.12), python3 (<< 3.13), python3-gi, gir1.2-gtk-3.0, gir1.2-webkit2-4.1, pkexec, polkitd, ca-certificates, hicolor-icon-theme, network-manager, iproute2, python3-psycopg2, postgresql-16 (>= 16.15), timescaledb-2-oss-postgresql-16 (= 2.29.2~ubuntu24.04-1615), udev, libc6 (>= 2.35), libstdc++6 (>= 12), libgcc-s1, zlib1g
Description: Mission Core onboard computer configuration Description: Mission Core onboard computer configuration
Local graphical setup, host inventory, SSH access and persistent node identity. Local graphical setup, host inventory, SSH access and persistent node identity.
""".encode() """.encode()
@@ -67,14 +68,34 @@ Description: Mission Core onboard computer configuration
("environment_helper.py", "usr/lib/mission-core-node/environment_helper.py", 0o644), ("environment_helper.py", "usr/lib/mission-core-node/environment_helper.py", 0o644),
("mission-core-node-environment.service", "usr/lib/systemd/system/mission-core-node-environment.service", 0o644), ("mission-core-node-environment.service", "usr/lib/systemd/system/mission-core-node-environment.service", 0o644),
("60-environment.conf", "usr/share/mission-core-node/60-environment.conf", 0o644), ("60-environment.conf", "usr/share/mission-core-node/60-environment.conf", 0o644),
("setup-monitor", "usr/lib/mission-core-node/setup-monitor", 0o755),
("mission-core-node-monitor.service", "usr/lib/systemd/system/mission-core-node-monitor.service", 0o644),
]: ]:
files.append((path, (p / source).read_bytes(), mode)) files.append((path, (p / source).read_bytes(), mode))
for path in sorted((ROOT / 'monitor').iterdir()):
if path.suffix in {'.py', '.sql'}:
files.append(('usr/lib/mission-core-node/monitor/' + path.name, path.read_bytes(), 0o644))
files.append(("usr/share/mission-core-node/environment-profile.json", (ROOT / "internal/node/environment-profile.json").read_bytes(), 0o644)) files.append(("usr/share/mission-core-node/environment-profile.json", (ROOT / "internal/node/environment-profile.json").read_bytes(), 0o644))
for name in ("realsense_prepare.py", "realsense_iio_access.py"): for name in ("realsense_prepare.py", "realsense_iio_access.py"):
files.append(("usr/lib/mission-core-node/" + name, (p / name).read_bytes(), 0o644)) files.append(("usr/lib/mission-core-node/" + name, (p / name).read_bytes(), 0o644))
for name in ("mission-core-realsense.service", "mission-core-node-realsense-prepare.service"): for name in ("mission-core-realsense.service", "mission-core-node-realsense-prepare.service"):
files.append(("usr/lib/systemd/system/" + name, (p / name).read_bytes(), 0o644)) files.append(("usr/lib/systemd/system/" + name, (p / name).read_bytes(), 0o644))
files.append(("usr/share/polkit-1/rules.d/50-mission-core-device-prepare.rules", (p / "50-mission-core-device-prepare.rules").read_bytes(), 0o644)) files.append(("usr/share/polkit-1/rules.d/50-mission-core-device-prepare.rules", (p / "50-mission-core-device-prepare.rules").read_bytes(), 0o644))
# Node owns the first-use bootstrap; the optional model package owns its
# SDK, worker processes, USB grants and runtime preparation. No overlapping
# dpkg file ownership and no compiler/download prerequisite at first use.
profile_raw = (p / "insta360-profile.json").read_bytes()
profile = json.loads(profile_raw)
package_name = "mission-core-insta360-x4_" + profile["version"] + "_amd64.deb"
x4 = (ROOT / "build/model-packages" / package_name).read_bytes()
if len(x4) != profile["bytes"] or hashlib.sha256(x4).hexdigest() != profile["sha256"]:
raise ValueError("Bundled X4 package differs from the admitted release")
files.extend([
("usr/lib/mission-core-node/insta360_profile.py", (p / "insta360_profile.py").read_bytes(), 0o644),
("usr/lib/systemd/system/mission-core-node-insta360-x4-profile.service", (p / "mission-core-node-insta360-x4-profile.service").read_bytes(), 0o644),
("usr/share/mission-core-node/profiles/insta360-x4/profile.json", profile_raw, 0o644),
("usr/share/mission-core-node/profiles/insta360-x4/" + package_name, x4, 0o644),
])
files.append(("usr/share/mission-core-node/realsense/70-mission-core-realsense.rules", (p / "70-mission-core-realsense.rules").read_bytes(), 0o644)) files.append(("usr/share/mission-core-node/realsense/70-mission-core-realsense.rules", (p / "70-mission-core-realsense.rules").read_bytes(), 0o644))
bundle = json.loads((p / "realsense-bundle.json").read_text()) bundle = json.loads((p / "realsense-bundle.json").read_text())
files.append(("usr/share/mission-core-node/realsense/bundle.json", (p / "realsense-bundle.json").read_bytes(), 0o644)) files.append(("usr/share/mission-core-node/realsense/bundle.json", (p / "realsense-bundle.json").read_bytes(), 0o644))
@@ -0,0 +1,128 @@
"""Snapshot the reviewed Node/Core sources and Linux build inputs for the Mini."""
import argparse
import hashlib
import json
import stat
import subprocess
import zipfile
from pathlib import Path
NODE = Path(__file__).resolve().parents[1]
REPO = NODE.parents[1]
DG = REPO.parent / "NODEDC_DESIGN_GUIDELINE"
DG_COMMIT = "8c53f73ee521561a1cc7944a7f7cf113702f40b5"
def files(root):
values = (
subprocess.check_output(
["git", "ls-files", "-c", "-o", "--exclude-standard", "-z"], cwd=root
)
.decode()
.split("\0")
)
for name in sorted(set(values)):
path = root / name
if not name or name.startswith(".codex/") or not path.is_file():
continue
if path.is_symlink() or not path.resolve().is_relative_to(root):
raise ValueError("Unexpected source link")
yield path
def build(qualified, node_only=False):
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=DG, text=True).strip()
if commit != DG_COMMIT:
raise ValueError("Design Guideline revision differs from the admitted source")
paths = list(files(REPO))
# Build DG from its own pinned workspace lock. Its generated dist and
# transitive dependencies are not copied from a developer installation.
paths += [
path
for path in files(DG)
if path.relative_to(DG).parts[0]
in ("packages", "registry", "docs", "scripts", "server", "apps")
]
paths += [
DG / name
for name in (
"package.json",
"package-lock.json",
"tsconfig.base.json",
"apps/catalog/package.json",
)
]
lock = json.loads((NODE / "packaging/linux-toolchains.json").read_text())
paths += [NODE / "build/linux-toolchains" / item["name"] for item in lock["files"]]
for item in lock["files"]:
data = (NODE / "build/linux-toolchains" / item["name"]).read_bytes()
if hashlib.sha256(data).hexdigest() != item["sha256"]:
raise ValueError("Build toolchain changed")
wheel_lock = json.loads((NODE / "packaging/realsense-bundle.json").read_text())
paths += [NODE / "build/realsense-wheels" / item["name"] for item in wheel_lock["wheels"]]
profile = json.loads((NODE / "packaging/insta360-profile.json").read_text())
package_name = "mission-core-insta360-x4_" + profile["version"] + "_amd64.deb"
if qualified.name != package_name:
raise ValueError("Unexpected model package name")
package = qualified.read_bytes()
if len(package) != profile["bytes"] or hashlib.sha256(package).hexdigest() != profile["sha256"]:
raise ValueError("Qualified model package changed")
entries = {str(path.relative_to(REPO.parent)): path for path in sorted(set(paths))}
# The source artifact owns this build staging copy; no manual copy on the
# board, runtime path override or operator compiler dependency is needed.
virtual = str(REPO.name + "/apps/node-agent/build/model-packages/" + package_name)
entries[virtual] = qualified
metadata = {}
for name, path in entries.items():
data = path.read_bytes()
if len(data) > 100 * 1024 * 1024:
raise ValueError("Source file exceeds the artifact bound")
metadata[name] = {
"bytes": len(data),
"sha256": hashlib.sha256(data).hexdigest(),
"mode": 0o755 if path.stat().st_mode & stat.S_IXUSR else 0o644,
}
entrypoint = (NODE / "packaging/linux_build_entry.py").read_bytes()
manifest = {
"schema": "missioncore.node.linux-build-source/v1",
"profile": "node-only" if node_only else "node-core",
"repository": REPO.name,
"base_commit": subprocess.check_output(
["git", "rev-parse", "HEAD"], cwd=REPO, text=True
).strip(),
"design_guideline_commit": commit,
"toolchains": lock,
"entrypoint_sha256": hashlib.sha256(entrypoint).hexdigest(),
"files": metadata,
}
raw = json.dumps(manifest, sort_keys=True, indent=2).encode() + b"\n"
identifier = hashlib.sha256(raw).hexdigest()[:24]
output = NODE / "build" / ("mission-core-node-linux-build-" + identifier + ".pyz")
with output.open("xb") as stream, zipfile.ZipFile(stream, "w") as archive:
for name, data in (("__main__.py", entrypoint), ("source.json", raw)):
archive.writestr(name, data)
for name, path in entries.items():
archive.write(
path,
"source/" + name,
compress_type=zipfile.ZIP_DEFLATED
if path.stat().st_size < 4 * 1024 * 1024
else zipfile.ZIP_STORED,
)
output.chmod(0o600)
return {
"artifact": str(output),
"source_id": identifier,
"files": len(entries),
"bytes": output.stat().st_size,
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
}
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--model-package", type=Path, required=True)
parser.add_argument("--node-only", action="store_true")
args = parser.parse_args()
print(json.dumps(build(args.model_package.resolve(), args.node_only)))
@@ -0,0 +1,72 @@
"""Package the Ubuntu-qualified Node installer with the shared release launcher."""
import argparse
import hashlib
import json
import re
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
REPO = ROOT.parents[1]
def build(qualified):
evidence = json.loads((qualified / "qualification.json").read_text())
if evidence["state"] != "complete":
raise ValueError("A completed Ubuntu qualification is required")
candidates = [name for name in evidence["artifacts"] if name.startswith("mission-core-node_")]
if len(candidates) != 1:
raise ValueError("One qualified Node package is required")
package = candidates[0]
match = re.fullmatch(
r"mission-core-node_([0-9]+\.[0-9]+\.[0-9]+(?:-[1-9][0-9]*)?)_amd64\.deb", package
)
if not match:
raise ValueError("Invalid package name")
payload = (qualified / package).read_bytes()
expected = evidence["artifacts"][package]
if (
len(payload) != expected["bytes"]
or hashlib.sha256(payload).hexdigest() != expected["sha256"]
):
raise ValueError("Qualified Node package changed")
files = {
package: payload,
"install": (ROOT / "packaging/install-owner-release").read_bytes(),
"install_release.py": (ROOT / "packaging/install_owner_release.py").read_bytes(),
}
entry = (REPO / "plugins/insta360-x4/packaging/owner_release_entry.py").read_bytes()
manifest = {
"schema": "missioncore.node.owner-release/v1",
"version": match[1],
"qualification_profile": "node-package-and-local-ui",
"qualification_sha256": hashlib.sha256(
(qualified / "qualification.json").read_bytes()
).hexdigest(),
"clean_image_qualified": False,
"entrypoint_sha256": hashlib.sha256(entry).hexdigest(),
"files": {
name: {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()}
for name, data in files.items()
},
}
raw = json.dumps(manifest, indent=2, sort_keys=True).encode() + b"\n"
identifier = hashlib.sha256(raw).hexdigest()[:24]
output = ROOT / "build" / ("mission-core-node-install-" + identifier + ".pyz")
with output.open("xb") as stream, zipfile.ZipFile(stream, "w") as archive:
for name, data in {"__main__.py": entry, "release.json": raw, **files}.items():
archive.writestr(name, data)
output.chmod(0o600)
return {
"artifact": str(output),
"release_id": identifier,
"bytes": output.stat().st_size,
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
}
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--qualified", type=Path, required=True)
print(json.dumps(build(parser.parse_args().qualified)))
@@ -0,0 +1,260 @@
"""Versioned Python/Go X509 interoperability check; synthetic public certificates only."""
import hashlib
import json
import os
import platform
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
import zipfile
from datetime import UTC, datetime
from pathlib import Path
GO_SOURCE = r"""package main
import (
"crypto/x509"
"encoding/json"
"encoding/pem"
"os"
)
func cert(name string) *x509.Certificate {
raw, err := os.ReadFile(name); if err != nil { panic(err) }
block, _ := pem.Decode(raw); if block == nil { panic("invalid fixture") }
value, err := x509.ParseCertificate(block.Bytes); if err != nil { panic(err) }; return value
}
func main() {
root := cert("root.pem"); bad := cert("legacy.pem"); good := cert("fixed.pem")
roots := x509.NewCertPool(); roots.AddCert(root)
options := x509.VerifyOptions{
Roots: roots, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
}
_, legacyErr := bad.Verify(options)
if _, ok := legacyErr.(x509.UnknownAuthorityError); !ok { panic("legacy failure not reproduced") }
if _, err := good.Verify(options); err != nil { panic(err) }
if string(good.RawSubjectPublicKeyInfo) != string(root.RawSubjectPublicKeyInfo) {
panic("Core key changed")
}
if string(good.RawSubject) == string(root.RawSubject) { panic("ambiguous leaf subject") }
json.NewEncoder(os.Stdout).Encode(map[string]any{"legacy_rejected":true,"fixed_verified":true,"core_key_preserved":true})
}
"""
def digest(data):
return hashlib.sha256(data).hexdigest()
def build():
from cryptography import x509
from cryptography.x509.oid import ExtendedKeyUsageOID
from k1link.fleet.recovery import client_context
from k1link.fleet.trust import CoreTrust, pem
node = Path(__file__).resolve().parents[1]
lock = json.loads((node / "packaging/linux-toolchains.json").read_text())
go = next(item for item in lock["files"] if item["directory"] == "go")
toolchain = (node / "build/linux-toolchains" / go["name"]).read_bytes()
if digest(toolchain) != go["sha256"]:
raise ValueError("Pinned toolchain changed")
with tempfile.TemporaryDirectory(prefix="missioncore-synthetic-ca-") as temporary:
trust = CoreTrust(Path(temporary))
client_context(trust)
fixed = x509.load_pem_x509_certificates(
(Path(temporary) / "recovery-client.pem").read_bytes()
)[0]
legacy = (
trust.builder(trust.ca.subject, trust.key.public_key(), 1)
.issuer_name(trust.ca.subject)
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]), critical=False)
.sign(trust.key, None)
)
files = {
"root.pem": pem(trust.ca).encode(),
"fixed.pem": pem(fixed).encode(),
"legacy.pem": pem(legacy).encode(),
"check.go": GO_SOURCE.encode(),
"go.tar.gz": toolchain,
}
entry = Path(__file__).read_bytes()
manifest = {
"schema": "missioncore.channel-x509-check/v1",
"toolchain": go,
"entry_sha256": digest(entry),
"files": {
name: {"bytes": len(data), "sha256": digest(data)} for name, data in files.items()
},
}
raw = json.dumps(manifest, sort_keys=True).encode()
identifier = digest(raw)[:24]
path = node / "build" / ("mission-core-channel-check-" + identifier + ".pyz")
with path.open("xb") as stream, zipfile.ZipFile(stream, "w") as archive:
for name, data in {"__main__.py": entry, "check.json": raw, **files}.items():
archive.writestr(name, data)
path.chmod(0o600)
print(
json.dumps(
{
"artifact": str(path),
"id": identifier,
"bytes": path.stat().st_size,
"sha256": digest(path.read_bytes()),
}
)
)
def run():
if os.geteuid() == 0 or (platform.system(), platform.machine()) != ("Linux", "x86_64"):
raise ValueError("Use the unprivileged Ubuntu account")
if sys.argv[1:] not in ([], ["--job"], ["--clean"]):
raise ValueError("Only the fixed certificate check is allowed")
os.umask(0o077)
artifact = Path(sys.argv[0]).resolve()
with zipfile.ZipFile(artifact) as archive:
raw = archive.read("check.json")
manifest = json.loads(raw)
names = {"root.pem", "legacy.pem", "fixed.pem", "check.go", "go.tar.gz"}
if (
manifest["schema"] != "missioncore.channel-x509-check/v1"
or set(manifest["files"]) != names
or set(archive.namelist()) != names | {"__main__.py", "check.json"}
or len(archive.namelist()) != 7
or digest(archive.read("__main__.py")) != manifest["entry_sha256"]
):
raise ValueError("Unexpected check artifact")
identifier = digest(raw)[:24]
root = Path("/var/tmp/mission-core-channel-checks")
folder = root / identifier
for path in (root, folder):
path.mkdir(mode=0o700, exist_ok=True)
info = path.lstat()
if path.is_symlink() or info.st_uid != os.geteuid() or info.st_mode & 0o077:
raise ValueError("Check directory is not private and owned")
if sys.argv[1:] == ["--clean"]:
if not (folder / "report.json").exists():
raise ValueError("Preserve a completed attempt before cleanup")
shutil.rmtree(folder)
print(json.dumps({"cleaned": identifier}))
return
if not sys.argv[1:]:
if any(folder.iterdir()):
raise ValueError("Preserve the prior attempt before retry")
for name, expected in manifest["files"].items():
data = archive.read(name)
if len(data) != expected["bytes"] or digest(data) != expected["sha256"]:
raise ValueError("Check input changed")
(folder / name).write_bytes(data)
(folder / "report.json").write_text(
json.dumps(
{
"state": "staging",
"id": identifier,
"started_at": datetime.now(UTC).isoformat(),
}
)
+ "\n"
)
with tarfile.open(folder / "go.tar.gz") as tar:
members = tar.getmembers()
if len(members) > 40000 or sum(m.size for m in members) > 1024**3:
raise ValueError("Toolchain extraction exceeds bound")
if any(
Path(m.name).is_absolute()
or Path(m.name).parts[0] != "go"
or ".." in Path(m.name).parts
for m in members
):
raise ValueError("Unexpected toolchain path")
tar.extractall(folder, members=members, filter="data")
subprocess.run(
[
"/usr/bin/systemd-run",
"--user",
"--quiet",
"--collect",
"--wait",
"--pipe",
"--unit=mission-core-channel-check-" + identifier,
"--property=MemoryMax=1G",
"--property=CPUQuota=150%",
"--property=TasksMax=128",
"--property=RuntimeMaxSec=180",
"--property=KillMode=control-group",
"--property=Nice=10",
"/usr/bin/python3",
str(artifact),
"--job",
],
check=True,
)
print((folder / "report.json").read_text())
return
group = next(
line.split(":", 2)[2]
for line in Path("/proc/self/cgroup").read_text().splitlines()
if line.startswith("0::")
)
control = Path("/sys/fs/cgroup") / group.lstrip("/")
quota, period = map(int, (control / "cpu.max").read_text().split())
if (
int((control / "memory.max").read_text()) > 1024**3
or quota / period > 1.5
or int((control / "pids.max").read_text()) > 128
):
raise ValueError("Check limits not enforced")
started = time.monotonic()
report = {
"schema": manifest["schema"],
"id": identifier,
"started_at": datetime.now(UTC).isoformat(),
"monotonic": started,
"artifact_sha256": digest(artifact.read_bytes()),
}
env = {
"PATH": str(folder / "go/bin") + ":/usr/bin:/bin",
"GOENV": "off",
"GOCACHE": str(folder / "cache"),
"GOPATH": str(folder / "gopath"),
"GOTOOLCHAIN": "local",
"GOPROXY": "off",
"GOMAXPROCS": "2",
"GOMEMLIMIT": "512MiB",
"CGO_ENABLED": "0",
"GOWORK": "off",
}
# No SDK, USB, installed files, network fetches, or real host credentials.
result = subprocess.run(
[str(folder / "go/bin/go"), "run", "-p", "1", "check.go"],
cwd=folder,
env=env,
capture_output=True,
timeout=150,
)
(folder / "stdout").write_bytes(result.stdout)
(folder / "stderr").write_bytes(result.stderr)
report.update(
state="complete" if result.returncode == 0 else "error",
exit_code=result.returncode,
duration_seconds=time.monotonic() - started,
finished_at=datetime.now(UTC).isoformat(),
stdout_sha256=digest(result.stdout),
stderr_sha256=digest(result.stderr),
)
if result.returncode == 0:
report["checks"] = json.loads(result.stdout)
(folder / "report.json").write_text(json.dumps(report, indent=2) + "\n")
if result.returncode:
raise RuntimeError("Certificate interop check failed; inspect private report")
if __name__ == "__main__":
if sys.argv[1:] == ["--build"]:
build()
else:
run()
@@ -0,0 +1,67 @@
"""Run only synthetic X4 bootstrap checks in disposable unprivileged Ubuntu staging."""
import hashlib
import json
import os
import platform
import subprocess
import sys
import tempfile
import time
import zipfile
from datetime import UTC, datetime
from pathlib import Path
FILES = {
"apps/node-agent/packaging/insta360_profile.py",
"plugins/insta360-x4/tests/check_profile.py",
}
def main():
if os.geteuid() == 0 or platform.freedesktop_os_release().get("VERSION_ID") != "24.04":
raise ValueError("Run as an ordinary Ubuntu 24.04 user")
started, monotonic = datetime.now(UTC).isoformat(), time.monotonic()
with zipfile.ZipFile(sys.argv[0]) as archive:
manifest = json.loads(archive.read("manifest.json"))
if set(archive.namelist()) != FILES | {"__main__.py", "manifest.json"} or set(
manifest
) != FILES | {"__main__.py"}:
raise ValueError("Unexpected check artifact")
payload = {name: archive.read(name) for name in manifest}
if any(hashlib.sha256(raw).hexdigest() != manifest[name] for name, raw in payload.items()):
raise ValueError("Check artifact changed")
with tempfile.TemporaryDirectory(
prefix="mission-core-x4-profile-check-", dir="/var/tmp"
) as folder:
root = Path(folder)
for name in FILES:
target = root / name
target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
target.write_bytes(payload[name])
(root / "plugins/insta360-x4/build").mkdir(mode=0o700)
result = subprocess.run(
["/usr/bin/python3", "-I", str(root / "plugins/insta360-x4/tests/check_profile.py")],
capture_output=True,
text=True,
timeout=30,
)
print(
json.dumps(
{
"schema": "missioncore.node.x4-profile-check/v1",
"started_at": started,
"monotonic_started": monotonic,
"duration_seconds": time.monotonic() - monotonic,
"state": "complete" if result.returncode == 0 else "error",
"files": manifest,
"stdout": result.stdout,
"stderr": result.stderr,
}
)
)
return result.returncode
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,138 @@
"""D01: display only the latest failed X4 installer logs in an owner sudo TTY.
No package installation, service operation, camera command or permission change.
The owner terminal records stdout in a private user-owned diagnostic directory.
"""
import hashlib
import json
import os
import re
import stat
import subprocess
import sys
import time
from datetime import UTC, datetime
from pathlib import Path
STATE = Path("/var/lib/mission-core-node-profiles/insta360-x4")
def read_root(path, limit):
for parent in reversed(path.parents):
info = parent.lstat()
if not stat.S_ISDIR(info.st_mode) or info.st_uid or info.st_mode & 0o022:
raise ValueError("Untrusted diagnostic path")
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
try:
info = os.fstat(fd)
if not stat.S_ISREG(info.st_mode) or info.st_uid or info.st_mode & 0o022:
raise ValueError("Untrusted diagnostic file")
data = os.read(fd, limit + 1)
if len(data) > limit:
raise ValueError("Diagnostic file exceeds bound")
return data
finally:
os.close(fd)
def report():
if os.geteuid() != 0:
raise ValueError("Use the owner terminal")
state = json.loads(read_root(STATE / "preparation.json", 65536))
run_id = state.get("run_id", "")
if state.get("state") != "error" or not re.fullmatch("[0-9a-f]{32}", run_id):
raise ValueError("No completed failed X4 profile")
logs = {}
for name in ("1.stdout", "1.stderr"):
data = read_root(STATE / run_id / name, 1024 * 1024)
logs[name] = {
"sha256": hashlib.sha256(data).hexdigest(),
"text": data.decode(errors="replace"),
}
print(
json.dumps(
{
"schema": "missioncore.node.x4-profile-diagnostic/v1",
"utc": datetime.now(UTC).isoformat(),
"monotonic": time.monotonic(),
"profile": state,
"logs": logs,
},
ensure_ascii=False,
),
flush=True,
)
def launch():
if os.geteuid() == 0:
raise ValueError("Launch as the desktop owner")
source = Path(__file__).resolve()
if not re.fullmatch(r"/var/tmp/mission-core-x4-diagnostic-[0-9a-f]{24}\.py", str(source)):
raise ValueError("Use the versioned diagnostic artifact")
raw = source.read_bytes()
if source.stem != "mission-core-x4-diagnostic-" + hashlib.sha256(raw).hexdigest()[:24]:
raise ValueError("Diagnostic artifact changed")
os.umask(0o077)
folder = source.with_suffix("")
folder.mkdir(mode=0o700, exist_ok=True)
info = folder.lstat()
if folder.is_symlink() or info.st_uid != os.getuid() or info.st_mode & 0o077:
raise ValueError("Diagnostic directory must be private")
script = folder / "read-report"
script.write_text(
"#!/bin/bash\nset -uo pipefail\numask 077\nprintf '%s\\n' "
"'Mission Core: чтение ошибки подготовки X4' "
"'Изменений системы и команд камеры не будет. Введите пароль Ubuntu.'\n"
"/usr/bin/sudo /usr/bin/python3 -I '"
+ str(source)
+ "' --read 2>&1 | /usr/bin/tee '"
+ str(folder / "report.json")
+ "'\nmc_x4_result=${PIPESTATUS[0]}\nprintf "
"'\\nКод завершения: %s\\nНажмите Enter, чтобы закрыть.\\n' "
'"$mc_x4_result"\nread -r mc_x4_close\nexit "$mc_x4_result"\n'
)
script.chmod(0o700)
env = dict(os.environ)
result = subprocess.run(
["/usr/bin/systemctl", "--user", "show-environment"],
capture_output=True,
text=True,
timeout=5,
check=True,
)
for line in result.stdout.splitlines():
key, separator, value = line.partition("=")
if separator and key in {
"DISPLAY",
"WAYLAND_DISPLAY",
"XDG_RUNTIME_DIR",
"DBUS_SESSION_BUS_ADDRESS",
"XAUTHORITY",
}:
env[key] = value
with (folder / "launcher.log").open("ab") as output:
subprocess.Popen(
[
"/usr/bin/gnome-terminal",
"--wait",
"--title=Mission Core · Диагностика X4",
"--",
str(script),
],
env=env,
stdout=output,
stderr=output,
start_new_session=True,
)
print(json.dumps({"directory": str(folder), "sha256": hashlib.sha256(raw).hexdigest()}))
if __name__ == "__main__":
if sys.argv[1:] == ["--read"]:
report()
elif sys.argv[1:] == ["--launch"]:
launch()
else:
sys.exit("Use --launch or --read")
@@ -0,0 +1,33 @@
"""Build-only pinned toolchains; never an operator installation prerequisite."""
import hashlib
import json
import os
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def main():
lock = json.loads((ROOT / "packaging/linux-toolchains.json").read_text())
output = ROOT / "build/linux-toolchains"
output.mkdir(parents=True, mode=0o700, exist_ok=True)
os.umask(0o077)
for item in lock["files"]:
target = output / item["name"]
if not target.exists():
with urllib.request.urlopen(item["url"], timeout=60) as response:
data = response.read(100 * 1024 * 1024 + 1)
if len(data) > 100 * 1024 * 1024 or hashlib.sha256(data).hexdigest() != item["sha256"]:
raise ValueError("Official toolchain differs from the pinned release")
with target.open("xb") as stream:
stream.write(data)
data = target.read_bytes()
if hashlib.sha256(data).hexdigest() != item["sha256"]:
raise ValueError("Cached toolchain hash mismatch")
print(json.dumps({"file": target.name, "bytes": len(data), "sha256": item["sha256"]}))
if __name__ == "__main__":
main()
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""Stage verified Timescale OSS Ubuntu packages, without APT/system mutation."""
import argparse
import gzip
import hashlib
import json
import subprocess
import urllib.request
from pathlib import Path
BASE = "https://packagecloud.io/timescale/timescaledb/ubuntu/"
VERSION = "2.29.2"
def fetch(url, limit):
with urllib.request.urlopen(url, timeout=30) as response:
data = response.read(limit + 1)
if len(data) > limit:
raise ValueError("Download budget exceeded")
return data
def main():
parser = argparse.ArgumentParser()
parser.add_argument("destination", type=Path)
args = parser.parse_args()
root = args.destination
root.mkdir(parents=True, exist_ok=True)
key = root / "timescale.asc"
key.write_bytes(fetch("https://packagecloud.io/timescale/timescaledb/gpgkey", 65536))
keyring = root / "timescale.gpg"
subprocess.run(
["gpg", "--batch", "--yes", "--dearmor", "--output", str(keyring), str(key)], check=True
)
release = root / "InRelease"
release.write_bytes(fetch(BASE + "dists/noble/InRelease", 1048576))
subprocess.run(["gpgv", "--keyring", str(keyring.resolve()), str(release)], check=True)
lines = release.read_text().splitlines()
hashes = {}
inside = False
for line in lines:
if line == "SHA256:":
inside = True
continue
if inside and not line.startswith(" "):
break
if inside:
sha, size, path = line.split()
hashes[path] = (sha, int(size))
sha, size = hashes["main/binary-amd64/Packages.gz"]
compressed = fetch(BASE + "dists/noble/main/binary-amd64/Packages.gz", 16000000)
if len(compressed) != size or hashlib.sha256(compressed).hexdigest() != sha:
raise ValueError("Signed package index mismatch")
(root / "Packages.gz").write_bytes(compressed)
wanted = {
name: VERSION + "~ubuntu24.04-1615"
for name in ("timescaledb-2-oss-postgresql-16", "timescaledb-2-loader-postgresql-16")
}
artifacts = []
for block in gzip.decompress(compressed).decode().split("\n\n"):
fields = dict(
line.split(": ", 1)
for line in block.splitlines()
if ": " in line and not line.startswith(" ")
)
if (
fields.get("Package") not in wanted
or fields.get("Version") != wanted[fields["Package"]]
):
continue
path = fields["Filename"]
if not path.startswith("pool/") or ".." in path.split("/"):
raise ValueError("Invalid package path")
data = fetch(BASE + path, 64000000)
if hashlib.sha256(data).hexdigest() != fields["SHA256"]:
raise ValueError("Package hash mismatch")
target = root / Path(path).name
target.write_bytes(data)
artifacts.append(
dict(
package=fields["Package"],
version=fields["Version"],
file=target.name,
sha256=fields["SHA256"],
bytes=len(data),
depends=fields["Depends"],
)
)
if len(artifacts) != len(wanted):
raise ValueError("Pinned package not found")
manifest = dict(
source=BASE,
version=VERSION,
key_sha256=hashlib.sha256(key.read_bytes()).hexdigest(),
inrelease_sha256=hashlib.sha256(release.read_bytes()).hexdigest(),
artifacts=artifacts,
)
(root / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
print(json.dumps(manifest, indent=2))
if __name__ == "__main__":
main()
@@ -0,0 +1,8 @@
{
"schema": "missioncore.node.bundled-model/v1",
"model_id": "insta360.x4",
"version": "0.1.3-3",
"revision": "b291418f2a404cbdafc57431",
"bytes": 58199970,
"sha256": "c10f9c1e7f8237d9df202bc29483d61f27280920d76611b1aa1c4f3a72332540"
}
@@ -0,0 +1,229 @@
"""Node-owned X4 bootstrap; the same fixed job serves local and paired Core UI.
This exists before the optional model package is installed. All package bytes
and hashes come from the Node release, never from a device or a client request.
"""
import fcntl
import hashlib
import json
import os
import platform
import re
import subprocess
import sys
import tempfile
import time
import uuid
from pathlib import Path
SHARE = Path("/usr/share/mission-core-node/profiles/insta360-x4")
STATE = Path("/var/lib/mission-core-node-profiles/insta360-x4")
PLUGIN_STATE = Path("/var/lib/mission-core-insta360")
UNIT = "mission-core-node-insta360-x4-prepare.service"
PACKAGE = "mission-core-insta360-x4"
def trusted(path, directory=False):
info = path.lstat()
if path.is_symlink() or info.st_uid != 0 or info.st_mode & 0o022:
raise RuntimeError("Небезопасный файл профиля камеры.")
if path.is_dir() != directory:
raise RuntimeError("Недопустимый файл профиля камеры.")
return path
def publish(value):
fd, name = tempfile.mkstemp(prefix=".preparation-", dir=STATE)
try:
with os.fdopen(fd, "w") as stream:
os.fchmod(stream.fileno(), 0o644)
json.dump(value, stream, ensure_ascii=False)
stream.flush()
os.fsync(stream.fileno())
target = STATE / "preparation.json"
if target.exists() or target.is_symlink():
trusted(target)
os.replace(name, target)
descriptor = os.open(STATE, os.O_RDONLY)
try:
os.fsync(descriptor)
finally:
os.close(descriptor)
finally:
if os.path.exists(name):
os.unlink(name)
def payload():
for path in (SHARE.parent, SHARE):
trusted(path, True)
value = json.loads(trusted(SHARE / "profile.json").read_text())
if value.get("schema") != "missioncore.node.bundled-model/v1":
raise RuntimeError("Неизвестный профиль камеры.")
version = value["version"]
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:-[1-9][0-9]*)?", version):
raise RuntimeError("Некорректная версия профиля камеры.")
if not re.fullmatch(r"[0-9a-f]{24}", value["revision"]):
raise RuntimeError("Некорректная версия драйвера.")
path = trusted(SHARE / (PACKAGE + "_" + version + "_amd64.deb"))
data = path.read_bytes()
if len(data) != value["bytes"] or hashlib.sha256(data).hexdigest() != value["sha256"]:
raise RuntimeError("Встроенный пакет камеры повреждён. Переустановите Mission Core Node.")
return value, path
def prepare():
for path in (STATE.parent, STATE):
path.mkdir(mode=0o755, exist_ok=True)
trusted(path, True)
fd = os.open(STATE / "prepare.lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, "r+b") as lock:
trusted(STATE / "prepare.lock")
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
return prepare_locked()
def prepare_locked():
report = {
"schema": "missioncore.node.device-preparation/v1",
"model_id": "insta360.x4",
"run_id": uuid.uuid4().hex,
"started_at": time.time(),
"monotonic_started": time.monotonic(),
"state": "running",
"steps": [
{"id": key, "label": label, "state": "pending"}
for key, label in (
("platform", "Проверка совместимости системы"),
("payload", "Проверка встроенного пакета камеры"),
("package", "Установка драйвера камеры"),
("prepare", "Подготовка камеры"),
)
],
}
env = {
"PATH": "/usr/sbin:/usr/bin:/sbin:/bin",
"LANG": "C.UTF-8",
"DEBIAN_FRONTEND": "noninteractive",
}
evidence = STATE / report["run_id"]
evidence.mkdir(mode=0o700)
trusted(evidence, True)
sequence = 0
def run(command, timeout=60):
nonlocal sequence
sequence += 1
result = subprocess.run(command, capture_output=True, env=env, timeout=timeout)
for suffix, data in (("stdout", result.stdout), ("stderr", result.stderr)):
path = evidence / (str(sequence) + "." + suffix)
with path.open("xb") as stream:
os.fchmod(stream.fileno(), 0o600)
stream.write(data)
if result.returncode:
raise RuntimeError(
"Этап установки камеры не завершён. Повторите подготовку устройства."
)
return result.stdout.decode().strip()
publish(report)
try:
for step in report["steps"]:
step["state"] = "running"
publish(report)
if step["id"] == "platform":
release = platform.freedesktop_os_release()
if (release.get("ID"), release.get("VERSION_ID"), platform.machine()) != (
"ubuntu",
"24.04",
"x86_64",
):
raise RuntimeError("Этот профиль поддерживает Ubuntu 24.04 amd64.")
elif step["id"] == "payload":
bundle, path = payload()
report.update(revision=bundle["revision"], package_sha256=bundle["sha256"])
elif step["id"] == "package":
result = subprocess.run(
["/usr/bin/dpkg-query", "-W", "-f", "${Version}\t${Status}", PACKAGE],
env=env,
capture_output=True,
text=True,
timeout=10,
)
previous = result.stdout.strip().split("\t") if result.returncode == 0 else []
if (
previous
and subprocess.run(
[
"/usr/bin/dpkg",
"--compare-versions",
previous[0],
"gt",
bundle["version"],
],
env=env,
capture_output=True,
timeout=10,
).returncode
== 0
):
raise RuntimeError(
"Установлен более новый драйвер X4. Обновите Mission Core Node."
)
if previous != [bundle["version"], "install ok installed"]:
# Node already declares every OS dependency. Install only
# the hash-verified local archive: APT --no-download drops
# its local-file acquisition path on Ubuntu 24.04. dpkg
# retains dependency and package-lock checks, without a
# network acquisition or changes to unrelated packages.
# Model preinst/prerm retain recording/preview safety.
run(
[
"/usr/bin/dpkg",
"--install",
str(path),
],
timeout=None,
)
elif step["id"] == "prepare":
current = PLUGIN_STATE / "preparation.json"
# Package postinst prepares an existing installation during an
# upgrade. Avoid a second preparation while its SDK connects.
value = json.loads(trusted(current).read_text()) if current.exists() else {}
same_upgrade = (
previous != [bundle["version"], "install ok installed"]
and value.get("started_at", 0) >= report["started_at"]
and value.get("state") == "complete"
and value.get("revision") == bundle["revision"]
)
if not same_upgrade:
run(["/usr/bin/systemctl", "start", UNIT], timeout=200)
value = json.loads(trusted(current).read_text())
if value.get("state") != "complete" or value.get("revision") != bundle["revision"]:
raise RuntimeError("Подготовка драйвера камеры не подтверждена.")
step["state"] = "complete"
publish(report)
report["state"] = "complete"
except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError) as error:
report["state"] = "error"
report["message"] = (
str(error)[:300]
if isinstance(error, RuntimeError)
else "Не удалось подготовить камеру."
)
for step in report["steps"]:
if step["state"] == "running":
step.update(state="error", message=report["message"])
elif step["state"] == "pending":
step["state"] = "blocked"
report["duration_seconds"] = time.monotonic() - report["monotonic_started"]
publish(report)
return report["state"] == "complete"
if __name__ == "__main__":
if os.geteuid() or sys.argv[1:]:
sys.exit(1)
os.umask(0o022)
sys.exit(0 if prepare() else 1)
@@ -0,0 +1,72 @@
#!/bin/sh
# Run by the owner-facing release installer after hash verification. Scope is
# this product's packages and its dedicated cluster; never remove another DB.
set -eu
test "$(id -u)" = 0
mc_release_dir=$1
cd "$mc_release_dir"
sha256sum --check SHA256SUMS
mc_pg_guard=/etc/postgresql-common/createcluster.d/60-mission-core-install.conf
mc_created_guard=0
cleanup() {
if [ "$mc_created_guard" = 1 ]; then
if [ "$(cat "$mc_pg_guard")" = 'create_main_cluster = false' ]; then
rm "$mc_pg_guard"
fi
fi
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' HUP TERM
if ! dpkg-query -W -f='${Status}' postgresql-16 2>/dev/null | grep -qx 'install ok installed'; then
# postgresql-common explicitly supports this drop-in. Suppress only automatic
# creation of the unrelated default main cluster during the first install.
test ! -e "$mc_pg_guard"
install -d -m 0755 /etc/postgresql-common/createcluster.d
printf '%s\n' 'create_main_cluster = false' > "$mc_pg_guard"
chmod 0644 "$mc_pg_guard"
mc_created_guard=1
fi
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-remove \
"$mc_release_dir/timescaledb-2-loader-postgresql-16_2.29.2~ubuntu24.04-1615_amd64.deb" \
"$mc_release_dir/timescaledb-2-oss-postgresql-16_2.29.2~ubuntu24.04-1615_amd64.deb" \
"$mc_release_dir/mission-core-node_0.8.16_amd64.deb" \
"$mc_release_dir/mission-core-xgrids-k1_0.1.14_amd64.deb"
systemctl is-active --quiet mission-core-node.service
systemctl is-active --quiet mission-core-k1.service
runuser -u mission-core-node -- /usr/bin/python3 - <<'K1CHECK'
import http.client,json,socket,time
deadline=time.monotonic()+20
while True:
c=http.client.HTTPConnection('k1',timeout=3)
c.sock=socket.socket(socket.AF_UNIX);c.sock.settimeout(3)
try:
c.sock.connect('/run/mission-core-k1/driver.sock')
c.request('GET','/status');r=c.getresponse();v=json.load(r)
if r.status==200 and v.get('available') is True:break
except (OSError, ValueError, http.client.HTTPException):pass
finally:c.close()
if time.monotonic()>deadline:raise SystemExit('K1 enrollment service did not become ready')
time.sleep(1)
print('K1 enrollment service: ready')
K1CHECK
systemctl is-active --quiet postgresql@16-ndcmonitor.service
systemctl is-active --quiet mission-core-node-monitor.service
runuser -u mission-core-monitor -- /usr/bin/python3 - <<'PY'
import http.client,json,socket,time
deadline=time.monotonic()+20
while True:
c=http.client.HTTPConnection('monitor',timeout=3)
c.sock=socket.socket(socket.AF_UNIX);c.sock.settimeout(3)
try:
c.sock.connect('/run/mission-core-monitor/monitor.sock')
c.request('GET','/status');r=c.getresponse();v=json.load(r)
if r.status==200 and v['storage']=='ready' and v['latest']['seq']>0:break
except (OSError, ValueError, KeyError, TypeError, http.client.HTTPException):
pass
finally:c.close()
if time.monotonic()>deadline:raise SystemExit('Local telemetry did not become ready')
time.sleep(1)
print('Local telemetry: ready')
PY
printf '%s\n' 'Mission Core Node R19: package and local archive checks passed.'
@@ -0,0 +1,14 @@
#!/bin/bash
set -euo pipefail
umask 077
mc_node_release_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
if [ ! -t 0 ]; then
exec /usr/bin/gnome-terminal --wait --title="Mission Core Node" -- "$mc_node_release_dir/install"
fi
printf '%s\n' 'Mission Core Node' 'Обновление приложения и встроенных пакетов камер на этом Ubuntu-компьютере.' 'Подготовка X4 выполняется затем из списка устройств в Node или Core.' 'Пароль администратора вводится только в этом локальном окне Ubuntu.'
set +e
/usr/bin/sudo /usr/bin/python3 -I "$mc_node_release_dir/install_release.py" 2>&1 | /usr/bin/tee -a "$mc_node_release_dir/install-output.log"
mc_node_install_result=${PIPESTATUS[0]}
printf '\nКод завершения: %s\nНажмите Enter, чтобы закрыть окно.\n' "$mc_node_install_result"
read -r mc_node_close
exit "$mc_node_install_result"
@@ -0,0 +1,296 @@
"""Fixed Node release installation, authenticated only in the owner's Ubuntu TTY."""
import hashlib
import http.client
import json
import os
import platform
import pwd
import re
import signal
import subprocess
import sys
import time
import uuid
from datetime import UTC, datetime
from pathlib import Path
ROOT = Path("/var/tmp/mission-core-node-installs")
SERVICES = (
"mission-core-node.service",
"mission-core-k1.service",
"mission-core-realsense.service",
)
def private(path):
path.mkdir(mode=0o700, exist_ok=True)
info = path.lstat()
if path.is_symlink() or not path.is_dir() or info.st_uid != 0 or info.st_mode & 0o077:
raise ValueError("Installer evidence directory is not private and root-owned")
def finish_legacy_monitor_pager():
"""Close only the known 0.8.17 postinst pager; never signal apt/dpkg/SQL."""
query = ["/usr/bin/dpkg-query", "-W", "-f", "${Version} ${Status}", "mission-core-node"]
state = subprocess.run(query, capture_output=True, text=True, timeout=5).stdout.strip()
if state != "0.8.17 install ok half-configured":
return {"required": False}
monitor_uid = pwd.getpwnam("mission-core-monitor").pw_uid
processes = {}
for path in Path("/proc").glob("[0-9]*"):
try:
fields = (path / "stat").read_text().split(") ", 1)[1].split()
args = (path / "cmdline").read_bytes().rstrip(b"\0").decode().split("\0")
processes[int(path.name)] = {
"parent": int(fields[1]),
"start": fields[19],
"args": args,
"uid": path.stat().st_uid,
}
except (OSError, ValueError, IndexError, UnicodeError):
continue
def parent(row):
return processes.get(row.get("parent"), {})
selected = []
for pid, row in processes.items():
if row["args"] != ["pager"] or row["uid"] != monitor_uid:
continue
shell = parent(row)
sql, user = parent(shell), parent(parent(shell))
setup, post = parent(user), parent(parent(user))
dpkg, apt = parent(post), parent(parent(post))
if (
shell.get("args") != ["sh", "-c", "--", "pager"]
or sql.get("args")
!= [
"/usr/lib/postgresql/16/bin/psql",
"-X",
"-v",
"ON_ERROR_STOP=1",
"-h",
"/run/mission-core-monitor-db",
"-p",
"5433",
"-d",
"mission_core_monitor",
"-f",
"/usr/lib/mission-core-node/monitor/schema.sql",
]
or setup.get("args") != ["/bin/sh", "/usr/lib/mission-core-node/setup-monitor"]
or post.get("args", [])[:3]
!= ["/bin/sh", "/var/lib/dpkg/info/mission-core-node.postinst", "configure"]
or dpkg.get("args", [""])[0] != "/usr/bin/dpkg"
or apt.get("args", [])[:4] != ["/usr/bin/apt-get", "install", "-y", "--no-remove"]
or len(apt["args"]) != 5
or not re.fullmatch(
r"/var/tmp/mission-core-node-installs/[0-9a-f]{32}/"
r"mission-core-node_0\.8\.17_amd64\.deb",
apt["args"][4],
)
):
continue
old_package = Path(apt["args"][4])
if hashlib.sha256(old_package.read_bytes()).hexdigest() != (
"f929c440e4965f728aa6cd00eb122e7cad09e5ade82da763cc36661f50ec66b5"
):
continue
selected.append((pid, row["start"]))
if len(selected) != 1:
raise RuntimeError("Не подтверждён известный просмотрщик старого установщика.")
pid, started = selected[0]
descriptor = os.pidfd_open(pid)
try:
current = (Path("/proc") / str(pid) / "stat").read_text().split(") ", 1)[1].split()
if current[19] != started:
raise RuntimeError("Процесс просмотрщика изменился.")
print(
"Закрываем зависший просмотрщик старого установщика; APT продолжает работу.", flush=True
)
signal.pidfd_send_signal(descriptor, signal.SIGTERM)
finally:
os.close(descriptor)
deadline = time.monotonic() + 45
while time.monotonic() < deadline:
state = subprocess.run(query, capture_output=True, text=True, timeout=5).stdout.strip()
if state == "0.8.17 install ok installed":
return {"required": True, "pager_pid": pid, "old_package_configured": True}
time.sleep(1)
raise RuntimeError("Старая транзакция ещё не завершилась; она не прерывалась.")
def main():
if os.geteuid() or sys.argv[1:]:
raise ValueError("Use the release's local Ubuntu installer")
release = platform.freedesktop_os_release()
if (release.get("ID"), release.get("VERSION_ID"), platform.machine()) != (
"ubuntu",
"24.04",
"x86_64",
):
raise ValueError("This package requires Ubuntu 24.04 amd64")
os.umask(0o077)
source = Path(__file__).resolve().parent
raw = (source / "release.json").read_bytes()
manifest = json.loads(raw)
version = manifest["version"]
if (
manifest.get("schema") != "missioncore.node.owner-release/v1"
or manifest.get("qualification_profile") != "node-package-and-local-ui"
or not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:-[1-9][0-9]*)?", version)
):
raise ValueError("Unknown Node release")
package = "mission-core-node_" + version + "_amd64.deb"
if set(manifest["files"]) != {package, "install", "install_release.py"}:
raise ValueError("Unexpected installer contents")
contents = {}
for name, expected in manifest["files"].items():
data = (source / name).read_bytes()
if len(data) != expected["bytes"] or hashlib.sha256(data).hexdigest() != expected["sha256"]:
raise ValueError("Installer payload changed")
contents[name] = data
private(ROOT)
folder = ROOT / uuid.uuid4().hex
private(folder)
(folder / package).write_bytes(contents[package])
report = {
"schema": "missioncore.node.install-run/v1",
"session_id": folder.name,
"release_sha256": hashlib.sha256(raw).hexdigest(),
"package_sha256": manifest["files"][package]["sha256"],
"started_at": datetime.now(UTC).isoformat(),
"monotonic_started": time.monotonic(),
"state": "running",
"scope": "Node-package-and-UI-only; X4-prepare-remains-in-application",
"steps": [],
}
env = {
"PATH": "/usr/sbin:/usr/bin:/sbin:/bin",
"LANG": "C.UTF-8",
"DEBIAN_FRONTEND": "noninteractive",
"PAGER": "/bin/cat",
"PSQL_PAGER": "/bin/cat",
}
def publish():
(folder / "report.json").write_text(json.dumps(report, indent=2) + "\n")
def run(name, command, timeout=60):
print("Установка Node: " + name, flush=True)
item = {"id": name, "state": "running", "started_at": datetime.now(UTC).isoformat()}
report["steps"].append(item)
publish()
result = subprocess.run(command, env=env, capture_output=True, timeout=timeout)
for suffix, data in (("stdout", result.stdout), ("stderr", result.stderr)):
(folder / (name + "." + suffix)).write_bytes(data)
item.update(
state="complete" if result.returncode == 0 else "error", exit_code=result.returncode
)
publish()
if result.returncode:
raise RuntimeError("Не завершён этап установки: " + name)
return result.stdout.decode().strip()
publish()
try:
report["legacy_pager_recovery"] = finish_legacy_monitor_pager()
publish()
report["services_before"] = run(
"baseline",
[
"/usr/bin/systemctl",
"show",
*SERVICES,
"-p",
"Id",
"-p",
"ActiveState",
"-p",
"NRestarts",
],
)
# APT refuses package removal and downgrade without explicit flags.
# Its transaction is never killed by an observer timeout.
run(
"apt-plan",
["/usr/bin/apt-get", "--simulate", "--no-remove", "install", str(folder / package)],
)
run(
"package",
[
"/usr/bin/apt-get",
"-o",
"Dpkg::Use-Pty=0",
"-o",
"DPkg::Lock::Timeout=45",
"install",
"-y",
"--no-remove",
str(folder / package),
],
timeout=None,
)
installed = run(
"installed",
["/usr/bin/dpkg-query", "-W", "-f", "${Version}\t${Status}", "mission-core-node"],
)
if installed != version + "\tinstall ok installed":
raise RuntimeError("Версия установленного Node не подтверждена.")
run(
"node-service",
["/usr/bin/systemctl", "is-active", "--quiet", "mission-core-node.service"],
)
deadline = time.monotonic() + 30
while True:
client = http.client.HTTPConnection("127.0.0.1", 8780, timeout=2)
try:
client.request("GET", "/")
response = client.getresponse()
body = response.read(262145)
if response.status == 200 and len(body) <= 262144 and b"<html" in body.lower():
report["ui_ready"] = True
break
except (OSError, http.client.HTTPException):
pass
finally:
client.close()
if time.monotonic() >= deadline:
raise RuntimeError("Пакет установлен, но локальный интерфейс Node не ответил.")
time.sleep(1)
report["services_after"] = run(
"services-after",
[
"/usr/bin/systemctl",
"show",
*SERVICES,
"-p",
"Id",
"-p",
"ActiveState",
"-p",
"NRestarts",
],
)
report["state"] = "complete"
except Exception as error:
report.update(state="error", error=str(error)[:500])
finally:
report.update(
finished_at=datetime.now(UTC).isoformat(),
duration_seconds=time.monotonic() - report["monotonic_started"],
)
publish()
(folder / package).unlink(missing_ok=True)
print("MISSION_CORE_NODE_RESULT " + json.dumps(report, ensure_ascii=False), flush=True)
if report["state"] != "complete":
raise RuntimeError(report["error"])
print(
"Mission Core Node обновлён. X4 можно подготовить из списка устройств в Node или Core.",
flush=True,
)
if __name__ == "__main__":
main()
+6 -1
View File
@@ -9,6 +9,7 @@ import re
import socket import socket
import subprocess import subprocess
import threading import threading
import syslog
from urllib.parse import urlsplit from urllib.parse import urlsplit
import gi import gi
@@ -261,11 +262,15 @@ class NodeApplication(Gtk.Application):
return False return False
def load_failed(self, _view, _event, uri, _error): def load_failed(self, _view, _event, uri, _error):
syslog.openlog('mission-core-node-ui')
syslog.syslog(syslog.LOG_ERR, 'node-ui-load-failed')
if local_url(uri): if local_url(uri):
self.problem("Служба ноды недоступна. Повторно откройте приложение после восстановления службы.") self.problem("Служба ноды недоступна. Повторно откройте приложение после восстановления службы.")
return True return True
def process_failed(self, *_): def process_failed(self, _view, reason):
syslog.openlog('mission-core-node-ui')
syslog.syslog(syslog.LOG_ERR, 'node-ui-process-terminated reason=' + str(int(reason)))
self.problem("Окно приложения остановилось. Закройте и повторно откройте Mission Core Node. Служба борта продолжает работать отдельно.") self.problem("Окно приложения остановилось. Закройте и повторно откройте Mission Core Node. Служба борта продолжает работать отдельно.")
def deny_permission(self, _view, permission): def deny_permission(self, _view, permission):
@@ -0,0 +1,18 @@
{
"schema": "missioncore.node.build-toolchains/v1",
"platform": "linux-amd64",
"files": [
{
"name": "go1.26.8.linux-amd64.tar.gz",
"url": "https://go.dev/dl/go1.26.8.linux-amd64.tar.gz",
"sha256": "d0f743b33e8d8945e6b1f432edd15785c70507121d6e2a723b21285eddf8b57b",
"directory": "go"
},
{
"name": "node-v24.9.0-linux-x64.tar.xz",
"url": "https://nodejs.org/dist/v24.9.0/node-v24.9.0-linux-x64.tar.xz",
"sha256": "f52ec50e959d72d5c680d9731420b2661cd2a8070e94c7369b6ddfcd8b7278be",
"directory": "node-v24.9.0-linux-x64"
}
]
}
@@ -0,0 +1,186 @@
"""Unprivileged self-verifying build, bounded by a transient user cgroup."""
import fcntl
import hashlib
import json
import os
import platform
import shutil
import subprocess
import sys
import time
import zipfile
from datetime import UTC, datetime
from pathlib import Path, PurePosixPath
ROOT = Path("/var/tmp/mission-core-node-builds")
def digest(data):
return hashlib.sha256(data).hexdigest()
def private(path):
path.mkdir(mode=0o700, exist_ok=True)
info = path.lstat()
if (
path.is_symlink()
or not path.is_dir()
or info.st_uid != os.geteuid()
or info.st_mode & 0o077
):
raise RuntimeError("Build staging is not private and owned")
def main():
if os.geteuid() == 0 or (platform.system(), platform.machine()) != ("Linux", "x86_64"):
raise RuntimeError("Use the unprivileged Ubuntu build account")
if sys.argv[1:] not in ([], ["--clean"]):
raise ValueError("No arbitrary build commands or paths are accepted")
os.umask(0o077)
started, monotonic = datetime.now(UTC).isoformat(), time.monotonic()
artifact = Path(sys.argv[0]).resolve()
with zipfile.ZipFile(artifact) as archive:
raw = archive.read("source.json")
manifest = json.loads(raw)
if manifest["schema"] != "missioncore.node.linux-build-source/v1":
raise ValueError("Unsupported source artifact")
if digest(archive.read("__main__.py")) != manifest["entrypoint_sha256"]:
raise ValueError("Build entry point changed")
identifier = digest(raw)[:24]
private(ROOT)
folder = ROOT / identifier
private(folder)
with (folder / "build.lock").open("a") as handle:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
if sys.argv[1:]:
shutil.rmtree(folder)
print(json.dumps({"cleaned": identifier}))
return
if (folder / "result.tar.gz").exists():
print(
json.dumps(
{
"result": str(folder / "result.tar.gz"),
"sha256": digest((folder / "result.tar.gz").read_bytes()),
"reused": True,
}
)
)
return
if (folder / "source").exists():
raise RuntimeError("Preserve prior failure evidence and use --clean before retry")
if shutil.disk_usage(folder).free < 6 * 1024**3:
raise RuntimeError("Build requires 6 GiB free temporary disk space")
admitted = {"source.json", "__main__.py"} | {
"source/" + name for name in manifest["files"]
}
if set(archive.namelist()) != admitted or len(archive.namelist()) != len(admitted):
raise ValueError("Unexpected source contents")
for name, expected in manifest["files"].items():
path = PurePosixPath(name)
if (
path.is_absolute()
or ".." in path.parts
or path.as_posix() != name
or "\\" in name
):
raise ValueError("Unsafe source path")
entry = archive.getinfo("source/" + name)
if entry.file_size != expected["bytes"] or entry.file_size > 100 * 1024**2:
raise ValueError("Invalid source size")
data = archive.read(entry)
if digest(data) != expected["sha256"] or expected["mode"] not in (0o644, 0o755):
raise ValueError("Invalid source bytes or mode")
target = folder / "source" / name
target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
target.write_bytes(data)
target.chmod(expected["mode"])
(folder / "source.json").write_bytes(raw)
report = {
"schema": "missioncore.node.linux-build-run/v1",
"id": identifier,
"started_at": started,
"monotonic_started": monotonic,
"state": "running",
"artifact_sha256": digest(artifact.read_bytes()),
"scope": "Node-Core-build-and-synthetic-tests",
"resource_limits": {
"memory_bytes": 3 * 1024**3,
"cpu_percent": 150,
"tasks": 256,
"seconds": 1200,
},
}
(folder / "report.json").write_text(json.dumps(report, indent=2) + "\n")
job = (
folder
/ "source"
/ manifest["repository"]
/ "apps/node-agent/packaging/linux_build_job.py"
)
try:
result = subprocess.run(
[
"/usr/bin/systemd-run",
"--user",
"--quiet",
"--collect",
"--wait",
"--pipe",
"--unit=mission-core-node-build-" + identifier,
"--property=MemoryMax=3G",
"--property=CPUQuota=150%",
"--property=TasksMax=256",
"--property=RuntimeMaxSec=1200",
"--property=TimeoutStopSec=10",
"--property=KillMode=control-group",
"--property=Nice=10",
"/usr/bin/python3",
"-I",
str(job),
str(folder),
],
capture_output=True,
)
(folder / "job.stdout").write_bytes(result.stdout)
(folder / "job.stderr").write_bytes(result.stderr)
if result.returncode:
raise RuntimeError("Node/Core build failed; inspect the private attempt report")
report.update(
state="complete",
finished_at=datetime.now(UTC).isoformat(),
duration_seconds=time.monotonic() - monotonic,
)
(folder / "report.json").write_text(json.dumps(report, indent=2) + "\n")
# The job creates the artifact list; these fixed files only
# are collected after its cgroup has exited successfully.
import tarfile
with tarfile.open(folder / "result.tar.gz", "w:gz") as result_archive:
for path in sorted((folder / "output").iterdir()):
if not path.is_file() or path.is_symlink():
raise ValueError("Unexpected build result")
result_archive.add(path, arcname=path.name, recursive=False)
result_archive.add(folder / "report.json", arcname="build-report.json")
print(
json.dumps(
{
"result": str(folder / "result.tar.gz"),
"state": "complete",
"sha256": digest((folder / "result.tar.gz").read_bytes()),
}
)
)
except Exception:
report.update(
state="error",
finished_at=datetime.now(UTC).isoformat(),
duration_seconds=time.monotonic() - monotonic,
)
(folder / "report.json").write_text(json.dumps(report, indent=2) + "\n")
raise
if __name__ == "__main__":
main()
@@ -0,0 +1,359 @@
"""Fixed sequential Node/Core build inside the source artifact's user cgroup."""
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tarfile
import time
from datetime import UTC, datetime
from pathlib import Path, PurePosixPath
def main():
if os.geteuid() == 0 or len(sys.argv) != 2:
raise ValueError("Use the versioned unprivileged build entry point")
folder = Path(sys.argv[1])
if folder.parent != Path("/var/tmp/mission-core-node-builds") or not re.fullmatch(
r"[0-9a-f]{24}", folder.name
):
raise ValueError("Unknown build staging")
manifest = json.loads((folder / "source.json").read_text())
if manifest.get("profile", "node-core") not in ("node-core", "node-only"):
raise ValueError("Unknown build profile")
source = folder / "source"
repo, dg = source / manifest["repository"], source / "NODEDC_DESIGN_GUIDELINE"
node = repo / "apps/node-agent"
if Path(__file__).resolve() != node / "packaging/linux_build_job.py":
raise ValueError("Build source path changed")
cgroup = next(
line.split(":", 2)[2]
for line in Path("/proc/self/cgroup").read_text().splitlines()
if line.startswith("0::")
)
control = Path("/sys/fs/cgroup") / cgroup.lstrip("/")
memory = (control / "memory.max").read_text().strip()
cpu, period = (control / "cpu.max").read_text().split()
tasks = (control / "pids.max").read_text().strip()
if (
memory == "max"
or int(memory) > 3 * 1024**3
or cpu == "max"
or int(cpu) / int(period) > 1.5
or tasks == "max"
or int(tasks) > 256
):
raise RuntimeError("Build resource limits are not enforced")
tools = folder / "toolchains"
tools.mkdir(mode=0o700)
for entry in manifest["toolchains"]["files"]:
path = node / "build/linux-toolchains" / entry["name"]
if hashlib.sha256(path.read_bytes()).hexdigest() != entry["sha256"]:
raise ValueError("Toolchain changed before extraction")
with tarfile.open(path) as archive:
members = archive.getmembers()
if len(members) > 40000 or sum(item.size for item in members) > 1024**3:
raise ValueError("Toolchain exceeds extraction budget")
for item in members:
name = PurePosixPath(item.name)
if (
name.is_absolute()
or ".." in name.parts
or not name.parts
or name.parts[0] != entry["directory"]
):
raise ValueError("Unexpected toolchain contents")
# Python's data filter also rejects links escaping the owned tree,
# devices, FIFOs and privilege-bearing modes in upstream archives.
archive.extractall(tools, members=members, filter="data")
go = tools / "go/bin/go"
nodejs = tools / "node-v24.9.0-linux-x64/bin/node"
npm = tools / "node-v24.9.0-linux-x64/lib/node_modules/npm/bin/npm-cli.js"
output = folder / "output"
output.mkdir(mode=0o700)
temporary = folder / "temporary"
temporary.mkdir(mode=0o700)
env = {
"PATH": str(nodejs.parent) + ":" + str(go.parent) + ":/usr/bin:/bin",
"LANG": "C.UTF-8",
"PYTHONDONTWRITEBYTECODE": "1",
"TMPDIR": str(temporary),
"GOTOOLCHAIN": "local",
"GOMAXPROCS": "2",
"GOMEMLIMIT": "768MiB",
"GOCACHE": str(folder / "go-cache"),
"GOPATH": str(folder / "go-path"),
"GOMODCACHE": str(folder / "go-mod"),
"npm_config_cache": str(folder / "npm-cache"),
"npm_config_audit": "false",
"npm_config_fund": "false",
"npm_config_update_notifier": "false",
"NODE_OPTIONS": "--max-old-space-size=1024",
}
report = {
"schema": "missioncore.node.linux-build-jobs/v1",
"started_at": datetime.now(UTC).isoformat(),
"monotonic_started": time.monotonic(),
"state": "running",
"jobs": [],
"limits_observed": {"memory.max": memory, "cpu.max": [cpu, period], "pids.max": tasks},
}
def publish():
(output / "qualification.json").write_text(json.dumps(report, indent=2) + "\n")
def run(name, command, cwd=repo, overrides=None, timeout=300):
started = time.monotonic()
item = {"id": name, "started_at": datetime.now(UTC).isoformat(), "state": "running"}
report["jobs"].append(item)
publish()
try:
result = subprocess.run(
command,
cwd=cwd,
env={**env, **(overrides or {})},
capture_output=True,
timeout=timeout,
)
except subprocess.TimeoutExpired as error:
(output / (name + ".stdout")).write_bytes(error.stdout or b"")
(output / (name + ".stderr")).write_bytes(error.stderr or b"")
item.update(
state="error", reason="timeout", duration_seconds=time.monotonic() - started
)
publish()
raise
(output / (name + ".stdout")).write_bytes(result.stdout)
(output / (name + ".stderr")).write_bytes(result.stderr)
item.update(
state="complete" if result.returncode == 0 else "error",
exit_code=result.returncode,
duration_seconds=time.monotonic() - started,
)
publish()
if result.returncode:
raise RuntimeError(name + " failed")
return result.stdout.decode().strip()
def app_dependencies(app, name):
lock = json.loads((app / "package-lock.json").read_text())
for value in lock["packages"].values():
resolved = value.get("resolved", "")
if "://" in resolved and not resolved.startswith("https://registry.npmjs.org/"):
raise ValueError("An npm dependency is outside the locked public registry")
command = [
str(nodejs),
str(npm),
"ci",
"--ignore-scripts",
"--no-audit",
"--no-fund",
"--prefer-offline",
"--maxsockets=4",
"--fetch-timeout=20000",
"--fetch-retries=1",
"--fetch-retry-mintimeout=1000",
"--fetch-retry-maxtimeout=2000",
]
for attempt in range(1, 4):
step = name + "-dependencies-" + str(attempt)
try:
run(step, command, cwd=app, timeout=45)
break
except subprocess.TimeoutExpired:
# npm can stall after a TLS download without surfacing its
# fetch timeout. Its killed process cannot overlap this retry.
if attempt == 3:
raise
time.sleep(1)
except RuntimeError:
error = (output / (step + ".stderr")).read_text()
if attempt == 3 or not any(
code in error for code in ("ETIMEDOUT", "ECONNRESET", "EAI_AGAIN")
):
raise
# Retry only a failed network fetch, retaining this attempt's
# integrity-checked cache and every failed command log.
time.sleep(1)
try:
if run("go-version", [str(go), "version"]).split()[2] != "go1.26.8":
raise ValueError("Unexpected Go toolchain")
if run("node-version", [str(nodejs), "--version"]) != "v24.9.0":
raise ValueError("Unexpected Node.js toolchain")
app_dependencies(dg, "design-guideline")
run("design-guideline-build", [str(nodejs), str(npm), "run", "build:packages"], cwd=dg)
run(
"design-guideline-typecheck",
[str(nodejs), str(npm), "run", "typecheck", "--workspaces", "--if-present"],
cwd=dg,
)
run(
"design-guideline-registry", [str(nodejs), str(npm), "run", "validate:registry"], cwd=dg
)
run(
"design-guideline-loading-tests",
[str(nodejs), str(npm), "run", "test:activity-indicator"],
cwd=dg,
)
run(
"design-guideline-catalog",
[str(nodejs), str(npm), "run", "build", "--workspace", "@nodedc/ui-catalog"],
cwd=dg,
overrides={"NODE_OPTIONS": "--max-old-space-size=2048"},
)
ui = node / "ui"
app_dependencies(ui, "node-ui")
run(
"node-ui-tests",
[
str(nodejs),
"--test",
"--test-concurrency=1",
*[str(path) for path in sorted((ui / "test").glob("*.test.mjs"))],
],
cwd=ui,
)
run("node-ui-build", [str(nodejs), str(npm), "run", "build"], cwd=ui)
assets = node / "web/dist"
if assets.exists():
shutil.rmtree(assets)
shutil.copytree(ui / "dist", assets)
# The real UI must exist before Go compiles web/assets.go's embed.
# Tests use private synthetic USB roots, never the Mini's inventory.
run(
"node-go-format-diff",
[
str(go.parent / "gofmt"),
"-d",
*[str(path) for path in sorted((node / "internal/node").glob("pairing*.go"))],
],
cwd=node,
)
run(
"node-go-tests",
[str(go), "test", "-race", "-p", "1", "./...", "-count=1"],
cwd=node,
overrides={"CGO_ENABLED": "1"},
timeout=480,
)
sys.path.insert(0, str(node / "packaging"))
from build_deb import BINARY_VERSION, VERSION, build
binary = node / "build/node-agent-linux-amd64"
run(
"node-binary",
[
str(go),
"build",
"-p",
"1",
"-trimpath",
"-ldflags=-s -w -X main.version=" + BINARY_VERSION,
"-o",
str(binary),
"./cmd/node-agent",
],
cwd=node,
overrides={"CGO_ENABLED": "0", "GOOS": "linux", "GOARCH": "amd64"},
)
provenance = {
"schema": "missioncore.node.source-provenance/v1",
"version": VERSION,
"base_commit": manifest["base_commit"],
"design_guideline_commit": manifest["design_guideline_commit"],
"source_manifest_sha256": hashlib.sha256(
(folder / "source.json").read_bytes()
).hexdigest(),
"toolchains": manifest["toolchains"],
"files": manifest["files"],
}
(node / "build/provenance.json").write_text(json.dumps(provenance, indent=2) + "\n")
package = output / ("mission-core-node_" + VERSION + "_amd64.deb")
build(binary, package)
if manifest.get("profile") == "node-only":
report.update(
state="complete",
profile="node-only",
finished_at=datetime.now(UTC).isoformat(),
duration_seconds=time.monotonic() - report["monotonic_started"],
memory_peak_bytes=int((control / "memory.peak").read_text()),
)
report["artifacts"] = {
package.name: {
"bytes": package.stat().st_size,
"sha256": hashlib.sha256(package.read_bytes()).hexdigest(),
}
}
publish()
return
core = repo / "apps/control-station"
app_dependencies(core, "core")
run(
"core-architecture",
[str(nodejs), "--test", "test/applicationArchitecture.test.mjs"],
cwd=core,
)
run("core-typecheck", [str(nodejs), str(npm), "run", "typecheck"], cwd=core)
# This existing K1 integration case generates RRD via a developer
# Python/Rerun environment. That environment is not a Node/X4 build
# dependency. Keep every other test; report this acceptance gap.
report["unqualified_tests"] = [
{
"name": "native RRD crosses many RTC fragments "
"and reaches decoder once, byte-for-byte",
"reason": "Python/Rerun fixture generator is outside the Node/X4 build inputs",
}
]
run(
"core-tests",
[
str(nodejs),
"--test",
"--test-concurrency=1",
"--test-skip-pattern=^native RRD crosses many RTC fragments "
"and reaches decoder once, byte-for-byte$",
*[str(path) for path in sorted((core / "test").glob("*.test.mjs"))],
],
cwd=core,
timeout=480,
)
run(
"core-build",
[str(nodejs), str(npm), "run", "build"],
cwd=core,
overrides={"NODE_OPTIONS": "--max-old-space-size=2048"},
)
with tarfile.open(output / "core-dist.tar.gz", "w:gz") as archive:
for path in sorted((core / "dist").rglob("*")):
if path.is_file():
archive.add(path, arcname=str(path.relative_to(core / "dist")), recursive=False)
report.update(
state="complete",
finished_at=datetime.now(UTC).isoformat(),
duration_seconds=time.monotonic() - report["monotonic_started"],
memory_peak_bytes=int((control / "memory.peak").read_text()),
)
report["artifacts"] = {
path.name: {
"bytes": path.stat().st_size,
"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
}
for path in (package, output / "core-dist.tar.gz")
}
publish()
except Exception:
report.update(
state="error",
finished_at=datetime.now(UTC).isoformat(),
duration_seconds=time.monotonic() - report["monotonic_started"],
)
publish()
raise
if __name__ == "__main__":
main()
@@ -0,0 +1,10 @@
[Unit]
Description=Mission Core fixed bundled Insta360 X4 profile
After=systemd-udevd.service
[Service]
Type=oneshot
ExecStart=/usr/bin/python3 -I /usr/lib/mission-core-node/insta360_profile.py
# Never kill dpkg in the middle of package configuration. The requesting Node
# operation has its own deadline; an expired observer cannot cancel this job.
TimeoutStartSec=infinity
UMask=0022
@@ -0,0 +1,38 @@
[Unit]
Description=Mission Core onboard system telemetry collector
After=postgresql@16-ndcmonitor.service
Wants=postgresql@16-ndcmonitor.service
[Service]
Type=simple
User=mission-core-monitor
Group=mission-core-node
SupplementaryGroups=systemd-journal
ExecStart=/usr/bin/python3 /usr/lib/mission-core-node/monitor/collector.py
RuntimeDirectory=mission-core-monitor
RuntimeDirectoryMode=0750
StateDirectory=mission-core-monitor
StateDirectoryMode=0750
UMask=0007
Restart=on-failure
RestartSec=5
MemoryHigh=96M
MemoryMax=128M
CPUQuota=15%
TasksMax=24
Nice=10
IOSchedulingClass=idle
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictAddressFamilies=AF_UNIX
CapabilityBoundingSet=
RestrictSUIDSGID=yes
[Install]
WantedBy=multi-user.target
+17
View File
@@ -15,6 +15,23 @@ case "$1" in
systemctl enable mission-core-node.service systemctl enable mission-core-node.service
systemctl restart mission-core-node.service systemctl restart mission-core-node.service
systemctl try-restart mission-core-realsense.service systemctl try-restart mission-core-realsense.service
if [ -f /run/mission-core-node-k1-upgrade-active ]; then
# A jointly upgraded plugin starts itself after its own configuration.
# Restore it here only when that package is already configured.
if [ "$(dpkg-query -W -f='${Status}' mission-core-xgrids-k1 2>/dev/null || true)" = "install ok installed" ]; then
systemctl start mission-core-k1.service
fi
rm -f /run/mission-core-node-k1-upgrade-active
fi
# A diagnostic service must not leave Node half-configured and prevent
# dpkg from configuring the separately packaged acquisition plugin.
if /usr/lib/mission-core-node/setup-monitor; then
rm -f /run/mission-core-monitor-setup-failed
else
mc_monitor_result=$?
printf '%s\n' "$mc_monitor_result" > /run/mission-core-monitor-setup-failed
echo "Mission Core Node: monitoring setup failed; device services remain independent." >&2
fi
fi fi
;; ;;
esac esac
+9 -1
View File
@@ -14,6 +14,10 @@ if [ "$1" = install ] || [ "$1" = upgrade ]; then
exit 1 exit 1
fi fi
fi fi
mc_node_x4_job=$(systemctl show --property=ActiveState --value mission-core-node-insta360-x4-profile.service 2>/dev/null || true)
case "$mc_node_x4_job" in
active|activating) echo "Mission Core Node: дождитесь завершения подготовки X4." >&2; exit 1 ;;
esac
mc_node_device_job=$(systemctl show --property=ActiveState --value mission-core-node-realsense-prepare.service 2>/dev/null || true) mc_node_device_job=$(systemctl show --property=ActiveState --value mission-core-node-realsense-prepare.service 2>/dev/null || true)
case "$mc_node_device_job" in case "$mc_node_device_job" in
active|activating) echo "Mission Core Node: дождитесь завершения подготовки устройства." >&2; exit 1 ;; active|activating) echo "Mission Core Node: дождитесь завершения подготовки устройства." >&2; exit 1 ;;
@@ -28,9 +32,13 @@ if [ "$1" = install ] || [ "$1" = upgrade ]; then
esac esac
# End the admitted idle worker before dpkg replaces its Python modules. # End the admitted idle worker before dpkg replaces its Python modules.
# New UI commands now fail unavailable instead of racing the package copy. # New UI commands now fail unavailable instead of racing the package copy.
if [ -f /usr/lib/systemd/system/mission-core-k1.service ]; then if systemctl is-active --quiet mission-core-k1.service; then
# Preserve an optional worker's prior running state across a Node-only
# update. /run is root-owned; the plugin still owns initial activation.
(umask 077; : > /run/mission-core-node-k1-upgrade-active)
systemctl stop mission-core-k1.service systemctl stop mission-core-k1.service
fi fi
systemctl stop mission-core-node-monitor.service 2>/dev/null || true
fi fi
. /etc/os-release . /etc/os-release
if [ "${ID:-}" != ubuntu ] || [ "${VERSION_ID:-}" != 24.04 ]; then if [ "${ID:-}" != ubuntu ] || [ "${VERSION_ID:-}" != 24.04 ]; then
+8
View File
@@ -13,6 +13,10 @@ if [ -d /run/systemd/system ]; then
exit 1 exit 1
fi fi
fi fi
mc_node_x4_job=$(systemctl show --property=ActiveState --value mission-core-node-insta360-x4-profile.service 2>/dev/null || true)
case "$mc_node_x4_job" in
active|activating) echo "Mission Core Node: дождитесь завершения подготовки X4." >&2; exit 1 ;;
esac
mc_node_device_job=$(systemctl show --property=ActiveState --value mission-core-node-realsense-prepare.service 2>/dev/null || true) mc_node_device_job=$(systemctl show --property=ActiveState --value mission-core-node-realsense-prepare.service 2>/dev/null || true)
case "$mc_node_device_job" in case "$mc_node_device_job" in
active|activating) echo "Mission Core Node: дождитесь завершения подготовки устройства." >&2; exit 1 ;; active|activating) echo "Mission Core Node: дождитесь завершения подготовки устройства." >&2; exit 1 ;;
@@ -52,6 +56,10 @@ case "$1" in
systemctl disable mission-core-realsense.service || true systemctl disable mission-core-realsense.service || true
systemctl stop mission-core-node.service systemctl stop mission-core-node.service
systemctl disable mission-core-node.service systemctl disable mission-core-node.service
systemctl stop mission-core-node-monitor.service
systemctl disable mission-core-node-monitor.service
systemctl stop postgresql@16-ndcmonitor.service
systemctl disable postgresql@16-ndcmonitor.service
fi fi
;; ;;
esac esac
@@ -0,0 +1,100 @@
"""Repack qualified N08: only disable psql paging in the monitoring installer."""
import hashlib
import io
import json
import sys
import tarfile
from pathlib import Path
NODE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(NODE.parents[1] / "scripts/packaging"))
from debian import package # noqa: E402
BASE = "f929c440e4965f728aa6cd00eb122e7cad09e5ade82da763cc36661f50ec66b5"
TARGET = "usr/lib/mission-core-node/setup-monitor"
def main():
original = NODE / "build/qualified-n08/mission-core-node_0.8.17_amd64.deb"
raw = original.read_bytes()
if hashlib.sha256(raw).hexdigest() != BASE or raw[:8] != b"!<arch>\n":
raise ValueError("The qualified Node package changed")
entries, cursor = {}, 8
while cursor < len(raw):
header = raw[cursor : cursor + 60]
if header[58:] != b"`\n":
raise ValueError("Invalid Debian archive")
name, size = header[:16].decode().strip().rstrip("/"), int(header[48:58])
if name in entries:
raise ValueError("Duplicate archive member")
entries[name] = raw[cursor + 60 : cursor + 60 + size]
cursor += 60 + size + size % 2
if set(entries) != {"debian-binary", "control.tar.gz", "data.tar.gz"}:
raise ValueError("Unexpected Debian contents")
def files(name):
result = []
with tarfile.open(fileobj=io.BytesIO(entries[name]), mode="r:gz") as archive:
for member in archive.getmembers():
if member.isdir():
continue
if not member.isfile() or member.uid or member.gid:
raise ValueError("Unexpected package member")
result.append((member.name, archive.extractfile(member).read(), member.mode))
return result
controls, data = files("control.tar.gz"), files("data.tar.gz")
control_count = sum(name == "control" for name, _, _ in controls)
if control_count != 1:
raise ValueError("Unexpected control metadata")
controls = [
(
name,
value.replace(b"Version: 0.8.17\n", b"Version: 0.8.17-1\n")
if name == "control"
else value,
mode,
)
for name, value, mode in controls
]
fixed = (NODE / "packaging/setup-monitor").read_bytes()
originals = [value for name, value, _ in data if name == TARGET]
if len(originals) != 1 or fixed.count(b" -P pager=off") != 3:
raise ValueError("Unexpected monitor patch")
if fixed.replace(b" -P pager=off", b"") != originals[0]:
raise ValueError("This recovery admits only the three pager flags")
data = [(name, fixed if name == TARGET else value, mode) for name, value, mode in data]
proof = {
"schema": "missioncore.node.packaging-revision/v1",
"version": "0.8.17-1",
"qualified_base_sha256": BASE,
"changed_files": [TARGET],
"binary_ui_and_model_packages_unchanged": True,
"setup_monitor_sha256": hashlib.sha256(fixed).hexdigest(),
}
data.append(
(
"usr/share/doc/mission-core-node/packaging-revision.json",
(json.dumps(proof, indent=2) + "\n").encode(),
0o644,
)
)
folder = NODE / "build/qualified-n08-r2"
folder.mkdir(mode=0o700)
path = folder / "mission-core-node_0.8.17-1_amd64.deb"
path.write_bytes(package(controls, data))
evidence = json.loads((NODE / "build/qualified-n08/qualification.json").read_text())
evidence["packaging_revision"] = proof
evidence["artifacts"] = {
path.name: {
"bytes": path.stat().st_size,
"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
}
}
(folder / "qualification.json").write_text(json.dumps(evidence, indent=2) + "\n")
print(json.dumps({"folder": str(folder), "artifacts": evidence["artifacts"]}))
if __name__ == "__main__":
main()
@@ -0,0 +1,125 @@
"""P07: deliver the qualified X4 streaming fix without recompiling Node or its UI."""
import hashlib
import io
import json
import sys
import tarfile
from pathlib import Path
NODE = Path(__file__).resolve().parents[1]
REPO = NODE.parents[1]
sys.path.insert(0, str(REPO / "scripts/packaging"))
from debian import package # noqa: E402
BASE = "00f4baefd0c6f4e8f56bbf881329dfd36935e2334f35e2d17eb685a969d4c181"
def main():
original = NODE / "build/qualified-n08-r4/mission-core-node_0.8.17-3_amd64.deb"
raw = original.read_bytes()
if hashlib.sha256(raw).hexdigest() != BASE or raw[:8] != b"!<arch>\n":
raise ValueError("Qualified Node package changed")
entries, cursor = {}, 8
while cursor < len(raw):
header = raw[cursor : cursor + 60]
name, size = header[:16].decode().strip().rstrip("/"), int(header[48:58])
if header[58:] != b"`\n" or name in entries:
raise ValueError("Invalid archive")
entries[name] = raw[cursor + 60 : cursor + 60 + size]
cursor += 60 + size + size % 2
if set(entries) != {"debian-binary", "control.tar.gz", "data.tar.gz"}:
raise ValueError("Unexpected archive contents")
def files(name):
result = []
with tarfile.open(fileobj=io.BytesIO(entries[name]), mode="r:gz") as archive:
for member in archive.getmembers():
if member.isdir():
continue
if not member.isfile() or member.uid or member.gid:
raise ValueError("Unexpected package member")
result.append((member.name, archive.extractfile(member).read(), member.mode))
return result
controls, data = files("control.tar.gz"), files("data.tar.gz")
old = {name: value for name, value, _ in data}
profile_path = "usr/lib/mission-core-node/insta360_profile.py"
profile = (NODE / "packaging/insta360_profile.py").read_bytes()
if profile != old[profile_path]:
raise ValueError("The qualified bootstrap must remain unchanged")
qualified = REPO / "plugins/insta360-x4/build/package-b10"
result = json.loads((qualified / "package-result.json").read_text())
checks = json.loads((qualified / "build-report.json").read_text())
if checks["state"] != "complete" or result["version"] != "0.1.3-2":
raise ValueError("The fixed X4 package is not qualified")
model_name = "mission-core-insta360-x4_0.1.3-2_amd64.deb"
model = (qualified / model_name).read_bytes()
if len(model) != result["bytes"] or hashlib.sha256(model).hexdigest() != result["sha256"]:
raise ValueError("Qualified model package changed")
manifest = {
"schema": "missioncore.node.bundled-model/v1",
"model_id": "insta360.x4",
**{key: result[key] for key in ("version", "revision", "bytes", "sha256")},
}
model_root = "usr/share/mission-core-node/profiles/insta360-x4/"
changes = {
profile_path: profile,
model_root + "profile.json": (json.dumps(manifest, indent=2) + "\n").encode(),
}
proof_path = "usr/share/doc/mission-core-node/packaging-revision.json"
proof = {
"schema": "missioncore.node.packaging-revision/v1",
"version": "0.8.17-4",
"qualified_base_sha256": BASE,
"changed_files": list(changes) + [model_root + model_name],
"binary_and_ui_unchanged": True,
"model": manifest,
"model_checks": checks,
}
changes[proof_path] = (json.dumps(proof, indent=2) + "\n").encode()
if not set(changes) <= old.keys():
raise ValueError("Unexpected replacement paths")
old_model = model_root + "mission-core-insta360-x4_0.1.3-1_amd64.deb"
if (
hashlib.sha256(old[old_model]).hexdigest()
!= "c11977a4d4c9779b96ee38ff3a474bdd820d9e3e5ecc642e7711762def14b6da"
):
raise ValueError("Unexpected prior model bundle")
data = [
(name, changes.get(name, value), mode) for name, value, mode in data if name != old_model
]
data.append((model_root + model_name, model, 0o644))
for index, (name, value, mode) in enumerate(controls):
if name == "control":
if value.count(b"Version: 0.8.17-3\n") != 1:
raise ValueError("Unexpected Node version")
controls[index] = (
name,
value.replace(b"Version: 0.8.17-3\n", b"Version: 0.8.17-4\n"),
mode,
)
folder = NODE / "build/qualified-n08-r5"
folder.mkdir(mode=0o700)
target = folder / "mission-core-node_0.8.17-4_amd64.deb"
target.write_bytes(package(controls, data))
evidence = json.loads((NODE / "build/qualified-n08-r4/qualification.json").read_text())
evidence["packaging_revision"] = proof
evidence["artifacts"] = {
target.name: {
"bytes": target.stat().st_size,
"sha256": hashlib.sha256(target.read_bytes()).hexdigest(),
}
}
(folder / "qualification.json").write_text(json.dumps(evidence, indent=2) + "\n")
(NODE / "packaging/insta360-profile.json").write_bytes(changes[model_root + "profile.json"])
model_directory = NODE / "build/model-packages"
model_directory.mkdir(mode=0o700, exist_ok=True)
(model_directory / model_name).write_bytes(model)
print(
json.dumps({"folder": str(folder), "artifacts": evidence["artifacts"], "model": manifest})
)
if __name__ == "__main__":
main()
+130
View File
@@ -0,0 +1,130 @@
"""P09: deliver B11 through qualified Node 0.8.18 without changing binary/UI."""
import hashlib
import io
import json
import sys
import tarfile
from pathlib import Path
NODE = Path(__file__).resolve().parents[1]
REPO = NODE.parents[1]
sys.path.insert(0, str(REPO / "scripts/packaging"))
from debian import package # noqa: E402
BASE = "db340f7d117a7cdf4707bbf43f58c0e8307c8ac3813b7bc7dd5ca8a4a47f73b2"
def main():
original = NODE / "build/qualified-n09/mission-core-node_0.8.18_amd64.deb"
raw = original.read_bytes()
if hashlib.sha256(raw).hexdigest() != BASE or raw[:8] != b"!<arch>\n":
raise ValueError("Qualified Node package changed")
entries, cursor = {}, 8
while cursor < len(raw):
header = raw[cursor : cursor + 60]
name, size = header[:16].decode().strip().rstrip("/"), int(header[48:58])
if header[58:] != b"`\n" or name in entries:
raise ValueError("Invalid archive")
entries[name] = raw[cursor + 60 : cursor + 60 + size]
cursor += 60 + size + size % 2
if set(entries) != {"debian-binary", "control.tar.gz", "data.tar.gz"}:
raise ValueError("Unexpected archive contents")
def files(name):
result = []
with tarfile.open(fileobj=io.BytesIO(entries[name]), mode="r:gz") as archive:
for member in archive.getmembers():
if member.isdir():
continue
if not member.isfile() or member.uid or member.gid:
raise ValueError("Unexpected package member")
result.append((member.name, archive.extractfile(member).read(), member.mode))
return result
controls, data = files("control.tar.gz"), files("data.tar.gz")
old = {name: value for name, value, _ in data}
profile_path = "usr/lib/mission-core-node/insta360_profile.py"
profile = (NODE / "packaging/insta360_profile.py").read_bytes()
if profile != old[profile_path]:
raise ValueError("The qualified bootstrap must remain unchanged")
qualified = REPO / "plugins/insta360-x4/build/package-b11"
result = json.loads((qualified / "package-result.json").read_text())
checks = json.loads((qualified / "build-report.json").read_text())
if checks["state"] != "complete" or result["version"] != "0.1.3-3":
raise ValueError("The fixed X4 package is not qualified")
model_name = "mission-core-insta360-x4_0.1.3-3_amd64.deb"
model = (qualified / model_name).read_bytes()
if len(model) != result["bytes"] or hashlib.sha256(model).hexdigest() != result["sha256"]:
raise ValueError("Qualified model package changed")
manifest = {
"schema": "missioncore.node.bundled-model/v1",
"model_id": "insta360.x4",
**{key: result[key] for key in ("version", "revision", "bytes", "sha256")},
}
model_root = "usr/share/mission-core-node/profiles/insta360-x4/"
changes = {
profile_path: profile,
model_root + "profile.json": (json.dumps(manifest, indent=2) + "\n").encode(),
}
proof_path = "usr/share/doc/mission-core-node/packaging-revision.json"
proof = {
"schema": "missioncore.node.packaging-revision/v1",
"version": "0.8.18-1",
"qualified_base_sha256": BASE,
"changed_files": list(changes) + [model_root + model_name],
"binary_and_ui_unchanged": True,
"model": manifest,
"model_checks": checks,
}
changes[proof_path] = (json.dumps(proof, indent=2) + "\n").encode()
if not set(changes) - {proof_path} <= old.keys():
raise ValueError("Unexpected replacement paths")
old_model = model_root + "mission-core-insta360-x4_0.1.3-2_amd64.deb"
if (
hashlib.sha256(old[old_model]).hexdigest()
!= "2931a5206478fcac67f74bd1fb579b98c0fcc43eda4c05e5ac4a721947619130"
):
raise ValueError("Unexpected prior model bundle")
data = [
(name, changes.get(name, value), mode) for name, value, mode in data if name != old_model
]
data.append((model_root + model_name, model, 0o644))
if proof_path not in old:
data.append((proof_path, changes[proof_path], 0o644))
for name, content, _mode in data:
if name not in changes and name != model_root + model_name and content != old[name]:
raise ValueError("Unrelated qualified payload changed")
for index, (name, value, mode) in enumerate(controls):
if name == "control":
if value.count(b"Version: 0.8.18\n") != 1:
raise ValueError("Unexpected Node version")
controls[index] = (
name,
value.replace(b"Version: 0.8.18\n", b"Version: 0.8.18-1\n"),
mode,
)
folder = NODE / "build/qualified-n09-r1"
folder.mkdir(mode=0o700)
target = folder / "mission-core-node_0.8.18-1_amd64.deb"
target.write_bytes(package(controls, data))
evidence = json.loads((NODE / "build/qualified-n09/qualification.json").read_text())
evidence["packaging_revision"] = proof
evidence["artifacts"] = {
target.name: {
"bytes": target.stat().st_size,
"sha256": hashlib.sha256(target.read_bytes()).hexdigest(),
}
}
(folder / "qualification.json").write_text(json.dumps(evidence, indent=2) + "\n")
(NODE / "packaging/insta360-profile.json").write_bytes(changes[model_root + "profile.json"])
model_directory = NODE / "build/model-packages"
model_directory.mkdir(mode=0o700, exist_ok=True)
(model_directory / model_name).write_bytes(model)
print(
json.dumps({"folder": str(folder), "artifacts": evidence["artifacts"], "model": manifest})
)
if __name__ == "__main__":
main()
@@ -0,0 +1,108 @@
"""P05: replace only X4 bootstrap in qualified Node 0.8.17-1; retain compiled bytes."""
import hashlib
import io
import json
import sys
import tarfile
from pathlib import Path
NODE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(NODE.parents[1] / "scripts/packaging"))
from debian import package # noqa: E402
BASE = "7033ad608765231b20773dee45edac3d8f63e65525410de2346c79b3f8756a4b"
TARGET = "usr/lib/mission-core-node/insta360_profile.py"
PROOF = "usr/share/doc/mission-core-node/packaging-revision.json"
def main():
original = NODE / "build/qualified-n08-r2/mission-core-node_0.8.17-1_amd64.deb"
raw = original.read_bytes()
if hashlib.sha256(raw).hexdigest() != BASE or raw[:8] != b"!<arch>\n":
raise ValueError("Qualified package changed")
entries, cursor = {}, 8
while cursor < len(raw):
header = raw[cursor : cursor + 60]
name, size = header[:16].decode().strip().rstrip("/"), int(header[48:58])
if header[58:] != b"`\n" or name in entries:
raise ValueError("Invalid archive")
entries[name] = raw[cursor + 60 : cursor + 60 + size]
cursor += 60 + size + size % 2
if set(entries) != {"debian-binary", "control.tar.gz", "data.tar.gz"}:
raise ValueError("Unexpected package contents")
def files(name):
result = []
with tarfile.open(fileobj=io.BytesIO(entries[name]), mode="r:gz") as archive:
for member in archive.getmembers():
if member.isdir():
continue
if not member.isfile() or member.uid or member.gid:
raise ValueError("Unexpected package member")
result.append((member.name, archive.extractfile(member).read(), member.mode))
return result
controls, data = files("control.tar.gz"), files("data.tar.gz")
original_control = [value for name, value, _ in controls if name == "control"]
if len(original_control) != 1 or original_control[0].count(b"Version: 0.8.17-1\n") != 1:
raise ValueError("Unexpected control version")
fixed = (NODE / "packaging/insta360_profile.py").read_bytes()
checks = json.loads((NODE / "build/x4-profile-p05-check.json").read_text())
if (
checks["state"] != "complete"
or checks["files"]["apps/node-agent/packaging/insta360_profile.py"]
!= hashlib.sha256(fixed).hexdigest()
):
raise ValueError("Current profile has not passed Ubuntu checks")
if sum(name == TARGET for name, _, _ in data) != 1:
raise ValueError("Missing profile")
proof = {
"schema": "missioncore.node.packaging-revision/v1",
"version": "0.8.17-2",
"qualified_base_sha256": BASE,
"changed_files": [TARGET],
"binary_ui_and_model_packages_unchanged": True,
"profile_sha256": hashlib.sha256(fixed).hexdigest(),
"profile_check": checks,
}
controls = [
(
name,
value.replace(b"Version: 0.8.17-1\n", b"Version: 0.8.17-2\n")
if name == "control"
else value,
mode,
)
for name, value, mode in controls
]
data = [
(
name,
fixed
if name == TARGET
else (json.dumps(proof, indent=2) + "\n").encode()
if name == PROOF
else value,
mode,
)
for name, value, mode in data
]
folder = NODE / "build/qualified-n08-r3"
folder.mkdir(mode=0o700)
path = folder / "mission-core-node_0.8.17-2_amd64.deb"
path.write_bytes(package(controls, data))
evidence = json.loads((NODE / "build/qualified-n08-r2/qualification.json").read_text())
evidence["packaging_revision"] = proof
evidence["artifacts"] = {
path.name: {
"bytes": path.stat().st_size,
"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
}
}
(folder / "qualification.json").write_text(json.dumps(evidence, indent=2) + "\n")
print(json.dumps({"folder": str(folder), "artifacts": evidence["artifacts"]}))
if __name__ == "__main__":
main()
@@ -0,0 +1,179 @@
"""One fixed recovery of N08's qualified sources after the Core V8 heap limit.
No dependency installation, source edits, Go recompilation or hardware access.
The original failed report and all stderr remain part of the result archive.
"""
import fcntl
import hashlib
import json
import os
import platform
import resource
import subprocess
import sys
import tarfile
import time
from datetime import UTC, datetime
from pathlib import Path
IDENTIFIER = "511010461b4f2cd4c0546af9"
SOURCE_HASH = "511010461b4f2cd4c0546af946adcb696a03d3134dc0f68c4b5c62b8bc57d766"
REPORT_HASH = "e5481d0cb9e2799ffe2ca4ec60390d1557e363b93e192e52df92e58fae3d21e6"
PACKAGE_HASH = "f929c440e4965f728aa6cd00eb122e7cad09e5ade82da763cc36661f50ec66b5"
FOLDER = Path("/var/tmp/mission-core-node-builds") / IDENTIFIER
PACKAGE = "mission-core-node_0.8.17_amd64.deb"
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def main():
if os.geteuid() == 0 or (platform.system(), platform.machine()) != ("Linux", "x86_64"):
raise ValueError("Use the unprivileged Ubuntu build account")
if sys.argv[1:] not in ([], ["--job"]):
raise ValueError("Only the fixed N08 Core recovery is admitted")
os.umask(0o077)
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
for path in (FOLDER.parent, FOLDER):
info = path.lstat()
if path.is_symlink() or info.st_uid != os.geteuid() or info.st_mode & 0o077:
raise ValueError("Build attempt is not private and owned")
output = FOLDER / "output"
if digest(FOLDER / "source.json") != SOURCE_HASH:
raise ValueError("Source manifest changed")
manifest = json.loads((FOLDER / "source.json").read_text())
if digest(output / PACKAGE) != PACKAGE_HASH:
raise ValueError("Qualified Node package changed")
if not sys.argv[1:]:
with (FOLDER / "build.lock").open("a") as handle:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
subprocess.run(
[
"/usr/bin/systemd-run",
"--user",
"--collect",
"--wait",
"--pipe",
"--unit=mission-core-node-core-resume-" + IDENTIFIER,
"--property=MemoryMax=3G",
"--property=CPUQuota=150%",
"--property=TasksMax=256",
"--property=RuntimeMaxSec=300",
"--property=Nice=10",
"/usr/bin/python3",
str(Path(__file__).resolve()),
"--job",
],
check=True,
)
with tarfile.open(FOLDER / "result.tar.gz", "w:gz") as archive:
for path in sorted(output.iterdir()):
if not path.is_file() or path.is_symlink():
raise ValueError("Unexpected build output")
archive.add(path, arcname=path.name, recursive=False)
archive.add(FOLDER / "report.json", arcname="build-report.json", recursive=False)
print(
json.dumps(
{
"result": str(FOLDER / "result.tar.gz"),
"sha256": digest(FOLDER / "result.tar.gz"),
}
)
)
return
group = next(
line.split(":", 2)[2]
for line in Path("/proc/self/cgroup").read_text().splitlines()
if line.startswith("0::")
)
control = Path("/sys/fs/cgroup") / group.lstrip("/")
cpu, period = map(int, (control / "cpu.max").read_text().split())
if (
int((control / "memory.max").read_text()) != 3 * 1024**3
or cpu / period > 1.5
or int((control / "pids.max").read_text()) > 256
):
raise ValueError("Recovery cgroup limits are not enforced")
for name, expected in manifest["files"].items():
path = FOLDER / "source" / name
if path.is_symlink() or digest(path) != expected["sha256"]:
raise ValueError("A previously qualified input changed: " + name)
if digest(output / "qualification.json") != REPORT_HASH:
raise ValueError("Qualification checkpoint changed")
report = json.loads((output / "qualification.json").read_text())
if (
report["state"] != "error"
or report["jobs"][-1]["id"] != "core-build"
or report["jobs"][-1]["exit_code"] != 134
):
raise ValueError("This recovery only admits N08's V8 heap failure")
with (output / "qualification-before-core-resume.json").open("xb") as stream:
stream.write((output / "qualification.json").read_bytes())
repo = FOLDER / "source" / manifest["repository"]
tool = FOLDER / "toolchains/node-v24.9.0-linux-x64"
env = {
"PATH": str(tool / "bin") + ":/usr/bin:/bin",
"LANG": "C.UTF-8",
"TMPDIR": str(FOLDER / "temporary"),
"NODE_OPTIONS": "--max-old-space-size=2048",
"npm_config_cache": str(FOLDER / "npm-cache"),
"npm_config_audit": "false",
"npm_config_fund": "false",
"npm_config_update_notifier": "false",
}
started = time.monotonic()
job = {
"id": "core-build-memory-recovery",
"started_at": datetime.now(UTC).isoformat(),
"monotonic_started": started,
"memory_max_bytes": 3 * 1024**3,
"v8_heap_mib": 2048,
"source_manifest_sha256": SOURCE_HASH,
}
with (
(output / "core-build-recovery.stdout").open("wb") as out,
(output / "core-build-recovery.stderr").open("wb") as err,
):
result = subprocess.run(
[
str(tool / "bin/node"),
str(tool / "lib/node_modules/npm/bin/npm-cli.js"),
"run",
"build",
],
cwd=repo / "apps/control-station",
env=env,
stdout=out,
stderr=err,
timeout=280,
)
job.update(
exit_code=result.returncode,
state="complete" if result.returncode == 0 else "error",
finished_at=datetime.now(UTC).isoformat(),
duration_seconds=time.monotonic() - started,
memory_peak_bytes=int((control / "memory.peak").read_text()),
)
(output / "core-resume-report.json").write_text(json.dumps(job, indent=2) + "\n")
if result.returncode:
raise RuntimeError("Core build recovery failed; preserve its evidence")
dist = repo / "apps/control-station/dist"
with tarfile.open(output / "core-dist.tar.gz", "w:gz") as archive:
for path in sorted(dist.rglob("*")):
if path.is_file():
archive.add(path, arcname=str(path.relative_to(dist)), recursive=False)
report["jobs"].append(job)
report.update(
state="complete", finished_at=datetime.now(UTC).isoformat(), recovered_from=REPORT_HASH
)
report["artifacts"] = {
path.name: {"bytes": path.stat().st_size, "sha256": digest(path)}
for path in (output / PACKAGE, output / "core-dist.tar.gz")
}
(output / "qualification.json").write_text(json.dumps(report, indent=2) + "\n")
if __name__ == "__main__":
main()
@@ -0,0 +1,230 @@
"""Fixed N09 test-contract recovery; no installed files or camera access."""
import fcntl
import hashlib
import json
import os
import platform
import subprocess
import sys
import tarfile
import time
import zipfile
from datetime import UTC, datetime
from pathlib import Path
IDENTIFIER = "d7aa79960717e4d62ab69633"
SOURCE_HASH = "d7aa79960717e4d62ab69633ec9ddc1ddabfa33998043635bdef2dbac807a3ca"
REPORT_HASH = "0d7b2390c5d546e1e442c1283afcbab6e63e03ac8f3033489f7b86cc3de71278"
PACKAGE_HASH = "db340f7d117a7cdf4707bbf43f58c0e8307c8ac3813b7bc7dd5ca8a4a47f73b2"
FOLDER = Path("/var/tmp/mission-core-node-builds") / IDENTIFIER
PACKAGE = "mission-core-node_0.8.18_amd64.deb"
TESTS = {
"apps/control-station/test/k1ManualControl.test.mjs",
"apps/control-station/test/k1SupervisorPresentation.test.mjs",
}
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def main():
if os.geteuid() == 0 or (platform.system(), platform.machine()) != ("Linux", "x86_64"):
raise ValueError("Use the unprivileged Ubuntu account")
if sys.argv[1:] not in ([], ["--job"]):
raise ValueError("Only the fixed N09 recovery is admitted")
os.umask(0o077)
artifact = Path(sys.argv[0]).resolve()
for p in (FOLDER.parent, FOLDER):
info = p.lstat()
if p.is_symlink() or info.st_uid != os.geteuid() or info.st_mode & 0o077:
raise ValueError("Staging is not private and owned")
with zipfile.ZipFile(artifact) as z:
patch = json.loads(z.read("patch.json"))
if (
set(patch["files"]) != TESTS
or set(z.namelist()) != {"__main__.py", "patch.json"} | TESTS
):
raise ValueError("Only the two test files can change")
payload = {name: z.read(name) for name in TESTS}
if hashlib.sha256(z.read("__main__.py")).hexdigest() != patch["entrypoint_sha256"]:
raise ValueError("Entry point changed")
for name, data in payload.items():
if (
len(data) != patch["files"][name]["bytes"]
or hashlib.sha256(data).hexdigest() != patch["files"][name]["sha256"]
):
raise ValueError("Test payload changed")
output = FOLDER / "output"
if digest(FOLDER / "source.json") != SOURCE_HASH or digest(output / PACKAGE) != PACKAGE_HASH:
raise ValueError("N09 checkpoint changed")
manifest = json.loads((FOLDER / "source.json").read_text())
repo = FOLDER / "source" / manifest["repository"]
if not sys.argv[1:]:
with (FOLDER / "build.lock").open("a") as handle:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
if (FOLDER / "result.tar.gz").exists():
raise ValueError("Recovery already completed")
subprocess.run(
[
"/usr/bin/systemd-run",
"--user",
"--collect",
"--wait",
"--pipe",
"--unit=mission-core-node-core-resume-" + IDENTIFIER,
"--property=MemoryMax=3G",
"--property=CPUQuota=150%",
"--property=TasksMax=256",
"--property=RuntimeMaxSec=600",
"--property=KillMode=control-group",
"--property=Nice=10",
"/usr/bin/python3",
str(artifact),
"--job",
],
check=True,
)
with tarfile.open(FOLDER / "result.tar.gz", "w:gz") as archive:
for path in sorted(output.iterdir()):
if path.is_symlink() or not path.is_file():
raise ValueError("Unexpected result")
archive.add(path, arcname=path.name, recursive=False)
archive.add(FOLDER / "report.json", arcname="build-report.json", recursive=False)
print(
json.dumps(
{
"result": str(FOLDER / "result.tar.gz"),
"sha256": digest(FOLDER / "result.tar.gz"),
}
)
)
return
group = next(
x.split(":", 2)[2]
for x in Path("/proc/self/cgroup").read_text().splitlines()
if x.startswith("0::")
)
control = Path("/sys/fs/cgroup") / group.lstrip("/")
cpu, period = map(int, (control / "cpu.max").read_text().split())
if (
int((control / "memory.max").read_text()) != 3 * 1024**3
or cpu / period > 1.5
or int((control / "pids.max").read_text()) > 256
):
raise ValueError("Resource limits not enforced")
for name, expected in manifest["files"].items():
path = FOLDER / "source" / name
if path.is_symlink() or digest(path) != expected["sha256"]:
raise ValueError("Original input changed: " + name)
if digest(output / "qualification.json") != REPORT_HASH:
raise ValueError("Qualification checkpoint changed")
report = json.loads((output / "qualification.json").read_text())
if report["state"] != "error" or report["jobs"][-1]["id"] != "core-tests":
raise ValueError("Only the observed N09 test failure can be resumed")
with (output / "qualification-before-n09-resume.json").open("xb") as f:
f.write((output / "qualification.json").read_bytes())
for name, data in payload.items():
(repo / name).write_bytes(data)
(output / "test-contract-patch.json").write_text(json.dumps(patch, indent=2))
tool = FOLDER / "toolchains/node-v24.9.0-linux-x64"
env = {
"PATH": str(tool / "bin") + ":/usr/bin:/bin",
"LANG": "C.UTF-8",
"TMPDIR": str(FOLDER / "temporary"),
"NODE_OPTIONS": "--max-old-space-size=2048",
"npm_config_cache": str(FOLDER / "npm-cache"),
"npm_config_audit": "false",
"npm_config_fund": "false",
"npm_config_update_notifier": "false",
}
started = time.monotonic()
report.update(
state="running",
recovered_from=REPORT_HASH,
recovery_started_at=datetime.now(UTC).isoformat(),
recovery_monotonic_started=started,
)
def save():
(output / "qualification.json").write_text(json.dumps(report, indent=2) + "\n")
def run(name, args, timeout):
job = {"id": name, "started_at": datetime.now(UTC).isoformat(), "state": "running"}
report["jobs"].append(job)
save()
begin = time.monotonic()
with (
(output / (name + ".stdout")).open("wb") as out,
(output / (name + ".stderr")).open("wb") as err,
):
result = subprocess.run(
args,
cwd=repo / "apps/control-station",
env=env,
stdout=out,
stderr=err,
timeout=timeout,
)
job.update(
exit_code=result.returncode,
state="complete" if result.returncode == 0 else "error",
duration_seconds=time.monotonic() - begin,
)
save()
if result.returncode:
raise RuntimeError(name + " failed")
try:
run(
"core-tests-n09-contract",
[
str(tool / "bin/node"),
"--test",
"--test-concurrency=1",
"--test-skip-pattern=^native RRD crosses many RTC fragments "
"and reaches decoder once, byte-for-byte$",
*[str(p) for p in sorted((repo / "apps/control-station/test").glob("*.test.mjs"))],
],
300,
)
run(
"core-build-n09",
[
str(tool / "bin/node"),
str(tool / "lib/node_modules/npm/bin/npm-cli.js"),
"run",
"build",
],
240,
)
roots = {
"core-dist.tar.gz": repo / "apps/control-station/dist",
"design-guideline-catalog.tar.gz": FOLDER
/ "source/NODEDC_DESIGN_GUIDELINE/apps/catalog/dist",
}
for name, root in roots.items():
with tarfile.open(output / name, "w:gz") as archive:
for path in sorted(root.rglob("*")):
if path.is_file() and not path.is_symlink():
archive.add(path, arcname=str(path.relative_to(root)), recursive=False)
report.update(
state="complete",
finished_at=datetime.now(UTC).isoformat(),
recovery_duration_seconds=time.monotonic() - started,
memory_peak_bytes=int((control / "memory.peak").read_text()),
)
report["artifacts"] = {
p.name: {"bytes": p.stat().st_size, "sha256": digest(p)}
for p in [output / PACKAGE, *[output / n for n in roots]]
}
save()
except Exception:
report.update(state="error", finished_at=datetime.now(UTC).isoformat())
save()
raise
if __name__ == "__main__":
main()
+65
View File
@@ -0,0 +1,65 @@
#!/bin/sh
# Fixed local database bootstrap; no supplied SQL, credentials or network address.
set -eu
test "$(id -u)" = 0
if ! getent passwd mission-core-monitor >/dev/null; then
adduser --system --group --home /var/lib/mission-core-monitor --no-create-home --disabled-login mission-core-monitor
fi
install -d -m 0750 -o mission-core-monitor -g mission-core-node /var/lib/mission-core-monitor
install -d -m 0755 -o postgres -g postgres /run/mission-core-monitor-db
install -d -m 0755 /etc/tmpfiles.d
printf '%s\n' 'd /run/mission-core-monitor-db 0755 postgres postgres -' > /etc/tmpfiles.d/mission-core-monitor.conf
# R18 used a dash, which the PostgreSQL systemd template expands as a slash.
# Rename only our exact cluster. pg_renamecluster preserves this custom data
# directory, updates its configuration paths, and retains all database files.
if [ -d /etc/postgresql/16/ndc-monitor ]; then
test ! -d /etc/postgresql/16/ndcmonitor
test "$(pg_conftool -s 16 ndc-monitor show data_directory)" = /var/lib/mission-core-monitor-db
test "$(pg_conftool -s 16 ndc-monitor show port)" = 5433
pg_renamecluster 16 ndc-monitor ndcmonitor
fi
if [ ! -d /etc/postgresql/16/ndcmonitor ]; then
pg_createcluster 16 ndcmonitor --port=5433 --socketdir=/run/mission-core-monitor-db --datadir=/var/lib/mission-core-monitor-db --start-conf=auto -- --auth-local=peer --auth-host=reject
fi
test "$(pg_conftool -s 16 ndcmonitor show data_directory)" = /var/lib/mission-core-monitor-db
test "$(pg_conftool -s 16 ndcmonitor show port)" = 5433
install -d -m 0755 /etc/postgresql/16/ndcmonitor/conf.d
cat > /etc/postgresql/16/ndcmonitor/conf.d/60-mission-core-monitor.conf <<'CONF'
listen_addresses = ''
unix_socket_directories = '/run/mission-core-monitor-db'
shared_preload_libraries = 'timescaledb'
shared_buffers = '32MB'
work_mem = '2MB'
maintenance_work_mem = '16MB'
max_connections = 12
max_worker_processes = 4
max_parallel_workers = 0
timescaledb.max_background_workers = 2
timescaledb.telemetry_level = 'off'
max_wal_size = '128MB'
min_wal_size = '32MB'
temp_file_limit = '32MB'
statement_timeout = '5s'
log_statement = 'none'
log_min_error_statement = 'panic'
CONF
install -d -m 0755 /etc/systemd/system/postgresql@16-ndcmonitor.service.d
cat > /etc/systemd/system/postgresql@16-ndcmonitor.service.d/60-mission-core-monitor.conf <<'CONF'
[Service]
ExecStartPre=+/usr/bin/install -d -m 0755 -o postgres -g postgres /run/mission-core-monitor-db
MemoryHigh=256M
MemoryMax=384M
CPUQuota=25%
TasksMax=32
Nice=10
CONF
systemctl daemon-reload
systemctl restart postgresql@16-ndcmonitor.service
runuser -u postgres -- psql -X -P pager=off -v ON_ERROR_STOP=1 -h /run/mission-core-monitor-db -p 5433 -d postgres <<'SQL'
SELECT 'CREATE ROLE "mission-core-monitor" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE' WHERE NOT EXISTS(SELECT FROM pg_roles WHERE rolname='mission-core-monitor') \gexec
SELECT 'CREATE DATABASE mission_core_monitor OWNER "mission-core-monitor"' WHERE NOT EXISTS(SELECT FROM pg_database WHERE datname='mission_core_monitor') \gexec
SQL
runuser -u postgres -- psql -X -P pager=off -v ON_ERROR_STOP=1 -h /run/mission-core-monitor-db -p 5433 -d mission_core_monitor -c 'CREATE EXTENSION IF NOT EXISTS timescaledb'
runuser -u mission-core-monitor -- psql -X -P pager=off -v ON_ERROR_STOP=1 -h /run/mission-core-monitor-db -p 5433 -d mission_core_monitor -f /usr/lib/mission-core-node/monitor/schema.sql
systemctl enable mission-core-node-monitor.service
systemctl restart mission-core-node-monitor.service
+22
View File
@@ -0,0 +1,22 @@
import { EnvironmentSettingsWindow, LandingStage } from "@nodedc/ui-react";
import type { EnvironmentPage } from "@nodedc/ui-core";
import { views, type ViewId } from "./nodeModel";
import type { usePresentation } from "./usePresentation";
const surfaces = [{ id: "home", home: true, description: "Главная страница продукта", actions: views }];
export function Home({ page, openView }: { page: EnvironmentPage; openView: (id: ViewId) => void }) {
const actions = [page.primaryWorkspaceId, page.secondaryWorkspaceId].flatMap(id => {
const view = views.find(item => item.id === id);
return view ? [{ id: view.id, label: view.label, icon: view.icon, onSelect: () => openView(view.id) }] : [];
});
return <LandingStage page={page} actions={actions} />;
}
export function HomeSettings({ open, onClose, presentation }: {
open: boolean; onClose: () => void; presentation: ReturnType<typeof usePresentation>;
}) {
return <EnvironmentSettingsWindow productName="Mission Core Node" open={open} onClose={onClose}
surfaces={surfaces} settings={presentation.settings} state={presentation.state} error={presentation.error}
onSave={presentation.save} onUpload={presentation.upload} />;
}
+4 -3
View File
@@ -1,7 +1,8 @@
import {xgridsK1SensorUi,K1EnrollmentWindow} from '../../../../plugins/xgrids-k1/frontend/src/sensors/plugin'; import {xgridsK1SensorUi} from '../../../../plugins/xgrids-k1/frontend/src/sensors/plugin';
import {insta360X4SensorUi} from '../../../../plugins/insta360-x4/frontend/src/plugin';
import {createIsolatedRerunHost} from '../../../control-station/src/components/rerun/isolatedRerunHost'; import {createIsolatedRerunHost} from '../../../control-station/src/components/rerun/isolatedRerunHost';
import {SensorWorkspace} from '../../../../packages/sensor-ui/src/SensorWorkspace'; import {SensorWorkspace} from '../../../../packages/sensor-ui/src/SensorWorkspace';
import type {SensorTransport} from '../../../../packages/sensor-ui/src/contracts'; import type {SensorTransport} from '../../../../packages/sensor-ui/src/contracts';
import {request} from './api'; import {request} from './api';
const transport:SensorTransport={enrollment:{state:()=>request("/api/devices/enrollment"),submit:value=>request("/api/devices/enrollment/operations","POST",value),operation:id=>request("/api/devices/enrollment/operations/"+encodeURIComponent(id))},subscribe:(receive,unavailable)=>{const events=new EventSource('/api/devices/events');events.onmessage=e=>{try{receive(JSON.parse(e.data));}catch{unavailable();}};events.onerror=unavailable;return()=>events.close();},inventory:()=>request('/api/devices'),submit:value=>request('/api/devices/operations','POST',value),operation:id=>request('/api/devices/operations/'+encodeURIComponent(id))}; const transport:SensorTransport={localPreview:{open:(command,signal)=>fetch("/api/devices/preview",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(command),signal}),read:(peer,after,signal)=>fetch("/api/devices/preview/read",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({peer_id:peer,after}),signal})},enrollment:{state:()=>request("/api/devices/enrollment"),submit:value=>request("/api/devices/enrollment/operations","POST",value),operation:id=>request("/api/devices/enrollment/operations/"+encodeURIComponent(id))},subscribe:(receive,unavailable)=>{const events=new EventSource('/api/devices/events');events.onmessage=e=>{try{receive(JSON.parse(e.data));}catch{unavailable();}};events.onerror=unavailable;return()=>events.close();},inventory:()=>request('/api/devices'),submit:value=>request('/api/devices/operations','POST',value),operation:id=>request('/api/devices/operations/'+encodeURIComponent(id))};
export function NodeSensors(){return <SensorWorkspace contributions={[xgridsK1SensorUi]} EnrollmentView={K1EnrollmentWindow} createRerunHost={createIsolatedRerunHost} transport={transport}/>;} export function NodeSensors(){return <SensorWorkspace contributions={[xgridsK1SensorUi,insta360X4SensorUi]} createRerunHost={createIsolatedRerunHost} transport={transport}/>;}
@@ -0,0 +1,20 @@
import {Component,type ReactNode} from 'react';
import {Button,SettingsCard} from '@nodedc/ui-react';
export function runtimeDiagnostic(error:unknown,code='ui-error') {
const kind=error instanceof Error&&/^[A-Za-z]{1,48}$/.test(error.name)?error.name:'Error';
// Never send exception messages, URLs, form values or arbitrary stack text.
const locations=error instanceof Error?(error.stack??'').match(/[A-Za-z0-9_-]+\.js:\d+:\d+/g)?.slice(0,8)??[]:[];
void fetch('/api/monitor/events',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({code,kind,locations}),keepalive:true}).catch(()=>{});
}
export function observeRuntime(){
window.addEventListener('error',event=>runtimeDiagnostic(event.error));
window.addEventListener('unhandledrejection',event=>runtimeDiagnostic(event.reason,'ui-rejection'));
}
export class RuntimeBoundary extends Component<{children:ReactNode;resetKey?:string},{failed:boolean}> {
state={failed:false};
static getDerivedStateFromError(){return {failed:true};}
componentDidCatch(error:Error){runtimeDiagnostic(error,'ui-render-error');}
componentDidUpdate(previous:Readonly<{children:ReactNode;resetKey?:string}>){if(this.state.failed&&previous.resetKey!==this.props.resetKey)this.setState({failed:false});}
render(){return this.state.failed?<SettingsCard title="Не удалось открыть представление" description="Вернитесь к устройствам или повторите открытие."><Button onClick={()=>this.setState({failed:false})}>Открыть повторно</Button></SettingsCard>:this.props.children;}
}
+18 -11
View File
@@ -16,19 +16,24 @@ import { EnvironmentView } from "./EnvironmentView";
import { CoreConnectionView } from "./CoreConnectionView"; import { CoreConnectionView } from "./CoreConnectionView";
import "./node.css"; import "./node.css";
import { NodeSensors } from "./NodeSensors"; import { NodeSensors } from "./NodeSensors";
import { Home, HomeSettings } from "./Home";
import { usePresentation } from "./usePresentation";
import {RuntimeBoundary,observeRuntime} from './RuntimeBoundary';
function App() { function App() {
const node = useNode(); const node = useNode();
const { value, pending, locked, refresh, failure } = node; const { value, pending, locked, refresh, failure } = node;
const environment = useEnvironment(!!value, failure); const environment = useEnvironment(!!value, failure);
const presentation = usePresentation(!!value);
const [settingsOpen, setSettingsOpen] = useState(false);
const refreshAll = () => {if(!environment.running) {void refresh();void environment.refresh();}}; const refreshAll = () => {if(!environment.running) {void refresh();void environment.refresh();}};
const [root, setRoot] = useState<RootId>("system"); const [root, setRoot] = useState<RootId | null>(null);
const workspace = useApplicationWorkspace<ViewId>({ activeView: "environment" }); const workspace = useApplicationWorkspace<ViewId>();
const [adding, setAdding] = useState(false); const [adding, setAdding] = useState(false);
const [theme, setTheme] = useState(() => localStorage.getItem("node-theme") === "light" ? "light" : "dark"); const [theme, setTheme] = useState(() => localStorage.getItem("node-theme") === "light" ? "light" : "dark");
// Theme applies to body portals as well as the application shell. // Theme applies to body portals as well as the application shell.
useEffect(() => { document.documentElement.dataset.nodedcTheme = theme; }, [theme]); useEffect(() => { document.documentElement.dataset.nodedcTheme = theme; }, [theme]);
const currentRoot = roots.find(item => item.id === root)!; const currentRoot = roots.find(item => item.id === root) ?? roots[0];
const currentView = views.find(item => item.id === workspace.activeView); const currentView = views.find(item => item.id === workspace.activeView);
function openView(id: ViewId) { if(environment.running) return; setAdding(false); setRoot(views.find(item => item.id === id)!.root); workspace.openView(id); } function openView(id: ViewId) { if(environment.running) return; setAdding(false); setRoot(views.find(item => item.id === id)!.root); workspace.openView(id); }
function selectRoot(id: RootId) { const first = roots.find(item => item.id === id)!.first; if (first) openView(first); } function selectRoot(id: RootId) { const first = roots.find(item => item.id === id)!.first; if (first) openView(first); }
@@ -41,22 +46,24 @@ function App() {
: workspace.activeView === "tailscale" ? <TailnetAccess failure={failure} revision={value.host.collected_at} /> : workspace.activeView === "tailscale" ? <TailnetAccess failure={failure} revision={value.host.collected_at} />
: workspace.activeView === "ssh" ? <SystemAccess revision={value.host.collected_at} failure={failure} success={node.success} adding={adding} closeAdd={() => setAdding(false)} /> : null; : workspace.activeView === "ssh" ? <SystemAccess revision={value.host.collected_at} failure={failure} success={node.success} adding={adding} closeAdd={() => setAdding(false)} /> : null;
return <> return <>
<ApplicationShell data-nodedc-ui className="node-app" header={<AppHeader brandMonochrome brand={<img src="/nodedc-logo.svg" alt="NODE.DC" />} brandLabel="Mission Core Node" <ApplicationShell data-nodedc-ui className="node-app" header={<AppHeader brandMonochrome brandHref="/" brand={<img src="/nodedc-logo.svg" alt="NODE.DC" />} brandLabel={presentation.settings.pages.home.headerLabel}
center={<HeaderNavigation label="Разделы бортового компьютера" value={root} items={roots.map(item => ({ value: item.id, label: item.label, disabled: !value || !item.first || environment.running }))} onChange={selectRoot} />} center={<HeaderNavigation label="Разделы бортового компьютера" value={root ?? undefined} items={roots.map(item => ({ value: item.id, label: item.label, disabled: !value || !item.first || environment.running }))} onChange={selectRoot} />}
right={<HeaderProfile><UserProfileMenu displayName="Node" subtitle={value?.name ?? "Mission Core Node"} triggerLabel={null} actions={[{ id: "refresh", label: "Обновить сведения", icon: "refresh", onSelect: refreshAll }, { id: "theme", label: theme === "dark" ? "Светлая тема" : "Тёмная тема", icon: "eye", onSelect: () => { const next = theme === "dark" ? "light" : "dark"; setTheme(next); localStorage.setItem("node-theme", next); } }]} /></HeaderProfile>} />} right={<HeaderProfile><UserProfileMenu displayName="Node" subtitle={value?.name ?? "Mission Core Node"} triggerLabel={null} actions={[{ id: "settings", label: "Настройки", icon: "settings", onSelect: () => { if (value) { void presentation.refresh(); setSettingsOpen(true); } } }, { id: "refresh", label: "Обновить сведения", icon: "refresh", onSelect: refreshAll }, { id: "theme", label: theme === "dark" ? "Светлая тема" : "Тёмная тема", icon: "eye", onSelect: () => { const next = theme === "dark" ? "light" : "dark"; setTheme(next); localStorage.setItem("node-theme", next); } }]} /></HeaderProfile>} />}
navigationOpen={!!value && workspace.navigationOpen} contentOpen={!!value && workspace.contentOpen} contentExpanded={workspace.contentExpanded} navigationOpen={!!value && workspace.navigationOpen} contentOpen={!!value && workspace.contentOpen} contentExpanded={workspace.contentExpanded}
navigation={<AdminNavigationPanel eyebrow="MISSION CORE NODE" title={currentRoot.label} onClose={workspace.closeNavigation} closeLabel="Закрыть навигацию" navigationLabel="Разделы выбранной вкладки" navigation={<AdminNavigationPanel eyebrow="MISSION CORE NODE" title={currentRoot.label} onClose={workspace.closeNavigation} closeLabel="Закрыть навигацию" navigationLabel="Разделы выбранной вкладки"
contexts={value ? [{ id: "board", label: value.name, description: value.host.hostname, icon: <Icon name="activity" />, onSelect: () => openView("overview") }] : []} contexts={value ? [{ id: "board", label: value.name, description: value.host.hostname, icon: <Icon name="activity" />, onSelect: () => openView("overview") }] : []}
items={views.filter(item => item.root === root).map(item => ({ id: item.id, label: item.label, icon: <Icon name={item.icon} /> }))} activeId={workspace.activeView ?? undefined} onItemChange={id => openView(id as ViewId)} footer={<span>Mission Core Node · {value?.version}</span>} />} items={views.filter(item => item.root === root).map(item => ({ id: item.id, label: item.label, icon: <Icon name={item.icon} /> }))} activeId={workspace.activeView ?? undefined} onItemChange={id => openView(id as ViewId)} footer={<span>Mission Core Node · {value?.version}</span>} />}
content={currentView && <ApplicationPanel title={currentView.label} eyebrow={currentRoot.label} expanded={workspace.contentExpanded} onExpandedChange={workspace.setContentExpanded} onClose={workspace.closeView} content={currentView && <ApplicationPanel title={currentView.label} eyebrow={currentRoot.label} expanded={workspace.contentExpanded} onExpandedChange={workspace.setContentExpanded} onClose={workspace.closeView}
utilityActions={[...(workspace.activeView === "ssh" ? [{ label: "Добавить доверенное устройство", icon: "plus" as const, onClick: () => setAdding(true) }] : []), { label: "Обновить сведения", icon: "refresh", disabled: pending || environment.running, onClick: refreshAll }]}>{content}</ApplicationPanel>} utilityActions={[...(workspace.activeView === "ssh" ? [{ label: "Добавить доверенное устройство", icon: "plus" as const, onClick: () => setAdding(true) }] : []), { label: "Обновить сведения", icon: "refresh", disabled: pending || environment.running, onClick: refreshAll }]}><RuntimeBoundary resetKey={workspace.activeView??undefined}>{content}</RuntimeBoundary></ApplicationPanel>}
stage={<div className="node-stage" aria-busy={pending}> stage={value ? <Home page={presentation.settings.pages.home} openView={openView} /> : <div className="node-stage" aria-busy={pending}>
{value ? <SettingsCard title={value.name} eyebrow="MISSION CORE NODE" description={`Бортовой компьютер · ${value.host.architecture}`}><div className="node-home-actions">{roots.map(item => <Button key={item.id} disabled={!item.first} onClick={() => selectRoot(item.id)}>{item.label}</Button>)}</div></SettingsCard> : <SettingsCard className="node-entry" title={pending ? "Подключаемся к ноде" : locked ? "Вход в Mission Core Node" : "Нода недоступна"}> <SettingsCard className="node-entry" title={pending ? "Подключаемся к ноде" : locked ? "Вход в Mission Core Node" : "Нода недоступна"}>
{pending ? <ActivityIndicator label="Получение сведений о ноде" /> : <p className="node-note">{locked ? "Подтвердите доступ в системном окне." : "Не удалось связаться со службой. Повторите подключение."}</p>} {pending ? <ActivityIndicator label="Получение сведений о ноде" /> : <p className="node-note">{locked ? "Подтвердите доступ в системном окне." : "Не удалось связаться со службой. Повторите подключение."}</p>}
<Button disabled={pending} onClick={() => { if (locked) { if (!desktopLogin()) failure(new Error("Откройте установленное приложение Mission Core Node из меню приложений.")); } else void refresh(); }}>{locked ? "Войти" : "Повторить подключение"}</Button> <Button disabled={pending} onClick={() => { if (locked) { if (!desktopLogin()) failure(new Error("Откройте установленное приложение Mission Core Node из меню приложений.")); } else void refresh(); }}>{locked ? "Войти" : "Повторить подключение"}</Button>
</SettingsCard>} </SettingsCard>
</div>} /> </div>} />
<ToastStack items={node.toasts} onDismiss={node.dismiss} /> <ToastStack items={node.toasts} onDismiss={node.dismiss} />
<HomeSettings open={!!value && settingsOpen} onClose={() => setSettingsOpen(false)} presentation={presentation} />
</>; </>;
} }
createRoot(document.getElementById("root")!).render(<App />); observeRuntime();
createRoot(document.getElementById("root")!).render(<RuntimeBoundary><App /></RuntimeBoundary>);

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