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 MutableRefObject,
type ReactNode,
} from "react";
import { usePathname } from "next/navigation";
import {
ConnectionState,
DisconnectReason,
RemoteTrack,
Room,
RoomEvent,
Track,
} from "livekit-client";
import { useIdentity } from "@/lib/identity";
import { BRIDGE_IDENTITY } from "@/lib/types";
import type { OfflineReason } from "@/lib/status";
type ConnStatus = "idle" | "connecting" | "connected" | "unconfigured" | "dormant";
type RoomContextValue = {
status: ConnStatus;
/** subscribed camera tracks keyed by LiveKit track name */
videoTracks: Record<string, RemoteTrack>;
/** Date.now() when this browser last reached Connected, or null while not connected — lets the
* status layer age out a bridge that's present but never broadcasts after we join. */
connectedAt: number | null;
/** number of remote participants in the room (cameras + bridge + other players) */
spectators: number;
/** identities of remote participants (e.g. to check the bridge "pi-control" is present) */
participants: string[];
/** the live Room, exposed so the control provider can publish/RPC/listen */
room: Room | null;
/** which flavor of "unconfigured" the token route reported (null unless status is unconfigured) */
offlineVariant: OfflineReason | null;
/** set true by the teleop layer while the user is queued/driving — vetoes idle disconnects so a
* backgrounded-but-queued tab never forfeits its spot */
holdRef: MutableRefObject<boolean>;
};
const Ctx = createContext<RoomContextValue | null>(null);
export function useRoom(): RoomContextValue {
const v = useContext(Ctx);
if (!v) throw new Error("useRoom must be used within <RoomProvider>");
return v;
}
// ---- idle economics: LiveKit Cloud bills per participant-minute, so don't hold a connection that
// can't be watching anything. Go dormant (hang up, cheap to wake) when the rig has been gone a while
// (no bridge AND no published cameras — nothing robot-side in the room) or the tab has been hidden a
// while. Wake on rig presence (CDN-cached poll) or tab visibility respectively. ----
const RIG_DOWN_IDLE_MS = 3 * 60_000; // connected but nothing robot-side this long → dormant
const HIDDEN_IDLE_MS = 5 * 60_000; // tab continuously hidden this long → dormant
const IDLE_CHECK_MS = 30_000;
// While rig-down dormant, ask /api/livekit/presence whether the rig is back. The route is CDN-cached
// (s-maxage=30), so any number of dormant tabs cost ~2 function invocations a minute in total.
const DORMANT_PRESENCE_POLL_MS = 60_000;
type DormantReason = "rig-down" | "hidden";
export function RoomProvider({ children }: { children: ReactNode }) {
const { identity } = useIdentity();
const [status, setStatus] = useState<ConnStatus>("idle");
const [connectedAt, setConnectedAt] = useState<number | null>(null);
const [videoTracks, setVideoTracks] = useState<Record<string, RemoteTrack>>({});
const [spectators, setSpectators] = useState(0);
const [participants, setParticipants] = useState<string[]>([]);
const [room, setRoom] = useState<Room | null>(null);
const [offlineVariant, setOfflineVariant] = useState<OfflineReason | null>(null);
const holdRef = useRef(false);
// The /broadcast pages run inside LiveKit Egress's headless Chrome — that renderer must hold its
// connection for the life of the stream, so it is exempt from all idle disconnects.
const pathname = usePathname();
const egressSurface = pathname?.startsWith("/broadcast") ?? false;
useEffect(() => {
if (!identity) return;
let cancelled = false;
let retryTimer: ReturnType<typeof setTimeout> | undefined;
let pollTimer: ReturnType<typeof setTimeout> | undefined;
// Backoff capped at 60s: every retry mints a token (a Vercel function invocation), and LiveKit
// already rides out transient blips internally — a dead server shouldn't be hammered at 15s.
let retryDelay = 1000;
let dormantReason: DormantReason | null = null;
let rigDownSince: number | null = null;
let hiddenSince: number | null = document.hidden ? Date.now() : null;
// adaptiveStream OFF: the director keeps all feeds decoding via hidden mux elements so promotion
// is instant; adaptive stream would throttle the active feed (its only sink is the offscreen mux).
// dynacast OFF: pull full published resolution.
const r = new Room({ adaptiveStream: false, dynacast: false });
const syncTracks = () => {
const next: Record<string, RemoteTrack> = {};
r.remoteParticipants.forEach((p) => {
p.trackPublications.forEach((pub) => {
if (pub.track && pub.kind === Track.Kind.Video && pub.trackName) {
next[pub.trackName] = pub.track as RemoteTrack;
}
});
});
// keep object identity stable when the track set is unchanged
setVideoTracks((prev) => {
const keys = Object.keys(next);
const pkeys = Object.keys(prev);
if (keys.length === pkeys.length && keys.every((k) => prev[k] === next[k])) {
return prev;
}
return next;
});
setSpectators(r.remoteParticipants.size);
setParticipants(Array.from(r.remoteParticipants.values(), (p) => p.identity));
};
/** anything robot-side in the room? (the bridge participant, or any published camera track) */
const rigUp = (): boolean => {
let up = false;
r.remoteParticipants.forEach((p) => {
if (p.identity === BRIDGE_IDENTITY) up = true;
p.trackPublications.forEach((pub) => {
if (pub.kind === Track.Kind.Video) up = true;
});
});
return up;
};
function goDormant(reason: DormantReason) {
if (cancelled || dormantReason) return;
dormantReason = reason;
rigDownSince = null;
setStatus("dormant");
r.disconnect(); // RoomEvent.Disconnected sees dormantReason and skips the auto-retry
if (reason === "rig-down") schedulePresencePoll();
}
function wake() {
if (cancelled || dormantReason == null) return;
dormantReason = null;
rigDownSince = null;
if (pollTimer) clearTimeout(pollTimer);
retryDelay = 1000;
connect();
}
function schedulePresencePoll() {
if (pollTimer) clearTimeout(pollTimer);
pollTimer = setTimeout(() => void pollPresence(), DORMANT_PRESENCE_POLL_MS);
}
async function pollPresence() {
if (cancelled || dormantReason !== "rig-down") return;
// a hidden tab has no reason to watch for the rig — visibilitychange re-polls on return
if (document.hidden) {
schedulePresencePoll();
return;
}
try {
const res = await fetch("/api/livekit/presence");
if (res.status === 503) {
// the kill switch was flipped while we were dormant — settle into OFF AIR and stop polling
const body = (await res.json().catch(() => null)) as { reason?: string } | null;
dormantReason = null;
setOfflineVariant(body?.reason === "offair" ? "offair" : "demo");
setStatus("unconfigured");
return;
}
if (res.ok) {
const { rigOnline } = (await res.json()) as { rigOnline?: boolean };
if (rigOnline) return wake();
}
} catch {
/* network blip — just try again next tick */
}
schedulePresencePoll();
}
// periodic idle check: cheap, and only ever disconnects (never blocks reconnects)
const idleTimer = egressSurface
? undefined
: setInterval(() => {
if (cancelled || dormantReason || holdRef.current) return;
if (r.state !== ConnectionState.Connected) return;
const now = Date.now();
if (hiddenSince != null && now - hiddenSince >= HIDDEN_IDLE_MS) return goDormant("hidden");
if (rigUp()) {
rigDownSince = null;
} else if (rigDownSince == null) {
rigDownSince = now;
} else if (now - rigDownSince >= RIG_DOWN_IDLE_MS) {
return goDormant("rig-down");
}
}, IDLE_CHECK_MS);
const onVisibility = () => {
if (document.hidden) {
hiddenSince = Date.now();
return;
}
hiddenSince = null;
if (dormantReason === "hidden") wake();
else if (dormantReason === "rig-down") void pollPresence(); // check immediately on return
};
if (!egressSurface) document.addEventListener("visibilitychange", onVisibility);
r.on(RoomEvent.TrackSubscribed, syncTracks)
.on(RoomEvent.TrackUnsubscribed, syncTracks)
.on(RoomEvent.ParticipantConnected, syncTracks)
.on(RoomEvent.ParticipantDisconnected, syncTracks)
.on(RoomEvent.ConnectionStateChanged, (s) => {
if (cancelled) return;
if (s === ConnectionState.Connected) {
setStatus("connected");
setConnectedAt(Date.now());
retryDelay = 1000; // healthy connection resets backoff
} else if (
s === ConnectionState.Connecting ||
s === ConnectionState.Reconnecting ||
s === ConnectionState.SignalReconnecting
) {
setStatus("connecting");
}
// Terminal Disconnected is handled by RoomEvent.Disconnected below (it carries the reason).
})
.on(RoomEvent.Disconnected, (reason) => {
if (cancelled) return;
setVideoTracks({});
setSpectators(0);
setParticipants([]);
setRoom(null);
setConnectedAt(null);
// A deliberate idle hang-up, not a fault — stay dormant; wake() reconnects when warranted.
if (dormantReason) return;
// Don't fight ourselves: a duplicate-identity kick means a newer connection (e.g. StrictMode
// remount, Fast Refresh) already took our slot — reconnecting would kick that. sessionStorage
// makes real user tabs distinct, so this is dev-only in practice; treat as reconnecting and let
// the newer mount own the socket.
if (reason === DisconnectReason.DUPLICATE_IDENTITY) {
setStatus("connecting");
return;
}
// LiveKit already retries transient blips internally (Reconnecting state). Reaching a terminal
// Disconnected means those were exhausted or the server closed the socket — recover instead of
// stranding the UI until a manual refresh.
setStatus("connecting");
retryTimer = setTimeout(connect, retryDelay);
retryDelay = Math.min(retryDelay * 2, 60_000);
});
async function connect() {
if (cancelled) return;
try {
setStatus("connecting");
const res = await fetch("/api/livekit/token?identity=" + encodeURIComponent(identity));
if (res.status === 503) {
if (cancelled) return;
const body = (await res.json().catch(() => null)) as { reason?: string } | null;
setOfflineVariant(body?.reason === "offair" ? "offair" : "demo");
setStatus("unconfigured");
return;
}
if (!res.ok) throw new Error(`token ${res.status}`);
const { url, token } = (await res.json()) as { url: string; token: string };
if (cancelled) return;
await r.connect(url, token);
if (cancelled) return;
setOfflineVariant(null);
setRoom(r);
syncTracks();
} catch (err) {
if (cancelled) return;
console.error("[livekit] connect failed, retrying in", retryDelay, "ms", err);
setStatus("connecting");
retryTimer = setTimeout(connect, retryDelay);
retryDelay = Math.min(retryDelay * 2, 60_000);
}
}
connect();
return () => {
cancelled = true;
if (retryTimer) clearTimeout(retryTimer);
if (pollTimer) clearTimeout(pollTimer);
if (idleTimer) clearInterval(idleTimer);
if (!egressSurface) document.removeEventListener("visibilitychange", onVisibility);
setRoom(null);
r.disconnect();
};
}, [identity, egressSurface]);
const value = useMemo<RoomContextValue>(
() => ({ status, connectedAt, videoTracks, spectators, participants, room, offlineVariant, holdRef }),
[status, connectedAt, videoTracks, spectators, participants, room, offlineVariant],
);
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}