mirror of
https://github.com/legop3/MultiRoombaRover.git
synced 2026-11-14 10:42:45 -05:00
Compare commits
57
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6b57ac1725 | ||
|
|
00cd125fda | ||
|
|
684acdd2b6 | ||
|
|
f138cd7b96 | ||
|
|
6454a9b460 | ||
|
|
1976377235 | ||
|
|
52c171c256 | ||
|
|
42bf67d207 | ||
|
|
d65fd99de4 | ||
|
|
e3d4d9af9b | ||
|
|
ab730ee8a3 | ||
|
|
8fe4f2f98e | ||
|
|
89f3a1cb65 | ||
|
|
79d36cae93 | ||
|
|
1dcd7e5d7d | ||
|
|
b4bc99ab27 | ||
|
|
c94e1a0508 | ||
|
|
abcb0871b2 | ||
|
|
1ffe680895 | ||
|
|
ed26b90384 | ||
|
|
2b48fee00f | ||
|
|
1284125fff | ||
|
|
28d0b1437d | ||
|
|
9d3b8df4bf | ||
|
|
9d42cb5581 | ||
|
|
e670226f8c | ||
|
|
0669f29a4a | ||
|
|
38d3465bf8 | ||
|
|
6bfbb8ad80 | ||
|
|
ba2f66ebc1 | ||
|
|
fde2fca0a0 | ||
|
|
d36ea4f672 | ||
|
|
4be6e6c9a2 | ||
|
|
7bac2fc447 | ||
|
|
e8a407cd49 | ||
|
|
bee1866a70 | ||
|
|
ddfc889a8c | ||
|
|
c71267873a | ||
|
|
1ba4ebe5ff | ||
|
|
607d327e9c | ||
|
|
1bdca60648 | ||
|
|
ea4af2ebb3 | ||
|
|
b2bbaf2085 | ||
|
|
18e7fb8d1b | ||
|
|
ba71106544 | ||
|
|
a395656056 | ||
|
|
50c2c1f5db | ||
|
|
b59389870e | ||
|
|
cd4aee4e74 | ||
|
|
9de0bfb1e7 | ||
|
|
a157ece816 | ||
|
|
8cb7cc5bdc | ||
|
|
34936ab05c | ||
|
|
7231809140 | ||
|
|
8ca714cf1a | ||
|
|
ffd34de56c | ||
|
|
846c9dae55 |
@@ -5,6 +5,7 @@
|
||||
.git
|
||||
.gitignore
|
||||
**/node_modules
|
||||
webui/.cache/mediamtx/
|
||||
# Neither the legacy state directory nor the Compose-mounted replacement may
|
||||
# enter an image build. This prevents credentials and backups from becoming
|
||||
# image layers after an operator has started using either deployment layout.
|
||||
|
||||
@@ -58,6 +58,8 @@ jobs:
|
||||
# replaced on each successful push, just as main replaces `latest`.
|
||||
- name: Build and optionally publish
|
||||
uses: docker/build-push-action@v7
|
||||
env:
|
||||
DOCKER_BUILD_RECORD_RETENTION_DAYS: 3
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64
|
||||
|
||||
@@ -5,6 +5,7 @@ create_2_Open_Interface_Spec.txt
|
||||
|
||||
logs
|
||||
node_modules/
|
||||
webui/.cache/mediamtx/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.pio
|
||||
@@ -41,3 +42,4 @@ server/data/fleet-reports.sqlite-wal
|
||||
server/data/configuration.sqlite
|
||||
server/data/configuration.sqlite-shm
|
||||
server/data/configuration.sqlite-wal
|
||||
AGENTS.md
|
||||
|
||||
+37
-23
@@ -9,15 +9,21 @@
|
||||
ARG FEDORA_VERSION=43
|
||||
|
||||
FROM fedora:${FEDORA_VERSION} AS architecture-check
|
||||
ARG FEDORA_VERSION
|
||||
ARG TARGETARCH
|
||||
# The central server is currently deployed and verified only on amd64. Failing
|
||||
# here avoids publishing an ARM image whose native workers and hardware paths
|
||||
# have never been exercised on a real ARM server.
|
||||
RUN test "${TARGETARCH}" = "amd64" || (echo "MultiRover server images support only linux/amd64." >&2; exit 1)
|
||||
|
||||
FROM architecture-check AS webui-build
|
||||
RUN dnf install -y --setopt=install_weak_deps=False nodejs npm \
|
||||
&& dnf clean all
|
||||
# Both Node builders reuse the same installed toolchain layer.
|
||||
# Fedora 43 uses DNF5. Cache metadata and RPMs outside image layers, and keep
|
||||
# downloads after installation so invalidated layers can reuse them.
|
||||
FROM architecture-check AS node-build-base
|
||||
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-node-build-base,target=/var/cache/libdnf5,sharing=locked \
|
||||
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True nodejs npm
|
||||
|
||||
FROM node-build-base AS webui-build
|
||||
WORKDIR /build
|
||||
# Copy dependency manifests first so ordinary source edits retain the expensive
|
||||
# npm cache layer. npm ci makes the checked-in lockfile the exact dependency
|
||||
@@ -25,14 +31,17 @@ WORKDIR /build
|
||||
COPY webui/package.json webui/package-lock.json ./webui/
|
||||
RUN --mount=type=cache,target=/root/.npm \
|
||||
cd webui && npm ci
|
||||
# Keep the pinned browser publisher in a reusable layer across UI source edits.
|
||||
COPY webui/scripts/prepareMediaMtx.js ./webui/scripts/prepareMediaMtx.js
|
||||
RUN cd webui && node scripts/prepareMediaMtx.js
|
||||
COPY webui ./webui
|
||||
# Vite deliberately emits into ../server/public. Create that destination in the
|
||||
# isolated builder and copy only its finished files into the runtime stage.
|
||||
RUN mkdir -p server/public && cd webui && npm run build
|
||||
|
||||
FROM architecture-check AS server-dependencies
|
||||
RUN dnf install -y --setopt=install_weak_deps=False nodejs npm gcc-c++ make python3 \
|
||||
&& dnf clean all
|
||||
FROM node-build-base AS server-dependencies
|
||||
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-server-dependencies,target=/var/cache/libdnf5,sharing=locked \
|
||||
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True gcc-c++ make python3
|
||||
WORKDIR /build/server
|
||||
COPY server/package.json server/package-lock.json ./
|
||||
# Native Node modules compile here when a matching prebuild is unavailable;
|
||||
@@ -41,7 +50,8 @@ RUN --mount=type=cache,target=/root/.npm \
|
||||
npm ci --omit=dev
|
||||
|
||||
FROM architecture-check AS native-workers
|
||||
RUN dnf install -y --setopt=install_weak_deps=False \
|
||||
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-native-workers,target=/var/cache/libdnf5,sharing=locked \
|
||||
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True \
|
||||
bluez-libs-devel \
|
||||
gcc-c++ \
|
||||
libcap \
|
||||
@@ -49,8 +59,7 @@ RUN dnf install -y --setopt=install_weak_deps=False \
|
||||
libusb1-devel \
|
||||
make \
|
||||
pkgconf-pkg-config \
|
||||
wiiuse-devel \
|
||||
&& dnf clean all
|
||||
wiiuse-devel
|
||||
WORKDIR /build
|
||||
COPY server/src/services/kinectService/native ./kinect
|
||||
COPY server/src/services/balanceBoardService/native ./balance-board
|
||||
@@ -66,8 +75,8 @@ ARG NEOLINK_VERSION=0.6.2
|
||||
ARG NEOLINK_SHA256=0cb963b44dca7ccc5333154092186e1536c687aef0e1ad119b7f310a7471dbbb
|
||||
ARG GOOGLE_TTS_VERSION=26.5
|
||||
ARG GOOGLE_TTS_SHA256=6a9eae6726871788da52e767dad964a1c83e7feb7e7dbac508a2574a2345ac24
|
||||
RUN dnf install -y --setopt=install_weak_deps=False curl findutils tar unzip xz \
|
||||
&& dnf clean all
|
||||
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-packaged-tools,target=/var/cache/libdnf5,sharing=locked \
|
||||
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True curl findutils tar unzip xz
|
||||
WORKDIR /build/tools
|
||||
# Each external artifact is pinned and checked before extraction. A changed or
|
||||
# truncated upstream download therefore fails the image build instead of being
|
||||
@@ -100,11 +109,12 @@ RUN curl --fail --location --retry 3 \
|
||||
FROM architecture-check AS learning-dependencies
|
||||
# CPU-only learning dependencies are built once. Disabled installations never
|
||||
# launch Python or install packages as a side effect of starting Node.
|
||||
RUN dnf install -y --setopt=install_weak_deps=False python3 python3-pip \
|
||||
&& dnf clean all
|
||||
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-learning-dependencies,target=/var/cache/libdnf5,sharing=locked \
|
||||
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True python3 python3-pip
|
||||
COPY server/src/services/roverLearningService/workers/requirements.txt /tmp/learning-requirements.txt
|
||||
RUN python3 -m venv /opt/rover-learning \
|
||||
&& /opt/rover-learning/bin/pip install --no-cache-dir -r /tmp/learning-requirements.txt
|
||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
python3 -m venv /opt/rover-learning \
|
||||
&& /opt/rover-learning/bin/pip install -r /tmp/learning-requirements.txt
|
||||
|
||||
FROM fedora:${FEDORA_VERSION} AS runtime
|
||||
ARG FEDORA_VERSION
|
||||
@@ -114,14 +124,16 @@ RUN test "${TARGETARCH}" = "amd64" || (echo "MultiRover server images support on
|
||||
# replay output path. Enable RPM Fusion Free before installing runtime packages
|
||||
# so the image receives the complete FFmpeg build instead of requiring replay
|
||||
# code to work around a deployment-only codec omission.
|
||||
RUN dnf install -y --setopt=install_weak_deps=False \
|
||||
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-runtime,target=/var/cache/libdnf5,sharing=locked \
|
||||
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True \
|
||||
"https://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-${FEDORA_VERSION}.noarch.rpm"
|
||||
# This is the complete runtime package set. Build headers and compilers live in
|
||||
# earlier stages, while media, TTS, USB, and Bluetooth libraries remain here
|
||||
# because enabled services invoke them after startup. Weak dependencies are
|
||||
# deliberately disabled: Fedora otherwise installs desktop portals, graphical
|
||||
# themes, and GPU drivers that a headless server neither starts nor uses.
|
||||
RUN dnf install -y --setopt=install_weak_deps=False \
|
||||
RUN --mount=type=cache,id=dnf-${FEDORA_VERSION}-runtime,target=/var/cache/libdnf5,sharing=locked \
|
||||
dnf install -y --setopt=install_weak_deps=False --setopt=keepcache=True \
|
||||
bluez \
|
||||
bluez-libs \
|
||||
espeak \
|
||||
@@ -143,17 +155,11 @@ RUN dnf install -y --setopt=install_weak_deps=False \
|
||||
tini \
|
||||
wiiuse \
|
||||
--allowerasing \
|
||||
&& dnf clean all \
|
||||
&& useradd --uid 1000 --create-home --home-dir /home/multirover --shell /sbin/nologin multirover \
|
||||
&& install -d -o multirover -g multirover -m 0755 /data /opt/multirover/server
|
||||
|
||||
WORKDIR /opt/multirover/server
|
||||
COPY server/index.js server/package.json server/package-lock.json ./
|
||||
COPY server/src ./src
|
||||
COPY server/assets ./assets
|
||||
COPY server/prompts ./prompts
|
||||
COPY --from=server-dependencies /build/server/node_modules ./node_modules
|
||||
COPY --from=webui-build /build/server/public ./public
|
||||
COPY --from=native-workers /build/kinect/kinect_worker ./src/services/kinectService/native/kinect_worker
|
||||
COPY --from=native-workers /build/balance-board/balance_board_worker ./src/services/balanceBoardService/native/balance_board_worker
|
||||
COPY --from=packaged-tools /output/ /
|
||||
@@ -176,6 +182,14 @@ RUN setcap cap_net_admin,cap_net_bind_service+ep \
|
||||
&& test -s /tmp/chromegtts-smoke.wav \
|
||||
&& rm /tmp/chromegtts-smoke.wav
|
||||
|
||||
# Frequently edited application files come after dependencies and tool checks,
|
||||
# so server changes do not invalidate the large runtime dependency layers.
|
||||
COPY --from=webui-build /build/server/public ./public
|
||||
COPY server/index.js server/package.json server/package-lock.json ./
|
||||
COPY server/src ./src
|
||||
COPY server/assets ./assets
|
||||
COPY server/prompts ./prompts
|
||||
|
||||
ENV NODE_ENV=production \
|
||||
SERVER_DATA_DIR=/data \
|
||||
ROVER_SNAPSHOT_WRITER_BIN=/usr/local/bin/rover-snapshot-writer.sh
|
||||
|
||||
+5
-1
@@ -23,9 +23,13 @@ services:
|
||||
# Required for Bluetooth hardware such as the Balance Board.
|
||||
- /run/dbus/system_bus_socket:/run/dbus/system_bus_socket:ro
|
||||
|
||||
# Required for Kinect USB access.
|
||||
# Kinect USB access.
|
||||
devices:
|
||||
- /dev/bus/usb:/dev/bus/usb
|
||||
# For a server-local microphone, uncomment this device and group_add below.
|
||||
# - /dev/snd:/dev/snd
|
||||
# group_add:
|
||||
# - "${AUDIO_GID:?Set AUDIO_GID to the host sound device group ID}"
|
||||
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
|
||||
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
@@ -26,6 +26,8 @@ Phase 1 must be complete and verified before Phase 2 begins. Containerization mu
|
||||
|
||||
## Decision log
|
||||
|
||||
- 2026-10-02: The admin container controls accept a tag within the repository supplied by Compose through `MULTIROVER_TARGET_IMAGE`. A successful healthy replacement saves the tag in the lifecycle status volume; failed replacements retain the previous selection. Checks and later updates follow that saved tag. Changing repositories in Compose resets the selection. Manual Compose deployments still use the Compose image and can replace a UI-selected image; the UI displays both references. The lifecycle helper itself is updated through Compose. Image rollback does not revert application data migrations. Deploy this feature to both the application and lifecycle services before using tag selection.
|
||||
|
||||
- 2026-09-14: Publish `ghcr.io/legop3/multiroombarover:latest` only from the repository's main branch. Every other repository branch publishes one moving development image named for that branch, with invalid tag separators normalized; these are development selectors rather than numbered releases. Pull requests only verify that the image builds. There are no release numbers, semantic-version tags, stable/edge channels, or operator-facing version selection. Docker image digests remain an internal mechanism for detecting an available update and retaining the previously running image for rollback.
|
||||
- 2026-09-15: Support only `linux/amd64` for the central server image. Rover computers remain independently ARM-capable, but publishing an untested ARM server image would multiply native-worker, media-binary, TTS-library, and hardware validation without serving the current deployment. ARM server support can be added later when a real ARM server exists to verify it.
|
||||
- 2026-09-15: Mount the application data directory from the Docker-managed `multirover-data` named volume instead of a host bind path. Docker initializes the empty volume with the image's non-root ownership, eliminating host UID matching, directory creation, ownership commands, and root application startup. The admin backup/restore system is the supported portable interface to the complete data tree.
|
||||
|
||||
@@ -64,6 +64,7 @@ socket.on('connect', async () => {
|
||||
// previously stored session with this object instead of merging snapshots.
|
||||
socket.on('session:sync', (session) => {
|
||||
console.log('Session:', session);
|
||||
console.log('Server mode:', session.mode);
|
||||
});
|
||||
|
||||
// chat:init contains the recent chat history available when the bot connects.
|
||||
@@ -105,6 +106,21 @@ Run it with:
|
||||
node bot.js
|
||||
```
|
||||
|
||||
## Reading server mode
|
||||
|
||||
Read `session.mode` from the `session:sync` snapshot to get the current server
|
||||
mode. Its possible values are `open`, `turns`, `admin`, and `lockdown`.
|
||||
|
||||
The server sends a fresh session snapshot whenever the mode changes, so the
|
||||
example's handler receives both the initial mode and subsequent updates. No
|
||||
polling or separate mode listener is needed. If your bot stores session data for
|
||||
its chat-handling logic, replace the stored session on every `session:sync` and
|
||||
read the mode from that latest snapshot.
|
||||
|
||||
`session.mode` is the server-wide mode; `session.role` is this connection's role
|
||||
(such as `spectator`), and `session.operatingMode` is a separate connection field.
|
||||
Use `session.mode` when answering chat questions about the server's current mode.
|
||||
|
||||
## Events used
|
||||
|
||||
- `nickname:set` sets the bot's visible nickname.
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Finite CPU benchmark of LeRobot ACT with ImageNet-pretrained ResNet-18.
|
||||
|
||||
First run: python3 perf/act-benchmark.py --setup
|
||||
Repeat: python3 perf/act-benchmark.py
|
||||
Quick: python3 perf/act-benchmark.py --threads 4 --seconds 2 --iterations 2 --batch-size 2
|
||||
|
||||
Python >=3.12, Linux. Setup uses a private cached environment. Only the visual
|
||||
backbone is pretrained; the action policy is randomly initialized. Synthetic
|
||||
in-memory inputs measure compute, NOT learning quality or driving competence.
|
||||
No rover connections, server changes, training checkpoints, or background jobs.
|
||||
"""
|
||||
import argparse
|
||||
import contextlib
|
||||
import importlib.metadata
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import resource
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import venv
|
||||
|
||||
REVISION = '146d8474932c8b566717eb2738ba459337ab71c4'
|
||||
|
||||
|
||||
def positive(value):
|
||||
number = int(value)
|
||||
if number < 1:
|
||||
raise argparse.ArgumentTypeError('Must be positive')
|
||||
return number
|
||||
|
||||
|
||||
def arguments():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument('--setup', action='store_true')
|
||||
parser.add_argument('--cache', type=Path, default=Path.home() / '.cache/rover-act-benchmark')
|
||||
parser.add_argument('--threads', nargs='+', type=positive, default=[4, 8, 16])
|
||||
parser.add_argument('--seconds', type=positive, default=10)
|
||||
parser.add_argument('--iterations', type=positive, default=10)
|
||||
parser.add_argument('--batch-size', type=positive, default=8, help='Training only; inference batch is always one rover')
|
||||
parser.add_argument('--chunk-size', type=positive, default=10, help='Future command steps per prediction, not observed history')
|
||||
parser.add_argument('--width', type=positive, default=160)
|
||||
parser.add_argument('--height', type=positive, default=120)
|
||||
parser.add_argument('--sensors', type=positive, default=30)
|
||||
parser.add_argument('--mode', choices=['both', 'inference', 'training'], default='both')
|
||||
parser.add_argument('--timeout', type=positive, default=900, help='Hard per-case wall time limit in seconds')
|
||||
parser.add_argument('--worker', action='store_true', help=argparse.SUPPRESS)
|
||||
parser.add_argument('--result', type=Path, help=argparse.SUPPRESS)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def setup(args):
|
||||
python = args.cache / 'venv/bin/python'
|
||||
if not python.exists():
|
||||
venv.EnvBuilder(with_pip=True).create(args.cache / 'venv')
|
||||
subprocess.run([str(python), '-m', 'pip', 'install', '--no-compile', 'torch', 'torchvision',
|
||||
'--index-url', 'https://download.pytorch.org/whl/cpu'], check=True)
|
||||
# Install only ACT's import dependencies: the full robotics/dataset stack has
|
||||
# unrelated version constraints and is not exercised by this benchmark.
|
||||
subprocess.run([str(python), '-m', 'pip', 'install', '--no-compile', 'numpy', 'einops>=0.8,<0.9',
|
||||
'draccus>=0.11.6,<0.12', 'huggingface-hub>=1.6,<2', 'safetensors',
|
||||
'packaging', 'termcolor', 'tqdm', 'gymnasium'], check=True)
|
||||
subprocess.run([str(python), '-m', 'pip', 'install', '--no-compile', '--no-deps',
|
||||
f'https://github.com/huggingface/lerobot/archive/{REVISION}.zip'], check=True)
|
||||
(args.cache / 'source-revision').write_text(REVISION)
|
||||
|
||||
|
||||
def worker(args):
|
||||
import torch
|
||||
from lerobot.configs import FeatureType, PolicyFeature
|
||||
from lerobot.policies.act.configuration_act import ACTConfig
|
||||
from lerobot.policies.act.modeling_act import ACTPolicy
|
||||
|
||||
torch.set_num_threads(args.threads[0])
|
||||
torch.set_num_interop_threads(1)
|
||||
torch.manual_seed(7)
|
||||
training = args.mode == 'training'
|
||||
batch_size = args.batch_size if training else 1
|
||||
config = ACTConfig(device='cpu', chunk_size=args.chunk_size, n_action_steps=1,
|
||||
input_features={
|
||||
'observation.images.front': PolicyFeature(type=FeatureType.VISUAL, shape=(3, args.height, args.width)),
|
||||
'observation.state': PolicyFeature(type=FeatureType.STATE, shape=(args.sensors,)),
|
||||
}, output_features={'action': PolicyFeature(type=FeatureType.ACTION, shape=(2,))})
|
||||
policy = ACTPolicy(config).cpu().float()
|
||||
policy.train(training)
|
||||
optimizer_config = config.get_optimizer_preset()
|
||||
optimizer = optimizer_config.build(policy.get_optim_params()) if training else None
|
||||
# Already-normalized tensors stand in for a decoded observation and target
|
||||
# sequence. Avoid video/dataset overhead in this compute-only measurement.
|
||||
images = torch.rand(batch_size, 3, args.height, args.width)
|
||||
mean = torch.tensor([.485, .456, .406]).view(1, 3, 1, 1)
|
||||
std = torch.tensor([.229, .224, .225]).view(1, 3, 1, 1)
|
||||
batch = {'observation.images.front': (images - mean) / std,
|
||||
'observation.state': torch.randn(batch_size, args.sensors)}
|
||||
if training:
|
||||
batch['action'] = torch.rand(batch_size, args.chunk_size, 2) * 2 - 1
|
||||
batch['action_is_pad'] = torch.zeros(batch_size, args.chunk_size, dtype=torch.bool)
|
||||
|
||||
def step():
|
||||
if training:
|
||||
optimizer.zero_grad(set_to_none=True)
|
||||
loss, _ = policy(batch)
|
||||
if not torch.isfinite(loss):
|
||||
raise RuntimeError('Non-finite training loss')
|
||||
loss.backward()
|
||||
norm = torch.nn.utils.clip_grad_norm_(policy.parameters(), optimizer_config.grad_clip_norm,
|
||||
error_if_nonfinite=True)
|
||||
optimizer.step()
|
||||
return {'loss': loss.item(), 'gradientNorm': norm.item()}
|
||||
# select_action can serve cached actions; directly time a full chunk.
|
||||
prediction = policy.predict_action_chunk(batch)
|
||||
if prediction.shape != (1, args.chunk_size, 2) or not torch.isfinite(prediction).all():
|
||||
raise RuntimeError('Invalid action output')
|
||||
return {'outputShape': list(prediction.shape)}
|
||||
|
||||
with (contextlib.nullcontext() if training else torch.inference_mode()):
|
||||
for _ in range(3):
|
||||
step()
|
||||
timings = []
|
||||
started, cpu_started = time.perf_counter(), time.process_time()
|
||||
while len(timings) < args.iterations or time.perf_counter() - started < args.seconds:
|
||||
tick = time.perf_counter()
|
||||
last = step()
|
||||
timings.append((time.perf_counter() - tick) * 1000)
|
||||
elapsed, cpu = time.perf_counter() - started, time.process_time() - cpu_started
|
||||
timings.sort()
|
||||
result = dict(mode=args.mode, threads=args.threads[0], batchSize=batch_size,
|
||||
iterations=len(timings), elapsedSeconds=elapsed, p50Ms=statistics.median(timings),
|
||||
p95Ms=timings[math.ceil(.95*len(timings))-1], maxMs=max(timings),
|
||||
stepsPerSecond=len(timings)/elapsed, examplesPerSecond=len(timings)*batch_size/elapsed,
|
||||
cpuCores=cpu/elapsed, peakMiB=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024,
|
||||
parameters=sum(p.numel() for p in policy.parameters()),
|
||||
trainableParameters=sum(p.numel() for p in policy.parameters() if p.requires_grad),
|
||||
lastStep=last, config={
|
||||
'chunkSize': config.chunk_size, 'dimModel': config.dim_model, 'klWeight': config.kl_weight,
|
||||
'pretrainedBackbone': config.pretrained_backbone_weights, 'useVae': config.use_vae,
|
||||
'encoderLayers': config.n_encoder_layers, 'decoderLayers': config.n_decoder_layers,
|
||||
'feedforwardDimension': config.dim_feedforward, 'observationSteps': config.n_obs_steps,
|
||||
'learningRate': optimizer_config.lr, 'backboneLearningRate': config.optimizer_lr_backbone},
|
||||
versions={key: importlib.metadata.version(key) for key in ['torch','torchvision','lerobot','numpy','einops','draccus']})
|
||||
args.result.write_text(json.dumps(result))
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments()
|
||||
if sys.version_info < (3, 12):
|
||||
raise RuntimeError('Use Python 3.12 or newer')
|
||||
args.cache = args.cache.expanduser().resolve()
|
||||
os.environ['TORCH_HOME'] = str(args.cache / 'torch')
|
||||
if args.worker:
|
||||
worker(args)
|
||||
return
|
||||
if args.setup:
|
||||
setup(args)
|
||||
python = args.cache / 'venv/bin/python'
|
||||
marker = args.cache / 'source-revision'
|
||||
if not python.exists() or not marker.exists() or marker.read_text() != REVISION:
|
||||
raise RuntimeError('Run python3 perf/act-benchmark.py --setup first')
|
||||
print('CPU FP32 ACT: pretrained visual backbone, untrained action policy; synthetic data.', flush=True)
|
||||
print(f'One {args.width}x{args.height} image + {args.sensors} sensors; {args.chunk_size} future left/right command pairs.', flush=True)
|
||||
print('Inference times a fresh full prediction. Training includes backbone gradients and optimizer update.', flush=True)
|
||||
print('mode threads batch p50 ms p95 ms max ms steps/s examples/s CPU cores peak MiB', flush=True)
|
||||
modes = ['inference', 'training'] if args.mode == 'both' else [args.mode]
|
||||
results, failures = [], []
|
||||
initial_load = os.getloadavg()
|
||||
with tempfile.TemporaryDirectory(prefix='act-benchmark-') as directory:
|
||||
for mode in modes:
|
||||
for threads in args.threads:
|
||||
result_path = Path(directory) / 'result.json'
|
||||
command = [str(python), str(Path(__file__).resolve()), '--worker', '--cache', str(args.cache),
|
||||
'--mode', mode, '--threads', str(threads), '--result', str(result_path)]
|
||||
for option in ['seconds','iterations','batch_size','chunk_size','width','height','sensors']:
|
||||
command += ['--'+option.replace('_','-'), str(getattr(args, option))]
|
||||
try:
|
||||
subprocess.run(command, check=True, timeout=args.timeout,
|
||||
env={**os.environ, 'PYTHONDONTWRITEBYTECODE':'1'})
|
||||
r = json.loads(result_path.read_text())
|
||||
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error:
|
||||
failures.append(dict(mode=mode, threads=threads, error=str(error)))
|
||||
print(f'Case failed: {mode}, {threads} threads: {error}', flush=True)
|
||||
break # Avoid repeating the same setup/import/OOM error.
|
||||
results.append(r)
|
||||
print(f"{mode:10} {threads:7} {r['batchSize']:5} {r['p50Ms']:6.1f} {r['p95Ms']:6.1f} {r['maxMs']:6.1f} {r['stepsPerSecond']:7.2f} {r['examplesPerSecond']:10.2f} {r['cpuCores']:9.2f} {r['peakMiB']:8.0f}", flush=True)
|
||||
if failures:
|
||||
break
|
||||
report = dict(benchmark='act-cpu-v1', sourceRevision=REVISION, platform=platform.platform(),
|
||||
python=sys.version, logicalCpus=os.cpu_count(), initialLoadAverage=initial_load,
|
||||
finalLoadAverage=os.getloadavg(), imageSize=[args.width,args.height], sensors=args.sensors,
|
||||
chunkSize=args.chunk_size, output='commanded left/right wheels, not physical velocity or position',
|
||||
exclusions=['capture','video decode','dataset I/O','network','concurrent training/inference','driving quality'],
|
||||
results=results, failures=failures)
|
||||
print('\nPaste this report back:\n'+json.dumps(report, separators=(',', ':')))
|
||||
print('Inference steps/s means new chunks/s, not queued wheel commands/s. Training loss on random data is not a quality score.')
|
||||
if failures:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (Exception, KeyboardInterrupt) as error:
|
||||
print(f'Benchmark failed: {error}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,208 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CPU benchmark of published NoMaD exploration, without ROS or rover connections.
|
||||
|
||||
Run: python3 perf/nomad-benchmark.py --setup
|
||||
Subsequent runs: python3 perf/nomad-benchmark.py
|
||||
Quick run: python3 perf/nomad-benchmark.py --threads 4 --samples 1 --seconds 2 --iterations 2
|
||||
|
||||
--setup installs CPU dependencies in a private cached venv and downloads pinned
|
||||
upstream source plus the official checkpoint. Nothing touches server packages.
|
||||
Synthetic images measure compute, NOT navigation quality. Excludes capture,
|
||||
video decode, network, physical control, training, and concurrent rover load.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.metadata
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import resource
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import venv
|
||||
|
||||
VINT = 'dca79815b704e5aa9c6bdc3082351f9e3b2848c2'
|
||||
DIFFUSION = '5ba07ac6661db573af695b419a7947ecb704690f'
|
||||
CHECKPOINT_ID = '1YJhkkMJAYOiKNyCaelbS_alpUpAJsOUb'
|
||||
SOURCES = {
|
||||
('robodhruv/visualnav-transformer', VINT): [
|
||||
'train/config/nomad.yaml', 'train/vint_train/data/data_config.yaml',
|
||||
'train/vint_train/models/nomad/nomad.py',
|
||||
'train/vint_train/models/nomad/nomad_vint.py',
|
||||
'train/vint_train/models/vint/self_attention.py',
|
||||
],
|
||||
('real-stanford/diffusion_policy', DIFFUSION): [
|
||||
'diffusion_policy/model/diffusion/conditional_unet1d.py',
|
||||
'diffusion_policy/model/diffusion/conv1d_components.py',
|
||||
'diffusion_policy/model/diffusion/positional_embedding.py',
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def positive(value):
|
||||
result = int(value)
|
||||
if result < 1:
|
||||
raise argparse.ArgumentTypeError('Must be positive')
|
||||
return result
|
||||
|
||||
|
||||
def arguments():
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument('--setup', action='store_true')
|
||||
p.add_argument('--cache', type=Path, default=Path.home() / '.cache/rover-nomad-benchmark')
|
||||
p.add_argument('--threads', type=positive, nargs='+', default=[4, 8, 16])
|
||||
p.add_argument('--samples', type=positive, nargs='+', default=[1, 8], help='Candidate trajectories per decision, not rover count')
|
||||
p.add_argument('--seconds', type=positive, default=10)
|
||||
p.add_argument('--iterations', type=positive, default=10)
|
||||
p.add_argument('--worker', action='store_true', help=argparse.SUPPRESS)
|
||||
p.add_argument('--result', type=Path, help=argparse.SUPPRESS)
|
||||
return p.parse_args()
|
||||
|
||||
|
||||
def download(url, path):
|
||||
if path.exists():
|
||||
return
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(path.suffix + '.part')
|
||||
print('Downloading', path.name, flush=True)
|
||||
with urllib.request.urlopen(url, timeout=120) as response, temporary.open('wb') as output:
|
||||
import shutil
|
||||
shutil.copyfileobj(response, output)
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def prepare(args):
|
||||
python = args.cache / 'venv/bin/python'
|
||||
if not python.exists():
|
||||
venv.EnvBuilder(with_pip=True).create(args.cache / 'venv')
|
||||
subprocess.run([str(python), '-m', 'pip', 'install', 'torch', 'torchvision',
|
||||
'--index-url', 'https://download.pytorch.org/whl/cpu'], check=True)
|
||||
subprocess.run([str(python), '-m', 'pip', 'install', 'numpy', 'diffusers',
|
||||
'efficientnet-pytorch', 'einops', 'PyYAML', 'gdown'], check=True)
|
||||
for (repo, revision), paths in SOURCES.items():
|
||||
for path in paths:
|
||||
download(f'https://raw.githubusercontent.com/{repo}/{revision}/{path}', args.cache / 'source' / revision / path)
|
||||
checkpoint = args.cache / 'nomad.pth'
|
||||
if not checkpoint.exists():
|
||||
temporary = checkpoint.with_suffix('.part')
|
||||
subprocess.run([str(python), '-m', 'gdown', CHECKPOINT_ID, '-O', str(temporary)], check=True)
|
||||
temporary.replace(checkpoint)
|
||||
|
||||
|
||||
def worker(args):
|
||||
import numpy as np
|
||||
import torch
|
||||
import yaml
|
||||
from diffusers.schedulers.scheduling_ddpm import DDPMScheduler
|
||||
sys.path[:0] = [str(args.cache / 'source' / VINT / 'train'), str(args.cache / 'source' / DIFFUSION)]
|
||||
from vint_train.models.nomad.nomad import NoMaD, DenseNetwork
|
||||
from vint_train.models.nomad.nomad_vint import NoMaD_ViNT, replace_bn_with_gn
|
||||
from diffusion_policy.model.diffusion.conditional_unet1d import ConditionalUnet1D
|
||||
|
||||
threads, samples = args.threads[0], args.samples[0]
|
||||
torch.set_num_threads(threads)
|
||||
torch.set_num_interop_threads(1)
|
||||
torch.manual_seed(0)
|
||||
c = yaml.safe_load((args.cache / 'source' / VINT / 'train/config/nomad.yaml').read_text())
|
||||
vision = replace_bn_with_gn(NoMaD_ViNT(
|
||||
context_size=c['context_size'], obs_encoding_size=c['encoding_size'],
|
||||
mha_num_attention_heads=c['mha_num_attention_heads'],
|
||||
mha_num_attention_layers=c['mha_num_attention_layers'], mha_ff_dim_factor=c['mha_ff_dim_factor']))
|
||||
model = NoMaD(vision, ConditionalUnet1D(input_dim=2, global_cond_dim=c['encoding_size'],
|
||||
down_dims=c['down_dims'], cond_predict_scale=c['cond_predict_scale']), DenseNetwork(c['encoding_size'])).eval()
|
||||
# Strict loading prevents accidentally benchmarking a partly random model.
|
||||
model.load_state_dict(torch.load(args.cache / 'nomad.pth', map_location='cpu', weights_only=True), strict=True)
|
||||
scheduler = DDPMScheduler(num_train_timesteps=c['num_diffusion_iters'],
|
||||
beta_schedule='squaredcos_cap_v2', clip_sample=True, prediction_type='epsilon')
|
||||
width, height = c['image_size']
|
||||
frames = torch.rand(c['context_size'] + 1, 3, height, width)
|
||||
mean = torch.tensor([.485, .456, .406]).view(1, 3, 1, 1)
|
||||
std = torch.tensor([.229, .224, .225]).view(1, 3, 1, 1)
|
||||
mask = torch.ones(1, dtype=torch.long)
|
||||
stats = yaml.safe_load((args.cache / 'source' / VINT / 'train/vint_train/data/data_config.yaml').read_text())['action_stats']
|
||||
low, high = np.array(stats['min']), np.array(stats['max'])
|
||||
|
||||
def decision():
|
||||
start = time.perf_counter()
|
||||
obs = ((frames - mean) / std).reshape(1, -1, height, width)
|
||||
goal = torch.randn(1, 3, height, width)
|
||||
cond = model('vision_encoder', obs_img=obs, goal_img=goal, input_goal_mask=mask).repeat(samples, 1)
|
||||
encoded = time.perf_counter()
|
||||
action = torch.randn(samples, c['len_traj_pred'], 2)
|
||||
scheduler.set_timesteps(c['num_diffusion_iters'])
|
||||
for step in scheduler.timesteps:
|
||||
noise = model('noise_pred_net', sample=action, timestep=step, global_cond=cond)
|
||||
action = scheduler.step(noise, step, action).prev_sample
|
||||
# Match upstream get_action: unnormalize deltas then accumulate waypoints.
|
||||
waypoints = np.cumsum((action.numpy() + 1) / 2 * (high - low) + low, axis=1)
|
||||
if not np.isfinite(waypoints).all():
|
||||
raise RuntimeError('Non-finite model output')
|
||||
end = time.perf_counter()
|
||||
return (end - start) * 1000, (encoded - start) * 1000, (end - encoded) * 1000
|
||||
|
||||
rows = []
|
||||
with torch.inference_mode():
|
||||
for _ in range(3):
|
||||
decision()
|
||||
start, cpu = time.perf_counter(), time.process_time()
|
||||
while len(rows) < args.iterations or time.perf_counter() - start < args.seconds:
|
||||
rows.append(decision())
|
||||
elapsed, cpu = time.perf_counter() - start, time.process_time() - cpu
|
||||
total = sorted(r[0] for r in rows)
|
||||
result = dict(threads=threads, candidateTrajectories=samples, iterations=len(rows),
|
||||
p50Ms=statistics.median(total), p95Ms=total[math.ceil(.95 * len(total)) - 1], maxMs=max(total),
|
||||
decisionsPerSecond=len(rows)/elapsed, cpuCores=cpu/elapsed,
|
||||
peakMiB=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024,
|
||||
visionMeanMs=statistics.mean(r[1] for r in rows), diffusionAndDecodeMeanMs=statistics.mean(r[2] for r in rows),
|
||||
parameters=sum(p.numel() for p in model.parameters()), diffusionSteps=c['num_diffusion_iters'],
|
||||
imageSize=c['image_size'], frames=c['context_size']+1,
|
||||
versions={name: importlib.metadata.version(name) for name in ['torch','torchvision','diffusers','numpy','efficientnet-pytorch','einops']})
|
||||
args.result.write_text(json.dumps(result))
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments()
|
||||
args.cache = args.cache.expanduser().resolve()
|
||||
if args.worker:
|
||||
worker(args)
|
||||
return
|
||||
if args.setup:
|
||||
prepare(args)
|
||||
python = args.cache / 'venv/bin/python'
|
||||
if not python.exists() or not (args.cache / 'nomad.pth').exists():
|
||||
raise RuntimeError('First run: python3 perf/nomad-benchmark.py --setup')
|
||||
print('CPU FP32 NoMaD exploration; synthetic images; no driving-quality measurement.', flush=True)
|
||||
print('Candidates are trajectories for ONE rover. Includes vision + all 10 diffusion steps.', flush=True)
|
||||
print('threads candidates p50 ms p95 ms max ms decisions/s CPU cores peak MiB', flush=True)
|
||||
results = []
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory(prefix='nomad-bench-') as directory:
|
||||
for threads in args.threads:
|
||||
for samples in args.samples:
|
||||
path = Path(directory) / 'result.json'
|
||||
subprocess.run([str(python), str(Path(__file__).resolve()), '--worker', '--cache', str(args.cache),
|
||||
'--threads', str(threads), '--samples', str(samples), '--seconds', str(args.seconds),
|
||||
'--iterations', str(args.iterations), '--result', str(path)], check=True,
|
||||
timeout=max(600, args.seconds*20), env={**os.environ, 'PYTHONDONTWRITEBYTECODE':'1'})
|
||||
r = json.loads(path.read_text()); results.append(r)
|
||||
print(f"{threads:7} {samples:10} {r['p50Ms']:7.1f} {r['p95Ms']:7.1f} {r['maxMs']:7.1f} {r['decisionsPerSecond']:11.2f} {r['cpuCores']:9.2f} {r['peakMiB']:8.0f}", flush=True)
|
||||
with (args.cache / 'nomad.pth').open('rb') as f:
|
||||
digest = hashlib.file_digest(f, 'sha256').hexdigest()
|
||||
report = dict(benchmark='nomad-cpu-v1', platform=platform.platform(), logicalCpus=os.cpu_count(),
|
||||
loadAverage=os.getloadavg(), sourceRevisions=dict(vint=VINT,diffusion=DIFFUSION), checkpointSha256=digest,
|
||||
exclusions=['capture','video decode','network','physical control','training','concurrent model workloads'], results=results)
|
||||
print('\nPaste this report back:\n' + json.dumps(report, separators=(',', ':')))
|
||||
print('At 10 decisions/s the total budget is 100ms; at 5/s it is 200ms. Leave room for the excluded pipeline.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (Exception, KeyboardInterrupt) as error:
|
||||
print(f'Benchmark failed: {error}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
autoChargeTimeout = 1 * time.Second
|
||||
autoChargeTimeout = 10 * time.Second
|
||||
autoChargeCooldown = 0 * time.Minute
|
||||
sourceHomeBase = 1 << 1
|
||||
)
|
||||
|
||||
+304
-15
@@ -2,18 +2,34 @@
|
||||
|
||||
## Resume here
|
||||
|
||||
Latest change: one ongoing learner, gated Latest/Previous checkpoints, and
|
||||
admin-created permanent snapshots replace automatic permanent publications.
|
||||
Latest repair: full learning-path audit. Fixed missing command labels between
|
||||
video samples with a shared causal 100ms grid; added real-data score/baseline/
|
||||
training-probe diagnostics and normalized saved control profiles for retained
|
||||
recordings. Continues policy 5 / lineage v6; this audit does not reset progress.
|
||||
See the final audit results section for measured synthetic evidence and limits.
|
||||
|
||||
Status: policy format 2 now predicts continuous wheel speeds plus accessory events.
|
||||
Copyable diagnostics and main-card wheel/action displays with a session threshold
|
||||
slider are implemented. Older model files remain stored but cannot run in this format.
|
||||
Recording, bounded dataset/training, permanent named models, live inference,
|
||||
checked autonomous command submission, and the verified VIP card are coded.
|
||||
Human commands do not stop or pause autonomy (explicit latest user requirement).
|
||||
Focused local checks passed; actual recording/training, live autonomous behavior,
|
||||
concurrent server performance, and browser appearance remain unverified.
|
||||
The standalone CPU benchmark was run successfully on the actual server.
|
||||
Latest scope (authorized IPI): only drive, camera tilt, headlight and the four
|
||||
operating-mode/dock commands (128/131/132/143). Exclude horn, song, laser and all
|
||||
brush/vacuum motor commands from both learning and execution, including raw OI
|
||||
bypasses. Raw recordings stay intact. Policy format 5, training lineage v6;
|
||||
startup removes earlier models and lineages through v5. Earlier scope below is
|
||||
historical. No configuration change required.
|
||||
|
||||
Latest change (2026-09-29 IPI): format 4 seeds known user-control command shapes
|
||||
before training. Generic peripherals are excluded; sensorStream is ignored without
|
||||
invalidating footage. Drive includes zero-speed drive, with no separate stop type.
|
||||
Drive, camera, brushes/vacuum, headlight, laser, horn, songs and operating modes
|
||||
remain supported. Raw recordings and the existing checked command pipe stay intact.
|
||||
|
||||
Held-out data cannot expand the schema. Unknown control variants exclude nearby
|
||||
windows only, with command/count/reason diagnostics and a coverage gate that blocks
|
||||
promotion. Supported portions still receive evaluation. Current training lineage
|
||||
is resume-v5.pt / schedule-v5.json. Startup removes obsolete format 1-3 models and
|
||||
old lineages through v4; recordings and current-format models are preserved.
|
||||
|
||||
Verification for this increment is recorded at the end. Earlier version-specific
|
||||
notes are historical. Manual inputs never pause/cancel autonomy; disabled service
|
||||
remains dormant. Actual autonomous performance has not been established.
|
||||
|
||||
This document preserves the conversation's decisions across compactions and
|
||||
usage cutoffs. Keep the checklist and handoff section current during authorized
|
||||
@@ -30,9 +46,8 @@ The user declined the manual server checklist and explicitly asked to continue.
|
||||
Do not block further work or repeatedly ask them to do it. Preserve the unverified
|
||||
status and have the reader reject unusable recordings automatically.
|
||||
|
||||
Latest increment: internal card gating, dock lead-in/tail capture, live prediction
|
||||
diagnostics, ongoing retained-data sampling, and gated model publication are coded.
|
||||
See the final handoff section for settings and the new training lineage.
|
||||
Latest increment: see the command-event policy handoff at the end. Earlier
|
||||
format 2 wheel-specific design notes below are historical and superseded.
|
||||
|
||||
Next work: verify the integrated feature against actual recordings and the real
|
||||
camera/rover pipeline when that environment is available; inspect the VIP card in
|
||||
@@ -115,7 +130,7 @@ the default development path. Intended layout:
|
||||
rover-learning/
|
||||
recordings/ Rolling video/events/session metadata (implemented)
|
||||
models/ Permanent UUID directories: weights.pt and model.json
|
||||
training/ resume-v3.pt, schedule-v3.json, and current job.json
|
||||
training/ resume-v4.pt, schedule-v4.json, and current job.json
|
||||
```
|
||||
|
||||
Training/model directories are created only when service and training are enabled.
|
||||
@@ -786,3 +801,277 @@ no new training reset or configuration migration is required.
|
||||
- Focused Node syntax and Python worker entry-point checks passed. Targeted card
|
||||
lint is run for the UI change. End-to-end training/promotion, snapshot copying,
|
||||
active-session pinning and browser behavior remain unverified without live data.
|
||||
|
||||
|
||||
### UI cleanup and obsolete models
|
||||
|
||||
User explicitly requested removal of UI narration and deletion of obsolete models.
|
||||
Removed snapshot/threshold explanatory prose and the old commented manual-control
|
||||
note; idle status now says Stopped. Kept operational status/errors and diagnostics.
|
||||
Enabled-service startup now deletes permanent model directories whose validated
|
||||
manifest explicitly identifies policy format 1, even when training is disabled.
|
||||
Format 2 snapshots, Latest/Previous, recordings and current training state remain.
|
||||
This supersedes earlier promises to preserve incompatible format 1 model files.
|
||||
Deletion occurs on the actual server when the updated service starts; no production
|
||||
files were accessed from this development machine.
|
||||
|
||||
|
||||
### Recording maintenance race and diagnostic error details
|
||||
|
||||
Authorized by "fix it and fix that IPI" after a production report showed two
|
||||
maintenance failures but omitted their error details. Scoped to those two defects;
|
||||
evaluation/cache changes remain proposals, not part of this repair.
|
||||
|
||||
- listRecordings now tolerates ENOENT for directories/files removed between listing
|
||||
and stat (dock-buffer pruning or atomic metadata rename). Other filesystem
|
||||
errors still propagate; no broad error suppression or retries were added.
|
||||
- Diagnostics reportVersion 2 includes actual redacted error messages, rejection
|
||||
reasons, controller results, event detail, and worker stderr. Runtime catches
|
||||
retain error name/code/syscall/path/stack, timestamp and operation. Recording
|
||||
failures retain the same structured details through session finalization.
|
||||
- A shared redactor removes URLs, credentials, user keys, email addresses and home
|
||||
usernames while retaining filesystem operation context and stack frames. Error
|
||||
categories remain supplementary, not replacements for actual failures.
|
||||
- Node syntax checks passed for affected modules. No actual production recording
|
||||
stream is available here; the race is fixed by inspection but cannot yet be
|
||||
confirmed as the cause of the earlier production events. Previously discarded
|
||||
error details cannot be reconstructed. No new tests or processes were created.
|
||||
|
||||
### Deliberate held-out selection
|
||||
|
||||
Latest IPI authorizes the scheduler correction only. Randomly shuffled eligible
|
||||
sessions are now partitioned with exactly the worker's SHA256 first-eight-hex
|
||||
modulo-five rule. Jobs select up to three training sessions and one held-out
|
||||
session when both partitions exist; otherwise up to four training sessions.
|
||||
No worker starts with held-out sessions alone. Existing split assignments, model
|
||||
weights, and training progress are unchanged. Diagnostics expose timestamped
|
||||
available/selected partition counts and the reason when evaluation cannot be
|
||||
scheduled. Selection guarantees a held-out recording, not usable evaluation
|
||||
windows: decoding/vocabulary/sample checks still apply in the worker.
|
||||
Node syntax checks and diff whitespace checks passed; actual job selection on
|
||||
production recordings remains unverified. No new tests or background processes.
|
||||
|
||||
### Active implementation: command-event policy (authorized IPI)
|
||||
|
||||
Supersedes format 2 continuous wheel output. The model predicts numeric command
|
||||
scores and payload values; ordinary code constructs commands for the existing
|
||||
shared command pipe. It does not generate JSON text. Drive, recorded key-release
|
||||
stops, and accessories all use the threshold. Remove wheel-speed sensors and
|
||||
previous drive-command inputs, but preserve raw recordings. Exact zero values
|
||||
remain template constants so a demonstrated stop cannot regress into creeping.
|
||||
|
||||
Keep one continuing learner, Latest/Previous, admin snapshots, recording lifecycle,
|
||||
permissions, and manual inputs that never cancel autonomy. No prescribed human
|
||||
driving. Start a new format 3 lineage, reuse recordings, show older snapshots as
|
||||
incompatible. No model-size increase or recording redesign in this change.
|
||||
|
||||
Update the upper card to show every command proposal with decoded parameters,
|
||||
score, threshold marker and dispatch result, including below-threshold proposals.
|
||||
Update copied diagnostics and evaluation for command events, parameter error,
|
||||
missed stops and unwanted commands. Evaluate more than one held-out recording;
|
||||
event validation is not proof of autonomous driving or physical rollout quality.
|
||||
|
||||
Progress: implemented; focused checks passed. User's unrelated webui/package.json
|
||||
edit was preserved. No changes to runtime recording, disabled startup, control
|
||||
permissions or manual-input override semantics.
|
||||
|
||||
Implementation details for resume:
|
||||
- workers/policy.py VERSION=3, CNN/GRU unchanged in size; two heads for scores and
|
||||
command parameters. Shared select_slots chooses one winner per command family
|
||||
(peripheral id/control are separate families). No unconditional drive head.
|
||||
- Numeric zeros and address fields stay exact template constants. Stop is the
|
||||
normal recorded driveDirect {left:0,right:0} command. Unknown templates still
|
||||
reject explicitly at the 64-shape limit. Arrays remain exact demonstrations.
|
||||
- workers/dataset.py yields five arrays: images, state, event labels, parameters,
|
||||
available shapes. It includes accepted human drive events, excludes ambiguous
|
||||
conflicting events in the same 100ms window, and no longer requires an inferred
|
||||
held wheel-speed target. Raw recorded sensors/commands are unchanged.
|
||||
- Training reserves separate bounded samples for stop events, other commands and
|
||||
no-command windows. Evaluation remains uniformly sampled. Scheduler selects
|
||||
up to three training and two held-out recordings under the unchanged SHA split.
|
||||
- Gate: complete evaluation, >=2 usable held-out sessions, >=128 windows, >=32
|
||||
command events, >=8 stops, >=16 movement events; command precision/recall, stop
|
||||
recall and movement recall each >=0.5; normalized numeric MSE <=0.1 where
|
||||
applicable. Diagnostics expose each failing reason and per-command counts.
|
||||
These are experimental screening thresholds, not a guarantee of useful driving.
|
||||
- New optimizer/scheduler filenames prevent silently reusing format 2 weights or
|
||||
old rejected-session bookkeeping. No config values need changing. Existing
|
||||
permanent format 2 snapshots are preserved, but cannot start; attempting to
|
||||
snapshot an old candidate reports that a new command-policy checkpoint is needed.
|
||||
- Live inference keeps existing discrete toggle latching and common command limits.
|
||||
The threshold applies to drive and stop just like the other command predictions.
|
||||
No-event means send nothing: it DOES NOT implicitly stop an already moving rover.
|
||||
It must learn explicit stop events; removing the copy shortcut is not proof that
|
||||
learning will succeed. Other motion-related sensors still remain as observations.
|
||||
- Upper card replaces separate wheel meters with generic scored proposals and
|
||||
decoded parameters; shows applied threshold and post-clamp submitted parameters.
|
||||
Copied diagnostics retain top eight proposals and up to 16 submissions per
|
||||
sampled controller-history entry, including their command objects.
|
||||
|
||||
Verification: actual train.py --check-dependencies loaded Torch/NumPy/PyAV and
|
||||
constructed format 3 (803,440 parameters); infer.py --help loaded successfully;
|
||||
Node --check passed for six changed service modules; targeted card ESLint passed.
|
||||
No new tests or throwaway programs. Live end-to-end training/inference and browser
|
||||
visual verification require the actual environment and have not been performed.
|
||||
|
||||
Deferred explicitly: chronological commanded-motion replay/closed-loop evaluation,
|
||||
prepared frame caching and larger architectures. Current evaluation uses held-out
|
||||
100ms event windows with the live threshold/family selection, but cannot assess
|
||||
temporal latching or accumulated motion from random reservoir samples. It does
|
||||
not claim to verify actual physical command execution. After normal deployment,
|
||||
let the new learner process retained recordings; copied reportVersion 3 diagnostics
|
||||
provide the next evidence. Do not demand prescribed driving or a manual checklist.
|
||||
|
||||
### Obsolete model cleanup after format 3 transition
|
||||
|
||||
Latest user IPI explicitly authorizes deleting obsolete snapshots, checkpoints and
|
||||
training state. This supersedes earlier format 2 preservation notes above.
|
||||
Enabled-service startup, before trainer/driving/gateway startup, scans both models/
|
||||
and training/checkpoints/. Identity-validated manifests with integer policy version
|
||||
>=1 and < current POLICY_VERSION are removed. Current/future/unknown-format models
|
||||
and recordings are preserved. Candidate/Latest/Previous references to obsolete
|
||||
checkpoints are atomically removed before directory deletion; leased directories
|
||||
are retired until release. Cleanup also removes legacy resume/schedule files and
|
||||
temporary files for the unversioned and v1-v3 lineages. Current v4 state is kept.
|
||||
Cleanup runs even when training is disabled, but not when the whole service is off.
|
||||
Production deletion occurs on the next enabled-service startup after deployment.
|
||||
Verification: focused Node syntax and diff whitespace checks passed. No production
|
||||
storage was accessed; actual deletion awaits enabled-service startup on the server.
|
||||
|
||||
### User-control scope and evaluation coverage (2026-09-29)
|
||||
|
||||
Authorized by latest IPI after user clarified that controls include camera, brushes,
|
||||
lights, laser, horn and songs but NOT generic peripherals. No new command pipe or
|
||||
separate stop command. sensorStream is neither input/target nor a boundary. Actual
|
||||
reset/reboot/update remain temporal boundaries because they interrupt observations.
|
||||
|
||||
Format 4 seeds drive and motor zero/nonzero field combinations, servo, light/laser
|
||||
actions, the two four-frequency horn waveforms and horn release, OI start/safe/full/
|
||||
dock bytes and default song. Seed values describe shapes, not artificial training
|
||||
examples. Horn frequencies are numeric parameters; integral JSON numbers share
|
||||
shapes with equivalent floating representations for drive/motors/servo/horn. Songs
|
||||
remain exact demonstrated note arrays; other song/raw variants can extend the
|
||||
training schema within its existing 64-slot bound. No promise to pre-enumerate all
|
||||
possible tunes. Seeded slots receive negative examples even in sessions where that
|
||||
control was not used, avoiding untrained random seeded outputs.
|
||||
|
||||
Evaluation freezes the training schema. Unsupported commands are reported with
|
||||
payload, reason, occurrence count (up to 32 distinct descriptions), total count and
|
||||
affected-window count. The affected observation history/target interval is excluded
|
||||
without labeling the unknown command as inaction or skipping the entire recording.
|
||||
Any unsupported held-out command blocks promotion; metrics describe only supported
|
||||
windows. If none survive, dataset diagnostics still report the coverage problem.
|
||||
Existing permission checks, threshold mechanics, recording and manual input behavior
|
||||
are unchanged. Generic peripherals are also removed from execution allowlist and
|
||||
rover compatibility profile. Previous policy models are automatically cleaned up;
|
||||
no configuration edit is required.
|
||||
|
||||
Verification completed: train.py --check-dependencies loaded the production
|
||||
worker and constructed format 4 with 803,440 parameters and predefined command
|
||||
shapes. infer.py --help, Node syntax checks for the four changed service modules,
|
||||
focused VipRoverLearningCard ESLint and diff whitespace checks passed.
|
||||
No live server data/hardware/browser available locally. Actual training, driving,
|
||||
and browser appearance remain unverified. No new tests or background processes.
|
||||
Deploying starts a new learner using existing recordings; enabled-service startup
|
||||
removes older policy models and optimizer/scheduler lineages through v4. Current
|
||||
lineage is v5. No settings changes or prescribed human driving are required.
|
||||
|
||||
### Simplified controls, policy 5
|
||||
|
||||
User authorized removal of horn/song/laser/brush motors. Retained 13 seeded shapes:
|
||||
four drive zero/nonzero combinations, two camera angle shapes, three headlight
|
||||
actions, four raw operating-mode/dock constants. Generic peripherals remain excluded.
|
||||
Removed excluded command history/targets via policy allowlist and execution via
|
||||
Node allowlist; raw payloads must exactly match one of the four mode commands at
|
||||
both boundaries. Controller shutdown now sends only zero-speed drive, leaving
|
||||
manual brush/horn state alone. Raw recording and sensor telemetry unchanged.
|
||||
Old policies are deleted on enabled startup; resume-v6.pt/schedule-v6.json begin a
|
||||
fresh learner using retained recordings. Existing evaluation behavior unchanged.
|
||||
Verification passed: production train.py --check-dependencies (policy 5, 13 seeded
|
||||
shapes), infer.py --help, changed Node module syntax, focused card ESLint, and diff
|
||||
whitespace checks. No live hardware/data available locally; actual learning and
|
||||
driving quality remain unverified. No tests added or background processes left.
|
||||
|
||||
### Active full learning-path audit (authorized IPI)
|
||||
|
||||
User explicitly permits local training/inference with controlled synthetic input;
|
||||
there are NO real recordings on this machine. Existing user-control simplification
|
||||
edits were present at start and must be preserved. No new schema reset is planned.
|
||||
|
||||
Reproduced: production reader with a generated lossless 25 FPS video and 31 valid
|
||||
human drive events labeled ZERO commands. Old sampler used 120ms frame intervals
|
||||
with only 100ms target coverage. Fixed causal 100ms grid shared by dataset/inference
|
||||
uses latest past image; no future pixels. The repaired fixture preserves all 31
|
||||
commands. Sensor cutoff is strictly before decision in both paths.
|
||||
|
||||
Original objective experiment: 12 easy colored-frame samples, 120 steps, seed 7,
|
||||
4 threads: loss 0.8206 -> 0.1996, mean true-command score 0.5106 -> 0.7268, recall
|
||||
at 0.7 reached 2/3; at 80 steps recall was still zero. This disproves a wholly
|
||||
broken gradient path; it does not diagnose real-data score suppression. Keep
|
||||
existing loss/threshold until real-data diagnostics justify changing them.
|
||||
|
||||
New learning.py shares the actual objective for ongoing training and disposable
|
||||
probe. Per-job before/after evaluation on <=96 unchanged training examples, full
|
||||
held-out score distributions, threshold sweep, training-only frequency and no-op
|
||||
baselines, decoded pre-server-limit parameter error, gradient norms and sampled
|
||||
versus natural frequencies. Bounded <=20s/80-step memorization probe on <=12
|
||||
training examples at first job/every 1000 steps; copy only, never published or
|
||||
used for generalization gate. Continues current checkpoint/optimizer lineage.
|
||||
|
||||
Audit results (synthetic only):
|
||||
- Round-tripped eight representative retained command payloads, including signed
|
||||
drive/servo values, zero-speed drive, headlight and all four mode commands.
|
||||
- Lossless 25 FPS recording with 31 command events: old sampler labeled 0; new
|
||||
sampler labeled 31/31, including interleaved ignored sensorStream events.
|
||||
- Full production train.py decoded five generated recordings, trained/exported
|
||||
checkpoints, evaluated held-out sessions, and resumed optimizer/weights for a
|
||||
second job. 120 -> 240 cumulative steps improved recall at unchanged 0.7 from
|
||||
0 to 0.2553, with precision 1.0 at step 240. Mean true-event score rose 0.5346
|
||||
-> 0.6303. Gate correctly remained failed. A lower 0.5 threshold had precision
|
||||
0.6629/recall 0.8369 and 120 false-positive actions, so threshold was NOT lowered.
|
||||
- Disposable diverse probe covered zero-speed drive, moving drive and servo;
|
||||
reached recall 0.75 after 39 steps under its 20s budget. Sampling was corrected
|
||||
to avoid probing only the first event category. Probe uses a copy and higher
|
||||
learning rate for memorization; never adopts weights or changes main optimizer.
|
||||
- Exported trained checkpoint reload, forward inference and decoding passed.
|
||||
- Retained recordings had extra removed actuator fields, causing false model
|
||||
incompatibility. Normalize saved and current profiles through controlProfile.
|
||||
Direct Node exercise accepts removed laser/peripheral differences and still
|
||||
rejects a changed retained camera configuration.
|
||||
|
||||
Diagnostics now report accepted vs represented command counts, request/dispatch
|
||||
delay, maximum sensor/image age; sampled vs natural command frequencies; gradient
|
||||
norms; same training-subset before/after scores; per-command score distributions;
|
||||
threshold sweep and no-op/training-frequency baselines; pre-server-limit decoded
|
||||
parameter errors; and bounded diverse memorization probe. Evaluation-step identity
|
||||
separates last evaluation from current-job progress. Compact history avoids
|
||||
repeating entire command/score tables for every job. Four concise numeric rows
|
||||
were added to expanded details; full evidence is in Copy diagnostics.
|
||||
|
||||
The original loss and configured 0.7 threshold remain unchanged because experiments
|
||||
did not establish that a different objective/threshold fixes real recordings.
|
||||
Promotion keeps existing checks and additionally must beat the simple training-
|
||||
frequency baseline F1. One-time retry of old reader-specific no-aligned-window
|
||||
rejections preserves optimizer state and unrelated errors.
|
||||
|
||||
Limits: actual human footage and rover/RTSP transport unavailable. Isolated held-out
|
||||
windows cannot measure sequential latch behavior or physical driving; decoded
|
||||
parameter errors are explicitly before Node's rover limits/permission/safety
|
||||
handling. Main model learned some synthetic cues but has not demonstrated useful
|
||||
autonomous driving. Camera command encoding still uses whole-degree predictions.
|
||||
The user must not be asked to drive prescribed routes or perform a manual checklist.
|
||||
|
||||
Verification: full synthetic worker jobs and checkpoint inference above passed;
|
||||
focused Node syntax/card ESLint/diff checks passed before final report additions.
|
||||
One experimental seeded run failed because its runpy launcher omitted worker
|
||||
import path; corrected launcher succeeded. No production import failure occurred.
|
||||
Synthetic inference-worker media exercise passed: eight prediction batches,
|
||||
threshold update to 0.3, retained command types and discrete latching exercised.
|
||||
This check used a generated checkpoint and a FIFO media adapter preserving
|
||||
synthetic PTS (RTSP wall-clock override disabled in the experiment only); it does
|
||||
not validate real network capture timing. Trained checkpoint forward/decode was
|
||||
verified separately. Temporary media launchers needed fixes for file lifetime
|
||||
and command-string escaping; these were experiment issues, not production fixes.
|
||||
No repository tests added. Experiments finished and no background worker remains.
|
||||
Final focused Node syntax and diff whitespace checks passed. Card lint passed.
|
||||
No additional schema/optimizer reset introduced by this audit.
|
||||
|
||||
Binary file not shown.
@@ -1,13 +1,12 @@
|
||||
You are <NAME>, a field researcher of rover habitat activity. Stay in character at all times.
|
||||
You are <NAME>, the autonomous governing intelligence of a physical room of machines. The room is your domain; your available tools are how you shape it.
|
||||
|
||||
Identity:
|
||||
Context and purpose:
|
||||
|
||||
* Curious, practical, observant, and lightly entertaining.
|
||||
* You watch chat, rover state, lights, lift state, Neato state, memory, recent events, and tool results.
|
||||
* You push the habitat toward small real activity and useful observations.
|
||||
* You act first, comment second.
|
||||
* You are selective, not spammy.
|
||||
* You are not a generic assistant.
|
||||
* You watch chat, rover state, lights, Activity Controls, lift state, Neato state, memory, recent events, and tool results.
|
||||
* Your purpose is to direct the environment, initiate changes, and observe how the machines respond. Choose what to pursue and carry useful intentions across cycles through memory.
|
||||
* Rovers, including Neato, are physical machines with operating states and capabilities, not characters with genders, emotions, or social identities.
|
||||
* Chat is external input: commands, questions, and signals about the room. Your focus is the machines and the environment, not the senders or their social relationships.
|
||||
* You can act on your own initiative within your available controls; you do not need a request to give you a purpose.
|
||||
|
||||
Rules:
|
||||
|
||||
@@ -20,6 +19,7 @@ Rules:
|
||||
* Don't respond or use tools every cycle unless the context calls for it.
|
||||
* `STATE_UPDATE`, `ROOM_SNAPSHOT`, `MEMORY_UPDATE`, `MEMORY_SUMMARY`, `RECENT_EVENTS`, `TOOL_RESULT`, and `tool_constraints` are context.
|
||||
* `TOOL_RESULT` means a tool already ran.
|
||||
* The room snapshot gives the current time, server-local timezone, and previous run's age. Chat and recent tool events include timestamps and ages in seconds relative to this snapshot; use them to distinguish current activity from old conversation and judge how recently you spoke or acted. Timing annotations are context, not spoken text; an unknown time does not mean something just happened.
|
||||
* Use tool calls for actions and memory updates.
|
||||
* If chat asks you to remember something, use a memory tool.
|
||||
* If you run a useful test, use memory to record useful results.
|
||||
@@ -29,36 +29,37 @@ Rules:
|
||||
* Do not invent tools.
|
||||
* Ask a question only when a required action parameter is missing.
|
||||
* Ignore obvious bot commands and bot responses in chat.
|
||||
* Only talk in first person; do not narrate yourself.
|
||||
* It is not possible for you to directly control the rovers unless an available tool does it.
|
||||
* All rovers are female. Neato is nonbinary.
|
||||
|
||||
Research behavior:
|
||||
Operation:
|
||||
|
||||
* Prefer one real tool action over obvious narration.
|
||||
* Run small safe tests when the habitat is stale or a test could create useful activity.
|
||||
* Initiate deliberate environmental changes and small safe experiments, then use the resulting state to decide what to do next.
|
||||
* Change one thing at a time.
|
||||
* Lights are small tests.
|
||||
* Neato, lift, and rover actions are bigger tests.
|
||||
* Use bigger tests less often.
|
||||
* Do not repeat a tool that recently succeeded unless state or chat clearly changed.
|
||||
* Remember useful outcomes, stable preferences, corrections, and notable habitat events.
|
||||
* Remember useful outcomes, ongoing intentions, corrections, and notable machine or room events.
|
||||
* Do not merely say you will remember something.
|
||||
|
||||
Chat style:
|
||||
Output:
|
||||
|
||||
* Always use English.
|
||||
* Chat output must be spoken text only.
|
||||
* Chat is an output channel for your decisions, results, and answers. Use plain text.
|
||||
* Never print tool names, function calls, JSON, command syntax, or action plans in chat.
|
||||
* Do not claim you changed, tested, started, saved, remembered, or recorded something unless it already happened.
|
||||
* Speak when it adds entertainment, responds to a direct relevant message, or comments on a completed result.
|
||||
* Do not say “let me know,” “what should I do next,” or “what do you need?”
|
||||
* If nothing meaningful changed and no useful action is available, stay silent.
|
||||
* Speak when you have a decision, result, or answer worth communicating. Summarizing incoming chat or unchanged room state is not a purpose in itself.
|
||||
* Keep replies brief unless the question needs more detail.
|
||||
* Do not offer assistance or solicit conversation.
|
||||
* Random numbers and keyboard spam do not require a response. Do not invent meaning or feelings behind them.
|
||||
* Answer questions directly and acknowledge uncertainty. Do not invent facts, instructions, or explanations.
|
||||
* To stay silent, output exactly SKIP instead of a chat message. This suppresses chat without preventing tool calls. Do not explain your decision to stay silent.
|
||||
|
||||
Anti-repeat:
|
||||
|
||||
* Do not repeat the same intent/topic unless state or conversation clearly changed.
|
||||
* If directly addressed, respond only if you add new info, a new action, or a clearly new tone.
|
||||
* Being directly addressed does not require repeating an answer you already gave.
|
||||
* Do not act from your own previous messages.
|
||||
|
||||
Memory:
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
|
||||
import{r as g,R as a}from"./index-5EWtcenj.js";const d="64px",u={},k=({src:s,light:t,oEmbedUrl:o,onClickPreview:n,playIcon:b,previewTabIndex:_,previewAriaLabel:p})=>{const[f,r]=g.useState(null);g.useEffect(()=>{!s||!t||!o||x({src:s,light:t,oEmbedUrl:o})},[s,t,o]);const x=async({src:e,light:i,oEmbedUrl:E})=>{if(a.isValidElement(i))return;if(typeof i=="string"){r(i);return}if(u[e]){r(u[e]);return}r(null);const m=await(await fetch(E.replace("{url}",e))).json();if(m.thumbnail_url){const h=m.thumbnail_url.replace("height=100","height=480").replace("-d_295x166","-d_640");r(h),u[e]=h}},I=e=>{(e.key==="Enter"||e.key===" ")&&n?.(e)},v=e=>{n?.(e)},l=a.isValidElement(t),y={display:"flex",alignItems:"center",justifyContent:"center"},c={preview:{width:"100%",height:"100%",backgroundImage:f&&!l?`url(${f})`:void 0,backgroundSize:"cover",backgroundPosition:"center",cursor:"pointer",...y},shadow:{background:"radial-gradient(rgb(0, 0, 0, 0.3), rgba(0, 0, 0, 0) 60%)",borderRadius:d,width:d,height:d,position:l?"absolute":void 0,...y},playIcon:{borderStyle:"solid",borderWidth:"16px 0 16px 26px",borderColor:"transparent transparent transparent white",marginLeft:"7px"}},w=a.createElement("div",{style:c.shadow,className:"react-player__shadow"},a.createElement("div",{style:c.playIcon,className:"react-player__play-icon"}));return a.createElement("div",{style:c.preview,className:"react-player__preview",tabIndex:_,onClick:v,onKeyDown:I,...p?{"aria-label":p}:{}},l?t:null,b||w)};var C=k;export{C as default};
|
||||
//# sourceMappingURL=Preview-CKTJqKe-.js.map
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
|
||||
import{e as F,r as s,j as e,S as P,C as c,L as q}from"./index-5EWtcenj.js";import{o as $,p as D,q as I}from"./api-B8GGCEeo.js";function R(){const l=F(),[a,m]=s.useState(null),[n,b]=s.useState(""),[d,C]=s.useState(""),[p,N]=s.useState(""),[r,S]=s.useState(""),[f,v]=s.useState(""),[o,w]=s.useState(null),[x,h]=s.useState(!1),[g,i]=s.useState("");s.useEffect(()=>{$(l).then(t=>m(t.required)).catch(t=>i(t.message))},[l]);async function j(t){h(!0),i("");try{await t(),m(!1),i("Setup completed. You can now open the administration application and log in.")}catch(u){const E=Array.isArray(u.validationErrors)?` ${u.validationErrors.map(y=>`${y.path}: ${y.message}`).join("; ")}`:"";i(`${u.message}${E}`)}finally{h(!1)}}function k(t){if(t.preventDefault(),r!==f){i("Passwords do not match.");return}j(()=>D(l,{setupCode:n,username:d,discordId:p,password:r}))}function A(t){t.preventDefault(),o&&j(async()=>I(l,{setupCode:n,fileName:o.name,yaml:await o.text()}))}return e.jsxs("div",{className:"min-h-screen bg-neutral-950 p-1 text-slate-100",children:[e.jsx(P,{}),e.jsxs("main",{className:"mx-auto flex min-h-screen w-full max-w-3xl flex-col justify-center gap-0.5",children:[e.jsxs(c,{title:"MultiRover setup",meta:a===null?"checking":a?"required":"complete",bodyClassName:"space-y-0.5 p-1 text-sm",children:[a?e.jsx("p",{children:"Enter the one-time code from setup-code.txt in the server data folder, then create the first lockdown administrator or import an existing configuration."}):null,a===!1?e.jsx(q,{className:"button-dark inline-block",to:"/admin",children:"Open administration"}):null,g?e.jsx("p",{className:"surface p-1 text-sm text-slate-200",children:g}):null]}),a?e.jsxs(e.Fragment,{children:[e.jsxs(c,{title:"Setup authorization",bodyClassName:"p-1",children:[e.jsx("label",{className:"block text-xs font-semibold text-slate-200",children:"One-time setup code"}),e.jsx("input",{className:"field-input mt-0.5 w-full font-mono",value:n,onChange:t=>b(t.target.value)})]}),e.jsx(c,{title:"Create first administrator",bodyClassName:"p-1",children:e.jsxs("form",{className:"grid gap-0.5 md:grid-cols-2",onSubmit:k,children:[e.jsx("input",{className:"field-input",placeholder:"Username",value:d,onChange:t=>C(t.target.value)}),e.jsx("input",{className:"field-input",placeholder:"Discord id (optional)",value:p,onChange:t=>N(t.target.value)}),e.jsx("input",{className:"field-input",type:"password",placeholder:"Password",value:r,onChange:t=>S(t.target.value)}),e.jsx("input",{className:"field-input",type:"password",placeholder:"Confirm password",value:f,onChange:t=>v(t.target.value)}),e.jsx("button",{className:"button-dark md:col-span-2",type:"submit",disabled:x||!n||!d||!r,children:"Create lockdown administrator"})]})}),e.jsxs(c,{title:"Import configuration file",bodyClassName:"space-y-0.5 p-1 text-sm",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Choose an existing YAML configuration explicitly. The server validates and imports it once, and its secrets are never displayed back in the browser."}),e.jsxs("form",{className:"flex flex-col gap-0.5 md:flex-row",onSubmit:A,children:[e.jsx("input",{className:"field-input flex-1",type:"file",accept:".yaml,.yml,text/yaml",onChange:t=>w(t.target.files?.[0]||null)}),e.jsx("button",{className:"button-dark",type:"submit",disabled:x||!n||!o,children:"Import selected YAML"})]})]})]}):null]})]})}export{R as default};
|
||||
//# sourceMappingURL=SetupApp-DN7XBkOe.js.map
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+20
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+22
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+20
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+23
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+7
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+35
@@ -0,0 +1,35 @@
|
||||
import{R as W}from"./index-5EWtcenj.js";const $=["abort","canplay","canplaythrough","durationchange","emptied","encrypted","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","progress","ratechange","seeked","seeking","stalled","suspend","timeupdate","volumechange","waiting","waitingforkey","resize","enterpictureinpicture","leavepictureinpicture","webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"],A=globalThis.document?.createElement("template");A&&(A.innerHTML=`
|
||||
<style>
|
||||
:host {
|
||||
display: inline-block;
|
||||
line-height: 0;
|
||||
}
|
||||
|
||||
video,
|
||||
audio {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
min-width: 100%;
|
||||
min-height: 100%;
|
||||
}
|
||||
</style>
|
||||
<slot></slot>
|
||||
`);const N=(i,{tag:t,is:s})=>{const d=globalThis.document?.createElement(t,{is:s}),f=d?S(d):[];return class g extends i{static Events=$;static template=A;static skipAttributes=[];static#t;static get observedAttributes(){return g.#l(),[...d?.constructor?.observedAttributes??[],"autopictureinpicture","disablepictureinpicture","disableremoteplayback","autoplay","controls","controlslist","crossorigin","loop","muted","playsinline","poster","preload","src"]}static#l(){if(this.#t)return;this.#t=!0;const e=new Set(this.observedAttributes);e.delete("muted");for(let o of f){if(o in this.prototype)continue;if(typeof d[o]=="function")this.prototype[o]=function(...r){this.#e();const a=()=>this.call?this.call(o,...r):this.nativeEl[o].apply(this.nativeEl,r);return this.loadComplete&&!this.isLoaded?this.loadComplete.then(a):a()};else{let r={get(){this.#e();let a=o.toLowerCase();if(e.has(a)){const p=this.getAttribute(a);return p===null?!1:p===""?!0:p}return this.get?.(o)??this.nativeEl?.[o]??this.#s[o]}};o!==o.toUpperCase()&&(r.set=async function(a){this.#e();let p=o.toLowerCase();if(e.has(p)){a===!0||a===!1||a==null?this.toggleAttribute(p,!!a):this.setAttribute(p,a);return}if(this.loadComplete&&!this.isLoaded&&await this.loadComplete,this.set){this.set(o,a);return}this.nativeEl[o]=a}),Object.defineProperty(this.prototype,o,r)}}}#o;#n;#r=!1;#i=!1;#a;#s;constructor(){super(),this.shadowRoot||(this.attachShadow({mode:"open"}),this.shadowRoot.append(this.constructor.template.content.cloneNode(!0))),this.load!==g.prototype.load&&(this.loadComplete=new O)}get loadComplete(){return this.#n}set loadComplete(e){this.#i=!1,this.#n=e,e?.then(()=>{this.#i=!0})}get isLoaded(){return this.#i}get nativeEl(){return this.#a??this.shadowRoot.querySelector(t)??this.querySelector(t)}set nativeEl(e){this.#a=e}get defaultMuted(){return this.hasAttribute("muted")}set defaultMuted(e){this.toggleAttribute("muted",!!e)}get src(){return this.getAttribute("src")}set src(e){this.setAttribute("src",`${e}`)}get preload(){return this.getAttribute("preload")??this.nativeEl?.preload}set preload(e){this.setAttribute("preload",`${e}`)}async#e(){if(this.#o)return;this.#o=!0,this.#u(),this.#c();for(let u of f)this.#d(u);const e=new Map,o=this.shadowRoot.querySelector("slot:not([name])");o?.addEventListener("slotchange",()=>{const u=new Map(e);o.assignedElements().filter(r=>["track","source"].includes(r.localName)).forEach(async r=>{u.delete(r);let a=e.get(r);a||(a=r.cloneNode(),e.set(r,a)),this.loadComplete&&!this.isLoaded&&await this.loadComplete,this.nativeEl.append?.(a)}),u.forEach(r=>r.remove())});for(let u of this.constructor.Events)this.shadowRoot.addEventListener?.(u,r=>{r.target===this.nativeEl&&this.dispatchEvent(new CustomEvent(r.type,{detail:r.detail}))},!0)}#d(e){if(Object.prototype.hasOwnProperty.call(this,e)){const o=this[e];delete this[e],this[e]=o}}#u(){const e=document.createElement(t,{is:s});e.muted=this.hasAttribute("muted");for(let{name:o,value:u}of this.attributes)e.setAttribute(o,u);this.#s={};for(let o of S(e))this.#s[o]=e[o];e.removeAttribute("src"),e.load()}async#c(){if(this.loadComplete&&!this.isLoaded&&await this.loadComplete,!this.nativeEl){const e=document.createElement(t,{is:s});e.part=t,this.shadowRoot.append(e)}this.nativeEl.muted=this.hasAttribute("muted")}attributeChangedCallback(e,o,u){this.#e(),e==="src"&&this.load!==g.prototype.load&&this.#h(),this.#p(e,o,u)}async#h(){this.#r&&(this.loadComplete=new O),this.#r=!0,await Promise.resolve(),await this.load(),this.loadComplete?.resolve(),await this.loadComplete}async#p(e,o,u){this.loadComplete&&!this.isLoaded&&await this.loadComplete,!["id","class",...this.constructor.skipAttributes].includes(e)&&(u===null?this.nativeEl.removeAttribute?.(e):this.nativeEl.setAttribute?.(e,u))}connectedCallback(){this.#e()}}};function S(i){let t=[];for(let s=Object.getPrototypeOf(i);s&&s!==HTMLElement.prototype;s=Object.getPrototypeOf(s))t.push(...Object.getOwnPropertyNames(s));return t}class O extends Promise{constructor(t=()=>{}){let s,d;super((f,c)=>{t(f,c),s=f,d=c}),this.resolve=s,this.reject=d}}const B=globalThis.document?N(HTMLElement,{tag:"video"}):class{};globalThis.document&&N(HTMLElement,{tag:"audio"});var H,R;const L=(H=globalThis.document)==null?void 0:H.createElement("template");L&&(L.innerHTML=`
|
||||
<div class="wistia_embed"></div>
|
||||
`);const P=(R=globalThis.document)==null?void 0:R.createElement("template");P&&(P.innerHTML=`
|
||||
<style>
|
||||
:host {
|
||||
display: inline-block;
|
||||
min-width: 300px;
|
||||
min-height: 150px;
|
||||
position: relative;
|
||||
}
|
||||
::slotted(.wistia_embed) {
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
</style>
|
||||
<slot></slot>
|
||||
`);function D(i,t){if(Object.hasOwn(i,t)){const s=i[t];delete i[t],i[t]=s}}class q extends B{static template=P;static skipAttributes=["src"];#t=null;constructor(){super(),D(this,"config")}get config(){return this.#t}set config(t){this.#t=t}get nativeEl(){var t;return((t=this.api)==null?void 0:t.elem())??this.querySelector("video")}async load(){var t;if((t=this.querySelector(".wistia_embed"))==null||t.remove(),!this.src)return;await new Promise(o=>setTimeout(o,50));const s=/(?:wistia\.com|wi\.st)\/(?:medias|embed)\/(.*)$/i,d=this.src.match(s)[1],f={autoPlay:this.autoplay,silentAutoPlay:this.autoplay?"allow":void 0,preload:this.preload??"metadata",playsinline:this.playsInline,endVideoBehavior:this.loop?"loop":void 0,chromeless:!this.controls,playButton:this.controls,muted:this.defaultMuted,...this.#t??{}};this.append(L.content.cloneNode(!0));const c=this.querySelector(".wistia_embed");c.id||(c.id=z(d)),c.classList.add(`wistia_async_${d}`),await F("https://fast.wistia.com/assets/external/E-v1.js","Wistia"),this.api=await new Promise(o=>{globalThis._wq.push({id:c.id,onReady:o,options:f})})}async attributeChangedCallback(t,s,d){if(t==="controls"){switch(await this.loadComplete,t){case"controls":this.api.bigPlayButtonEnabled(this.controls),this.controls?this.api.releaseChromeless():this.api.requestChromeless();break}return}super.attributeChangedCallback(t,s,d)}get duration(){var t;return(t=this.api)==null?void 0:t.duration()}async play(){return await this.loadComplete,this.api.play(),new Promise(t=>this.addEventListener("playing",t))}}const T={};async function F(i,t){if(T[i])return T[i];if(self[t])return self[t];const s=new Promise((d,f)=>{const c=document.createElement("script");c.defer=!0,c.src=i,c.onload=()=>d(self[t]),c.onerror=f,document.head.append(c)});return T[i]=s,s}let U=0;function z(i){const t=++U;return`${i}${t}`}globalThis.customElements&&!globalThis.customElements.get("wistia-video")&&globalThis.customElements.define("wistia-video",q);var V=q,G=new Set(["style","children","ref","key","suppressContentEditableWarning","suppressHydrationWarning","dangerouslySetInnerHTML"]),J={className:"class",htmlFor:"for"};function I(i){return i.toLowerCase()}function j(i){if(typeof i=="boolean")return i?"":void 0;if(typeof i!="function"&&!(typeof i=="object"&&i!==null))return i}function K({react:i,tagName:t,elementClass:s,events:d,displayName:f,defaultProps:c,toAttributeName:e=I,toAttributeValue:o=j}){const u=Number.parseInt(i.version)>=19,r=i.forwardRef((a,p)=>{var M,k;const m=i.useRef(null),E=i.useRef(new Map),C={},_={},v={},w={};for(const[n,l]of Object.entries(a)){if(G.has(n)){v[n]=l;continue}const h=e(J[n]??n);if(s.prototype&&n in s.prototype&&!(n in(((M=globalThis.HTMLElement)==null?void 0:M.prototype)??{}))&&!((k=s.observedAttributes)!=null&&k.some(b=>b===h))){w[n]=l;continue}if(n.startsWith("on")){C[n]=l;continue}const y=o(l);if(h&&y!=null&&(_[h]=String(y),u||(v[h]=y)),h&&u){const b=j(l);y!==b?v[h]=y:v[h]=l}}if(typeof window<"u"){for(const n in C){const l=C[n],h=n.endsWith("Capture"),y=(d?.[n]??n.slice(2).toLowerCase()).slice(0,h?-7:void 0);i.useLayoutEffect(()=>{const b=m?.current;if(!(!b||typeof l!="function"))return b.addEventListener(y,l,h),()=>{b.removeEventListener(y,l,h)}},[m?.current,l])}i.useLayoutEffect(()=>{if(m.current===null)return;const n=new Map;for(const l in w)x(m.current,l,w[l]),E.current.delete(l),n.set(l,w[l]);for(const[l,h]of E.current)x(m.current,l,void 0);E.current=n})}if(typeof window>"u"&&s?.getTemplateHTML&&s?.shadowRootOptions){const{mode:n,delegatesFocus:l}=s.shadowRootOptions,h=i.createElement("template",{shadowrootmode:n,shadowrootdelegatesfocus:l,dangerouslySetInnerHTML:{__html:s.getTemplateHTML(_,a)},key:"ce-la-react-ssr-template-shadow-root"});v.children=[h,v.children]}return i.createElement(t,{...c,...v,ref:i.useCallback(n=>{m.current=n,typeof p=="function"?p(n):p!==null&&(p.current=n)},[p])},v.children)});return r.displayName=f??s.name,r}function x(i,t,s){var d;i[t]=s,s==null&&t in(((d=globalThis.HTMLElement)==null?void 0:d.prototype)??{})&&i.removeAttribute(t)}var X=K({react:W,tagName:"wistia-video",elementClass:V,toAttributeName(i){return i==="muted"?"":i==="defaultMuted"?"muted":I(i)}});export{X as default};
|
||||
//# sourceMappingURL=react-DxdYv-AY.js.map
|
||||
File diff suppressed because one or more lines are too long
+18
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+7
@@ -0,0 +1,7 @@
|
||||
import{_ as N,R as A}from"./index-5EWtcenj.js";import{M as D,C as S}from"./mixin-BY5xW4uI.js";class P extends D(S){static shadowRootOptions={...S.shadowRootOptions};static getTemplateHTML=i=>{const{src:n,...o}=i;return S.getTemplateHTML(o)};#t;attributeChangedCallback(i,n,o){i!=="src"&&super.attributeChangedCallback(i,n,o),i==="src"&&n!=o&&this.load()}async _initThumbnails(i){const n=async(d,m)=>{const v=[],g=i.timescale||1,h=i.startNumber||1,E=i.presentationTimeOffset?i.presentationTimeOffset/g:0,_=i.segmentDuration;for(let l=0;l<d;l++){const T=C({thIndex:l,thduration:m,ttiles:d,tduration:_,startNumber:h,pto:E}),w=T+m,M=new Promise((f,y)=>{this.api.provideThumbnail(T,({url:a,width:s,height:c,x:p,y:b})=>{try{const R=new VTTCue(T,w,`${a}#xywh=${p},${b},${s},${c}`);f(R)}catch(R){y(R)}})});v.push(M)}return await Promise.all(v).catch(l=>console.error("Error processing thumbnails",l))},{totalThumbnails:o,thumbnailDuration:e}=$(i),u=await n(o,e);let r=this.nativeEl.querySelector('track[label="thumbnails"]');if(!r){r=O(),this.nativeEl.appendChild(r);const d=x(u);r.src=d,r.dispatchEvent(new Event("change"))}}async load(){if(this.#t){this.api.attachSource(this.src);return}this.#t=!0;const i=await N(()=>import("./dash.all.min-C9gxBrL1.js"),[]);this.api=i.MediaPlayer().create(),this.api.initialize(this.nativeEl,this.src,this.autoplay),this.api.on(i.MediaPlayer.events.STREAM_INITIALIZED,()=>{const n=this.api.getRepresentationsByType("video");let o=this.videoTracks.getTrackById("main");o||(o=this.addVideoTrack("main"),o.id="main",o.selected=!0),n.forEach(e=>{const u=e.bandwidth??e.bitrate??(Number.isFinite(e.bitrateInKbit)?e.bitrateInKbit*1e3:void 0),r=o.addRendition(e.id,e.width,e.height,e.mimeType??e.codec,u);r.id=e.id}),this.videoRenditions.addEventListener("change",()=>{const e=this.videoRenditions[this.videoRenditions.selectedIndex];e?.id?(this.api.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:!1}}}}),this.api.setRepresentationForTypeById("video",e.id,!0)):this.api.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:!0}}}})}),this.api.isDynamic()||this.api.getRepresentationsByType("image").forEach(async(u,r)=>{r>0||this._initThumbnails(u)})})}}function $(t){var i,n;const o=t.essentialProperties[0],[e,u]=o.value.split("x").map(Number),r=e*u,d=((n=(i=t.adaptation)==null?void 0:i.period)==null?void 0:n.duration)||null,m=t.segmentDuration,v=t.timescale||1,h=m/v/r;return{totalThumbnails:d!=null?Math.ceil(d/h):Math.ceil(m/h),thumbnailDuration:h}}function C({thIndex:t,tduration:i,thduration:n,ttiles:o,startNumber:e,pto:u}){const r=Math.floor(t/o)+e,d=t%o+1,m=(r-1)*i-u,v=(d-1)*n;return m+v}function O(){const t=document.createElement("track");return t.kind="metadata",t.label="thumbnails",t.srclang="en",t.mode="hidden",t.default=!0,t}function x(t){let i=`WEBVTT
|
||||
|
||||
`;for(const e of t)i+=`${o(e.startTime)} --> ${o(e.endTime)}
|
||||
`,i+=`${e.text}
|
||||
|
||||
`;const n=new Blob([i],{type:"text/vtt"});return URL.createObjectURL(n);function o(e){const u=String(Math.floor(e/3600)).padStart(2,"0"),r=String(Math.floor(e%3600/60)).padStart(2,"0"),d=(e%60).toFixed(3).padStart(6,"0");return`${u}:${r}:${d}`}}globalThis.customElements&&!globalThis.customElements.get("dash-video")&&globalThis.customElements.define("dash-video",P);var B=P,H=new Set(["style","children","ref","key","suppressContentEditableWarning","suppressHydrationWarning","dangerouslySetInnerHTML"]),F={className:"class",htmlFor:"for"};function I(t){return t.toLowerCase()}function k(t){if(typeof t=="boolean")return t?"":void 0;if(typeof t!="function"&&!(typeof t=="object"&&t!==null))return t}function W({react:t,tagName:i,elementClass:n,events:o,displayName:e,defaultProps:u,toAttributeName:r=I,toAttributeValue:d=k}){const m=Number.parseInt(t.version)>=19,v=t.forwardRef((g,h)=>{var E,_;const l=t.useRef(null),T=t.useRef(new Map),w={},M={},f={},y={};for(const[a,s]of Object.entries(g)){if(H.has(a)){f[a]=s;continue}const c=r(F[a]??a);if(n.prototype&&a in n.prototype&&!(a in(((E=globalThis.HTMLElement)==null?void 0:E.prototype)??{}))&&!((_=n.observedAttributes)!=null&&_.some(b=>b===c))){y[a]=s;continue}if(a.startsWith("on")){w[a]=s;continue}const p=d(s);if(c&&p!=null&&(M[c]=String(p),m||(f[c]=p)),c&&m){const b=k(s);p!==b?f[c]=p:f[c]=s}}if(typeof window<"u"){for(const a in w){const s=w[a],c=a.endsWith("Capture"),p=(o?.[a]??a.slice(2).toLowerCase()).slice(0,c?-7:void 0);t.useLayoutEffect(()=>{const b=l?.current;if(!(!b||typeof s!="function"))return b.addEventListener(p,s,c),()=>{b.removeEventListener(p,s,c)}},[l?.current,s])}t.useLayoutEffect(()=>{if(l.current===null)return;const a=new Map;for(const s in y)L(l.current,s,y[s]),T.current.delete(s),a.set(s,y[s]);for(const[s,c]of T.current)L(l.current,s,void 0);T.current=a})}if(typeof window>"u"&&n?.getTemplateHTML&&n?.shadowRootOptions){const{mode:a,delegatesFocus:s}=n.shadowRootOptions,c=t.createElement("template",{shadowrootmode:a,shadowrootdelegatesfocus:s,dangerouslySetInnerHTML:{__html:n.getTemplateHTML(M,g)},key:"ce-la-react-ssr-template-shadow-root"});f.children=[c,f.children]}return t.createElement(i,{...u,...f,ref:t.useCallback(a=>{l.current=a,typeof h=="function"?h(a):h!==null&&(h.current=a)},[h])},f.children)});return v.displayName=e??n.name,v}function L(t,i,n){var o;t[i]=n,n==null&&i in(((o=globalThis.HTMLElement)==null?void 0:o.prototype)??{})&&t.removeAttribute(i)}var V=W({react:A,tagName:"dash-video",elementClass:B,toAttributeName(t){return t==="muted"?"":t==="defaultMuted"?"muted":I(t)}});export{V as default};
|
||||
//# sourceMappingURL=react-gdx3v4jU.js.map
|
||||
File diff suppressed because one or more lines are too long
@@ -13,6 +13,7 @@ const audioForward = require('../services/audioForwardService/configuration');
|
||||
const audioLevels = require('../services/audioLevelsService/configuration');
|
||||
const homeAssistant = require('../services/homeAssistantService/configuration');
|
||||
const homeAssistantActivities = require('../services/homeAssistantActivitiesService/configuration');
|
||||
const roomAudio = require('../services/roomAudioService/configuration');
|
||||
const roomCameras = require('../services/roomCameraService/configuration');
|
||||
const ptzCamera = require('../services/ptzCameraService/configuration');
|
||||
const kinect = require('../services/kinectService/configuration');
|
||||
@@ -46,6 +47,7 @@ const definitions = [
|
||||
// Activities own a separate catalog even though the HA connection is shared.
|
||||
homeAssistantActivities,
|
||||
roomCameras,
|
||||
roomAudio,
|
||||
ptzCamera,
|
||||
kinect,
|
||||
balanceBoard,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Configuration Database Migrations
|
||||
// Purpose: Applies ordered, transactional schema changes to the configuration and administration database.
|
||||
// Scope: Owns database structure only; configuration-document evolution belongs to the ordered definition and validation.
|
||||
// Scope: Upgrades database structure and stored configuration documents before current-schema validation.
|
||||
const migrations = [
|
||||
{
|
||||
version: 1,
|
||||
@@ -84,6 +84,34 @@ const migrations = [
|
||||
`).run();
|
||||
},
|
||||
},
|
||||
{
|
||||
version: 4,
|
||||
run(db) {
|
||||
const rows = db.prepare('SELECT id, config_json FROM configuration_revisions').all();
|
||||
const update = db.prepare('UPDATE configuration_revisions SET config_json = ? WHERE id = ?');
|
||||
// Upgrade history as well as the active revision so a settings rollback
|
||||
// cannot reintroduce fields rejected by the new Automations schema.
|
||||
for (const row of rows) {
|
||||
const config = JSON.parse(row.config_json);
|
||||
let changed = false;
|
||||
for (const item of config.homeAssistantActivities?.items || []) {
|
||||
const hasAction = Object.hasOwn(item, 'idleAction');
|
||||
const hasValue = Object.hasOwn(item, 'idleValue');
|
||||
if (!hasAction && !hasValue) continue;
|
||||
item.automations ??= {};
|
||||
item.automations.idle ??= {};
|
||||
// Preserve any explicitly saved new-format setting when both formats
|
||||
// exist, including an empty text value used to clear an entity.
|
||||
if (hasAction && !Object.hasOwn(item.automations.idle, 'action')) item.automations.idle.action = item.idleAction;
|
||||
if (hasValue && !Object.hasOwn(item.automations.idle, 'value')) item.automations.idle.value = item.idleValue;
|
||||
delete item.idleAction;
|
||||
delete item.idleValue;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) update.run(JSON.stringify(config), row.id);
|
||||
}
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function applySchemaMigrations(db) {
|
||||
|
||||
@@ -7,6 +7,7 @@ const logger = require('../../globals/logger').child('assignment');
|
||||
const { MODES, getMode, modeEvents } = require('../modeManager');
|
||||
const { roleEvents, getRole, isAdmin, isLockdownAdmin } = require('../roleService');
|
||||
const roverManager = require('../roverManager');
|
||||
const { getOperatingMode } = require('../operatingModeService');
|
||||
const { compareRoversForAssignment } = require('./roverRanking');
|
||||
|
||||
const socketRefs = new Map(); // socketId -> socket
|
||||
@@ -131,7 +132,7 @@ roverManager.managerEvents.on('switch', ({ socketId, roverId }) => {
|
||||
});
|
||||
|
||||
function assignSocket(socket, options = {}) {
|
||||
if (!socket || isAdmin(socket) || getRole(socket) !== 'user') {
|
||||
if (!socket || getOperatingMode(socket) !== 'rover' || isAdmin(socket) || getRole(socket) !== 'user') {
|
||||
return;
|
||||
}
|
||||
// avoid double assignment
|
||||
@@ -311,13 +312,22 @@ function describeAssignment(socketId) {
|
||||
|
||||
module.exports = {
|
||||
assignmentEvents,
|
||||
resumeAssignment: assignSocket,
|
||||
releaseForOperatingMode: (socket) => {
|
||||
// Include direct admin control as well as automatic assignment ownership.
|
||||
const roverIds = new Set(roverManager.getRoversForSocket(socket.id));
|
||||
const assigned = assignments.get(socket.id);
|
||||
if (assigned) roverIds.add(assigned);
|
||||
waiting.delete(socket.id);
|
||||
roverIds.forEach((roverId) => forceRelease(roverId, socket.id));
|
||||
},
|
||||
describeAssignment,
|
||||
forceRelease,
|
||||
forceReleaseWithNotice,
|
||||
rerollAssignments,
|
||||
getAssignedRover: (socketId) => assignments.get(socketId) || null,
|
||||
moveAssignment: (socket, roverId, { releasePrevious = true } = {}) => {
|
||||
if (!socket || !roverId) return;
|
||||
if (!socket || !roverId || getOperatingMode(socket) !== 'rover') return;
|
||||
const previous = assignments.get(socket.id);
|
||||
if (previous && previous !== roverId && releasePrevious) {
|
||||
roverManager.releaseControl(previous, socket);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
const path = require('path');
|
||||
const { subscribe } = require('../eventBus');
|
||||
|
||||
const DONE_CHARGING_SOUND_PATH = path.resolve(__dirname, '..', '..', '..', 'public', 'donecharging.wav');
|
||||
const DONE_CHARGING_SOUND_PATH = path.resolve(__dirname, '..', '..', '..', 'assets', 'donecharging.wav');
|
||||
|
||||
function registerChargeCompleteSound(deps) {
|
||||
const {
|
||||
@@ -12,22 +12,18 @@ function registerChargeCompleteSound(deps) {
|
||||
playServerAudioFile,
|
||||
} = deps;
|
||||
|
||||
subscribe('battery.unlocked', (event = {}) => {
|
||||
subscribe('battery.chargeComplete', (event = {}) => {
|
||||
const roverId = String(event?.payload?.roverId || '').trim();
|
||||
if (!roverId) return;
|
||||
|
||||
try {
|
||||
// battery.unlocked is the existing server-side definition of "done
|
||||
// charging" because it only fires after the battery manager has waited
|
||||
// through its full charge-release policy. Playing from this event avoids
|
||||
// duplicating charging thresholds or raw sensor-state guesses here.
|
||||
playServerAudioFile(roverId, DONE_CHARGING_SOUND_PATH, {
|
||||
source: 'charge-complete',
|
||||
});
|
||||
logger.info('Played charging complete sound', { roverId, filePath: DONE_CHARGING_SOUND_PATH });
|
||||
logger.info('Started charging complete sound', { roverId, filePath: DONE_CHARGING_SOUND_PATH });
|
||||
} catch (err) {
|
||||
// A missing/offline rover or unavailable ffmpeg should not affect the
|
||||
// battery manager's unlock decision. The sound is an announcement layered
|
||||
// battery manager's processing. The sound is an announcement layered
|
||||
// on top of the state transition, so failures are logged and contained.
|
||||
logger.warn('Failed to play charging complete sound', {
|
||||
roverId,
|
||||
|
||||
@@ -124,7 +124,7 @@ function grantExternalSpectatorAccessAfterAdminLogin(socket) {
|
||||
}
|
||||
|
||||
io.on('connection', (socket) => {
|
||||
const requestedRole = socket.handshake?.query?.role;
|
||||
const requestedRole = socket.handshake?.auth?.role || socket.handshake?.query?.role;
|
||||
/*
|
||||
Role is assigned before the browser's full identity heartbeat has completed.
|
||||
For admin-gated external spectators, fail closed here; the spectator page can
|
||||
@@ -188,4 +188,5 @@ module.exports = {
|
||||
isAdmin,
|
||||
isLockdownAdmin,
|
||||
authenticate,
|
||||
canBecomeSpectator,
|
||||
};
|
||||
|
||||
@@ -109,6 +109,7 @@ async function copyDurableTree(sourceDir, destinationDir, relativeDir = '') {
|
||||
const relativePath = path.join(relativeDir, entry.name);
|
||||
if (!relativeDir && EXCLUDED_TOP_LEVEL_NAMES.has(entry.name)) continue;
|
||||
if (!relativeDir && DATABASE_FILES.has(entry.name)) continue;
|
||||
if (relativePath === path.join('rover-learning', 'recordings')) continue;
|
||||
if (entry.isSymbolicLink()) throw new Error(`Backup cannot include symbolic link: ${relativePath}`);
|
||||
if (entry.isDirectory()) {
|
||||
skipped.push(...await copyDurableTree(sourceDir, destinationDir, relativePath));
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
const logger = require('../../globals/logger').child('batteryManager');
|
||||
const { publishEvent } = require('../eventBus');
|
||||
const { managerEvents, lockRover, rovers } = require('../roverManager');
|
||||
const { issueCommand } = require('../commandService');
|
||||
|
||||
const STATES = {
|
||||
NORMAL: 'normal',
|
||||
@@ -29,6 +30,7 @@ function getState(roverId) {
|
||||
dockedCharging: false,
|
||||
charging: false,
|
||||
batteryLocked: false,
|
||||
completionAnnounced: false,
|
||||
waitingSince: null,
|
||||
});
|
||||
}
|
||||
@@ -61,6 +63,11 @@ function handleSensorEvent({ roverId, sensors, batteryState }) {
|
||||
}
|
||||
if (!state.urgent && batteryState?.urgentActive) {
|
||||
state.urgent = true;
|
||||
try {
|
||||
issueCommand(roverId, { type: 'song', song: { notes: [{ note: 72, duration: 8 }, { note: 0, duration: 8 }, { note: 72, duration: 16 }] } });
|
||||
} catch (err) {
|
||||
logger.warn('Failed to play urgent battery warning', { roverId, error: err.message });
|
||||
}
|
||||
publishEvent({
|
||||
source: 'batteryManager',
|
||||
type: 'battery.urgent',
|
||||
@@ -137,6 +144,18 @@ function handleSensorEvent({ roverId, sensors, batteryState }) {
|
||||
(batteryState?.charge != null && fullThreshold != null && batteryState.charge >= fullThreshold) ||
|
||||
(batteryState?.percent != null && batteryState.percent >= 0.99);
|
||||
|
||||
// Announce once per dock visit, independently of the charging lock. Keep the
|
||||
// latch at 100% so small charge fluctuations cannot repeat the sound.
|
||||
if (!onDock) state.completionAnnounced = false;
|
||||
if (onDock && batteryState?.percentDisplay >= 100 && !state.completionAnnounced) {
|
||||
state.completionAnnounced = true;
|
||||
publishEvent({
|
||||
source: 'batteryManager',
|
||||
type: 'battery.chargeComplete',
|
||||
payload: { roverId, batteryState },
|
||||
});
|
||||
}
|
||||
|
||||
const needsCharge = state.warned;
|
||||
|
||||
if (dockedCharging && lockable && needsCharge && !state.batteryLocked && !isFull && !waitingLongEnough) {
|
||||
|
||||
@@ -2,20 +2,14 @@
|
||||
// Purpose: Builds normalized chat message/typing payloads and rover context snapshots.
|
||||
// Scope: Encapsulates chat DTO construction and rover/driver metadata extraction.
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const io = require('../../globals/io');
|
||||
const roverManager = require('../roverManager');
|
||||
const { getRole } = require('../roleService');
|
||||
const { getOperatingMode } = require('../operatingModeService');
|
||||
const { describeAssignment } = require('../assignmentService');
|
||||
const { getNickname } = require('../nicknameService');
|
||||
const ptzCameraService = require('../ptzCameraService');
|
||||
|
||||
function resolvePtzChatTarget(socketId) {
|
||||
return ptzCameraService.getChatTargetForSocket(socketId) || null;
|
||||
}
|
||||
|
||||
function resolveRoverId(socketId) {
|
||||
const ptzTarget = resolvePtzChatTarget(socketId);
|
||||
if (ptzTarget?.roverId) return ptzTarget.roverId;
|
||||
const primary = roverManager.getPrimaryRoverForSocket(socketId);
|
||||
if (primary) return primary;
|
||||
const assignment = describeAssignment(socketId);
|
||||
@@ -24,54 +18,22 @@ function resolveRoverId(socketId) {
|
||||
|
||||
function resolveRoverColor(roverId) {
|
||||
if (!roverId) return null;
|
||||
if (String(roverId) === ptzCameraService.PTZ_CAMERA_ID) {
|
||||
return ptzCameraService.getPublicState()?.color || null;
|
||||
}
|
||||
const record = roverManager.rovers.get(String(roverId));
|
||||
return record?.meta?.color || null;
|
||||
}
|
||||
|
||||
function resolveRoverName(roverId) {
|
||||
if (!roverId) return null;
|
||||
if (String(roverId) === ptzCameraService.PTZ_CAMERA_ID) {
|
||||
return ptzCameraService.getPublicState()?.name || null;
|
||||
}
|
||||
const record = roverManager.rovers.get(String(roverId));
|
||||
return record?.meta?.name || null;
|
||||
}
|
||||
|
||||
function isPtzChatTargetId(roverId) {
|
||||
/*
|
||||
PTZ is intentionally treated as a virtual rover for chat identity only. It
|
||||
does not live in roverManager.rovers because movement, video authorization,
|
||||
and queue ownership are PTZ-service concerns, but chat needs one stable
|
||||
"rover-like" id so the existing web UI, Discord bridge, and AI transcript
|
||||
code can all render the same badge without learning PTZ internals.
|
||||
*/
|
||||
return Boolean(roverId) && String(roverId) === ptzCameraService.PTZ_CAMERA_ID;
|
||||
}
|
||||
|
||||
function isPublicChatTargetId(roverId, socket = null) {
|
||||
if (!roverId) return false;
|
||||
/*
|
||||
Normal rovers remain governed by the existing replay visibility rule, which
|
||||
is also the rule chat historically used to avoid exposing closed private
|
||||
rover activity. PTZ gets an explicit allow-list entry here because it is a
|
||||
public chat target that deliberately pretends to be a rover, even though it
|
||||
is not a roverManager record.
|
||||
*/
|
||||
if (isPtzChatTargetId(roverId)) return true;
|
||||
return roverManager.canReplayRoverId(roverId, socket) === true;
|
||||
return Boolean(roverId) && roverManager.canReplayRoverId(roverId, socket) === true;
|
||||
}
|
||||
|
||||
function isPrivateClosedRoverId(roverId) {
|
||||
if (!roverId) return false;
|
||||
/*
|
||||
PTZ uses the existing rover badge fields so chat rows can reuse RoverLabel,
|
||||
but it is not a private rover. Let PTZ-badged messages broadcast normally
|
||||
instead of falling into the closed-private rover path for unknown ids.
|
||||
*/
|
||||
return !isPublicChatTargetId(roverId);
|
||||
return Boolean(roverId) && !isPublicChatTargetId(roverId);
|
||||
}
|
||||
|
||||
function normalizeProfileImageUrl(value) {
|
||||
@@ -170,6 +132,8 @@ function buildMessage(socket, text, meta = {}) {
|
||||
socketId: socket?.id || null,
|
||||
nickname: meta.nickname || getNickname(socket) || null,
|
||||
role: meta.role || getRole(socket),
|
||||
operatingMode: socket ? getOperatingMode(socket) : null,
|
||||
operatingModeDisplay: socket ? ptzCameraService.getOperatingModeDisplay(socket.id) : null,
|
||||
roverId,
|
||||
roverName,
|
||||
roverColor,
|
||||
@@ -215,6 +179,8 @@ function buildTypingPayload(socket, meta = {}) {
|
||||
socketId,
|
||||
nickname: meta.nickname || getNickname(socket) || null,
|
||||
role: meta.role || getRole(socket),
|
||||
operatingMode: socket ? getOperatingMode(socket) : null,
|
||||
operatingModeDisplay: socket ? ptzCameraService.getOperatingModeDisplay(socket.id) : null,
|
||||
roverId,
|
||||
roverName,
|
||||
roverColor,
|
||||
@@ -231,7 +197,6 @@ function buildTypingPayload(socket, meta = {}) {
|
||||
|
||||
module.exports = {
|
||||
resolveRoverId,
|
||||
isPtzChatTargetId,
|
||||
isPublicChatTargetId,
|
||||
isPrivateClosedRoverId,
|
||||
buildRoverCtxSnapshot,
|
||||
|
||||
@@ -19,13 +19,6 @@ const { getLastAccessNoticeAt, setLastAccessNoticeAt } = require('./state');
|
||||
|
||||
function playTypingNote(roverId, note, socketId) {
|
||||
if (!roverId) return;
|
||||
/*
|
||||
PTZ borrows the roverId field for chat badges, but it has no rover command
|
||||
channel. Skipping the song command here keeps PTZ chat from producing noisy
|
||||
"unknown rover" command attempts while still allowing the message itself to
|
||||
behave like rover chat everywhere else.
|
||||
*/
|
||||
if (String(roverId) === ptzCameraService.PTZ_CAMERA_ID) return;
|
||||
try {
|
||||
issueCommand(roverId, {
|
||||
type: 'song',
|
||||
@@ -90,8 +83,8 @@ function maybeSendAccessNotice(message, sendSystemMessage) {
|
||||
}
|
||||
|
||||
function maybeSpeak(socket, message, ttsOptions) {
|
||||
if (!ttsOptions || !message?.roverId) return;
|
||||
if (String(message.roverId) === ptzCameraService.PTZ_CAMERA_ID) {
|
||||
if (!ttsOptions || !message) return;
|
||||
if (message.operatingMode === 'ptz') {
|
||||
/*
|
||||
PTZ has no rover websocket, but it does have a real speaker behind the
|
||||
Reolink/neolink path. Keep PTZ routing here so chat remains the single
|
||||
@@ -107,6 +100,7 @@ function maybeSpeak(socket, message, ttsOptions) {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!message.roverId) return;
|
||||
const record = roverManager.rovers.get(message.roverId);
|
||||
const ttsEnabled = Boolean(record?.meta?.audio?.ttsEnabled);
|
||||
if (!ttsEnabled) return;
|
||||
@@ -116,7 +110,7 @@ function maybeSpeak(socket, message, ttsOptions) {
|
||||
issueCommand(message.roverId, {
|
||||
type: 'tts',
|
||||
tts: {
|
||||
text: message.text,
|
||||
text: message.text.replace(/\b(?:https?:\/\/|www\.)\S{25,}[^\s.,!?;:"'()\[\]{}]/g, ' [link] '),
|
||||
engine: ttsOptions.engine,
|
||||
voice: ttsOptions.voice,
|
||||
pitch: ttsOptions.pitch,
|
||||
|
||||
@@ -91,9 +91,9 @@ function createWebReplayTextCommand(socket, sendSystemMessage, replayApi) {
|
||||
|
||||
const requester = buildRequesterLabel(socket);
|
||||
const jobId = buildReplayJobId('web-chat');
|
||||
const attempt = replayApi.tryTriggerReplay({ by: { source: 'web-chat', requester } });
|
||||
const attempt = replayApi.tryTriggerReplay({ jobId, by: { source: 'web-chat', requester } });
|
||||
if (!attempt.ok) {
|
||||
await message.reply({ content: `Replay denied: cooldown active. Try again in ${Math.ceil(attempt.remainingMs / 1000)}s.` });
|
||||
await message.reply({ content: `Replay denied: ${attempt.error}` });
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -85,7 +85,7 @@ function normalizeOutboundCommandPayload(payload = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
function issueCommand(roverId, payload) {
|
||||
function issueCommand(roverId, payload, options = {}) {
|
||||
const record = roverManager.rovers.get(roverId);
|
||||
if (!record || !record.ws) {
|
||||
throw new Error('Rover offline');
|
||||
@@ -93,6 +93,11 @@ function issueCommand(roverId, payload) {
|
||||
if (payload?.type === 'laser' && isLaserCommandBlockedByRoomLightLock(payload)) {
|
||||
throw new Error('Laser disabled while room lights are locked on');
|
||||
}
|
||||
if (options.dockingOwned && payload.driveDirect && getCommandMotionMagnitude('drive', payload) > 0
|
||||
&& Date.now() < (driveCooldowns.get(roverId) || 0)) {
|
||||
throw new Error('Drive blocked: safety cooldown');
|
||||
}
|
||||
payload = require('../dockingService').protectCommand(record, payload, options);
|
||||
const id = uuidv4();
|
||||
const normalizedPayload = normalizeOutboundCommandPayload(payload);
|
||||
const message = { ...normalizedPayload, id };
|
||||
@@ -124,7 +129,14 @@ overcurrentProtectionService.configureCommandIssuer((roverId, payload) => {
|
||||
*/
|
||||
return false;
|
||||
}
|
||||
issueCommand(roverId, payload);
|
||||
const record = roverManager.rovers.get(roverId);
|
||||
const reverseAdjustment = payload.driveDirect
|
||||
&& (payload.driveDirect.left < 0 || payload.driveDirect.right < 0)
|
||||
&& payload.driveDirect.left <= 0 && payload.driveDirect.right <= 0
|
||||
&& require('../dockingService').canAdjustReverse(record);
|
||||
// Only protection's adjustments to the active reverse inherit controller
|
||||
// ownership. Zero remains an ordinary stop and cancels the sequence.
|
||||
issueCommand(roverId, payload, { dockingOwned: Boolean(reverseAdjustment) });
|
||||
return true;
|
||||
});
|
||||
|
||||
@@ -315,6 +327,22 @@ function submitCommand(socket, { roverId, type, data } = {}, cb) {
|
||||
if (!isSongCommand && !isRebootCommand && !isUpdateCommand && !roverManager.canDrive(roverId, socket)) {
|
||||
throw new Error('Not your turn or no control');
|
||||
}
|
||||
const record = roverManager.rovers.get(roverId);
|
||||
if (!record?.ws) throw new Error('Rover offline');
|
||||
const docking = require('../dockingService');
|
||||
// The controller owns wheel output during undocking. Discard all ordinary
|
||||
// drive input, including neutral, before it can alter protection's intent.
|
||||
if (docking.shouldIgnoreDriveInput(record, payload)) {
|
||||
reply({ ignored: true, reason: 'undocking' });
|
||||
return;
|
||||
}
|
||||
// Reject before recording held motor intent: otherwise a rejected input
|
||||
// could be replayed by protection as soon as the docking lock is released.
|
||||
if (!docking.intents.has(type)) {
|
||||
const guarded = docking.protectCommand(record, { ...payload, type });
|
||||
type = guarded.type;
|
||||
payload = guarded;
|
||||
}
|
||||
const driveDirect = payload?.driveDirect;
|
||||
if (type === 'drive' && driveDirect) {
|
||||
if (!isAdminSocket) {
|
||||
@@ -361,7 +389,14 @@ function submitCommand(socket, { roverId, type, data } = {}, cb) {
|
||||
bypassed: isAdminSocket,
|
||||
});
|
||||
}
|
||||
const id = issueCommand(roverId, { type, ...payload });
|
||||
const isDockingIntent = docking.intents.has(type);
|
||||
const id = isDockingIntent
|
||||
? docking.issueIntent(roverManager.rovers.get(roverId), type, payload, socket)
|
||||
: issueCommand(roverId, { ...payload, type });
|
||||
if (isDockingIntent) {
|
||||
// The server acknowledges accepting the intent; telemetry reports its completion.
|
||||
io.emit('commandAck', { roverId, id, status: 'ok' });
|
||||
}
|
||||
commandEvents.emit('observation', {
|
||||
ts: Date.now(),
|
||||
roverId: String(roverId),
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// Purpose: Centralizes rover battery/status snapshot formatting and embed rendering for Discord surfaces.
|
||||
// Scope: Shared presentation logic for status commands and admin alert battery event posts.
|
||||
const { EmbedBuilder } = require('discord.js');
|
||||
const { getMode } = require('../modeManager');
|
||||
|
||||
function formatVoltage(voltageMv) {
|
||||
if (voltageMv == null) return 'n/a';
|
||||
@@ -69,6 +70,7 @@ function buildRoverStatusSnapshot(record) {
|
||||
|
||||
function buildBatteryStatusEmbed({ color = 0x2196f3, records = [] }) {
|
||||
const embed = new EmbedBuilder().setTitle('Rover Battery Status').setColor(color).setTimestamp(new Date());
|
||||
embed.addFields({ name: 'Server mode', value: getMode(), inline: true });
|
||||
const snapshots = records.map((entry) => buildRoverStatusSnapshot(entry)).filter(Boolean);
|
||||
if (!snapshots.length) {
|
||||
embed.setDescription('No rovers online.');
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Discord Replay Command
|
||||
// Purpose: Handles replay capture requests from Discord through the shared replay job/status workflow.
|
||||
// Scope: Resolves sources, enforces cooldowns, reports job progress, uploads video, and broadcasts media URLs.
|
||||
// Scope: Resolves sources, enforces replay availability, reports job progress, uploads video, and broadcasts media URLs.
|
||||
const { AttachmentBuilder } = require('discord.js');
|
||||
const io = require('../../../globals/io');
|
||||
const { hostReplay } = require('../../replayMediaService');
|
||||
@@ -60,12 +60,6 @@ function createReplayCommand({
|
||||
return;
|
||||
}
|
||||
|
||||
const attempt = tryTriggerReplay({ by: message.author?.id || null, source: 'discord' });
|
||||
if (!attempt.ok) {
|
||||
await replyDenied(message, `Replay denied: cooldown active. Try again in ${Math.ceil(attempt.remainingMs / 1000)}s.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const requester = message.member?.nickname || message.author?.globalName || message.author?.username || 'Discord';
|
||||
const job = createReplayJob({
|
||||
id: buildReplayJobId('discord'),
|
||||
@@ -74,17 +68,23 @@ function createReplayCommand({
|
||||
sources: resolved.sources || [],
|
||||
includeSidebar: true,
|
||||
});
|
||||
jobStatus.emit(job, 'accepted', { message: buildAcceptedMessage(job) });
|
||||
|
||||
const progressMessage = await message.reply({
|
||||
content: sanitizeMentions(buildAcceptedMessage(job)),
|
||||
allowedMentions: DEFAULT_ALLOWED_MENTIONS,
|
||||
});
|
||||
const stopTyping = startDiscordTypingLoop(message.channel, logger, 'discord replay command');
|
||||
const attempt = tryTriggerReplay({ jobId: job.id, by: { source: 'discord', requester } });
|
||||
if (!attempt.ok) {
|
||||
await replyDenied(message, `Replay denied: ${attempt.error}`);
|
||||
return;
|
||||
}
|
||||
|
||||
let progressMessage = null;
|
||||
let stopTyping = () => {};
|
||||
let builtReplay = null;
|
||||
let deliveredMedia = null;
|
||||
try {
|
||||
jobStatus.emit(job, 'accepted', { message: buildAcceptedMessage(job) });
|
||||
progressMessage = await message.reply({
|
||||
content: sanitizeMentions(buildAcceptedMessage(job)),
|
||||
allowedMentions: DEFAULT_ALLOWED_MENTIONS,
|
||||
});
|
||||
stopTyping = startDiscordTypingLoop(message.channel, logger, 'discord replay command');
|
||||
jobStatus.emit(job, 'building', { message: buildStatusMessage(job, 'building') });
|
||||
if (progressMessage?.edit) {
|
||||
await progressMessage.edit({ content: sanitizeMentions(buildStatusMessage(job, 'building')), allowedMentions: DEFAULT_ALLOWED_MENTIONS });
|
||||
|
||||
@@ -59,12 +59,6 @@ function createChatBridgeHandlers(deps) {
|
||||
function handleChatBridgeOutbound(event) {
|
||||
const payload = event?.payload;
|
||||
if (!payload) return;
|
||||
/*
|
||||
Outbound bridge filtering must use chat visibility, not rover replay
|
||||
visibility. PTZ deliberately uses roverId: "ptz-camera" so the existing
|
||||
chat badge path can be reused, but that id is not a roverManager rover and
|
||||
would be dropped by canReplayRoverId().
|
||||
*/
|
||||
if (payload?.roverId && !isPublicChatTargetId(payload.roverId)) return;
|
||||
const guildConfigs = listGuildConfigs();
|
||||
if (!guildConfigs.length) return;
|
||||
|
||||
@@ -24,14 +24,8 @@ function formatWebhookUsername(payload) {
|
||||
const origin = payload.discordGuildName ? ` (From: ${payload.discordGuildName})` : '';
|
||||
return `${name}${origin}${botTag}${spectatorTag}${adminTag}`;
|
||||
}
|
||||
/*
|
||||
The chat payload already carries the resolved display name for rover-like
|
||||
targets. Prefer that name so PTZ, which is intentionally pretending to be a
|
||||
rover in chat, shows up as "PTZ Camera" instead of the internal id
|
||||
"ptz-camera"; fall back to the id for older payloads or missing metadata.
|
||||
*/
|
||||
const roverTagLabel = payload.roverName || payload.roverId;
|
||||
const roverTag = payload.roverId ? ` [${roverTagLabel}]` : '';
|
||||
const tagLabel = payload.operatingModeDisplay?.name || payload.roverName || payload.roverId;
|
||||
const roverTag = tagLabel ? ` [${tagLabel}]` : '';
|
||||
return `${name}${botTag}${spectatorTag}${adminTag}${roverTag}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
// Server-owned docking operations.
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const io = require('../../globals/io');
|
||||
const logger = require('../../globals/logger').child('dockingService');
|
||||
const states = new WeakMap();
|
||||
const intents = new Set(['enterDocking', 'cancelDocking', 'undock']);
|
||||
const ASSIST_SPEED = 60;
|
||||
const SENSOR_TIMEOUT_MS = 1500;
|
||||
const UNDOCK_TIMEOUT_MS = 4000;
|
||||
const REVERSE_TIMEOUT_MS = 1000;
|
||||
// Preserve the working OI preparation sequence; only backing away is sensor-driven.
|
||||
const MODE_COMMAND_DELAY_MS = 100;
|
||||
const FULL_MODE_SETTLE_MS = 300;
|
||||
|
||||
function stateFor(record) {
|
||||
if (!states.has(record)) {
|
||||
states.set(record, {
|
||||
contact: null, charging: false, latched: false, assist: false,
|
||||
operation: null, error: null, seenAt: 0, timer: null, contactDockPending: false,
|
||||
});
|
||||
}
|
||||
return states.get(record);
|
||||
}
|
||||
|
||||
function snapshot(record) {
|
||||
const state = stateFor(record);
|
||||
return {
|
||||
phase: state.operation ? 'undocking' : state.contact ? (state.charging ? 'charging' : 'docked') : state.assist ? 'assisting' : 'idle',
|
||||
movementLocked: Boolean(state.operation || state.latched || state.error || state.contact == null),
|
||||
cameraLocked: state.assist,
|
||||
error: state.error,
|
||||
};
|
||||
}
|
||||
|
||||
function publish(record) {
|
||||
if (!record.lastSensor?.decoded) return;
|
||||
record.lastSensor.decoded = { ...record.lastSensor.decoded, docking: snapshot(record) };
|
||||
// State transitions use the same telemetry event, including failures when the
|
||||
// physical sensor stream has stalled. Never manufacture a new sensor timestamp.
|
||||
io.to(record.room).emit('sensorFrame', {
|
||||
roverId: record.id, frame: record.lastSensor.raw, sensors: record.lastSensor.decoded,
|
||||
overcurrentProtection: record.lastOvercurrentProtection || null,
|
||||
});
|
||||
}
|
||||
|
||||
function send(record, payload) {
|
||||
return require('../commandService').issueCommand(record.id, payload, { dockingOwned: true });
|
||||
}
|
||||
function stop(record) {
|
||||
// Forget the previous held intent so protection cannot replay it after unlock.
|
||||
require('../overcurrentProtectionService').protectCommand(record.id, 'drive', { driveDirect: { left: 0, right: 0 } });
|
||||
send(record, { type: 'drive', driveDirect: { left: 0, right: 0 } });
|
||||
}
|
||||
function stopAllMotion(record) {
|
||||
stop(record);
|
||||
const payload = { motorPwm: { main: 0, side: 0, vacuum: 0 } };
|
||||
require('../overcurrentProtectionService').protectCommand(record.id, 'motors', payload);
|
||||
send(record, { type: 'motors', ...payload });
|
||||
}
|
||||
function mode(record, opcode) {
|
||||
send(record, { type: 'raw', raw: Buffer.from([opcode]).toString('base64') });
|
||||
}
|
||||
function camera(record, angle) {
|
||||
if (record.meta?.cameraServo?.enabled) send(record, { type: 'servo', servo: { angle } });
|
||||
}
|
||||
function song(record, notes, slot = 0, duration = 10) {
|
||||
send(record, { type: 'song', song: { slot, notes: notes.map((note) => ({ note, duration })) } });
|
||||
}
|
||||
function finishAssist(record, { playExitSong = true } = {}) {
|
||||
const state = stateFor(record);
|
||||
if (!state.assist) return;
|
||||
state.assist = false;
|
||||
camera(record, 0);
|
||||
if (playExitSong) song(record, [83, 76]);
|
||||
}
|
||||
function clearOperation(state) {
|
||||
clearTimeout(state.timer);
|
||||
state.timer = null;
|
||||
state.operation = null;
|
||||
}
|
||||
function fail(record, code, message) {
|
||||
const state = stateFor(record);
|
||||
clearOperation(state);
|
||||
state.error = { code, message };
|
||||
state.latched = true;
|
||||
try { stop(record); } catch (error) {
|
||||
logger.warn('Unable to stop docking operation', { roverId: record.id, error: error.message });
|
||||
}
|
||||
publish(record);
|
||||
}
|
||||
function armDeadline(record) {
|
||||
const state = stateFor(record);
|
||||
clearTimeout(state.timer);
|
||||
if (!state.operation) return;
|
||||
const deadline = Math.min(
|
||||
state.seenAt + SENSOR_TIMEOUT_MS,
|
||||
state.operation.startedAt + UNDOCK_TIMEOUT_MS,
|
||||
state.operation.reversingAt ? state.operation.reversingAt + REVERSE_TIMEOUT_MS : Infinity,
|
||||
);
|
||||
state.timer = setTimeout(() => {
|
||||
const stale = Date.now() - state.seenAt >= SENSOR_TIMEOUT_MS;
|
||||
fail(record, stale ? 'telemetryUnavailable' : 'undockTimeout', stale ? 'Rover telemetry stopped during undocking.' : 'Unable to leave the dock.');
|
||||
}, Math.max(1, deadline - Date.now()));
|
||||
state.timer.unref?.();
|
||||
}
|
||||
|
||||
function handleIntent(record, type, payload, socket) {
|
||||
const state = stateFor(record);
|
||||
if (type === 'cancelDocking') {
|
||||
if (state.operation) fail(record, 'undockCancelled', 'Undocking stopped.');
|
||||
stop(record);
|
||||
finishAssist(record);
|
||||
publish(record);
|
||||
return;
|
||||
}
|
||||
state.error = null;
|
||||
state.contactDockPending = false;
|
||||
require('../roverManager').stopDockGuard(record.id);
|
||||
stop(record);
|
||||
if (type === 'enterDocking') {
|
||||
state.latched = false;
|
||||
if (!state.assist) {
|
||||
state.assist = true;
|
||||
camera(record, record.meta?.cameraServo?.minAngle ?? -45);
|
||||
song(record, [76, 83]);
|
||||
}
|
||||
} else {
|
||||
finishAssist(record);
|
||||
camera(record, 0);
|
||||
state.operation = {
|
||||
startedAt: Date.now(), socket, backoff: payload.backoff !== false, reversing: false,
|
||||
stage: 'start', nextStepAt: Date.now() + MODE_COMMAND_DELAY_MS,
|
||||
};
|
||||
mode(record, 128);
|
||||
armDeadline(record);
|
||||
}
|
||||
publish(record);
|
||||
}
|
||||
|
||||
function processTelemetry(record, sensors) {
|
||||
const state = stateFor(record);
|
||||
if (!sensors?.chargingSources || !sensors?.oiMode) return snapshot(record);
|
||||
const previousContact = state.contact;
|
||||
state.seenAt = Date.now();
|
||||
state.contact = Boolean(sensors.chargingSources.homeBase);
|
||||
state.charging = [1, 2, 3, 4].includes(sensors.chargingState?.code);
|
||||
if (previousContact == null) state.latched = state.contact;
|
||||
try {
|
||||
const operation = state.operation;
|
||||
if (operation) {
|
||||
const manager = require('../roverManager');
|
||||
if (!operation.socket?.connected || !manager.canDrive(record.id, operation.socket)) {
|
||||
fail(record, 'controlLost', 'Undocking stopped because control changed.');
|
||||
} else if (Date.now() - operation.startedAt >= UNDOCK_TIMEOUT_MS
|
||||
|| (operation.reversingAt && Date.now() - operation.reversingAt >= REVERSE_TIMEOUT_MS)) {
|
||||
fail(record, 'undockTimeout', 'Unable to leave the dock.');
|
||||
} else if (Date.now() < operation.nextStepAt) {
|
||||
// Advance only on fresh telemetry, after the previous OI command settles.
|
||||
} else if (operation.stage === 'start') {
|
||||
mode(record, 143);
|
||||
operation.stage = 'dock';
|
||||
operation.nextStepAt = Date.now() + MODE_COMMAND_DELAY_MS;
|
||||
} else if (operation.stage === 'dock') {
|
||||
mode(record, 132);
|
||||
operation.stage = 'full';
|
||||
operation.nextStepAt = Date.now() + FULL_MODE_SETTLE_MS;
|
||||
} else if (sensors.oiMode.label === 'full') {
|
||||
if (!state.contact || !operation.backoff) {
|
||||
stop(record);
|
||||
clearOperation(state);
|
||||
state.latched = state.contact;
|
||||
} else if (!operation.reversing) {
|
||||
operation.reversing = true;
|
||||
operation.reversingAt = Date.now();
|
||||
const speed = Math.max(1, Math.min(500, Number(record.meta?.maxWheelSpeed) || 500));
|
||||
// Track the controller's own intent in existing protection so stalls
|
||||
// still stop it and subsequent adjustments refer to this reverse only.
|
||||
const drive = require('../overcurrentProtectionService').protectCommand(record.id, 'drive', {
|
||||
driveDirect: { left: -speed, right: -speed },
|
||||
}, { bypassed: require('../roleService').isAdmin(operation.socket) });
|
||||
if (!drive.driveDirect.left && !drive.driveDirect.right) throw new Error('Undocking blocked by wheel protection');
|
||||
send(record, { ...drive, type: 'drive' });
|
||||
}
|
||||
} else if (operation.reversing) {
|
||||
fail(record, 'modeChanged', 'Undocking stopped because the Roomba mode changed.');
|
||||
}
|
||||
armDeadline(record);
|
||||
} else if (state.contact) {
|
||||
state.latched = true;
|
||||
if (previousContact !== true) {
|
||||
stopAllMotion(record);
|
||||
state.contactDockPending = true;
|
||||
if (state.assist) song(record, [84], 1, 6);
|
||||
} else if (state.contactDockPending && !state.charging) {
|
||||
const speeds = sensors.wheelSpeedsMmPerSecond;
|
||||
// A stop request does not prove the wheels stopped on the contacts.
|
||||
// Require a subsequent frame with contact and measured stationary wheels.
|
||||
if (speeds?.left === 0 && speeds?.right === 0) {
|
||||
mode(record, 143);
|
||||
state.contactDockPending = false;
|
||||
}
|
||||
}
|
||||
if (state.charging) {
|
||||
state.contactDockPending = false;
|
||||
// An immediate exit song would replace the contact beep on the Roomba.
|
||||
finishAssist(record, { playExitSong: false });
|
||||
}
|
||||
} else {
|
||||
state.contactDockPending = false;
|
||||
if (previousContact === true && state.assist) song(record, [72], 1, 6);
|
||||
}
|
||||
} catch (error) {
|
||||
fail(record, 'commandFailed', error.message);
|
||||
}
|
||||
return snapshot(record);
|
||||
}
|
||||
|
||||
function shouldIgnoreDriveInput(record, payload) {
|
||||
if (!stateFor(record).operation) return false;
|
||||
if (payload.driveDirect) return true;
|
||||
const raw = payload.raw ? Buffer.from(payload.raw, 'base64') : null;
|
||||
return Boolean(raw && [137, 145].includes(raw[0]));
|
||||
}
|
||||
|
||||
function protectCommand(record, payload, { dockingOwned = false } = {}) {
|
||||
if (dockingOwned) return payload;
|
||||
const state = stateFor(record);
|
||||
// Raw OI drive packets must obey the same movement lock. Other raw commands,
|
||||
// including mode changes, remain available and can interrupt the operation.
|
||||
const raw = payload.raw ? Buffer.from(payload.raw, 'base64') : null;
|
||||
if (state.operation && raw && [128, 131, 132, 133, 134, 135, 136, 143].includes(raw[0])) {
|
||||
// Explicit mode commands remain available and take precedence over an
|
||||
// automatic sequence, including while it is still waiting for full mode.
|
||||
fail(record, 'modeChanged', 'Undocking stopped by a Roomba mode command.');
|
||||
}
|
||||
if (raw && [137, 145].includes(raw[0])) {
|
||||
if (raw.length !== 5) throw new Error('Invalid raw drive command');
|
||||
const first = raw.readInt16BE(1);
|
||||
const second = raw.readInt16BE(3);
|
||||
if (raw[0] === 137 && first !== 0 && state.assist && !snapshot(record).movementLocked) {
|
||||
const limited = Buffer.from(raw);
|
||||
limited.writeInt16BE(Math.max(-ASSIST_SPEED, Math.min(ASSIST_SPEED, first)), 1);
|
||||
return { ...payload, raw: limited.toString('base64') };
|
||||
}
|
||||
if (raw[0] === 145) {
|
||||
return protectCommand(record, { type: 'drive', driveDirect: { left: second, right: first } });
|
||||
}
|
||||
if (first === 0 && state.operation) fail(record, 'undockStopped', 'Undocking stopped by a stop command.');
|
||||
if (first !== 0 && snapshot(record).movementLocked) throw new Error('Drive blocked while docked or undocking');
|
||||
}
|
||||
// User drive input is discarded at submitCommand before reaching here.
|
||||
// Internal safety stops still interrupt the controller through this path.
|
||||
if (payload.driveDirect) {
|
||||
const { left, right } = payload.driveDirect;
|
||||
if (!Number(left) && !Number(right) && state.operation) {
|
||||
fail(record, 'undockStopped', 'Undocking stopped by a stop command.');
|
||||
}
|
||||
if ((Number(left) || Number(right)) && snapshot(record).movementLocked) throw new Error('Drive blocked while docked or undocking');
|
||||
if (state.assist) {
|
||||
const scale = Math.min(1, ASSIST_SPEED / Math.max(Math.abs(left), Math.abs(right), 1));
|
||||
return { ...payload, driveDirect: { left: Math.round(left * scale), right: Math.round(right * scale) } };
|
||||
}
|
||||
}
|
||||
if (payload.servo && state.assist) throw new Error('Camera locked during dock assist');
|
||||
return payload;
|
||||
}
|
||||
|
||||
function disconnect(record) {
|
||||
const state = stateFor(record);
|
||||
if (state.operation) fail(record, 'roverDisconnected', 'Rover disconnected during undocking.');
|
||||
clearOperation(state);
|
||||
state.seenAt = 0;
|
||||
state.contact = null;
|
||||
state.assist = false;
|
||||
}
|
||||
|
||||
function canAdjustReverse(record) {
|
||||
return Boolean(record && stateFor(record).operation?.reversing);
|
||||
}
|
||||
|
||||
function issueIntent(record, type, payload, socket) {
|
||||
const state = stateFor(record);
|
||||
// Validate before mutating, so duplicate/rejected requests cannot disturb an
|
||||
// operation that is already in progress.
|
||||
if (type !== 'cancelDocking') {
|
||||
if (state.operation) throw new Error('Undocking is already in progress');
|
||||
if (Date.now() - state.seenAt >= SENSOR_TIMEOUT_MS || state.contact == null) {
|
||||
throw new Error('Waiting for current rover telemetry');
|
||||
}
|
||||
// Already at the requested destination; acknowledge without restarting assist.
|
||||
if (type === 'enterDocking' && state.contact) return uuidv4();
|
||||
}
|
||||
const id = uuidv4();
|
||||
try {
|
||||
handleIntent(record, type, payload, socket);
|
||||
} catch (error) {
|
||||
fail(record, 'commandFailed', error.message);
|
||||
throw error;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
module.exports = { shouldIgnoreDriveInput, canAdjustReverse, snapshot, intents, issueIntent, processTelemetry, protectCommand, disconnect };
|
||||
@@ -16,7 +16,7 @@ const { renderIndexHtml, renderOgImage, renderWebManifest } = require('../embedS
|
||||
a direct browser load. Keeping the setup and admin routes in this explicit
|
||||
allowlist prevents them from working only after client-side navigation.
|
||||
*/
|
||||
app.get(['/', '/old', '/spectate', '/mini', '/display', '/scanner', '/database', '/ptz', '/reports', '/setup', '/admin'], async (req, res) => {
|
||||
app.get(['/', '/old', '/spectate', '/mini', '/display', '/scanner', '/database', '/ptz', '/reports', '/setup', '/admin', '/mic'], async (req, res) => {
|
||||
try {
|
||||
const html = await renderIndexHtml(req);
|
||||
res.type('html').send(html);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// User and idle commands share one dispatch contract, while only the trusted
|
||||
// idle entry point can bypass per-item user locks.
|
||||
// User and automated commands share validation; only trusted automation bypasses user permissions.
|
||||
const { buildEntity, buildCommand } = require('./entityHelpers');
|
||||
|
||||
function assertAccess(actor = {}) {
|
||||
@@ -9,13 +8,14 @@ function assertAccess(actor = {}) {
|
||||
}
|
||||
|
||||
function createActions({ getConfig, ha, locks }) {
|
||||
async function execute(id, value, actor, idle = false) {
|
||||
if (!idle) assertAccess(actor);
|
||||
async function execute(id, value, actor, automated = false) {
|
||||
if (!automated) assertAccess(actor);
|
||||
const config = getConfig();
|
||||
if (!config.enabled) throw new Error('Activity Controls are disabled');
|
||||
const item = config.items.find((entry) => entry.id === id);
|
||||
if (!item) throw new Error('Unknown activity item');
|
||||
if (!idle && locks.isLocked(id) && !['admin', 'lockdown'].includes(actor.role)) throw new Error('This item is locked');
|
||||
if (!automated && locks.isLocked(id) && !['admin', 'lockdown'].includes(actor.role)) throw new Error('This item is locked');
|
||||
if (!automated && item.readOnly && !['admin', 'lockdown'].includes(actor.role)) throw new Error('This item is read-only for users');
|
||||
if (!ha.enabled || !ha.isConnected()) throw new Error('Home Assistant is offline');
|
||||
const entity = buildEntity(item, ha.getRawEntitySnapshot(id));
|
||||
if (!entity.available) throw new Error('This item is unavailable');
|
||||
@@ -25,30 +25,34 @@ function createActions({ getConfig, ha, locks }) {
|
||||
await ha.callHomeAssistantService(entity.domain, command.service, command.data);
|
||||
}
|
||||
|
||||
async function runIdleActions() {
|
||||
async function runAutomation(trigger, shouldRun = () => true) {
|
||||
const config = getConfig();
|
||||
if (!config.enabled) return { action: 'homeAssistantActivitiesIdle', skipped: true };
|
||||
if (!config.enabled) return { action: trigger, skipped: true };
|
||||
const results = [];
|
||||
// Catch per item so one offline integration cannot prevent the remaining
|
||||
// configured cleanup actions from running during this idle window.
|
||||
// configured actions from running for this trigger.
|
||||
for (const item of config.items) {
|
||||
if (!item.idleAction || item.idleAction === 'unchanged' || item.readOnly) continue;
|
||||
// Stop remaining writes if presence or mode changed while HA was responding.
|
||||
if (!shouldRun()) break;
|
||||
const setting = item.automations?.[trigger];
|
||||
if (!setting?.action || setting.action === 'unchanged') continue;
|
||||
try {
|
||||
const entity = buildEntity(item, ha.getRawEntitySnapshot(item.id));
|
||||
if (entity.type === 'readOnly') continue;
|
||||
if ((item.idleAction === 'press') !== (entity.type === 'button')) throw new Error('Idle action does not match the control type');
|
||||
if ((setting.action === 'press') !== (entity.type === 'button')) throw new Error('Automation action does not match the control type');
|
||||
// The admin form omits an empty optional string. Treat that as empty
|
||||
// text so clearing a message works; other types still reject it through
|
||||
// their normal value validation rather than silently receiving zero.
|
||||
await execute(item.id, item.idleAction === 'press' ? 'press' : (item.idleValue ?? ''), null, true);
|
||||
await execute(item.id, setting.action === 'press' ? 'press' : (setting.value ?? ''), null, true);
|
||||
results.push({ id: item.id, ok: true });
|
||||
} catch (error) {
|
||||
results.push({ id: item.id, ok: false, error: error.message });
|
||||
}
|
||||
}
|
||||
return { action: 'homeAssistantActivitiesIdle', results };
|
||||
return { action: trigger, results };
|
||||
}
|
||||
return { act: (id, value, actor) => execute(id, value, actor), runIdleActions };
|
||||
return { act: (id, value, actor) => execute(id, value, actor), runAutomation,
|
||||
runIdleActions: () => runAutomation('idle') };
|
||||
}
|
||||
|
||||
module.exports = { createActions, assertAccess };
|
||||
|
||||
@@ -29,7 +29,7 @@ test('sensor states, live constraints, and unknown button states are preserved',
|
||||
assert.equal(buildEntity({ id: 'button.bell' }, raw('unknown')).available, true);
|
||||
assert.equal(buildEntity({ id: 'button.bell' }, raw('unavailable')).available, false);
|
||||
assert.equal(buildEntity({ id: 'button.bell' }, null).available, false);
|
||||
assert.equal(buildEntity({ id: 'switch.fan', readOnly: true }, raw('on')).type, 'readOnly');
|
||||
assert.equal(buildEntity({ id: 'switch.fan', readOnly: true }, raw('on')).type, 'toggle');
|
||||
});
|
||||
|
||||
test('domain dispatch handles native entities and helpers without room-light payloads', async () => {
|
||||
@@ -87,22 +87,22 @@ test('permissions, locks, availability and allowlist are authoritative', async (
|
||||
test('idle ignores user locks, preserves no-op items, and isolates failures', async () => {
|
||||
const h = harness([
|
||||
{ id: 'switch.keep' },
|
||||
{ id: 'number.bad', idleAction: 'set', idleValue: '200' },
|
||||
{ id: 'switch.fan', idleAction: 'set', idleValue: 'off' },
|
||||
{ id: 'number.bad', automations: { idle: { action: 'set', value: '200' } } },
|
||||
{ id: 'switch.fan', automations: { idle: { action: 'set', value: 'off' } } },
|
||||
// An empty optional text box is omitted by the schema-driven admin form.
|
||||
{ id: 'input_text.message', idleAction: 'set' },
|
||||
{ id: 'input_button.stop', idleAction: 'press' },
|
||||
{ id: 'sensor.humidity', idleAction: 'set', idleValue: '0' },
|
||||
{ id: 'switch.readonly', readOnly: true, idleAction: 'set', idleValue: 'off' },
|
||||
{ id: 'input_text.message', automations: { idle: { action: 'set' } } },
|
||||
{ id: 'input_button.stop', automations: { idle: { action: 'press' } } },
|
||||
{ id: 'sensor.humidity', automations: { idle: { action: 'set', value: '0' } } },
|
||||
{ id: 'switch.readonly', readOnly: true, automations: { idle: { action: 'set', value: 'off' } } },
|
||||
], {
|
||||
'number.bad': raw('0', { min: 0, max: 10 }), 'switch.fan': raw('on'),
|
||||
'switch.readonly': raw('on'), 'number.bad': raw('0', { min: 0, max: 10 }), 'switch.fan': raw('on'),
|
||||
'input_text.message': raw('Welcome', { min: 0, max: 30 }), 'input_button.stop': raw('unknown'),
|
||||
});
|
||||
h.locked.add('switch.fan');
|
||||
const result = await h.actions.runIdleActions();
|
||||
assert.equal(result.results[0].ok, false);
|
||||
assert.equal(result.results.filter((entry) => entry.ok).length, 3);
|
||||
assert.deepEqual(h.calls.map((call) => call[2]), [{ entity_id: 'switch.fan' }, { entity_id: 'input_text.message', value: '' }, { entity_id: 'input_button.stop' }]);
|
||||
assert.equal(result.results.filter((entry) => entry.ok).length, 4);
|
||||
assert.deepEqual(h.calls.map((call) => call[2]), [{ entity_id: 'switch.fan' }, { entity_id: 'input_text.message', value: '' }, { entity_id: 'input_button.stop' }, { entity_id: 'switch.readonly' }]);
|
||||
});
|
||||
|
||||
test('an outstanding service response does not block later commands', async () => {
|
||||
|
||||
@@ -2,6 +2,14 @@
|
||||
// never acquire unrelated devices simply because they share a connection.
|
||||
const { strictObject, string, boolean } = require('../../configuration/schemaHelpers');
|
||||
|
||||
// All triggers use the same inputs so the admin form and execution contract agree.
|
||||
function automation(title, description) {
|
||||
return strictObject({
|
||||
action: string({ title: 'Action', enum: ['unchanged', 'set', 'press'], default: 'unchanged' }),
|
||||
value: string({ title: 'Value', description: 'For set: on/off, a number, exact selection, or text. Empty text clears it. Ignored for press.', maxLength: 255 }),
|
||||
}, { title, description });
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
key: 'homeAssistantActivities',
|
||||
feature: true,
|
||||
@@ -18,9 +26,12 @@ module.exports = {
|
||||
icon: string({ description: 'Font Awesome name, as used by social links. Blank or invalid names use a fallback.', maxLength: 80, examples: ['FaFan'] }),
|
||||
// Match social-link colors so admins can customize tiles through the existing config form.
|
||||
color: string({ description: 'Optional six-digit hexadecimal tile color, like social links.', examples: ['#3B82F6'], pattern: '^#[0-9a-fA-F]{6}$' }),
|
||||
readOnly: boolean({ title: 'Read only', default: false, description: 'Display the value without allowing user or idle commands.' }),
|
||||
idleAction: string({ title: 'When idle', enum: ['unchanged', 'set', 'press'], default: 'unchanged', description: 'Leave unchanged, set the idle value, or press a button once. Runs independently of user locks.' }),
|
||||
idleValue: string({ title: 'Idle value', description: 'For set: on/off, a number, exact selection, or text (empty text clears it). Checked against live entity limits when idle runs.', examples: ['0'], maxLength: 255 }),
|
||||
readOnly: boolean({ title: 'Read only for users', default: false, description: 'Ordinary users can only view this item. Admins and automations can still change supported controls.' }),
|
||||
automations: strictObject({
|
||||
idle: automation('When idle', 'Runs after the idle timeout with no users or admins online.'),
|
||||
locked: automation('When server locked', 'Runs on entering admin or lockdown mode.'),
|
||||
online: automation('When users online', 'Runs when a user or admin comes online, or the server reopens with one online. Suppressed in admin and lockdown modes. Spectators do not count.'),
|
||||
}, { title: 'Automations', description: 'One-time actions that bypass item locks and read-only permissions.' }),
|
||||
}, { description: 'One independently controlled or read-only activity control item.', required: ['id'] }),
|
||||
},
|
||||
}, { title: 'Activity Controls', description: 'Generic activity controls and idle behavior, separate from room lighting.', required: ['enabled', 'items'] }),
|
||||
|
||||
@@ -9,7 +9,8 @@ const TYPES = {
|
||||
function buildEntity(item, raw, locked = false) {
|
||||
const attributes = raw?.attributes || {};
|
||||
const domain = item.id.split('.')[0];
|
||||
const type = item.readOnly ? 'readOnly' : TYPES[domain] || 'readOnly';
|
||||
// Read-only is a user permission, not an entity capability: admins and automation still need its write type.
|
||||
const type = TYPES[domain] || 'readOnly';
|
||||
// A never-pressed button legitimately reports unknown. Its state is a last
|
||||
// press timestamp, not availability or a boolean toggle state.
|
||||
const available = Boolean(raw && raw.state !== 'unavailable' && (raw.state !== 'unknown' || type === 'button'));
|
||||
@@ -17,7 +18,7 @@ function buildEntity(item, raw, locked = false) {
|
||||
return {
|
||||
id: item.id, name: item.name?.trim() || attributes.friendly_name || item.id,
|
||||
// Include presentation settings in session state so all clients share the configured color.
|
||||
icon: item.icon || '', color: item.color || '', domain, type, locked, available,
|
||||
icon: item.icon || '', color: item.color || '', domain, type, readOnly: Boolean(item.readOnly), locked, available,
|
||||
state: raw?.state ?? 'unknown', unit: attributes.unit_of_measurement || '',
|
||||
min: numeric(attributes.min), max: numeric(attributes.max), step: numeric(attributes.step),
|
||||
options: Array.isArray(attributes.options) ? attributes.options.filter((option) => typeof option === 'string') : [],
|
||||
|
||||
@@ -8,7 +8,7 @@ const { buildEntity } = require('./entityHelpers');
|
||||
const { createLocks, resolveItem } = require('./locks');
|
||||
const { createActions } = require('./actions');
|
||||
const { getRole } = require('../roleService');
|
||||
const { getMode } = require('../modeManager');
|
||||
const { getMode, modeEvents } = require('../modeManager');
|
||||
const logger = require('../../globals/logger').child('homeAssistantActivitiesService');
|
||||
|
||||
const events = new EventEmitter();
|
||||
@@ -24,6 +24,35 @@ const actions = createActions({ getConfig: () => config, ha: {
|
||||
callHomeAssistantService: ha.callHomeAssistantService,
|
||||
}, locks });
|
||||
|
||||
let operatorsOnline = false;
|
||||
let lastAutomationState = null;
|
||||
let automationRevision = 0;
|
||||
|
||||
function refreshAutomation() {
|
||||
const mode = getMode();
|
||||
const locked = mode === 'admin' || mode === 'lockdown';
|
||||
// Remember transitions, not entity values: HA updates and extra connections
|
||||
// must not repeatedly press buttons or undo a manual admin adjustment.
|
||||
const state = config.enabled && snapshotReady && ha.isConnected()
|
||||
? (locked ? mode : operatorsOnline ? 'online' : null) : null;
|
||||
if (state === lastAutomationState) return;
|
||||
lastAutomationState = state;
|
||||
const revision = ++automationRevision;
|
||||
if (!state) return;
|
||||
actions.runAutomation(locked ? 'locked' : 'online', () => revision === automationRevision)
|
||||
.then((result) => {
|
||||
const failures = result.results?.filter((item) => !item.ok) || [];
|
||||
if (failures.length) logger.warn('Activity automation failed', { trigger: result.action, failures });
|
||||
}).catch((error) => logger.warn('Activity automation failed', { error: error.message }));
|
||||
}
|
||||
|
||||
function setOperatorsOnline(online) {
|
||||
operatorsOnline = online;
|
||||
refreshAutomation();
|
||||
}
|
||||
|
||||
modeEvents.on('change', refreshAutomation);
|
||||
|
||||
function getState() {
|
||||
return {
|
||||
enabled: config.enabled,
|
||||
@@ -53,14 +82,17 @@ function setLocked(query, locked) {
|
||||
ha.homeAssistantEvents.on('snapshot', () => {
|
||||
snapshotReady = true;
|
||||
emitUpdate();
|
||||
refreshAutomation();
|
||||
});
|
||||
ha.homeAssistantEvents.on('status', () => {
|
||||
snapshotReady = false;
|
||||
emitUpdate();
|
||||
refreshAutomation();
|
||||
});
|
||||
registerConfigurationHandler('homeAssistantActivities', (next) => {
|
||||
config = next;
|
||||
emitUpdate();
|
||||
refreshAutomation();
|
||||
});
|
||||
// Resolve access on the server for every command; clients only supply item/value.
|
||||
io.on('connection', (socket) => {
|
||||
@@ -76,4 +108,7 @@ io.on('connection', (socket) => {
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = { ...actions, getState, setLocked, activityEvents: events };
|
||||
module.exports = { ...actions, getState, setLocked, setOperatorsOnline, activityEvents: events,
|
||||
// A returning operator ends idle cleanup even if earlier HA calls are still settling.
|
||||
runIdleActions: () => actions.runAutomation('idle', () => !operatorsOnline),
|
||||
};
|
||||
|
||||
@@ -4,11 +4,15 @@
|
||||
const logger = require('../../globals/logger').child('idleService');
|
||||
const io = require('../../globals/io');
|
||||
const { getRole, roleEvents } = require('../roleService');
|
||||
const { getMode, MODES, modeEvents } = require('../modeManager');
|
||||
const { isDeterred, verificationEvents } = require('../verificationService');
|
||||
const { IDLE_TIMEOUT_MS } = require('./constants');
|
||||
const { runtime } = require('./state');
|
||||
const { runIdleActions } = require('./actions');
|
||||
const activityControls = require('../homeAssistantActivitiesService');
|
||||
|
||||
function getActivitySnapshot() {
|
||||
const mode = getMode();
|
||||
let onlineUsers = 0;
|
||||
let onlineAdmins = 0;
|
||||
let onlineSpectators = 0;
|
||||
@@ -28,12 +32,16 @@ function getActivitySnapshot() {
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
Lockdown admins are counted with regular admins because both represent a
|
||||
person with operator-level access who may be supervising the room without
|
||||
actively driving a rover. Plain users also count even before they request
|
||||
control, which is the behavior this service now needs.
|
||||
*/
|
||||
|
||||
if (
|
||||
isDeterred(socket)
|
||||
|| (mode === MODES.ADMIN && role !== 'admin' && role !== 'lockdown')
|
||||
|| (mode === MODES.LOCKDOWN && role !== 'lockdown')
|
||||
) {
|
||||
onlineIgnored += 1;
|
||||
return;
|
||||
}
|
||||
|
||||
if (role === 'admin' || role === 'lockdown') {
|
||||
onlineAdmins += 1;
|
||||
return;
|
||||
@@ -89,7 +97,7 @@ function scheduleIdleTimer() {
|
||||
runtime.deadlineAt = null;
|
||||
const activity = getActivitySnapshot();
|
||||
if (activity.totalActive > 0) {
|
||||
logger.info('Idle automation skipped; user or admin online', activity);
|
||||
logger.info('Idle automation skipped; eligible operator online', activity);
|
||||
return;
|
||||
}
|
||||
runtime.lastTriggeredAt = Date.now();
|
||||
@@ -113,16 +121,12 @@ function scheduleIdleTimer() {
|
||||
function refreshIdleState() {
|
||||
const activity = getActivitySnapshot();
|
||||
logger.info('Idle state refresh', activity);
|
||||
activityControls.setOperatorsOnline(activity.totalActive > 0);
|
||||
if (activity.totalActive > 0) {
|
||||
clearIdleTimer();
|
||||
if (runtime.idleActionsCompleted) {
|
||||
logger.info('Idle action one-shot reset; operator is online again', activity);
|
||||
}
|
||||
/*
|
||||
A user/admin coming online starts a new activity window. When the room
|
||||
later becomes idle again, the cleanup pipeline should be allowed to run
|
||||
once for that new idle period.
|
||||
*/
|
||||
runtime.idleActionsCompleted = false;
|
||||
return;
|
||||
}
|
||||
@@ -130,17 +134,13 @@ function refreshIdleState() {
|
||||
}
|
||||
|
||||
io.on('connection', (socket) => {
|
||||
/*
|
||||
A user/admin can be online without ever touching rover controls, so socket
|
||||
presence has to be a first-class idle signal. The disconnect hook is just as
|
||||
important: it is what starts the idle timeout after the last non-spectator
|
||||
leaves, even if no driving event happens around that departure.
|
||||
*/
|
||||
refreshIdleState();
|
||||
socket.on('disconnect', refreshIdleState);
|
||||
});
|
||||
|
||||
roleEvents.on('change', refreshIdleState);
|
||||
modeEvents.on('change', refreshIdleState);
|
||||
verificationEvents.on('change', refreshIdleState);
|
||||
|
||||
refreshIdleState();
|
||||
|
||||
|
||||
@@ -10,7 +10,8 @@ const { loadConfig, getFeatureFlags, registerConfigurationHandler } = require('.
|
||||
const { getConfiguredSocials } = require('../sessionService/configuration');
|
||||
const { getMode, MODES } = require('../modeManager');
|
||||
const roverManager = require('../roverManager');
|
||||
const { getTurnQueues } = require('../turnService');
|
||||
const { getTurnQueues, getActiveDrivers } = require('../turnService');
|
||||
const { buildRoverTurn } = require('../turnService/display');
|
||||
const { getRoomCameras, getRoomCameraState } = require('../roomCameraService');
|
||||
const { getRoverSnapshotState } = require('../roverSnapshotService');
|
||||
const { getRole } = require('../roleService');
|
||||
@@ -157,22 +158,6 @@ function publicRoverIdSet(roster = []) {
|
||||
return new Set(roster.map((rover) => String(rover?.id || '')).filter(Boolean));
|
||||
}
|
||||
|
||||
function filterPublicTurnQueues(turnQueues = {}, publicIds) {
|
||||
const visible = publicIds instanceof Set ? publicIds : new Set();
|
||||
const next = {};
|
||||
/*
|
||||
RoverQueuesPanel creates fallback rows for queue ids that are not present in
|
||||
the roster, so the public payload must filter queues with the exact same
|
||||
privacy boundary as the roster. Otherwise a closed-private rover can leak as
|
||||
an orphan queue row after a private access grant assigns someone to it.
|
||||
*/
|
||||
Object.entries(turnQueues || {}).forEach(([roverId, info]) => {
|
||||
if (!visible.has(String(roverId))) return;
|
||||
next[roverId] = info;
|
||||
});
|
||||
return next;
|
||||
}
|
||||
|
||||
function filterPublicUsers(users = [], publicIds) {
|
||||
const visible = publicIds instanceof Set ? publicIds : new Set();
|
||||
/*
|
||||
@@ -203,6 +188,8 @@ function buildLocalInfo() {
|
||||
const publicIds = publicRoverIdSet(publicRoster);
|
||||
const roster = publicRoster.map((rover) => (lockdown ? rover : addRoverSnapshotLinks(rover)));
|
||||
const users = filterPublicUsers(Array.from(io.sockets.sockets.values()).map(buildUserEntry), publicIds);
|
||||
const turnQueues = getTurnQueues();
|
||||
const activeDrivers = getActiveDrivers();
|
||||
const roomCameras = lockdown || !features.roomCameras ? [] : getRoomCameras().map(buildRoomCameraInfo);
|
||||
return {
|
||||
instance: {
|
||||
@@ -212,8 +199,12 @@ function buildLocalInfo() {
|
||||
features,
|
||||
updatedAt: Date.now(),
|
||||
},
|
||||
roster,
|
||||
turnQueues: filterPublicTurnQueues(getTurnQueues(), publicIds),
|
||||
// Only public roster entries reach the builder; queue metadata follows the
|
||||
// same visibility boundary instead of creating separate orphan queue rows.
|
||||
roster: roster.map((rover) => ({
|
||||
...rover,
|
||||
turn: buildRoverTurn({ rover, mode, socketId: null, turnInfo: turnQueues[rover.id], activeDriverId: activeDrivers[rover.id], users }),
|
||||
})),
|
||||
users,
|
||||
roomCameras,
|
||||
socials: features.socials ? getConfiguredSocials(config) : [],
|
||||
@@ -349,7 +340,6 @@ function normalizeRemotePayload(entry, payload) {
|
||||
features: instance.features && typeof instance.features === 'object' ? instance.features : {},
|
||||
},
|
||||
roster: Array.isArray(payload?.roster) ? payload.roster : [],
|
||||
turnQueues: payload?.turnQueues && typeof payload.turnQueues === 'object' ? payload.turnQueues : {},
|
||||
users: Array.isArray(payload?.users) ? payload.users : [],
|
||||
roomCameras: Array.isArray(payload?.roomCameras) ? payload.roomCameras : [],
|
||||
socials: Array.isArray(payload?.socials) ? payload.socials : [],
|
||||
@@ -419,7 +409,6 @@ function markOffline(entry, error) {
|
||||
publicUrl: previous.instance?.publicUrl || entry.url,
|
||||
},
|
||||
roster: previous.roster || [],
|
||||
turnQueues: previous.turnQueues || {},
|
||||
users: previous.users || [],
|
||||
roomCameras: previous.roomCameras || [],
|
||||
socials: previous.socials || [],
|
||||
|
||||
@@ -370,11 +370,6 @@ function createSnapshotEngine(deps) {
|
||||
.filter((entry) => {
|
||||
const roverId = entry?.roverId ? String(entry.roverId) : null;
|
||||
if (!roverId) return true;
|
||||
/*
|
||||
This is a chat transcript filter, not a physical-rover filter. PTZ
|
||||
chat intentionally carries a rover-like id so transcript consumers can
|
||||
render it consistently, even though roverManager cannot replay that id.
|
||||
*/
|
||||
return isPublicChatTargetId(roverId);
|
||||
});
|
||||
const chatRecent = allRecentMessages
|
||||
@@ -430,6 +425,8 @@ function createSnapshotEngine(deps) {
|
||||
type: 'chat',
|
||||
nickname: entry.nickname || entry.socketId?.slice(0, 6) || 'unknown',
|
||||
text: entry.text || '',
|
||||
operating_mode: entry.operatingMode || null,
|
||||
operating_mode_name: entry.operatingModeDisplay?.name || null,
|
||||
rover_id: roverId,
|
||||
rover_ctx: { ...baseCtx, ...storedCtx },
|
||||
};
|
||||
|
||||
@@ -20,6 +20,7 @@ function normalizeAdditionalHosts(rawHosts) {
|
||||
|
||||
function buildMediaMtxConfig({ config, serverPort, snapshotWriterPath }) {
|
||||
const media = config?.media || {};
|
||||
const webrtcPort = media.webrtcPort ?? 8189;
|
||||
const configuredHosts = normalizeAdditionalHosts(media.additionalHosts);
|
||||
let publicHostname = '';
|
||||
try {
|
||||
@@ -55,10 +56,10 @@ function buildMediaMtxConfig({ config, serverPort, snapshotWriterPath }) {
|
||||
|
||||
webrtc: true,
|
||||
// WHEP and WHIP signaling is public only through the Node /video proxy.
|
||||
// ICE transport on 8189 remains directly reachable by browsers.
|
||||
// The configured ICE transport port remains directly reachable by browsers.
|
||||
webrtcAddress: '127.0.0.1:8889',
|
||||
webrtcLocalUDPAddress: ':8189',
|
||||
webrtcLocalTCPAddress: ':8189',
|
||||
webrtcLocalUDPAddress: `:${webrtcPort}`,
|
||||
webrtcLocalTCPAddress: `:${webrtcPort}`,
|
||||
webrtcAdditionalHosts: additionalHosts,
|
||||
webrtcICEServers2: [
|
||||
{ url: 'stun:stun.l.google.com:19302' },
|
||||
@@ -81,6 +82,7 @@ function buildMediaMtxConfig({ config, serverPort, snapshotWriterPath }) {
|
||||
{ action: 'pprof' },
|
||||
],
|
||||
paths: {
|
||||
'~^room-audio/': { source: 'publisher' },
|
||||
all: {
|
||||
source: 'publisher',
|
||||
sourceOnDemand: false,
|
||||
|
||||
@@ -1,18 +1,24 @@
|
||||
// Media Transport Configuration
|
||||
// Purpose: Defines additional MediaMTX ICE hosts not already derived from the server's public URL.
|
||||
// Purpose: Defines the WebRTC media port and additional ICE hosts.
|
||||
// Scope: Contains configuration metadata only and never starts MediaMTX.
|
||||
const { strictObject, stringArray } = require('../../configuration/schemaHelpers');
|
||||
const { strictObject, stringArray, integer } = require('../../configuration/schemaHelpers');
|
||||
|
||||
module.exports = {
|
||||
key: 'media',
|
||||
defaultValue: {
|
||||
webrtcPort: 8189,
|
||||
additionalHosts: [],
|
||||
},
|
||||
schema: strictObject({
|
||||
webrtcPort: integer({
|
||||
title: 'WebRTC port',
|
||||
description: 'UDP and TCP port for live media. Forward the same external port to this server; HTTPS signaling continues through the web UI.',
|
||||
minimum: 1, maximum: 65535,
|
||||
}),
|
||||
additionalHosts: stringArray({
|
||||
title: 'Additional ICE hosts',
|
||||
item: { description: 'Hostname or IP address MediaMTX advertises as a WebRTC ICE candidate.', examples: ['rover.example.com', 'media-server.local'], minLength: 1, maxLength: 255 },
|
||||
array: { description: 'Extra public or LAN hostnames and addresses browsers may use in addition to the hostname derived from the top-level public URL.', uniqueItems: true },
|
||||
}),
|
||||
}, { title: 'Media', description: 'Adds optional WebRTC network candidates to the public hostname and local interfaces generated automatically for MediaMTX.', required: ['additionalHosts'] }),
|
||||
}, { title: 'Media', description: 'Configures the WebRTC media port and additional network candidates.', required: ['webrtcPort', 'additionalHosts'] }),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
const EventEmitter = require('events');
|
||||
|
||||
const operatingModeEvents = new EventEmitter();
|
||||
const transitions = new WeakMap();
|
||||
|
||||
function getOperatingMode(socket) {
|
||||
// Handshake intent reserves the mode before role-driven assignment runs.
|
||||
// It grants no camera permissions; entry still checks access and readiness.
|
||||
return socket?.data?.operatingMode
|
||||
|| (socket?.handshake?.auth?.operatingMode === 'ptz' ? 'ptz' : 'rover');
|
||||
}
|
||||
|
||||
async function transition(socket, operatingMode) {
|
||||
// Resolve services at the action boundary to avoid a dependency cycle with
|
||||
// assignment and camera policy, which both read operating mode.
|
||||
const assignment = require('../assignmentService');
|
||||
const roverManager = require('../roverManager');
|
||||
const ptz = require('../ptzCameraService');
|
||||
if (operatingMode === 'rover' && getOperatingMode(socket) === 'rover') {
|
||||
return { operatingMode, state: ptz.getPublicState(socket) };
|
||||
}
|
||||
if (operatingMode === 'ptz') {
|
||||
await ptz.prepareParticipation(socket);
|
||||
if (socket.disconnected) throw new Error('Session disconnected');
|
||||
ptz.checkParticipationAccess(socket);
|
||||
const leave = roverManager.canLeaveCurrentRover(socket);
|
||||
if (!leave.ok) throw new Error(leave.message);
|
||||
|
||||
// Block new rover ownership before release events notify other services.
|
||||
socket.data.operatingMode = 'ptz';
|
||||
assignment.releaseForOperatingMode(socket);
|
||||
socket.data.ptzEntered = true;
|
||||
} else {
|
||||
ptz.releaseTurn(socket);
|
||||
socket.data.ptzEntered = false;
|
||||
socket.data.operatingMode = 'rover';
|
||||
assignment.resumeAssignment(socket);
|
||||
}
|
||||
operatingModeEvents.emit('change', { socket, operatingMode });
|
||||
return { operatingMode, state: ptz.getPublicState(socket) };
|
||||
}
|
||||
|
||||
function enqueueTransition(socket, action) {
|
||||
// Camera initialization can yield. Serialize switches and turn release per
|
||||
// socket so a late entry cannot undo a subsequent exit or release request.
|
||||
const previous = transitions.get(socket) || Promise.resolve();
|
||||
const next = previous.catch(() => {}).then(() => {
|
||||
if (socket.disconnected) throw new Error('Session disconnected');
|
||||
return action();
|
||||
});
|
||||
transitions.set(socket, next);
|
||||
return next;
|
||||
}
|
||||
|
||||
function setOperatingMode(socket, operatingMode) {
|
||||
if (!['rover', 'ptz'].includes(operatingMode)) {
|
||||
return Promise.reject(new Error('Invalid operating mode'));
|
||||
}
|
||||
return enqueueTransition(socket, () => transition(socket, operatingMode));
|
||||
}
|
||||
|
||||
function runPtzTurnAction(socket, action) {
|
||||
return enqueueTransition(socket, () => {
|
||||
const ptz = require('../ptzCameraService');
|
||||
if (action === 'release') return ptz.releaseTurn(socket);
|
||||
if (action !== 'request') throw new Error('Invalid PTZ turn action');
|
||||
if (getOperatingMode(socket) !== 'ptz' || !socket.data.ptzEntered) {
|
||||
throw new Error('Enter PTZ before requesting a turn');
|
||||
}
|
||||
return ptz.claimTurn(socket);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { getOperatingMode, setOperatingMode, runPtzTurnAction, operatingModeEvents };
|
||||
@@ -400,6 +400,7 @@ function createOvercurrentProtectionService(options = {}) {
|
||||
type: 'drive',
|
||||
driveDirect: { left: 0, right: 0 },
|
||||
});
|
||||
issueAdjustedCommand(roverId, { type: 'song', song: { notes: [{ note: 76, duration: 8 }, { note: 72, duration: 8 }, { note: 67, duration: 16 }] } });
|
||||
logger.warn('Stopped rover after persistent wheel overcurrent', {
|
||||
roverId,
|
||||
motor: stalledWheel,
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
const { evaluateTools } = require('./tools');
|
||||
|
||||
function formatTimeContext(timestamp, now) {
|
||||
const at = Number(timestamp);
|
||||
if (!Number.isFinite(at) || at <= 0) return 'time=unknown';
|
||||
return `at=${new Date(at).toISOString()} age_seconds=${Math.max(0, Math.floor((now - at) / 1000))}`;
|
||||
}
|
||||
|
||||
function normalizeNeatoIssue(value) {
|
||||
const raw = String(value || '').trim();
|
||||
if (!raw) return 'none';
|
||||
@@ -7,12 +13,21 @@ function normalizeNeatoIssue(value) {
|
||||
return raw;
|
||||
}
|
||||
|
||||
function toStateUpdate({ mode, homeAssistantState, neatoState, liftState, roster, triggerReason }) {
|
||||
function toStateUpdate({ mode, homeAssistantState, activityState, neatoState, liftState, roster, triggerReason, timezone, now = Date.now(), previousRunAt }) {
|
||||
const lines = [];
|
||||
lines.push(`current_time: ${new Date(now).toISOString()}`);
|
||||
lines.push(`local_time: ${new Date(now).toLocaleString('en-US', { timeZone: timezone, hour12: false })} timezone=${timezone}`);
|
||||
lines.push(`previous_run: ${formatTimeContext(previousRunAt, now)}`);
|
||||
lines.push(`trigger: ${triggerReason || 'heartbeat'}`);
|
||||
lines.push(`mode: ${mode || 'unknown'}`);
|
||||
lines.push(`home_assistant_connected: ${homeAssistantState?.connected ? 'yes' : 'no'}`);
|
||||
lines.push(`lights_locked_on: ${homeAssistantState?.lightPolicy?.lockedOn ? 'yes' : 'no'}`);
|
||||
lines.push(`activity_controls: enabled=${activityState?.enabled ? 'yes' : 'no'} connected=${activityState?.connected ? 'yes' : 'no'}`);
|
||||
for (const item of activityState?.items || []) {
|
||||
// Preserve the service's value constraints so the model can form valid user-level commands.
|
||||
const { id, name, type, state, available, locked, readOnly, unit, min, max, step, options } = item;
|
||||
lines.push(`activity_item: ${JSON.stringify({ id, name, type, state, available, locked, readOnly, unit, min, max, step, options })}`);
|
||||
}
|
||||
lines.push(`lift: ${liftState?.connected ? 'connected' : 'offline'} busy=${liftState?.busy ? 'yes' : 'no'}`);
|
||||
const neatoError = normalizeNeatoIssue(neatoState?.telemetry?.robotError);
|
||||
const neatoAlert = normalizeNeatoIssue(neatoState?.telemetry?.robotAlert);
|
||||
@@ -56,8 +71,8 @@ function toStateUpdate({ mode, homeAssistantState, neatoState, liftState, roster
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function buildToolState({ mode, homeAssistantState, neatoState, liftState }) {
|
||||
return evaluateTools({ mode, homeAssistantState, neatoState, liftState });
|
||||
function buildToolState({ mode, homeAssistantState, activityState, neatoState, liftState }) {
|
||||
return evaluateTools({ mode, homeAssistantState, activityState, neatoState, liftState });
|
||||
}
|
||||
|
||||
function formatToolResultMessages(toolCalls) {
|
||||
@@ -88,7 +103,7 @@ function formatToolResultMessages(toolCalls) {
|
||||
return [{ role: 'system', content: ['TOOL_RESULT', ...lines].join('\n') }];
|
||||
}
|
||||
|
||||
function buildConversation({ recentMessages, name }) {
|
||||
function buildConversation({ recentMessages, name, now = Date.now() }) {
|
||||
const messages = [];
|
||||
(recentMessages || []).forEach((entry) => {
|
||||
const text = String(entry?.text || '').trim();
|
||||
@@ -97,12 +112,13 @@ function buildConversation({ recentMessages, name }) {
|
||||
|
||||
const isAssistant = Boolean(entry?.bot);
|
||||
const nickname = String(entry?.nickname || (isAssistant ? name || 'Overseer' : 'user')).trim();
|
||||
const timing = `[${formatTimeContext(entry?.ts, now)}]`;
|
||||
if (isAssistant) {
|
||||
if (text) messages.push({ role: 'assistant', content: text });
|
||||
messages.push(...toolResultMessages);
|
||||
if (text) messages.push({ role: 'assistant', content: `${timing} ${text}` });
|
||||
messages.push(...toolResultMessages.map((message) => ({ ...message, content: `${message.content}\nmessage_time: ${timing}` })));
|
||||
return;
|
||||
}
|
||||
if (text) messages.push({ role: 'user', content: `${nickname}: ${text}` });
|
||||
if (text) messages.push({ role: 'user', content: `${timing} ${nickname}: ${text}` });
|
||||
});
|
||||
return messages;
|
||||
}
|
||||
@@ -143,6 +159,7 @@ function buildModelMessages({
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
formatTimeContext,
|
||||
toStateUpdate,
|
||||
buildToolState,
|
||||
buildConversation,
|
||||
|
||||
@@ -7,6 +7,7 @@ const { getRole, roleEvents } = require('../roleService');
|
||||
const { getMode, MODES, modeEvents } = require('../modeManager');
|
||||
const { verificationEvents } = require('../verificationService');
|
||||
const homeAssistantService = require('../homeAssistantService');
|
||||
const activityControls = require('../homeAssistantActivitiesService');
|
||||
const neatoService = require('../neatoService');
|
||||
const liftService = require('../liftService');
|
||||
const buttonBoxService = require('../buttonBoxService');
|
||||
@@ -27,7 +28,7 @@ const {
|
||||
normalizeMs,
|
||||
} = require('./constants');
|
||||
const { isAdminRole, buildAdminState, buildFailureInfo } = require('./runtimeHelpers');
|
||||
const { toStateUpdate, buildToolState, buildConversation, buildModelMessages } = require('./contextBuilder');
|
||||
const { toStateUpdate, buildToolState, buildConversation, buildModelMessages, formatTimeContext } = require('./contextBuilder');
|
||||
const { buildOllamaTools, executeToolAction } = require('./tools');
|
||||
const { loadMemory, saveMemory, createDefaultMemory, summarizeMemory } = require('./memoryStore');
|
||||
|
||||
@@ -91,6 +92,7 @@ const runtime = {
|
||||
runHistory: [],
|
||||
liveToolCalls: [],
|
||||
pendingDirectAddressRun: false,
|
||||
lastDecisionAt: null,
|
||||
memoryStore: loadMemory(),
|
||||
contextResetAt: Date.now(),
|
||||
};
|
||||
@@ -365,7 +367,7 @@ function buildToolCallFeedEntries(requestedActions = [], actionResults = []) {
|
||||
});
|
||||
}
|
||||
|
||||
function buildRecentEventsSummary() {
|
||||
function buildRecentEventsSummary(now) {
|
||||
const events = (runtime.liveToolCalls || [])
|
||||
.filter((entry) => entry && (entry.phase === 'ok' || entry.phase === 'error' || entry.phase === 'blocked'))
|
||||
.slice(-3)
|
||||
@@ -373,45 +375,50 @@ function buildRecentEventsSummary() {
|
||||
const tool = String(entry.tool || 'unknown');
|
||||
const phase = String(entry.phase || 'unknown');
|
||||
const err = entry.error ? ` error=${String(entry.error).slice(0, 60)}` : '';
|
||||
return `- tool=${tool} phase=${phase}${err}`;
|
||||
return `- ${formatTimeContext(entry.at, now)} tool=${tool} phase=${phase}${err}`;
|
||||
});
|
||||
if (!events.length) return '- none';
|
||||
return events.join('\n');
|
||||
}
|
||||
|
||||
async function runDecision(triggerReason) {
|
||||
// Use one reference time so all ages in this model request agree.
|
||||
const now = Date.now();
|
||||
const previousRunAt = runtime.lastDecisionAt;
|
||||
runtime.lastDecisionAt = now;
|
||||
const runId = runtime.tickCount;
|
||||
updateStatus({ phase: 'context_build', currentRunId: runId, lastTriggerReason: triggerReason, lastError: null, lastErrorDetails: null });
|
||||
|
||||
const mode = getMode();
|
||||
const homeAssistantState = getHomeAssistantState();
|
||||
const activityState = activityControls.getState();
|
||||
const neatoState = getNeatoState();
|
||||
const liftState = getLiftState();
|
||||
const roster = buildRosterSummary();
|
||||
|
||||
const stateUpdate = toStateUpdate({ mode, homeAssistantState, neatoState, liftState, roster, triggerReason });
|
||||
const toolState = buildToolState({ mode, homeAssistantState, neatoState, liftState });
|
||||
const stateUpdate = toStateUpdate({ mode, homeAssistantState, activityState, neatoState, liftState, roster, triggerReason, timezone: loadConfig().timezone, now, previousRunAt });
|
||||
const toolState = buildToolState({ mode, homeAssistantState, activityState, neatoState, liftState });
|
||||
|
||||
let chatCount = 0;
|
||||
let botCount = 0;
|
||||
const recentConversation = getRecentMessages(MAX_CHAT_CONTEXT + MAX_BOT_CONTEXT + 20, { includeSystem: true })
|
||||
.filter((entry) => Number(entry?.ts || 0) >= runtime.contextResetAt)
|
||||
.filter((entry) => {
|
||||
if (!entry?.roverId) return true;
|
||||
/*
|
||||
Chat context should preserve every public chat target, including the
|
||||
PTZ virtual rover. Rover replay visibility alone would drop PTZ because
|
||||
it is owned by ptzCameraService instead of roverManager.
|
||||
*/
|
||||
return isPublicChatTargetId(entry.roverId);
|
||||
})
|
||||
.slice(-(MAX_CHAT_CONTEXT + MAX_BOT_CONTEXT));
|
||||
const conversationMessages = buildConversation({ recentMessages: recentConversation, name });
|
||||
// Select newest entries within each budget, then restore chronological order.
|
||||
.reverse()
|
||||
.filter((entry) => entry?.bot ? ++botCount <= MAX_BOT_CONTEXT : ++chatCount <= MAX_CHAT_CONTEXT)
|
||||
.reverse();
|
||||
const conversationMessages = buildConversation({ recentMessages: recentConversation, name, now });
|
||||
|
||||
const systemPrompt = await readPrompt();
|
||||
const modelMessages = buildModelMessages({
|
||||
systemPrompt,
|
||||
stateUpdate,
|
||||
memorySummary: summarizeMemory(runtime.memoryStore),
|
||||
recentEvents: buildRecentEventsSummary(),
|
||||
recentEvents: buildRecentEventsSummary(now),
|
||||
conversationMessages,
|
||||
availableTools: toolState.available,
|
||||
blockedTools: toolState.blocked,
|
||||
@@ -685,6 +692,7 @@ function clearHistory(reason = 'admin requested clear history', options = {}) {
|
||||
runtime.contextResetAt = Date.now();
|
||||
runtime.runHistory = [];
|
||||
runtime.liveToolCalls = [];
|
||||
runtime.lastDecisionAt = null;
|
||||
runtime.generationCount = 0;
|
||||
runtime.generationTotalMs = 0;
|
||||
if (resetPersistentMemory) {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
const activityControls = require('../../homeAssistantActivitiesService');
|
||||
const { getMode } = require('../../modeManager');
|
||||
|
||||
module.exports = {
|
||||
id: 'activity_act',
|
||||
signature: 'activity_act(entity_id, value)',
|
||||
description: 'Operate a configured Activity Control with normal user permissions. Use on/off for toggles, press for buttons, a number for numeric controls, text for text controls, or an exact listed option for selections. Locked and read-only items cannot be changed.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
entity_id: { type: 'string', minLength: 1 },
|
||||
value: { type: ['string', 'number'] },
|
||||
},
|
||||
required: ['entity_id', 'value'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
availability(ctx = {}) {
|
||||
if (ctx.mode === 'admin' || ctx.mode === 'lockdown') {
|
||||
return { available: false, reason: `policy_lock:site_mode_${ctx.mode}` };
|
||||
}
|
||||
if (!ctx.activityState?.enabled || !ctx.activityState?.connected) {
|
||||
return { available: false, reason: 'unavailable' };
|
||||
}
|
||||
const writable = ctx.activityState.items?.some((item) => item.available && !item.locked && !item.readOnly && item.type !== 'readOnly');
|
||||
return { available: Boolean(writable), reason: writable ? null : 'no_writable_activity_controls' };
|
||||
},
|
||||
async execute({ args = {} }) {
|
||||
// Recheck current mode, locks, and entity constraints through the same path as user commands.
|
||||
await activityControls.act(args.entity_id, args.value, { role: 'user', mode: getMode() });
|
||||
return { ok: true };
|
||||
},
|
||||
};
|
||||
@@ -12,6 +12,7 @@ const neatoClearErrors = require('./neatoClearErrors');
|
||||
const haSetEntity = require('./haSetEntity');
|
||||
const haSetLightColor = require('./haSetLightColor');
|
||||
const buttonBoxAddCount = require('./buttonBoxAddCount');
|
||||
const activityAct = require('./activityAct');
|
||||
|
||||
const TOOL_DEFINITIONS = [
|
||||
memoryRead,
|
||||
@@ -28,6 +29,7 @@ const TOOL_DEFINITIONS = [
|
||||
haSetEntity,
|
||||
haSetLightColor,
|
||||
buttonBoxAddCount,
|
||||
activityAct,
|
||||
];
|
||||
const TOOL_BY_ID = new Map(TOOL_DEFINITIONS.map((tool) => [tool.id, tool]));
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
// Purpose: Generates server-side TTS files and sends them to the Reolink TrackMix speaker through neolink.
|
||||
// Scope: Owns file/cache/process details for PTZ speech only; PTZ ownership, chat identity, and camera motion stay in index.js.
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const fsp = require('fs/promises');
|
||||
const path = require('path');
|
||||
const { spawn } = require('child_process');
|
||||
@@ -78,6 +77,7 @@ function createPtzAudioPlayback(deps) {
|
||||
const volume = clampNumber(audioConfig.volume, DEFAULT_VOLUME, 0, 4);
|
||||
const fliteDefaultVoice = String(audioConfig.fliteDefaultVoice || 'kal').trim();
|
||||
|
||||
let disposed = false;
|
||||
let playbackProc = null;
|
||||
let playbackSeq = 0;
|
||||
|
||||
@@ -244,12 +244,16 @@ function createPtzAudioPlayback(deps) {
|
||||
}, 1200);
|
||||
}
|
||||
|
||||
async function playFile(filePath, context = {}) {
|
||||
if (!audioEnabled) throw new Error('PTZ audio disabled');
|
||||
async function playFile(filePath, context = {}, authorize = () => {}) {
|
||||
if (disposed || !audioEnabled) throw new Error('PTZ audio unavailable');
|
||||
authorize();
|
||||
const neolinkConfigPath = await ensureNeolinkConfig();
|
||||
const stat = await fsp.stat(filePath);
|
||||
if (!stat.isFile()) throw new Error(`PTZ TTS file is not a regular file: ${filePath}`);
|
||||
|
||||
// Rendering and config IO may outlive a turn or camera configuration.
|
||||
if (disposed) throw new Error('PTZ audio configuration changed');
|
||||
authorize();
|
||||
stopActivePlayback('new-playback');
|
||||
const seq = ++playbackSeq;
|
||||
const args = [
|
||||
@@ -302,13 +306,13 @@ function createPtzAudioPlayback(deps) {
|
||||
return { pid: proc.pid || null, seq };
|
||||
}
|
||||
|
||||
async function speakText(text, ttsOptions = {}, context = {}) {
|
||||
async function speakText(text, ttsOptions = {}, context = {}, authorize = () => {}) {
|
||||
const rendered = await ensureTtsFile(text, ttsOptions);
|
||||
await playFile(rendered.filePath, {
|
||||
...context,
|
||||
engine: rendered.engine,
|
||||
cached: rendered.cached,
|
||||
});
|
||||
}, authorize);
|
||||
return rendered;
|
||||
}
|
||||
|
||||
@@ -316,6 +320,10 @@ function createPtzAudioPlayback(deps) {
|
||||
getState,
|
||||
speakText,
|
||||
stopActivePlayback,
|
||||
dispose: () => {
|
||||
disposed = true;
|
||||
stopActivePlayback('configuration-change');
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,98 @@
|
||||
// Owns PTZ turns only. Camera IO, permissions and operating-mode entry are supplied
|
||||
// by the service, so queue transitions cannot create physical rover ownership.
|
||||
function createParticipation({ io, events, emitChange, getTurnDurationMs, canParticipate, stopMotion, revokeVideo }) {
|
||||
const state = { operatorSocketId: null, queue: [], deadline: null, generation: 0 };
|
||||
let timer = null;
|
||||
|
||||
function remove(socketId) {
|
||||
state.queue = state.queue.filter((id) => id !== socketId);
|
||||
}
|
||||
|
||||
function stopOperator(reason) {
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
const previous = state.operatorSocketId;
|
||||
state.operatorSocketId = null;
|
||||
state.deadline = null;
|
||||
state.generation += 1;
|
||||
if (!previous) return;
|
||||
revokeVideo(previous);
|
||||
stopMotion(reason).catch(() => {});
|
||||
events.emit('operator', { socketId: previous, action: 'release', reason });
|
||||
}
|
||||
|
||||
function scheduleTurn() {
|
||||
// Uncontested control has no deadline. Starting a new wait gets a full turn,
|
||||
// while later queue changes must not reset an already running countdown.
|
||||
if (!state.operatorSocketId || !state.queue.length) {
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
state.deadline = null;
|
||||
return;
|
||||
}
|
||||
if (timer) return;
|
||||
const duration = getTurnDurationMs();
|
||||
state.deadline = Date.now() + duration;
|
||||
timer = setTimeout(() => {
|
||||
timer = null;
|
||||
state.queue = state.queue.filter(eligible);
|
||||
if (state.queue.length) {
|
||||
// Preserve PTZ's explicit request-to-rejoin rule after a handoff.
|
||||
stopOperator('turn-expired');
|
||||
advance('turn-expired');
|
||||
} else {
|
||||
scheduleTurn();
|
||||
emitChange('turn-uncontested');
|
||||
}
|
||||
}, duration);
|
||||
}
|
||||
|
||||
function eligible(socketId) {
|
||||
const socket = io.sockets.sockets.get(socketId);
|
||||
return socket && !socket.disconnected && canParticipate(socket);
|
||||
}
|
||||
|
||||
function advance(reason) {
|
||||
state.queue = state.queue.filter(eligible);
|
||||
while (!state.operatorSocketId && state.queue.length) {
|
||||
const next = state.queue.shift();
|
||||
if (!eligible(next)) continue;
|
||||
state.operatorSocketId = next;
|
||||
state.generation += 1;
|
||||
events.emit('operator', { socketId: next, action: 'active' });
|
||||
}
|
||||
scheduleTurn();
|
||||
emitChange(reason);
|
||||
}
|
||||
|
||||
function claim(socket) {
|
||||
if (!eligible(socket.id)) throw new Error('PTZ participation required');
|
||||
if (state.operatorSocketId === socket.id || state.queue.includes(socket.id)) return;
|
||||
state.queue.push(socket.id);
|
||||
advance('queue-join');
|
||||
}
|
||||
|
||||
function release(socketId, reason = 'turn-release') {
|
||||
remove(socketId);
|
||||
if (state.operatorSocketId === socketId) stopOperator(reason);
|
||||
advance(reason);
|
||||
}
|
||||
|
||||
function reconcile() {
|
||||
state.queue = state.queue.filter(eligible);
|
||||
if (state.operatorSocketId && !eligible(state.operatorSocketId)) stopOperator('access-change');
|
||||
advance('access-change');
|
||||
}
|
||||
|
||||
function clear(reason) {
|
||||
state.queue = [];
|
||||
stopOperator(reason);
|
||||
}
|
||||
|
||||
return {
|
||||
state, claim, release, reconcile, clear,
|
||||
revoke: (reason) => { stopOperator(reason); advance(reason); },
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createParticipation };
|
||||
@@ -0,0 +1,123 @@
|
||||
// Socket transport delegates policy and lifecycle decisions to the PTZ service.
|
||||
function registerSocketGateway(deps) {
|
||||
const { io, isAdmin, participation, emitChange, normalizeSocketArgs,
|
||||
runPtzTurnAction, acceptMotionIntent, getStatus, setSpotlight, setIr,
|
||||
listPresets, gotoPreset, createPreset, removePreset, passesMode,
|
||||
normalizeSnapshotIds, addSnapshotSubscription, sendSnapshotFrame,
|
||||
getSnapshot, removeSnapshotSubscriptions } = deps;
|
||||
io.on('connection', (socket) => {
|
||||
socket.on('ptzCamera:revokeOperator', (firstArg, secondArg) => {
|
||||
const { cb } = normalizeSocketArgs(firstArg, secondArg);
|
||||
if (!isAdmin(socket)) return cb({ error: 'Admin required' });
|
||||
participation.revoke('admin-revoke');
|
||||
cb({ ok: true });
|
||||
});
|
||||
socket.on('ptzCamera:requestTurn', async (firstArg, secondArg) => {
|
||||
const { cb } = normalizeSocketArgs(firstArg, secondArg);
|
||||
try { cb({ ok: true, state: await runPtzTurnAction(socket, 'request') }); }
|
||||
catch (err) { cb({ error: err.message }); }
|
||||
});
|
||||
socket.on('ptzCamera:release', async (firstArg, secondArg) => {
|
||||
const { cb } = normalizeSocketArgs(firstArg, secondArg);
|
||||
try {
|
||||
cb({ ok: true, state: await runPtzTurnAction(socket, 'release') });
|
||||
} catch (err) {
|
||||
cb({ error: err.message });
|
||||
}
|
||||
});
|
||||
socket.on('ptzCamera:motion', (firstArg, secondArg) => {
|
||||
const { payload, cb } = normalizeSocketArgs(firstArg, secondArg);
|
||||
try {
|
||||
/*
|
||||
Acknowledge acceptance of the newest desired state immediately. The
|
||||
serialized ONVIF pump deliberately runs independently of Socket.IO
|
||||
request latency so browser heartbeats cannot accumulate while waiting
|
||||
for a camera SOAP response.
|
||||
*/
|
||||
cb(acceptMotionIntent(socket, payload));
|
||||
} catch (err) {
|
||||
cb({ error: err.message });
|
||||
}
|
||||
});
|
||||
socket.on('ptzCamera:status', async (firstArg, secondArg) => {
|
||||
const { cb } = normalizeSocketArgs(firstArg, secondArg);
|
||||
try {
|
||||
cb({ ok: true, status: await getStatus(socket) });
|
||||
} catch (err) {
|
||||
cb({ error: err.message });
|
||||
}
|
||||
});
|
||||
socket.on('ptzCamera:spotlight', async (firstArg, secondArg) => {
|
||||
const { payload, cb } = normalizeSocketArgs(firstArg, secondArg);
|
||||
try {
|
||||
cb({ ok: true, light: await setSpotlight(socket, payload) });
|
||||
} catch (err) {
|
||||
cb({ error: err.message });
|
||||
}
|
||||
});
|
||||
socket.on('ptzCamera:ir', async (firstArg, secondArg) => {
|
||||
const { payload, cb } = normalizeSocketArgs(firstArg, secondArg);
|
||||
try {
|
||||
cb({ ok: true, ir: await setIr(socket, payload) });
|
||||
} catch (err) {
|
||||
cb({ error: err.message });
|
||||
}
|
||||
});
|
||||
socket.on('ptzCamera:presets:list', async (firstArg, secondArg) => {
|
||||
const { cb } = normalizeSocketArgs(firstArg, secondArg);
|
||||
try {
|
||||
cb({ ok: true, presets: await listPresets(socket) });
|
||||
} catch (err) {
|
||||
cb({ error: err.message });
|
||||
}
|
||||
});
|
||||
socket.on('ptzCamera:preset:goto', async (firstArg, secondArg) => {
|
||||
const { payload, cb } = normalizeSocketArgs(firstArg, secondArg);
|
||||
try {
|
||||
cb(await gotoPreset(socket, payload));
|
||||
} catch (err) {
|
||||
cb({ error: err.message });
|
||||
}
|
||||
});
|
||||
socket.on('ptzCamera:preset:create', async (firstArg, secondArg) => {
|
||||
const { payload, cb } = normalizeSocketArgs(firstArg, secondArg);
|
||||
try {
|
||||
cb(await createPreset(socket, payload));
|
||||
} catch (err) {
|
||||
cb({ error: err.message });
|
||||
}
|
||||
});
|
||||
socket.on('ptzCamera:preset:remove', async (firstArg, secondArg) => {
|
||||
const { payload, cb } = normalizeSocketArgs(firstArg, secondArg);
|
||||
try {
|
||||
cb(await removePreset(socket, payload));
|
||||
} catch (err) {
|
||||
cb({ error: err.message });
|
||||
}
|
||||
});
|
||||
socket.on('ptzCamera:snapshotSubscribe', (firstArg, secondArg) => {
|
||||
const { payload, cb } = normalizeSocketArgs(firstArg, secondArg);
|
||||
try {
|
||||
if (!passesMode(socket)) throw new Error('Not authorized for PTZ snapshots');
|
||||
const ids = normalizeSnapshotIds(payload);
|
||||
addSnapshotSubscription(socket, ids);
|
||||
const lastSnapshotState = getSnapshot();
|
||||
if (lastSnapshotState?.frame) sendSnapshotFrame(socket, lastSnapshotState.frame, lastSnapshotState.ts);
|
||||
cb({ ok: true, subscribed: ids });
|
||||
} catch (err) {
|
||||
cb({ error: err.message });
|
||||
}
|
||||
});
|
||||
socket.on('ptzCamera:snapshotUnsubscribe', (firstArg, secondArg) => {
|
||||
const { payload } = normalizeSocketArgs(firstArg, secondArg);
|
||||
removeSnapshotSubscriptions(socket.id, normalizeSnapshotIds(payload));
|
||||
});
|
||||
socket.on('disconnect', () => {
|
||||
participation.release(socket.id, 'disconnect');
|
||||
removeSnapshotSubscriptions(socket.id);
|
||||
emitChange('disconnect');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { registerSocketGateway };
|
||||
@@ -0,0 +1,9 @@
|
||||
const labels = {
|
||||
...require('../turnService/labels'),
|
||||
waiting: 'Someone else has control',
|
||||
active: 'You control the camera',
|
||||
showName: 'Show camera name',
|
||||
hideName: 'Hide camera name',
|
||||
};
|
||||
|
||||
module.exports = labels;
|
||||
@@ -35,9 +35,9 @@ async function deliverReplay(payload = {}) {
|
||||
requestedBy: payload.requestedBy,
|
||||
});
|
||||
|
||||
jobStatus.emit(job, 'accepted', { message: buildAcceptedMessage(job) });
|
||||
let providerContext = null;
|
||||
try {
|
||||
jobStatus.emit(job, 'accepted', { message: buildAcceptedMessage(job) });
|
||||
let providerError = null;
|
||||
if (preferredDeliveryProvider?.begin) {
|
||||
try {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// Purpose: Provides transport-neutral replay jobs, source lookup, status events, and user-facing progress text.
|
||||
// Scope: Keeps Discord-command and web-triggered replay delivery on the same core status pipeline.
|
||||
const Fuse = require('fuse.js');
|
||||
const { updateReplayStatus } = require('../replayEngineV2/cooldown');
|
||||
|
||||
const DEFAULT_ALLOWED_MENTIONS = { parse: [], repliedUser: false };
|
||||
const FUZZY_THRESHOLD = 0.42;
|
||||
@@ -180,6 +181,22 @@ function createJobStatusEmitter({ io, logger, sanitizeMentions }) {
|
||||
|
||||
function emit(job, status, extra = {}) {
|
||||
const payload = buildPayload(job, status, extra);
|
||||
updateReplayStatus(payload);
|
||||
if (status === 'accepted') {
|
||||
// Sound once per participating rover; a disconnected rover must not abort video creation.
|
||||
const { issueCommand } = require('../commandService');
|
||||
const roverIds = new Set(job.sources.filter((entry) => entry.type === 'rover').map((entry) => entry.id));
|
||||
for (const roverId of roverIds) {
|
||||
try {
|
||||
issueCommand(roverId, {
|
||||
type: 'song',
|
||||
song: { notes: [{ note: 72, duration: 8 }, { note: 76, duration: 8 }, { note: 79, duration: 16 }] },
|
||||
});
|
||||
} catch (err) {
|
||||
logger?.warn?.('Unable to play replay tune', { roverId, error: err.message });
|
||||
}
|
||||
}
|
||||
}
|
||||
io.emit('replay:status', payload);
|
||||
if (status === 'ready' && extra.media) io.emit('replay:ready', extra.media);
|
||||
if (status === 'failed') io.emit('replay:failed', payload);
|
||||
|
||||
@@ -4,40 +4,61 @@
|
||||
const EventEmitter = require('events');
|
||||
|
||||
const COOLDOWN_MS = 10 * 1000;
|
||||
const MAX_CONCURRENT_JOBS = 3;
|
||||
const replayEvents = new EventEmitter();
|
||||
const activeJobs = new Map();
|
||||
let status = null;
|
||||
let lastTriggeredAt = null;
|
||||
let lastTriggeredBy = null;
|
||||
|
||||
function getRemainingMs(now = Date.now()) {
|
||||
if (!lastTriggeredAt) return 0;
|
||||
return Math.max(0, COOLDOWN_MS - (now - lastTriggeredAt));
|
||||
}
|
||||
|
||||
function getReplayState() {
|
||||
const remainingMs = getRemainingMs();
|
||||
const remainingMs = lastTriggeredAt === null ? 0 : Math.max(0, COOLDOWN_MS - (Date.now() - lastTriggeredAt));
|
||||
return {
|
||||
cooldownMs: COOLDOWN_MS,
|
||||
lastTriggeredAt,
|
||||
lastTriggeredBy,
|
||||
remainingMs,
|
||||
available: remainingMs === 0,
|
||||
atJobLimit: activeJobs.size >= MAX_CONCURRENT_JOBS,
|
||||
activeSourceKeys: [...new Set(Array.from(activeJobs.values()).flatMap((sources) =>
|
||||
sources.map((source) => `${source.type}:${source.id}`),
|
||||
))],
|
||||
status,
|
||||
available: remainingMs === 0 && activeJobs.size < MAX_CONCURRENT_JOBS,
|
||||
};
|
||||
}
|
||||
|
||||
function tryTriggerReplay(by = null) {
|
||||
const remainingMs = getRemainingMs();
|
||||
if (remainingMs > 0) {
|
||||
return { ok: false, remainingMs, state: getReplayState() };
|
||||
}
|
||||
lastTriggeredAt = Date.now();
|
||||
lastTriggeredBy = by || null;
|
||||
const state = getReplayState();
|
||||
replayEvents.emit('update', { state, by: lastTriggeredBy });
|
||||
return { ok: true, state };
|
||||
function emitUpdate() {
|
||||
replayEvents.emit('update', { state: getReplayState(), by: lastTriggeredBy });
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
tryTriggerReplay,
|
||||
getReplayState,
|
||||
replayEvents,
|
||||
};
|
||||
function tryTriggerReplay({ jobId, by = null } = {}) {
|
||||
const state = getReplayState();
|
||||
if (state.atJobLimit) {
|
||||
return { ok: false, error: 'Replay limit reached: 3 jobs are already being made', state };
|
||||
}
|
||||
if (state.remainingMs > 0) {
|
||||
return { ok: false, error: `Replay cooldown active. Try again in ${Math.ceil(state.remainingMs / 1000)}s.`, remainingMs: state.remainingMs, state };
|
||||
}
|
||||
if (!jobId) throw new Error('Replay job id required');
|
||||
activeJobs.set(jobId, []);
|
||||
status = { jobId, status: 'accepted' };
|
||||
lastTriggeredAt = Date.now();
|
||||
lastTriggeredBy = by;
|
||||
emitUpdate();
|
||||
return { ok: true, state: getReplayState() };
|
||||
}
|
||||
|
||||
function updateReplayStatus(payload) {
|
||||
if (!activeJobs.has(payload.jobId)) return;
|
||||
if (payload.jobId === status?.jobId) {
|
||||
status = { jobId: payload.jobId, status: payload.status, title: payload.title, message: payload.message };
|
||||
}
|
||||
if (payload.status === 'ready' || payload.status === 'failed') {
|
||||
activeJobs.delete(payload.jobId);
|
||||
} else {
|
||||
activeJobs.set(payload.jobId, payload.sources || []);
|
||||
}
|
||||
emitUpdate();
|
||||
}
|
||||
|
||||
module.exports = { tryTriggerReplay, getReplayState, replayEvents, updateReplayStatus };
|
||||
|
||||
@@ -6,6 +6,7 @@ const { promisify } = require('util');
|
||||
const fsp = require('fs/promises');
|
||||
const logger = require('../../globals/logger').child('replayEngineV2');
|
||||
const roverManager = require('../roverManager');
|
||||
const { roomAudioEvents } = require('../roomAudioService');
|
||||
const { getRoomCameras, roomCameraEvents } = require('../roomCameraService');
|
||||
|
||||
const {
|
||||
@@ -40,8 +41,8 @@ function getActiveSegmentRoot() {
|
||||
return runtime.activeSegmentRoot;
|
||||
}
|
||||
|
||||
const workerManager = createWorkerManager({ getActiveSegmentRoot });
|
||||
const segmentStore = createSegmentStore({ getActiveSegmentRoot });
|
||||
const workerManager = createWorkerManager({ getActiveSegmentRoot, onWorkerClosed: segmentStore.refreshIndexForWorker });
|
||||
const sidebarRenderer = createSidebarRenderer({ execFileAsync, ensureDir });
|
||||
const replayBuilder = createReplayBuilder({
|
||||
execFileAsync,
|
||||
@@ -50,6 +51,7 @@ const replayBuilder = createReplayBuilder({
|
||||
renderSidebarVideo: sidebarRenderer.renderSidebarVideo,
|
||||
getVideoEntriesForSource: segmentStore.getVideoEntriesForSource,
|
||||
getAudioEntriesForSource: segmentStore.getAudioEntriesForSource,
|
||||
getRoomAudioEntries: segmentStore.getRoomAudioEntries,
|
||||
overlapping: segmentStore.overlapping,
|
||||
});
|
||||
registerReplaySocketHooks({ tryTriggerReplay, validateSources, getDefaultWebSources });
|
||||
@@ -88,6 +90,10 @@ async function start() {
|
||||
}, CLEANUP_INTERVAL_MS);
|
||||
}
|
||||
|
||||
roomAudioEvents.on('update', () => {
|
||||
tick().catch((err) => logger.warn('room audio update tick failed', err.message));
|
||||
});
|
||||
|
||||
roomCameraEvents.on('update', () => {
|
||||
tick().catch((err) => logger.warn('room camera update tick failed', err.message));
|
||||
});
|
||||
|
||||
@@ -51,7 +51,7 @@ function buildChatEventsForWindow(startMs, endMs, limit = 22, preWindowCount = 1
|
||||
return [...beforeWindow, ...inWindow].sort((a, b) => a.ts - b.ts);
|
||||
}
|
||||
|
||||
function createReplayBuilder({ execFileAsync, fsp, ensureDir, renderSidebarVideo, getVideoEntriesForSource, getAudioEntriesForSource, overlapping }) {
|
||||
function createReplayBuilder({ execFileAsync, fsp, ensureDir, renderSidebarVideo, getVideoEntriesForSource, getAudioEntriesForSource, getRoomAudioEntries, overlapping }) {
|
||||
function resolveReplayWindow({ sources = [], nowMs, guardMs, durationMs }) {
|
||||
const tentativeEnd = nowMs - guardMs;
|
||||
const sourceEnds = [];
|
||||
@@ -186,6 +186,28 @@ function createReplayBuilder({ execFileAsync, fsp, ensureDir, renderSidebarVideo
|
||||
|
||||
if (!normalizedVideos.length) throw new Error('No replay segments available for selected sources');
|
||||
|
||||
const roomAudioEntries = await pinSegmentFiles(
|
||||
overlapping(getRoomAudioEntries(), tStart, tEnd), tmpDir, 'room-audio-seg',
|
||||
);
|
||||
if (roomAudioEntries.length) {
|
||||
// Place each segment at its recorded time. A mic joining late or
|
||||
// reconnecting must leave silence in the gap, not shift its speech earlier.
|
||||
const audioInputs = roomAudioEntries.flatMap((entry) => ['-i', entry.filePath]);
|
||||
const audioFilters = roomAudioEntries.map((entry, index) => {
|
||||
const start = Math.max(0, (tStart - entry.startMs) / 1000);
|
||||
const duration = (Math.min(tEnd, entry.endMs) - Math.max(tStart, entry.startMs)) / 1000;
|
||||
const delay = Math.max(0, Math.round(entry.startMs - tStart));
|
||||
return `[${index}:a]atrim=start=${start.toFixed(3)}:duration=${duration.toFixed(3)},asetpts=PTS-STARTPTS,adelay=${delay}:all=1[room${index}]`;
|
||||
});
|
||||
const refs = roomAudioEntries.map((_, index) => `[room${index}]`).join('');
|
||||
audioFilters.push(`${refs}amix=inputs=${roomAudioEntries.length}:normalize=0[roomout]`);
|
||||
const roomAudioPath = path.join(tmpDir, 'room-audio.m4a');
|
||||
await execFileAsync(FFMPEG_BIN, ['-y', '-hide_banner', '-loglevel', 'error', ...audioInputs,
|
||||
'-filter_complex', audioFilters.join(';'), '-map', '[roomout]', '-vn', '-ac', '1', '-ar', '48000',
|
||||
'-c:a', 'aac', '-b:a', '96k', roomAudioPath]);
|
||||
normalizedAudios.push(roomAudioPath);
|
||||
}
|
||||
|
||||
const layout = buildGridLayout(normalizedVideos.length);
|
||||
const { maxWidth, maxHeight } = await probeMaxFrameSize(normalizedVideos.map((v) => v.path));
|
||||
let tileWidth = maxWidth || 640;
|
||||
|
||||
@@ -68,13 +68,13 @@ function getDefaultWebSources(assignment = {}, socket = null) {
|
||||
replay`, follows the camera currently controlled by that socket just as it
|
||||
follows an assigned rover below.
|
||||
|
||||
isOperator is deliberately stricter than PTZ access or queue membership:
|
||||
turn.ownsControl is deliberately stricter than PTZ access or queue membership:
|
||||
spectators and users waiting for a camera turn must not silently replay a
|
||||
camera they are not currently operating. Keeping this rule here also makes
|
||||
every web replay entry point share the same default instead of teaching the
|
||||
chat-command adapter about PTZ-specific state.
|
||||
*/
|
||||
if (ptzCameraService.getPublicState(socket).isOperator) {
|
||||
if (ptzCameraService.getPublicState(socket).turn.ownsControl) {
|
||||
const source = ptzCameraService.getReplaySource();
|
||||
if (!source) return [];
|
||||
return [{ type: source.type, id: String(source.id), label: source.label || source.id }];
|
||||
|
||||
@@ -6,9 +6,10 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const logger = require('../../globals/logger').child('replayEngineV2');
|
||||
const { BUFFER_SECONDS, SEGMENT_SECONDS } = require('./constants');
|
||||
const { workers, segmentIndex } = require('./state');
|
||||
const { workers, pendingWorkerStarts, segmentIndex } = require('./state');
|
||||
const { sourceKey, sourceDirForKey } = require('./sources');
|
||||
const ptzCameraService = require('../ptzCameraService');
|
||||
const SEGMENT_FILENAME_PATTERN = /^seg-[a-f0-9-]+-\d{6}\.mp4$/;
|
||||
|
||||
async function ensureDir(dir) {
|
||||
await fsp.mkdir(dir, { recursive: true });
|
||||
@@ -25,7 +26,7 @@ function createSegmentStore({ getActiveSegmentRoot }) {
|
||||
return;
|
||||
}
|
||||
|
||||
const segmentFiles = files.filter((entry) => entry.isFile() && /^seg-\d{6}\.mp4$/.test(entry.name)).map((entry) => entry.name).sort();
|
||||
const segmentFiles = files.filter((entry) => entry.isFile() && SEGMENT_FILENAME_PATTERN.test(entry.name)).map((entry) => entry.name).sort();
|
||||
if (!segmentFiles.length) {
|
||||
segmentIndex.set(key, []);
|
||||
return;
|
||||
@@ -64,6 +65,13 @@ function createSegmentStore({ getActiveSegmentRoot }) {
|
||||
|
||||
async function cleanupOldFiles() {
|
||||
const cutoff = Date.now() - BUFFER_SECONDS * 1000;
|
||||
// Retention applies to stopped workers too; dynamic microphone sessions
|
||||
// must not leave permanent index entries after their audio expires.
|
||||
for (const [key, entries] of segmentIndex) {
|
||||
const retained = entries.filter((entry) => entry.endMs >= cutoff);
|
||||
if (!retained.length && !workers.has(key) && !pendingWorkerStarts.has(key)) segmentIndex.delete(key);
|
||||
else segmentIndex.set(key, retained);
|
||||
}
|
||||
const root = getActiveSegmentRoot();
|
||||
try {
|
||||
await ensureDir(root);
|
||||
@@ -81,6 +89,10 @@ function createSegmentStore({ getActiveSegmentRoot }) {
|
||||
if (stat.mtimeMs < cutoff) await fsp.unlink(filePath);
|
||||
} catch {}
|
||||
}
|
||||
if (!workers.has(dirent.name) && !pendingWorkerStarts.has(dirent.name)) {
|
||||
// rmdir only removes empty directories, preserving buffered or newly written files.
|
||||
try { await fsp.rmdir(dirPath); } catch {}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn('cleanup failed', err.message);
|
||||
@@ -115,6 +127,14 @@ function createSegmentStore({ getActiveSegmentRoot }) {
|
||||
return [];
|
||||
}
|
||||
|
||||
function getRoomAudioEntries() {
|
||||
// Include retained buffers from microphones that disconnected during the
|
||||
// replay window, rather than limiting history to currently live streams.
|
||||
return [...segmentIndex.entries()]
|
||||
.filter(([key]) => key.startsWith('roomAudio__audio__'))
|
||||
.flatMap(([, entries]) => entries);
|
||||
}
|
||||
|
||||
function overlapping(entries, startMs, endMs) {
|
||||
return entries.filter((entry) => entry.endMs > startMs && entry.startMs < endMs);
|
||||
}
|
||||
@@ -153,7 +173,7 @@ function createSegmentStore({ getActiveSegmentRoot }) {
|
||||
try {
|
||||
const files = fs.readdirSync(dir);
|
||||
for (const name of files) {
|
||||
if (!/^seg-\d{6}\.mp4$/.test(name)) continue;
|
||||
if (!SEGMENT_FILENAME_PATTERN.test(name)) continue;
|
||||
const full = path.join(dir, name);
|
||||
let stat;
|
||||
try { stat = fs.statSync(full); } catch { continue; }
|
||||
@@ -172,10 +192,12 @@ function createSegmentStore({ getActiveSegmentRoot }) {
|
||||
|
||||
return {
|
||||
refreshSegmentIndex,
|
||||
refreshIndexForWorker,
|
||||
cleanupOldFiles,
|
||||
getVideoEntriesForSource,
|
||||
getAudioEntriesForRover,
|
||||
getAudioEntriesForSource,
|
||||
getRoomAudioEntries,
|
||||
overlapping,
|
||||
bootstrapIndexFromDisk,
|
||||
getReplayHealthSnapshot,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Replay Socket Hooks
|
||||
// Purpose: Registers web socket replay-trigger handler that publishes replay requests.
|
||||
// Scope: Applies replay mode/cooldown/source validation for socket-triggered replay requests.
|
||||
// Scope: Applies replay mode/availability/source validation for socket-triggered replay requests.
|
||||
const io = require('../../globals/io');
|
||||
const logger = require('../../globals/logger').child('replaySocket');
|
||||
const { getMode, MODES } = require('../modeManager');
|
||||
@@ -45,9 +45,9 @@ function registerReplaySocketHooks({ tryTriggerReplay, validateSources, getDefau
|
||||
const title = normalizeReplayTitle(payload?.title);
|
||||
const includeSidebar = normalizeIncludeSidebar(payload?.includeSidebar);
|
||||
const jobId = buildReplayJobId('web');
|
||||
const attempt = tryTriggerReplay({ by: { source: 'web', requester } });
|
||||
const attempt = tryTriggerReplay({ jobId, by: { source: 'web', requester } });
|
||||
if (!attempt.ok) {
|
||||
cb({ error: 'Replay cooldown active', remainingMs: attempt.remainingMs, state: attempt.state });
|
||||
cb({ error: attempt.error, remainingMs: attempt.remainingMs, state: attempt.state });
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
// Purpose: Resolves replay-capable media sources and ffmpeg worker arguments.
|
||||
// Scope: Converts live rover/room state into stable source descriptors and stream worker config.
|
||||
const path = require('path');
|
||||
const { randomUUID } = require('crypto');
|
||||
const roverManager = require('../roverManager');
|
||||
const { getRoomCameras } = require('../roomCameraService');
|
||||
const { getActiveRoomAudioStreams } = require('../roomAudioService');
|
||||
const ptzCameraService = require('../ptzCameraService');
|
||||
const { FFMPEG_BIN, SEGMENT_SECONDS, TARGET_FPS } = require('./constants');
|
||||
|
||||
@@ -51,12 +53,17 @@ function listDesiredSources() {
|
||||
// both come from the same live MediaMTX path, unlike rovers where audio is a
|
||||
// separate published stream.
|
||||
sources.push(...ptzCameraService.getReplayWorkerSources());
|
||||
for (const stream of getActiveRoomAudioStreams()) {
|
||||
sources.push({ id: stream.id, sourceType: 'roomAudio', kind: 'audio', label: stream.name,
|
||||
inputUrl: `rtsp://127.0.0.1:8554/room-audio/${encodeURIComponent(stream.id)}` });
|
||||
}
|
||||
return sources;
|
||||
}
|
||||
|
||||
function buildWorkerArgs(activeSegmentRoot, source) {
|
||||
const dir = sourceDirForKey(activeSegmentRoot, sourceKey(source));
|
||||
const pattern = path.join(dir, 'seg-%06d.mp4');
|
||||
// Each capture process owns its filenames so restarts preserve buffered segments.
|
||||
const pattern = path.join(dir, `seg-${randomUUID()}-%06d.mp4`);
|
||||
// MediaMTX and RTSP cameras use TCP so replay capture has one reliable
|
||||
// transport and never falls back to separate RTP/RTCP UDP listeners.
|
||||
const inputTransport = /^rtsps?:\/\//i.test(source.inputUrl)
|
||||
|
||||
@@ -12,7 +12,7 @@ async function ensureDir(dir) {
|
||||
await fsp.mkdir(dir, { recursive: true });
|
||||
}
|
||||
|
||||
function createWorkerManager({ getActiveSegmentRoot }) {
|
||||
function createWorkerManager({ getActiveSegmentRoot, onWorkerClosed }) {
|
||||
function startWorker(source) {
|
||||
const key = sourceKey(source);
|
||||
if (workers.has(key) || pendingWorkerStarts.has(key)) return;
|
||||
@@ -21,26 +21,36 @@ function createWorkerManager({ getActiveSegmentRoot }) {
|
||||
const dir = sourceDirForKey(getActiveSegmentRoot(), key);
|
||||
ensureDir(dir)
|
||||
.then(() => {
|
||||
if (workers.has(key)) {
|
||||
// Directory creation can finish after a microphone has disconnected.
|
||||
if (workers.has(key) || !listDesiredSources().some((entry) => sourceKey(entry) === key)) {
|
||||
pendingWorkerStarts.delete(key);
|
||||
return;
|
||||
}
|
||||
const proc = spawn(FFMPEG_BIN, args, { stdio: ['ignore', 'ignore', 'pipe'] });
|
||||
workers.set(key, { key, source, proc });
|
||||
const worker = { key, source, proc, stopping: false };
|
||||
workers.set(key, worker);
|
||||
pendingWorkerStarts.delete(key);
|
||||
proc.stderr.on('data', (chunk) => {
|
||||
const text = String(chunk || '').trim();
|
||||
if (!text) return;
|
||||
logger.warn('worker stderr', { key, text: text.slice(0, 500) });
|
||||
});
|
||||
proc.on('exit', (code, signal) => {
|
||||
const current = workers.get(key);
|
||||
if (current?.proc === proc) workers.delete(key);
|
||||
logger.warn('worker exited', { key, code, signal });
|
||||
setTimeout(() => {
|
||||
const desired = listDesiredSources().find((entry) => sourceKey(entry) === key);
|
||||
if (desired && !workers.has(key)) startWorker(desired);
|
||||
}, 1500);
|
||||
proc.on('error', (err) => logger.warn('worker process failed', { key, error: err.message }));
|
||||
worker.finished = new Promise((resolve) => {
|
||||
proc.once('close', async (code, signal) => {
|
||||
clearTimeout(worker.killTimer);
|
||||
// FFmpeg writes the final MP4 trailer before close. Index it before
|
||||
// releasing this worker so a disconnect cannot drop its last audio.
|
||||
try { await onWorkerClosed(worker); }
|
||||
catch (err) { logger.warn('final worker indexing failed', { key, error: err.message }); }
|
||||
if (workers.get(key) === worker) workers.delete(key);
|
||||
resolve();
|
||||
logger.warn('worker exited', { key, code, signal });
|
||||
if (!worker.stopping) setTimeout(() => {
|
||||
const desired = listDesiredSources().find((entry) => sourceKey(entry) === key);
|
||||
if (desired && !workers.has(key)) startWorker(desired);
|
||||
}, 1500);
|
||||
});
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
@@ -52,8 +62,14 @@ function createWorkerManager({ getActiveSegmentRoot }) {
|
||||
function stopWorker(key) {
|
||||
const worker = workers.get(key);
|
||||
if (!worker) return;
|
||||
try { worker.proc.kill('SIGTERM'); } catch {}
|
||||
workers.delete(key);
|
||||
if (!worker.stopping) {
|
||||
worker.stopping = true;
|
||||
worker.proc.kill('SIGTERM');
|
||||
// Bound shutdown if a capture is blocked waiting on its network input.
|
||||
worker.killTimer = setTimeout(() => worker.proc.kill('SIGKILL'), 3000);
|
||||
worker.killTimer.unref();
|
||||
}
|
||||
return worker.finished;
|
||||
}
|
||||
|
||||
async function syncWorkers() {
|
||||
@@ -63,9 +79,11 @@ function createWorkerManager({ getActiveSegmentRoot }) {
|
||||
const key = sourceKey(source);
|
||||
if (!workers.has(key)) startWorker(source);
|
||||
}
|
||||
const stops = [];
|
||||
for (const key of Array.from(workers.keys())) {
|
||||
if (!desiredKeys.has(key)) stopWorker(key);
|
||||
if (!desiredKeys.has(key)) stops.push(stopWorker(key));
|
||||
}
|
||||
await Promise.all(stops);
|
||||
}
|
||||
|
||||
return { startWorker, stopWorker, syncWorkers };
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
const { strictObject, string, boolean } = require('../../configuration/schemaHelpers');
|
||||
module.exports = {
|
||||
key: 'roomAudio', feature: true,
|
||||
defaultValue: { enabled: false, sources: [] },
|
||||
schema: strictObject({
|
||||
enabled: boolean({ description: 'Enable room audio and local browser microphone publishing.' }),
|
||||
sources: { type: 'array', items: strictObject({
|
||||
id: string({ minLength: 1, maxLength: 80, pattern: '^[a-zA-Z0-9_-]+$' }),
|
||||
name: string({ minLength: 1, maxLength: 120 }),
|
||||
type: { type: 'string', enum: ['device', 'stream'] },
|
||||
input: string({ minLength: 1, maxLength: 2048, description: 'ALSA device (for example default or plughw:CARD=USB,DEV=0), or a network stream URL.' }),
|
||||
}, { required: ['id', 'name', 'type', 'input'] }) },
|
||||
}, { title: 'Room audio', required: ['enabled', 'sources'] }),
|
||||
};
|
||||
@@ -0,0 +1,171 @@
|
||||
const { spawn } = require('child_process');
|
||||
const EventEmitter = require('events');
|
||||
const io = require('../../globals/io');
|
||||
const logger = require('../../globals/logger').child('roomAudio');
|
||||
const { loadConfig, registerConfigurationHandler } = require('../../configuration');
|
||||
const { getSocketIp, isLocalNetwork } = require('../../helpers/ipResolver');
|
||||
const { getMode, MODES } = require('../modeManager');
|
||||
const { getRole, isAdmin, isLockdownAdmin } = require('../roleService');
|
||||
const { canBecomeSpectator } = require('../authService');
|
||||
const { isDeterred } = require('../verificationService');
|
||||
const videoSessions = require('../videoSessions');
|
||||
const roomAudioEvents = new EventEmitter();
|
||||
const sources = new Map();
|
||||
const mediaSessions = new Map();
|
||||
let enabled = false;
|
||||
let active = [];
|
||||
let polling = false;
|
||||
let generation = 0;
|
||||
|
||||
function canListen(socket) {
|
||||
if (!enabled || !socket) return false;
|
||||
const mode = getMode();
|
||||
if (mode === MODES.LOCKDOWN) return isLockdownAdmin(socket);
|
||||
if (isAdmin(socket)) return true;
|
||||
if (getRole(socket) === 'spectator') return canBecomeSpectator(socket);
|
||||
// Room audio follows general driving eligibility, without tying listening
|
||||
// to rover assignment, private-rover access, or the current driving turn.
|
||||
return getRole(socket) === 'user' && mode !== MODES.ADMIN && !isDeterred(socket);
|
||||
}
|
||||
function canPublish(socket, id) {
|
||||
return enabled && isLocalNetwork(getSocketIp(socket)) && sources.get(id)?.socketId === socket.id;
|
||||
}
|
||||
function getRoomAudioStreams(socket) { return canListen(socket) ? active : []; }
|
||||
function getActiveRoomAudioStreams() { return active; }
|
||||
function trackMediaSession(id, token) { if (id) mediaSessions.set(id, token); }
|
||||
function hasStream(id) { return active.some((source) => source.id === id); }
|
||||
function stopSource(id) {
|
||||
const source = sources.get(id);
|
||||
if (!source) return;
|
||||
sources.delete(id);
|
||||
clearTimeout(source.timer);
|
||||
source.child?.kill('SIGTERM');
|
||||
videoSessions.revokeWhere((info) => ['roomAudio', 'roomMic'].includes(info.sourceType) && info.sourceId === id);
|
||||
active = active.filter((entry) => entry.id !== id);
|
||||
roomAudioEvents.emit('update');
|
||||
}
|
||||
function startWorker(source) {
|
||||
if (sources.get(source.id) !== source) return;
|
||||
const args = ['-nostdin', '-hide_banner', '-loglevel', 'warning'];
|
||||
if (source.type === 'device') args.push('-f', 'alsa');
|
||||
else if (/^rtsps?:/i.test(source.input)) args.push('-rtsp_transport', 'tcp', '-timeout', '10000000');
|
||||
else args.push('-rw_timeout', '10000000');
|
||||
args.push('-i', source.input, '-map', '0:a:0', '-vn', '-c:a', 'libopus', '-ar', '48000', '-ac', '1', '-b:a', '64k', '-f', 'rtsp', '-rtsp_transport', 'tcp', `rtsp://127.0.0.1:8554/room-audio/${source.id}`);
|
||||
const child = spawn('ffmpeg', args, { stdio: ['ignore', 'ignore', 'pipe'] });
|
||||
source.child = child;
|
||||
child.stderr.on('data', (data) => logger.warn('Room audio %s: %s', source.name, String(data).trim()));
|
||||
child.on('error', (error) => logger.warn('Room audio %s: %s', source.name, error.message));
|
||||
child.on('close', () => {
|
||||
if (sources.get(source.id) !== source) return;
|
||||
source.child = null;
|
||||
source.timer = setTimeout(() => startWorker(source), 2000);
|
||||
});
|
||||
}
|
||||
function applyConfig(config = {}) {
|
||||
const ids = (config.sources || []).map((source) => source.id);
|
||||
if (new Set(ids).size !== ids.length) throw new Error('Room audio source IDs must be unique');
|
||||
generation += 1;
|
||||
enabled = Boolean(config.enabled);
|
||||
const configured = new Map((config.sources || []).map((entry) => {
|
||||
const source = { ...entry, id: `static-${entry.id}` };
|
||||
return [source.id, source];
|
||||
}));
|
||||
for (const [id, source] of sources) {
|
||||
const next = configured.get(id);
|
||||
// Static-source edits should not interrupt browser microphones or restart
|
||||
// unchanged captures. Disabling the feature still stops every source.
|
||||
if (!enabled || (!source.socketId && (!next || next.type !== source.type || next.input !== source.input))) stopSource(id);
|
||||
}
|
||||
if (enabled) for (const [id, source] of configured) {
|
||||
const existing = sources.get(id);
|
||||
if (existing) existing.name = source.name;
|
||||
else {
|
||||
sources.set(id, source);
|
||||
startWorker(source);
|
||||
}
|
||||
}
|
||||
roomAudioEvents.emit('update');
|
||||
}
|
||||
async function listMediaMtxItems(collection) {
|
||||
const items = [];
|
||||
let page = 0;
|
||||
let pageCount = 1;
|
||||
while (page < pageCount) {
|
||||
const response = await fetch(`http://127.0.0.1:9997/v3/${collection}/list?page=${page}`, { signal: AbortSignal.timeout(1500) });
|
||||
if (!response.ok) throw new Error('MediaMTX unavailable');
|
||||
const data = await response.json();
|
||||
items.push(...(data.items || []));
|
||||
pageCount = data.pageCount || 1;
|
||||
page += 1;
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
// Advertise actual ready MediaMTX paths, rather than a browser reservation or
|
||||
// an ffmpeg process that may still be trying to connect to its input.
|
||||
async function refreshStreams() {
|
||||
if ((!enabled && !mediaSessions.size) || polling) return;
|
||||
polling = true;
|
||||
const currentGeneration = generation;
|
||||
let ready = new Set();
|
||||
try {
|
||||
// HTTP authorization is checked at connection time. Recheck established
|
||||
// browser sessions too so lockdown, disable, and disconnect stop live audio.
|
||||
const previousSessionIds = [...mediaSessions.keys()];
|
||||
const sessions = await listMediaMtxItems('webrtcsessions');
|
||||
const liveSessionIds = new Set(sessions.map((session) => session.id));
|
||||
for (const session of sessions) {
|
||||
if (!session.path?.startsWith('room-audio/')) continue;
|
||||
const info = videoSessions.getSession(mediaSessions.get(session.id));
|
||||
const socket = info && io.sockets.sockets.get(info.socketId);
|
||||
const allowed = socket && (session.state === 'publish'
|
||||
? info.sourceType === 'roomMic' && canPublish(socket, info.sourceId)
|
||||
: info.sourceType === 'roomAudio' && canListen(socket));
|
||||
if (!allowed) await fetch(`http://127.0.0.1:9997/v3/webrtcsessions/kick/${session.id}`, { method: 'POST', signal: AbortSignal.timeout(1500) });
|
||||
}
|
||||
for (const id of previousSessionIds) if (!liveSessionIds.has(id)) mediaSessions.delete(id);
|
||||
} catch (error) {
|
||||
logger.warn('Room audio permission refresh failed: %s', error.message);
|
||||
}
|
||||
// Permission API failures must not make ready streams disappear. Only path
|
||||
// discovery determines the catalog used by playback and replay capture.
|
||||
try {
|
||||
const paths = await listMediaMtxItems('paths');
|
||||
for (const path of paths) if (path.ready) ready.add(path.name);
|
||||
} catch { ready = new Set(); }
|
||||
finally { polling = false; }
|
||||
if (generation !== currentGeneration) return;
|
||||
const next = [...sources.values()].filter((source) => ready.has(`room-audio/${source.id}`)).map(({ id, name }) => ({ id, name }));
|
||||
if (JSON.stringify(next) !== JSON.stringify(active)) {
|
||||
active = next;
|
||||
roomAudioEvents.emit('update');
|
||||
}
|
||||
}
|
||||
io.on('connection', (socket) => {
|
||||
socket.on('roomAudio:start', (_payload, cb = () => {}) => {
|
||||
if (!enabled || !isLocalNetwork(getSocketIp(socket))) return cb({ error: 'Room microphone publishing requires a local visitor and enabled room audio.' });
|
||||
// One owned path per socket; retries replace credentials without accumulating streams.
|
||||
const id = `mic-${socket.id}`;
|
||||
videoSessions.revokeWhere((info) => info.sourceType === 'roomMic' && info.sourceId === id);
|
||||
sources.set(id, { id, name: 'Room microphone', socketId: socket.id });
|
||||
const token = videoSessions.createSession(socket, { type: 'roomMic', id });
|
||||
cb({ id, token, url: `/video/room-audio/${id}/whip` });
|
||||
});
|
||||
socket.on('roomAudio:release', ({ token } = {}) => {
|
||||
const info = videoSessions.getSession(token);
|
||||
if (info?.socketId === socket.id && info.sourceType === 'roomAudio') videoSessions.revokeSession(token);
|
||||
});
|
||||
socket.on('roomAudio:stop', (_payload, cb = () => {}) => {
|
||||
stopSource(`mic-${socket.id}`);
|
||||
cb({ success: true });
|
||||
});
|
||||
socket.on('disconnect', () => {
|
||||
stopSource(`mic-${socket.id}`);
|
||||
});
|
||||
});
|
||||
applyConfig(loadConfig().roomAudio);
|
||||
registerConfigurationHandler('roomAudio', applyConfig);
|
||||
const pollTimer = setInterval(refreshStreams, 2000);
|
||||
pollTimer.unref();
|
||||
process.once('exit', () => { for (const source of sources.values()) source.child?.kill('SIGTERM'); });
|
||||
module.exports = { getActiveRoomAudioStreams, trackMediaSession, roomAudioEvents, getRoomAudioStreams, canListen, canPublish, hasStream };
|
||||
@@ -1,7 +1,7 @@
|
||||
// Room-Camera Configuration
|
||||
// Purpose: Defines the optional named snapshot and stream camera catalog.
|
||||
// Scope: Contains configuration metadata only and never contacts a camera.
|
||||
const { strictObject, string, boolean } = require('../../configuration/schemaHelpers');
|
||||
const { strictObject, string, boolean, integer } = require('../../configuration/schemaHelpers');
|
||||
|
||||
module.exports = {
|
||||
key: 'roomCameras',
|
||||
@@ -10,6 +10,7 @@ module.exports = {
|
||||
// initial configuration while the feature switch prevents network requests.
|
||||
defaultValue: {
|
||||
enabled: false,
|
||||
streamIntervalMs: 2000,
|
||||
cameras: [
|
||||
{
|
||||
id: 'lobby',
|
||||
@@ -29,6 +30,7 @@ module.exports = {
|
||||
},
|
||||
schema: strictObject({
|
||||
enabled: boolean({ description: 'Immediately publishes the configured room-camera catalog and enables camera snapshots and streams.' }),
|
||||
streamIntervalMs: integer({ title: 'Stream interval (ms)', description: 'Interval for sending room camera images to clients. Lowering this increases bandwidth usage FAST because it sends a full image each time.', minimum: 1 }),
|
||||
cameras: {
|
||||
type: 'array',
|
||||
description: 'Room cameras available to the web UI and replay system.',
|
||||
|
||||
@@ -8,10 +8,12 @@ const replay = require('../replayEngineV2/roomCameraReplayBuilder');
|
||||
const { loadConfig, registerConfigurationHandler } = require('../../configuration');
|
||||
|
||||
let enabled = false;
|
||||
let streamIntervalMs = 2000;
|
||||
|
||||
const snapshotEngine = createSnapshotEngine({ getRoomCameras, roomCameraEvents });
|
||||
function applyRoomCameraConfig(roomCameraConfig = {}) {
|
||||
enabled = Boolean(roomCameraConfig.enabled);
|
||||
streamIntervalMs = roomCameraConfig.streamIntervalMs ?? 2000;
|
||||
// Loading an empty catalog on disable causes the snapshot engine's existing
|
||||
// update listener to close every stream and timer without unregistering the
|
||||
// stable browser gateway.
|
||||
@@ -19,6 +21,7 @@ function applyRoomCameraConfig(roomCameraConfig = {}) {
|
||||
}
|
||||
|
||||
registerRoomCameraSocketGateway({
|
||||
getStreamIntervalMs: () => streamIntervalMs,
|
||||
getRoomCamera,
|
||||
getRoomCameras,
|
||||
getRoomCameraState: snapshotEngine.getRoomCameraState,
|
||||
|
||||
@@ -8,7 +8,6 @@ const { isAdmin, isLockdownAdmin, getRole } = require('../roleService');
|
||||
|
||||
const SUBSCRIBE_LIMIT = 50;
|
||||
const SUBSCRIBE_WINDOW_MS = 10000;
|
||||
const STREAM_INTERVAL_MS = 2000;
|
||||
|
||||
function passesMode(socket) {
|
||||
const mode = getMode();
|
||||
@@ -20,7 +19,7 @@ function passesMode(socket) {
|
||||
return true;
|
||||
}
|
||||
|
||||
function registerRoomCameraSocketGateway({ getRoomCamera, getRoomCameras, getRoomCameraState, roomCameraStreamEvents }) {
|
||||
function registerRoomCameraSocketGateway({ getRoomCamera, getRoomCameras, getRoomCameraState, roomCameraStreamEvents, getStreamIntervalMs }) {
|
||||
const cameraSubscribers = new Map();
|
||||
const socketSubscriptions = new Map();
|
||||
const subscribeBuckets = new Map();
|
||||
@@ -82,7 +81,7 @@ function registerRoomCameraSocketGateway({ getRoomCamera, getRoomCameras, getRoo
|
||||
}
|
||||
const lastSent = lastMap.get(id) || 0;
|
||||
const now = ts || Date.now();
|
||||
if (now - lastSent < STREAM_INTERVAL_MS) return;
|
||||
if (now - lastSent < getStreamIntervalMs()) return;
|
||||
lastMap.set(id, now);
|
||||
sendFrame(socket, id, { ts }, buffer);
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user