Compare commits

...
25 Commits
Author SHA1 Message Date
legop3 9d8e22ad1e fix some wording in response to community complaints 2026-07-16 16:58:27 -04:00
legop3 385e7c25fa fixins 2026-07-16 16:45:51 -04:00
legop3 3a8a2ebb13 the big 2026-07-15 00:35:39 -04:00
legop3 96d06091ee going on a command sidequest 2026-07-14 23:47:42 -04:00
legop3 15e03e62ed page title from interinstance config name!! 2026-07-14 23:11:14 -04:00
legop3 3aa97baa4f vip only spectator option 2026-07-14 21:38:55 -04:00
legop3 017b3c69d5 spectator page selectors 2026-07-14 21:13:09 -04:00
legop3 ad7de34d6d appoint spectator access when you login from external, actually... 2026-07-14 20:42:37 -04:00
legop3 51fbee400c spectator login for exties 2026-07-14 20:32:25 -04:00
legop3 7fe5730953 idle service and lght lock improvements 2026-07-14 17:38:17 -04:00
legop3 0d6b4d68de bandwidth savings configs 2026-07-14 17:04:08 -04:00
legop3 1c401ff90a label adjustments 2026-07-14 14:47:46 -04:00
legop3 f6b9fa798e ptz operator in /display 2026-07-14 14:32:25 -04:00
legop3 f667bbce53 tryina make mini not reload stuff.. 2026-07-14 13:34:12 -04:00
legop3 f480e01bf7 dont replace mmtx config 2026-07-14 01:23:11 -04:00
legop3 e2e94da656 ptz in mini and better mini 2026-07-13 18:52:37 -04:00
legop3 8ee680ce9f let everyone make ptz presets.. .. .. .. .. . . . . 2026-07-13 17:39:13 -04:00
legop3 be37a39291 oitercurrent 2026-07-13 16:21:05 -04:00
legop3 af484f5099 oitercurrenting 2026-07-13 16:17:36 -04:00
legop3 5d8cb48fd0 update all rovers buttone 2026-07-13 16:03:51 -04:00
legop3 c742fa1c81 run self update as systemd run 2026-07-13 15:49:09 -04:00
legop3 6dc067580d reboot on self update finally 2026-07-13 15:41:17 -04:00
legop3 d9e6317220 slower iframes 2026-07-13 15:34:44 -04:00
legop3 f969e50772 Merge pull request #14 from legop3/ptz
Ptz
2026-07-13 14:55:09 -04:00
legop3 6e63f0e19c Acknowledge use of language models in project
Added acknowledgment for assistance from language models.
2026-07-11 22:04:54 -04:00
83 changed files with 2634 additions and 712 deletions
+2
View File
@@ -4,6 +4,8 @@ A system for controlling create 2 compatible roombas through a webpage.
You can explore my basement through this project here:
https://rover.otter.land
*some of this code was created with help from large language models, and some of it was written by me. This project would not have been possible for me to create without it.*
## This guide is a work in progress, it will cover:
- Building rovers
- Installing roverd on a rover's raspberry pi
+10
View File
@@ -29,6 +29,15 @@ if [[ "${EUID}" -ne 0 ]]; then
exit 1
fi
if [[ "${ROVERD_SELF_UPDATE_SYSTEMD:-}" != "1" ]] && command -v systemd-run >/dev/null 2>&1; then
exec systemd-run \
--unit=roverd-self-update \
--collect \
--property=Type=exec \
--setenv=ROVERD_SELF_UPDATE_SYSTEMD=1 \
"$0"
fi
if [[ ! -f "$ENV_FILE" ]]; then
echo "Missing $ENV_FILE; run pi/install_roverd.sh once to register the repository path" >&2
exit 1
@@ -86,3 +95,4 @@ log "Repository fast-forward pull complete"
# drift away from the normal manual install path.
"$ROVERD_REPO_DIR/pi/install_roverd.sh"
log "Installer completed successfully"
systemctl reboot
+1
View File
@@ -120,6 +120,7 @@ run_pipeline() {
--framerate "${ROVERD_VIDEO_FPS}" \
--bitrate "${ROVERD_VIDEO_BITRATE}" \
--codec h264 \
--intra 120 \
--profile baseline \
--denoise auto \
--nopreview \
@@ -0,0 +1,359 @@
# Command system and optional Discord feature
## Purpose
Commands were originally implemented as part of the Discord bot. Web chat support was later added by adapting site chat messages into Discord-shaped messages and reusing the Discord command router. This leaves an important server capability owned by an optional external integration and creates inconsistent behavior between transports.
The command system should instead be an always-available server capability. Web chat and Discord should both be adapters for the same command system, while Discord itself becomes an optional feature that can be disabled without affecting commands or the rest of the server.
This is an internal architecture change. Existing behavior on the outside must remain unchanged unless this plan explicitly introduces a new command.
## Non-negotiable behavior
- Existing command names and syntax continue to work.
- Existing permission and lockdown rules continue to work.
- Existing web-chat command messages and replies continue to look and behave the same.
- Existing Discord replies and embeds retain the same content, titles, field ordering, colors, timestamps, mention behavior, attachment names, progress updates, and edit behavior.
- Existing Discord chat bridge, presence, moderation workflows, announcements, and other integrations continue to work when Discord is enabled.
- Disabling Discord does not disable site-chat commands, replay generation, or unrelated server features.
- Discord.js types, messages, embeds, guilds, channels, and configuration do not leak into the shared command implementation.
- Replay hosting requires no new configuration. It must be automatic, conservative, and functional.
- Backwards compatibility for obsolete internal architecture is not required after migration. Temporary migration adapters should be deleted when the new path is complete.
## Target dependency direction
```text
Web chat adapter ---------+
|
v
Operator command service ----> Existing server services
^
|
Optional Discord adapter -+
```
The operator command service owns parsing, command discovery, permission policy, execution, and neutral results. It does not know how a web-chat message or Discord message is represented.
The name `operatorCommandService` avoids confusion with the existing rover `commandService`, which sends operational commands to individual rovers.
## Command configuration
Command naming belongs to the command system rather than Discord:
```yaml
commands:
prefix: "rs"
timeStatusCommand: "ts"
```
Both web chat and Discord must read these same values. Prefix matching remains case-insensitive and must match a whole token so a prefix such as `rs` does not treat a word such as `rsvp` as a command.
Discord becomes an explicitly optional feature:
```yaml
discord:
enabled: false
token: ""
```
The existing Discord channel, role, site URL, and other settings stay under `discord`. `discord.enabled` is authoritative: a stored token must not silently enable the feature. If Discord is enabled but required credentials are missing or login fails, the failure is clearly logged and must not prevent the rest of the server from operating.
### Existing server feature system is authoritative
Use `server/src/helpers/features.js` as the single source of truth for whether optional features are configured and enabled. Do not add a command-specific feature registry, duplicate configuration checks inside command handlers, or infer availability independently from individual config fields.
- Add Discord to `buildFeatureFlags()` using the same explicit feature-gating pattern as the other optional server features. Discord is enabled only when `discord.enabled` is explicitly true and the required token is present.
- Discord service bootstrap, command-adapter registration, integrations, presence, bridge behavior, alerts, and Discord replay delivery all consult the shared Discord feature flag.
- Command definitions use `requiredFeature` metadata, and the command dispatcher resolves that metadata through `isFeatureEnabled()` or a feature-flags snapshot from the same helper.
- Help availability and command execution use the same feature result so help cannot advertise a command as available when execution considers it disabled.
- Lift and Neato availability comes from the existing `lift` and `neato` feature flags. Commands must not reproduce their Home Assistant, switch, device, or enabled-field checks.
- Configuration-level feature availability is separate from runtime health. For example, an enabled lift may currently be disconnected, and configured Discord may fail login. The shared feature helper answers whether the feature is enabled and configured; the owning service remains authoritative for runtime readiness and returns a clear operational failure.
- Replay generation and automatic local replay hosting are core server capabilities and are not feature-gated. Only the optional Discord delivery provider depends on the Discord feature flag and live Discord readiness.
When Discord is disabled:
- Do not construct a Discord client.
- Do not attempt login.
- Do not register Discord event handlers or event-bus integrations.
- Do not register Discord chat bridge subscriptions.
- Do not start Discord presence behavior.
- Keep the shared command service and all site-chat commands active.
## Neutral command request
Every transport converts its native user/message state into one normalized request:
```js
{
text: 'rs lock alpha',
source: 'web-chat',
actor: {
id: 'stable actor id',
label: 'display name',
role: 'admin',
isAdmin: true,
isLockdownAdmin: false,
},
context: {}
}
```
The web adapter derives the actor from the authenticated socket, identity, and role services. The Discord adapter derives it from the Discord user and configured administrator mapping. Command handlers consume the normalized actor and never inspect a socket or `message.author`.
Transport-specific context is allowed only for transport-specific extension commands. For example, the Discord-only bridge command needs guild and channel context, but shared commands must not depend on it.
## Command registry
Replace the large dispatcher switch and scattered help definitions with a command registry. A command definition should contain enough metadata to drive parsing, authorization, availability, and help:
```js
{
name: 'lift',
category: 'feature',
summary: 'Control the rover lift.',
description: 'Show lift state or request upward or downward movement.',
usage: ['lift status', 'lift up', 'lift down'],
examples: ['rs lift status', 'rs lift down'],
access: 'admin',
lockdownAccess: 'lockdown-admin',
requiredFeature: 'lift',
execute,
}
```
The dispatcher should be responsible for common authorization. Individual handlers may perform finer-grained checks when subcommands truly require different access, but they should not duplicate the ordinary admin and lockdown gates.
## Command categories
Categories organize registration and help. Existing syntax must not be changed merely to add categories; for example, `rs mode` stays `rs mode` rather than becoming `rs admin mode`.
### System commands
General server information and server-wide user actions:
- `rs help`
- `rs status`
- `rs replay`
- The configured time-status command, currently `ts`
- Future health, session, or informational commands that do not belong to one optional feature
### Admin commands
Operational, access, and moderation controls:
- `rs lock`
- `rs unlock`
- `rs mode`
- `rs kick`
- `rs goal`
- `rs reason`
- `rs verify`
- `rs deter`
- `rs lights`
Existing admin and lockdown-admin policies remain authoritative.
### Feature commands
Commands belonging to optional hardware or server features. Initial additions should include:
- `rs lift status`
- `rs lift up`
- `rs lift down`
- `rs neato status`
- `rs neato start`
- `rs neato home`
- `rs neato locate`
- `rs neato clear-errors`
Feature command handlers must call the existing feature services. They must not reimplement lift interlocks, cooldowns, connectivity checks, Home Assistant calls, Neato state rules, or other hardware safety logic. The feature service remains the source of truth and the command reports its result.
The dispatcher checks each command's `requiredFeature` against the existing server feature system before execution. The owning feature service then performs runtime availability and safety checks. This deliberately keeps configuration eligibility centralized in `helpers/features.js` while keeping live device state and operational rules inside the service that controls the feature.
Commands for an unavailable or disabled feature return a clear unavailable response rather than throwing or silently doing nothing.
### Discord-only commands
Discord bridge configuration is not a general server command. Keep `bridge` as a Discord extension command registered by the Discord adapter:
- `rs bridge`
- `rs bridge here`
- `rs bridge mode`
- `rs bridge off`
These commands retain their current syntax and Discord behavior but do not appear as available commands in web chat.
## Organized help
Help is generated from registry metadata so command definitions and documentation cannot drift apart.
The default help should be detailed but scannable, grouped into System, Admin, and Features. Discord-only commands can appear in a Discord section when help is requested from Discord. Help should respect the configured prefix and time-status command.
Support focused help:
- `rs help system`
- `rs help admin`
- `rs help features`
- `rs help status`
- `rs help replay`
- `rs help lift`
- `rs help neato`
- The same pattern for every registered command
Focused command help should include:
- A clear description
- Required permission level
- Availability or required feature
- Accepted usage forms
- Useful examples
- Subcommand explanations where applicable
The registry provides neutral help data. Web chat renders readable plain text. Discord uses its own renderer and must preserve the established outward style. Improving organization must not accidentally change unrelated Discord embeds such as rover status and time status.
## Neutral command results and transport rendering
Shared handlers return neutral results instead of calling `message.reply()`:
```js
{
handled: true,
ok: true,
messages: [
{
kind: 'text',
text: 'Locked Alpha.',
},
],
}
```
Simple commands should return text results. Structured results should be used only where transports benefit from different faithful presentations, such as rover status, time status, help, administrative lists, or replay progress.
Discord renderers translate neutral results into the same Discord.js reply and embed objects used today. Existing embed builders should be extracted and retained where possible instead of visually rewriting them during this architecture change.
The web adapter translates the same results into the existing `Rover bot` system messages. The current behavior where the user's command remains visible in the chat transcript should remain unchanged.
## Replay architecture
Replay generation and replay delivery are separate responsibilities:
```text
Replay request
|
v
Replay engine builds one completed MP4
|
v
Replay delivery coordinator
|-- Discord is enabled, ready, and replay channel works
| -> upload MP4 to Discord
| -> use returned Discord attachment URL
|
`-- Discord unavailable, unconfigured, or upload fails
-> store MP4 under the server data directory
-> use server-hosted media URL
|
v
Publish the playable replay media payload to clients
```
Discord remains the preferred host when it is configured for replay delivery. A Discord upload failure after a successful replay build must fall back to local hosting instead of failing the replay. The Discord failure should be logged clearly, while clients still receive a working replay.
The common client media payload should remain compatible with the current payload so `/mini`, `/display`, spectator clients, and other replay consumers behave the same. Discord-specific metadata remains present when Discord hosted the media. Locally hosted media supplies the same common playable URL and media fields without pretending to be a Discord attachment.
### Automatic local replay hosting
No replay-hosting configuration is added. Use conservative internal constants chosen after checking typical generated replay sizes.
The local media service should:
- Store completed files in `data/replays/` through the canonical data-directory helper.
- Use random, non-guessable IDs in public filenames.
- Expose a deliberate route such as `/media/replays/:id.mp4` rather than placing runtime media in built web assets.
- Support HTTP range requests so browsers can seek and play MP4 files normally.
- Set the correct media type and safe cache headers.
- Write atomically by completing a temporary file and renaming it into place.
- Never expose or delete a file that is still being written.
- Remove abandoned temporary files.
- Delete expired replay files during server startup.
- Run one lightweight periodic cleanup while the server is running.
- Stop the cleanup timer during graceful shutdown if the server has a shutdown lifecycle.
- Enforce both a conservative age limit and a conservative total storage ceiling.
- Delete the oldest completed files first when the storage ceiling is exceeded.
- Treat cleanup errors as logged, nonfatal maintenance failures.
- Prevent path traversal and serve only known replay filenames from the replay directory.
Cleanup must operate only on the hosted replay directory and must not touch replay frame caches, unrelated data files, or active replay builds.
## Optional Discord feature boundary
The Discord feature owns:
- Discord client creation and login
- Intents and partials
- Discord message-to-command adaptation
- Neutral-result-to-Discord rendering
- Existing embed presentation
- Discord replay upload delivery
- Chat bridge and webhook behavior
- Guild bridge storage and bridge commands
- Presence
- Discord announcements and alerts
- DM verification and private-access moderation workflows
- Reactions and Discord event handling
Discord must be added to and activated through the existing server feature system. The Discord entrypoint must not maintain a separate interpretation of `discord.enabled` and token availability. Runtime client readiness may still be tracked inside the Discord feature for operations such as replay upload, but that readiness supplements rather than replaces the shared configuration feature flag.
The Discord feature may import the operator command service. The operator command service, replay engine, chat service, and feature command handlers must not import the Discord feature or Discord.js.
## Focused regression protection
The existing implementation is the reference for current command wording and behavior. Read and preserve that behavior while moving each handler; do not first catalogue every reply or build exhaustive snapshots for all commands.
Use focused tests and practical checks at the boundaries most likely to cause meaningful regressions:
- Discord status and time-status embeds retain their existing content, structure, colors, field order, timestamps, and links.
- Discord replay progress edits, attachment upload, filename, URL extraction, and client media publication continue to work.
- A failed or unavailable Discord replay delivery falls back to working locally hosted media.
- Commands remain operational when Discord is disabled or fails login.
- Web chat and Discord use the same configured prefix and whole-token matching behavior.
- Admin and lockdown permissions are enforced consistently from both transports.
- Disabled feature commands return a clear unavailable result, while enabled feature commands use their owning service's runtime safety checks.
- Hosted replay routes support playback and seeking, reject invalid paths, and cleanup only expired completed media.
Use direct inspection and practical command checks for ordinary response wording. Additional tests are appropriate when complex logic is extracted, but exhaustive output transcription is not a prerequisite for the refactor.
## Implementation sequence
Build directly toward the final architecture. It is acceptable to move commands in logical groups while working, but avoid investing in a durable old/new compatibility framework. Once a replacement path works, remove the obsolete adapter and duplicated implementation.
1. Add the operator command request, actor, result, parser, registry, authorization, and help foundations.
2. Extract existing Discord formatting and embed construction into transport-owned renderers without changing their output.
3. Move existing system and admin commands into the registry, using their current code as the behavioral reference.
4. Move status and time status while separating neutral data collection from unchanged Discord embed rendering.
5. Add organized registry-driven help with transport-specific output.
6. Add lift and Neato feature command families using the existing feature flags, services, and safety rules.
7. Add the automatic local replay media store, HTTP route, range serving, startup cleanup, periodic cleanup, and storage limits.
8. Split replay generation from delivery and add the Discord-preferred/local-fallback delivery coordinator.
9. Move replay onto the shared command service while preserving existing Discord progress and upload behavior.
10. Convert web chat and Discord to the shared command service and move bridge commands into the Discord-only extension registry.
11. Add Discord to the existing feature system and gate all Discord bootstrap and integrations through it.
12. Remove the Discord-owned shared router, fake Discord message objects, web replay command injection, result-flattening workaround, and duplicate replay paths.
13. Add or update focused tests for the high-risk boundaries listed above.
14. Run server tests, practical command checks, the web UI build, and targeted lint for touched files.
## Completion criteria
- The server has one transport-neutral command registry and execution path.
- Web chat commands work with Discord completely disabled.
- Discord consumes the shared command service as an optional adapter.
- The configured command prefix behaves consistently everywhere.
- Help is organized by System, Admin, Features, and Discord-only extensions where applicable.
- Detailed per-command and per-category help is available.
- Lift and Neato commands use existing service safety and availability behavior.
- Discord-hosted replays behave exactly as before when Discord delivery succeeds.
- Replays automatically fall back to maintained server-hosted media without configuration.
- Existing clients continue receiving compatible replay media payloads.
- Existing Discord embeds and outward behavior remain unchanged.
- Temporary adapters and duplicated command logic are removed.
+19 -6
View File
@@ -1,16 +1,29 @@
# make all bandwidth saving options toggleable in one centralized server config
- external spectators are people outside of local network
- multitab protection mode
- allowed
- verified only
- not allowed
- snapshots
- non-turn snapshots
- on (you see snapshots when its not your turn)
- off (everyone gets full video all the time)
- non-local spectator snapshots
- on (external spectators are only allowed snapshots)
- off (all spectators get full video)
- non-turn video
- snapshots (rover non-active turn holders and PTZ non-operators see snapshots)
- live (rover non-active turn holders and PTZ non-operators can get full video)
- external spectator video
- snapshots (external spectators are only allowed snapshots)
- live (external spectators can get full video)
- external spectator access (new)
- off (no one can access the spectate page externally)
- on (everyone can access the spectate page externally)
- verifiedOnly (only verified identities can access the spectate page externally)
- admin (external spectators need a saved spectatorAccess.external identity grant)
- anything else related to bandwidth savings should also get config
## implemented config shape
```yaml
bandwidthSavings:
multiTabProtection: "verifiedOnly" # allowed | verifiedOnly | notAllowed
nonTurnVideo: "snapshots" # snapshots | live
externalSpectatorVideo: "snapshots" # snapshots | live
externalSpectatorAccess: "on" # off | on | verifiedOnly | admin
```
+30 -9
View File
@@ -54,6 +54,26 @@ media:
# Example: http://192.168.0.86:8889/video
whepBaseUrl: "http://192.168.0.86:8889/video"
bandwidthSavings:
# Duplicate driver-tab handling for the same browser identity.
# allowed: no duplicate-tab protection
# verifiedOnly: verified/admin users may keep multiple driver tabs; unverified users may not
# notAllowed: every identity is limited to one driver tab
multiTabProtection: "verifiedOnly"
# Live video for users who are attached to a source but do not currently own
# its active turn. "snapshots" saves upload bandwidth; "live" allows full
# video whenever the normal mode/visibility rules allow it.
nonTurnVideo: "snapshots"
# Live video for spectators outside the local network. Local spectators are
# not restricted by this switch because LAN traffic is not the upload limit.
externalSpectatorVideo: "snapshots"
# Whether non-local users may enter the spectator page.
# off: block external spectators
# on: allow external spectators
# verifiedOnly: require a verified identity, but no separate spectator grant
# admin: require an identity feature-state grant at spectatorAccess.external
externalSpectatorAccess: "on"
audioForward:
enabled: true
ffmpegBin: "ffmpeg"
@@ -157,23 +177,24 @@ buttonBox:
barcodeScanner:
enabled: false
commands:
# Commands are a core server capability shared by site chat and optional
# transports. Their names therefore do not belong to Discord configuration.
prefix: "rs"
# Set this to null to disable the legacy bare time-status shortcut.
timeStatusCommand: "ts"
discord:
# Discord is optional. A token by itself never enables an external login.
enabled: false
token: "DISCORD_BOT_TOKEN"
guildId: "123456789012345678" # optional; bot works in any guild it's invited to
siteUrl: "https://rover.example.com"
# Give each bot instance a unique command prefix when several rover servers
# share one Discord server. Commands are matched as whole tokens, so "rs"
# handles "rs status" but ignores normal words like "rsvp".
commandPrefix: "rs"
# Set this to null to disable the bare time-status shortcut. It is separate
# from commandPrefix because the legacy command is just "ts", and multiple
# bots in the same Discord server should not all answer the same bare word.
timeStatusCommand: "ts"
channels:
general: "123456789012345678"
announcements: "123456789012345678"
adminAlerts: "123456789012345678"
# chat bridge is configured per guild via `<commandPrefix> bridge` commands
# chat bridge is configured per guild via the shared `commands.prefix`
replay: "123456789012345678"
humanAlerts: "123456789012345678"
roles:
+3
View File
@@ -49,5 +49,8 @@ require('./src/services/kinectService');
require('./src/services/sessionService');
require('./src/services/batteryManager');
require('./src/services/replayEngineV2');
// Replay delivery is a core service. It must subscribe before the optional
// Discord feature so web requests always have a local delivery path.
require('./src/services/replayDeliveryService');
require('./src/services/discordBotService');
require('./src/services/httpServer');
+6 -3
View File
@@ -229,9 +229,12 @@ if [[ ! -f "$ROVER_SNAPSHOT_WRITER_TEMPLATE" ]]; then
echo "Snapshot writer template missing at $ROVER_SNAPSHOT_WRITER_TEMPLATE" >&2
exit 1
fi
echo " Installing mediaMTX config -> $MEDIAMTX_CONFIG"
rm -f "$MEDIAMTX_CONFIG"
install -m 0644 "$MEDIAMTX_TEMPLATE" "$MEDIAMTX_CONFIG"
if [[ -f "$MEDIAMTX_CONFIG" ]]; then
echo " Preserving existing mediaMTX config -> $MEDIAMTX_CONFIG"
else
echo " Installing mediaMTX config -> $MEDIAMTX_CONFIG"
install -m 0644 "$MEDIAMTX_TEMPLATE" "$MEDIAMTX_CONFIG"
fi
echo " Installing rover snapshot writer -> $ROVER_SNAPSHOT_WRITER_BIN"
install -m 0755 "$ROVER_SNAPSHOT_WRITER_TEMPLATE" "$ROVER_SNAPSHOT_WRITER_BIN"
chown -R "$TARGET_USER":"$TARGET_USER" "$MEDIAMTX_CONF_DIR"
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
+2 -2
View File
@@ -78,8 +78,8 @@
<script defer src="https://analytics.otter.land/script.js" data-website-id="82dd56a5-db44-4279-bd1e-a4d9fee39af7" data-domains="rover.otter.land"></script>
<script defer src="https://analytics.otter.land/recorder.js" data-website-id="82dd56a5-db44-4279-bd1e-a4d9fee39af7" data-domains="rover.otter.land" data-sample-rate="0.15" data-mask-level="moderate" data-max-duration="300000"></script>
<title>Roomba Rover</title>
<script type="module" crossorigin src="/assets/index-D5vPzVhj.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-BN3kEVFL.css">
<script type="module" crossorigin src="/assets/index-B8ElczOE.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-ZpgWUPKf.css">
</head>
<body>
<div id="root"></div>
+110
View File
@@ -0,0 +1,110 @@
// Bandwidth Savings Helper
// Purpose: Normalizes bandwidth-saving config and exposes tiny policy helpers.
// Scope: Keeps cross-service video/tab/spectator decisions consistent without
// making individual services know raw YAML defaults or legacy config shapes.
const { loadConfig } = require('./configLoader');
const MULTI_TAB_MODES = new Set(['allowed', 'verifiedOnly', 'notAllowed']);
const VIDEO_MODES = new Set(['snapshots', 'live']);
const EXTERNAL_SPECTATOR_ACCESS_MODES = new Set(['off', 'on', 'verifiedOnly', 'admin']);
const DEFAULT_BANDWIDTH_SAVINGS = Object.freeze({
multiTabProtection: 'verifiedOnly',
nonTurnVideo: 'snapshots',
externalSpectatorVideo: 'snapshots',
externalSpectatorAccess: 'on',
});
function normalizeEnum(value, allowed, fallback) {
/*
Config files are hand-edited on the server, so a typo should not crash the
process or silently broaden access. Each option falls back to the current
conservative behavior unless it exactly matches a known value.
*/
const normalized = typeof value === 'string' ? value.trim() : '';
return allowed.has(normalized) ? normalized : fallback;
}
function buildBandwidthSavingsPolicy(config = loadConfig()) {
const raw = config.bandwidthSavings || {};
return {
multiTabProtection: normalizeEnum(
raw.multiTabProtection,
MULTI_TAB_MODES,
DEFAULT_BANDWIDTH_SAVINGS.multiTabProtection,
),
nonTurnVideo: normalizeEnum(
raw.nonTurnVideo,
VIDEO_MODES,
DEFAULT_BANDWIDTH_SAVINGS.nonTurnVideo,
),
externalSpectatorVideo: normalizeEnum(
raw.externalSpectatorVideo,
VIDEO_MODES,
DEFAULT_BANDWIDTH_SAVINGS.externalSpectatorVideo,
),
externalSpectatorAccess: normalizeEnum(
raw.externalSpectatorAccess,
EXTERNAL_SPECTATOR_ACCESS_MODES,
DEFAULT_BANDWIDTH_SAVINGS.externalSpectatorAccess,
),
};
}
function getBandwidthSavingsPolicy() {
/*
loadConfig() is cached by configLoader, so rebuilding this small object per
caller is cheap while still letting tests pass explicit config objects into
buildBandwidthSavingsPolicy().
*/
return buildBandwidthSavingsPolicy(loadConfig());
}
function shouldEnforceSingleDriverTab({ isVerified = false, isAdmin = false } = {}) {
const { multiTabProtection } = getBandwidthSavingsPolicy();
if (multiTabProtection === 'allowed') return false;
if (multiTabProtection === 'notAllowed') return true;
/*
verifiedOnly preserves the old behavior: trusted users can run multiple
driver tabs for operations/testing, while anonymous users are limited to one
active driver surface for fairness and bandwidth.
*/
return !isVerified && !isAdmin;
}
function shouldUseSnapshotsForNonTurnVideo() {
return getBandwidthSavingsPolicy().nonTurnVideo === 'snapshots';
}
function shouldUseSnapshotsForExternalSpectatorVideo() {
return getBandwidthSavingsPolicy().externalSpectatorVideo === 'snapshots';
}
function canUseExternalSpectatorAccess({
isLocal = false,
isAdmin = false,
isVerified = false,
hasGrant = false,
} = {}) {
/*
Local/LAN spectators are not the upload-bandwidth problem, and admins need
to retain access for maintenance. The configured external mode only applies
to ordinary non-local spectator sockets.
*/
if (isLocal || isAdmin) return true;
const { externalSpectatorAccess } = getBandwidthSavingsPolicy();
if (externalSpectatorAccess === 'off') return false;
if (externalSpectatorAccess === 'verifiedOnly') return Boolean(isVerified);
if (externalSpectatorAccess === 'admin') return Boolean(hasGrant);
return true;
}
module.exports = {
DEFAULT_BANDWIDTH_SAVINGS,
buildBandwidthSavingsPolicy,
getBandwidthSavingsPolicy,
shouldEnforceSingleDriverTab,
shouldUseSnapshotsForNonTurnVideo,
shouldUseSnapshotsForExternalSpectatorVideo,
canUseExternalSpectatorAccess,
};
+8
View File
@@ -50,6 +50,7 @@ function buildFeatureFlags(config = loadConfig()) {
const socialsConfig = config.socials || {};
const interInstanceConfig = config.interInstance || {};
const ptzCameraConfig = config.ptzCamera || {};
const discordConfig = config.discord || {};
const homeAssistant = Boolean(
asBoolean(homeAssistantConfig.enabled) &&
asTrimmedString(homeAssistantConfig.url) &&
@@ -87,6 +88,13 @@ function buildFeatureFlags(config = loadConfig()) {
asTrimmedString(ptzCameraConfig.username) &&
asTrimmedString(ptzCameraConfig.password),
),
/*
Discord is an optional transport, not a prerequisite for chat commands.
Requiring both the explicit switch and a token prevents an old token from
silently enabling external connections on installations that have chosen
to run without the integration.
*/
discord: Boolean(asBoolean(discordConfig.enabled) && asTrimmedString(discordConfig.token)),
};
}
+7 -13
View File
@@ -1,10 +1,8 @@
// Reward Definition: Darkness
// Purpose: Defines the darkness reward that alters visibility/lighting behavior. Scope: Encapsulates reward metadata and effect configuration for runtime execution.
const DURATION_MS = 15 * 60 * 1000;
const LIGHT_ENFORCE_TICK_MS = 3000;
let activeTimer = null;
let enforceLightsTimer = null;
let headlightLockUntil = 0;
function isHeadlightBlocked() {
@@ -16,10 +14,6 @@ function clearTimers() {
clearTimeout(activeTimer);
activeTimer = null;
}
if (enforceLightsTimer) {
clearInterval(enforceLightsTimer);
enforceLightsTimer = null;
}
}
async function forceAllLightsOff(ctx) {
@@ -55,7 +49,6 @@ async function stopDarkness(ctx, effect = {}) {
if (prevLockState === 'on' || prevLockState === 'off') {
await ctx.setHomeAssistantLightsLockedOn(true, {
source: 'buttonbox:darknessRestore',
forceApply: true,
targetState: prevLockState,
});
} else {
@@ -92,7 +85,6 @@ async function startDarkness(ctx, effect) {
try {
await ctx.setHomeAssistantLightsLockedOn(true, {
source: 'buttonbox:darkness',
forceApply: true,
targetState: 'off',
});
} catch (err) {
@@ -100,11 +92,13 @@ async function startDarkness(ctx, effect) {
}
ctx.saveEffect('darkness', effect);
enforceLightsTimer = setInterval(() => {
forceAllLightsOff(ctx).catch((err) => {
ctx.logger.warn('darkness periodic light enforcement failed', { error: err.message });
});
}, LIGHT_ENFORCE_TICK_MS);
/*
Darkness locks the room-light policy off and performs the initial off
command through setHomeAssistantLightsLockedOn above. It deliberately does
not keep a polling interval that re-forces Home Assistant entities off:
after the lock is established, out-of-band manual controls must remain able
to change individual room lights without the server fighting them.
*/
activeTimer = setTimeout(() => {
stopDarkness(ctx, effect).catch((err) => {
+107 -1
View File
@@ -8,9 +8,20 @@ const { loadConfig } = require('../../helpers/configLoader');
const { clearLockdownTimer } = require('../lockdownGuard');
const { getMode, MODES } = require('../modeManager');
const { setRole } = require('../roleService');
const { getSocketIp, isLocalNetwork } = require('../../helpers/ipResolver');
const {
canUseExternalSpectatorAccess,
getBandwidthSavingsPolicy,
} = require('../../helpers/bandwidthSavings');
const {
getFeatureState,
getUserIdForSocket,
updateFeatureState,
} = require('../identityService');
const config = loadConfig();
const admins = config.admins || [];
const SPECTATOR_ACCESS_NAMESPACE = 'spectatorAccess';
function findAdmin(username) {
return admins.find((admin) => admin.username === username);
@@ -36,9 +47,91 @@ function isLockdownAdmin(socket) {
return socket?.data?.role === 'lockdown';
}
function hasExternalSpectatorGrant(socket) {
const userId = getUserIdForSocket(socket);
if (!userId) return false;
const state = getFeatureState(userId, SPECTATOR_ACCESS_NAMESPACE, {});
/*
The identity database already owns per-user feature state. Keeping the grant
as a tiny namespaced boolean avoids a new table and lets the existing admin
database editor grant/revoke external spectator access immediately.
*/
return Boolean(state?.external);
}
function canBecomeSpectator(socket) {
const ip = getSocketIp(socket);
const local = isLocalNetwork(ip);
return canUseExternalSpectatorAccess({
isLocal: local,
isAdmin: isAdmin(socket),
isVerified: Boolean(socket?.data?.isVerified),
hasGrant: hasExternalSpectatorGrant(socket),
});
}
function externalSpectatorAccessError() {
const mode = getBandwidthSavingsPolicy().externalSpectatorAccess;
if (mode === 'verifiedOnly') {
return 'External spectator access requires a verified identity.';
}
if (mode === 'admin') {
return 'External spectator access requires admin approval for this identity.';
}
return 'External spectator access is disabled.';
}
function grantExternalSpectatorAccessAfterAdminLogin(socket) {
const policy = getBandwidthSavingsPolicy();
if (policy.externalSpectatorAccess !== 'admin') {
return false;
}
const ip = getSocketIp(socket);
if (isLocalNetwork(ip)) {
return false;
}
const userId = getUserIdForSocket(socket);
if (!userId) {
/*
Sockets are normally identified on connection before login, but keeping a
guard here makes the admin grant fail closed instead of writing an orphan
feature-state row if identity setup changes later.
*/
logger.warn('External spectator grant skipped because socket has no identity', { socketId: socket?.id });
return false;
}
updateFeatureState(
userId,
SPECTATOR_ACCESS_NAMESPACE,
(current) => ({
/*
Preserve any future spectatorAccess settings beside `external`. The
login flow is only approving this identity for external spectating, not
resetting the whole namespace back to a one-field object.
*/
...(current || {}),
external: true,
grantedByAdminLoginAt: Date.now(),
grantedByAdminUsername: socket?.data?.user?.username || null,
}),
{},
);
logger.info('External spectator access granted after admin login', {
socketId: socket.id,
userId,
username: socket?.data?.user?.username || null,
});
return true;
}
io.on('connection', (socket) => {
const requestedRole = socket.handshake?.query?.role;
const initialRole = requestedRole === 'spectator' ? 'spectator' : 'user';
/*
Role is assigned before the browser's full identity heartbeat has completed.
For admin-gated external spectators, fail closed here; the spectator page can
identify the socket and then retry session:setRole once the grant exists.
*/
const initialRole = requestedRole === 'spectator' && canBecomeSpectator(socket) ? 'spectator' : 'user';
setRole(socket, initialRole);
logger.info('Socket connected with role', socket.id, initialRole);
socket.emit('auth:role', { role: initialRole });
@@ -51,6 +144,13 @@ io.on('connection', (socket) => {
const role = admin.lockdown ? 'lockdown' : 'admin';
socket.data.user = { username: admin.username, discordId: admin.discord_id };
setRole(socket, role);
/*
In admin-gated external spectator mode, logging in from /spectate is the
approval action for this browser identity. Persist the grant before the
client retries switching back to spectator, otherwise the user would
lose the admin bypass and immediately fall back into the gate.
*/
grantExternalSpectatorAccessAfterAdminLogin(socket);
socket.emit('auth:role', { role });
clearLockdownTimer(socket);
logger.info('Login success', socket.id, role);
@@ -63,6 +163,12 @@ io.on('connection', (socket) => {
function handleRoleChange({ role } = {}, cb = () => {}) {
if (role === 'spectator' || role === 'user') {
if (role === 'spectator' && !canBecomeSpectator(socket)) {
const error = externalSpectatorAccessError();
logger.info('Spectator role denied by bandwidth policy', socket.id, { error });
cb({ error });
return;
}
setRole(socket, role);
socket.emit('auth:role', { role });
logger.info('Role changed via client request', socket.id, role);
+23 -20
View File
@@ -10,6 +10,9 @@ const { getNickname } = require('../nicknameService');
const { getGlobalObjective, setGlobalObjective, clearGlobalObjective } = require('../globalObjectiveService');
const { getAdminReason, setAdminReason, clearAdminReason } = require('../adminReasonService');
const homeAssistantService = require('../homeAssistantService');
const liftService = require('../liftService');
const neatoService = require('../neatoService');
const { isFeatureEnabled } = require('../../helpers/features');
const {
listVerifiedUsers,
removeVerifiedUser,
@@ -20,20 +23,21 @@ const {
const { publishEvent } = require('../eventBus');
const assignmentService = require('../assignmentService');
const { loadConfig } = require('../../helpers/configLoader');
const { createCommandHandlers } = require('../discordBotService/commands');
const { createCommandHandlers } = require('../operatorCommandService');
const { parseCommandText } = require('../operatorCommandService/config');
const { createWebTransportHandlers } = require('../operatorCommandService/webTransport');
const { commandReplyToText } = require('./commandResultFormatter');
const {
buildReplayJobId,
buildReplayTitle,
createReplaySourceResolver,
} = require('../discordBotService/replayWorkflow');
} = require('../replayDeliveryService/workflow');
const config = loadConfig();
const discordConfig = config.discord || {};
function isTextCommand(text) {
const clean = String(text || '').trim();
return clean.toLowerCase() === 'ts' || /^rs(?:\s|$)/i.test(clean);
return parseCommandText(text, config).matched;
}
function sanitizeMentions(text) {
@@ -70,12 +74,6 @@ function createWebReplayTextCommand(socket, sendSystemMessage, replayApi) {
return;
}
const channelId = discordConfig?.channels?.replay || null;
if (!channelId) {
await message.reply({ content: 'Replay denied: replay channel is not configured.' });
return;
}
const resolved = sourceResolver.resolve(query);
if (resolved?.error) {
await message.reply({ content: resolved.error });
@@ -99,7 +97,6 @@ function createWebReplayTextCommand(socket, sendSystemMessage, replayApi) {
type: 'replay.requested',
payload: {
jobId,
channelId,
requester,
title: '',
includeSidebar: true,
@@ -113,18 +110,18 @@ function createWebReplayTextCommand(socket, sendSystemMessage, replayApi) {
};
}
function createChatCommandMessage({ socket, text, sendSystemMessage }) {
function createChatCommandRequest({ socket, text, sendSystemMessage }) {
const nickname = buildRequesterLabel(socket);
return {
content: String(text || '').trim(),
author: {
actor: {
bot: false,
id: socket.id,
username: nickname,
},
member: {
nickname,
label: nickname,
isAdmin: isAdmin(socket),
isLockdownAdmin: isLockdownAdmin(socket),
},
transport: 'web-chat',
reply: async (payload) => {
const response = sanitizeMentions(commandReplyToText(payload));
if (!response) return null;
@@ -139,8 +136,8 @@ async function runChatTextCommand({ text, socket, sendSystemMessage }) {
// keeps ordinary chatService initialization from changing the service boot
// order, while still letting `rs replay` use the existing replay pipeline.
const replayApi = require('../replayEngineV2');
const message = createChatCommandMessage({ socket, text, sendSystemMessage });
const commands = createCommandHandlers({
const message = createChatCommandRequest({ socket, text, sendSystemMessage });
const commandDependencies = {
logger: null,
client: null,
io,
@@ -168,6 +165,9 @@ async function runChatTextCommand({ text, socket, sendSystemMessage }) {
// lights lock/unlock` from becoming transport-specific, and it preserves
// the existing session update path for all connected browsers.
homeAssistantService,
liftService,
neatoService,
isFeatureEnabled,
getGuildConfig: () => null,
setGuildConfig: () => null,
removeGuildConfig: () => null,
@@ -183,9 +183,12 @@ async function runChatTextCommand({ text, socket, sendSystemMessage }) {
isAdminUser: (id) => String(id) === String(socket.id) && isAdmin(socket),
isLockdownAdminUser: (id) => String(id) === String(socket.id) && isLockdownAdmin(socket),
discordConfig,
siteUrl: String(discordConfig.siteUrl || ''),
config,
createReplayTextCommand: createWebReplayTextCommand(socket, sendSystemMessage, replayApi),
});
};
commandDependencies.transportHandlers = createWebTransportHandlers(commandDependencies);
const commands = createCommandHandlers(commandDependencies);
// Let the shared router perform normal command permission checks. Site chat
// has already broadcast the user's command text, so command replies become a
@@ -106,6 +106,28 @@ function handleAck(msg) {
});
}
function issueUpdateToAllRovers() {
const updated = [];
const failed = [];
roverManager.rovers.forEach((record) => {
if (!record?.ws) return;
const roverId = String(record.id);
try {
// Use the same narrow update payload as the per-rover admin action. The
// browser only asks for "update all"; the Pi still owns the privileged
// pull/install/reboot sequence through its fixed self-update helper.
issueCommand(roverId, { type: 'update', update: {} });
updated.push(roverId);
} catch (err) {
failed.push({ roverId, error: err.message });
}
});
return { updated, failed };
}
function getRecentDriveActivity(windowMs, options = {}) {
const now = Date.now();
const results = [];
@@ -288,6 +310,26 @@ io.on('connection', (socket) => {
socket.on('command', handleCommand);
socket.on('command:issue', handleCommand);
socket.on('command:updateAllRovers', (_payload = {}, cb) => {
const reply = typeof cb === 'function' ? cb : () => {};
try {
if (!isAdmin(socket)) {
throw new Error('Not authorized');
}
const result = issueUpdateToAllRovers();
logger.warn('Admin requested update for all online rovers', {
socketId: socket.id,
updated: result.updated,
failed: result.failed,
});
reply(result);
} catch (err) {
logger.warn('Update-all rovers rejected', socket.id, err.message);
reply({ error: err.message });
}
});
});
homeAssistantService.homeAssistantEvents.on('update', () => {
@@ -0,0 +1,39 @@
// Discord Command Adapter
// Purpose: Supplies Discord-specific renderers and extension commands to the operator command service.
// Scope: Keeps Discord embeds, attachments, guild permissions, and bridge context outside the shared command core.
const { createStatusCommand } = require('./commands/status');
const { createReplayCommand } = require('./commands/replay');
const { createBridgeCommand } = require('./commands/bridge');
const { createTimeStatusCommand } = require('./commands/timeStatus');
function createDiscordTransportHandlers(deps) {
const status = createStatusCommand(deps);
const replay = createReplayCommand(deps);
const bridge = createBridgeCommand(deps);
const timeStatus = createTimeStatusCommand(deps);
return {
status: (request, query) => status(request.context.discordMessage, query),
replay: (request, query) => replay(request.context.discordMessage, query),
bridge: (request, tokens) => bridge(request.context.discordMessage, tokens),
timeStatus: (request) => timeStatus(request.context.discordMessage),
};
}
function createDiscordCommandRequest(message, { isAdminUser, isLockdownAdminUser }) {
const id = message.author?.id || null;
return {
content: String(message.content || ''),
transport: 'discord',
actor: {
id,
label: message.member?.nickname || message.author?.globalName || message.author?.username || 'Discord',
bot: Boolean(message.author?.bot),
isAdmin: isAdminUser(id),
isLockdownAdmin: isLockdownAdminUser(id),
},
reply: (payload) => message.reply(payload),
context: { discordMessage: message },
};
}
module.exports = { createDiscordTransportHandlers, createDiscordCommandRequest };
@@ -2,11 +2,12 @@
// Purpose: Handles chat bridge configuration/status commands per guild.
// Scope: Manages bridge channel, mode, and webhook provisioning.
const { PermissionsBitField } = require('discord.js');
const { getCommandConfig } = require('../../operatorCommandService/config');
function createBridgeCommand({ getGuildConfig, setGuildConfig, removeGuildConfig, normalizeMode, VALID_MODES, isAdminUser, discordConfig }) {
function createBridgeCommand({ getGuildConfig, setGuildConfig, removeGuildConfig, normalizeMode, VALID_MODES, isAdminUser, config }) {
// Error text should name the active prefix because bridge setup is one of the
// first commands an admin runs when a bot instance joins a shared Discord.
const commandPrefix = String(discordConfig?.commandPrefix || 'rs').trim() || 'rs';
const { prefix: commandPrefix } = getCommandConfig(config);
function canManageBridge(message) {
if (isAdminUser(message.author.id)) return true;
if (!message.guild || !message.member) return false;
@@ -1,32 +0,0 @@
// Discord Help Command
// Purpose: Provides help text for rover bot Discord commands.
// Scope: Returns usage text with the configured command names for this bot instance.
function formatHelp({ commandPrefix = 'rs', timeStatusCommand = 'ts' } = {}) {
const prefix = String(commandPrefix || 'rs').trim() || 'rs';
const timeCommand = timeStatusCommand ? String(timeStatusCommand).trim() : '';
return [
'**Rover Bot Commands**',
`\`${prefix} help\` — show this help`,
`\`${prefix} status [rover]\` — show rover status; rover names can be fuzzy`,
`\`${prefix} replay [sources]\` — send instant replay; source names can be fuzzy`,
`\`${prefix} bridge\` — show chat bridge status for this server`,
`\`${prefix} bridge here <global|private>\` — set chat bridge to this channel`,
`\`${prefix} bridge mode <global|private>\` — change chat bridge mode`,
`\`${prefix} bridge off\` — disable chat bridge for this server`,
`\`${prefix} lights <status|lock|unlock>\` — show or change room light lock state`,
`\`${prefix} kick <user> [reason]\` — remove a user from their current rover; use \`user | reason\` for multi-word names`,
`\`${prefix} lock <rover>\` — lock a rover; rover names can be fuzzy`,
`\`${prefix} unlock <rover>\` — unlock a rover; rover names can be fuzzy`,
`\`${prefix} mode <open|turns|admin|lockdown>\` — change server mode`,
`\`${prefix} reason [text|clear]\` — show or set admin mode reason`,
`\`${prefix} goal [text|clear]\` — show or set global objective`,
`\`${prefix} verify list\` — list verified users (lockdown admins)`,
`\`${prefix} verify remove <cookieUserId|nickname>\` — remove verified user; nicknames can be fuzzy or multi-word (lockdown admins)`,
`\`${prefix} deter list\` — list deterred users (lockdown admins)`,
`\`${prefix} deter ban <cookieUserId|nickname|ip>\` — deter a user; nicknames can be fuzzy or multi-word (lockdown admins)`,
`\`${prefix} deter unban <id|cookieUserId|nickname|ip>\` — remove deterrence; nicknames can be fuzzy or multi-word (lockdown admins)`,
timeCommand ? `\`${timeCommand}\` — show time status` : '',
].filter(Boolean).join('\n');
}
module.exports = { formatHelp };
@@ -1,141 +0,0 @@
// Discord Commands Router
// Purpose: Routes incoming Discord command messages to one-file-per-command handlers.
// Scope: Central command dispatcher and permission gate orchestration.
const { formatHelp } = require('./help');
const { createStatusCommand } = require('./status');
const { createReplayCommand } = require('./replay');
const { createLockCommand } = require('./lock');
const { createModeCommand } = require('./mode');
const { createReasonCommand } = require('./reason');
const { createGoalCommand } = require('./goal');
const { createVerifyCommand } = require('./verify');
const { createDeterCommand } = require('./deter');
const { createBridgeCommand } = require('./bridge');
const { createTimeStatusCommand } = require('./timeStatus');
const { createLightsCommand } = require('./lights');
const { createKickCommand } = require('./kick');
function createCommandHandlers(deps) {
const {
getMode,
MODES,
isAdminUser,
isLockdownAdminUser,
} = deps;
// Each running rover server can bring its own Discord bot into the same
// guild, so the primary command prefix must come from config instead of
// being hard-coded globally. The fallback preserves existing installs.
const commandPrefix = String(deps.discordConfig?.commandPrefix || 'rs').trim() || 'rs';
// The legacy time command is a bare word rather than a prefixed command. It
// therefore needs its own configurable value, and `null` intentionally
// disables it so multiple bots do not all answer `ts` in the same channel.
const timeStatusCommand = deps.discordConfig?.timeStatusCommand === null
? ''
: String(deps.discordConfig?.timeStatusCommand || 'ts').trim();
// Lowercase cached copies avoid re-normalizing every message and keep command
// matching case-insensitive without changing the original configured text
// that is shown in help output.
const normalizedCommandPrefix = commandPrefix.toLowerCase();
const normalizedTimeStatusCommand = timeStatusCommand.toLowerCase();
const handleStatusCommand = createStatusCommand(deps);
const handleReplayCommand = deps.createReplayTextCommand
? deps.createReplayTextCommand(deps)
: createReplayCommand(deps);
const handleLockCommand = createLockCommand(deps);
const handleModeCommand = createModeCommand(deps);
const handleReasonCommand = createReasonCommand(deps);
const handleGoalCommand = createGoalCommand(deps);
const handleVerifyCommand = createVerifyCommand(deps);
const handleDeterCommand = createDeterCommand(deps);
const handleBridgeCommand = createBridgeCommand(deps);
const handleTimeStatusCommand = createTimeStatusCommand(deps);
const handleLightsCommand = createLightsCommand(deps);
const handleKickCommand = createKickCommand(deps);
function stripCommandPrefix(content) {
const trimmed = String(content || '').trim();
const lower = trimmed.toLowerCase();
if (!lower.startsWith(normalizedCommandPrefix)) return null;
const nextCharacter = trimmed.charAt(commandPrefix.length);
// Prefixes are matched as whole command tokens so an instance using `rs`
// still ignores ordinary words such as `rsvp`. This mirrors the old regex
// behavior while letting each Discord bot instance use its own prefix.
if (nextCharacter && !/\s/.test(nextCharacter)) return null;
return trimmed.slice(commandPrefix.length).trim();
}
async function handleCommand(message) {
if (message.author.bot) return;
const content = (message.content || '').trim();
const lower = content.toLowerCase();
// Commands are intentionally matched as whole prefixes. The previous
// startsWith checks made ordinary messages such as "rsvp" or "tshirt" look
// like commands, which is especially bad now that web chat will run the
// same server-side dispatcher before broadcasting user text.
if (normalizedTimeStatusCommand && lower === normalizedTimeStatusCommand) return handleTimeStatusCommand(message);
const commandBody = stripCommandPrefix(content);
if (commandBody === null) return;
const tokens = commandBody ? commandBody.split(/\s+/) : [];
const action = (tokens.shift() || '').toLowerCase();
const rest = tokens.join(' ').trim();
const isAdmin = isAdminUser(message.author.id);
const isLockdownAdmin = isLockdownAdminUser(message.author.id);
const mode = getMode();
// Actions in this set can change operational safety or access policy, so
// lockdown mode narrows them from normal admins to lockdown admins. Room
// light locking belongs here because it can force the physical room lights
// on and disables ordinary Home Assistant room controls for everyone else.
const moderationActions = new Set(['lock', 'unlock', 'mode', 'goal', 'reason', 'verify', 'deter', 'lights', 'kick']);
if (!isAdmin && action !== '' && action !== 'status' && action !== 'help' && action !== 'replay' && action !== 'bridge' && action !== 'goal' && action !== 'reason' && action !== 'verify' && action !== 'deter') {
await message.reply({ content: 'Only admins can run that command.', allowedMentions: { parse: [], repliedUser: false } });
return;
}
if (mode === MODES.LOCKDOWN && moderationActions.has(action) && !isLockdownAdmin) {
await message.reply({ content: 'Lockdown mode: only lockdown admins can run that command.', allowedMentions: { parse: [], repliedUser: false } });
return;
}
switch (action) {
case '':
case 'status':
return handleStatusCommand(message, rest);
case 'help':
return message.reply(formatHelp({ commandPrefix, timeStatusCommand }));
case 'replay':
return handleReplayCommand(message, tokens.join(' '));
case 'bridge':
return handleBridgeCommand(message, tokens);
case 'lights':
return handleLightsCommand(message, tokens);
case 'kick':
return handleKickCommand(message, rest);
case 'lock':
return handleLockCommand(message, rest, true);
case 'unlock':
return handleLockCommand(message, rest, false);
case 'mode':
return handleModeCommand(message, tokens);
case 'goal':
return handleGoalCommand(message, tokens);
case 'reason':
return handleReasonCommand(message, tokens);
case 'verify':
return handleVerifyCommand(message, tokens);
case 'deter':
return handleDeterCommand(message, tokens);
default:
return message.reply(formatHelp({ commandPrefix, timeStatusCommand }));
}
}
return { handleCommand };
}
module.exports = { createCommandHandlers };
@@ -3,6 +3,7 @@
// Scope: Resolves sources, enforces cooldowns, reports job progress, uploads video, and broadcasts media URLs.
const { AttachmentBuilder } = require('discord.js');
const io = require('../../../globals/io');
const { hostReplay } = require('../../replayMediaService');
const {
DEFAULT_ALLOWED_MENTIONS,
buildReplayJobId,
@@ -17,7 +18,7 @@ const {
buildAcceptedMessage,
buildStatusMessage,
normalizeUserError,
} = require('../replayWorkflow');
} = require('../../replayDeliveryService/workflow');
function createReplayCommand({
logger,
@@ -32,6 +33,7 @@ function createReplayCommand({
getActiveDrivers,
getNickname,
rovers,
discordConfig,
}) {
const sourceResolver = createReplaySourceResolver({
rovers,
@@ -80,18 +82,21 @@ function createReplayCommand({
});
const stopTyping = startDiscordTypingLoop(message.channel, logger, 'discord replay command');
let builtReplay = null;
let deliveredMedia = null;
try {
jobStatus.emit(job, 'building', { message: buildStatusMessage(job, 'building') });
if (progressMessage?.edit) {
await progressMessage.edit({ content: sanitizeMentions(buildStatusMessage(job, 'building')), allowedMentions: DEFAULT_ALLOWED_MENTIONS });
}
const { buffer, usedSources = job.sources, missingSources = [] } = await buildReplayVideo({
builtReplay = await buildReplayVideo({
sources: job.sources,
title: job.title,
requester: job.requester,
includeSidebar: job.includeSidebar,
});
const { buffer, usedSources = job.sources, missingSources = [] } = builtReplay;
jobStatus.emit(job, 'uploading', { message: buildStatusMessage(job, 'uploading') });
if (progressMessage?.edit) {
@@ -108,14 +113,36 @@ function createReplayCommand({
if (!uploadMessage) throw new Error('Discord upload did not return a message');
const uploadedAttachment = firstAttachmentFromMessage(uploadMessage);
const media = buildDiscordReplayMediaPayload({ message: uploadMessage, attachment: uploadedAttachment, job });
if (!media) throw new Error('Discord upload did not include a replay attachment URL');
deliveredMedia = buildDiscordReplayMediaPayload({ message: uploadMessage, attachment: uploadedAttachment, job });
if (!deliveredMedia) throw new Error('Discord upload did not include a replay attachment URL');
jobStatus.emit(job, 'ready', { message: buildStatusMessage(job, 'ready'), media });
jobStatus.emit(job, 'ready', { message: buildStatusMessage(job, 'ready'), media: deliveredMedia });
if (progressMessage?.edit) {
await progressMessage.edit({ content: sanitizeMentions(buildStatusMessage(job, 'ready')), allowedMentions: DEFAULT_ALLOWED_MENTIONS });
}
} catch (err) {
if (deliveredMedia) {
logger?.warn?.('Replay uploaded but Discord progress message could not be finalized', { jobId: job.id, error: err.message });
return;
}
// A completed video should never be discarded merely because the
// optional Discord upload failed. Host that exact buffer locally and
// publish the same ready event consumed by existing clients.
if (builtReplay?.buffer && !deliveredMedia) {
try {
const media = await hostReplay({ buffer: builtReplay.buffer, job });
jobStatus.emit(job, 'ready', { message: buildStatusMessage(job, 'ready'), media });
if (progressMessage?.edit) {
await progressMessage.edit({ content: sanitizeMentions(buildStatusMessage(job, 'ready')), allowedMentions: DEFAULT_ALLOWED_MENTIONS });
}
const siteUrl = String(discordConfig?.siteUrl || '').replace(/\/$/, '');
const publicUrl = siteUrl ? `${siteUrl}${media.url}` : media.url;
await progressMessage.reply({ content: `Replay hosted by the rover server: ${publicUrl}`, allowedMentions: DEFAULT_ALLOWED_MENTIONS });
return;
} catch (fallbackError) {
logger?.warn?.('Local replay fallback failed', { jobId: job.id, error: fallbackError.message });
}
}
const userMessage = normalizeUserError(err);
jobStatus.emit(job, 'failed', { message: userMessage });
if (progressMessage?.edit) {
@@ -3,7 +3,7 @@
// Scope: Builds and sends rover status embed for one rover or all visible rovers.
const { EmbedBuilder } = require('discord.js');
const { buildBatteryStatusEmbed } = require('../batteryEmbeds');
const { resolveRoverSelector } = require('./resolvers');
const { resolveRoverSelector } = require('../../operatorCommandService/commands/resolvers');
function createStatusCommand({ rovers, roverManager }) {
return async function handleStatusCommand(message, roverId) {
+97 -22
View File
@@ -5,10 +5,13 @@ const {
Client,
GatewayIntentBits,
Partials,
AttachmentBuilder,
} = require('discord.js');
const logger = require('../../globals/logger').child('discordBot');
const io = require('../../globals/io');
const { loadConfig } = require('../../helpers/configLoader');
const { isFeatureEnabled } = require('../../helpers/features');
const { parseCommandText } = require('../operatorCommandService/config');
const roverManager = require('../roverManager');
const { getRoster, lockRover, rovers } = roverManager;
const { MODES, getMode, setMode } = require('../modeManager');
@@ -20,6 +23,8 @@ const { getNickname } = require('../nicknameService');
const { getGlobalObjective, setGlobalObjective, clearGlobalObjective } = require('../globalObjectiveService');
const { getAdminReason, setAdminReason, clearAdminReason } = require('../adminReasonService');
const homeAssistantService = require('../homeAssistantService');
const liftService = require('../liftService');
const neatoService = require('../neatoService');
const {
getGuildConfig,
listGuildConfigs,
@@ -48,26 +53,32 @@ const {
const { subscribe } = require('../eventBus');
const { createPresenceManager } = require('./presence');
const { createChannelIO } = require('./channelIO');
const { createCommandHandlers } = require('./commands');
const { createCommandHandlers } = require('../operatorCommandService');
const { createDiscordTransportHandlers, createDiscordCommandRequest } = require('./commandAdapter');
const { createIntegrations } = require('./integrations');
const { registerPreferredDeliveryProvider } = require('../replayDeliveryService');
const {
DEFAULT_ALLOWED_MENTIONS,
createReplayCaptionBuilder,
startDiscordTypingLoop,
sanitizeReplayTitleForFilename,
firstAttachmentFromMessage,
buildDiscordReplayMediaPayload,
buildAcceptedMessage,
buildStatusMessage,
} = require('../replayDeliveryService/workflow');
const config = loadConfig();
const discordConfig = config.discord || {};
const enabled = Boolean(discordConfig.token);
const enabled = isFeatureEnabled('discord');
// These normalized command names mirror the command router. Bridge-channel
// command replies are mirrored into web chat, so this entrypoint needs to know
// the configured command names before it wraps message.reply.
const commandPrefix = String(discordConfig.commandPrefix || 'rs').trim() || 'rs';
const timeStatusCommand = discordConfig.timeStatusCommand === null
? ''
: String(discordConfig.timeStatusCommand || 'ts').trim();
const normalizedCommandPrefix = commandPrefix.toLowerCase();
const normalizedTimeStatusCommand = timeStatusCommand.toLowerCase();
const adminIds = new Set((config.admins || []).map((a) => String(a.discord_id || '').trim()).filter(Boolean));
const lockdownAdminIds = new Set((config.admins || []).filter((admin) => admin.lockdown).map((admin) => String(admin.discord_id || '').trim()).filter(Boolean));
if (!enabled) {
logger.info('Discord bot disabled; missing token in config.discord.token');
logger.info('Discord feature disabled or missing required token');
return;
}
@@ -123,7 +134,72 @@ const presence = createPresenceManager({
countReady,
});
const commands = createCommandHandlers({
const replayCaption = createReplayCaptionBuilder({
io,
rovers,
getActiveDrivers,
getNickname,
sanitizeMentions,
});
// Discord is the preferred replay host only while this optional feature is
// active. The core replay delivery service owns generation and automatically
// falls back to its local media store when any operation below fails.
if (discordConfig?.channels?.replay) {
registerPreferredDeliveryProvider({
async begin(job) {
const channelId = discordConfig.channels.replay;
const progressMessage = await channelIO.sendToChannel(channelId, buildAcceptedMessage(job), {}, DEFAULT_ALLOWED_MENTIONS);
if (!progressMessage) throw new Error('Discord replay progress message could not be sent');
const channel = await channelIO.fetchChannel(channelId);
return {
channelId,
progressMessage,
stopTyping: startDiscordTypingLoop(channel, logger, 'web replay delivery'),
};
},
async deliver({ job, context, buffer, usedSources = job.sources, missingSources = [] }) {
const progressMessage = context?.progressMessage;
try {
if (progressMessage?.edit) {
await progressMessage.edit({ content: buildStatusMessage(job, 'uploading'), allowedMentions: DEFAULT_ALLOWED_MENTIONS });
}
const attachment = new AttachmentBuilder(buffer, { name: `${sanitizeReplayTitleForFilename(job.title)}.mp4` });
const body = replayCaption.build({ job, usedSources, missingSources });
const uploadMessage = await channelIO.sendToChannel(context.channelId, body, { files: [attachment] }, DEFAULT_ALLOWED_MENTIONS);
if (!uploadMessage) throw new Error('Discord upload did not return a message');
const media = buildDiscordReplayMediaPayload({ message: uploadMessage, attachment: firstAttachmentFromMessage(uploadMessage), job });
if (!media) throw new Error('Discord upload did not include a replay attachment URL');
if (progressMessage?.edit) {
// The attachment URL is already durable once Discord returns it. A
// cosmetic progress-edit failure must not trigger a duplicate local
// replay or replace the successful media payload sent to clients.
await progressMessage.edit({ content: buildStatusMessage(job, 'ready'), allowedMentions: DEFAULT_ALLOWED_MENTIONS }).catch((err) => {
logger.warn('Discord replay uploaded but progress message update failed', { jobId: job.id, error: err.message });
});
}
return media;
} catch (err) {
err.progressMessage = progressMessage;
throw err;
} finally {
if (context?.stopTyping) context.stopTyping();
}
},
async completeFallback({ context, media }) {
const siteUrl = String(discordConfig.siteUrl || '').replace(/\/$/, '');
const publicUrl = siteUrl ? `${siteUrl}${media.url}` : media.url;
if (context?.progressMessage?.reply) {
await context.progressMessage.reply({
content: `Replay hosted by the rover server: ${publicUrl}`,
allowedMentions: DEFAULT_ALLOWED_MENTIONS,
});
}
},
});
}
const commandDependencies = {
logger,
client,
io,
@@ -151,6 +227,9 @@ const commands = createCommandHandlers({
// service into the shared command router keeps Discord and mirrored web-chat
// command behavior aligned without duplicating Home Assistant calls here.
homeAssistantService,
liftService,
neatoService,
isFeatureEnabled,
getGuildConfig,
setGuildConfig,
removeGuildConfig,
@@ -167,7 +246,9 @@ const commands = createCommandHandlers({
isLockdownAdminUser,
discordConfig,
config,
});
};
commandDependencies.transportHandlers = createDiscordTransportHandlers(commandDependencies);
const commands = createCommandHandlers(commandDependencies);
const integrations = createIntegrations({
logger,
@@ -209,16 +290,9 @@ const commands = createCommandHandlers({
const integrationHandlers = integrations.register();
function isTextCommand(content) {
const clean = String(content || '').trim();
const lower = clean.toLowerCase();
if (normalizedTimeStatusCommand && lower === normalizedTimeStatusCommand) return true;
if (!lower.startsWith(normalizedCommandPrefix)) return false;
const nextCharacter = clean.charAt(commandPrefix.length);
// Mirrored bridge commands must use the exact same whole-token prefix rule
// as the command router. If this check is looser than the router, normal
// bridge chat can be wrapped as a command reply even though no command runs.
return !nextCharacter || /\s/.test(nextCharacter);
// Both transports share this parser so command detection cannot drift from
// the dispatcher when an installation changes its prefix.
return parseCommandText(content, config).matched;
}
function isBridgeChannelMessage(message) {
@@ -263,7 +337,8 @@ function createBridgeMirroredCommandMessage(message) {
client.on('messageCreate', async (message) => {
try {
await integrationHandlers.handleBridgeInbound(message);
await commands.handleCommand(createBridgeMirroredCommandMessage(message));
const commandMessage = createBridgeMirroredCommandMessage(message);
await commands.handleCommand(createDiscordCommandRequest(commandMessage, { isAdminUser, isLockdownAdminUser }));
} catch (err) {
logger.warn('Error handling Discord message', err.message);
}
@@ -2,28 +2,12 @@
// Purpose: Handles event-bus announcements to Discord channels.
// Scope: Processes supported event types and posts formatted messages/embeds.
const { EmbedBuilder, AttachmentBuilder } = require('discord.js');
const io = require('../../../globals/io');
const { buildBatteryStatusEmbed, buildBatteryCaption } = require('../batteryEmbeds');
const {
DEFAULT_ALLOWED_MENTIONS,
createReplayJob,
createJobStatusEmitter,
createReplayCaptionBuilder,
startDiscordTypingLoop,
sanitizeReplayTitleForFilename,
firstAttachmentFromMessage,
buildDiscordReplayMediaPayload,
buildAcceptedMessage,
buildStatusMessage,
normalizeUserError,
} = require('../replayWorkflow');
function createBusEventHandler(deps) {
const { logger, discordConfig, roverManager, rovers, schedulePresenceRotation, formatDuration, sendToChannel, fetchChannel, buildReplayVideo, getActiveDrivers, getNickname, sanitizeMentions } = deps;
const { logger, discordConfig, roverManager, rovers, schedulePresenceRotation, formatDuration, sendToChannel } = deps;
const ADMIN_ALERT_EVENT_TYPES = new Set(['rover.online', 'rover.offline', 'rover.dockGuard', 'battery.warn', 'battery.urgent', 'battery.docked', 'battery.undocked', 'battery.charging.start', 'battery.charging.stop', 'battery.locked', 'battery.unlocked']);
let skippedFirstModeAnnouncement = false;
const jobStatus = createJobStatusEmitter({ io, logger, sanitizeMentions });
const replayCaption = createReplayCaptionBuilder({ io, rovers, getActiveDrivers, getNickname, sanitizeMentions });
function buildEmbed({ title, description, color, includeSiteUrl = true }) {
const embed = new EmbedBuilder().setTitle(title || 'Update').setColor(color || 0x2196f3);
@@ -55,66 +39,6 @@ function createBusEventHandler(deps) {
await sendToChannel(channelId, `${prefix}${content || ''}`.trim(), { embeds: payloadEmbeds, files: Array.isArray(files) ? files : undefined }, { parse: [], roles: pingRoleId ? [pingRoleId] : [] }, !pingRoleId);
}
async function sendReplayToChannel(channelId, requester, sources = [], explicitTitle = '', includeSidebar = true, jobId = null, requestedBy = null) {
if (!channelId) throw new Error('Replay channel not configured');
const job = createReplayJob({
id: jobId,
requester,
source: 'web',
title: explicitTitle,
sources,
includeSidebar,
requestedBy,
});
jobStatus.emit(job, 'accepted', { message: buildAcceptedMessage(job) });
const progressMessage = await sendToChannel(channelId, buildAcceptedMessage(job), {}, DEFAULT_ALLOWED_MENTIONS);
const channel = await fetchChannel(channelId);
const stopTyping = startDiscordTypingLoop(channel, logger, 'web replay delivery');
try {
jobStatus.emit(job, 'building', { message: buildStatusMessage(job, 'building') });
if (progressMessage?.edit) await progressMessage.edit({ content: buildStatusMessage(job, 'building'), allowedMentions: DEFAULT_ALLOWED_MENTIONS });
const { buffer, usedSources = job.sources, missingSources = [] } = await buildReplayVideo({
sources: job.sources,
title: job.title,
requester: job.requester,
includeSidebar: job.includeSidebar,
});
jobStatus.emit(job, 'uploading', { message: buildStatusMessage(job, 'uploading') });
if (progressMessage?.edit) await progressMessage.edit({ content: buildStatusMessage(job, 'uploading'), allowedMentions: DEFAULT_ALLOWED_MENTIONS });
const attachment = new AttachmentBuilder(buffer, { name: `${sanitizeReplayTitleForFilename(job.title)}.mp4` });
const body = replayCaption.build({ job, usedSources, missingSources });
const uploadMessage = await sendToChannel(channelId, body, { files: [attachment] }, DEFAULT_ALLOWED_MENTIONS);
if (!uploadMessage) throw new Error('Discord upload did not return a message');
const uploadedAttachment = firstAttachmentFromMessage(uploadMessage);
const media = buildDiscordReplayMediaPayload({ message: uploadMessage, attachment: uploadedAttachment, job });
if (!media) throw new Error('Discord upload did not include a replay attachment URL');
jobStatus.emit(job, 'ready', { message: buildStatusMessage(job, 'ready'), media });
if (progressMessage?.edit) await progressMessage.edit({ content: buildStatusMessage(job, 'ready'), allowedMentions: DEFAULT_ALLOWED_MENTIONS });
} catch (err) {
const message = normalizeUserError(err);
jobStatus.emit(job, 'failed', { message });
if (progressMessage?.edit) await progressMessage.edit({ content: sanitizeMentions(message), allowedMentions: DEFAULT_ALLOWED_MENTIONS });
throw err;
} finally {
stopTyping();
}
}
function handleReplayRequested(event) {
const payload = event?.payload || {};
sendReplayToChannel(
payload?.channelId,
payload?.requester,
payload?.sources || [],
payload?.title || '',
payload?.includeSidebar !== false,
payload?.jobId || null,
payload?.requestedBy || null,
).catch((err) => {
logger.warn('Replay send failed', { error: err.message });
});
}
function handleBusEvent(event) {
const { type, payload } = event || {};
const channels = discordConfig.channels || {};
@@ -200,9 +124,9 @@ function createBusEventHandler(deps) {
});
break;
}
case 'replay.requested':
handleReplayRequested(event);
break;
// Replay requests are deliberately consumed by replayDeliveryService.
// Discord registers only a preferred delivery provider, allowing the
// same request to fall back locally without a second event subscriber.
case 'buttonBox.discordStalkerPing': {
const message = payload?.message ? String(payload.message) : 'Button box chaos reward triggered.';
announce({
@@ -234,7 +158,7 @@ function createBusEventHandler(deps) {
}
}
return { handleBusEvent, handleReplayRequested };
return { handleBusEvent };
}
module.exports = { createBusEventHandler };
@@ -35,11 +35,26 @@ function registerHomeAssistantHooks(deps) {
return true;
}
function isBlockedByRoomControlLock() {
/*
The lock is meant to keep normal users and automated room-control
surfaces from changing the preferred room-light policy. Admins are the
exception because they may need to correct a single lamp, verify a Home
Assistant integration, or make an operational adjustment while the
public controls remain locked.
This server-side bypass is the authoritative rule. The React UI also
enables admin controls for usability, but clients are not trusted to
enforce permissions.
*/
return isLightControlLocked() && !isAdmin(socket);
}
socket.on('homeAssistant:toggle', async ({ entityId } = {}, cb = () => {}) => {
if (!hasPermission()) {
return cb({ error: 'Insufficient permissions to control Home Assistant' });
}
if (isLightControlLocked()) {
if (isBlockedByRoomControlLock()) {
return cb({ error: 'Room controls are locked' });
}
try {
@@ -55,7 +70,7 @@ function registerHomeAssistantHooks(deps) {
if (!hasPermission()) {
return cb({ error: 'Insufficient permissions to control Home Assistant' });
}
if (isLightControlLocked()) {
if (isBlockedByRoomControlLock()) {
return cb({ error: 'Room controls are locked' });
}
try {
@@ -71,7 +86,7 @@ function registerHomeAssistantHooks(deps) {
if (!hasPermission()) {
return cb({ error: 'Insufficient permissions to control Home Assistant' });
}
if (isLightControlLocked()) {
if (isBlockedByRoomControlLock()) {
return cb({ error: 'Room controls are locked' });
}
try {
@@ -90,7 +105,7 @@ function registerHomeAssistantHooks(deps) {
if (!hasPermission()) {
return cb({ error: 'Insufficient permissions to control Home Assistant' });
}
if (isLightControlLocked()) {
if (isBlockedByRoomControlLock()) {
return cb({ error: 'Room controls are locked' });
}
try {
@@ -426,14 +426,26 @@ function createRuntimeEngine(deps) {
async function setLightsLockedOn(nextValue, options = {}) {
const next = Boolean(nextValue);
const targetState = options?.targetState === 'off' ? 'off' : 'on';
const forceApply = Boolean(options.forceApply);
const nextLockState = next ? targetState : null;
const changed = runtime.lightsLockState !== nextLockState;
runtime.lightsLockState = nextLockState;
if (runtime.lightsLockState != null) {
if ((changed || forceApply) && enabled) {
if (changed && enabled) {
const source = String(options?.source || 'homeAssistant:setLightsLockedOn');
/*
A room-light lock is a policy boundary, not an ongoing reconciliation
loop. Entering locked-on or locked-off sets every configured room
control to the preferred state once so the room starts from the
requested condition. After that first transition, the server leaves
Home Assistant alone so out-of-band controls such as wall switches,
Home Assistant dashboards, or vendor apps can still adjust individual
lights without being periodically overwritten.
Older callers may still pass forceApply from the previous behavior.
It is intentionally ignored here because repeated lock requests must
not become repeated light commands.
*/
if (runtime.lightsLockState === 'on') {
// The lock-on path is intentionally stronger than a normal bulk
// turn_on. It makes actual light entities white while still turning
@@ -151,7 +151,6 @@ async function handleTrigger(event = {}) {
if (action === LIGHTS_LOCK_TOGGLE_ACTION) {
const lockedOn = await toggleLightsLockedOn({
source: 'ha-button:lightsLockToggle',
forceApply: true,
});
const message = lockedOn ? LIGHTS_LOCKED_TTS : LIGHTS_UNLOCKED_TTS;
sendTtsToNonPrivateRovers(message);
+22
View File
@@ -73,6 +73,12 @@ function clearIdleTimer() {
function scheduleIdleTimer() {
if (runtime.timer) return;
if (runtime.idleActionsCompleted) {
logger.info('Idle timer not scheduled; idle actions already completed for this no-operator window', {
lastTriggeredAt: runtime.lastTriggeredAt,
});
return;
}
runtime.deadlineAt = Date.now() + IDLE_TIMEOUT_MS;
logger.info('Idle timer scheduled', {
timeoutMs: IDLE_TIMEOUT_MS,
@@ -87,6 +93,13 @@ function scheduleIdleTimer() {
return;
}
runtime.lastTriggeredAt = Date.now();
/*
Mark this idle window as handled before running the action pipeline. The
pipeline can take time and can call into services that emit their own
state changes; setting the guard first prevents any nested refresh from
scheduling a second timer for the same continuous no-operator period.
*/
runtime.idleActionsCompleted = true;
const results = await runIdleActions();
logger.info('Idle automation executed', {
idleMs: IDLE_TIMEOUT_MS,
@@ -102,6 +115,15 @@ function refreshIdleState() {
logger.info('Idle state refresh', activity);
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;
}
scheduleIdleTimer();
+1
View File
@@ -5,6 +5,7 @@ const runtime = {
timer: null,
deadlineAt: null,
lastTriggeredAt: null,
idleActionsCompleted: false,
};
module.exports = {
+14 -11
View File
@@ -7,7 +7,7 @@ const logger = require('../../globals/logger').child('liftService');
const { loadConfig } = require('../../helpers/configLoader');
const { isFeatureEnabled } = require('../../helpers/features');
const { getMode, MODES } = require('../modeManager');
const { isLockdownAdmin } = require('../roleService');
const { isAdmin, isLockdownAdmin } = require('../roleService');
const {
homeAssistantEvents,
getRawEntitySnapshot,
@@ -186,13 +186,20 @@ if (featureEnabled) {
homeAssistantEvents.on('status', emitUpdate);
io.on('connection', (socket) => {
function assertFeatureAccess() {
const mode = getMode();
// Lift is a public activity feature in open and turns modes. Restricted
// access modes mirror the rest of the server: admin mode admits normal
// admins, while lockdown admits only the explicitly stronger lockdown
// role. Enforcing this in the owning service keeps UI buttons and text
// command behavior aligned instead of trusting individual callers.
if (mode === MODES.ADMIN && !isAdmin(socket)) throw new Error('Admin mode: admins only');
if (mode === MODES.LOCKDOWN && !isLockdownAdmin(socket)) throw new Error('Server in lockdown');
}
socket.on('lift:up', async (_, cb = () => {}) => {
try {
if (getMode() === MODES.LOCKDOWN && !isLockdownAdmin(socket)) {
throw new Error('Server in lockdown');
}
// Lift movement is now a public activity feature. Lockdown still wins
// above because that mode is the global safety/admin gate for the room.
assertFeatureAccess();
const resp = await moveUp(socket.id || 'socket');
cb({ success: true, ...resp });
} catch (err) {
@@ -202,11 +209,7 @@ if (featureEnabled) {
socket.on('lift:down', async (_, cb = () => {}) => {
try {
if (getMode() === MODES.LOCKDOWN && !isLockdownAdmin(socket)) {
throw new Error('Server in lockdown');
}
// Public access intentionally mirrors lift:up so both directions share
// the same policy and cannot drift into different permission behavior.
assertFeatureAccess();
const resp = await moveDown(socket.id || 'socket');
cb({ success: true, ...resp });
} catch (err) {
+14 -18
View File
@@ -8,7 +8,7 @@ const { loadConfig } = require('../../helpers/configLoader');
const { isFeatureEnabled } = require('../../helpers/features');
const { isVerified } = require('../verificationService');
const { getMode, MODES } = require('../modeManager');
const { isLockdownAdmin } = require('../roleService');
const { isAdmin, isLockdownAdmin } = require('../roleService');
const {
homeAssistantEvents,
getRawEntitySnapshot,
@@ -269,17 +269,19 @@ function hasVerifiedSockets() {
if (featureEnabled) {
io.on('connection', (socket) => {
function assertLockdownAccess() {
if (getMode() === MODES.LOCKDOWN && !isLockdownAdmin(socket)) {
throw new Error('Server in lockdown');
}
function assertFeatureAccess() {
const mode = getMode();
// Neato shares the same public-activity policy as lift: everyone may use
// it in open/turns modes, admin mode requires an admin, and lockdown
// requires a lockdown admin. This service-level gate protects every socket
// action even if a future client bypasses the current UI presentation.
if (mode === MODES.ADMIN && !isAdmin(socket)) throw new Error('Admin mode: admins only');
if (mode === MODES.LOCKDOWN && !isLockdownAdmin(socket)) throw new Error('Server in lockdown');
}
socket.on('neato:start', async (_, cb = () => {}) => {
try {
assertLockdownAccess();
// Neato commands are public activity features. The lockdown check above
// remains the room-wide safety/admin gate when the server is restricted.
assertFeatureAccess();
await startCleaning();
cb({ success: true });
} catch (err) {
@@ -289,8 +291,7 @@ if (featureEnabled) {
socket.on('neato:sendHome', async (_, cb = () => {}) => {
try {
assertLockdownAccess();
// Keep send-home public for consistency with the rest of the Neato card.
assertFeatureAccess();
await sendHome();
cb({ success: true });
} catch (err) {
@@ -300,8 +301,7 @@ if (featureEnabled) {
socket.on('neato:locate', async (_, cb = () => {}) => {
try {
assertLockdownAccess();
// Locate is a public activity action; lockdown still blocks it above.
assertFeatureAccess();
await locateRobot();
cb({ success: true });
} catch (err) {
@@ -311,9 +311,7 @@ if (featureEnabled) {
socket.on('neato:clearErrors', async (_, cb = () => {}) => {
try {
assertLockdownAccess();
// Error clearing is grouped with the public Neato controls so the UI does
// not show a button that only some public users can actually run.
assertFeatureAccess();
await clearErrors();
cb({ success: true });
} catch (err) {
@@ -323,9 +321,7 @@ if (featureEnabled) {
socket.on('neato:powerCycle', async (_, cb = () => {}) => {
try {
assertLockdownAccess();
// Power cycle follows the same public policy as the rest of the card;
// operational safety remains controlled by lockdown mode.
assertFeatureAccess();
await powerCycle();
cb({ success: true });
} catch (err) {
@@ -1,16 +1,15 @@
// Discord Deter Command
// Operator Deter Command
// Purpose: Handles deterrence moderation commands for lockdown admins.
// Scope: Supports list, ban, and unban subcommands.
const { mask, resolveIdentitySelector } = require('./resolvers');
const { getCommandConfig } = require('../../operatorCommandService/config');
function createDeterCommand({ listDeterredUsers, listVerifiedUsers, deterUser, undeterUser, isLockdownAdminUser, sanitizeMentions, discordConfig }) {
// Moderation errors often get copied into Discord chat, so they should show
// the configured bot prefix instead of the legacy default when several bots
// are present in the same server.
const commandPrefix = String(discordConfig?.commandPrefix || 'rs').trim() || 'rs';
function createDeterCommand({ listDeterredUsers, listVerifiedUsers, deterUser, undeterUser, sanitizeMentions, config }) {
// Moderation usage errors use the same core prefix shown by organized help.
const { prefix: commandPrefix } = getCommandConfig(config);
return async function handleDeterCommand(message, tokens) {
if (!isLockdownAdminUser(message.author?.id)) {
if (!message.actor?.isLockdownAdmin) {
await message.reply({ content: 'Only lockdown admins can manage deterred users.', allowedMentions: { parse: [], repliedUser: false } });
return;
}
@@ -33,7 +32,7 @@ function createDeterCommand({ listDeterredUsers, listVerifiedUsers, deterUser, u
// full remaining text is now always the selector, which lets lockdown
// admins deter multi-word nicknames without quoting or delimiter rules.
const stableSelector = verifiedMatch.record?.userId || verifiedMatch.record?.id || verifiedMatch.record?.cookieUserId || selector;
const deterred = deterUser(stableSelector, { actor: message.author?.id || null });
const deterred = deterUser(stableSelector, { actor: message.actor?.id || null });
return message.reply({ content: sanitizeMentions(`${deterred.created ? 'Deterred' : 'Updated deterrence for'} ${deterred.nickname || 'unknown'} (${mask(deterred.cookieUserId)}).`), allowedMentions: { parse: [], repliedUser: false } });
} catch (err) {
return message.reply({ content: sanitizeMentions(`Failed to deter user: ${err.message}`), allowedMentions: { parse: [], repliedUser: false } });
@@ -45,7 +44,7 @@ function createDeterCommand({ listDeterredUsers, listVerifiedUsers, deterUser, u
try {
const resolved = resolveIdentitySelector(selector, listDeterredUsers(), { includeId: true });
if (resolved.error) return message.reply({ content: sanitizeMentions(resolved.error), allowedMentions: { parse: [], repliedUser: false } });
const removed = undeterUser(resolved.record.id || resolved.record.cookieUserId || selector, message.author?.id || null);
const removed = undeterUser(resolved.record.id || resolved.record.cookieUserId || selector, message.actor?.id || null);
return message.reply({ content: sanitizeMentions(`Removed deterrence for ${removed.nickname || 'unknown'} (${mask(removed.cookieUserId)}).`), allowedMentions: { parse: [], repliedUser: false } });
} catch (err) {
return message.reply({ content: sanitizeMentions(`Failed to remove deterrence: ${err.message}`), allowedMentions: { parse: [], repliedUser: false } });
@@ -1,7 +1,7 @@
// Discord Goal Command
// Operator Goal Command
// Purpose: Handles global objective view/update/clear operations.
// Scope: Allows read by all and write by admins.
function createGoalCommand({ getGlobalObjective, setGlobalObjective, clearGlobalObjective, isAdminUser, sanitizeMentions }) {
function createGoalCommand({ getGlobalObjective, setGlobalObjective, clearGlobalObjective, sanitizeMentions }) {
return async function handleGoalCommand(message, tokens) {
const query = tokens.join(' ').trim();
const lower = query.toLowerCase();
@@ -10,16 +10,16 @@ function createGoalCommand({ getGlobalObjective, setGlobalObjective, clearGlobal
await message.reply({ content: goal?.text ? `Global objective: ${sanitizeMentions(goal.text)}` : 'No global objective set.', allowedMentions: { parse: [], repliedUser: false } });
return;
}
if (!isAdminUser(message.author.id)) {
if (!message.actor?.isAdmin) {
await message.reply({ content: 'Only admins can update the global objective.', allowedMentions: { parse: [], repliedUser: false } });
return;
}
try {
if (lower === 'clear') {
clearGlobalObjective({ by: message.author?.id || null });
clearGlobalObjective({ by: message.actor?.id || null });
await message.reply({ content: 'Global objective cleared.', allowedMentions: { parse: [], repliedUser: false } });
} else {
setGlobalObjective(query, { by: message.author?.id || null });
setGlobalObjective(query, { by: message.actor?.id || null });
await message.reply({ content: sanitizeMentions(`Global objective set: ${query}`), allowedMentions: { parse: [], repliedUser: false } });
}
} catch (err) {
@@ -1,7 +1,8 @@
// Discord Kick Command
// Operator Kick Command
// Purpose: Removes a connected user from their current rover without applying any persistent moderation state.
// Scope: Resolves an online driver, sends them a UI-visible reason, and releases their current rover assignment.
const Fuse = require('fuse.js');
const { getCommandConfig } = require('../../operatorCommandService/config');
const DEFAULT_KICK_REASON = 'Removed from rover by admin.';
@@ -97,11 +98,11 @@ function resolveKickTarget(selector, candidates, commandPrefix = 'rs') {
return { target: first.item };
}
function createKickCommand({ io, roverManager, getNickname, sanitizeMentions, discordConfig }) {
function createKickCommand({ io, roverManager, getNickname, sanitizeMentions, config }) {
// The kick parser itself does not need the prefix, but its validation message
// does. Keeping this local avoids passing display-only config through the
// lower-level fuzzy target resolver except when an error string is needed.
const commandPrefix = String(discordConfig?.commandPrefix || 'rs').trim() || 'rs';
const { prefix: commandPrefix } = getCommandConfig(config);
return async function handleKickCommand(message, rawText) {
const { selector, reason } = splitSelectorAndReason(rawText);
const assignmentService = require('../../assignmentService');
@@ -127,7 +128,7 @@ function createKickCommand({ io, roverManager, getNickname, sanitizeMentions, di
title: 'Removed by admin',
message: removalReason,
reasonCode: 'admin-kick',
actor: message.author?.id || null,
actor: message.actor?.id || null,
});
await message.reply({
content: sanitizeMentions(`Removed ${target.label} from ${target.roverId}: ${removalReason}`),
@@ -0,0 +1,27 @@
// Lift Feature Command
// Purpose: Exposes lift state and movement through the shared text command route.
// Scope: Delegates interlocks, cooldowns, Home Assistant access, and runtime safety to liftService.
function describeState(state = {}) {
const position = state.position || 'unknown';
const connection = state.connected ? 'connected' : 'offline';
const activity = state.busy ? `moving ${state.target || ''}`.trim() : 'idle';
return `Lift: ${connection}; position ${position}; ${activity}.`;
}
function createLiftCommand({ liftService, sanitizeMentions }) {
return async function handleLiftCommand(message, tokens = []) {
const action = String(tokens.shift() || 'status').toLowerCase();
if (action === 'status') return message.reply({ content: describeState(liftService.getState()) });
try {
if (action === 'up') await liftService.moveUp(`command:${message.actor?.id || 'unknown'}`);
else if (action === 'down') await liftService.moveDown(`command:${message.actor?.id || 'unknown'}`);
else return message.reply({ content: 'Invalid lift command. Use `lift status`, `lift up`, or `lift down`.' });
return message.reply({ content: `Lift moving ${action}.` });
} catch (err) {
return message.reply({ content: sanitizeMentions(`Lift command failed: ${err.message}`) });
}
};
}
module.exports = { createLiftCommand };
@@ -1,6 +1,8 @@
// Discord Lights Command
// Operator Lights Command
// Purpose: Handles admin room-light lock policy commands from Discord and web chat.
// Scope: Delegates all actual Home Assistant policy behavior to homeAssistantService.
const { getCommandConfig } = require('../../operatorCommandService/config');
function describeLightPolicy(lightPolicy = {}) {
// The HA service exposes both the newer explicit lockState and the older
// lockedOn boolean. Prefer lockState because it can distinguish locked-on
@@ -12,10 +14,10 @@ function describeLightPolicy(lightPolicy = {}) {
return 'Room lights are unlocked.';
}
function createLightsCommand({ homeAssistantService, sanitizeMentions, discordConfig }) {
function createLightsCommand({ homeAssistantService, sanitizeMentions, config }) {
// The HA policy behavior is prefix-agnostic; this value is only used so
// invalid-command guidance points admins at this bot instance's namespace.
const commandPrefix = String(discordConfig?.commandPrefix || 'rs').trim() || 'rs';
const { prefix: commandPrefix } = getCommandConfig(config);
return async function handleLightsCommand(message, tokens = []) {
// Defaulting to status makes the bare lights command safe to type while
// still exposing explicit mutating forms under the configured prefix. This
@@ -52,12 +54,11 @@ function createLightsCommand({ homeAssistantService, sanitizeMentions, discordCo
// The bot command intentionally calls the shared policy setter instead of
// issuing direct Home Assistant entity commands. That keeps all secondary
// behavior centralized: web UI controls become disabled through the
// session lightPolicy update, lock-on still forces configured lights to
// white where possible, and commandService sees the same update event that
// forces rover lasers off while the room is locked on.
// session lightPolicy update, entering lock-on still sets configured
// lights to white where possible once, and commandService sees the same
// update event that forces rover lasers off while the room is locked on.
await homeAssistantService.setLightsLockedOn(locked, {
source: `bot-command:lights:${action}`,
forceApply: true,
});
await message.reply({
@@ -1,12 +1,13 @@
// Discord Lock Command
// Operator Lock Command
// Purpose: Handles lock and unlock operations for rover availability control.
// Scope: Applies lock state updates for a single rover ID.
const { resolveRoverSelector } = require('./resolvers');
const { getCommandConfig } = require('../../operatorCommandService/config');
function createLockCommand({ lockRover, sanitizeMentions, rovers, discordConfig }) {
function createLockCommand({ lockRover, sanitizeMentions, rovers, config }) {
// Only the user-facing example depends on the prefix. The actual lock logic
// still receives the already-parsed rover selector from the shared router.
const commandPrefix = String(discordConfig?.commandPrefix || 'rs').trim() || 'rs';
const { prefix: commandPrefix } = getCommandConfig(config);
return async function handleLockCommand(message, roverId, locked) {
if (!roverId) {
await message.reply({ content: `Specify a rover ID. Example: \`${commandPrefix} lock alpha\``, allowedMentions: { parse: [], repliedUser: false } });
@@ -21,7 +22,9 @@ function createLockCommand({ lockRover, sanitizeMentions, rovers, discordConfig
// Mutate by canonical id after fuzzy resolution. This avoids letting a
// display-name typo create a new path through roverManager, and it also
// makes the response name match the rover that was actually changed.
lockRover(resolved.id, locked, { reason: 'discord' });
// Preserve the established Discord reason while allowing other adapters
// to identify themselves without pretending their request came from Discord.
lockRover(resolved.id, locked, { reason: message.transport === 'discord' ? 'discord' : 'web-chat' });
await message.reply({ content: sanitizeMentions(`${locked ? 'Locked' : 'Unlocked'} ${resolved.label || resolved.id}.`), allowedMentions: { parse: [], repliedUser: false } });
} catch (err) {
await message.reply({ content: sanitizeMentions(`Failed: ${err.message}`), allowedMentions: { parse: [], repliedUser: false } });
@@ -1,7 +1,7 @@
// Discord Mode Command
// Purpose: Handles mode updates from Discord admins through the configured bot prefix.
// Operator Mode Command
// Purpose: Handles mode updates from authorized operators through the shared command prefix.
// Scope: Validates mode values and applies mode changes with optional reason text.
function createModeCommand({ MODES, setMode, setAdminReason, isLockdownAdminUser, sanitizeMentions }) {
function createModeCommand({ MODES, setMode, setAdminReason, sanitizeMentions }) {
return async function handleModeCommand(message, tokens = []) {
const next = String(tokens.shift() || '').toLowerCase();
const reasonText = tokens.join(' ').trim();
@@ -10,9 +10,9 @@ function createModeCommand({ MODES, setMode, setAdminReason, isLockdownAdminUser
return;
}
try {
const role = isLockdownAdminUser(message.author?.id) ? 'lockdown' : 'admin';
setMode(next, { data: { role, user: { username: `discord:${message.author?.username || 'unknown'}` } } });
if (reasonText) setAdminReason(reasonText, { by: message.author?.id || null });
const role = message.actor?.isLockdownAdmin ? 'lockdown' : 'admin';
setMode(next, { data: { role, user: { username: `${message.transport}:${message.actor?.label || 'unknown'}` } } });
if (reasonText) setAdminReason(reasonText, { by: message.actor?.id || null });
await message.reply({ content: sanitizeMentions(`Mode set to ${next}.`), allowedMentions: { parse: [], repliedUser: false } });
} catch (err) {
await message.reply({ content: sanitizeMentions(`Failed to set mode: ${err.message}`), allowedMentions: { parse: [], repliedUser: false } });
@@ -0,0 +1,35 @@
// Neato Feature Command
// Purpose: Exposes Neato state and supported actions through the shared text command route.
// Scope: Delegates device availability, Home Assistant calls, and operational errors to neatoService.
function describeState(state = {}) {
const telemetry = state.telemetry || {};
const connection = state.connected ? 'connected' : 'offline';
return `Neato: ${connection}; state ${telemetry.robotState || 'unknown'}; battery ${telemetry.batteryLevel ?? 'unknown'}%.`;
}
function createNeatoCommand({ neatoService, sanitizeMentions }) {
return async function handleNeatoCommand(message, tokens = []) {
const action = String(tokens.shift() || 'status').toLowerCase();
if (action === 'status') return message.reply({ content: describeState(neatoService.getState()) });
const actions = {
start: ['now cleaning', neatoService.startCleaning],
home: ['returning home', neatoService.sendHome],
locate: ['playing locate sound', neatoService.locateRobot],
'clear-errors': ['clearing errors', neatoService.clearErrors],
};
const selected = actions[action];
if (!selected) {
return message.reply({ content: 'Invalid Neato command. Use `neato status`, `neato start`, `neato home`, `neato locate`, or `neato clear-errors`.' });
}
try {
await selected[1]();
return message.reply({ content: `Neato is ${selected[0]}.` });
} catch (err) {
return message.reply({ content: sanitizeMentions(`Neato command failed: ${err.message}`) });
}
};
}
module.exports = { createNeatoCommand };
@@ -1,7 +1,7 @@
// Discord Reason Command
// Operator Reason Command
// Purpose: Handles admin-mode reason view/update/clear operations.
// Scope: Allows read by all and write by admins.
function createReasonCommand({ getAdminReason, setAdminReason, clearAdminReason, isAdminUser, sanitizeMentions }) {
function createReasonCommand({ getAdminReason, setAdminReason, clearAdminReason, sanitizeMentions }) {
return async function handleReasonCommand(message, tokens) {
const query = tokens.join(' ').trim();
const lower = query.toLowerCase();
@@ -10,16 +10,16 @@ function createReasonCommand({ getAdminReason, setAdminReason, clearAdminReason,
await message.reply({ content: reason?.text ? `Admin mode reason: ${sanitizeMentions(reason.text)}` : 'No admin mode reason set.', allowedMentions: { parse: [], repliedUser: false } });
return;
}
if (!isAdminUser(message.author.id)) {
if (!message.actor?.isAdmin) {
await message.reply({ content: 'Only admins can update the admin mode reason.', allowedMentions: { parse: [], repliedUser: false } });
return;
}
try {
if (lower === 'clear') {
clearAdminReason({ by: message.author?.id || null });
clearAdminReason({ by: message.actor?.id || null });
await message.reply({ content: 'Admin mode reason cleared.', allowedMentions: { parse: [], repliedUser: false } });
} else {
setAdminReason(query, { by: message.author?.id || null });
setAdminReason(query, { by: message.actor?.id || null });
await message.reply({ content: sanitizeMentions(`Admin mode reason set: ${query}`), allowedMentions: { parse: [], repliedUser: false } });
}
} catch (err) {
@@ -1,4 +1,4 @@
// Discord Command Resolvers
// Operator Command Resolvers
// Purpose: Provides shared selector parsing and fuzzy matching for command handlers.
// Scope: Keeps potentially destructive commands from each inventing their own lookup rules.
const Fuse = require('fuse.js');
@@ -1,14 +1,14 @@
// Discord Verify Command
// Operator Verify Command
// Purpose: Handles verified-user moderation commands for lockdown admins.
// Scope: Supports list and remove subcommands.
const { mask, resolveIdentitySelector } = require('./resolvers');
const { getCommandConfig } = require('../../operatorCommandService/config');
function createVerifyCommand({ listVerifiedUsers, removeVerifiedUser, isLockdownAdminUser, sanitizeMentions, discordConfig }) {
// Verification usage text follows the configured prefix for the same reason
// as the command router: each bot instance needs its own command namespace.
const commandPrefix = String(discordConfig?.commandPrefix || 'rs').trim() || 'rs';
function createVerifyCommand({ listVerifiedUsers, removeVerifiedUser, sanitizeMentions, config }) {
// Usage text comes from the same core prefix that both transports parse.
const { prefix: commandPrefix } = getCommandConfig(config);
return async function handleVerifyCommand(message, tokens) {
if (!isLockdownAdminUser(message.author?.id)) {
if (!message.actor?.isLockdownAdmin) {
await message.reply({ content: 'Only lockdown admins can manage verified users.', allowedMentions: { parse: [], repliedUser: false } });
return;
}
@@ -29,7 +29,7 @@ function createVerifyCommand({ listVerifiedUsers, removeVerifiedUser, isLockdown
// The command resolver only turns a human-friendly or fuzzy nickname
// into the stable cookie id so the service does not need Discord/Web
// command concerns baked into its storage API.
const removed = removeVerifiedUser(resolved.record.userId || resolved.record.id || resolved.record.cookieUserId, message.author?.id || null);
const removed = removeVerifiedUser(resolved.record.userId || resolved.record.id || resolved.record.cookieUserId, message.actor?.id || null);
return message.reply({ content: `Removed verified user ${sanitizeMentions(removed.nickname || 'unknown')} (${mask(removed.cookieUserId)}).`, allowedMentions: { parse: [], repliedUser: false } });
} catch (err) {
return message.reply({ content: sanitizeMentions(`Failed to remove verified user: ${err.message}`), allowedMentions: { parse: [], repliedUser: false } });
@@ -0,0 +1,45 @@
// Operator Command Configuration
// Purpose: Owns transport-neutral command names used by site chat and optional integrations.
// Scope: Prevents Discord configuration from defining whether core server commands can be parsed.
const { loadConfig } = require('../../helpers/configLoader');
function getCommandConfig(config = loadConfig()) {
const commandConfig = config.commands || {};
const prefix = String(commandConfig.prefix || 'rs').trim() || 'rs';
const timeStatusCommand = commandConfig.timeStatusCommand === null
? ''
: String(commandConfig.timeStatusCommand || 'ts').trim();
return { prefix, timeStatusCommand };
}
function parseCommandText(text, config = loadConfig()) {
const clean = String(text || '').trim();
const lower = clean.toLowerCase();
const { prefix, timeStatusCommand } = getCommandConfig(config);
const normalizedPrefix = prefix.toLowerCase();
const normalizedTimeStatus = timeStatusCommand.toLowerCase();
if (normalizedTimeStatus && lower === normalizedTimeStatus) {
return { matched: true, kind: 'time-status', body: '', action: 'time-status', tokens: [] };
}
if (!lower.startsWith(normalizedPrefix)) return { matched: false };
const nextCharacter = clean.charAt(prefix.length);
if (nextCharacter && !/\s/.test(nextCharacter)) return { matched: false };
const body = clean.slice(prefix.length).trim();
const tokens = body ? body.split(/\s+/) : [];
return {
matched: true,
kind: 'prefixed',
body,
action: String(tokens[0] || '').toLowerCase(),
tokens,
};
}
module.exports = {
getCommandConfig,
parseCommandText,
};
@@ -0,0 +1,46 @@
// Operator Command Help
// Purpose: Generates organized command help from one descriptive command catalogue.
// Scope: Keeps shared command discovery consistent while allowing Discord-only extensions to stay transport-specific.
const { CATEGORIES, buildCommandRegistry } = require('./registry');
function renderDetailed(name, entry, isFeatureEnabled) {
const details = [`**${name}**`, entry.summary];
if (entry.access) details.push(`Permission: ${entry.access}`);
if (entry.requiredFeature) details.push(`Required feature: ${entry.requiredFeature}`);
if (entry.requiredFeature && !isFeatureEnabled(entry.requiredFeature)) details.push('Availability: unavailable on this server');
details.push('Usage:', ...entry.usage.map((usage) => `- \`${usage}\``));
return details.join('\n');
}
function formatHelp({ commandPrefix = 'rs', timeStatusCommand = 'ts', topic = '', includeDiscord = true, isFeatureEnabled = () => true } = {}) {
const prefix = String(commandPrefix || 'rs').trim() || 'rs';
const timeCommand = timeStatusCommand ? String(timeStatusCommand).trim() : '';
const entries = buildCommandRegistry(prefix, timeCommand);
const normalizedTopic = String(topic || '').trim().toLowerCase();
if (entries[normalizedTopic] && (normalizedTopic !== 'bridge' || includeDiscord)) {
return renderDetailed(normalizedTopic, entries[normalizedTopic], isFeatureEnabled);
}
const requestedCategory = normalizedTopic === 'feature' ? 'features' : normalizedTopic;
const categoryNames = requestedCategory && CATEGORIES[requestedCategory]
? [requestedCategory]
: ['system', 'admin', 'features', ...(includeDiscord ? ['discord'] : [])];
const output = ['**Rover Bot Commands**'];
for (const categoryName of categoryNames) {
if (categoryName === 'discord' && !includeDiscord) continue;
const category = CATEGORIES[categoryName];
output.push('', `**${category.title}**`);
for (const name of category.names) {
const entry = entries[name];
if (!entry?.usage?.length) continue;
const availability = entry.requiredFeature && !isFeatureEnabled(entry.requiredFeature) ? ' *(unavailable)*' : '';
output.push(`\`${entry.usage[0]}\`${entry.summary}${availability}`);
}
}
output.push('', `Use \`${prefix} help <command|category>\` for details.`);
return output.join('\n');
}
module.exports = { formatHelp };
@@ -0,0 +1,163 @@
// Operator Command Service
// Purpose: Routes transport-neutral operator command requests to registered server handlers.
// Scope: Owns shared parsing, authorization, feature gating, help, and execution without importing Discord.js.
const { formatHelp } = require('./help');
const { createLockCommand } = require('./commands/lock');
const { createModeCommand } = require('./commands/mode');
const { createReasonCommand } = require('./commands/reason');
const { createGoalCommand } = require('./commands/goal');
const { createVerifyCommand } = require('./commands/verify');
const { createDeterCommand } = require('./commands/deter');
const { createLightsCommand } = require('./commands/lights');
const { createKickCommand } = require('./commands/kick');
const { createLiftCommand } = require('./commands/lift');
const { createNeatoCommand } = require('./commands/neato');
const { getCommandConfig } = require('./config');
const { buildCommandRegistry } = require('./registry');
function createCommandHandlers(deps) {
const {
getMode,
MODES,
} = deps;
// The prefix belongs to the always-available command system so every
// transport parses the same namespace instead of maintaining local defaults.
const { prefix: commandPrefix, timeStatusCommand } = getCommandConfig(deps.config);
// The legacy time command is a bare word rather than a prefixed command. It
// therefore needs its own configurable value, and `null` intentionally
// disables it so multiple bots do not all answer `ts` in the same channel.
// Lowercase cached copies avoid re-normalizing every message and keep command
// matching case-insensitive without changing the original configured text
// that is shown in help output.
const normalizedCommandPrefix = commandPrefix.toLowerCase();
const normalizedTimeStatusCommand = timeStatusCommand.toLowerCase();
const registry = buildCommandRegistry(commandPrefix, timeStatusCommand);
// Status, time status, replay delivery, and transport extensions may have
// different presentation needs. Adapters inject those focused handlers while
// the core retains parsing, policy, and command discovery ownership.
const transportHandlers = deps.transportHandlers || {};
const handleStatusCommand = transportHandlers.status;
const handleReplayCommand = deps.createReplayTextCommand
? deps.createReplayTextCommand(deps)
: transportHandlers.replay;
const handleLockCommand = createLockCommand(deps);
const handleModeCommand = createModeCommand(deps);
const handleReasonCommand = createReasonCommand(deps);
const handleGoalCommand = createGoalCommand(deps);
const handleVerifyCommand = createVerifyCommand(deps);
const handleDeterCommand = createDeterCommand(deps);
const handleBridgeCommand = transportHandlers.bridge;
const handleTimeStatusCommand = transportHandlers.timeStatus;
const handleLightsCommand = createLightsCommand(deps);
const handleKickCommand = createKickCommand(deps);
const handleLiftCommand = createLiftCommand(deps);
const handleNeatoCommand = createNeatoCommand(deps);
function stripCommandPrefix(content) {
const trimmed = String(content || '').trim();
const lower = trimmed.toLowerCase();
if (!lower.startsWith(normalizedCommandPrefix)) return null;
const nextCharacter = trimmed.charAt(commandPrefix.length);
// Prefixes are matched as whole command tokens so an instance using `rs`
// still ignores ordinary words such as `rsvp`. This mirrors the old regex
// behavior while letting each Discord bot instance use its own prefix.
if (nextCharacter && !/\s/.test(nextCharacter)) return null;
return trimmed.slice(commandPrefix.length).trim();
}
async function handleCommand(request) {
if (request.actor?.bot) return;
const content = (request.content || '').trim();
const lower = content.toLowerCase();
// Commands are intentionally matched as whole prefixes. The previous
// startsWith checks made ordinary messages such as "rsvp" or "tshirt" look
// like commands, which is especially bad now that web chat will run the
// same server-side dispatcher before broadcasting user text.
if (normalizedTimeStatusCommand && lower === normalizedTimeStatusCommand) return handleTimeStatusCommand?.(request);
const commandBody = stripCommandPrefix(content);
if (commandBody === null) return;
const tokens = commandBody ? commandBody.split(/\s+/) : [];
const action = (tokens.shift() || '').toLowerCase();
const rest = tokens.join(' ').trim();
const isAdmin = Boolean(request.actor?.isAdmin);
const isLockdownAdmin = Boolean(request.actor?.isLockdownAdmin);
const mode = getMode();
const commandDefinition = registry[action];
if (commandDefinition?.requiredFeature && !deps.isFeatureEnabled(commandDefinition.requiredFeature)) {
await request.reply({ content: `${commandDefinition.unavailableLabel || commandDefinition.requiredFeature} feature is not configured.` });
return;
}
// Actions in this set can change operational safety or access policy, so
// lockdown mode narrows them from normal admins to lockdown admins. Room
// light locking belongs here because it can force the physical room lights
// on and disables ordinary Home Assistant room controls for everyone else.
const moderationActions = new Set(['lock', 'unlock', 'mode', 'goal', 'reason', 'verify', 'deter', 'lights', 'kick', 'lift', 'neato']);
const isAccessModeCommand = commandDefinition?.permission === 'access-mode';
// Feature commands are public activities while access is open or managed
// by turns. In admin mode they follow the same admin-only boundary as rover
// access, and lockdown continues to require the stricter lockdown role.
// Keeping this policy in the shared dispatcher makes web chat and Discord
// behave identically instead of each transport interpreting modes itself.
if (isAccessModeCommand && mode === MODES.ADMIN && !isAdmin) {
await request.reply({ content: 'Admin mode: only admins can run feature commands.', allowedMentions: { parse: [], repliedUser: false } });
return;
}
if (!isAccessModeCommand && !isAdmin && action !== '' && action !== 'status' && action !== 'help' && action !== 'replay' && action !== 'bridge' && action !== 'goal' && action !== 'reason' && action !== 'verify' && action !== 'deter') {
await request.reply({ content: 'Only admins can run that command.', allowedMentions: { parse: [], repliedUser: false } });
return;
}
if (mode === MODES.LOCKDOWN && moderationActions.has(action) && !isLockdownAdmin) {
await request.reply({ content: 'Lockdown mode: only lockdown admins can run that command.', allowedMentions: { parse: [], repliedUser: false } });
return;
}
switch (action) {
case '':
case 'status':
return handleStatusCommand?.(request, rest);
case 'help':
return request.reply(formatHelp({ commandPrefix, timeStatusCommand, topic: rest, includeDiscord: request.transport === 'discord', isFeatureEnabled: deps.isFeatureEnabled }));
case 'replay':
return handleReplayCommand?.(request, tokens.join(' '));
case 'bridge':
if (!handleBridgeCommand) return request.reply(formatHelp({ commandPrefix, timeStatusCommand, includeDiscord: false, isFeatureEnabled: deps.isFeatureEnabled }));
return handleBridgeCommand(request, tokens);
case 'lights':
return handleLightsCommand(request, tokens);
case 'kick':
return handleKickCommand(request, rest);
case 'lift':
return handleLiftCommand(request, tokens);
case 'neato':
return handleNeatoCommand(request, tokens);
case 'lock':
return handleLockCommand(request, rest, true);
case 'unlock':
return handleLockCommand(request, rest, false);
case 'mode':
return handleModeCommand(request, tokens);
case 'goal':
return handleGoalCommand(request, tokens);
case 'reason':
return handleReasonCommand(request, tokens);
case 'verify':
return handleVerifyCommand(request, tokens);
case 'deter':
return handleDeterCommand(request, tokens);
default:
return request.reply(formatHelp({ commandPrefix, timeStatusCommand, includeDiscord: request.transport === 'discord', isFeatureEnabled: deps.isFeatureEnabled }));
}
}
return { handleCommand };
}
module.exports = { createCommandHandlers };
@@ -0,0 +1,32 @@
// Operator Command Registry
// Purpose: Describes command categories, discovery text, permissions, and feature requirements in one place.
// Scope: Supplies transport-neutral metadata; execution handlers remain focused on server operations.
const CATEGORIES = {
system: { title: 'System', names: ['help', 'status', 'replay', 'time-status'] },
admin: { title: 'Admin', names: ['lock', 'unlock', 'mode', 'reason', 'goal', 'lights', 'kick', 'verify', 'deter'] },
features: { title: 'Features', names: ['lift', 'neato'] },
discord: { title: 'Discord', names: ['bridge'] },
};
function buildCommandRegistry(prefix, timeCommand) {
return {
help: { category: 'system', summary: 'Show command help.', usage: [`${prefix} help [command|category]`] },
status: { category: 'system', summary: 'Show rover status; rover names can be fuzzy.', usage: [`${prefix} status [rover]`] },
replay: { category: 'system', summary: 'Create an instant replay from selected sources.', usage: [`${prefix} replay [sources]`] },
'time-status': { category: 'system', summary: 'Show the current time status.', usage: timeCommand ? [timeCommand] : [] },
lock: { category: 'admin', summary: 'Lock a rover.', usage: [`${prefix} lock <rover>`], access: 'Admin', permission: 'admin' },
unlock: { category: 'admin', summary: 'Unlock a rover.', usage: [`${prefix} unlock <rover>`], access: 'Admin', permission: 'admin' },
mode: { category: 'admin', summary: 'Change the server mode.', usage: [`${prefix} mode <open|turns|admin|lockdown>`], access: 'Admin', permission: 'admin' },
reason: { category: 'admin', summary: 'Show, set, or clear the admin-mode reason.', usage: [`${prefix} reason [text|clear]`], access: 'Admin to change' },
goal: { category: 'admin', summary: 'Show, set, or clear the global objective.', usage: [`${prefix} goal [text|clear]`], access: 'Admin to change' },
lights: { category: 'admin', summary: 'Show or change the room-light lock.', usage: [`${prefix} lights <status|lock|unlock>`], access: 'Admin', permission: 'admin' },
kick: { category: 'admin', summary: 'Remove a user from their current rover.', usage: [`${prefix} kick <user> [reason]`], access: 'Admin', permission: 'admin' },
verify: { category: 'admin', summary: 'List or remove verified identities.', usage: [`${prefix} verify list`, `${prefix} verify remove <identity>`], access: 'Lockdown admin', permission: 'lockdown-admin' },
deter: { category: 'admin', summary: 'List, add, or remove identity deterrence.', usage: [`${prefix} deter list`, `${prefix} deter ban <identity>`, `${prefix} deter unban <identity>`], access: 'Lockdown admin', permission: 'lockdown-admin' },
lift: { category: 'features', summary: 'Show or move the lift.', usage: [`${prefix} lift <status|up|down>`], access: 'Public unless server access is restricted', permission: 'access-mode', requiredFeature: 'lift', unavailableLabel: 'Lift' },
neato: { category: 'features', summary: 'Show or control Neato.', usage: [`${prefix} neato <status|start|home|locate|clear-errors>`], access: 'Public unless server access is restricted', permission: 'access-mode', requiredFeature: 'neato', unavailableLabel: 'Neato' },
bridge: { category: 'discord', summary: 'Configure this Discord server chat bridge.', usage: [`${prefix} bridge`, `${prefix} bridge here <global|private>`, `${prefix} bridge mode <global|private>`, `${prefix} bridge off`], access: 'Discord server manager' },
};
}
module.exports = { CATEGORIES, buildCommandRegistry };
@@ -0,0 +1,68 @@
// Web Chat Command Transport
// Purpose: Renders status-oriented operator commands as the same plain text web chat expects.
// Scope: Avoids importing Discord.js merely to flatten an embed back into text.
const { resolveRoverSelector } = require('./commands/resolvers');
function formatTimeInZone(date, timeZone) {
try {
return new Intl.DateTimeFormat('en-US', { timeZone, hour: '2-digit', minute: '2-digit', hour12: false }).format(date);
} catch (_err) {
return 'n/a';
}
}
function createWebTransportHandlers({ rovers, roverManager, config, siteUrl = '' }) {
return {
async status(message, roverId) {
const resolved = roverId ? resolveRoverSelector(roverId, rovers) : null;
if (roverId && resolved?.error) return message.reply(`Rover Status\n\n${resolved.error}`);
const records = roverId
? [resolved.record]
: Array.from(rovers.values()).filter((entry) => roverManager.canReplayRoverId(entry?.id));
if (!records.length) return message.reply('Rover Battery Status\n\nNo rovers online.');
// This mirrors the human-readable content of the established Discord
// battery embed while remaining a plain transport-neutral chat result.
const fields = records.map((record) => {
const sensors = record.lastSensor?.decoded || record.lastSensor?.sensors || {};
const battery = record.batteryState || {};
const name = record.meta?.name || record.id;
const docked = Boolean(sensors?.chargingSources?.homeBase);
const chargingLabel = String(sensors?.chargingState?.label || 'unknown');
const charging = ['waiting', 'full charging', 'trickle charging'].includes(chargingLabel.toLowerCase()) || [2, 3, 4].includes(sensors?.chargingState?.code);
const lockLabel = record.locked ? `locked${record.lockReason ? ` (${record.lockReason})` : ''}` : 'unlocked';
const charge = battery.charge != null && battery.capacity != null ? `${battery.charge}/${battery.capacity}mAh` : 'n/a';
const percent = battery.percentDisplay != null ? `${battery.percentDisplay}%` : 'n/a';
return [
name,
`Dock: ${docked ? 'docked' : 'undocked'}`,
`Charging: ${charging ? `charging (${chargingLabel})` : 'not charging'}`,
`Battery: ${charge} (${percent})`,
`Voltage: ${sensors?.voltageMv == null ? 'n/a' : `${(sensors.voltageMv / 1000).toFixed(2)}V`}`,
`Current: ${sensors?.currentMa == null ? 'n/a' : `${sensors.currentMa}mA`}`,
`OI: ${String(sensors?.oiMode?.label || 'unknown').toLowerCase()}`,
`Lock: ${lockLabel}`,
].join('\n');
});
return message.reply(['Rover Battery Status', ...fields].join('\n\n'));
},
async timeStatus(message) {
const serverTimezone = config.timezone || config.server?.timezone || process.env.TZ || 'America/New_York';
const zones = [
['UTC', 'UTC'], ['US Pacific', 'America/Los_Angeles'], ['US Mountain', 'America/Denver'],
['US Central', 'America/Chicago'], ['US Eastern', 'America/New_York'], ['Europe London', 'Europe/London'],
['Europe Berlin', 'Europe/Berlin'], ['Asia Kolkata', 'Asia/Kolkata'], ['Asia Shanghai', 'Asia/Shanghai'],
['Asia Tokyo', 'Asia/Tokyo'], ['Australia Sydney', 'Australia/Sydney'], ['New Zealand Auckland', 'Pacific/Auckland'],
];
const now = new Date();
const lines = zones.map(([label, zone]) => `${label}${formatTimeInZone(now, zone)}${zone.toLowerCase() === String(serverTimezone).toLowerCase() ? ' **(server local timezone)**' : ''}`);
if (!zones.some(([, zone]) => zone.toLowerCase() === String(serverTimezone).toLowerCase())) {
lines.push(`Server Local — ${formatTimeInZone(now, serverTimezone)} **(server local timezone)**`);
}
const siteLink = siteUrl ? `\n\n${siteUrl}` : '';
return message.reply(`Time Status\n${lines.join('\n')}${siteLink}\n\nServer local timezone: ${serverTimezone}`);
},
};
}
module.exports = { createWebTransportHandlers };
+29 -5
View File
@@ -11,6 +11,10 @@ const io = require('../../globals/io');
const logger = require('../../globals/logger').child('ptzCamera');
const { loadConfig } = require('../../helpers/configLoader');
const { isFeatureEnabled } = require('../../helpers/features');
const {
shouldUseSnapshotsForNonTurnVideo,
shouldUseSnapshotsForExternalSpectatorVideo,
} = require('../../helpers/bandwidthSavings');
const { getMode, MODES, modeEvents } = require('../modeManager');
const { isAdmin, isLockdownAdmin, getRole } = require('../roleService');
const { isVerified } = require('../verificationService');
@@ -1013,9 +1017,10 @@ function requirePtzUser(socket) {
function requirePresetAdmin(socket) {
/*
Preset creation and deletion changes shared camera state for everyone. Keep
that narrower than normal PTZ operation so regular camera users can only
choose from positions an admin has intentionally published.
Preset removal is intentionally narrower than normal PTZ operation because
deleting a shared camera position is destructive for every future operator.
Creation now uses requirePtzUser instead so any authorized PTZ user can save
a useful current position without also being allowed to remove presets.
*/
if (!enabled) throw new Error('PTZ camera disabled');
if (!passesMode(socket)) throw new Error('Not authorized for PTZ camera');
@@ -1117,7 +1122,7 @@ async function gotoPreset(socket, payload = {}) {
}
async function createPreset(socket, payload = {}) {
requirePresetAdmin(socket);
requirePtzUser(socket);
await initialize();
const presetName = normalizePresetCreateName(payload.name || payload.presetName);
const options = {
@@ -1290,7 +1295,26 @@ function canRequestLiveVideo(socket) {
if (!enabled || !passesMode(socket)) return false;
if (state.operatorSocketId === socket?.id) return true;
if (isAdmin(socket) || isLockdownAdmin(socket)) return true;
return isLocalNetwork(getSocketIp(socket));
const role = getRole(socket);
const local = isLocalNetwork(getSocketIp(socket));
if (role === 'spectator') {
/*
Spectator PTZ viewing follows the spectator bandwidth switch. LAN viewers
stay live because they do not consume server upload; non-local spectators
only get live PTZ when the external spectator video policy allows it.
*/
return local || !shouldUseSnapshotsForExternalSpectatorVideo();
}
if (canUsePtzFeature(socket) && !shouldUseSnapshotsForNonTurnVideo()) {
/*
Verified/VIP users who can queue or claim the camera are PTZ "turn"
participants even before they become operator. When non-turn video is set
to live, they may watch the live feed while waiting; camera movement still
remains limited to the active operator by the command handlers.
*/
return true;
}
return false;
}
function getSnapshotPath() {
@@ -0,0 +1,109 @@
// Replay Delivery Service
// Purpose: Builds each web-requested replay once and chooses Discord or automatic local hosting.
// Scope: Keeps replay generation functional even when the optional Discord feature is disabled or unhealthy.
const io = require('../../globals/io');
const logger = require('../../globals/logger').child('replayDelivery');
const { subscribe } = require('../eventBus');
const { buildReplayVideo } = require('../replayEngineV2');
const { hostReplay } = require('../replayMediaService');
const {
createReplayJob,
createJobStatusEmitter,
buildAcceptedMessage,
buildStatusMessage,
normalizeUserError,
} = require('./workflow');
const jobStatus = createJobStatusEmitter({ io, logger, sanitizeMentions: (value) => String(value || '') });
let preferredDeliveryProvider = null;
function registerPreferredDeliveryProvider(provider) {
preferredDeliveryProvider = provider && typeof provider.deliver === 'function' ? provider : null;
return () => {
if (preferredDeliveryProvider === provider) preferredDeliveryProvider = null;
};
}
async function deliverReplay(payload = {}) {
const job = createReplayJob({
id: payload.jobId,
requester: payload.requester,
source: 'web',
title: payload.title,
sources: payload.sources,
includeSidebar: payload.includeSidebar,
requestedBy: payload.requestedBy,
});
jobStatus.emit(job, 'accepted', { message: buildAcceptedMessage(job) });
let providerContext = null;
try {
let providerError = null;
if (preferredDeliveryProvider?.begin) {
try {
providerContext = await preferredDeliveryProvider.begin(job);
} catch (err) {
providerError = err;
logger.warn('Preferred replay delivery could not start; using hosted media', { jobId: job.id, error: err.message });
}
}
jobStatus.emit(job, 'building', { message: buildStatusMessage(job, 'building') });
if (providerContext?.progressMessage?.edit) {
await providerContext.progressMessage.edit({ content: buildStatusMessage(job, 'building'), allowedMentions: { parse: [], repliedUser: false } }).catch(() => {});
}
const built = await buildReplayVideo({
sources: job.sources,
title: job.title,
requester: job.requester,
includeSidebar: job.includeSidebar,
});
let media = null;
if (preferredDeliveryProvider && !providerError) {
try {
jobStatus.emit(job, 'uploading', { message: buildStatusMessage(job, 'uploading') });
media = await preferredDeliveryProvider.deliver({ job, context: providerContext, ...built });
} catch (err) {
providerError = err;
if (!providerError.progressMessage && providerContext?.progressMessage) providerError.progressMessage = providerContext.progressMessage;
logger.warn('Preferred replay delivery failed; using hosted media', { jobId: job.id, error: err.message });
}
}
if (!media) media = await hostReplay({ buffer: built.buffer, job });
jobStatus.emit(job, 'ready', { message: buildStatusMessage(job, 'ready'), media });
if (providerError && preferredDeliveryProvider?.completeFallback) {
await preferredDeliveryProvider.completeFallback({ job, context: providerContext, media }).catch((err) => {
logger.warn('Unable to announce hosted replay fallback', { jobId: job.id, error: err.message });
});
}
if (providerContext?.stopTyping) providerContext.stopTyping();
// A Discord progress message may already exist when upload fails. Let the
// provider attach it to the error so fallback can finish that outward UI
// instead of leaving a permanent "uploading" message in the channel.
if (providerError?.progressMessage?.edit) {
await providerError.progressMessage.edit({ content: buildStatusMessage(job, 'ready'), allowedMentions: { parse: [], repliedUser: false } }).catch(() => {});
}
return media;
} catch (err) {
if (providerContext?.stopTyping) providerContext.stopTyping();
const message = normalizeUserError(err);
jobStatus.emit(job, 'failed', { message });
if (providerContext?.progressMessage?.edit) {
await providerContext.progressMessage.edit({ content: message, allowedMentions: { parse: [], repliedUser: false } }).catch(() => {});
}
throw err;
}
}
subscribe('replay.requested', (event) => {
deliverReplay(event?.payload || {}).catch((err) => {
logger.warn('Replay delivery failed', { error: err.message });
});
});
module.exports = {
deliverReplay,
registerPreferredDeliveryProvider,
};
@@ -1,6 +1,6 @@
// Discord Replay Workflow
// Purpose: Provides the shared replay job, Discord upload, fuzzy source lookup, and user-facing status helpers.
// Scope: Keeps Discord-command and web-triggered replay delivery on the same status pipeline.
// Replay Delivery Workflow
// 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 DEFAULT_ALLOWED_MENTIONS = { parse: [], repliedUser: false };
@@ -7,11 +7,7 @@ const { getMode, MODES } = require('../modeManager');
const { publishEvent } = require('../eventBus');
const assignmentService = require('../assignmentService');
const { getNickname } = require('../nicknameService');
const { loadConfig } = require('../../helpers/configLoader');
const { buildReplayJobId, buildReplayTitle } = require('../discordBotService/replayWorkflow');
const config = loadConfig();
const discordConfig = config.discord || {};
const { buildReplayJobId, buildReplayTitle } = require('../replayDeliveryService/workflow');
function buildRequesterLabel(socket) {
return getNickname(socket) || socket?.data?.user?.username || socket?.id || 'unknown';
@@ -34,11 +30,6 @@ function registerReplaySocketHooks({ tryTriggerReplay, validateSources, getDefau
cb({ error: 'Replay disabled in lockdown', state: null });
return;
}
const channelId = discordConfig?.channels?.replay || null;
if (!channelId) {
cb({ error: 'Replay channel not configured', state: null });
return;
}
const requestedSources = Array.isArray(payload?.sources) ? payload.sources : null;
let sources = requestedSources ? validateSources(requestedSources, socket) : [];
if (!sources.length) {
@@ -65,7 +56,6 @@ function registerReplaySocketHooks({ tryTriggerReplay, validateSources, getDefau
type: 'replay.requested',
payload: {
jobId,
channelId,
requester,
title,
includeSidebar,
@@ -0,0 +1,123 @@
// Replay Media Service
// Purpose: Stores and serves completed replay videos when Discord delivery is unavailable.
// Scope: Owns only final hosted MP4 files; replay frame caches and active video builds remain outside this service.
const crypto = require('crypto');
const fsp = require('fs/promises');
const path = require('path');
const logger = require('../../globals/logger').child('replayMedia');
const { app } = require('../../globals/http');
const { resolveDataDir } = require('../../helpers/dataPaths');
const REPLAY_DIR = path.join(resolveDataDir(), 'replays');
const MAX_AGE_MS = 6 * 60 * 60 * 1000;
const CLEANUP_INTERVAL_MS = 30 * 60 * 1000;
const MAX_TOTAL_BYTES = 1024 * 1024 * 1024;
const PUBLIC_FILE_PATTERN = /^[a-f0-9]{32}\.mp4$/;
async function listCompletedFiles() {
await fsp.mkdir(REPLAY_DIR, { recursive: true });
const entries = await fsp.readdir(REPLAY_DIR, { withFileTypes: true });
const files = [];
for (const entry of entries) {
if (!entry.isFile()) continue;
const filePath = path.join(REPLAY_DIR, entry.name);
try {
const stat = await fsp.stat(filePath);
files.push({ name: entry.name, path: filePath, size: stat.size, mtimeMs: stat.mtimeMs });
} catch (err) {
if (err.code !== 'ENOENT') logger.warn('Unable to inspect hosted replay', { file: entry.name, error: err.message });
}
}
return files;
}
async function cleanup() {
const now = Date.now();
const files = await listCompletedFiles();
const completed = files.filter((file) => PUBLIC_FILE_PATTERN.test(file.name)).sort((a, b) => a.mtimeMs - b.mtimeMs);
const temporary = files.filter((file) => file.name.endsWith('.tmp'));
// Temporary files are never served. An old one means a write was interrupted,
// so it is safe to remove after the same conservative expiry used for media.
const expiredTemporary = temporary.filter((file) => now - file.mtimeMs > MAX_AGE_MS);
const expiredCompleted = completed.filter((file) => now - file.mtimeMs > MAX_AGE_MS);
const toDelete = new Set([...expiredTemporary, ...expiredCompleted].map((file) => file.path));
let retainedBytes = completed.reduce((total, file) => total + file.size, 0)
- expiredCompleted.reduce((total, file) => total + file.size, 0);
for (const file of completed) {
if (retainedBytes <= MAX_TOTAL_BYTES) break;
if (toDelete.has(file.path)) continue;
toDelete.add(file.path);
retainedBytes -= file.size;
}
await Promise.all(Array.from(toDelete).map(async (filePath) => {
try {
await fsp.unlink(filePath);
} catch (err) {
if (err.code !== 'ENOENT') logger.warn('Unable to remove hosted replay', { file: path.basename(filePath), error: err.message });
}
}));
}
async function hostReplay({ buffer, job }) {
if (!Buffer.isBuffer(buffer) || !buffer.length) throw new Error('Replay output was empty');
await fsp.mkdir(REPLAY_DIR, { recursive: true });
const filename = `${crypto.randomBytes(16).toString('hex')}.mp4`;
const finalPath = path.join(REPLAY_DIR, filename);
const temporaryPath = `${finalPath}.${process.pid}.tmp`;
// Atomic rename ensures cleanup and HTTP requests can only observe a fully
// written MP4, never a partially flushed replay.
try {
await fsp.writeFile(temporaryPath, buffer, { flag: 'wx' });
await fsp.rename(temporaryPath, finalPath);
} catch (err) {
await fsp.unlink(temporaryPath).catch(() => {});
throw err;
}
return {
jobId: job.id,
status: 'ready',
title: job.title,
requester: job.requester,
requestedBy: job.requestedBy || null,
url: `/media/replays/${filename}`,
proxyUrl: null,
messageUrl: null,
filename,
size: buffer.length,
contentType: 'video/mp4',
sources: Array.isArray(job.sources) ? job.sources : [],
ts: Date.now(),
};
}
app.get('/media/replays/:filename', (req, res, next) => {
const filename = String(req.params.filename || '');
if (!PUBLIC_FILE_PATTERN.test(filename)) return res.status(404).end();
const filePath = path.join(REPLAY_DIR, filename);
// Express sendFile supports byte-range requests, which preserves seeking in
// the existing browser video players without implementing a second streamer.
res.setHeader('Cache-Control', 'private, max-age=3600');
return res.sendFile(filePath, { headers: { 'Content-Type': 'video/mp4' } }, (err) => {
if (!err || res.headersSent) return;
if (err.code === 'ENOENT') return res.status(404).end();
return next(err);
});
});
cleanup().catch((err) => logger.warn('Initial hosted replay cleanup failed', err.message));
const cleanupTimer = setInterval(() => {
cleanup().catch((err) => logger.warn('Hosted replay cleanup failed', err.message));
}, CLEANUP_INTERVAL_MS);
// Maintenance must never keep a process alive during normal shutdown.
if (typeof cleanupTimer.unref === 'function') cleanupTimer.unref();
module.exports = {
hostReplay,
cleanup,
replayDirectory: REPLAY_DIR,
};
+40 -1
View File
@@ -3,7 +3,7 @@
// Scope: Keeps runtime behavior unchanged while isolating responsibilities into a clear module boundary.
const io = require('../../globals/io');
const logger = require('../../globals/logger').child('sessionService');
const { getRole, roleEvents } = require('../roleService');
const { getRole, isAdmin, roleEvents } = require('../roleService');
const { getMode, modeEvents } = require('../modeManager');
const roverManager = require('../roverManager');
const { managerEvents } = roverManager;
@@ -39,6 +39,14 @@ const { getAdminReason } = require('../adminReasonService');
const { subscribe } = require('../eventBus');
const { getSocketIp, isLocalNetwork } = require('../../helpers/ipResolver');
const { getFeatureFlags } = require('../../helpers/features');
const {
canUseExternalSpectatorAccess,
getBandwidthSavingsPolicy,
} = require('../../helpers/bandwidthSavings');
const {
getFeatureState,
getUserIdForSocket,
} = require('../identityService');
const { getAudioForwardState, audioForwardEvents } = require('../audioForwardService');
const { getAudioLevels, audioLevelsEvents } = require('../audioLevelsService');
const { getButtonBoxState } = require('../buttonBoxService');
@@ -62,6 +70,36 @@ logger.info('Discord invite loaded:', discordInvite ? 'present' : 'not configure
logger.info('Ko-fi link loaded:', kofiLink ? 'present' : 'not configured');
logger.info('Socials config loaded:', configuredSocials?.length ? `${configuredSocials.length} entries` : 'not configured');
const SPECTATOR_ACCESS_NAMESPACE = 'spectatorAccess';
function hasExternalSpectatorGrant(socket) {
const userId = getUserIdForSocket(socket);
if (!userId) return false;
const state = getFeatureState(userId, SPECTATOR_ACCESS_NAMESPACE, {});
return Boolean(state?.external);
}
function buildBandwidthSavingsSessionState(socket) {
const policy = getBandwidthSavingsPolicy();
const local = isLocalNetwork(getSocketIp(socket));
const granted = hasExternalSpectatorGrant(socket);
return {
...policy,
/*
These derived fields let browser routes make clear UI choices without
re-implementing IP/admin/grant logic. The server still enforces the same
decisions in auth and video services, so the UI remains advisory only.
*/
externalSpectatorGranted: granted,
canUseExternalSpectatorAccess: canUseExternalSpectatorAccess({
isLocal: local,
isAdmin: isAdmin(socket),
isVerified: Boolean(socket?.data?.isVerified),
hasGrant: granted,
}),
};
}
function buildUserEntry(socket) {
if (!socket) return null;
const role = getRole(socket);
@@ -110,6 +148,7 @@ function buildSession(socket) {
role: getRole(socket),
mode: getMode(),
isLocalNetwork: isLocalNetwork(getSocketIp(socket)),
bandwidthSavings: buildBandwidthSavingsSessionState(socket),
/*
Features is the single UI contract for optional server capabilities. A
disabled feature should be absent from navigation/layout decisions even
@@ -31,6 +31,7 @@ const {
resolveUserBySelector,
userToLegacyIdentityEntry,
} = require('../identityService');
const { shouldEnforceSingleDriverTab } = require('../../helpers/bandwidthSavings');
const verificationEvents = new EventEmitter();
const IDENTITY_TIMEOUT_MS = 2 * 60 * 1000;
@@ -103,7 +104,7 @@ function identifySocket(socket, payload = {}) {
nickname: incomingNickname || getNickname(socket) || '',
});
refreshSocketIdentityFlags(socket);
enforceSingleUnverifiedSocketPerIdentity(socket);
enforceSingleDriverSocketPerIdentity(socket);
emitChange('identify', { socketId: socket.id, userId: result.userId });
return {
@@ -132,13 +133,18 @@ function emitDuplicateIdentityAndDisconnect(socket, payload = {}) {
}, DUPLICATE_IDENTITY_DISCONNECT_DELAY_MS);
}
function enforceSingleUnverifiedSocketPerIdentity(currentSocket) {
function enforceSingleDriverSocketPerIdentity(currentSocket) {
const currentUserId = getUserIdForSocket(currentSocket);
const currentRole = getRole(currentSocket);
const enforceForCurrentSocket = shouldEnforceSingleDriverTab({
isVerified: Boolean(currentSocket?.data?.isVerified),
isAdmin: isAdminRole(currentRole),
});
if (
!currentSocket?.id ||
!currentUserId ||
currentSocket.data?.isVerified ||
currentSocket.data?.identitySurface !== 'driver'
currentSocket.data?.identitySurface !== 'driver' ||
!enforceForCurrentSocket
) {
return;
}
@@ -150,9 +156,21 @@ function enforceSingleUnverifiedSocketPerIdentity(currentSocket) {
});
if (!duplicates.length) return;
const verifiedDuplicate = duplicates.find((candidate) => candidate?.data?.isVerified);
const verifiedDuplicate = duplicates.find((candidate) => {
/*
verifiedOnly keeps the previous "verified tab wins" rule. In notAllowed
mode, verified users are subject to the same single-driver-tab rule, so a
verified duplicate should not protect the newer socket from enforcement.
*/
const candidateRole = getRole(candidate);
const enforceForCandidate = shouldEnforceSingleDriverTab({
isVerified: Boolean(candidate?.data?.isVerified),
isAdmin: isAdminRole(candidateRole),
});
return candidate?.data?.isVerified && !enforceForCandidate;
});
if (verifiedDuplicate) {
logger.info('Disconnecting non-verified socket because its user is already active on a verified socket', {
logger.info('Disconnecting driver socket because its user is already active on an exempt verified socket', {
socketId: currentSocket.id,
retainedSocketId: verifiedDuplicate.id,
userId: currentUserId,
@@ -162,7 +180,7 @@ function enforceSingleUnverifiedSocketPerIdentity(currentSocket) {
}
duplicates.forEach((duplicate) => {
logger.info('Disconnecting older non-verified duplicate user socket', {
logger.info('Disconnecting older duplicate driver socket', {
socketId: duplicate.id,
retainedSocketId: currentSocket.id,
userId: currentUserId,
+14 -1
View File
@@ -1,6 +1,11 @@
// Video Auth Policy
// Purpose: Encapsulates mode, role, and stream-specific authorization decisions for MediaMTX auth checks.
// Scope: Evaluates viewer/publisher eligibility from normalized request context and socket/session state.
const {
shouldUseSnapshotsForNonTurnVideo,
shouldUseSnapshotsForExternalSpectatorVideo,
} = require('../../helpers/bandwidthSavings');
function createVideoAuthPolicy(deps) {
const {
getMode,
@@ -63,7 +68,7 @@ function createVideoAuthPolicy(deps) {
const isAudio = streamInfo.id?.endsWith('-audio');
if (role === 'spectator' && !isAdmin(socket) && !isAudio) {
const socketIp = getSocketIp(socket);
if (!isLocalNetwork(socketIp)) {
if (!isLocalNetwork(socketIp) && shouldUseSnapshotsForExternalSpectatorVideo()) {
return false;
}
}
@@ -73,6 +78,14 @@ function createVideoAuthPolicy(deps) {
if (!roverManager.isDriver(roverId, socket)) {
return false;
}
if (!isAudio && shouldUseSnapshotsForNonTurnVideo() && !turnService.canDrive(roverId, socket)) {
/*
This mirrors videoSocketService's token gate. MediaMTX can ask auth
after a token has been issued, so the active-turn bandwidth rule must
be evaluated here too instead of trusting an older browser decision.
*/
return false;
}
}
return true;
@@ -8,8 +8,13 @@ const { isAdmin, isLockdownAdmin, getRole } = require('../roleService');
const videoSessions = require('../videoSessions');
const roverManager = require('../roverManager');
const ptzCameraService = require('../ptzCameraService');
const turnService = require('../turnService');
const { loadConfig } = require('../../helpers/configLoader');
const { getSocketIp, isLocalNetwork } = require('../../helpers/ipResolver');
const {
shouldUseSnapshotsForNonTurnVideo,
shouldUseSnapshotsForExternalSpectatorVideo,
} = require('../../helpers/bandwidthSavings');
const config = loadConfig();
const mediaConfig = config.media || {};
@@ -116,10 +121,25 @@ io.on('connection', (socket) => {
const role = getRole(socket);
if (role === 'spectator' && !isAdmin(socket) && !isAudio) {
const ip = getSocketIp(socket);
if (!isLocalNetwork(ip)) {
if (!isLocalNetwork(ip) && shouldUseSnapshotsForExternalSpectatorVideo()) {
throw new Error('Not authorized for video');
}
}
if (
!isAudio &&
role !== 'spectator' &&
!isAdmin(socket) &&
shouldUseSnapshotsForNonTurnVideo() &&
!turnService.canDrive(baseId, socket)
) {
/*
The browser also forces snapshots for non-active turn holders, but
the socket token path must enforce the same rule. Otherwise a stale
component or direct socket caller could still mint a MediaMTX token
while the UI is showing snapshots.
*/
throw new Error('Live video is limited to the active turn');
}
} else if (target.type === 'room') {
throw new Error('Room cameras now use the snapshot feed');
} else if (target.type === 'ptz') {
+5 -9
View File
@@ -1,12 +1,8 @@
1. improve spectator page, options on what to see and what not to see
2. assign rovers based on battery percentage, give people highest one
3. add config to disable client snapshot forcing, disable bandwidth saving
4. add admin ui for VIP and private requests instead of only through discord
5. pull page / tab title from session, use the name from profile of interinstance if enabled, if not just default to old one
6. make overcurrent limiter speed sensitive, slower fill at lower speeds
7. add feature chat commands, like /neato start, /lift up, etc
8. add more background gap themes
9. fix this:
1. assign rovers based on battery percentage, give people highest one
2. add admin ui for VIP and private requests instead of only through discord
3. make overcurrent limiter speed sensitive, slower fill at lower speeds
4. add more background gap themes
5. fix this:
`Jun 18 15:14:18 roombaserver.local node[216731]: /home/daniel/MultiRoombaRover/server/src/services/roverManager/socketHandlers.js:92
Jun 18 15:14:18 roombaserver.local node[216731]: cb({ error: err.message });
Jun 18 15:14:18 roombaserver.local node[216731]: ^
@@ -69,6 +69,7 @@ export default function AdminPanelContent() {
setAdminReason,
rebootRover,
updateRover,
updateAllRovers,
rebootServer,
setAudioLevels,
setPrivateSafety,
@@ -181,6 +182,35 @@ export default function AdminPanelContent() {
}
};
const handleUpdateAll = async () => {
const roverCount = roster.filter((rover) => rover?.id).length;
if (roverCount === 0) return;
const ok = window.confirm(
`Update all ${roverCount} rover${roverCount === 1 ? '' : 's'} now? Each rover will run its self-update and reboot if the update starts successfully.`,
);
if (!ok) return;
trackAnalyticsEvent('rover_update_all_click', { roverCount });
try {
// The server owns the fan-out because it has the authoritative online
// rover map and can enforce admin privileges once before issuing the
// existing per-rover update command to every connected rover.
const result = await updateAllRovers();
trackAnalyticsEvent('rover_update_all_result', {
status: 'accepted',
updated: result?.updated?.length || 0,
failed: result?.failed?.length || 0,
});
if (result?.failed?.length) {
alert(`Update requested for ${result.updated?.length || 0} rover(s). ${result.failed.length} rover(s) failed to queue.`);
}
} catch (err) {
trackAnalyticsEvent('rover_update_all_result', { status: 'failed', reason: err?.message || 'unknown' });
alert(err.message);
}
};
const handleServerReboot = async () => {
const ok = window.confirm('Reboot the server host now? This will disconnect all users.');
if (!ok) return;
@@ -487,6 +517,17 @@ export default function AdminPanelContent() {
</div>
</div>
<div className="flex items-center justify-between gap-0.5 text-xs">
<span className="text-slate-400">Rovers</span>
<button
type="button"
onClick={handleUpdateAll}
disabled={roster.length === 0}
className="button-danger disabled:cursor-not-allowed disabled:opacity-60"
>
Update All
</button>
</div>
<RoverRoster
roster={roster}
renderActions={(rover) => (
@@ -187,9 +187,13 @@ function HomeAssistantControlsContent() {
const ha = useSessionSelector((state) => state.session?.homeAssistant || null);
const { homeAssistantToggle, homeAssistantSetLightColor, homeAssistantSetLightWhite } =
useSessionActions();
const role = useSessionSelector((state) => state.session?.role || null);
const mode = useSessionSelector((state) => state.session?.mode || null);
const entities = useMemo(() => ha?.entities || [], [ha?.entities]);
const lightPolicy = ha?.lightPolicy || null;
const controlsLocked = Boolean(lightPolicy?.locked || lightPolicy?.lockedOn);
const adminCanControlLockedLights = role === 'lockdown' || (role === 'admin' && mode !== 'lockdown');
const lightPolicyLocked = Boolean(lightPolicy?.locked || lightPolicy?.lockedOn);
const controlsLocked = lightPolicyLocked && !adminCanControlLockedLights;
const lockState = lightPolicy?.lockState || (lightPolicy?.lockedOn ? 'on' : null);
const onKeyLabel = formatKeyLabel(keymap?.homeAssistantOn?.[0]);
const offKeyLabel = formatKeyLabel(keymap?.homeAssistantOff?.[0]);
@@ -224,16 +228,20 @@ function HomeAssistantControlsContent() {
{offKeyLabel ? <KeyPill label={offKeyLabel} /> : null}
</span>
</div>
{controlsLocked ? <StatusBadge label={lockState === 'off' ? 'Locked Off' : 'Locked On'} tone="warn" /> : null}
{lightPolicyLocked ? <StatusBadge label={lockState === 'off' ? 'Locked Off' : 'Locked On'} tone="warn" /> : null}
<StatusBadge label={connected ? 'Connected' : 'Offline'} tone={connected ? 'success' : 'warn'} />
</>
);
return (
<CardFrame title="Room Controls" actions={actions} bodyClassName="space-y-0.5 text-base">
{controlsLocked ? (
{lightPolicyLocked ? (
<p className="rounded border border-amber-600/60 bg-amber-900/40 px-1 py-0.5 text-xs text-amber-100">
{lockState === 'off'
{adminCanControlLockedLights
? lockState === 'off'
? 'Lights are locked off. Admin room controls remain available.'
: 'Lights are locked on. Admin room controls remain available.'
: lockState === 'off'
? 'Lights are locked off. Room controls are disabled.'
: 'Lights are locked on. Room controls are disabled.'}
</p>
+27 -10
View File
@@ -372,6 +372,7 @@ function PtzPresetPanel({ ptz }) {
const [busy, setBusy] = useState('');
const presets = Array.isArray(ptz?.presets) ? ptz.presets : [];
const isPresetAdmin = role === 'admin' || role === 'lockdown';
const canCreatePreset = Boolean(ptz?.canUse);
const canMoveToPreset = Boolean(ptz?.isOperator);
const refreshPresets = async () => {
@@ -410,13 +411,14 @@ function PtzPresetPanel({ ptz }) {
const createPreset = async (event) => {
event.preventDefault();
const trimmed = name.trim();
if (!isPresetAdmin || busy || !trimmed) return;
if (!canCreatePreset || busy || !trimmed) return;
setBusy('create');
try {
/*
ONVIF setPreset stores the camera's current physical position. The UI
only sends the admin's label; the server supplies the active profile
token so browser code does not need to know camera profile internals.
only sends the user's label; the server supplies the active profile
token so browser code does not need camera profile internals, and the
server still enforces the PTZ feature gate for raw socket callers.
*/
await ptzCreatePreset({ name: trimmed });
setName('');
@@ -461,15 +463,20 @@ function PtzPresetPanel({ ptz }) {
{ptz.presetsError}
</div>
) : null}
<div className="min-h-0 flex-1 space-y-0.5 overflow-y-auto">
<div className="flex min-h-0 flex-1 flex-wrap content-start items-start gap-0.5 overflow-y-auto">
{/*
Presets should behave like a compact pile of actions, not a table.
flex-wrap lets each preset keep its natural button width and only
starts a new visual line when the current line runs out of room.
*/}
{presets.length ? presets.map((preset) => {
const gotoBusy = busy === `goto:${preset.token}`;
const removeBusy = busy === `remove:${preset.token}`;
return (
<div key={preset.token} className="surface grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1">
<div key={preset.token} className="surface inline-flex max-w-full items-center gap-1">
<button
type="button"
className="button-dark min-w-0 truncate text-left text-xs disabled:opacity-50"
className="button-dark min-w-0 max-w-40 truncate text-left text-xs disabled:opacity-50"
disabled={!canMoveToPreset || Boolean(busy)}
onClick={() => goToPreset(preset)}
title={canMoveToPreset ? `Move to ${preset.name}` : 'Your PTZ turn must be active'}
@@ -494,10 +501,10 @@ function PtzPresetPanel({ ptz }) {
</div>
)}
</div>
{isPresetAdmin ? (
{canCreatePreset ? (
<form className="grid grid-cols-[minmax(0,1fr)_auto] gap-1" onSubmit={createPreset}>
<input
className="min-w-0 rounded border border-slate-700 bg-black px-2 py-1 text-xs text-slate-100 outline-none focus:border-cyan-300"
className="field-input min-w-0 text-xs"
value={name}
maxLength={60}
disabled={Boolean(busy)}
@@ -533,13 +540,23 @@ function buildPtzTurnModel(ptz, selfId) {
function PtzMediaPane({ ptz, open, framed = true }) {
const isOperator = Boolean(ptz?.isOperator);
const nonTurnVideoPolicy = useSessionSelector(
(state) => state.session?.bandwidthSavings?.nonTurnVideo || 'snapshots',
);
const selfId = useSessionSelector((state) => state.session?.socketId || null);
const snapshotFeeds = usePtzCameraSnapshots([PTZ_CAMERA_ID], { enabled: open && !isOperator });
/*
PTZ has its own turn queue, so non-operators are the camera equivalent of a
non-active rover driver. The server enforces the same policy in
canRequestLiveVideo(); this branch only chooses the expected browser render
path and never unlocks movement controls.
*/
const shouldUseLiveVideo = isOperator || nonTurnVideoPolicy === 'live';
const snapshotFeeds = usePtzCameraSnapshots([PTZ_CAMERA_ID], { enabled: open && !shouldUseLiveVideo });
const snapshot = snapshotFeeds[PTZ_CAMERA_ID] || null;
const turnModel = useMemo(() => buildPtzTurnModel(ptz, selfId), [ptz, selfId]);
const media = (
<>
{isOperator ? (
{shouldUseLiveVideo ? (
<PtzLiveVideo enabled={open} startMuted={false} />
) : (
<PtzSnapshotPreview feed={snapshot} label={ptz?.name || 'PTZ Camera'} />
@@ -1,5 +1,5 @@
// Replay Ready Popup
// Purpose: Presents the latest Discord-hosted replay video to web users as soon as upload completes.
// Purpose: Presents the latest delivered replay video, whether Discord-hosted or served by the rover server.
// Scope: Owns the ephemeral modal shell, immediate video loading, and click-outside close behavior.
import { useCallback, useEffect, useRef } from 'react';
import CardFrame from '../CardFrame/index.jsx';
@@ -0,0 +1,38 @@
// Session Document Title
// Purpose: Uses the configured local inter-instance profile name as the browser tab title.
// Scope: Owns only the document title lifecycle; the static HTML title remains the fallback.
import { useEffect } from 'react';
import { useSessionSelector } from '../../context/SessionContext.jsx';
const DEFAULT_DOCUMENT_TITLE = document.title;
export default function SessionDocumentTitle() {
const interInstanceEnabled = useSessionSelector((state) => Boolean(state.session?.interInstances?.enabled));
const interInstanceName = useSessionSelector((state) =>
String(state.session?.interInstances?.profile?.name || '').trim(),
);
useEffect(() => {
/*
The static title from index.html remains the source of truth until the
server confirms that inter-instance sharing is enabled and supplies a
usable profile name. This prevents the profile's loading state from
replacing the familiar fallback title with an empty or temporary value.
*/
if (!interInstanceEnabled || !interInstanceName) return undefined;
document.title = interInstanceName;
/*
Restore the static title when the synchronized profile disappears or the
feature is disabled. React also runs this cleanup during development's
StrictMode effect check, so the component never leaves a stale server name
behind when its session-derived conditions stop being true.
*/
return () => {
document.title = DEFAULT_DOCUMENT_TITLE;
};
}, [interInstanceEnabled, interInstanceName]);
return null;
}
@@ -4,6 +4,7 @@ import RoverDescriptionOverlay from '../HudOverlays/RoverDescriptionOverlay/inde
import OvercurrentOverlay from '../HudOverlays/OvercurrentOverlay/index.jsx';
import LowBatteryOverlay from '../HudOverlays/LowBatteryOverlay/index.jsx';
import VerticalBatteryOverlay from '../HudOverlays/VerticalBatteryOverlay/index.jsx';
import { useSessionSelector } from '../../context/SessionContext.jsx';
export default function SpectateVideo({
roverId = null,
@@ -11,12 +12,24 @@ export default function SpectateVideo({
fitParent = false,
layoutFormat = 'desktop',
}) {
const isExternalSpectatorSnapshotOnly = useSessionSelector((state) =>
state.session?.role === 'spectator' &&
state.session?.isLocalNetwork === false &&
state.session?.bandwidthSavings?.externalSpectatorVideo === 'snapshots',
);
/*
Server auth already denies external spectator WHEP when this policy is set,
but explicitly selecting snapshot mode avoids expected authorization denials
and keeps analytics focused on actual stream failures.
*/
const videoMode = isExternalSpectatorSnapshotOnly ? 'snapshot' : null;
return (
<div className={`flex flex-col gap-0.5 ${fitParent ? 'h-full' : ''}`}>
<div className={`relative w-full overflow-hidden bg-black ${fitParent ? 'h-full flex-1' : 'aspect-[4/3]'}`}>
<RoverMediaPlayer
roverId={roverId}
label={label}
videoMode={videoMode}
/>
<RoverDescriptionOverlay
roverId={roverId}
+11 -2
View File
@@ -326,9 +326,18 @@ function PtzControlReference() {
function PtzController({ open, onClose, layout = 'desktop' }) {
const ptz = useSessionSelector((state) => state.session?.ptzCamera || null);
const isOperator = Boolean(ptz?.isOperator);
const nonTurnVideoPolicy = useSessionSelector(
(state) => state.session?.bandwidthSavings?.nonTurnVideo || 'snapshots',
);
const isMobile = layout === 'mobile-portrait' || layout === 'mobile-landscape';
const { ptzRelease } = useSessionActions();
const snapshotFeeds = usePtzCameraSnapshots([PTZ_CAMERA_ID], { enabled: open && !isOperator });
/*
The VIP fullscreen surface is available to queued PTZ users too. Let queued
users see live video only when the central non-turn video policy allows it;
all movement and light controls still remain guarded by isOperator.
*/
const shouldUseLiveVideo = isOperator || nonTurnVideoPolicy === 'live';
const snapshotFeeds = usePtzCameraSnapshots([PTZ_CAMERA_ID], { enabled: open && !shouldUseLiveVideo });
const snapshot = snapshotFeeds[PTZ_CAMERA_ID] || null;
const [releasePending, setReleasePending] = useState(false);
@@ -431,7 +440,7 @@ function PtzController({ open, onClose, layout = 'desktop' }) {
bodyClassName={`grid h-full min-h-0 overflow-hidden ${sidebarWidthClass}`}
>
<main className="relative min-h-0 min-w-0 bg-black">
{isOperator ? (
{shouldUseLiveVideo ? (
<PtzLiveVideo enabled startMuted={false} />
) : (
<PtzSnapshotPreview feed={snapshot} label={ptz?.name || 'PTZ Camera'} />
+4
View File
@@ -410,6 +410,10 @@ export function SessionProvider({ children }) {
// maintenance without becoming a remote shell.
updateRover: (roverId) =>
emitWithAck('command', { roverId, type: 'update', data: { update: {} } }),
// Bulk rover updates stay server-owned so the admin browser sends one
// intent, then the server checks privileges and fans out the same fixed
// update command to every currently connected rover.
updateAllRovers: () => emitWithAck('command:updateAllRovers'),
rebootServer: () => emitWithAck('server:reboot'),
playUploadedAudio: ({ roverId, name, mime, dataBase64 }) =>
emitWithAck('audio:uploadPlay', { roverId, name, mime, dataBase64 }),
+18 -2
View File
@@ -168,7 +168,12 @@ export function ControlSystemProvider({ children }) {
: true;
const roverId = useSessionSelector((state) => state.session?.assignment?.roverId ?? null);
const homeAssistantEntities = useSessionSelector((state) => state.session?.homeAssistant?.entities ?? []);
const roomLightsLockedOn = useSessionSelector((state) => Boolean(state.session?.homeAssistant?.lightPolicy?.lockedOn));
const roomLightsLocked = useSessionSelector((state) =>
Boolean(state.session?.homeAssistant?.lightPolicy?.locked || state.session?.homeAssistant?.lightPolicy?.lockedOn),
);
const roomLightsLockedOn = useSessionSelector((state) =>
Boolean(state.session?.homeAssistant?.lightPolicy?.lockedOn),
);
const { homeAssistantSetState } = useSessionActions();
const overcurrentLimiter = useOvercurrentLimiter(roverId);
const driveTransform = useCallback(
@@ -183,6 +188,17 @@ export function ControlSystemProvider({ children }) {
const ptzControls = usePtzControlAdapter();
const turnOnAllLights = useCallback(() => {
/*
Automatic drive-mode lighting is convenience behavior for the open room.
A room-light lock is an explicit policy decision, including locked-off,
so this helper must not issue any Home Assistant commands while that
policy is active. Admins can still use the dedicated room controls when
they need to override individual lamps.
*/
if (roomLightsLocked) {
pendingLightsRef.current = false;
return;
}
const entities = homeAssistantEntities || [];
const targets = entities.filter(
(ent) =>
@@ -200,7 +216,7 @@ export function ControlSystemProvider({ children }) {
});
// Give the loop a chance; clear pending after issuing commands.
pendingLightsRef.current = false;
}, [homeAssistantEntities, homeAssistantSetState]);
}, [homeAssistantEntities, homeAssistantSetState, roomLightsLocked]);
useEffect(() => {
dispatch({ type: 'control/set-rover', payload: pipeline.roverId });
@@ -108,6 +108,9 @@ export default function KeyboardInputManager() {
const roverId = useControlSelector((control) => control.state.roverId);
const hornActive = useControlSelector((control) => Boolean(control.state.horn?.active));
const homeAssistant = useSessionSelector((state) => state.session?.homeAssistant || null);
const role = useSessionSelector((state) => state.session?.role || null);
const mode = useSessionSelector((state) => state.session?.mode || null);
const adminCanControlLockedLights = role === 'lockdown' || (role === 'admin' && mode !== 'lockdown');
const dockAssist = useManualDockAssist();
const { homeAssistantSetState, pushAlert } = useSessionActions();
const { focusChat } = useChatActions();
@@ -310,7 +313,14 @@ export default function KeyboardInputManager() {
const latest = latestRef.current;
const ha = latest?.homeAssistant;
if (!ha?.enabled || !ha?.connected) return;
if (ha?.lightPolicy?.locked || ha?.lightPolicy?.lockedOn) return;
/*
Room-light lock disables keyboard cycling for normal users because those
shortcuts are part of the public room-control surface. Admin sessions are
allowed through when the current site mode would also allow their socket
command, so keyboard behavior matches the server-side authorization and
the clickable Room Controls panel.
*/
if ((ha?.lightPolicy?.locked || ha?.lightPolicy?.lockedOn) && !latest?.adminCanControlLockedLights) return;
const entities = ha.entities || [];
const eligible = entities.filter(
(ent) =>
@@ -371,6 +381,7 @@ export default function KeyboardInputManager() {
homeAssistant,
homeAssistantSetState,
isChatFocused,
adminCanControlLockedLights,
keyboardSpeeds,
keymap,
nudgeServo,
+3 -3
View File
@@ -11,9 +11,9 @@ export const OVERCURRENT_GROUPS = [
];
export const DEFAULT_OVERCURRENT_LIMITS = {
downRatePerSec: 0.5,
upRatePerSec: 0.7,
releaseDelaySec: 1,
downRatePerSec: 0.4,
upRatePerSec: 0.5,
releaseDelaySec: 2.5,
outputRateMs: 250,
};
@@ -11,6 +11,7 @@ import OnlinePeopleStrip from './components/OnlinePeopleStrip.jsx';
import DisplayRoverGrid from './components/DisplayRoverGrid.jsx';
import DisplayChatFeed from './components/DisplayChatFeed.jsx';
import DisplayNoticeOverlay from './components/DisplayNoticeOverlay.jsx';
import DisplayPtzOperatorBadge from './components/DisplayPtzOperatorBadge.jsx';
export default function ServerDisplayContent() {
const { session } = useSession();
@@ -44,6 +45,11 @@ export default function ServerDisplayContent() {
<div className="min-h-0 flex-[1.28]">
<DisplayChatFeed />
</div>
{/* Keep the PTZ operator visible on the room board without changing the
existing rover/chat layout. The badge is self-hiding when nobody owns
the camera, so the display remains exactly as sparse as before between
PTZ turns. */}
<DisplayPtzOperatorBadge />
<DisplayNoticeOverlay />
<RewardRunOverlay />
{/* Display is spectator-like: every Discord-hosted replay should take over
@@ -0,0 +1,40 @@
// Display PTZ Operator Badge
// Purpose: Gives the physical /display page a simple, always-readable indicator
// for who currently owns the single PTZ camera turn.
// Scope: This is intentionally display-only chrome; PTZ ownership, naming, and
// permission rules stay in the server session state that every client already receives.
import { useSessionSelector } from '../../../context/SessionContext.jsx';
export default function DisplayPtzOperatorBadge() {
const ptz = useSessionSelector((state) => state.session?.ptzCamera || null);
const operatorLabel = String(ptz?.operatorLabel || '').trim();
if (!ptz?.enabled || !operatorLabel) {
/*
The display should stay clean when nobody has the camera. Returning null
instead of showing "none" makes the badge behave like a popup: it appears
only for an active PTZ operator and disappears as soon as the turn ends.
*/
return null;
}
return (
<aside
className="pointer-events-none fixed bottom-[2vh] right-[2vw] z-[90] max-w-[42vw] border-4 border-sky-200 bg-sky-700 px-[1.4vw] py-[1vh] text-center"
aria-label={`PTZ operator ${operatorLabel}`}
>
{/*
The label is deliberately short because /display is a room board, not a
control panel. The large name is the useful information from across the
room, while the smaller prefix prevents the blue box from being mistaken
for a rover driver or chat message.
*/}
<div className="text-7xl font-black tracking-normal text-sky-100">
PTZ camera
</div>
<div className="truncate text-9xl font-black leading-none text-white">
{operatorLabel}
</div>
</aside>
);
}
+10 -1
View File
@@ -9,6 +9,9 @@ export function useDriverVideoModePolicy(roverId) {
const turnQueues = useSessionSelector((state) => state.session?.turnQueues ?? {});
const socketId = useSessionSelector((state) => state.session?.socketId || null);
const activeDrivers = useSessionSelector((state) => state.session?.activeDrivers ?? {});
const nonTurnVideoPolicy = useSessionSelector(
(state) => state.session?.bandwidthSavings?.nonTurnVideo || 'snapshots',
);
const isTurnsMode = mode === 'turns';
/*
This policy only switches preview/full video around a multi-second turn
@@ -43,7 +46,13 @@ export function useDriverVideoModePolicy(roverId) {
});
return unique.size;
}, [users]);
const shouldUsePreviewByLoad = isTurnsMode && totalDrivers > totalRovers;
/*
The server sends the bandwidth policy because the same rule is enforced in
video authorization. The hook only mirrors that policy so the UI avoids
requesting live video when snapshots are the intended non-turn experience.
*/
const shouldUsePreviewByLoad =
nonTurnVideoPolicy === 'snapshots' && isTurnsMode && totalDrivers > totalRovers;
const isPreSwitchWindow =
isTurnsMode && isNextDriver && msUntilTurn != null && msUntilTurn <= 5000 && msUntilTurn > 0;
const showNotTurnNotice = isTurnsMode && !isActiveDriver;
+11 -1
View File
@@ -6,6 +6,7 @@ import { useSession } from '../context/SessionContext.jsx';
export function useSpectatorMode() {
const { session, setRole, subscribeAll, connected } = useSession();
const [ready, setReady] = useState(false);
const canUseSpectatorAccess = session?.bandwidthSavings?.canUseExternalSpectatorAccess !== false;
useEffect(() => {
let cancelled = false;
@@ -14,6 +15,15 @@ export function useSpectatorMode() {
setReady(false);
return;
}
if (!canUseSpectatorAccess) {
/*
The server will reject the role change too, but stopping here prevents
a blocked external spectator from retrying on every session sync while
the page is intentionally waiting for an admin grant or config change.
*/
setReady(false);
return;
}
try {
if (session?.role !== 'spectator') {
await setRole('spectator');
@@ -33,7 +43,7 @@ export function useSpectatorMode() {
return () => {
cancelled = true;
};
}, [connected, session?.mode, session?.role, setRole, subscribeAll]);
}, [canUseSpectatorAccess, connected, session?.mode, session?.role, setRole, subscribeAll]);
return ready;
}
+2
View File
@@ -17,11 +17,13 @@ import DatabaseAdminApp from './database/DatabaseAdminApp.jsx'
import { SettingsProvider } from './settings/index.js'
import DeterrenceChaos from './components/DeterrenceChaos/index.jsx'
import AnalyticsReporter from './analytics/AnalyticsReporter.jsx'
import SessionDocumentTitle from './components/SessionDocumentTitle/index.jsx'
createRoot(document.getElementById('root')).render(
<StrictMode>
<SocketProvider>
<SessionProvider>
<SessionDocumentTitle />
<TelemetryProvider>
<SettingsProvider>
<ChatProvider>
@@ -1,7 +1,7 @@
// Mini Summary Content
// Purpose: Defines the Mini Summary Content module and the local helpers/components used in this file.
// Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit.
import { useEffect, useMemo, useState } from 'react';
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useSession } from '../../context/SessionContext.jsx';
import { useVisualTelemetryFrames } from '../../context/TelemetryContext.jsx';
import { useVideoRequests } from '../../hooks/useVideoRequests.js';
@@ -9,6 +9,7 @@ import { useRoverSnapshots } from '../../hooks/useRoverSnapshots.js';
import { useSpectatorMode } from '../../hooks/useSpectatorMode.js';
import useDefaultNickname from '../../hooks/useDefaultNickname.js';
import useUserIdentitySync from '../../hooks/useUserIdentitySync.js';
import PtzLiveVideo from '../../components/PtzLiveVideo/index.jsx';
import RoverMediaPlayer from '../../components/RoverMediaPlayer/index.jsx';
import FitViewportFrame from './components/FitViewportFrame.jsx';
import InfoColumn from './components/InfoColumn.jsx';
@@ -21,6 +22,133 @@ function hasRoverAudioCapture(rover) {
return Boolean(rover?.media?.audioCapture?.enabled && rover?.media?.audioCapture?.publishUrl);
}
function AutoFitBoxText({ children, className = '', maxSize = 1000, minSize = 14 }) {
const containerRef = useRef(null);
const textRef = useRef(null);
const [fontSize, setFontSize] = useState(maxSize);
useLayoutEffect(() => {
const container = containerRef.current;
const textEl = textRef.current;
if (!container || !textEl) return undefined;
let raf = null;
const fit = () => {
const width = container.clientWidth;
const height = container.clientHeight;
if (!width || !height) {
scheduleFit();
return;
}
/*
Unlike the shared AutoFitText helper, the PTZ operator label has a real
second constraint: before rotation, text length must fit the screen
height and text thickness must fit the blue column width. Binary search
lets the name use as much of both dimensions as possible without
clipping either after the 90-degree transform.
*/
let low = minSize;
let high = maxSize;
let best = minSize;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
textEl.style.fontSize = `${mid}px`;
const fits = textEl.scrollWidth <= width && textEl.scrollHeight <= height;
if (fits) {
best = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
setFontSize(best);
};
const scheduleFit = () => {
if (raf) cancelAnimationFrame(raf);
raf = requestAnimationFrame(fit);
};
scheduleFit();
const ro = new ResizeObserver(scheduleFit);
ro.observe(container);
return () => {
if (raf) cancelAnimationFrame(raf);
ro.disconnect();
};
}, [children, maxSize, minSize]);
return (
<div ref={containerRef} className="flex h-full w-full min-w-0 items-center justify-center overflow-hidden">
<div
ref={textRef}
className={`whitespace-nowrap ${className}`}
style={{ fontSize: `${fontSize}px`, lineHeight: 1 }}
>
{children}
</div>
</div>
);
}
function MiniPtzUserColumn({ label }) {
const columnRef = useRef(null);
const [columnSize, setColumnSize] = useState({ width: 0, height: 0 });
useLayoutEffect(() => {
const column = columnRef.current;
if (!column) return undefined;
const updateSize = () => {
/*
The label box is measured before rotation, so the blue column's screen
height becomes the label's unrotated width, and the blue column's screen
width becomes the label's unrotated height. That swapped geometry is the
key difference from normal horizontal auto-fit text.
*/
setColumnSize({
width: column.clientWidth,
height: column.clientHeight,
});
};
updateSize();
const ro = new ResizeObserver(updateSize);
ro.observe(column);
return () => ro.disconnect();
}, []);
return (
<div ref={columnRef} className="relative flex h-full w-full min-w-0 items-center justify-center overflow-hidden bg-sky-600 text-white">
{/*
The mini page is intended for glanceable room displays, so the PTZ user
gets the same right-side identity treatment as rover metadata while
letting the blue column absorb any extra horizontal room after the
full-height PTZ video takes the camera-shaped part of the viewport.
*/}
{columnSize.width > 16 && columnSize.height > 16 ? (
<div
className="absolute left-1/2 top-1/2 origin-center -translate-x-1/2 -translate-y-1/2 rotate-90 px-2 text-center leading-none"
style={{
width: `${columnSize.height - 16}px`,
height: `${columnSize.width - 16}px`,
}}
>
{/*
This fitter checks both text width and text height before rotation.
After rotation, that means the username fits both the vertical
reading length and the visible thickness of the blue column.
*/}
<AutoFitBoxText className="font-black leading-none text-white" maxSize={1000} minSize={16}>
{label}
</AutoFitBoxText>
</div>
) : null}
</div>
);
}
export default function MiniSummaryContent() {
const { session } = useSession();
const spectatorReady = useSpectatorMode();
@@ -33,24 +161,30 @@ export default function MiniSummaryContent() {
const canSpectateVideo = Boolean(session?.isLocalNetwork);
const frames = useVisualTelemetryFrames();
const roster = session?.roster ?? [];
const ptz = session?.ptzCamera || null;
const ptzOperatorLabel = String(ptz?.operatorLabel || '').trim();
const hasActivePtzOperator = Boolean(ptz?.enabled && ptzOperatorLabel);
const [index, setIndex] = useState(0);
const activeDrivers = session?.activeDrivers || {};
const driverRoster = useMemo(
() => roster.filter((rover) => activeDrivers[rover.id]),
[roster, activeDrivers],
);
const snapshotRoster = driverRoster.length ? driverRoster : roster;
const mediaRovers = useMemo(
() => roster.filter((rover) => rover?.id),
[roster],
);
const snapshotFeeds = useRoverSnapshots(
snapshotRoster.map((rover) => rover.id),
mediaRovers.map((rover) => rover.id),
{ enabled: !inLockdown && !canSpectateVideo, version: session?.mode },
);
const videoEntries = useMemo(
() =>
canSpectateVideo
? snapshotRoster.map((rover) => ({ type: 'rover', id: rover.id, key: rover.id }))
? mediaRovers.map((rover) => ({ type: 'rover', id: rover.id, key: rover.id }))
: [],
[canSpectateVideo, snapshotRoster],
[canSpectateVideo, mediaRovers],
);
const videoSources = useVideoRequests(videoEntries, {
enabled: !inLockdown && canSpectateVideo,
@@ -67,27 +201,23 @@ export default function MiniSummaryContent() {
);
const audioSources = useVideoRequests(audioEntries, { enabled: !inLockdown, version: session?.mode });
const roverPool = useMemo(() => {
if (!driverRoster.length) return [];
if (!canSpectateVideo) {
const withSnapshot = driverRoster.filter((rover) => snapshotFeeds[rover.id]?.objectUrl);
return withSnapshot.length ? withSnapshot : driverRoster;
}
const withVideo = driverRoster.filter((rover) => {
const sessionInfo = videoSources[rover.id];
return sessionInfo?.url && !sessionInfo?.error;
});
return withVideo.length ? withVideo : driverRoster;
}, [driverRoster, snapshotFeeds, videoSources, canSpectateVideo]);
const rotationPool = useMemo(() => {
return roverPool.map((rover) => ({ type: 'rover', rover }));
}, [roverPool]);
/*
Rotation membership is intentionally based on human-controlled sources,
not on WHEP response timing. The mounted media players below are a
separate full-roster list, so a video token refresh, snapshot arrival, or
active-driver update changes which already-warm layer is visible instead
of tearing down the player components themselves.
*/
const entries = driverRoster.map((rover) => ({ type: 'rover', rover }));
if (hasActivePtzOperator) entries.push({ type: 'ptz' });
return entries;
}, [driverRoster, hasActivePtzOperator]);
const rotationKey = useMemo(
() =>
rotationPool
.map((entry) => `r:${entry.rover.id}`)
.map((entry) => (entry.type === 'ptz' ? 'p:ptz-camera' : `r:${entry.rover.id}`))
.join('|'),
[rotationPool],
);
@@ -106,12 +236,14 @@ export default function MiniSummaryContent() {
const activeEntry = rotationPool.length ? rotationPool[index % rotationPool.length] : null;
const activeRover = activeEntry?.type === 'rover' ? activeEntry.rover : null;
const activePtz = activeEntry?.type === 'ptz';
const activeSnapshot = !canSpectateVideo && activeRover ? snapshotFeeds[activeRover.id] || null : null;
const activeVideo = canSpectateVideo && activeRover ? videoSources[activeRover.id] || null : null;
const activeAudio = activeRover ? audioSources[`${activeRover.id}-audio`] || null : null;
const activeFrame = activeRover ? frames[activeRover.id] || null : null;
const driverLabel = activeRover ? formatDriverLabel({ roverId: activeRover.id, session }) : null;
const showSideBySideFallback = !driverRoster.length && !hasActivePtzOperator;
const hasMountedMediaSources = Boolean(mediaRovers.length || ptz?.enabled);
if (inLockdown) {
return (
@@ -124,10 +256,10 @@ export default function MiniSummaryContent() {
);
}
if (!driverRoster.length) {
return (
<div className="relative flex h-screen w-screen overflow-hidden bg-black text-slate-100">
<section className="flex h-full w-full gap-x-3 bg-slate-900 px-0">
{showSideBySideFallback ? (
<section className="absolute inset-0 z-30 flex h-full w-full gap-x-3 bg-slate-900 px-0">
{roster.length ? (
roster.map((rover) => (
<InfoColumn
@@ -148,34 +280,50 @@ export default function MiniSummaryContent() {
</div>
)}
</section>
</div>
);
}
return (
<div className="relative flex h-screen w-screen overflow-hidden bg-black text-slate-100">
) : null}
<section
className="relative flex h-full shrink-0 items-center justify-start overflow-hidden bg-black"
style={{ width: 'min(100vw, calc(100vh * 4 / 3))' }}
className={`relative flex h-full shrink-0 items-center justify-start overflow-hidden bg-black ${
/*
The no-driver view is still visually the old side-by-side roster,
but keeping this carousel layer mounted behind it prevents every
rover WHEP player from cold-starting when the first driver appears.
*/
showSideBySideFallback ? 'opacity-0 pointer-events-none' : ''
}`}
style={{
/*
Rover cameras are framed by the existing 4:3 viewport helper below,
but the PTZ camera is a 16:9 source. Give PTZ a 16:9 full-height
media lane here so the actual camera image reaches the top and
bottom of the screen, then let the right-side blue column consume
whatever width remains.
*/
width: activePtz ? 'min(100vw, calc(100vh * 16 / 9))' : 'min(100vw, calc(100vh * 4 / 3))',
}}
>
{!spectatorReady ? (
<div className="flex h-full w-full items-center justify-center text-sm text-slate-500">
Switching to spectator
</div>
) : activeRover ? (
<FitViewportFrame>
{canSpectateVideo ? (
<div className="relative h-full w-full">
{rotationPool.map((entry) => {
const rover = entry.rover;
) : hasMountedMediaSources ? (
<div className="relative h-full w-full overflow-hidden bg-black">
{/*
Keep every mini media source mounted while the carousel rotates.
WHEP negotiation is the expensive part that caused the visible
blank gap, so inactive sources are hidden with opacity instead of
being removed from React's tree and forced to reconnect later.
*/}
{mediaRovers.map((rover) => {
const isActive = activeRover?.id === rover.id;
return (
<div
key={rover.id}
className={`absolute inset-0 ${isActive ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}
>
<FitViewportFrame>
{canSpectateVideo ? (
<RoverMediaPlayer
sessionInfo={videoSources[rover.id] || null}
roverId={rover.id}
videoMode="whep"
snapshotFeed={null}
audioSessionInfo={isActive ? activeAudio : null}
@@ -183,29 +331,53 @@ export default function MiniSummaryContent() {
label={rover.name || rover.id}
sensors={frames[rover.id]?.sensors || null}
/>
</div>
);
})}
</div>
) : (
<RoverMediaPlayer
sessionInfo={null}
videoMode="snapshot"
snapshotFeed={activeSnapshot}
audioSessionInfo={activeAudio}
label={activeRover.name || activeRover.id}
sensors={activeFrame?.sensors || null}
snapshotFeed={snapshotFeeds[rover.id] || null}
audioSessionInfo={isActive ? activeAudio : null}
forceMute={!isActive}
label={rover.name || rover.id}
sensors={frames[rover.id]?.sensors || null}
/>
)}
</FitViewportFrame>
</div>
);
})}
{ptz?.enabled ? (
<div className={`absolute inset-0 ${activePtz ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}>
{/*
PTZ bypasses FitViewportFrame because that helper intentionally
enforces the rover camera's 4:3 shape. Keeping this component
mounted preserves the PTZ WHEP session across rover/PTZ
rotations while still letting the visible pane resize to 16:9
when PTZ becomes active.
*/}
<PtzLiveVideo
enabled={!inLockdown}
startMuted
className="relative h-full w-full bg-black"
videoClassName="h-full w-full object-cover"
/>
</div>
) : null}
</div>
) : (
<div className="flex h-full w-full items-center justify-center text-sm text-slate-500">
{driverRoster.length ? 'No sources available.' : 'No active drivers.'}
</div>
)}
</section>
<aside className="flex h-full min-w-0 flex-1 flex-col border-l border-slate-800/60 bg-black">
{activeRover ? (
<aside
className={`flex h-full min-w-0 flex-1 flex-col border-l border-slate-800/60 bg-black ${
showSideBySideFallback ? 'opacity-0 pointer-events-none' : ''
}`}
>
{activePtz ? (
<MiniPtzUserColumn label={ptzOperatorLabel} />
) : activeRover ? (
<InfoColumn
rover={activeRover}
frame={activeFrame}
@@ -3,6 +3,7 @@
// Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit.
import { useSession, useSessionActions, useSessionSelector } from '../../context/SessionContext.jsx';
import { useSpectatorMode } from '../../hooks/useSpectatorMode.js';
import { useSettingsNamespace } from '../../settings/index.js';
import useDefaultNickname from '../../hooks/useDefaultNickname.js';
import useUserIdentitySync from '../../hooks/useUserIdentitySync.js';
import ChatPanel from '../../components/ChatPanel/index.jsx';
@@ -17,12 +18,26 @@ import usePortraitLayout from './hooks/usePortraitLayout.js';
import RoverRow from './components/RoverRow.jsx';
import SecondaryRow from './components/SecondaryRow.jsx';
import LogsRow from './components/LogsRow.jsx';
import SpectatorViewControls from './components/SpectatorViewControls.jsx';
const SPECTATOR_VIEW_DEFAULTS = {
showSidebar: true,
showRovers: true,
showPtz: true,
showRoomCameras: true,
};
export default function SpectatorContent() {
const { session } = useSession();
const latestReplay = useSessionSelector((state) => state.latestReplay);
const { clearLatestReplay } = useSessionActions();
const { value: viewPreferences, save: saveViewPreferences } = useSettingsNamespace(
'spectatorPage',
SPECTATOR_VIEW_DEFAULTS,
);
const inLockdown = session?.mode === 'lockdown';
const canUseSpectatorAccess = session?.bandwidthSavings?.canUseExternalSpectatorAccess !== false;
const spectatorAccessMode = session?.bandwidthSavings?.externalSpectatorAccess || 'on';
useDefaultNickname();
// The spectator route is not rendered through App.jsx, so it must opt into
// the same persisted identity heartbeat here. That keeps the existing
@@ -32,6 +47,15 @@ export default function SpectatorContent() {
useSpectatorMode();
const isPortraitLayout = usePortraitLayout();
const roster = session?.roster ?? [];
// Treat absent keys as enabled so older settings cookies gain every new view
// option by default instead of unexpectedly hiding parts of the page.
const showSidebar = viewPreferences?.showSidebar !== false;
const showRovers = viewPreferences?.showRovers !== false;
const showPtz = viewPreferences?.showPtz !== false;
const showRoomCameras = viewPreferences?.showRoomCameras !== false;
const updateViewPreference = (key, enabled) => {
saveViewPreferences((current) => ({ ...(current || {}), [key]: Boolean(enabled) }));
};
if (inLockdown) {
return (
@@ -44,9 +68,33 @@ export default function SpectatorContent() {
);
}
if (session && !canUseSpectatorAccess) {
/*
The server keeps this socket in the normal user role when external
spectating is blocked. Rendering a full-page gate makes that intentional
state obvious instead of showing an empty spectator shell that repeatedly
fails to subscribe.
*/
const message = spectatorAccessMode === 'admin'
? 'This external spectator identity needs admin approval before it can view the spectator page.'
: spectatorAccessMode === 'verifiedOnly'
? 'This external spectator identity must be verified before it can view the spectator page.'
: 'External spectator access is disabled on this server.';
return (
<div className="flex min-h-screen items-center justify-center bg-black text-slate-200">
<div className="surface max-w-md space-y-0.5 p-1 text-center text-sm">
<p className="text-lg font-semibold text-white">Spectate access required.</p>
<p className="text-slate-300">{message}</p>
</div>
</div>
);
}
const mainClass = isPortraitLayout
? 'flex min-h-screen flex-col bg-black text-slate-100 md:h-screen md:overflow-hidden'
: 'grid min-h-screen grid-cols-1 gap-0.5 bg-black text-slate-100 md:h-full md:min-h-0 md:grid-cols-[minmax(0,1fr)_18rem] lg:grid-cols-[minmax(0,1fr)_20rem]';
: showSidebar
? 'grid min-h-screen grid-cols-1 gap-0.5 bg-black text-slate-100 md:h-full md:min-h-0 md:grid-cols-[minmax(0,1fr)_18rem] lg:grid-cols-[minmax(0,1fr)_20rem]'
: 'grid min-h-screen grid-cols-1 gap-0.5 bg-black text-slate-100 md:h-full md:min-h-0';
const contentClass = isPortraitLayout
? 'order-2 flex min-h-0 min-w-0 flex-1 flex-col gap-0.5 overflow-y-auto'
: 'order-1 flex min-h-0 min-w-0 flex-col gap-0.5 md:overflow-y-auto';
@@ -59,7 +107,7 @@ export default function SpectatorContent() {
return (
<div className="min-h-screen bg-black text-slate-100 md:h-screen md:overflow-hidden">
<main className={mainClass}>
<section className={sidebarClass}>
{showSidebar ? <section className={sidebarClass}>
{isPortraitLayout ? (
<div className={`${topBarItemClass} ${portraitItemHeight} flex flex-col gap-0.5`}>
<GlobalObjectiveBanner layout="desktop" dismissable={false} className="text-sm" />
@@ -90,12 +138,20 @@ export default function SpectatorContent() {
<div className={`${topBarItemClass} ${isPortraitLayout ? portraitItemHeight : ''}`}>
<LogsRow className={`${isPortraitLayout ? 'h-full' : 'h-40'} overflow-hidden`} />
</div>
</section>
</section> : null}
<section className={contentClass}>
<RoverRow roster={roster} />
<SecondaryRow />
{/*
Conditional rendering is deliberate: CSS-only hiding would leave
WHEP peer connections and snapshot socket subscriptions active.
Unmounting delegates cleanup to the media components that own them.
*/}
{showRovers || showPtz ? (
<RoverRow roster={roster} showRovers={showRovers} showPtz={showPtz} />
) : null}
{showRoomCameras ? <SecondaryRow /> : null}
</section>
</main>
<SpectatorViewControls preferences={viewPreferences} onToggle={updateViewPreference} />
<AlertFeed />
<RewardRunOverlay />
{/* Spectators do not have the replay request panel that normal web users see, so
@@ -81,6 +81,19 @@ function PtzSnapshotFallback({ label, source }) {
}
function PtzLiveOrSnapshot({ label }) {
const isExternalSpectatorSnapshotOnly = useSessionSelector((state) =>
state.session?.role === 'spectator' &&
state.session?.isLocalNetwork === false &&
state.session?.bandwidthSavings?.externalSpectatorVideo === 'snapshots',
);
/*
PTZ live authorization is server-owned, but the spectator page knows when
the configured outcome is snapshot-only. Rendering the fallback directly
avoids a guaranteed denied WHEP request for every external spectator card.
*/
if (isExternalSpectatorSnapshotOnly) {
return <PtzSnapshotFallback label={label} source={null} />;
}
return (
<PtzLiveVideo
enabled
@@ -4,14 +4,21 @@
import RoverSpectatorCard from './RoverSpectatorCard.jsx';
import PtzSpectatorCard from './PtzSpectatorCard.jsx';
export default function RoverRow({ roster }) {
export default function RoverRow({ roster, showRovers = true, showPtz = true }) {
return (
<section className="grid grid-cols-1 gap-0.5 md:grid-cols-2">
{roster.length === 0 ? <p className="col-span-full text-slate-400">No rovers registered.</p> : null}
{roster.map((rover) => (
{showRovers && roster.length === 0 ? <p className="col-span-full text-slate-400">No rovers registered.</p> : null}
{showRovers
? roster.map((rover) => (
<RoverSpectatorCard key={rover.id} rover={rover} />
))}
<PtzSpectatorCard />
))
: null}
{/*
PTZ intentionally remains the last grid item. With three rovers it
therefore occupies the fourth tile, preserving the spectator layout's
designed visual balance while still allowing independent unmounting.
*/}
{showPtz ? <PtzSpectatorCard /> : null}
</section>
);
}
@@ -0,0 +1,82 @@
// Spectator View Controls
// Purpose: Lets each spectator choose which major page regions consume space and media bandwidth.
// Scope: Owns only the fixed gear menu UI; cookie persistence and layout decisions remain in SpectatorContent.
import { useEffect, useRef, useState } from 'react';
import { FaCog } from 'react-icons/fa';
import CardFrame from '../../../components/CardFrame/index.jsx';
const VIEW_OPTIONS = [
{ key: 'showSidebar', label: 'Sidebar' },
{ key: 'showRovers', label: 'Rovers' },
{ key: 'showPtz', label: 'PTZ camera' },
{ key: 'showRoomCameras', label: 'Room cameras' },
];
export default function SpectatorViewControls({ preferences, onToggle }) {
const [open, setOpen] = useState(false);
const controlsRef = useRef(null);
useEffect(() => {
if (!open) return undefined;
const handlePointerDown = (event) => {
/*
The popup floats above both the sidebar and camera grid, so clicking
elsewhere should dismiss it without changing any saved preference.
Keeping the gear and popup under one ref makes clicks on either safe.
*/
if (!controlsRef.current?.contains(event.target)) setOpen(false);
};
const handleKeyDown = (event) => {
// Escape mirrors normal dialog/menu behavior without trapping keyboard focus.
if (event.key === 'Escape') setOpen(false);
};
document.addEventListener('pointerdown', handlePointerDown);
document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('pointerdown', handlePointerDown);
document.removeEventListener('keydown', handleKeyDown);
};
}, [open]);
return (
<div ref={controlsRef} className="fixed right-1 top-1 z-50 flex flex-col items-end gap-0.5">
<button
type="button"
className="button-dark flex h-8 w-8 items-center justify-center p-0 text-slate-100 shadow-lg"
aria-label="Spectator view settings"
aria-expanded={open}
aria-controls="spectator-view-controls"
onClick={() => setOpen((current) => !current)}
>
<FaCog aria-hidden="true" />
</button>
{open ? (
<CardFrame
title="Spectator view"
className="w-48 shadow-xl"
bodyClassName="space-y-0.5 p-0.5 text-sm"
clipOverflow={false}
>
<div id="spectator-view-controls" className="space-y-0.5">
{VIEW_OPTIONS.map((option) => (
<label
key={option.key}
className="surface-muted flex cursor-pointer items-center gap-0.5 px-1 py-0.75 text-slate-100"
>
<input
type="checkbox"
className="h-3.5 w-3.5 accent-sky-500"
checked={preferences[option.key] !== false}
onChange={(event) => onToggle(option.key, event.target.checked)}
/>
<span>{option.label}</span>
</label>
))}
</div>
</CardFrame>
) : null}
</div>
);
}