@camstack/ui-library 1.2.241 → 1.2.243

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -8026,16 +8026,20 @@ var usePipelineOrchestratorSetAgentInferenceDevices = trpc.pipelineOrchestrator.
8026
8026
  var usePipelineOrchestratorGetNodeInferenceDevices = trpc.pipelineOrchestrator.getNodeInferenceDevices.useQuery;
8027
8027
  /** Generated alias around `trpc.pipelineOrchestrator.resetNodePipelineDefaults.useMutation`. */
8028
8028
  var usePipelineOrchestratorResetNodePipelineDefaults = trpc.pipelineOrchestrator.resetNodePipelineDefaults.useMutation;
8029
- /** Generated alias around `trpc.pipelineOrchestrator.planBestSettings.useQuery`. */
8030
- var usePipelineOrchestratorPlanBestSettings = trpc.pipelineOrchestrator.planBestSettings.useQuery;
8031
- /** Generated alias around `trpc.pipelineOrchestrator.applyBestSettings.useMutation`. */
8032
- var usePipelineOrchestratorApplyBestSettings = trpc.pipelineOrchestrator.applyBestSettings.useMutation;
8029
+ /** Generated alias around `trpc.pipelineOrchestrator.planAutoTune.useQuery`. */
8030
+ var usePipelineOrchestratorPlanAutoTune = trpc.pipelineOrchestrator.planAutoTune.useQuery;
8031
+ /** Generated alias around `trpc.pipelineOrchestrator.applyAutoTune.useMutation`. */
8032
+ var usePipelineOrchestratorApplyAutoTune = trpc.pipelineOrchestrator.applyAutoTune.useMutation;
8033
8033
  /** Generated alias around `trpc.pipelineOrchestrator.setLoadBalancingShares.useMutation`. */
8034
8034
  var usePipelineOrchestratorSetLoadBalancingShares = trpc.pipelineOrchestrator.setLoadBalancingShares.useMutation;
8035
8035
  /** Generated alias around `trpc.pipelineOrchestrator.getPlacementStats.useQuery`. */
8036
8036
  var usePipelineOrchestratorGetPlacementStats = trpc.pipelineOrchestrator.getPlacementStats.useQuery;
8037
8037
  /** Generated alias around `trpc.pipelineOrchestrator.suggestShares.useQuery`. */
8038
8038
  var usePipelineOrchestratorSuggestShares = trpc.pipelineOrchestrator.suggestShares.useQuery;
8039
+ /** Generated alias around `trpc.pipelineOrchestrator.getEffectiveShares.useQuery`. */
8040
+ var usePipelineOrchestratorGetEffectiveShares = trpc.pipelineOrchestrator.getEffectiveShares.useQuery;
8041
+ /** Generated alias around `trpc.pipelineOrchestrator.setShareSource.useMutation`. */
8042
+ var usePipelineOrchestratorSetShareSource = trpc.pipelineOrchestrator.setShareSource.useMutation;
8039
8043
  /** Generated alias around `trpc.pipelineOrchestrator.getCameraSettings.useQuery`. */
8040
8044
  var usePipelineOrchestratorGetCameraSettings = trpc.pipelineOrchestrator.getCameraSettings.useQuery;
8041
8045
  /** Generated alias around `trpc.pipelineOrchestrator.setCameraStepToggle.useMutation`. */
@@ -31631,6 +31635,27 @@ function nextClientSample(prev, cur, ctx) {
31631
31635
  };
31632
31636
  }
31633
31637
  //#endregion
31638
+ //#region src/composites/peer-connection-config.ts
31639
+ /**
31640
+ * The player's `RTCConfiguration`, in one place for every connect path.
31641
+ *
31642
+ * The player never forces `iceTransportPolicy: 'relay'` on its own (werift's
31643
+ * relay forward is unreliable across two real TURN servers, and relay would
31644
+ * defeat the direct LAN/Tailscale path). The policy exists for the WebRTC
31645
+ * diagnostics only, which run the SAME player once with `all` and once with
31646
+ * `relay` to tell a reachable relay path from a dead one. Absent, the key is
31647
+ * not set at all, so a production connect is byte-for-byte what it was.
31648
+ */
31649
+ /** Public STUN kept as a fallback beside whatever the hub's TURN provider returns. */
31650
+ var FALLBACK_STUN_SERVER = { urls: "stun:stun.l.google.com:19302" };
31651
+ function buildPeerConnectionConfig(iceServers, iceTransportPolicy) {
31652
+ const servers = [...iceServers ?? [], FALLBACK_STUN_SERVER];
31653
+ return iceTransportPolicy === void 0 ? { iceServers: servers } : {
31654
+ iceServers: servers,
31655
+ iceTransportPolicy
31656
+ };
31657
+ }
31658
+ //#endregion
31634
31659
  //#region src/composites/stream-debug/webrtc-debug-stats.ts
31635
31660
  /** Beyond this the log is a scroll, not a signal. */
31636
31661
  var RESOLUTION_LOG_MAX = 8;
@@ -32354,7 +32379,7 @@ function mergePlayerHints(autoHints, override, downlinkMbps, coldStart) {
32354
32379
  return coldStart ? stripDownlinkForColdStart(merged) : merged;
32355
32380
  }
32356
32381
  var FIRST_FRAME_TIMEOUT_MS = 8e3;
32357
- function CameraStreamPlayer({ serverUrl, streamKey, label, autoPlay = true, muted: initialMuted = true, showControls = true, showStats = false, onDebugStats, onPlaybackStats, onClientNetworkSample, probeAuthToken, onConnectTiming, className = "", onStateChange, onError, onReconnectAttempt, overlay, createSession, sendAnswer, handleOffer, getIceServers, addIceCandidate, getIceCandidates, closeSession, getSessionState, getSessionDebug, applyDownlinkProbe, reoffer, posterUrl, hintsOverride, onAdaptiveHints, reconnectSignal, onControlChannel, onVideoElement }) {
32382
+ function CameraStreamPlayer({ serverUrl, streamKey, label, autoPlay = true, muted: initialMuted = true, showControls = true, showStats = false, onDebugStats, onPlaybackStats, onClientNetworkSample, probeAuthToken, onConnectTiming, className = "", onStateChange, onError, onReconnectAttempt, overlay, createSession, sendAnswer, handleOffer, getIceServers, addIceCandidate, getIceCandidates, closeSession, getSessionState, getSessionDebug, applyDownlinkProbe, reoffer, posterUrl, hintsOverride, onAdaptiveHints, reconnectSignal, onControlChannel, onVideoElement, iceTransportPolicy, onPeerConnection }) {
32358
32383
  const videoRef = (0, react$1.useRef)(null);
32359
32384
  const containerRef = (0, react$1.useRef)(null);
32360
32385
  const pcRef = (0, react$1.useRef)(null);
@@ -32370,6 +32395,12 @@ function CameraStreamPlayer({ serverUrl, streamKey, label, autoPlay = true, mute
32370
32395
  * consumer, without re-creating the connect callback on every render. */
32371
32396
  const onControlChannelRef = (0, react$1.useRef)(onControlChannel);
32372
32397
  onControlChannelRef.current = onControlChannel;
32398
+ /** Read at connect time through refs so neither diagnostics prop re-creates
32399
+ * the connect callbacks (and so neither forces a reconnect when it changes). */
32400
+ const iceTransportPolicyRef = (0, react$1.useRef)(iceTransportPolicy);
32401
+ iceTransportPolicyRef.current = iceTransportPolicy;
32402
+ const onPeerConnectionRef = (0, react$1.useRef)(onPeerConnection);
32403
+ onPeerConnectionRef.current = onPeerConnection;
32373
32404
  /** Same pattern for the video-element handle: delivered once on mount, null
32374
32405
  * on unmount — the ref keeps the latest consumer without re-running. */
32375
32406
  const onVideoElementRef = (0, react$1.useRef)(onVideoElement);
@@ -32579,7 +32610,8 @@ function CameraStreamPlayer({ serverUrl, streamKey, label, autoPlay = true, mute
32579
32610
  sessionIdsRef.current.delete(sessionId);
32580
32611
  return;
32581
32612
  }
32582
- const pc = new RTCPeerConnection({ iceServers: [...iceServers ?? [], { urls: "stun:stun.l.google.com:19302" }] });
32613
+ const pc = new RTCPeerConnection(buildPeerConnectionConfig(iceServers, iceTransportPolicyRef.current));
32614
+ onPeerConnectionRef.current?.(pc);
32583
32615
  if (!seamless) pcRef.current = pc;
32584
32616
  const combinedStream = new MediaStream();
32585
32617
  if (!withDownlink) probeAfterThisStreamsFirstFrame({
@@ -32780,7 +32812,8 @@ function CameraStreamPlayer({ serverUrl, streamKey, label, autoPlay = true, mute
32780
32812
  const iceServers = await getIceServers?.();
32781
32813
  timing.iceServersMs = ms();
32782
32814
  if (!mountedRef.current || abort.signal.aborted) return;
32783
- const pc = new RTCPeerConnection({ iceServers: [...iceServers ?? [], { urls: "stun:stun.l.google.com:19302" }] });
32815
+ const pc = new RTCPeerConnection(buildPeerConnectionConfig(iceServers, iceTransportPolicyRef.current));
32816
+ onPeerConnectionRef.current?.(pc);
32784
32817
  if (!seamless) pcRef.current = pc;
32785
32818
  const combinedStream = new MediaStream();
32786
32819
  /** This connect's server session — known once `handleOffer` answers,
@@ -32986,7 +33019,8 @@ function CameraStreamPlayer({ serverUrl, streamKey, label, autoPlay = true, mute
32986
33019
  try {
32987
33020
  const iceServers = await getIceServers?.();
32988
33021
  if (!mountedRef.current) return;
32989
- const pc = new RTCPeerConnection({ iceServers: [...iceServers ?? [], { urls: "stun:stun.l.google.com:19302" }] });
33022
+ const pc = new RTCPeerConnection(buildPeerConnectionConfig(iceServers, iceTransportPolicyRef.current));
33023
+ onPeerConnectionRef.current?.(pc);
32990
33024
  const newStream = new MediaStream();
32991
33025
  let swappedIn = false;
32992
33026
  let warmupStarted = false;
@@ -33826,281 +33860,6 @@ async function waitForIceGathering(pc) {
33826
33860
  });
33827
33861
  }
33828
33862
  //#endregion
33829
- //#region src/composites/cap-settings/scene-monitor-copy.ts
33830
- /** The lighting variants an operator is OFFERED. The resolver can also report
33831
- * `night`, `dawn` and `dusk`; those are shown when present but never demanded,
33832
- * because most installs only ever see day and IR. */
33833
- var SCENE_CAPTURE_VARIANTS = ["day", "ir"];
33834
- var VARIANT_LABEL = {
33835
- day: "Daylight",
33836
- ir: "Night (IR)",
33837
- night: "Night",
33838
- dawn: "Dawn",
33839
- dusk: "Dusk"
33840
- };
33841
- function variantLabel(condition) {
33842
- return VARIANT_LABEL[condition] ?? condition;
33843
- }
33844
- /**
33845
- * "Daylight ✓ · Night (IR) ✗ — optional; checks in night (ir) are skipped."
33846
- *
33847
- * Converts the silent cross-condition fallback this engine used to have into an
33848
- * operator-visible fact. Without it, a scene with only a daylight reference
33849
- * simply stops answering after sunset and nothing anywhere says why.
33850
- *
33851
- * It used to end *"reports 'can't tell' in night (ir)"*, which was accurate and
33852
- * read as a defect: the operator saw a ✗ and a complaint for a scene that was
33853
- * configured exactly as they meant it. The missing half is now named as what it
33854
- * is — the part you do not have to do — and the sentence says what actually
33855
- * happens instead, which differs by the scene's own policy.
33856
- */
33857
- function coverageLine(monitor) {
33858
- const covered = new Set(monitor.coveredConditions);
33859
- const parts = SCENE_CAPTURE_VARIANTS.map((v) => `${variantLabel(v)} ${covered.has(v) ? "✓" : "✗"}`);
33860
- const extra = [...covered].filter((c) => !SCENE_CAPTURE_VARIANTS.some((v) => v === c));
33861
- for (const c of extra) parts.push(`${variantLabel(c)} ✓`);
33862
- const missing = SCENE_CAPTURE_VARIANTS.filter((v) => !covered.has(v));
33863
- if (missing.length === 0) return parts.join(" · ");
33864
- if (covered.size === 0) return `${parts.join(" · ")} — nothing captured yet, so this scene is not watching.`;
33865
- const names = missing.map((v) => variantLabel(v).toLowerCase()).join(" and ");
33866
- return monitor.onUncoveredCondition === "judge-anyway" ? `${parts.join(" · ")} — ${names} judged against the references you do have.` : `${parts.join(" · ")} — optional; checks in ${names} are skipped.`;
33867
- }
33868
- /**
33869
- * The calm sentence for a scene that is sitting the current light out — `null`
33870
- * whenever it is checking normally.
33871
- *
33872
- * Separate from {@link statusLine} because it is not a verdict and must not
33873
- * read like one. A paused scene has not failed, has not lost its flag, and
33874
- * needs nothing from the operator; the only thing worth saying is which light
33875
- * it is waiting out and that it will pick itself back up.
33876
- */
33877
- function suspensionLine(monitor) {
33878
- if (monitor.suspendedCondition === null) return null;
33879
- const light = variantLabel(monitor.suspendedCondition).toLowerCase();
33880
- return `Paused — nothing was captured in ${light}, so checks are on hold until the light changes back. Capture ${light} if you want it watched around the clock.`;
33881
- }
33882
- var UNAVAILABLE_SENTENCE = {
33883
- "no-reference-for-condition": "can’t tell — nothing has been captured for this scene yet. Press “Capture daylight” to photograph what normal looks like.",
33884
- "view-shifted": "can’t tell — the camera view has moved since the reference was captured. Re-capture it.",
33885
- "no-vision-profile": "can’t tell — the vision model is unreachable, so the change is on hold.",
33886
- "encoder-model-changed": "can’t tell — the embedding model changed, so the stored references are unreadable. Re-capture them.",
33887
- "no-snapshot": "can’t tell — this camera did not return a frame."
33888
- };
33889
- /**
33890
- * The one line under a scene's name. It answers, in order: can it judge, what
33891
- * does it say, and how long has it said it.
33892
- */
33893
- function statusLine(monitor, now) {
33894
- if (monitor.states.length === 0) return "Not armed yet — capture the initial state to start watching.";
33895
- if (monitor.verdict === "unknown") return monitor.unavailable !== null ? UNAVAILABLE_SENTENCE[monitor.unavailable] : "can’t tell right now.";
33896
- const since = monitor.verdict === "diverged" ? monitor.divergedAt : monitor.armedAt;
33897
- const held = since !== null ? ` for ${humanDuration(Math.max(0, now - since))}` : "";
33898
- if (monitor.latched) return monitor.verdict === "diverged" ? `CHANGED${held} — press Reset when you have dealt with it.` : `Back to normal, but still flagged as changed${held}. Press Reset to clear it.`;
33899
- const paused = suspensionLine(monitor);
33900
- if (paused !== null) return paused;
33901
- return monitor.verdict === "diverged" ? `CHANGED${held}` : `Normal${held}`;
33902
- }
33903
- /** The badge word. `latched` wins over `verdict`, because the latch is the
33904
- * thing the operator asked to be told and it outlives the live state.
33905
- *
33906
- * A scene sitting out an uncovered light reads `Paused`, in the NEUTRAL tone —
33907
- * never `alarm`, and never the `danger` variant the page maps that to. A
33908
- * missing IR reference must not be able to paint a red badge on a scene that
33909
- * is doing exactly what it was configured to do. */
33910
- function badgeFor(monitor) {
33911
- if (monitor.states.length === 0) return {
33912
- text: "Not armed",
33913
- tone: "unknown"
33914
- };
33915
- if (monitor.latched) return {
33916
- text: "Changed",
33917
- tone: "alarm"
33918
- };
33919
- if (monitor.suspendedCondition !== null) return {
33920
- text: "Paused",
33921
- tone: "unknown"
33922
- };
33923
- if (monitor.verdict === "unknown") return {
33924
- text: "Can’t tell",
33925
- tone: "unknown"
33926
- };
33927
- return monitor.verdict === "diverged" ? {
33928
- text: "Changed",
33929
- tone: "alarm"
33930
- } : {
33931
- text: "Normal",
33932
- tone: "ok"
33933
- };
33934
- }
33935
- /** A rect covering most of the frame is dominated by weather, sky and parked
33936
- * cars: the bin is 2 % of the pixels and CLIP will not notice it leaving. The
33937
- * failure is silent INSENSITIVITY, which is the worst kind — hence a warning
33938
- * rather than a refusal. */
33939
- var ROI_AREA_WARN_FRACTION = .4;
33940
- function roiTooLarge(roi) {
33941
- return roi.width * roi.height > ROI_AREA_WARN_FRACTION;
33942
- }
33943
- function humanDuration(ms) {
33944
- const s = Math.floor(ms / 1e3);
33945
- if (s < 60) return `${s}s`;
33946
- const m = Math.floor(s / 60);
33947
- if (m < 60) return `${m}m`;
33948
- const h = Math.floor(m / 60);
33949
- if (h < 48) return `${h}h`;
33950
- return `${Math.floor(h / 24)}d`;
33951
- }
33952
- //#endregion
33953
- //#region src/composites/code-block.tsx
33954
- function CodeBlock({ children, maxHeight = 300, className }) {
33955
- const [copied, setCopied] = (0, react$1.useState)(false);
33956
- const handleCopy = (0, react$1.useCallback)(() => {
33957
- navigator.clipboard.writeText(children).then(() => {
33958
- setCopied(true);
33959
- setTimeout(() => setCopied(false), 2e3);
33960
- });
33961
- }, [children]);
33962
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
33963
- className: cn("relative group", className),
33964
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(ScrollArea, {
33965
- style: { maxHeight },
33966
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
33967
- className: "font-mono text-xs bg-surface p-3 rounded-md border border-border-subtle",
33968
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", { children })
33969
- })
33970
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
33971
- className: "absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity",
33972
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(IconButton, {
33973
- icon: copied ? Check : Copy,
33974
- "aria-label": "Copy code",
33975
- variant: "ghost",
33976
- size: "sm",
33977
- onClick: handleCopy
33978
- })
33979
- })]
33980
- });
33981
- }
33982
- //#endregion
33983
- //#region src/composites/confirm-action-button.tsx
33984
- /**
33985
- * ConfirmActionButton — destructive-action button with a modal confirm.
33986
- *
33987
- * Two-step UX for any operation operators shouldn't trigger by accident:
33988
- * reboot device, restart addon, regenerate token, etc. The trigger is a
33989
- * normal Button that opens a Dialog; confirming runs the async action,
33990
- * the trigger spinner-disables itself for the duration, and the dialog
33991
- * closes on success. Errors surface inline at the dialog's bottom.
33992
- *
33993
- * Generic on `TResult` so callers don't have to discard the return
33994
- * value. Pass an `icon` to render it inside the trigger (e.g. RotateCw
33995
- * for reboot, RefreshCw for restart).
33996
- */
33997
- function ConfirmActionButton({ label, icon: Icon, title = "Confirm action", description, confirmLabel, triggerVariant = "outline", confirmVariant = "danger", size = "sm", disabled, className, action, onSuccess }) {
33998
- const [open, setOpen] = (0, react$1.useState)(false);
33999
- const [running, setRunning] = (0, react$1.useState)(false);
34000
- const [error, setError] = (0, react$1.useState)(null);
34001
- const handleConfirm = async () => {
34002
- setError(null);
34003
- setRunning(true);
34004
- try {
34005
- const result = await action();
34006
- onSuccess?.(result);
34007
- setOpen(false);
34008
- } catch (err) {
34009
- setError(err instanceof Error ? err.message : String(err));
34010
- } finally {
34011
- setRunning(false);
34012
- }
34013
- };
34014
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Button, {
34015
- type: "button",
34016
- variant: triggerVariant,
34017
- size,
34018
- disabled,
34019
- onClick: () => {
34020
- setError(null);
34021
- setOpen(true);
34022
- },
34023
- className,
34024
- children: [Icon && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Icon, { className: "h-3.5 w-3.5" }), label]
34025
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Dialog, {
34026
- open,
34027
- onOpenChange: (next) => !running && setOpen(next),
34028
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(DialogContent, { children: [
34029
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(DialogHeader, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(DialogTitle, {
34030
- className: "flex items-center gap-2",
34031
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(TriangleAlert, { className: "h-4 w-4 text-amber-400" }), title]
34032
- }), typeof description === "string" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DialogDescription, { children: description }) : description] }),
34033
- error && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
34034
- className: cn("mt-2 px-3 py-2 rounded border border-danger/40 bg-danger/10", "text-xs text-danger"),
34035
- children: error
34036
- }),
34037
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(DialogFooter, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
34038
- type: "button",
34039
- variant: "ghost",
34040
- size,
34041
- disabled: running,
34042
- onClick: () => setOpen(false),
34043
- children: "Cancel"
34044
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Button, {
34045
- type: "button",
34046
- variant: confirmVariant,
34047
- size,
34048
- disabled: running,
34049
- onClick: () => {
34050
- handleConfirm();
34051
- },
34052
- children: [running && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LoaderCircle, { className: "h-3.5 w-3.5 animate-spin" }), confirmLabel ?? label]
34053
- })] })
34054
- ] })
34055
- })] });
34056
- }
34057
- //#endregion
34058
- //#region src/composites/copy-button.tsx
34059
- /**
34060
- * `CopyButton` — a compact button that copies a string `value` to the
34061
- * clipboard via `navigator.clipboard.writeText`, showing a brief
34062
- * "copied" check state. Addon-agnostic; used wherever a secret / URL
34063
- * needs a one-click copy affordance (export setup panels, etc.).
34064
- */
34065
- var COPIED_RESET_MS = 2e3;
34066
- function CopyButton({ value, label, srLabel, className, disabled }) {
34067
- const [copied, setCopied] = (0, react$1.useState)(false);
34068
- const handleCopy = (0, react$1.useCallback)(() => {
34069
- if (!value) return;
34070
- navigator.clipboard.writeText(value).then(() => {
34071
- setCopied(true);
34072
- setTimeout(() => setCopied(false), COPIED_RESET_MS);
34073
- });
34074
- }, [value]);
34075
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Button, {
34076
- size: "sm",
34077
- variant: "ghost",
34078
- type: "button",
34079
- disabled: disabled || value.length === 0,
34080
- onClick: handleCopy,
34081
- className: cn(className),
34082
- "aria-label": copied ? "Copied" : `Copy ${srLabel ?? label ?? "value"}`,
34083
- children: [copied ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Check, { className: "h-3.5 w-3.5 text-success" }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Copy, { className: "h-3.5 w-3.5" }), label ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
34084
- className: "ml-1",
34085
- children: copied ? "Copied" : label
34086
- }) : null]
34087
- });
34088
- }
34089
- //#endregion
34090
- //#region src/composites/data-table-layout.ts
34091
- /**
34092
- * At this many columns and above, `auto` switches a narrow viewport to cards.
34093
- * Three columns still fit a phone at a readable size; four do not.
34094
- */
34095
- var CARD_MODE_MIN_COLUMNS = 4;
34096
- function resolveTableLayout({ mode, columnCount, isNarrow }) {
34097
- if (!isNarrow) return "table";
34098
- if (mode === "scroll") return "table";
34099
- if (mode === "cards") return "cards";
34100
- if (columnCount === 0) return "table";
34101
- return columnCount >= 4 ? "cards" : "table";
34102
- }
34103
- //#endregion
34104
33863
  //#region src/lib/responsive.ts
