Compare commits

...
Author SHA1 Message Date
DCCONSTRUCTIONS 1b67d5f7df feat(events): deliver state changes to the configurable operator event center 2026-11-21 20:58:27 +03:00
DCCONSTRUCTIONS d4ed96f3cd feat(dev): correlate telemetry recovery, safety stops and passive drive evidence 2026-11-21 20:58:26 +03:00
DCCONSTRUCTIONS 43d4916331 feat(network): verify selected uplinks, roll back failures and manage NetBird policy 2026-11-21 20:58:26 +03:00
DCCONSTRUCTIONS a50d638ced feat(observatory): show present equipment and compact router and telemetry panes 2026-11-21 20:58:25 +03:00
DCCONSTRUCTIONS 3ff43dd2af feat(router): confirm DexaFlow modes and expose the paired admin interface 2026-11-21 20:58:25 +03:00
DCCONSTRUCTIONS bed1db3508 fix(video): recover encoder capacity, pace RTP and isolate preview sessions 2026-11-21 20:58:25 +03:00
DCCONSTRUCTIONS 3d04fa45d3 fix(vesc): recover cancelled controller preparation without rearming 2026-11-21 20:58:25 +03:00
DCCONSTRUCTIONS 1635299252 feat(network): measure Core and onboard links against registered LibreSpeed servers 2026-11-21 20:58:24 +03:00
DCCONSTRUCTIONS 22f262ca59 fix(installer): coordinate K1 maintenance with active recordings 2026-11-21 20:58:24 +03:00
DCCONSTRUCTIONS c45bd6b882 build(packaging): retain qualified payloads through verified owner archives 2026-11-21 20:58:24 +03:00
DCCONSTRUCTIONS bd8af772d9 Update BIM viewer with cursor-anchored navigation 2026-11-17 22:34:38 +03:00
DCCONSTRUCTIONS e26582fc75 feat(bim): ship unified scene settings and independent photo window layout 2026-11-17 21:53:01 +03:00
DCCONSTRUCTIONS e9527060f6 fix(bim): ship visible spatial note markers 2026-11-17 19:50:53 +03:00
DCCONSTRUCTIONS 56d89197a8 feat(bim): ship surface notes, photo galleries and favorites 2026-11-17 18:34:36 +03:00
DCCONSTRUCTIONS 29ef038a43 feat(core): persist viewer state and integrate Cesium services and profiles 2026-11-17 17:20:15 +03:00
DCCONSTRUCTIONS 9cbdd4ea5c fix(ui): consume shared borderless drag-handle focus 2026-11-17 02:06:23 +03:00
DCCONSTRUCTIONS b1533ce0ea fix(bim): retain Cesium inspector geometry and outline lock states 2026-11-17 01:45:33 +03:00
DCCONSTRUCTIONS f4b506d593 Integrate Cesium scan locks and persistent row ordering 2026-11-17 00:48:28 +03:00
DCCONSTRUCTIONS a3781bcf4b Pin Cesium import recovery and map editor corrections 2026-11-17 00:07:00 +03:00
DCCONSTRUCTIONS a3927ce846 Pin portable Cesium Gaussian inspector release 2026-11-16 22:52:25 +03:00
DCCONSTRUCTIONS 0a29522f2f Integrate Cesium Gaussian lifecycle and source-based cleanup rebuilds 2026-11-16 22:16:12 +03:00
DCCONSTRUCTIONS 7c0dbd4e06 Make simulation imports background tasks with Worker-owned sources and durable deletion 2026-11-16 18:13:27 +03:00
DCCONSTRUCTIONS 9871ae500f Upgrade Cesium runtime with versioned assets and verified cache-safe rollback 2026-11-16 16:18:59 +03:00
DCCONSTRUCTIONS a80e3a8ff5 Connect architectural project maps to the existing Cesium gateway 2026-11-16 15:24:11 +03:00
DCCONSTRUCTIONS a5e4fba807 Integrate compact BIM inspector, measurement editing and shared tooltips 2026-11-16 14:34:19 +03:00
DCCONSTRUCTIONS 996ce7efdf Update portable BIM viewer for concurrent flight and orbit 2026-11-16 00:47:22 +03:00
DCCONSTRUCTIONS 0f97f79216 Integrate layer notes, project views and resilient BIM uploads 2026-11-16 00:40:03 +03:00
DCCONSTRUCTIONS 8aeb5b3fd2 docs(ui): record shared collapsible navigation acceptance 2026-11-15 22:50:56 +03:00
DCCONSTRUCTIONS 958e9c396d fix(bim): record qualified legacy LAS worker correction 2026-11-15 22:20:30 +03:00
DCCONSTRUCTIONS 778a558a34 feat(bim): integrate version notes and verified photo intake fixes 2026-11-15 22:07:36 +03:00
DCCONSTRUCTIONS 4a8fffb418 feat(bim): integrate selection sync and flight speed rail 2026-11-15 15:40:33 +03:00
DCCONSTRUCTIONS 6911da71d8 Integrate BIM material labels and canvas context menu fix 2026-11-15 15:10:05 +03:00
DCCONSTRUCTIONS 87c0c7960a Integrate BIM shared coordinates and layer placement tools 2026-11-15 14:44:48 +03:00
DCCONSTRUCTIONS b96bea1599 Integrate BIM 0.2.16 background checks and grouped glass panels 2026-11-15 13:45:17 +03:00
DCCONSTRUCTIONS 136be019af fix(bim): integrate surface picking and stable hierarchy viewer 2026-11-15 12:49:31 +03:00
DCCONSTRUCTIONS e8e450e93a fix(bim): integrate consistent keyboard navigation speed 2026-11-15 12:09:13 +03:00
DCCONSTRUCTIONS 28cb2e49a4 feat(bim): integrate surface pivot navigation and transparent dock resizing 2026-11-15 11:57:14 +03:00
DCCONSTRUCTIONS c6280525ba fix(bim): install keyboard-only viewport navigation 2026-11-15 11:14:36 +03:00
DCCONSTRUCTIONS 4002ae4c96 feat(bim): install source preflight and layout-independent viewport flight 2026-11-15 10:53:57 +03:00
DCCONSTRUCTIONS 71705ea862 Integrate BIM project uniqueness and shared content lifecycle 2026-11-15 10:29:45 +03:00
DCCONSTRUCTIONS 91a18c580a fix(bim): align upload bar and status in catalog and layers 2026-11-15 09:57:52 +03:00
DCCONSTRUCTIONS 8e37ef6968 feat(bim): integrate acknowledged upload pause and converter progress 2026-11-15 09:50:23 +03:00
DCCONSTRUCTIONS 1a0b5b0bd7 fix(bim): integrate whole-surface intake and background uploads 2026-11-15 09:07:23 +03:00
DCCONSTRUCTIONS d88ea2de93 feat(bim): integrate Worker point clouds and format downloads 2026-11-15 01:29:41 +03:00
DCCONSTRUCTIONS c785f1173f docs(bim): record lifecycle audit and multiuser readiness limits 2026-11-15 00:13:46 +03:00
DCCONSTRUCTIONS 1c092ff0e3 feat(bim): integrate portable viewport settings and shared screen picker 2026-11-15 00:01:32 +03:00
DCCONSTRUCTIONS f6e0bab559 Integrate BIM selection, cube settings and shared viewport refinements 2026-11-14 23:16:52 +03:00
DCCONSTRUCTIONS e8920f56a2 Integrate dockable BIM viewer, IFC hierarchy and scene tools 2026-11-14 22:16:11 +03:00
DCCONSTRUCTIONS 9937eb66d8 Integrate BIM entry hierarchy, durable retirement and viewport glass 2026-11-14 20:44:00 +03:00
DCCONSTRUCTIONS cd27a5e483 feat(bim): integrate portable IFC viewer, project map and prepared layers 2026-11-14 18:49:43 +03:00
DCCONSTRUCTIONS a49fb00b8e feat(routers): integrate Banana Pi Client API and onboard LibreSpeed measurements
Discover Ethernet routers under the board, map physical SIM slots, expose vendor controls and real telemetry, and provide packaged VPS speed tests with a live monochrome gauge. Enforce compact typography across Core and Node UI.
2026-11-11 23:53:46 +03:00
DCCONSTRUCTIONS 58ac9fe3d2 Assemble complete modular LAB recordings on Worker before readiness 2026-11-10 04:44:02 +03:00
DCCONSTRUCTIONS 800518ea80 Record cold-cache LAB playback acceptance and remaining producer integration 2026-11-10 03:23:43 +03:00
DCCONSTRUCTIONS 1317f78672 Restore complete LAB recordings from verified Worker publications 2026-11-10 03:23:20 +03:00
DCCONSTRUCTIONS a724a9796a docs(worker): qualify Wi-Fi result transfer and explicit range recovery 2026-11-10 02:29:07 +03:00
DCCONSTRUCTIONS 4d0306f353 docs(worker): record LTE telemetry acceptance and local LAB reuse 2026-11-10 02:07:12 +03:00
DCCONSTRUCTIONS 40872d3534 fix(system): keep network configuration in worker settings 2026-11-10 02:06:41 +03:00
DCCONSTRUCTIONS 1472926112 docs: record Ops reconciliation and remaining network acceptance plan 2026-11-10 01:17:10 +03:00
DCCONSTRUCTIONS e8025bc99f feat(system): add worker and VPS catalogs with guarded local removal 2026-11-10 01:11:24 +03:00
DCCONSTRUCTIONS ad5a929e06 feat(worker): supervise VPN connections and recover batched telemetry 2026-11-10 01:10:37 +03:00
DCCONSTRUCTIONS fe5900ff3b refactor(lab): move execution to Worker and manage replay and transfer lifecycles 2026-11-10 01:09:39 +03:00
DCCONSTRUCTIONS cd34b6ce1a fix(scene): persist editor and battery profiles in Core 2026-11-10 01:08:00 +03:00
DCCONSTRUCTIONS 7595bea07c fix(simulation): isolate semantics and correct clipping and orthographic LOD 2026-11-10 01:05:59 +03:00
DCCONSTRUCTIONS ab5766df6a Bound semantic worker storage and add verified evidence closeout 2026-11-07 18:53:56 +03:00
DCCONSTRUCTIONS 43148a8769 Bound semantic map publication and define experiment storage closeout 2026-11-07 17:31:06 +03:00
DCCONSTRUCTIONS 09c13a5c68 Retain imported originals on Worker before retiring Core staging 2026-11-07 16:45:17 +03:00
DCCONSTRUCTIONS b0332fa377 docs: preserve useful experiment history in Ops 2026-11-04 19:22:04 +03:00
DCCONSTRUCTIONS d5f35e4a74 feat(battery): support compact charge indicators and header offset 2026-11-04 18:18:33 +03:00
DCCONSTRUCTIONS 14e6426cd5 feat(scene-editor): duplicate independent materials with named copies 2026-11-04 18:18:33 +03:00
DCCONSTRUCTIONS f228b20c2b feat(battery): configure observatory indicator geometry and space design controls 2026-11-04 17:46:06 +03:00
DCCONSTRUCTIONS 55e1ab8d1c feat(scene-editor): share environment profiles and separate SOC material surfaces 2026-11-04 17:46:05 +03:00
DCCONSTRUCTIONS 5f8ed0d94c feat(battery-ui): integrate observatory detail, appearance controls and compact BMS hierarchy 2026-11-04 17:14:56 +03:00
DCCONSTRUCTIONS c9d79456ef feat(battery): add welded R05 frame and correct CATL enclosure labels 2026-11-04 17:14:56 +03:00
DCCONSTRUCTIONS 42213001ba feat(bms): add read-only diagnostics and guarded operating switch commands 2026-11-04 17:14:54 +03:00
DCCONSTRUCTIONS ab8e977f11 feat(node): add confirmed board shutdown with expiring commands 2026-11-04 15:52:46 +03:00
DCCONSTRUCTIONS f76928b606 feat(bms): collapse connection details and separate telemetry tiles 2026-11-04 15:48:01 +03:00
DCCONSTRUCTIONS df743a9f6c build(node): package NetBird and JK BMS with pinned shared UI sources 2026-11-04 00:43:00 +03:00
DCCONSTRUCTIONS f3d0c25ccd feat(bms): discover JK batteries and integrate read-only telemetry scenes 2026-11-04 00:43:00 +03:00
DCCONSTRUCTIONS 2f0a066dde feat(playcanvas): share dockable scene tools and persistent model editing 2026-11-04 00:42:59 +03:00
DCCONSTRUCTIONS 038337783f feat(k1): add USB networking, device management and acquisition recovery 2026-11-04 00:42:57 +03:00
DCCONSTRUCTIONS 14c3c7c2b6 feat(observatory): persist scene profiles and stable device view bindings 2026-11-04 00:42:56 +03:00
DCCONSTRUCTIONS b7b5ac9cf0 feat(semantics): version scene edits and refine paint geometry 2026-11-04 00:42:55 +03:00
DCCONSTRUCTIONS 7a3c3c00b3 feat(rerun): retain live playback and recover isolated viewer resources 2026-11-04 00:42:54 +03:00
DCCONSTRUCTIONS 669ada973f feat(node): expose fresh network interface and hardware status 2026-11-04 00:42:26 +03:00
DCCONSTRUCTIONS 2c0a10b687 feat(network): integrate NetBird clients, profiles and private backups 2026-11-04 00:42:25 +03:00
DCCONSTRUCTIONS 1e77b198cb fix(transport): recover rover feedback and retained WireGuard routes 2026-11-04 00:42:24 +03:00
DCCONSTRUCTIONS f4cdf3744a feat(ui): integrate fleet equipment and expanded workspace layouts
Compose expanded workspaces and fleet equipment through shared product controls. Integrate device surfaces and preserve the documented UI grammar.
2026-10-29 09:10:02 +03:00
DCCONSTRUCTIONS 755a124bd8 build(node): ship qualified installers with CAN maintenance and rollback
Publish qualified Node and device bundles through versioned installers. Coordinate CAN maintenance, dependency closure, retained rollback and packaging provenance.
2026-10-29 09:10:02 +03:00
DCCONSTRUCTIONS fa8bde584f feat(video): recover camera previews and reduce encoding and playout cost
Improve camera recovery, shared preview lifecycle and receiver playout diagnostics. Preserve qualified X4 runtime changes and restore async admission in loopback media tests.
2026-10-29 09:10:01 +03:00
DCCONSTRUCTIONS e06ff9a214 feat(fleet): add shared WireGuard profiles and bounded rover transport
Add portable shared WireGuard profiles while retaining Tailscale and Worker boundaries. Bound rover command/telemetry delivery, recovery and diagnostic capture across Core and Node.
2026-10-29 09:10:01 +03:00
DCCONSTRUCTIONS bec20d63e2 feat(monitor): keep operator telemetry live and retire local replicas
Keep operator monitoring in bounded live snapshots and provide scoped replica retirement. Update the board dashboard and retirement regressions.
2026-10-29 09:10:01 +03:00
DCCONSTRUCTIONS 7878937691 feat(viewer): unify spatial clipping, planning and observation surfaces
Share spatial clipping and height slices across live planning and recorded observations. Refine scene navigation, report serialization and viewer presentation.
2026-10-29 09:10:01 +03:00
DCCONSTRUCTIONS f48411f8fe feat(simulation): integrate infrastructure jobs and semantic scene editing
Integrate infrastructure preparation and qualified map delivery with local scenes. Add semantic editing, object provenance, survey caching and operator scene tools.
2026-10-29 09:10:01 +03:00
DCCONSTRUCTIONS 25dc0a1b44 feat(semantics): add portable annotation, learning and review contracts
Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
2026-10-29 09:10:00 +03:00
DCCONSTRUCTIONS 69dc566665 feat(research): preserve urban geometry pipelines and qualification suites
Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
2026-10-29 09:10:00 +03:00
DCCONSTRUCTIONS 5d56237124 feat(routers): add observed router inventory and scoped controls
Separate router discovery, evidence and authorized control from device runtime. Add Node/Core contracts and reusable operator surfaces.
2026-10-29 09:09:59 +03:00
DCCONSTRUCTIONS 8b210258ca feat(usb-can): add isolated adapter runtime and confirmed CAN transactions
Package the adapter SDK boundary and runtime lifecycle. Confirm admitted CAN transactions, bound retained data and test failure paths with synthetic hardware.
2026-10-29 09:09:59 +03:00
DCCONSTRUCTIONS f32c7b400b feat(vesc): extend motor diagnostics, configuration and transport recovery
Add firmware and extension catalogues, configuration transactions, sample review and QML diagnostics. Preserve explicit authority, bounded retries and stop recovery in motor transport.
2026-10-29 09:09:59 +03:00
DCCONSTRUCTIONS 115476d2e6 feat(sdk): add bounded media admission, diagnostics and H264 recovery
Introduce deadline-bound admission and common diagnostics for constrained links. Add H264 packetization, recovery and the measured two-thread veryfast encoder path.
2026-10-29 09:09:59 +03:00
DCCONSTRUCTIONS 70ef3f9f1c chore(storage): bound build retention, caches and test resources
Track build ownership, qualified pins and bounded cache/log lifecycles. Move Vite fixtures to a job-owned server helper and preserve private outputs outside Git.
2026-10-29 09:09:58 +03:00
DCCONSTRUCTIONS 55f64f195b Add vector infrastructure maps and persistent location experience 2026-10-10 14:35:50 +03:00
DCCONSTRUCTIONS e095a43f00 Restore collision layers in local route planner 2026-10-10 11:33:47 +03:00
DCCONSTRUCTIONS ac980912e0 Plan translation before choosing motion toward a local goal 2026-10-10 08:29:26 +03:00
DCCONSTRUCTIONS fe495fa302 Include SOG converter bootstrap chunk in cold project packages 2026-10-10 07:40:45 +03:00
DCCONSTRUCTIONS 670e8047b3 Advance passed advisory route joints from observed body progress 2026-10-10 06:48:19 +03:00
DCCONSTRUCTIONS 621023380a Keep detector planning reserve out of native body collision map 2026-10-10 06:13:32 +03:00
DCCONSTRUCTIONS 3657998f9d Measure advisory route progress beyond approximate joints 2026-10-10 05:38:35 +03:00
DCCONSTRUCTIONS b071c6131b Retain measured local intent support across range resampling 2026-10-10 05:17:03 +03:00
DCCONSTRUCTIONS 3735f21fc2 Prevent accumulated range sampling drift in observed passages 2026-10-10 05:02:18 +03:00
DCCONSTRUCTIONS 5a68240511 Batch exact ground support queries in the control loop 2026-10-10 04:57:32 +03:00
DCCONSTRUCTIONS d8c79a1134 Carry captured sensor range envelopes into navigation observations 2026-10-10 04:18:27 +03:00
DCCONSTRUCTIONS e1fa0f8e2d Admit observed crossing areas before the unknown-road planning boundary 2026-10-10 04:00:55 +03:00
DCCONSTRUCTIONS 18e6a0e971 Version urban lidar horizon and retain measured crossing exits 2026-10-10 03:50:39 +03:00
DCCONSTRUCTIONS 857bd1fc7b Keep live guarded path when a same-leg extension is rejected 2026-10-10 03:38:04 +03:00
DCCONSTRUCTIONS 6b656a8a57 Advance observed passage intent without repeated lateral retargeting 2026-10-10 03:07:54 +03:00
DCCONSTRUCTIONS f12f5e86c9 Keep through-travel heading at lateral local goals 2026-10-10 02:48:25 +03:00
DCCONSTRUCTIONS e3d116d5b0 Select urban passage intent from measured world geometry 2026-10-10 02:12:18 +03:00
DCCONSTRUCTIONS 7ee42c44f0 Retain observed passage intent through range crop changes 2026-10-10 01:42:04 +03:00
DCCONSTRUCTIONS d0f6c80ee2 Reconstruct crossing permission from observed approach geometry 2026-10-10 01:19:52 +03:00
DCCONSTRUCTIONS 04b940e8e1 Preserve native command ownership for a moving direction hint 2026-10-10 00:46:23 +03:00
DCCONSTRUCTIONS 41fa11e6c8 Keep advisory route joints directional and preserve observed clearance 2026-10-10 00:29:41 +03:00
DCCONSTRUCTIONS daabdb9450 Keep passage clearance tied to observed spatial geometry 2026-10-10 00:12:01 +03:00
DCCONSTRUCTIONS 8bd2a9967a Choose local passage centres before route guidance 2026-10-09 23:40:19 +03:00
DCCONSTRUCTIONS e61aa6da5f Admit observed crossing ground between zebra markings 2026-10-09 23:01:29 +03:00
DCCONSTRUCTIONS 60d660f447 Allow bounded physics catch-up beyond sensor acquisition overhead 2026-10-09 22:45:15 +03:00
DCCONSTRUCTIONS be5cc98d5c Include selected source LOD in Worker scene package 2026-10-09 22:28:06 +03:00
DCCONSTRUCTIONS 37d6f90456 Select complete source LOD explicitly and reject renderer allocation failures 2026-10-09 22:24:46 +03:00
DCCONSTRUCTIONS 16865574d0 Align Nav2 with physics time and preserve complete simulation scenes 2026-10-09 22:15:20 +03:00
DCCONSTRUCTIONS 3376b1a9e6 Keep local reroutes bound to original edges within simplified guidance 2026-10-09 20:43:44 +03:00
DCCONSTRUCTIONS b2faab8ada Preserve admitted command ownership across route path refinements 2026-10-09 20:37:04 +03:00
DCCONSTRUCTIONS 286e1fbf33 Keep local navigation on its path across goal refinements 2026-10-09 20:02:11 +03:00
DCCONSTRUCTIONS 4e84aad33f Complete local XY goals without artificial terminal rotations 2026-10-09 19:08:57 +03:00
DCCONSTRUCTIONS 70e47fc83b Allow observed detours to join advisory route segments 2026-10-09 18:43:54 +03:00
DCCONSTRUCTIONS b4dab01f2a Persist rover observation configuration and calibrate Insta360 panorama 2026-10-09 18:17:54 +03:00
DCCONSTRUCTIONS c43b097a3a Bound corridor ranking work and retire aborted local actions 2026-10-09 14:36:52 +03:00
DCCONSTRUCTIONS 25e8fb7e43 Look beyond short local goals and stabilize observed surface intent 2026-10-09 14:16:53 +03:00
DCCONSTRUCTIONS 35c1b88cd7 Keep clearance refresh bounded and preserve rear recovery observation 2026-10-09 13:29:20 +03:00
DCCONSTRUCTIONS ade3c19d2a Guide local goals around observed obstacles and finish native recovery 2026-10-09 13:06:04 +03:00
DCCONSTRUCTIONS 51406fc90c Separate Nav2 body collision from ground search costs 2026-10-09 12:22:26 +03:00
DCCONSTRUCTIONS 39dd3bb551 Separate forbidden ground from body collision and retain capture phase 2026-10-09 11:39:34 +03:00
DCCONSTRUCTIONS f449caa6e0 Publish fresh front perception before supplementary neural views 2026-10-09 10:56:08 +03:00
DCCONSTRUCTIONS 4153c122a3 perf(simulation): copy native ray hits without NumPy protocol probing 2026-10-09 10:21:22 +03:00
DCCONSTRUCTIONS 0fb9636683 fix(simulation): include native experience in runtime identity 2026-10-09 10:11:59 +03:00
DCCONSTRUCTIONS 5e2e0aa4d7 perf(simulation): push current previews and streamline native sensor startup 2026-10-09 10:09:59 +03:00
DCCONSTRUCTIONS c4d4ea4cf8 Measure Worker video delivery separately from simulation cadence 2026-10-09 09:33:52 +03:00
DCCONSTRUCTIONS c4622332e6 Reconsider transient native planner rejections after bounded backoff 2026-10-09 08:40:52 +03:00
DCCONSTRUCTIONS 8c520ba32e Bound urban route clearance preference and expose Nav2 costmap diagnostics 2026-10-09 07:48:20 +03:00
DCCONSTRUCTIONS a14158e483 Bind Nav2 route transitions to current observed body support
Return a separate positive-surface body receipt before reaching a guide vertex. Keep mission arrival and command admission independent, reject stale transaction reuse, and include the bridge helper in module identity. Validate the actual Nav2 plan entry with observed, unknown and obstructed support.
2026-10-08 23:54:38 +03:00
DCCONSTRUCTIONS 31b74e4571 Add prepared urban route guidance to Gaussian simulation planning
Introduce a content-bound scene route provider, advisory runtime graph and plan-preview-launch workflow. Preserve live sensing authority and retire blocked intermediate goals without discarding final-arrival evidence. Bound native visual context losslessly and provide verified cache relocation. Full Maroseyka route qualification remains open.
2026-10-08 23:42:26 +03:00
DCCONSTRUCTIONS 2e85d95c71 Prevent goal oscillation and unintended differential drive arcs 2026-10-08 21:14:12 +03:00
DCCONSTRUCTIONS 012286e972 Align native planning clearance and admit observed tracked pivots 2026-10-08 21:14:12 +03:00
DCCONSTRUCTIONS 7f87b5aa4d Optimize range clearing with equivalent early pixel rejection 2026-10-08 21:14:11 +03:00
DCCONSTRUCTIONS 9a2ea5fc2e perf(simulation): cache SAM3 text and retain exact perception evidence 2026-10-08 18:29:32 +03:00
DCCONSTRUCTIONS 021b9f427f fix(simulation): retire rejected Nav2 intermediate goals 2026-10-08 15:29:41 +03:00
DCCONSTRUCTIONS 1f1d4a2807 perf(simulation): reuse support surface within an observation 2026-10-08 15:14:14 +03:00
DCCONSTRUCTIONS bc915c01e1 fix(simulation): consume Nav2 local action completion 2026-10-08 14:00:54 +03:00
DCCONSTRUCTIONS 6a89f809a4 fix(simulation): bound Nav2 heading discretization by rover geometry
Use pinned Smac Hybrid with a geometry-derived angular grid so rectangular starts are not rejected by coarse lattice headings. Keep the full padded footprint, unknown-space veto, TTLs, and native controller/behavior ownership.

Validated on the same archived costmap, five native pass/block scenarios, HTTP/PCL/Nav2 lifecycle and rear-obstacle checks, and 12 CPU tests. Original-route live check moved 20.13 m before its fixed wall budget; the 30 m integration criterion and full-route acceptance remain open.
2026-10-08 13:07:24 +03:00
DCCONSTRUCTIONS 140b6002e0 Restore observed recovery through native Nav2 2026-10-08 11:11:12 +03:00
DCCONSTRUCTIONS 117e937906 Link project rules to the canonical Ops architecture record 2026-10-08 11:04:30 +03:00
DCCONSTRUCTIONS 8bf6571ce2 Keep operator telemetry live-only with bounded volatile state 2026-10-08 10:54:35 +03:00
DCCONSTRUCTIONS 15a60e7e31 chore: consolidate Mission Core workspace and bound local build storage 2026-10-08 10:22:16 +03:00
DCCONSTRUCTIONS d0e5f90952 Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
2026-10-08 09:59:51 +03:00
DCCONSTRUCTIONS 97614742bb Accept qualified ARNavi VPS 0.2.5 v1 compatibility contract 2026-10-01 14:38:42 +03:00
DCCONSTRUCTIONS a78fdeae66 Accept qualified ARNavi VPS 0.2.4 client contract 2026-10-01 09:13:14 +03:00
DCCONSTRUCTIONS b17ff5554e Preserve ARNavi full settings support through VPS 0.2.3 2026-10-01 01:07:13 +03:00
DCCONSTRUCTIONS 43b63e8eb9 Accept shared B2 VPS 0.2.1 for equipment settings and commands 2026-09-30 22:43:12 +03:00
DCCONSTRUCTIONS df36e92500 Accept ARNavi VPS 0.2.0 through the existing client contract 2026-09-30 15:34:24 +03:00
DCCONSTRUCTIONS 6dd652f71e Keep B2 client fixes and move VPS implementation to its standalone repository 2026-09-29 12:41:21 +03:00
DCCONSTRUCTIONS 03d44d0fb1 docs(handoff): record ARNavi cards, source revisions and closeout checks 2026-09-28 18:52:10 +03:00
DCCONSTRUCTIONS 21f46ac38a docs(arnavi): consolidate server and tracker handoff with qualification evidence 2026-09-28 18:44:50 +03:00
DCCONSTRUCTIONS 67ae1f4d77 feat(map): show independent tracker positions and recover unavailable layers 2026-09-28 18:44:18 +03:00
DCCONSTRUCTIONS 031e01a99b feat(ui): add tracker provisioning, SIM policies, command history and firmware archive 2026-09-28 18:44:18 +03:00
DCCONSTRUCTIONS f3a7592d90 feat(fleet): integrate independent trackers, VPS pairing and recoverable commands 2026-09-28 18:44:12 +03:00
DCCONSTRUCTIONS d684eb7e05 feat(vps): ship durable ARNavi host with reproducible install and recovery 2026-09-28 18:43:39 +03:00
DCCONSTRUCTIONS b6efae3272 feat(arnavi): add qualified B2 protocols, USB provisioning and SIM evidence 2026-09-28 18:43:32 +03:00
DCCONSTRUCTIONS fb33a6d45c fix(ui): label connectivity checks as Проверка состояния 2026-09-25 23:26:51 +03:00
DCCONSTRUCTIONS 0fb117fe7b docs: record worker recovery acceptance and deployment boundaries 2026-09-25 23:25:02 +03:00
DCCONSTRUCTIONS e2cf3078b6 fix(ui): unify connectivity labels and move contour refresh to header 2026-09-25 23:24:45 +03:00
DCCONSTRUCTIONS f3640026cf fix(telemetry): recover worker agent and Tailscale transport automatically 2026-09-25 23:24:27 +03:00
DCCONSTRUCTIONS bd5873ef34 fix(fleet): derive contour status from registered nodes and remove obsolete tabs 2026-09-25 22:28:42 +03:00
DCCONSTRUCTIONS aecae4a986 feat(fleet): edit apparatus name independently of onboard availability 2026-09-25 22:28:22 +03:00
DCCONSTRUCTIONS ee7576b7b4 refactor(fleet-ui): consolidate apparatus header and computer status 2026-09-25 21:58:57 +03:00
DCCONSTRUCTIONS e2b0d839eb feat(fleet-ui): organize apparatus equipment beneath its computer 2026-09-25 21:38:25 +03:00
DCCONSTRUCTIONS d2ec9e95b1 feat(fleet): replace onboard computer without replacing apparatus 2026-09-25 21:38:13 +03:00
DCCONSTRUCTIONS 8283f9ba85 feat(observation): expose offline sources with transparent viewport headers 2026-09-25 19:14:21 +03:00
DCCONSTRUCTIONS db3b1d7b67 fix(navigation): return repeated section selections to their entry view 2026-09-25 19:14:21 +03:00
DCCONSTRUCTIONS a993eda6b8 feat(rover): add live scene and material editing with environment migration 2026-09-25 19:13:52 +03:00
DCCONSTRUCTIONS 9d3329f608 docs: record rover integration closeout and verification 2026-09-25 16:49:52 +03:00
DCCONSTRUCTIONS 399af98841 merge: integrate final rover control with operator simulation workspace 2026-09-25 16:48:42 +03:00
DCCONSTRUCTIONS 71a648fec8 feat(fleet): preserve operator VESC integration before final driver merge 2026-09-25 16:40:46 +03:00
DCCONSTRUCTIONS dad11b47d7 docs(simulation): record polygon experiments and bounded route acceptance 2026-09-25 16:40:46 +03:00
DCCONSTRUCTIONS e627500295 feat(control-station): add AI polygon setup streaming and mission controls 2026-09-25 16:40:45 +03:00
DCCONSTRUCTIONS f01bd39037 feat(simulation): add Worker AI polygon runtime and terrain navigation 2026-09-25 16:40:45 +03:00
DCCONSTRUCTIONS a7c64e009d fix(core): keep launchd service logs outside protected Downloads 2026-09-25 16:40:45 +03:00
DCCONSTRUCTIONS 6bbbd5bf7d docs(rover): record calibration control acceptance and operating boundaries 2026-09-25 16:39:19 +03:00
DCCONSTRUCTIONS bc55901d4d fix(core): serialize planning reports outside the control event loop 2026-09-25 16:37:57 +03:00
DCCONSTRUCTIONS 6d772b29fe feat(control-station): add rover scene telemetry and guarded keyboard control 2026-09-25 16:37:57 +03:00
DCCONSTRUCTIONS 63cbb08ea0 feat(rover): add drive profiles and leased remote command channel 2026-09-25 16:37:56 +03:00
DCCONSTRUCTIONS 53818230f9 feat(node): ship managed environment startup and USB recovery 2026-09-25 16:37:56 +03:00
DCCONSTRUCTIONS 45fb14b206 feat(vesc): integrate native calibration diagnostics and configuration archives 2026-09-25 16:37:56 +03:00
DCCONSTRUCTIONS 24bbaefb00 chore(repo): keep private evidence local and version rover assets with LFS 2026-09-25 16:37:20 +03:00
DCCONSTRUCTIONS 2e5d52521f feat: finalize corrected-route planning and Rerun recording review 2026-09-22 10:10:03 +03:00
DCCONSTRUCTIONS c804d89b18 fix(lab): separate direct device launches from planning profiles 2026-09-21 09:19:14 +03:00
DCCONSTRUCTIONS 76dc9f19c9 chore: consolidate superseded experiment history into main
History-only merge: retain the original Node worktree snapshot 1c7dd29 without reverting its canonicalized implementation (63ea2be and subsequent main fixes). RAV004 commits 45019f8/cd16ea2/88e47fc and Gaussian commits 2ccf172/2e44e27 are patch-equivalent to commits already in main (verified with git cherry). The current source tree is intentionally unchanged; old snapshots remain reachable for audit.
2026-09-21 08:48:14 +03:00
DCCONSTRUCTIONS e515ab1b8c feat(planning): consolidate recorded-route localization and spatial scene
Preserve the completed teach-and-repeat laboratory stage: reference preparation, cascaded acquisition, local tracking and recovery, recording lifecycle, replay qualification, and persistent Rerun scene controls. Document the open grid-picking regression and Rerun upgrade contract. No autonomous driving or loop-closure optimization is claimed.
2026-09-21 08:47:19 +03:00
DCCONSTRUCTIONS 1c7dd29d8a chore(node): preserve pre-canonicalization experiment snapshot
Historical working copy retained for audit before consolidation into main. The canonicalized plugin architecture and later fixes already live in main; this snapshot is not a release or a request to restore obsolete source layout.
2026-09-21 08:45:34 +03:00
DCCONSTRUCTIONS be58d589e2 feat(fleet): add board observation center with live sources and maps
Add adaptive per-vehicle layouts, full-panel dragging, source controls and automatic preview recovery for RealSense, Insta360 X4 and XGRIDS K1 observation views. Integrate cached Cesium map layers through the private NAS gateway link, retain bounded sensor command receipts, and document validation and operational handoff.
2026-09-10 22:12:05 +03:00
DCCONSTRUCTIONS 5f75afb720 docs(node): record current handoff status and X4 acceptance boundaries 2026-09-10 16:39:29 +03:00
DCCONSTRUCTIONS 99f29218d7 feat(x4): add per-camera manual wake and hide power action when connected 2026-09-10 16:27:48 +03:00
DCCONSTRUCTIONS db14ee5435 Record repeatable X4 reconnect and prepare recovery cancellation test 2026-09-10 14:36:07 +03:00
DCCONSTRUCTIONS 81dd44906d Record first X4 USB reconnect and automatic preview acceptance 2026-09-10 14:28:34 +03:00
DCCONSTRUCTIONS d45b329de8 Add packaged per-camera X4 wake and preview recovery 2026-09-10 14:20:52 +03:00
DCCONSTRUCTIONS f164606828 Add bounded X4 Bluetooth wake and record Android recovery proof 2026-09-10 12:48:09 +03:00
DCCONSTRUCTIONS 556e376a62 Record X4 wake by short Power with USB retained and BLE discovery 2026-09-10 12:08:01 +03:00
DCCONSTRUCTIONS 1a2de8df65 Package bounded X4 BLE diagnostics and USB mode reader 2026-09-10 11:59:00 +03:00
DCCONSTRUCTIONS b536f0049a Document X4 Android reconnect protocol research and recovery options 2026-09-10 11:25:07 +03:00
DCCONSTRUCTIONS 3b85299fd9 Document X4 USB power limits from root hub diagnostics 2026-09-10 11:04:04 +03:00
DCCONSTRUCTIONS 505844adc3 Record failed X4 USB reconnect with preview stopped 2026-09-10 10:44:27 +03:00
DCCONSTRUCTIONS 89b0eeca3f Record automatic X4 USB mode and two-camera viewing confirmation 2026-09-10 10:27:40 +03:00
DCCONSTRUCTIONS 1488a46794 Document X4 USB mode recovery and verified video after restart 2026-09-10 10:09:29 +03:00
DCCONSTRUCTIONS e4339f4e88 Record B11 hardware acceptance and X4 USB reconnect failure 2026-09-10 09:47:34 +03:00
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
DCCONSTRUCTIONS d8cc5367c4 Package onboard K1 separately with a private portable installer 2026-09-07 11:43:24 +03:00
DCCONSTRUCTIONS 111fe3dcfb docs(k1): record Node 0.7.1 installation and acceptance boundaries 2026-09-07 10:57:56 +03:00
DCCONSTRUCTIONS 63ea2bed67 feat(k1): stabilize LAB bridge and isolate onboard device integration 2026-09-07 10:31:33 +03:00
DCCONSTRUCTIONS 020a878915 docs(node): reconcile release status and build provenance for 0.6.11 2026-09-06 01:39:02 +03:00
DCCONSTRUCTIONS 404285419f fix(sensors): align device lamp with identity and refresh to end 2026-09-06 01:18:47 +03:00
DCCONSTRUCTIONS ba0c948ca1 fix(node): show camera connectivity and remove company header marks 2026-09-06 01:05:19 +03:00
DCCONSTRUCTIONS 429b4681fe fix(node): use compact guideline copy and plain setup checkmarks 2026-09-06 00:44:23 +03:00
DCCONSTRUCTIONS 22d69107ba feat(node): push USB changes and preserve sensor setup across sessions 2026-09-06 00:24:48 +03:00
DCCONSTRUCTIONS a8647c4d87 fix(node): verify D455 access and share sensor progress and recording UI 2026-09-05 23:25:11 +03:00
DCCONSTRUCTIONS b1aaa40508 Add D455 sensor host and shared Node/Core preparation surface 2026-09-05 22:27:07 +03:00
DCCONSTRUCTIONS 3616acc648 fix(node): clear consumed invitations after confirmed pairing 2026-09-05 21:37:56 +03:00
DCCONSTRUCTIONS e82d012907 feat(node): pair onboard computers with the Core fleet through UI 2026-09-05 21:16:13 +03:00
DCCONSTRUCTIONS fc545f8440 docs(node): proceed to pairing with clean-install acceptance deferred 2026-09-05 20:31:43 +03:00
DCCONSTRUCTIONS a98ef339de fix(node): show completed setup checks with a timestamp 2026-09-05 20:11:17 +03:00
DCCONSTRUCTIONS 9062126913 fix(node): make environment progress readable from the desktop 2026-09-05 19:54:08 +03:00
DCCONSTRUCTIONS 59e14c5bc0 feat(node): configure system environment through the desktop workflow 2026-09-05 19:46:52 +03:00
DCCONSTRUCTIONS 15bb793e5e fix(node): restore Linux network inventory and expose read failures 2026-09-05 18:47:12 +03:00
DCCONSTRUCTIONS 79911eb316 feat(node): consolidate board system views and plan fleet pairing 2026-09-05 18:35:57 +03:00
DCCONSTRUCTIONS d696842f5d feat(node): package Ubuntu desktop setup and trusted access 2026-09-05 17:27:59 +03:00
DCCONSTRUCTIONS 57f2537af3 Document AI Inference architecture and freeze current baseline 2026-09-05 10:05:01 +03:00
DCCONSTRUCTIONS e56eb42507 docs: inventory Rerun customizations and upstream dependencies 2026-09-05 09:21:28 +03:00
DCCONSTRUCTIONS b2a1b23131 fix(observatory): preserve camera across follow transitions 2026-09-05 08:46:35 +03:00
DCCONSTRUCTIONS cada687173 feat(observatory): ship modular AI inference labs 2026-09-04 17:59:05 +03:00
DCCONSTRUCTIONS eff60e490a docs(observatory): record saved replay evidence and open visual gates 2026-09-03 13:24:32 +03:00
DCCONSTRUCTIONS 9db29bcdc6 feat(observatory): share native result replay and expose saved TGS layers 2026-09-03 13:23:56 +03:00
DCCONSTRUCTIONS 27979854a7 feat(observatory): cache sealed camera and TGS replay on Core 2026-09-03 13:15:07 +03:00
DCCONSTRUCTIONS 3ea8d987a7 docs(observatory): record real M49 publication and restart acceptance 2026-09-03 11:50:32 +03:00
DCCONSTRUCTIONS bd947b49f4 fix(observatory): preserve source identity on unchanged reindex 2026-09-03 11:43:03 +03:00
DCCONSTRUCTIONS 54c8d82884 ops(observatory): install exact recorded-progress agent layers 2026-09-03 11:22:03 +03:00
DCCONSTRUCTIONS bee8552003 feat(observatory): expose attempt-bound recorded progress 2026-09-03 11:17:56 +03:00
DCCONSTRUCTIONS 4e0565eb4b docs(observatory): refresh four-stage recorded-first roadmap 2026-09-03 10:35:48 +03:00
DCCONSTRUCTIONS 44afadb021 docs(observatory): record selector rules and local UI acceptance 2026-09-03 10:16:12 +03:00
DCCONSTRUCTIONS e436fb56d4 fix(observatory): offer only uncalculated profiles without completion badges 2026-09-03 10:16:01 +03:00
DCCONSTRUCTIONS c2710b55a7 docs(observatory): record cache activation and Docker memory recovery 2026-09-03 09:44:02 +03:00
DCCONSTRUCTIONS d777f3198b docs(observatory): record cache proof and pending activation 2026-09-03 09:15:12 +03:00
DCCONSTRUCTIONS 1e4ddc2cff feat(observatory): verify exact published result reuse 2026-09-03 09:14:54 +03:00
DCCONSTRUCTIONS 80fc0058cb docs(observatory): record claim-v3 repair and preserved queue history 2026-09-03 00:00:08 +03:00
DCCONSTRUCTIONS 43f1cdc862 fix(worker): preserve transport patch in Docker snapshot layers 2026-09-02 23:50:22 +03:00
DCCONSTRUCTIONS 0041e9fadb fix(worker): bind claim migration to the imported transport module 2026-09-02 23:45:06 +03:00
DCCONSTRUCTIONS cabd3081c7 fix(observatory): version non-binding idle claims and preserve grant history 2026-09-02 23:40:11 +03:00
DCCONSTRUCTIONS 049ed3eed4 docs(observatory): prioritize recorded laboratories and cached review before onboard profiles 2026-09-02 23:16:01 +03:00
DCCONSTRUCTIONS 35c1249631 fix(observatory): reject duplicate active portable computations atomically 2026-09-02 23:15:39 +03:00
DCCONSTRUCTIONS 941183d624 docs(perception): record TLS and direct TCP latency attribution 2026-09-02 22:40:08 +03:00
DCCONSTRUCTIONS 6af4c208ce test(perception): localize transport tails with bounded TLS record witnesses 2026-09-02 22:34:12 +03:00
DCCONSTRUCTIONS 75a5320756 docs(perception): record clock route A/B/A and continuous LAN canary 2026-09-02 22:14:58 +03:00
DCCONSTRUCTIONS 59a74a3677 test(perception): add bounded clock-only route and scheduler diagnostics 2026-09-02 21:57:02 +03:00
DCCONSTRUCTIONS 35d28418f3 docs(perception): record joint startup proof and remaining clock wait 2026-09-02 21:16:03 +03:00
DCCONSTRUCTIONS 48835a0499 fix(perception): require joint clock readiness before source activation 2026-09-02 21:03:33 +03:00
DCCONSTRUCTIONS 93ae1edbb4 docs(perception): record cross-host canary failure and joint startup gate 2026-09-02 20:44:08 +03:00
DCCONSTRUCTIONS 093df8b38f style(perception): format streaming lifecycle guards 2026-09-02 20:43:31 +03:00
DCCONSTRUCTIONS 35b6cd9e9e feat(perception): gate cross-host graph with acknowledged source clocks 2026-09-02 20:37:21 +03:00
DCCONSTRUCTIONS d80df61a7e docs(perception): record cross-host clock and control proof 2026-09-02 19:46:27 +03:00
DCCONSTRUCTIONS d7b8989e43 feat(perception): add scoped stream control and bounded clock observations 2026-09-02 19:41:43 +03:00
DCCONSTRUCTIONS 0cc6b96306 docs(perception): record full-graph network and recovery evidence 2026-09-02 19:05:13 +03:00
DCCONSTRUCTIONS 6469505c41 feat(perception): connect full graph to external streaming source and scene receiver 2026-09-02 19:04:41 +03:00
DCCONSTRUCTIONS 191612282b test(perception): record cross-host gRPC recovery and backpressure proof 2026-09-02 18:14:51 +03:00
DCCONSTRUCTIONS 0310592ee3 feat(perception): add bounded authenticated gRPC stream transport 2026-09-02 18:11:42 +03:00
DCCONSTRUCTIONS df0158e1ba docs(perception): record Worker observability repair and remaining stream gates 2026-09-02 17:40:45 +03:00
DCCONSTRUCTIONS 2ef8c08bf2 feat(perception): export bounded runtime observations outside heartbeat lane 2026-09-02 17:35:46 +03:00
DCCONSTRUCTIONS c570f7d938 fix(telemetry): restore worker agent delivery and truthful system status 2026-09-02 17:35:20 +03:00
DCCONSTRUCTIONS 03e8e71bea docs(perception): record host telemetry recovery and scoped inventory evidence 2026-09-02 16:56:22 +03:00
DCCONSTRUCTIONS 61cbdb30a0 feat(perception): connect scoped host telemetry to recoverable profile lifecycle 2026-09-02 16:50:57 +03:00
DCCONSTRUCTIONS e91721fe6a docs(perception): record full graph recovery and separate availability latency 2026-09-02 16:01:36 +03:00
DCCONSTRUCTIONS 70927ea585 feat(perception): resume full graph on fresh input without restarting models 2026-09-02 15:54:13 +03:00
DCCONSTRUCTIONS 03a7e730ae docs(perception): record recoverable input policy and decoder continuity proof 2026-09-02 15:33:53 +03:00
DCCONSTRUCTIONS c31c46caa5 feat(perception): preserve resident runtime across recoverable input gaps 2026-09-02 15:27:06 +03:00
DCCONSTRUCTIONS 06a66a3da8 docs(perception): record controller readiness boundary and fault evidence 2026-09-02 14:54:43 +03:00
DCCONSTRUCTIONS 92625bf48b feat(perception): gate streaming lifecycle on controller readiness 2026-09-02 14:49:36 +03:00
DCCONSTRUCTIONS b8ba0cae1e docs(perception): record exact parity and fixed-envelope IPC comparison 2026-09-02 14:28:58 +03:00
DCCONSTRUCTIONS f39f1ff0b6 perf(perception): borrow contiguous image buffers for local IPC 2026-09-02 14:20:39 +03:00
DCCONSTRUCTIONS 380b6eaba7 fix(perception): preserve quaternion alignment across binary ingress 2026-09-02 14:20:38 +03:00
DCCONSTRUCTIONS f6d73d8bfb docs(perception): record binary full-graph evidence and remaining gates 2026-09-02 14:02:28 +03:00
DCCONSTRUCTIONS 221e429c0a feat(perception): connect binary ingress to the supervised full graph 2026-09-02 13:53:25 +03:00
DCCONSTRUCTIONS a85aed2e03 docs(perception): record decoder parity and remaining full-graph bridge 2026-09-02 13:14:11 +03:00
DCCONSTRUCTIONS f102712f0b test(perception): verify incremental decoder parity and binary ingress on Worker 2026-09-02 13:07:33 +03:00
DCCONSTRUCTIONS 350366bae0 refactor(perception): decode bounded fMP4 without source file dependencies 2026-09-02 13:07:33 +03:00
DCCONSTRUCTIONS c23e86fd39 docs(perception): record bounded binary ingress evidence and remaining bridge 2026-09-02 12:37:25 +03:00
DCCONSTRUCTIONS 79ce55d197 test(perception): verify reuse of existing raw live ingress 2026-09-02 12:30:16 +03:00
DCCONSTRUCTIONS a937400942 test(perception): seal source end marker before IPC shutdown 2026-09-02 12:28:23 +03:00
DCCONSTRUCTIONS da60feff90 feat(perception): add bounded binary stream ingress 2026-09-02 12:21:25 +03:00
DCCONSTRUCTIONS 85349f42f9 docs(perception): record lifecycle ownership and expiry evidence 2026-09-02 12:05:00 +03:00
DCCONSTRUCTIONS ac69e3b444 test(perception): exercise lifecycle and lease loss in full profile 2026-09-02 11:55:57 +03:00
DCCONSTRUCTIONS 6acf468b25 feat(perception): fence streaming lifecycle with worker-local ownership 2026-09-02 11:55:56 +03:00
DCCONSTRUCTIONS d264cbce04 docs(perception): record stage-two scheduler and cell freshness proof 2026-09-02 11:03:26 +03:00
DCCONSTRUCTIONS 1f8101e4a5 feat(perception): expire costmap permissions per cell 2026-09-02 10:57:42 +03:00
DCCONSTRUCTIONS bcacb02a22 refactor(perception): share bounded streaming scheduler 2026-09-02 10:57:41 +03:00
DCCONSTRUCTIONS adcca7aa81 docs(perception): close stage-one baseline and record freshness proof 2026-09-02 10:21:44 +03:00
DCCONSTRUCTIONS 097e450a87 feat(perception): enforce six-layer freshness through receipt 2026-09-02 10:14:28 +03:00
DCCONSTRUCTIONS 4e633a662c docs(perception): record gpu clock latency proof 2026-09-02 09:42:40 +03:00
DCCONSTRUCTIONS c6c42c29e8 fix(perception): reject material ties and trace gpu pacing 2026-09-02 09:34:20 +03:00
DCCONSTRUCTIONS ce09d30c1a docs(perception): record latency and triton parity limits 2026-09-02 02:52:38 +03:00
DCCONSTRUCTIONS 34f13ba59e feat(perception): add bounded triton runtime diagnostics 2026-09-02 02:52:11 +03:00
DCCONSTRUCTIONS d9ea7c1129 perf(perception): reuse local surface cell observations 2026-09-02 02:03:09 +03:00
DCCONSTRUCTIONS a3c67e249c docs(perception): record rendezvous worker proof 2026-09-02 01:50:35 +03:00
DCCONSTRUCTIONS 294585936f fix(perception): rendezvous completed gpu handoff 2026-09-02 01:48:25 +03:00
DCCONSTRUCTIONS 380a13688c docs(perception): record preroll worker pilot 2026-09-02 01:40:06 +03:00
DCCONSTRUCTIONS fd8313899b fix(perception): separate preroll history from current sensor binding
Preserve rolling points and original clocks; expose per-modality ages, held pose and rejection reasons. Saved-lineage audit changes only the first admission (75 to 76 of 128). No new model/performance claim. 384 focused Python and 62 frontend tests passed.
2026-09-02 01:09:03 +03:00
DCCONSTRUCTIONS 05c99efb68 test(observatory): isolate legacy contracts from installed package pins
Freeze configuration-only legacy fixtures from 7025e17, update current installed-image assertions, and explicitly reject the prior agent image. Production admission and digest validation are unchanged.
2026-09-02 01:02:38 +03:00
DCCONSTRUCTIONS ffd6be5606 docs(observatory): record realtime plan and measured latency evidence 2026-09-02 00:59:48 +03:00
DCCONSTRUCTIONS bfe6ef4c77 feat(perception): add bounded full-graph streaming and latency pilots 2026-09-02 00:59:48 +03:00
DCCONSTRUCTIONS 4e04d06191 feat(perception): define stream-first profile and qualification contracts 2026-09-02 00:59:47 +03:00
DCCONSTRUCTIONS 5a78c997ac feat(observatory-ui): review portable results and retry publication
Checkpoint the existing generic result-viewing and publication lifecycle UI. Focused architecture and Observatory tests: 62 passed; no new visual changes or rebuild in this checkpoint.
2026-09-02 00:59:21 +03:00
DCCONSTRUCTIONS 62d5520c7a feat(worker): package independent installed LAB container steps
Preserve local installer, offline validation and pinned component adapters; 62 focused packaging tests pass. No deployment performed by this commit.
2026-09-02 00:58:51 +03:00
DCCONSTRUCTIONS a945d665dd feat(observatory): add installed package dispatch and durable publication
Checkpoint existing backend lifecycle changes. Focused verification found nine legacy fixture failures in portable LAB V1 executor/runtime tests; repair follows separately without rewriting this snapshot. ADR date retains its intentional Markdown hard break.
2026-09-02 00:58:37 +03:00
DCCONSTRUCTIONS d655d6998d feat(observatory): attest recording equipment and capture profiles 2026-09-02 00:57:27 +03:00
DCCONSTRUCTIONS 7025e173a3 fix(worker): accept omitted empty image command 2026-08-31 21:47:47 +03:00
DCCONSTRUCTIONS 10fe727561 fix(worker): preserve exec-form entrypoint 2026-08-31 21:45:51 +03:00
DCCONSTRUCTIONS 00ee5f163a fix(worker): keep commit labels shell-safe 2026-08-31 21:42:31 +03:00
DCCONSTRUCTIONS cbcc09afd6 fix(worker): mount generated shell scripts 2026-08-31 21:39:07 +03:00
DCCONSTRUCTIONS e958729e9d fix(worker): seal coordinator Python dependencies 2026-08-31 21:31:45 +03:00
DCCONSTRUCTIONS 0fcd037e4f fix(worker): compose staged source paths safely 2026-08-31 21:01:30 +03:00
DCCONSTRUCTIONS 11a146011f feat(worker): install combined observatory profiles 2026-08-31 20:56:29 +03:00
DCCONSTRUCTIONS 44ebbe7ca2 test(lab): import adapters in legacy runtimes 2026-08-31 20:04:31 +03:00
DCCONSTRUCTIONS a3299dcfc3 fix(lab): avoid runtime typing on Python 3.9 2026-08-31 20:01:49 +03:00
DCCONSTRUCTIONS 2989fba99c fix(lab): support legacy Python 3.9 adapters 2026-08-31 19:58:20 +03:00
DCCONSTRUCTIONS 142481f0d8 fix(lab): probe optional adapter image safely 2026-08-31 19:52:34 +03:00
DCCONSTRUCTIONS b2ae29b8d8 feat(lab): install thin adapter layers offline 2026-08-31 19:51:51 +03:00
DCCONSTRUCTIONS 8eced6c34d feat(worker): compose installed LAB V1 profile 2026-08-31 19:47:24 +03:00
DCCONSTRUCTIONS 732cc139fd refactor(worker): externalize runtime registries 2026-08-31 19:47:07 +03:00
DCCONSTRUCTIONS 104e54f4dd refactor(lab): separate release contract identity 2026-08-31 19:46:58 +03:00
DCCONSTRUCTIONS 7b021782d3 feat(lab): install sealed component adapters 2026-08-31 19:46:47 +03:00
DCCONSTRUCTIONS 759830b054 feat(lab): seal reusable EoMT runtime trees 2026-08-31 19:24:42 +03:00
DCCONSTRUCTIONS 19c0bd70d0 feat(lab): bind sealed component adapter images 2026-08-31 19:19:47 +03:00
DCCONSTRUCTIONS 35d99e40d5 perf(m49): verify source payloads during assembly 2026-08-31 19:06:59 +03:00
DCCONSTRUCTIONS bfc1f1bbed feat(worker): define unified agent image artifact 2026-08-31 19:00:06 +03:00
DCCONSTRUCTIONS f41428f907 feat(lab): add sealed local component runners 2026-08-31 18:59:47 +03:00
DCCONSTRUCTIONS 3744d79ad3 feat(lab): seal reusable ffmpeg runtime asset 2026-08-31 18:59:37 +03:00
DCCONSTRUCTIONS b57c3e94da perf(m49): defer fresh stage revalidation 2026-08-31 18:42:31 +03:00
DCCONSTRUCTIONS 73a7d28065 perf(lidar): avoid duplicate replay decode during build 2026-08-31 18:35:12 +03:00
DCCONSTRUCTIONS f64fbb1fa6 feat(worker): compose all ready observatory profiles 2026-08-31 18:31:54 +03:00
DCCONSTRUCTIONS 1ff527b264 perf(observatory): avoid duplicate camera verification 2026-08-31 18:25:09 +03:00
DCCONSTRUCTIONS def8c71410 perf(observatory): bound source destination planning 2026-08-31 18:19:04 +03:00
DCCONSTRUCTIONS 7e59176581 fix(observatory): disable source artifact compression 2026-08-31 18:05:34 +03:00
DCCONSTRUCTIONS 4cd94b5805 perf(observatory): pack camera epoch source transfer 2026-08-31 17:59:18 +03:00
DCCONSTRUCTIONS 1766c0bdb2 feat(observatory): reconcile quarantined recorded jobs 2026-08-31 17:59:03 +03:00
DCCONSTRUCTIONS 56bfeaee7b fix(observatory): admit camera archive metadata overhead 2026-08-31 17:19:45 +03:00
DCCONSTRUCTIONS 892d0085e3 refactor(worker): defer optional visualization imports 2026-08-31 17:15:13 +03:00
DCCONSTRUCTIONS e2de8188ab feat(observatory): bridge local M49 worker container 2026-08-31 16:58:03 +03:00
DCCONSTRUCTIONS 9c69d81296 feat(observatory): install local M49 worker path 2026-08-31 16:51:10 +03:00
DCCONSTRUCTIONS 2f6e45bc96 fix(observatory): validate M49 fixture filtering 2026-08-31 16:12:45 +03:00
DCCONSTRUCTIONS 8a1c578e0e fix(observatory): admit committed M49 executor candidates 2026-08-31 16:06:23 +03:00
DCCONSTRUCTIONS 9beb534108 feat(observatory): add portable calculation profiles 2026-08-31 15:42:56 +03:00
DCCONSTRUCTIONS d1b75efcea fix(observatory): fence portable catalog refresh 2026-08-31 11:11:36 +03:00
DCCONSTRUCTIONS c9302c78c2 feat(observatory): add portable LAB V1 foundation 2026-08-31 11:02:34 +03:00
DCCONSTRUCTIONS d67e86176e feat(observatory): add durable recorded compute queue 2026-08-31 01:04:25 +03:00
DCCONSTRUCTIONS e72609120f fix(observatory): align setup typography 2026-08-30 23:31:09 +03:00
DCCONSTRUCTIONS 177be8869f feat(local-service): allow exact worktree migration 2026-08-30 23:23:36 +03:00
DCCONSTRUCTIONS 2a5763d3fb feat(observatory): seal blocked run preparations 2026-08-30 23:14:05 +03:00
DCCONSTRUCTIONS 8d5aeb0533 feat(observatory): add laboratory setup preflight 2026-08-30 22:21:58 +03:00
DCCONSTRUCTIONS be83283ee0 fix(observatory): refine catalog and replay UX 2026-08-30 20:36:12 +03:00
DCCONSTRUCTIONS 023151c186 feat(observatory): admit canonical recorded replay 2026-08-30 19:21:27 +03:00
DCCONSTRUCTIONS e6a9846167 feat(observatory): add bounded M5.1 session review 2026-08-30 17:29:39 +03:00
DCCONSTRUCTIONS 81fdf6904a refactor(lab): объединить RAV004 в единый Rerun replay 2026-08-30 16:40:12 +03:00
DCCONSTRUCTIONS 9c5259dbc9 fix(lab): запускать RAV004 с первого кадра 2026-08-30 14:33:17 +03:00
DCCONSTRUCTIONS 35daf73d5c fix(lab): сжать и адресовать RAV004 overlay 2026-08-30 14:05:32 +03:00
DCCONSTRUCTIONS 07453142c2 fix(lab): стабилизировать нативный RAV004 replay 2026-08-30 13:28:33 +03:00
DCCONSTRUCTIONS f5ee42751d refactor(lab): перевести RAV004 на канонический Rerun pipeline 2026-08-30 12:59:16 +03:00
DCCONSTRUCTIONS e9ffb829c9 docs(sim): зафиксировать контур AI-улучшения гауссов 2026-08-30 11:57:49 +03:00
DCCONSTRUCTIONS 757d368c86 fix(lab): seal RAV004 spatial replay transport 2026-08-30 10:42:41 +03:00
DCCONSTRUCTIONS f1cbe0061a refactor(lab): restore canonical RAV004 replay 2026-08-30 01:22:44 +03:00
DCCONSTRUCTIONS 74da6437e9 refactor(lab): canonicalize recorded spatial replay 2026-08-29 23:38:17 +03:00
DCCONSTRUCTIONS bd2892140f fix(lab): enforce canonical replay runtime 2026-08-29 22:42:30 +03:00
DCCONSTRUCTIONS 525ab74168 fix(lab): restore canonical RAV004 replay 2026-08-29 21:08:49 +03:00
DCCONSTRUCTIONS c30d77572e fix(lab): restore canonical vegetation evidence layers 2026-08-29 20:33:52 +03:00
DCCONSTRUCTIONS 5179e93f4a fix(lab): restore canonical spatial replay 2026-08-29 19:52:06 +03:00
DCCONSTRUCTIONS c06b709fd7 refactor(viewer): profile rerun loading by playback stage 2026-08-29 17:46:07 +03:00
DCCONSTRUCTIONS 856b61be99 fix(simulation): standardize streamed rendering and UGV proxies 2026-08-29 17:39:40 +03:00
DCCONSTRUCTIONS 76694cc869 fix(simulation): reserve disk space before artifact import 2026-08-29 16:18:56 +03:00
DCCONSTRUCTIONS e6df8cb264 fix(simulation): retry temporary provider proxy failures 2026-08-29 16:01:28 +03:00
DCCONSTRUCTIONS 4b487e367f fix(simulation): retry builds across worker tunnel outages 2026-08-29 14:37:27 +03:00
DCCONSTRUCTIONS d7d9485724 fix(lab): overlay full route semantic masks 2026-08-29 14:19:32 +03:00
DCCONSTRUCTIONS 88e47fc39a fix(lab): overlay full route semantic masks 2026-08-29 14:14:38 +03:00
DCCONSTRUCTIONS 0a0cde7b0e fix(lab): keep full route result indexable 2026-08-29 13:54:40 +03:00
DCCONSTRUCTIONS cd16ea28a6 fix(lab): keep full route result indexable 2026-08-29 13:54:10 +03:00
DCCONSTRUCTIONS 9dec37a8a9 feat(lab): seal full RAVNOVES004TREE semantic review 2026-08-29 13:37:57 +03:00
DCCONSTRUCTIONS 45019f8952 feat(lab): seal full RAVNOVES004TREE semantic review 2026-08-29 13:36:37 +03:00
DCCONSTRUCTIONS 24b65926fe fix(simulation): hold ugv on sloped collision meshes 2026-08-29 12:41:28 +03:00
DCCONSTRUCTIONS 57dacc5a04 fix(simulation): model parked UGV tyre grip 2026-08-29 12:03:33 +03:00
DCCONSTRUCTIONS d9ec8c9cef fix(simulation): tune physical UGV braking 2026-08-29 11:26:01 +03:00
DCCONSTRUCTIONS af1e530162 feat(perception): add mixed-route vegetation review 2026-08-28 23:13:48 +03:00
DCCONSTRUCTIONS e10b96b546 feat(perception): split vegetation evidence layers 2026-08-28 15:37:10 +03:00
DCCONSTRUCTIONS a2c3385062 feat(simulation): auto-build source mesh collision 2026-08-28 13:46:55 +03:00
DCCONSTRUCTIONS 7fcfecd063 perf(perception): phase vegetation behind safety 2026-08-28 13:14:35 +03:00
DCCONSTRUCTIONS 7a3b0b84d0 perf(perception): split safety and vegetation rates 2026-08-28 12:59:34 +03:00
DCCONSTRUCTIONS e1c3e7e90a fix(perception): isolate vegetation qualification IO 2026-08-28 12:30:43 +03:00
DCCONSTRUCTIONS 14877b6683 fix(perception): validate decoded vegetation frames 2026-08-28 12:01:36 +03:00
DCCONSTRUCTIONS 0848cefc89 fix(perception): bound vegetation load decoding 2026-08-28 11:55:54 +03:00
DCCONSTRUCTIONS 722e60e5ef feat(simulation): add Gaussian UGV runtime pipeline 2026-08-28 11:50:47 +03:00
DCCONSTRUCTIONS c4c2392c79 feat(perception): integrate vegetation policy review 2026-08-28 11:22:00 +03:00
4012 changed files with 662281 additions and 12000 deletions
+8 -20
View File
@@ -193,7 +193,7 @@ The compact summary must cover:
- retained authority.
Keep manifests, long hashes, implementation files, validation logs, regressions,
rejected approaches, and next-stage planning in the Mission Core Ops report.
rejected approaches, and next-stage planning in local engineering evidence.
Do not expose roadmap steps, next-gate checklists, internal reason taxonomies,
debug controls, placeholder blocks, or implementation scaffolding in product
@@ -214,26 +214,14 @@ UI.
- Keep renderer colors semantic and token-derived. Never use them to invent
control states or persistent colored outlines.
## Ops report boundary
## Ops result boundary — owner revision, 2026-10-09
When the task includes reporting a completed LAB or architecture milestone, use
the direct `nodedc-ops-agent` tools and write titled structured blocks in this
order:
1. Objective and architecture stage.
2. Decision question and hypothesis.
3. Immutable source evidence and bounds.
4. Method, preprocessing, models, algorithms, tools, and identities.
5. Worker/runtime topology and resource policy.
6. Experimental implementation.
7. Validation and reproduced evidence.
8. Results.
9. Regressions, rejected approaches, and limitations.
10. Decision.
11. Next stage and forbidden authority.
12. Acceptance checker.
Do not turn the product UI into a duplicate Ops report.
Use the direct `nodedc-ops-agent` tools only for concise verified delivered
results: what works, what implementation is used, and the accepted scope.
Keep intermediate measurements, failed attempts, architecture proposals,
hypotheses and next-stage plans in local engineering evidence, not Ops.
Consolidate superseded intermediate blocks instead of appending a run diary.
Do not turn a partial experiment into a completed-product claim.
## Validation
+3
View File
@@ -10,3 +10,6 @@
*.las binary
*.lcc binary
apps/control-station/vendor/rerun-web-viewer-0.34.1/re_viewer_bg.nodedc.wasm filter=lfs diff=lfs merge=lfs -text
apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer_bg.nodedc.wasm filter=lfs diff=lfs merge=lfs -text
apps/control-station/public/rover-scene/*.glb filter=lfs diff=lfs merge=lfs -text
apps/control-station/public/battery-scene/*.glb filter=lfs diff=lfs merge=lfs -text
+10
View File
@@ -49,3 +49,13 @@ mqtt.summary.json
# Small synthetic/redacted fixtures under tests/fixtures are allowed.
!tests/fixtures/**/*.pcap
!tests/fixtures/**/*.pcapng
# Dependency caches may be links into an existing local checkout.
.venv
node_modules
# Private experiment evidence and generated build archives.
/outputs/
# Packaged WireGuard binaries are published artifacts, not source.
/apps/wireguard-client/build/
+262 -6
View File
@@ -5,6 +5,142 @@ real device plugin investigates an owner-controlled XGRIDS/LixelKity K1 as a
black-box sensor. Preserve the device, the host, the working LAN, raw evidence,
and the boundary between Mission Core and vendor-specific integration code.
- Owner clarification (2026-11-08): LAB trash means permanent deletion of that
LAB's admitted files on Core and Worker, followed by removal from history.
Do not replace it with catalog-only hiding or leave unreachable result bytes.
Source recordings and files shared by retained LABs are separate owners.
Worker acknowledgement is mandatory; on failure keep a retryable history row.
Local-copy expiry/delete is a separate action that preserves history and Worker
results. Pin protects against expiry, not explicit full-LAB deletion.
A LAB module/registered component, its model, benchmark and shared inputs are
not disposable run output. Missing UI history alone is never evidence of junk;
establish ownership and dependencies before retiring an old experiment.
## Single working directory — owner requirement, 2026-10-08
The governing Ops record is [MISSIONCOR-50 — Фундаментальная архитектура Mission Core](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-50),
in the owner rules dated 2026-10-08. The main [MISSIONCOR-1 architecture plan](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-1)
links to that record for monorepo, storage, resource and live-only telemetry rules.
- Keep exactly one Mission Core checkout on the operator Mac:
`NODEDC/NODEDC_MISSION_CORE`. Use commits and branches in that repository.
Do not create sibling clones, worktrees, baseline copies, or task-specific
Mission Core directories without a new explicit owner request.
- The canonical service on port 8000 and its LaunchAgent use this checkout.
Keep its existing runtime data under `.runtime/mission-core`; never merge
retired worktree application states into that live data directory.
- Keep private rover/CAD working materials under `private/engineering`,
local engineering reports under `outputs`, and simulation qualification
evidence under `.runtime/simulation-qualifications`. These are local data,
not source files to add to normal Git. Preserve unique evidence when moving
or retiring a workspace, and verify equality before removing duplicate files.
- Bound generated build storage. Retain the two most recent intermediate Linux
build-input packages per active build line; preserve separately designated
qualified releases and required rollback artifacts. Do not accumulate a new
full package after every iteration without retiring superseded intermediates.
- Build storage lifecycle is implemented by `scripts/packaging/build_retention.py`;
follow `docs/STORAGE_RETENTION.md`. New input generators return a persistent
active owner handle. After the remote job/transfer/qualification is confirmed
terminal, close only your own hold with `finish` (pin qualified/rollback
outcomes), review its plan and apply it as part of build completion. Never
expire active holds by age or declare unknown legacy inputs disposable.
- Node/X4 owner installers close out their exact unpacked `.deb` duplicates via
`scripts/packaging/qualified_payloads.py` after durable publication and full
hash verification. Keep the installer and `PAYLOAD_LOCATION.json`. Register a
persistent payload hold before a dependent consumer needs loose files; release
it only after that consumer ends. Read retired payloads through the helper,
not by leaving another permanent extracted copy. See `docs/STORAGE_RETENTION.md`.
- Run local Python validation through `scripts/check_python.py pytest|ruff|mypy`
(pass the usual file/selection arguments). It owns temporary caches, disables
persistent pytest/Ruff cache output, and cleans its own scratch after child
processes end. Never sweep another active job's cache or unknown crash residue.
- Runtime cache publication quotas and bounded service journals are defined in
`docs/STORAGE_RETENTION.md`. Existing replay/overlay data remains protected;
a full quota refuses a new copy rather than deleting recovery material.
- Check disk space before large builds or captures. Keep task scratch work
under `.runtime` and clean generated scratch at completion; do not scatter
temporary project folders through the parent repository directory.
- Owner amendment, 2026-10-19: completed simulation/urban-infrastructure
engineering experiments must not retain unlimited raw frames, render arrays
and step-by-step traces by default. At closeout preserve a compact textual
report, exact inputs/configuration/source identities, result/limitations and
regression evidence; archive text with verified hashes, then retire the
explicitly inventoried disposable derived files after all owners stop.
Use one content-addressed text copy for duplicates. Keep only the limited
visual evidence needed by the final report. Do not leave a complete new
media export after every iteration or require the owner to clean it manually.
This is a closeout obligation for engineering-owned scratch, not permission
to TTL-delete application runs, scans, accepted maps, working code, offline
dependencies, installers, qualified releases or pinned rollback. Unknown or
active ownership blocks removal; retain a deletion receipt and link the
archive from the report/Ops. See the amendment in docs/STORAGE_RETENTION.md.
- Other repositories, platform worktrees, infrastructure, DOC, workspace bridge,
Site/SEO, BIM Viewer, Device Core, Design Guideline, and Gaussian Pipeline are
separate ownership boundaries. Mission Core cleanup must not alter them.
- Operator telemetry is live-only: bounded latest values in RAM, expiry and a
daily reset. Do not reintroduce a local time-series database or persistent raw
monitoring history on the Mac. Diagnostic logs must rotate. Future historical
monitoring requires an explicitly provisioned separate service; simulation
evidence and recordings have a separate lifecycle and must not be deleted as
part of telemetry cleanup.
- Owner amendment, 2026-10-20: new semantic-learning images, observations,
datasets, checkpoints and heavy experiments belong to a separate portable
persistent store on Worker 006, outside the source checkout and container
writable layer. Never accumulate them on the operator Mac or add a local
fallback. Core may keep viewer scenes, semantic results and bounded edit
metadata. Saving an edit is not dataset preparation or training acceptance;
retain the immutable algorithm result and human provenance separately.
See `docs/SEMANTIC_EDITOR.md` for the delivered scope and outstanding gates.
## LAB placement — owner clarification, 2026-11-08
All supported laboratory execution, raw inputs, intermediate arrays and heavy
working directories belong to the portable Worker runtime. The operator Core is
a viewport: retain ready visual products, semantic maps/manual edits and bounded
metadata, never a silent local compute fallback. See
`docs/LAB_AND_INSTALLER_STORAGE.md` and `deploy/laboratory/README.md`.
Canonical Ops policy: [MISSIONCOR-97 — Storage rules](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-97).
Read its current rules before a new LAB/AI data producer or storage migration;
keep current implementation distinct from the dated distributed-storage research.
A LAB viewing result means a full playable recording with synchronized
segmentation/camera frames, 3D cuboids and timeline where the experiment provides
those layers. Catalog JSON, a screenshot or a textual report does not establish
playback acceptance. Preserve the current UI; do not add neural/narrative reports
or redesign LAB as part of storage migration. Later owner clarification on
8 November explicitly adds global Storage settings (configurable local LAB-copy
retention), offline pins, actual local availability and removal of local copies.
Run history must remain discoverable independently of replay compatibility or
local cache presence. These are requirements, not features already implemented
by the storage audit; see `outputs/storage-fresh-audit-20261108/REPORT.md`.
Verify real playback before retiring local working data; preserve accepted
recordings, Gaussians, semantic edits and original captures.
The configurable LAB-copy TTL (default 30 days) applies exclusively to unpinned
local viewing copies in Mission Core, never to Worker experiments or their models.
Integrated/experimental model assets, installed executor packages/images, runtime
environments and experimental configurations are retained until a separate owner
decision consolidates the pipeline, even under `cache` or `derived`. Do not apply
LAB-copy TTL or absence-from-UI cleanup to them. A disposable transport package
means job input/output transfer bytes, not an executor/model distribution. Before retiring an intermediate
copy, verify publication/retry readers, shared owners and restoration of its exact
identity. See the 8 November intermediate-store rules in
`docs/STORAGE_RETENTION.md` and `outputs/intermediate-storage-review-20261108/REPORT.md`.
Portable source/result transfer uses shared physical-disk reservations (2 GiB
free reserve), not fixed 8/4 GiB directory ceilings or model-count limits.
Source copies registered by admitted producers retire only after durable queue
consumers finish and exact originals remain available. HTTP reader locks span the
whole response. Preserve unknown paths, changed originals, shared filesystem
owners and pending publication/reconciliation. Source retirement is not a TTL.
Result closeout retains manifest/receipt for archive-backed retries; do not
readmit retired compute definitions merely to retire historical copies.
Use an explicit target allowlist for one-time historical cleanup and verify
unselected files; unknown old copies are not automatically adopted by a scan.
These rules do not change installed model/executor assets or viewing-copy TTL.
See the 9 November transfer lifecycle section of `docs/STORAGE_RETENTION.md`.
## Non-negotiable safety boundaries
- Default to non-mutating discovery or read-only operations. CoreBluetooth BLE
@@ -62,6 +198,58 @@ and the boundary between Mission Core and vendor-specific integration code.
- Synthetic or explicitly redacted fixtures may be committed under
`tests/fixtures/`.
## Onboard environment ownership — owner requirement, 2026-09-24
- Every onboard OS change belongs to the shipped, versioned installer or the
application's environment/device preparation workflow from the first test.
The operator installs the build and configures it in the application; never
require hand-written service files, USB rules, permission fixes or commands.
- This applies to all Node features, including GUI/service autostart and USB
recovery, not just individual camera drivers. Read-only SSH inspection and
bounded artifact-owned build staging remain allowed.
- Detect the distribution, architecture and required capabilities. Maintain
explicit supported environment profiles; do not claim arbitrary Linux
compatibility from a qualified Ubuntu build. Preserve foreign configuration,
report unsupported features, make preparation repeatable, and ship rollback.
- Do not add USB administration controls or port resets to inventory refresh.
Automatic startup recovery may retry terminal enumeration failures only;
preserve enumerated devices and active companion ports. Device identity and
assignments must survive changes of USB port and tty number.
## 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
Follow the gates in `docs/01_IMPLEMENTATION_PLAN.md`. Do not build heavy
@@ -121,7 +309,7 @@ decoders before BLE/Wi-Fi/data-session evidence exists.
canonical Design Guideline exports.
- Product UI must not expose implementation steps, roadmap gates, internal
reason taxonomies, debug controls, placeholder status blocks, or temporary
experiment scaffolding. Keep these in Ops, engineering reports, or developer
experiment scaffolding. Keep these in local engineering reports or developer
tooling.
- Extend one reusable application pattern instead of adding per-LAB layouts.
A new LAB supplies data and renderer configuration; it does not invent a new
@@ -158,11 +346,79 @@ decoders before BLE/Wi-Fi/data-session evidence exists.
- The compact summary must explain the decision question, immutable source,
tested method/models/algorithms, experimental mode, principal result,
limitations, and retained authority. It is not the engineering report.
- The complete engineering report belongs in the Mission Core Ops card as
titled structured blocks: objective and architecture stage, source evidence,
method/models/algorithms, worker/runtime, implementation, validation,
results, regressions and limitations, decision, next stage, and acceptance
checker.
- Owner reporting rule (2026-10-09), clarified 2026-11-04: keep current Ops
summaries concise and evidence-backed: what works, implementation and accepted
scope. Replace or remove obsolete assertions about the current state.
Preserve decision-relevant dated experiments: capability/limit findings, tested
alternatives and consequential failures that explain a decision or prevent
repeating a dead end. Keep the method/conditions, outcome, limitation, decision
and evidence reference separate from current state. Age alone does not make
useful evidence disposable. Do not retain every attempt, intermediate UI edit,
routine check or duplicate metric merely for history; consolidate nonessential
detail and keep traces local. A local backup alone does not preserve important
experiment findings in Ops. Annotate disproved interpretations without erasing
their observations; never invent why an untested option was rejected.
Raw logs/media, credentials and secret fields remain in private evidence;
proposals remain explicitly unverified. Never present a partial experiment as
a completed product result. Follow the ops-context skill for card updates.
- Spatial evidence uses 3D by default. Image-space reprojection may be offered
as a 2D diagnostic mode inside the same reusable viewer. Primary evidence
viewers must provide the canonical expand/restore action.
## Urban semantic agent contract — owner requirement, 2026-10-26
- Product foundation: read `docs/SCENE_SEMANTICS_PRODUCT_CONCEPT.md`. Each scan is
a standalone local scene, including unnamed/unmapped locations. Raw recorded
sensor points support localization; Gaussian observations support the current
semantic research. Never substitute Gaussian-derived geometry for raw points.
- No GPS/address/public-map prerequisite and no automatic cross-scan geographic
matching, overlap search, registration or merging. Those require a separate
explicit owner request. Named train/evaluation source lists do not authorize
geographic investigation. Preserve source lineage and evaluation honesty.
- Crosswalks are functionally important; the target includes all observed road
markings for scene context, interface/product value and difficult-task
validation. Do not reduce the scope to demo-only markings or crosswalks only.
- For automated infrastructure annotation, dataset preparation and learning,
begin with live Ops MISSIONCOR-93 (agent contract) and MISSIONCOR-88 (product),
then `docs/SEMANTIC_AGENT_OPERATING_CONTRACT.md`. Reuse the current hypothesis
register and existing experiments; a new chat does not reset the investigation.
- The owner explicitly requests MISSIONCOR-93 to hold current architecture,
rules, bounded next steps and portable handoff. This is the scoped exception
to the earlier delivered-results-only Ops rule. Keep raw logs/media in local
engineering evidence; update the current card blocks after meaningful changes.
- Root owns the useful outcome, real dispatch, integration and final decision.
Use one reusable critic and an optional bounded research scout, at most two
active helpers and no nested delegation. Send compact briefs, not full history.
- New annotation cycles use the v2 objective/dispatch contract. Approved partial
annotations are distinct from completing the enclosing product work package.
Handle introduced critical regressions within the session or revert/isolate
the change. Do not declare success merely because a ledger or test completed.
- Choose reusable pipelines against actual inputs/outputs and accumulated
evidence before narrow tuning. Every closed hypothesis states tested scope,
supporting artifacts and a substantive condition for reopening. Do not repeat
unchanged searches or model variants under a new name.
- Worker access/power/runtime authority comes from the owner's current session
instructions, never from the card or an old experiment's training allowance.
## Scene profile persistence — owner requirement, 2026-11-09
- Rover/battery materials, imported textures, scene/environment profiles, camera
pose, editor-window layout and battery UI/view settings are durable Core JSON
configuration. Use `data_dir/scene-profiles/.../meta.json`; never make browser
IndexedDB/localStorage their sole authority. Do not classify these files or
their recovery copies as cache or task scratch.
- Legacy browser records may be read once only when the Core document is absent.
A failed read must not save defaults over user settings. Preserve source data
during migration/recovery; use atomic replacement, previous-version backup and
revision checks so a stale tab cannot silently replace a newer profile.
- Recover actual settings from retained JSON/records before considering manual
reconstruction. Distinguish a proven storage defect from an unproven deletion
trigger, and state the timestamp/fidelity limit of any recovered source.
## Enforced compact typography
Operational values/section headings use md (13 px), explanatory/status/error copy uses Description/sm (12 px). Only canonical window/page title roles use title (18 px). Do not add browser-default paragraphs, local larger sizes, font shorthand or inline fontSize. Typography checks are mandatory build gates; never extend the frozen compact legacy baseline or generalize scene/display exceptions to satisfy a feature. Run the typography contract tests and verify computed sizes in centered/floating and narrow windows. See Design Guideline docs/OPERATIONAL_TYPOGRAPHY.md.
+30
View File
@@ -1,5 +1,10 @@
# NODEDC MISSION CORE
ARNavi B2 VPS server development moved to
[NODEDC_MISSION_CORE_ARNAVI-VPS](https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS).
Mission Core retains its B2 client and existing pairing; see the
[repository boundary](docs/arnavi_b2/VPS_REPOSITORY_SPLIT_20260929.md).
NODEDC MISSION CORE is the vendor-neutral control, observation, mission-planning,
recording, and integration platform for NODEDC autonomous systems. This
repository is the canonical early-stage monorepo: it contains the Mission Core
@@ -202,6 +207,12 @@ See [the Dataset Gateway plan](docs/14_LIDAR_DATASET_GATEWAY.md),
## Simulation Polygon
Current AI Polygon purpose, architecture, measured status and experiment plan:
[AI Polygon workflow](docs/AI_POLYGON_WORKFLOW.md), reconciled 2026-10-02.
It uses Isaac and shared AI modules entirely on Worker006, with operator video
on the Mac. The Gazebo/PX4 S0/S1 account below is a historical profile with its
own evidence; it must not be read as the current AI Polygon implementation.
Mission Core now has a parallel Polygon product branch for reproducible
autonomy qualification. Mission Core owns scenarios, qualification-run
lifecycle, authority, canonical contracts, provenance and reports; Gazebo, PX4
@@ -627,3 +638,22 @@ Real captures, projects, router metadata, serials, credentials, maps, images,
and logs under `.runtime/`, canonical evidence roots and legacy `sessions/` are
ignored by normal Git. Redacted manifests and SHA-256 inventories are committed;
encrypted/replicated artifact storage remains a deployment decision.
## Local working directory
The operator installation uses one checkout, `NODEDC_MISSION_CORE`, including
the service on `http://127.0.0.1:8000`. Work on source through commits and branches
in this checkout; do not create sibling Mission Core worktrees or project copies.
- `.runtime/mission-core`: existing application data and location registry.
- `.runtime/simulation-qualifications`: preserved simulation runs and evidence.
- `private/engineering`: private DCD-006, camera-mount and K1 modelling materials.
- `outputs`: local engineering reports and retained task outputs.
- `.runtime/archived-app-state`: retired worktree data, separate from live state.
The 2026-10-08 consolidation preserved the operator sources in
`archive/operator-before-consolidation-20261008` and the separate unfinished
simulation sources in `work/simulation-before-consolidation-20261008`.
These are source-preservation branches, not additional accepted deployments.
The local move, hash-verification and cleanup receipts are retained under
`.runtime/consolidation-20261008`. No remote branches were changed.
+1
View File
@@ -0,0 +1 @@
@nvidia:registry=https://edge.urm.nvidia.com/artifactory/api/npm/omniverse-client-npm/
+81 -10
View File
@@ -10,17 +10,21 @@
"hasInstallScript": true,
"dependencies": {
"@noble/hashes": "^2.2.0",
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.86.tgz",
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
"@nodedc/ui-core": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/ui-core",
"@nodedc/ui-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/ui-react",
"@rerun-io/web-viewer": "0.34.1",
"@nvidia/ov-web-rtc": "6.7.0",
"@rerun-io/web-viewer": "0.36.3",
"meshoptimizer": "1.1.1",
"playcanvas": "2.21.4",
"polygon-clipping": "0.15.7",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"three": "0.185.1"
"three": "0.185.1",
"three-mesh-bvh": "0.9.15"
},
"devDependencies": {
"@types/node": "^24.0.0",
@@ -38,9 +42,9 @@
},
"../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react": {
"name": "@nodedc/map-cesium-react",
"version": "0.1.0",
"version": "0.1.4",
"dependencies": {
"cesium": "1.143.0"
"cesium": "1.147.0"
},
"devDependencies": {
"@types/react": "^19.1.0",
@@ -60,19 +64,19 @@
},
"../../../NODEDC_DESIGN_GUIDELINE/packages/ui-core": {
"name": "@nodedc/ui-core",
"version": "0.7.0",
"version": "0.7.4",
"dependencies": {
"@nodedc/tokens": "0.6.0"
}
},
"../../../NODEDC_DESIGN_GUIDELINE/packages/ui-react": {
"name": "@nodedc/ui-react",
"version": "0.7.0",
"version": "0.7.10",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@nodedc/ui-core": "0.7.0",
"@nodedc/ui-core": "0.7.4",
"lucide-react": "^0.468.0"
},
"devDependencies": {
@@ -879,6 +883,17 @@
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@nodedc/bim-viewer": {
"version": "0.2.86",
"resolved": "file:../../vendor/bim/nodedc-bim-viewer-0.2.86.tgz",
"integrity": "sha512-1yaWhAbEx3Y1V93b+T1HKfra7Z6hGpFL/Fhz/S6Bi+AzFMEJsQ4TpE32uVIARxN6EWJtAx3QuBlmaD8TP499IQ==",
"peerDependencies": {
"@nodedc/map-cesium-react": ">=0.1.4 <0.2",
"@nodedc/ui-react": ">=0.7.10 <0.8",
"react": ">=19 <20",
"react-dom": ">=19 <20"
}
},
"node_modules/@nodedc/map-cesium-react": {
"resolved": "../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
"link": true
@@ -899,10 +914,23 @@
"resolved": "../../../NODEDC_DESIGN_GUIDELINE/packages/ui-react",
"link": true
},
"node_modules/@nvidia/ov-web-rtc": {
"version": "6.7.0",
"resolved": "https://edge.urm.nvidia.com/artifactory/api/npm/omniverse-client-npm/@nvidia/ov-web-rtc/-/@nvidia/ov-web-rtc-6.7.0.tgz",
"integrity": "sha512-Knt393yvuI1tFmQgJM7VuMlVKDh5GyuKq8fAIarNLyY7Ucxw+lSY/72ceWR+3HyCnNtL39J0DZ27dn9riqpGWw==",
"license": "SEE LICENSE IN LICENSE.txt",
"dependencies": {
"is-plain-object": "^5.0.0"
},
"engines": {
"node": ">=20.0.0",
"npm": ">=10.0.0"
}
},
"node_modules/@rerun-io/web-viewer": {
"version": "0.34.1",
"resolved": "https://registry.npmjs.org/@rerun-io/web-viewer/-/web-viewer-0.34.1.tgz",
"integrity": "sha512-2Oq9Mw3qOs765XArGq4e/0pAIksPFKlAqkgo+PDsRkPd77/KdnQhb835suRmYQ6tuqlbPeVCFhlNIXT0+TjmTg==",
"version": "0.36.3",
"resolved": "https://registry.npmjs.org/@rerun-io/web-viewer/-/web-viewer-0.36.3.tgz",
"integrity": "sha512-LMGnsxRmY5UwiGras2dZrMnEYkow5Xr4v+1hAUSspXWPPiilMqoz9G77jo8Ps/deAaX81TnOq123DFO8iX/Ulw==",
"license": "MIT"
},
"node_modules/@rolldown/pluginutils": {
@@ -1615,6 +1643,15 @@
"node": ">=6.9.0"
}
},
"node_modules/is-plain-object": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.1.0.tgz",
"integrity": "sha512-bUi/yjmtKYcRVUtWRGr0UA6xEFh2I6zWUwMrUXB3s7bmYCaZ8a+0ZsTRkrawh/mzlSD1Y0Ph8bp/U+TvBpWDNw==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@@ -1733,6 +1770,16 @@
"node": ">=18.3.0"
}
},
"node_modules/polygon-clipping": {
"version": "0.15.7",
"resolved": "https://registry.npmjs.org/polygon-clipping/-/polygon-clipping-0.15.7.tgz",
"integrity": "sha512-nhfdr83ECBg6xtqOAJab1tbksbBAOMUltN60bU+llHVOL0e5Onm1WpAXXWXVB39L8AJFssoIhEVuy/S90MmotA==",
"license": "MIT",
"dependencies": {
"robust-predicates": "^3.0.2",
"splaytree": "^3.1.0"
}
},
"node_modules/postcss": {
"version": "8.5.19",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.19.tgz",
@@ -1793,6 +1840,12 @@
"node": ">=0.10.0"
}
},
"node_modules/robust-predicates": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz",
"integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==",
"license": "Unlicense"
},
"node_modules/rollup": {
"version": "4.62.2",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz",
@@ -1864,12 +1917,30 @@
"node": ">=0.10.0"
}
},
"node_modules/splaytree": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/splaytree/-/splaytree-3.2.3.tgz",
"integrity": "sha512-7OXrNWzy6CK+r7Ch9OLPBDTKfB6XlWHjX4P0RU5B3IgFuWPeYN0XtRtlexGRjgbQxpfaUve6jTAwBGWuGntz/w==",
"license": "MIT",
"engines": {
"node": ">=18.20 || >=20"
}
},
"node_modules/three": {
"version": "0.185.1",
"resolved": "https://registry.npmjs.org/three/-/three-0.185.1.tgz",
"integrity": "sha512-5aojFCXKwnjBRZvUnt3WFfEcvUJgkN5LlijRFN95hMy8WVkG4I0QNcJE+OuWvuJ0bOdStrbfXn0pkd6/QyiAlg==",
"license": "MIT"
},
"node_modules/three-mesh-bvh": {
"version": "0.9.15",
"resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.9.15.tgz",
"integrity": "sha512-9xdEDkCzFoT8VPFH9DznwFSdbaIEjMvM106Iqq7TJurrIheUKDcdW4prfJTCxryih4XS/UxWs0H3K4MLMRFyOQ==",
"license": "MIT",
"peerDependencies": {
"three": ">= 0.159.0"
}
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+11 -5
View File
@@ -4,26 +4,32 @@
"private": true,
"type": "module",
"scripts": {
"postinstall": "node scripts/patch-rerun-web-viewer.mjs",
"dev": "vite",
"postinstall": "node scripts/install-rerun-navigation.mjs",
"prebuild": "npm run check:typography && node scripts/install-rerun-navigation.mjs",
"build": "tsc -b && vite build",
"preview": "vite preview",
"test:unit": "node --test test/*.test.mjs",
"typecheck": "tsc -b --pretty false"
"test:unit": "node --test --test-concurrency=1 test/*.test.mjs",
"typecheck": "tsc -b --pretty false",
"check:typography": "node --test test/operationalTypography.test.mjs"
},
"dependencies": {
"@noble/hashes": "^2.2.0",
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.86.tgz",
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
"@nodedc/ui-core": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/ui-core",
"@nodedc/ui-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/ui-react",
"@rerun-io/web-viewer": "0.34.1",
"@nvidia/ov-web-rtc": "6.7.0",
"@rerun-io/web-viewer": "0.36.3",
"meshoptimizer": "1.1.1",
"playcanvas": "2.21.4",
"polygon-clipping": "0.15.7",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"three": "0.185.1"
"three": "0.185.1",
"three-mesh-bvh": "0.9.15"
},
"devDependencies": {
"@types/node": "^24.0.0",
Binary file not shown.
@@ -0,0 +1,132 @@
{
"source": "CATL_Battery_Enclosure_R05.blend",
"source_sha256": "8a3da0abaeeabc3a006dec51e2ae5a1af8af56b3b1361772279d7766084faea3",
"model": "catl-r04.glb",
"sha256": "7a01c35d7b8fac13e841053841e372170715c7b79b865f8719ab137b24d5cd20",
"bytes": 39916192,
"groups": 75,
"cell_bodies": 13,
"objects": [
"bms/Cable / red silicone",
"bms/Cable / graphite silicone",
"bms/Mount / G10 dielectric",
"bms/Nickel plated copper / busbars",
"bms/Sense / warm yellow",
"bms/labels/electronics",
"bms/Connector / ivory polymer",
"bms/BMS / green PCB",
"bms/Aluminium / satin",
"bms/Lid / insulating black",
"bms/Mount / adhesive film",
"bms/Steel / fasteners",
"bms/cells/C01",
"bms/Cell / wrapped lower edge",
"bms/labels/cells",
"bms/cell-display/C01",
"bms/cells/C02",
"bms/cell-display/C02",
"bms/cells/C03",
"bms/cell-display/C03",
"bms/cells/C04",
"bms/cell-display/C04",
"bms/cells/C05",
"bms/cell-display/C05",
"bms/cells/C06",
"bms/cell-display/C06",
"bms/cells/C07",
"bms/cell-display/C07",
"bms/cells/C08",
"bms/cell-display/C08",
"bms/cells/C09",
"bms/cell-display/C09",
"bms/cells/C10",
"bms/cell-display/C10",
"bms/cells/C11",
"bms/cell-display/C11",
"bms/cells/C12",
"bms/cell-display/C12",
"bms/cells/C13",
"bms/cell-display/C13",
"bms/CASE | bead-blasted graphite/CASE | base tray",
"bms/CASE | bead-blasted graphite/CASE | front endplate",
"bms/CASE | bead-blasted graphite/CASE | rear endplate",
"bms/glass/CASE | removable solid top",
"bms/glass/CASE | slotted side -1",
"bms/glass/CASE | slotted side 1",
"bms/R04 | elastomer seal",
"bms/R04 | graphite moulded polymer",
"bms/labels/enclosure",
"bms/R04 | smoked polycarbonate",
"bms/R04 | display protective polycarbonate",
"bms/DISPLAY | black glass",
"bms/CASE | recessed black",
"bms/CASE | darker frame",
"bms/FRAME | welded graphite steel/FRAME | bottom cross front",
"bms/FRAME | welded graphite steel/FRAME | bottom cross rear",
"bms/FRAME | welded graphite steel/FRAME | bottom longitudinal left",
"bms/FRAME | welded graphite steel/FRAME | bottom longitudinal right",
"bms/FRAME | welded graphite steel/FRAME | post front left",
"bms/FRAME | welded graphite steel/FRAME | post front right",
"bms/FRAME | welded graphite steel/FRAME | post rear left",
"bms/FRAME | welded graphite steel/FRAME | post rear right",
"bms/FRAME | welded graphite steel/FRAME | top cross front",
"bms/FRAME | welded graphite steel/FRAME | top cross rear",
"bms/FRAME | welded graphite steel/FRAME | top longitudinal left",
"bms/FRAME | welded graphite steel/FRAME | top longitudinal right",
"bms/CASE | bead-blasted graphite/HANDLE | folded aperture return",
"bms/CASE | bead-blasted graphite/HANDLE | folded aperture return.001",
"bms/CASE | bead-blasted graphite/HANDLE | integral web underside",
"bms/CASE | dielectric liner",
"bms/CASE | dielectric liner/left",
"bms/CASE | dielectric liner/right",
"bms/Connector / gold plated contacts",
"bms/XT90-S / anti spark green insert",
"bms/XT90-S / yellow PA housing"
],
"materials": [
"bms/Cable / red silicone",
"bms/Cable / graphite silicone",
"bms/Mount / G10 dielectric",
"bms/Nickel plated copper / busbars",
"bms/Sense / warm yellow",
"bms/labels",
"bms/Connector / ivory polymer",
"bms/BMS / green PCB",
"bms/Aluminium / satin",
"bms/Lid / insulating black",
"bms/Mount / adhesive film",
"bms/Steel / fasteners",
"bms/cells",
"bms/Cell / wrapped lower edge",
"bms/cell-display/C01",
"bms/cell-display/C02",
"bms/cell-display/C03",
"bms/cell-display/C04",
"bms/cell-display/C05",
"bms/cell-display/C06",
"bms/cell-display/C07",
"bms/cell-display/C08",
"bms/cell-display/C09",
"bms/cell-display/C10",
"bms/cell-display/C11",
"bms/cell-display/C12",
"bms/cell-display/C13",
"bms/CASE | bead-blasted graphite",
"bms/glass",
"bms/R04 | elastomer seal",
"bms/R04 | graphite moulded polymer",
"bms/R04 | smoked polycarbonate",
"bms/R04 | display protective polycarbonate",
"bms/DISPLAY | black glass",
"bms/CASE | recessed black",
"bms/CASE | darker frame",
"bms/FRAME | welded graphite steel",
"bms/CASE | dielectric liner",
"bms/Connector / gold plated contacts",
"bms/XT90-S / anti spark green insert",
"bms/XT90-S / yellow PA housing"
],
"cell_displays": 13,
"uv": "cube_projection; original cell display faces use planar X/Z UV",
"source_modified": false
}
@@ -0,0 +1,174 @@
{
"schema_version": "missioncore.rover-motion/v1",
"source_scene": "DCD-006_rover_v020.blend",
"source_sha256": "c49a0470974bbe65b4e65b4b5c06cb887730715a1ddfa231b86426fed6de8f79",
"source_saved": false,
"visual_sha256": "4a3892f019b29a40b95ca302e3411053d9532da21e571ff190aeda76bf83836e",
"forward_axis": "+X",
"up_axis": "Y",
"track_centres_m": {
"L": 0.3425,
"R": -0.3425
},
"track_width_m": 0.685,
"shift_m": [
-0.05350000038743019,
0.0,
0.0
],
"length_m": 2.222,
"pitch_m": 0.0505,
"phase_m": 0.03069696662739778,
"segments": [
[
"arc",
0,
0.060539054924808725,
[
-0.16593354688111153,
0.32184557191629776,
0.0655,
2.3390854961098873
]
],
[
"line",
0.060539054924808725,
0.5760464371429339,
[
-0.15575880346026824,
0.3865504758751169,
0.9878611291422765,
-0.1553395942113481,
0.15533959421134813,
0.9878611291422766
]
],
[
"arc",
0.6365854920677426,
0.15172294911931034,
[
0.40182697,
0.22413776,
0.07382606110411796,
1.4148251155784564
]
],
[
"line",
0.7883084411870529,
0.1629407568053742,
[
0.46102862009488454,
0.18003048254840684,
-0.5974486081464921,
-0.8019072020027126,
0.8019072020027126,
-0.5974486081464921
]
],
[
"arc",
0.9512491979924271,
0.06094648310379254,
[
0.31115497,
0.0885,
0.0655,
-0.6403156687217281
]
],
[
"line",
1.0121956810962196,
0.7185584980197575,
[
0.31115497,
0.022999999999999993,
-1.0,
0.0,
-0.0,
-1.0
]
],
[
"arc",
1.730754179115977,
0.15545137821999958,
[
-0.40740352801975754,
0.0885,
0.0655,
-1.5707963267948966
]
],
[
"line",
1.8862055573359766,
0.33579444266402353,
[
-0.45291987081346463,
0.1356010885085021,
0.719100587916063,
0.6949059968504895,
-0.6949059968504895,
0.719100587916063
]
]
],
"link_count": 44,
"wheels": [
{
"node": "R_SPIN_rear_lower",
"radius_m": 0.0625
},
{
"node": "R_SPIN_middle_lower",
"radius_m": 0.0625
},
{
"node": "R_SPIN_rear_upper",
"radius_m": 0.0625
},
{
"node": "R_SPIN_front_lower",
"radius_m": 0.0625
},
{
"node": "R_SPIN_DRIVE",
"radius_m": 0.07233592163526643
},
{
"node": "L_SPIN_rear_lower",
"radius_m": 0.0625
},
{
"node": "L_SPIN_middle_lower",
"radius_m": 0.0625
},
{
"node": "L_SPIN_rear_upper",
"radius_m": 0.0625
},
{
"node": "L_SPIN_front_lower",
"radius_m": 0.0625
},
{
"node": "L_SPIN_DRIVE",
"radius_m": 0.07233592163526643
}
],
"dimensions_m": [
1.1630001068115234,
0.9049999713897705,
0.7378441095352173
],
"minimum_m": [
-0.5814999938011169,
-0.45249998569488525,
-0.003844098187983036
],
"method": "44 rigid visual pitches per belt; rolling assemblies retain original CAD pivots; no track contact dynamics"
}
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 251 KiB

+30
View File
@@ -0,0 +1,30 @@
# Panorama optical conventions
`frontend/src/panoramaCalibration.ts` adapts calibration layouts and projection
conventions from [GyroView](https://github.com/bubo-squared/GyroView), revision
`ae5c22b155ab4ec9c28d141e61340ca2d6f94994`. This is not Insta360 Media SDK.
Legacy radius angles, polynomial normalization and lens-pose signs are
open-source interpretations; they require qualification on the actual live camera.
No GyroView application, recording parser or dependency tree is included.
MIT License
Copyright (c) 2026 Bubo²
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Синхронизированная запись</title>
<style>
html, body, #viewer { width: 100%; height: 100%; margin: 0; overflow: hidden; }
canvas { display: block; }
</style>
</head>
<body>
<div id="viewer"></div>
<script type="module" src="/src/components/rerun/isolatedRerunEntry.ts"></script>
</body>
</html>
@@ -0,0 +1,79 @@
import { createHash } from "node:crypto";
import { readFileSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const packageRoot = resolve(root, "node_modules/@rerun-io/web-viewer");
const vendorRoot = resolve(root, "vendor/rerun-web-viewer-0.36.3");
const manifest = JSON.parse(readFileSync(resolve(vendorRoot, "navigation-build.json"), "utf8"));
const installed = JSON.parse(readFileSync(resolve(packageRoot, "package.json"), "utf8"));
const sha = bytes => createHash("sha256").update(bytes).digest("hex");
if (installed.version !== "0.36.3" || manifest.upstreamVersion !== installed.version) {
throw new Error("Rerun navigation requires the audited 0.36.3 package; rebase before upgrading");
}
if (sha(readFileSync(resolve(vendorRoot, "NODEDC_NAVIGATION.patch"))) !== manifest.patchSha256) {
throw new Error("Rerun navigation source patch identity mismatch");
}
const eyeType = "{ position: [number, number, number]; lookTarget: [number, number, number]; eyeUp: [number, number, number] } | null";
const additions = {
"index.js": {
marker: " get_active_recording_id() {",
code: ` get_camera_eye() {\n if (!this.#handle) throw new Error("Rerun viewer is stopped");\n return JSON.parse(this.#handle.nodedc_camera_eye() ?? "null");\n }\n`,
},
"index.ts": {
marker: " get_active_recording_id(): string | null {",
code: ` get_camera_eye(): ${eyeType} {\n if (!this.#handle) throw new Error("Rerun viewer is stopped");\n return JSON.parse(this.#handle.nodedc_camera_eye() ?? "null");\n }\n`,
},
"index.d.ts": {
marker: " get_active_recording_id(): string | null;",
code: ` get_camera_eye(): ${eyeType};\n`,
},
};
// Preserve the exact previous patch as an audited upgrade path.
for (const [name, addition] of Object.entries(additions)) {
addition.previousCode = addition.code;
if (name === "index.d.ts") {
addition.code += " set_height_slice(lower: number | null, upper: number | null): boolean;\n get_height_bounds(): {min: number; max: number} | null;\n";
} else {
const typed = name === "index.ts";
addition.code += ` set_height_slice(lower${typed ? ": number | null" : ""}, upper${typed ? ": number | null" : ""})${typed ? ": boolean" : ""} {
if (!this.#handle) throw new Error("Rerun viewer is stopped");
const off = lower === null && upper === null;
return this.#handle.nodedc_height_slice(off ? undefined : (lower ?? -3e38), off ? undefined : (upper ?? 3e38));
}
get_height_bounds()${typed ? ": {min: number; max: number} | null" : ""} {
if (!this.#handle) throw new Error("Rerun viewer is stopped");
return JSON.parse(this.#handle.nodedc_height_bounds() ?? "null");
}
`;
}
}
// Validate the complete set before changing any installed file. A package
// upgrade, corrupt artifact or independently modified wrapper fails closed.
const writes = [];
for (const [name, identity] of Object.entries(manifest.files)) {
const current = readFileSync(resolve(packageRoot, name));
let output;
if (additions[name]) {
const { marker, code, previousCode } = additions[name];
const source = current.toString("utf8");
const original = source.includes(code) ? source.replace(code, "") : source.replace(previousCode, "");
if (sha(original) !== identity.upstreamSha256 || original.split(marker).length !== 2) {
throw new Error(`Unexpected upstream wrapper: ${name}`);
}
output = Buffer.from(original.replace(marker, code + marker));
} else {
output = readFileSync(resolve(vendorRoot, identity.artifact));
if (sha(output) !== identity.sha256) throw new Error(`Corrupt navigation artifact: ${name}`);
if (![identity.upstreamSha256, identity.previousArtifactSha256, identity.sha256].includes(sha(current))) {
throw new Error(`Unexpected installed runtime: ${name}`);
}
}
writes.push([resolve(packageRoot, name), output]);
}
for (const [path, output] of writes) writeFileSync(path, output);
console.log("Installed NODE.DC Rerun 0.36.3 navigation/v1 (native camera, one renderer).");
@@ -0,0 +1,4 @@
<!doctype html>
<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Worker video</title></head>
<body><video id="worker-video" autoplay muted playsinline></video><audio id="worker-audio" muted></audio>
<script type="module" src="/src/components/simulation/streamFrame.ts"></script></body></html>
+116 -235
View File
@@ -1,22 +1,19 @@
import {SceneDisplayControls} from "../../../packages/spatial-ui/src/SceneDisplayControls";
import {SceneLayerControls} from "../../../packages/spatial-ui/src/SceneLayerControls";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
import { Description,
AdminNavigationPanel,
AppHeader,
ApplicationPanel,
ApplicationShell,
Button,
Checker,
ColorField,
ControlRow,
HeaderNavigation,
HeaderProfile,
HeaderWorkspace,
Icon,
Inspector,
RangeControl,
Select,
StatusBadge,
TextField,
ToastStack,
UserProfileMenu,
Window,
WindowFooterActions,
@@ -30,6 +27,8 @@ import { SystemNavigationPanel } from "./components/system/SystemNavigationPanel
import { SystemWorkspaceSelector } from "./components/system/SystemWorkspaceSelector";
import { useComputeContourSettings } from "./components/system/useComputeContourSettings";
import { useApplicationPanelActions } from "./components/useApplicationPanelActions";
import { useSessionOverviewMode } from "./core/observation/useSessionOverview";
import { SessionOverviewWorkspace } from "./workspaces/recordings/SessionOverviewWorkspace";
import { useEnvironmentSettings } from "./core/environment/useEnvironmentSettings";
import { useDevicePluginHost } from "./core/device-plugins/DevicePluginHost";
import { useMissionRuntime } from "./core/runtime/MissionRuntimeContext";
@@ -50,6 +49,9 @@ import type {
} from "./core/observation/sessionArchive";
import { useRecordedSessionAdmission } from "./core/observation/useRecordedSessionAdmission";
import { useWorkspaceLayoutProfile } from "./core/observation/useWorkspaceLayoutProfile";
import { useSessionDisplayProfile } from "./core/observation/useSessionDisplayProfile";
import { EventPanel } from './components/notifications/NotificationHost';
import { useNotifications } from './core/notifications/useNotificationHistory';
import { viewerSettingsTargetIdentity } from "./core/observation/viewerSettingsTarget";
import { resolvePolygonRunRoute } from "./core/polygon/runArchive";
import {
@@ -58,6 +60,7 @@ import {
type ObservationWorkspaceLayoutProfile,
} from "./core/observation/workspaceLayout";
import {
capabilityStatusLabel,
rootById,
roots,
workspaceById,
@@ -67,33 +70,18 @@ import {
import { backendLabel, localConnectionPhaseLabel, phaseTone } from "./presentation";
import {
defaultSceneSettings,
type PointColorMode,
type PointPalette,
type SceneSettings,
} from "./sceneSettings";
import { DeviceWorkspace } from "./workspaces/DeviceWorkspace";
import { PlanningConnectionWindow } from "./components/missions/PlanningConnectionWindow";
import { PlanningCaptureGuard } from "./components/missions/PlanningCaptureGuard";
import { workspaceLaunchProfile, type WorkspaceLaunchProfile } from "./core/observation/workspaceLaunch";
import { WorkspaceRenderer } from "./workspaces/Workspaces";
import { useLaboratoryAnnotationHeader } from "./components/laboratory/useLaboratoryAnnotationHeader";
import "./styles/scene-windows.css";
type SceneToolWindowId = "sources" | "display" | "layers";
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 {
detections2d: boolean;
segmentation: boolean;
@@ -166,11 +154,15 @@ export default function App() {
contentExpanded: true,
});
const [navigationRevision, setNavigationRevision] = useState(0);
const [activeRoot, setActiveRoot] = useState<RootId | null>(
polygonDatasetRoute.active ? "data" : null,
);
const [environmentSettingsOpen, setEnvironmentSettingsOpen] = useState(false);
const [launchProfile, setLaunchProfile] = useState<WorkspaceLaunchProfile>('direct');
const [sourceUrl, setSourceUrl] = useState("");
const [workspaceHeaderToolsHost, setWorkspaceHeaderToolsHost] = useState<HTMLDivElement | null>(null);
const [workspaceHeaderTitleHost, setWorkspaceHeaderTitleHost] = useState<HTMLSpanElement | null>(null);
const [recordedReplay, setRecordedReplay] = useState<ObservationSessionReplayLaunch | null>(null);
const [recordedReplayLabel, setRecordedReplayLabel] = useState<string | null>(null);
const [replayTransitioning, setReplayTransitioning] = useState(false);
@@ -195,6 +187,7 @@ export default function App() {
const appliedProfileKeyRef = useRef<string | null>(null);
const sceneSettingsRef = useRef<SceneSettings>(defaultSceneSettings);
const displayDraftRef = useRef<SceneSettings>(defaultSceneSettings);
const closeDisplayRef = useRef<() => void>(() => {});
const confirmedSceneSettingsRef = useRef<SceneSettings>(defaultSceneSettings);
const viewerSettingsCommitTimerRef = useRef<number | null>(null);
const runtimeUpdateViewerSettingsRef = useRef(runtime.updateViewerSettings);
@@ -242,6 +235,14 @@ export default function App() {
);
runtimeUpdateViewerSettingsRef.current = runtime.updateViewerSettings;
replayActiveRef.current = replayPresented;
const notifications = useNotifications();
const sessionDisplayProfile = useSessionDisplayProfile(replayPresented ? recordedReplay?.sessionId ?? null : null, (settings) => {
sceneSettingsRef.current = settings;
displayDraftRef.current = settings;
confirmedSceneSettingsRef.current = settings;
setSceneSettings(settings);
setDisplayDraft(settings);
});
useEffect(() => {
if (!polygonDatasetRoute.active || polygonDatasetRouteOpenedRef.current) return;
@@ -324,6 +325,7 @@ export default function App() {
const remote = runtime.state?.viewerSettings;
if (
!remote ||
replayActiveRef.current ||
workspaceLayoutProfile.profile ||
sceneSettingsCommitterRef.current?.isBusy()
) return;
@@ -346,7 +348,7 @@ export default function App() {
useEffect(() => {
const profile = workspaceLayoutProfile.profile;
if (!profile) return;
if (!profile || selectedRecordedSessionIdRef.current) return;
if (viewerSettingsCommitTimerRef.current !== null) {
window.clearTimeout(viewerSettingsCommitTimerRef.current);
viewerSettingsCommitTimerRef.current = null;
@@ -417,7 +419,10 @@ export default function App() {
const closeSceneWindow = useCallback((windowId: SceneToolWindowId) => {
if (windowId === "sources") setSourceWindowOpen(false);
if (windowId === "display") setDisplayWindowOpen(false);
if (windowId === "display") {
setDisplayWindowOpen(false);
closeDisplayRef.current();
}
if (windowId === "layers") setLayerInspectorOpen(false);
setSceneWindowOrder((current) => current.filter((candidate) => candidate !== windowId));
}, []);
@@ -442,20 +447,32 @@ export default function App() {
workspace.openNavigation();
if (rootId === "system") {
workspace.openView(
activeDefinition?.root === "system" ? activeDefinition.id : "modules",
activeDefinition?.id === "vps" ? "vps" : "workers",
);
} else {
workspace.closeView();
}
};
const openView = (viewId: string) => {
const openView = (viewId: string, profile?: WorkspaceLaunchProfile) => {
const definition = workspaceById(viewId);
if (!definition) return;
setLaunchProfile(current => workspaceLaunchProfile(current, definition.kind, profile));
setActiveRoot(definition.root);
workspace.openView(viewId);
};
// Explicit menu navigation always returns to that workspace's entry screen.
const openNavigationView = (viewId: string) => {
if (!workspaceById(viewId)) return;
setNavigationRevision(value => value + 1);
sessionOverview.close();
setSourceWindowOpen(false);
setDisplayWindowOpen(false);
setLayerInspectorOpen(false);
openView(viewId);
};
const openSource = () => {
if (!sceneWorkspaceActive) return;
setSourceDraft(sourceUrl);
@@ -477,14 +494,22 @@ export default function App() {
const next = { ...displayDraftRef.current, ...patch };
displayDraftRef.current = next;
setDisplayDraft(next);
sessionDisplayProfile.edited();
if (viewerSettingsCommitTimerRef.current !== null) {
window.clearTimeout(viewerSettingsCommitTimerRef.current);
}
// Preview and persistence are separate. An open inspector must not freeze
// either its controls or the shared accumulation slider below the scene.
if (replayActiveRef.current && (patch.pointDecimationPercent === 0 || patch.pointDecimationPercent === 100)) {
viewerSettingsCommitTimerRef.current = null;
sceneSettingsCommitterRef.current?.enqueue(next);
return;
}
viewerSettingsCommitTimerRef.current = window.setTimeout(() => {
viewerSettingsCommitTimerRef.current = null;
sceneSettingsCommitterRef.current?.enqueue(displayDraftRef.current);
}, viewerSettingsQuietPeriodMs);
}, []);
}, [sessionDisplayProfile.edited]);
const flushDisplaySettings = useCallback(() => {
if (viewerSettingsCommitTimerRef.current === null) return;
@@ -494,8 +519,15 @@ export default function App() {
}, []);
const commitDisplayPatch = useCallback((patch: Partial<SceneSettings>) => {
sessionDisplayProfile.edited();
commitDisplaySettings({ ...displayDraftRef.current, ...patch });
}, [commitDisplaySettings]);
}, [commitDisplaySettings, sessionDisplayProfile.edited]);
closeDisplayRef.current = () => {
const settings = {...displayDraftRef.current};
commitDisplaySettings(settings);
if (replayActiveRef.current) sessionDisplayProfile.save(settings);
};
const openDisplay = () => {
if (!sceneWorkspaceActive) return;
@@ -629,6 +661,7 @@ export default function App() {
return () => window.clearTimeout(timer);
}, [layoutSaveNotice]);
const sessionOverview = useSessionOverviewMode(activeDefinition?.kind === "recordings");
const contentActions = useApplicationPanelActions({
definition: activeDefinition,
refreshRuntime: runtime.refresh,
@@ -636,7 +669,8 @@ export default function App() {
connectionScenarioResetting: runtime.pendingAction === "mode",
saveWorkspaceLayout,
workspaceLayoutSaving: workspaceLayoutProfile.state === "saving",
systemUtilityActions: computeContourSettings.utilityActions,
systemUtilityActions: [...computeContourSettings.utilityActions, {label: "К списку воркеров", icon: "chevron-left", onClick: () => openNavigationView("workers")}],
sessionOverview: { ...sessionOverview, available: Boolean(recordedReplay && replayPresented && !sourceSwitchBlocked) },
});
const header = (
@@ -645,8 +679,6 @@ export default function App() {
brandHref="/"
brandLabel="NODEDC MISSION CORE"
center={
<>
<HeaderWorkspace kind="mark" label="Mission Core" imageUrl="/nodedc-mark.svg" />
<HeaderNavigation
label="Архитектурные блоки пункта управления"
value={activeRoot ?? undefined}
@@ -656,14 +688,13 @@ export default function App() {
}))}
onChange={selectRoot}
/>
</>
}
right={
<HeaderProfile>
<UserProfileMenu
displayName="DC"
subtitle="Mission Core"
triggerLabel={null}
headerAction={{label: notifications.unread ? `Центр событий · непрочитанных: ${notifications.unread}` : 'Центр событий', pressed: notifications.open, controls: 'operator-events', onSelect: () => notifications.setOpen(open => !open)}}
actions={[
{
id: "refresh",
@@ -679,7 +710,6 @@ export default function App() {
},
]}
/>
</HeaderProfile>
}
/>
);
@@ -694,9 +724,11 @@ export default function App() {
workspace.navigationOpen && activeRoot !== null
}
contentOpen={workspace.contentOpen && activeDefinition !== null}
contentExpanded={workspace.contentExpanded}
contentExpanded
endPanel={<EventPanel/>}
endPanelOpen={notifications.open}
header={header}
stage={
stage={activeDefinition ? null :
<LandingStage
root={currentRoot}
backendStatus={runtime.backendStatus}
@@ -710,7 +742,8 @@ export default function App() {
navigation={currentRoot && activeRoot === "system" ? (
<SystemNavigationPanel
title={currentRoot.title}
onAdd={computeContourSettings.openCreate}
activeId={activeDefinition?.id ?? "workers"}
onNavigate={openNavigationView}
onClose={workspace.closeNavigation}
/>
) : currentRoot ? (
@@ -737,7 +770,7 @@ export default function App() {
icon: <Icon name={item.icon} />,
}))}
activeId={workspace.activeView ?? undefined}
onItemChange={openView}
onItemChange={openNavigationView}
footer={
<>
<span className="nodedc-admin-panel__nav-icon" aria-hidden="true">
@@ -747,7 +780,8 @@ export default function App() {
{rootWorkspaces.length}{" "}
{rootWorkspaces.length === 1
? "рабочая поверхность"
: "рабочих поверхностей"}
: rootWorkspaces.length >= 2 && rootWorkspaces.length <= 4
? "рабочие поверхности" : "рабочих поверхностей"}
</span>
</>
}
@@ -756,17 +790,19 @@ export default function App() {
content={activeDefinition ? (
<ApplicationPanel
key={activeDefinition.id}
allowFullscreen={activeDefinition.kind === "vehicles"}
eyebrow={activeDefinition.eyebrow}
title={
activeDefinition.kind === "recordings"
(activeDefinition.kind === "vehicles" || activeDefinition.kind === "architectural-projects")
? <>{activeDefinition.title}<span className="fleet-header-title" ref={setWorkspaceHeaderTitleHost}/></>
: activeDefinition.kind === "recordings"
&& replayPresented
&& recordedReplayLabel
? `${activeDefinition.title}: ${recordedReplayLabel}`
: activeDefinition.title
}
description={activeDefinition.description}
expanded={workspace.contentExpanded}
onExpandedChange={workspace.setContentExpanded}
expanded
headerTools={
activeDefinition.kind === "device" ? (
<StatusBadge tone={phaseTone(runtime.state?.phase)}>
@@ -802,30 +838,52 @@ export default function App() {
settleRecordedReplaySwitch(outcome)}
onDeleteBegin={releaseRecordedReplayForDelete}
/>
) : activeDefinition.kind === "datasets" ? (
) : activeDefinition.kind === "missions" ? (
<div ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.kind === "vehicles" || activeDefinition.kind === "architectural-projects" ? <div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? <div className="ai-polygon__actions" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "datasets" ? (
<StatusBadge tone="neutral">Offline evaluation</StatusBadge>
) : activeDefinition.kind === "lab-archive" ? (
laboratoryAnnotation.control
) : activeDefinition.kind === "observatory" ? (
<StatusBadge tone="neutral">Только наблюдение</StatusBadge>
) : activeDefinition.kind === "contour-health" ? (
<div ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.kind === "workers" || activeDefinition.kind === "vps" ? (
<div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.root === "system" ? (
<SystemWorkspaceSelector
value={activeDefinition.id}
onChange={openView}
onChange={openNavigationView}
/>
) : (
<StatusBadge tone="warning">Интерфейс готов</StatusBadge>
<StatusBadge tone={activeDefinition.status === "active" ? "success" : "warning"}>{capabilityStatusLabel[activeDefinition.status ?? "contract"]}</StatusBadge>
)
}
utilityActions={contentActions}
onClose={workspace.closeView}
>
<PlanningCaptureGuard key={`${activeDefinition.id}:${navigationRevision}`}
enabled={launchProfile === 'direct' && (activeDefinition.kind === 'device' || activeDefinition.kind === 'spatial')}
onResume={() => openView('local-device', 'planning')}
>
{activeDefinition.kind === "device" ? (
<DeviceWorkspace
onOpenSpatialScene={() => openView("spatial-scene")}
launchProfile === 'planning' ? <PlanningConnectionWindow>
<DeviceWorkspace
onOpenSpatialScene={() => openView("spatial-scene", 'planning')}
onActivateAutomaticSpatialSource={activateAutomaticSpatialSource}
/>
</PlanningConnectionWindow> : <DeviceWorkspace
onOpenSpatialScene={() => openView("spatial-scene", 'direct')}
onActivateAutomaticSpatialSource={activateAutomaticSpatialSource}
/>
) : activeDefinition.kind === "recordings" && sessionOverview.open && recordedReplay && replayPresented ? (
<SessionOverviewWorkspace key={recordedReplay.sessionId} sessionId={recordedReplay.sessionId} />
) : (
<WorkspaceRenderer
launchProfile={launchProfile}
definition={activeDefinition}
headerToolsHost={workspaceHeaderToolsHost}
headerTitleHost={workspaceHeaderTitleHost}
state={activeRuntimeState}
backendStatus={runtime.backendStatus}
sourceUrl={effectiveSourceUrl}
@@ -866,6 +924,7 @@ export default function App() {
}}
/>
)}
</PlanningCaptureGuard>
</ApplicationPanel>
) : null}
/>
@@ -1027,133 +1086,12 @@ export default function App() {
onPointerDown={() => activateSceneWindow("display")}
onClose={() => closeSceneWindow("display")}
>
<Inspector
defaultOpen={["points"]}
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>
),
},
]}
/>
<SceneDisplayControls displayDraft={displayDraft} stageDisplayPatch={stageDisplayPatch}
commitDisplayPatch={replayPresented ? stageDisplayPatch : commitDisplayPatch} flushDisplaySettings={flushDisplaySettings} replayPresented={replayPresented}/>
</Window>
<ToastStack items={sessionDisplayProfile.error ? [{id: 'session-display-profile', tone: 'error',
title: 'Настройки записи', description: sessionDisplayProfile.error}] : []}
onDismiss={sessionDisplayProfile.dismissError} />
<Window
open={sceneWorkspaceActive && layerInspectorOpen}
@@ -1176,66 +1114,9 @@ export default function App() {
<i className="api-dot" data-status={effectiveSourceUrl ? "online" : "checking"} aria-hidden="true" />
{effectiveSourceUrl ? "Источник назначен" : "Источник не назначен"}
</span>
<p>Структура повторяет продуктовые сущности, а не внутренние панели визуального движка.</p>
<Description>Структура повторяет продуктовые сущности, а не внутренние панели визуального движка.</Description>
</div>
<Inspector
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>
),
},
]}
/>
<SceneLayerControls sceneSettings={sceneSettings} pending={runtime.pendingAction === "viewer"} applyScenePatch={applyScenePatch}/>
</Window>
</>
);
@@ -1,92 +1 @@
import { useEffect, useMemo, useState } from "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>
);
}
export { EnvironmentBackgroundMedia } from "@nodedc/ui-react";
@@ -1,248 +1 @@
import { useEffect, useMemo, useRef, useState } from "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>
);
}
export { EnvironmentMediaPlaylistEditor } from "@nodedc/ui-react";
@@ -1,358 +1,29 @@
import { useEffect, useMemo, useState } from "react";
import {
Button,
FeatureSettingsWindow,
Select,
SettingsCard,
Switch,
TextAreaField,
TextField,
WindowFooterActions,
} from "@nodedc/ui-react";
import { EnvironmentSettingsWindow as SharedEnvironmentSettingsWindow } from "@nodedc/ui-react";
import { environmentSurfaceIds, type EnvironmentSettings, type EnvironmentSurfaceId, type UploadedEnvironmentMedia } from "../core/environment/environmentSettings";
import { NetworkSettings } from "./network/NetworkSettings";
import { CesiumServiceSettings } from "./map/CesiumServiceSettings";
import { useLabStorageSettings } from "./storage/LabStorageSettings";
import { roots, workspaces, workspacesForRoot } from "../productModel";
import {
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 {
interface Props {
open: boolean;
settings: EnvironmentSettings;
state: "loading" | "ready" | "saving" | "error";
error: string | null;
onClose: () => void;
onSave: (settings: EnvironmentSettings) => Promise<EnvironmentSettings>;
onUpload: (
surfaceId: EnvironmentSurfaceId,
itemId: string,
file: File,
) => Promise<UploadedEnvironmentMedia>;
onUpload: (surfaceId: EnvironmentSurfaceId, itemId: string, file: File) => Promise<UploadedEnvironmentMedia>;
}
function patchPage(
draft: EnvironmentSettings,
surfaceId: EnvironmentSurfaceId,
patch: Partial<EnvironmentPage>,
): EnvironmentSettings {
return {
...draft,
pages: {
...draft.pages,
[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>
);
const surfaces = environmentSurfaceIds.map(id => ({
id, home: id === "home", description: id === "home" ? "Главная страница продукта" : `Стартовая страница раздела «${roots.find(root => root.id === id)?.label}»`,
actions: id === "home" ? workspaces.filter(item => !item.internalOnly) : workspacesForRoot(id),
}));
export function EnvironmentSettingsWindow(props: Props) {
const storage = useLabStorageSettings(props.open);
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet" additionalSections={[storage, {id: "network", label: "Сеть", icon: "network", content: props.open ? <NetworkSettings/> : null}, {id: "services", label: "Сервисы", icon: "key", content: props.open ? <CesiumServiceSettings/> : null}]}
onSave={draft => props.onSave({ ...draft, pages: Object.fromEntries(environmentSurfaceIds.map(id => [id, draft.pages[id]])) as EnvironmentSettings["pages"] })}
onUpload={(id, itemId, file) => {
if (!environmentSurfaceIds.includes(id as EnvironmentSurfaceId)) throw new Error("Страница окружения недоступна.");
return props.onUpload(id as EnvironmentSurfaceId, itemId, file);
}} />;
}
@@ -1,5 +1,6 @@
import { useLayoutEffect, useState, type RefObject } from "react";
import { WorkspaceWindow } from "@nodedc/ui-react";
import type {RefObject} from "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 { ObservationSourceDescriptor } from "../core/runtime/contracts";
@@ -10,60 +11,6 @@ import type {
RecordedCameraAdmissionState,
} 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({
source,
index,
@@ -104,76 +51,12 @@ export function FloatingObservationWindow({
state: RecordedCameraAdmissionState,
) => void;
}) {
const [bounds, setBounds] = useState<{ width: number; height: number } | null>(null);
useLayoutEffect(() => {
const element = boundsRef.current;
if (!element) return;
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}`}
>
return <FloatingMediaWindow title={source.label} subtitle={source.description}
index={index} count={count} boundsRef={boundsRef} rect={rect} maximized={maximized}
active={active} hidden={hidden} onRectChange={onRectChange} onMaximizedChange={onMaximizedChange}
onActivate={onActivate} onClose={onClose} resizable={source.capabilities.resizable}
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>}>
<ObservationMedia
source={source}
playback={playback}
@@ -182,6 +65,5 @@ export function FloatingObservationWindow({
recordedAdmissionKey={recordedAdmissionKey}
onRecordedAdmissionChange={onRecordedAdmissionChange}
/>
</WorkspaceWindow>
);
</FloatingMediaWindow>;
}
@@ -1,10 +1,9 @@
import { Button, Icon, StatusBadge } from "@nodedc/ui-react";
import { Description, LandingStage as SharedLandingStage, StatusBadge } from "@nodedc/ui-react";
import type { BackendStatus, RuntimePhase } from "../core/runtime/contracts";
import type { EnvironmentPage } from "../core/environment/environmentSettings";
import type { RootDefinition, WorkspaceDefinition } from "../productModel";
import { backendLabel, backendTone, phaseLabel, phaseTone } from "../presentation";
import { EnvironmentBackgroundMedia } from "./EnvironmentBackgroundMedia";
export interface LandingStageProps {
root: RootDefinition | null;
@@ -25,40 +24,10 @@ export function LandingStage({
quickActions,
onOpenWorkspace,
}: LandingStageProps) {
const { background } = page;
const hasMedia = background.enabled && background.items.some(
(item) => item.url && item.mediaKind,
);
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>
return <SharedLandingStage page={page} pageId={root?.id ?? "home"}
actions={quickActions.map(workspace => ({ id: workspace.id, label: workspace.label, icon: workspace.icon, onSelect: () => onOpenWorkspace(workspace.id) }))}
status={<>
<div>
<span className="section-eyebrow">ЛОКАЛЬНЫЙ КОНТУР</span>
<StatusBadge tone={backendTone(backendStatus)}>{backendLabel(backendStatus)}</StatusBadge>
</div>
@@ -66,13 +35,10 @@ export function LandingStage({
<span className="section-eyebrow">ИСТОЧНИК</span>
<StatusBadge tone={phaseTone(phase)}>{phaseLabel(phase)}</StatusBadge>
</div>
<p>{message || "Выберите архитектурный блок в верхней навигации."}</p>
</div>
<footer className="landing-stage__footer">
<span>{root?.accent ?? "НАБЛЮДЕНИЕ · МИССИИ · ДАННЫЕ"}</span>
<Description>{message || "Выберите архитектурный блок в верхней навигации."}</Description>
</>}
footer={<>
<span>{root?.accent ?? "НАБЛЮДЕНИЕ · МИССИИ · ДАННЫЕ"}</span>
<span>01 / ЛОКАЛЬНЫЙ СТЕНД</span>
</footer>
</section>
);
</>} />;
}
@@ -1,4 +1,4 @@
import { GlassSurface } from "@nodedc/ui-react";
import { Description, GlassSurface } from "@nodedc/ui-react";
export interface MetricCardProps {
eyebrow: string;
@@ -16,7 +16,7 @@ export function MetricCard({ eyebrow, value, unit, detail, featured = false }: M
<strong>{value}</strong>
{unit ? <span>{unit}</span> : null}
</div>
<p>{detail}</p>
<Description>{detail}</Description>
</GlassSurface>
);
}
@@ -28,6 +28,7 @@ export interface CameraLeaseRetryBudget {
const CAMERA_LEASE_RETRY_DELAYS = [400, 1_000, 2_000, 5_000] as const;
export const CAMERA_FIRST_MEDIA_TIMEOUT_MS = 8_000;
export const CAMERA_FIRST_PLAYABLE_FRAME_TIMEOUT_MS = 8_000;
export const CAMERA_BUFFERING_NOTICE_DELAY_MS = 1_000;
// The gateway may release an 8 MiB / 64-fragment slow-reader backlog after a
// main-thread stall. Keep one bounded append margin above that complete batch;
// crossing either limit replaces the MSE epoch instead of dropping fragments.
@@ -284,6 +285,7 @@ export function MseFmp4WebSocketPlayer({
let onBufferError: (() => void) | null = null;
let objectUrl = "";
let retryTimer: number | undefined;
let bufferingNoticeTimer: number | undefined;
let receivedMedia = false;
let failed = false;
let playingReported = false;
@@ -295,10 +297,15 @@ export function MseFmp4WebSocketPlayer({
);
const queue: ArrayBuffer[] = [];
let queuedBytes = 0;
const clearBufferingNotice = () => {
if (bufferingNoticeTimer !== undefined) window.clearTimeout(bufferingNoticeTimer);
bufferingNoticeTimer = undefined;
};
const fail = (copy: string) => {
if (!transportIsCurrent() || failed) return;
startupWatchdog?.clear();
clearBufferingNotice();
failed = true;
transportHealthyRef.current = false;
recoveryPendingAuthorityRef.current = null;
@@ -335,6 +342,7 @@ export function MseFmp4WebSocketPlayer({
return;
}
startupWatchdog?.clear();
clearBufferingNotice();
failed = true;
transportHealthyRef.current = false;
const retry = consumeCameraLeaseRetry(leaseRetryRef.current, delivery.id);
@@ -392,6 +400,7 @@ export function MseFmp4WebSocketPlayer({
const onPlaying = () => {
if (!transportIsCurrent() || failed) return;
clearBufferingNotice();
startupWatchdog?.markPlaying();
transportHealthyRef.current = true;
leaseRetryRef.current = resetCameraLeaseRetryBudget(delivery.id);
@@ -410,7 +419,21 @@ export function MseFmp4WebSocketPlayer({
}
};
const onWaiting = () => {
if (!transportIsCurrent() || failed || !playingReported) return;
// A short receipt gap must not flicker or restart the acquisition-owned
// stream. A sustained decoder wait must not retain a playing presentation.
if (bufferingNoticeTimer !== undefined) return;
bufferingNoticeTimer = window.setTimeout(() => {
bufferingNoticeTimer = undefined;
if (!transportIsCurrent() || failed || video.readyState >= 3) return;
setStatus("buffering");
setMessage("Ожидание новых кадров.");
}, CAMERA_BUFFERING_NOTICE_DELAY_MS);
};
video.addEventListener("playing", onPlaying);
video.addEventListener("waiting", onWaiting);
video.addEventListener("stalled", onWaiting);
const appendNext = () => {
if (
@@ -594,10 +617,13 @@ export function MseFmp4WebSocketPlayer({
disposed = true;
transportHealthyRef.current = false;
startupWatchdog?.clear();
clearBufferingNotice();
if (retryTimer !== undefined) window.clearTimeout(retryTimer);
queue.length = 0;
socket?.close(1000, "Browser preview transport replaced or hidden");
video.removeEventListener("playing", onPlaying);
video.removeEventListener("waiting", onWaiting);
video.removeEventListener("stalled", onWaiting);
mediaSource.removeEventListener("sourceopen", onSourceOpen);
if (sourceBuffer && onBufferUpdateEnd) {
sourceBuffer.removeEventListener("updateend", onBufferUpdateEnd);
@@ -708,7 +734,7 @@ export function MseFmp4WebSocketPlayer({
{status !== "playing" ? (
<div className="mse-fmp4-player__status" role="status" aria-live="polite">
<Icon name={status === "error" ? "alert" : "video"} size={20} />
<strong>{status === "error" ? "Канал прерван" : "Подготовка камеры"}</strong>
<strong>{status === "error" ? "Канал прерван" : status === "buffering" ? "Ожидание изображения" : "Подготовка камеры"}</strong>
<span>{message}</span>
{status === "error" ? (
<button
@@ -1,5 +1,5 @@
import { useState } from "react";
import { ConfirmationModal, Dropdown, Icon } from "@nodedc/ui-react";
import { Description, ConfirmationModal, Dropdown, Icon } from "@nodedc/ui-react";
import {
type ObservationSessionReplayLaunch,
@@ -124,7 +124,7 @@ export function ObservationSessionSelect({
const [deleteTarget, setDeleteTarget] = useState<ObservationSessionSummary | null>(null);
const sessions = useObservationSessions({
limit,
scope: "source",
scope: "standalone",
replayEnabled: blockedReason === null,
onReplayBegin,
onReplayAccepted,
@@ -279,16 +279,16 @@ export function ObservationSessionSelect({
description={deleteTarget ? <>
<strong>{deleteTarget.label}</strong>
{deleteTarget.lab ? (
<p>
<Description>
Будут удалены только LAB-запись из каталога и её подготовленный кэш.
Исходная запись {deleteTarget.lab.sourceSessionId} и зафиксированный
лабораторный результат останутся неизменными.
</p>
</Description>
) : (
<p>
<Description>
Сессия, исходные данные наблюдения, подготовленная Rerun-запись и
видеоматериалы будут удалены с этого сервера без возможности восстановления.
</p>
</Description>
)}
{sessions.error && sessions.deletingSessionId === null ? (
<p className="observation-session-delete-error" role="alert">{sessions.error}</p>
@@ -346,11 +346,11 @@ export function ObservationSessionArchive({
{labsOnly ? "ВОСПРОИЗВОДИМЫЕ ЛАБОРАТОРНЫЕ ЗАПИСИ" : "АРХИВ НАБЛЮДЕНИЯ"}
</span>
<h2>{labsOnly ? "Записанные лабораторные работы" : "Сохранённые сессии"}</h2>
<p>
<Description>
{labsOnly
? "Каждая запись связана с LAB-конфигурацией и открывается как самостоятельный визуальный результат."
: "Выберите запись: сцена и синхронные каналы откроются ниже, не меняя эфир наблюдения."}
</p>
</Description>
</div>
<button
type="button"
@@ -457,16 +457,16 @@ export function ObservationSessionArchive({
description={deleteTarget ? <>
<strong>{deleteTarget.label}</strong>
{deleteTarget.lab ? (
<p>
<Description>
Будут удалены только LAB-запись из каталога и её подготовленный кэш.
Исходная запись {deleteTarget.lab.sourceSessionId} и зафиксированный
лабораторный результат останутся неизменными.
</p>
</Description>
) : (
<p>
<Description>
Сессия, исходные данные наблюдения, подготовленная Rerun-запись и
видеоматериалы будут удалены с этого сервера без возможности восстановления.
</p>
</Description>
)}
</> : null}
confirmLabel="Удалить сессию"
@@ -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 {
ObservationSourceAvailability,
ObservationSourceDescriptor,
ObservationSourceModality,
} from "../core/runtime/contracts";
import { MseFmp4WebSocketPlayer } from "./MseFmp4WebSocketPlayer";
import {
@@ -16,28 +16,6 @@ import type {
} from "../core/observation/recordedSessionAdmission";
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({
source,
playback,
@@ -159,105 +137,3 @@ export function ObservationMedia({
</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";
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")}`;
}
export * from "../../../../packages/spatial-ui/src/ObservationTimeline";
@@ -29,7 +29,9 @@ export type RecordedMediaPresentationState = "loading" | "ready" | "waiting" | "
export const RECORDED_MEDIA_DURATION_TOLERANCE_SECONDS = 1;
const RECORDED_MEDIA_SOURCE_OPEN_TIMEOUT_MS = 10_000;
const RECORDED_MEDIA_TARGET_TIMEOUT_MS = 10_000;
// A valid local fragment becomes decoder-ready well below one second. Keeping
// a damaged GOP on screen for ten seconds only delays the keyframe recovery.
const RECORDED_MEDIA_TARGET_TIMEOUT_MS = 2_500;
const RECORDED_MEDIA_FRAGMENT_TIMEOUT_MS = 15_000;
const RECORDED_MEDIA_REQUIRED_AHEAD_SEGMENTS = 12;
const RECORDED_MEDIA_SEGMENTS_AHEAD = 36;
@@ -72,6 +74,39 @@ export function recordedMediaDecodeStartSequence(
return selected;
}
export function nextRecordedMediaRandomAccessSequence(
randomAccessSequences: readonly number[],
failedSequence: number,
): number | null {
if (!Number.isInteger(failedSequence) || failedSequence < 1) return null;
for (const sequence of randomAccessSequences) {
if (!Number.isInteger(sequence) || sequence < 1) return null;
if (sequence > failedSequence) return sequence;
}
return null;
}
export function recordedMediaRecoveryTargetSequence(
requestedSequence: number | null,
failedSequence: number | null,
recoverySequence: number | null,
): number | null {
if (requestedSequence === null) return null;
if (
!Number.isInteger(requestedSequence)
|| requestedSequence < 1
|| failedSequence === null
|| recoverySequence === null
|| !Number.isInteger(failedSequence)
|| !Number.isInteger(recoverySequence)
|| failedSequence < 1
|| recoverySequence <= failedSequence
) return requestedSequence;
return requestedSequence >= failedSequence && requestedSequence < recoverySequence
? recoverySequence
: requestedSequence;
}
export function recordedMediaSegmentAppendOrder(
appended: ReadonlySet<number>,
decodeStartSequence: number,
@@ -90,6 +125,32 @@ export function recordedMediaSegmentAppendOrder(
return missing;
}
/** Resolve a source-clock timestamp to the first fMP4 fragment covering it. */
export function recordedMediaSegmentSequenceAtTime(
segmentEndTimesSeconds: readonly number[],
epochStartSeconds: number,
currentSeconds: number,
): number | null {
if (
!segmentEndTimesSeconds.length ||
!Number.isFinite(epochStartSeconds) ||
!Number.isFinite(currentSeconds)
) return null;
const localSeconds = Math.max(0, currentSeconds - epochStartSeconds);
let left = 0;
let right = segmentEndTimesSeconds.length - 1;
while (left < right) {
const middle = Math.floor((left + right) / 2);
const endSeconds = segmentEndTimesSeconds[middle];
if (!Number.isFinite(endSeconds) || endSeconds <= 0) return null;
if (endSeconds + 0.001 >= localSeconds) right = middle;
else left = middle + 1;
}
const finalEndSeconds = segmentEndTimesSeconds[left];
if (!Number.isFinite(finalEndSeconds) || finalEndSeconds + 0.001 < localSeconds) return null;
return left + 1;
}
export function recordedMediaCanRollTarget(
previousSequence: number,
nextSequence: number,
@@ -121,6 +182,27 @@ function recordedMediaTimeRangesContain(
return false;
}
export function recordedMediaTimestampStallRecoveryTarget(
currentSeconds: number,
bufferedRanges: readonly (readonly [number, number])[],
skipSeconds = 0.18,
): number | null {
if (!Number.isFinite(currentSeconds) || !Number.isFinite(skipSeconds) || skipSeconds <= 0) {
return null;
}
for (const [startSeconds, endSeconds] of bufferedRanges) {
if (
!Number.isFinite(startSeconds)
|| !Number.isFinite(endSeconds)
|| currentSeconds < startSeconds - 0.05
|| currentSeconds > endSeconds
) continue;
const targetSeconds = Math.min(currentSeconds + skipSeconds, endSeconds - 0.05);
return targetSeconds >= currentSeconds + 0.04 ? targetSeconds : null;
}
return null;
}
export function recordedMediaPresentationState(
state: "loading" | "ready" | "error",
readyGeneration: string | null,
@@ -151,6 +233,24 @@ export function selectRecordedMediaEpoch(
return selected && currentSeconds <= selected.timelineEndSeconds ? selected : null;
}
/**
* Keep admission bounded even when the shared Rerun clock is currently before,
* between, or after camera epochs. Presentation still reports `waiting`; this
* selector only chooses the nearest epoch whose first/last fragment can prove
* that the camera transport is usable without downloading the whole MP4.
*/
export function selectRecordedMediaPreparationEpoch(
epochs: readonly ObservationRecordedMediaEpoch[],
currentSeconds: number,
): ObservationRecordedMediaEpoch | null {
if (!epochs.length || !Number.isFinite(currentSeconds)) return null;
const active = selectRecordedMediaEpoch(epochs, currentSeconds);
if (active) return active;
return epochs.find((epoch) => epoch.timelineStartSeconds > currentSeconds)
?? epochs.at(-1)
?? null;
}
export function recordedMediaSeekableCoverage(
durationSeconds: number,
seekableEndSeconds: number,
@@ -231,29 +331,14 @@ export async function fetchRecordedMediaArchive(
return { manifest, byteLength: totalBytes };
}
function videoHasSeekableArchive(
function waitForRecordedVideoInitialFrame(
video: HTMLVideoElement,
declaredDurationSeconds: number,
): boolean {
if (video.readyState < 1 || video.seekable.length < 1) return false;
return recordedMediaSeekableCoverage(
video.duration,
video.seekable.end(video.seekable.length - 1),
declaredDurationSeconds,
RECORDED_MEDIA_DURATION_TOLERANCE_SECONDS,
video.seekable.start(0),
);
}
function waitForSeekableArchive(
video: HTMLVideoElement,
declaredDurationSeconds: number,
signal: AbortSignal,
): Promise<void> {
if (signal.aborted) return Promise.reject(new DOMException("Aborted", "AbortError"));
if (videoHasSeekableArchive(video, declaredDurationSeconds)) return Promise.resolve();
if (video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA) return Promise.resolve();
return new Promise((resolve, reject) => {
const events = ["loadedmetadata", "durationchange", "progress", "canplay"] as const;
const events = ["loadeddata", "canplay", "progress"] as const;
let stallTimer: ReturnType<typeof globalThis.setTimeout> | undefined;
const armStallTimer = () => {
if (stallTimer !== undefined) globalThis.clearTimeout(stallTimer);
@@ -270,7 +355,7 @@ function waitForSeekableArchive(
};
const onProgress = () => {
armStallTimer();
if (!videoHasSeekableArchive(video, declaredDurationSeconds)) return;
if (video.readyState < HTMLMediaElement.HAVE_CURRENT_DATA) return;
cleanup();
resolve();
};
@@ -313,11 +398,7 @@ async function mountRecordedEpochStream(
};
video.load();
try {
await waitForSeekableArchive(
video,
descriptor.timelineEndSeconds - descriptor.timelineStartSeconds,
signal,
);
await waitForRecordedVideoInitialFrame(video, signal);
return cleanup;
} catch (error) {
cleanup();
@@ -336,6 +417,11 @@ interface RecordedSegmentTarget {
resetAttempts: number;
}
interface RecordedSegmentRecovery {
readonly failedSequence: number;
readonly recoverySequence: number;
}
interface RecordedSegmentStreamRuntime {
readonly generation: string;
readonly mediaSource: MediaSource;
@@ -716,6 +802,9 @@ export function RecordedFmp4Player({
onAdmissionChange,
onPlaybackChange,
onPlayingRejected,
playbackAuthority = "media",
playbackTransport = "segmented",
recoverTimestampStalls = false,
}: {
source: ObservationSourceDescriptor;
playback?: RecordedObservationPlayback | null;
@@ -728,6 +817,9 @@ export function RecordedFmp4Player({
onAdmissionChange?: (state: RecordedCameraAdmissionState) => void;
onPlaybackChange?: (playback: RecordedObservationPlayback) => void;
onPlayingRejected?: () => void;
playbackAuthority?: "media" | "host";
playbackTransport?: "segmented" | "epoch-stream";
recoverTimestampStalls?: boolean;
}) {
const videoRef = useRef<HTMLVideoElement>(null);
const onAdmissionChangeRef = useRef(onAdmissionChange);
@@ -768,12 +860,16 @@ export function RecordedFmp4Player({
);
const [archive, setArchive] = useState<RecordedMediaArchive | null>(null);
const [state, setState] = useState<"loading" | "ready" | "error">("loading");
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [readyGeneration, setReadyGeneration] = useState<string | null>(null);
const [bufferRevision, setBufferRevision] = useState(0);
const [segmentRecoveryGeneration, setSegmentRecoveryGeneration] = useState(0);
const [segmentRecovery, setSegmentRecovery] = useState<RecordedSegmentRecovery | null>(null);
const segmentedRuntimeRef = useRef<RecordedSegmentStreamRuntime | null>(null);
const [segmentedRuntimeGeneration, setSegmentedRuntimeGeneration] = useState<string | null>(null);
const targetRevisionRef = useRef(0);
const targetReadyAbortRef = useRef<AbortController | null>(null);
const lastSegmentRecoveryRef = useRef<string | null>(null);
const playAttemptRevisionRef = useRef(0);
const currentSeconds = playback?.currentSeconds ?? contract?.timelineStartSeconds ?? 0;
const playbackPlayingRef = useRef(Boolean(playback?.playing));
@@ -781,25 +877,63 @@ export function RecordedFmp4Player({
const playbackRate = playback?.rate && Number.isFinite(playback.rate)
? Math.min(4, Math.max(0.25, playback.rate))
: 1;
const epoch = useMemo(
const playbackRateRef = useRef(playbackRate);
playbackRateRef.current = playbackRate;
const presentationEpoch = useMemo(
() => selectRecordedMediaEpoch(archive?.manifest.epochs ?? [], currentSeconds),
[archive?.manifest.epochs, currentSeconds],
);
const epoch = useMemo(
() => selectRecordedMediaPreparationEpoch(
archive?.manifest.epochs ?? [],
currentSeconds,
),
[archive?.manifest.epochs, currentSeconds],
);
const segmentClockSeconds = epoch
? Math.min(
Math.max(currentSeconds, epoch.timelineStartSeconds),
epoch.timelineEndSeconds,
)
: currentSeconds;
const effectiveSegmentCount = segmentCount ?? epoch?.segmentCount ?? null;
const requestedSegmentSequence = segmentSequence ?? (epoch
? recordedMediaSegmentSequenceAtTime(
epoch.segmentEndTimesSeconds,
epoch.timelineStartSeconds,
segmentClockSeconds,
)
: null);
const effectiveSegmentSequence = recordedMediaRecoveryTargetSequence(
requestedSegmentSequence,
segmentRecovery?.failedSequence ?? null,
segmentRecovery?.recoverySequence ?? null,
);
const holdingForSegmentRecovery = Boolean(
segmentRecovery
&& requestedSegmentSequence !== null
&& effectiveSegmentSequence !== requestedSegmentSequence,
);
const segmented = Boolean(
segmentCount !== null
&& Number.isInteger(segmentCount)
&& segmentCount >= 1
playbackTransport === "segmented"
&& requestedSegmentSequence !== null
&& Number.isInteger(requestedSegmentSequence)
&& requestedSegmentSequence >= 1
&&
effectiveSegmentCount !== null
&& Number.isInteger(effectiveSegmentCount)
&& effectiveSegmentCount >= 1
&& typeof MediaSource !== "undefined"
&& epoch
&& epoch.segmentCount === segmentCount
&& epoch.segmentCount === effectiveSegmentCount
&& epoch.randomAccessSequences.length > 0
&& epoch.segmentEndTimesSeconds.length === segmentCount
&& epoch.segmentEndTimesSeconds.length === effectiveSegmentCount
&& MediaSource.isTypeSupported(epoch.mediaType),
);
const directPlaybackSeconds = segmented ? null : currentSeconds;
const waitingForEpoch = Boolean(archive && !epoch);
const selectedGeneration = contract && epoch
? `${contract.manifestGenerationSha256}:${epoch.ordinal}:${epoch.timelineStartSeconds}:${epoch.timelineEndSeconds}`
const waitingForEpoch = Boolean(archive && !presentationEpoch);
const selectedGeneration = contract && presentationEpoch
? `${contract.manifestGenerationSha256}:${presentationEpoch.ordinal}:${presentationEpoch.timelineStartSeconds}:${presentationEpoch.timelineEndSeconds}`
: null;
const visualState = recordedMediaPresentationState(
state,
@@ -813,6 +947,7 @@ export function RecordedFmp4Player({
if (!contract) {
setArchive(null);
setReadyGeneration(null);
setErrorMessage("Некорректный descriptor записанной камеры.");
setState("error");
reportAdmission({
phase: "error",
@@ -825,6 +960,9 @@ export function RecordedFmp4Player({
const abort = new AbortController();
setArchive(null);
setReadyGeneration(null);
setSegmentRecovery(null);
lastSegmentRecoveryRef.current = null;
setErrorMessage(null);
setState("loading");
reportAdmission({
phase: "loading",
@@ -842,6 +980,7 @@ export function RecordedFmp4Player({
}
setArchive(null);
setReadyGeneration(null);
setErrorMessage("Архив записанной камеры не прошёл проверку.");
setState("error");
reportAdmission({
phase: "error",
@@ -853,43 +992,14 @@ export function RecordedFmp4Player({
}, [admissionKey, contract, prepare]);
useEffect(() => {
if (!archive || !contract || !prepare || segmented) return;
const abort = new AbortController();
let disposed = false;
void (async () => {
for (const candidate of archive.manifest.epochs) {
const probe = document.createElement("video");
probe.muted = true;
probe.playsInline = true;
const cleanup = await mountRecordedEpochStream(probe, candidate, abort.signal);
cleanup();
if (disposed || abort.signal.aborted) return;
}
if (disposed || abort.signal.aborted) return;
reportAdmission({
phase: "ready",
byteLength: archive.byteLength,
message: null,
});
})().catch((error: unknown) => {
if (
disposed ||
abort.signal.aborted ||
(error instanceof DOMException && error.name === "AbortError")
) return;
setReadyGeneration(null);
setState("error");
reportAdmission({
phase: "error",
byteLength: archive.byteLength,
message: "Не все codec epoch записанной камеры декодируются и доступны для seek.",
});
});
return () => {
disposed = true;
abort.abort();
};
}, [admissionKey, archive, contract, prepare, segmented]);
if (!segmentRecovery || requestedSegmentSequence === null) return;
if (
requestedSegmentSequence >= segmentRecovery.failedSequence
&& requestedSegmentSequence < segmentRecovery.recoverySequence
) return;
lastSegmentRecoveryRef.current = null;
setSegmentRecovery(null);
}, [requestedSegmentSequence, segmentRecovery]);
useEffect(() => {
const video = videoRef.current;
@@ -910,6 +1020,7 @@ export function RecordedFmp4Player({
setReadyGeneration(null);
setSegmentedRuntimeGeneration(null);
setErrorMessage(null);
setState("loading");
video.pause();
const sourceOpened = waitForMediaSourceOpen(mediaSource, abort.signal);
@@ -957,6 +1068,7 @@ export function RecordedFmp4Player({
return;
}
setReadyGeneration(null);
setErrorMessage("Покадровый буфер записанной камеры не открылся.");
setState("error");
reportAdmission({
phase: "error",
@@ -982,7 +1094,14 @@ export function RecordedFmp4Player({
}
URL.revokeObjectURL(objectUrl);
};
}, [archive, contract, epoch, segmentCount, segmented]);
}, [
archive,
contract,
effectiveSegmentCount,
epoch,
segmented,
segmentRecoveryGeneration,
]);
useEffect(() => {
const runtime = segmentedRuntimeRef.current;
@@ -993,18 +1112,19 @@ export function RecordedFmp4Player({
|| !archive
|| !segmented
|| segmentedRuntimeGeneration !== runtime.generation
|| segmentSequence === null
|| !Number.isInteger(segmentSequence)
|| segmentSequence < 1
|| segmentSequence > runtime.segmentCount
|| effectiveSegmentSequence === null
|| !Number.isInteger(effectiveSegmentSequence)
|| effectiveSegmentSequence < 1
|| effectiveSegmentSequence > runtime.segmentCount
) return;
const archiveByteLength = archive.byteLength;
const decodeStart = recordedMediaDecodeStartSequence(
runtime.randomAccessSequences,
segmentSequence,
effectiveSegmentSequence,
);
if (decodeStart === null) {
setReadyGeneration(null);
setErrorMessage("Для кадра записанной камеры нет random-access фрагмента.");
setState("error");
reportAdmission({
phase: "error",
@@ -1015,10 +1135,11 @@ export function RecordedFmp4Player({
}
const targetSeconds = recordedSegmentStartSeconds(
runtime.segmentEndTimesSeconds,
segmentSequence,
effectiveSegmentSequence,
);
if (targetSeconds === null) {
setReadyGeneration(null);
setErrorMessage("Для кадра записанной камеры нет точной media timestamp.");
setState("error");
reportAdmission({
phase: "error",
@@ -1030,15 +1151,15 @@ export function RecordedFmp4Player({
const previousTarget = runtime.target;
const readyEnd = Math.min(
runtime.segmentCount,
segmentSequence + RECORDED_MEDIA_REQUIRED_AHEAD_SEGMENTS,
effectiveSegmentSequence + RECORDED_MEDIA_REQUIRED_AHEAD_SEGMENTS,
);
const desiredEnd = Math.min(
runtime.segmentCount,
segmentSequence + RECORDED_MEDIA_SEGMENTS_AHEAD,
effectiveSegmentSequence + RECORDED_MEDIA_SEGMENTS_AHEAD,
);
const candidateTarget: RecordedSegmentTarget = {
revision: previousTarget?.revision ?? 0,
sequence: segmentSequence,
sequence: effectiveSegmentSequence,
decodeStart,
readyEnd,
desiredEnd,
@@ -1046,6 +1167,24 @@ export function RecordedFmp4Player({
forceReset: false,
resetAttempts: 0,
};
const recoverFromSegmentFailure = (failedSequence: number): boolean => {
const recoverySequence = nextRecordedMediaRandomAccessSequence(
runtime.randomAccessSequences,
failedSequence,
);
if (recoverySequence === null) return false;
const recoveryToken = `${runtime.generation}:${failedSequence}:${recoverySequence}`;
if (lastSegmentRecoveryRef.current === recoveryToken) return true;
lastSegmentRecoveryRef.current = recoveryToken;
setReadyGeneration(null);
setSegmentRecovery({ failedSequence, recoverySequence });
setErrorMessage(
`Восстанавливаем камеру с ключевого кадра ${recoverySequence}.`,
);
setState("loading");
setSegmentRecoveryGeneration((generation) => generation + 1);
return true;
};
const rollingTarget = Boolean(previousTarget && recordedMediaCanRollTarget(
previousTarget.sequence,
candidateTarget.sequence,
@@ -1059,21 +1198,62 @@ export function RecordedFmp4Player({
|| runtime.abort.signal.aborted
|| (error instanceof DOMException && error.name === "AbortError")
) return;
const failedSequence = runtime.target?.sequence ?? effectiveSegmentSequence;
if (failedSequence !== null && recoverFromSegmentFailure(failedSequence)) return;
const detail = error instanceof Error && error.message
? `: ${error.message}`
: ".";
const message = `Покадровый фрагмент записанной камеры недоступен${detail}`;
setReadyGeneration(null);
setErrorMessage(message);
setState("error");
reportAdmission({
phase: "error",
byteLength: archiveByteLength,
message: "Покадровый фрагмент записанной камеры недоступен.",
message,
});
};
const resumePlaybackIfRequested = async (revision: number) => {
if (
runtime.disposed
|| segmentedRuntimeRef.current !== runtime
|| runtime.target?.revision !== revision
|| !playbackPlayingRef.current
) return;
video.playbackRate = playbackRateRef.current;
try {
await video.play();
} catch {
if (
runtime.disposed
|| segmentedRuntimeRef.current !== runtime
|| runtime.target?.revision !== revision
) return;
// Canonical recorded LABs run one host-owned clock for camera and
// spatial evidence. A transient MSE play() rejection (commonly a
// pause/reset race while the next fragment is admitted) must stay a
// decoder concern: the rolling target will retry and catch up.
if (playbackAuthority === "host") return;
onPlayingRejectedRef.current?.();
setReadyGeneration(null);
setErrorMessage("Запуск записанной камеры отклонён браузером.");
setState("error");
reportAdmission({
phase: "error",
byteLength: archiveByteLength,
message: "Запуск записанной камеры отклонён браузером.",
});
}
};
if (rollingTarget && previousTarget) {
runtime.target = {
...candidateTarget,
revision: previousTarget.revision,
};
runtime.onTargetBuffered = null;
void pumpRecordedSegmentWindow(runtime).catch(reportPumpError);
void pumpRecordedSegmentWindow(runtime)
.then(() => resumePlaybackIfRequested(previousTarget.revision))
.catch(reportPumpError);
return;
}
@@ -1128,18 +1308,22 @@ export function RecordedFmp4Player({
setBufferRevision((revision) => revision + 1);
runtime.hasPresentedFrame = true;
setReadyGeneration(runtime.generation);
setErrorMessage(null);
setState("ready");
reportAdmission({
phase: "ready",
byteLength: archiveByteLength,
message: null,
});
await resumePlaybackIfRequested(bufferedTarget.revision);
} catch (error) {
if (
targetReadyAbort.signal.aborted
|| (error instanceof DOMException && error.name === "AbortError")
) return;
if (recoverFromSegmentFailure(bufferedTarget.sequence)) return;
setReadyGeneration(null);
setErrorMessage("Кадр записанной камеры не стал decoder-ready.");
setState("error");
reportAdmission({
phase: "error",
@@ -1160,7 +1344,13 @@ export function RecordedFmp4Player({
if (targetReadyAbortRef.current === targetReadyAbort) targetReadyAbortRef.current = null;
if (runtime.onTargetBuffered === markBuffered) runtime.onTargetBuffered = null;
};
}, [archive?.byteLength, segmentSequence, segmented, segmentedRuntimeGeneration]);
}, [
archive?.byteLength,
effectiveSegmentSequence,
playbackAuthority,
segmented,
segmentedRuntimeGeneration,
]);
useEffect(() => {
const video = videoRef.current;
@@ -1170,6 +1360,7 @@ export function RecordedFmp4Player({
? `${contract.manifestGenerationSha256}:${epochDescriptor.ordinal}:${epochDescriptor.timelineStartSeconds}:${epochDescriptor.timelineEndSeconds}`
: null;
setReadyGeneration(null);
setErrorMessage(null);
setState("loading");
const abort = new AbortController();
let disposed = false;
@@ -1185,7 +1376,13 @@ export function RecordedFmp4Player({
}
setBufferRevision((revision) => revision + 1);
setReadyGeneration(generation);
setErrorMessage(null);
setState("ready");
reportAdmission({
phase: "ready",
byteLength: archive?.byteLength ?? null,
message: null,
});
} catch (error) {
if (
disposed ||
@@ -1195,11 +1392,12 @@ export function RecordedFmp4Player({
return;
}
setReadyGeneration(null);
setErrorMessage("Записанная камера не открыла первый декодируемый кадр.");
setState("error");
reportAdmission({
phase: "error",
byteLength: archive?.byteLength ?? null,
message: "Записанная камера не стала seekable.",
message: "Записанная камера не открыла первый декодируемый кадр.",
});
}
};
@@ -1234,6 +1432,7 @@ export function RecordedFmp4Player({
video.currentTime = target;
} catch {
setReadyGeneration(null);
setErrorMessage("Seek записанной камеры завершился ошибкой.");
setState("error");
reportAdmission({
phase: "error",
@@ -1244,11 +1443,13 @@ export function RecordedFmp4Player({
}
}
video.playbackRate = playbackRate;
if (playback?.playing) {
if (playback?.playing && !holdingForSegmentRecovery) {
void video.play().catch(() => {
if (playAttemptRevisionRef.current !== playAttemptRevision) return;
if (playbackAuthority === "host") return;
onPlayingRejectedRef.current?.();
setReadyGeneration(null);
setErrorMessage("Запуск записанной камеры отклонён браузером.");
setState("error");
reportAdmission({
phase: "error",
@@ -1264,12 +1465,95 @@ export function RecordedFmp4Player({
bufferRevision,
directPlaybackSeconds,
epoch,
holdingForSegmentRecovery,
playback?.playing,
playbackAuthority,
playbackRate,
segmented,
visualState,
]);
useEffect(() => {
const video = videoRef.current;
if (!video || !recoverTimestampStalls || !playback?.playing || visualState !== "ready") {
return;
}
let lastSeconds = video.currentTime;
let lastProgressAtMs = performance.now();
const interval = window.setInterval(() => {
if (
!playbackPlayingRef.current
|| video.paused
|| video.ended
|| video.seeking
|| video.readyState < HTMLMediaElement.HAVE_CURRENT_DATA
) {
lastSeconds = video.currentTime;
lastProgressAtMs = performance.now();
return;
}
const nowMs = performance.now();
if (video.currentTime >= lastSeconds + 0.02) {
lastSeconds = video.currentTime;
lastProgressAtMs = nowMs;
return;
}
if (nowMs - lastProgressAtMs < 1_250) return;
const bufferedRanges = Array.from(
{ length: video.buffered.length },
(_, index) => [video.buffered.start(index), video.buffered.end(index)] as const,
);
const targetSeconds = recordedMediaTimestampStallRecoveryTarget(
video.currentTime,
bufferedRanges,
);
lastProgressAtMs = nowMs;
if (targetSeconds === null) return;
// Field recordings can contain non-monotonic or corrupt H.264 timestamps.
// If decoded time is frozen despite proven buffered media ahead, skip only
// the broken timestamp interval and return authority to the media clock.
video.currentTime = targetSeconds;
lastSeconds = targetSeconds;
}, 250);
return () => window.clearInterval(interval);
}, [playback?.playing, recoverTimestampStalls, visualState]);
useEffect(() => {
const video = videoRef.current;
if (!video || !segmented || !playback?.playing || visualState !== "ready") return;
let cancelled = false;
const resumeIfDecoderReady = () => {
if (cancelled || !playbackPlayingRef.current || !video.paused) return;
const runtime = segmentedRuntimeRef.current;
const target = runtime?.target;
if (
!runtime
|| !target
|| runtime.disposed
|| video.seeking
|| video.readyState < HTMLMediaElement.HAVE_CURRENT_DATA
|| Math.abs(video.currentTime - target.targetSeconds) > 0.25
|| !recordedMediaTimeRangesContain(video.buffered, target.targetSeconds)
) return;
playAttemptRevisionRef.current += 1;
const playAttemptRevision = playAttemptRevisionRef.current;
video.playbackRate = playbackRateRef.current;
void video.play().catch(() => {
if (cancelled || playAttemptRevisionRef.current !== playAttemptRevision) return;
if (playbackAuthority === "host") return;
onPlayingRejectedRef.current?.();
});
};
const queueResume = () => window.queueMicrotask(resumeIfDecoderReady);
const events = ["pause", "canplay", "seeked"] as const;
for (const event of events) video.addEventListener(event, queueResume);
resumeIfDecoderReady();
return () => {
cancelled = true;
for (const event of events) video.removeEventListener(event, queueResume);
};
}, [bufferRevision, playback?.playing, playbackAuthority, segmented, visualState]);
useEffect(() => {
const video = videoRef.current;
if ((!interactive && onPlaybackChange === undefined) || !video || !epoch || visualState !== "ready") return;
@@ -1327,7 +1611,9 @@ export function RecordedFmp4Player({
{visualState === "waiting"
? "Камера на этой позиции ещё не записывалась"
: visualState === "error"
? "Записанное видео недоступно"
? errorMessage ?? "Записанное видео недоступно"
: errorMessage
? errorMessage
: archive
? "Проверяем seek и codec записанного видео…"
: "Читаем manifest записанного видео…"}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,8 @@
import {createPortal} from 'react-dom';
import {Icon,IconButton} from '@nodedc/ui-react';
/** A nested workspace returns through the shared panel header. */
export function WorkspaceBackButton({label,onClick,host}:{label:string;onClick:()=>void;host?:HTMLElement|null}) {
const button=<IconButton label={label} onClick={onClick}><Icon name="chevron-left"/></IconButton>;
return host?createPortal(button,host):button;
}
@@ -0,0 +1,23 @@
import {BatteryDesignSettings} from './BatteryDesignSettings';
import {useRef,useState} from 'react';
import {Button,ColorField,ControlRow,Description,FeatureSettingsWindow,Icon,IconButton,RangeControl,SettingsCard} from '@nodedc/ui-react';
import {parseBatteryAppearance} from '../../core/batteryScene/appearance';
import type {useBatteryAppearance} from '../../core/batteryScene/useBatteryAppearance';
import type {SensorDetailProps} from '../../../../../packages/sensor-ui/src/extensions';
import {BmsSettings} from '../../../../../plugins/jk-bms/frontend/src/BmsSettings';
type Section='markings'|'panels'|'diagnostics'|'protection'|'control';
export function BatteryAppearanceSettings({open,onClose,profile,sensor}:{sensor?:SensorDetailProps;open:boolean;onClose:()=>void;profile:ReturnType<typeof useBatteryAppearance>}){
const [section,setSection]=useState<Section>('markings'),input=useRef<HTMLInputElement>(null);
const {value,update}=profile,m=value.markings;
const range=(label:string,value:number,min:number,max:number,onChange:(v:number)=>void)=><RangeControl label={label} value={value} min={min} max={max} step={1} exactValueBounds={{min,max}} onChange={onChange}/>;
const exportJson=()=>{const url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='battery-ui.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
return <FeatureSettingsWindow open={open} title="Настройки батареи" identity={{title:'Батарея',subtitle:section==='markings'||section==='panels'?'Профиль Mission Core':'BMS',avatarLabel:'АКБ'}} sections={[{id:'markings',label:'Маркировка ячеек',icon:'layers'},{id:'panels',label:'Дизайн',icon:'settings'},...(sensor?[{id:'diagnostics' as const,label:'Диагностика BMS',icon:'activity' as const},{id:'protection' as const,label:'Параметры BMS',icon:'sliders' as const},{id:'control' as const,label:'Управление BMS',icon:'power' as const}]:[])]} activeSection={section} onSectionChange={setSection} onClose={onClose}
headerActions={(section==='markings'||section==='panels')&&<><IconButton label="Отменить настройку батареи" disabled={!profile.canUndo} onClick={profile.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить настройку батареи" disabled={!profile.canRedo} onClick={profile.redo}><Icon name="redo"/></IconButton></>}
footer={(section==='markings'||section==='panels')&&<><Button onClick={exportJson}>Экспорт JSON</Button><Button onClick={()=>input.current?.click()}>Импорт JSON</Button><input ref={input} type="file" accept="application/json,.json" hidden onChange={async event=>{const file=event.currentTarget.files?.[0];event.currentTarget.value='';if(!file)return;try{if(file.size>32000)throw new Error('Файл настроек слишком большой.');update(parseBatteryAppearance(JSON.parse(await file.text())));}catch(error){profile.setError(error instanceof Error?error.message:'Не удалось прочитать профиль.');}}}/></>}>
{sensor&&section!=='markings'&&section!=='panels'?<BmsSettings {...sensor} section={section} open={open}/>:section==='markings'?<SettingsCard title="Маркировка ячеек" description="Номер и напряжение на заводских площадках модели. Размер меняет надпись внутри площадки.">
<ControlRow label="Цвет маркировки"><ColorField label="Цвет маркировки" value={m.color} onChange={color=>update({...value,markings:{...m,color}})}/></ControlRow>
{range('Размер маркировки, %',m.size,50,160,size=>update({...value,markings:{...m,size}}))}
</SettingsCard>:<BatteryDesignSettings value={value} update={update}/>}
{(section==='markings'||section==='panels')&&<Description>Сохраняется в Mission Core для этой батареи. Ctrl Z / ⌘ Z — отмена, Shift Ctrl Z / ⇧ ⌘ Z — повтор.</Description>}
</FeatureSettingsWindow>;
}
@@ -0,0 +1,35 @@
import {useEffect,useRef} from 'react';
import * as pc from 'playcanvas';
import type {PlayCanvasViewerProps} from '../rover/playcanvas/PlayCanvasViewer';
import type {CellMarkingAppearance} from '../../core/batteryScene/appearance';
import {cellDisplayIndex,drawCellDisplay} from '../../core/batteryScene/cellDisplay';
type Api=Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0];
/** GPU textures on the thirteen original Blender faces. Opaque geometry owns occlusion. */
export function BatteryCellLabels({api,values,ready,appearance}:{api:Api|null;values:readonly number[];ready:boolean;appearance:CellMarkingAppearance}){
const latest=useRef({values,appearance});latest.current={values,appearance};
useEffect(()=>{
if(!api||!ready)return;
const displays=(api.modelRoot.findComponents('render') as pc.RenderComponent[]).flatMap(component=>component.meshInstances).flatMap(mesh=>{
const index=cellDisplayIndex(mesh.node.name);if(index===null)return [];
const canvas=document.createElement('canvas');canvas.width=canvas.height=256;const ctx=canvas.getContext('2d');if(!ctx)return [];
const texture=new pc.Texture(api.app.graphicsDevice,{name:mesh.node.name,format:pc.PIXELFORMAT_SRGBA8,mipmaps:true,addressU:pc.ADDRESS_CLAMP_TO_EDGE,addressV:pc.ADDRESS_CLAMP_TO_EDGE});
const original=mesh.material,material=new pc.StandardMaterial();material.name=mesh.node.name;
material.diffuse.set(0,0,0);material.emissive.set(1,1,1);material.emissiveMap=texture;material.opacityMap=texture;material.opacityMapChannel='a';
material.useLighting=false;material.useFog=false;material.blendType=pc.BLEND_NORMAL;material.depthTest=true;material.depthWrite=false;material.cull=pc.CULLFACE_BACK;material.update();
return [{mesh,index,canvas,ctx,texture,material,original,signature:''}];
});
const update=()=>{for(const display of displays){
const {values,appearance}=latest.current,value=values[display.index],signature=JSON.stringify([Number.isFinite(value)?value:null,appearance.color,appearance.size]);
if(display.signature!==signature){drawCellDisplay(display.ctx,display.index,value,appearance);display.texture.setSource(display.canvas);display.texture.upload();display.signature=signature;}
// These material slots carry live readings; their appearance is owned by battery settings.
display.mesh.material=display.material;
}};
update();api.app.on('prerender',update);
let disposed=false;
const dispose=()=>{if(disposed)return;disposed=true;api.app.off('prerender',update);api.app.off('destroy',dispose);for(const display of displays){if(display.mesh.material===display.material)display.mesh.material=display.original;display.material.destroy();display.texture.destroy();}};
// Viewer cleanup precedes sibling effect cleanup. Release GPU resources before the device.
api.app.on('destroy',dispose);
return dispose;
},[api,ready]);
return null;
}
@@ -0,0 +1,2 @@
.battery-design-settings{display:grid;gap:var(--nodedc-space-4);min-width:0}
.battery-indicator-previews{display:flex;flex-wrap:wrap;align-items:center;gap:var(--nodedc-space-3)}
@@ -0,0 +1,40 @@
import {BatteryIndicator} from './BatteryIndicator';
import './BatteryDesignSettings.css';
import {useState} from 'react';
import {ColorField,ControlRow,Description,RangeControl,Select,SettingsCard} from '@nodedc/ui-react';
import type {BatteryAppearance} from '../../core/batteryScene/appearance';
export function BatteryDesignSettings({value,update}:{value:BatteryAppearance;update:(value:BatteryAppearance)=>void}){
const [target,setTarget]=useState<'panels'|'indicator'>('panels');
const p=value.panels,i=value.indicator;
const panel=(patch:Partial<typeof p>)=>update({...value,panels:{...p,...patch}});
const glass=(patch:Partial<typeof p.glass>)=>panel({glass:{...p.glass,...patch}});
const indicator=(patch:Partial<typeof i>)=>update({...value,indicator:{...i,...patch}});
const range=(label:string,value:number,min:number,max:number,onChange:(v:number)=>void)=><RangeControl label={label} value={value} min={min} max={max} step={1} exactValueBounds={{min,max}} onChange={onChange}/>;
const color=(label:string,value:string,onChange:(v:string)=>void)=><ControlRow label={label}><ColorField label={label} value={value} onChange={onChange}/></ControlRow>;
return <div className="battery-design-settings"><Select label="Элемент дизайна" value={target} onChange={setTarget} options={[{value:'panels',label:'Плашки показаний'},{value:'indicator',label:'Индикатор в обсерватории'}]}/>
{target==='panels'?<SettingsCard title="Плашки показаний" description="Общий вид верхних и нижних плашек над моделью.">
{range('Высота плашек, px',p.height,56,160,height=>panel({height}))}
{range('Радиус углов, px',p.radius,0,48,radius=>panel({radius}))}
{range('Размер подписей, px',p.labelSize,10,20,labelSize=>panel({labelSize}))}
{range('Размер значений, px',p.valueSize,12,30,valueSize=>panel({valueSize}))}
{color('Цвет текста',p.textColor,textColor=>panel({textColor}))}
{color('Цвет стекла',p.glass.tintHex,tintHex=>glass({tintHex}))}
{range('Прозрачность стекла, %',100-p.glass.tintOpacity,0,100,transparency=>glass({tintOpacity:100-transparency}))}
{range('Размытие стекла, px',p.glass.blur,0,60,blur=>glass({blur}))}
</SettingsCard>:<SettingsCard title="Индикатор в обсерватории" description="Размеры, цвет заливки и диапазоны уровня заряда для этой батареи.">
{range('Ширина индикатора, px',i.width,32,320,width=>indicator({width}))}
{range('Высота индикатора, px',i.height,12,96,height=>indicator({height}))}
{range('Радиус углов индикатора, px',i.radius,0,48,radius=>indicator({radius}))}
{range('Отступ от кнопок шапки влево, px',i.offset,0,320,offset=>indicator({offset}))}
<Select label="Режим цвета индикатора" value={i.mode} onChange={mode=>indicator({mode})} options={[{value:'ranges',label:'По уровню заряда'},{value:'mono',label:'Один цвет'}]}/>
{i.mode==='mono'?color('Цвет индикатора',i.color,color=>indicator({color})):<>
{range('Низкий заряд ниже, %',i.lowUntil,0,99,lowUntil=>indicator({lowUntil,middleUntil:Math.max(i.middleUntil,lowUntil+1)}))}
{color('Низкий заряд',i.lowColor,lowColor=>indicator({lowColor}))}
{range('Средний заряд ниже, %',i.middleUntil,i.lowUntil+1,100,middleUntil=>indicator({middleUntil}))}
{color('Средний заряд',i.middleColor,middleColor=>indicator({middleColor}))}
{color('Высокий заряд',i.highColor,highColor=>indicator({highColor}))}
</>}
<Description>Чёрный или белый текст выбирается автоматически по цвету заливки. Предпросмотр:</Description>
<div className="battery-indicator-previews">{[10,25,80].map(soc=><BatteryIndicator key={soc} appearance={i} soc={soc} label="Предпросмотр заряда" valueText={`${soc}%`} disabled/>)}</div>
</SettingsCard>}</div>;
}
@@ -0,0 +1,6 @@
import {LevelButton,type LevelButtonProps} from '@nodedc/ui-react';
import {batteryIndicatorColor,type BatteryIndicatorAppearance} from '../../core/batteryScene/appearance';
type Props=Omit<LevelButtonProps,'value'|'fillColor'>&{appearance:BatteryIndicatorAppearance;soc:number|null};
export function BatteryIndicator({appearance,soc,style,...props}:Props){
return <LevelButton {...props} value={soc===null?null:soc/100} fillColor={batteryIndicatorColor(appearance,soc)} geometry={{width:appearance.width,height:appearance.height,radius:appearance.radius}} style={style}/>;
}
@@ -0,0 +1,20 @@
import type {CellMarkingAppearance} from '../../core/batteryScene/appearance';
import {BatteryCellLabels} from './BatteryCellLabels';
import type {PlayCanvasViewerProps} from '../rover/playcanvas/PlayCanvasViewer';
import {useMemo,useState} from 'react';
import {Description} from '@nodedc/ui-react';
import {SceneEditor} from '../rover/editor/RoverScene';
import {useSceneDocument} from '../../core/roverScene/useSceneDocument';
import {batterySceneProfile} from '../../core/batteryScene/profile';
export function BatteryScene({editing,soc,fresh,deviceId,seedKey,cellVoltages=[],markingAppearance}:{editing:boolean;soc:number|null;fresh:boolean;deviceId:string;seedKey?:string;cellVoltages?:readonly number[];markingAppearance:CellMarkingAppearance}){
const profile=useMemo(()=>batterySceneProfile(seedKey),[seedKey]);
const scene=useSceneDocument(deviceId,profile);
const [api,setApi]=useState<Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0]|null>(null);
const [phase,setPhase]=useState<'loading'|'ready'|'error'>('loading');
return <div className="bms-scene" data-editing={editing} aria-label="3D-модель батареи R05">
<SceneEditor scene={scene} editing={editing} modelUrl="/battery-scene/catl-r04.glb?objects-v6-r05" minFitDistance={.6} chargeState={{soc,fresh}} onModelState={setPhase} onSceneReady={setApi}/>
<BatteryCellLabels api={api} ready={phase==='ready'} values={cellVoltages} appearance={markingAppearance}/>
{phase!=='ready'&&<div className="bms-scene-status"><Description role="status">{phase==='error'?'Модель не загрузилась. Показания BMS доступны ниже.':'Загружается модель аккумулятора…'}</Description></div>}
</div>;
}
@@ -0,0 +1,24 @@
import {useBatteryView} from '../../core/batteryScene/useBatteryView';
import type {SensorDetailProps} from '../../../../../packages/sensor-ui/src/extensions';
import {BatteryAppearanceSettings} from './BatteryAppearanceSettings';
import {useBatteryAppearance} from '../../core/batteryScene/useBatteryAppearance';
import type {BatteryAppearance} from '../../core/batteryScene/appearance';
import {useEffect,useState,type ReactNode} from 'react';
import {createPortal} from 'react-dom';
import {EditorWorkspace,Icon,IconButton,LoadingRegion,ResizableViewport,ToastStack,useApplicationPanelFullscreen} from '@nodedc/ui-react';
import {minBatteryViewHeight,maxBatteryViewHeight} from '../../core/batteryScene/viewHeight';
export function BatteryWorkspace({children,deviceId,title,headerActionsTarget,back,sensor,fullscreenControl}:{sensor?:SensorDetailProps;fullscreenControl?:{fullscreen:boolean;setFullscreen:(value:boolean)=>void};deviceId:string;title:string;headerActionsTarget?:HTMLElement|null;back:()=>void;children:(controls:{editing:boolean;appearance:BatteryAppearance;renderViewport:(children:ReactNode)=>ReactNode})=>ReactNode}){
const inheritedFull=useApplicationPanelFullscreen(),full=fullscreenControl??inheritedFull,[editing,setEditing]=useState(false),[error,setError]=useState(''),[settings,setSettings]=useState(false);
const profile=useBatteryAppearance(deviceId,settings);
const view=useBatteryView(deviceId);const {height,setHeight,commitHeight}=view;
const fullscreen=full?.fullscreen??false,setFullscreen=full?.setFullscreen;
useEffect(()=>()=>{setFullscreen?.(false);},[setFullscreen]);
useEffect(()=>{const escape=(event:KeyboardEvent)=>{
if(event.key!=='Escape'||event.defaultPrevented||document.querySelector('[role=dialog],[role=listbox]'))return;
event.preventDefault();if(fullscreen)setFullscreen?.(false);else if(editing)setEditing(false);else back();
};window.addEventListener('keydown',escape);return()=>window.removeEventListener('keydown',escape);},[editing,fullscreen,setFullscreen,back]);
const actions=<>{full&&<IconButton label={fullscreen?'Восстановить окно батареи':'Развернуть окно батареи'} onClick={()=>setFullscreen?.(!fullscreen)}><Icon name={fullscreen?'minimize':'expand'}/></IconButton>}<IconButton label={editing?'Завершить редактирование сцены':'Редактировать сцену'} aria-pressed={editing} onClick={()=>{setSettings(false);setEditing(value=>!value);}}><Icon name="edit"/></IconButton><IconButton label="Настройки батареи" aria-pressed={settings} onClick={()=>{setEditing(false);setSettings(true);}}><Icon name="settings"/></IconButton></>;
return <>{headerActionsTarget?createPortal(actions,headerActionsTarget):actions}<LoadingRegion loading={!profile.ready||!view.ready} label="Загрузка настроек батареи">{profile.ready&&view.ready&&children({editing,appearance:profile.value,renderViewport:content=><ResizableViewport resizeIndicator={false} className="bms-stage" height={height} minHeight={minBatteryViewHeight} maxHeight={maxBatteryViewHeight} onHeightChange={setHeight} onHeightCommit={commitHeight}><EditorWorkspace editing={editing} title={title} subtitle="Редактирование сцены аккумулятора" onBack={()=>setEditing(false)}><div className="bms-stage bms-editor-content">{content}</div></EditorWorkspace></ResizableViewport>})}</LoadingRegion><BatteryAppearanceSettings open={settings} onClose={()=>setSettings(false)} profile={profile} sensor={sensor}/><ToastStack items={(error||profile.error||view.error)?[{id:'battery-view-save',title:error||profile.error||view.error,tone:'error'}]:[]} onDismiss={()=>{setError('');profile.setError('');view.setError('');}}/></>;
}
@@ -0,0 +1,33 @@
import { CanonicalResultRerunReplay } from "./CanonicalResultRerunReplay";
import { resolveAICompositionReplay } from "../../core/laboratory/canonicalLabReplay";
import type { ObservationSessionReplayLaunch } from "../../core/observation/sessionArchive";
import type { AICompositionRun } from "../../core/observatory/aiComposition";
function resolveComposition(
runId: string,
launch: ObservationSessionReplayLaunch,
options: { signal: AbortSignal },
) {
return resolveAICompositionReplay(runId, launch, options);
}
export function AICompositionReplay({ run }: { run: AICompositionRun }) {
const semantics = run.moduleIds.includes("ddrnet") || run.moduleIds.includes("eomt");
const detections = run.moduleIds.includes("rf-detr")
|| run.moduleIds.includes("object-distance");
const costmap = run.moduleIds.includes("tgs");
return (
<CanonicalResultRerunReplay
key={run.runId}
resultId={run.runId}
sessionId={run.sourceSessionId}
resolveReplay={resolveComposition}
semantics={semantics}
detections={detections}
costmap={costmap}
moduleIds={run.moduleIds}
viewerLayers={run.presentation.viewerLayers}
label={run.configurationLabel}
/>
);
}
@@ -0,0 +1,265 @@
import { useCallback, useEffect, useState, type ReactNode } from "react";
import { SegmentedControl, SplitPane, type SplitPaneOrientation } from "@nodedc/ui-react";
import { LaboratoryEvidenceViewer } from "./LaboratoryEvidenceViewer";
export const CANONICAL_RECORDED_LAB_REPLAY_CONTRACT =
"missioncore.canonical-recorded-lab-replay/v1";
export interface CanonicalRecordedLabMode<T extends string> {
value: T;
label: string;
disabled?: boolean;
}
/**
* The interaction contract from the accepted recorded-LAB instrument.
*
* Keeping pane selection, collapse semantics, responsive split orientation,
* expansion and splitter state here prevents individual experiments from
* quietly growing their own replay behaviour. Experiments provide evidence
* layers; they do not reimplement the laboratory shell.
*/
export function useCanonicalRecordedLabReplayState<
TMedia extends string,
TSpatial extends string,
>({
initialMediaMode,
initialSpatialMode,
}: {
initialMediaMode: TMedia;
initialSpatialMode: TSpatial | null;
}) {
const [mediaMode, setMediaMode] = useState<TMedia | null>(initialMediaMode);
const [spatialMode, setSpatialMode] = useState<TSpatial | null>(initialSpatialMode);
const [splitPrimarySize, setSplitPrimarySize] = useState(50);
const [splitOrientation, setSplitOrientation] = useState<SplitPaneOrientation>(() => (
typeof window !== "undefined" && window.matchMedia("(max-width: 900px)").matches
? "horizontal"
: "vertical"
));
const [expanded, setExpanded] = useState(false);
useEffect(() => {
const query = window.matchMedia("(max-width: 900px)");
const update = () => setSplitOrientation(query.matches ? "horizontal" : "vertical");
update();
query.addEventListener("change", update);
return () => query.removeEventListener("change", update);
}, []);
const onMediaModeChange = useCallback((next: TMedia | "none") => {
if (next === "none") return;
setMediaMode((current) => current === next ? null : next);
}, []);
const onSpatialModeChange = useCallback((next: TSpatial | "none") => {
if (next === "none") return;
setSpatialMode((current) => current === next ? null : next);
}, []);
return {
mediaMode,
spatialMode,
splitView: mediaMode !== null && spatialMode !== null,
splitPrimarySize,
splitOrientation,
expanded,
onMediaModeChange,
onSpatialModeChange,
onSplitPrimarySizeChange: setSplitPrimarySize,
onExpandedChange: setExpanded,
};
}
export function CanonicalRecordedLabReplay<
TMedia extends string,
TSpatial extends string,
>({
label,
mediaMode,
mediaModes,
spatialMode,
spatialModes,
expanded,
splitPrimarySize,
splitOrientation,
mediaAriaLabel,
spatialAriaLabel,
mediaLayerControls,
spatialLayerControls,
spatialLeadingControl,
spatialTrailingControl,
mediaModeControlsVisible = true,
paneToolbarsAlwaysVisible = false,
mediaMultiLayer = false,
mediaContent,
spatialContent,
unifiedContent,
emptyMessage,
deckOverlays,
actions,
overlay,
transport,
trailingActions,
onMediaModeChange,
onSpatialModeChange,
onExpandedChange,
onSplitPrimarySizeChange,
}: {
label: string;
mediaMode: TMedia;
mediaModes: readonly CanonicalRecordedLabMode<TMedia>[];
spatialMode: TSpatial;
spatialModes: readonly CanonicalRecordedLabMode<TSpatial>[];
expanded: boolean;
splitPrimarySize: number;
splitOrientation: SplitPaneOrientation;
mediaAriaLabel: string;
spatialAriaLabel: string;
mediaLayerControls?: ReactNode;
spatialLayerControls?: ReactNode;
spatialLeadingControl?: ReactNode;
spatialTrailingControl?: ReactNode;
mediaModeControlsVisible?: boolean;
/** Keeps renderer-local controls inside their viewport when only one pane is present. */
paneToolbarsAlwaysVisible?: boolean;
mediaMultiLayer?: boolean;
mediaContent?: ReactNode;
spatialContent?: ReactNode;
/** One upstream Rerun viewer owns both panes; this controlled split owns their shared geometry. */
unifiedContent?: ReactNode;
emptyMessage: string;
deckOverlays?: ReactNode;
actions?: ReactNode;
overlay?: ReactNode;
transport?: ReactNode;
trailingActions?: ReactNode;
onMediaModeChange: (mode: TMedia) => void;
onSpatialModeChange: (mode: TSpatial) => void;
onExpandedChange: (expanded: boolean) => void;
onSplitPrimarySizeChange: (size: number) => void;
}) {
const splitView = mediaMode !== "none" && spatialMode !== "none";
const mediaModeControls = (
<div className="m4-replay-threat-visual__pane-mode-controls" data-pane-mode="media">
<SegmentedControl
value={mediaMode}
items={[...mediaModes]}
label="Видео и камера"
size="dense"
onChange={onMediaModeChange}
/>
</div>
);
const spatialModeControls = (
<div className="m4-replay-threat-visual__pane-mode-controls" data-pane-mode="spatial">
<SegmentedControl
value={spatialMode}
items={[...spatialModes]}
label="3D и план"
size="dense"
onChange={onSpatialModeChange}
/>
</div>
);
const mediaPane = (
<section
className="m4-replay-threat-visual__pane"
data-pane="media"
aria-label={mediaAriaLabel}
hidden={mediaMode === "none"}
>
{splitView || paneToolbarsAlwaysVisible ? (
<div
className="m4-replay-threat-visual__pane-toolbar nodedc-viewport-controls"
data-pane-toolbar="media"
data-multi-semantic={mediaMultiLayer ? "true" : undefined}
>
{mediaLayerControls}
{mediaModeControlsVisible ? mediaModeControls : null}
</div>
) : null}
{mediaContent}
</section>
);
const spatialPane = spatialMode !== "none" ? (
<section
className="m4-replay-threat-visual__pane"
data-pane="spatial"
aria-label={spatialAriaLabel}
>
{splitView || paneToolbarsAlwaysVisible ? (
<div
className="m4-replay-threat-visual__pane-toolbar nodedc-viewport-controls"
data-pane-toolbar="spatial"
>
{spatialLeadingControl}
<div className="m4-replay-threat-visual__spatial-toolbar-end">
{spatialLayerControls}
{spatialModeControls}
{spatialTrailingControl}
</div>
</div>
) : null}
{spatialContent}
</section>
) : null;
return (
<div
className="l3-visual-audit m4-replay-threat-visual"
data-contract={CANONICAL_RECORDED_LAB_REPLAY_CONTRACT}
>
<LaboratoryEvidenceViewer
label={label}
className="m4-replay-threat-evidence-viewer"
mode={mediaMode}
modes={[...mediaModes]}
secondaryMode={{
value: spatialMode,
modes: [...spatialModes],
label: "3D и план",
onChange: onSpatialModeChange,
}}
expanded={expanded}
onModeChange={onMediaModeChange}
onExpandedChange={onExpandedChange}
modeControlsVisible={!splitView && !paneToolbarsAlwaysVisible}
actions={actions}
overlay={overlay}
transport={transport}
trailingActions={trailingActions}
>
<div
className="m4-replay-threat-visual__deck"
data-split={splitView ? "true" : undefined}
data-empty={mediaMode === "none" && spatialMode === "none" ? "true" : undefined}
data-native-rerun={unifiedContent ? "true" : undefined}
>
{unifiedContent ? (
<div className="m4-replay-threat-visual__unified-content">
{unifiedContent}
</div>
) : null}
<SplitPane
primary={mediaPane}
secondary={spatialPane ?? <div />}
primarySize={splitView ? splitPrimarySize : mediaMode !== "none" ? 100 : 0}
onPrimarySizeChange={onSplitPrimarySizeChange}
orientation={splitOrientation}
minPrimarySize={splitView ? 24 : 0}
minSecondarySize={splitView ? 24 : 0}
resizable={splitView}
separatorLabel="Изменить размер видео/камеры и 3D/плана"
/>
{mediaMode === "none" && spatialMode === "none" ? (
<div className="l3-visual-audit__state" role="status">
{emptyMessage}
</div>
) : null}
{deckOverlays}
</div>
</LaboratoryEvidenceViewer>
</div>
);
}
@@ -0,0 +1,524 @@
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import {
Button,
Checker,
ControlRow,
Icon,
IconButton,
Inspector,
InspectorSelectField,
RangeControl,
ToastStack,
Window,
type ToastItem,
} from "@nodedc/ui-react";
import { ObservationTimeline } from "../ObservationTimeline";
import {
RerunViewport,
isRecordedPlaybackPresentationReady,
type RerunPlaybackController,
type RerunPlaybackState,
type RerunViewportStatus,
} from "../RerunViewport";
import {
CanonicalRecordedLabReplay,
useCanonicalRecordedLabReplayState,
} from "../laboratory/CanonicalRecordedLabReplay";
import type { CanonicalLabReplayDescriptor } from "../../core/laboratory/canonicalLabReplay";
import type { ObservationSessionReplayLaunch } from "../../core/observation/sessionArchive";
import { laboratoryResultRerunProfile } from "../../core/observation/viewerProfile";
import { prepareLabReplay, type LabReplayProgress as Progress } from "../../core/laboratory/prepareLabReplay";
import { LabReplayProgress } from "./LabReplayProgress";
import { announceLabStorageChange } from "../../core/storage/localLabStorage";
import type { AIViewerLayer } from "../../core/observatory/aiComposition";
import {
fetchLabViewProfile,
saveLabViewProfile,
} from "../../core/observatory/labViewProfile";
import {
defaultSceneSettings,
type PointColorMode,
type PointPalette,
type SceneSettings,
} from "../../sceneSettings";
type MediaMode = "camera";
type SpatialMode = "3d" | "plan";
interface CanonicalReplayLaunch {
base: ObservationSessionReplayLaunch;
replay: CanonicalLabReplayDescriptor;
}
const RERUN_UNIFIED_CAMERA_SHARE_PERCENT = 46;
const LAB_SCENE_SETTINGS_STORAGE_PREFIX = "missioncore.observatory.lab-scene-settings.v1:";
const LAB_VIEW_PROFILE_ERROR_TOAST = "observatory-lab-view-profile-error";
const COLOR_OPTIONS: readonly { value: PointColorMode; label: string }[] = [
{ value: "intensity", label: "Интенсивность" },
{ value: "height", label: "Высота Z" },
{ value: "distance", label: "Дистанция" },
{ value: "rgb", label: "RGB" },
{ value: "class", label: "Класс" },
];
const PALETTE_OPTIONS: readonly { value: PointPalette; label: string }[] = [
{ value: "turbo", label: "Turbo" },
{ value: "viridis", label: "Viridis" },
{ value: "plasma", label: "Plasma" },
{ value: "grayscale", label: "Серый" },
];
const LAB_SCENE_DEFAULTS: SceneSettings = {
...defaultSceneSettings,
pointSize: 3.8,
accumulationSeconds: 5,
};
export function normalizeLabSceneSettings(settings: SceneSettings): SceneSettings {
const pointSize = Number.isFinite(settings.pointSize) ? settings.pointSize : LAB_SCENE_DEFAULTS.pointSize;
const accumulationSeconds = Number.isFinite(settings.accumulationSeconds)
? settings.accumulationSeconds : LAB_SCENE_DEFAULTS.accumulationSeconds;
return {
...settings,
pointSize: Math.round(Math.max(0.1, pointSize) * 10) / 10,
accumulationSeconds: Math.round(Math.max(0, accumulationSeconds)),
};
}
function loadLabSceneSettings(resultId: string): SceneSettings {
if (typeof window === "undefined") return LAB_SCENE_DEFAULTS;
try {
const raw = window.localStorage.getItem(`${LAB_SCENE_SETTINGS_STORAGE_PREFIX}${resultId}`);
if (raw === null) return LAB_SCENE_DEFAULTS;
const value: unknown = JSON.parse(raw);
if (typeof value !== "object" || value === null || Array.isArray(value)) return LAB_SCENE_DEFAULTS;
const row = value as Record<string, unknown>;
const pointSize = row.pointSize;
const accumulationSeconds = row.accumulationSeconds;
const colorMode = row.colorMode;
const palette = row.palette;
const showGrid = row.showGrid;
const showLabels = row.showLabels;
const showCameraFrustums = row.showCameraFrustums;
if (
typeof pointSize !== "number" || !Number.isFinite(pointSize) || pointSize < 0.1
|| typeof accumulationSeconds !== "number" || !Number.isFinite(accumulationSeconds)
|| accumulationSeconds < 0
|| !COLOR_OPTIONS.some((option) => option.value === colorMode)
|| !PALETTE_OPTIONS.some((option) => option.value === palette)
|| typeof showGrid !== "boolean"
|| typeof showLabels !== "boolean"
|| typeof showCameraFrustums !== "boolean"
) return LAB_SCENE_DEFAULTS;
return {
...LAB_SCENE_DEFAULTS,
pointSize,
accumulationSeconds,
colorMode: colorMode as PointColorMode,
palette: palette as PointPalette,
showGrid,
showLabels,
showCameraFrustums,
};
} catch {
return LAB_SCENE_DEFAULTS;
}
}
export function CanonicalResultRerunReplay({
resultId,
sessionId,
initialPlaybackStartSeconds,
resolveReplay,
semantics = false,
detections = false,
costmap = false,
moduleIds = [],
viewerLayers = [],
label = "Сохранённый результат",
}: {
resultId: string;
sessionId: string;
initialPlaybackStartSeconds?: number;
resolveReplay: (resultId: string, launch: ObservationSessionReplayLaunch, options: { signal: AbortSignal }) => Promise<CanonicalLabReplayDescriptor>;
semantics?: boolean;
detections?: boolean;
costmap?: boolean;
portable?: boolean;
moduleIds?: readonly string[];
viewerLayers?: readonly AIViewerLayer[];
label?: string;
}) {
const {
mediaMode,
spatialMode,
splitPrimarySize,
splitOrientation,
expanded,
onMediaModeChange,
onSpatialModeChange,
onSplitPrimarySizeChange,
onExpandedChange,
} = useCanonicalRecordedLabReplayState<MediaMode, SpatialMode>({
initialMediaMode: "camera",
initialSpatialMode: "3d",
});
const layerIds = useMemo(
() => new Set(viewerLayers.map((layer) => layer.layerId)),
[viewerLayers],
);
const hasProjectedLayers = viewerLayers.length > 0;
const hasDDRNet = layerIds.has("camera.ddrnet")
|| (!hasProjectedLayers && semantics && moduleIds.includes("ddrnet"));
const hasEoMT = layerIds.has("camera.eomt")
|| (!hasProjectedLayers && semantics && moduleIds.includes("eomt"));
const hasFallbackSemantics = semantics && !hasDDRNet && !hasEoMT;
const hasDetections = layerIds.has("camera.detections") || (!hasProjectedLayers && detections);
const hasTgs = layerIds.has("spatial.tgs") || (!hasProjectedLayers && costmap);
const legacyUnclassified = !hasProjectedLayers
&& moduleIds.length === 0
&& !semantics
&& !detections
&& !costmap;
const hasCameraPane = layerIds.has("camera.source")
|| (!hasProjectedLayers && (legacyUnclassified || semantics || detections));
const hasSourcePoints = layerIds.has("spatial.source-points")
|| (!hasProjectedLayers && (legacyUnclassified || costmap || moduleIds.includes("object-distance")));
const hasLocalSlam = layerIds.has("spatial.local-slam")
|| (!hasProjectedLayers && (legacyUnclassified || costmap || moduleIds.includes("object-distance")));
const hasSpatialPane = hasSourcePoints || hasLocalSlam || hasTgs;
const splitView = hasCameraPane && hasSpatialPane;
const [showCamera, setShowCamera] = useState(true);
const [showDDRNet, setShowDDRNet] = useState(hasDDRNet || hasFallbackSemantics);
const [showEoMT, setShowEoMT] = useState(hasEoMT);
const [showDetections, setShowDetections] = useState(hasDetections);
const [showSourcePoints, setShowSourcePoints] = useState(hasSourcePoints);
const [showLocalSlam, setShowLocalSlam] = useState(hasLocalSlam);
const [showTgs, setShowTgs] = useState(hasTgs);
const [followTarget, setFollowTarget] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [sceneDraft, setSceneDraft] = useState<SceneSettings>(() => loadLabSceneSettings(resultId));
const [blueprintSplitPrimarySize, setBlueprintSplitPrimarySize] = useState(
RERUN_UNIFIED_CAMERA_SHARE_PERCENT,
);
const [toasts, setToasts] = useState<ToastItem[]>([]);
const [viewResetGeneration, setViewResetGeneration] = useState<0 | 1>(hasTgs ? 1 : 0);
const [playback, setPlayback] = useState<RerunPlaybackState | null>(null);
const [playbackController, setPlaybackController] = useState<RerunPlaybackController | null>(null);
const [viewerStatus, setViewerStatus] = useState<RerunViewportStatus>("idle");
const [launch, setLaunch] = useState<CanonicalReplayLaunch | null>(null);
const [launchError, setLaunchError] = useState<string | null>(null);
const [preparationProgress, setPreparationProgress] = useState<Progress>({ phase: "checking", fraction: null });
const sceneDraftRef = useRef(sceneDraft);
const previousSplitViewRef = useRef(splitView);
const trackedLaunchSha256Ref = useRef<string | null>(null);
useEffect(() => {
const launchSha256 = launch?.replay.sha256 ?? null;
if (trackedLaunchSha256Ref.current !== launchSha256 || (splitView && !previousSplitViewRef.current)) {
onSplitPrimarySizeChange(RERUN_UNIFIED_CAMERA_SHARE_PERCENT);
setBlueprintSplitPrimarySize(RERUN_UNIFIED_CAMERA_SHARE_PERCENT);
}
trackedLaunchSha256Ref.current = launchSha256;
previousSplitViewRef.current = splitView;
}, [launch?.replay.sha256, onSplitPrimarySizeChange, splitView]);
useEffect(() => {
if (!splitView) return;
const timer = window.setTimeout(() => setBlueprintSplitPrimarySize(splitPrimarySize), 75);
return () => window.clearTimeout(timer);
}, [splitPrimarySize, splitView]);
useEffect(() => {
try {
window.localStorage.setItem(
`${LAB_SCENE_SETTINGS_STORAGE_PREFIX}${resultId}`,
JSON.stringify({
pointSize: sceneDraft.pointSize,
accumulationSeconds: sceneDraft.accumulationSeconds,
colorMode: sceneDraft.colorMode,
palette: sceneDraft.palette,
showGrid: sceneDraft.showGrid,
showLabels: sceneDraft.showLabels,
showCameraFrustums: sceneDraft.showCameraFrustums,
}),
);
} catch {
// The visual remains usable when the browser refuses local persistence.
}
}, [resultId, sceneDraft]);
useEffect(() => {
const controller = new AbortController();
void fetchLabViewProfile(resultId, controller.signal).then((settings) => {
if (!controller.signal.aborted && settings) {
sceneDraftRef.current = settings;
setSceneDraft(settings);
}
}).catch(() => {
// The per-browser copy remains a usable fallback while the local service recovers.
});
return () => controller.abort();
}, [resultId]);
useEffect(() => {
const controller = new AbortController();
setLaunch(null);
setLaunchError(null);
setPlayback(null);
setPlaybackController(null);
setViewerStatus("idle");
void prepareLabReplay(resultId, sessionId, resolveReplay, {
signal: controller.signal, onProgress: setPreparationProgress,
}).then((value) => {
if (!controller.signal.aborted) { setLaunch(value); announceLabStorageChange(); }
}).catch((caught: unknown) => {
if (!controller.signal.aborted) {
setLaunchError(caught instanceof Error ? caught.message : "Сохранённая запись недоступна.");
}
});
return () => controller.abort();
}, [resultId, sessionId, resolveReplay]);
const presentationReady = playbackController !== null
&& isRecordedPlaybackPresentationReady(viewerStatus, playback);
const presentationState = launchError || viewerStatus === "error"
? "error"
: presentationReady ? "ready" : "loading";
const sceneSettings = useMemo<SceneSettings>(() => ({
...sceneDraft,
projection: spatialMode === "plan" ? "2d" : "3d",
showPoints: spatialMode !== null && (showSourcePoints || showLocalSlam),
showTrajectory: spatialMode !== null && showLocalSlam,
accumulationSeconds: showLocalSlam ? sceneDraft.accumulationSeconds : 0,
}), [sceneDraft, showLocalSlam, showSourcePoints, spatialMode]);
const semanticVisible = showDDRNet || showEoMT;
const profile = launch ? laboratoryResultRerunProfile({
resultId,
sourceUrl: launch.replay.sourceUrl,
artifact: {
sourceUrl: launch.replay.sourceUrl,
viewerSourceUrl: launch.replay.viewerSourceUrl,
byteLength: launch.replay.byteLength,
sha256: launch.replay.sha256,
},
blueprintSourceUrl: launch.replay.blueprintSourceUrl,
autoplayWhenReady: false,
presentationGate: "ready",
expectedTimelineStartSeconds: launch.base.timelineStartSeconds,
expectedTimelineEndSeconds: launch.base.timelineEndSeconds,
initialPlaybackStartSeconds: initialPlaybackStartSeconds
?? ((launch.base.mediaSources[0]?.timelineStartSeconds ?? launch.base.timelineStartSeconds)
+ (hasTgs ? 0.000001 : 0)),
view: hasCameraPane && !hasSpatialPane ? "perception" : "spatial",
viewResetGeneration,
followTrajectory: followTarget,
semanticLayer: showEoMT ? "city" : "vegetation",
unifiedPerception: splitView,
unifiedCameraShare: blueprintSplitPrimarySize / 100,
planView: spatialMode === "plan",
perceptionLayers: {
enabled: true,
cameraImage: showCamera,
detections2d: hasDetections && showDetections,
segmentation: semantics && semanticVisible,
cuboids3d: false,
costmap: hasTgs && showTgs,
},
perceptionRetryGeneration: 0,
lockPerceptionCameraInteraction: false,
}) : null;
const toggle = (caption: string, active: boolean, onClick: () => void) => (
<Button key={caption} size="dense" shape="pill" variant={active ? "primary" : "secondary"}
aria-pressed={active} onClick={onClick}>
{caption}
</Button>
);
const openSlamSettings = useCallback(() => {
if (expanded) onExpandedChange(false);
setSettingsOpen(true);
}, [expanded, onExpandedChange]);
const patchSceneDraft = useCallback((patch: Partial<SceneSettings>) => {
const next = { ...sceneDraftRef.current, ...patch };
sceneDraftRef.current = next;
setSceneDraft(next);
}, []);
const closeSlamSettings = useCallback(() => {
const next = normalizeLabSceneSettings(sceneDraftRef.current);
sceneDraftRef.current = next;
setSceneDraft(next);
setSettingsOpen(false);
void saveLabViewProfile(resultId, next).then((settings) => {
sceneDraftRef.current = settings;
setSceneDraft(settings);
setToasts((current) => current.filter(({ id }) => id !== LAB_VIEW_PROFILE_ERROR_TOAST));
}).catch(() => {
setToasts((current) => [
...current.filter(({ id }) => id !== LAB_VIEW_PROFILE_ERROR_TOAST),
{
id: LAB_VIEW_PROFILE_ERROR_TOAST,
tone: "error",
title: "Настройки LAB не сохранились",
description: "Изменения остались в текущем просмотре. Откройте настройки и повторите.",
},
]);
});
}, [resultId]);
const mediaLayerControls = (
<div className="m4-replay-threat-visual__pane-layer-controls" role="group" aria-label="Слои камеры">
{toggle("КАМЕРА", showCamera, () => setShowCamera((value) => !value))}
{hasEoMT ? toggle("EOMT", showEoMT, () => setShowEoMT((value) => !value)) : null}
{hasDDRNet || hasFallbackSemantics
? toggle("DDRNET", showDDRNet, () => setShowDDRNet((value) => !value)) : null}
{hasDetections
? toggle("РАМКИ", showDetections, () => setShowDetections((value) => !value)) : null}
</div>
);
const spatialLayerControls = (
<div className="m4-replay-threat-visual__pane-layer-controls" role="group" aria-label="Слои облака точек">
{hasSourcePoints
? toggle("ИСХ. ТОЧКИ", showSourcePoints, () => setShowSourcePoints((value) => !value)) : null}
{hasLocalSlam ? (
<div className="m4-replay-threat-visual__layer-with-settings">
{toggle("ЛОК. SLAM", showLocalSlam, () => setShowLocalSlam((value) => !value))}
<IconButton label="Настройки облака SLAM" onClick={openSlamSettings}>
<Icon name="settings" size={14} />
</IconButton>
</div>
) : null}
{hasTgs ? toggle("TGS", showTgs, () => setShowTgs((value) => !value)) : null}
</div>
);
const followTargetControl = toggle(
"СЛЕДОВАТЬ",
followTarget,
() => setFollowTarget((value) => !value),
);
const resetSpatialView = (
<IconButton label="Сбросить положение видов"
onClick={() => setViewResetGeneration((value) => value === 0 ? 1 : 0)}>
<Icon name="refresh" size={16} />
</IconButton>
);
const transport = presentationReady && playback && playbackController ? (
<ObservationTimeline
className="m4-replay-threat-visual__timeline canonical-vegetation-rerun-replay__timeline"
active
sourceCount={3}
mode="recorded"
seekable
synchronization="shared-clock"
rangeNs={playback.rangeNs}
currentNs={playback.currentNs}
playing={playback.playing}
onSeek={playbackController.seek}
onPlayingChange={playbackController.setPlaying}
showJumpToEnd={false}
/>
) : undefined;
return (
<div className="canonical-vegetation-rerun-replay" data-presentation-state={presentationState}
aria-busy={presentationState === "loading"}>
<CanonicalRecordedLabReplay
label={label}
mediaMode={hasCameraPane ? mediaMode ?? "camera" : "none"}
mediaModes={[{ value: "camera", label: "КАМЕРА" }]}
spatialMode={hasSpatialPane ? spatialMode ?? "3d" : "none"}
spatialModes={[{ value: "3d", label: "3D" }, { value: "plan", label: "ПЛАН" }]}
expanded={expanded}
splitPrimarySize={splitPrimarySize}
splitOrientation={splitView ? "vertical" : splitOrientation}
mediaAriaLabel="Камера и рассчитанные слои"
spatialAriaLabel={spatialMode === "plan" ? "Вид сверху" : "Трёхмерная сцена"}
mediaLayerControls={mediaLayerControls}
spatialLayerControls={spatialLayerControls}
spatialTrailingControl={followTargetControl}
mediaModeControlsVisible={false}
paneToolbarsAlwaysVisible
mediaMultiLayer
actions={resetSpatialView}
unifiedContent={profile ? (
<div className="canonical-vegetation-rerun-replay__viewport-lock"
data-split-view={splitView ? "true" : undefined}>
<RerunViewport profile={profile} sceneSettings={sceneSettings}
onStatusChange={setViewerStatus} onPlaybackChange={setPlayback}
onPlaybackControllerChange={setPlaybackController} />
</div>
) : launchError ? (
<div className="l3-visual-audit__state" role="alert">{launchError}</div>
) : <div aria-hidden="true" />}
emptyMessage="Слои результата недоступны."
deckOverlays={presentationState === "loading" ? (
<div className="canonical-vegetation-rerun-replay__loading">
<LabReplayProgress progress={launch
? { phase: "opening", fraction: playback?.bufferProgress ?? null }
: preparationProgress} />
</div>
) : undefined}
transport={transport}
onMediaModeChange={onMediaModeChange}
onSpatialModeChange={onSpatialModeChange}
onExpandedChange={onExpandedChange}
onSplitPrimarySizeChange={onSplitPrimarySizeChange}
/>
<Window open={settingsOpen} title="Отображение" subtitle="Параметры облака SLAM"
placement="end" size="sm" onClose={closeSlamSettings}>
<Inspector defaultOpen={["points"]} sections={[
{
id: "points",
label: "Облако точек",
description: "Размер и способ окрашивания",
content: <>
<RangeControl label="Размер точки" min={0.1} max={10} step={0.1}
exactValueBounds={{ min: 0.1 }}
value={sceneDraft.pointSize} formatValue={(value) => `${value.toFixed(1)} пкс`}
onChange={(pointSize) => patchSceneDraft({ pointSize })} />
<InspectorSelectField label="Атрибут цвета" value={sceneDraft.colorMode}
options={[...COLOR_OPTIONS]}
onChange={(colorMode) => patchSceneDraft({ colorMode })} />
<InspectorSelectField label="Палитра" value={sceneDraft.palette}
options={[...PALETTE_OPTIONS]}
onChange={(palette) => patchSceneDraft({ palette })} />
</>,
},
{
id: "history",
label: "Накопление и время",
description: "История облака и траектория",
content: <RangeControl label="Накопление" min={0} max={500} step={1}
exactValueBounds={{ min: 0 }}
value={sceneDraft.accumulationSeconds} formatValue={(value) => `${value} с`}
onChange={(accumulationSeconds) => patchSceneDraft({ accumulationSeconds })} />,
},
{
id: "environment",
label: "Окружение сцены",
description: "Сетка, подписи и камеры",
content: <>
<ControlRow label="Сетка"><Checker checked={sceneDraft.showGrid} label="Показывать"
onChange={(showGrid) => patchSceneDraft({ showGrid })} /></ControlRow>
<ControlRow label="Подписи"><Checker checked={sceneDraft.showLabels} label="Показывать"
onChange={(showLabels) => patchSceneDraft({ showLabels })} /></ControlRow>
<ControlRow label="Камеры"><Checker checked={sceneDraft.showCameraFrustums} label="Показывать"
onChange={(showCameraFrustums) => patchSceneDraft({ showCameraFrustums })} /></ControlRow>
</>,
},
]} />
</Window>
<ToastStack items={toasts}
onDismiss={(id) => setToasts((current) => current.filter((item) => item.id !== id))} />
</div>
);
}
@@ -0,0 +1,12 @@
import { CanonicalResultRerunReplay } from "./CanonicalResultRerunReplay";
import { resolveCanonicalLabReplay } from "../../core/laboratory/canonicalLabReplay";
import type { VegetationFullRouteReview } from "../../core/laboratory/vegetationShadow";
export function CanonicalVegetationRerunReplay({ resultId, review }: {
resultId: string;
review: VegetationFullRouteReview;
}) {
return <CanonicalResultRerunReplay resultId={resultId} sessionId={review.sessionId}
initialPlaybackStartSeconds={review.timelineStartSeconds} semantics
resolveReplay={resolveCanonicalLabReplay} label="RAVNOVES004TREE · канонический повтор Rerun" />;
}
@@ -0,0 +1,10 @@
import { Description, ProgressBar } from "@nodedc/ui-react";
import { labReplayProgressView, type LabReplayProgress as Progress } from "../../core/laboratory/prepareLabReplay";
export function LabReplayProgress({ progress }: { progress: Progress }) {
const view = labReplayProgressView(progress);
return <div className="lab-replay-progress" aria-busy="true">
<Description role="status" aria-live="polite">{view.text}</Description>
<ProgressBar label={view.label} value={view.value} valueText={view.text} />
</div>;
}
@@ -83,7 +83,7 @@ export function LaboratoryEvidenceViewer<
}, [expanded, onExpandedChange]);
const controls = (
<div className="laboratory-evidence-viewer__controls">
<div className="laboratory-evidence-viewer__controls nodedc-viewport-controls">
{actions}
{modeControlsVisible && secondaryMode ? (
<SegmentedControl
@@ -137,7 +137,7 @@ export function LaboratoryEvidenceViewer<
{children}
</div>
{transport ? (
<div className="laboratory-evidence-viewer__transport">
<div className="laboratory-evidence-viewer__transport nodedc-viewport-controls">
{transport}
</div>
) : null}
@@ -149,7 +149,7 @@ export function LaboratoryEvidenceViewer<
</div>
{overlay}
{transport ? (
<div className="laboratory-evidence-viewer__transport">
<div className="laboratory-evidence-viewer__transport nodedc-viewport-controls">
{transport}
</div>
) : null}
@@ -1,3 +1,4 @@
import { Description } from '@nodedc/ui-react';
import {
forwardRef,
type CSSProperties,
@@ -265,6 +266,8 @@ LaboratoryMetricEvidenceSceneHandle,
showCurrentIncrement: boolean;
showLocalSurface: boolean;
showRollingMap: boolean;
showReferenceGeometry?: boolean;
showRenderStats?: boolean;
showLowStep?: boolean;
pointSemanticClassIds?: readonly (number | null)[];
semanticClasses?: readonly RecordedEvidenceSemanticClass[];
@@ -287,6 +290,8 @@ LaboratoryMetricEvidenceSceneHandle,
showLocalSurface,
showRollingMap,
showLowStep = true,
showReferenceGeometry = true,
showRenderStats = true,
pointSemanticClassIds,
semanticClasses,
semanticPalette,
@@ -746,6 +751,7 @@ LaboratoryMetricEvidenceSceneHandle,
if (!host || !content) return;
clearGroup(content);
if (!showReferenceGeometry) { requestRenderRef.current(); return; }
const corridorLength = rig.lengthM / 2 + corridor.forwardLengthM + corridor.rearMarginM;
const corridorCenterX = (rig.lengthM / 2 + corridor.forwardLengthM - corridor.rearMarginM) / 2;
const corridorMesh = new THREE.Mesh(
@@ -806,6 +812,7 @@ LaboratoryMetricEvidenceSceneHandle,
content.add(grid);
requestRenderRef.current();
}, [
showReferenceGeometry,
corridor.forwardLengthM,
corridor.halfWidthM,
corridor.rearMarginM,
@@ -909,10 +916,10 @@ LaboratoryMetricEvidenceSceneHandle,
return (
<div className="laboratory-metric-evidence-scene">
<div ref={hostRef} className="laboratory-metric-evidence-scene__viewport">
{renderError ? <p>{renderError}</p> : null}
{renderError ? <Description>{renderError}</Description> : null}
</div>
<div className="laboratory-metric-evidence-scene__legend">
{renderStats ? (
{showRenderStats && renderStats ? (
<span
data-decision="performance"
title="CPU-время отправки последнего WebGL render pass; это не GPU timer. В покое сцена не перерисовывается."
@@ -1,5 +1,5 @@
import { useId, useState, type ReactNode } from "react";
import { Icon, IconButton, Select, StatusBadge } from "@nodedc/ui-react";
import { Description, Icon, IconButton, Select, StatusBadge } from "@nodedc/ui-react";
export interface LaboratoryOption<T extends string> {
id: T;
@@ -53,7 +53,7 @@ export const LABORATORY_REPORT_TEMPLATE_VERSION =
const EXECUTION_LABELS: Record<LaboratoryExecutionClass, string> = {
deterministic: "Детерминированный",
"ai-inference": "AI inference",
"ai-inference": "AI Inference",
hybrid: "Гибридный",
};
@@ -91,7 +91,7 @@ export function LaboratorySelector<T extends string>({
<div>
<span className="section-eyebrow">{eyebrow}</span>
<h2>{title}</h2>
<p>{description}</p>
<Description>{description}</Description>
</div>
<div className="laboratory-selector__control">
<span>{label}</span>
@@ -59,6 +59,16 @@ export function laboratoryRecordedClipEndExclusiveNs(
return last.sourceTimeNs + typicalDelta;
}
export function laboratoryRecordedClipClockGate(
pendingSequence: number | null,
observedSequence: number,
): { accept: boolean; pendingSequence: number | null } {
if (pendingSequence !== null && pendingSequence !== observedSequence) {
return { accept: false, pendingSequence };
}
return { accept: true, pendingSequence: null };
}
export function LaboratoryRecordedClipPlayer({
source,
segmentCount,
@@ -94,7 +104,8 @@ export function LaboratoryRecordedClipPlayer({
}) {
const [companionSpatialSize, setCompanionSpatialSize] = useState(69);
const lastEmittedSequenceRef = useRef(sequence);
lastEmittedSequenceRef.current = sequence;
const lastObservedSequenceRef = useRef<number | null>(sequence);
const pendingSequenceRef = useRef<number | null>(null);
const frame = useMemo(
() => frames.find((candidate) => candidate.sequence === sequence) ?? frames[0] ?? null,
[frames, sequence],
@@ -113,23 +124,42 @@ export function LaboratoryRecordedClipPlayer({
if (!continuousPlayback && playing) onPlayingChange(false);
}, [continuousPlayback, onPlayingChange, playing]);
useEffect(() => {
if (lastObservedSequenceRef.current !== sequence) {
pendingSequenceRef.current = sequence;
}
lastEmittedSequenceRef.current = sequence;
}, [sequence]);
const emitSequence = useCallback((nextSequence: number) => {
if (lastEmittedSequenceRef.current === nextSequence) return;
lastEmittedSequenceRef.current = nextSequence;
onSequenceChange(nextSequence);
}, [onSequenceChange]);
const requestSequence = useCallback((nextSequence: number) => {
pendingSequenceRef.current = nextSequence;
emitSequence(nextSequence);
}, [emitSequence]);
const handlePlaybackChange = useCallback((next: RecordedObservationPlayback) => {
const sourceTimeNs = Math.round(next.currentSeconds * 1_000_000_000);
const first = frames[0];
if (!first || endExclusiveNs === null) return;
if (sourceTimeNs >= endExclusiveNs) {
emitSequence(first.sequence);
requestSequence(first.sequence);
return;
}
const nearest = nearestLaboratoryRecordedClipFrame(frames, sourceTimeNs);
if (nearest) emitSequence(nearest.sequence);
}, [emitSequence, endExclusiveNs, frames]);
if (!nearest) return;
lastObservedSequenceRef.current = nearest.sequence;
const gate = laboratoryRecordedClipClockGate(
pendingSequenceRef.current,
nearest.sequence,
);
pendingSequenceRef.current = gate.pendingSequence;
if (gate.accept) emitSequence(nearest.sequence);
}, [emitSequence, endExclusiveNs, frames, requestSequence]);
const timelineStart = frames[0]?.sourceTimeNs ?? 0;
const timelineEnd = frames.at(-1)?.sourceTimeNs ?? timelineStart + 1;
@@ -142,7 +172,7 @@ export function LaboratoryRecordedClipPlayer({
className="laboratory-recorded-clip-player__spatial"
aria-hidden={cameraPresentation === "primary"}
>
{cameraPresentation !== "primary" ? alternativeScene : null}
{alternativeScene}
</div>
);
const cameraPane = (
@@ -202,7 +232,7 @@ export function LaboratoryRecordedClipPlayer({
onPlayingChange={continuousPlayback ? onPlayingChange : undefined}
onSeek={(timeNs) => {
const nearest = nearestLaboratoryRecordedClipFrame(frames, timeNs);
if (nearest) emitSequence(nearest.sequence);
if (nearest) requestSequence(nearest.sequence);
}}
showJumpToEnd={false}
/>
@@ -101,7 +101,7 @@ export function LaboratoryReviewWorkspaceFrame({
keepFocusInside(event, event.currentTarget);
}}
>
<header className="laboratory-review-workspace__toolbar">{toolbar}</header>
<header className="laboratory-review-workspace__toolbar nodedc-viewport-controls">{toolbar}</header>
<div className="laboratory-review-workspace__stage">{stage}</div>
{inspector ? <footer className="laboratory-review-workspace__inspector">{inspector}</footer> : null}
{overlays}
@@ -0,0 +1,51 @@
import { Description, GlassSurface } from "@nodedc/ui-react";
import { CanonicalResultRerunReplay } from "./CanonicalResultRerunReplay";
import { resolveCanonicalLabReplay } from "../../core/laboratory/canonicalLabReplay";
import type { ObservatoryPortableResultReview } from "../../core/observatory/recordedRun";
import type { ObservationSessionReplayLaunch } from "../../core/observation/sessionArchive";
function resolvePortableTgsReplay(resultId: string, launch: ObservationSessionReplayLaunch,
options: { signal: AbortSignal }) {
return resolveCanonicalLabReplay(resultId, launch, { ...options, sourceKind: "portable-tgs" });
}
function resolvePortableSemanticReplay(resultId: string, launch: ObservationSessionReplayLaunch,
options: { signal: AbortSignal }) {
return resolveCanonicalLabReplay(resultId, launch, { ...options, sourceKind: "portable-semantic" });
}
function resolvePortableObjectReplay(resultId: string, launch: ObservationSessionReplayLaunch,
options: { signal: AbortSignal }) {
return resolveCanonicalLabReplay(resultId, launch, { ...options, sourceKind: "portable-objects" });
}
export function PortableResultReplay({
review,
label,
}: {
review: ObservatoryPortableResultReview;
label?: string;
}) {
const schema = review.resultDocument.schema_version;
const tgs = schema === "missioncore.recorded-tgs-costmap-review/v2";
const module = review.resultDocument.module;
const moduleId = module && typeof module === "object" && "module_id" in module
? module.module_id : undefined;
const semantics = schema === "missioncore.recorded-eomt-ddrnet-review/v2"
|| (schema === "missioncore.recorded-ai-layer-review/v1"
&& (moduleId === "ddrnet" || moduleId === "eomt"));
const objects = schema === "missioncore.recorded-ai-layer-review/v1"
&& (moduleId === "rf-detr" || moduleId === "object-distance");
if (!tgs && !semantics && !objects) return (
<GlassSurface className="observatory-replay-state" padding="lg">
<Description role="alert">Сохранённый результат этого профиля пока не поддерживает визуальный разбор.</Description>
</GlassSurface>
);
return <CanonicalResultRerunReplay key={review.resultId} resultId={review.resultId}
sessionId={review.sourceSessionId} portable costmap={tgs} semantics={semantics}
detections={objects}
moduleIds={typeof moduleId === "string" ? [moduleId] : []}
label={label}
resolveReplay={tgs ? resolvePortableTgsReplay
: objects ? resolvePortableObjectReplay : resolvePortableSemanticReplay} />;
}
@@ -1,8 +1,11 @@
import { useEffect, useState } from "react";
import {
RecordedFmp4Player,
type RecordedObservationPlayback,
} from "../RecordedFmp4Player";
import type { ObservationSourceDescriptor } from "../../core/runtime/contracts";
import type { RecordedCameraAdmissionState } from "../../core/observation/recordedSessionAdmission";
import {
RecordedEvidenceBoxOverlay,
type RecordedEvidenceBox,
@@ -25,6 +28,7 @@ export function RecordedEvidenceVideoScene({
imageWidth,
imageHeight,
boxes,
overlaySeconds,
semanticOverlay,
pointCloudOverlay,
ariaLabel,
@@ -33,12 +37,17 @@ export function RecordedEvidenceVideoScene({
segmentCount,
onPlaybackChange,
onPlayingRejected,
onAdmissionChange,
playbackAuthority = "media",
playbackTransport = "segmented",
recoverTimestampStalls = false,
}: {
source: ObservationSourceDescriptor;
playback: RecordedObservationPlayback;
imageWidth: number;
imageHeight: number;
boxes: readonly RecordedEvidenceBox[];
overlaySeconds?: number;
semanticOverlay?: RecordedEvidenceSemanticOverlay;
pointCloudOverlay?: RecordedEvidencePointCloudOverlayData;
ariaLabel: string;
@@ -47,7 +56,41 @@ export function RecordedEvidenceVideoScene({
segmentCount?: number;
onPlaybackChange?: (playback: RecordedObservationPlayback) => void;
onPlayingRejected?: () => void;
onAdmissionChange?: (state: RecordedCameraAdmissionState) => void;
playbackAuthority?: "media" | "host";
playbackTransport?: "segmented" | "epoch-stream";
recoverTimestampStalls?: boolean;
}) {
const generation = source.delivery?.kind === "recorded-fmp4-manifest"
? source.delivery.manifestGenerationSha256
: "invalid";
const [admissionPhase, setAdmissionPhase] = useState<RecordedCameraAdmissionState["phase"]>(
"loading",
);
const [presentedSeconds, setPresentedSeconds] = useState<number | null>(null);
useEffect(() => {
setAdmissionPhase("loading");
setPresentedSeconds(null);
}, [generation, source.id]);
const handleAdmissionChange = (next: RecordedCameraAdmissionState) => {
setAdmissionPhase(next.phase);
onAdmissionChange?.(next);
};
const sourceReady = admissionPhase === "ready";
const overlaysPresented = sourceReady
&& presentedSeconds !== null
&& Math.abs(presentedSeconds - playback.currentSeconds) <= 0.25
&& (overlaySeconds === undefined || Math.abs(presentedSeconds - overlaySeconds) <= 0.25);
const handlePlaybackChange = (next: RecordedObservationPlayback) => {
setPresentedSeconds(next.currentSeconds);
// During a paused operator seek the existing media element can emit its old
// timestamp while the requested MSE window is being rebuilt. That stale
// callback must not undo the host target before the decoder reaches it.
if (!playback.playing && Math.abs(next.currentSeconds - playback.currentSeconds) > 0.35) {
return;
}
onPlaybackChange?.(next);
};
return (
<div className="recorded-evidence-video-scene">
<RecordedFmp4Player
@@ -57,29 +100,35 @@ export function RecordedEvidenceVideoScene({
prepare
segmentSequence={segmentSequence}
segmentCount={segmentCount}
onPlaybackChange={onPlaybackChange}
onPlaybackChange={handlePlaybackChange}
onPlayingRejected={onPlayingRejected}
onAdmissionChange={handleAdmissionChange}
playbackAuthority={playbackAuthority}
playbackTransport={playbackTransport}
recoverTimestampStalls={recoverTimestampStalls}
/>
{semanticOverlay ? (
{overlaysPresented && semanticOverlay ? (
<RecordedEvidenceSemanticMaskOverlay
{...semanticOverlay}
imageWidth={imageWidth}
imageHeight={imageHeight}
/>
) : null}
{pointCloudOverlay ? (
{overlaysPresented && pointCloudOverlay ? (
<RecordedEvidencePointCloudOverlay
imageWidth={imageWidth}
imageHeight={imageHeight}
overlay={pointCloudOverlay}
/>
) : null}
<RecordedEvidenceBoxOverlay
imageWidth={imageWidth}
imageHeight={imageHeight}
boxes={boxes}
ariaLabel={ariaLabel}
/>
{overlaysPresented ? (
<RecordedEvidenceBoxOverlay
imageWidth={imageWidth}
imageHeight={imageHeight}
boxes={boxes}
ariaLabel={ariaLabel}
/>
) : null}
</div>
);
}
@@ -0,0 +1,116 @@
import { useEffect, useRef, useState } from "react";
import {
fetchCanonicalRecordedLabSpatialFrame,
type CanonicalRecordedLabSpatialFrame,
} from "../../core/laboratory/canonicalRecordedLabSpatial";
const FRAME_CACHE_LIMIT = 12;
/**
* Shared latest-request-wins scheduler for recorded LAB spatial evidence.
*
* A feature supplies only the sealed session identity and host-clock time.
* Cache ownership, identity fencing and stale-response suppression remain in
* the canonical instrument instead of being reimplemented per experiment.
*/
export function useCanonicalRecordedLabSpatialFrame({
sessionId,
generationSha256,
targetTimeNs,
}: {
sessionId: string;
generationSha256: string | null;
targetTimeNs: number;
}) {
const [frame, setFrame] = useState<CanonicalRecordedLabSpatialFrame | null>(null);
const [error, setError] = useState<string | null>(null);
const desiredRef = useRef<number | null>(null);
const runningRef = useRef(false);
const mountedRef = useRef(true);
const identityRef = useRef("");
const cacheRef = useRef(new Map<number, CanonicalRecordedLabSpatialFrame>());
const pumpRef = useRef<() => void>(() => undefined);
const identity = `${sessionId}:${generationSha256 ?? "unavailable"}`;
identityRef.current = identity;
pumpRef.current = () => {
if (runningRef.current || desiredRef.current === null || !generationSha256) return;
runningRef.current = true;
const requestIdentity = identity;
let settledTimeNs: number | null = null;
void (async () => {
while (
mountedRef.current
&& identityRef.current === requestIdentity
&& desiredRef.current !== null
) {
const requestedTimeNs = desiredRef.current;
const cached = cacheRef.current.get(requestedTimeNs);
try {
const next = cached ?? await fetchCanonicalRecordedLabSpatialFrame(
sessionId,
generationSha256,
requestedTimeNs,
);
if (!mountedRef.current || identityRef.current !== requestIdentity) break;
if (!cached) {
cacheRef.current.set(requestedTimeNs, next);
while (cacheRef.current.size > FRAME_CACHE_LIMIT) {
const oldest = cacheRef.current.keys().next().value as number | undefined;
if (oldest === undefined) break;
cacheRef.current.delete(oldest);
}
}
setFrame(next);
setError(null);
} catch (caught: unknown) {
if (!mountedRef.current || identityRef.current !== requestIdentity) break;
setError(caught instanceof Error
? caught.message
: "Spatial-слои записанной LAB недоступны.");
}
settledTimeNs = requestedTimeNs;
if (desiredRef.current === requestedTimeNs) break;
}
})().finally(() => {
runningRef.current = false;
if (
mountedRef.current
&& desiredRef.current !== null
&& (identityRef.current !== requestIdentity || desiredRef.current !== settledTimeNs)
) {
pumpRef.current();
}
});
};
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
desiredRef.current = null;
};
}, []);
useEffect(() => {
cacheRef.current.clear();
desiredRef.current = null;
setFrame(null);
setError(null);
}, [identity]);
useEffect(() => {
if (!generationSha256) return;
desiredRef.current = targetTimeNs;
const cached = cacheRef.current.get(targetTimeNs);
if (cached) {
setFrame(cached);
setError(null);
return;
}
pumpRef.current();
}, [generationSha256, identity, targetTimeNs]);
return { frame, error, loading: Boolean(generationSha256) && !frame && !error };
}
@@ -130,8 +130,12 @@ export function useRecordedEvidencePlayback(
const synchronize = useCallback((next: RecordedObservationPlayback) => {
if (!validRange(range) || !Number.isFinite(next.currentSeconds)) return;
// Animation-clock mode is retained only for non-media diagnostics. A
// recorded LAB with video uses the external media clock so spatial and
// overlays never advance past the frame the decoder actually presented.
if (clock === "animation") return;
setPlayback((current) => synchronizeRecordedEvidencePlayback(current, next, range));
}, [range]);
}, [clock, range]);
return useMemo(() => ({
playback,
@@ -0,0 +1,89 @@
import {useEffect, useState} from "react";
import {Description, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField} from "@nodedc/ui-react";
import {cesiumServiceMessage, cesiumTokenIndicator, readCesiumService, saveCesiumService, verifyCesiumService,
type CesiumRouteMode, type CesiumServiceSettings as Settings, type CesiumVerification} from "../../core/map/cesiumService";
import "./cesiumServiceSettings.css";
import {serverRequest, type Server} from "../../core/system/servers";
export function CesiumServiceSettings() {
const [service, setService] = useState("");
const [pending, setPending] = useState<"verify" | "save" | "remove" | null>(null);
const [settings, setSettings] = useState<Settings | null>(null);
const [mode, setMode] = useState<CesiumRouteMode>("auto");
const [egress, setEgress] = useState("");
const [servers, setServers] = useState<Server[]>([]);
const [routesError, setRoutesError] = useState("");
const [token, setToken] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [checking, setChecking] = useState(false);
const [checkError, setCheckError] = useState("");
const [showVerification, setShowVerification] = useState(false);
const [verification, setVerification] = useState<CesiumVerification | null>(null);
useEffect(() => {
let active = true;
void readCesiumService().then(value => {if (active) {setSettings(value); setMode(value.mode); setEgress(value.egress_id || "");}})
.catch(reason => {if (active) setError(reason.message);});
void serverRequest<{items:Server[]}>("").then(value => {if(active) setServers(value.items);})
.catch(reason => {if(active) setRoutesError(reason.message);});
return () => {active = false;};
}, []);
useEffect(() => {
let active = true;
setVerification(null); setCheckError(""); setShowVerification(false);
if (service !== "cesium" || !settings?.token_configured || token.trim() || egress !== (settings.egress_id || "")) {setChecking(false); return;}
setChecking(true);
void verifyCesiumService().then(value => {if (active) setVerification(value);})
.catch(reason => {if (active) setCheckError(reason instanceof Error ? reason.message : cesiumServiceMessage());})
.finally(() => {if (active) setChecking(false);});
return () => {active = false;};
}, [service, settings?.revision, settings?.token_configured, token, egress]);
const indicator = cesiumTokenIndicator({configured: !!settings?.token_configured, draft: !!token.trim(),
checking: checking || pending === "verify" || pending === "save", error: error || checkError, verification});
async function action(kind: "verify" | "save" | "remove") {
if (!settings || busy) return;
setBusy(true); setPending(kind); setError(""); setCheckError(""); setVerification(null); setShowVerification(kind === "verify");
try {
if (kind === "verify") setVerification(await verifyCesiumService(token.trim() || undefined, egress));
else {
const result = await saveCesiumService({revision: settings.revision, mode, egress_id: egress,
...(kind === "remove" ? {remove_token: true} : token.trim() ? {token: token.trim()} : {})});
setSettings(result); setToken("");
}
} catch (reason) {setError(reason instanceof Error ? reason.message : cesiumServiceMessage());}
finally {setBusy(false); setPending(null);}
}
return <SettingsCard title="Сервисы" actions={service === "cesium" && <>
<IconButton label="Проверить доступ" disabled={busy || checking || !settings || (!token.trim() && !settings.token_configured)}
loading={pending === "verify"} onClick={() => void action("verify")}><Icon name="activity"/></IconButton>
<IconButton label="Сохранить" disabled={busy || !settings} loading={pending === "save"}
onClick={() => void action("save")}><Icon name="save"/></IconButton>
{settings?.token_configured && <IconButton label="Удалить токен" disabled={busy} loading={pending === "remove"}
onClick={() => void action("remove")}><Icon name="trash"/></IconButton>}
</>}>
<Select label="Выберите сервис" value={service} disabled={busy} onChange={setService}
options={[{value: "", label: "Выберите сервис"}, {value: "cesium", label: "Cesium ion",
icon: <StatusBadge variant="indicator" tone={indicator.tone} pulse={indicator.pulse} title={indicator.label} aria-label={indicator.label}/>} ]}/>
{service === "cesium" && <>
<Description>Общий доступ к спутниковым картам, рельефу и зданиям во всех разделах Mission Core.</Description>
{!settings && !error && <Description role="status">Получаем настройки…</Description>}
{settings && <>
<Select label="Подключение" value={mode} disabled={busy} onChange={value => setMode(value as CesiumRouteMode)}
options={[{value: "auto", label: "Автоматически"}, {value: "direct", label: "Напрямую к источнику"},
{value: "gateway", label: "Сервер хранения локальных данных"}]}/>
<Description>{mode === "auto" ? "Карты используют сервер хранения локальных данных. Если сервер недоступен, подключение переключается на источник через интернет." :
mode === "direct" ? "Карты загружаются через интернет без сохранения тайлов на этом компьютере." : "Карты загружаются только через сервер хранения локальных данных. Если сервер недоступен, загрузка приостанавливается."}</Description>
<Select label="Маршрутизация" value={egress} disabled={busy} onChange={value=>{setEgress(value);setVerification(null);setError("");}}
options={[{value:"",label:"Текущий маршрут"},...servers.flatMap(server=>server.services.filter(item=>item.kind==='egress').map(item=>({value:item.id,label:`${server.name} · ${server.address}`})))]}/>
{routesError&&<Description role="alert">{routesError}</Description>}
<TextField label={settings.token_configured ? "Новый токен Cesium ion" : "Токен Cesium ion"} type="password" value={token}
disabled={busy} autoComplete="off" spellCheck={false} onChange={event => {setToken(event.target.value); setVerification(null); setError("");}}
placeholder={settings.token_configured ? "Токен сохранён; заполните для замены" : "Токен"}/>
<Description>Токен сохраняется только в Mission Core. Для прямого подключения нужен доступ к рельефу, спутниковой карте и зданиям Cesium ion.</Description>
{showVerification && verification && <div className="cesium-service-results" role="status">{Object.entries(verification.assets).map(([id, result]) =>
<Description key={id}>{({"1": "Рельеф", "2": "Спутниковая карта", "96188": "Здания"} as Record<string, string>)[id] ?? id}: {result.ok ? "доступ подтверждён" : cesiumServiceMessage(result.code)}</Description>)}</div>}
</>}
{error && <Description role="alert">{error}</Description>}
</>}
</SettingsCard>;
}
@@ -652,6 +652,7 @@ function CacheHealth({
);
}
const { cache } = health.snapshot;
if (!cache) return <ControlRow label="Подключение"><StatusBadge tone="neutral">Источник · без кэша</StatusBadge></ControlRow>;
return (
<dl className="mission-map__cache-health">
<div>
@@ -0,0 +1 @@
.cesium-service-results { display: grid; gap: var(--nodedc-space-2); }
@@ -0,0 +1,59 @@
import type {MapVisualSettings} from '../../core/map/mapView';
import type {CesiumMapRendererProps} from '@nodedc/map-cesium-react';
export function mapPresentation(settings:MapVisualSettings):CesiumMapRendererProps['settings'] {
return {
atmosphere_enabled: settings.atmosphereEnabled,
atmosphere_hue: settings.atmosphereHue,
atmosphere_saturation:
settings.atmosphereSaturation,
atmosphere_brightness:
settings.atmosphereBrightness,
fog_enabled: settings.fogEnabled,
fog_density: settings.fogDensity,
sun_enabled: settings.sunEnabled,
sun_hour: settings.sunHour,
sun_intensity: settings.sunIntensity,
shadows_enabled: settings.shadowsEnabled,
monochrome_enabled: settings.monochromeEnabled,
monochrome_color: settings.monochromeColor,
imagery_brightness: settings.imageryBrightness,
imagery_contrast: settings.imageryContrast,
imagery_saturation: settings.imagerySaturation,
imagery_gamma: settings.imageryGamma,
imagery_hue: settings.imageryHue,
imagery_alpha: settings.imageryAlpha,
globe_color: settings.globeColor,
background_color: settings.backgroundColor,
terrain_exaggeration:
settings.terrainExaggeration,
buildings_color: settings.buildingsColor,
buildings_opacity: settings.buildingsOpacity,
buildings_maximum_screen_space_error:
settings.buildingsMaximumScreenSpaceError,
grid_lod_enabled: settings.gridLodEnabled,
grid_height_meters: settings.gridHeightMeters,
grid_lod_1_max_height_km:
settings.gridLod1MaxHeightKm,
grid_lod_1_step_km:
settings.gridLod1StepKm,
grid_lod_2_max_height_km:
settings.gridLod2MaxHeightKm,
grid_lod_2_step_km:
settings.gridLod2StepKm,
grid_lod_3_step_km:
settings.gridLod3StepKm,
grid_radius_km: settings.gridRadiusKm,
grid_line_width: settings.gridLineWidth,
grid_color: settings.gridColor,
grid_opacity: settings.gridOpacity,
grid_dots_enabled:
settings.gridDotsEnabled,
grid_dots_size: settings.gridDotsSize,
grid_dots_color: settings.gridDotsColor,
grid_dots_opacity:
settings.gridDotsOpacity,
camera_animation_enabled:
settings.cameraAnimationEnabled,
};
}
@@ -0,0 +1,21 @@
import { Description, Button, LoadingRegion, Window } from "@nodedc/ui-react";
import type { RouteCheck } from "../../core/missions/planner";
export function MissionCheckWindow({ open, onClose, busy, error, report, run }: {
open: boolean; onClose: () => void; busy: boolean; error: string | null; report: RouteCheck | null; run: () => void;
}) {
return <Window open={open} title="Проверка маршрута" size="md" onClose={onClose}><div className="mission-planner__check">
<Description>Проверка сохранённой записи и выбранного участка. Новый проход со сканером для этой проверки не требуется.</Description>
<LoadingRegion loading={busy} label="Проверка исходных данных">
{error && <Description role="alert">{error}</Description>}
{report && <><dl>
<div><dt>Исходная запись</dt><dd>{report.source_verified ? "Контрольные суммы совпадают" : "Недоступна"}</dd></div>
<div><dt>Версия черновика</dt><dd>{report.revision}</dd></div>
<div><dt>Длина маршрута</dt><dd>{report.length_m.toFixed(2)} м</dd></div>
<div><dt>Положения сканера</dt><dd>{report.pose_count.toLocaleString("ru-RU")}</dd></div>
<div><dt>Максимальный шаг</dt><dd>{report.max_step_m.toFixed(2)} м</dd></div></dl>
{report.warnings.map(w => <Description key={w}>{w}</Description>)}
<Description>Совмещение с повторным проходом не выполнялось. Записанная траектория описывает движение сканера; проходимость для аппарата по ней не проверена.</Description></>}
<Button disabled={busy} onClick={run}>{report ? "Повторить проверку" : "Начать проверку"}</Button>
</LoadingRegion>
</div></Window>;
}
@@ -0,0 +1,29 @@
import { useEffect, useMemo, useState } from "react";
import { Description, RangeControl } from "@nodedc/ui-react";
import { routeLength, type PlanningPose, type PlanningSource } from "../../core/missions/planner";
/** Equal-axis plan projection; the moving marker is an archive pose, not localization. */
export function MissionRoutePreview({ source, poses }: { source: PlanningSource; poses: PlanningPose[] }) {
const [cursor, setCursor] = useState(0);
useEffect(() => setCursor(0), [poses]);
const projection = useMemo(() => {
let xmin = Infinity, xmax = -Infinity, ymin = Infinity, ymax = -Infinity;
for (const p of (poses.length ? poses : source.poses)) { xmin = Math.min(xmin, p.position[0]); xmax = Math.max(xmax, p.position[0]); ymin = Math.min(ymin, p.position[1]); ymax = Math.max(ymax, p.position[1]); }
const scale = Math.min(720 / Math.max(1, xmax - xmin), 400 / Math.max(1, ymax - ymin));
const project = (p: PlanningPose) => [400 + (p.position[0] - (xmin + xmax) / 2) * scale, 240 - (p.position[1] - (ymin + ymax) / 2) * scale];
const line = (items: PlanningPose[]) => items.filter((_, i) => i % Math.max(1, Math.ceil(items.length / 5000)) === 0 || i === items.length - 1).map(p => project(p).join(",")).join(" ");
return { project, reference: line(source.poses), selected: line(poses), scale };
}, [source, poses]);
const point = poses[Math.min(cursor, poses.length - 1)];
if (!point) return <div className="session-overview__empty">Выберите участок траектории.</div>;
const [x, y] = projection.project(point);
return <div className="mission-route-preview"><h2>Выбранный маршрут · вид сверху</h2>
<svg viewBox="0 0 800 480" role="img" aria-label="Траектория записи и выбранный маршрут">
<polyline points={projection.reference} className="mission-route-preview__reference" fill="none" />
<polyline points={projection.selected} className="mission-route-preview__selected" fill="none" />
<circle cx={x} cy={y} r="6" className="mission-route-preview__cursor" />
<path d="M40 450h100" className="mission-route-preview__selected" /><text x="40" y="438">{(100 / projection.scale).toFixed(1)} м</text>
</svg><Description>Путь: {routeLength(poses).toFixed(2)} м · {poses.length.toLocaleString("ru-RU")} положений · X/Y, масштаб осей одинаковый</Description>
<RangeControl label="Положение на маршруте" value={Math.min(cursor, poses.length - 1) + 1} min={1} max={poses.length} step={1} formatValue={n => `${n} / ${poses.length}`} onChange={n => setCursor(n - 1)} />
<Description>Кадр {point.index + 1} · X {point.position[0].toFixed(2)} · Y {point.position[1].toFixed(2)} · Z {point.position[2].toFixed(2)} м</Description>
</div>;
}
@@ -0,0 +1,12 @@
import type {ReactNode} from "react";
import { Button, LoadingRegion } from "@nodedc/ui-react";
import { useSessionOverview } from "../../core/observation/useSessionOverview";
import { SessionOverviewScene } from "../observation/SessionOverviewScene";
export function MissionZonePreview({ sessionId, generation, toolbar }: { sessionId: string; generation: string; toolbar?:ReactNode }) {
const { data, error, retry } = useSessionOverview(sessionId);
const pending = !error && (!data || data.state === "queued" || data.state === "preparing");
const failure = error || (data?.state === "error" ? data.message : null);
if (pending) return <LoadingRegion loading label="Подготовка облака зоны" className="mission-planner__zone-loading" />;
if (failure || !data?.scene_url) return <div className="session-overview__empty"><span>{failure || "Облако записи недоступно."}</span><Button onClick={retry}>Повторить</Button></div>;
return <SessionOverviewScene sourceUrl={`${data.scene_url}&reference_generation=${encodeURIComponent(generation)}`} toolbar={toolbar} hideTitle />;
}
@@ -0,0 +1,23 @@
import type {ReactNode} from 'react';
import { Description,Button, StatusBadge} from '@nodedc/ui-react';
import {planningAwaitsCapture, usePlanningTest} from '../../core/missions/PlanningTestContext';
/** Composition-level handoff; never sends a device or acquisition command. */
export function PlanningCaptureGuard({enabled, onResume, children}: {
enabled: boolean;
onResume: () => void;
children: ReactNode;
}) {
const planning = usePlanningTest();
if (!enabled || !planningAwaitsCapture(planning.test)) return <>{children}</>;
return <div className="mission-planner__check">
<StatusBadge tone="warning">Исследование ожидает новую запись</StatusBadge>
<Description>{planning.test!.draft.name}</Description>
<Description>Для самостоятельной съёмки завершите подготовленное исследование. Запись и подключение сканера не будут остановлены.</Description>
{planning.error && <Description role="alert">{planning.error}</Description>}
<div className="mission-planner__actions">
<Button loading={planning.busy} onClick={() => void planning.finish()}>Завершить исследование</Button>
<Button disabled={planning.busy} onClick={onResume}>Вернуться к исследованию</Button>
</div>
</div>;
}
@@ -0,0 +1,32 @@
import {useEffect,useState,type ReactNode} from 'react';
import { Description,Button,LoadingRegion,StatusBadge,Window} from '@nodedc/ui-react';
import {useDevicePluginHost} from '../../core/device-plugins/DevicePluginHost';
import {planningTestTerminal,usePlanningTest} from '../../core/missions/PlanningTestContext';
/** Wrap the existing plugin connection flow, retaining its acquisition authority. */
export function PlanningConnectionWindow({children}:{children:ReactNode}){
const p=usePlanningTest(); const [open,setOpen]=useState(true);
const {selection,registry,selectModel,selectionTransitionPending}=useDevicePluginHost();
useEffect(()=>{
if(!p.test||planningTestTerminal(p.test)||selection||selectionTransitionPending)return;
const models=registry.models.filter(m=>m.plugin.manifest.metadata.id===p.test!.plugin_id);
if(models.length===1)void selectModel(models[0].model.id);
},[p.test?.plugin_id,p.test?.state,selection,registry,selectModel,selectionTransitionPending]);
if(!p.test)return <>{children}</>;
const t=p.test, terminal=planningTestTerminal(t);
const details=<><StatusBadge tone="neutral">Профиль · Планирование</StatusBadge>
<Description>{t.draft.name} · эталон {t.draft.zone.label} · {t.draft.route.length_m.toFixed(1)} м</Description>
<Description>Укажите новое имя проекта сканера. Неподвижная калибровка просматривает весь выбранный маршрут; после калибровки сканера оставайтесь на месте до статуса «Сопровождение». Если совпадение не найдено или неоднозначно, сцена сообщит причину и не начнёт сопровождение.</Description></>;
return <div className="mission-planner__check">
{details}<Description>{t.message}</Description>{p.error&&<Description role="alert">{p.error}</Description>}
<div className="mission-planner__actions"><Button onClick={()=>setOpen(true)}>Подключение сканера</Button>
{t.state==='running'&&t.planning_phase==='lost'&&!t.tracking_established&&<Button loading={p.busy} onClick={()=>void p.retryInitialization()}>Переинициализировать</Button>}
{!terminal&&<Button loading={p.busy} onClick={()=>void p.finish()}>Завершить исследование</Button>}</div>
<Window open={open} title="Подключение сканера · Планирование" size="lg" className="planning-connection" onClose={()=>setOpen(false)}>
<div className="mission-planner__check">{details}
{t.state==='preparing'?<LoadingRegion loading label="Подготовка эталонного участка" />
: terminal?<Description>{t.message}</Description>:children}
</div>
</Window>
</div>;
}
@@ -0,0 +1,108 @@
import {heightSlice} from "../../core/heightSlice";
import {useEffect,useRef,useState} from 'react';
import {Button,LoadingRegion,RangeControl} from '@nodedc/ui-react';
import {createIsolatedRerunHost} from '../rerun/isolatedRerunHost';
import {plannerBase} from '../../core/missions/planner';
import {startPlanningSceneStream} from '../../core/missions/planningSceneStream';
import {createPlanningPresentationReporter} from '../../core/missions/planningPresentationTelemetry';
function nextAnimationFrame(limitMs=500):Promise<number|null>{
return new Promise(resolve=>{
let frame:number|undefined,settled=false;
const finish=(value:number|null)=>{
if(settled)return;
settled=true;
if(frame!==undefined&&value===null)cancelAnimationFrame(frame);
clearTimeout(timeout);resolve(value);
};
const timeout=setTimeout(()=>finish(null),limitMs);
frame=requestAnimationFrame(()=>finish(performance.now()));
});
}
/** One persistent viewer/channel. Updates replace entities without resetting the camera. */
type HeightBounds={min:number;max:number};
const CLIP_CEILING_M=80;
export function PlanningLiveScene({runId,options={},active=false,revision=0,heightBounds=null}:{runId:string;options?:Record<string,string|number|boolean>;active?:boolean;revision?:number;heightBounds?:HeightBounds|null}){
const optionsRef=useRef(options);optionsRef.current=options;
const stateRef=useRef({active,revision});stateRef.current={active,revision};
const ceilingRef=useRef<number|null>(null);
const floorRef=useRef<number|null>(null);
const boundsRef=useRef<{min:number;max:number}|null>(null);
const host=useRef<HTMLDivElement>(null);
const [state,setState]=useState('loading'),[retry,setRetry]=useState(0);
const [bounds,setBounds]=useState<{min:number;max:number}|null>(null);
const [ceiling,setCeiling]=useState<number|null>(null);
const [floor,setFloor]=useState<number|null>(null);
useEffect(()=>{
ceilingRef.current=null;floorRef.current=null;setCeiling(null);setFloor(null);
},[runId]);
useEffect(()=>{
const next=heightBounds&&Number.isFinite(heightBounds.min)&&Number.isFinite(heightBounds.max)&&heightBounds.max>heightBounds.min?heightBounds:null;
boundsRef.current=next;
setBounds(next);
},[runId,heightBounds?.min,heightBounds?.max]);
useEffect(()=>{
if(!host.current)return;
let disposed=false,sceneAvailable=false,stopStream:(()=>void)|undefined;
const reporter=createPlanningPresentationReporter({
url:`${plannerBase}/live-tests/${runId}/presentation-observations`,
});
const runtime=createIsolatedRerunHost(host.current);setState('loading');
const timeout=setTimeout(()=>{if(!disposed){setState('error');stopStream?.();runtime.dispose();}},60000);
void runtime.ready.then(async({viewer,mount})=>{
if(disposed)return;
await viewer.start(null,mount,{width:'100%',height:'100%',hide_welcome_screen:true,enable_history:false,allow_fullscreen:false});
if(disposed)return;
const channel=viewer.open_channel('planning-'+runId);
viewer.on('recording_open',()=>{if(!disposed&&sceneAvailable){clearTimeout(timeout);setState('ready');}});
stopStream=startPlanningSceneStream({
url:`${plannerBase}/live-tests/${runId}/scene-delta.rrd`,
snapshot:()=>({...stateRef.current,options:{...optionsRef.current,
...(floorRef.current===null?{}:{floor_m:floorRef.current}),
...(ceilingRef.current===null?{}:{ceiling_m:ceilingRef.current})}}),
apply:async(bytes,delivery)=>{
if(disposed)return;
if(delivery.heightMinM!==null&&delivery.heightMaxM!==null&&delivery.heightMaxM>delivery.heightMinM){
const next={min:delivery.heightMinM,max:delivery.heightMaxM};
const previous=boundsRef.current;
if(!previous||previous.min!==next.min||previous.max!==next.max){
boundsRef.current=next;setBounds(next);
}
}
sceneAvailable=true;
const admissionStarted=performance.now();
channel.send_rrd(bytes);
const admissionEnded=performance.now();
for(const panel of ['top','blueprint','selection','time'] as const)viewer.override_panel_state(panel,'hidden');
if(viewer.get_active_recording_id()){clearTimeout(timeout);setState('ready');}
// Rerun exposes no canvas-paint receipt. Two bounded browser frame
// opportunities are retained as an explicit proxy, never as a GPU claim.
const first=await nextAnimationFrame();
const second=first===null?null:await nextAnimationFrame();
if(!disposed)reporter.record(delivery,{
rerunAdmissionMs:admissionEnded-admissionStarted,
firstAnimationFrameMs:first===null?null:first-admissionEnded,
secondAnimationFrameMs:second===null?null:second-admissionEnded,
});
},
error:()=>{sceneAvailable=false;if(!disposed)setState('error');},
});
}).catch(()=>{if(!disposed){clearTimeout(timeout);setState('error');}});
return()=>{disposed=true;stopStream?.();reporter.dispose();clearTimeout(timeout);runtime.dispose();};
},[runId,retry]);
const sourceBounds=bounds??heightBounds;
const rangeBounds=sourceBounds?{min:Math.min(sourceBounds.min,0,floor??Infinity),max:Math.max(CLIP_CEILING_M,sourceBounds.max,ceiling??-Infinity)}:null;
return <LoadingRegion loading={state==='loading'} label="Загрузка эталона и нового прохода" className="planning-live__scene">
<div ref={host} className="session-overview__runtime rerun-single-view-content" style={{visibility:state==='ready'?'visible':'hidden'}} />
{rangeBounds&&state==='ready'&&<div className="session-overview__height">
<RangeControl orientation="vertical" limitSide="left" label="Срез" value={[floor??rangeBounds.min,ceiling??rangeBounds.max]} min={rangeBounds.min} max={rangeBounds.max} step="any"
formatValue={value=>`${value.toFixed(1).replace('.',',')} м`} formatLimit={value=>value.toFixed(1).replace('.',',')}
onChange={value=>{
const next=heightSlice(value,[rangeBounds.min,rangeBounds.max]);
floorRef.current=next.floor;setFloor(next.floor);ceilingRef.current=next.ceiling;setCeiling(next.ceiling);
}}/>
</div>}
{state==='error'&&<div className="session-overview__empty"><span>Обновление сцены недоступно.</span><Button onClick={()=>setRetry(v=>v+1)}>Повторить подключение сцены</Button></div>}
</LoadingRegion>;
}
@@ -0,0 +1,25 @@
import { Description, Inspector, Icon, StatusBadge } from '@nodedc/ui-react';
import { planningProjectStatus, type PlanningProjectDetail } from '../../core/missions/planningProjects';
export function PlanningProjectResult({project:p}:{project:PlanningProjectDetail}) {
const r=p.result;
return <Inspector variant="panel" defaultOpen={['sources','result']} sections={[
{id:'sources',label:'Проект',icon:<Icon name="file"/>,content:<div className="inspector-control-stack">
<Description>{p.name}</Description><small>{new Date(p.created_at_utc).toLocaleString('ru-RU')}</small>
<dl><div><dt>Эталон</dt><dd>{p.reference_label}</dd></div><div><dt>Повторный проход</dt><dd>{p.query_label??'—'}</dd></div>
<div><dt>Участок эталона</dt><dd>{p.draft.route.length_m.toFixed(2)} м</dd></div></dl>
</div>},
{id:'result',label:'Результат',icon:<Icon name="activity"/>,content:<div className="inspector-control-stack">
<StatusBadge tone={r?.status==='rejected'?'warning':'neutral'}>{planningProjectStatus(p)}</StatusBadge>
{r?<><dl><div><dt>Точки в пределах 0,5 м</dt><dd>{(r.overlap*100).toFixed(1)}%</dd></div>
<div><dt>Расхождение поверхностей</dt><dd>{r.inlier_rmse_m==null?'—':`${r.inlier_rmse_m.toFixed(3)} м`}</dd></div>
{r.correction_m!=null&&<div><dt>Уточнение привязки</dt><dd>{r.correction_m.toFixed(2)} м · {r.correction_deg.toFixed(1)}°</dd></div>}
{r.registration_seconds!=null&&<div><dt>Расчёт</dt><dd>{r.registration_seconds.toFixed(2)} с</dd></div>}
</dl><small>Совпадение поверхностей не является измеренной точностью положения.</small></>:<Description>{p.message?`Сохранённое сообщение: ${p.message}`:'Расчёт совмещения ещё не выполнен.'}</Description>}
{p.evidence_relation==='same_recording'&&<small>Оба участка из одной записи: внутренняя проверка общей карты.</small>}
{p.scene_note&&p.scene_url&&<small>{p.scene_note}</small>}
{r?.reasons.map(reason=><small key={reason}>{reason}</small>)}
{!p.scene_url&&r&&<small>Сохранённое совмещённое облако недоступно.</small>}
</div>},
]}/>;
}
@@ -0,0 +1,47 @@
import { useState } from 'react';
import { Description, ConfirmationModal, Icon, Select, ToastStack } from '@nodedc/ui-react';
import { planningProjectDeletable, planningProjectStatus, type PlanningProject } from '../../core/missions/planningProjects';
export function PlanningProjectSelect({items, value, disabled, onChange, onRemove}: {
items: PlanningProject[];
value: string;
disabled?: boolean;
onChange: (key: string) => void;
onRemove: (project: PlanningProject) => Promise<void>;
}) {
const [target, setTarget] = useState<PlanningProject | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
return <>
<Select label="Совмещённые маршруты" value={value} disabled={disabled || busy} searchable
options={[{value: '', label: 'Совмещённые маршруты'}, ...items.map(item => ({
value: item.key, label: item.name,
description: `${new Date(item.created_at_utc).toLocaleString('ru-RU')} · ${planningProjectStatus(item)}${item.query_label ? ` · ${item.query_label}` : ''}`,
action: {
label: `Удалить совмещённый маршрут ${item.name} · ${new Date(item.created_at_utc).toLocaleString('ru-RU')}`,
icon: <Icon name="trash" />,
tone: 'danger' as const,
disabled: !planningProjectDeletable(item),
onAction: () => { setError(null); setTarget(item); },
},
}))]}
onChange={key => { if (key) onChange(key); }} />
<ConfirmationModal open={target !== null} title="Удалить совмещённый маршрут?"
description={target ? <>
<strong>{target.name}</strong>
<Description>{new Date(target.created_at_utc).toLocaleString('ru-RU')} · {planningProjectStatus(target)}</Description>
<Description>Проект будет удалён из списка совмещённых маршрутов. Эталон, запись прохода и сохранённые отчёты останутся на диске. Другие проекты не изменятся.</Description>
</> : null}
confirmLabel="Удалить маршрут" pendingLabel="Удаление…" danger
onClose={() => { if (!busy) setTarget(null); }}
onConfirm={async () => {
if (!target || busy) return;
setBusy(true); setError(null);
try { await onRemove(target); setTarget(null); }
catch (e) { setError(e instanceof Error ? e.message : 'Не удалось удалить проект. Повторите попытку.'); }
finally { setBusy(false); }
}} />
<ToastStack items={error ? [{id: 'planning-project-delete-error', tone: 'error', title: 'Маршрут не удалён', description: error}] : []}
onDismiss={() => setError(null)} />
</>;
}
@@ -0,0 +1,30 @@
import { Description, Button, Icon, Inspector, InspectorSelectField, TextField } from '@nodedc/ui-react';
import { routeLength, canStartPlanningRoute } from '../../core/missions/planner';
import type { useMissionPlanner } from '../../core/missions/useMissionPlanner';
export function PlanningProjectSettings({p,onStart,starting}:{
p:ReturnType<typeof useMissionPlanner>; onStart:()=>void; starting:boolean;
}) {
const disabled=p.busy||starting;
const length=routeLength(p.poses);
const routeReady=canStartPlanningRoute(length,'scanner');
return <><Inspector variant="panel" defaultOpen={['project','zone']} sections={[
{id:'project',label:'Проект',icon:<Icon name="file"/>,content:<div className="inspector-control-stack">
<TextField label="Название проекта" placeholder="Название совмещения" value={p.name} maxLength={120} disabled={disabled} onChange={e=>p.setName(e.target.value)}/>
</div>},
{id:'zone',label:'Эталон',icon:<Icon name="globe"/>,content:<div className="inspector-control-stack">
<InspectorSelectField label="Сохранённая запись" searchable value={p.sessionId} options={p.options} disabled={disabled||p.catalogBusy} onChange={p.chooseSource}/>
{p.cursor&&<Button disabled={p.catalogBusy} onClick={()=>void p.loadMore()}>Ещё записи</Button>}
{p.source&&<>
<small>Вся запись · {p.source.path_m.toFixed(2)} м · {p.source.poses.length.toLocaleString('ru-RU')} положений</small>
<InspectorSelectField label="Направление" value={p.direction} onChange={p.setDirection} disabled={disabled} options={[{value:'forward',label:'По записи'},{value:'reverse',label:'В обратную сторону'}]}/>
</>}
</div>},
]}/>
<div className="inspector-control-stack">
{p.source&&!routeReady&&<small>В записи недостаточно перемещения для привязки. Выберите другой эталон.</small>}
<Button variant="primary" loading={starting} disabled={disabled||!p.ready||!routeReady} onClick={onStart}><Icon name="play"/>Начать новый проход</Button>
{p.error&&<Description role="alert">{p.error}</Description>}
</div>
</>;
}
@@ -0,0 +1,19 @@
import {useState,type ReactNode,type RefObject} from 'react';
import {WorkspaceWindow,type WorkspaceWindowRect} from '@nodedc/ui-react';
/** A scene-bounded tool: never a portal, backdrop or renderer owner. */
export function PlanningSceneToolWindow({boundsRef,title,children,onClose}:{
boundsRef:RefObject<HTMLDivElement|null>;title:string;children:ReactNode;onClose:()=>void;
}){
const [rect,setRect]=useState<WorkspaceWindowRect>({x:16,y:120,width:390,height:260});
const [maximized,setMaximized]=useState(false);
return <WorkspaceWindow boundsRef={boundsRef} rect={rect} onRectChange={setRect}
title={title} maximized={maximized} onMaximizedChange={setMaximized}
minWidth={280} minHeight={200} active zIndex={100} onClose={onClose}
closeLabel="Закрыть инструмент" moveLabel="Переместить инструмент"
resizeLabel="Изменить размер инструмента" maximizeLabel="Развернуть инструмент" restoreLabel="Восстановить инструмент" onKeyDown={event=>{
if(event.key==='Escape'&&!event.defaultPrevented){event.preventDefault();event.stopPropagation();onClose();}
}}>
<div className="mission-planner__check">{children}</div>
</WorkspaceWindow>;
}
@@ -0,0 +1,30 @@
import { useEffect, useRef, useState } from "react";
import { Button, LoadingRegion } from "@nodedc/ui-react";
import { createIsolatedRerunHost } from "../rerun/isolatedRerunHost";
/** One isolated, read-only Rerun realm; disposal releases its WASM memory. */
export function RegistrationScene({ sourceUrl }: { sourceUrl: string }) {
const host = useRef<HTMLDivElement>(null);
const [state, setState] = useState("loading"), [retry, setRetry] = useState(0);
useEffect(() => {
if (!host.current) return;
let disposed = false; setState("loading");
const runtime = createIsolatedRerunHost(host.current);
const timer = window.setTimeout(() => { if (!disposed) { setState("error"); runtime.dispose(); } }, 60_000);
void runtime.ready.then(async ({ viewer, mount }) => {
if (disposed) return;
viewer.on("recording_open", () => { if (!disposed) { clearTimeout(timer); setState("ready"); } });
await viewer.start(new URL(sourceUrl, window.location.origin).href, mount, {
width: "100%", height: "100%", hide_welcome_screen: true, enable_history: false, allow_fullscreen: false,
});
if (disposed) return;
if (viewer.get_active_recording_id()) { clearTimeout(timer); setState("ready"); }
for (const panel of ["top", "blueprint", "selection", "time"] as const) viewer.override_panel_state(panel, "hidden");
}).catch(() => { if (!disposed) { clearTimeout(timer); setState("error"); runtime.dispose(); } });
return () => { disposed = true; clearTimeout(timer); runtime.dispose(); };
}, [sourceUrl, retry]);
return <LoadingRegion loading={state === "loading"} label="Загрузка совмещённых облаков" className="mission-registration__scene">
<div ref={host} className="session-overview__runtime rerun-single-view-content" style={{ visibility: state === "ready" ? "visible" : "hidden" }} />
{state === "error" && <div className="session-overview__empty"><span>Облако недоступно.</span><Button onClick={() => setRetry(n => n+1)}>Повторить</Button></div>}
</LoadingRegion>;
}
@@ -0,0 +1,11 @@
import {Fragment,useEffect,useState} from 'react';
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]};
export function InstallerCard({kind,connectionInstruction}:{connectionInstruction?:string;kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'|'vps-librespeed'|'vps-egress'}){
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((original,index)=>{const step=connectionInstruction&&index===item.instructions.length-1?connectionInstruction:original;return <Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>;})}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
<Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button>
</SettingsCard>;
}
@@ -0,0 +1,15 @@
import {useRef} from 'react';
import {Button,Description,Icon,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {useNetBirdBackups} from '../../core/fleet/useNetBirdBackups';
export function NetBirdBackups(){
const {items,loading,busy,error,upload}=useNetBirdBackups();const input=useRef<HTMLInputElement>(null);
return <SettingsCard title="Резервные копии сети" description="Полная копия базы NetBird, ключей и зарегистрированных устройств хранится в этом Mission Core отдельно от VPS. Она содержит секреты сети." actions={<StatusBadge tone={items.length?'success':'warning'}>{loading?'Проверяем хранилище':items.length?`Сохранено: ${items.length}`:'Копий пока нет'}</StatusBadge>}>
<Description>После изменения устройств или настроек сети сохраните свежую копию. Автоматическое получение копий пока не настроено.</Description>
<input ref={input} type="file" accept=".zip,application/zip" hidden aria-label="Полная резервная копия NetBird" disabled={busy} onChange={event=>{const file=event.target.files?.[0];event.target.value='';if(file)void upload(file);}}/>
<Button icon={<Icon name="upload"/>} loading={busy} disabled={busy||loading} onClick={()=>input.current?.click()}>Сохранить копию в Mission Core</Button>
{error&&<StatusBadge tone="danger">{error}</StatusBadge>}
{items.map(item=><SettingsCard key={item.id} title={item.domain} description={`Сохранена ${new Date(item.stored_at).toLocaleString('ru-RU')} · ${(item.bytes/1024/1024).toFixed(1)} МиБ · Контрольные суммы проверены`}>
<Button icon={<Icon name="download"/>} onClick={()=>{const link=document.createElement('a');link.href=`/api/v1/fleet/netbird/backups/${item.id}/download`;link.download='mission-core-netbird-backup.zip';link.click();}}>Скачать для восстановления</Button>
</SettingsCard>)}
</SettingsCard>;
}
@@ -0,0 +1,36 @@
import {useEffect,useState} from 'react';
import {Button,Description,Icon,Select,SettingsCard,StatusBadge,TextField} from '@nodedc/ui-react';
import {InstallerCard} from './InstallerCard';
import {NetBirdBackups} from './NetBirdBackups';
import {useNetBird,type NetBirdState} from '../../core/fleet/useNetBird';
const labels:Record<NetBirdState,string>={missing_client:'Клиент не установлен',unsupported_client:'Требуется другая версия клиента',unavailable:'Клиент недоступен',disconnected:'Не подключён',connecting:'Подключение',connected:'Подключён',other_network:'Клиент подключён к другой сети',address_conflict:'Проверьте адресацию сервера'};
export function NetBirdConnection(){
const network=useNetBird();const {status,clients,error,busy,clientError}=network;
const [server,setServer]=useState(''),[edited,setEdited]=useState(false),[installer,setInstaller]=useState('macos');
useEffect(()=>{if(!edited&&status?.server_url)setServer(status.server_url);},[status?.server_url,edited]);
const selected=clients.find(item=>item.id===installer);
const state=status?.pending==='installing'?'Устанавливаем клиент':status?.pending==='cancelling'?'Отменяем подключение':status?.pending==='authentication'?'Требуется вход':status?.pending==='verifying'?'Проверяем соединение':status?.pending?'Подключаемся':status?labels[status.state]:'Получаем состояние';
return <>
<InstallerCard kind="vps-netbird"/>
<NetBirdBackups/>
<SettingsCard title="Этот компьютер" description="NetBird соединяет компьютеры через ваш сервер. Вход выполняется в браузере; подключение поддерживает системный клиент." actions={<StatusBadge tone={busy?'warning':status?.state==='connected'?'success':'neutral'}>{state}</StatusBadge>}>
<TextField label="Адрес сервера NetBird" placeholder="https://netbird.example.com" value={server} maxLength={300} disabled={busy} onChange={event=>{setEdited(true);setServer(event.target.value);}} hint="Адрес выдаёт установщик VPS или администратор вашей сети."/>
{status?.state==='connected'&&<Description>Адрес этого компьютера: {status.address}</Description>}
{status?.can_install&&['missing_client','unsupported_client'].includes(status.state)&&<Button disabled={busy||!clients.find(item=>item.id==='macos')?.available} onClick={()=>void network.action('install')}>Установить клиент на этот Mac</Button>}
<Button variant="primary" disabled={busy||!server.trim()||!status||['missing_client','unsupported_client','unavailable','other_network'].includes(status.state)} onClick={()=>void network.action('connect',server)}>{status?.state==='connected'?'Проверить подключение':'Подключить этот компьютер'}</Button>
{status?.pending&&status.pending!=='installing'&&<Button disabled={network.requestBusy||status.pending==='cancelling'} onClick={()=>void network.action('cancel')}>Прекратить ожидание</Button>}
{status?.auth_url&&<Button onClick={()=>window.open(status.auth_url,'_blank','noopener,noreferrer')}>Войти на сервере</Button>}
{status?.pending==='installing'&&<Description>Подтвердите системный запрос macOS. Пароль администратора вводится только в системном окне.</Description>}
{(error||status?.error)&&<StatusBadge tone="danger">{error||status?.error}</StatusBadge>}
</SettingsCard>
<SettingsCard title="Клиенты для других компьютеров" description={`Официальные установщики NetBird${status?.client_version?' '+status.client_version:''}. Файлы хранятся в этом Mission Core и проверяются перед скачиванием.`}>
{clientError&&<StatusBadge tone="danger">{clientError}</StatusBadge>}
<Select label="Операционная система" value={installer} options={clients.map(item=>({value:item.id,label:item.label}))} onChange={setInstaller}/>
<Button icon={<Icon name="download"/>} disabled={!selected?.available} onClick={()=>{if(selected){const link=document.createElement('a');link.href=selected.download_url;link.download=selected.filename;link.click();}}}>Скачать клиент</Button>
<Description>Установите клиент, укажите этот же адрес сервера в его настройках и выполните вход. Mission Core на другом компьютере для подключения к сети не требуется.</Description>
{installer.startsWith('linux')&&<Description>Пакет «интерфейс» устанавливается вместе с основным клиентом той же версии. Для устройства без экрана используйте ключ подключения из панели NetBird.</Description>}
{selected&&!selected.available&&<Description>Этот установщик пока отсутствует в локальном каталоге.</Description>}
</SettingsCard>
</>;
}
@@ -0,0 +1,50 @@
import {useState} from 'react';
import {Button,Description,Select,SettingsCard} from '@nodedc/ui-react';
import {useServers,useServerHealth} from '../../core/system/servers';
import {selectedSpeedServer,speedtestServers} from '../../core/system/speedtestServers';
import {useCoreSpeedtest} from '../../core/system/networkSpeedtest';
import {ServerServiceSetup} from '../system/ServerServiceSetup';
import {RouterSpeedGauge} from './RouterSpeedGauge';
import './networkSettings.css';
const format=(value:number)=>`${new Intl.NumberFormat('ru-RU',{maximumFractionDigits:1}).format(value)} мс`;
export function NetworkSettings(){
const servers=useServers(),health=useServerHealth(servers.items,servers.generation),test=useCoreSpeedtest();
const [selected,setSelected]=useState(''),[setup,setSetup]=useState(false);
const items=speedtestServers(servers.items,health);
const chosen=selectedSpeedServer(items,selected,test.running?test.receipt?.server_id:undefined);
const measurement=test.receipt?.measurement;
const busy=test.sending||test.running;
const ready=test.loaded&&test.fresh&&chosen?.online&&!servers.error;
return <>
<SettingsCard title="Замер скорости" description="Проверяется интернет компьютера, на котором работает Mission Core. Замер занимает около 30 секунд.">
{!servers.items&&!test.receipt?<Description role="status">{servers.error||'Получаем список VPS…'}</Description>:items.length===0&&!test.receipt?<>
<Description>Для замера подключите службу LibreSpeed на одном из ваших VPS.</Description>
<Button disabled={busy||!!servers.error} onClick={()=>setSetup(true)}>Добавить службу</Button>
</>:<>
{items.length>0?<Select label="Сервер замера" disabled={busy} value={chosen?.service.id??''} onChange={setSelected}
options={[{value:'',label:'Выберите VPS'},...items.map(item=>({value:item.service.id,label:`${item.server.name} · ${item.server.address}${item.online?'':` · ${item.label}`}`}))]}/>:<Description>Служба замера больше не доступна в списке VPS.</Description>}
{chosen&&!chosen.online&&<Description role="status">Служба не подтвердила доступность. Список обновляется автоматически.</Description>}
{servers.error&&<Description role="alert">{servers.error}</Description>}
<RouterSpeedGauge key={test.receipt?.operation_id??'idle'} measurement={measurement} waiting={test.receipt?.state==='queued'} fresh={test.fresh} staleLabel="Обновляем данные замера"/>
{test.receipt?.state==='cancelling'&&<Description role="status">Останавливаем замер…</Description>}
{measurement?.phase==='complete'&&<>
<dl className="network-speed-facts">
<div><dt>Задержка HTTP</dt><dd>{format(measurement.latency_ms)}</dd></div>
<div><dt>Джиттер HTTP</dt><dd>{format(measurement.jitter_ms)}</dd></div>
</dl>
<Description>{test.receipt?.server_name} · {new Date((measurement.finished_at??measurement.started_at)*1000).toLocaleString('ru-RU')}</Description>
</>}
{measurement?.phase==='error'&&<Description role="alert">Замер не завершён. Проверьте соединение и доступность VPS. Возможно, на сервере уже идёт другой замер.</Description>}
{test.loaded&&!test.fresh&&<Description role="status">Нет свежих данных от Mission Core. Состояние замера уточняется.</Description>}
<div className="network-speed-actions">
{test.running?<Button disabled={test.sending||test.receipt?.state==='cancelling'} onClick={()=>void test.cancel()}>Остановить замер</Button>:<Button disabled={test.sending||!ready} loading={test.sending} onClick={()=>chosen&&void test.start(chosen.service.id)}>Начать замер</Button>}
<Button disabled={busy} onClick={()=>setSetup(true)}>Добавить службу</Button>
</div>
<Description>Используется текущее соединение компьютера, включая VPN, если он включён. Результат относится к выбранному VPS и времени замера.</Description>
</>}
{test.error&&<Description role="alert">{test.error}</Description>}
</SettingsCard>
{setup&&<ServerServiceSetup fixedKind="librespeed" onClose={()=>setSetup(false)} onSaved={()=>{setSetup(false);servers.refresh();}}/>}
</>;
}
@@ -0,0 +1,9 @@
import {Button,Window,WindowFooterActions} from '@nodedc/ui-react';
import {NetBirdConnection} from './NetBirdConnection';
export function OperatorNetworkWindow({onClose}:{onClose:()=>void}){
return <Window open title="Сеть операторского компьютера" subtitle="NetBird · WireGuard" size="lg" onClose={onClose}
footer={<WindowFooterActions><Button variant="secondary" onClick={onClose}>Закрыть</Button></WindowFooterActions>}>
<NetBirdConnection/>
</Window>;
}
@@ -0,0 +1,24 @@
import {Description,StatusBadge} from '@nodedc/ui-react';
import {ObservationHeader} from '../../../../../packages/sensor-ui/src/ObservationHeader';
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
import {metric,type RouterDevice,type RouterSnapshot} from '../../../../../packages/router-ui/src/contracts';
import {RouterSignal} from '../../../../../packages/router-ui/src/RouterSignal';
import {routerObservation} from '../../core/fleet/routerObservation';
import '../../../../../packages/router-ui/src/router.css';
import './routerObservation.css';
export function RouterObservation({device,value,compact=false,header}:{device:RouterDevice;value:RouterSnapshot|null;compact?:boolean;header?:ObservationHeaderTargets}){
const view=routerObservation(device,value);
return <div className="router-observation" aria-label={`Связь · ${view.name}`}>
{header&&<ObservationHeader targets={header} live={view.live} waiting={view.waiting} label={view.status}/>}
{!compact&&<div>
<div className="router-observation__summary"><strong>{view.mode.current}</strong><StatusBadge variant="indicator" tone={view.ready?'success':'neutral'} aria-label={view.status} title={view.status}/></div>
<Description>{view.internet}</Description>
{view.ready&&view.mode.message&&<Description role="status">{view.mode.message}</Description>}
</div>}
{view.channels.map(channel=><section key={channel.slot} className="router-observation__channel" aria-label={`${channel.label} · ${channel.detail} · ${channel.status}`}>
<div className="router-observation__summary"><StatusBadge variant="indicator" tone={channel.indicator} aria-label={`${channel.label} · ${channel.indicatorLabel}`} title={`${channel.label} · ${channel.indicatorLabel}`}/><strong>{channel.label}</strong><span>{channel.operator}</span><strong className="router-observation__value">{channel.rsrp==null?'—':metric(channel.rsrp,'dBm')}</strong></div>
{!compact&&<RouterSignal rsrp={channel.rsrp} compact/>}
</section>)}
</div>;
}
@@ -0,0 +1,52 @@
import {useEffect,useRef,useState} from 'react';
import {Description,Icon} from '@nodedc/ui-react';
import type {SpeedMeasurement} from '../../../../../packages/router-ui/src/contracts';
import {speedFraction,speedPoint,speedTrack,speedValues} from './speedGauge';
import './routerSpeedGauge.css';
function useMarker(target:number){
const [position,setPosition]=useState(target),last=useRef(target);
useEffect(()=>{
if(window.matchMedia('(prefers-reduced-motion: reduce)').matches){last.current=target;setPosition(target);return;}
const start=performance.now(),from=last.current;let frame=0;
function animate(now:number){const t=Math.min(1,(now-start)/650),next=from+(target-from)*(1-Math.pow(1-t,3));last.current=next;setPosition(next);if(t<1)frame=requestAnimationFrame(animate);}
frame=requestAnimationFrame(animate);return()=>cancelAnimationFrame(frame);
},[target]);
return position;
}
const format=(n:number|null)=>n===null?'—':new Intl.NumberFormat('ru-RU',{maximumFractionDigits:1}).format(n/1e6);
const tickLength=12;
function markerPoint(fraction:number){
const p=speedPoint(fraction);
return{x:p.x+p.nx*tickLength/2,y:p.y+p.ny*tickLength/2};
}
export function RouterSpeedGauge({measurement,waiting,fresh,staleLabel="Ожидаем данные борта"}:{measurement?:SpeedMeasurement;waiting:boolean;fresh:boolean;staleLabel?:string}){
const {down,up}=speedValues(measurement),phase=measurement?.phase;
const running=phase==='download'||phase==='upload';
const [clock,setClock]=useState(Date.now());
useEffect(()=>{if(!running)return;const timer=setInterval(()=>setClock(Date.now()),1000);return()=>clearInterval(timer);},[running]);
const stale=running&&(!fresh||!!measurement?.sampled_at&&clock-measurement.sampled_at>6000);
const ceiling=Math.max(down??0,up??0)>1e9?1e10:1e9;
const active=phase==='upload'?up:down;
const marker=markerPoint(useMarker(speedFraction(active??0,ceiling)));
const secondary=markerPoint(speedFraction(up??0,ceiling));
const state=waiting?'Подготовка замера':stale?staleLabel:phase==='latency'?'Проверяем задержку':phase==='download'?'Измеряем приём':phase==='upload'?'Измеряем передачу':phase==='complete'?'Замер завершён':phase==='cancelled'?'Замер остановлен':phase==='error'?'Замер не завершён':'Готов к замеру';
const caption=phase==='download'||phase==='upload'?'Текущая средняя · Мбит/с':'Мбит/с';
return <div className="router-speed-visual"><div className="router-speed-state"><Description role="status">{state}</Description></div><figure className="router-speed-gauge" aria-label={`Скорость соединения. ${state}. Приём ${format(down)}, передача ${format(up)} Мбит/с.`}>
<svg viewBox="0 0 720 280" aria-hidden="true" className={stale?'router-speed-instrument is-stale':'router-speed-instrument'}>
<path d={speedTrack} className="router-speed-track"/>
{Array.from({length:121},(_,i)=>{const p=speedPoint(i/120),lit=active!==null&&i/120<=speedFraction(active,ceiling);return <line key={i} x1={p.x} y1={p.y} x2={p.x+p.nx*tickLength} y2={p.y+p.ny*tickLength} className={lit?'router-speed-tick is-lit':'router-speed-tick'}/>;})}
{[0,10,100,1000].map(n=>{const p=speedPoint(speedFraction(n*1e6*(ceiling/1e9),ceiling));return <line key={n} x1={p.x} y1={p.y} x2={p.x+p.nx*22} y2={p.y+p.ny*22} className="router-speed-major"/>;})}
{active!==null&&<g className="router-speed-marker"><circle cx={marker.x} cy={marker.y} r="11" className="router-speed-halo"/><circle cx={marker.x} cy={marker.y} r="4"/></g>}
{phase==='complete'&&up!==null&&<circle cx={secondary.x} cy={secondary.y} r="5" className="router-speed-upload-marker"/>}
</svg>
{[0,10,100,1000].map(n=>{const p=speedPoint(speedFraction(n*1e6*(ceiling/1e9),ceiling));return <span key={n} className="router-speed-scale" style={{left:`${(p.x-p.nx*22)/720*100}%`,top:`${(p.y-p.ny*22)/280*100}%`}}>{n*(ceiling/1e9)}</span>;})}
<figcaption className="router-speed-center">
<div className="router-speed-readings">
<div data-active={phase==='download'}><span><Icon name="download"/> Приём</span><strong>{format(down)}</strong></div>
<div data-active={phase==='upload'}><span><Icon name="upload"/> Передача</span><strong>{format(up)}</strong></div>
</div>
<Description>{caption}</Description>
</figcaption>
</figure></div>;
}
@@ -0,0 +1,4 @@
.network-speed-facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--nodedc-space-4);margin:0;}
.network-speed-facts dt{color:var(--nodedc-text-secondary);font-size:var(--nodedc-font-size-sm);}
.network-speed-facts dd{margin:var(--nodedc-space-1) 0 0;font-size:var(--nodedc-font-size-md);}
.network-speed-actions{display:flex;flex-wrap:wrap;gap:var(--nodedc-space-2);}
@@ -0,0 +1,10 @@
.router-observation {height:100%;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:var(--nodedc-space-2);padding:var(--nodedc-space-2);font-size:var(--nodedc-font-size-sm);--nodedc-description-font-size:var(--nodedc-font-size-xs);}
.router-observation__channel {display:flex;flex-direction:column;}
.router-observation__summary {display:flex;align-items:center;flex-wrap:wrap;gap:var(--nodedc-space-2);}
.router-observation__summary strong {font-weight:var(--nodedc-font-weight-medium);}
.router-observation__value {margin-inline-start:auto;white-space:nowrap;}
.router-observation .router-signal-scale {margin-top:0;}
.router-observation .router-signal-zone {min-height:24px;}
.router-observation .router-signal-track {height:4px;}
.router-observation .router-signal-marker {width:8px;height:8px;}
@@ -0,0 +1,20 @@
.router-speed-visual{margin:8px 0}.router-speed-state{text-align:center}
.router-speed-gauge{position:relative;width:100%;max-width:600px;aspect-ratio:18/7;margin:0 auto;isolation:isolate;color:var(--nodedc-text-primary)}
.router-speed-instrument{display:block;width:100%;height:100%;overflow:visible}
.router-speed-track{fill:none;stroke:currentColor;stroke-width:1;opacity:.06}
.router-speed-tick{stroke:currentColor;stroke-width:1.4;stroke-linecap:round;opacity:.18;transition:opacity 450ms ease}
.router-speed-tick.is-lit{opacity:.8}
.router-speed-major{stroke:currentColor;stroke-width:1.5;stroke-linecap:round;opacity:.5}
.router-speed-marker{fill:currentColor}
.router-speed-halo{opacity:.1}
.router-speed-upload-marker{fill:none;stroke:var(--nodedc-text-muted);stroke-width:2}
.router-speed-instrument.is-stale{opacity:.45}
.router-speed-scale{position:absolute;transform:translate(-50%,-50%);font-size:var(--nodedc-font-size-sm);color:var(--nodedc-text-muted);font-variant-numeric:tabular-nums}
.router-speed-center{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:52%;display:grid;gap:12px;text-align:center}
.router-speed-readings{display:grid;grid-template-columns:1fr 1fr;gap:16px}
.router-speed-readings>div{display:grid;gap:8px}
.router-speed-readings span{display:flex;align-items:center;justify-content:center;gap:6px;color:var(--nodedc-text-muted);font-size:var(--nodedc-font-size-sm)}
.router-speed-readings strong{font-size:var(--nodedc-font-size-md);font-weight:600;font-variant-numeric:tabular-nums}
.router-speed-readings [data-active=true] span{color:var(--nodedc-text-primary)}
@media(max-width:600px){.router-speed-gauge{margin:8px auto}.router-speed-center{gap:6px;width:58%}.router-speed-readings{gap:8px}.router-speed-readings>div{gap:4px}.router-speed-scale{font-size:var(--nodedc-font-size-xs)}}
@media(prefers-reduced-motion:reduce){.router-speed-tick{transition:none}}
@@ -0,0 +1,21 @@
/** Geometry of the router speed instrument. Values stay measured, only the marker interpolates. */
export function speedFraction(bps:number,ceiling=1e9){
return Math.log1p(Math.max(0,Math.min(ceiling,bps))/(ceiling/100))/Math.log(101);
}
export function speedPoint(fraction:number){
const radius=95,left=142,right=578,top=45,bottom=235,tail=143,straight=right-left;
let d=Math.max(0,Math.min(1,fraction))*(tail*2+Math.PI*radius*2+straight);
if(d<=tail)return{x:285-d,y:bottom,nx:0,ny:1};d-=tail;
if(d<=Math.PI*radius){const a=Math.PI/2+d/radius;return{x:left+radius*Math.cos(a),y:140+radius*Math.sin(a),nx:Math.cos(a),ny:Math.sin(a)};}d-=Math.PI*radius;
if(d<=straight)return{x:left+d,y:top,nx:0,ny:-1};d-=straight;
if(d<=Math.PI*radius){const a=-Math.PI/2+d/radius;return{x:right+radius*Math.cos(a),y:140+radius*Math.sin(a),nx:Math.cos(a),ny:Math.sin(a)};}d-=Math.PI*radius;
return{x:right-d,y:bottom,nx:0,ny:1};
}
export const speedTrack='M285 235 H142 A95 95 0 0 1 142 45 H578 A95 95 0 0 1 578 235 H435';
export function speedValues(m:{phase:string;current_bps?:number;sampled_at?:number;download_bps:number;upload_bps:number}|undefined){
if(!m)return{down:null,up:null};
if(m.phase==='complete')return{down:m.download_bps,up:m.upload_bps};
if(m.phase==='download')return{down:m.sampled_at?m.current_bps??null:null,up:null};
if(m.phase==='upload')return{down:m.download_bps,up:m.sampled_at?m.current_bps??null:null};
return{down:null,up:null};
}
@@ -0,0 +1,54 @@
import {useEffect, useState} from 'react';
import {Button, Checker, Description, FeatureSettingsWindow, SettingsCard} from '@nodedc/ui-react';
import {notificationRequest} from '../../core/notifications/history';
interface Preference {
key: string;
section: string;
group: string;
label: string;
enabled: boolean;
}
export function EventSettings({onClose}: {onClose: () => void}) {
const [items, setItems] = useState<Preference[]>([]);
const [section, setSection] = useState('Сеть');
const [error, setError] = useState('');
const [saving, setSaving] = useState(false);
const [attempt, setAttempt] = useState(0);
useEffect(() => {
let active = true;
setError('');
notificationRequest<Preference[]>('/preferences').then(result => {
if (active) setItems(result);
}).catch(() => { if (active) setError('Не удалось загрузить настройки событий.'); });
return () => { active = false; };
}, [attempt]);
async function configure(key: string, enabled: boolean) {
setSaving(true);
setError('');
try {
setItems(await notificationRequest<Preference[]>('/preferences', 'PATCH', {key, enabled}));
} catch {
setError('Не удалось подтвердить изменение. Обновите настройки и повторите попытку.');
} finally {
setSaving(false);
}
}
const sections = [...new Set(items.map(item => item.section))];
const current = items.filter(item => item.section === section);
const groups = [...new Set(current.map(item => item.group))];
return <FeatureSettingsWindow open title="Настройки центра событий"
identity={{title: 'Центр событий', avatarLabel: 'ЦС'}}
sections={sections.map(label => ({id: label, label, icon: label === 'Сеть' ? 'network' : 'activity'}))}
activeSection={section} onSectionChange={setSection} onClose={onClose}>
{error && <><Description role="alert">{error}</Description><Button onClick={() => setAttempt(n => n + 1)}>Обновить настройки</Button></>}
{!error && !items.length && <Description role="status">Загружаем настройки…</Description>}
{groups.map(group => <SettingsCard key={group} title={group}>
{current.filter(item => item.group === group).map(item => <Checker key={item.key}
label={item.label} checked={item.enabled} disabled={saving}
onChange={enabled => void configure(item.key, enabled)}/>)}
</SettingsCard>)}
</FeatureSettingsWindow>;
}
@@ -0,0 +1,47 @@
import {useEffect, useRef, useState, type ReactNode} from 'react';
import {ApplicationSidePanel, Button, Description, Icon, IconButton, ResourceList, ResourceRow, StatusBadge, ToastStack} from '@nodedc/ui-react';
import {NotificationContext, useNotificationHistory, useNotifications} from '../../core/notifications/useNotificationHistory';
import type {NotificationTone} from '../../core/notifications/history';
import {EventSettings} from './EventSettings';
const tones = {success: 'success', warning: 'warning', error: 'danger', info: 'neutral'} as const;
const labels: Record<NotificationTone, string> = {success: 'Успешно', warning: 'Внимание', error: 'Ошибка', info: 'Информация'};
export function NotificationHost({children}: {children: ReactNode}) {
const state = useNotificationHistory();
return <NotificationContext.Provider value={state}>
{children}
<ToastStack items={state.toasts} onDismiss={state.dismiss} observe={false}/>
</NotificationContext.Provider>;
}
export function EventPanel() {
const state = useNotifications();
const [settings, setSettings] = useState(false);
const gear = useRef<HTMLButtonElement>(null);
const close = () => {
state.setOpen(false);
document.querySelector<HTMLButtonElement>('[aria-controls="operator-events"]')?.focus();
};
useEffect(() => {
if (!state.open) return;
gear.current?.focus({preventScroll: true});
}, [state.open]);
return <ApplicationSidePanel id="operator-events" eyebrow="Mission Core" title="Центр событий"
inert={!state.open} aria-label="Центр событий" closeLabel="Закрыть центр событий" onClose={close}
onKeyDown={event => {
if (event.key === 'Escape' && !settings) { event.stopPropagation(); close(); }
}}
headerActions={<IconButton ref={gear} label="Настройки центра событий" onClick={() => setSettings(true)}><Icon name="settings"/></IconButton>}>
{state.error && <Description role="status">{state.error}</Description>}
{!state.items.length && <Description>{state.loading ? 'Получаем события…' : 'Событий пока нет.'}</Description>}
<ResourceList aria-label="История событий">{state.items.map(item => <li key={item.identity}>
<ResourceRow title={item.title} description={item.description}
metadata={new Date(item.at * 1000).toLocaleString('ru-RU')}
statusPlacement="leading" status={<StatusBadge variant="indicator" tone={tones[item.tone]}
aria-label={labels[item.tone]} title={labels[item.tone]}/>}/>
</li>)}</ResourceList>
{state.more && <Button loading={state.loading} onClick={() => void state.loadMore()}>Показать ещё</Button>}
{settings && state.open && <EventSettings onClose={() => setSettings(false)}/>}
</ApplicationSidePanel>;
}
@@ -0,0 +1,17 @@
import {useLayoutEffect,useRef,type ReactNode} from 'react';
import {DockLayout,type DockTree} from '@nodedc/ui-react';
import {observationTree,type ObservationLayout} from '../../core/fleet/observationLayout';
export function ObservationMount({element,className='observation-mount'}:{element:HTMLElement;className?:string}){
const ref=useRef<HTMLDivElement>(null);
useLayoutEffect(()=>{const host=ref.current!;host.append(element);return()=>{if(element.parentElement===host)element.remove();};},[element]);
return <div ref={ref} className={className}/>;
}
export function ObservationDeck({ids,mounts,layout,onTreeChange,labels,focusedId,minimumSizes,children}:{
ids:string[];mounts:Map<string,HTMLElement>;layout:ObservationLayout;onTreeChange:(tree:DockTree)=>void;
minimumSizes?:Record<string,{width:number;height:number}>; labels:Record<string,string>;focusedId?:string|null;children:ReactNode;
}){
return <DockLayout tree={observationTree(layout,ids)} onTreeChange={onTreeChange}
focusedId={focusedId} panels={ids.map(id=>({id,label:labels[id]??id,minimumSize:minimumSizes?.[id],preferredSize:!layout.tree&&!Object.keys(layout.splits).length?minimumSizes?.[id]:undefined}))}
renderPanel={id=><ObservationMount element={mounts.get(id)!}/>}>{children}</DockLayout>;
}
@@ -0,0 +1,16 @@
import {useState} from 'react';
import {Button,Icon,TextField,Window,WindowFooterActions} from '@nodedc/ui-react';
export function ObservationLayoutSaveWindow({onClose,onSave,initialName='',onRemove}:{onClose:()=>void;onSave:(name:string)=>boolean;initialName?:string;onRemove?:()=>boolean}) {
const [name,setName]=useState(initialName);
const save=()=>{if(name.trim()&&onSave(name))onClose();};
return <Window open title={onRemove?'Редактировать раскладку':'Сохранить расположение'} size="sm" onClose={onClose}
footer={<WindowFooterActions>
{onRemove&&<Button icon={<Icon name="trash"/>} onClick={()=>{if(onRemove())onClose();}}>Удалить раскладку</Button>}
<Button variant="primary" disabled={!name.trim()} onClick={save}>{onRemove?'Сохранить имя':'Сохранить'}</Button>
</WindowFooterActions>}>
<TextField label="Название раскладки" value={name} maxLength={120} onChange={event=>setName(event.target.value)}
onKeyDown={event=>{if(event.key==='Enter'&&!event.nativeEvent.isComposing){event.preventDefault();save();}}}
description={onRemove?undefined:'Сохраняются выбранные камеры, слои и расположение окон. Недоступные устройства появятся при подключении.'}/>
</Window>;
}
@@ -0,0 +1,13 @@
import {useLayoutEffect,useRef,type ReactNode} from 'react';
/** Reserve the actual overlay height for text/status content, including wrapped controls. */
export function ObservationPanelHeader({children}:{children:ReactNode}) {
const ref=useRef<HTMLElement>(null);
useLayoutEffect(()=>{
const header=ref.current!;
const measure=()=>header.parentElement?.style.setProperty('--observation-overlay-header-space',`${header.getBoundingClientRect().height}px`);
measure();const observer=new ResizeObserver(measure);observer.observe(header);
return()=>observer.disconnect();
},[]);
return <header ref={ref} className="observation-panel__header nodedc-viewport-controls">{children}</header>;
}
@@ -0,0 +1,34 @@
import { useEffect, useRef, useState } from "react";
import { overviewChartPoints } from "../../core/observation/sessionOverview";
export function SessionIntervalChart({ chart, bucketSeconds }: { chart: [number, number][]; bucketSeconds: number }) {
const svg = useRef<SVGSVGElement>(null);
const [size, setSize] = useState({ width: 900, height: 160 });
useEffect(() => {
if (!svg.current) return;
const observer = new ResizeObserver(([entry]) => {
if (entry.contentRect.width > 0 && entry.contentRect.height > 0) {
setSize({ width: entry.contentRect.width, height: entry.contentRect.height });
}
});
observer.observe(svg.current);
return () => observer.disconnect();
}, [chart.length > 0]);
const width = Math.max(1, size.width - 106);
const height = Math.max(1, size.height - 38);
const { points, xmax, ymax } = overviewChartPoints(chart, width, height);
if (!chart.length) return <div className="session-overview__empty">Временные метки кадров отсутствуют.</div>;
return <div className="session-overview__chart">
<svg ref={svg} viewBox={`0 0 ${size.width} ${size.height}`} role="img" aria-label="Интервалы поступления кадров облака">
<g transform="translate(64,10)">
{(height >= 70 ? [0, .5, 1] : height >= 32 ? [0, 1] : [1]).map(f => <g key={f}>
<line x1="0" x2={width} y1={height * (1 - f)} y2={height * (1 - f)} className="session-overview__grid" />
<text x="-12" y={height * (1 - f) + 4} textAnchor="end">{(f * ymax).toFixed(2)} с</text>
</g>)}
<polyline points={points} fill="none" className="session-overview__series" vectorEffect="non-scaling-stroke" />
{[0, .25, .5, .75, 1].map(f => <text key={f} x={f * width} y={height + 24} textAnchor="middle">{(f * xmax / 60).toFixed(1)} мин</text>)}
</g>
</svg>
<span className="session-overview__note">Максимальный интервал за каждые {bucketSeconds} с · время от первого кадра</span>
</div>;
}
@@ -0,0 +1,98 @@
import { heightSlice } from "../../core/heightSlice";
import { type ReactNode, useEffect, useRef, useState } from "react";
import { Button, LoadingRegion, RangeControl, SegmentedControl } from "@nodedc/ui-react";
import { createIsolatedRerunHost } from "../rerun/isolatedRerunHost";
import type { RecordedRerunViewer } from "../rerun/recordedRerunFacade";
import { fetchOverviewSpatial, updateOverviewSpatial, type OverviewSpatialMetadata, type OverviewViewMode, type OverviewRepresentation } from "../../core/observation/sessionOverviewSpatial";
/** A separate, bounded static recording; teardown releases the whole WASM realm. */
export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, compareVersions=false }: { sourceUrl: string; toolbar?:ReactNode; hideTitle?:boolean; compareVersions?:boolean }) {
const host = useRef<HTMLDivElement>(null);
const [state, setState] = useState<"loading" | "ready" | "error">("loading");
const [retry, setRetry] = useState(0);
const [metadata, setMetadata] = useState<OverviewSpatialMetadata | null>(null);
const [ceiling, setCeiling] = useState<number | null>(null);
const [floor, setFloor] = useState<number | null>(null);
const [mode, setMode] = useState<OverviewViewMode>("3d");
const [viewError, setViewError] = useState<string | null>(null);
const [visiblePoints, setVisiblePoints] = useState<number | null>(null);
const [representation, setRepresentation] = useState<OverviewRepresentation>("original");
const [appliedRepresentation, setAppliedRepresentation] = useState<OverviewRepresentation>("original");
const [updating, setUpdating] = useState(false);
const comparison = metadata?.comparison;
const appliedMode = useRef<OverviewViewMode | null>(null);
const controller = useRef<{ viewer: RecordedRerunViewer; channel: ReturnType<RecordedRerunViewer["open_channel"]> } | null>(null);
useEffect(() => {
if (!host.current) return;
let disposed = false;
const abort = new AbortController();
appliedMode.current = null;
setState("loading");
setMetadata(null); setCeiling(null); setFloor(null); setMode("3d"); setVisiblePoints(null); setViewError(null);
setRepresentation("original"); setAppliedRepresentation("original"); setUpdating(false);
void fetchOverviewSpatial(sourceUrl, abort.signal).then(data => {
if (disposed) return;
setRepresentation(data.default_representation ?? "original"); setMetadata(data);
}).catch(() => { if (!disposed) { setState("error"); setViewError("Версия облака недоступна."); } });
const runtime = createIsolatedRerunHost(host.current);
const timer = window.setTimeout(() => { if (!disposed) { setState("error"); runtime.dispose(); } }, 60_000);
void runtime.ready.then(async ({ viewer, mount }) => {
if (disposed) return;
viewer.on("recording_open", () => { if (!disposed) { clearTimeout(timer); setState("ready"); } });
await viewer.start(new URL(sourceUrl, window.location.origin).href, mount, {
width: "100%", height: "100%", hide_welcome_screen: true,
enable_history: false, allow_fullscreen: false,
});
if (disposed) return;
controller.current = { viewer, channel: viewer.open_channel("session-overview-controls") };
if (viewer.get_active_recording_id()) { clearTimeout(timer); setState("ready"); }
for (const panel of ["top", "blueprint", "selection", "time"] as const) viewer.override_panel_state(panel, "hidden");
}).catch(() => { if (!disposed) { clearTimeout(timer); setState("error"); runtime.dispose(); } });
return () => { disposed = true; abort.abort(); controller.current = null; clearTimeout(timer); runtime.dispose(); };
}, [sourceUrl, retry]);
useEffect(() => {
if (state !== "ready" || !metadata || !controller.current) return;
const abort = new AbortController();
setUpdating(true);
const timer = setTimeout(() => {
const aspect = Math.max(.1, Math.min(20, (host.current?.clientWidth ?? 1) / Math.max(1, (host.current?.clientHeight ?? 1) - 28)));
void updateOverviewSpatial(sourceUrl, ceiling, appliedMode.current === mode ? null : mode, aspect, abort.signal,
comparison?.generation ?? null, comparison ? representation : "original", floor).then(result => {
if (abort.signal.aborted || !controller.current) return;
controller.current.channel.send_rrd(result.bytes);
appliedMode.current = mode;
setVisiblePoints(result.visiblePoints); setViewError(null);
setAppliedRepresentation(comparison ? representation : "original"); setUpdating(false);
}).catch(() => { if (!abort.signal.aborted) { setUpdating(false); setViewError("Не удалось обновить вид облака. Показан предыдущий вид."); } });
}, 180);
return () => { abort.abort(); clearTimeout(timer); };
}, [state, metadata, sourceUrl, ceiling, floor, mode, retry, comparison, representation]);
const low = comparison?.height_min_m ?? metadata?.height_min_m;
const high = comparison?.height_max_m ?? metadata?.height_max_m;
return <>
<div className={`session-overview__scene-head nodedc-viewport-controls ${hideTitle?"session-overview__scene-head--end":""}`}>{!hideTitle&&<h2>Облако и траектория</h2>}
{compareVersions && comparison && <SegmentedControl label="Версия облака" value={representation} onChange={setRepresentation}
items={[{ value: "original", label: "Исходное", disabled: state !== "ready" }, { value: "corrected", label: "Исправленное", disabled: state !== "ready" }]} />}
<SegmentedControl label="Вид облака" value={mode} onChange={setMode}
items={[{ value: "top", label: "Сверху", disabled: state !== "ready" }, { value: "3d", label: "3D", disabled: state !== "ready" }]} />
{toolbar}
</div>
<LoadingRegion loading={state === "loading" || (state === "ready" && !!metadata && visiblePoints === null && !viewError)} label="Загрузка облака" className="session-overview__scene">
<div ref={host} className={`session-overview__runtime ${hideTitle?"rerun-single-view-content":""}`} style={{ visibility: state === "ready" && metadata && visiblePoints !== null ? "visible" : "hidden" }} />
{low != null && high != null && high > low && state === "ready" && <div className="session-overview__height">
<RangeControl orientation="vertical" limitSide="left" label="Срез" value={[floor ?? low, ceiling ?? high]} min={low} max={high} step="any"
formatValue={value => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={value => value.toFixed(1).replace('.', ',')}
onChange={value => { const next = heightSlice(value, [low, high]); setFloor(next.floor); setCeiling(next.ceiling); }} />
</div>}
{state === "error" && <div className="session-overview__empty"><span>Не удалось открыть облако.</span><Button onClick={() => setRetry(n => n + 1)}>Повторить</Button></div>}
</LoadingRegion>
<span className="session-overview__note" role="status" aria-busy={updating}>
{updating ? "Обновление · " : comparison ? `${appliedRepresentation === "corrected" ? "Исправленное" : "Исходное"} · ` : ""}
{floor == null && ceiling == null ? "Без среза" : `${floor == null ? "" : `${floor.toFixed(1)} м ≤ `}Высота${ceiling == null ? "" : ` ≤ ${ceiling.toFixed(1)} м`}`} · {visiblePoints?.toLocaleString("ru-RU") ?? "—"} точек
{comparison && <><br />Выборка для просмотра. Исходная запись сохранена отдельно.</>}
</span>
{viewError && <div className="session-overview__note" role="alert">{viewError}<Button onClick={() => setRetry(n => n + 1)}>Повторить</Button></div>}
</>;
}
@@ -0,0 +1,62 @@
.observation-center { display:flex; flex-direction:column; gap:var(--nodedc-space-3); padding:var(--nodedc-space-4); min-width:0; height:max(600px, calc(100dvh - 260px)); }
.observation-center--expanded { position:fixed; inset:0; z-index:calc(var(--nodedc-layer-overlay) - 1); background:var(--nodedc-canvas); height:100dvh; box-sizing:border-box; }
/* Inline fallback for browsers without state-preserving DOM moves. */
.nodedc-application-panel:has(.observation-center--expanded) { transform:none; overflow:visible; }
.observation-toolbar, .observation-summary, .observation-actions { display:flex; align-items:center; gap:var(--nodedc-space-2); }
.observation-toolbar { justify-content:space-between; flex-wrap:wrap; }
.observation-toolbar h2, .observation-panel h3 { margin:0; }
.observation-toolbar span { color:var(--nodedc-text-muted); font-size:var(--nodedc-font-size-sm); }
.observation-actions { flex-shrink:0; }
.observation-deck { flex:1; min-height:0; min-width:0; }
.observation-layout { position:relative; height:100%; min-height:0; min-width:0; }
.observation-layout__slot { height:100%; min-height:0; }
.observation-layout__panel { position:absolute; min-height:0; min-width:0; }
.observation-layout__panel:has(.is-dragging) { z-index:var(--nodedc-layer-panel); }
.observation-mount, .observation-panel-mount, .observation-media-mount, .observation-panel, .observation-split { height:100%; min-height:0; min-width:0; }
.observation-panel__surface { display:flex; flex-direction:column; height:100%; overflow:hidden; container-type:inline-size; }
.observation-panel__surface > .observation-mount { flex:1; }
.observation-panel__surface--flow > .observation-mount { height:0; flex:1 1 0; }
.observation-panel__surface--overlay { position:relative; --observation-overlay-header-space:62px; }
.observation-panel__surface--overlay > .observation-panel__header { position:absolute; inset:0 0 auto; z-index:1; background:transparent; pointer-events:none; }
.observation-panel__surface--overlay > .observation-panel__header > * { pointer-events:auto; }
.observation-panel__header { display:flex; align-items:center; gap:var(--nodedc-space-2); padding:var(--nodedc-space-2); flex-shrink:0; }
.observation-panel__header h3 { min-width:0; font-size:var(--nodedc-font-size-sm); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.observation-source { position:relative; display:flex; flex-direction:column; height:100%; min-height:0; }
.observation-panel__title { display:flex; align-items:center; gap:var(--nodedc-space-2); flex:1; min-width:0; }
.observation-header-slot, .observation-header-slot > div { display:flex; align-items:center; gap:var(--nodedc-space-2); flex-shrink:0; }
.observation-header-slot:has(> div:empty) { display:none; }
.observation-panel__title .observation-header-slot, .observation-panel__title .observation-header-slot > div { min-width:0; max-width:100%; flex-shrink:1; }
.observation-layer-select { min-width:0; max-width:120px; }
.observation-layer-select button { max-width:100%; }
.observation-layer-select button > span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.observation-source__media { position:relative; flex:1; min-height:0; overflow:hidden; display:flex; align-items:center; justify-content:center; }
.observation-source__media video, .observation-source__media canvas { width:100%; height:100%; object-fit:contain; }
.observation-source__media[data-live="false"] > *, .observation-source__media [data-live="false"] { visibility:hidden; }
/* Notices use the full viewport, independent of its overlaid header. */
.observation-source__notice { position:absolute; inset:0; box-sizing:border-box; margin:0; padding:var(--nodedc-space-4); display:flex; flex-direction:column; align-items:center; justify-content:center; gap:var(--nodedc-space-3); text-align:center; font-family:inherit; font-size:var(--nodedc-font-size-sm); font-weight:400; line-height:1.4; color:var(--nodedc-text-muted); pointer-events:none; }
.observation-source__notice > p { margin:0; }
.observation-source__notice > button, .observation-source__notice > a { pointer-events:auto; }
.observation-rerun, .observation-rerun > div, .observation-map > div { width:100%; height:100%; }
.observation-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-4); }
.observation-layer { display:grid; grid-template-columns:minmax(0, 1fr) 50%; align-items:center; gap:var(--nodedc-space-3); }
.observation-layer > * { min-width:0; width:100%; }
.observation-layer > .nodedc-switch { text-align:left; }
.observation-empty { display:grid; place-content:center; height:100%; text-align:center; }
.observation-decoder { position:absolute; width:1px; height:1px; opacity:0; pointer-events:none; }
@media(max-width:700px) { .observation-toolbar .observation-actions { flex-wrap:wrap; } .observation-center { height:max(650px, calc(100dvh - 200px)); } .observation-center--expanded { height:100dvh; } }
.observation-map[data-available="false"] > [data-nodedc-map-renderer] { visibility:hidden; }
/* Transform the live panel as one item; reveal it across nested split boundaries. */
.observation-panel-drag { position:relative; height:100%; min-height:0; }
.observation-panel-drag.is-dragging { z-index:var(--nodedc-layer-panel); }
.observation-split:has(.observation-panel-drag.is-dragging),
.observation-split > .nodedc-split-pane__panel:has(.observation-panel-drag.is-dragging) { position:relative; overflow:visible; z-index:var(--nodedc-layer-panel); }
@container (max-width:420px) {
.observation-panel__header { flex-wrap:wrap; }
.observation-panel__title { min-width:80px; }
.observation-panel__title:has(.rover-view__title) { min-width:min(160px, 100%); }
.observation-panel__header > .observation-actions { max-width:100%; flex-wrap:wrap; justify-content:flex-end; margin-left:auto; gap:var(--nodedc-space-1); }
}
.observation-panel__surface--overlay .rover-telemetry { padding-top:calc(var(--observation-overlay-header-space) + var(--nodedc-space-3)); }
@@ -0,0 +1,261 @@
import { useEffect, useMemo, useState } from "react";
import {
ActivityIndicator,
Button,
FieldFrame,
Select,
StatusBadge,
Window,
WindowFooterActions,
} from "@nodedc/ui-react";
import {
aiModuleIdForSetup,
fetchAIModuleCatalog,
fetchAICompositionRuns,
fetchAICompositionJobs,
saveAIComposition,
type AICompositionReceipt,
type AICompositionRun,
type AIGroupId,
type AIModuleCatalog,
} from "../../core/observatory/aiComposition";
import type { ObservatoryRecordedJob } from "../../core/observatory/recordedJobs";
const groups: readonly { id: AIGroupId; label: string; description: string }[] = [
{ id: "segmentation", label: "Сегментация", description: "Пиксельные маски сцены" },
{ id: "detection", label: "Объекты", description: "Рамки и классы объектов" },
{ id: "geometry", label: "Облако точек / TGS", description: "Опорная поверхность и карта проходимости" },
{ id: "range", label: "Дистанция", description: "Расстояния до объектов" },
{ id: "motion", label: "Движение", description: "Треки и динамика объектов" },
{ id: "policy", label: "Политика", description: "Теневые правила интерпретации" },
];
export function AIConfigurationWindow({
open, sourceSessionId, sourceLabel, onClose, onCalculated,
}: {
readonly open: boolean;
readonly sourceSessionId: string;
readonly sourceLabel: string;
readonly onClose: () => void;
readonly onCalculated: (receipt: AICompositionReceipt) => void;
}) {
const [catalog, setCatalog] = useState<AIModuleCatalog | null>(null);
const [existingJobs, setExistingJobs] = useState<readonly ObservatoryRecordedJob[]>([]);
const [existingRuns, setExistingRuns] = useState<readonly AICompositionRun[]>([]);
const [selected, setSelected] = useState<Partial<Record<AIGroupId, string>>>({});
const [state, setState] = useState<"idle" | "loading" | "ready" | "saving" | "error">("idle");
const [message, setMessage] = useState<string | null>(null);
useEffect(() => {
if (!open) return;
const request = new AbortController();
setState("loading");
setMessage(null);
void Promise.all([
fetchAIModuleCatalog(request.signal),
fetchAICompositionJobs(sourceSessionId, request.signal),
fetchAICompositionRuns(sourceSessionId, request.signal),
]).then(([value, jobs, runs]) => {
if (request.signal.aborted) return;
setCatalog(value);
setExistingJobs(jobs);
setExistingRuns(runs);
setSelected({});
setState("ready");
}).catch((error: unknown) => {
if (request.signal.aborted) return;
setMessage(error instanceof Error ? error.message : "Каталог AI-модулей недоступен.");
setState("error");
});
return () => request.abort();
}, [open, sourceSessionId]);
const existingByModule = useMemo(() => {
const result = new Map<string, ObservatoryRecordedJob>();
for (const job of existingJobs) {
if (job.state === "failed" || job.publication.state === "failed") continue;
const moduleId = aiModuleIdForSetup(job.setupId);
if (moduleId && !result.has(moduleId)) result.set(moduleId, job);
}
return result;
}, [existingJobs]);
const selections = useMemo(() => groups.flatMap(({ id }) => {
const moduleId = selected[id];
const module = catalog?.groups.find((item) => item.group === id)?.modules.find(
(item) => item.moduleId === moduleId,
);
return module ? [{ group: id, module }] : [];
}), [catalog, selected]);
const selectedModuleIds = useMemo(
() => selections.map(({ module }) => module.moduleId).sort(),
[selections],
);
const matchingRun = useMemo(() => existingRuns.find((run) => (
run.state !== "failed"
&& [...run.moduleIds].sort().join("\0") === selectedModuleIds.join("\0")
)), [existingRuns, selectedModuleIds]);
const configurationAlreadyExists = selections.length > 0 && matchingRun !== undefined;
const configurationIsRunning = matchingRun?.state === "running";
function selectModule(group: AIGroupId, moduleId: string): void {
if (!catalog) return;
setSelected((current) => {
const next = { ...current, [group]: moduleId === "none" ? undefined : moduleId };
const modules = catalog.groups.flatMap((item) => item.modules);
const selectedIds = new Set(Object.values(next).filter((value): value is string => Boolean(value)));
if (moduleId !== "none") {
const module = modules.find((item) => item.moduleId === moduleId);
for (const requirement of module?.requires ?? []) {
if (requirement.startsWith("source.")) continue;
if (modules.some((item) => selectedIds.has(item.moduleId) && item.provides.includes(requirement))) {
continue;
}
const providers = modules.filter((item) => item.provides.includes(requirement));
if (providers.length === 1) {
const providerGroup = catalog.groups.find((item) => item.modules.some(
(candidate) => candidate.moduleId === providers[0]?.moduleId,
))?.group;
if (providerGroup) {
next[providerGroup] = providers[0]?.moduleId;
selectedIds.add(providers[0]?.moduleId ?? "");
}
}
}
} else {
let changed = true;
while (changed) {
changed = false;
const capabilities = new Set(modules.filter((item) => Object.values(next).includes(item.moduleId))
.flatMap((item) => item.provides));
for (const item of modules.filter((candidate) => Object.values(next).includes(candidate.moduleId))) {
if (item.requires.some((requirement) => !requirement.startsWith("source.") && !capabilities.has(requirement))) {
const dependentGroup = catalog.groups.find((candidate) => candidate.modules.some(
(module) => module.moduleId === item.moduleId,
))?.group;
if (dependentGroup) {
next[dependentGroup] = undefined;
changed = true;
}
}
}
}
}
return next;
});
setMessage(null);
if (state === "error") setState("ready");
}
async function calculate(): Promise<void> {
if (selections.length === 0 || state === "saving") return;
if (configurationAlreadyExists) {
setMessage("Эта конфигурация уже рассчитана. Выберите другую конфигурацию.");
return;
}
setState("saving");
setMessage(null);
try {
const receipt = await saveAIComposition(sourceSessionId, selections);
onCalculated(receipt);
onClose();
} catch (error) {
setMessage(error instanceof Error ? error.message : "Не удалось запустить расчёт.");
setState("error");
}
}
return <Window
open={open}
className="observatory-ai-config-window"
title="Сконфигурировать AI-слой"
subtitle={sourceLabel}
size="lg"
closeOnBackdrop={state !== "saving"}
closeOnEscape={state !== "saving"}
onClose={onClose}
footer={<WindowFooterActions>
{configurationAlreadyExists ? (
<span className="observatory-ai-config__duplicate" role="status">
{configurationIsRunning
? "Текущая конфигурация уже рассчитывается."
: "Текущая конфигурация уже рассчитана."}
</span>
) : null}
<Button
variant="primary"
className={state === "saving" ? "observatory-ai-config__calculate--saving" : undefined}
disabled={state !== "ready" || selections.length === 0 || configurationAlreadyExists}
aria-busy={state === "saving"}
onClick={() => void calculate()}
>
{state === "saving" ? "Отправляем на Worker…" : "Рассчитать"}
</Button>
</WindowFooterActions>}
>
<div className="observatory-ai-config" aria-busy={state === "loading" || state === "saving"}>
<p className="observatory-ai-config__lead">
Выберите модуль в каждом нужном слое. Зависимые блоки подключаются явно в этой конфигурации.
</p>
{state === "loading" ? <ActivityIndicator label="Загружаем AI-модули" /> : null}
{catalog ? groups.map(({ id, label, description }) => {
const modules = catalog.groups.find((item) => item.group === id)?.modules ?? [];
const selectedModule = modules.find((item) => item.moduleId === selected[id]);
const selectedExisting = selectedModule
? existingByModule.get(selectedModule.moduleId)
: undefined;
const allCalculated = modules.length > 0 && modules.every(
(module) => existingByModule.has(module.moduleId),
);
return <section className="observatory-ai-module-group" key={id}>
<header>
<div>
<strong>{label}</strong>
<span>{description}</span>
</div>
<StatusBadge tone={selectedModule ? "accent" : "neutral"}>
{selectedExisting
? selectedExisting.state === "succeeded" ? "Уже рассчитано" : "В расчёте"
: selectedModule?.label ?? (allCalculated
? "Результат доступен"
: modules.length ? "Не используется" : "Не установлен")}
</StatusBadge>
</header>
<div className="observatory-ai-module-group__body">
<FieldFrame
label={`Модуль: ${label}`}
description={modules.length
? allCalculated
? "Готовый результат можно включить в новую конфигурацию без повторного расчёта."
: id === "segmentation"
? "DDRNet и EoMT — независимые альтернативы; выберите одну модель."
: id === "range"
? "Дистанция использует рамки детектора и синхронное облако точек."
: id === "geometry"
? "TGS обрабатывает LiDAR независимо от сегментации и детектора."
: "Связи с другими блоками определяются входами выбранного модуля."
: "Для этого слоя на Worker 006 пока нет установленного модуля."}
>
<Select
label={`Выбрать модуль: ${label}`}
value={selected[id] ?? "none"}
options={[{ value: "none", label: "Не использовать" }, ...modules.map((module) => ({
value: module.moduleId,
label: module.label,
description: existingByModule.has(module.moduleId)
? "Готовый результат будет использован без повторного расчёта"
: module.dockerName,
}))]}
disabled={modules.length === 0 || state === "saving"}
onChange={(value) => selectModule(id, value)}
/>
</FieldFrame>
</div>
</section>;
}) : null}
{message ? <p className="observatory-ai-config__error" role="alert">{message}</p> : null}
</div>
</Window>;
}
@@ -0,0 +1,29 @@
import { useState } from "react";
import { Description, ConfirmationModal, Icon, IconButton } from "@nodedc/ui-react";
import type { ObservatoryRecordedJob } from "../../core/observatory/recordedJobs";
import { deleteFailedRunProjection } from "../../core/observatory/failedRunHistory";
export function FailedRunActions({ job, onDeleted }: {
job: ObservatoryRecordedJob;
onDeleted: () => void;
}) {
const [open, setOpen] = useState(false);
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
return <>
<IconButton label="Удалить ошибочную попытку" onClick={() => { setError(null); setOpen(true); }}>
<Icon name="trash" size={16} />
</IconButton>
<ConfirmationModal open={open} title="Удалить ошибочную попытку?"
description={<><Description>Попытка и её рабочие файлы будут удалены с этого устройства и Worker. Исходная запись сохранится.</Description>
{error ? <Description role="alert">{error}</Description> : null}</>}
confirmLabel="Удалить попытку" pendingLabel="Удаляем…" danger
onClose={() => { if (!pending) setOpen(false); }}
onConfirm={async () => {
setPending(true); setError(null);
try { await deleteFailedRunProjection(job); setOpen(false); onDeleted(); }
catch (cause) { setError(cause instanceof Error ? cause.message : "Не удалось удалить попытку."); }
finally { setPending(false); }
}} />
</>;
}
@@ -0,0 +1,71 @@
import { useEffect, useRef, useState } from "react";
import { ConfirmationModal, Icon, IconButton, ToastStack, type ToastItem } from "@nodedc/ui-react";
import { announceLabStorageChange, pinLabCopy, prepareLocalLabCopy, removeLabCopy,
type LocalLabCopy } from "../../core/storage/localLabStorage";
import { formatLocalLabSize } from "../../core/storage/localLabPresentation";
import type { LabReplayProgress } from "../../core/laboratory/prepareLabReplay";
export type LabCopyProgress = LabReplayProgress;
export function LabCopyActions({ id, sourceId, composition = false, copy, available, storageError, onProgress }: {
id: string; sourceId: string; composition?: boolean; copy?: LocalLabCopy;
available: boolean; storageError: string | null;
onProgress?: (value: LabReplayProgress | null) => void;
}) {
const [busy, setBusy] = useState<"download" | "pin" | "remove" | null>(null);
const [toasts, setToasts] = useState<ToastItem[]>([]);
const [confirm, setConfirm] = useState(false);
const request = useRef<AbortController | null>(null);
const progressCallback = useRef(onProgress);
progressCallback.current = onProgress;
useEffect(() => () => { request.current?.abort(); progressCallback.current?.(null); }, []);
const status = storageError ?? (!available ? "Проверяем локальную копию"
: copy?.local ? `На этом устройстве · ${formatLocalLabSize(copy, true)}`
: "Загрузить запись на это устройство");
async function perform(kind: "download" | "pin" | "remove", action: (signal: AbortSignal) => Promise<unknown>) {
if (request.current) return;
const controller = new AbortController(); request.current = controller;
setBusy(kind); setToasts([]);
try {
await action(controller.signal);
if (!controller.signal.aborted) setConfirm(false);
} catch (reason) {
if (!controller.signal.aborted) setToasts([{ id: "lab-copy-error", tone: "error",
title: "Не удалось изменить локальную копию",
description: reason instanceof Error ? reason.message : "Повторите действие." }]);
} finally {
announceLabStorageChange();
progressCallback.current?.(null);
request.current = null;
if (!controller.signal.aborted) setBusy(null);
}
}
const prepare = (signal: AbortSignal) => prepareLocalLabCopy(id, sourceId, composition,
{ signal, onProgress: (value) => progressCallback.current?.(value) });
const unavailable = !available || !!storageError;
return <>
<IconButton label={status} loading={busy === "download"}
disabled={!!busy || unavailable || !!copy?.local}
onClick={() => void perform("download", prepare)}>
<Icon name={copy?.local ? "database" : "download"} size={16} />
</IconButton>
<IconButton label={copy?.pinned ? "Открепить локальную запись" : "Оставить полную запись на этом устройстве"}
aria-pressed={copy?.pinned ?? false} loading={busy === "pin"} disabled={!!busy || unavailable}
onClick={() => void perform("pin", async (signal) => {
if (!copy?.local && !copy?.pinned) await prepare(signal);
signal.throwIfAborted();
await pinLabCopy(id, !copy?.pinned);
})}>
<Icon name="pin" size={16} />
</IconButton>
{copy?.local ? <IconButton label="Удалить только локальную копию" loading={busy === "remove"}
disabled={!!busy || copy.pinned || unavailable} onClick={() => setConfirm(true)}>
<Icon name="minus" size={16} />
</IconButton> : null}
<ToastStack items={toasts} onDismiss={(key) => setToasts((items) => items.filter((item) => item.id !== key))} />
<ConfirmationModal open={confirm} title="Удалить локальную копию?"
description="Результат и история запуска останутся. Копию можно вернуть кнопкой загрузки или открытием просмотра."
confirmLabel="Удалить копию" cancelLabel="Отмена" onClose={() => { if (!busy) setConfirm(false); }}
onConfirm={() => perform("remove", () => removeLabCopy(id))} />
</>;
}
@@ -0,0 +1,10 @@
import { WebViewer } from "@rerun-io/web-viewer";
import type { RerunFrameWindow } from "./recordedRerunProtocol";
import { createRecordedRerunOwner } from "./recordedRerunOwner";
// This entry is loaded only in the owned iframe. Upstream code is unmodified;
// destroying the frame also ends its timers, WASM, video and WebGPU lifetime.
const mount = document.getElementById("viewer");
if (!mount) throw new Error("Recorded viewer mount is missing");
(window as RerunFrameWindow).missionCoreRerun = createRecordedRerunOwner(() => new WebViewer(), mount);
@@ -0,0 +1,141 @@
import { createRecordedRerunFacade, type RecordedRerunViewer } from "./recordedRerunFacade";
import type { RerunFrameWindow } from "./recordedRerunProtocol";
import { relayIsolatedRerunInput } from "./isolatedRerunInput";
/** Own the complete recorded-viewer realm, not just its canvas or SDK handle. */
export function createIsolatedRerunHost(host: HTMLElement) {
let frame: HTMLIFrameElement | null = host.ownerDocument.createElement("iframe");
frame.title = "Синхронизированная запись";
frame.className = "rerun-viewport__runtime";
frame.loading = "eager";
let navigation: number | undefined;
let disposed = false;
let releaseFacade: (() => void) | null = null;
let releaseInput: (() => void) | null = null;
let frameWindow: RerunFrameWindow | null = null;
let rejectReady: ((reason: Error) => void) | null = null;
let timer: ReturnType<typeof setTimeout> | undefined;
const bootstrapAbort = new AbortController();
let markup: string | null = null;
let fetching = false;
const scheduleNavigation = () => {
if (disposed || navigation !== undefined) return;
const window = host.ownerDocument.defaultView;
const navigate = () => {
navigation = undefined;
if (disposed) return;
// Observation portals may exist before the asynchronous dock is mounted.
// Start the isolated realm only once its host belongs to the document.
if (host.isConnected === false) {
scheduleNavigation();
return;
}
frame!.src = "/rerun-runtime.html";
if (markup === null) {
if (fetching) return;
fetching = true;
// Fetch only the bundled, same-origin document. Inline it into the
// isolated realm so startup does not depend on a deferred iframe
// document navigation inside a dock/portal. Its assets use root URLs.
void fetch("/rerun-runtime.html", {signal: bootstrapAbort.signal, credentials: "same-origin", redirect: "error"})
.then(response => { if (!response.ok) throw new Error("Recorded viewer host failed to load"); return response.text(); })
.then(value => { if (!disposed) { markup = value; scheduleNavigation(); } })
.catch(() => { if (!disposed) { rejectReady?.(new Error("Recorded viewer host failed to load")); dispose(); } });
return;
}
frame!.srcdoc = markup;
if (frame!.parentNode !== host) host.append(frame!);
};
// A background operator tab may suspend animation frames completely.
// Bootstrap must progress independently of painting or focus.
if (window?.setTimeout) navigation = window.setTimeout(navigate, 50);
else navigate();
};
const dispose = () => {
if (disposed) return;
disposed = true;
if (navigation !== undefined) host.ownerDocument.defaultView?.clearTimeout(navigation);
clearTimeout(timer);
bootstrapAbort.abort();
delete host.dataset.rerunCamera;
frame!.onload = null;
frame!.onerror = null;
releaseInput?.();
releaseInput = null;
try {
releaseFacade?.();
} catch {
// Realm teardown is required even if a partial native start failed.
} finally {
releaseFacade = null;
frameWindow = null;
frame!.remove();
frame = null;
markup = null;
rejectReady?.(new Error("Recorded viewer was disposed"));
rejectReady = null;
}
};
const ready = new Promise<{ viewer: RecordedRerunViewer; mount: HTMLElement }>((resolve, reject) => {
rejectReady = reject;
const handleLoad = () => {
if (disposed) return;
try {
frameWindow = frame!.contentWindow as RerunFrameWindow | null;
const api = frameWindow?.missionCoreRerun;
if (!api && frame!.contentDocument?.URL === "about:blank") {
return;
}
if (!api || api.version !== 2) throw new Error("Recorded viewer host is unavailable");
const owner = createRecordedRerunFacade((request, bytes) => {
const current = frameWindow?.missionCoreRerun;
if (!current) throw new Error("Recorded viewer was disposed");
const response = current.invoke(request, bytes);
// Bounded, read-only evidence of the rendered eye at the existing
// playback poll. No extra timer, transport, history or camera writes.
if (JSON.parse(request).method === "get_current_time") {
try {
const eye = JSON.parse(current.invoke('{"method":"get-camera-eye"}'));
host.dataset.rerunCamera = JSON.stringify({
timeNs: JSON.parse(response).result ?? null, eye: eye.result ?? null,
});
} catch { delete host.dataset.rerunCamera; }
}
return response;
});
releaseFacade = owner.dispose;
api.connect(owner.notify);
releaseInput = relayIsolatedRerunInput(host, frameWindow, frame);
clearTimeout(timer);
bootstrapAbort.abort();
if (navigation !== undefined) host.ownerDocument.defaultView?.clearTimeout(navigation);
navigation = undefined;
rejectReady = null;
frame!.onload = null;
frame!.onerror = null;
resolve({ viewer: owner.facade, mount: host });
} catch (error) {
reject(new Error(String(error)));
dispose();
}
};
const handleError = () => {
reject(new Error("Recorded viewer host failed to load"));
dispose();
};
const bind = (element: HTMLIFrameElement) => {
element.onload = () => { if (frame === element) handleLoad(); };
element.onerror = () => { if (frame === element) handleError(); };
};
bind(frame!);
timer = setTimeout(() => {
reject(new Error("Recorded viewer host timed out"));
dispose();
}, 30_000);
});
scheduleNavigation();
return { ready, dispose };
}
@@ -0,0 +1,17 @@
/** Relay Escape from the isolated viewer realm to the owning application. */
export function relayIsolatedRerunInput(
host: HTMLElement,
frameWindow: Window | null,
_frame: HTMLIFrameElement | null,
) {
const parent = host.ownerDocument.defaultView;
const escape = (event: KeyboardEvent) => {
if (event.key !== "Escape" || event.defaultPrevented || !parent) return;
host.dispatchEvent(new parent.KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
};
frameWindow?.addEventListener("keydown", escape);
return () => {
frameWindow?.removeEventListener("keydown", escape);
frameWindow = null;
};
}
@@ -0,0 +1,39 @@
// Presets and the native snapshot boundary. No DOM-input journal: only Rerun
// knows the actual eye after navigation, auto-fit, interpolation and tracking.
export type RecordedRerunCameraEye = {
readonly position: readonly [number, number, number];
readonly lookTarget: readonly [number, number, number];
readonly eyeUp: readonly [number, number, number];
};
export const RECORDED_RERUN_ORBITAL_EYE: RecordedRerunCameraEye = {
position: [16, -16, 18], lookTarget: [0, 0, 0], eyeUp: [0, 0, 1],
};
export const RECORDED_RERUN_PLAN_EYE: RecordedRerunCameraEye = {
position: [0, 0, 30], lookTarget: [0, 0, 0], eyeUp: [0, 1, 0],
};
export function readNativeRerunCameraEye(value: unknown): RecordedRerunCameraEye | null {
if (value == null) return null; // No 3D frame rendered yet.
if (typeof value !== "object") throw new Error("Invalid native Rerun camera snapshot");
const eye = value as Record<string, unknown>;
const vector = (key: string): [number, number, number] => {
const item = eye[key];
if (!Array.isArray(item) || item.length !== 3 ||
!item.every(component => typeof component === "number" && Number.isFinite(component))) {
throw new Error("Invalid native Rerun camera vector");
}
return [item[0], item[1], item[2]];
};
return { position: vector("position"), lookTarget: vector("lookTarget"), eyeUp: vector("eyeUp") };
}
/** Select an eye for blueprint replacement, never implement camera motion. */
export function selectRecordedRerunCameraEye(
cameraContractChanged: boolean,
planView: boolean,
currentEye: RecordedRerunCameraEye | null,
): RecordedRerunCameraEye | undefined {
return cameraContractChanged
? (planView ? RECORDED_RERUN_PLAN_EYE : RECORDED_RERUN_ORBITAL_EYE)
: currentEye ?? undefined;
}
@@ -0,0 +1,97 @@
import type { WebViewer } from "@rerun-io/web-viewer";
import type { RerunInvoke } from "./recordedRerunProtocol";
import type { RecordedRerunCameraEye } from "./recordedRerunCameraJournal";
type NativeChannel = ReturnType<WebViewer["open_channel"]>;
type Channel = Pick<NativeChannel, "ready" | "send_rrd" | "close">;
export type RecordedRerunViewer = Pick<WebViewer,
"start" | "stop" | "ready" | "on" | "open" | "close" | "override_panel_state" |
"get_active_recording_id" | "get_active_timeline" | "get_current_time" |
"get_playing" | "get_time_range" | "set_active_timeline" |
"set_current_time" | "set_playing"
> & {
open_channel: (name?: string) => Channel;
get_camera_eye: () => RecordedRerunCameraEye | null;
set_height_slice: (lower:number|null,upper:number|null)=>boolean;
get_height_bounds: ()=>{min:number;max:number}|null;
};
/** Parent-owned values only. No SDK Promise or foreign prototype escapes. */
export function createRecordedRerunFacade(invoke: RerunInvoke | null) {
let nextId = 0;
const callbacks = new Map<number, (...args: unknown[]) => void>();
const starts = new Map<number, { resolve: () => void; reject: (error: Error) => void }>();
const command = (method: string, args: unknown[] = [], id?: number, bytes?: Uint8Array) => {
if (!invoke) throw new Error("Recorded viewer was disposed");
const response = JSON.parse(invoke(JSON.stringify({ method, args, id }), bytes));
if (response.error) throw new Error(response.error);
return response.result;
};
const dispose = () => {
callbacks.clear();
for (const pending of starts.values()) pending.reject(new Error("Recorded viewer was disposed"));
starts.clear();
try { if (invoke) command("stop"); } finally { invoke = null; }
};
const notify = (message: string) => {
if (!invoke) return;
const event = JSON.parse(message);
if (event.type === "event") callbacks.get(event.id)?.(...event.values);
else {
const pending = starts.get(event.id);
starts.delete(event.id);
if (event.type === "started") pending?.resolve();
else pending?.reject(new Error(event.message));
}
};
const facade: RecordedRerunViewer = {
get ready() { return invoke ? command("ready") : false; },
start(source, _parent, options) {
return new Promise<void>((resolve, reject) => {
const id = ++nextId;
starts.set(id, { resolve, reject });
try { command("start", [source, options], id); }
catch (error) { starts.delete(id); reject(error); }
});
},
stop: dispose,
on: ((event: string, callback: (...args: unknown[]) => void) => {
const id = ++nextId;
callbacks.set(id, callback);
try { command("on", [event], id); }
catch (error) { callbacks.delete(id); throw error; }
return () => {
if (callbacks.delete(id) && invoke) command("off", [], id);
};
}) as WebViewer["on"],
open_channel(name) {
const id = ++nextId;
command("channel-open", name === undefined ? [] : [name], id);
let closed = false;
return {
get ready() { return !closed && invoke ? command("channel-ready", [], id) : false; },
send_rrd(bytes) { if (!closed && invoke) command("channel-send", [], id, bytes); },
close() {
if (closed) return;
closed = true;
if (invoke) command("channel-close", [], id);
},
};
},
open: (...args) => command("open", args),
close: (...args) => { if (invoke) command("close", args); },
override_panel_state: (...args) => command("override_panel_state", args),
get_active_recording_id: () => command("get_active_recording_id"),
get_active_timeline: (...args) => command("get_active_timeline", args),
get_current_time: (...args) => command("get_current_time", args),
get_playing: (...args) => command("get_playing", args),
get_time_range: (...args) => command("get_time_range", args),
set_active_timeline: (...args) => command("set_active_timeline", args),
set_current_time: (...args) => command("set_current_time", args),
set_playing: (...args) => command("set_playing", args),
get_camera_eye: () => command("get-camera-eye"),
set_height_slice: (lower,upper) => command("set-height-slice",[lower,upper]),
get_height_bounds: () => command("get-height-bounds"),
};
return { facade, dispose, notify };
}
@@ -0,0 +1,111 @@
import type { WebViewer } from "@rerun-io/web-viewer";
import type { RerunFrameApi, RerunNotify } from "./recordedRerunProtocol";
import { readNativeRerunCameraEye } from "./recordedRerunCameraJournal";
/** Lives entirely inside the disposable iframe, including pending SDK starts. */
export function createRecordedRerunOwner(create: () => WebViewer, mount: HTMLElement): RerunFrameApi {
let native: WebViewer | null = null;
let notify: RerunNotify | null = null;
const subscriptions = new Map<number, () => void>();
const channels = new Map<number, ReturnType<WebViewer["open_channel"]>>();
const send = (message: object) => notify?.(JSON.stringify(message));
const stop = () => {
notify = null;
for (const unsubscribe of subscriptions.values()) {
try { unsubscribe(); } catch { /* Continue partial-start cleanup. */ }
}
subscriptions.clear();
for (const channel of channels.values()) {
try { channel.close(); } catch { /* Other channels must still close. */ }
}
channels.clear();
const current = native;
native = null;
try { current?.stop(); } catch { /* Realm teardown remains authoritative. */ }
};
const required = () => {
if (!native) throw new Error("Recorded viewer was disposed");
return native;
};
const start = async (id: number, args: [string | string[] | null, Parameters<WebViewer["start"]>[2]]) => {
const starting = required();
try {
await starting.start(args[0], mount, args[1]);
if (native === starting) send({ type: "started", id });
} catch (error) {
if (native === starting) send({ type: "start-failed", id, message: String(error) });
} finally {
if (native !== starting) {
try { starting.stop(); } catch { /* Late completion after disposal. */ }
}
}
};
return {
version: 2,
connect(callback) {
if (native) throw new Error("Recorded viewer already has an owner");
native = create();
notify = callback;
},
invoke(request, bytes) {
try {
const { method, args = [], id } = JSON.parse(request);
let result: unknown;
switch (method) {
case "stop": stop(); break;
case "start": required(); void start(id, args); break;
case "ready": result = native?.ready ?? false; break;
case "on": {
const subscribe = required().on as (event: string, callback: (...values: unknown[]) => void) => () => void;
subscriptions.set(id, subscribe.call(required(), args[0], (...values) => send({ type: "event", id, values })));
break;
}
case "off":
try { subscriptions.get(id)?.(); } finally { subscriptions.delete(id); }
break;
case "channel-open": {
const name = args[0] as string | undefined;
channels.set(id, required().open_channel(name));
break;
}
case "channel-ready": result = channels.get(id)?.ready ?? false; break;
case "channel-send": if (bytes) {
channels.get(id)?.send_rrd(bytes);
} break;
case "channel-close":
try { channels.get(id)?.close(); } finally {
channels.delete(id);
}
break;
case "get-camera-eye": result = readNativeRerunCameraEye(
(required() as WebViewer & { get_camera_eye?(): unknown }).get_camera_eye?.(),
); break;
case "set-height-slice": {
const [lower,upper]=args;
if ([lower,upper].some(v=>v!==null&&(typeof v!=="number"||!Number.isFinite(v))) ||
(lower!==null&&upper!==null&&lower>upper)) throw new Error("Invalid height slice");
result=(required() as WebViewer & {set_height_slice?(lower:number|null,upper:number|null):boolean}).set_height_slice?.(lower,upper)??false;
} break;
case "get-height-bounds": result=(required() as WebViewer & {get_height_bounds?():{min:number;max:number}|null}).get_height_bounds?.()??null; break;
case "open": required().open(args[0]); break;
case "close": required().close(args[0]); break;
case "override_panel_state": required().override_panel_state(args[0], args[1]); break;
case "get_active_recording_id": result = required().get_active_recording_id(); break;
case "get_active_timeline": result = required().get_active_timeline(args[0]); break;
case "get_current_time": result = required().get_current_time(args[0], args[1]); break;
case "get_playing": result = required().get_playing(args[0]); break;
case "get_time_range": result = required().get_time_range(args[0], args[1]); break;
case "set_active_timeline": required().set_active_timeline(args[0], args[1]); break;
case "set_current_time": required().set_current_time(args[0], args[1], args[2]); break;
case "set_playing": required().set_playing(args[0], args[1]); break;
default: throw new Error("Unsupported recorded viewer command");
}
return JSON.stringify({ result });
} catch (error) {
// A native Error also has a foreign prototype. Return text, never throw
// that object into a parent Promise/callback retained after disposal.
return JSON.stringify({ error: String(error) });
}
},
};
}
@@ -0,0 +1,12 @@
/** Only parent-owned inputs and primitive strings cross the recorded realm.
* An SDK instance, Promise, DOM node or native callback never becomes a value
* retained by React. This is not a second playback clock.
*/
export type RerunInvoke = (request: string, bytes?: Uint8Array) => string;
export type RerunNotify = (message: string) => void;
export interface RerunFrameApi {
version: 2;
connect: (notify: RerunNotify) => void;
invoke: RerunInvoke;
}
export type RerunFrameWindow = Window & { missionCoreRerun?: RerunFrameApi };

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