Loading files
05241c15dThis file is pinned to the selected release. Download the original to open it in your design tool.
"use client";
import {
createContext,
useContext,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import type { RemoteTrack } from "livekit-client";
import { useRoom } from "@/components/livekit/RoomProvider";
import { useTeleop } from "@/components/control/TeleopProvider";
import { CHANNELS } from "@/lib/config";
import { BRIDGE_IDENTITY } from "@/lib/types";
import {
BRIDGE_STALE_MS,
REQUIRED_CAMS,
STATUS_META,
deriveRawStatus,
isDisabled as isDisabledFor,
type OfflineReason,
type StatusAction,
type StatusMeta,
type SystemStatus,
} from "@/lib/status";
import { statusMockOverride, useMockKey } from "@/lib/mockStates";
export type SystemStatusValue = {
status: SystemStatus;
meta: StatusMeta;
/** marquee word (specialized for OFFLINE variants) */
label: string;
/** one-line caption (specialized per OFFLINE variant + driver/queued role) */
caption: string;
tone: StatusMeta["tone"];
offlineReason?: OfflineReason;
/** true only when fully LIVE */
drivable: boolean;
/** every non-LIVE status pauses the queue */
queuePaused: boolean;
isDisabled: (a: StatusAction) => boolean;
/** read-only token (can't publish data) — orthogonal to health, never a severity rank */
spectating: boolean;
// ---- diagnostics for the admin readout ----
operationalCams: number;
totalCams: number;
frozenCams: string[];
anyArmOnline: boolean;
bridgePresent: boolean;
/** whole seconds since the last bridge broadcast (null if never / not connected) */
bridgeSilentS: number | null;
/** human-readable reasons the system isn't LIVE (for admin) */
reasons: string[];
};
const Ctx = createContext<SystemStatusValue | null>(null);
export function useSystemStatus(): SystemStatusValue {
const v = useContext(Ctx);
if (!v) throw new Error("useSystemStatus must be used within <SystemStatusProvider>");
return v;
}
const TICK_MS = 500; // re-evaluate ages + pending debounce transitions at 2 Hz
const FREEZE_POLL_MS = 1000;
const FREEZE_FLAT_TICKS = 2; // ~2s of no new decoded frames ⇒ treat a subscribed feed as frozen
function setsEqual(a: Set<string>, b: Set<string>): boolean {
if (a.size !== b.size) return false;
for (const x of a) if (!b.has(x)) return false;
return true;
}
/** Pull decoded-frame count out of a track's WebRTC stats, or null if unavailable. */
async function framesDecoded(track: RemoteTrack): Promise<number | null> {
try {
const report = await track.getRTCStatsReport?.();
if (!report) return null;
let frames: number | null = null;
report.forEach((s) => {
if (s.type === "inbound-rtp" && typeof s.framesDecoded === "number") frames = s.framesDecoded;
});
return frames;
} catch {
return null; // stats blocked/unsupported — assume the feed is flowing rather than false-alarm
}
}
export function SystemStatusProvider({ children }: { children: ReactNode }) {
const { status, videoTracks, participants, connectedAt, offlineVariant } = useRoom();
const { session, lastSessionAt, canDrive, phase, controlling } = useTeleop();
// 2 Hz clock so ages + pending transitions re-evaluate even when no signal changes
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const id = setInterval(() => setNow(Date.now()), TICK_MS);
return () => clearInterval(id);
}, []);
// ---- freeze watchdog: a subscribed-but-frozen feed reads LIVE otherwise, and driving blind
// against a static image is worse than a visible "low signal". Frame-flow, not track presence. ----
const frameHistRef = useRef<Record<string, { frames: number; flat: number }>>({});
const [frozen, setFrozen] = useState<Set<string>>(new Set());
useEffect(() => {
let alive = true;
async function poll() {
if (!alive) return;
// A backgrounded tab stops decoding video, which looks identical to a frozen feed — don't
// accuse cameras of freezing while hidden (the deadman already halts driving when unfocused).
if (typeof document !== "undefined" && document.hidden) {
frameHistRef.current = {};
setFrozen((prev) => (prev.size ? new Set() : prev));
return;
}
const next = new Set<string>();
await Promise.all(
CHANNELS.map(async (c) => {
const track = videoTracks[c.trackName];
if (!track) {
delete frameHistRef.current[c.trackName];
return;
}
const frames = await framesDecoded(track);
if (frames == null) {
delete frameHistRef.current[c.trackName]; // can't measure ⇒ assume flowing
return;
}
const prev = frameHistRef.current[c.trackName];
if (prev && frames <= prev.frames) {
const flat = prev.flat + 1;
frameHistRef.current[c.trackName] = { frames, flat };
if (flat >= FREEZE_FLAT_TICKS) next.add(c.trackName);
} else {
frameHistRef.current[c.trackName] = { frames, flat: 0 };
}
}),
);
if (alive) setFrozen((prev) => (setsEqual(prev, next) ? prev : next));
}
void poll();
const id = setInterval(poll, FREEZE_POLL_MS);
return () => {
alive = false;
clearInterval(id);
};
}, [videoTracks]);
// ---- fuse the three domains into raw inputs ----
const bridgePresent = participants.includes(BRIDGE_IDENTITY);
const operationalCams = CHANNELS.reduce(
(n, c) => n + (videoTracks[c.trackName] && !frozen.has(c.trackName) ? 1 : 0),
0,
);
const arms = session?.arms ?? {};
const armIds = Object.keys(arms);
const armsKnown = armIds.length > 0;
// per the owner: ≥1 arm online ⇒ arms are online. A missing `online` (pre-probe bridge) is
// treated as online so arms are never falsely reported offline before the heartbeat ships.
const anyArmOnline = armsKnown && armIds.some((id) => arms[id]?.online !== false);
const paused = Boolean(session?.robots_paused || session?.cameras_paused);
const sessionAgeMs: number | null =
status !== "connected"
? null
: lastSessionAt != null
? now - lastSessionAt
: connectedAt != null
? now - connectedAt
: 0;
const { status: rawStatus, offlineReason: rawOfflineReason } = deriveRawStatus({
conn: status,
offlineVariant: offlineVariant ?? undefined,
bridgePresent,
sessionAgeMs,
operationalCams,
armsKnown,
anyArmOnline,
paused,
});
// ---- asymmetric debounce: only commit to a new state after its raw signal has held for
// enterDelayMs, so a re-subscribe flap or a sub-second socket blip can't strobe the marquee. ----
const [committed, setCommitted] = useState<{ status: SystemStatus; offlineReason?: OfflineReason }>({
status: "RECONNECTING",
});
const candidateRef = useRef<{ status: SystemStatus; since: number }>({ status: "RECONNECTING", since: 0 });
useEffect(() => {
if (rawStatus === committed.status) return;
const t = Date.now();
if (candidateRef.current.status !== rawStatus) candidateRef.current = { status: rawStatus, since: t };
if (t - candidateRef.current.since >= STATUS_META[rawStatus].enterDelayMs) {
setCommitted({ status: rawStatus, offlineReason: rawOfflineReason });
}
}, [rawStatus, rawOfflineReason, committed.status, now]);
// ---- copy: specialize the OFFLINE variants + the driver/queued role in the paused band ----
const meta = STATUS_META[committed.status];
let label = meta.label;
let caption = meta.caption;
if (committed.status === "OFFLINE" && committed.offlineReason === "offair") {
label = "OFF AIR";
caption = "the arcade is asleep — back soon";
} else if (committed.status === "OFFLINE" && committed.offlineReason === "demo") {
label = "DEMO MODE";
caption = "set LIVEKIT_* env to go live";
} else if (meta.queuePaused && committed.status !== "RECONNECTING") {
if (controlling) caption = `arm parked & held — ${meta.caption}`;
else if (phase === "queueing") caption = `holding your spot — ${meta.caption}`;
}
const reasons: string[] = [];
if (status === "connected") {
if (!bridgePresent) reasons.push("bridge not in room");
else if (sessionAgeMs != null && sessionAgeMs > BRIDGE_STALE_MS)
reasons.push(`bridge silent ${Math.round(sessionAgeMs / 1000)}s`);
if (paused) reasons.push("admin paused");
if (armsKnown && !anyArmOnline) reasons.push("all arms offline");
if (operationalCams < REQUIRED_CAMS) reasons.push(`${operationalCams}/${CHANNELS.length} feeds up`);
if (frozen.size) reasons.push(`frozen: ${[...frozen].join(", ")}`);
}
const reasonsKey = reasons.join("|");
const frozenKey = [...frozen].sort().join("|");
const bridgeSilentS = sessionAgeMs == null ? null : Math.round(sessionAgeMs / 1000);
// `?mock=<state>` overlays a fixed UX fixture onto the fused status (no-op when the param is absent)
const mockKey = useMockKey();
const value = useMemo<SystemStatusValue>(
() => {
const base: SystemStatusValue = {
status: committed.status,
meta,
label,
caption,
tone: meta.tone,
offlineReason: committed.offlineReason,
drivable: committed.status === "LIVE",
queuePaused: meta.queuePaused,
isDisabled: (a: StatusAction) => isDisabledFor(committed.status, a),
spectating: !canDrive,
operationalCams,
totalCams: CHANNELS.length,
frozenCams: [...frozen],
anyArmOnline,
bridgePresent,
bridgeSilentS,
reasons,
};
const override = statusMockOverride(mockKey);
return override ? { ...base, ...override } : base;
},
// eslint-disable-next-line react-hooks/exhaustive-deps -- reasons/frozen tracked via *Key strings
[
mockKey,
committed.status,
committed.offlineReason,
label,
caption,
meta,
canDrive,
operationalCams,
frozenKey,
anyArmOnline,
bridgePresent,
bridgeSilentS,
reasonsKey,
],
);
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}