34105
33864
  /**
34106
33865
  * Responsive design tokens — three-tier system.
@@ -34212,6 +33971,20 @@ var CHIP_BASE = "inline-flex items-center gap-1 rounded-full border px-1.5 py-0.
34212
33971
  var CHIP_ACTIVE = "border-primary/50 bg-primary/15 text-primary";
34213
33972
  var CHIP_INACTIVE = "border-border bg-surface text-foreground-subtle hover:bg-surface-hover";
34214
33973
  //#endregion
33974
+ //#region src/composites/data-table-layout.ts
33975
+ /**
33976
+ * At this many columns and above, `auto` switches a narrow viewport to cards.
33977
+ * Three columns still fit a phone at a readable size; four do not.
33978
+ */
33979
+ var CARD_MODE_MIN_COLUMNS = 4;
33980
+ function resolveTableLayout({ mode, columnCount, isNarrow }) {
33981
+ if (!isNarrow) return "table";
33982
+ if (mode === "scroll") return "table";
33983
+ if (mode === "cards") return "cards";
33984
+ if (columnCount === 0) return "table";
33985
+ return columnCount >= 4 ? "cards" : "table";
33986
+ }
33987
+ //#endregion
34215
33988
  //#region src/composites/setting-row.tsx
34216
33989
  function SettingRow({ label, children, actions, elements = "plain", className, valueClassName }) {
34217
33990
  const LabelTag = elements === "description" ? "dt" : "span";
@@ -34247,263 +34020,2418 @@ function SortHeaderButton({ label, active, dir, onSort }) {
34247
34020
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: label }), active ? dir === "asc" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ChevronUp, { className: "h-3 w-3 flex-shrink-0" }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ChevronDown, { className: "h-3 w-3 flex-shrink-0" }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ChevronUp, { className: cn("h-3 w-3 flex-shrink-0 opacity-0 transition-opacity", "group-hover/sort:opacity-30") })]
34248
34021
  });
34249
34022
  }
