Compare commits

..
Author SHA1 Message Date
legop3 79d36cae93 update donecharging wav sound
Container image / image (push) Failing after 1m4s
2026-10-18 14:52:27 -04:00
legop3 1dcd7e5d7d add beeps for overcurrent, HELP clear, and low battery 2026-10-18 14:32:59 -04:00
legop3 b4bc99ab27 add server access node to battery embed 2026-10-18 14:22:36 -04:00
legop3 c94e1a0508 change request to switch
Container image / image (push) Failing after 59s
2026-10-09 18:44:50 -04:00
legop3 abcb0871b2 allowed to leave is now used in the web UI to show and hide request / open buttons and trigger popup when leaving the page 2026-10-09 18:30:10 -04:00
legop3 1ffe680895 redoing dock your rover popup thingy
Container image / image (push) Failing after 56s
2026-10-09 17:27:55 -04:00
legop3 ed26b90384 Merge pull request #32 from legop3/FEAT-announcer-audio-stream
Feat announcer audio stream
2026-10-09 14:42:52 -04:00
15 changed files with 200 additions and 141 deletions
Binary file not shown.
@@ -4,7 +4,7 @@
const path = require('path'); const path = require('path');
const { subscribe } = require('../eventBus'); const { subscribe } = require('../eventBus');
const DONE_CHARGING_SOUND_PATH = path.resolve(__dirname, '..', '..', '..', 'public', 'donecharging.wav'); const DONE_CHARGING_SOUND_PATH = path.resolve(__dirname, '..', '..', '..', 'assets', 'donecharging.wav');
function registerChargeCompleteSound(deps) { function registerChargeCompleteSound(deps) {
const { const {
@@ -12,22 +12,18 @@ function registerChargeCompleteSound(deps) {
playServerAudioFile, playServerAudioFile,
} = deps; } = deps;
subscribe('battery.unlocked', (event = {}) => { subscribe('battery.chargeComplete', (event = {}) => {
const roverId = String(event?.payload?.roverId || '').trim(); const roverId = String(event?.payload?.roverId || '').trim();
if (!roverId) return; if (!roverId) return;
try { try {
// battery.unlocked is the existing server-side definition of "done
// charging" because it only fires after the battery manager has waited
// through its full charge-release policy. Playing from this event avoids
// duplicating charging thresholds or raw sensor-state guesses here.
playServerAudioFile(roverId, DONE_CHARGING_SOUND_PATH, { playServerAudioFile(roverId, DONE_CHARGING_SOUND_PATH, {
source: 'charge-complete', source: 'charge-complete',
}); });
logger.info('Played charging complete sound', { roverId, filePath: DONE_CHARGING_SOUND_PATH }); logger.info('Started charging complete sound', { roverId, filePath: DONE_CHARGING_SOUND_PATH });
} catch (err) { } catch (err) {
// A missing/offline rover or unavailable ffmpeg should not affect the // A missing/offline rover or unavailable ffmpeg should not affect the
// battery manager's unlock decision. The sound is an announcement layered // battery manager's processing. The sound is an announcement layered
// on top of the state transition, so failures are logged and contained. // on top of the state transition, so failures are logged and contained.
logger.warn('Failed to play charging complete sound', { logger.warn('Failed to play charging complete sound', {
roverId, roverId,
@@ -4,6 +4,7 @@
const logger = require('../../globals/logger').child('batteryManager'); const logger = require('../../globals/logger').child('batteryManager');
const { publishEvent } = require('../eventBus'); const { publishEvent } = require('../eventBus');
const { managerEvents, lockRover, rovers } = require('../roverManager'); const { managerEvents, lockRover, rovers } = require('../roverManager');
const { issueCommand } = require('../commandService');
const STATES = { const STATES = {
NORMAL: 'normal', NORMAL: 'normal',
@@ -29,6 +30,7 @@ function getState(roverId) {
dockedCharging: false, dockedCharging: false,
charging: false, charging: false,
batteryLocked: false, batteryLocked: false,
completionAnnounced: false,
waitingSince: null, waitingSince: null,
}); });
} }
@@ -61,6 +63,11 @@ function handleSensorEvent({ roverId, sensors, batteryState }) {
} }
if (!state.urgent && batteryState?.urgentActive) { if (!state.urgent && batteryState?.urgentActive) {
state.urgent = true; state.urgent = true;
try {
issueCommand(roverId, { type: 'song', song: { notes: [{ note: 72, duration: 8 }, { note: 0, duration: 8 }, { note: 72, duration: 16 }] } });
} catch (err) {
logger.warn('Failed to play urgent battery warning', { roverId, error: err.message });
}
publishEvent({ publishEvent({
source: 'batteryManager', source: 'batteryManager',
type: 'battery.urgent', type: 'battery.urgent',
@@ -137,6 +144,18 @@ function handleSensorEvent({ roverId, sensors, batteryState }) {
(batteryState?.charge != null && fullThreshold != null && batteryState.charge >= fullThreshold) || (batteryState?.charge != null && fullThreshold != null && batteryState.charge >= fullThreshold) ||
(batteryState?.percent != null && batteryState.percent >= 0.99); (batteryState?.percent != null && batteryState.percent >= 0.99);
// Announce once per dock visit, independently of the charging lock. Keep the
// latch at 100% so small charge fluctuations cannot repeat the sound.
if (!onDock) state.completionAnnounced = false;
if (onDock && batteryState?.percentDisplay >= 100 && !state.completionAnnounced) {
state.completionAnnounced = true;
publishEvent({
source: 'batteryManager',
type: 'battery.chargeComplete',
payload: { roverId, batteryState },
});
}
const needsCharge = state.warned; const needsCharge = state.warned;
if (dockedCharging && lockable && needsCharge && !state.batteryLocked && !isFull && !waitingLongEnough) { if (dockedCharging && lockable && needsCharge && !state.batteryLocked && !isFull && !waitingLongEnough) {
@@ -2,6 +2,7 @@
// Purpose: Centralizes rover battery/status snapshot formatting and embed rendering for Discord surfaces. // Purpose: Centralizes rover battery/status snapshot formatting and embed rendering for Discord surfaces.
// Scope: Shared presentation logic for status commands and admin alert battery event posts. // Scope: Shared presentation logic for status commands and admin alert battery event posts.
const { EmbedBuilder } = require('discord.js'); const { EmbedBuilder } = require('discord.js');
const { getMode } = require('../modeManager');
function formatVoltage(voltageMv) { function formatVoltage(voltageMv) {
if (voltageMv == null) return 'n/a'; if (voltageMv == null) return 'n/a';
@@ -69,6 +70,7 @@ function buildRoverStatusSnapshot(record) {
function buildBatteryStatusEmbed({ color = 0x2196f3, records = [] }) { function buildBatteryStatusEmbed({ color = 0x2196f3, records = [] }) {
const embed = new EmbedBuilder().setTitle('Rover Battery Status').setColor(color).setTimestamp(new Date()); const embed = new EmbedBuilder().setTitle('Rover Battery Status').setColor(color).setTimestamp(new Date());
embed.addFields({ name: 'Server mode', value: getMode(), inline: true });
const snapshots = records.map((entry) => buildRoverStatusSnapshot(entry)).filter(Boolean); const snapshots = records.map((entry) => buildRoverStatusSnapshot(entry)).filter(Boolean);
if (!snapshots.length) { if (!snapshots.length) {
embed.setDescription('No rovers online.'); embed.setDescription('No rovers online.');
@@ -400,6 +400,7 @@ function createOvercurrentProtectionService(options = {}) {
type: 'drive', type: 'drive',
driveDirect: { left: 0, right: 0 }, driveDirect: { left: 0, right: 0 },
}); });
issueAdjustedCommand(roverId, { type: 'song', song: { notes: [{ note: 76, duration: 8 }, { note: 72, duration: 8 }, { note: 67, duration: 16 }] } });
logger.warn('Stopped rover after persistent wheel overcurrent', { logger.warn('Stopped rover after persistent wheel overcurrent', {
roverId, roverId,
motor: stalledWheel, motor: stalledWheel,
@@ -2,20 +2,19 @@
// Purpose: Publishes sustained 600-series Roomba trouble as roster and alert state. // Purpose: Publishes sustained 600-series Roomba trouble as roster and alert state.
// Scope: Integrates the pure monitor with roverManager, browser alerts, and the event bus. // Scope: Integrates the pure monitor with roverManager, browser alerts, and the event bus.
const roverManager = require('../roverManager'); const roverManager = require('../roverManager');
const { issueCommand } = require('../commandService');
const { sendAlert } = require('../alertService'); const { sendAlert } = require('../alertService');
const { publishEvent } = require('../eventBus'); const { publishEvent } = require('../eventBus');
const { REASON_LABELS, createRoverHelpMonitor } = require('./monitor'); const { REASON_LABELS, createRoverHelpMonitor } = require('./monitor');
const { createHelpHornNotifier } = require('./hornNotifier'); const { createHelpHornNotifier } = require('./hornNotifier');
const logger = require('../../globals/logger').child('roverHelpService');
const HELP_ALERT_COLOR = '#ef4444'; const HELP_ALERT_COLOR = '#ef4444';
const hornNotifier = createHelpHornNotifier({ const hornNotifier = createHelpHornNotifier({
getRover: (roverId) => roverManager.rovers.get(String(roverId)), getRover: (roverId) => roverManager.rovers.get(String(roverId)),
// commandService imports roverManager, so resolving it only when a chirp is issueCommand,
// actually issued avoids turning server startup order into a circular module logger,
// dependency while retaining the established command transport.
issueCommand: (roverId, payload) => require('../commandService').issueCommand(roverId, payload),
logger: require('../../globals/logger').child('roverHelpService'),
}); });
const monitor = createRoverHelpMonitor({ const monitor = createRoverHelpMonitor({
@@ -42,6 +41,11 @@ const monitor = createRoverHelpMonitor({
}); });
} else if (wasNeedingHelp && !needsHelp) { } else if (wasNeedingHelp && !needsHelp) {
hornNotifier.stop(roverId); hornNotifier.stop(roverId);
try {
issueCommand(roverId, { type: 'song', song: { notes: [{ note: 72, duration: 8 }, { note: 79, duration: 16 }] } });
} catch (err) {
logger.warn('Failed to play HELP-cleared confirmation', { roverId, error: err.message });
}
publishEvent({ publishEvent({
source: 'roverHelpService', source: 'roverHelpService',
type: 'rover.helpCleared', type: 'rover.helpCleared',
+19 -5
View File
@@ -187,6 +187,7 @@ function buildSession(socket) {
socketId: socket?.id || null, socketId: socket?.id || null,
role: getRole(socket), role: getRole(socket),
operatingMode: getOperatingMode(socket), operatingMode: getOperatingMode(socket),
canLeaveRover: roverManager.canLeaveCurrentRover(socket).ok,
mode: getMode(), mode: getMode(),
isLocalNetwork: isLocalNetwork(getSocketIp(socket)), isLocalNetwork: isLocalNetwork(getSocketIp(socket)),
bandwidthSavings: buildBandwidthSavingsSessionState(socket, controllableUserCount), bandwidthSavings: buildBandwidthSavingsSessionState(socket, controllableUserCount),
@@ -263,10 +264,14 @@ function buildSession(socket) {
}; };
} }
// Cache only the published decision so sensor frames send updates on transitions.
const leavePermissionBySocket = new WeakMap();
function syncSocket(socket) { function syncSocket(socket) {
if (!socket) return; if (!socket) return;
const payload = buildSession(socket); const payload = buildSession(socket);
logger.info('Syncing session', socket.id, payload.role, payload.assignment); logger.info('Syncing session', socket.id, payload.role, payload.assignment);
leavePermissionBySocket.set(socket, payload.canLeaveRover);
socket.emit('session:sync', payload); socket.emit('session:sync', payload);
} }
@@ -287,6 +292,15 @@ io.on('connection', (socket) => {
syncSocket(socket); syncSocket(socket);
}); });
managerEvents.on('sensor', ({ roverId }) => {
io.sockets.sockets.forEach((socket) => {
const decision = roverManager.canLeaveCurrentRover(socket);
if (decision.currentId !== roverId) return;
if (leavePermissionBySocket.get(socket) === decision.ok) return;
syncSocket(socket);
});
});
operatingModeEvents.on('change', () => syncAll()); operatingModeEvents.on('change', () => syncAll());
roleEvents.on('change', ({ socket }) => { roleEvents.on('change', ({ socket }) => {
@@ -365,13 +379,13 @@ privateRoverAccessRequestEvents.on('change', (event = {}) => {
syncAll(); syncAll();
}); });
managerEvents.on('driver', ({ socketId }) => { // Update the changed driver and anyone whose departure permission depends on them.
if (!socketId) return; managerEvents.on('driver', ({ socketId, roverId }) => {
const socket = io.sockets.sockets.get(socketId); io.sockets.sockets.forEach((socket) => {
if (socket) { if (socket.id === socketId || roverManager.isDriver(roverId, socket)) {
logger.info('Driver assignment change; syncing session', socketId);
syncSocket(socket); syncSocket(socket);
} }
});
}); });
turnEvents.on('activeDriver', () => { turnEvents.on('activeDriver', () => {
@@ -59,20 +59,6 @@ function BarcodeScanToast({ payload }) {
); );
} }
function UndockedExitWarningToast() {
return (
<div
className="w-[min(32rem,80vw)] rounded-md bg-amber-950 px-4 py-3 text-left text-amber-50"
role="alert"
>
<p className="text-xl font-bold leading-tight text-amber-100">Please dock your rover</p>
<p className="mt-1 text-base font-medium leading-snug text-amber-50/90">
Your rover is still undocked. Please dock it before leaving the page.
</p>
</div>
);
}
export default function AlertContent({ alert }) { export default function AlertContent({ alert }) {
if (alert.kind === 'buttonbox-active' && alert.payload) { if (alert.kind === 'buttonbox-active' && alert.payload) {
const payload = alert.payload; const payload = alert.payload;
@@ -112,9 +98,6 @@ export default function AlertContent({ alert }) {
if (alert.kind === 'barcode-scan' && alert.payload) { if (alert.kind === 'barcode-scan' && alert.payload) {
return <BarcodeScanToast payload={alert.payload} />; return <BarcodeScanToast payload={alert.payload} />;
} }
if (alert.kind === 'undocked-exit-warning') {
return <UndockedExitWarningToast />;
}
const color = typeof alert.color === 'string' ? alert.color.trim() : ''; const color = typeof alert.color === 'string' ? alert.color.trim() : '';
const backgroundColor = /^#?[0-9a-f]{6}$/i.test(color) ? `#${color.replace('#', '')}` : '#2196f3'; const backgroundColor = /^#?[0-9a-f]{6}$/i.test(color) ? `#${color.replace('#', '')}` : '#2196f3';
@@ -0,0 +1,93 @@
import { useEffect, useState } from 'react';
import { createPortal, flushSync } from 'react-dom';
import { useBlocker } from 'react-router-dom';
import { useSessionSelector } from '../../context/SessionContext.jsx';
export default function PageExitGuard() {
const shouldBlock = useSessionSelector((state) => state.session?.canLeaveRover === false);
const [warning, setWarning] = useState({ blocked: shouldBlock, visible: false });
// Clear an old exit attempt when server permission changes, so undocking
// again does not resurrect a warning from the previous trip.
if (warning.blocked !== shouldBlock) {
setWarning({ blocked: shouldBlock, visible: false });
}
const blocker = useBlocker(({ currentLocation, nextLocation }) => shouldBlock && (
currentLocation.pathname !== nextLocation.pathname || currentLocation.search !== nextLocation.search
));
useEffect(() => {
if (!shouldBlock) return undefined;
function handleBeforeUnload(event) {
// Commit before the native dialog pauses JavaScript. The browser still
// decides whether it repaints the document before displaying its dialog.
flushSync(() => setWarning({ blocked: true, visible: true }));
event.preventDefault();
event.returnValue = true;
}
function blockNavigation(event) {
event.preventDefault();
event.stopPropagation();
setWarning({ blocked: true, visible: true });
}
function handleLinkClick(event) {
if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
const link = event.target instanceof Element ? event.target.closest('a[href]') : null;
if (!link || link.hasAttribute('download')) return;
const target = (link.getAttribute('target') || document.querySelector('base[target]')?.getAttribute('target') || '_self').toLowerCase();
if (target !== '_self') return;
const destination = new URL(link.href, window.location.href);
if (destination.protocol !== 'http:' && destination.protocol !== 'https:') return;
// Hash links stay in this document and do not abandon the rover.
if (destination.origin === window.location.origin
&& destination.pathname === window.location.pathname
&& destination.search === window.location.search
&& link.getAttribute('href').includes('#')) return;
blockNavigation(event);
}
window.addEventListener('beforeunload', handleBeforeUnload);
document.addEventListener('click', handleLinkClick, true);
window.addEventListener('page:navigate', blockNavigation);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
document.removeEventListener('click', handleLinkClick, true);
window.removeEventListener('page:navigate', blockNavigation);
};
}, [shouldBlock]);
useEffect(() => {
// Docking cancels the attempted navigation; the next attempt can proceed.
if (!shouldBlock && blocker.state === 'blocked') blocker.reset();
}, [shouldBlock, blocker]);
const visible = shouldBlock && (warning.visible || blocker.state === 'blocked');
if (!visible) return null;
function dismiss() {
setWarning({ blocked: shouldBlock, visible: false });
if (blocker.state === 'blocked') blocker.reset();
}
return createPortal(
<div
role="dialog"
aria-modal="true"
aria-labelledby="page-exit-warning"
className="fixed inset-0 z-[2147483647] flex flex-col items-center justify-between gap-4 bg-black p-6 text-center text-white"
onKeyDown={(event) => {
event.stopPropagation();
if (event.key === 'Escape') dismiss();
}}
>
<p id="page-exit-warning" className="text-[clamp(3rem,10vw,10rem)] font-bold leading-tight">
Please dock your rover!
</p>
<button type="button" autoFocus className="button-dark px-8 py-4 text-3xl" onClick={dismiss}>
Okay
</button>
<p aria-hidden="true" className="text-[clamp(3rem,10vw,10rem)] font-bold leading-tight">
Please dock your rover!
</p>
</div>,
document.body,
);
}
+4 -3
View File
@@ -21,6 +21,7 @@ export default function PtzQueueCard() {
const featureEnabled = useSessionSelector((state) => isFeatureEnabled(state, 'ptzCamera')); const featureEnabled = useSessionSelector((state) => isFeatureEnabled(state, 'ptzCamera'));
const ptz = useSessionSelector((state) => state.session?.ptzCamera || null); const ptz = useSessionSelector((state) => state.session?.ptzCamera || null);
const selfId = useSessionSelector((state) => state.session?.socketId || null); const selfId = useSessionSelector((state) => state.session?.socketId || null);
const canLeaveRover = useSessionSelector((state) => state.session?.canLeaveRover !== false);
const { setOperatingMode } = useSessionActions(); const { setOperatingMode } = useSessionActions();
const navigate = useNavigate(); const navigate = useNavigate();
const now = useSharedClock(1000, Boolean(ptz?.turn?.deadline)); const now = useSharedClock(1000, Boolean(ptz?.turn?.deadline));
@@ -32,7 +33,7 @@ export default function PtzQueueCard() {
if (!featureEnabled) return null; if (!featureEnabled) return null;
const handleRequest = async () => { const handleRequest = async () => {
if (!canUse || pending) return; if (!canUse || !canLeaveRover || pending) return;
if (isParticipant) { if (isParticipant) {
navigate('/ptz'); navigate('/ptz');
return; return;
@@ -76,14 +77,14 @@ export default function PtzQueueCard() {
}} }}
turn={ptz?.turn} turn={ptz?.turn}
selfId={selfId} selfId={selfId}
canClick={canUse && !pending} canClick={canUse && canLeaveRover && !pending}
pending={pending} pending={pending}
buttonLabel={actionLabel} buttonLabel={actionLabel}
batteryLabel={ptz?.turn?.ownsControl ? 'LIVE' : ptz?.turn?.turnsAhead ? `#${ptz.turn.turnsAhead}` : '--'} batteryLabel={ptz?.turn?.ownsControl ? 'LIVE' : ptz?.turn?.turnsAhead ? `#${ptz.turn.turnsAhead}` : '--'}
batteryClassName={ptz?.turn?.ownsControl ? 'text-emerald-300' : ptz?.turn?.turnsAhead ? 'text-sky-300' : 'text-slate-400'} batteryClassName={ptz?.turn?.ownsControl ? 'text-emerald-300' : ptz?.turn?.turnsAhead ? 'text-sky-300' : 'text-slate-400'}
timerLabel={timerLabel} timerLabel={timerLabel}
onRequest={handleRequest} onRequest={handleRequest}
showAction={canUse} showAction={canUse && canLeaveRover}
/> />
</ul> </ul>
{isParticipant ? ( {isParticipant ? (
@@ -101,6 +101,7 @@ export default function RoverQueuesPanel({
fillHeight = false, fillHeight = false,
}) { }) {
const role = useSessionSelector((state) => state.session?.role || null); const role = useSessionSelector((state) => state.session?.role || null);
const canLeaveRover = useSessionSelector((state) => state.session?.canLeaveRover !== false);
const localRoster = useSessionSelector((state) => state.session?.roster ?? []); const localRoster = useSessionSelector((state) => state.session?.roster ?? []);
const interInstanceEnabled = useSessionSelector((state) => isFeatureEnabled(state, 'interInstance')); const interInstanceEnabled = useSessionSelector((state) => isFeatureEnabled(state, 'interInstance'));
const { value: pageSettings } = useSettingsNamespace('page', { interInstanceTransferSettings: true }); const { value: pageSettings } = useSettingsNamespace('page', { interInstanceTransferSettings: true });
@@ -122,8 +123,8 @@ export default function RoverQueuesPanel({
const roster = Array.isArray(rosterOverride) ? rosterOverride : localRoster; const roster = Array.isArray(rosterOverride) ? rosterOverride : localRoster;
const canRequest = useMemo( const canRequest = useMemo(
() => (externalMode ? !externalBlocked : role && role !== 'spectator'), () => canLeaveRover && (externalMode ? !externalBlocked : role && role !== 'spectator'),
[externalBlocked, externalMode, role], [canLeaveRover, externalBlocked, externalMode, role],
); );
const adminCapable = useMemo( const adminCapable = useMemo(
() => role === 'admin' || role === 'lockdown', () => role === 'admin' || role === 'lockdown',
@@ -142,7 +143,7 @@ export default function RoverQueuesPanel({
async function handleRequest(targetRoverId) { async function handleRequest(targetRoverId) {
if (!targetRoverId) return; if (!targetRoverId) return;
if (externalBlocked) return; if (!canRequest) return;
if (externalMode) { if (externalMode) {
/* /*
External queue cards deliberately reuse the local row layout, but their External queue cards deliberately reuse the local row layout, but their
@@ -252,7 +253,7 @@ export default function RoverQueuesPanel({
? lockLabel ? lockLabel
: externalMode : externalMode
? 'Open' ? 'Open'
: 'request'; : 'Switch';
const canClickRow = canRequest && !lockedBlocked && !pending[roverId]; const canClickRow = canRequest && !lockedBlocked && !pending[roverId];
return ( return (
<QueueTargetRow <QueueTargetRow
@@ -1,66 +0,0 @@
// Undocked Page Exit Guard
// Purpose: Asks the browser to confirm document-level navigation while the current driver's rover is undocked.
// Scope: Owns the native beforeunload lifecycle and queues the matching AlertFeed explanation when leaving is attempted.
import { useEffect } from 'react';
import { useControlSelector } from '../../controls/index.js';
import { useSessionActions } from '../../context/SessionContext.jsx';
import { useTelemetrySelector } from '../../context/TelemetryContext.jsx';
const UNDOCKED_EXIT_ALERT_LIFETIME_MS = 15 * 1000;
function selectHomeBaseState(frame) {
const homeBase = frame?.sensors?.chargingSources?.homeBase;
/*
Missing telemetry must remain distinct from a real "not on the home base"
reading. Treating the initial empty frame as undocked would enable the exit
warning before the browser has received enough information to justify it.
*/
return typeof homeBase === 'boolean' ? homeBase : null;
}
export default function UndockedPageExitGuard() {
const roverId = useControlSelector((control) => control.state.roverId);
const homeBaseState = useTelemetrySelector(roverId, selectHomeBaseState);
const { pushAlert } = useSessionActions();
const shouldConfirmExit = Boolean(roverId) && homeBaseState === false;
useEffect(() => {
if (!shouldConfirmExit) return undefined;
function handleBeforeUnload(event) {
/*
Browsers intentionally own the wording and presentation of this dialog.
preventDefault is the modern signal, while assigning returnValue keeps
the confirmation working in browsers that still require the legacy part
of the beforeunload contract.
*/
event.preventDefault();
event.returnValue = true;
/*
If the driver cancels the browser-owned confirmation, React remains
mounted and AlertFeed presents the actionable reason for the warning.
A stable id refreshes this one warning lane on another exit attempt
instead of stacking duplicate cards over the driving interface.
*/
pushAlert({
id: 'undocked-page-exit-warning',
kind: 'undocked-exit-warning',
lifetimeMs: UNDOCKED_EXIT_ALERT_LIFETIME_MS,
});
}
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
/*
Removing the listener as soon as the rover docks or the assignment ends
prevents ordinary spectators and completed drivers from seeing a stale
leave-page confirmation.
*/
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, [pushAlert, shouldConfirmExit]);
return null;
}
-2
View File
@@ -28,7 +28,6 @@ import useLayoutMode from '../hooks/useLayoutMode.js';
import { DriverHelpProvider } from '../layouts/driver/DriverHelpContext.jsx'; import { DriverHelpProvider } from '../layouts/driver/DriverHelpContext.jsx';
import { LayoutProvider } from '../layouts/LayoutContext.jsx'; import { LayoutProvider } from '../layouts/LayoutContext.jsx';
import DriverLayoutRoot from '../layouts/driver/DriverLayoutRoot.jsx'; import DriverLayoutRoot from '../layouts/driver/DriverLayoutRoot.jsx';
import UndockedPageExitGuard from '../components/UndockedPageExitGuard/index.jsx';
/* Driver-page compositions live under layouts/driver. App retains only global providers, overlays, and route-level state. */ /* Driver-page compositions live under layouts/driver. App retains only global providers, overlays, and route-level state. */
function DriverPageRoot({ oldDesktop = false }) { function DriverPageRoot({ oldDesktop = false }) {
@@ -92,7 +91,6 @@ function DriverPageContent({ layout, oldDesktop }) {
return ( return (
<ControlSystemProvider> <ControlSystemProvider>
<RoomAudioPlayer /> <RoomAudioPlayer />
<UndockedPageExitGuard />
<KeyboardInputManager /> <KeyboardInputManager />
<GamepadInputManager /> <GamepadInputManager />
<main className={`relative flex w-full flex-col ${themeGapClass} text-base`}> <main className={`relative flex w-full flex-col ${themeGapClass} text-base`}>
+3
View File
@@ -40,5 +40,8 @@ export function buildExternalRoverUrl(instance, roverId, { includeSettings = fal
export function openExternalRover(instance, roverId, { includeSettings = true } = {}) { export function openExternalRover(instance, roverId, { includeSettings = true } = {}) {
const targetUrl = buildExternalRoverUrl(instance, roverId, { includeSettings }); const targetUrl = buildExternalRoverUrl(instance, roverId, { includeSettings });
if (!targetUrl) return; if (!targetUrl) return;
// These queue actions are buttons, so let the page guard veto navigation
// before beforeunload would pause painting behind the native browser dialog.
if (!window.dispatchEvent(new Event('page:navigate', { cancelable: true }))) return;
window.location.href = targetUrl; window.location.href = targetUrl;
} }
+27 -17
View File
@@ -2,7 +2,7 @@
// Purpose: Boots the React application and mounts global providers/router roots. Scope: Defines top-level route wiring and root render lifecycle for the browser app. // Purpose: Boots the React application and mounts global providers/router roots. Scope: Defines top-level route wiring and root render lifecycle for the browser app.
import { lazy, StrictMode, Suspense } from 'react' import { lazy, StrictMode, Suspense } from 'react'
import { createRoot } from 'react-dom/client' import { createRoot } from 'react-dom/client'
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom' import { createBrowserRouter, Route, RouterProvider, Routes } from 'react-router-dom'
import './index.css' import './index.css'
// Theme artwork is a separate style concern from global component utilities. Loading its dedicated // Theme artwork is a separate style concern from global component utilities. Loading its dedicated
// entrypoint here keeps every route consistent without returning theme definitions to index.css. // entrypoint here keeps every route consistent without returning theme definitions to index.css.
@@ -22,6 +22,7 @@ import AnalyticsReporter from './analytics/AnalyticsReporter.jsx'
import PtzAppRoot from './ptz/PtzAppRoot.jsx' import PtzAppRoot from './ptz/PtzAppRoot.jsx'
import MicApp from './mic/MicApp.jsx' import MicApp from './mic/MicApp.jsx'
import OperatingModeRouteSync from './components/OperatingModeRouteSync/index.jsx' import OperatingModeRouteSync from './components/OperatingModeRouteSync/index.jsx'
import PageExitGuard from './components/PageExitGuard/index.jsx'
import InitialSessionOverlay from './components/InitialSessionOverlay/index.jsx' import InitialSessionOverlay from './components/InitialSessionOverlay/index.jsx'
import AppErrorBoundary from './components/AppErrorBoundary.jsx' import AppErrorBoundary from './components/AppErrorBoundary.jsx'
@@ -41,23 +42,14 @@ function lazyRoute(element, label) {
) )
} }
createRoot(document.getElementById('root')).render( // A data router provides one blocker for links, programmatic navigation, and history.
<AppErrorBoundary> const router = createBrowserRouter([{
<StrictMode> path: '*',
<SocketProvider> element: (
<SessionProvider> <>
{/* Every route depends on the first authoritative session snapshot.
Mounting this opaque layer at the shared provider boundary prevents
incomplete route-specific placeholders from flashing while still
allowing every application tree to initialize underneath it. */}
<InitialSessionOverlay />
<TelemetryProvider>
<SettingsProvider>
<ChatProvider>
<DeterrenceChaos />
<BrowserRouter>
<AnalyticsReporter /> <AnalyticsReporter />
<OperatingModeRouteSync /> <OperatingModeRouteSync />
<PageExitGuard />
<Routes> <Routes>
<Route path="/" element={<DriverPageRoot />} /> <Route path="/" element={<DriverPageRoot />} />
{/* The retired desktop composition remains available for direct comparison {/* The retired desktop composition remains available for direct comparison
@@ -82,7 +74,25 @@ createRoot(document.getElementById('root')).render(
element={lazyRoute(<FleetReportsApp />, 'fleet reports')} element={lazyRoute(<FleetReportsApp />, 'fleet reports')}
/> />
</Routes> </Routes>
</BrowserRouter> </>
),
}])
createRoot(document.getElementById('root')).render(
<AppErrorBoundary>
<StrictMode>
<SocketProvider>
<SessionProvider>
{/* Every route depends on the first authoritative session snapshot.
Mounting this opaque layer at the shared provider boundary prevents
incomplete route-specific placeholders from flashing while still
allowing every application tree to initialize underneath it. */}
<InitialSessionOverlay />
<TelemetryProvider>
<SettingsProvider>
<ChatProvider>
<DeterrenceChaos />
<RouterProvider router={router} />
</ChatProvider> </ChatProvider>
</SettingsProvider> </SettingsProvider>
</TelemetryProvider> </TelemetryProvider>