34250
- //#endregion
34251
- //#region src/composites/table-sort.ts
34023
+ //#endregion
34024
+ //#region src/composites/table-sort.ts
34025
+ /**
34026
+ * The toggle rule, and the only copy of it.
34027
+ *
34028
+ * none → asc → desc → none, and a click on a DIFFERENT column starts that
34029
+ * column fresh at `asc`. `sameColumn` says whether the clicked column is the
34030
+ * one currently sorted; `currentDir` is its direction (`null` when nothing is
34031
+ * sorted). Returns the next direction, or `null` for "unsorted".
34032
+ *
34033
+ * Split out from {@link nextTableSort} so the device list — whose sort state
34034
+ * keys columns by `columnId`, not `columnKey` — can reuse the rule without a
34035
+ * cast and without a second copy of it.
34036
+ */
34037
+ function nextSortDirection(sameColumn, currentDir) {
34038
+ if (!sameColumn || currentDir === null) return "asc";
34039
+ return currentDir === "asc" ? "desc" : null;
34040
+ }
34041
+ /**
34042
+ * Toggle a column's sort on header click: none → asc → desc → none.
34043
+ * Clicking a DIFFERENT column starts it fresh at `asc`.
34044
+ */
34045
+ function nextTableSort(current, columnKey) {
34046
+ const dir = nextSortDirection(current !== null && current.columnKey === columnKey, current === null ? null : current.dir);
34047
+ return dir === null ? null : {
34048
+ columnKey,
34049
+ dir
34050
+ };
34051
+ }
34052
+ /**
34053
+ * Ascending comparison of two cell values.
34054
+ *
34055
+ * Numbers compare numerically and strings compare with `localeCompare` — a
34056
+ * numeric column must never be ordered as text ("100" before "9"), and a text
34057
+ * column must respect the locale's collation. A mixed column (one row a
34058
+ * number, another a string) falls back to string comparison of both, which is
34059
+ * the only total order available; it is not a shape any caller should build on
34060
+ * purpose.
34061
+ *
34062
+ * `null` is NOT handled here — {@link sortRowsByColumn} pulls it out first,
34063
+ * because its placement is direction-independent and a comparator that is
34064
+ * multiplied by the direction factor cannot express that.
34065
+ */
34066
+ function compareValues(a, b) {
34067
+ if (typeof a === "number" && typeof b === "number") return a - b;
34068
+ return String(a).localeCompare(String(b));
34069
+ }
34070
+ /**
34071
+ * Return a NEW array of `rows` ordered by `sort`.
34072
+ *
34073
+ * `valueOf` is the column's `sortValue` — it is called once per row per
34074
+ * comparison, so it must be cheap (read a field, do not format a string).
34075
+ * `sort === null` ⇒ a fresh shallow copy in the incoming order.
34076
+ */
34077
+ function sortRowsByColumn(rows, sort, valueOf) {
34078
+ if (sort === null) return [...rows];
34079
+ const factor = sort.dir === "asc" ? 1 : -1;
34080
+ return rows.toSorted((a, b) => {
34081
+ const av = valueOf(a);
34082
+ const bv = valueOf(b);
34083
+ if (av === null || bv === null) {
34084
+ if (av === bv) return 0;
34085
+ return av === null ? 1 : -1;
34086
+ }
34087
+ return factor * compareValues(av, bv);
34088
+ });
34089
+ }
34090
+ /** Derive the `<th>` `aria-sort` for `columnKey` from the table's sort state. */
34091
+ function ariaSortForColumn(sort, columnKey) {
34092
+ if (sort === null || sort.columnKey !== columnKey) return "none";
34093
+ return sort.dir === "asc" ? "ascending" : "descending";
34094
+ }
34095
+ //#endregion
34096
+ //#region src/composites/data-table.tsx
34097
+ /**
34098
+ * DataTable — shared responsive table for admin pages.
34099
+ *
34100
+ * Recipes baked in:
34101
+ * - `overflow-x-auto` wrapper so narrow viewports don't clip the
34102
+ * right edge (the rounded border survives the scroll).
34103
+ * - `min-w-[Npx]` on the inner table so columns don't squash below
34104
+ * readable width before the scroll kicks in.
34105
+ * - `whitespace-nowrap` on headers — column titles never wrap to
34106
+ * two lines (`AUTO-KILL` was the regression that triggered this).
34107
+ * - Themed `bg-surface` + `border-border` so contrast works in both
34108
+ * light and dark themes.
34109
+ *
34110
+ * Column model: caller supplies `columns: DataColumn<T>[]` and
34111
+ * `rows: T[]`. Each column declares `header`, optional `align`,
34112
+ * optional `nowrap`, and a `render(row) => ReactNode` that produces
34113
+ * the cell content.
34114
+ *
34115
+ * <DataTable
34116
+ * columns={[
34117
+ * { key: 'username', header: 'Username', render: (u) => u.username },
34118
+ * { key: 'role', header: 'Role', render: (u) => <RoleBadge .../> },
34119
+ * { key: 'actions', header: '', align: 'right', render: (u) => <Actions .../> },
34120
+ * ]}
34121
+ * rows={users}
34122
+ * minWidthPx={560}
34123
+ * />
34124
+ *
34125
+ * If finer header markup is needed, pass `headerRender` instead of
34126
+ * `header` (e.g. for a sortable click affordance).
34127
+ *
34128
+ * ── Narrow viewports ──────────────────────────────────────────────────────
34129
+ * The table stays a table. The wrapper is `overflow-x-auto`, so a phone
34130
+ * scrolls the columns sideways INSIDE the table — the page body never moves
34131
+ * sideways, and the cells stay one line (`whitespace-nowrap`). That is the
34132
+ * default (`mobileMode="scroll"`). Cards are opt-in via `mobileMode="cards"`;
34133
+ * `auto` still applies the old column-count rule for a surface that wants it.
34134
+ * See `resolveTableLayout`.
34135
+ *
34136
+ * ── Scrolling the BODY, not the page ──────────────────────────────────────
34137
+ * `maxBodyHeight` caps the table and scrolls its rows INSIDE the container
34138
+ * with the column header pinned. It is ONE prop, not two, because "this list
34139
+ * scrolls internally" and "its header stays visible" are the same decision: a
34140
+ * capped table whose header scrolls away is a list of unlabelled cells.
34141
+ *
34142
+ * Use it wherever the row count is open-ended (rules, targets, delivery
34143
+ * history) so the page keeps its own header, filters and actions in view while
34144
+ * the operator moves through the rows.
34145
+ */
34146
+ /**
34147
+ * The default cap for an internally-scrolling table.
34148
+ *
34149
+ * `60vh` leaves the page header, its filters and its actions on screen at
34150
+ * every viewport while still showing ~10 rows — and it is a fraction, so it
34151
+ * does not need a breakpoint of its own.
34152
+ */
34153
+ var TABLE_SCROLL_MAX_H = "max-h-[60vh]";
34154
+ var ALIGN_CLASS = {
34155
+ left: "text-left",
34156
+ right: "text-right",
34157
+ center: "text-center"
34158
+ };
34159
+ function DataTable({ columns, rows, rowKey, onRowClick, minWidthPx = 480, emptyMessage, className, bordered = true, rowClassName, mobileMode = "scroll", maxBodyHeight, defaultSort }) {
34160
+ const isNarrow = useIsMobile();
34161
+ const [sort, setSort] = (0, react$1.useState)(defaultSort ?? null);
34162
+ const layout = resolveTableLayout({
34163
+ mode: mobileMode,
34164
+ columnCount: columns.length,
34165
+ isNarrow
34166
+ });
34167
+ const scrolls = maxBodyHeight !== void 0;
34168
+ const sortedColumn = (0, react$1.useMemo)(() => sort === null ? void 0 : columns.find((col) => col.key === sort.columnKey && col.sortValue !== void 0), [columns, sort]);
34169
+ const sortValue = sortedColumn?.sortValue;
34170
+ const displayRows = (0, react$1.useMemo)(() => sortValue === void 0 ? rows : sortRowsByColumn(rows, sort, sortValue), [
34171
+ rows,
34172
+ sort,
34173
+ sortValue
34174
+ ]);
34175
+ const activeSort = sortedColumn === void 0 ? null : sort;
34176
+ if (rows.length === 0 && emptyMessage) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
34177
+ className: `rounded-lg ${bordered ? "border border-border" : ""} bg-surface px-3 py-4 text-xs text-foreground-subtle text-center ${className ?? ""}`,
34178
+ children: emptyMessage
34179
+ });
34180
+ if (rows.length === 0) return null;
34181
+ if (layout === "cards") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
34182
+ className: `space-y-2 ${scrolls ? `${maxBodyHeight} overflow-y-auto` : ""} ${className ?? ""}`,
34183
+ children: displayRows.map((row, rowIndex) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DataTableCard, {
34184
+ row,
34185
+ rowIndex,
34186
+ columns,
34187
+ bordered,
34188
+ onRowClick,
34189
+ rowClassName
34190
+ }, rowKey ? rowKey(row, rowIndex) : rowIndex))
34191
+ });
34192
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
34193
+ className: [
34194
+ "rounded-lg",
34195
+ bordered ? "border border-border" : "",
34196
+ "bg-surface overflow-x-auto",
34197
+ scrolls ? `${maxBodyHeight} overflow-y-auto` : "",
34198
+ className ?? ""
34199
+ ].filter(Boolean).join(" "),
34200
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("table", {
34201
+ className: `w-full text-xs ${scrolls ? "border-separate border-spacing-0" : ""}`,
34202
+ style: { minWidth: `${minWidthPx}px` },
34203
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("thead", {
34204
+ className: "bg-surface",
34205
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tr", { children: columns.map((col) => {
34206
+ const align = col.align ?? "left";
34207
+ const nowrap = col.nowrap ?? true;
34208
+ const sortable = col.sortValue !== void 0;
34209
+ const isSorted = activeSort !== null && activeSort.columnKey === col.key;
34210
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", {
34211
+ "aria-sort": sortable ? ariaSortForColumn(activeSort, col.key) : void 0,
34212
+ title: sortable ? void 0 : col.notSortableReason,
34213
+ className: [
34214
+ "px-3 py-2 text-foreground-subtle font-medium bg-surface border-b border-border",
34215
+ scrolls ? "sticky top-0 z-10" : "",
34216
+ ALIGN_CLASS[align],
34217
+ nowrap ? "whitespace-nowrap" : "",
34218
+ col.width ?? ""
34219
+ ].filter(Boolean).join(" "),
34220
+ children: sortable ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SortHeaderButton, {
34221
+ label: col.headerRender ? col.headerRender() : col.header,
34222
+ active: isSorted,
34223
+ dir: isSorted && activeSort !== null ? activeSort.dir : "asc",
34224
+ onSort: () => setSort((prev) => nextTableSort(prev, col.key))
34225
+ }) : col.headerRender ? col.headerRender() : col.header
34226
+ }, col.key);
34227
+ }) })
34228
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tbody", { children: displayRows.map((row, rowIndex) => {
34229
+ const key = rowKey ? rowKey(row, rowIndex) : rowIndex;
34230
+ const extra = rowClassName?.(row, rowIndex) ?? "";
34231
+ const interactive = onRowClick !== void 0;
34232
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tr", {
34233
+ onClick: interactive ? () => onRowClick(row, rowIndex) : void 0,
34234
+ className: [interactive ? "cursor-pointer hover:bg-primary/5" : "hover:bg-primary/5", extra].filter(Boolean).join(" "),
34235
+ children: columns.map((col) => {
34236
+ const align = col.align ?? "left";
34237
+ const nowrap = col.nowrap ?? true;
34238
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", {
34239
+ className: [
34240
+ "px-3 py-2 text-foreground border-b border-border",
34241
+ ALIGN_CLASS[align],
34242
+ nowrap ? "whitespace-nowrap" : ""
34243
+ ].filter(Boolean).join(" "),
34244
+ children: col.render(row, rowIndex)
34245
+ }, col.key);
34246
+ })
34247
+ }, key);
34248
+ }) })]
34249
+ })
34250
+ });
34251
+ }
34252
+ /**
34253
+ * One row as a card. Columns that carry a plain-text `header` become labelled
34254
+ * `SettingRow`s — the label is the column title and the value gets the full
34255
+ * card width. Columns with no text header (an actions column, a
34256
+ * `headerRender`-only column) have no label to show, so they render as a
34257
+ * full-width strip at the foot of the card.
34258
+ */
34259
+ function DataTableCard({ row, rowIndex, columns, bordered, onRowClick, rowClassName }) {
34260
+ const labelled = columns.filter((col) => col.header !== void 0 && col.header !== "");
34261
+ const unlabelled = columns.filter((col) => col.header === void 0 || col.header === "");
34262
+ const interactive = onRowClick !== void 0;
34263
+ const extra = rowClassName?.(row, rowIndex) ?? "";
34264
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
34265
+ "data-data-table-card": "",
34266
+ onClick: interactive ? () => onRowClick(row, rowIndex) : void 0,
34267
+ className: [
34268
+ "rounded-lg bg-surface px-3 py-1.5 divide-y divide-border-subtle",
34269
+ bordered ? "border border-border" : "",
34270
+ interactive ? "cursor-pointer hover:bg-primary/5" : "",
34271
+ extra
34272
+ ].filter(Boolean).join(" "),
34273
+ children: [labelled.map((col) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SettingRow, {
34274
+ label: col.header,
34275
+ children: col.render(row, rowIndex)
34276
+ }, col.key)), unlabelled.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
34277
+ className: "flex flex-wrap items-center justify-end gap-2 py-1.5",
34278
+ children: unlabelled.map((col) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { children: col.render(row, rowIndex) }, col.key))
34279
+ })]
34280
+ });
34281
+ }
34282
+ //#endregion
34283
+ //#region src/composites/key-value-list.tsx
34284
+ /**
34285
+ * A `<dl>` of label/value rows. Layout (including the L1 stacking) is owned by
34286
+ * `SettingRow`; this composite only supplies the description-list semantics.
34287
+ *
34288
+ * The rows used to be `flex items-center h-7` with a `w-1/3` term, so a label
34289
+ * could neither wrap nor stack: on a phone it took a third of the width and
34290
+ * the value took whatever was left.
34291
+ */
34292
+ function KeyValueList({ items, className }) {
34293
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("dl", {
34294
+ className: cn("flex flex-col", className),
34295
+ children: items.map((item) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SettingRow, {
34296
+ elements: "description",
34297
+ label: item.key,
34298
+ children: item.value
34299
+ }, item.key))
34300
+ });
34301
+ }
34302
+ //#endregion
34303
+ //#region src/composites/section-card.tsx
34304
+ function SectionCard({ headingId, title, icon: Icon, actions, testId, children }) {
34305
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
34306
+ "aria-labelledby": headingId,
34307
+ className: SECTION_CARD,
34308
+ "data-testid": testId,
34309
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("header", {
34310
+ className: `${SECTION_HEADER} flex min-h-9 flex-wrap items-center gap-2`,
34311
+ children: [
34312
+ Icon !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Icon, {
34313
+ className: "h-3.5 w-3.5 shrink-0 text-foreground-subtle",
34314
+ "aria-hidden": true
34315
+ }),
34316
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h2", {
34317
+ id: headingId,
34318
+ className: `${TEXT_SECTION_LABEL} min-w-0 flex-1`,
34319
+ children: title
34320
+ }),
34321
+ actions
34322
+ ]
34323
+ }), children]
34324
+ });
34325
+ }
34326
+ //#endregion
34327
+ //#region src/composites/webrtc-diagnostics/ice-candidates.ts
34328
+ var CANDIDATE_TYPES = [
34329
+ "host",
34330
+ "srflx",
34331
+ "prflx",
34332
+ "relay"
34333
+ ];
34334
+ function intOrNull(token) {
34335
+ if (token === void 0 || !/^\d+$/.test(token)) return null;
34336
+ const n = Number(token);
34337
+ return Number.isSafeInteger(n) ? n : null;
34338
+ }
34339
+ function familyOf(address) {
34340
+ if (address.length === 0) return "unknown";
34341
+ if (address.toLowerCase().endsWith(".local")) return "mdns";
34342
+ if (address.includes(":")) return "ipv6";
34343
+ if (/^\d{1,3}(\.\d{1,3}){3}$/.test(address)) return "ipv4";
34344
+ return "unknown";
34345
+ }
34346
+ function ipv4Octets(address) {
34347
+ const parts = address.split(".");
34348
+ if (parts.length !== 4) return null;
34349
+ const octets = parts.map((p) => Number(p));
34350
+ return octets.every((o) => Number.isInteger(o) && o >= 0 && o <= 255) ? octets : null;
34351
+ }
34352
+ function ipv4Scope(address) {
34353
+ const o = ipv4Octets(address);
34354
+ if (o === null) return "unknown";
34355
+ const [a = -1, b = -1] = o;
34356
+ if (a === 127) return "loopback";
34357
+ if (a === 169 && b === 254) return "link-local";
34358
+ if (a === 10 || a === 192 && b === 168 || a === 172 && b >= 16 && b <= 31) return "lan";
34359
+ if (a === 100 && b >= 64 && b <= 127) return "tailscale";
34360
+ return "public";
34361
+ }
34362
+ function ipv6Scope(address) {
34363
+ const lower = address.toLowerCase();
34364
+ if (lower === "::1") return "loopback";
34365
+ if (/^fe[89ab]/.test(lower)) return "link-local";
34366
+ if (lower.startsWith("fd7a:115c:a1e0:")) return "tailscale";
34367
+ if (/^f[cd]/.test(lower)) return "lan";
34368
+ return "public";
34369
+ }
34370
+ function classifyAddressScope(address) {
34371
+ switch (familyOf(address)) {
34372
+ case "mdns": return "mdns";
34373
+ case "ipv4": return ipv4Scope(address);
34374
+ case "ipv6": return ipv6Scope(address);
34375
+ default: return "unknown";
34376
+ }
34377
+ }
34378
+ /** Parse one candidate attribute (`candidate:…`, with or without `a=`). */
34379
+ function parseIceCandidate(line) {
34380
+ const raw = line.trim().replace(/^a=/, "");
34381
+ if (!raw.startsWith("candidate:")) return null;
34382
+ const parts = raw.slice(10).split(/\s+/);
34383
+ const address = parts[4] ?? "";
34384
+ const typIdx = parts.indexOf("typ");
34385
+ const typeToken = typIdx >= 0 ? parts[typIdx + 1] : void 0;
34386
+ const type = CANDIDATE_TYPES.find((t) => t === typeToken) ?? "unknown";
34387
+ const raddrIdx = parts.indexOf("raddr");
34388
+ const rportIdx = parts.indexOf("rport");
34389
+ const protocol = parts[2]?.toLowerCase();
34390
+ return {
34391
+ type,
34392
+ protocol: protocol !== void 0 && protocol.length > 0 ? protocol : null,
34393
+ address: address.length > 0 ? address : null,
34394
+ port: intOrNull(parts[5]),
34395
+ relatedAddress: raddrIdx >= 0 ? parts[raddrIdx + 1] ?? null : null,
34396
+ relatedPort: rportIdx >= 0 ? intOrNull(parts[rportIdx + 1]) : null,
34397
+ family: familyOf(address),
34398
+ scope: classifyAddressScope(address),
34399
+ raw
34400
+ };
34401
+ }
34402
+ /** Every `a=candidate` line of an SDP, in order. */
34403
+ function candidateLinesFromSdp(sdp) {
34404
+ return sdp.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.startsWith("a=candidate:"));
34405
+ }
34406
+ function candidateKey(c) {
34407
+ return `${c.type}|${c.protocol ?? "?"}|${c.address ?? "?"}|${String(c.port ?? "?")}`;
34408
+ }
34409
+ var PRIVATE_SCOPES = new Set([
34410
+ "loopback",
34411
+ "link-local",
34412
+ "lan",
34413
+ "tailscale",
34414
+ "mdns"
34415
+ ]);
34416
+ function emptyCounts() {
34417
+ return {
34418
+ host: 0,
34419
+ srflx: 0,
34420
+ prflx: 0,
34421
+ relay: 0,
34422
+ unknown: 0
34423
+ };
34424
+ }
34425
+ function countCandidateTypes(candidates) {
34426
+ const counts = emptyCounts();
34427
+ for (const c of candidates) counts[c.type] += 1;
34428
+ return counts;
34429
+ }
34430
+ function reachabilityFlag(answered, candidates) {
34431
+ if (!answered && candidates.length === 0) return "unknown";
34432
+ if (candidates.length === 0) return "none";
34433
+ if (candidates.some((c) => c.type === "srflx" || c.type === "relay" || c.type === "host" && c.scope === "public")) return "public-path";
34434
+ return candidates.every((c) => PRIVATE_SCOPES.has(c.scope)) ? "private-only" : "public-path";
34435
+ }
34436
+ /** The hub's offered candidates: answer SDP plus trickle, deduplicated. */
34437
+ function summarizeHubCandidates(input) {
34438
+ const seen = /* @__PURE__ */ new Set();
34439
+ const candidates = [];
34440
+ const add = (line) => {
34441
+ const c = parseIceCandidate(line);
34442
+ if (c === null) return false;
34443
+ const key = candidateKey(c);
34444
+ if (seen.has(key)) return false;
34445
+ seen.add(key);
34446
+ candidates.push(c);
34447
+ return true;
34448
+ };
34449
+ let fromSdp = 0;
34450
+ for (const line of candidateLinesFromSdp(input.sdpAnswer ?? "")) if (add(line)) fromSdp += 1;
34451
+ let fromTrickle = 0;
34452
+ for (const line of input.trickled) if (add(line)) fromTrickle += 1;
34453
+ return {
34454
+ candidates,
34455
+ fromSdp,
34456
+ fromTrickle,
34457
+ countByType: countCandidateTypes(candidates),
34458
+ hasSrflx: candidates.some((c) => c.type === "srflx"),
34459
+ hasRelay: candidates.some((c) => c.type === "relay"),
34460
+ hasPublicHost: candidates.some((c) => c.type === "host" && c.scope === "public"),
34461
+ flag: reachabilityFlag(input.sdpAnswer !== null, candidates),
34462
+ trickleDone: input.trickleDone
34463
+ };
34464
+ }
34465
+ //#endregion
34466
+ //#region src/composites/webrtc-diagnostics/endpoint-probe.ts
34467
+ /**
34468
+ * Browser-side probes behind "Test each endpoint" and the NAT mapping check.
34469
+ *
34470
+ * Everything runs in the operator's browser against real `RTCPeerConnection`s;
34471
+ * the only server round-trip is fetching the ICE server list.
34472
+ *
34473
+ * - `gatherCandidates` — one peer connection, a given server set: which
34474
+ * candidate types it produces, which server URL produced each (the ICE
34475
+ * event's `url`) and, for a relay, the transport to the TURN server
34476
+ * (`relayProtocol`: udp / tcp / tls).
34477
+ * - `relayLoopback` — two peer connections in this page, both forced to
34478
+ * `relay`: the ONLY way they connect is through the TURN server, so a
34479
+ * connect proves allocation and forwarding work, and the selected pair
34480
+ * gives the relay RTT and the local relay protocol from `getStats()`.
34481
+ * (A same-page loopback with policy `all` proves nothing — the two peers
34482
+ * connect host↔host — which is why it is not offered.)
34483
+ *
34484
+ * Credentials are attached to `turn:`/`turns:` entries only and never leave
34485
+ * this module: nothing here logs or returns them.
34486
+ */
34487
+ function toRtcIceServers(servers) {
34488
+ return servers.map((s) => {
34489
+ if (/^turns?:/i.test(s.url) && s.username !== void 0 && s.credential !== void 0) return {
34490
+ urls: s.url,
34491
+ username: s.username,
34492
+ credential: s.credential
34493
+ };
34494
+ return { urls: s.url };
34495
+ });
34496
+ }
34497
+ /** `RTCPeerConnectionIceEvent.url` — a real field missing from this lib.dom. */
34498
+ function iceEventUrl(e) {
34499
+ if ("url" in e && typeof e.url === "string" && e.url.length > 0) return e.url;
34500
+ return null;
34501
+ }
34502
+ /** `RTCIceCandidate.relayProtocol` — Chromium and WebKit report it; lib.dom does not type it. */
34503
+ function candidateRelayProtocol(c) {
34504
+ if ("relayProtocol" in c && typeof c.relayProtocol === "string" && c.relayProtocol.length > 0) return c.relayProtocol;
34505
+ return null;
34506
+ }
34507
+ /** One local candidate from an ICE event, or null for the end-of-candidates event. */
34508
+ function probedCandidateFromEvent(e, tMs) {
34509
+ const raw = e.candidate?.candidate;
34510
+ if (e.candidate === null || raw === void 0 || raw.length === 0) return null;
34511
+ const candidate = parseIceCandidate(raw);
34512
+ if (candidate === null) return null;
34513
+ return {
34514
+ candidate,
34515
+ url: iceEventUrl(e),
34516
+ relayProtocol: candidateRelayProtocol(e.candidate),
34517
+ tMs
34518
+ };
34519
+ }
34520
+ function errorText$1(err) {
34521
+ return err instanceof Error ? err.message : String(err);
34522
+ }
34523
+ async function gatherCandidates(servers, policy, timeoutMs = 8e3) {
34524
+ const start = performance.now();
34525
+ const candidates = [];
34526
+ const pc = new RTCPeerConnection({
34527
+ iceServers: toRtcIceServers(servers),
34528
+ iceTransportPolicy: policy
34529
+ });
34530
+ try {
34531
+ pc.createDataChannel("probe");
34532
+ const done = new Promise((resolve) => {
34533
+ const timer = setTimeout(() => resolve(true), timeoutMs);
34534
+ pc.addEventListener("icecandidate", (e) => {
34535
+ if (e.candidate === null) {
34536
+ clearTimeout(timer);
34537
+ resolve(false);
34538
+ return;
34539
+ }
34540
+ const probed = probedCandidateFromEvent(e, performance.now() - start);
34541
+ if (probed !== null) candidates.push(probed);
34542
+ });
34543
+ });
34544
+ await pc.setLocalDescription(await pc.createOffer());
34545
+ const timedOut = await done;
34546
+ return {
34547
+ candidates,
34548
+ durationMs: performance.now() - start,
34549
+ timedOut,
34550
+ error: null
34551
+ };
34552
+ } catch (err) {
34553
+ return {
34554
+ candidates,
34555
+ durationMs: performance.now() - start,
34556
+ timedOut: false,
34557
+ error: errorText$1(err)
34558
+ };
34559
+ } finally {
34560
+ pc.close();
34561
+ }
34562
+ }
34563
+ function selectedPairFacts(report) {
34564
+ const byId = /* @__PURE__ */ new Map();
34565
+ const pairs = [];
34566
+ const selected = { id: null };
34567
+ report.forEach((raw) => {
34568
+ const s = raw;
34569
+ if (s.id !== void 0) byId.set(s.id, s);
34570
+ if (s.type === "candidate-pair") pairs.push(s);
34571
+ if (s.type === "transport" && s.selectedCandidatePairId !== void 0) selected.id = s.selectedCandidatePairId;
34572
+ });
34573
+ const pair = pairs.find((p) => selected.id !== null && p.id === selected.id) ?? pairs.find((p) => p.selected === true) ?? pairs.find((p) => p.nominated === true && p.state === "succeeded") ?? null;
34574
+ if (pair === null) return {
34575
+ rttMs: null,
34576
+ relayProtocol: null
34577
+ };
34578
+ const local = pair.localCandidateId !== void 0 ? byId.get(pair.localCandidateId) : void 0;
34579
+ return {
34580
+ rttMs: typeof pair.currentRoundTripTime === "number" ? Math.round(pair.currentRoundTripTime * 1e3) : null,
34581
+ relayProtocol: typeof local?.relayProtocol === "string" ? local.relayProtocol : null
34582
+ };
34583
+ }
34584
+ async function relayLoopback(servers, timeoutMs = 1e4) {
34585
+ const start = performance.now();
34586
+ const config = {
34587
+ iceServers: toRtcIceServers(servers),
34588
+ iceTransportPolicy: "relay"
34589
+ };
34590
+ const pcA = new RTCPeerConnection(config);
34591
+ const pcB = new RTCPeerConnection(config);
34592
+ try {
34593
+ pcA.createDataChannel("probe");
34594
+ pcA.addEventListener("icecandidate", (e) => {
34595
+ if (e.candidate) pcB.addIceCandidate(e.candidate).catch(() => void 0);
34596
+ });
34597
+ pcB.addEventListener("icecandidate", (e) => {
34598
+ if (e.candidate) pcA.addIceCandidate(e.candidate).catch(() => void 0);
34599
+ });
34600
+ const connected = new Promise((resolve) => {
34601
+ const timer = setTimeout(() => resolve(false), timeoutMs);
34602
+ pcA.addEventListener("iceconnectionstatechange", () => {
34603
+ const st = pcA.iceConnectionState;
34604
+ if (st === "connected" || st === "completed") {
34605
+ clearTimeout(timer);
34606
+ resolve(true);
34607
+ } else if (st === "failed" || st === "closed") {
34608
+ clearTimeout(timer);
34609
+ resolve(false);
34610
+ }
34611
+ });
34612
+ });
34613
+ const offer = await pcA.createOffer();
34614
+ await pcA.setLocalDescription(offer);
34615
+ await pcB.setRemoteDescription(offer);
34616
+ const answer = await pcB.createAnswer();
34617
+ await pcB.setLocalDescription(answer);
34618
+ await pcA.setRemoteDescription(answer);
34619
+ const ok = await connected;
34620
+ const facts = ok ? selectedPairFacts(await pcA.getStats()) : {
34621
+ rttMs: null,
34622
+ relayProtocol: null
34623
+ };
34624
+ return {
34625
+ connected: ok,
34626
+ state: pcA.iceConnectionState,
34627
+ rttMs: facts.rttMs,
34628
+ relayProtocol: facts.relayProtocol,
34629
+ durationMs: performance.now() - start,
34630
+ error: null
34631
+ };
34632
+ } catch (err) {
34633
+ return {
34634
+ connected: false,
34635
+ state: pcA.iceConnectionState,
34636
+ rttMs: null,
34637
+ relayProtocol: null,
34638
+ durationMs: performance.now() - start,
34639
+ error: errorText$1(err)
34640
+ };
34641
+ } finally {
34642
+ pcA.close();
34643
+ pcB.close();
34644
+ }
34645
+ }
34646
+ //#endregion
34647
+ //#region src/composites/webrtc-diagnostics/nat-mapping.ts
34648
+ function isHiddenBase(o) {
34649
+ return o.relatedAddress === null || o.relatedAddress === "0.0.0.0" || o.relatedAddress === "::" || o.relatedPort === null || o.relatedPort === 0;
34650
+ }
34651
+ function baseKey(o) {
34652
+ return isHiddenBase(o) ? `public:${o.address}` : `base:${o.relatedAddress ?? "?"}:${String(o.relatedPort ?? "?")}`;
34653
+ }
34654
+ function unknown(reason, mappings = []) {
34655
+ return {
34656
+ kind: "unknown",
34657
+ confidence: "none",
34658
+ reason,
34659
+ mappings
34660
+ };
34661
+ }
34662
+ /**
34663
+ * The distinct STUN destinations (`stun:host:port`) among the given URLs —
34664
+ * the number the check needs to be at least two. TURN URLs are excluded:
34665
+ * this check is about plain STUN binding.
34666
+ */
34667
+ function distinctStunDestinations(urls) {
34668
+ const out = [];
34669
+ for (const url of urls) {
34670
+ const m = /^stuns?:([^?]+)/i.exec(url.trim());
34671
+ if (m === null) continue;
34672
+ const dest = `stun:${(m[1] ?? "").toLowerCase()}`;
34673
+ if (!out.includes(dest)) out.push(dest);
34674
+ }
34675
+ return out;
34676
+ }
34677
+ function compareSrflxMappings(observations, stunDestinationsQueried) {
34678
+ const udp = observations.filter((o) => o.protocol.toLowerCase() === "udp");
34679
+ if (stunDestinationsQueried < 2) return unknown("needs two STUN destinations to compare; only one was queried");
34680
+ if (udp.length === 0) return unknown("no server-reflexive candidate: STUN unreachable or blocked from this browser");
34681
+ const groups = /* @__PURE__ */ new Map();
34682
+ for (const o of udp) {
34683
+ const key = baseKey(o);
34684
+ groups.set(key, [...groups.get(key) ?? [], o]);
34685
+ }
34686
+ const mappings = [...new Set(udp.map((o) => `${o.address}:${String(o.port)}`))];
34687
+ for (const group of groups.values()) {
34688
+ const distinct = new Set(group.map((o) => `${o.address}:${String(o.port)}`));
34689
+ if (distinct.size > 1) return {
34690
+ kind: "endpoint-dependent",
34691
+ confidence: "confirmed",
34692
+ reason: `one local socket got ${String(distinct.size)} different public mappings — symmetric NAT: only a TURN relay reaches this browser`,
34693
+ mappings
34694
+ };
34695
+ }
34696
+ const confirmed = [...groups.values()].some((group) => new Set(group.map((o) => o.url).filter((u) => u !== null)).size >= 2);
34697
+ return {
34698
+ kind: "endpoint-independent",
34699
+ confidence: confirmed ? "confirmed" : "likely",
34700
+ reason: confirmed ? "two STUN destinations saw the same public mapping" : "one public mapping across the STUN destinations (the browser drops an identical second candidate, so the second answer cannot be told from no answer)",
34701
+ mappings
34702
+ };
34703
+ }
34704
+ //#endregion
34705
+ //#region src/composites/webrtc-diagnostics/endpoint-test.ts
34706
+ /**
34707
+ * "Test each endpoint" and the NAT mapping check — the orchestration around
34708
+ * the browser probes, with the row derivation kept pure so it is tested
34709
+ * without a browser.
34710
+ */
34711
+ /** Queried in addition to the configured STUN servers until two distinct destinations exist. */
34712
+ var FALLBACK_STUN_URLS = ["stun:stun.l.google.com:19302", "stun:stun1.l.google.com:19302"];
34713
+ function schemeOf(url) {
34714
+ const lower = url.toLowerCase();
34715
+ if (lower.startsWith("turns:")) return "turns";
34716
+ if (lower.startsWith("turn:")) return "turn";
34717
+ if (lower.startsWith("stun:") || lower.startsWith("stuns:")) return "stun";
34718
+ return "other";
34719
+ }
34720
+ function transportOf(url) {
34721
+ return /[?&]transport=([a-z]+)/i.exec(url)?.[1]?.toLowerCase() ?? null;
34722
+ }
34723
+ /** One row per URL: an entry's `urls` may be a string or a list. */
34724
+ function flattenIceServers(servers) {
34725
+ const out = [];
34726
+ for (const s of servers) {
34727
+ const urls = typeof s.urls === "string" ? [s.urls] : s.urls;
34728
+ for (const url of urls) {
34729
+ if (out.some((e) => e.id === url)) continue;
34730
+ out.push({
34731
+ id: url,
34732
+ url,
34733
+ ...s.username !== void 0 ? { username: s.username } : {},
34734
+ ...s.credential !== void 0 ? { credential: s.credential } : {},
34735
+ scheme: schemeOf(url),
34736
+ transport: transportOf(url),
34737
+ hasCredentials: s.credential !== void 0
34738
+ });
34739
+ }
34740
+ }
34741
+ return out;
34742
+ }
34743
+ function endpointRowFromProbe(endpoint, gather, loopback) {
34744
+ const srflx = gather.candidates.find((c) => c.candidate.type === "srflx");
34745
+ const relay = gather.candidates.find((c) => c.candidate.type === "relay");
34746
+ const mapped = srflx !== void 0 && srflx.candidate.address !== null && srflx.candidate.port !== null ? `${srflx.candidate.address}:${String(srflx.candidate.port)}` : null;
34747
+ return {
34748
+ id: endpoint.id,
34749
+ url: endpoint.url,
34750
+ scheme: endpoint.scheme,
34751
+ transport: endpoint.transport,
34752
+ srflx: mapped,
34753
+ relay: relay !== void 0,
34754
+ relayProtocol: loopback?.relayProtocol ?? relay?.relayProtocol ?? null,
34755
+ eventUrl: relay?.url ?? srflx?.url ?? null,
34756
+ relayConnected: loopback?.connected ?? null,
34757
+ rttMs: loopback?.rttMs ?? null,
34758
+ timedOut: gather.timedOut,
34759
+ error: gather.error ?? loopback?.error ?? null
34760
+ };
34761
+ }
34762
+ var GATHER_TIMEOUT_MS = 6e3;
34763
+ var LOOPBACK_TIMEOUT_MS = 8e3;
34764
+ function configOf(e) {
34765
+ return [{
34766
+ url: e.url,
34767
+ ...e.username !== void 0 ? { username: e.username } : {},
34768
+ ...e.credential !== void 0 ? { credential: e.credential } : {}
34769
+ }];
34770
+ }
34771
+ /** Gather against ONE endpoint; for a TURN endpoint, also prove the relay forwards. */
34772
+ async function testEndpoint(endpoint) {
34773
+ const cfg = configOf(endpoint);
34774
+ return endpointRowFromProbe(endpoint, await gatherCandidates(cfg, "all", GATHER_TIMEOUT_MS), endpoint.scheme === "turn" || endpoint.scheme === "turns" ? await relayLoopback(cfg, LOOPBACK_TIMEOUT_MS) : null);
34775
+ }
34776
+ /** The STUN destinations the NAT check queries: configured first, public fallbacks to reach two. */
34777
+ function natCheckDestinations(endpoints) {
34778
+ const out = [...distinctStunDestinations(endpoints.map((e) => e.url))];
34779
+ for (const url of distinctStunDestinations(FALLBACK_STUN_URLS)) {
34780
+ if (out.length >= 2) break;
34781
+ if (!out.includes(url)) out.push(url);
34782
+ }
34783
+ return out;
34784
+ }
34785
+ function srflxObservations(gather) {
34786
+ const out = [];
34787
+ for (const c of gather.candidates) {
34788
+ const p = c.candidate;
34789
+ if (p.type !== "srflx" || p.address === null || p.port === null || p.protocol === null) continue;
34790
+ out.push({
34791
+ address: p.address,
34792
+ port: p.port,
34793
+ protocol: p.protocol,
34794
+ relatedAddress: p.relatedAddress,
34795
+ relatedPort: p.relatedPort,
34796
+ url: c.url
34797
+ });
34798
+ }
34799
+ return out;
34800
+ }
34801
+ async function runNatCheck(endpoints) {
34802
+ const destinations = natCheckDestinations(endpoints);
34803
+ const gather = await gatherCandidates(destinations.map((url) => ({ url })), "all", GATHER_TIMEOUT_MS);
34804
+ return {
34805
+ destinations,
34806
+ verdict: compareSrflxMappings(srflxObservations(gather), destinations.length),
34807
+ error: gather.error
34808
+ };
34809
+ }
34810
+ //#endregion
34811
+ //#region src/composites/webrtc-diagnostics/format.ts
34812
+ /**
34813
+ * Rendering helpers for the WebRTC diagnostics: an unmeasured value is the
34814
+ * word "unknown", never a dash that reads as zero and never a 0 (D393).
34815
+ */
34816
+ var UNKNOWN_TEXT = "unknown";
34817
+ function formatMaybe(value, render) {
34818
+ return value === null ? UNKNOWN_TEXT : render(value);
34819
+ }
34820
+ var fmtMs = (v) => formatMaybe(v, (n) => `${String(Math.round(n))} ms`);
34821
+ var fmtCount = (v) => formatMaybe(v, (n) => n.toLocaleString());
34822
+ var fmtBytes = (v) => formatMaybe(v, (n) => {
34823
+ if (n < 1024) return `${String(n)} B`;
34824
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`;
34825
+ return `${(n / (1024 * 1024)).toFixed(2)} MiB`;
34826
+ });
34827
+ var fmtPercent = (v) => formatMaybe(v, (n) => `${n.toFixed(1)} %`);
34828
+ var fmtText = (v) => formatMaybe(v, (s) => s);
34829
+ //#endregion
34830
+ //#region src/composites/webrtc-diagnostics/EndpointTestCard.tsx
34831
+ /**
34832
+ * "ICE servers" — the live ICE server list (`turnProvider.getTurnServers`, the
34833
+ * same union every viewer is handed) probed endpoint by endpoint from THIS
34834
+ * browser, plus the NAT mapping check.
34835
+ *
34836
+ * Owns no hub data beyond the list it is given through `loadServers`.
34837
+ * Credentials are passed to the probes and never rendered: a row shows `auth`.
34838
+ */
34839
+ var SCHEME_VARIANT = {
34840
+ stun: "info",
34841
+ turn: "warning",
34842
+ turns: "success",
34843
+ other: "default"
34844
+ };
34845
+ function errorText(err) {
34846
+ return err instanceof Error ? err.message : String(err);
34847
+ }
34848
+ function yesNo(value, yes, no) {
34849
+ if (value === null) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
34850
+ className: "text-foreground-subtle",
34851
+ children: UNKNOWN_TEXT
34852
+ });
34853
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
34854
+ className: value ? "text-success" : "text-danger",
34855
+ children: value ? yes : no
34856
+ });
34857
+ }
34858
+ var RESULT_COLUMNS = [
34859
+ {
34860
+ key: "endpoint",
34861
+ header: "Endpoint",
34862
+ nowrap: false,
34863
+ render: (r) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
34864
+ className: "break-all font-mono text-[11px]",
34865
+ children: r.url
34866
+ })
34867
+ },
34868
+ {
34869
+ key: "srflx",
34870
+ header: "Mapped (srflx)",
34871
+ render: (r) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
34872
+ className: "font-mono text-[11px]",
34873
+ children: r.srflx ?? "none"
34874
+ })
34875
+ },
34876
+ {
34877
+ key: "relay",
34878
+ header: "Relay",
34879
+ render: (r) => r.scheme === "stun" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
34880
+ className: "text-foreground-subtle",
34881
+ children: "n/a"
34882
+ }) : yesNo(r.relay, "allocated", "none")
34883
+ },
34884
+ {
34885
+ key: "proto",
34886
+ header: "Relay protocol",
34887
+ render: (r) => r.scheme === "stun" ? "n/a" : fmtText(r.relayProtocol)
34888
+ },
34889
+ {
34890
+ key: "connect",
34891
+ header: "Relay connect",
34892
+ render: (r) => r.relayConnected === null ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
34893
+ className: "text-foreground-subtle",
34894
+ children: "n/a"
34895
+ }) : yesNo(r.relayConnected, "connected", "failed")
34896
+ },
34897
+ {
34898
+ key: "rtt",
34899
+ header: "RTT",
34900
+ align: "right",
34901
+ render: (r) => fmtMs(r.rttMs)
34902
+ },
34903
+ {
34904
+ key: "url",
34905
+ header: "Event url",
34906
+ nowrap: false,
34907
+ render: (r) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
34908
+ className: "break-all font-mono text-[10px]",
34909
+ children: fmtText(r.eventUrl)
34910
+ })
34911
+ },
34912
+ {
34913
+ key: "note",
34914
+ header: "Note",
34915
+ nowrap: false,
34916
+ render: (r) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
34917
+ className: TEXT_HINT,
34918
+ children: r.error ?? (r.timedOut ? "gathering timed out" : "")
34919
+ })
34920
+ }
34921
+ ];
34922
+ var NAT_LABEL = {
34923
+ "endpoint-independent": "Endpoint-independent mapping",
34924
+ "endpoint-dependent": "Symmetric NAT (endpoint-dependent)",
34925
+ unknown: "Unknown"
34926
+ };
34927
+ function NatResult({ result }) {
34928
+ const { verdict } = result;
34929
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
34930
+ className: SECTION_BODY,
34931
+ "data-testid": "nat-check-result",
34932
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(KeyValueList, { items: [
34933
+ {
34934
+ key: "NAT mapping",
34935
+ value: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
34936
+ className: "flex flex-wrap items-center gap-1.5",
34937
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Badge, {
34938
+ variant: verdict.kind === "endpoint-independent" ? "success" : verdict.kind === "endpoint-dependent" ? "danger" : "default",
34939
+ children: NAT_LABEL[verdict.kind]
34940
+ }), verdict.confidence !== "none" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
34941
+ className: "text-[10px] text-foreground-subtle",
34942
+ children: verdict.confidence
34943
+ })]
34944
+ })
34945
+ },
34946
+ {
34947
+ key: "Why",
34948
+ value: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
34949
+ className: "text-xs",
34950
+ children: verdict.reason
34951
+ })
34952
+ },
34953
+ {
34954
+ key: "Mappings seen",
34955
+ value: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
34956
+ className: "font-mono text-[11px]",
34957
+ children: verdict.mappings.length > 0 ? verdict.mappings.join(", ") : "none"
34958
+ })
34959
+ },
34960
+ {
34961
+ key: "STUN queried",
34962
+ value: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
34963
+ className: "break-all font-mono text-[11px]",
34964
+ children: result.destinations.join(", ")
34965
+ })
34966
+ },
34967
+ ...result.error !== null ? [{
34968
+ key: "Error",
34969
+ value: result.error
34970
+ }] : []
34971
+ ] })
34972
+ });
34973
+ }
34974
+ /** The per-endpoint result table — one row per tested ICE URL. */
34975
+ function EndpointResultsCard({ rows }) {
34976
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SectionCard, {
34977
+ headingId: "webrtc-diag-endpoint-results",
34978
+ title: "Per-endpoint results",
34979
+ icon: Play,
34980
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DataTable, {
34981
+ columns: RESULT_COLUMNS,
34982
+ rows,
34983
+ rowKey: (r) => r.id,
34984
+ bordered: false,
34985
+ minWidthPx: 760,
34986
+ mobileMode: "cards"
34987
+ })
34988
+ });
34989
+ }
34990
+ /** The NAT mapping verdict for this browser. */
34991
+ function NatResultCard({ result }) {
34992
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SectionCard, {
34993
+ headingId: "webrtc-diag-nat",
34994
+ title: "NAT mapping (this browser)",
34995
+ icon: Route,
34996
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NatResult, { result })
34997
+ });
34998
+ }
34999
+ function EndpointRow({ endpoint, checked, onToggle }) {
35000
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
35001
+ className: `${LIST_ROW} flex cursor-pointer items-center gap-2 hover:bg-surface-hover/40`,
35002
+ children: [
35003
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Checkbox, {
35004
+ checked,
35005
+ onChange: () => onToggle(endpoint.id)
35006
+ }),
35007
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Badge, {
35008
+ variant: SCHEME_VARIANT[endpoint.scheme],
35009
+ className: "shrink-0 uppercase text-[10px]",
35010
+ children: endpoint.scheme
35011
+ }),
35012
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
35013
+ className: "min-w-0 flex-1 break-all font-mono text-[11px] text-foreground",
35014
+ children: endpoint.url
35015
+ }),
35016
+ endpoint.transport !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
35017
+ className: `text-[10px] text-foreground-subtle uppercase`,
35018
+ children: endpoint.transport
35019
+ }),
35020
+ endpoint.hasCredentials && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
35021
+ className: `text-[10px] text-foreground-subtle text-success`,
35022
+ children: "auth"
35023
+ })
35024
+ ]
35025
+ });
35026
+ }
35027
+ function EndpointTestCard({ loadServers }) {
35028
+ const [endpoints, setEndpoints] = (0, react$1.useState)(null);
35029
+ const [loadError, setLoadError] = (0, react$1.useState)(null);
35030
+ const [loading, setLoading] = (0, react$1.useState)(false);
35031
+ const [enabled, setEnabled] = (0, react$1.useState)(/* @__PURE__ */ new Set());
35032
+ const [running, setRunning] = (0, react$1.useState)(null);
35033
+ const [rows, setRows] = (0, react$1.useState)([]);
35034
+ const [nat, setNat] = (0, react$1.useState)(null);
35035
+ const reload = (0, react$1.useCallback)(async () => {
35036
+ setLoading(true);
35037
+ setLoadError(null);
35038
+ try {
35039
+ const flat = flattenIceServers(await loadServers());
35040
+ setEndpoints(flat);
35041
+ setEnabled(new Set(flat.map((e) => e.id)));
35042
+ } catch (err) {
35043
+ setLoadError(errorText(err));
35044
+ } finally {
35045
+ setLoading(false);
35046
+ }
35047
+ }, [loadServers]);
35048
+ (0, react$1.useEffect)(() => {
35049
+ reload();
35050
+ }, [reload]);
35051
+ const selected = (0, react$1.useMemo)(() => (endpoints ?? []).filter((e) => enabled.has(e.id)), [endpoints, enabled]);
35052
+ const toggle = (0, react$1.useCallback)((id) => {
35053
+ setEnabled((prev) => {
35054
+ const next = new Set(prev);
35055
+ if (next.has(id)) next.delete(id);
35056
+ else next.add(id);
35057
+ return next;
35058
+ });
35059
+ }, []);
35060
+ const runEndpoints = (0, react$1.useCallback)(async () => {
35061
+ setRunning("endpoints");
35062
+ setRows([]);
35063
+ const out = [];
35064
+ for (const e of selected) {
35065
+ out.push(await testEndpoint(e));
35066
+ setRows([...out]);
35067
+ }
35068
+ setRunning(null);
35069
+ }, [selected]);
35070
+ const runNat = (0, react$1.useCallback)(async () => {
35071
+ setRunning("nat");
35072
+ setNat(null);
35073
+ try {
35074
+ setNat(await runNatCheck(endpoints ?? []));
35075
+ } finally {
35076
+ setRunning(null);
35077
+ }
35078
+ }, [endpoints]);
35079
+ const busy = running !== null;
35080
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
35081
+ className: "space-y-3 sm:space-y-4",
35082
+ children: [
35083
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SectionCard, {
35084
+ headingId: "webrtc-diag-ice-servers",
35085
+ title: `ICE servers${endpoints !== null ? ` (${String(endpoints.length)})` : ""}`,
35086
+ icon: Network,
35087
+ testId: "webrtc-diag-ice-servers",
35088
+ actions: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
35089
+ className: "flex flex-wrap items-center gap-1.5",
35090
+ children: [
35091
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Button, {
35092
+ variant: "ghost",
35093
+ onClick: () => void reload(),
35094
+ disabled: loading || busy,
35095
+ children: [loading ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LoaderCircle, { className: "h-3 w-3 animate-spin" }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RefreshCw, { className: "h-3 w-3" }), "Reload"]
35096
+ }),
35097
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Button, {
35098
+ variant: "outline",
35099
+ onClick: () => void runNat(),
35100
+ disabled: busy || endpoints === null,
35101
+ children: [running === "nat" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LoaderCircle, { className: "h-3 w-3 animate-spin" }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Route, { className: "h-3 w-3" }), "Check NAT"]
35102
+ }),
35103
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Button, {
35104
+ onClick: () => void runEndpoints(),
35105
+ disabled: busy || selected.length === 0,
35106
+ children: [running === "endpoints" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LoaderCircle, { className: "h-3 w-3 animate-spin" }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Play, { className: "h-3 w-3" }), "Test each endpoint"]
35107
+ })
35108
+ ]
35109
+ }),
35110
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
35111
+ className: "divide-y divide-border/50",
35112
+ children: [
35113
+ loadError !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
35114
+ className: `px-3 sm:px-4 py-1.5 sm:py-2 text-xs text-danger`,
35115
+ children: ["Failed to load ICE servers: ", loadError]
35116
+ }),
35117
+ loadError === null && endpoints === null && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
35118
+ className: `px-3 sm:px-4 py-1.5 sm:py-2 text-[10px] text-foreground-subtle`,
35119
+ children: "Loading…"
35120
+ }),
35121
+ endpoints !== null && endpoints.length === 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
35122
+ className: `px-3 sm:px-4 py-1.5 sm:py-2 text-[10px] text-foreground-subtle`,
35123
+ children: "No ICE servers configured. Add a TURN provider under TURN Servers."
35124
+ }),
35125
+ (endpoints ?? []).map((e) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(EndpointRow, {
35126
+ endpoint: e,
35127
+ checked: enabled.has(e.id),
35128
+ onToggle: toggle
35129
+ }, e.id))
35130
+ ]
35131
+ })
35132
+ }),
35133
+ rows.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(EndpointResultsCard, { rows }),
35134
+ nat !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NatResultCard, { result: nat })
35135
+ ]
35136
+ });
35137
+ }
35138
+ //#endregion
35139
+ //#region src/hooks/turn-server-cache.ts
35140
+ /** Short enough that rotated credentials are picked up promptly. */
35141
+ var DEFAULT_FRESH_TTL_MS = 5 * 6e4;
35142
+ /** Half of the shortest provider credential lifetime in the fleet (24 h). */
35143
+ var DEFAULT_STALE_CAP_MS = 720 * 6e4;
35144
+ var DEFAULT_STORAGE_KEY = "camstack:turn-servers:v1";
35145
+ function defaultStorage() {
35146
+ const g = globalThis;
35147
+ try {
35148
+ return g.localStorage ?? null;
35149
+ } catch {
35150
+ return null;
35151
+ }
35152
+ }
35153
+ /** Type guard for a persisted entry — storage content is external data. */
35154
+ function isCacheEntry(value) {
35155
+ if (typeof value !== "object" || value === null) return false;
35156
+ const v = value;
35157
+ if (typeof v.fetchedAt !== "number" || !Array.isArray(v.servers)) return false;
35158
+ return v.servers.every((s) => {
35159
+ if (typeof s !== "object" || s === null) return false;
35160
+ const srv = s;
35161
+ if (!(typeof srv.urls === "string" || Array.isArray(srv.urls) && srv.urls.every((u) => typeof u === "string"))) return false;
35162
+ if (srv.username !== void 0 && typeof srv.username !== "string") return false;
35163
+ if (srv.credential !== void 0 && typeof srv.credential !== "string") return false;
35164
+ return true;
35165
+ });
35166
+ }
35167
+ var TurnServerCache = class {
35168
+ freshTtlMs;
35169
+ staleCapMs;
35170
+ storage;
35171
+ now;
35172
+ storageKey;
35173
+ /** Keyed on the caller's tRPC client object (stable per connected system). */
35174
+ memory = /* @__PURE__ */ new WeakMap();
35175
+ /** In-flight fetch per key — concurrent callers share one round trip. */
35176
+ inflight = /* @__PURE__ */ new WeakMap();
35177
+ constructor(options = {}) {
35178
+ this.freshTtlMs = options.freshTtlMs ?? DEFAULT_FRESH_TTL_MS;
35179
+ this.staleCapMs = options.staleCapMs ?? DEFAULT_STALE_CAP_MS;
35180
+ this.storage = "storage" in options ? options.storage ?? null : defaultStorage();
35181
+ this.now = options.now ?? (() => Date.now());
35182
+ this.storageKey = options.storageKey ?? DEFAULT_STORAGE_KEY;
35183
+ }
35184
+ /**
35185
+ * Resolve the ICE servers for `key`, fetching via `fetch` only when no
35186
+ * fresh-enough entry exists. Never rejects: a failed fetch resolves to the
35187
+ * stale entry when one exists, else `undefined`.
35188
+ */
35189
+ async getOrFetch(key, fetch) {
35190
+ const at = this.now();
35191
+ const entry = this.memory.get(key) ?? this.readStorage();
35192
+ if (entry) {
35193
+ const age = at - entry.fetchedAt;
35194
+ if (age < this.freshTtlMs) return entry.servers;
35195
+ if (age < this.staleCapMs) {
35196
+ this.startFetch(key, fetch, entry);
35197
+ return entry.servers;
35198
+ }
35199
+ }
35200
+ return this.startFetch(key, fetch, entry);
35201
+ }
35202
+ startFetch(key, fetch, stale) {
35203
+ const pending = this.inflight.get(key);
35204
+ if (pending) return pending;
35205
+ const run = (async () => {
35206
+ try {
35207
+ const servers = await fetch();
35208
+ if (servers.length > 0) {
35209
+ const entry = {
35210
+ servers,
35211
+ fetchedAt: this.now()
35212
+ };
35213
+ this.memory.set(key, entry);
35214
+ this.writeStorage(entry);
35215
+ }
35216
+ return servers;
35217
+ } catch {
35218
+ return stale?.servers;
35219
+ }
35220
+ })().finally(() => {
35221
+ this.inflight.delete(key);
35222
+ });
35223
+ this.inflight.set(key, run);
35224
+ return run;
35225
+ }
35226
+ readStorage() {
35227
+ if (!this.storage) return void 0;
35228
+ try {
35229
+ const raw = this.storage.getItem(this.storageKey);
35230
+ if (raw === null) return void 0;
35231
+ const parsed = JSON.parse(raw);
35232
+ return isCacheEntry(parsed) ? parsed : void 0;
35233
+ } catch {
35234
+ return;
35235
+ }
35236
+ }
35237
+ writeStorage(entry) {
35238
+ if (!this.storage) return;
35239
+ try {
35240
+ this.storage.setItem(this.storageKey, JSON.stringify(entry));
35241
+ } catch {}
35242
+ }
35243
+ };
35244
+ //#endregion
35245
+ //#region src/hooks/use-device-webrtc.ts
35246
+ /**
35247
+ * useDeviceWebrtc — WebRTC signaling hook for device-scoped streaming.
35248
+ *
35249
+ * Provides `createSession`, `sendAnswer`, `closeSession` callbacks and
35250
+ * a `streams` list (Adaptive + High/Mid/Low) for a given device.
35251
+ *
35252
+ * Works in both admin-ui (BackendClient.trpc) and addon pages
35253
+ * (AddonPageProps.trpc) — parametrized by a minimal tRPC proxy shape.
35254
+ */
35255
+ /**
35256
+ * Hook that provides WebRTC signaling callbacks and stream choices for a device.
35257
+ *
35258
+ * @param trpc - tRPC proxy (admin-ui BackendClient.trpc or addon page trpc)
35259
+ * @param deviceId - numeric device ID (null = disabled)
35260
+ * @param pollIntervalMs - how often to refresh profile slots (default: 5000)
35261
+ */
35262
+ /** Module-level TURN/STUN credential cache. Keyed on the caller's trpc client
35263
+ * object (stable per connected system — NOT on `trpc.turnProvider`, which is
35264
+ * a proxy minted fresh on every property access), so two admin tabs pointed
35265
+ * at different hubs never cross-serve credentials from the memory layer; the
35266
+ * storage layer is per-origin, and the page's origin IS the hub. Coalesces
35267
+ * concurrent fetches (the mount prefetch and the connect's own call used to
35268
+ * race into TWO round trips) and persists across page loads so a fresh embed
35269
+ * page — one per camera open on native — finds warm credentials instead of
35270
+ * re-paying the measured 0.2–3.6 s serialized fetch. See turn-server-cache.ts. */
35271
+ var turnServersCache = new TurnServerCache();
35272
+ function useDeviceWebrtc(trpc, deviceId, pollIntervalMs = 5e3) {
35273
+ const [remoteStreams, setRemoteStreams] = (0, react$1.useState)([]);
35274
+ (0, react$1.useEffect)(() => {
35275
+ if (deviceId === null) return;
35276
+ let cancelled = false;
35277
+ const fetch = () => {
35278
+ trpc.webrtcSession.listStreams.query({ deviceId }).then((rows) => {
35279
+ if (!cancelled) setRemoteStreams(rows);
35280
+ }).catch(() => {});
35281
+ };
35282
+ fetch();
35283
+ const iv = setInterval(fetch, pollIntervalMs);
35284
+ return () => {
35285
+ cancelled = true;
35286
+ clearInterval(iv);
35287
+ };
35288
+ }, [
35289
+ trpc,
35290
+ deviceId,
35291
+ pollIntervalMs
35292
+ ]);
35293
+ const [pipelineMetrics, setPipelineMetrics] = (0, react$1.useState)(null);
35294
+ (0, react$1.useEffect)(() => {
35295
+ if (deviceId === null) return;
35296
+ let cancelled = false;
35297
+ if (trpc.pipelineOrchestrator) trpc.pipelineOrchestrator.getCameraMetrics.query({ deviceId }).then((m) => {
35298
+ if (cancelled || !m) return;
35299
+ setPipelineMetrics({
35300
+ phase: m.phase,
35301
+ detectionFps: m.actualFps,
35302
+ avgInferenceMs: m.avgInferenceTimeMs,
35303
+ droppedFrames: m.droppedFrames
35304
+ });
35305
+ }).catch(() => {});
35306
+ return () => {
35307
+ cancelled = true;
35308
+ };
35309
+ }, [trpc, deviceId]);
35310
+ useLiveEvent("pipeline.camera-metrics-snapshot", (evt) => {
35311
+ if (deviceId === null) return;
35312
+ const payload = evt.data;
35313
+ if (payload.deviceId !== deviceId || !payload.metrics) return;
35314
+ setPipelineMetrics({
35315
+ phase: payload.metrics.phase,
35316
+ detectionFps: payload.metrics.actualFps,
35317
+ avgInferenceMs: payload.metrics.avgInferenceTimeMs,
35318
+ droppedFrames: payload.metrics.droppedFrames
35319
+ });
35320
+ });
35321
+ const { streams, hasWebrtc } = (0, react$1.useMemo)(() => {
35322
+ if (deviceId === null || remoteStreams.length === 0) return {
35323
+ streams: [],
35324
+ hasWebrtc: false
35325
+ };
35326
+ return {
35327
+ streams: remoteStreams.map((r) => ({
35328
+ id: r.id,
35329
+ label: r.label,
35330
+ target: r.target,
35331
+ status: r.status,
35332
+ inputFps: r.inputFps,
35333
+ decodeFps: r.decodeFps,
35334
+ bitrateKbps: r.bitrateKbps
35335
+ })),
35336
+ hasWebrtc: true
35337
+ };
35338
+ }, [deviceId, remoteStreams]);
35339
+ const getIceServers = (0, react$1.useCallback)(async () => {
35340
+ const provider = trpc.turnProvider;
35341
+ if (!provider) return void 0;
35342
+ return turnServersCache.getOrFetch(trpc, async () => {
35343
+ return (await provider.getTurnServers.query()).map((s) => {
35344
+ return {
35345
+ urls: typeof s.urls === "string" ? s.urls : [...s.urls],
35346
+ ...s.username !== void 0 ? { username: s.username } : {},
35347
+ ...s.credential !== void 0 ? { credential: s.credential } : {}
35348
+ };
35349
+ });
35350
+ });
35351
+ }, [trpc]);
35352
+ (0, react$1.useEffect)(() => {
35353
+ getIceServers();
35354
+ }, [getIceServers]);
35355
+ const createSession = (0, react$1.useCallback)(async (target, hints) => {
35356
+ if (deviceId === null) throw new Error("No device selected");
35357
+ const res = await trpc.webrtcSession.createSession.mutate({
35358
+ deviceId,
35359
+ target,
35360
+ hints
35361
+ });
35362
+ const iceServers = await getIceServers();
35363
+ return {
35364
+ sessionId: res.sessionId,
35365
+ sdpOffer: res.sdpOffer,
35366
+ ...iceServers ? { iceServers } : {}
35367
+ };
35368
+ }, [
35369
+ trpc,
35370
+ deviceId,
35371
+ getIceServers
35372
+ ]);
35373
+ const handleOffer = (0, react$1.useCallback)(async (target, sdpOffer, sessionId, hints) => {
35374
+ if (deviceId === null) throw new Error("No device selected");
35375
+ return trpc.webrtcSession.handleOffer.mutate({
35376
+ deviceId,
35377
+ target,
35378
+ sdpOffer,
35379
+ ...sessionId !== void 0 ? { sessionId } : {},
35380
+ ...hints !== void 0 ? { hints } : {}
35381
+ });
35382
+ }, [trpc, deviceId]);
35383
+ const sendAnswer = (0, react$1.useCallback)(async (sessionId, sdpAnswer) => {
35384
+ if (deviceId === null) throw new Error("No device selected");
35385
+ await trpc.webrtcSession.handleAnswer.mutate({
35386
+ deviceId,
35387
+ sessionId,
35388
+ sdpAnswer
35389
+ });
35390
+ }, [trpc, deviceId]);
35391
+ return {
35392
+ streams,
35393
+ hasWebrtc,
35394
+ pipelineMetrics,
35395
+ createSession,
35396
+ handleOffer,
35397
+ getIceServers,
35398
+ addIceCandidate: (0, react$1.useCallback)(async (sessionId, candidate) => {
35399
+ if (deviceId === null) return;
35400
+ await trpc.webrtcSession.addIceCandidate.mutate({
35401
+ deviceId,
35402
+ sessionId,
35403
+ candidate: candidate.candidate ?? "",
35404
+ sdpMid: candidate.sdpMid ?? null,
35405
+ sdpMLineIndex: candidate.sdpMLineIndex ?? null
35406
+ }).catch(() => {});
35407
+ }, [trpc, deviceId]),
35408
+ getIceCandidates: (0, react$1.useCallback)(async (sessionId) => {
35409
+ if (deviceId === null) return {
35410
+ candidates: [],
35411
+ done: true
35412
+ };
35413
+ return trpc.webrtcSession.getIceCandidates.query({
35414
+ deviceId,
35415
+ sessionId
35416
+ });
35417
+ }, [trpc, deviceId]),
35418
+ sendAnswer,
35419
+ closeSession: (0, react$1.useCallback)(async (sessionId) => {
35420
+ if (deviceId === null) return;
35421
+ await trpc.webrtcSession.closeSession.mutate({
35422
+ deviceId,
35423
+ sessionId
35424
+ }).catch(() => {});
35425
+ }, [trpc, deviceId]),
35426
+ getSessionState: (0, react$1.useCallback)(async (sessionId) => {
35427
+ if (deviceId === null) return { pendingRenegotiation: null };
35428
+ try {
35429
+ return await trpc.webrtcSession.getSessionState.query({
35430
+ deviceId,
35431
+ sessionId
35432
+ });
35433
+ } catch {
35434
+ return { pendingRenegotiation: null };
35435
+ }
35436
+ }, [trpc, deviceId]),
35437
+ getSessionDebug: (0, react$1.useCallback)(async (sessionId) => {
35438
+ if (deviceId === null) throw new Error("getSessionDebug: no device bound to this player");
35439
+ return trpc.webrtcSession.getSessionDebug.query({
35440
+ deviceId,
35441
+ sessionId
35442
+ });
35443
+ }, [trpc, deviceId]),
35444
+ applyDownlinkProbe: (0, react$1.useCallback)(async (sessionId, downlinkMbps) => {
35445
+ const mutate = trpc.webrtcSession.applyDownlinkProbe;
35446
+ if (deviceId === null || mutate === void 0) throw new Error("applyDownlinkProbe: not available for this player");
35447
+ return mutate.mutate({
35448
+ deviceId,
35449
+ sessionId,
35450
+ downlinkMbps
35451
+ });
35452
+ }, [trpc, deviceId])
35453
+ };
35454
+ }
35455
+ //#endregion
35456
+ //#region src/composites/webrtc-diagnostics/RunReport.tsx
35457
+ var VERDICT_VARIANT = {
35458
+ healthy: "success",
35459
+ "loss-keyframe": "warning",
35460
+ transport: "danger",
35461
+ "hub-dtls": "danger",
35462
+ "media-black-hole": "danger",
35463
+ "hub-not-sending": "danger",
35464
+ unknown: "default"
35465
+ };
35466
+ var FLAG_TEXT = {
35467
+ "public-path": "has a public path (srflx / relay / public host)",
35468
+ "private-only": "LAN/Tailscale only, no srflx/relay",
35469
+ none: "answered with no candidate",
35470
+ unknown: "no answer received"
35471
+ };
35472
+ function candidateText(c) {
35473
+ const where = c.address === null ? "unknown" : `${c.address}:${c.port === null ? "?" : String(c.port)}`;
35474
+ return `${c.type} ${c.protocol ?? "?"} ${where} · ${c.scope}`;
35475
+ }
35476
+ function typeCounts(counts) {
35477
+ const parts = Object.entries(counts).filter(([, n]) => n > 0).map(([t, n]) => `${String(n)} ${t}`);
35478
+ return parts.length > 0 ? parts.join(" · ") : "none";
35479
+ }
35480
+ function Group({ title, children }) {
35481
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
35482
+ className: "space-y-0.5",
35483
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
35484
+ className: TEXT_SECTION_LABEL,
35485
+ children: title
35486
+ }), children]
35487
+ });
35488
+ }
35489
+ function RunReport({ report, title }) {
35490
+ const { hub, timeline, path, media, verdict, local } = report;
35491
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
35492
+ className: SECTION_CARD,
35493
+ "data-testid": `webrtc-diag-run-${report.policy}`,
35494
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("header", {
35495
+ className: `${SECTION_HEADER} flex flex-wrap items-center gap-2`,
35496
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h3", {
35497
+ className: `${TEXT_SECTION_LABEL} min-w-0 flex-1`,
35498
+ children: title
35499
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Badge, {
35500
+ variant: VERDICT_VARIANT[verdict.layer],
35501
+ children: verdict.title
35502
+ })]
35503
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
35504
+ className: `${SECTION_BODY} space-y-3`,
35505
+ children: [
35506
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
35507
+ className: "text-xs text-foreground",
35508
+ children: verdict.detail
35509
+ }),
35510
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Group, {
35511
+ title: "Hub candidates",
35512
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(KeyValueList, { items: [{
35513
+ key: "Offered",
35514
+ value: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
35515
+ className: "flex flex-wrap items-center gap-1.5 text-xs",
35516
+ children: [typeCounts(hub.countByType), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Badge, {
35517
+ variant: hub.flag === "private-only" ? "warning" : hub.flag === "public-path" ? "success" : "default",
35518
+ children: FLAG_TEXT[hub.flag]
35519
+ })]
35520
+ })
35521
+ }, {
35522
+ key: "Source",
35523
+ value: `${String(hub.fromSdp)} in the answer SDP · ${String(hub.fromTrickle)} trickled${hub.trickleDone === true ? " · gathering done" : ""}`
35524
+ }] }), hub.candidates.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("ul", {
35525
+ className: "mt-1 space-y-0.5 font-mono text-[10px] text-foreground-subtle",
35526
+ children: hub.candidates.map((c) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("li", {
35527
+ className: "break-all",
35528
+ children: candidateText(c)
35529
+ }, c.raw))
35530
+ })]
35531
+ }),
35532
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Group, {
35533
+ title: "Timeline",
35534
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(KeyValueList, { items: [
35535
+ {
35536
+ key: "ICE connected",
35537
+ value: fmtMs(timeline.iceConnectedMs)
35538
+ },
35539
+ {
35540
+ key: "DTLS connected",
35541
+ value: fmtMs(timeline.dtlsConnectedMs)
35542
+ },
35543
+ {
35544
+ key: "First frame",
35545
+ value: fmtMs(timeline.firstFrameMs)
35546
+ },
35547
+ {
35548
+ key: "ICE · DTLS final",
35549
+ value: `${fmtText(timeline.iceFinalState)} · ${fmtText(timeline.dtlsFinalState)}`
35550
+ }
35551
+ ] })
35552
+ }),
35553
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Group, {
35554
+ title: "Path",
35555
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(KeyValueList, { items: [
35556
+ {
35557
+ key: "Selected pair",
35558
+ value: path.pairType === null ? fmtText(null) : `${path.pairType} (local/remote)`
35559
+ },
35560
+ {
35561
+ key: "Protocol · RTT",
35562
+ value: `${fmtText(path.protocol)} · ${fmtMs(path.rttMs)}`
35563
+ },
35564
+ {
35565
+ key: "Browser offered",
35566
+ value: `${typeCounts(local.countByType)}${local.relayProtocols.length > 0 ? ` · relay over ${local.relayProtocols.join("/")}` : ""}`
35567
+ }
35568
+ ] })
35569
+ }),
35570
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Group, {
35571
+ title: "Media",
35572
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(KeyValueList, { items: [
35573
+ {
35574
+ key: "Hub sent",
35575
+ value: `${fmtCount(media.serverPacketsSent)} RTP packets${media.servedTier !== null ? ` · ${media.servedTier}` : ""}${media.egressLeg !== null ? ` · ${media.egressLeg}` : ""}`
35576
+ },
35577
+ {
35578
+ key: "Browser got",
35579
+ value: `${fmtCount(media.clientPacketsReceived)} packets · ${fmtBytes(media.clientBytesReceived)}`
35580
+ },
35581
+ {
35582
+ key: "Frames decoded",
35583
+ value: fmtCount(media.framesDecoded)
35584
+ },
35585
+ {
35586
+ key: "Loss · freezes",
35587
+ value: `${fmtPercent(media.lossPercent)} · ${fmtCount(media.freezeCount)} (${fmtMs(media.totalFreezeMs)})`
35588
+ },
35589
+ {
35590
+ key: "PLI · NACK",
35591
+ value: `${fmtCount(media.pliCount)} · ${fmtCount(media.nackCount)}`
35592
+ }
35593
+ ] })
35594
+ }),
35595
+ (report.reconnects > 0 || report.errors.length > 0 || report.serverError !== null) && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
35596
+ className: "text-[10px] text-foreground-subtle",
35597
+ children: [
35598
+ report.reconnects > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: ["Player reconnects: ", String(report.reconnects)] }),
35599
+ report.errors.map((e, i) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: ["Player error: ", e] }, `${String(i)}-${e}`)),
35600
+ report.serverError !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: ["Server debug: ", report.serverError] })
35601
+ ]
35602
+ }),
35603
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
35604
+ className: TEXT_HINT,
35605
+ children: [
35606
+ "Sessions:",
35607
+ " ",
35608
+ report.sessionIds.length > 0 ? report.sessionIds.map((s) => s.slice(0, 8)).join(", ") : "none",
35609
+ " ",
35610
+ "· ",
35611
+ String(Math.round(report.durationMs / 1e3)),
35612
+ " s"
35613
+ ]
35614
+ })
35615
+ ]
35616
+ })]
35617
+ });
35618
+ }
35619
+ function transportDetail(input) {
35620
+ const state = input.iceFinalState ?? "unknown";
35621
+ if (input.hubFlag === "unknown") return `ICE ${state}; the hub never answered the offer, so no hub candidate was seen`;
35622
+ if (input.hubFlag === "none") return `ICE ${state}; the hub answered but offered no candidate`;
35623
+ if (input.policy === "relay" && input.hubFlag === "private-only") return `ICE ${state}; this browser was limited to TURN relay candidates and the hub offered only LAN/Tailscale addresses (no srflx/relay) — a relayed client cannot reach it`;
35624
+ if (input.hubFlag === "private-only") return `ICE ${state}; the hub offered only LAN/Tailscale addresses (no srflx/relay) — reachable only from inside those networks`;
35625
+ return `ICE ${state}; no candidate pair between this browser and the hub succeeded`;
35626
+ }
35627
+ function verdict(layer, title, detail) {
35628
+ return {
35629
+ layer,
35630
+ title,
35631
+ detail
35632
+ };
35633
+ }
35634
+ function mediaVerdict(input) {
35635
+ const client = input.clientPacketsReceived;
35636
+ const sent = input.serverPacketsSent;
35637
+ if (client === null) return verdict("unknown", "Media unknown", "the browser reported no inbound video statistics");
35638
+ if (client === 0) {
35639
+ if (sent === null) return verdict("unknown", "Nothing received", "the browser received no packets and the hub's own count is unknown");
35640
+ if (sent > 0) return verdict("media-black-hole", "Media black-hole", `the hub sent ${String(sent)} RTP packets and this browser received none — media is lost between them after DTLS`);
35641
+ return verdict("hub-not-sending", "Hub not sending", "the session is connected but the hub sent no RTP — the source or the broker is not producing");
35642
+ }
35643
+ if (input.framesDecoded === null) return verdict("unknown", "Decode unknown", "packets arrive; the browser reported no decode count");
35644
+ if (input.framesDecoded === 0) return verdict("loss-keyframe", "Loss / keyframe size", "packets arrive but no frame decoded — a keyframe never completes over this path");
35645
+ const { pliCount: pli, freezeCount: freezes, lossPercent: loss } = input;
35646
+ const storm = pli !== null && pli >= 3 || freezes !== null && freezes > 0 || loss !== null && loss >= 2;
35647
+ const signals = [
35648
+ `${pli === null ? "unknown" : String(pli)} PLI`,
35649
+ `${freezes === null ? "unknown" : String(freezes)} freezes`,
35650
+ `${loss === null ? "unknown" : `${loss.toFixed(1)}%`} loss`
35651
+ ].join(", ");
35652
+ if (storm) return verdict("loss-keyframe", "Loss / keyframe size", `frames decode but the path is lossy: ${signals}`);
35653
+ if (pli === null && freezes === null && loss === null) return verdict("healthy", "Decoding", "frames decode; the browser reported no loss signal to judge");
35654
+ return verdict("healthy", "Healthy", `connected, receiving and decoding: ${signals}`);
35655
+ }
35656
+ function classifySessionVerdict(input) {
35657
+ if (!input.iceConnected) return verdict("transport", "Transport (ICE) failed", transportDetail(input));
35658
+ if (!input.dtlsConnected && input.dtlsFinalState !== null) return verdict("hub-dtls", "DTLS stuck (hub side)", `ICE connected but DTLS stayed ${input.dtlsFinalState} — the hub never completed the handshake`);
35659
+ return mediaVerdict(input);
35660
+ }
35661
+ //#endregion
35662
+ //#region src/composites/webrtc-diagnostics/session-run.ts
35663
+ function emptySessionRun(policy) {
35664
+ return {
35665
+ policy,
35666
+ sessionIds: [],
35667
+ sdpAnswer: null,
35668
+ trickled: [],
35669
+ trickleDone: null,
35670
+ local: [],
35671
+ ice: [],
35672
+ dtls: [],
35673
+ peer: [],
35674
+ firstFrameAt: null,
35675
+ lastStats: null,
35676
+ lastServer: null,
35677
+ maxServerPacketsSent: null,
35678
+ lastServerError: null,
35679
+ samples: 0,
35680
+ reconnects: 0,
35681
+ errors: []
35682
+ };
35683
+ }
35684
+ function mark(list, state, at) {
35685
+ return list.at(-1)?.state === state ? list : [...list, {
35686
+ state,
35687
+ at
35688
+ }];
35689
+ }
35690
+ function maxOrNull(a, b) {
35691
+ if (a === null) return b;
35692
+ if (b === null) return a;
35693
+ return Math.max(a, b);
35694
+ }
35695
+ function reduceSample(state, sample) {
35696
+ return {
35697
+ ...state,
35698
+ samples: state.samples + 1,
35699
+ lastStats: sample.stats ?? state.lastStats,
35700
+ lastServer: sample.server ?? state.lastServer,
35701
+ maxServerPacketsSent: maxOrNull(state.maxServerPacketsSent, sample.server?.rtpPacketsSent ?? null),
35702
+ lastServerError: sample.serverError,
35703
+ sessionIds: sample.sessionId !== null && !state.sessionIds.includes(sample.sessionId) ? [...state.sessionIds, sample.sessionId] : state.sessionIds
35704
+ };
35705
+ }
35706
+ function reduceSessionRun(state, event) {
35707
+ switch (event.kind) {
35708
+ case "offer-answered": return {
35709
+ ...state,
35710
+ sdpAnswer: state.sdpAnswer ?? event.sdpAnswer,
35711
+ sessionIds: state.sessionIds.includes(event.sessionId) ? state.sessionIds : [...state.sessionIds, event.sessionId]
35712
+ };
35713
+ case "hub-candidates": return {
35714
+ ...state,
35715
+ trickled: [...state.trickled, ...event.candidates.filter((c) => !state.trickled.includes(c))],
35716
+ trickleDone: event.done || state.trickleDone === true
35717
+ };
35718
+ case "local-candidate": {
35719
+ const candidate = parseIceCandidate(event.candidate);
35720
+ if (candidate === null) return state;
35721
+ return {
35722
+ ...state,
35723
+ local: [...state.local, {
35724
+ candidate,
35725
+ url: event.url,
35726
+ relayProtocol: event.relayProtocol
35727
+ }]
35728
+ };
35729
+ }
35730
+ case "ice-state": return {
35731
+ ...state,
35732
+ ice: mark(state.ice, event.state, event.at)
35733
+ };
35734
+ case "dtls-state": return {
35735
+ ...state,
35736
+ dtls: mark(state.dtls, event.state, event.at)
35737
+ };
35738
+ case "peer-state": return {
35739
+ ...state,
35740
+ peer: mark(state.peer, event.state, event.at)
35741
+ };
35742
+ case "first-frame": return {
35743
+ ...state,
35744
+ firstFrameAt: state.firstFrameAt ?? event.at
35745
+ };
35746
+ case "sample": return reduceSample(state, event.sample);
35747
+ case "reconnect": return {
35748
+ ...state,
35749
+ reconnects: state.reconnects + 1
35750
+ };
35751
+ case "error": return {
35752
+ ...state,
35753
+ errors: [...state.errors, event.message]
35754
+ };
35755
+ }
35756
+ }
35757
+ var CONNECTED_ICE = new Set(["connected", "completed"]);
35758
+ function firstAt(list, states) {
35759
+ return list.find((m) => states.has(m.state))?.at ?? null;
35760
+ }
35761
+ var CONNECTED = new Set(["connected"]);
35762
+ function timelineOf(state) {
35763
+ const dtlsAt = firstAt(state.dtls, CONNECTED) ?? firstAt(state.peer, CONNECTED);
35764
+ const dtlsFinal = state.dtls.at(-1)?.state ?? state.peer.at(-1)?.state ?? null;
35765
+ return {
35766
+ iceConnectedMs: firstAt(state.ice, CONNECTED_ICE),
35767
+ dtlsConnectedMs: dtlsAt,
35768
+ firstFrameMs: state.firstFrameAt,
35769
+ iceFinalState: state.ice.at(-1)?.state ?? null,
35770
+ dtlsFinalState: dtlsFinal
35771
+ };
35772
+ }
35773
+ function mediaOf(state) {
35774
+ const s = state.lastStats;
35775
+ const srv = state.lastServer;
35776
+ return {
35777
+ clientBytesReceived: s?.raw.bytesReceived ?? null,
35778
+ clientPacketsReceived: s?.packetsReceived ?? null,
35779
+ framesDecoded: s?.framesDecoded ?? null,
35780
+ serverPacketsSent: state.maxServerPacketsSent,
35781
+ serverAlive: srv?.alive ?? null,
35782
+ servedTier: srv?.servedTier ?? null,
35783
+ egressLeg: srv?.egressLeg ?? null,
35784
+ lossPercent: s?.lossPercent ?? null,
35785
+ freezeCount: s?.freezeCount ?? null,
35786
+ totalFreezeMs: s?.totalFreezeMs ?? null,
35787
+ pliCount: s?.pliCount ?? null,
35788
+ nackCount: s?.nackCount ?? null
35789
+ };
35790
+ }
35791
+ function localOf(state) {
35792
+ const unique = (xs) => [...new Set(xs.filter((x) => x !== null))];
35793
+ return {
35794
+ countByType: countCandidateTypes(state.local.map((l) => l.candidate)),
35795
+ relayProtocols: unique(state.local.filter((l) => l.candidate.type === "relay").map((l) => l.relayProtocol)),
35796
+ urls: unique(state.local.map((l) => l.url))
35797
+ };
35798
+ }
35799
+ function finalizeSessionRun(state, durationMs) {
35800
+ const hub = summarizeHubCandidates({
35801
+ sdpAnswer: state.sdpAnswer,
35802
+ trickled: state.trickled,
35803
+ trickleDone: state.trickleDone
35804
+ });
35805
+ const timeline = timelineOf(state);
35806
+ const media = mediaOf(state);
35807
+ const verdict = classifySessionVerdict({
35808
+ policy: state.policy,
35809
+ durationMs,
35810
+ iceConnected: timeline.iceConnectedMs !== null,
35811
+ iceFinalState: timeline.iceFinalState,
35812
+ dtlsConnected: timeline.dtlsConnectedMs !== null,
35813
+ dtlsFinalState: timeline.dtlsFinalState,
35814
+ hubFlag: hub.flag,
35815
+ clientPacketsReceived: media.clientPacketsReceived,
35816
+ framesDecoded: media.framesDecoded,
35817
+ serverPacketsSent: media.serverPacketsSent,
35818
+ pliCount: media.pliCount,
35819
+ freezeCount: media.freezeCount,
35820
+ lossPercent: media.lossPercent
35821
+ });
35822
+ return {
35823
+ policy: state.policy,
35824
+ durationMs,
35825
+ sessionIds: state.sessionIds,
35826
+ hub,
35827
+ local: localOf(state),
35828
+ timeline,
35829
+ path: {
35830
+ pairType: state.lastStats?.candidatePairType ?? null,
35831
+ protocol: state.lastStats?.candidateProtocol ?? null,
35832
+ rttMs: state.lastStats?.rttMs ?? null
35833
+ },
35834
+ media,
35835
+ reconnects: state.reconnects,
35836
+ errors: state.errors,
35837
+ serverError: state.lastServerError,
35838
+ verdict
35839
+ };
35840
+ }
35841
+ //#endregion
35842
+ //#region src/composites/webrtc-diagnostics/HubSessionTestCard.tsx
35843
+ /**
35844
+ * "Hub session test" — a real live session from THIS browser to the hub,
35845
+ * through the same `CameraStreamPlayer` + `useDeviceWebrtc` signaling every
35846
+ * viewer uses, run twice: browser ICE policy `all`, then `relay`.
35847
+ *
35848
+ * Nothing is simulated. The player's own client-offer path builds the offer,
35849
+ * trickles, polls the hub's candidates, and reports its 1 Hz
35850
+ * `StreamDebugSample` (the `webrtc-debug-stats` collector plus the server's
35851
+ * `getSessionDebug`). This card only LISTENS: it wraps the signaling callbacks
35852
+ * to see the hub's answer SDP and trickled candidates, and adds listeners to
35853
+ * each peer connection the player builds (`onPeerConnection`) for the ICE /
35854
+ * DTLS timeline and the browser's own candidates. The target is pinned (a low
35855
+ * or sub stream by default) so a large keyframe does not decide the verdict.
35856
+ */
35857
+ var HUB_SESSION_RUN_MS = 15e3;
35858
+ var POLICIES = ["all", "relay"];
35859
+ /** Between runs, so the first session is closed on the hub before the second opens. */
35860
+ var RUN_GAP_MS = 750;
35861
+ var PROGRESS_TICK_MS = 500;
35862
+ /** Pinned targets only, cheapest first: an adaptive target would climb mid-run. */
35863
+ function pinnedStreamChoices(streams) {
35864
+ const rank = (s) => {
35865
+ const t = s.target;
35866
+ if (t.kind === "profile") return t.profile === "low" ? 0 : t.profile === "mid" ? 2 : 3;
35867
+ if (t.kind === "cam-stream") return /sub|low|ext/i.test(t.camStreamId) ? 1 : 4;
35868
+ return 9;
35869
+ };
35870
+ return streams.filter((s) => s.target.kind !== "adaptive").toSorted((a, b) => rank(a) - rank(b));
35871
+ }
35872
+ var POLICY_LABEL = {
35873
+ all: "ICE policy all",
35874
+ relay: "ICE policy relay (TURN only)"
35875
+ };
35876
+ function HubSessionTestCard({ trpc, serverUrl, deviceId, cameraField, runMs = HUB_SESSION_RUN_MS }) {
35877
+ const webrtc = useDeviceWebrtc(trpc, deviceId);
35878
+ const choices = (0, react$1.useMemo)(() => pinnedStreamChoices(webrtc.streams), [webrtc.streams]);
35879
+ const [choiceId, setChoiceId] = (0, react$1.useState)(null);
35880
+ const choice = choices.find((c) => c.id === choiceId) ?? choices[0] ?? null;
35881
+ const [live, setLive] = (0, react$1.useState)(null);
35882
+ const [reports, setReports] = (0, react$1.useState)([]);
35883
+ const [elapsedMs, setElapsedMs] = (0, react$1.useState)(0);
35884
+ /** True from Run until the last policy reported or Stop — the gap between runs included. */
35885
+ const [active, setActive] = (0, react$1.useState)(false);
35886
+ const stateRef = (0, react$1.useRef)(emptySessionRun("all"));
35887
+ const t0Ref = (0, react$1.useRef)(0);
35888
+ const tokenRef = (0, react$1.useRef)(0);
35889
+ const gapTimerRef = (0, react$1.useRef)(null);
35890
+ const elapsed = (0, react$1.useCallback)(() => Math.round(performance.now() - t0Ref.current), []);
35891
+ /** Fold one observation into the CURRENT run; a late event from a closed run is dropped. */
35892
+ const record = (0, react$1.useCallback)((token, event) => {
35893
+ if (token !== tokenRef.current) return;
35894
+ stateRef.current = reduceSessionRun(stateRef.current, event);
35895
+ }, []);
35896
+ const stop = (0, react$1.useCallback)(() => {
35897
+ tokenRef.current += 1;
35898
+ if (gapTimerRef.current !== null) clearTimeout(gapTimerRef.current);
35899
+ gapTimerRef.current = null;
35900
+ setLive(null);
35901
+ setActive(false);
35902
+ }, []);
35903
+ const startRun = (0, react$1.useCallback)((index) => {
35904
+ const policy = POLICIES[index];
35905
+ if (policy === void 0) return;
35906
+ tokenRef.current += 1;
35907
+ stateRef.current = emptySessionRun(policy);
35908
+ t0Ref.current = performance.now();
35909
+ setElapsedMs(0);
35910
+ setLive({
35911
+ index,
35912
+ policy,
35913
+ token: tokenRef.current
35914
+ });
35915
+ }, []);
35916
+ (0, react$1.useEffect)(() => {
35917
+ if (live === null) return;
35918
+ const tick = setInterval(() => setElapsedMs(elapsed()), PROGRESS_TICK_MS);
35919
+ const done = setTimeout(() => {
35920
+ const report = finalizeSessionRun(stateRef.current, elapsed());
35921
+ setReports((prev) => [...prev, report]);
35922
+ tokenRef.current += 1;
35923
+ setLive(null);
35924
+ const next = live.index + 1;
35925
+ if (next < POLICIES.length) gapTimerRef.current = setTimeout(() => startRun(next), RUN_GAP_MS);
35926
+ else setActive(false);
35927
+ }, runMs);
35928
+ return () => {
35929
+ clearInterval(tick);
35930
+ clearTimeout(done);
35931
+ };
35932
+ }, [
35933
+ live,
35934
+ runMs,
35935
+ elapsed,
35936
+ startRun
35937
+ ]);
35938
+ (0, react$1.useEffect)(() => () => {
35939
+ tokenRef.current += 1;
35940
+ if (gapTimerRef.current !== null) clearTimeout(gapTimerRef.current);
35941
+ }, []);
35942
+ const start = (0, react$1.useCallback)(() => {
35943
+ setReports([]);
35944
+ setActive(true);
35945
+ startRun(0);
35946
+ }, [startRun]);
35947
+ const target = choice?.target ?? null;
35948
+ const token = live?.token ?? -1;
35949
+ const handleOffer = (0, react$1.useCallback)(async (sdpOffer, sessionId, hints) => {
35950
+ if (target === null) throw new Error("no stream selected");
35951
+ const res = await webrtc.handleOffer(target, sdpOffer, sessionId, hints);
35952
+ record(token, {
35953
+ kind: "offer-answered",
35954
+ at: elapsed(),
35955
+ sessionId: res.sessionId,
35956
+ sdpAnswer: res.sdpAnswer
35957
+ });
35958
+ return res;
35959
+ }, [
35960
+ target,
35961
+ webrtc,
35962
+ record,
35963
+ token,
35964
+ elapsed
35965
+ ]);
35966
+ const getIceCandidates = (0, react$1.useCallback)(async (sessionId) => {
35967
+ const res = await webrtc.getIceCandidates(sessionId);
35968
+ record(token, {
35969
+ kind: "hub-candidates",
35970
+ at: elapsed(),
35971
+ candidates: res.candidates.map((c) => c.candidate ?? "").filter((c) => c.length > 0),
35972
+ done: res.done
35973
+ });
35974
+ return res;
35975
+ }, [
35976
+ webrtc,
35977
+ record,
35978
+ token,
35979
+ elapsed
35980
+ ]);
35981
+ const onPeerConnection = (0, react$1.useCallback)((pc) => {
35982
+ const seen = /* @__PURE__ */ new WeakSet();
35983
+ pc.addEventListener("iceconnectionstatechange", () => record(token, {
35984
+ kind: "ice-state",
35985
+ at: elapsed(),
35986
+ state: pc.iceConnectionState
35987
+ }));
35988
+ pc.addEventListener("connectionstatechange", () => record(token, {
35989
+ kind: "peer-state",
35990
+ at: elapsed(),
35991
+ state: pc.connectionState
35992
+ }));
35993
+ pc.addEventListener("icecandidate", (e) => {
35994
+ const probed = probedCandidateFromEvent(e, elapsed());
35995
+ if (probed === null) return;
35996
+ record(token, {
35997
+ kind: "local-candidate",
35998
+ at: probed.tMs,
35999
+ candidate: probed.candidate.raw,
36000
+ url: probed.url,
36001
+ relayProtocol: probed.relayProtocol
36002
+ });
36003
+ });
36004
+ pc.addEventListener("track", (e) => {
36005
+ const transport = e.receiver.transport;
36006
+ if (transport === null || seen.has(transport)) return;
36007
+ seen.add(transport);
36008
+ record(token, {
36009
+ kind: "dtls-state",
36010
+ at: elapsed(),
36011
+ state: transport.state
36012
+ });
36013
+ transport.addEventListener("statechange", () => record(token, {
36014
+ kind: "dtls-state",
36015
+ at: elapsed(),
36016
+ state: transport.state
36017
+ }));
36018
+ });
36019
+ }, [
36020
+ record,
36021
+ token,
36022
+ elapsed
36023
+ ]);
36024
+ const onDebugStats = (0, react$1.useCallback)((sample) => record(token, {
36025
+ kind: "sample",
36026
+ at: elapsed(),
36027
+ sample
36028
+ }), [
36029
+ record,
36030
+ token,
36031
+ elapsed
36032
+ ]);
36033
+ const onConnectTiming = (0, react$1.useCallback)((timing) => {
36034
+ if (timing["firstFrameMs"] !== void 0) record(token, {
36035
+ kind: "first-frame",
36036
+ at: elapsed()
36037
+ });
36038
+ }, [
36039
+ record,
36040
+ token,
36041
+ elapsed
36042
+ ]);
36043
+ const progress = live === null ? null : Math.min(100, Math.round(elapsedMs / runMs * 100));
36044
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(SectionCard, {
36045
+ headingId: "webrtc-diag-hub-session",
36046
+ title: "Hub session test",
36047
+ icon: Activity,
36048
+ testId: "webrtc-diag-hub-session",
36049
+ actions: !active ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Button, {
36050
+ onClick: start,
36051
+ disabled: !(deviceId !== null && choice !== null && !active),
36052
+ children: [
36053
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Play, { className: "h-3 w-3" }),
36054
+ "Run test (",
36055
+ String(Math.round(runMs * POLICIES.length / 1e3)),
36056
+ " s)"
36057
+ ]
36058
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Button, {
36059
+ variant: "outline",
36060
+ onClick: stop,
36061
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Square, { className: "h-3 w-3" }), "Stop"]
36062
+ }),
36063
+ children: [
36064
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
36065
+ className: `${SECTION_BODY} space-y-3`,
36066
+ children: [
36067
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
36068
+ className: `grid grid-cols-1 sm:grid-cols-2 ${GRID_GAP}`,
36069
+ children: [cameraField, /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
36070
+ className: "flex min-w-0 flex-col gap-1",
36071
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
36072
+ className: "text-[11px] text-foreground-subtle",
36073
+ children: "Stream (pinned)"
36074
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Select, {
36075
+ value: choice?.id ?? "",
36076
+ disabled: choices.length === 0 || active,
36077
+ onChange: (e) => setChoiceId(e.target.value),
36078
+ options: choices.length === 0 ? [{
36079
+ value: "",
36080
+ label: deviceId === null ? "Pick a camera first" : "No pinned stream"
36081
+ }] : choices.map((c) => ({
36082
+ value: c.id,
36083
+ label: c.label
36084
+ }))
36085
+ })]
36086
+ })]
36087
+ }),
36088
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
36089
+ className: TEXT_HINT,
36090
+ children: "Opens a real live session from this browser twice — first with every candidate type, then TURN relay only — and reads both ends of it."
36091
+ }),
36092
+ live !== null && deviceId !== null && choice !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
36093
+ className: `grid grid-cols-1 sm:grid-cols-[minmax(0,16rem)_1fr] gap-2 sm:gap-3 items-start`,
36094
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
36095
+ className: "aspect-video w-full overflow-hidden rounded-md border border-border bg-black",
36096
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CameraStreamPlayer, {
36097
+ serverUrl,
36098
+ streamKey: `diag-${choice.id}-${live.policy}`,
36099
+ autoPlay: true,
36100
+ muted: true,
36101
+ showControls: false,
36102
+ className: "h-full w-full",
36103
+ handleOffer,
36104
+ getIceServers: webrtc.getIceServers,
36105
+ addIceCandidate: webrtc.addIceCandidate,
36106
+ getIceCandidates,
36107
+ closeSession: webrtc.closeSession,
36108
+ getSessionDebug: webrtc.getSessionDebug,
36109
+ applyDownlinkProbe: webrtc.applyDownlinkProbe,
36110
+ iceTransportPolicy: live.policy,
36111
+ onPeerConnection,
36112
+ onDebugStats,
36113
+ onConnectTiming,
36114
+ onReconnectAttempt: () => record(token, {
36115
+ kind: "reconnect",
36116
+ at: elapsed()
36117
+ }),
36118
+ onError: (message) => record(token, {
36119
+ kind: "error",
36120
+ at: elapsed(),
36121
+ message
36122
+ })
36123
+ }, `${String(live.token)}-${live.policy}`)
36124
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
36125
+ className: "space-y-1.5",
36126
+ "data-testid": "webrtc-diag-progress",
36127
+ children: [
36128
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
36129
+ className: "flex items-center gap-2 text-xs text-foreground",
36130
+ children: [
36131
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LoaderCircle, { className: "h-3 w-3 animate-spin" }),
36132
+ "Run ",
36133
+ String(live.index + 1),
36134
+ " of ",
36135
+ String(POLICIES.length),
36136
+ " ·",
36137
+ " ",
36138
+ POLICY_LABEL[live.policy]
36139
+ ]
36140
+ }),
36141
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
36142
+ className: "h-1.5 w-full overflow-hidden rounded bg-surface-hover",
36143
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
36144
+ className: "h-full bg-primary transition-[width]",
36145
+ style: { width: `${String(progress ?? 0)}%` }
36146
+ })
36147
+ }),
36148
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
36149
+ className: "text-[10px] text-foreground-subtle",
36150
+ children: [
36151
+ String(Math.round(elapsedMs / 1e3)),
36152
+ " s of ",
36153
+ String(Math.round(runMs / 1e3)),
36154
+ " s"
36155
+ ]
36156
+ })
36157
+ ]
36158
+ })]
36159
+ })
36160
+ ]
36161
+ }),
36162
+ reports.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
36163
+ className: `grid grid grid-cols-1 lg:grid-cols-2 gap-2 sm:gap-3 border-t border-border p-2 sm:p-3`,
36164
+ children: reports.map((r, i) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RunReport, {
36165
+ report: r,
36166
+ title: `Run ${String(i + 1)} · ${POLICY_LABEL[r.policy]}`
36167
+ }, `${String(i)}-${r.policy}`))
36168
+ }),
36169
+ reports.length === 0 && !active && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
36170
+ className: `px-3 sm:px-4 py-1.5 sm:py-2 border-t border-border text-[10px] text-foreground-subtle`,
36171
+ children: "No run yet."
36172
+ })
36173
+ ]
36174
+ });
36175
+ }
36176
+ //#endregion
36177
+ //#region src/composites/cap-settings/scene-monitor-copy.ts
36178
+ /** The lighting variants an operator is OFFERED. The resolver can also report
36179
+ * `night`, `dawn` and `dusk`; those are shown when present but never demanded,
36180
+ * because most installs only ever see day and IR. */
36181
+ var SCENE_CAPTURE_VARIANTS = ["day", "ir"];
36182
+ var VARIANT_LABEL = {
36183
+ day: "Daylight",
36184
+ ir: "Night (IR)",
36185
+ night: "Night",
36186
+ dawn: "Dawn",
36187
+ dusk: "Dusk"
36188
+ };
36189
+ function variantLabel(condition) {
36190
+ return VARIANT_LABEL[condition] ?? condition;
36191
+ }
34252
36192
  /**
34253
- * The toggle rule, and the only copy of it.
36193
+ * "Daylight ✓ · Night (IR) ✗ — optional; checks in night (ir) are skipped."
34254
36194
  *
34255
- * none → asc → desc → none, and a click on a DIFFERENT column starts that
34256
- * column fresh at `asc`. `sameColumn` says whether the clicked column is the
34257
- * one currently sorted; `currentDir` is its direction (`null` when nothing is
34258
- * sorted). Returns the next direction, or `null` for "unsorted".
36195
+ * Converts the silent cross-condition fallback this engine used to have into an
36196
+ * operator-visible fact. Without it, a scene with only a daylight reference
36197
+ * simply stops answering after sunset and nothing anywhere says why.
34259
36198
  *
34260
- * Split out from {@link nextTableSort} so the device list — whose sort state
34261
- * keys columns by `columnId`, not `columnKey` — can reuse the rule without a
34262
- * cast and without a second copy of it.
36199
+ * It used to end *"reports 'can't tell' in night (ir)"*, which was accurate and
36200
+ * read as a defect: the operator saw a ✗ and a complaint for a scene that was
36201
+ * configured exactly as they meant it. The missing half is now named as what it
36202
+ * is — the part you do not have to do — and the sentence says what actually
36203
+ * happens instead, which differs by the scene's own policy.
34263
36204
  */
34264
- function nextSortDirection(sameColumn, currentDir) {
34265
- if (!sameColumn || currentDir === null) return "asc";
34266
- return currentDir === "asc" ? "desc" : null;
36205
+ function coverageLine(monitor) {
36206
+ const covered = new Set(monitor.coveredConditions);
36207
+ const parts = SCENE_CAPTURE_VARIANTS.map((v) => `${variantLabel(v)} ${covered.has(v) ? "✓" : "✗"}`);
36208
+ const extra = [...covered].filter((c) => !SCENE_CAPTURE_VARIANTS.some((v) => v === c));
36209
+ for (const c of extra) parts.push(`${variantLabel(c)} ✓`);
36210
+ const missing = SCENE_CAPTURE_VARIANTS.filter((v) => !covered.has(v));
36211
+ if (missing.length === 0) return parts.join(" · ");
36212
+ if (covered.size === 0) return `${parts.join(" · ")} — nothing captured yet, so this scene is not watching.`;
36213
+ const names = missing.map((v) => variantLabel(v).toLowerCase()).join(" and ");
36214
+ return monitor.onUncoveredCondition === "judge-anyway" ? `${parts.join(" · ")} — ${names} judged against the references you do have.` : `${parts.join(" · ")} — optional; checks in ${names} are skipped.`;
34267
36215
  }
34268
36216
  /**
34269
- * Toggle a column's sort on header click: none → asc → desc → none.
34270
- * Clicking a DIFFERENT column starts it fresh at `asc`.
36217
+ * The calm sentence for a scene that is sitting the current light out — `null`
36218
+ * whenever it is checking normally.
36219
+ *
36220
+ * Separate from {@link statusLine} because it is not a verdict and must not
36221
+ * read like one. A paused scene has not failed, has not lost its flag, and
36222
+ * needs nothing from the operator; the only thing worth saying is which light
36223
+ * it is waiting out and that it will pick itself back up.
34271
36224
  */
34272
- function nextTableSort(current, columnKey) {
34273
- const dir = nextSortDirection(current !== null && current.columnKey === columnKey, current === null ? null : current.dir);
34274
- return dir === null ? null : {
34275
- columnKey,
34276
- dir
34277
- };
36225
+ function suspensionLine(monitor) {
36226
+ if (monitor.suspendedCondition === null) return null;
36227
+ const light = variantLabel(monitor.suspendedCondition).toLowerCase();
36228
+ return `Paused — nothing was captured in ${light}, so checks are on hold until the light changes back. Capture ${light} if you want it watched around the clock.`;
34278
36229
  }
36230
+ var UNAVAILABLE_SENTENCE = {
36231
+ "no-reference-for-condition": "can’t tell — nothing has been captured for this scene yet. Press “Capture daylight” to photograph what normal looks like.",
36232
+ "view-shifted": "can’t tell — the camera view has moved since the reference was captured. Re-capture it.",
36233
+ "no-vision-profile": "can’t tell — the vision model is unreachable, so the change is on hold.",
36234
+ "encoder-model-changed": "can’t tell — the embedding model changed, so the stored references are unreadable. Re-capture them.",
36235
+ "no-snapshot": "can’t tell — this camera did not return a frame."
36236
+ };
34279
36237
  /**
34280
- * Ascending comparison of two cell values.
34281
- *
34282
- * Numbers compare numerically and strings compare with `localeCompare` — a
34283
- * numeric column must never be ordered as text ("100" before "9"), and a text
34284
- * column must respect the locale's collation. A mixed column (one row a
34285
- * number, another a string) falls back to string comparison of both, which is
34286
- * the only total order available; it is not a shape any caller should build on
34287
- * purpose.
34288
- *
34289
- * `null` is NOT handled here — {@link sortRowsByColumn} pulls it out first,
34290
- * because its placement is direction-independent and a comparator that is
34291
- * multiplied by the direction factor cannot express that.
36238
+ * The one line under a scene's name. It answers, in order: can it judge, what
36239
+ * does it say, and how long has it said it.
34292
36240
  */
34293
- function compareValues(a, b) {
34294
- if (typeof a === "number" && typeof b === "number") return a - b;
34295
- return String(a).localeCompare(String(b));
36241
+ function statusLine(monitor, now) {
36242
+ if (monitor.states.length === 0) return "Not armed yet — capture the initial state to start watching.";
36243
+ if (monitor.verdict === "unknown") return monitor.unavailable !== null ? UNAVAILABLE_SENTENCE[monitor.unavailable] : "can’t tell right now.";
36244
+ const since = monitor.verdict === "diverged" ? monitor.divergedAt : monitor.armedAt;
36245
+ const held = since !== null ? ` for ${humanDuration(Math.max(0, now - since))}` : "";
36246
+ if (monitor.latched) return monitor.verdict === "diverged" ? `CHANGED${held} — press Reset when you have dealt with it.` : `Back to normal, but still flagged as changed${held}. Press Reset to clear it.`;
36247
+ const paused = suspensionLine(monitor);
36248
+ if (paused !== null) return paused;
36249
+ return monitor.verdict === "diverged" ? `CHANGED${held}` : `Normal${held}`;
34296
36250
  }
34297
- /**
34298
- * Return a NEW array of `rows` ordered by `sort`.
36251
+ /** The badge word. `latched` wins over `verdict`, because the latch is the
36252
+ * thing the operator asked to be told and it outlives the live state.
34299
36253
  *
34300
- * `valueOf` is the column's `sortValue` — it is called once per row per
34301
- * comparison, so it must be cheap (read a field, do not format a string).
34302
- * `sort === null` ⇒ a fresh shallow copy in the incoming order.
34303
- */
34304
- function sortRowsByColumn(rows, sort, valueOf) {
34305
- if (sort === null) return [...rows];
34306
- const factor = sort.dir === "asc" ? 1 : -1;
34307
- return rows.toSorted((a, b) => {
34308
- const av = valueOf(a);
34309
- const bv = valueOf(b);
34310
- if (av === null || bv === null) {
34311
- if (av === bv) return 0;
34312
- return av === null ? 1 : -1;
34313
- }
34314
- return factor * compareValues(av, bv);
34315
- });
36254
+ * A scene sitting out an uncovered light reads `Paused`, in the NEUTRAL tone —
36255
+ * never `alarm`, and never the `danger` variant the page maps that to. A
36256
+ * missing IR reference must not be able to paint a red badge on a scene that
36257
+ * is doing exactly what it was configured to do. */
36258
+ function badgeFor(monitor) {
36259
+ if (monitor.states.length === 0) return {
36260
+ text: "Not armed",
36261
+ tone: "unknown"
36262
+ };
36263
+ if (monitor.latched) return {
36264
+ text: "Changed",
36265
+ tone: "alarm"
36266
+ };
36267
+ if (monitor.suspendedCondition !== null) return {
36268
+ text: "Paused",
36269
+ tone: "unknown"
36270
+ };
36271
+ if (monitor.verdict === "unknown") return {
36272
+ text: "Can’t tell",
36273
+ tone: "unknown"
36274
+ };
36275
+ return monitor.verdict === "diverged" ? {
36276
+ text: "Changed",
36277
+ tone: "alarm"
36278
+ } : {
36279
+ text: "Normal",
36280
+ tone: "ok"
36281
+ };
34316
36282
  }
34317
- /** Derive the `<th>` `aria-sort` for `columnKey` from the table's sort state. */
34318
- function ariaSortForColumn(sort, columnKey) {
34319
- if (sort === null || sort.columnKey !== columnKey) return "none";
34320
- return sort.dir === "asc" ? "ascending" : "descending";
36283
+ /** A rect covering most of the frame is dominated by weather, sky and parked
36284
+ * cars: the bin is 2 % of the pixels and CLIP will not notice it leaving. The
36285
+ * failure is silent INSENSITIVITY, which is the worst kind — hence a warning
36286
+ * rather than a refusal. */
36287
+ var ROI_AREA_WARN_FRACTION = .4;
36288
+ function roiTooLarge(roi) {
36289
+ return roi.width * roi.height > ROI_AREA_WARN_FRACTION;
36290
+ }
36291
+ function humanDuration(ms) {
36292
+ const s = Math.floor(ms / 1e3);
36293
+ if (s < 60) return `${s}s`;
36294
+ const m = Math.floor(s / 60);
36295
+ if (m < 60) return `${m}m`;
36296
+ const h = Math.floor(m / 60);
36297
+ if (h < 48) return `${h}h`;
36298
+ return `${Math.floor(h / 24)}d`;
34321
36299
  }
34322
36300
  //#endregion
34323
- //#region src/composites/data-table.tsx
36301
+ //#region src/composites/code-block.tsx
36302
+ function CodeBlock({ children, maxHeight = 300, className }) {
36303
+ const [copied, setCopied] = (0, react$1.useState)(false);
36304
+ const handleCopy = (0, react$1.useCallback)(() => {
36305
+ navigator.clipboard.writeText(children).then(() => {
36306
+ setCopied(true);
36307
+ setTimeout(() => setCopied(false), 2e3);
36308
+ });
36309
+ }, [children]);
36310
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
36311
+ className: cn("relative group", className),
36312
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(ScrollArea, {
36313
+ style: { maxHeight },
36314
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
36315
+ className: "font-mono text-xs bg-surface p-3 rounded-md border border-border-subtle",
36316
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", { children })
36317
+ })
36318
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
36319
+ className: "absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity",
36320
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(IconButton, {
36321
+ icon: copied ? Check : Copy,
36322
+ "aria-label": "Copy code",
36323
+ variant: "ghost",
36324
+ size: "sm",
36325
+ onClick: handleCopy
36326
+ })
36327
+ })]
36328
+ });
36329
+ }
36330
+ //#endregion
36331
+ //#region src/composites/confirm-action-button.tsx
34324
36332
  /**
34325
- * DataTable — shared responsive table for admin pages.
34326
- *
34327
- * Recipes baked in:
34328
- * - `overflow-x-auto` wrapper so narrow viewports don't clip the
34329
- * right edge (the rounded border survives the scroll).
34330
- * - `min-w-[Npx]` on the inner table so columns don't squash below
34331
- * readable width before the scroll kicks in.
34332
- * - `whitespace-nowrap` on headers — column titles never wrap to
34333
- * two lines (`AUTO-KILL` was the regression that triggered this).
34334
- * - Themed `bg-surface` + `border-border` so contrast works in both
34335
- * light and dark themes.
34336
- *
34337
- * Column model: caller supplies `columns: DataColumn<T>[]` and
34338
- * `rows: T[]`. Each column declares `header`, optional `align`,
34339
- * optional `nowrap`, and a `render(row) => ReactNode` that produces
34340
- * the cell content.
34341
- *
34342
- * <DataTable
34343
- * columns={[
34344
- * { key: 'username', header: 'Username', render: (u) => u.username },
34345
- * { key: 'role', header: 'Role', render: (u) => <RoleBadge .../> },
34346
- * { key: 'actions', header: '', align: 'right', render: (u) => <Actions .../> },
34347
- * ]}
34348
- * rows={users}
34349
- * minWidthPx={560}
34350
- * />
34351
- *
34352
- * If finer header markup is needed, pass `headerRender` instead of
34353
- * `header` (e.g. for a sortable click affordance).
34354
- *
34355
- * ── Narrow viewports ──────────────────────────────────────────────────────
34356
- * The table stays a table. The wrapper is `overflow-x-auto`, so a phone
34357
- * scrolls the columns sideways INSIDE the table — the page body never moves
34358
- * sideways, and the cells stay one line (`whitespace-nowrap`). That is the
34359
- * default (`mobileMode="scroll"`). Cards are opt-in via `mobileMode="cards"`;
34360
- * `auto` still applies the old column-count rule for a surface that wants it.
34361
- * See `resolveTableLayout`.
34362
- *
34363
- * ── Scrolling the BODY, not the page ──────────────────────────────────────
34364
- * `maxBodyHeight` caps the table and scrolls its rows INSIDE the container
34365
- * with the column header pinned. It is ONE prop, not two, because "this list
34366
- * scrolls internally" and "its header stays visible" are the same decision: a
34367
- * capped table whose header scrolls away is a list of unlabelled cells.
36333
+ * ConfirmActionButton — destructive-action button with a modal confirm.
34368
36334
  *
34369
- * Use it wherever the row count is open-ended (rules, targets, delivery
34370
- * history) so the page keeps its own header, filters and actions in view while
34371
- * the operator moves through the rows.
34372
- */
34373
- /**
34374
- * The default cap for an internally-scrolling table.
36335
+ * Two-step UX for any operation operators shouldn't trigger by accident:
36336
+ * reboot device, restart addon, regenerate token, etc. The trigger is a
36337
+ * normal Button that opens a Dialog; confirming runs the async action,
36338
+ * the trigger spinner-disables itself for the duration, and the dialog
36339
+ * closes on success. Errors surface inline at the dialog's bottom.
34375
36340
  *
34376
- * `60vh` leaves the page header, its filters and its actions on screen at
34377
- * every viewport while still showing ~10 rows — and it is a fraction, so it
34378
- * does not need a breakpoint of its own.
36341
+ * Generic on `TResult` so callers don't have to discard the return
36342
+ * value. Pass an `icon` to render it inside the trigger (e.g. RotateCw
36343
+ * for reboot, RefreshCw for restart).
34379
36344
  */
34380
- var TABLE_SCROLL_MAX_H = "max-h-[60vh]";
34381
- var ALIGN_CLASS = {
34382
- left: "text-left",
34383
- right: "text-right",
34384
- center: "text-center"
34385
- };
34386
- function DataTable({ columns, rows, rowKey, onRowClick, minWidthPx = 480, emptyMessage, className, bordered = true, rowClassName, mobileMode = "scroll", maxBodyHeight, defaultSort }) {
34387
- const isNarrow = useIsMobile();
34388
- const [sort, setSort] = (0, react$1.useState)(defaultSort ?? null);
34389
- const layout = resolveTableLayout({
34390
- mode: mobileMode,
34391
- columnCount: columns.length,
34392
- isNarrow
34393
- });
34394
- const scrolls = maxBodyHeight !== void 0;
34395
- const sortedColumn = (0, react$1.useMemo)(() => sort === null ? void 0 : columns.find((col) => col.key === sort.columnKey && col.sortValue !== void 0), [columns, sort]);
34396
- const sortValue = sortedColumn?.sortValue;
34397
- const displayRows = (0, react$1.useMemo)(() => sortValue === void 0 ? rows : sortRowsByColumn(rows, sort, sortValue), [
34398
- rows,
34399
- sort,
34400
- sortValue
34401
- ]);
34402
- const activeSort = sortedColumn === void 0 ? null : sort;
34403
- if (rows.length === 0 && emptyMessage) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
34404
- className: `rounded-lg ${bordered ? "border border-border" : ""} bg-surface px-3 py-4 text-xs text-foreground-subtle text-center ${className ?? ""}`,
34405
- children: emptyMessage
34406
- });
34407
- if (rows.length === 0) return null;
34408
- if (layout === "cards") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
34409
- className: `space-y-2 ${scrolls ? `${maxBodyHeight} overflow-y-auto` : ""} ${className ?? ""}`,
34410
- children: displayRows.map((row, rowIndex) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DataTableCard, {
34411
- row,
34412
- rowIndex,
34413
- columns,
34414
- bordered,
34415
- onRowClick,
34416
- rowClassName
34417
- }, rowKey ? rowKey(row, rowIndex) : rowIndex))
34418
- });
34419
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
34420
- className: [
34421
- "rounded-lg",
34422
- bordered ? "border border-border" : "",
34423
- "bg-surface overflow-x-auto",
34424
- scrolls ? `${maxBodyHeight} overflow-y-auto` : "",
34425
- className ?? ""
34426
- ].filter(Boolean).join(" "),
34427
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("table", {
34428
- className: `w-full text-xs ${scrolls ? "border-separate border-spacing-0" : ""}`,
34429
- style: { minWidth: `${minWidthPx}px` },
34430
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("thead", {
34431
- className: "bg-surface",
34432
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tr", { children: columns.map((col) => {
34433
- const align = col.align ?? "left";
34434
- const nowrap = col.nowrap ?? true;
34435
- const sortable = col.sortValue !== void 0;
34436
- const isSorted = activeSort !== null && activeSort.columnKey === col.key;
34437
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", {
34438
- "aria-sort": sortable ? ariaSortForColumn(activeSort, col.key) : void 0,
34439
- title: sortable ? void 0 : col.notSortableReason,
34440
- className: [
34441
- "px-3 py-2 text-foreground-subtle font-medium bg-surface border-b border-border",
34442
- scrolls ? "sticky top-0 z-10" : "",
34443
- ALIGN_CLASS[align],
34444
- nowrap ? "whitespace-nowrap" : "",
34445
- col.width ?? ""
34446
- ].filter(Boolean).join(" "),
34447
- children: sortable ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SortHeaderButton, {
34448
- label: col.headerRender ? col.headerRender() : col.header,
34449
- active: isSorted,
34450
- dir: isSorted && activeSort !== null ? activeSort.dir : "asc",
34451
- onSort: () => setSort((prev) => nextTableSort(prev, col.key))
34452
- }) : col.headerRender ? col.headerRender() : col.header
34453
- }, col.key);
34454
- }) })
34455
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tbody", { children: displayRows.map((row, rowIndex) => {
34456
- const key = rowKey ? rowKey(row, rowIndex) : rowIndex;
34457
- const extra = rowClassName?.(row, rowIndex) ?? "";
34458
- const interactive = onRowClick !== void 0;
34459
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tr", {
34460
- onClick: interactive ? () => onRowClick(row, rowIndex) : void 0,
34461
- className: [interactive ? "cursor-pointer hover:bg-primary/5" : "hover:bg-primary/5", extra].filter(Boolean).join(" "),
34462
- children: columns.map((col) => {
34463
- const align = col.align ?? "left";
34464
- const nowrap = col.nowrap ?? true;
34465
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", {
34466
- className: [
34467
- "px-3 py-2 text-foreground border-b border-border",
34468
- ALIGN_CLASS[align],
34469
- nowrap ? "whitespace-nowrap" : ""
34470
- ].filter(Boolean).join(" "),
34471
- children: col.render(row, rowIndex)
34472
- }, col.key);
34473
- })
34474
- }, key);
34475
- }) })]
34476
- })
34477
- });
36345
+ function ConfirmActionButton({ label, icon: Icon, title = "Confirm action", description, confirmLabel, triggerVariant = "outline", confirmVariant = "danger", size = "sm", disabled, className, action, onSuccess }) {
36346
+ const [open, setOpen] = (0, react$1.useState)(false);
36347
+ const [running, setRunning] = (0, react$1.useState)(false);
36348
+ const [error, setError] = (0, react$1.useState)(null);
36349
+ const handleConfirm = async () => {
36350
+ setError(null);
36351
+ setRunning(true);
36352
+ try {
36353
+ const result = await action();
36354
+ onSuccess?.(result);
36355
+ setOpen(false);
36356
+ } catch (err) {
36357
+ setError(err instanceof Error ? err.message : String(err));
36358
+ } finally {
36359
+ setRunning(false);
36360
+ }
36361
+ };
36362
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Button, {
36363
+ type: "button",
36364
+ variant: triggerVariant,
36365
+ size,
36366
+ disabled,
36367
+ onClick: () => {
36368
+ setError(null);
36369
+ setOpen(true);
36370
+ },
36371
+ className,
36372
+ children: [Icon && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Icon, { className: "h-3.5 w-3.5" }), label]
36373
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Dialog, {
36374
+ open,
36375
+ onOpenChange: (next) => !running && setOpen(next),
36376
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(DialogContent, { children: [
36377
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(DialogHeader, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(DialogTitle, {
36378
+ className: "flex items-center gap-2",
36379
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(TriangleAlert, { className: "h-4 w-4 text-amber-400" }), title]
36380
+ }), typeof description === "string" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DialogDescription, { children: description }) : description] }),
36381
+ error && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
36382
+ className: cn("mt-2 px-3 py-2 rounded border border-danger/40 bg-danger/10", "text-xs text-danger"),
36383
+ children: error
36384
+ }),
36385
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(DialogFooter, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
36386
+ type: "button",
36387
+ variant: "ghost",
36388
+ size,
36389
+ disabled: running,
36390
+ onClick: () => setOpen(false),
36391
+ children: "Cancel"
36392
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Button, {
36393
+ type: "button",
36394
+ variant: confirmVariant,
36395
+ size,
36396
+ disabled: running,
36397
+ onClick: () => {
36398
+ handleConfirm();
36399
+ },
36400
+ children: [running && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LoaderCircle, { className: "h-3.5 w-3.5 animate-spin" }), confirmLabel ?? label]
36401
+ })] })
36402
+ ] })
36403
+ })] });
34478
36404
  }
36405
+ //#endregion
36406
+ //#region src/composites/copy-button.tsx
34479
36407
  /**
34480
- * One row as a card. Columns that carry a plain-text `header` become labelled
34481
- * `SettingRow`s — the label is the column title and the value gets the full
34482
- * card width. Columns with no text header (an actions column, a
34483
- * `headerRender`-only column) have no label to show, so they render as a
34484
- * full-width strip at the foot of the card.
36408
+ * `CopyButton` — a compact button that copies a string `value` to the
36409
+ * clipboard via `navigator.clipboard.writeText`, showing a brief
36410
+ * "copied" check state. Addon-agnostic; used wherever a secret / URL
36411
+ * needs a one-click copy affordance (export setup panels, etc.).
34485
36412
  */
34486
- function DataTableCard({ row, rowIndex, columns, bordered, onRowClick, rowClassName }) {
34487
- const labelled = columns.filter((col) => col.header !== void 0 && col.header !== "");
34488
- const unlabelled = columns.filter((col) => col.header === void 0 || col.header === "");
34489
- const interactive = onRowClick !== void 0;
34490
- const extra = rowClassName?.(row, rowIndex) ?? "";
34491
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
34492
- "data-data-table-card": "",
34493
- onClick: interactive ? () => onRowClick(row, rowIndex) : void 0,
34494
- className: [
34495
- "rounded-lg bg-surface px-3 py-1.5 divide-y divide-border-subtle",
34496
- bordered ? "border border-border" : "",
34497
- interactive ? "cursor-pointer hover:bg-primary/5" : "",
34498
- extra
34499
- ].filter(Boolean).join(" "),
34500
- children: [labelled.map((col) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SettingRow, {
34501
- label: col.header,
34502
- children: col.render(row, rowIndex)
34503
- }, col.key)), unlabelled.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
34504
- className: "flex flex-wrap items-center justify-end gap-2 py-1.5",
34505
- children: unlabelled.map((col) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { children: col.render(row, rowIndex) }, col.key))
34506
- })]
36413
+ var COPIED_RESET_MS = 2e3;
36414
+ function CopyButton({ value, label, srLabel, className, disabled }) {
36415
+ const [copied, setCopied] = (0, react$1.useState)(false);
36416
+ const handleCopy = (0, react$1.useCallback)(() => {
36417
+ if (!value) return;
36418
+ navigator.clipboard.writeText(value).then(() => {
36419
+ setCopied(true);
36420
+ setTimeout(() => setCopied(false), COPIED_RESET_MS);
36421
+ });
36422
+ }, [value]);
36423
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Button, {
36424
+ size: "sm",
36425
+ variant: "ghost",
36426
+ type: "button",
36427
+ disabled: disabled || value.length === 0,
36428
+ onClick: handleCopy,
36429
+ className: cn(className),
36430
+ "aria-label": copied ? "Copied" : `Copy ${srLabel ?? label ?? "value"}`,
36431
+ children: [copied ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Check, { className: "h-3.5 w-3.5 text-success" }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Copy, { className: "h-3.5 w-3.5" }), label ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
36432
+ className: "ml-1",
36433
+ children: copied ? "Copied" : label
36434
+ }) : null]
34507
36435
  });
34508
36436
  }
34509
36437
  //#endregion
@@ -54170,30 +56098,6 @@ function DoorbellRecentPanel({ history, limit = 5, latestIsFresh, className }) {
54170
56098
  });
54171
56099
  }
54172
56100
  //#endregion
54173
- //#region src/composites/section-card.tsx
54174
- function SectionCard({ headingId, title, icon: Icon, actions, testId, children }) {
54175
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
54176
- "aria-labelledby": headingId,
54177
- className: SECTION_CARD,
54178
- "data-testid": testId,
54179
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("header", {
54180
- className: `${SECTION_HEADER} flex min-h-9 flex-wrap items-center gap-2`,
54181
- children: [
54182
- Icon !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Icon, {
54183
- className: "h-3.5 w-3.5 shrink-0 text-foreground-subtle",
54184
- "aria-hidden": true
54185
- }),
54186
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h2", {
54187
- id: headingId,
54188
- className: `${TEXT_SECTION_LABEL} min-w-0 flex-1`,
54189
- children: title
54190
- }),
54191
- actions
54192
- ]
54193
- }), children]
54194
- });
54195
- }
54196
- //#endregion
54197
56101
  //#region src/composites/filter-bar.tsx
54198
56102
  function FilterBar({ filters, values, onChange, className }) {
54199
56103
  const isMobile = useIsMobile();
@@ -54706,26 +56610,6 @@ function KebabMenu({ items, header, triggerClassName, title = "More actions" })
54706
56610
  });
54707
56611
  }
54708
56612
  //#endregion
54709
- //#region src/composites/key-value-list.tsx
54710
- /**
54711
- * A `<dl>` of label/value rows. Layout (including the L1 stacking) is owned by
54712
- * `SettingRow`; this composite only supplies the description-list semantics.
54713
- *
54714
- * The rows used to be `flex items-center h-7` with a `w-1/3` term, so a label
54715
- * could neither wrap nor stack: on a phone it took a third of the width and
54716
- * the value took whatever was left.
54717
- */
54718
- function KeyValueList({ items, className }) {
54719
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("dl", {
54720
- className: cn("flex flex-col", className),
54721
- children: items.map((item) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SettingRow, {
54722
- elements: "description",
54723
- label: item.key,
54724
- children: item.value
54725
- }, item.key))
54726
- });
54727
- }
54728
- //#endregion
54729
56613
  //#region src/composites/mount-addon-page.tsx
54730
56614
  /**
54731
56615
  * mountAddonPage — one-liner to mount an addon page in dev mode.
@@ -58875,323 +60759,6 @@ function useStationaryOverlay(trpc, deviceId) {
58875
60759
  return query.isError ? void 0 : query.data;
58876
60760
  }
58877
60761
  //#endregion
58878
- //#region src/hooks/turn-server-cache.ts
58879
- /** Short enough that rotated credentials are picked up promptly. */
58880
- var DEFAULT_FRESH_TTL_MS = 5 * 6e4;
58881
- /** Half of the shortest provider credential lifetime in the fleet (24 h). */
58882
- var DEFAULT_STALE_CAP_MS = 720 * 6e4;
58883
- var DEFAULT_STORAGE_KEY = "camstack:turn-servers:v1";
58884
- function defaultStorage() {
58885
- const g = globalThis;
58886
- try {
58887
- return g.localStorage ?? null;
58888
- } catch {
58889
- return null;
58890
- }
58891
- }
58892
- /** Type guard for a persisted entry — storage content is external data. */
58893
- function isCacheEntry(value) {
58894
- if (typeof value !== "object" || value === null) return false;
58895
- const v = value;
58896
- if (typeof v.fetchedAt !== "number" || !Array.isArray(v.servers)) return false;
58897
- return v.servers.every((s) => {
58898
- if (typeof s !== "object" || s === null) return false;
58899
- const srv = s;
58900
- if (!(typeof srv.urls === "string" || Array.isArray(srv.urls) && srv.urls.every((u) => typeof u === "string"))) return false;
58901
- if (srv.username !== void 0 && typeof srv.username !== "string") return false;
58902
- if (srv.credential !== void 0 && typeof srv.credential !== "string") return false;
58903
- return true;
58904
- });
58905
- }
58906
- var TurnServerCache = class {
58907
- freshTtlMs;
58908
- staleCapMs;
58909
- storage;
58910
- now;
58911
- storageKey;
58912
- /** Keyed on the caller's tRPC client object (stable per connected system). */
58913
- memory = /* @__PURE__ */ new WeakMap();
58914
- /** In-flight fetch per key — concurrent callers share one round trip. */
58915
- inflight = /* @__PURE__ */ new WeakMap();
58916
- constructor(options = {}) {
58917
- this.freshTtlMs = options.freshTtlMs ?? DEFAULT_FRESH_TTL_MS;
58918
- this.staleCapMs = options.staleCapMs ?? DEFAULT_STALE_CAP_MS;
58919
- this.storage = "storage" in options ? options.storage ?? null : defaultStorage();
58920
- this.now = options.now ?? (() => Date.now());
58921
- this.storageKey = options.storageKey ?? DEFAULT_STORAGE_KEY;
58922
- }
58923
- /**
58924
- * Resolve the ICE servers for `key`, fetching via `fetch` only when no
58925
- * fresh-enough entry exists. Never rejects: a failed fetch resolves to the
58926
- * stale entry when one exists, else `undefined`.
58927
- */
58928
- async getOrFetch(key, fetch) {
58929
- const at = this.now();
58930
- const entry = this.memory.get(key) ?? this.readStorage();
58931
- if (entry) {
58932
- const age = at - entry.fetchedAt;
58933
- if (age < this.freshTtlMs) return entry.servers;
58934
- if (age < this.staleCapMs) {
58935
- this.startFetch(key, fetch, entry);
58936
- return entry.servers;
58937
- }
58938
- }
58939
- return this.startFetch(key, fetch, entry);
58940
- }
58941
- startFetch(key, fetch, stale) {
58942
- const pending = this.inflight.get(key);
58943
- if (pending) return pending;
58944
- const run = (async () => {
58945
- try {
58946
- const servers = await fetch();
58947
- if (servers.length > 0) {
58948
- const entry = {
58949
- servers,
58950
- fetchedAt: this.now()
58951
- };
58952
- this.memory.set(key, entry);
58953
- this.writeStorage(entry);
58954
- }
58955
- return servers;
58956
- } catch {
58957
- return stale?.servers;
58958
- }
58959
- })().finally(() => {
58960
- this.inflight.delete(key);
58961
- });
58962
- this.inflight.set(key, run);
58963
- return run;
58964
- }
58965
- readStorage() {
58966
- if (!this.storage) return void 0;
58967
- try {
58968
- const raw = this.storage.getItem(this.storageKey);
58969
- if (raw === null) return void 0;
58970
- const parsed = JSON.parse(raw);
58971
- return isCacheEntry(parsed) ? parsed : void 0;
58972
- } catch {
58973
- return;
58974
- }
58975
- }
58976
- writeStorage(entry) {
58977
- if (!this.storage) return;
58978
- try {
58979
- this.storage.setItem(this.storageKey, JSON.stringify(entry));
58980
- } catch {}
58981
- }
58982
- };
58983
- //#endregion
58984
- //#region src/hooks/use-device-webrtc.ts
58985
- /**
58986
- * useDeviceWebrtc — WebRTC signaling hook for device-scoped streaming.
58987
- *
58988
- * Provides `createSession`, `sendAnswer`, `closeSession` callbacks and
58989
- * a `streams` list (Adaptive + High/Mid/Low) for a given device.
58990
- *
58991
- * Works in both admin-ui (BackendClient.trpc) and addon pages
58992
- * (AddonPageProps.trpc) — parametrized by a minimal tRPC proxy shape.
58993
- */
58994
- /**
58995
- * Hook that provides WebRTC signaling callbacks and stream choices for a device.
58996
- *
58997
- * @param trpc - tRPC proxy (admin-ui BackendClient.trpc or addon page trpc)
58998
- * @param deviceId - numeric device ID (null = disabled)
58999
- * @param pollIntervalMs - how often to refresh profile slots (default: 5000)
59000
- */
59001
- /** Module-level TURN/STUN credential cache. Keyed on the caller's trpc client
59002
- * object (stable per connected system — NOT on `trpc.turnProvider`, which is
59003
- * a proxy minted fresh on every property access), so two admin tabs pointed
59004
- * at different hubs never cross-serve credentials from the memory layer; the
59005
- * storage layer is per-origin, and the page's origin IS the hub. Coalesces
59006
- * concurrent fetches (the mount prefetch and the connect's own call used to
59007
- * race into TWO round trips) and persists across page loads so a fresh embed
59008
- * page — one per camera open on native — finds warm credentials instead of
59009
- * re-paying the measured 0.2–3.6 s serialized fetch. See turn-server-cache.ts. */
59010
- var turnServersCache = new TurnServerCache();
59011
- function useDeviceWebrtc(trpc, deviceId, pollIntervalMs = 5e3) {
59012
- const [remoteStreams, setRemoteStreams] = (0, react$1.useState)([]);
59013
- (0, react$1.useEffect)(() => {
59014
- if (deviceId === null) return;
59015
- let cancelled = false;
59016
- const fetch = () => {
59017
- trpc.webrtcSession.listStreams.query({ deviceId }).then((rows) => {
59018
- if (!cancelled) setRemoteStreams(rows);
59019
- }).catch(() => {});
59020
- };
59021
- fetch();
59022
- const iv = setInterval(fetch, pollIntervalMs);
59023
- return () => {
59024
- cancelled = true;
59025
- clearInterval(iv);
59026
- };
59027
- }, [
59028
- trpc,
59029
- deviceId,
59030
- pollIntervalMs
59031
- ]);
59032
- const [pipelineMetrics, setPipelineMetrics] = (0, react$1.useState)(null);
59033
- (0, react$1.useEffect)(() => {
59034
- if (deviceId === null) return;
59035
- let cancelled = false;
59036
- if (trpc.pipelineOrchestrator) trpc.pipelineOrchestrator.getCameraMetrics.query({ deviceId }).then((m) => {
59037
- if (cancelled || !m) return;
59038
- setPipelineMetrics({
59039
- phase: m.phase,
59040
- detectionFps: m.actualFps,
59041
- avgInferenceMs: m.avgInferenceTimeMs,
59042
- droppedFrames: m.droppedFrames
59043
- });
59044
- }).catch(() => {});
59045
- return () => {
59046
- cancelled = true;
59047
- };
59048
- }, [trpc, deviceId]);
59049
- useLiveEvent("pipeline.camera-metrics-snapshot", (evt) => {
59050
- if (deviceId === null) return;
59051
- const payload = evt.data;
59052
- if (payload.deviceId !== deviceId || !payload.metrics) return;
59053
- setPipelineMetrics({
59054
- phase: payload.metrics.phase,
59055
- detectionFps: payload.metrics.actualFps,
59056
- avgInferenceMs: payload.metrics.avgInferenceTimeMs,
59057
- droppedFrames: payload.metrics.droppedFrames
59058
- });
59059
- });
59060
- const { streams, hasWebrtc } = (0, react$1.useMemo)(() => {
59061
- if (deviceId === null || remoteStreams.length === 0) return {
59062
- streams: [],
59063
- hasWebrtc: false
59064
- };
59065
- return {
59066
- streams: remoteStreams.map((r) => ({
59067
- id: r.id,
59068
- label: r.label,
59069
- target: r.target,
59070
- status: r.status,
59071
- inputFps: r.inputFps,
59072
- decodeFps: r.decodeFps,
59073
- bitrateKbps: r.bitrateKbps
59074
- })),
59075
- hasWebrtc: true
59076
- };
59077
- }, [deviceId, remoteStreams]);
59078
- const getIceServers = (0, react$1.useCallback)(async () => {
59079
- const provider = trpc.turnProvider;
59080
- if (!provider) return void 0;
59081
- return turnServersCache.getOrFetch(trpc, async () => {
59082
- return (await provider.getTurnServers.query()).map((s) => {
59083
- return {
59084
- urls: typeof s.urls === "string" ? s.urls : [...s.urls],
59085
- ...s.username !== void 0 ? { username: s.username } : {},
59086
- ...s.credential !== void 0 ? { credential: s.credential } : {}
59087
- };
59088
- });
59089
- });
59090
- }, [trpc]);
59091
- (0, react$1.useEffect)(() => {
59092
- getIceServers();
59093
- }, [getIceServers]);
59094
- const createSession = (0, react$1.useCallback)(async (target, hints) => {
59095
- if (deviceId === null) throw new Error("No device selected");
59096
- const res = await trpc.webrtcSession.createSession.mutate({
59097
- deviceId,
59098
- target,
59099
- hints
59100
- });
59101
- const iceServers = await getIceServers();
59102
- return {
59103
- sessionId: res.sessionId,
59104
- sdpOffer: res.sdpOffer,
59105
- ...iceServers ? { iceServers } : {}
59106
- };
59107
- }, [
59108
- trpc,
59109
- deviceId,
59110
- getIceServers
59111
- ]);
59112
- const handleOffer = (0, react$1.useCallback)(async (target, sdpOffer, sessionId, hints) => {
59113
- if (deviceId === null) throw new Error("No device selected");
59114
- return trpc.webrtcSession.handleOffer.mutate({
59115
- deviceId,
59116
- target,
59117
- sdpOffer,
59118
- ...sessionId !== void 0 ? { sessionId } : {},
59119
- ...hints !== void 0 ? { hints } : {}
59120
- });
59121
- }, [trpc, deviceId]);
59122
- const sendAnswer = (0, react$1.useCallback)(async (sessionId, sdpAnswer) => {
59123
- if (deviceId === null) throw new Error("No device selected");
59124
- await trpc.webrtcSession.handleAnswer.mutate({
59125
- deviceId,
59126
- sessionId,
59127
- sdpAnswer
59128
- });
59129
- }, [trpc, deviceId]);
59130
- return {
59131
- streams,
59132
- hasWebrtc,
59133
- pipelineMetrics,
59134
- createSession,
59135
- handleOffer,
59136
- getIceServers,
59137
- addIceCandidate: (0, react$1.useCallback)(async (sessionId, candidate) => {
59138
- if (deviceId === null) return;
59139
- await trpc.webrtcSession.addIceCandidate.mutate({
59140
- deviceId,
59141
- sessionId,
59142
- candidate: candidate.candidate ?? "",
59143
- sdpMid: candidate.sdpMid ?? null,
59144
- sdpMLineIndex: candidate.sdpMLineIndex ?? null
59145
- }).catch(() => {});
59146
- }, [trpc, deviceId]),
59147
- getIceCandidates: (0, react$1.useCallback)(async (sessionId) => {
59148
- if (deviceId === null) return {
59149
- candidates: [],
59150
- done: true
59151
- };
59152
- return trpc.webrtcSession.getIceCandidates.query({
59153
- deviceId,
59154
- sessionId
59155
- });
59156
- }, [trpc, deviceId]),
59157
- sendAnswer,
59158
- closeSession: (0, react$1.useCallback)(async (sessionId) => {
59159
- if (deviceId === null) return;
59160
- await trpc.webrtcSession.closeSession.mutate({
59161
- deviceId,
59162
- sessionId
59163
- }).catch(() => {});
59164
- }, [trpc, deviceId]),
59165
- getSessionState: (0, react$1.useCallback)(async (sessionId) => {
59166
- if (deviceId === null) return { pendingRenegotiation: null };
59167
- try {
59168
- return await trpc.webrtcSession.getSessionState.query({
59169
- deviceId,
59170
- sessionId
59171
- });
59172
- } catch {
59173
- return { pendingRenegotiation: null };
59174
- }
59175
- }, [trpc, deviceId]),
59176
- getSessionDebug: (0, react$1.useCallback)(async (sessionId) => {
59177
- if (deviceId === null) throw new Error("getSessionDebug: no device bound to this player");
59178
- return trpc.webrtcSession.getSessionDebug.query({
59179
- deviceId,
59180
- sessionId
59181
- });
59182
- }, [trpc, deviceId]),
59183
- applyDownlinkProbe: (0, react$1.useCallback)(async (sessionId, downlinkMbps) => {
59184
- const mutate = trpc.webrtcSession.applyDownlinkProbe;
59185
- if (deviceId === null || mutate === void 0) throw new Error("applyDownlinkProbe: not available for this player");
59186
- return mutate.mutate({
59187
- deviceId,
59188
- sessionId,
59189
- downlinkMbps
59190
- });
59191
- }, [trpc, deviceId])
59192
- };
59193
- }
59194
- //#endregion
59195
60762
  //#region src/hooks/use-doorbell-events.ts
59196
60763
  /**
59197
60764
  * useDoorbellEvents — subscribe to doorbell.onPressed across the cluster.
@@ -59580,6 +61147,8 @@ exports.DummyInline = DummyInline;
59580
61147
  exports.EMPTY_DATA_TABLE_FILTER = EMPTY_DATA_TABLE_FILTER;
59581
61148
  exports.EVENT_KIND_ICONS = EVENT_KIND_ICONS;
59582
61149
  exports.EmptyState = EmptyState;
61150
+ exports.EndpointResultsCard = EndpointResultsCard;
61151
+ exports.EndpointTestCard = EndpointTestCard;
59583
61152
  exports.ErrorBox = ErrorBox;
59584
61153
  exports.EventKindGlyph = EventKindGlyph;
59585
61154
  exports.EventStream = EventStream;
@@ -59604,8 +61173,10 @@ exports.Grid2x2 = Grid2x2;
59604
61173
  exports.GripTrack = GripTrack;
59605
61174
  exports.GroupedModelSelector = GroupedModelSelector;
59606
61175
  exports.HOST_WIDGETS = HOST_WIDGETS;
61176
+ exports.HUB_SESSION_RUN_MS = HUB_SESSION_RUN_MS;
59607
61177
  exports.HlsVideo = HlsVideo;
59608
61178
  exports.HoverZoomImage = HoverZoomImage;
61179
+ exports.HubSessionTestCard = HubSessionTestCard;
59609
61180
  exports.HumidifierHeroCard = HumidifierHeroCard;
59610
61181
  exports.HumidifierInlineControl = HumidifierInlineControl;
59611
61182
  exports.INPUT_COMPACT = INPUT_COMPACT;
@@ -59643,6 +61214,7 @@ exports.MobileDrawer = MobileDrawer;
59643
61214
  exports.ModelPicker = ModelPicker;
59644
61215
  exports.MotionZonesSettings = MotionZonesSettings;
59645
61216
  exports.NAVIGATION_DRIVE_INTERVAL_MS = NAVIGATION_DRIVE_INTERVAL_MS;
61217
+ exports.NatResultCard = NatResultCard;
59646
61218
  exports.NavigationPanel = NavigationPanel;
59647
61219
  exports.NetworkLinkBadge = NetworkLinkBadge;
59648
61220
  exports.NodeMultiSelectField = NodeMultiSelectField;
@@ -59695,6 +61267,7 @@ exports.ResponseLog = ResponseLog;
59695
61267
  exports.RoleDisplayDefaultsFromServer = RoleDisplayDefaultsFromServer;
59696
61268
  exports.RoleDisplayDefaultsProvider = RoleDisplayDefaultsProvider;
59697
61269
  exports.RotateCcw = RotateCcw;
61270
+ exports.RunReport = RunReport;
59698
61271
  exports.SCENE_CAPTURE_VARIANTS = SCENE_CAPTURE_VARIANTS;
59699
61272
  exports.SCENE_CAPTURE_VARIANTS$1 = SCENE_CAPTURE_VARIANTS;
59700
61273
  exports.SECTION_BODY = SECTION_BODY;
@@ -59790,15 +61363,19 @@ exports.applyPickerFilters = applyPickerFilters;
59790
61363
  exports.ariaSortForColumn = ariaSortForColumn;
59791
61364
  exports.badgeFor = badgeFor;
59792
61365
  exports.badgeFor$1 = badgeFor;
61366
+ exports.buildPeerConnectionConfig = buildPeerConnectionConfig;
59793
61367
  exports.buildStepTreeFromSchema = buildStepTreeFromSchema;
59794
61368
  exports.catalogHasDraft = catalogHasDraft;
59795
61369
  exports.childEntityId = childEntityId;
59796
61370
  exports.childListName = childListName;
59797
61371
  exports.chipOverflow = chipOverflow;
61372
+ exports.classifyAddressScope = classifyAddressScope;
59798
61373
  exports.classifyCapability = classifyCapability;
61374
+ exports.classifySessionVerdict = classifySessionVerdict;
59799
61375
  exports.clearPickerGroup = clearPickerGroup;
59800
61376
  exports.cn = cn;
59801
61377
  exports.columnsForContext = columnsForContext;
61378
+ exports.compareSrflxMappings = compareSrflxMappings;
59802
61379
  exports.containerChildToRef = containerChildToRef;
59803
61380
  exports.countableDevices = countableDevices;
59804
61381
  exports.coverHighlight = coverHighlight;
@@ -59826,12 +61403,14 @@ exports.deviceTypeMetaOf = deviceTypeMetaOf;
59826
61403
  exports.devicesToOptions = devicesToOptions;
59827
61404
  exports.draftFromQuery = draftFromQuery;
59828
61405
  exports.emptyDevicesWidens = emptyDevicesWidens;
61406
+ exports.emptySessionRun = emptySessionRun;
59829
61407
  exports.ensureMfHostInit = ensureMfHostInit;
59830
61408
  exports.eventKindLabel = eventKindLabel;
59831
61409
  exports.filterDataTableRows = filterDataTableRows;
59832
61410
  exports.filterDeviceOptions = filterDeviceOptions;
59833
61411
  exports.filterOptionSelectOptions = filterOptions;
59834
61412
  exports.filterPickerDevices = filterPickerDevices;
61413
+ exports.finalizeSessionRun = finalizeSessionRun;
59835
61414
  exports.findTimezone = _camstack_types.findTimezone;
59836
61415
  exports.flattenPickerGrouping = flattenPickerGrouping;
59837
61416
  exports.flattenPickerRows = flattenPickerRows;
@@ -59883,6 +61462,7 @@ exports.orphanDeviceLabel = orphanDeviceLabel;
59883
61462
  exports.overrideEntityIdFromLink = overrideEntityIdFromLink;
59884
61463
  exports.pageRows = pageRows;
59885
61464
  exports.parentDetailOf = parentDetailOf;
61465
+ exports.parseIceCandidate = parseIceCandidate;
59886
61466
  exports.parsePickerGroupBy = parsePickerGroupBy;
59887
61467
  exports.parseRecordedServerMessage = parseRecordedServerMessage;
59888
61468
  exports.partitionOptionSelectSelected = partitionSelected;
@@ -59898,8 +61478,10 @@ exports.pickerQueryTokens = pickerQueryTokens;
59898
61478
  exports.pickerRowFacts = pickerRowFacts;
59899
61479
  exports.pickerSearchText = pickerSearchText;
59900
61480
  exports.pickerZoneFilterSuspended = pickerZoneFilterSuspended;
61481
+ exports.pinnedStreamChoices = pinnedStreamChoices;
59901
61482
  exports.providerIcons = providerIcons;
59902
61483
  exports.readStoredGroupBy = readStoredGroupBy;
61484
+ exports.reduceSessionRun = reduceSessionRun;
59903
61485
  exports.resetHubMountForTests = resetHubMountForTests;
59904
61486
  exports.resetPickerFilters = resetPickerFilters;
59905
61487
  exports.resolveContainerPrimary = resolveContainerPrimary;
@@ -59940,6 +61522,7 @@ exports.statusLine$1 = statusLine;
59940
61522
  exports.stepHasModelForFormat = stepHasModelForFormat;
59941
61523
  exports.stepModelOptions = stepModelOptions;
59942
61524
  exports.stripParentNamePrefix = stripParentNamePrefix;
61525
+ exports.summarizeHubCandidates = summarizeHubCandidates;
59943
61526
  exports.tabForSelector = tabForSelector;
59944
61527
  exports.tankAlert = tankAlert;
59945
61528
  exports.themeToCss = require_theme_index.themeToCss$1;
@@ -60717,7 +62300,7 @@ exports.usePipelineExecutorSpinEngine = usePipelineExecutorSpinEngine;
60717
62300
  exports.usePipelineExecutorUncacheFrame = usePipelineExecutorUncacheFrame;
60718
62301
  exports.usePipelineExecutorUpdateTemplate = usePipelineExecutorUpdateTemplate;
60719
62302
  exports.usePipelineExecutorValidatePipeline = usePipelineExecutorValidatePipeline;
60720
- exports.usePipelineOrchestratorApplyBestSettings = usePipelineOrchestratorApplyBestSettings;
62303
+ exports.usePipelineOrchestratorApplyAutoTune = usePipelineOrchestratorApplyAutoTune;
60721
62304
  exports.usePipelineOrchestratorApplyDeviceSettingsPatch = usePipelineOrchestratorApplyDeviceSettingsPatch;
60722
62305
  exports.usePipelineOrchestratorAssignAudio = usePipelineOrchestratorAssignAudio;
60723
62306
  exports.usePipelineOrchestratorAssignPipeline = usePipelineOrchestratorAssignPipeline;
@@ -60737,6 +62320,7 @@ exports.usePipelineOrchestratorGetCapabilityBindings = usePipelineOrchestratorGe
60737
62320
  exports.usePipelineOrchestratorGetClusterModelChoice = usePipelineOrchestratorGetClusterModelChoice;
60738
62321
  exports.usePipelineOrchestratorGetDeviceLiveContribution = usePipelineOrchestratorGetDeviceLiveContribution;
60739
62322
  exports.usePipelineOrchestratorGetDeviceSettingsContribution = usePipelineOrchestratorGetDeviceSettingsContribution;
62323
+ exports.usePipelineOrchestratorGetEffectiveShares = usePipelineOrchestratorGetEffectiveShares;
60740
62324
  exports.usePipelineOrchestratorGetGlobalMetrics = usePipelineOrchestratorGetGlobalMetrics;
60741
62325
  exports.usePipelineOrchestratorGetIngestOwner = usePipelineOrchestratorGetIngestOwner;
60742
62326
  exports.usePipelineOrchestratorGetNodeInferenceDevices = usePipelineOrchestratorGetNodeInferenceDevices;
@@ -60748,7 +62332,7 @@ exports.usePipelineOrchestratorGetReconcileFromDiskStatus = usePipelineOrchestra
60748
62332
  exports.usePipelineOrchestratorListAgentSettings = usePipelineOrchestratorListAgentSettings;
60749
62333
  exports.usePipelineOrchestratorListTemplates = usePipelineOrchestratorListTemplates;
60750
62334
  exports.usePipelineOrchestratorPauseForStorageMigration = usePipelineOrchestratorPauseForStorageMigration;
60751
- exports.usePipelineOrchestratorPlanBestSettings = usePipelineOrchestratorPlanBestSettings;
62335
+ exports.usePipelineOrchestratorPlanAutoTune = usePipelineOrchestratorPlanAutoTune;
60752
62336
  exports.usePipelineOrchestratorRebalance = usePipelineOrchestratorRebalance;
60753
62337
  exports.usePipelineOrchestratorReconcileFromDisk = usePipelineOrchestratorReconcileFromDisk;
60754
62338
  exports.usePipelineOrchestratorRemoveAgentSettings = usePipelineOrchestratorRemoveAgentSettings;
@@ -60770,6 +62354,7 @@ exports.usePipelineOrchestratorSetCameraSwitch = usePipelineOrchestratorSetCamer
60770
62354
  exports.usePipelineOrchestratorSetCapabilityBinding = usePipelineOrchestratorSetCapabilityBinding;
60771
62355
  exports.usePipelineOrchestratorSetLoadBalancingShares = usePipelineOrchestratorSetLoadBalancingShares;
60772
62356
  exports.usePipelineOrchestratorSetPipelineDevicePin = usePipelineOrchestratorSetPipelineDevicePin;
62357
+ exports.usePipelineOrchestratorSetShareSource = usePipelineOrchestratorSetShareSource;
60773
62358
  exports.usePipelineOrchestratorSuggestShares = usePipelineOrchestratorSuggestShares;
60774
62359
  exports.usePipelineOrchestratorUnassignAudio = usePipelineOrchestratorUnassignAudio;
60775
62360
  exports.usePipelineOrchestratorUnassignPipeline = usePipelineOrchestratorUnassignPipeline;