diff --git a/README.md b/README.md index b780625..d7bc07e 100644 --- a/README.md +++ b/README.md @@ -521,7 +521,7 @@ With these settings, `auto` selects CoreML for SCRFD at 640 px and ArcFace `w600 To run an individual model on CPU, add its label from the `inference` section of `/api/status` to `acceleration.cpu_models`, for example `["face:w600k_r50"]`. The environment equivalent is the comma-separated `KEYSTONE_ACCEL_CPU_MODELS`. -On macOS, `keystone macos setup` starts with `ffmpeg_hwaccel: none` (software decode); set `ffmpeg_hwaccel: auto` to check for VideoToolbox in the configured FFmpeg. On Linux it probes the VA-API device. VideoToolbox samples frames on hardware surfaces, then downloads the selected frames in NV12 or P010 before scaling and JPEG encoding. A camera with a decoder failure falls back to software decode. The dashboard shows each camera's decode backend and the active inference provider for loaded models. Set `ffmpeg_hwaccel: none` to use software decode everywhere. +AI Port decode defaults to `ffmpeg_hwaccel: auto`. On Linux it checks that the configured FFmpeg can initialize VA-API on the render device. If the default `/dev/dri/renderD128` is missing, it checks other accessible render nodes. On macOS, `auto` checks for VideoToolbox in the configured FFmpeg. `keystone macos setup` writes `ffmpeg_hwaccel: none` for new setups. Change it to `auto` to opt in. VideoToolbox samples frames on hardware surfaces, then downloads the selected frames in NV12 or P010 before scaling and JPEG encoding. A camera with a decoder failure falls back to software decode. The dashboard shows each camera's decode backend. Its Acceleration popover shows detected devices, decode readiness, loaded inference providers, and CPU fallbacks. Run `keystone doctor` for local device permissions and driver diagnostics. Set `ffmpeg_hwaccel: none` to use software decode everywhere. Use the [Apple Silicon inference benchmark](docs/macos-inference-benchmark.md) to compare CLIP, detection and caption latency, CPU use and memory on your Mac. diff --git a/config.example.yaml b/config.example.yaml index ce588a4..3a4c956 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -118,7 +118,7 @@ acceleration: # coreml_cache_dir: /state/coreml_cache # Persistent .mlmodelc cache, defaults to /coreml_cache migraphx_precision: FP32 # FP32 | FP16 (AMD MIGraphX) # migraphx_cache_dir: /state/migraphx_cache # Compiled MIGraphX programs, defaults to /migraphx_cache - ffmpeg_hwaccel: none # none | auto | vaapi | videotoolbox (AI Port analyzer decode) + ffmpeg_hwaccel: auto # none | auto | vaapi | videotoolbox (AI Port analyzer decode) ffmpeg_device: /dev/dri/renderD128 # VA-API only # If the GPU context is lost (e.g. an Intel xe engine reset), every GPU model keeps failing until # Keystone restarts. With this on, Keystone exits (code 75) so systemd Restart=on-failure or the diff --git a/src/keystone/acceleration.py b/src/keystone/acceleration.py new file mode 100644 index 0000000..c319c64 --- /dev/null +++ b/src/keystone/acceleration.py @@ -0,0 +1,96 @@ +"""Shared hardware diagnostics for the daemon and doctor.""" + +from __future__ import annotations + +import os +import sys +from typing import TYPE_CHECKING, Any + +from .hw_probe import ( + probe_gpu_device_files, + probe_render_nodes, + probe_vaapi_device, + probe_video_decode, + vaapi_candidates, +) +from .ort_runtime import ( + OPENVINO_EP, + available_providers, + openvino_targets_gpu, + probe_openvino_devices, +) + +if TYPE_CHECKING: + from .config import AccelerationConfig + + +def acceleration_diagnostics(accel: AccelerationConfig, ffmpeg_path: str) -> dict[str, Any]: + nodes = probe_render_nodes() + gpu_nodes = probe_gpu_device_files() + devices = probe_openvino_devices() + providers = available_providers() + mode = accel.ffmpeg_hwaccel + backend, device = probe_video_decode(ffmpeg_path, mode, accel.ffmpeg_device) + hints = [] + + spec = accel.openvino_device.upper() + wants_openvino = accel.provider == "openvino" or (accel.provider == "auto" and OPENVINO_EP in providers) + wants_openvino_gpu = wants_openvino and (spec == "AUTO" or openvino_targets_gpu(spec)) + if accel.provider == "openvino" and OPENVINO_EP not in providers: + hints.append("Install Keystone's OpenVINO extra in the runtime environment to enable the ONNX Runtime provider.") + elif wants_openvino and devices is None: + hints.append("Keystone could not enumerate OpenVINO devices. Check that the OpenVINO Python package can load in the runtime environment.") + + if sys.platform == "linux": + needs_dri = mode == "vaapi" or (accel.provider == "openvino" and wants_openvino_gpu) + if needs_dri and not nodes and not probe_vaapi_device(accel.ffmpeg_device): + hints.append("No /dev/dri render nodes found. Check the host GPU driver and pass the render device through to the container or VM.") + + candidates = vaapi_candidates(mode, accel.ffmpeg_device) + for node in nodes: + decode_needs_node = not backend and (node.path in candidates or (mode == "auto" and not candidates)) + if not node.accessible and (wants_openvino_gpu or decode_needs_node): + hints.append( + f"{node.path} requires read/write access. Give the Keystone process access via " + f"the render node's owning group (GID {node.gid})." + ) + + if ( + wants_openvino_gpu and devices and all(device_id == "CPU" for device_id, _ in devices) + and any(node.accessible and node.vendor == "Intel" for node in nodes) + ): + hints.append( + "OpenVINO sees only CPU despite an accessible Intel render node. " + "Check for intel-opencl-icd or libze-intel-gpu1 in Keystone's runtime environment." + ) + + if not backend: + if any(probe_vaapi_device(path) for path in candidates): + hints.append( + "FFmpeg could not initialize VA-API on an accessible render node. " + "Check FFmpeg's VA-API support and install the matching userspace driver " + "(intel-media-va-driver for recent Intel GPUs or mesa-va-drivers for AMD)." + ) + elif candidates and nodes and not os.path.exists(accel.ffmpeg_device): + hints.append(f"{accel.ffmpeg_device} is missing. Set acceleration.ffmpeg_device to an accessible render node.") + elif mode == "vaapi": + hints.append("Keystone's VA-API decode requires Linux. Set acceleration.ffmpeg_hwaccel to auto to select the platform backend.") + + if (mode == "videotoolbox" or (mode == "auto" and sys.platform == "darwin")) and not backend: + hints.append("VideoToolbox requires macOS and an FFmpeg build that lists videotoolbox in ffmpeg -hwaccels.") + + return { + "openvinoDevices": [{"id": device_id, "name": name} for device_id, name in devices or ()], + "hardware": { + "renderNodes": [ + { + "path": node.path, "accessible": node.accessible, "gid": node.gid, + "vendor": node.vendor, "vendorId": node.vendor_id, "deviceId": node.device_id, + } + for node in nodes + ], + "gpuDeviceFiles": list(gpu_nodes), + "videoDecode": {"ready": backend is not None, "backend": backend or "software", "device": device}, + }, + "diagnostics": hints, + } diff --git a/src/keystone/aiport.py b/src/keystone/aiport.py index 6bba112..95d9f9b 100644 --- a/src/keystone/aiport.py +++ b/src/keystone/aiport.py @@ -72,9 +72,10 @@ from .embedder import Embedder from .face import DetectedFace, FaceRecognizer from .history import HistoryStore +from .hw_probe import probe_vaapi_device as probe_vaapi_device +from .hw_probe import probe_video_decode from .launchd import AIPORT_SOCKET, activated_sockets from .lpr import LPR_LOCK_CONFIDENCE, LicensePlateRecognizer, PlateDetection, PlateVoteTracker -from .ort_runtime import probe_vaapi_device, probe_videotoolbox from .tls import ( PinnedTCPConnector, build_client_ssl_context, @@ -2293,19 +2294,13 @@ async def _record_plate(self, cam: PairedCameraState, plate: PlateDetection) -> plate.confidence, ) - async def _analyzer_hwaccel(self, cam: PairedCameraState) -> str | None: + async def _analyzer_hwaccel(self, cam: PairedCameraState) -> tuple[str | None, str | None]: if cam.hwaccel_disabled: - return None + return None, None accel = self.config.acceleration - if accel.ffmpeg_hwaccel == "vaapi": - return "vaapi" - if accel.ffmpeg_hwaccel in {"auto", "videotoolbox"} and sys.platform == "darwin": - if await asyncio.to_thread(probe_videotoolbox, self.config.ffmpeg_path): - return "videotoolbox" - elif accel.ffmpeg_hwaccel == "auto" and sys.platform == "linux": - if probe_vaapi_device(accel.ffmpeg_device): - return "vaapi" - return None + return await asyncio.to_thread( + probe_video_decode, self.config.ffmpeg_path, accel.ffmpeg_hwaccel, accel.ffmpeg_device + ) def _package_enabled_for(self, cam: PairedCameraState) -> bool: return bool( @@ -2457,7 +2452,7 @@ async def _analyze_camera_loop(self, cam: PairedCameraState) -> None: while self._cameras.get(cam.device_id) is cam: proc: asyncio.subprocess.Process | None = None - hwaccel = await self._analyzer_hwaccel(cam) + hwaccel, vaapi_device = await self._analyzer_hwaccel(cam) frames_this_run = 0 stderr_task = None failure = "" @@ -2469,7 +2464,7 @@ async def _analyze_camera_loop(self, cam: PairedCameraState) -> None: stream_url=cam.stream_url, detect_fps=self.config.aiport.detect_fps, analyze_max_width=self.config.aiport.analyze_max_width, - vaapi_device=self.config.acceleration.ffmpeg_device if hwaccel == "vaapi" else None, + vaapi_device=vaapi_device, hwaccel_backend=hwaccel, videotoolbox_format=videotoolbox_format, ) diff --git a/src/keystone/app.py b/src/keystone/app.py index f1208eb..6d0a3e7 100644 --- a/src/keystone/app.py +++ b/src/keystone/app.py @@ -9,6 +9,7 @@ from aiohttp import web +from .acceleration import acceleration_diagnostics from .aiport import AiPortService from .brand import APP_NAME, APP_VERSION from .config import Config @@ -23,6 +24,7 @@ from .ort_runtime import ( GPU_WATCHDOG, coreml_available, + cuda_available, inference_health, migraphx_available, openvino_available, @@ -115,6 +117,7 @@ def get_status(self) -> dict[str, Any]: vision_auth_error = getattr(self.vision, "auth_error", None) if ai_key else None emb_enabled = ai_key and self.config.embeddings.enabled and self.embedder is not None protect_ai = self.control.protect_ai_settings if self.control else {} + inference = inference_health() return { "app": APP_NAME, "version": APP_VERSION, @@ -165,8 +168,8 @@ def get_status(self) -> dict[str, Any]: "cameras": { cid: cam.name for cid, cam in self.config.cameras.items() if cam.name }, - "acceleration": self._acceleration_status(), - "inference": inference_health(), + "acceleration": self._acceleration_status(inference), + "inference": inference, "faces": self.faces.status() if self.faces else {"enabled": False}, "enhance": self.enhancer.status() if self.enhancer else {"enabled": False}, "stt": self._stt_status(protect_ai), @@ -188,7 +191,7 @@ def get_status(self) -> dict[str, Any]: ), } - def _acceleration_status(self) -> dict[str, Any]: + def _acceleration_status(self, inference: dict[str, dict[str, Any]]) -> dict[str, Any]: accel = self.config.acceleration active: dict[str, str] = {} if self.config.device.enabled and self.config.embeddings.enabled and self.embedder is not None: @@ -230,12 +233,21 @@ def _acceleration_status(self) -> dict[str, Any]: "coremlComputeUnits": accel.coreml_compute_units, "coremlModelFormat": accel.coreml_model_format, "coremlCacheDir": accel.coreml_cache_dir, + "cudaAvailable": cuda_available(), "migraphxAvailable": migraphx_available(), "migraphxPrecision": accel.migraphx_precision, "migraphxCacheDir": accel.migraphx_cache_dir, "ffmpegHwaccel": accel.ffmpeg_hwaccel, "ffmpegDevice": accel.ffmpeg_device, "activeProviders": active, + "fallbacks": { + label: { + "requestedProvider": model["requestedProvider"], + "reason": model["fallbackReason"], + } + for label, model in inference.items() if model["fellBack"] + }, + **acceleration_diagnostics(accel, self.config.ffmpeg_path), "gpuWatchdog": GPU_WATCHDOG.status(), } @@ -445,6 +457,9 @@ async def _on_adopted() -> None: # 2. Start optional status web UI if self.config.web.enabled: + await asyncio.to_thread( + acceleration_diagnostics, self.config.acceleration, self.config.ffmpeg_path, + ) ui_app = create_status_app( self.get_status, lambda: list(self.worker.recent_events) if self.worker else [], diff --git a/src/keystone/config.py b/src/keystone/config.py index dbd3ed7..86446ac 100644 --- a/src/keystone/config.py +++ b/src/keystone/config.py @@ -14,6 +14,7 @@ from .brand import DEFAULT_HOSTNAME, env_var from .homebrew import resolve_tool +from .hw_probe import DEFAULT_VAAPI_DEVICE from .peer_networks import normalize_trusted_peers @@ -144,8 +145,8 @@ class AccelerationConfig: coreml_cache_dir: str = "" # Defaults to /coreml_cache migraphx_precision: str = "FP32" # "FP16" | "FP32" migraphx_cache_dir: str = "" # Defaults to /migraphx_cache - ffmpeg_hwaccel: str = "none" # "none" | "auto" | "vaapi" | "videotoolbox" - ffmpeg_device: str = "/dev/dri/renderD128" + ffmpeg_hwaccel: str = "auto" # "none" | "auto" | "vaapi" | "videotoolbox" + ffmpeg_device: str = DEFAULT_VAAPI_DEVICE # When the GPU context is lost (e.g. an Intel xe engine reset), exit so systemd/Docker # restart Keystone with a fresh one. After gpu_loss_max_restarts such restarts within # gpu_loss_window_minutes, start on the CPU instead to avoid a restart loop. @@ -697,7 +698,7 @@ def validate_acceleration(self) -> None: str(Path(cache_dir).expanduser().resolve() if cache_dir else self.state_dir / default_dir), ) acc.ffmpeg_hwaccel = normalize_ffmpeg_hwaccel(acc.ffmpeg_hwaccel) - acc.ffmpeg_device = (acc.ffmpeg_device or "/dev/dri/renderD128").strip() or "/dev/dri/renderD128" + acc.ffmpeg_device = (acc.ffmpeg_device or "").strip() or DEFAULT_VAAPI_DEVICE acc.restart_on_gpu_loss = ( _as_bool(acc.restart_on_gpu_loss) if isinstance(acc.restart_on_gpu_loss, str) diff --git a/src/keystone/doctor.py b/src/keystone/doctor.py index 7fdbcc3..549e43f 100644 --- a/src/keystone/doctor.py +++ b/src/keystone/doctor.py @@ -19,11 +19,13 @@ import yaml +from .acceleration import acceleration_diagnostics from .config import Config, load_config from .control import ControlService from .homebrew import resolve_tool from .macos_cli import default_config_path from .macos_postgres import PG_ADMIN_URL, PG_EXTENSIONS, PG_PORT, PG_SOCKET +from .ort_runtime import available_providers def _tcp_open(host: str, port: int) -> bool: @@ -256,6 +258,33 @@ def _report_discovery(cfg: Config) -> None: "system services with sudo keystone macos install-daemons.") +def _report_acceleration(cfg: Config) -> None: + report = acceleration_diagnostics(cfg.acceleration, cfg.ffmpeg_path) + hardware = report["hardware"] + print("INFO Hardware acceleration") + if sys.platform == "linux" and not hardware["renderNodes"]: + print("INFO No /dev/dri render nodes detected") + for node in hardware["renderNodes"]: + gpu = " ".join(filter(None, (node["vendor"], node["deviceId"]))) or "unknown GPU" + access = "read/write" if node["accessible"] else "read/write unavailable" + print(f"INFO {gpu} at {node['path']} ({access}, GID {node['gid']})") + for path in hardware["gpuDeviceFiles"]: + vendor = "AMD ROCm" if path == "/dev/kfd" else "NVIDIA" + print(f"INFO {vendor} device detected at {path}") + video = hardware["videoDecode"] + if video["ready"]: + backend = "VA-API" if video["backend"] == "vaapi" else "VideoToolbox" + target = f" on {video['device']}" if video["device"] else "" + print(f"INFO Video decode: {backend} available{target}") + else: + print(f"INFO Video decode: software (ffmpeg_hwaccel={cfg.acceleration.ffmpeg_hwaccel})") + print(f"INFO ONNX Runtime providers: {', '.join(available_providers()) or 'unavailable'}") + devices = ", ".join(f"{dev['id']} ({dev['name']})" for dev in report["openvinoDevices"]) + print(f"INFO OpenVINO devices: {devices or 'none detected'}") + for hint in report["diagnostics"]: + print(f"WARN {hint}") + + def command(path: str | None) -> int: try: cfg = load_config(default_config_path(path)) @@ -270,6 +299,7 @@ def check(label: str, ok: bool) -> None: results.append(ok) check("FFmpeg executable", _probe_process([cfg.ffmpeg_path, "-version"]) is not None) + _report_acceleration(cfg) if cfg.device.enabled: if cfg.device.sync_postgres_password: psql = cfg.device.psql_path or resolve_tool("psql") or "psql" diff --git a/src/keystone/embedder.py b/src/keystone/embedder.py index 5f3e085..453d77f 100644 --- a/src/keystone/embedder.py +++ b/src/keystone/embedder.py @@ -229,7 +229,10 @@ def __init__( self._unload_task: asyncio.Task[None] | None = None self.text_model_loads = 0 self.text_model_unloads = 0 - self._openvino_device: str | None = None + + @property + def _openvino_device(self) -> str | None: + return extract_openvino_device(self.active_provider) @property def ready(self) -> bool: @@ -322,16 +325,20 @@ def _load_clip_session(self, path: Path, *, encoder: str) -> tuple[GuardedSessio feed = {inp.name: mask if "mask" in inp.name.lower() else ids for inp in inputs} if outputs_are_finite(sess.run(None, feed)): return sess, session_provider_label(sess) + reason = "CLIP sanity check produced non-finite output." LOG.warning("CLIP %s on %s produced non-finite output", encoder, provider) except Exception as exc: + reason = f"CLIP sanity check failed: {exc}" LOG.warning("CLIP %s sanity check failed on %s: %s", encoder, provider, exc) - return create_onnx_session( + cpu, active = create_onnx_session( path, threads=self.config.threads, acceleration=self.acceleration, allow_openvino=False, label=f"clip:{encoder}", ) + cpu.record_cpu_fallback(sess.requested_provider or provider, reason) + return cpu, active def _load_vision_session(self) -> GuardedSession: if not self.config.coreai_vision_model or ( @@ -353,7 +360,9 @@ def load_cpu() -> GuardedSession: session = CoreAIVisionSession(Path(self.config.coreai_vision_model), self.config.coreai_python) except Exception as exc: LOG.warning("Could not start Core AI CLIP vision: %s; using CPU", exc) - return load_cpu() + cpu = load_cpu() + cpu.record_cpu_fallback(COREAI_PROVIDER, f"Core AI initialization failed: {exc}") + return cpu return GuardedSession( session, label="clip:vision", provider=COREAI_PROVIDER, cpu_fallback=lambda: load_cpu().wrapped @@ -376,7 +385,6 @@ def _ensure_and_load_sync(self) -> None: vision.close() raise self._vision_sess = vision - self._openvino_device = extract_openvino_device(self.active_provider) LOG.info( "Loaded CLIP ViT-L/14 (ONNX cache=%s, quantization=%s, vision=%s, text=%s, " "provider=%s, threads=%d)", @@ -564,7 +572,6 @@ async def close(self) -> None: self._vision_sess = None self._tokenizer = None self._ready = False - self._openvino_device = None class OllamaTextEmbedder: diff --git a/src/keystone/enhancer.py b/src/keystone/enhancer.py index 65220ca..72f16c5 100644 --- a/src/keystone/enhancer.py +++ b/src/keystone/enhancer.py @@ -355,7 +355,6 @@ def __init__( self.plate_sr = plate_sr self._sr_session: Any | None = None self._sr_failed_at: float | None = None - self.sr_provider = "unloaded" self.model_dir = Path(config.model_dir).expanduser() if config.model_dir else Path(".") self.max_side = int(config.max_output_side) self.quality = int(config.jpeg_quality) @@ -394,6 +393,11 @@ def active_provider(self) -> str: return session_provider_label(session) return "pillow" if self.backend == "pillow" else "unloaded" + @property + def sr_provider(self) -> str: + session = self._sr_session + return session_provider_label(session) if session is not None else "unloaded" + def _load_locked(self) -> Any: if self._session is not None: return self._session @@ -456,7 +460,6 @@ def unload(self) -> bool: def _unload_locked(self) -> bool: count = int(self._session is not None) + int(self._sr_session is not None) self._session = self._sr_session = None - self.sr_provider = "unloaded" self.unloads += count return bool(count) @@ -486,7 +489,7 @@ def _load_plate_sr_locked(self, *, allow_openvino: bool) -> None: PLATE_SR_X4, self.model_dir / PLATE_SR_X4.name, auto_download=bool(self.config.auto_download), ) - self._sr_session, self.sr_provider = create_onnx_session( + self._sr_session, _ = create_onnx_session( path, threads=self.config.threads, acceleration=self.acceleration, allow_openvino=allow_openvino, label="enhance:realesr-general-x4v3", ) @@ -499,12 +502,14 @@ def _run_plate_sr(self, img: Image.Image) -> Image.Image: feeds = {"input": np.ascontiguousarray(tensor)} try: output = self._sr_session.run(None, feeds)[0] - except Exception: + except Exception as exc: # Some OpenVINO devices compile dynamic shapes only on their first run. if not self.sr_provider.startswith(OPENVINO_EP): raise LOG.warning("OpenVINO plate SR inference failed; retrying on CPU", exc_info=True) + requested = self._sr_session.requested_provider self._load_plate_sr_locked(allow_openvino=False) + self._sr_session.record_cpu_fallback(requested, f"Inference failed: {exc}") output = self._sr_session.run(None, feeds)[0] if output.shape != (1, 3, img.height * 4, img.width * 4) or not np.isfinite(output).all(): raise ValueError("Invalid plate super-resolution output") @@ -538,7 +543,6 @@ def _enhance_locked(self, data: bytes, kind: str) -> bytes: self._sr_failed_at = None except Exception as exc: self._sr_session = None - self.sr_provider = "unloaded" self._sr_failed_at = time.monotonic() self.last_error = f"{type(exc).__name__}: {exc}" LOG.warning("Plate SR failed (%s); using Pillow", self.last_error) diff --git a/src/keystone/hw_probe.py b/src/keystone/hw_probe.py new file mode 100644 index 0000000..1713fc1 --- /dev/null +++ b/src/keystone/hw_probe.py @@ -0,0 +1,159 @@ +"""Read-only hardware inventory and FFmpeg decode readiness probes.""" + +from __future__ import annotations + +import os +import subprocess +import sys +import threading +import time +from dataclasses import dataclass +from functools import lru_cache +from pathlib import Path + +DEFAULT_VAAPI_DEVICE = "/dev/dri/renderD128" +_DRI = Path("/dev/dri") +_DRM_SYSFS = Path("/sys/class/drm") +_KFD = Path("/dev/kfd") +_NVIDIA = Path("/dev/nvidia0") +_VENDORS = {"0x8086": "Intel", "0x1002": "AMD", "0x10de": "NVIDIA"} +_VAAPI_LOCK = threading.Lock() +_VAAPI_FAILURE_TTL_S = 60.0 +_VAAPI_CACHE: dict[tuple[str, str], tuple[bool, float]] = {} + + +@dataclass(frozen=True) +class RenderNode: + path: str + accessible: bool + gid: int + vendor_id: str | None + device_id: str | None + + @property + def vendor(self) -> str | None: + return _VENDORS.get(self.vendor_id or "") + + +def _read_pci_id(path: Path) -> str | None: + try: + return path.read_text(encoding="ascii").strip().lower() or None + except (OSError, UnicodeError): + return None + + +@lru_cache(maxsize=1) +def probe_render_nodes() -> tuple[RenderNode, ...]: + if sys.platform != "linux": + return () + try: + paths = sorted(_DRI.glob("renderD*")) + except OSError: + return () + nodes = [] + for path in paths: + try: + gid = path.stat().st_gid + except OSError: + continue + pci = _DRM_SYSFS / path.name / "device" + nodes.append(RenderNode( + str(path), os.access(path, os.R_OK | os.W_OK), gid, + _read_pci_id(pci / "vendor"), _read_pci_id(pci / "device"), + )) + return tuple(nodes) + + +def probe_gpu_device_files() -> tuple[str, ...]: + if sys.platform != "linux": + return () + return tuple(str(path) for path in (_KFD, _NVIDIA) if os.path.exists(path)) + + +def probe_vaapi_device(device: str) -> bool: + """Check read/write access to the configured VA-API render node.""" + return bool(device) and os.path.exists(device) and os.access(device, os.R_OK | os.W_OK) + + +def _probe_vaapi_ffmpeg(ffmpeg_path: str, device: str) -> bool: + if not probe_vaapi_device(device): + return False + key = (ffmpeg_path, device) + now = time.monotonic() + cached = _VAAPI_CACHE.get(key) + if cached is not None: + ok, expires_at = cached + if ok or now < expires_at: + return ok + try: + subprocess.run( + [ + ffmpeg_path, "-hide_banner", "-loglevel", "error", "-nostdin", + "-init_hw_device", f"vaapi=va:{device}", + "-f", "lavfi", "-i", "nullsrc=s=16x16", "-frames:v", "1", "-f", "null", "-", + ], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=5, + check=True, + ) + except (OSError, subprocess.SubprocessError): + if len(_VAAPI_CACHE) >= 16: + _VAAPI_CACHE.clear() + _VAAPI_CACHE[key] = (False, time.monotonic() + _VAAPI_FAILURE_TTL_S) + return False + if len(_VAAPI_CACHE) >= 16: + _VAAPI_CACHE.clear() + _VAAPI_CACHE[key] = (True, float("inf")) + return True + + +def _clear_vaapi_cache() -> None: + with _VAAPI_LOCK: + _VAAPI_CACHE.clear() + + +_probe_vaapi_ffmpeg.cache_clear = _clear_vaapi_cache # type: ignore[attr-defined] + + +def probe_vaapi_ffmpeg(ffmpeg_path: str, device: str) -> bool: + # Lock serializes concurrent misses when cameras start together. + with _VAAPI_LOCK: + return _probe_vaapi_ffmpeg(ffmpeg_path, device) + + +@lru_cache(maxsize=8) +def probe_videotoolbox(ffmpeg_path: str) -> bool: + """Check whether the configured macOS FFmpeg advertises VideoToolbox decode.""" + if sys.platform != "darwin": + return False + try: + result = subprocess.run( + [ffmpeg_path, "-hide_banner", "-hwaccels"], + capture_output=True, + text=True, + timeout=5, + check=True, + ) + except (OSError, subprocess.SubprocessError): + return False + return "videotoolbox" in result.stdout.splitlines() + + +def vaapi_candidates(mode: str, device: str) -> tuple[str, ...]: + if sys.platform != "linux" or mode not in {"auto", "vaapi"}: + return () + if mode == "auto" and device == DEFAULT_VAAPI_DEVICE and not os.path.exists(device): + return tuple(node.path for node in probe_render_nodes() if node.accessible) + return (device,) + + +def probe_video_decode(ffmpeg_path: str, mode: str, device: str) -> tuple[str | None, str | None]: + """Return the available backend and its selected device, if required.""" + if sys.platform == "darwin" and mode in {"auto", "videotoolbox"}: + if probe_videotoolbox(ffmpeg_path): + return "videotoolbox", None + for path in vaapi_candidates(mode, device): + if probe_vaapi_ffmpeg(ffmpeg_path, path): + return "vaapi", path + return None, None diff --git a/src/keystone/macos_cli.py b/src/keystone/macos_cli.py index 9b4d66f..ce169bf 100644 --- a/src/keystone/macos_cli.py +++ b/src/keystone/macos_cli.py @@ -123,6 +123,7 @@ def _setup(args: argparse.Namespace, prefix: Path) -> None: state = data.setdefault("state_dir", str(prefix / "var/lib/keystone")) if not Path(state).expanduser().is_absolute(): raise ValueError("macOS services require an absolute state_dir.") + # Start macOS-managed services with software decoding unless the operator opts in. data.setdefault("acceleration", {}).setdefault("ffmpeg_hwaccel", "none") updated = yaml.safe_dump(data, sort_keys=False) path.parent.mkdir(parents=True, exist_ok=True) diff --git a/src/keystone/ort_runtime.py b/src/keystone/ort_runtime.py index 4595cf5..1f8fe51 100644 --- a/src/keystone/ort_runtime.py +++ b/src/keystone/ort_runtime.py @@ -8,7 +8,6 @@ import os import platform import re -import subprocess import sys import threading import time @@ -19,6 +18,9 @@ from pathlib import Path from typing import TYPE_CHECKING, Any +from .hw_probe import probe_vaapi_device as probe_vaapi_device +from .hw_probe import probe_videotoolbox as probe_videotoolbox + if TYPE_CHECKING: from .config import AccelerationConfig @@ -59,7 +61,7 @@ def normalize_openvino_precision(value: str) -> str: def normalize_ffmpeg_hwaccel(value: str) -> str: - key = str(value or "none").strip().lower() + key = str(value or "auto").strip().lower() if key not in FFMPEG_HWACCEL_MODES: raise ValueError( f"acceleration.ffmpeg_hwaccel must be one of {FFMPEG_HWACCEL_MODES} (got {value!r})" @@ -67,13 +69,17 @@ def normalize_ffmpeg_hwaccel(value: str) -> str: return key -def _provider_available(provider: str) -> bool: +def available_providers() -> tuple[str, ...]: try: import onnxruntime as ort - return provider in (ort.get_available_providers() or ()) + return tuple(ort.get_available_providers() or ()) except Exception: - return False + return () + + +def _provider_available(provider: str) -> bool: + return provider in available_providers() def openvino_available() -> bool: @@ -88,29 +94,28 @@ def migraphx_available() -> bool: return _provider_available(MIGRAPHX_EP) -@lru_cache(maxsize=8) -def probe_videotoolbox(ffmpeg_path: str) -> bool: - """Check whether the configured macOS FFmpeg advertises VideoToolbox decode.""" - if sys.platform != "darwin": - return False - try: - result = subprocess.run( - [ffmpeg_path, "-hide_banner", "-hwaccels"], - capture_output=True, - text=True, - timeout=5, - check=True, - ) - except (OSError, subprocess.SubprocessError): - return False - return "videotoolbox" in result.stdout.splitlines() +def cuda_available() -> bool: + return _provider_available(CUDA_EP) -def probe_vaapi_device(device: str) -> bool: - """Return True if ``device`` exists and is readable and writable for VA-API decode.""" - if not device: - return False - return os.path.exists(device) and os.access(device, os.R_OK | os.W_OK) +@lru_cache(maxsize=1) +def probe_openvino_devices() -> tuple[tuple[str, str], ...] | None: + """Return detected device IDs and names, or None if enumeration failed.""" + try: + from openvino import Core + + core = Core() + ids = core.available_devices + except Exception: + return None + devices = [] + for device_id in ids: + try: + name = core.get_property(device_id, "FULL_DEVICE_NAME") + except Exception: + name = device_id + devices.append((device_id, str(name or device_id))) + return tuple(devices) def extract_openvino_device(provider_label: str) -> str | None: @@ -164,9 +169,7 @@ def _now_ms() -> int: class GuardedSession: """An ``InferenceSession`` that records whether each ``run()`` succeeds. - Everything else is forwarded to the wrapped session, so callers are unchanged. - Before this, an inference error was only a per-call log line: a model that - failed on every call still reported itself ready. + It also tracks CPU fallback. Other methods are forwarded to the wrapped session. """ def __init__( @@ -176,10 +179,14 @@ def __init__( label: str, provider: str = "", cpu_fallback: Callable[[], Any] | None = None, + requested_provider: str = "", + fallback_reason: str | None = None, ) -> None: self._backend = (session, cpu_fallback) self.label = label self.provider = provider + self.requested_provider = requested_provider or provider + self.fallback_reason = fallback_reason[:_MAX_ERROR_CHARS] if fallback_reason else None self.created_at = _now_ms() self.runs = 0 self.failures = 0 @@ -214,7 +221,16 @@ def run(self, *args: Any, **kwargs: Any) -> Any: def _run_with_fallback(self, *args: Any, **kwargs: Any) -> Any: session, cpu_fallback = self._backend if cpu_fallback is None: - return session.run(*args, **kwargs) + try: + return session.run(*args, **kwargs) + finally: + # ORT can replace OpenVINO with its own CPU session during run(). + if self.provider.startswith(OPENVINO_EP) and _session_dropped_openvino(session): + with self._lock: + self.provider = CPU_EP + self.fallback_reason = ( + self.fallback_reason or "ONNX Runtime switched to CPU during inference." + ) try: outputs = session.run(*args, **kwargs) if not outputs_are_finite(outputs): @@ -226,8 +242,19 @@ def _run_with_fallback(self, *args: Any, **kwargs: Any) -> Any: LOG.warning("%s failed on %s: %s; switching to CPU", self.label, self.provider, exc) self._backend = (cpu_fallback(), None) self.provider = CPU_EP + self.fallback_reason = f"Inference failed: {exc}"[:_MAX_ERROR_CHARS] return self.wrapped.run(*args, **kwargs) + @property + def fell_back(self) -> bool: + return self.fallback_reason is not None + + def record_cpu_fallback(self, requested_provider: str, reason: str) -> None: + """Record the reason a caller loaded this CPU session.""" + with self._lock: + self.requested_provider = requested_provider + self.fallback_reason = reason[:_MAX_ERROR_CHARS] + @property def failing(self) -> bool: return self.consecutive_failures >= FAILING_AFTER @@ -262,8 +289,12 @@ def inference_health() -> dict[str, dict[str, Any]]: continue newest_error = max(sessions, key=lambda s: s.last_error_at or 0) newest = max(sessions, key=lambda s: s.created_at) + fallback = max((s for s in sessions if s.fell_back), key=lambda s: s.created_at, default=newest) report[label] = { "provider": newest.provider, + "requestedProvider": fallback.requested_provider, + "fellBack": fallback.fell_back, + "fallbackReason": fallback.fallback_reason, "runs": sum(s.runs for s in sessions), "failures": sum(s.failures for s in sessions), "consecutiveFailures": max(s.consecutive_failures for s in sessions), @@ -305,7 +336,7 @@ def is_device_lost_error(message: str) -> bool: def provider_uses_gpu(provider: str) -> bool: """True when a session label runs on an OpenVINO GPU (or a device list including it).""" device = extract_openvino_device(provider or "") - return bool(device) and "GPU" in device.upper() + return bool(device) and openvino_targets_gpu(device) def exit_for_restart(code: int = GPU_LOSS_EXIT_CODE) -> None: @@ -507,7 +538,7 @@ def _make_session_options(ort: Any, threads: int) -> Any: ) -def _device_targets_gpu(device: str) -> bool: +def openvino_targets_gpu(device: str) -> bool: """Return True if an OpenVINO device spec can schedule work on a GPU.""" for token in re.split(r"[:,]", device or ""): base = token.strip().upper().split(".", 1)[0].split("_", 1)[0] @@ -516,6 +547,36 @@ def _device_targets_gpu(device: str) -> bool: return False +def _resolve_openvino_device(device: str) -> tuple[str | None, str | None]: + """Resolve missing OpenVINO targets before ORT silently selects the CPU.""" + if device.upper() in {"CPU", "AUTO:CPU"}: + return "CPU", None + devices = probe_openvino_devices() + if devices is None: + return device, None + available = {device_id.upper() for device_id, _ in devices} + available |= {device_id.split(".", 1)[0] for device_id in available} + mode, sep, targets = device.upper().partition(":") + if mode == "AUTO" and not sep: + if available.intersection({"GPU", "NPU"}): + return device, None + targets = "CPU" + elif not sep: + targets = mode + requested = [target.strip() for target in targets.split(",")] + matched = [target for target in requested if target.split("_", 1)[0] in available] + if matched and any(target != "CPU" for target in matched): + if mode == "AUTO": + if len(matched) == 1: + return matched[0], None + if len(matched) != len(requested): + return f"AUTO:{','.join(matched)}", None + return device, None + visible = ", ".join(device_id for device_id, _ in devices) or "no devices" + reason = f"OpenVINO found {visible} and no accelerator matching {device}." + return ("CPU" if matched else None), reason + + def _is_load_config_rejection(exc: Exception) -> bool: """Return True when an older OpenVINO/ORT rejected our injected ``load_config``.""" msg = str(exc).lower() @@ -562,7 +623,7 @@ def build_openvino_provider_options( prec = (precision or "").strip().upper() if prec and dev.upper() != "CPU": opts["precision"] = prec - if gpu_large_allocations and _device_targets_gpu(dev): + if gpu_large_allocations and openvino_targets_gpu(dev): opts["load_config"] = _OPENVINO_GPU_LARGE_ALLOCATIONS_CONFIG return opts @@ -632,7 +693,7 @@ def create_onnx_session( allow_cuda: bool = False, allow_migraphx: bool = False, label: str = "", -) -> tuple[Any, str]: +) -> tuple[GuardedSession, str]: """Return a guarded ONNX session and its initial provider label.""" import onnxruntime as ort @@ -645,11 +706,7 @@ def create_onnx_session( ) if tag in getattr(acceleration, "cpu_models", ()): provider_mode = "cpu" - device = ( - (getattr(acceleration, "openvino_device", "AUTO:GPU,CPU") or "AUTO:GPU,CPU").strip() - if acceleration is not None - else "AUTO:GPU,CPU" - ) + device = (getattr(acceleration, "openvino_device", "") or "").strip() or "AUTO:GPU,CPU" cache_dir = ( str(getattr(acceleration, "openvino_cache_dir", "") or "").strip() if acceleration is not None @@ -667,141 +724,136 @@ def create_onnx_session( ) available = list(ort.get_available_providers() or ()) + requested_provider = CPU_EP + fallback_reason = None def create_cpu() -> Any: return ort.InferenceSession( path_str, _make_session_options(ort, n_threads), providers=[CPU_EP] ) - def create_with_cpu_fallback(ep: str, options: dict[str, str]) -> tuple[GuardedSession, str]: - session = ort.InferenceSession( - path_str, - _make_session_options(ort, n_threads), - providers=[ep, CPU_EP], - provider_options=[options, {}], - ) - active = session_provider_label(session) - if active == ep: - session.disable_fallback() - if ep == MIGRAPHX_EP: - session = _SerializedSession(session) - return GuardedSession(session, label=tag, provider=active, cpu_fallback=create_cpu), active - LOG.warning("%s session for %s initialized on %s", ep, tag, active) - return guard_session(session, label=tag, provider=active), active - - if allow_cuda and provider_mode == "cuda" and not GPU_WATCHDOG.suspended: - if CUDA_EP in available: - # Limit arena growth and cuDNN workspace across concurrent model sessions. - cuda_options = { - "arena_extend_strategy": "kSameAsRequested", - "cudnn_conv_algo_search": "HEURISTIC", - "cudnn_conv_use_max_workspace": "0", - } - try: - return create_with_cpu_fallback(CUDA_EP, cuda_options) - except Exception as exc: - LOG.warning("CUDA session init failed for %s: %s; falling back to CPU", tag, exc) + def try_accelerated( + ep: str, options: Callable[[], dict[str, str]], *, usable: bool = True + ) -> tuple[GuardedSession, str] | None: + nonlocal requested_provider, fallback_reason + requested_provider = ep + if not usable or ep not in available: + fallback_reason = f"{ep} is unavailable." + elif GPU_WATCHDOG.suspended and ep != COREML_EP: + fallback_reason = "The GPU watchdog suspended acceleration after repeated device losses." else: - LOG.warning("CUDAExecutionProvider requested for %s but unavailable; using CPU", tag) - - if allow_migraphx and provider_mode == "migraphx" and not GPU_WATCHDOG.suspended: - if MIGRAPHX_EP in available: try: - # Compiles the model for the GPU on first use, which can take minutes - # without a cached program. - return create_with_cpu_fallback(MIGRAPHX_EP, _migraphx_options(acceleration)) + session = ort.InferenceSession( + path_str, + _make_session_options(ort, n_threads), + providers=[ep, CPU_EP], + provider_options=[options(), {}], + ) + active = session_provider_label(session) + if active == ep: + session.disable_fallback() + if ep == MIGRAPHX_EP: + session = _SerializedSession(session) + return GuardedSession(session, label=tag, provider=active, cpu_fallback=create_cpu), active + fallback_reason = f"ONNX Runtime did not activate {ep}." if active == CPU_EP else None + LOG.warning("%s session for %s initialized on %s", ep, tag, active) + return GuardedSession( + session, label=tag, provider=active, requested_provider=ep, + fallback_reason=fallback_reason, + ), active except Exception as exc: - LOG.warning("MIGraphX session init failed for %s: %s; falling back to CPU", tag, exc) - else: - LOG.warning("MIGraphXExecutionProvider requested for %s but unavailable; using CPU", tag) + fallback_reason = f"Session initialization failed: {exc}" + LOG.warning("%s for %s: %s Using CPU.", ep, tag, fallback_reason) + return None + + if allow_cuda and provider_mode == "cuda": + result = try_accelerated(CUDA_EP, lambda: { + # Limit arena growth and cuDNN workspace across concurrent model sessions. + "arena_extend_strategy": "kSameAsRequested", + "cudnn_conv_algo_search": "HEURISTIC", + "cudnn_conv_use_max_workspace": "0", + }) + if result: + return result + + if allow_migraphx and provider_mode == "migraphx": + result = try_accelerated(MIGRAPHX_EP, lambda: _migraphx_options(acceleration)) + if result: + return result want_coreml = allow_coreml and acceleration is not None and ( provider_mode == "coreml" or (provider_mode == "auto" and sys.platform == "darwin" and platform.machine() == "arm64") ) - if want_coreml: - if sys.platform == "darwin" and COREML_EP in available: - try: - coreml_opts = _coreml_options(Path(model_path), acceleration, ort.__version__) - return create_with_cpu_fallback(COREML_EP, coreml_opts) - except Exception as exc: - LOG.warning("CoreML session init failed for %s: %s; falling back to CPU", tag, exc) - elif provider_mode == "coreml": - LOG.warning("CoreMLExecutionProvider requested for %s but unavailable; using CPU", tag) - - want_ov = allow_openvino and provider_mode in {"auto", "openvino"} and not GPU_WATCHDOG.suspended + if want_coreml and (provider_mode == "coreml" or COREML_EP in available): + result = try_accelerated( + COREML_EP, lambda: _coreml_options(Path(model_path), acceleration, ort.__version__), + usable=sys.platform == "darwin", + ) + if result: + return result + + want_ov = allow_openvino and provider_mode in {"auto", "openvino"} + resolved_device = None + if want_ov and (OPENVINO_EP in available or provider_mode == "openvino"): + requested_provider = f"{OPENVINO_EP}({device})" + if GPU_WATCHDOG.suspended: + fallback_reason = "The GPU watchdog suspended acceleration after repeated device losses." + elif OPENVINO_EP not in available: + fallback_reason = f"{OPENVINO_EP} is unavailable." + else: + resolved_device, fallback_reason = _resolve_openvino_device(device) + if fallback_reason: + LOG.warning("%s for %s: %s Using CPU.", OPENVINO_EP, tag, fallback_reason) - if want_ov and OPENVINO_EP in available: + if resolved_device is not None: ov_opts = build_openvino_provider_options( - device=device, + device=resolved_device, cache_dir=cache_dir, precision=precision, threads=n_threads, gpu_large_allocations=gpu_large_allocations, ) - sess: Any = None - retry_without_load_config = False - try: - sess = ort.InferenceSession( - path_str, - _make_session_options(ort, n_threads), - providers=[OPENVINO_EP, CPU_EP], - provider_options=[ov_opts, {}], - ) - if "load_config" in ov_opts and _session_dropped_openvino(sess): - LOG.warning( - "OpenVINO silently fell back to %s for %s with GPU_ENABLE_LARGE_ALLOCATIONS " - "(device=%s, model=%s); retrying OpenVINO without load_config", - session_provider_label(sess), - tag, - ov_opts["device_type"], - Path(model_path).name, - ) - sess = None - retry_without_load_config = True - except Exception as exc: - if "load_config" in ov_opts and _is_load_config_rejection(exc): - LOG.warning( - "OpenVINO rejected GPU_ENABLE_LARGE_ALLOCATIONS for %s (device=%s, model=%s): " - "%s; retrying OpenVINO without load_config", - tag, - ov_opts["device_type"], - Path(model_path).name, - exc, - ) - retry_without_load_config = True - else: - LOG.warning( - "OpenVINO session init failed for %s (device=%s, model=%s): %s; " - "falling back to %s", - tag, - ov_opts["device_type"], - Path(model_path).name, - exc, - CPU_EP, - ) - if retry_without_load_config: - retry_opts = {k: v for k, v in ov_opts.items() if k != "load_config"} + attempts = [ov_opts] + if "load_config" in ov_opts: + attempts.append({key: value for key, value in ov_opts.items() if key != "load_config"}) + for options in attempts: + with_load_config = "load_config" in options try: sess = ort.InferenceSession( path_str, _make_session_options(ort, n_threads), providers=[OPENVINO_EP, CPU_EP], - provider_options=[retry_opts, {}], + provider_options=[options, {}], ) - except Exception as retry_exc: + except Exception as exc: + if with_load_config and _is_load_config_rejection(exc): + LOG.warning( + "OpenVINO rejected GPU_ENABLE_LARGE_ALLOCATIONS for %s (device=%s): " + "%s; retrying OpenVINO without load_config", + tag, resolved_device, exc, + ) + continue + fallback_reason = f"OpenVINO session initialization failed: {exc}" LOG.warning( - "OpenVINO session init failed for %s (device=%s, model=%s): %s; " - "falling back to %s", - tag, - retry_opts["device_type"], - Path(model_path).name, - retry_exc, - CPU_EP, + "OpenVINO session init failed for %s (device=%s): %s; falling back to %s", + tag, resolved_device, exc, CPU_EP, ) - if sess is not None: + break + if with_load_config and _session_dropped_openvino(sess): + LOG.warning( + "OpenVINO silently fell back to %s for %s with GPU_ENABLE_LARGE_ALLOCATIONS " + "(device=%s); retrying OpenVINO without load_config", + session_provider_label(sess), tag, resolved_device, + ) + continue active = session_provider_label(sess, openvino_device=ov_opts["device_type"]) - sess = guard_session(sess, label=tag, provider=active) + if active == CPU_EP: + fallback_reason = fallback_reason or "ONNX Runtime initialized the OpenVINO session on CPU." + sess = GuardedSession( + sess, label=tag, provider=active, requested_provider=requested_provider, + fallback_reason=fallback_reason, + ) LOG.debug( "Created ONNX session for %s using %s (threads=%d, cache=%s)", tag, @@ -810,15 +862,8 @@ def create_with_cpu_fallback(ep: str, options: dict[str, str]) -> tuple[GuardedS ov_opts.get("cache_dir", "disabled"), ) return sess, active - elif want_ov and provider_mode == "openvino": - LOG.warning( - "OpenVINOExecutionProvider requested for %s but unavailable (available=%s); " - "falling back to %s", - tag, - available, - CPU_EP, - ) - sess = create_cpu() - active = session_provider_label(sess) - return guard_session(sess, label=tag, provider=active), active + return GuardedSession( + create_cpu(), label=tag, provider=CPU_EP, requested_provider=requested_provider, + fallback_reason=fallback_reason, + ), CPU_EP diff --git a/src/keystone/stt.py b/src/keystone/stt.py index 0659e3f..f741330 100644 --- a/src/keystone/stt.py +++ b/src/keystone/stt.py @@ -43,7 +43,7 @@ import numpy as np from .config import AccelerationConfig, SttConfig -from .ort_runtime import CPU_EP, OPENVINO_EP, create_onnx_session +from .ort_runtime import CPU_EP, OPENVINO_EP, create_onnx_session, session_provider_label LOG = logging.getLogger(__name__) @@ -589,14 +589,20 @@ def __init__( self._ready = False self._prepare_lock = asyncio.Lock() self._run_lock = threading.Lock() - self.encoder_provider: str = "unloaded" - self.decoder_provider: str = "unloaded" self.decoder_quantization: str | None = None self.last_error: str | None = None self.transcriptions = 0 self.last_elapsed_ms = 0 self.total_elapsed_ms = 0 + @property + def encoder_provider(self) -> str: + return session_provider_label(self._encoder) if self._encoder is not None else "unloaded" + + @property + def decoder_provider(self) -> str: + return session_provider_label(self._decoder) if self._decoder is not None else "unloaded" + # ---- files --------------------------------------------------------------------------- @property def files(self) -> tuple[str, ...]: @@ -616,14 +622,15 @@ def _ensure_files_sync(self) -> None: for rel in self.files: self._ensure_file(rel) - def _load_cpu_decoder(self, path: Path, threads: int) -> tuple[Any, str]: - return create_onnx_session( + def _load_cpu_decoder(self, path: Path, threads: int) -> Any: + session, _ = create_onnx_session( path, threads=threads, acceleration=self.acceleration, allow_openvino=False, label=f"stt:{self.model}:decoder", ) + return session def _load_sync(self) -> None: self._ensure_files_sync() @@ -633,7 +640,7 @@ def _load_sync(self) -> None: threads = max(1, int(self.config.threads)) # Static-shape encoder may use OpenVINO with automatic CPU fallback; merged KV-cache # decoder has dynamic past-length axes and stays on CPUExecutionProvider. - self._encoder, self.encoder_provider = create_onnx_session( + self._encoder, _ = create_onnx_session( enc_path, threads=threads, acceleration=self.acceleration, @@ -652,7 +659,7 @@ def _load_sync(self) -> None: self.model, ) try: - self._decoder, self.decoder_provider = self._load_cpu_decoder(dec_path, threads) + self._decoder = self._load_cpu_decoder(dec_path, threads) self.decoder_quantization = self.quantization except Exception as exc: # Some fp16 exports return an outer-scope value directly from an If branch. @@ -664,7 +671,7 @@ def _load_sync(self) -> None: self.model, exc, ) _, rel = whisper_model_files("fp32") - self._decoder, self.decoder_provider = self._load_cpu_decoder(self._ensure_file(rel), threads) + self._decoder = self._load_cpu_decoder(self._ensure_file(rel), threads) self.decoder_quantization = "fp32" self._tokenizer = Tokenizer.from_file(str(self.model_dir / "tokenizer.json")) gen = json.loads((self.model_dir / "generation_config.json").read_text(encoding="utf-8")) @@ -755,8 +762,6 @@ async def close(self) -> None: self._encoder = None self._decoder = None self._ready = False - self.encoder_provider = "unloaded" - self.decoder_provider = "unloaded" self.decoder_quantization = None # ---- inference ----------------------------------------------------------------------- diff --git a/src/keystone/ui/index.html b/src/keystone/ui/index.html index 192c9ca..1b3672a 100644 --- a/src/keystone/ui/index.html +++ b/src/keystone/ui/index.html @@ -75,9 +75,9 @@ - less than the value passed to \`max\` (or ${Wd} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. -Defaulting to \`null\`.`}Hd(af,`getInvalidValueError`);var of=Object.defineProperty,sf=(e,t)=>of(e,`name`,{value:t,configurable:!0}),cf={Horizontal:`horizontal`,Vertical:`vertical`},lf=cf.Horizontal,uf=Object.values(cf),df=_.forwardRef(sf(function(e,t){let{decorative:n,orientation:r=lf,...i}=e,a=ff(r)?r:lf,o=a===cf.Vertical?a:void 0,s=n?{role:`none`}:{"aria-orientation":o,role:`separator`};return(0,z.jsx)(B.div,{"data-orientation":a,...s,...i,ref:t})},`Separator`));function ff(e){return uf.includes(e)}sf(ff,`isValidOrientation`);var pf=Object.defineProperty,mf=(e,t)=>pf(e,`name`,{value:t,configurable:!0}),hf=`Toggle`,gf=_.forwardRef(mf(function(e,t){let{pressed:n,defaultPressed:r,onPressedChange:i,...a}=e,[o,s]=vr({prop:n,onChange:i,defaultProp:r??!1,caller:hf});return(0,z.jsx)(B.button,{type:`button`,"aria-pressed":o,"data-state":o?`on`:`off`,"data-disabled":e.disabled?``:void 0,...a,ref:t,onClick:V(e.onClick,()=>{e.disabled||s(!o)})})},`Toggle`)),_f=Object.defineProperty,vf=(e,t)=>_f(e,`name`,{value:t,configurable:!0}),yf=`ToggleGroup`,bf={Single:`single`,Multiple:`multiple`},[xf,Sf]=Bn(yf,[Bl]),Cf=Bl(),wf=_.forwardRef(vf(function(e,t){let{type:n,...r}=e;if(n===bf.Single)return(0,z.jsx)(Df,{role:`radiogroup`,...r,ref:t});if(n===bf.Multiple)return(0,z.jsx)(Of,{role:`toolbar`,...r,ref:t});throw Error(`Missing prop \`type\` expected on \`${yf}\``)},`ToggleGroup`)),[Tf,Ef]=xf(yf),Df=_.forwardRef(vf(function(e,t){let{value:n,defaultValue:r,onValueChange:i=vf(()=>{},`onValueChange`),...a}=e,[o,s]=vr({prop:n,defaultProp:r??``,onChange:i,caller:yf});return(0,z.jsx)(Tf,{scope:e.__scopeToggleGroup,type:bf.Single,value:_.useMemo(()=>o?[o]:[],[o]),onItemActivate:s,onItemDeactivate:_.useCallback(()=>s(``),[s]),children:(0,z.jsx)(jf,{...a,ref:t})})},`ToggleGroupImplSingle`)),Of=_.forwardRef(vf(function(e,t){let{value:n,defaultValue:r,onValueChange:i=vf(()=>{},`onValueChange`),...a}=e,[o,s]=vr({prop:n,defaultProp:r??[],onChange:i,caller:yf}),c=_.useCallback(e=>s((t=[])=>[...t,e]),[s]),l=_.useCallback(e=>s((t=[])=>t.filter(t=>t!==e)),[s]);return(0,z.jsx)(Tf,{scope:e.__scopeToggleGroup,type:bf.Multiple,value:o,onItemActivate:c,onItemDeactivate:l,children:(0,z.jsx)(jf,{...a,ref:t})})},`ToggleGroupImplMultiple`)),[kf,Af]=xf(yf),jf=_.forwardRef(vf(function(e,t){let{__scopeToggleGroup:n,disabled:r=!1,rovingFocus:i=!0,orientation:a,dir:o,loop:s=!0,...c}=e,l=Cf(n),u=ti(o),d={dir:u,...c};return(0,z.jsx)(kf,{scope:n,rovingFocus:i,disabled:r,children:i?(0,z.jsx)(Gl,{asChild:!0,...l,orientation:a,dir:u,loop:s,children:(0,z.jsx)(B.div,{...d,ref:t})}):(0,z.jsx)(B.div,{...d,ref:t})})},`ToggleGroupImpl`)),Mf=`ToggleGroupItem`,Nf=_.forwardRef(vf(function(e,t){let n=Ef(Mf,e.__scopeToggleGroup),r=Af(Mf,e.__scopeToggleGroup),i=Cf(e.__scopeToggleGroup),a=n.value.includes(e.value),o=r.disabled||e.disabled,s={...e,pressed:a,disabled:o},c=_.useRef(null);return r.rovingFocus?(0,z.jsx)(Jl,{asChild:!0,...i,focusable:!o,active:a,ref:c,children:(0,z.jsx)(Pf,{...s,ref:t})}):(0,z.jsx)(Pf,{...s,ref:t})},`ToggleGroupItem`)),Pf=_.forwardRef(vf(function(e,t){let{__scopeToggleGroup:n,value:r,...i}=e,a=Ef(Mf,n),o={role:`radio`,"aria-checked":e.pressed,"aria-pressed":void 0},s=a.type===bf.Single?o:void 0;return(0,z.jsx)(gf,{...s,...i,ref:t,onPressedChange:e=>{e?a.onItemActivate(r):a.onItemDeactivate(r)}})},`ToggleGroupItemImpl`)),Ff=Object.defineProperty,If=(e,t)=>Ff(e,`name`,{value:t,configurable:!0}),[Lf,Rf]=Bn(`Tooltip`,[sl]),zf=sl(),Bf=`TooltipProvider`,Vf=700,Hf=`tooltip.open`,[Uf,X]=Lf(Bf),Wf=If(e=>{let{__scopeTooltip:t,delayDuration:n=Vf,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:a}=e,o=_.useRef(!0),s=_.useRef(!1),c=_.useRef(0);return _.useEffect(()=>{let e=c.current;return()=>window.clearTimeout(e)},[]),(0,z.jsx)(Uf,{scope:t,isOpenDelayedRef:o,delayDuration:n,onOpen:_.useCallback(()=>{r<=0||(window.clearTimeout(c.current),o.current=!1)},[r]),onClose:_.useCallback(()=>{r<=0||(window.clearTimeout(c.current),c.current=window.setTimeout(()=>o.current=!0,r))},[r]),isPointerInTransitRef:s,onPointerInTransitChange:_.useCallback(e=>{s.current=e},[]),disableHoverableContent:i,children:a})},`TooltipProvider`),Gf=`Tooltip`,[Kf,qf]=Lf(Gf),Jf=If(e=>{let{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:a,disableHoverableContent:o,delayDuration:s}=e,c=X(Gf,e.__scopeTooltip),l=zf(t),[u,d]=_.useState(null),[f,p]=_.useState(void 0),m=Ir(),h=_.useRef(0),g=o??c.disableHoverableContent,v=s??c.delayDuration,y=_.useRef(!1),[b,x]=vr({prop:r,defaultProp:i??!1,onChange:If(e=>{e?(c.onOpen(),document.dispatchEvent(new CustomEvent(Hf))):c.onClose(),a?.(e)},`onChange`),caller:Gf}),S=_.useMemo(()=>b?y.current?`delayed-open`:`instant-open`:`closed`,[b]),C=_.useCallback(()=>{window.clearTimeout(h.current),h.current=0,y.current=!1,x(!0)},[x]),w=_.useCallback(()=>{window.clearTimeout(h.current),h.current=0,x(!1)},[x]),T=_.useCallback(()=>{window.clearTimeout(h.current),h.current=window.setTimeout(()=>{y.current=!0,x(!0),h.current=0},v)},[v,x]);_.useEffect(()=>()=>{h.current&&=(window.clearTimeout(h.current),0)},[]);let E=f??m;return(0,z.jsx)(ul,{...l,children:(0,z.jsx)(Kf,{scope:t,contentId:E,setContentId:p,open:b,stateAttribute:S,trigger:u,onTriggerChange:d,onTriggerEnter:_.useCallback(()=>{c.isOpenDelayedRef.current?T():C()},[c.isOpenDelayedRef,T,C]),onTriggerLeave:_.useCallback(()=>{g?w():(window.clearTimeout(h.current),h.current=0)},[w,g]),onOpen:C,onClose:w,disableHoverableContent:g,children:n})})},`Tooltip`),Yf=`TooltipTrigger`,Xf=_.forwardRef(If(function(e,t){let{__scopeTooltip:n,"aria-describedby":r,...i}=e,a=qf(Yf,n),o=X(Yf,n),s=zf(n),c=R(t,_.useRef(null),a.onTriggerChange),l=_.useRef(!1),u=_.useRef(!1),d=_.useCallback(()=>l.current=!1,[]);return _.useEffect(()=>()=>document.removeEventListener(`pointerup`,d),[d]),(0,z.jsx)(fl,{asChild:!0,...s,children:(0,z.jsx)(B.button,{"aria-describedby":a.open?pp(r,a.contentId):r,"data-state":a.stateAttribute,...i,ref:c,onPointerMove:V(e.onPointerMove,e=>{e.pointerType!==`touch`&&!u.current&&!o.isPointerInTransitRef.current&&(a.onTriggerEnter(),u.current=!0)}),onPointerLeave:V(e.onPointerLeave,()=>{a.onTriggerLeave(),u.current=!1}),onPointerDown:V(e.onPointerDown,()=>{a.open&&a.onClose(),l.current=!0,document.addEventListener(`pointerup`,d,{once:!0})}),onFocus:V(e.onFocus,()=>{l.current||a.onOpen()}),onBlur:V(e.onBlur,a.onClose),onClick:V(e.onClick,a.onClose)})})},`TooltipTrigger`)),Zf=`TooltipPortal`,[Qf,$f]=Lf(Zf,{forceMount:void 0}),ep=If(e=>{let{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,a=qf(Zf,t);return(0,z.jsx)(Qf,{scope:t,forceMount:n,children:(0,z.jsx)(Er,{present:n||a.open,children:(0,z.jsx)(Hi,{asChild:!0,container:i,children:r})})})},`TooltipPortal`),tp=`TooltipContent`,np=_.forwardRef(If(function(e,t){let n=$f(tp,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i=`top`,...a}=e,o=qf(tp,e.__scopeTooltip);return(0,z.jsx)(Er,{present:r||o.open,children:o.disableHoverableContent?(0,z.jsx)(ap,{side:i,...a,ref:t}):(0,z.jsx)(rp,{side:i,...a,ref:t})})},`TooltipContent`)),rp=_.forwardRef(If(function(e,t){let n=qf(tp,e.__scopeTooltip),r=X(tp,e.__scopeTooltip),i=_.useRef(null),a=R(t,i),[o,s]=_.useState(null),{trigger:c,onClose:l}=n,u=i.current,{onPointerInTransitChange:d}=r,f=_.useCallback(()=>{s(null),d(!1)},[d]),p=_.useCallback((e,t)=>{let n=e.currentTarget,r={x:e.clientX,y:e.clientY},i=cp(r,sp(r,n.getBoundingClientRect())),a=lp(t.getBoundingClientRect()),o=dp([...i,...a]);s(o),d(!0)},[d]);return _.useEffect(()=>()=>f(),[f]),_.useEffect(()=>{if(c&&u){let e=If(e=>p(e,u),`handleTriggerLeave`),t=If(e=>p(e,c),`handleContentLeave`);return c.addEventListener(`pointerleave`,e),u.addEventListener(`pointerleave`,t),()=>{c.removeEventListener(`pointerleave`,e),u.removeEventListener(`pointerleave`,t)}}},[c,u,p,f]),_.useEffect(()=>{if(o){let e=If(e=>{let t=e.target,n={x:e.clientX,y:e.clientY},r=c?.contains(t)||u?.contains(t),i=!up(n,o);r?f():i&&(f(),l())},`handleTrackPointerGrace`);return document.addEventListener(`pointermove`,e),()=>document.removeEventListener(`pointermove`,e)}},[c,u,o,l,f]),(0,z.jsx)(ap,{...e,ref:a})},`TooltipContentHoverable`)),ip=mn(`TooltipContent`),ap=_.forwardRef(If(function(e,t){let{__scopeTooltip:n,children:r,"aria-label":i,id:a,onEscapeKeyDown:o,onPointerDownOutside:s,...c}=e,l=qf(tp,n),u=zf(n),{onClose:d}=l,[f,p]=_.useState(null),m=R(t,p);ki(f),_.useEffect(()=>(document.addEventListener(Hf,d),()=>document.removeEventListener(Hf,d)),[d]),_.useEffect(()=>{if(l.trigger){let e=If(e=>{e.target instanceof Node&&e.target.contains(l.trigger)&&d()},`handleScroll`);return window.addEventListener(`scroll`,e,{capture:!0}),()=>window.removeEventListener(`scroll`,e,{capture:!0})}},[l.trigger,d]);let{setContentId:h}=l;return Hn(()=>(h(a),()=>{h(void 0)}),[a,h]),(0,z.jsx)(pi,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:e=>e.preventDefault(),onDismiss:d,children:(0,z.jsxs)(gl,{"data-state":l.stateAttribute,role:i?void 0:`tooltip`,id:i?void 0:l.contentId,...u,...c,ref:m,style:{...c.style,"--radix-tooltip-content-transform-origin":`var(--radix-popper-transform-origin)`,"--radix-tooltip-content-available-width":`var(--radix-popper-available-width)`,"--radix-tooltip-content-available-height":`var(--radix-popper-available-height)`,"--radix-tooltip-trigger-width":`var(--radix-popper-anchor-width)`,"--radix-tooltip-trigger-height":`var(--radix-popper-anchor-height)`},children:[(0,z.jsx)(ip,{children:r}),i?(0,z.jsx)(In,{id:l.contentId,role:`tooltip`,children:i}):null]})})},`TooltipContentImpl`)),op=_.forwardRef(If(function(e,t){let{__scopeTooltip:n,...r}=e,i=zf(n);return(0,z.jsx)(yl,{...i,...r,ref:t})},`TooltipArrow`));function sp(e,t){let n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),a=Math.abs(t.left-e.x);switch(Math.min(n,r,i,a)){case a:return`left`;case i:return`right`;case n:return`top`;case r:return`bottom`;default:throw Error(`unreachable`)}}If(sp,`getExitSideFromRect`);function cp(e,t,n=5){let r=[];switch(t){case`top`:r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case`bottom`:r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case`left`:r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case`right`:r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n})}return r}If(cp,`getPaddedExitPoints`);function lp(e){let{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}If(lp,`getPointsFromRect`);function up(e,t){let{x:n,y:r}=e,i=!1;for(let e=0,a=t.length-1;er!=d>r&&n<(u-c)*(r-l)/(d-l)+c&&(i=!i)}return i}If(up,`isPointInPolygon`);function dp(e){let t=e.slice();return t.sort((e,t)=>e.xt.x?1:e.yt.y)),fp(t)}If(dp,`getHull`);function fp(e){if(e.length<=1)return e.slice();let t=[];for(let n=0;n=2;){let e=t[t.length-1],n=t[t.length-2];if((e.x-n.x)*(r.y-n.y)>=(e.y-n.y)*(r.x-n.x))t.pop();else break}t.push(r)}t.pop();let n=[];for(let t=e.length-1;t>=0;t--){let r=e[t];for(;n.length>=2;){let e=n[n.length-1],t=n[n.length-2];if((e.x-t.x)*(r.y-t.y)>=(e.y-t.y)*(r.x-t.x))n.pop();else break}n.push(r)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}If(fp,`getHullPresorted`);function pp(...e){let t=new Set;for(let n of e)if(typeof n==`string`)for(let e of String(n).trim().split(/\s+/))e&&t.add(e);return t.size>0?Array.from(t).join(` `):void 0}If(pp,`concatAriaDescribedby`);var mp=rn(`group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,{variants:{variant:{default:`bg-primary text-primary-foreground hover:bg-primary/80`,outline:`border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50`,secondary:`bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground`,ghost:`hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50`,destructive:`bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40`,link:`text-primary underline-offset-4 hover:underline`},size:{default:`h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2`,xs:`h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3`,sm:`h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5`,lg:`h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2`,icon:`size-8`,"icon-xs":`size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3`,"icon-sm":`size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg`,"icon-lg":`size-9`}},defaultVariants:{variant:`default`,size:`default`}});function hp({className:e,variant:t=`default`,size:n=`default`,asChild:r=!1,...i}){let a=r?fn:`button`;return(0,z.jsx)(a,{"data-slot":`button`,"data-variant":t,"data-size":n,className:L(mp({variant:t,size:n,className:e})),...i})}function gp(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function _p(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/[_-]+/g,` `).replace(/^./,e=>e.toUpperCase())}function vp({value:e}){if(e==null||e===``)return(0,z.jsx)(`span`,{className:`text-muted-foreground/70`,children:`—`});if(typeof e==`boolean`)return(0,z.jsx)(`span`,{className:e?`text-success`:`text-muted-foreground`,children:e?`true`:`false`});if(typeof e==`number`)return(0,z.jsx)(`span`,{className:`tabular`,children:Number.isInteger(e)?e.toLocaleString(`en-US`):e});if(Array.isArray(e))return e.length?(0,z.jsx)(`span`,{className:`[overflow-wrap:anywhere]`,children:e.map(e=>typeof e==`object`?JSON.stringify(e):String(e)).join(`, `)}):(0,z.jsx)(`span`,{className:`text-muted-foreground/70`,children:`[]`});if(typeof e==`object`){let t=JSON.stringify(e);return(0,z.jsx)(`span`,{className:L(`[overflow-wrap:anywhere]`,t===`{}`&&`text-muted-foreground/70`),children:t})}return(0,z.jsx)(`span`,{className:`[overflow-wrap:anywhere]`,children:String(e)})}function yp({data:e,depth:t=0}){let n=Object.entries(e);return n.length?(0,z.jsx)(`dl`,{className:L(`text-sm`,t>0&&`ml-1 border-l pl-3`),children:n.map(([e,n])=>gp(n)&&Object.keys(n).length?(0,z.jsxs)(`div`,{className:`py-1.5`,children:[(0,z.jsx)(`dt`,{className:`mb-1 text-[13px] font-medium text-foreground`,children:_p(e)}),(0,z.jsx)(`dd`,{children:(0,z.jsx)(yp,{data:n,depth:t+1})})]},e):(0,z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 border-b border-dashed py-1.5 last:border-b-0`,children:[(0,z.jsx)(`dt`,{className:`shrink-0 text-muted-foreground`,title:e,children:_p(e)}),(0,z.jsx)(`dd`,{className:`min-w-0 text-right font-mono text-xs`,children:(0,z.jsx)(vp,{value:n})})]},e))}):(0,z.jsx)(`p`,{className:`py-2 text-sm text-muted-foreground`,children:`No fields reported.`})}function bp({text:e,label:t=`Copy`,size:n=`sm`,className:r}){let[i,a]=(0,_.useState)(!1);return(0,z.jsxs)(hp,{variant:`outline`,size:n,className:r,onClick:async()=>{try{await navigator.clipboard.writeText(e),a(!0),window.setTimeout(()=>a(!1),1400)}catch{}},children:[i?(0,z.jsx)(ce,{className:`text-success`}):(0,z.jsx)(ve,{}),i?`Copied`:t]})}function xp({data:e}){return(0,z.jsx)(bp,{text:JSON.stringify(e,null,2),label:`Copy JSON`})}function Sp(e){e.preventDefault(),e.currentTarget?.focus()}function Cp({delayDuration:e=0,...t}){return(0,z.jsx)(Wf,{"data-slot":`tooltip-provider`,delayDuration:e,...t})}function wp({...e}){return(0,z.jsx)(Jf,{"data-slot":`tooltip`,...e})}function Tp({...e}){return(0,z.jsx)(Xf,{"data-slot":`tooltip-trigger`,...e})}function Ep({className:e,sideOffset:t=0,children:n,...r}){return(0,z.jsx)(ep,{children:(0,z.jsxs)(np,{"data-slot":`tooltip-content`,sideOffset:t,className:L(`z-50 inline-flex w-fit max-w-xs origin-(--radix-tooltip-content-transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95`,e),...r,children:[n,(0,z.jsx)(op,{className:`z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground`})]})})}var Dp={ok:`text-success`,info:`text-info`,warn:`text-warning`,error:`text-danger`,off:`text-muted-foreground`,neutral:`text-muted-foreground`},Op={ok:`bg-success-soft text-success`,info:`bg-info-soft text-info`,warn:`bg-warning-soft text-warning`,error:`bg-danger-soft text-danger`,off:`bg-muted text-muted-foreground`,neutral:`bg-muted text-muted-foreground shadow-[inset_0_0_0_1px_var(--border)]`},kp={ok:`bg-success`,info:`bg-info`,warn:`bg-warning`,error:`bg-danger`,off:`bg-muted-foreground/50`};function Ap({tone:e,pulse:t=!1,className:n}){return(0,z.jsxs)(`span`,{className:L(`relative inline-flex size-1.5 shrink-0`,n),"aria-hidden":`true`,children:[t&&(0,z.jsx)(`span`,{className:L(`absolute inset-0 rounded-full animate-ping-slow`,kp[e])}),(0,z.jsx)(`span`,{className:L(`relative inline-flex size-full rounded-full`,kp[e])})]})}function jp({tone:e,children:t,pulse:n,className:r}){return(0,z.jsxs)(`span`,{className:L(`inline-flex h-5 shrink-0 items-center gap-1.5 rounded-full px-2 text-xs font-medium whitespace-nowrap`,Op[e],r),children:[(0,z.jsx)(Ap,{tone:e,pulse:n}),t]})}function Mp({tone:e=`neutral`,mono:t=!1,className:n,children:r,title:i}){let a=(0,z.jsx)(`span`,{className:L(`inline-flex h-5 max-w-full shrink-0 items-center gap-1 truncate rounded-full px-2 text-xs font-medium whitespace-nowrap`,t&&`font-mono text-[11px] font-normal`,Op[e],n),children:r});return i?(0,z.jsxs)(wp,{children:[(0,z.jsx)(Tp,{asChild:!0,children:a}),(0,z.jsx)(Ep,{className:`max-w-72`,children:i})]}):a}function Np({chips:e,className:t}){return e.length?(0,z.jsx)(`div`,{className:L(`flex flex-wrap gap-1.5`,t),children:e.map(e=>(0,z.jsx)(Mp,{tone:e.tone,title:e.title,children:e.label},e.label))}):null}function Pp({className:e,value:t,...n}){return(0,z.jsx)(Yd,{"data-slot":`progress`,className:L(`relative flex h-1 w-full items-center overflow-x-hidden rounded-full bg-muted`,e),...n,children:(0,z.jsx)(Zd,{"data-slot":`progress-indicator`,className:`size-full flex-1 bg-primary transition-all`,style:{transform:`translateX(-${100-(t||0)}%)`}})})}function Fp({...e}){return(0,z.jsx)(bo,{"data-slot":`sheet`,...e})}function Ip({...e}){return(0,z.jsx)(wo,{"data-slot":`sheet-portal`,...e})}function Lp({className:e,...t}){return(0,z.jsx)(Eo,{"data-slot":`sheet-overlay`,className:L(`fixed inset-0 z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0`,e),...t})}function Rp({className:e,children:t,side:n=`right`,showCloseButton:r=!0,...i}){return(0,z.jsxs)(Ip,{children:[(0,z.jsx)(Lp,{}),(0,z.jsxs)(Ao,{"data-slot":`sheet-content`,"data-side":n,className:L(`fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-[side=bottom]:data-open:slide-in-from-bottom-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:animate-out data-closed:fade-out-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=right]:data-closed:slide-out-to-right-10 data-[side=top]:data-closed:slide-out-to-top-10`,e),...i,children:[t,r&&(0,z.jsx)(Lo,{"data-slot":`sheet-close`,asChild:!0,children:(0,z.jsxs)(hp,{variant:`ghost`,className:`absolute top-3 right-3`,size:`icon-sm`,children:[(0,z.jsx)(ot,{}),(0,z.jsx)(`span`,{className:`sr-only`,children:`Close`})]})})]})]})}function zp({className:e,...t}){return(0,z.jsx)(`div`,{"data-slot":`sheet-header`,className:L(`flex flex-col gap-0.5 p-4`,e),...t})}function Bp({className:e,...t}){return(0,z.jsx)(`div`,{"data-slot":`sheet-footer`,className:L(`mt-auto flex flex-col gap-2 p-4`,e),...t})}function Vp({className:e,...t}){return(0,z.jsx)(Po,{"data-slot":`sheet-title`,className:L(`font-heading text-base font-medium text-foreground`,e),...t})}function Hp({className:e,...t}){return(0,z.jsx)(Fo,{"data-slot":`sheet-description`,className:L(`text-sm text-muted-foreground`,e),...t})}var Up={control:{icon:Oe,blurb:`Keystone presents itself to UniFi Protect as an AI Key over the UCP4 control channel.`},aiport:{icon:Xe,blurb:`A virtual AI Port X. Protect relays paired cameras over FLV and Keystone runs smart detections locally.`},vision:{icon:ne,blurb:`A vision-language model writes the event descriptions and tags shown in Protect.`},search:{icon:We,blurb:`CLIP image and text embeddings back Protect’s Find Anything search.`},faces:{icon:He,blurb:`Detects faces in event frames and matches them against your local gallery.`},lpr:{icon:Re,blurb:`Finds and reads license plates locally, then reports them back to Protect.`},stt:{icon:M,blurb:`Transcribes speech clips locally with Whisper.`},enhance:{icon:it,blurb:`Restores low-resolution face crops before recognition and display.`}};function Wp(e){let t=e.trim().split(/\s+/);return((t[0]?.[0]??``)+(t.length>1?t[t.length-1]?.[0]??``:``)).toUpperCase()}function Gp(e){let t=(0,_.useRef)(null),[n,r]=(0,_.useState)(!1);return(0,_.useLayoutEffect)(()=>{let n=t.current;if(!e||!n)return;let i=()=>r(n.scrollHeight>n.clientHeight+1);i();let a=new ResizeObserver(i);return a.observe(n),()=>a.disconnect()},[e]),[t,e&&n]}function Kp({error:e,label:t,expanded:n}){let[r,i]=Gp(!n);return(0,z.jsxs)(`div`,{className:`rounded-md bg-danger-soft px-2.5 py-2 text-danger`,children:[(0,z.jsxs)(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[(0,z.jsx)(`p`,{className:`min-w-0 truncate text-[11.5px] font-medium`,title:t,children:t??`Last error`}),n&&(0,z.jsx)(bp,{text:e,label:`Copy error`,size:`xs`,className:`h-6 bg-card text-foreground`})]}),n?(0,z.jsx)(`pre`,{className:`max-h-80 overflow-auto font-mono text-[11.5px] leading-relaxed whitespace-pre-wrap [overflow-wrap:anywhere]`,children:e}):(0,z.jsx)(`p`,{ref:r,className:`line-clamp-3 font-mono text-[11.5px] leading-relaxed [overflow-wrap:anywhere]`,children:e}),i&&(0,z.jsx)(`p`,{className:`mt-1 text-[11.5px] font-medium underline-offset-2 group-hover:underline`,children:`View full error`})]})}function qp({notice:e,label:t,expanded:n}){let[r,i]=Gp(!n);return(0,z.jsxs)(`div`,{className:`rounded-md bg-warning-soft px-2.5 py-2 text-warning`,children:[(0,z.jsx)(`p`,{className:`mb-1 min-w-0 truncate text-[11.5px] font-medium`,title:t,children:t??`Notice`}),(0,z.jsx)(`p`,{ref:r,className:L(`text-[12px] leading-relaxed [overflow-wrap:anywhere]`,!n&&`line-clamp-3`),children:e}),i&&(0,z.jsx)(`p`,{className:`mt-1 text-[11.5px] font-medium underline-offset-2 group-hover:underline`,children:`View full note`})]})}function Jp({s:e,expanded:t=!1}){return(0,z.jsxs)(z.Fragment,{children:[e.headline&&(0,z.jsxs)(`p`,{className:`flex min-w-0 items-baseline gap-2`,children:[(0,z.jsx)(`span`,{className:L(`truncate text-lg font-medium tracking-[-0.025em]`,e.headlineMono&&`font-mono text-base tracking-normal`),children:e.headline}),e.headlineSub&&(0,z.jsx)(`span`,{className:`shrink-0 truncate text-[13px] text-muted-foreground`,children:e.headlineSub})]}),(0,z.jsx)(Np,{chips:e.chips}),e.stats&&(0,z.jsxs)(`div`,{className:L(`grid gap-px overflow-hidden rounded-md border bg-border`,e.stats.length===4?`grid-cols-4`:e.stats.length===2?`grid-cols-2`:`grid-cols-3`),children:[e.stats.map(e=>(0,z.jsxs)(`div`,{className:`min-w-0 bg-card px-2 py-2`,children:[(0,z.jsx)(`p`,{className:L(`truncate text-[15px] font-medium tabular`,e.tone&&Dp[e.tone]),children:e.value}),(0,z.jsx)(`p`,{className:`truncate text-[11px] text-muted-foreground`,children:e.label})]},e.label)),e.stats.length!==4&&e.stats.length!==2&&Array.from({length:(3-e.stats.length%3)%3},(e,t)=>(0,z.jsx)(`div`,{className:`bg-card`},`pad-${t}`))]}),e.progress&&(0,z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-[13px]`,children:[(0,z.jsx)(`span`,{className:`text-muted-foreground`,children:e.progress.label}),(0,z.jsxs)(`span`,{className:`font-mono text-xs tabular`,children:[e.progress.pct,`%`]})]}),(0,z.jsx)(Pp,{value:e.progress.pct,className:`h-1`}),(0,z.jsx)(`p`,{className:`font-mono text-[11.5px] text-muted-foreground`,children:e.progress.detail})]}),e.rows.length>0&&(0,z.jsx)(`dl`,{className:`text-[13px]`,children:e.rows.map(e=>(0,z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-3 py-0.5`,title:e.title,children:[(0,z.jsx)(`dt`,{className:`shrink-0 text-muted-foreground`,children:e.label}),(0,z.jsx)(`dd`,{className:`truncate font-mono text-xs tabular`,children:e.value})]},e.label))}),e.people&&e.people.length>0&&(0,z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,z.jsx)(`div`,{className:`flex -space-x-1.5`,children:e.people.slice(0,6).map(e=>(0,z.jsxs)(wp,{children:[(0,z.jsx)(Tp,{asChild:!0,children:(0,z.jsx)(`span`,{className:`grid size-6 place-items-center rounded-full border-2 border-card bg-muted text-[10px] font-semibold text-muted-foreground`,children:Wp(e.name)})}),(0,z.jsxs)(Ep,{children:[e.name,` · `,e.refs,` reference`,e.refs===1?``:`s`]})]},e.name))}),(0,z.jsx)(`span`,{className:`truncate text-xs text-muted-foreground`,children:e.people.map(e=>e.name).join(`, `)})]}),e.rejections&&e.rejections.length>0&&(0,z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Rejected`}),(0,z.jsx)(Np,{chips:e.rejections})]}),e.disabledHint&&(0,z.jsxs)(`p`,{className:`text-[13px] text-muted-foreground`,children:[`Disabled. Enable with `,(0,z.jsx)(`code`,{className:`rounded bg-muted px-1 py-0.5 font-mono text-[11.5px]`,children:e.disabledHint})]}),e.notice&&(0,z.jsx)(qp,{notice:e.notice,label:e.noticeLabel,expanded:t}),e.error&&(0,z.jsx)(Kp,{error:e.error,label:e.errorLabel,expanded:t})]})}function Yp({s:e,onOpen:t}){let n=Up[e.id].icon;return(0,z.jsxs)(`button`,{type:`button`,onClick:t,className:L(`group flex h-full flex-col gap-3 rounded-lg border bg-card p-4 text-left transition-colors hover:border-border-strong focus-visible:ring-3 focus-visible:ring-ring/40 focus-visible:outline-none`,e.tone===`error`&&`border-danger/40 hover:border-danger/60`,e.tone===`warn`&&e.notice&&`border-warning/40 hover:border-warning/60`),children:[(0,z.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2.5`,children:[(0,z.jsx)(`span`,{className:L(`grid size-8 shrink-0 place-items-center rounded-md border bg-background text-muted-foreground`,e.tone===`off`&&`opacity-60`),children:(0,z.jsx)(n,{className:`size-4`,strokeWidth:1.75})}),(0,z.jsx)(`p`,{className:`min-w-0 truncate text-sm font-medium tracking-[-0.01em]`,children:e.title})]}),(0,z.jsx)(jp,{tone:e.tone,pulse:e.tone===`info`,children:e.state})]}),(0,z.jsx)(Jp,{s:e}),(0,z.jsxs)(`span`,{className:`mt-auto flex items-center gap-1 pt-1 text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100`,children:[`Details `,(0,z.jsx)(me,{className:`size-3 transition-transform group-hover:translate-x-0.5`})]})]})}function Xp({services:e,onOpen:t}){let n=e.filter(e=>e.tone!==`off`).length;return(0,z.jsxs)(`section`,{id:`services`,className:`scroll-mt-28`,children:[(0,z.jsx)(Zp,{title:`Services`,meta:`${n} of ${e.length} enabled`}),(0,z.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 sm:gap-4 xl:grid-cols-4`,children:e.map(e=>(0,z.jsx)(Yp,{s:e,onOpen:()=>t(e)},e.id))})]})}function Zp({title:e,meta:t,children:n}){return(0,z.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1`,children:[(0,z.jsx)(`h2`,{className:`text-2xl font-semibold tracking-[-0.035em]`,children:e}),t&&(0,z.jsx)(`p`,{className:`text-sm text-muted-foreground tabular`,children:t}),n]})}function Qp({service:e,onOpenChange:t}){let n=e,r=n?Up[n.id].icon:null;return(0,z.jsx)(Fp,{open:!!n,onOpenChange:t,children:(0,z.jsx)(Rp,{className:`w-full gap-0 outline-none sm:max-w-md`,onOpenAutoFocus:Sp,children:n&&r&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(zp,{className:`border-b`,children:[(0,z.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,z.jsx)(`span`,{className:`grid size-8 place-items-center rounded-md border bg-background text-muted-foreground`,children:(0,z.jsx)(r,{className:`size-4`,strokeWidth:1.75})}),(0,z.jsx)(Vp,{className:`text-base tracking-[-0.02em]`,children:n.title}),n.port&&(0,z.jsx)(Mp,{mono:!0,children:n.port}),(0,z.jsx)(jp,{tone:n.tone,className:`mr-8 ml-auto`,children:n.state})]}),(0,z.jsx)(Hp,{children:Up[n.id].blurb})]}),(0,z.jsxs)(`div`,{className:`flex-1 space-y-6 overflow-y-auto p-4`,children:[(0,z.jsx)(`div`,{className:`space-y-3`,children:(0,z.jsx)(Jp,{s:n,expanded:!0})}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`p`,{className:`mb-2 text-[13px] font-medium text-muted-foreground`,children:`Raw status`}),(0,z.jsx)(`div`,{className:`rounded-lg border bg-card px-3 py-1.5`,children:(0,z.jsx)(yp,{data:n.raw??{}})})]})]}),(0,z.jsx)(Bp,{className:`border-t`,children:(0,z.jsx)(xp,{data:n.raw})})]})})})}function $p({className:e,...t}){return(0,z.jsx)(`div`,{"data-slot":`empty`,className:L(`flex w-full min-w-0 flex-1 flex-col items-center justify-center gap-4 rounded-xl border-dashed p-6 text-center text-balance`,e),...t})}function em({className:e,...t}){return(0,z.jsx)(`div`,{"data-slot":`empty-header`,className:L(`flex max-w-sm flex-col items-center gap-2`,e),...t})}var tm=rn(`mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0`,{variants:{variant:{default:`bg-transparent`,icon:`flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground [&_svg:not([class*='size-'])]:size-4`}},defaultVariants:{variant:`default`}});function nm({className:e,variant:t=`default`,...n}){return(0,z.jsx)(`div`,{"data-slot":`empty-icon`,"data-variant":t,className:L(tm({variant:t,className:e})),...n})}function rm({className:e,...t}){return(0,z.jsx)(`div`,{"data-slot":`empty-title`,className:L(`font-heading text-sm font-medium tracking-tight`,e),...t})}function im({className:e,...t}){return(0,z.jsx)(`div`,{"data-slot":`empty-description`,className:L(`text-sm/relaxed text-muted-foreground [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary`,e),...t})}function am({className:e,type:t,...n}){return(0,z.jsx)(`input`,{type:t,"data-slot":`input`,className:L(`h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40`,e),...n})}function om({className:e,...t}){return(0,z.jsx)(`div`,{"data-slot":`input-group`,role:`group`,className:L(`group/input-group relative flex h-8 w-full min-w-0 items-center rounded-lg border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5`,e),...t})}var sm=rn(`flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4`,{variants:{align:{"inline-start":`order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]`,"inline-end":`order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]`,"block-start":`order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2`,"block-end":`order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2`}},defaultVariants:{align:`inline-start`}});function cm({className:e,align:t=`inline-start`,...n}){return(0,z.jsx)(`div`,{role:`group`,"data-slot":`input-group-addon`,"data-align":t,className:L(sm({align:t}),e),onClick:e=>{e.target.closest(`button`)||e.currentTarget.parentElement?.querySelector(`input`)?.focus()},...n})}var lm=rn(`flex items-center gap-2 text-sm shadow-none`,{variants:{size:{xs:`h-6 gap-1 rounded-[calc(var(--radius)-3px)] px-1.5 [&>svg:not([class*='size-'])]:size-3.5`,sm:``,"icon-xs":`size-6 rounded-[calc(var(--radius)-3px)] p-0 has-[>svg]:p-0`,"icon-sm":`size-8 p-0 has-[>svg]:p-0`}},defaultVariants:{size:`xs`}});function um({className:e,type:t=`button`,variant:n=`ghost`,size:r=`xs`,...i}){return(0,z.jsx)(hp,{type:t,"data-size":r,variant:n,className:L(lm({size:r}),e),...i})}function dm({className:e,...t}){return(0,z.jsx)(am,{"data-slot":`input-group-control`,className:L(`flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent`,e),...t})}function fm({className:e,...t}){return(0,z.jsx)(`kbd`,{"data-slot":`kbd`,className:L(`pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm bg-muted px-1 font-sans text-xs font-medium text-muted-foreground select-none in-data-[slot=tooltip-content]:bg-background/20 in-data-[slot=tooltip-content]:text-background dark:in-data-[slot=tooltip-content]:bg-background/10 [&_svg:not([class*='size-'])]:size-3`,e),...t})}var pm=rn(`group/toggle inline-flex items-center justify-center gap-1 rounded-lg text-sm font-medium whitespace-nowrap transition-all outline-none hover:bg-muted hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 aria-pressed:bg-muted data-[state=on]:bg-muted dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,{variants:{variant:{default:`bg-transparent`,outline:`border border-input bg-transparent hover:bg-muted`},size:{default:`h-8 min-w-8 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2`,sm:`h-7 min-w-7 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5`,lg:`h-9 min-w-9 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2`}},defaultVariants:{variant:`default`,size:`default`}}),mm=_.createContext({size:`default`,variant:`default`,spacing:2,orientation:`horizontal`});function hm({className:e,variant:t,size:n,spacing:r=2,orientation:i=`horizontal`,children:a,...o}){return(0,z.jsx)(wf,{"data-slot":`toggle-group`,"data-variant":t,"data-size":n,"data-spacing":r,"data-orientation":i,style:{"--gap":r},className:L(`group/toggle-group flex w-fit flex-row items-center gap-[--spacing(var(--gap))] rounded-lg data-[size=sm]:rounded-[min(var(--radius-md),10px)] data-vertical:flex-col data-vertical:items-stretch`,e),...o,children:(0,z.jsx)(mm.Provider,{value:{variant:t,size:n,spacing:r,orientation:i},children:a})})}function gm({className:e,children:t,variant:n=`default`,size:r=`default`,...i}){let a=_.useContext(mm);return(0,z.jsx)(Nf,{"data-slot":`toggle-group-item`,"data-variant":a.variant||n,"data-size":a.size||r,"data-spacing":a.spacing,className:L(`shrink-0 group-data-[spacing=0]/toggle-group:rounded-none group-data-[spacing=0]/toggle-group:px-2 focus:z-10 focus-visible:z-10 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-end]:pr-1.5 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-start]:pl-1.5 group-data-horizontal/toggle-group:data-[spacing=0]:first:rounded-l-lg group-data-vertical/toggle-group:data-[spacing=0]:first:rounded-t-lg group-data-horizontal/toggle-group:data-[spacing=0]:last:rounded-r-lg group-data-vertical/toggle-group:data-[spacing=0]:last:rounded-b-lg group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:border-l-0 group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:border-t-0 group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-l group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-t`,pm({variant:a.variant||n,size:a.size||r}),e),...i,children:t})}function Z(e,t=0){let n=Number(e);return Number.isFinite(n)?n:t}function Q(e){return Math.trunc(Z(e)).toLocaleString(`en-US`)}function _m(e){let t=Math.max(0,Z(e));if(!t)return`0 B`;if(t<1024)return`${Math.trunc(t)} B`;if(t<1024**2)return`${(t/1024).toFixed(0)} KB`;if(t<1024**3){let e=t/1024**2;return`${e>=100?e.toFixed(0):e.toFixed(1)} MB`}return`${(t/1024**3).toFixed(2)} GB`}function vm(e){let t=Math.trunc(Z(e));return t<=0?`—`:t<1e3?`${t} ms`:`${(t/1e3).toFixed(1)}s`}function ym(e){return`${Math.round(Z(e)*100)}%`}function bm(e){let t=Z(e);if(t<=0)return`—`;let n=new Date(t);return Number.isNaN(n.getTime())?`—`:n.toLocaleTimeString(`en-GB`,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function xm(e){let t=Z(e);if(t<=0)return`—`;let n=new Date(t);return Number.isNaN(n.getTime())?`—`:n.toLocaleString(void 0,{weekday:`short`,year:`numeric`,timeZoneName:`short`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function Sm(e){let t=Z(e);if(t<=0)return`—`;let n=new Date(t);return Number.isNaN(n.getTime())?`—`:`${n.toLocaleDateString(void 0,{month:`short`,day:`numeric`})}, ${n.toLocaleTimeString(`en-GB`,{hour:`2-digit`,minute:`2-digit`})}`}function Cm(e,t){let n=Z(e);if(n<=0)return`—`;let r=Math.round((t-n)/1e3);if(r<5)return`now`;if(r<60)return`${r}s ago`;let i=Math.floor(r/60);if(i<60)return`${i}m ago`;let a=Math.floor(i/60);return a<48?`${a}h ago`:`${Math.floor(a/24)}d ago`}function wm(e,t){let n=new Date(e),r=new Date(t),i=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime(),a=Math.round((i(r)-i(n))/864e5);return a===0?`Today`:a===1?`Yesterday`:n.toLocaleDateString(void 0,{weekday:`long`,month:`short`,day:`numeric`})}function Tm(e){let t=new Date(e);return`${t.getFullYear()}-${t.getMonth()}-${t.getDate()}`}var Em={blurry:`Sharpness below faces.min_sharpness (Laplacian variance of the native-resolution face crop)`,small:`Face box smaller than faces.min_face_px (source pixels)`,low_score:`SCRFD confidence below faces.min_det_score`,profile:`Head turn exceeded faces.max_yaw (near-profile angle)`,yaw:`Head turn exceeded faces.max_yaw (near-profile angle)`},Dm={alrmspeak:`Speech`,speak:`Speech`,speech:`Speech`,alrmbark:`Dog bark`,bark:`Dog bark`,alrmsiren:`Siren`,siren:`Siren`,alrmsmoke:`Smoke alarm`,smoke:`Smoke alarm`,alrmcmonx:`CO alarm`,cmonx:`CO alarm`,alrmbabycry:`Baby cry`,babycry:`Baby cry`,alrmglassbreak:`Glass break`,glassbreak:`Glass break`,alrmcaralarm:`Car alarm`,caralarm:`Car alarm`,alrmcarhorn:`Car horn`,carhorn:`Car horn`,alrmburglar:`Burglar alarm`,burglar:`Burglar alarm`},Om=/^data:image\/(?:jpeg|png|webp);base64,[A-Za-z0-9+/=]+$/,km=2e4;function Am(e){return typeof e==`string`&&e.length<=km&&Om.test(e)?e:null}function jm(e){let t=String(e??``).trim();return t?Dm[t.toLowerCase()]??t:`Audio`}function Mm(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function $(e){return e==null?``:String(e).trim()}function Nm(e){let t=$(e),n=t.indexOf(` (`);return n>0?[t.slice(0,n).trim(),t]:[t,t]}function Pm(e){let t=$(e);if(!t)return`—`;if(t.toLowerCase()===`unloaded`)return`Unloaded`;if(t===`CoreAI`)return`Core AI`;let n=/^([A-Za-z]+?)(?:ExecutionProvider)?(?:\((.+)\))?$/.exec(t);if(!n)return t;let r=n[1]===`CPU`?`CPU`:n[1].replace(/^Openvino$/i,`OpenVINO`);return n[2]?`${r} · ${n[2].toUpperCase()}`:r}function Fm(e){let t=$(e).toLowerCase();return!t||t===`unloaded`||t===`coreai`||t.startsWith(`cpu`)?!1:!t.includes(`(cpu)`)}var Im={embeddingsVision:`CLIP vision`,embeddingsText:`CLIP text`,aiportDetector:`AI Port detector`,faceDetector:`Face detector`,faceRecognizer:`Face recognizer`,lprDetector:`Plate detector`,lprOcr:`Plate OCR`,faceEnhancer:`Face enhancer`,sttEncoder:`Whisper encoder`,sttDecoder:`Whisper decoder`},Lm=[`CUDA`,`MIGraphX`],Rm={CPUAndNeuralEngine:`ANE`,ALL:`ALL`,CPUAndGPU:`GPU`,CPUOnly:`CPU`};function zm(e){let t=Bm(e),n=Mm(e.acceleration?.gpuWatchdog),r=Z(n.recentRestarts),i=Z(n.windowMinutes,30);if(n.suspended){let e=Z(n.suspendedAfterRestarts)||r;return{...t,label:`CPU · GPU suspended`,detail:`Running on CPU`,hardware:!1,warning:`The GPU was lost ${e} times within ${i} min, so every model is running on the CPU. Restart Keystone to try the GPU again.`}}return Z(n.lossDetectedAt)>0&&!n.restartOnLoss?{...t,warning:`The GPU was lost${n.lossModel?` (first seen in ${n.lossModel})`:``} and GPU models will keep failing. Automatic restart is off (acceleration.restart_on_gpu_loss); restart Keystone to recover.`}:r>0?{...t,note:`Restarted ${r} time${r===1?``:`s`} in the last ${i} min to recover a lost GPU.`}:t}function Bm(e){let t=Mm(e.acceleration),n=Mm(e.embeddings),r=t.coremlComputeUnits===`CPUOnly`,i=Object.entries(Mm(t.activeProviders)).map(([e,t])=>{let n=Pm(t);return{key:e,label:Im[e]??e,provider:n,hardware:Fm(t)&&!(n===`CoreML`&&r),loaded:$(t).toLowerCase()!==`unloaded`}});for(let e of Lm){let n=i.filter(t=>t.provider===e).length;if(n){let t=i.filter(e=>e.loaded).length;return{models:i,label:i.some(e=>e.provider===`CPU`)?`${e} + CPU`:`${e} · GPU`,detail:`${e}ExecutionProvider on ${n}/${t} loaded models`,hardware:!0}}if($(t.provider).toLowerCase()===e.toLowerCase())return i.some(e=>e.provider===`CPU`)?{models:i,label:`CPU`,detail:`CPUExecutionProvider`,hardware:!1}:{models:i,label:`Idle`,detail:`No ${e} sessions loaded`,hardware:!1}}let a=i.some(e=>e.provider===`CoreML`),o=i.some(e=>e.provider.startsWith(`OpenVINO`)),s={models:i,precision:$(a?t.coremlModelFormat:t.precision)||void 0};if(Object.keys(t).length){let e=$(t.label||t.active),n=$(t.backend||t.provider||t.executionProvider),c=n.toLowerCase(),l=$(t.device||t.openvinoDevice);if(e){let t=/^openvino$/i.test(n)?`OpenVINO`:n,r=l?` on ${l.toUpperCase()}`:``;return{...s,label:e,detail:t?`${t}${r}`:e,hardware:!e.toUpperCase().startsWith(`CPU`)}}if(a||!t.activeProviders&&c.includes(`coreml`)){let e=$(t.coremlComputeUnits),n=Rm[e];return{...s,label:n?`CoreML · ${n}`:`CoreML`,detail:e?`CoreML (${e})`:`CoreML`,hardware:!r}}if(o||c.includes(`openvino`)||t.openvino){let e=(l||`AUTO`).toUpperCase();return{...s,label:`OpenVINO · ${e}`,detail:`OpenVINO on ${e}`,hardware:e!==`CPU`}}return i.some(e=>e.provider===`Core AI`)?{...s,label:`Core AI`,detail:`CLIP vision encoder with GPU preference`,hardware:!1}:c.includes(`cuda`)?{...s,label:`CUDA · GPU`,detail:n,hardware:!0}:c.includes(`tensorrt`)?{...s,label:`TensorRT · GPU`,detail:n,hardware:!0}:t.device&&l.toUpperCase()!==`CPU`?{...s,label:`${n||`Accelerated`} · ${l.toUpperCase()}`,detail:`${n} (${l})`,hardware:!0}:{...s,label:`CPU`,detail:n||`CPUExecutionProvider`,hardware:!1}}let c=$(n.provider),l=$(n.device||n.openvinoDevice),u=c.toLowerCase();if(u.includes(`openvino`)){let e=(l||`GPU`).toUpperCase();return{...s,label:`OpenVINO · ${e}`,detail:`${c} (${e})`,hardware:e!==`CPU`}}return u.includes(`cuda`)?{...s,label:`CUDA · GPU`,detail:c,hardware:!0}:u.includes(`coreml`)?{...s,label:`CoreML`,detail:c,hardware:!0}:u.includes(`tensorrt`)?{...s,label:`TensorRT · GPU`,detail:c,hardware:!0}:{...s,label:`CPU`,detail:c||`CPUExecutionProvider`,hardware:!1}}var Vm=[{key:`all`,label:`All`},{key:`detection`,label:`Detections`},{key:`caption`,label:`Captions`},{key:`face`,label:`Faces`},{key:`lpr`,label:`Plates`},{key:`audio`,label:`Audio`},{key:`package`,label:`Packages`}];function Hm(e){let t=$(e.kind||e.type).toLowerCase();return t===`detection`?{label:`Detection`,tone:`detection`}:t===`stt`||t===`speechtotext`?{label:`Speech`,tone:`audio`}:t===`audio`?{label:`Audio`,tone:`audio`}:t===`enhance`?{label:`Enhance`,tone:`face`}:t===`face`?{label:`Face`,tone:`face`}:t===`lpr`?{label:`Plate`,tone:`lpr`}:t===`package`?{label:`Package`,tone:`package`}:$(e.subtype).toLowerCase()===`on_demand`?{label:`Summary`,tone:`caption`}:{label:`Caption`,tone:`caption`}}function Um(e){let t=e.plates;return Array.isArray(t)?t:t&&Array.isArray(t.plates)?t.plates:[]}function Wm(e){let t=[],n=e=>{t.includes(e)||t.push(e)},r=$(e.kind||e.type).toLowerCase();r===`detection`&&n(`detection`),(!r||[`caption`,`recognizekeyframes`,`describeimage`,`on_demand`].includes(r))&&n(`caption`),(r===`face`||r===`enhance`)&&n(`face`),r===`lpr`&&n(`lpr`),(r===`stt`||r===`speechtotext`||r===`audio`)&&n(`audio`),r===`package`&&n(`package`);let i=e.faces;i&&(Z(i.detections)>0||Z(i.qualityFaces)>0||Array.isArray(i.matches)&&i.matches.length>0||i.rejectedReasons&&Object.keys(i.rejectedReasons).length>0)&&n(`face`);for(let t of Array.isArray(e.identities)?e.identities:[]){let e=$(t?.source).toLowerCase(),r=$(t?.kind).toLowerCase();e===`lpr`||r===`vehicle`?n(`lpr`):(e===`face`||e===`propagated`)&&n(`face`)}return Um(e).length&&n(`lpr`),(e.transcript||e.audioType||e.audioAlarm)&&n(`audio`),((Array.isArray(e.tags)?e.tags.map(e=>String(e).toLowerCase()):[]).some(e=>[`package`,`parcel`,`delivery`,`box`,`cardboard`].includes(e))||e.packageCount)&&n(`package`),t.length||t.push(`caption`),t}function Gm(e,t,n){let r=$(t);if(r&&r!==e)return r;if(e&&n&&typeof n==`object`){let t=e=>typeof e==`string`?e.trim():e&&typeof e==`object`?$(e.name):``,r=t(n[e]);if(r)return r;let i=e=>e.replace(/[:-]/g,``).trim().toUpperCase(),a=i(e);for(let[e,r]of Object.entries(n))if(i(e)===a){let e=t(r);if(e)return e}}return e||`Unknown camera`}function Km(e,t,n){let r=$(e.cameraId),i=Hm(e).label,a=$(e.eventId),o=e.historyId==null?`${Z(e.timestamp)}|${r}|${i}|${a||n}|${$(e.audioType)}`:String(e.historyId),s={...e,key:o,cameraName:Gm(r,e.cameraName,t),categories:Wm(e)},c=Am(s.thumbnail);return c?s.thumbnail=c:delete s.thumbnail,s}function qm(e,t,n){let r=[],i=new Set,a=(e,t)=>{if(!e||typeof e!=`object`)return;let a=Km(e,n,t);i.has(a.key)||(i.add(a.key),r.push(a))};return(t??[]).forEach(a),(e??[]).forEach((e,t)=>a(e,t+1e4)),r.sort((e,t)=>Z(t.timestamp)-Z(e.timestamp)),r}function Jm(e){let t={all:e.length,detection:0,caption:0,face:0,lpr:0,audio:0,package:0};for(let n of e)for(let e of n.categories)t[e]+=1;return t}function Ym(e,t){let n=t.trim().toLowerCase();return!n||[e.cameraName,e.cameraId,e.description,e.transcript,e.audioType&&jm(e.audioType),e.audioAlarm&&jm(e.audioAlarm),Hm(e).label,...Array.isArray(e.tags)?e.tags:[],...Array.isArray(e.identities)?e.identities.map(e=>`${e?.name??``} ${e?.plate??``} ${e?.source??``}`):[],...Um(e).map(e=>e?.plate||e?.text||``)].filter(Boolean).join(` `).toLowerCase().includes(n)}function Xm(e){let t=new Set,n=[];for(let r of Um(e)){let e=$(r?.plate||r?.text);e&&!t.has(e)&&(t.add(e),n.push({plate:e,confidence:Z(r?.confidence)}))}return n}function Zm(e){let t=$(e.audioType||e.audioAlarm);if(!t)return null;let n=Z(e.audioConfidence),r=n>0?` · ${Math.round(n*100)}%`:e.leveldB==null?``:` · ${Z(e.leveldB)} dB`;return`${jm(t)}${r}`}function Qm(e,t){let n=Mm(e.faces?.rejectedReasons);if(Object.values(n).some(e=>Z(e)>0))return Object.fromEntries(Object.entries(n).filter(([,e])=>Z(e)>0).map(([e,t])=>[e,Math.trunc(Z(t))]));let r={};for(let e of t)for(let[t,n]of Object.entries(Mm(e.faces?.rejectedReasons)))Z(n)>0&&(r[t]=(r[t]??0)+Math.trunc(Z(n)));return r}function $m(e,t){let n=Math.trunc(Z(e.avgLatencyMs)),r=Math.trunc(Z(e.lastLatencyMs));if(n>0||r>0)return{avg:n,last:r};let i=t.filter(e=>![`speechtotext`,`stt`,`audio`].includes($(e?.type||e?.kind).toLowerCase())&&Z(e?.elapsedMs)>0).map(e=>Z(e.elapsedMs));return i.length?{avg:Math.round(i.reduce((e,t)=>e+t,0)/i.length),last:Math.trunc(i[0])}:{avg:0,last:0}}function eh(e){return $(e)||void 0}function th(e){return Mm(e.packageDetector??e.packageDetection??e.packages)}function nh(e){let t=th(e),n=(Array.isArray(e.pairedCameras)?e.pairedCameras:[]).reduce((e,t)=>e+Z(t?.packagesDetected),0);return Z(e.totalPackages,Z(t.totalPackages,Z(t.detections??t.eventsEmitted,n)))}function rh(e){let t=Array.isArray(e.pairedCameras)?e.pairedCameras:[];return Z(e.totalPlates,t.reduce((e,t)=>e+Z(t?.platesRecognized),0))}function ih(e,t){let n=e.toLowerCase();return n.includes(`openvino`)?`OpenVINO ${t||/\((\w+)\)/.exec(e)?.[1]||`GPU`}`.trim():n.includes(`cuda`)?`CUDA`:n.includes(`coreml`)?`CoreML`:n.includes(`tensorrt`)?`TensorRT`:n.startsWith(`cpu`)?`CPU`:e||`Ready`}function ah(e){return e.captionConsecutiveFailed===void 0?Z(e.completed)===0?Math.trunc(Z(e.failed)):0:Math.max(0,Math.trunc(Z(e.captionConsecutiveFailed)))}function oh(e){let t=(e??``).trim().match(/^(\d+)\.(\d+)/);if(!t)return!1;let n=Number(t[1]),r=Number(t[2]);return n<7||n===7&&r<4}function sh(e,t,n){let r=Mm(e.control),i=Mm(e.search),a=Mm(e.worker),o=Mm(e.vision),s=Mm(e.embeddings),c=Mm(e.aiport),l=Mm(e.faces),u=Mm(e.lpr),d=Mm(e.stt),f=Mm(e.enhance),p=r.enabled!==!1,m=Mm(r.commands),h=Object.values(m).reduce((e,t)=>e+Z(t),0),g=Object.entries(m).sort((e,t)=>Z(t[1])-Z(e[1])).slice(0,6).map(([e,t])=>`${e}: ${Q(t)}`).join(`, `),_={id:`control`,title:`Protect control`,port:`:7442`,...p?r.connected?{tone:`ok`,state:`Online`}:r.lastError?{tone:`error`,state:`Error`}:{tone:`warn`,state:`Waiting`}:{tone:`off`,state:`Off`},headline:p?$(r.consoleName)||$(e.controllerHost)||`Pending adoption`:void 0,headlineSub:p&&r.adopted?`Adopted`:void 0,chips:[],rows:p?[{label:`Port`,value:`7442`,title:`UCP4 control channel (WSS)`},{label:`Protect`,value:$(r.protectVersion)||`pending`},{label:`UCP4 commands`,value:Q(h),title:g},{label:`Controller`,value:$(e.controllerHost)||`—`}]:[],disabledHint:p?void 0:`device.enabled: true`,error:p?eh(r.lastError):void 0,raw:e.control??{}},v=Array.isArray(c.pairedCameras)?c.pairedCameras:[],y=th(c),b=nh(c),x=[];if(c.audioVadEnabled){let e=!!c.audioVad?.ready;x.push({label:`Silero VAD`,tone:e?`ok`:`neutral`,title:`Voice activity detection (${e?`ready`:`standby`})`})}let S=c.audioClassifier??c.yamnet;if(S&&S.enabled!==!1){let e=S.ready!==!1;x.push({label:`YAMNet`,tone:e?`info`:`neutral`,title:`Smart audio classifier (${e?`ready`:`loads on first audio`})`})}if(Object.keys(y).length&&y.enabled!==!1){let e=$(y.model)||`D-FINE`,t=/d-?fine/i.test(e)?`D-FINE packages`:`${Nm(e)[0]} packages`,n=y.ready!==!1;x.push({label:t,tone:n?`info`:`neutral`,title:`${e} (${n?`ready`:`loads on demand`})`})}let C=[{label:`Smart`,value:Q(c.totalSmartEvents)},{label:`Audio`,value:Q(c.totalAudioEvents)},{label:`Faces`,value:Q(c.totalFaces)},{label:`Plates`,value:Q(rh(c))}];(b>0||y.enabled)&&C.push({label:`Packages`,value:Q(b)});let w={id:`aiport`,title:`Virtual AI Port`,...c.enabled?c.connected?{tone:`ok`,state:`Online`}:c.lastError?{tone:`error`,state:`Error`}:{tone:`warn`,state:`Ready to adopt`}:{tone:`off`,state:`Off`},headline:c.enabled?`${v.length} camera${v.length===1?``:`s`} paired`:void 0,headlineSub:c.enabled&&$(c.model)||void 0,chips:c.enabled?x:[],rows:c.enabled?[{label:`MAC`,value:$(c.mac)||`—`}]:[],stats:c.enabled?C:void 0,disabledHint:c.enabled?void 0:`aiport.enabled: true`,error:eh(c.lastError),raw:(({pairedCameras:e,...t})=>t)(c)},T=$(o.provider)||`disabled`,E=$(o.model)||`disabled`,D=T.toLowerCase()!==`disabled`&&E.toLowerCase()!==`disabled`,O=Math.trunc(Z(a.liveActive??a.active)),k=Math.trunc(Z(a.liveQueued??a.queued)),A=Math.trunc(Z(a.completed)),ee=Math.trunc(Z(a.failed)),j=$m(a,t),te=$(o.frameLayout||o.layout)||(Z(o.maxFrames)>0?`${Z(o.maxFrames)}-frame`:``),M=ah(a),N=eh(o.lastError),ne=o.ready===!1||M>=3,re=oh(r.protectVersion),ie=D&&(o.protectAiSummary===!1||r.protectAiSettings?.aiSummary===!1),ae={id:`vision`,title:`Vision captions`,...D?ne?{tone:`error`,state:`Failing`}:O>0?{tone:`info`,state:`Running`}:{tone:`ok`,state:`Ready`}:{tone:`off`,state:`Disabled`},...D&&N?{error:N,errorLabel:`Vision backend error`}:D&&M>0&&$(a.captionLastError)?{error:$(a.captionLastError),errorLabel:ne?`${M} caption jobs failed in a row`:`Last caption job failed`}:{},headline:D?E:void 0,headlineMono:!0,chips:D?[{label:T,tone:`neutral`},...te?[{label:te,tone:`info`}]:[],...ie?[{label:`Protect AI Summary off`,tone:`neutral`,title:re?`Protect sent postVLM=false (AI Summary is off in Protect → Settings → Intelligence). Keystone still uploads captions; click the NeXT AI Summary icon in Protect's event player to view them, or enable AI Summary in Protect.`:`Protect sent postVLM=false (AI Summary is off under Settings → Intelligence → Basic Understanding). Keystone still uploads captions; click the NeXT AI Summary icon in Protect's event player to view them, or toggle Basic Understanding Off then On and click Apply Changes.`}]:[]]:[],rows:D?[{label:`Latency`,value:`${vm(j.avg)} avg · ${vm(j.last)} last`}]:[],stats:D?[{label:`Active`,value:Q(O),tone:O>0?`info`:void 0},{label:`Queued`,value:Q(k)},{label:`Done`,value:Q(A)},{label:`Failed`,value:Q(ee),tone:ee>0?`error`:void 0}]:void 0,disabledHint:D?void 0:`vision.provider, base_url, model`,raw:{...o,worker:a}},oe=s.enabled!==!1,se=$(s.provider)||`ready`,ce=$(s.device||s.openvinoDevice),le=ih(se,ce),ue=[];s.quantization&&ue.push({label:$(s.quantization),tone:`info`}),`textModelLoaded`in s&&ue.push({label:`text ${s.textModelLoaded?`loaded`:`lazy`}`,tone:s.textModelLoaded?`ok`:`neutral`,title:s.textModelLoaded?`Text encoder resident in memory`:`Text encoder loads on the first search`}),ce&&!le.toUpperCase().includes(ce.toUpperCase())&&ue.push({label:ce.toUpperCase(),tone:`info`});let de=Math.trunc(Z(a.retroactiveCompleted)),fe=Math.trunc(Z(a.retroactiveQueued)),pe=Math.trunc(Z(a.retroactiveFailed)),me=Math.trunc(Z(a.retroactiveImagesIndexed)),he=de+fe,ge=[{label:`Port`,value:`7443`,title:`Find Anything search channel (WSS)`},{label:`Queries`,value:`${Q(i.queriesServed)} text · ${Q(i.imageQueriesServed)} image`}],P;if(he>0||me>0){let e=de>0&&fe===0?100:he>0?Math.round(de/he*100):0,t=[`${Q(de)} events`,`${Q(me)} images`];fe&&t.push(`${Q(fe)} queued`),pe&&t.push(`${Q(pe)} failed`),P={label:`Retroactive backfill`,detail:t.join(` · `),pct:e}}else s.retroactiveProcessing&&ge.push({label:`Retroactive backfill`,value:`Idle`});let F={id:`search`,title:`Find Anything`,port:`:7443`,...oe?i.connected?{tone:`ok`,state:`Online`}:i.lastError?{tone:`error`,state:`Error`}:{tone:`warn`,state:`Waiting`}:{tone:`off`,state:`Disabled`},headline:oe?$(s.backend||`clip`).toUpperCase():void 0,headlineSub:oe?le:void 0,chips:oe?ue:[],rows:oe?ge:[],progress:oe?P:void 0,disabledHint:oe?void 0:`embeddings.enabled: true`,error:eh(i.lastError),raw:{...s,search:i}},_e=Mm(l.gallery),ve=Qm(e,n),ye={id:`faces`,title:`Face recognition`,...l.enabled?l.ready?{tone:`ok`,state:`Ready`}:l.lastError?{tone:`error`,state:`Error`}:{tone:`warn`,state:`Loading`}:{tone:`off`,state:`Off`},headline:l.enabled?`${Q(_e.people)} ${Z(_e.people)===1?`person`:`people`} enrolled`:void 0,headlineSub:l.enabled?`${Q(_e.templates)} refs`:void 0,chips:l.enabled?[...l.nativeProtect?[{label:`Native Protect`,tone:`info`,title:`Names flow into Protect's face library`}]:[],...l.detector?[{label:[l.detector,l.recognizer].filter(Boolean).join(` + `),tone:`neutral`}]:[]]:[],rows:l.enabled?[{label:`Matched`,value:`${Q(l.facesMatched)} of ${Q(l.eventsScanned)} scans`}]:[],people:l.enabled?Object.entries(Mm(_e.perPerson)).map(([e,t])=>({name:e,refs:Z(t)})):void 0,rejections:Object.entries(ve).sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,6).map(([e,t])=>({label:`${e} ${t}`,tone:`warn`,title:Em[e]??`Face rejected: ${e}`})),disabledHint:l.enabled?void 0:`faces.enabled: true`,error:eh(l.lastError),raw:e.faces??{}},[be,xe]=Nm(u.detector),[Se,Ce]=Nm(u.ocr),we=Z(u.platesRecognized,Z(u.aiKeyPlates)),Te={id:`lpr`,title:`License plates`,...u.enabled?u.ready?{tone:`ok`,state:`Ready`}:u.lastError?{tone:`error`,state:`Error`}:{tone:`warn`,state:`Loading`}:{tone:`off`,state:`Off`},headline:u.enabled?`${Q(we)} plate${we===1?``:`s`} read`:void 0,chips:u.enabled?[...u.nativeProtect?[{label:`Native Protect`,tone:`info`}]:[],...be||Se?[{label:[be,Se].filter(Boolean).join(` + `),tone:`neutral`,title:[xe,Ce].filter(Boolean).join(` / `)}]:[]]:[],rows:u.enabled?[{label:`AI Key uploads`,value:Q(u.aiKeyUploads)},{label:`Last inference`,value:vm(u.lastInferMs)}]:[],disabledHint:u.enabled?void 0:`lpr.enabled: true`,error:eh(u.lastError),raw:e.lpr??{}},Ee=Z(d.completed||d.transcriptions),De=!!d.enabled&&(d.protectEnabled===!1||r.protectAiSettings?.stt===!1),Oe={id:`stt`,title:`Speech to text`,...d.enabled?d.ready?De?{tone:`warn`,state:`Off in Protect`}:{tone:`ok`,state:`Ready`}:d.lastError?{tone:`error`,state:`Error`}:{tone:`warn`,state:`Loading`}:{tone:`off`,state:`Off`},headline:d.enabled?$(d.model)||`whisper`:void 0,headlineMono:!0,chips:d.enabled&&d.quantization?[{label:$(d.quantization),tone:`info`}]:[],rows:d.enabled?[{label:`Transcripts`,value:`${Q(Ee)} · ${Q(d.segments)} segments`},{label:`Latency`,value:`${vm(d.avgElapsedMs||d.lastElapsedMs)} avg`}]:[],disabledHint:d.enabled?void 0:`stt.enabled: true`,...De?{noticeLabel:`Disabled in UniFi Protect`,notice:re?`Protect is not sending Speech-to-Text jobs. Enable Speech-to-Text under Protect → Settings → Intelligence.`:`Protect is not sending Speech-to-Text jobs. In Protect → Settings → Intelligence → Basic Understanding, toggle it Off then On and click Apply Changes (or choose Selected Only to enable Speech to Text per camera).`}:{},error:eh(d.lastError),raw:e.stt??{}},ke=Z(f.enhanced||a.enhanceCompleted);return[_,w,ae,F,ye,Te,Oe,{id:`enhance`,title:`Face enhance`,...f.enabled?f.lastError?{tone:`error`,state:`Error`}:{tone:`ok`,state:`Ready`}:{tone:`off`,state:`Off`},headline:f.enabled?$(f.backend||`gfpgan`).toUpperCase():void 0,headlineSub:f.enabled?f.modelLoaded?`Loaded`:`Loads on demand`:void 0,chips:f.enabled&&f.model?[{label:Nm(f.model)[0],tone:`neutral`,title:$(f.model)}]:[],rows:f.enabled?[{label:`Faces restored`,value:Q(ke)},{label:`Last run`,value:vm(f.lastElapsedMs)}]:[],disabledHint:f.enabled?void 0:`enhance.enabled: true`,error:eh(f.lastError),raw:e.enhance??{}}].map(t=>uh(t,e.inference))}var ch={aiport:[`aiport:`],search:[`clip:`],faces:[`face:`],lpr:[`lpr`],stt:[`stt:`],enhance:[`enhance:`]};function lh(e,t){let n=ch[e]??[];return Object.entries(Mm(t)).filter(([e])=>n.some(t=>e.startsWith(t)))}function uh(e,t){if(e.tone===`off`)return e;let n=lh(e.id,t),r=n.filter(([,e])=>e.failing),i=n.filter(([,e])=>Z(e.consecutiveFailures)>0),a=(r.length?r:i).sort((e,t)=>Z(t[1].lastErrorAt)-Z(e[1].lastErrorAt))[0];if(!a)return e;let[o,s]=a,c=Z(s.consecutiveFailures);return{...e,...r.length?{tone:`error`,state:`Failing`}:e.tone===`error`?{}:{tone:`warn`,state:`Degraded`},error:$(s.lastError)||e.error,errorLabel:`${o} · ${c} failed run${c===1?``:`s`} in a row`}}function dh(e){let t=e.control??{};if(t.enabled===!1)return{subtitle:`Standalone Virtual AI Port for UniFi Protect`,adoption:e.aiport?.adopted?`AI Port adopted`:`Waiting for AI Port adoption in UniFi Protect`};let n=$(t.consoleName);return{subtitle:`Local AI Key for UniFi Protect`,adoption:t.adopted?n?`Adopted by ${n}`:`Adopted`:`Waiting for adoption in UniFi Protect`}}function fh(e){let t=e.filter(e=>e.tone!==`off`),n=t.filter(e=>e.tone===`error`),r=t.filter(e=>e.tone===`warn`),i=[...n,...r],a=`${t.length-i.length} of ${t.length} services healthy`;return n.length?{tone:`error`,title:n.length===1?`${n[0].title} is failing`:`${n.length} services are failing`,detail:a,attention:i}:r.length?{tone:`warn`,title:r.length===1?`${r[0].title} needs attention`:`${r.length} services need attention`,detail:a,attention:i}:{tone:`ok`,title:`All systems operational`,detail:a,attention:i}}var ph=[`person`,`vehicle`,`animal`,`face`,`licensePlate`,`package`];function mh(e){let t=Mm(e.aiport);return t.enabled?(Array.isArray(t.pairedCameras)?t.pairedCameras:[]).filter(e=>e&&typeof e==`object`).map(t=>{let n=$(t.deviceId),r=Gm(n,t.name,e.cameras),i=Mm(t.channels),a=Object.keys(i).sort((e,t)=>Number(!e.startsWith(`video`))-Number(!t.startsWith(`video`))||e.localeCompare(t)).map(e=>({name:e,connected:!!i[e]?.connected,bytes:Z(i[e]?.bytesSent),stream:$(i[e]?.streamName)||e}));a.length||a.push({name:`relay`,connected:!!t.relayRunning,bytes:Z(t.bytesSent),stream:`relay`});let o=a.filter(e=>e.connected).length,s=new Set((Array.isArray(t.enabledTypes)?t.enabledTypes:[]).map(e=>String(e))),c=new Set([...s].map(e=>e.toLowerCase())),l=e=>s.has(e)||c.has(e.toLowerCase()),u={face:Z(t.facesDetected),licensePlate:Z(t.platesRecognized),package:Z(t.packagesDetected)},d={licensePlate:!!t.licensePlateEnabled,package:!!t.packageEnabled},f=ph.filter(e=>l(e)||d[e]||(u[e]??0)>0).map(e=>({key:e,count:u[e]??0})),p=[];(t.audioSpeakEnabled||t.audioVadRunning)&&p.push(`Speech`);for(let e of t.audioTypes??t.enabledAudioTypes??t.smartDetectAudioTypes??[]){let t=jm(e);p.includes(t)||p.push(t)}let m=Z(t.width),h=Z(t.height);return{id:n,name:r,showId:!!n&&r!==n,resolution:m&&h?`${m}×${h}`:`—`,fps:Z(t.fps),state:o===a.length?`live`:o>0?`partial`:`idle`,channels:a,bytes:Z(t.bytesSent,a.reduce((e,t)=>e+t.bytes,0)),hwaccelLabel:hh(t),detections:f,audio:p,frames:Z(t.framesAnalyzed),events:Z(t.eventsEmitted),audioEvents:Z(t.audioEventsEmitted)}}):[]}function hh(e){return e.hwaccelBackend===`videotoolbox`?`VideoToolbox`:e.hwaccelBackend===`vaapi`||e.hwaccelBackend===void 0&&e.vaapiActive?`VA-API`:null}function gh(e){return{count:e.length,streaming:e.filter(e=>e.state!==`idle`).length,bytes:e.reduce((e,t)=>e+t.bytes,0),frames:e.reduce((e,t)=>e+t.frames,0),events:e.reduce((e,t)=>e+t.events+t.audioEvents,0),bytesLabel:_m(e.reduce((e,t)=>e+t.bytes,0))}}var _h={"1h":{label:`Last hour`,hours:1},"24h":{label:`Last 24 hours`,hours:24},"7d":{label:`Last 7 days`,hours:168},"30d":{label:`Last 30 days`,hours:720}};function vh(e,t,n,r){let i=new URLSearchParams({range:e,limit:`50`});return t!==`all`&&i.set(`category`,t),n.trim()&&i.set(`q`,n.trim()),r&&i.set(`cursor`,r),`api/history?${i}`}function yh(e,t,n,r,i,a){let o=t-_h[n].hours*36e5,s=e.filter(({timestamp:e})=>e!=null&&e>=o&&e<=t),c=s.filter(e=>(r===`all`||e.categories.includes(r))&&Ym(e,i)),l=Number(a??0);return{items:c.slice(l,l+50),counts:Jm(s),cameraCounts:{},matched:c.length,nextCursor:l+50o&&a.push(e.slice(o,s)),a.push((0,z.jsx)(`mark`,{className:`bg-transparent font-semibold text-foreground underline decoration-info/50 underline-offset-2`,children:e.slice(s,s+n.length)},s)),o=s+n.length,s=r.indexOf(i,o);return o0?`OCR confidence ${Math.round(t*100)}%`:`License plate`,children:[e,t>0&&(0,z.jsxs)(`span`,{className:`font-normal tracking-normal text-muted-foreground`,children:[Math.round(t*100),`%`]})]})}function wh({item:e}){return(0,z.jsx)(z.Fragment,{children:(e.identities??[]).map((e,t)=>{let n=String(e?.name??``).trim();if(!n)return null;let r=String(e?.source??`face`).toLowerCase();if(r===`propagated`)return(0,z.jsxs)(Mp,{tone:`info`,title:e.fromCamera?`Propagated from ${e.fromCamera}`:`Propagated identity`,children:[(0,z.jsx)(be,{className:`size-3`}),n]},`${n}-${t}`);if(r===`lpr`)return(0,z.jsx)(Mp,{tone:`warn`,title:`Vehicle matched by license plate`,children:n},`${n}-${t}`);let i=Z(e?.similarity);return(0,z.jsx)(Mp,{tone:`ok`,title:`Matched by ${r}${i>0?` · ${Math.round(i*100)}% similarity`:``}`,children:n},`${n}-${t}`)})})}function Th({item:e,query:t,now:n,fresh:r,onOpen:i}){let a=Hm(e),o=Xm(e),s=Zm(e),c=String(e.transcript??``).trim(),l=String(e.description??``).trim(),u=(Array.isArray(e.tags)?e.tags:[]).map(String).filter(Boolean),d=Object.entries(e.faces?.rejectedReasons??{}),f=Z(e.timestamp);return(0,z.jsx)(`li`,{children:(0,z.jsxs)(`button`,{type:`button`,onClick:i,className:L(`group grid w-full grid-cols-[auto_minmax(0,1fr)_auto] items-start gap-3.5 px-4 py-3 text-left transition-colors hover:bg-muted/60 focus-visible:bg-muted focus-visible:outline-none sm:gap-4`,r&&`animate-arrive`),children:[(0,z.jsx)(Sh,{item:e}),(0,z.jsxs)(`div`,{className:`min-w-0 space-y-1`,children:[(0,z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,z.jsx)(`span`,{className:L(`text-xs font-medium`,bh[a.tone].text),children:a.label}),(0,z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:(0,z.jsx)(xh,{text:e.cameraName,query:t})}),o.map(e=>(0,z.jsx)(Ch,{...e},e.plate)),(0,z.jsx)(wh,{item:e}),s&&(0,z.jsx)(Mp,{tone:`warn`,children:s})]}),c?(0,z.jsxs)(`p`,{className:`line-clamp-2 text-sm text-foreground/90 italic`,children:[`“`,(0,z.jsx)(xh,{text:c,query:t}),`”`]}):(0,z.jsx)(`p`,{className:L(`line-clamp-2 text-sm`,l?`text-foreground/90`:`text-muted-foreground`),children:l?(0,z.jsx)(xh,{text:l,query:t}):`No description`}),(u.length>0||d.length>0)&&(0,z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground`,children:[u.length>0&&(0,z.jsxs)(`span`,{className:`truncate`,children:[u.slice(0,8).map((e,n)=>(0,z.jsxs)(`span`,{children:[n>0&&(0,z.jsx)(`span`,{className:`px-1 text-muted-foreground/50`,children:`·`}),(0,z.jsx)(xh,{text:e,query:t})]},e)),u.length>8&&(0,z.jsxs)(`span`,{className:`pl-1 text-muted-foreground/70`,children:[`+`,u.length-8]})]}),d.length>0&&(0,z.jsxs)(`span`,{className:`text-warning`,children:[`Face rejected: `,d.map(([e,t])=>`${e} ×${Z(t)}`).join(`, `)]})]})]}),(0,z.jsxs)(`div`,{className:`flex flex-col items-end gap-0.5 pt-0.5 text-right`,children:[(0,z.jsx)(`time`,{dateTime:f>0&&f<=864e13?new Date(f).toISOString():void 0,title:xm(f),className:`font-mono text-xs tabular`,children:bm(f)}),(0,z.jsx)(`span`,{className:`text-xs text-muted-foreground tabular`,children:Cm(f,n)}),Z(e.elapsedMs)>0&&(0,z.jsx)(`span`,{className:`font-mono text-[11px] text-muted-foreground/80 tabular`,title:`Processing time`,children:vm(e.elapsedMs)})]})]})})}var Eh=[];function Dh({history:e,now:t,onOpen:n}){let{page:r,range:i,counts:a,category:o,query:s,setCategory:c,setQuery:l}=e,u=r?.items??Eh,d=(0,_.useRef)(null),[f,p]=(0,_.useState)(u),[m,h]=(0,_.useState)(()=>new Set);if(u!==f){let e=new Set(f.map(e=>e.key));h(new Set(u.filter(t=>!e.has(t.key)).map(e=>e.key))),p(u)}(0,_.useEffect)(()=>{let e=e=>{let t=e.target?.closest(`input, textarea, [contenteditable=true]`);e.key!==`/`||t||e.metaKey||e.ctrlKey||(e.preventDefault(),d.current?.focus())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let g=[];for(let e of u){let n=Z(e.timestamp),r=n>0?Tm(n):`unknown`,i=g[g.length-1];i&&i.key===r||(i={key:r,label:n>0?wm(n,t):`Unknown time`,items:[]},g.push(i)),i.items.push(e)}let v=r?`${Q(r.matched)}${r.matchede.setRange(t.target.value),className:`h-8 cursor-pointer rounded-md border bg-card px-2 text-sm font-medium`,children:Object.entries(_h).map(([e,{label:t}])=>(0,z.jsx)(`option`,{value:e,children:t},e))})]})}),(0,z.jsxs)(`div`,{className:`overflow-hidden rounded-lg border bg-card`,children:[(0,z.jsxs)(`div`,{className:`flex flex-col gap-3 border-b p-3 lg:flex-row lg:items-center lg:justify-between`,children:[(0,z.jsx)(`div`,{className:`-mx-3 overflow-x-auto px-3 md:mx-0 md:px-0`,children:(0,z.jsx)(hm,{type:`single`,variant:`outline`,size:`sm`,value:o,onValueChange:e=>e&&c(e),"aria-label":`Filter events`,children:Vm.map(e=>(0,z.jsxs)(gm,{value:e.key,className:`gap-1.5 px-2.5 text-[13px]`,children:[e.label,(0,z.jsx)(`span`,{className:`font-mono text-[11px] text-muted-foreground tabular`,children:a?Q(a[e.key]):`—`})]},e.key))})}),(0,z.jsxs)(om,{className:`h-8 lg:w-64`,children:[(0,z.jsx)(cm,{children:(0,z.jsx)(Je,{className:`size-3.5`})}),(0,z.jsx)(dm,{ref:d,value:s,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(l(``),e.currentTarget.blur())},id:`activity-search`,name:`q`,autoComplete:`off`,maxLength:512,placeholder:`Search cameras, captions, plates…`,"aria-label":`Search events`,type:`search`}),(0,z.jsx)(cm,{align:`inline-end`,children:s?(0,z.jsx)(um,{size:`icon-xs`,"aria-label":`Clear search`,onClick:()=>l(``),children:(0,z.jsx)(ot,{})}):(0,z.jsx)(fm,{children:`/`})})]})]}),e.incomplete&&(0,z.jsx)(`p`,{role:`status`,className:`border-b px-4 py-3 text-sm text-warning`,children:`Some activity in this period could not be saved. Event totals may be incomplete.`}),e.fallback===`store-unavailable`&&(0,z.jsxs)(`div`,{role:`status`,className:`flex items-center justify-between gap-3 border-b px-4 py-3 text-sm text-warning`,children:[`Saved history is unavailable. Showing recent activity.`,(0,z.jsx)(hp,{size:`sm`,variant:`outline`,onClick:e.refresh,children:`Retry`})]}),e.error&&(0,z.jsxs)(`div`,{role:`status`,className:`flex items-center justify-between gap-3 border-b px-4 py-3 text-sm text-warning`,children:[r?`Activity could not refresh. Showing the last update.`:`Could not load activity history.`,(0,z.jsx)(hp,{size:`sm`,variant:`outline`,onClick:e.refresh,children:`Retry`})]}),r?u.length===0?(0,z.jsx)($p,{className:`rounded-none py-14`,children:(0,z.jsxs)(em,{children:[(0,z.jsx)(nm,{variant:`icon`,children:(0,z.jsx)(ne,{strokeWidth:1.75})}),(0,z.jsx)(rm,{children:r.counts.all?`No matching events`:`No recorded activity in this time range`}),(0,z.jsx)(im,{children:r.counts.all?`Try another category or search term.`:i===`30d`?`No events are available for the last 30 days.`:`Choose a longer range to see earlier events.`})]})}):(0,z.jsx)(`div`,{children:g.map(e=>(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`p`,{className:`sticky top-14 z-10 border-b bg-card/95 px-4 py-1.5 text-[11.5px] font-medium text-muted-foreground backdrop-blur`,children:e.label}),(0,z.jsx)(`ul`,{className:`divide-y`,children:e.items.map(e=>(0,z.jsx)(Th,{item:e,query:s,now:t,fresh:m.has(e.key),onOpen:()=>n(e)},e.key))})]},e.key))}):!e.error&&(0,z.jsx)(`p`,{role:`status`,className:`py-14 text-center text-sm text-muted-foreground`,children:`Loading activity…`}),(e.hasPrevious||r?.nextCursor)&&(0,z.jsxs)(`nav`,{"aria-label":`Activity pages`,className:`flex justify-end gap-2 border-t px-3 py-2`,children:[(0,z.jsxs)(hp,{variant:`outline`,size:`sm`,disabled:!e.hasPrevious,onClick:e.previous,children:[(0,z.jsx)(fe,{}),` Newer events`]}),(0,z.jsxs)(hp,{variant:`outline`,size:`sm`,disabled:!r?.nextCursor,onClick:e.next,children:[`Older events `,(0,z.jsx)(me,{})]})]})]})]})}function Oh({className:e,...t}){return(0,z.jsx)(`div`,{"data-slot":`table-container`,className:`relative w-full overflow-x-auto`,children:(0,z.jsx)(`table`,{"data-slot":`table`,className:L(`w-full caption-bottom text-sm`,e),...t})})}function kh({className:e,...t}){return(0,z.jsx)(`thead`,{"data-slot":`table-header`,className:L(`[&_tr]:border-b`,e),...t})}function Ah({className:e,...t}){return(0,z.jsx)(`tbody`,{"data-slot":`table-body`,className:L(`[&_tr:last-child]:border-0`,e),...t})}function jh({className:e,...t}){return(0,z.jsx)(`tr`,{"data-slot":`table-row`,className:L(`border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted`,e),...t})}function Mh({className:e,...t}){return(0,z.jsx)(`th`,{"data-slot":`table-head`,className:L(`h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0`,e),...t})}function Nh({className:e,...t}){return(0,z.jsx)(`td`,{"data-slot":`table-cell`,className:L(`p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0`,e),...t})}var Ph={person:{icon:nt,label:`Person`},vehicle:{icon:ie,label:`Vehicle`},animal:{icon:Pe,label:`Animal`},face:{icon:He,label:`Face`},licensePlate:{icon:Re,label:`License plate`},package:{icon:Ae,label:`Package`}};function Fh({cam:e}){return(0,z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1`,children:[e.detections.map(({key:e,count:t})=>{let n=Ph[e],r=n.icon;return(0,z.jsxs)(wp,{children:[(0,z.jsx)(Tp,{asChild:!0,children:(0,z.jsxs)(`span`,{className:L(`inline-flex h-6 items-center gap-1 rounded-md border bg-background px-1.5 text-muted-foreground`,t>0&&`border-info/30 bg-info-soft text-info`),children:[(0,z.jsx)(r,{className:`size-3.5`,strokeWidth:1.75}),t>0&&(0,z.jsx)(`span`,{className:`font-mono text-[11px] tabular`,children:Q(t)})]})}),(0,z.jsxs)(Ep,{children:[n.label,t>0?` · ${Q(t)} detected`:``]})]},e)}),e.audio.length>0&&(0,z.jsxs)(wp,{children:[(0,z.jsx)(Tp,{asChild:!0,children:(0,z.jsxs)(`span`,{className:`inline-flex h-6 items-center gap-1 rounded-md border bg-background px-1.5 text-muted-foreground`,children:[(0,z.jsx)(M,{className:`size-3.5`,strokeWidth:1.75}),(0,z.jsx)(`span`,{className:`text-[11px]`,children:e.audio.length})]})}),(0,z.jsxs)(Ep,{children:[`Audio: `,e.audio.join(`, `)]})]})]})}function Ih({cam:e}){return(0,z.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:e.channels.map(e=>(0,z.jsxs)(wp,{children:[(0,z.jsx)(Tp,{asChild:!0,children:(0,z.jsxs)(`span`,{className:L(`inline-flex h-6 items-center gap-1.5 rounded-md border bg-background px-2 font-mono text-[11px]`,!e.connected&&`text-muted-foreground`),children:[(0,z.jsx)(Ap,{tone:e.connected?`ok`:`off`}),e.name]})}),(0,z.jsxs)(Ep,{children:[e.connected?`Streaming`:`Idle`,` · `,_m(e.bytes),` relayed`,(0,z.jsx)(`span`,{className:`block font-mono opacity-70`,children:e.stream})]})]},e.name))})}var Lh={live:`All channels streaming`,partial:`Some channels idle`,idle:`Not streaming`};function Rh({cameras:e,aiportEnabled:t,range:n,cameraCounts:r,incomplete:i}){let a=gh(e);return(0,z.jsxs)(`section`,{id:`cameras`,className:`scroll-mt-28`,children:[(0,z.jsx)(Zp,{title:`Cameras`,meta:e.length?`${a.streaming} of ${a.count} streaming · ${a.bytesLabel} relayed`:void 0}),e.length===0?(0,z.jsx)($p,{className:`border bg-card`,children:(0,z.jsxs)(em,{children:[(0,z.jsx)(nm,{variant:`icon`,children:(0,z.jsx)(oe,{strokeWidth:1.75})}),(0,z.jsx)(rm,{children:`No paired cameras`}),(0,z.jsx)(im,{children:t?`Adopt the virtual AI Port in UniFi Protect and pair ONVIF cameras to it. They’ll show up here.`:`The virtual AI Port is off. Set aiport.enabled: true to run smart detections on ONVIF cameras.`})]})}):(0,z.jsx)(`div`,{className:`overflow-hidden rounded-lg border bg-card`,children:(0,z.jsxs)(Oh,{children:[(0,z.jsx)(kh,{children:(0,z.jsxs)(jh,{className:`hover:bg-transparent`,children:[(0,z.jsx)(Mh,{className:`h-10 pl-4 text-xs font-medium text-muted-foreground`,children:`Camera`}),(0,z.jsx)(Mh,{className:`hidden h-10 text-xs font-medium text-muted-foreground sm:table-cell`,children:`Stream`}),(0,z.jsx)(Mh,{className:`hidden h-10 text-xs font-medium text-muted-foreground lg:table-cell`,children:`Channels`}),(0,z.jsx)(Mh,{className:`h-10 text-xs font-medium text-muted-foreground`,children:`Detections`}),(0,z.jsx)(Mh,{className:`hidden h-10 text-right text-xs font-medium text-muted-foreground md:table-cell`,title:`Frames analyzed since Keystone started`,children:`Frames`}),(0,z.jsxs)(Mh,{className:`h-10 pr-4 text-right text-xs font-medium text-muted-foreground`,title:n?`AI Port events emitted · ${_h[n].label}`:`AI Port events emitted since startup`,children:[`Events `,(0,z.jsxs)(`span`,{className:`font-normal`,children:[`· `,n??`session`]})]})]})}),(0,z.jsx)(Ah,{children:e.map(e=>(0,z.jsxs)(jh,{className:`h-14`,children:[(0,z.jsx)(Nh,{className:`max-w-56 pl-4`,children:(0,z.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,z.jsxs)(wp,{children:[(0,z.jsx)(Tp,{asChild:!0,children:(0,z.jsx)(`span`,{className:`grid size-4 place-items-center`,children:(0,z.jsx)(Ap,{tone:e.state===`live`?`ok`:e.state===`partial`?`warn`:`off`})})}),(0,z.jsx)(Ep,{children:Lh[e.state]})]}),(0,z.jsxs)(`div`,{className:`min-w-0`,children:[(0,z.jsx)(`p`,{className:`truncate font-medium`,children:e.name}),e.showId&&(0,z.jsx)(`p`,{className:`truncate font-mono text-[11px] text-muted-foreground`,children:e.id})]})]})}),(0,z.jsx)(Nh,{className:`hidden sm:table-cell`,children:(0,z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,z.jsxs)(`span`,{className:`font-mono text-xs tabular`,children:[e.resolution,e.fps?(0,z.jsxs)(`span`,{className:`text-muted-foreground`,children:[` · `,e.fps,` fps`]}):null]}),e.hwaccelLabel&&(0,z.jsx)(Mp,{tone:`info`,title:`Hardware video decode via ${e.hwaccelLabel}`,children:e.hwaccelLabel})]})}),(0,z.jsx)(Nh,{className:`hidden lg:table-cell`,children:(0,z.jsx)(Ih,{cam:e})}),(0,z.jsx)(Nh,{children:(0,z.jsx)(Fh,{cam:e})}),(0,z.jsx)(Nh,{className:`hidden text-right font-mono text-xs tabular md:table-cell`,children:Q(e.frames)}),(0,z.jsxs)(Nh,{className:`pr-4 text-right font-mono text-xs tabular`,title:i?`Some events in this period could not be saved`:void 0,children:[i&&`≥`,n?r?Q(r[e.id]??0):`—`:Q(e.events+e.audioEvents)]})]},e.id||e.name))})]})})]})}function zh({...e}){return(0,z.jsx)(Wr,{"data-slot":`collapsible`,...e})}function Bh({...e}){return(0,z.jsx)(Kr,{"data-slot":`collapsible-trigger`,...e})}function Vh({...e}){return(0,z.jsx)(Jr,{"data-slot":`collapsible-content`,...e})}function Hh({title:e,children:t}){return(0,z.jsxs)(`section`,{className:`space-y-2`,children:[(0,z.jsx)(`h3`,{className:`text-[13px] font-medium text-muted-foreground`,children:e}),t]})}function Uh({rows:e}){let t=e.filter(([,e])=>e!=null&&e!==``);return t.length?(0,z.jsx)(`dl`,{className:`divide-y rounded-lg border bg-card text-sm`,children:t.map(([e,t])=>(0,z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-3 py-2`,children:[(0,z.jsx)(`dt`,{className:`text-muted-foreground`,children:e}),(0,z.jsx)(`dd`,{className:`text-right font-mono text-xs tabular`,children:t})]},e))}):null}function Wh({item:e,onOpenChange:t}){return(0,z.jsx)(Fp,{open:!!e,onOpenChange:t,children:(0,z.jsx)(Rp,{className:`w-full gap-0 outline-none sm:max-w-lg`,onOpenAutoFocus:Sp,children:e&&(0,z.jsx)(Gh,{item:e})})})}function Gh({item:e}){let t=Hm(e),n=Xm(e),r=Zm(e),i=String(e.transcript??``).trim(),a=String(e.description??``).trim(),o=(Array.isArray(e.tags)?e.tags:[]).map(String).filter(Boolean),s=(e.identities??[]).filter(e=>e&&String(e.name??``).trim()),c=e.faces,l=Object.entries(c?.rejectedReasons??{}),{thumbnail:u,categories:d,key:f,...p}=e;return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(zp,{className:`border-b`,children:(0,z.jsxs)(`div`,{className:`flex items-start gap-4 pr-8`,children:[(0,z.jsx)(Sh,{item:e,size:`lg`}),(0,z.jsxs)(`div`,{className:`min-w-0 space-y-1.5`,children:[(0,z.jsx)(`p`,{className:L(`text-xs font-medium`,bh[t.tone].text),children:t.label}),(0,z.jsx)(Vp,{className:`text-lg leading-tight tracking-[-0.02em]`,children:e.cameraName}),(0,z.jsx)(Hp,{className:`tabular`,children:xm(e.timestamp)}),(0,z.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 pt-0.5`,children:[n.map(e=>(0,z.jsx)(Ch,{...e},e.plate)),(0,z.jsx)(wh,{item:e}),r&&(0,z.jsx)(Mp,{tone:`warn`,children:r})]})]})]})}),(0,z.jsxs)(`div`,{className:`flex-1 space-y-6 overflow-y-auto p-4`,children:[i?(0,z.jsx)(Hh,{title:`Transcript`,children:(0,z.jsxs)(`blockquote`,{className:`border-l-2 border-info/50 pl-3 text-[15px] leading-relaxed`,children:[`“`,i,`”`]})}):(0,z.jsx)(Hh,{title:`Description`,children:(0,z.jsx)(`p`,{className:L(`text-[15px] leading-relaxed`,!a&&`text-muted-foreground`),children:a||`No description`})}),o.length>0&&(0,z.jsx)(Hh,{title:`Tags`,children:(0,z.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:o.map(e=>(0,z.jsx)(Mp,{children:e},e))})}),s.length>0&&(0,z.jsx)(Hh,{title:`Identities`,children:(0,z.jsx)(`div`,{className:`divide-y rounded-lg border bg-card text-sm`,children:s.map((e,t)=>(0,z.jsxs)(`div`,{className:`flex items-center justify-between gap-3 px-3 py-2`,children:[(0,z.jsxs)(`div`,{className:`min-w-0`,children:[(0,z.jsx)(`p`,{className:`truncate font-medium`,children:e.name}),(0,z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[String(e.source??`face`),e.fromCamera?` from ${e.fromCamera}`:``,Z(e.secondsAgo)>0?` · ${Z(e.secondsAgo)}s earlier`:``]})]}),(0,z.jsxs)(`div`,{className:`text-right font-mono text-xs tabular`,children:[Z(e.similarity)>0&&(0,z.jsx)(`p`,{children:ym(e.similarity)}),Z(e.margin)>0&&(0,z.jsxs)(`p`,{className:`text-muted-foreground`,children:[`margin `,Z(e.margin).toFixed(2)]})]})]},`${e.name}-${t}`))})}),n.length>0&&(0,z.jsx)(Hh,{title:`License plates`,children:(0,z.jsx)(Uh,{rows:n.map(e=>[e.plate,e.confidence>0?ym(e.confidence):`—`])})}),c&&(Z(c.framesScanned)>0||Z(c.detections)>0)&&(0,z.jsxs)(Hh,{title:`Face scan`,children:[(0,z.jsx)(Uh,{rows:[[`Frames scanned`,Z(c.framesScanned)],[`Faces detected`,Z(c.detections)],[`Passed quality gate`,Z(c.qualityFaces)],[`Scan time`,Z(c.elapsedMs)>0?vm(c.elapsedMs):null]]}),l.length>0&&(0,z.jsx)(`ul`,{className:`space-y-1.5 pt-1`,children:l.map(([e,t])=>(0,z.jsxs)(`li`,{className:`flex gap-2 text-xs`,children:[(0,z.jsxs)(Mp,{tone:`warn`,children:[e,` ×`,Z(t)]}),(0,z.jsx)(`span`,{className:`pt-0.5 text-muted-foreground`,children:Em[e]??`Quality gate`})]},e))})]}),(0,z.jsx)(Hh,{title:`Processing`,children:(0,z.jsx)(Uh,{rows:[[`Total time`,Z(e.elapsedMs)>0?vm(e.elapsedMs):null],[`Objects indexed`,Z(e.indexedObjects)>0?Z(e.indexedObjects):null],[`Speech segments`,Z(e.sttSegments)>0?Z(e.sttSegments):null],[`Audio length`,Z(e.audioSeconds)>0?`${Z(e.audioSeconds).toFixed(1)}s`:null],[`Packages`,Z(e.packageCount)>0?Z(e.packageCount):null],[`Source`,e.source?String(e.source):null],[`Event ID`,e.eventId?String(e.eventId):null]]})}),(0,z.jsxs)(zh,{children:[(0,z.jsxs)(Bh,{className:`group flex items-center gap-1 text-[13px] font-medium text-muted-foreground hover:text-foreground`,children:[(0,z.jsx)(ue,{className:`size-3.5 transition-transform group-data-[state=closed]:-rotate-90`}),`Raw event`]}),(0,z.jsx)(Vh,{className:`pt-2`,children:(0,z.jsx)(`div`,{className:`rounded-lg border bg-card px-3 py-1.5`,children:(0,z.jsx)(yp,{data:p})})})]})]}),(0,z.jsx)(Bp,{className:`border-t`,children:(0,z.jsx)(xp,{data:p})})]})}function Kh({values:e,className:t,label:n}){let r=(0,_.useId)();if(e.length<2)return(0,z.jsx)(`div`,{className:L(`h-7`,t),"aria-hidden":`true`});let i=Math.max(...e,1),a=Math.min(...e,0),o=i-a||1,s=120/(e.length-1),c=e.map((e,t)=>[t*s,25-(e-a)/o*21]),l=c.map(([e,t],n)=>`${n?`L`:`M`}${e.toFixed(1)},${t.toFixed(1)}`).join(` `),u=`${l} L120,28 L0,28 Z`,d=c[c.length-1][1];return(0,z.jsxs)(`div`,{className:L(`relative h-7 w-full text-info`,t),role:`img`,"aria-label":n,children:[(0,z.jsxs)(`svg`,{viewBox:`0 0 120 28`,preserveAspectRatio:`none`,className:`absolute inset-0 size-full overflow-visible`,children:[(0,z.jsx)(`defs`,{children:(0,z.jsxs)(`linearGradient`,{id:r,x1:`0`,x2:`0`,y1:`0`,y2:`1`,children:[(0,z.jsx)(`stop`,{offset:`0%`,stopColor:`currentColor`,stopOpacity:`0.2`}),(0,z.jsx)(`stop`,{offset:`100%`,stopColor:`currentColor`,stopOpacity:`0`})]})}),(0,z.jsx)(`path`,{d:u,fill:`url(#${r})`}),(0,z.jsx)(`path`,{d:l,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,vectorEffect:`non-scaling-stroke`})]}),(0,z.jsx)(`span`,{className:`absolute size-1.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-current`,style:{left:`100%`,top:`${d/28*100}%`},"aria-hidden":`true`,children:(0,z.jsx)(`span`,{className:`absolute inset-0 rounded-full bg-current animate-ping-slow`})})]})}function qh({label:e,value:t}){let[n,r]=(0,_.useState)(!1);return(0,z.jsxs)(wp,{open:n||void 0,children:[(0,z.jsx)(Tp,{asChild:!0,children:(0,z.jsxs)(`button`,{type:`button`,onClick:async()=>{try{await navigator.clipboard.writeText(t),r(!0),window.setTimeout(()=>r(!1),1400)}catch{}},className:`group inline-flex h-7 items-center gap-2 rounded-md border bg-card px-2.5 text-xs transition-colors hover:border-border-strong`,children:[(0,z.jsx)(`span`,{className:`text-muted-foreground`,children:e}),(0,z.jsx)(`span`,{className:`font-mono text-foreground`,children:t}),n?(0,z.jsx)(ce,{className:`size-3 text-success`}):(0,z.jsx)(ve,{className:`size-3 text-muted-foreground/60 transition-colors group-hover:text-muted-foreground`})]})}),(0,z.jsx)(Ep,{children:n?`Copied`:`Copy ${e}`})]})}var Jh={ok:ge,info:ge,warn:et,error:F,off:ge};function Yh({status:e,health:t,cameras:n,history:r,lastUpdated:i,generatedAt:a,demo:o,accel:s,now:c,onOpenService:l}){let u=((e.control??{}).protectVersion??``).trim(),d=Jh[t.tone],f=dh(e),p=[f.adoption];u&&p.push(`Protect ${u}`),p.push(t.detail),o?p.push(`sample data`):a?p.push(`snapshot from ${Sm(a)}`):i&&p.push(`updated ${Cm(i,c)}`);let m=[];return e.mac&&m.push({label:`MAC`,value:e.mac}),e.advertiseIp&&m.push({label:`IP`,value:e.advertiseIp}),e.controllerHost&&m.push({label:`Controller`,value:e.controllerHost}),(0,z.jsxs)(`section`,{id:`top`,className:`scroll-mt-20 pt-10 pb-2 sm:pt-14`,children:[(0,z.jsx)(`p`,{className:`text-[13px] font-medium text-muted-foreground`,children:f.subtitle}),(0,z.jsxs)(`h1`,{className:`mt-2 flex items-center gap-3 text-3xl font-semibold tracking-[-0.045em] text-balance sm:text-[40px] sm:leading-[1.1]`,children:[(0,z.jsx)(d,{className:L(`size-7 shrink-0 sm:size-8`,Dp[t.tone]),strokeWidth:2}),t.title]}),(0,z.jsx)(`p`,{className:`mt-3 max-w-[68ch] text-base text-muted-foreground`,children:p.join(` · `)}),t.attention.length>0&&(0,z.jsx)(`div`,{className:`mt-4 flex flex-wrap gap-2`,children:t.attention.map(e=>(0,z.jsxs)(`button`,{type:`button`,onClick:()=>l(e),className:`group inline-flex h-7 items-center gap-2 rounded-md border bg-card pr-1.5 pl-2 text-xs transition-colors hover:border-border-strong`,children:[(0,z.jsx)(jp,{tone:e.tone,className:`-ml-1 h-5`,children:e.state}),(0,z.jsx)(`span`,{className:`font-medium`,children:e.title}),(0,z.jsx)(me,{className:`size-3.5 text-muted-foreground transition-transform group-hover:translate-x-0.5`})]},e.id))}),m.length>0&&(0,z.jsxs)(`div`,{className:`mt-5 flex flex-wrap gap-2`,children:[m.map(e=>(0,z.jsx)(qh,{...e},e.label)),(0,z.jsxs)(`span`,{className:L(`inline-flex h-7 items-center gap-1.5 rounded-md border bg-card px-2.5 font-mono text-xs md:hidden`,s.warning?`text-warning`:s.hardware?`text-info`:`text-muted-foreground`),children:[(0,z.jsx)(Se,{className:`size-3.5`,strokeWidth:1.75}),s.label]}),s.warning&&(0,z.jsx)(`p`,{className:`w-full rounded-md bg-warning-soft px-2.5 py-2 text-xs leading-relaxed text-warning md:hidden`,children:s.warning})]}),(0,z.jsx)(Qh,{status:e,cameras:n,history:r,snapshot:!!a})]})}function Xh({label:e,value:t,unit:n,sub:r,children:i,tone:a}){return(0,z.jsxs)(`div`,{className:`flex min-h-[116px] flex-col rounded-lg border bg-card px-5 pt-4 pb-4`,children:[(0,z.jsx)(`p`,{className:`text-[13px] font-medium text-muted-foreground`,children:e}),(0,z.jsxs)(`p`,{className:`mt-2.5 flex items-baseline gap-1.5 truncate`,children:[(0,z.jsx)(`span`,{className:`text-xl font-medium tracking-[-0.025em] tabular`,children:t}),n&&(0,z.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:n})]}),i,r&&(0,z.jsx)(`p`,{className:L(`mt-auto pt-1 text-[13px] text-muted-foreground tabular`,a&&Dp[a]),children:r})]})}function Zh(e,t){let n=[];for(let r=1;r0&&a>=0?a/i:0)}return n}function Qh({status:e,cameras:t,history:n,snapshot:r}){let i=gh(t),a=Zh(n,`frames`),o=a.length?a[a.length-1]:null,s=e.worker??{},c=Z(s.completed),l=Z(s.failed),u=e.aiport??{};return(0,z.jsxs)(`div`,{className:`mt-8 grid grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-4`,children:[(0,z.jsx)(Xh,{label:`Cameras`,value:Q(i.count),unit:i.count?`paired`:void 0,sub:i.count?`${i.streaming} streaming · ${i.bytesLabel} relayed`:`No AI Port cameras yet`}),(0,z.jsx)(Xh,{label:`Frames analyzed`,value:o==null?Q(i.frames):o.toFixed(1),unit:o==null?void 0:`fps`,sub:o==null?r||!i.count?`Across ${i.count} camera${i.count===1?``:`s`}`:`Live rate appears after a few seconds`:`${Q(i.frames)} total`,children:a.length>=2&&(0,z.jsx)(Kh,{values:a,className:`mt-2`,label:`Frames analyzed per second`})}),(0,z.jsx)(Xh,{label:`Captions`,value:Q(c),unit:`done`,tone:ah(s)>=3?`error`:void 0,sub:`${vm(s.avgLatencyMs)} avg${l?` · ${Q(l)} failed`:``}`}),(0,z.jsx)(Xh,{label:`Smart detections since startup`,value:Q(u.totalSmartEvents),sub:`${Q(u.totalAudioEvents)} audio · ${Q(u.totalFaces)} faces · ${Q(u.totalPlates)} plates`})]})}function $h({...e}){return(0,z.jsx)(sd,{"data-slot":`dropdown-menu`,...e})}function eg({...e}){return(0,z.jsx)(ld,{"data-slot":`dropdown-menu-trigger`,...e})}function tg({className:e,align:t=`start`,sideOffset:n=4,...r}){return(0,z.jsx)(ud,{children:(0,z.jsx)(fd,{"data-slot":`dropdown-menu-content`,sideOffset:n,align:t,className:L(`z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) min-w-32 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:overflow-hidden data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95`,e),...r})})}function ng({...e}){return(0,z.jsx)(md,{"data-slot":`dropdown-menu-radio-group`,...e})}function rg({className:e,children:t,inset:n,...r}){return(0,z.jsxs)(hd,{"data-slot":`dropdown-menu-radio-item`,"data-inset":n,className:L(`relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,e),...r,children:[(0,z.jsx)(`span`,{className:`pointer-events-none absolute right-2 flex items-center justify-center`,"data-slot":`dropdown-menu-radio-item-indicator`,children:(0,z.jsx)(gd,{children:(0,z.jsx)(ce,{})})}),t]})}function ig({className:e,inset:t,...n}){return(0,z.jsx)(pd,{"data-slot":`dropdown-menu-label`,"data-inset":t,className:L(`px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7`,e),...n})}function ag({className:e,...t}){return(0,z.jsx)(_d,{"data-slot":`dropdown-menu-separator`,className:L(`-mx-1 my-1 h-px bg-border`,e),...t})}function og({...e}){return(0,z.jsx)(Ed,{"data-slot":`popover`,...e})}function sg({...e}){return(0,z.jsx)(Od,{"data-slot":`popover-trigger`,...e})}function cg({className:e,align:t=`center`,sideOffset:n=4,...r}){return(0,z.jsx)(Md,{children:(0,z.jsx)(Pd,{"data-slot":`popover-content`,align:t,sideOffset:n,className:L(`z-50 flex w-72 origin-(--radix-popover-content-transform-origin) flex-col gap-2.5 rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95`,e),...r})})}function lg({className:e,orientation:t=`horizontal`,decorative:n=!0,...r}){return(0,z.jsx)(df,{"data-slot":`separator`,decorative:n,orientation:t,className:L(`shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch`,e),...r})}function ug(e,t){return e.map(e=>Z(e.timestamp)>0?{...e,timestamp:Z(e.timestamp)+t}:e)}function dg(e,t,n){let r=e.aiport?.pairedCameras;if(!Array.isArray(r)||!r.length)return e;let i=r.map((e,r)=>{let i=e.channels??{};if(!(Object.values(i).some(e=>e?.connected)||e.relayRunning))return e;let a=Z(e.fps,15)*(.45+.15*Math.sin(n/9+r*1.7)),o=Object.fromEntries(Object.entries(i).map(([e,n])=>[e,n?.connected?{...n,bytesSent:Z(n.bytesSent)+Math.round(t*18e4)}:n])),s=Object.values(o).reduce((e,t)=>e+Z(t?.bytesSent),0)-Object.values(i).reduce((e,t)=>e+Z(t?.bytesSent),0);return{...e,channels:o,framesAnalyzed:Z(e.framesAnalyzed)+Math.round(t*a),bytesSent:Z(e.bytesSent)+s}});return{...e,aiport:{...e.aiport,pairedCameras:i}}}function fg(e,t){let n=String(t.kind??t.type??``).toLowerCase(),r=n===`stt`||n===`speechtotext`,i=n===`audio`,a=!r&&!i,o=Xm(t).length,s=(t.identities??[]).filter(e=>String(e?.source??``).toLowerCase()===`face`).length,c=Math.max(Z(t.faces?.qualityFaces),s),l=!!(t.faces&&Z(t.faces.framesScanned)>0),u={...e.aiport};u.pairedCameras=(u.pairedCameras??[]).map(e=>!e.deviceId||e.deviceId!==t.cameraId||r?e:{...e,eventsEmitted:Z(e.eventsEmitted)+ +!!a,audioEventsEmitted:Z(e.audioEventsEmitted)+ +!!i,platesRecognized:Z(e.platesRecognized)+o,facesDetected:Z(e.facesDetected)+c,packagesDetected:Z(e.packagesDetected)+ +(n===`package`)}),a&&(u.totalSmartEvents=Z(u.totalSmartEvents)+1),i&&(u.totalAudioEvents=Z(u.totalAudioEvents)+1),n===`package`&&(u.totalPackages=Z(u.totalPackages)+1),o&&(u.totalPlates=Z(u.totalPlates)+o),c&&(u.totalFaces=Z(u.totalFaces)+c);let d={...e,aiport:u};if((n===``||n===`caption`)&&(d.worker={...e.worker,completed:Z(e.worker?.completed)+1}),r){let n=Z(e.stt?.completed??e.stt?.transcriptions)+1;d.stt={...e.stt,completed:n,transcriptions:n,segments:Z(e.stt?.segments)+Z(t.sttSegments)}}return o&&(d.lpr={...e.lpr,platesRecognized:Z(e.lpr?.platesRecognized)+o}),(l||s)&&(d.faces={...e.faces,eventsScanned:Z(e.faces?.eventsScanned)+1,facesMatched:Z(e.faces?.facesMatched)+s}),d}var pg=3e3,mg=8e3,hg=14,gg=4;function _g(){try{let e=document.getElementById(`keystone-initial-data`);if(e?.textContent){let t=JSON.parse(e.textContent);if(t&&typeof t==`object`)return t}}catch{}return{}}function vg(){return window.location.protocol===`http:`||window.location.protocol===`https:`}function yg(e){let t=Array.isArray(e.aiport?.pairedCameras)?e.aiport.pairedCameras:[];return{frames:t.reduce((e,t)=>e+Z(t?.framesAnalyzed),0),events:t.reduce((e,t)=>e+Z(t?.eventsEmitted)+Z(t?.audioEventsEmitted),0),captions:Z(e.worker?.completed)}}async function bg(e,t){let n=await fetch(e,{cache:`no-store`,signal:t});if(!n.ok)throw Error(`${e} → HTTP ${n.status}`);return await n.json()}function xg(e,t,n){let r=e.status??{},i=Array.isArray(e.events)?e.events:[],a=Array.isArray(e.activity)?e.activity:[],o=Object.keys(r).length>0,s=Date.now();if(n){let t=Z(e.generatedAt)||Math.max(0,...[...i,...a].map(e=>Z(e.timestamp))),n=t>0?s-t:0,o=r,c=[];for(let e=hg;e>=0;e--){let t=s-e*pg;eSg(e)),n=vg()&&!t,r=!!(e.status&&Object.keys(e.status).length),[i]=(0,_.useState)(()=>xg(e,n,t)),[a,o]=(0,_.useState)(i.status),[s,c]=(0,_.useState)(i.events),[l,u]=(0,_.useState)(i.activity),[d,f]=(0,_.useState)(n||!!t),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(r),[v,y]=(0,_.useState)(i.lastUpdated),[b,x]=(0,_.useState)(i.history),S=(0,_.useRef)(null),C=(0,_.useRef)(i.status),w=(0,_.useRef)(0),T=(0,_.useRef)(Array.isArray(t?.queue)?[...t.queue]:[]),E=(0,_.useRef)(!r),D=(0,_.useCallback)(async()=>{if(!n)return;S.current?.abort();let e=new AbortController;S.current=e;let t=window.setTimeout(()=>e.abort(),mg);try{let[t,n,r]=await Promise.all([bg(`api/status`,e.signal),bg(`api/events`,e.signal),bg(`api/activity`,e.signal)]);if(!t||typeof t!=`object`)throw Error(`Malformed /api/status payload`);let i=Date.now();o(t),c(Array.isArray(n?.events)?n.events:[]),u(Array.isArray(r?.activity)?r.activity:[]),y(i),m(!1),g(!0),x(e=>[...e,{t:i,...yg(t)}].slice(-40))}catch(t){if(e.signal.aborted&&S.current!==e)return;m(!0),t instanceof DOMException||console.warn(`Keystone poll failed:`,t)}finally{window.clearTimeout(t)}},[n]);(0,_.useEffect)(()=>{if(!n||!d)return;let e,t=()=>{document.visibilityState===`visible`&&D()},r=()=>{window.clearInterval(e),e=window.setInterval(t,pg)},i=()=>{document.visibilityState===`visible`?(D(),r()):window.clearInterval(e)},a=E.current?window.setTimeout(t,0):void 0;return E.current=!1,r(),document.addEventListener(`visibilitychange`,i),()=>{window.clearTimeout(a),window.clearInterval(e),document.removeEventListener(`visibilitychange`,i);let t=S.current;S.current=null,t?.abort()}},[n,d,D]),(0,_.useEffect)(()=>{C.current=a},[a]),(0,_.useEffect)(()=>{if(!t||!d)return;let e=window.setInterval(()=>{if(document.visibilityState!==`visible`)return;let e=Date.now();w.current+=1;let t=dg(C.current,pg/1e3,e/1e3);if(w.current%gg===2&&T.current.length){let n={...T.current.shift(),timestamp:e};t=fg(t,n),u(e=>[n,...e].slice(0,60))}C.current=t,o(t),y(e),x(n=>[...n,{t:e,...yg(t)}].slice(-40))},pg);return()=>window.clearInterval(e)},[t,d]);let O=(0,_.useCallback)(e=>{f(e),e&&D()},[D]),k;return k=t?d?`demo`:`paused`:n?d?p?`reconnecting`:h?`live`:`connecting`:`paused`:`snapshot`,{status:a,events:s,activity:l,connection:k,lastUpdated:v,generatedAt:Z(e.generatedAt)>0?Z(e.generatedAt):null,demo:t,history:b,live:d,setLive:O,refresh:D}}function wg({className:e}){return(0,z.jsxs)(`svg`,{viewBox:`0 0 24 24`,className:L(`size-6 shrink-0`,e),"aria-hidden":`true`,children:[(0,z.jsx)(`rect`,{width:`24`,height:`24`,rx:`6`,className:`fill-foreground`}),(0,z.jsxs)(`g`,{transform:`translate(0 0.2)`,children:[(0,z.jsx)(`path`,{d:`M4 18.6L4 15.2A8 8 0 0 1 8.37 8.07L10.18 11.64A4 4 0 0 0 8 15.2L8 18.6Z`,className:`fill-background`}),(0,z.jsx)(`path`,{d:`M9.53 7.59A8 8 0 0 1 14.47 7.59L13.24 11.4A4 4 0 0 0 10.76 11.4Z`,className:`fill-mark-key`}),(0,z.jsx)(`path`,{d:`M15.63 8.07A8 8 0 0 1 20 15.2L20 18.6L16 18.6L16 15.2A4 4 0 0 0 13.82 11.64Z`,className:`fill-background`})]})]})}var Tg={live:{label:`Live`,tone:`ok`},demo:{label:`Demo`,tone:`info`},connecting:{label:`Connecting`,tone:`info`},reconnecting:{label:`Reconnecting`,tone:`warn`},paused:{label:`Paused`,tone:`off`},snapshot:{label:`Snapshot`,tone:`off`}};function Eg({connection:e,live:t,setLive:n,lastUpdated:r}){let i=Tg[e];if(e===`snapshot`)return(0,z.jsxs)(wp,{children:[(0,z.jsx)(Tp,{asChild:!0,children:(0,z.jsxs)(`span`,{className:`inline-flex h-7 items-center gap-2 rounded-md border px-2.5 text-xs font-medium text-muted-foreground`,children:[(0,z.jsx)(Ap,{tone:`off`}),`Snapshot`]})}),(0,z.jsx)(Ep,{children:`Static export. Open the served dashboard for live data.`})]});let a=Math.round(pg/1e3);return(0,z.jsxs)(wp,{children:[(0,z.jsx)(Tp,{asChild:!0,children:(0,z.jsxs)(hp,{variant:`outline`,size:`sm`,onClick:()=>n(!t),"aria-pressed":t,className:`gap-2 font-medium tabular`,children:[(0,z.jsx)(Ap,{tone:i.tone,pulse:e===`live`||e===`demo`}),i.label,t?(0,z.jsx)(Me,{className:`size-3 text-muted-foreground`}):(0,z.jsx)(Ie,{className:`size-3 text-muted-foreground`})]})}),(0,z.jsxs)(Ep,{children:[e===`demo`?`Sample data, animated in your browser · click to pause`:t?`Refreshing every ${a}s · click to pause`:`Paused · click to resume`,r&&e!==`demo`?` · updated ${bm(r)}`:``]})]})}function Dg({accel:e}){return(0,z.jsxs)(og,{children:[(0,z.jsx)(sg,{asChild:!0,children:(0,z.jsxs)(hp,{variant:`ghost`,size:`sm`,className:L(`gap-1.5 font-mono text-xs font-normal`,e.warning?`text-warning`:e.hardware?`text-info`:`text-muted-foreground`),children:[e.warning?(0,z.jsx)(et,{className:`size-3.5`,strokeWidth:1.75}):(0,z.jsx)(Se,{className:`size-3.5`,strokeWidth:1.75}),e.label]})}),(0,z.jsxs)(cg,{align:`end`,className:`w-80 p-0`,children:[(0,z.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b px-4 py-3`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`p`,{className:`text-sm font-medium tracking-tight`,children:`Inference acceleration`}),(0,z.jsx)(`p`,{className:`font-mono text-xs text-muted-foreground`,children:e.detail})]}),e.precision&&(0,z.jsx)(Mp,{mono:!0,children:e.precision})]}),(e.warning||e.note)&&(0,z.jsx)(`p`,{className:L(`mx-3 mt-3 rounded-md px-2.5 py-2 text-xs leading-relaxed`,e.warning?`bg-warning-soft text-warning`:`bg-muted text-muted-foreground`),children:e.warning??e.note}),e.models.length?(0,z.jsx)(`ul`,{className:`max-h-80 overflow-y-auto p-1.5`,children:e.models.map(e=>(0,z.jsxs)(`li`,{className:`flex items-center justify-between gap-3 rounded-md px-2.5 py-1.5 text-sm hover:bg-muted`,children:[(0,z.jsx)(`span`,{className:L(!e.loaded&&`text-muted-foreground`),children:e.label}),(0,z.jsx)(Mp,{mono:!0,tone:e.loaded?e.hardware?`info`:`neutral`:`off`,children:e.provider})]},e.key))}):(0,z.jsx)(`p`,{className:`px-4 py-3 text-sm text-muted-foreground`,children:`This runtime doesn’t report per-model execution providers.`})]})]})}function Og({preference:e,setPreference:t}){return(0,z.jsxs)($h,{children:[(0,z.jsx)(eg,{asChild:!0,children:(0,z.jsx)(hp,{variant:`ghost`,size:`icon-sm`,"aria-label":`Theme`,children:(0,z.jsx)(e===`dark`?Ee:e===`light`?Qe:we,{className:`size-4`,strokeWidth:1.75})})}),(0,z.jsxs)(tg,{align:`end`,className:`w-40`,children:[(0,z.jsx)(ig,{children:`Appearance`}),(0,z.jsx)(ag,{}),(0,z.jsxs)(ng,{value:e,onValueChange:e=>t(e),children:[(0,z.jsxs)(rg,{value:`system`,children:[(0,z.jsx)(we,{strokeWidth:1.75}),` System`]}),(0,z.jsxs)(rg,{value:`light`,children:[(0,z.jsx)(Qe,{strokeWidth:1.75}),` Light`]}),(0,z.jsxs)(rg,{value:`dark`,children:[(0,z.jsx)(Ee,{strokeWidth:1.75}),` Dark`]})]})]})]})}function kg(e){let[t,n]=(0,_.useState)(null),r=e.join(`|`);return(0,_.useEffect)(()=>{let e=r.split(`|`).map(e=>document.getElementById(e)).filter(e=>!!e);if(!e.length||!(`IntersectionObserver`in window))return;let t=new Map,i=new IntersectionObserver(r=>{for(let e of r)t.set(e.target.id,e.isIntersecting?e.intersectionRatio:0);let i=null,a=0;for(let n of e){let e=t.get(n.id)??0;e>a&&(i=n.id,a=e)}n(i)},{rootMargin:`-96px 0px -45% 0px`,threshold:[0,.1,.25,.5]});return e.forEach(e=>i.observe(e)),()=>i.disconnect()},[r]),t}function Ag({sections:e}){let t=kg(e.map(e=>e.id));return(0,z.jsx)(`nav`,{"aria-label":`Sections`,className:`ml-4 hidden h-full items-stretch md:flex`,children:e.map(e=>(0,z.jsxs)(`a`,{href:`#${e.id}`,"aria-current":t===e.id?`location`:void 0,className:L(`relative flex items-center gap-1.5 px-3 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground`,`after:absolute after:inset-x-3 after:bottom-[-1px] after:h-0.5 after:rounded-t after:bg-foreground after:opacity-0 after:transition-opacity`,t===e.id&&`text-foreground after:opacity-100`),children:[e.label,e.tone&&e.tone!==`ok`&&(0,z.jsx)(Ap,{tone:e.tone}),e.count!=null&&e.count>0&&(0,z.jsx)(`span`,{className:`font-mono text-[11px] text-muted-foreground tabular`,children:e.count})]},e.id))})}function jg({appName:e,version:t,accel:n,connection:r,live:i,setLive:a,lastUpdated:o,refresh:s,theme:c,setTheme:l,sections:u}){return(0,z.jsx)(`header`,{className:`sticky top-0 z-40 border-b bg-background/85 backdrop-blur-md backdrop-saturate-150`,children:(0,z.jsxs)(`div`,{className:`mx-auto flex h-14 max-w-[1200px] items-center gap-3 px-4 sm:px-6`,children:[(0,z.jsxs)(`a`,{href:`#top`,className:`flex items-center gap-2.5 rounded-md outline-offset-4`,children:[(0,z.jsx)(wg,{}),(0,z.jsx)(`span`,{className:`text-[15px] font-semibold tracking-[-0.03em]`,children:e})]}),(0,z.jsxs)(Mp,{mono:!0,className:`hidden sm:inline-flex`,children:[`v`,t]}),(0,z.jsx)(Ag,{sections:u}),(0,z.jsxs)(`div`,{className:`ml-auto flex items-center gap-1.5`,children:[(0,z.jsx)(`div`,{className:`hidden md:block`,children:(0,z.jsx)(Dg,{accel:n})}),(0,z.jsx)(lg,{orientation:`vertical`,className:`mx-1 hidden h-5 md:block`}),r===`reconnecting`&&(0,z.jsx)(hp,{variant:`ghost`,size:`icon-sm`,onClick:s,"aria-label":`Retry now`,children:(0,z.jsx)(Be,{className:`size-3.5`})}),(0,z.jsx)(Eg,{connection:r,live:i,setLive:a,lastUpdated:o}),(0,z.jsx)(Og,{preference:c,setPreference:l})]})]})})}var Mg=[`api/status`,`api/events`,`api/activity`,`healthz`];function Ng({appName:e,version:t,snapshot:n,demoLink:r}){let i=r!==void 0;return(0,z.jsx)(`footer`,{className:`border-t`,children:(0,z.jsxs)(`div`,{className:`mx-auto flex max-w-[1200px] flex-col gap-3 px-4 py-6 text-[13px] text-muted-foreground sm:flex-row sm:items-center sm:justify-between sm:px-6`,children:[(0,z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,z.jsx)(wg,{className:`size-4 opacity-70`}),(0,z.jsxs)(`span`,{children:[e,t?` ${t}`:``,` · open-source local AI for UniFi Protect`]})]}),i&&(0,z.jsxs)(`p`,{children:[`Demo with sample data; nothing here is a real home.`,r&&(0,z.jsxs)(z.Fragment,{children:[` `,(0,z.jsx)(`a`,{href:r,className:`font-medium text-foreground underline-offset-4 hover:underline`,children:`Get Keystone →`})]})]}),!n&&!i&&(0,z.jsx)(`nav`,{"aria-label":`JSON endpoints`,className:`flex flex-wrap gap-x-4 gap-y-1 font-mono text-xs`,children:Mg.map(e=>(0,z.jsxs)(`a`,{href:e,className:`transition-colors hover:text-foreground`,children:[`/`,e]},e))})]})})}function Pg(e,t,n,r,i,a){let[o,s]=(0,_.useState)(null),c=e||o!==null,[l,u]=(0,_.useState)(`24h`),[d,f]=(0,_.useState)(`all`),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)([]),v=h.at(-1)??null,y=c?null:v,b=vh(l,d,p,y),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(null),[T,E]=(0,_.useState)(0),D=()=>E(e=>e+1);(0,_.useEffect)(()=>{if(e||o===`older-runtime`)return;let t=!1,n,r=null,c=async()=>{if(t||r)return;window.clearTimeout(n);let e=new AbortController;r=e;let u=window.setTimeout(()=>e.abort(),8e3);try{let n=await fetch(b,{signal:e.signal,cache:`no-store`});if(n.status===404||n.status===503){if(!t){let e=n.status===404?`older-runtime`:`store-unavailable`;e!==o&&(s(e),g([]),e===`store-unavailable`&&a())}return}if(!n.ok)throw Error(String(n.status));let r=await n.json();t||(o&&(s(null),g([])),S({url:b,range:l,page:r}),w(null))}catch{t||w(b)}finally{window.clearTimeout(u),r=null,!t&&i&&!y&&document.visibilityState===`visible`&&(n=window.setTimeout(c,pg))}},u=()=>{document.visibilityState===`visible`&&i&&!y?c():window.clearTimeout(n)},d=window.setTimeout(c,p.trim()?180:0);return document.addEventListener(`visibilitychange`,u),()=>{t=!0,window.clearTimeout(d),r?.abort(),window.clearTimeout(n),document.removeEventListener(`visibilitychange`,u)}},[e,o,b,l,i,y,p,T,a]);let O=(0,_.useMemo)(()=>c?yh(t,r,l,d,p,v):!x||x.url!==b?null:{...x.page,items:x.page.items.map((e,t)=>Km(e,n,t))},[c,t,r,l,d,p,v,x,b,n]);return{page:O,counts:O?.counts??(x?.range===l?x.page.counts:null),incomplete:!c&&x?.range===l&&!!x.page.incomplete,cameraCounts:x?.range===l?x.page.cameraCounts:null,error:!c&&C===b,fallback:o,range:l,category:d,query:p,setRange:e=>{u(e),g([])},setCategory:e=>{f(e),g([])},setQuery:e=>{m(e),g([])},hasPrevious:!!v,previous:()=>g(e=>e.slice(0,-1)),next:()=>{O?.nextCursor&&g([...h,O.nextCursor])},refresh:D}}var Fg=`keystone-theme`;function Ig(){try{let e=window.localStorage.getItem(Fg);if(e===`light`||e===`dark`||e===`system`)return e}catch{}return`system`}function Lg(e){let t=e===`dark`||e===`system`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches;document.documentElement.classList.toggle(`dark`,t)}function Rg(){let[e,t]=(0,_.useState)(Ig);return(0,_.useEffect)(()=>{if(Lg(e),e!==`system`)return;let t=window.matchMedia(`(prefers-color-scheme: dark)`),n=()=>Lg(`system`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)},[e]),{preference:e,setPreference:(0,_.useCallback)(e=>{t(e);try{window.localStorage.setItem(Fg,e)}catch{}},[])}}function zg(e=1e3){let[t,n]=(0,_.useState)(()=>Date.now());return(0,_.useEffect)(()=>{let t=window.setInterval(()=>n(Date.now()),e);return()=>window.clearInterval(t)},[e]),t}function Bg(){let e=Cg(),{preference:t,setPreference:n}=Rg(),r=zg(1e3),{status:i,events:a,activity:o}=e,s=e.connection===`snapshot`&&e.generatedAt?e.generatedAt:r,c=(0,_.useMemo)(()=>qm(a,o,i.cameras),[a,o,i.cameras]),l=!!e.demo||e.connection===`snapshot`,u=e.connection===`snapshot`?s:e.lastUpdated??s,d=Pg(l,c,i.cameras,u,e.live,e.refresh),f=(0,_.useMemo)(()=>sh(i,a,c),[i,a,c]),p=(0,_.useMemo)(()=>mh(i),[i]),m=(0,_.useMemo)(()=>fh(f),[f]),h=(0,_.useMemo)(()=>zm(i),[i]),[g,v]=(0,_.useState)(null),[y,b]=(0,_.useState)(null),x=f.find(e=>e.id===g)??null,S=String(i.app||`Keystone`),C=String(i.control?.consoleName??``).trim();return(0,_.useEffect)(()=>{let e=m.tone===`error`?`● `:``;document.title=`${e}${S}${C?` · ${C}`:``}`},[S,C,m.tone]),(0,z.jsxs)(Cp,{delayDuration:200,children:[(0,z.jsxs)(`div`,{className:`min-h-svh`,children:[(0,z.jsx)(jg,{appName:S,version:String(i.version||`—`),accel:h,connection:e.connection,live:e.live,setLive:e.setLive,lastUpdated:e.lastUpdated,refresh:()=>{e.refresh(),d.refresh()},theme:t,setTheme:n,sections:[{id:`services`,label:`Services`,tone:m.tone===`ok`?void 0:m.tone},{id:`cameras`,label:`Cameras`},{id:`activity`,label:`Activity`,count:d.counts?.all}]}),(0,z.jsxs)(`main`,{className:`mx-auto max-w-[1200px] space-y-12 px-4 pb-16 sm:px-6`,children:[(0,z.jsx)(Yh,{status:i,health:m,cameras:p,history:e.history,lastUpdated:e.lastUpdated,generatedAt:e.connection===`snapshot`?e.generatedAt:null,demo:!!e.demo,accel:h,now:s,onOpenService:e=>v(e.id)}),(0,z.jsx)(Xp,{services:f,onOpen:e=>v(e.id)}),(0,z.jsx)(Rh,{cameras:p,aiportEnabled:!!i.aiport?.enabled,range:l||d.fallback?null:d.range,cameraCounts:d.cameraCounts,incomplete:d.incomplete}),(0,z.jsx)(Dh,{history:d,now:s,onOpen:b})]}),(0,z.jsx)(Ng,{appName:S,version:String(i.version||``),snapshot:e.connection===`snapshot`,demoLink:e.demo?e.demo.link??null:void 0})]}),(0,z.jsx)(Qp,{service:x,onOpenChange:e=>!e&&v(null)}),(0,z.jsx)(Wh,{item:y,onOpenChange:e=>!e&&b(null)})]})}(0,v.createRoot)(document.getElementById(`root`)).render((0,z.jsx)(_.StrictMode,{children:(0,z.jsx)(Bg,{})})); +Defaulting to \`null\`.`}Hd(af,`getInvalidValueError`);var of=Object.defineProperty,sf=(e,t)=>of(e,`name`,{value:t,configurable:!0}),cf={Horizontal:`horizontal`,Vertical:`vertical`},lf=cf.Horizontal,uf=Object.values(cf),df=_.forwardRef(sf(function(e,t){let{decorative:n,orientation:r=lf,...i}=e,a=ff(r)?r:lf,o=a===cf.Vertical?a:void 0,s=n?{role:`none`}:{"aria-orientation":o,role:`separator`};return(0,z.jsx)(B.div,{"data-orientation":a,...s,...i,ref:t})},`Separator`));function ff(e){return uf.includes(e)}sf(ff,`isValidOrientation`);var pf=Object.defineProperty,mf=(e,t)=>pf(e,`name`,{value:t,configurable:!0}),hf=`Toggle`,gf=_.forwardRef(mf(function(e,t){let{pressed:n,defaultPressed:r,onPressedChange:i,...a}=e,[o,s]=vr({prop:n,onChange:i,defaultProp:r??!1,caller:hf});return(0,z.jsx)(B.button,{type:`button`,"aria-pressed":o,"data-state":o?`on`:`off`,"data-disabled":e.disabled?``:void 0,...a,ref:t,onClick:V(e.onClick,()=>{e.disabled||s(!o)})})},`Toggle`)),_f=Object.defineProperty,vf=(e,t)=>_f(e,`name`,{value:t,configurable:!0}),yf=`ToggleGroup`,bf={Single:`single`,Multiple:`multiple`},[xf,Sf]=Bn(yf,[Bl]),Cf=Bl(),wf=_.forwardRef(vf(function(e,t){let{type:n,...r}=e;if(n===bf.Single)return(0,z.jsx)(Df,{role:`radiogroup`,...r,ref:t});if(n===bf.Multiple)return(0,z.jsx)(Of,{role:`toolbar`,...r,ref:t});throw Error(`Missing prop \`type\` expected on \`${yf}\``)},`ToggleGroup`)),[Tf,Ef]=xf(yf),Df=_.forwardRef(vf(function(e,t){let{value:n,defaultValue:r,onValueChange:i=vf(()=>{},`onValueChange`),...a}=e,[o,s]=vr({prop:n,defaultProp:r??``,onChange:i,caller:yf});return(0,z.jsx)(Tf,{scope:e.__scopeToggleGroup,type:bf.Single,value:_.useMemo(()=>o?[o]:[],[o]),onItemActivate:s,onItemDeactivate:_.useCallback(()=>s(``),[s]),children:(0,z.jsx)(jf,{...a,ref:t})})},`ToggleGroupImplSingle`)),Of=_.forwardRef(vf(function(e,t){let{value:n,defaultValue:r,onValueChange:i=vf(()=>{},`onValueChange`),...a}=e,[o,s]=vr({prop:n,defaultProp:r??[],onChange:i,caller:yf}),c=_.useCallback(e=>s((t=[])=>[...t,e]),[s]),l=_.useCallback(e=>s((t=[])=>t.filter(t=>t!==e)),[s]);return(0,z.jsx)(Tf,{scope:e.__scopeToggleGroup,type:bf.Multiple,value:o,onItemActivate:c,onItemDeactivate:l,children:(0,z.jsx)(jf,{...a,ref:t})})},`ToggleGroupImplMultiple`)),[kf,Af]=xf(yf),jf=_.forwardRef(vf(function(e,t){let{__scopeToggleGroup:n,disabled:r=!1,rovingFocus:i=!0,orientation:a,dir:o,loop:s=!0,...c}=e,l=Cf(n),u=ti(o),d={dir:u,...c};return(0,z.jsx)(kf,{scope:n,rovingFocus:i,disabled:r,children:i?(0,z.jsx)(Gl,{asChild:!0,...l,orientation:a,dir:u,loop:s,children:(0,z.jsx)(B.div,{...d,ref:t})}):(0,z.jsx)(B.div,{...d,ref:t})})},`ToggleGroupImpl`)),Mf=`ToggleGroupItem`,Nf=_.forwardRef(vf(function(e,t){let n=Ef(Mf,e.__scopeToggleGroup),r=Af(Mf,e.__scopeToggleGroup),i=Cf(e.__scopeToggleGroup),a=n.value.includes(e.value),o=r.disabled||e.disabled,s={...e,pressed:a,disabled:o},c=_.useRef(null);return r.rovingFocus?(0,z.jsx)(Jl,{asChild:!0,...i,focusable:!o,active:a,ref:c,children:(0,z.jsx)(Pf,{...s,ref:t})}):(0,z.jsx)(Pf,{...s,ref:t})},`ToggleGroupItem`)),Pf=_.forwardRef(vf(function(e,t){let{__scopeToggleGroup:n,value:r,...i}=e,a=Ef(Mf,n),o={role:`radio`,"aria-checked":e.pressed,"aria-pressed":void 0},s=a.type===bf.Single?o:void 0;return(0,z.jsx)(gf,{...s,...i,ref:t,onPressedChange:e=>{e?a.onItemActivate(r):a.onItemDeactivate(r)}})},`ToggleGroupItemImpl`)),Ff=Object.defineProperty,If=(e,t)=>Ff(e,`name`,{value:t,configurable:!0}),[Lf,Rf]=Bn(`Tooltip`,[sl]),zf=sl(),Bf=`TooltipProvider`,Vf=700,Hf=`tooltip.open`,[Uf,X]=Lf(Bf),Wf=If(e=>{let{__scopeTooltip:t,delayDuration:n=Vf,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:a}=e,o=_.useRef(!0),s=_.useRef(!1),c=_.useRef(0);return _.useEffect(()=>{let e=c.current;return()=>window.clearTimeout(e)},[]),(0,z.jsx)(Uf,{scope:t,isOpenDelayedRef:o,delayDuration:n,onOpen:_.useCallback(()=>{r<=0||(window.clearTimeout(c.current),o.current=!1)},[r]),onClose:_.useCallback(()=>{r<=0||(window.clearTimeout(c.current),c.current=window.setTimeout(()=>o.current=!0,r))},[r]),isPointerInTransitRef:s,onPointerInTransitChange:_.useCallback(e=>{s.current=e},[]),disableHoverableContent:i,children:a})},`TooltipProvider`),Gf=`Tooltip`,[Kf,qf]=Lf(Gf),Jf=If(e=>{let{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:a,disableHoverableContent:o,delayDuration:s}=e,c=X(Gf,e.__scopeTooltip),l=zf(t),[u,d]=_.useState(null),[f,p]=_.useState(void 0),m=Ir(),h=_.useRef(0),g=o??c.disableHoverableContent,v=s??c.delayDuration,y=_.useRef(!1),[b,x]=vr({prop:r,defaultProp:i??!1,onChange:If(e=>{e?(c.onOpen(),document.dispatchEvent(new CustomEvent(Hf))):c.onClose(),a?.(e)},`onChange`),caller:Gf}),S=_.useMemo(()=>b?y.current?`delayed-open`:`instant-open`:`closed`,[b]),C=_.useCallback(()=>{window.clearTimeout(h.current),h.current=0,y.current=!1,x(!0)},[x]),w=_.useCallback(()=>{window.clearTimeout(h.current),h.current=0,x(!1)},[x]),T=_.useCallback(()=>{window.clearTimeout(h.current),h.current=window.setTimeout(()=>{y.current=!0,x(!0),h.current=0},v)},[v,x]);_.useEffect(()=>()=>{h.current&&=(window.clearTimeout(h.current),0)},[]);let E=f??m;return(0,z.jsx)(ul,{...l,children:(0,z.jsx)(Kf,{scope:t,contentId:E,setContentId:p,open:b,stateAttribute:S,trigger:u,onTriggerChange:d,onTriggerEnter:_.useCallback(()=>{c.isOpenDelayedRef.current?T():C()},[c.isOpenDelayedRef,T,C]),onTriggerLeave:_.useCallback(()=>{g?w():(window.clearTimeout(h.current),h.current=0)},[w,g]),onOpen:C,onClose:w,disableHoverableContent:g,children:n})})},`Tooltip`),Yf=`TooltipTrigger`,Xf=_.forwardRef(If(function(e,t){let{__scopeTooltip:n,"aria-describedby":r,...i}=e,a=qf(Yf,n),o=X(Yf,n),s=zf(n),c=R(t,_.useRef(null),a.onTriggerChange),l=_.useRef(!1),u=_.useRef(!1),d=_.useCallback(()=>l.current=!1,[]);return _.useEffect(()=>()=>document.removeEventListener(`pointerup`,d),[d]),(0,z.jsx)(fl,{asChild:!0,...s,children:(0,z.jsx)(B.button,{"aria-describedby":a.open?pp(r,a.contentId):r,"data-state":a.stateAttribute,...i,ref:c,onPointerMove:V(e.onPointerMove,e=>{e.pointerType!==`touch`&&!u.current&&!o.isPointerInTransitRef.current&&(a.onTriggerEnter(),u.current=!0)}),onPointerLeave:V(e.onPointerLeave,()=>{a.onTriggerLeave(),u.current=!1}),onPointerDown:V(e.onPointerDown,()=>{a.open&&a.onClose(),l.current=!0,document.addEventListener(`pointerup`,d,{once:!0})}),onFocus:V(e.onFocus,()=>{l.current||a.onOpen()}),onBlur:V(e.onBlur,a.onClose),onClick:V(e.onClick,a.onClose)})})},`TooltipTrigger`)),Zf=`TooltipPortal`,[Qf,$f]=Lf(Zf,{forceMount:void 0}),ep=If(e=>{let{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,a=qf(Zf,t);return(0,z.jsx)(Qf,{scope:t,forceMount:n,children:(0,z.jsx)(Er,{present:n||a.open,children:(0,z.jsx)(Hi,{asChild:!0,container:i,children:r})})})},`TooltipPortal`),tp=`TooltipContent`,np=_.forwardRef(If(function(e,t){let n=$f(tp,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i=`top`,...a}=e,o=qf(tp,e.__scopeTooltip);return(0,z.jsx)(Er,{present:r||o.open,children:o.disableHoverableContent?(0,z.jsx)(ap,{side:i,...a,ref:t}):(0,z.jsx)(rp,{side:i,...a,ref:t})})},`TooltipContent`)),rp=_.forwardRef(If(function(e,t){let n=qf(tp,e.__scopeTooltip),r=X(tp,e.__scopeTooltip),i=_.useRef(null),a=R(t,i),[o,s]=_.useState(null),{trigger:c,onClose:l}=n,u=i.current,{onPointerInTransitChange:d}=r,f=_.useCallback(()=>{s(null),d(!1)},[d]),p=_.useCallback((e,t)=>{let n=e.currentTarget,r={x:e.clientX,y:e.clientY},i=cp(r,sp(r,n.getBoundingClientRect())),a=lp(t.getBoundingClientRect()),o=dp([...i,...a]);s(o),d(!0)},[d]);return _.useEffect(()=>()=>f(),[f]),_.useEffect(()=>{if(c&&u){let e=If(e=>p(e,u),`handleTriggerLeave`),t=If(e=>p(e,c),`handleContentLeave`);return c.addEventListener(`pointerleave`,e),u.addEventListener(`pointerleave`,t),()=>{c.removeEventListener(`pointerleave`,e),u.removeEventListener(`pointerleave`,t)}}},[c,u,p,f]),_.useEffect(()=>{if(o){let e=If(e=>{let t=e.target,n={x:e.clientX,y:e.clientY},r=c?.contains(t)||u?.contains(t),i=!up(n,o);r?f():i&&(f(),l())},`handleTrackPointerGrace`);return document.addEventListener(`pointermove`,e),()=>document.removeEventListener(`pointermove`,e)}},[c,u,o,l,f]),(0,z.jsx)(ap,{...e,ref:a})},`TooltipContentHoverable`)),ip=mn(`TooltipContent`),ap=_.forwardRef(If(function(e,t){let{__scopeTooltip:n,children:r,"aria-label":i,id:a,onEscapeKeyDown:o,onPointerDownOutside:s,...c}=e,l=qf(tp,n),u=zf(n),{onClose:d}=l,[f,p]=_.useState(null),m=R(t,p);ki(f),_.useEffect(()=>(document.addEventListener(Hf,d),()=>document.removeEventListener(Hf,d)),[d]),_.useEffect(()=>{if(l.trigger){let e=If(e=>{e.target instanceof Node&&e.target.contains(l.trigger)&&d()},`handleScroll`);return window.addEventListener(`scroll`,e,{capture:!0}),()=>window.removeEventListener(`scroll`,e,{capture:!0})}},[l.trigger,d]);let{setContentId:h}=l;return Hn(()=>(h(a),()=>{h(void 0)}),[a,h]),(0,z.jsx)(pi,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:e=>e.preventDefault(),onDismiss:d,children:(0,z.jsxs)(gl,{"data-state":l.stateAttribute,role:i?void 0:`tooltip`,id:i?void 0:l.contentId,...u,...c,ref:m,style:{...c.style,"--radix-tooltip-content-transform-origin":`var(--radix-popper-transform-origin)`,"--radix-tooltip-content-available-width":`var(--radix-popper-available-width)`,"--radix-tooltip-content-available-height":`var(--radix-popper-available-height)`,"--radix-tooltip-trigger-width":`var(--radix-popper-anchor-width)`,"--radix-tooltip-trigger-height":`var(--radix-popper-anchor-height)`},children:[(0,z.jsx)(ip,{children:r}),i?(0,z.jsx)(In,{id:l.contentId,role:`tooltip`,children:i}):null]})})},`TooltipContentImpl`)),op=_.forwardRef(If(function(e,t){let{__scopeTooltip:n,...r}=e,i=zf(n);return(0,z.jsx)(yl,{...i,...r,ref:t})},`TooltipArrow`));function sp(e,t){let n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),a=Math.abs(t.left-e.x);switch(Math.min(n,r,i,a)){case a:return`left`;case i:return`right`;case n:return`top`;case r:return`bottom`;default:throw Error(`unreachable`)}}If(sp,`getExitSideFromRect`);function cp(e,t,n=5){let r=[];switch(t){case`top`:r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case`bottom`:r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case`left`:r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case`right`:r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n})}return r}If(cp,`getPaddedExitPoints`);function lp(e){let{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}If(lp,`getPointsFromRect`);function up(e,t){let{x:n,y:r}=e,i=!1;for(let e=0,a=t.length-1;er!=d>r&&n<(u-c)*(r-l)/(d-l)+c&&(i=!i)}return i}If(up,`isPointInPolygon`);function dp(e){let t=e.slice();return t.sort((e,t)=>e.xt.x?1:e.yt.y)),fp(t)}If(dp,`getHull`);function fp(e){if(e.length<=1)return e.slice();let t=[];for(let n=0;n=2;){let e=t[t.length-1],n=t[t.length-2];if((e.x-n.x)*(r.y-n.y)>=(e.y-n.y)*(r.x-n.x))t.pop();else break}t.push(r)}t.pop();let n=[];for(let t=e.length-1;t>=0;t--){let r=e[t];for(;n.length>=2;){let e=n[n.length-1],t=n[n.length-2];if((e.x-t.x)*(r.y-t.y)>=(e.y-t.y)*(r.x-t.x))n.pop();else break}n.push(r)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}If(fp,`getHullPresorted`);function pp(...e){let t=new Set;for(let n of e)if(typeof n==`string`)for(let e of String(n).trim().split(/\s+/))e&&t.add(e);return t.size>0?Array.from(t).join(` `):void 0}If(pp,`concatAriaDescribedby`);var mp=rn(`group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,{variants:{variant:{default:`bg-primary text-primary-foreground hover:bg-primary/80`,outline:`border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50`,secondary:`bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground`,ghost:`hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50`,destructive:`bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40`,link:`text-primary underline-offset-4 hover:underline`},size:{default:`h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2`,xs:`h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3`,sm:`h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5`,lg:`h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2`,icon:`size-8`,"icon-xs":`size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3`,"icon-sm":`size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg`,"icon-lg":`size-9`}},defaultVariants:{variant:`default`,size:`default`}});function hp({className:e,variant:t=`default`,size:n=`default`,asChild:r=!1,...i}){let a=r?fn:`button`;return(0,z.jsx)(a,{"data-slot":`button`,"data-variant":t,"data-size":n,className:L(mp({variant:t,size:n,className:e})),...i})}function gp(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function _p(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/[_-]+/g,` `).replace(/^./,e=>e.toUpperCase())}function vp({value:e}){if(e==null||e===``)return(0,z.jsx)(`span`,{className:`text-muted-foreground/70`,children:`—`});if(typeof e==`boolean`)return(0,z.jsx)(`span`,{className:e?`text-success`:`text-muted-foreground`,children:e?`true`:`false`});if(typeof e==`number`)return(0,z.jsx)(`span`,{className:`tabular`,children:Number.isInteger(e)?e.toLocaleString(`en-US`):e});if(Array.isArray(e))return e.length?(0,z.jsx)(`span`,{className:`[overflow-wrap:anywhere]`,children:e.map(e=>typeof e==`object`?JSON.stringify(e):String(e)).join(`, `)}):(0,z.jsx)(`span`,{className:`text-muted-foreground/70`,children:`[]`});if(typeof e==`object`){let t=JSON.stringify(e);return(0,z.jsx)(`span`,{className:L(`[overflow-wrap:anywhere]`,t===`{}`&&`text-muted-foreground/70`),children:t})}return(0,z.jsx)(`span`,{className:`[overflow-wrap:anywhere]`,children:String(e)})}function yp({data:e,depth:t=0}){let n=Object.entries(e);return n.length?(0,z.jsx)(`dl`,{className:L(`text-sm`,t>0&&`ml-1 border-l pl-3`),children:n.map(([e,n])=>gp(n)&&Object.keys(n).length?(0,z.jsxs)(`div`,{className:`py-1.5`,children:[(0,z.jsx)(`dt`,{className:`mb-1 text-[13px] font-medium text-foreground`,children:_p(e)}),(0,z.jsx)(`dd`,{children:(0,z.jsx)(yp,{data:n,depth:t+1})})]},e):(0,z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 border-b border-dashed py-1.5 last:border-b-0`,children:[(0,z.jsx)(`dt`,{className:`shrink-0 text-muted-foreground`,title:e,children:_p(e)}),(0,z.jsx)(`dd`,{className:`min-w-0 text-right font-mono text-xs`,children:(0,z.jsx)(vp,{value:n})})]},e))}):(0,z.jsx)(`p`,{className:`py-2 text-sm text-muted-foreground`,children:`No fields reported.`})}function bp({text:e,label:t=`Copy`,size:n=`sm`,className:r}){let[i,a]=(0,_.useState)(!1);return(0,z.jsxs)(hp,{variant:`outline`,size:n,className:r,onClick:async()=>{try{await navigator.clipboard.writeText(e),a(!0),window.setTimeout(()=>a(!1),1400)}catch{}},children:[i?(0,z.jsx)(ce,{className:`text-success`}):(0,z.jsx)(ve,{}),i?`Copied`:t]})}function xp({data:e}){return(0,z.jsx)(bp,{text:JSON.stringify(e,null,2),label:`Copy JSON`})}function Sp(e){e.preventDefault(),e.currentTarget?.focus()}function Cp({delayDuration:e=0,...t}){return(0,z.jsx)(Wf,{"data-slot":`tooltip-provider`,delayDuration:e,...t})}function wp({...e}){return(0,z.jsx)(Jf,{"data-slot":`tooltip`,...e})}function Tp({...e}){return(0,z.jsx)(Xf,{"data-slot":`tooltip-trigger`,...e})}function Ep({className:e,sideOffset:t=0,children:n,...r}){return(0,z.jsx)(ep,{children:(0,z.jsxs)(np,{"data-slot":`tooltip-content`,sideOffset:t,className:L(`z-50 inline-flex w-fit max-w-xs origin-(--radix-tooltip-content-transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95`,e),...r,children:[n,(0,z.jsx)(op,{className:`z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground`})]})})}var Dp={ok:`text-success`,info:`text-info`,warn:`text-warning`,error:`text-danger`,off:`text-muted-foreground`,neutral:`text-muted-foreground`},Op={ok:`bg-success-soft text-success`,info:`bg-info-soft text-info`,warn:`bg-warning-soft text-warning`,error:`bg-danger-soft text-danger`,off:`bg-muted text-muted-foreground`,neutral:`bg-muted text-muted-foreground shadow-[inset_0_0_0_1px_var(--border)]`},kp={ok:`bg-success`,info:`bg-info`,warn:`bg-warning`,error:`bg-danger`,off:`bg-muted-foreground/50`};function Ap({tone:e,pulse:t=!1,className:n}){return(0,z.jsxs)(`span`,{className:L(`relative inline-flex size-1.5 shrink-0`,n),"aria-hidden":`true`,children:[t&&(0,z.jsx)(`span`,{className:L(`absolute inset-0 rounded-full animate-ping-slow`,kp[e])}),(0,z.jsx)(`span`,{className:L(`relative inline-flex size-full rounded-full`,kp[e])})]})}function jp({tone:e,children:t,pulse:n,className:r}){return(0,z.jsxs)(`span`,{className:L(`inline-flex h-5 shrink-0 items-center gap-1.5 rounded-full px-2 text-xs font-medium whitespace-nowrap`,Op[e],r),children:[(0,z.jsx)(Ap,{tone:e,pulse:n}),t]})}function Mp({tone:e=`neutral`,mono:t=!1,className:n,children:r,title:i}){let a=(0,z.jsx)(`span`,{className:L(`inline-flex h-5 max-w-full shrink-0 items-center gap-1 truncate rounded-full px-2 text-xs font-medium whitespace-nowrap`,t&&`font-mono text-[11px] font-normal`,Op[e],n),children:r});return i?(0,z.jsxs)(wp,{children:[(0,z.jsx)(Tp,{asChild:!0,children:a}),(0,z.jsx)(Ep,{className:`max-w-72`,children:i})]}):a}function Np({chips:e,className:t}){return e.length?(0,z.jsx)(`div`,{className:L(`flex flex-wrap gap-1.5`,t),children:e.map(e=>(0,z.jsx)(Mp,{tone:e.tone,title:e.title,children:e.label},e.label))}):null}function Pp({className:e,value:t,...n}){return(0,z.jsx)(Yd,{"data-slot":`progress`,className:L(`relative flex h-1 w-full items-center overflow-x-hidden rounded-full bg-muted`,e),...n,children:(0,z.jsx)(Zd,{"data-slot":`progress-indicator`,className:`size-full flex-1 bg-primary transition-all`,style:{transform:`translateX(-${100-(t||0)}%)`}})})}function Fp({...e}){return(0,z.jsx)(bo,{"data-slot":`sheet`,...e})}function Ip({...e}){return(0,z.jsx)(wo,{"data-slot":`sheet-portal`,...e})}function Lp({className:e,...t}){return(0,z.jsx)(Eo,{"data-slot":`sheet-overlay`,className:L(`fixed inset-0 z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0`,e),...t})}function Rp({className:e,children:t,side:n=`right`,showCloseButton:r=!0,...i}){return(0,z.jsxs)(Ip,{children:[(0,z.jsx)(Lp,{}),(0,z.jsxs)(Ao,{"data-slot":`sheet-content`,"data-side":n,className:L(`fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-[side=bottom]:data-open:slide-in-from-bottom-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:animate-out data-closed:fade-out-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=right]:data-closed:slide-out-to-right-10 data-[side=top]:data-closed:slide-out-to-top-10`,e),...i,children:[t,r&&(0,z.jsx)(Lo,{"data-slot":`sheet-close`,asChild:!0,children:(0,z.jsxs)(hp,{variant:`ghost`,className:`absolute top-3 right-3`,size:`icon-sm`,children:[(0,z.jsx)(ot,{}),(0,z.jsx)(`span`,{className:`sr-only`,children:`Close`})]})})]})]})}function zp({className:e,...t}){return(0,z.jsx)(`div`,{"data-slot":`sheet-header`,className:L(`flex flex-col gap-0.5 p-4`,e),...t})}function Bp({className:e,...t}){return(0,z.jsx)(`div`,{"data-slot":`sheet-footer`,className:L(`mt-auto flex flex-col gap-2 p-4`,e),...t})}function Vp({className:e,...t}){return(0,z.jsx)(Po,{"data-slot":`sheet-title`,className:L(`font-heading text-base font-medium text-foreground`,e),...t})}function Hp({className:e,...t}){return(0,z.jsx)(Fo,{"data-slot":`sheet-description`,className:L(`text-sm text-muted-foreground`,e),...t})}var Up={control:{icon:Oe,blurb:`Keystone presents itself to UniFi Protect as an AI Key over the UCP4 control channel.`},aiport:{icon:Xe,blurb:`A virtual AI Port X. Protect relays paired cameras over FLV and Keystone runs smart detections locally.`},vision:{icon:ne,blurb:`A vision-language model writes the event descriptions and tags shown in Protect.`},search:{icon:We,blurb:`CLIP image and text embeddings back Protect’s Find Anything search.`},faces:{icon:He,blurb:`Detects faces in event frames and matches them against your local gallery.`},lpr:{icon:Re,blurb:`Finds and reads license plates locally, then reports them back to Protect.`},stt:{icon:M,blurb:`Transcribes speech clips locally with Whisper.`},enhance:{icon:it,blurb:`Restores low-resolution face crops before recognition and display.`}};function Wp(e){let t=e.trim().split(/\s+/);return((t[0]?.[0]??``)+(t.length>1?t[t.length-1]?.[0]??``:``)).toUpperCase()}function Gp(e){let t=(0,_.useRef)(null),[n,r]=(0,_.useState)(!1);return(0,_.useLayoutEffect)(()=>{let n=t.current;if(!e||!n)return;let i=()=>r(n.scrollHeight>n.clientHeight+1);i();let a=new ResizeObserver(i);return a.observe(n),()=>a.disconnect()},[e]),[t,e&&n]}function Kp({error:e,label:t,expanded:n}){let[r,i]=Gp(!n);return(0,z.jsxs)(`div`,{className:`rounded-md bg-danger-soft px-2.5 py-2 text-danger`,children:[(0,z.jsxs)(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[(0,z.jsx)(`p`,{className:`min-w-0 truncate text-[11.5px] font-medium`,title:t,children:t??`Last error`}),n&&(0,z.jsx)(bp,{text:e,label:`Copy error`,size:`xs`,className:`h-6 bg-card text-foreground`})]}),n?(0,z.jsx)(`pre`,{className:`max-h-80 overflow-auto font-mono text-[11.5px] leading-relaxed whitespace-pre-wrap [overflow-wrap:anywhere]`,children:e}):(0,z.jsx)(`p`,{ref:r,className:`line-clamp-3 font-mono text-[11.5px] leading-relaxed [overflow-wrap:anywhere]`,children:e}),i&&(0,z.jsx)(`p`,{className:`mt-1 text-[11.5px] font-medium underline-offset-2 group-hover:underline`,children:`View full error`})]})}function qp({notice:e,label:t,expanded:n}){let[r,i]=Gp(!n);return(0,z.jsxs)(`div`,{className:`rounded-md bg-warning-soft px-2.5 py-2 text-warning`,children:[(0,z.jsx)(`p`,{className:`mb-1 min-w-0 truncate text-[11.5px] font-medium`,title:t,children:t??`Notice`}),(0,z.jsx)(`p`,{ref:r,className:L(`text-[12px] leading-relaxed [overflow-wrap:anywhere]`,!n&&`line-clamp-3`),children:e}),i&&(0,z.jsx)(`p`,{className:`mt-1 text-[11.5px] font-medium underline-offset-2 group-hover:underline`,children:`View full note`})]})}function Jp({s:e,expanded:t=!1}){return(0,z.jsxs)(z.Fragment,{children:[e.headline&&(0,z.jsxs)(`p`,{className:`flex min-w-0 items-baseline gap-2`,children:[(0,z.jsx)(`span`,{className:L(`truncate text-lg font-medium tracking-[-0.025em]`,e.headlineMono&&`font-mono text-base tracking-normal`),children:e.headline}),e.headlineSub&&(0,z.jsx)(`span`,{className:`shrink-0 truncate text-[13px] text-muted-foreground`,children:e.headlineSub})]}),(0,z.jsx)(Np,{chips:e.chips}),e.stats&&(0,z.jsxs)(`div`,{className:L(`grid gap-px overflow-hidden rounded-md border bg-border`,e.stats.length===4?`grid-cols-4`:e.stats.length===2?`grid-cols-2`:`grid-cols-3`),children:[e.stats.map(e=>(0,z.jsxs)(`div`,{className:`min-w-0 bg-card px-2 py-2`,children:[(0,z.jsx)(`p`,{className:L(`truncate text-[15px] font-medium tabular`,e.tone&&Dp[e.tone]),children:e.value}),(0,z.jsx)(`p`,{className:`truncate text-[11px] text-muted-foreground`,children:e.label})]},e.label)),e.stats.length!==4&&e.stats.length!==2&&Array.from({length:(3-e.stats.length%3)%3},(e,t)=>(0,z.jsx)(`div`,{className:`bg-card`},`pad-${t}`))]}),e.progress&&(0,z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-[13px]`,children:[(0,z.jsx)(`span`,{className:`text-muted-foreground`,children:e.progress.label}),(0,z.jsxs)(`span`,{className:`font-mono text-xs tabular`,children:[e.progress.pct,`%`]})]}),(0,z.jsx)(Pp,{value:e.progress.pct,className:`h-1`}),(0,z.jsx)(`p`,{className:`font-mono text-[11.5px] text-muted-foreground`,children:e.progress.detail})]}),e.rows.length>0&&(0,z.jsx)(`dl`,{className:`text-[13px]`,children:e.rows.map(e=>(0,z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-3 py-0.5`,title:e.title,children:[(0,z.jsx)(`dt`,{className:`shrink-0 text-muted-foreground`,children:e.label}),(0,z.jsx)(`dd`,{className:`truncate font-mono text-xs tabular`,children:e.value})]},e.label))}),e.people&&e.people.length>0&&(0,z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,z.jsx)(`div`,{className:`flex -space-x-1.5`,children:e.people.slice(0,6).map(e=>(0,z.jsxs)(wp,{children:[(0,z.jsx)(Tp,{asChild:!0,children:(0,z.jsx)(`span`,{className:`grid size-6 place-items-center rounded-full border-2 border-card bg-muted text-[10px] font-semibold text-muted-foreground`,children:Wp(e.name)})}),(0,z.jsxs)(Ep,{children:[e.name,` · `,e.refs,` reference`,e.refs===1?``:`s`]})]},e.name))}),(0,z.jsx)(`span`,{className:`truncate text-xs text-muted-foreground`,children:e.people.map(e=>e.name).join(`, `)})]}),e.rejections&&e.rejections.length>0&&(0,z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Rejected`}),(0,z.jsx)(Np,{chips:e.rejections})]}),e.disabledHint&&(0,z.jsxs)(`p`,{className:`text-[13px] text-muted-foreground`,children:[`Disabled. Enable with `,(0,z.jsx)(`code`,{className:`rounded bg-muted px-1 py-0.5 font-mono text-[11.5px]`,children:e.disabledHint})]}),e.notice&&(0,z.jsx)(qp,{notice:e.notice,label:e.noticeLabel,expanded:t}),e.error&&(0,z.jsx)(Kp,{error:e.error,label:e.errorLabel,expanded:t})]})}function Yp({s:e,onOpen:t}){let n=Up[e.id].icon;return(0,z.jsxs)(`button`,{type:`button`,onClick:t,className:L(`group flex h-full flex-col gap-3 rounded-lg border bg-card p-4 text-left transition-colors hover:border-border-strong focus-visible:ring-3 focus-visible:ring-ring/40 focus-visible:outline-none`,e.tone===`error`&&`border-danger/40 hover:border-danger/60`,e.tone===`warn`&&e.notice&&`border-warning/40 hover:border-warning/60`),children:[(0,z.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2.5`,children:[(0,z.jsx)(`span`,{className:L(`grid size-8 shrink-0 place-items-center rounded-md border bg-background text-muted-foreground`,e.tone===`off`&&`opacity-60`),children:(0,z.jsx)(n,{className:`size-4`,strokeWidth:1.75})}),(0,z.jsx)(`p`,{className:`min-w-0 truncate text-sm font-medium tracking-[-0.01em]`,children:e.title})]}),(0,z.jsx)(jp,{tone:e.tone,pulse:e.tone===`info`,children:e.state})]}),(0,z.jsx)(Jp,{s:e}),(0,z.jsxs)(`span`,{className:`mt-auto flex items-center gap-1 pt-1 text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100`,children:[`Details `,(0,z.jsx)(me,{className:`size-3 transition-transform group-hover:translate-x-0.5`})]})]})}function Xp({services:e,onOpen:t}){let n=e.filter(e=>e.tone!==`off`).length;return(0,z.jsxs)(`section`,{id:`services`,className:`scroll-mt-28`,children:[(0,z.jsx)(Zp,{title:`Services`,meta:`${n} of ${e.length} enabled`}),(0,z.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 sm:gap-4 xl:grid-cols-4`,children:e.map(e=>(0,z.jsx)(Yp,{s:e,onOpen:()=>t(e)},e.id))})]})}function Zp({title:e,meta:t,children:n}){return(0,z.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1`,children:[(0,z.jsx)(`h2`,{className:`text-2xl font-semibold tracking-[-0.035em]`,children:e}),t&&(0,z.jsx)(`p`,{className:`text-sm text-muted-foreground tabular`,children:t}),n]})}function Qp({service:e,onOpenChange:t}){let n=e,r=n?Up[n.id].icon:null;return(0,z.jsx)(Fp,{open:!!n,onOpenChange:t,children:(0,z.jsx)(Rp,{className:`w-full gap-0 outline-none sm:max-w-md`,onOpenAutoFocus:Sp,children:n&&r&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(zp,{className:`border-b`,children:[(0,z.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,z.jsx)(`span`,{className:`grid size-8 place-items-center rounded-md border bg-background text-muted-foreground`,children:(0,z.jsx)(r,{className:`size-4`,strokeWidth:1.75})}),(0,z.jsx)(Vp,{className:`text-base tracking-[-0.02em]`,children:n.title}),n.port&&(0,z.jsx)(Mp,{mono:!0,children:n.port}),(0,z.jsx)(jp,{tone:n.tone,className:`mr-8 ml-auto`,children:n.state})]}),(0,z.jsx)(Hp,{children:Up[n.id].blurb})]}),(0,z.jsxs)(`div`,{className:`flex-1 space-y-6 overflow-y-auto p-4`,children:[(0,z.jsx)(`div`,{className:`space-y-3`,children:(0,z.jsx)(Jp,{s:n,expanded:!0})}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`p`,{className:`mb-2 text-[13px] font-medium text-muted-foreground`,children:`Raw status`}),(0,z.jsx)(`div`,{className:`rounded-lg border bg-card px-3 py-1.5`,children:(0,z.jsx)(yp,{data:n.raw??{}})})]})]}),(0,z.jsx)(Bp,{className:`border-t`,children:(0,z.jsx)(xp,{data:n.raw})})]})})})}function $p({className:e,...t}){return(0,z.jsx)(`div`,{"data-slot":`empty`,className:L(`flex w-full min-w-0 flex-1 flex-col items-center justify-center gap-4 rounded-xl border-dashed p-6 text-center text-balance`,e),...t})}function em({className:e,...t}){return(0,z.jsx)(`div`,{"data-slot":`empty-header`,className:L(`flex max-w-sm flex-col items-center gap-2`,e),...t})}var tm=rn(`mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0`,{variants:{variant:{default:`bg-transparent`,icon:`flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground [&_svg:not([class*='size-'])]:size-4`}},defaultVariants:{variant:`default`}});function nm({className:e,variant:t=`default`,...n}){return(0,z.jsx)(`div`,{"data-slot":`empty-icon`,"data-variant":t,className:L(tm({variant:t,className:e})),...n})}function rm({className:e,...t}){return(0,z.jsx)(`div`,{"data-slot":`empty-title`,className:L(`font-heading text-sm font-medium tracking-tight`,e),...t})}function im({className:e,...t}){return(0,z.jsx)(`div`,{"data-slot":`empty-description`,className:L(`text-sm/relaxed text-muted-foreground [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary`,e),...t})}function am({className:e,type:t,...n}){return(0,z.jsx)(`input`,{type:t,"data-slot":`input`,className:L(`h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40`,e),...n})}function om({className:e,...t}){return(0,z.jsx)(`div`,{"data-slot":`input-group`,role:`group`,className:L(`group/input-group relative flex h-8 w-full min-w-0 items-center rounded-lg border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5`,e),...t})}var sm=rn(`flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4`,{variants:{align:{"inline-start":`order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]`,"inline-end":`order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]`,"block-start":`order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2`,"block-end":`order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2`}},defaultVariants:{align:`inline-start`}});function cm({className:e,align:t=`inline-start`,...n}){return(0,z.jsx)(`div`,{role:`group`,"data-slot":`input-group-addon`,"data-align":t,className:L(sm({align:t}),e),onClick:e=>{e.target.closest(`button`)||e.currentTarget.parentElement?.querySelector(`input`)?.focus()},...n})}var lm=rn(`flex items-center gap-2 text-sm shadow-none`,{variants:{size:{xs:`h-6 gap-1 rounded-[calc(var(--radius)-3px)] px-1.5 [&>svg:not([class*='size-'])]:size-3.5`,sm:``,"icon-xs":`size-6 rounded-[calc(var(--radius)-3px)] p-0 has-[>svg]:p-0`,"icon-sm":`size-8 p-0 has-[>svg]:p-0`}},defaultVariants:{size:`xs`}});function um({className:e,type:t=`button`,variant:n=`ghost`,size:r=`xs`,...i}){return(0,z.jsx)(hp,{type:t,"data-size":r,variant:n,className:L(lm({size:r}),e),...i})}function dm({className:e,...t}){return(0,z.jsx)(am,{"data-slot":`input-group-control`,className:L(`flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent`,e),...t})}function fm({className:e,...t}){return(0,z.jsx)(`kbd`,{"data-slot":`kbd`,className:L(`pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm bg-muted px-1 font-sans text-xs font-medium text-muted-foreground select-none in-data-[slot=tooltip-content]:bg-background/20 in-data-[slot=tooltip-content]:text-background dark:in-data-[slot=tooltip-content]:bg-background/10 [&_svg:not([class*='size-'])]:size-3`,e),...t})}var pm=rn(`group/toggle inline-flex items-center justify-center gap-1 rounded-lg text-sm font-medium whitespace-nowrap transition-all outline-none hover:bg-muted hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 aria-pressed:bg-muted data-[state=on]:bg-muted dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,{variants:{variant:{default:`bg-transparent`,outline:`border border-input bg-transparent hover:bg-muted`},size:{default:`h-8 min-w-8 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2`,sm:`h-7 min-w-7 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5`,lg:`h-9 min-w-9 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2`}},defaultVariants:{variant:`default`,size:`default`}}),mm=_.createContext({size:`default`,variant:`default`,spacing:2,orientation:`horizontal`});function hm({className:e,variant:t,size:n,spacing:r=2,orientation:i=`horizontal`,children:a,...o}){return(0,z.jsx)(wf,{"data-slot":`toggle-group`,"data-variant":t,"data-size":n,"data-spacing":r,"data-orientation":i,style:{"--gap":r},className:L(`group/toggle-group flex w-fit flex-row items-center gap-[--spacing(var(--gap))] rounded-lg data-[size=sm]:rounded-[min(var(--radius-md),10px)] data-vertical:flex-col data-vertical:items-stretch`,e),...o,children:(0,z.jsx)(mm.Provider,{value:{variant:t,size:n,spacing:r,orientation:i},children:a})})}function gm({className:e,children:t,variant:n=`default`,size:r=`default`,...i}){let a=_.useContext(mm);return(0,z.jsx)(Nf,{"data-slot":`toggle-group-item`,"data-variant":a.variant||n,"data-size":a.size||r,"data-spacing":a.spacing,className:L(`shrink-0 group-data-[spacing=0]/toggle-group:rounded-none group-data-[spacing=0]/toggle-group:px-2 focus:z-10 focus-visible:z-10 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-end]:pr-1.5 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-start]:pl-1.5 group-data-horizontal/toggle-group:data-[spacing=0]:first:rounded-l-lg group-data-vertical/toggle-group:data-[spacing=0]:first:rounded-t-lg group-data-horizontal/toggle-group:data-[spacing=0]:last:rounded-r-lg group-data-vertical/toggle-group:data-[spacing=0]:last:rounded-b-lg group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:border-l-0 group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:border-t-0 group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-l group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-t`,pm({variant:a.variant||n,size:a.size||r}),e),...i,children:t})}function Z(e,t=0){let n=Number(e);return Number.isFinite(n)?n:t}function Q(e){return Math.trunc(Z(e)).toLocaleString(`en-US`)}function _m(e){let t=Math.max(0,Z(e));if(!t)return`0 B`;if(t<1024)return`${Math.trunc(t)} B`;if(t<1024**2)return`${(t/1024).toFixed(0)} KB`;if(t<1024**3){let e=t/1024**2;return`${e>=100?e.toFixed(0):e.toFixed(1)} MB`}return`${(t/1024**3).toFixed(2)} GB`}function vm(e){let t=Math.trunc(Z(e));return t<=0?`—`:t<1e3?`${t} ms`:`${(t/1e3).toFixed(1)}s`}function ym(e){return`${Math.round(Z(e)*100)}%`}function bm(e){let t=Z(e);if(t<=0)return`—`;let n=new Date(t);return Number.isNaN(n.getTime())?`—`:n.toLocaleTimeString(`en-GB`,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function xm(e){let t=Z(e);if(t<=0)return`—`;let n=new Date(t);return Number.isNaN(n.getTime())?`—`:n.toLocaleString(void 0,{weekday:`short`,year:`numeric`,timeZoneName:`short`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function Sm(e){let t=Z(e);if(t<=0)return`—`;let n=new Date(t);return Number.isNaN(n.getTime())?`—`:`${n.toLocaleDateString(void 0,{month:`short`,day:`numeric`})}, ${n.toLocaleTimeString(`en-GB`,{hour:`2-digit`,minute:`2-digit`})}`}function Cm(e,t){let n=Z(e);if(n<=0)return`—`;let r=Math.round((t-n)/1e3);if(r<5)return`now`;if(r<60)return`${r}s ago`;let i=Math.floor(r/60);if(i<60)return`${i}m ago`;let a=Math.floor(i/60);return a<48?`${a}h ago`:`${Math.floor(a/24)}d ago`}function wm(e,t){let n=new Date(e),r=new Date(t),i=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime(),a=Math.round((i(r)-i(n))/864e5);return a===0?`Today`:a===1?`Yesterday`:n.toLocaleDateString(void 0,{weekday:`long`,month:`short`,day:`numeric`})}function Tm(e){let t=new Date(e);return`${t.getFullYear()}-${t.getMonth()}-${t.getDate()}`}var Em={blurry:`Sharpness below faces.min_sharpness (Laplacian variance of the native-resolution face crop)`,small:`Face box smaller than faces.min_face_px (source pixels)`,low_score:`SCRFD confidence below faces.min_det_score`,profile:`Head turn exceeded faces.max_yaw (near-profile angle)`,yaw:`Head turn exceeded faces.max_yaw (near-profile angle)`},Dm={alrmspeak:`Speech`,speak:`Speech`,speech:`Speech`,alrmbark:`Dog bark`,bark:`Dog bark`,alrmsiren:`Siren`,siren:`Siren`,alrmsmoke:`Smoke alarm`,smoke:`Smoke alarm`,alrmcmonx:`CO alarm`,cmonx:`CO alarm`,alrmbabycry:`Baby cry`,babycry:`Baby cry`,alrmglassbreak:`Glass break`,glassbreak:`Glass break`,alrmcaralarm:`Car alarm`,caralarm:`Car alarm`,alrmcarhorn:`Car horn`,carhorn:`Car horn`,alrmburglar:`Burglar alarm`,burglar:`Burglar alarm`},Om=/^data:image\/(?:jpeg|png|webp);base64,[A-Za-z0-9+/=]+$/,km=2e4;function Am(e){return typeof e==`string`&&e.length<=km&&Om.test(e)?e:null}function jm(e){let t=String(e??``).trim();return t?Dm[t.toLowerCase()]??t:`Audio`}function Mm(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function $(e){return e==null?``:String(e).trim()}function Nm(e){let t=$(e),n=t.indexOf(` (`);return n>0?[t.slice(0,n).trim(),t]:[t,t]}function Pm(e){let t=$(e);if(!t)return`—`;if(t.toLowerCase()===`unloaded`)return`Unloaded`;if(t===`CoreAI`)return`Core AI`;let n=/^([A-Za-z]+?)(?:ExecutionProvider)?(?:\((.+)\))?$/.exec(t);if(!n)return t;let r=n[1]===`CPU`?`CPU`:n[1].replace(/^Openvino$/i,`OpenVINO`);return n[2]?`${r} · ${n[2].toUpperCase()}`:r}function Fm(e){let t=$(e).toLowerCase();return!t||t===`unloaded`||t===`coreai`||t.startsWith(`cpu`)?!1:t.startsWith(`openvino`)?/\((?:gpu|npu)(?:[._][\w.]+)?\)$/.test(t):!t.includes(`(cpu)`)}var Im={embeddingsVision:`CLIP vision`,embeddingsText:`CLIP text`,aiportDetector:`AI Port detector`,faceDetector:`Face detector`,faceRecognizer:`Face recognizer`,lprDetector:`Plate detector`,lprOcr:`Plate OCR`,faceEnhancer:`Face enhancer`,sttEncoder:`Whisper encoder`,sttDecoder:`Whisper decoder`},Lm=[`CUDA`,`MIGraphX`],Rm={CPUAndNeuralEngine:`ANE`,ALL:`ALL`,CPUAndGPU:`GPU`,CPUOnly:`CPU`};function zm(e,t){let n=t.openvinoDevices?.filter(({id:e})=>/^(?:GPU|NPU)(?:\.|$)/i.test(e))??[],r=n.filter(({id:e})=>/^GPU(?:\.|$)/i.test(e)).length,i=(t.hardware?.renderNodes??[]).filter(e=>e.vendor===`Intel`).length,a=r>0&&r>=i,o=new Set(n.map(({name:e})=>e));for(let e of t.hardware?.renderNodes??[])e.vendor===`Intel`&&a||o.add([e.vendor,e.deviceId].filter(Boolean).join(` `)||e.path);for(let e of t.hardware?.gpuDeviceFiles??[]){let n=e===`/dev/kfd`?`AMD`:`NVIDIA`;t.hardware?.renderNodes.some(e=>e.vendor===n)||o.add(n)}let s=t.hardware?.videoDecode,c;if(s?.ready){let t=s.backend===`vaapi`?`VA-API`:`VideoToolbox`,n=e.aiport?.pairedCameras?.filter(e=>e.hwaccelBackend===s.backend).length??0;c=n>0?`${t} · active on ${n} ${n===1?`camera`:`cameras`}`:`${t} · available`}else s&&(c=t.ffmpegHwaccel===`none`?`Software · hardware decode disabled`:`Software`);return{devices:[...o],videoDecode:c,fallbacks:Object.entries(t.fallbacks??{}).map(([e,t])=>({model:e,requestedProvider:Pm(t.requestedProvider),reason:t.reason})),diagnostics:t.diagnostics}}function Bm(e){let t={...Vm(e),...zm(e,e.acceleration??{})},n=Mm(e.acceleration?.gpuWatchdog),r=Z(n.recentRestarts),i=Z(n.windowMinutes,30);if(n.suspended){let e=Z(n.suspendedAfterRestarts)||r;return{...t,label:`CPU · GPU suspended`,detail:`Running on CPU`,hardware:!1,warning:`The GPU was lost ${e} times within ${i} min, so every model is running on the CPU. Restart Keystone to try the GPU again.`}}return Z(n.lossDetectedAt)>0&&!n.restartOnLoss?{...t,warning:`The GPU was lost${n.lossModel?` (first seen in ${n.lossModel})`:``} and GPU models will keep failing. Automatic restart is off (acceleration.restart_on_gpu_loss); restart Keystone to recover.`}:r>0?{...t,note:`Restarted ${r} time${r===1?``:`s`} in the last ${i} min to recover a lost GPU.`}:t}function Vm(e){let t=Mm(e.acceleration),n=Mm(e.embeddings),r=t.coremlComputeUnits===`CPUOnly`,i=Object.entries(Mm(t.activeProviders)).map(([e,n])=>{let i=Pm(n),a=/^OpenVINO · ((?:GPU|NPU)(?:[._][\w.]+)?)$/.exec(i)?.[1].split(`_`)[0],o=!a||!t.openvinoDevices||t.openvinoDevices.some(({id:e})=>e===a||e.split(`.`)[0]===a);return{key:e,label:Im[e]??e,provider:i,hardware:o&&Fm(n)&&!(i===`CoreML`&&r),loaded:$(n).toLowerCase()!==`unloaded`}});for(let e of Lm){let n=i.filter(t=>t.provider===e).length;if(n){let t=i.filter(e=>e.loaded).length;return{models:i,label:i.some(e=>e.provider===`CPU`)?`${e} + CPU`:`${e} · GPU`,detail:`${e}ExecutionProvider on ${n}/${t} loaded models`,hardware:!0}}if($(t.provider).toLowerCase()===e.toLowerCase())return i.some(e=>e.provider===`CPU`)?{models:i,label:`CPU`,detail:`CPUExecutionProvider`,hardware:!1}:{models:i,label:`Idle`,detail:`No ${e} sessions loaded`,hardware:!1}}let a=i.some(e=>e.provider===`CoreML`),o=i.filter(e=>e.provider.startsWith(`OpenVINO`)),s=o.find(e=>e.hardware)??o[0],c=$(a?t.coremlModelFormat:t.precision)||void 0,l={models:i,precision:c};if(Object.keys(t).length){let e=$(t.label||t.active),n=$(t.backend||t.provider||t.executionProvider),o=n.toLowerCase(),u=$(t.device||t.openvinoDevice);if(e){let t=/^openvino$/i.test(n)?`OpenVINO`:n,r=u?` on ${u.toUpperCase()}`:``;return{...l,label:e,detail:t?`${t}${r}`:e,hardware:!e.toUpperCase().startsWith(`CPU`)}}if(a||!t.activeProviders&&o.includes(`coreml`)){let e=$(t.coremlComputeUnits),n=Rm[e];return{...l,label:n?`CoreML · ${n}`:`CoreML`,detail:e?`CoreML (${e})`:`CoreML`,hardware:!r}}if(s){let e=s.provider,t=e.split(` · `)[1],n=`OpenVINO execution device unverified`;return t?.startsWith(`AUTO`)&&(n=`OpenVINO automatic device selection (${t})`),(t===`CPU`||s.hardware)&&(n=`OpenVINO on ${t}`),{...l,label:e,detail:n,hardware:s.hardware,precision:t===`CPU`?void 0:c}}if(!t.activeProviders&&(o.includes(`openvino`)||t.openvino)){let e=(u||`AUTO`).toUpperCase();return{...l,label:`OpenVINO · ${e}`,detail:`OpenVINO on ${e}`,hardware:Fm(`OpenVINO(${e})`)}}return i.some(e=>e.provider===`Core AI`)?{...l,label:`Core AI`,detail:`CLIP vision encoder with GPU preference`,hardware:!1}:o.includes(`cuda`)?{...l,label:`CUDA · GPU`,detail:n,hardware:!0}:o.includes(`tensorrt`)?{...l,label:`TensorRT · GPU`,detail:n,hardware:!0}:t.device&&u.toUpperCase()!==`CPU`?{...l,label:`${n||`Accelerated`} · ${u.toUpperCase()}`,detail:`${n} (${u})`,hardware:!0}:{...l,label:`CPU`,detail:n||`CPUExecutionProvider`,hardware:!1}}let u=$(n.provider),d=$(n.device||n.openvinoDevice),f=u.toLowerCase();if(f.includes(`openvino`)){let e=(d||`GPU`).toUpperCase();return{...l,label:`OpenVINO · ${e}`,detail:`${u} (${e})`,hardware:Fm(`OpenVINO(${e})`)}}return f.includes(`cuda`)?{...l,label:`CUDA · GPU`,detail:u,hardware:!0}:f.includes(`coreml`)?{...l,label:`CoreML`,detail:u,hardware:!0}:f.includes(`tensorrt`)?{...l,label:`TensorRT · GPU`,detail:u,hardware:!0}:{...l,label:`CPU`,detail:u||`CPUExecutionProvider`,hardware:!1}}var Hm=[{key:`all`,label:`All`},{key:`detection`,label:`Detections`},{key:`caption`,label:`Captions`},{key:`face`,label:`Faces`},{key:`lpr`,label:`Plates`},{key:`audio`,label:`Audio`},{key:`package`,label:`Packages`}];function Um(e){let t=$(e.kind||e.type).toLowerCase();return t===`detection`?{label:`Detection`,tone:`detection`}:t===`stt`||t===`speechtotext`?{label:`Speech`,tone:`audio`}:t===`audio`?{label:`Audio`,tone:`audio`}:t===`enhance`?{label:`Enhance`,tone:`face`}:t===`face`?{label:`Face`,tone:`face`}:t===`lpr`?{label:`Plate`,tone:`lpr`}:t===`package`?{label:`Package`,tone:`package`}:$(e.subtype).toLowerCase()===`on_demand`?{label:`Summary`,tone:`caption`}:{label:`Caption`,tone:`caption`}}function Wm(e){let t=e.plates;return Array.isArray(t)?t:t&&Array.isArray(t.plates)?t.plates:[]}function Gm(e){let t=[],n=e=>{t.includes(e)||t.push(e)},r=$(e.kind||e.type).toLowerCase();r===`detection`&&n(`detection`),(!r||[`caption`,`recognizekeyframes`,`describeimage`,`on_demand`].includes(r))&&n(`caption`),(r===`face`||r===`enhance`)&&n(`face`),r===`lpr`&&n(`lpr`),(r===`stt`||r===`speechtotext`||r===`audio`)&&n(`audio`),r===`package`&&n(`package`);let i=e.faces;i&&(Z(i.detections)>0||Z(i.qualityFaces)>0||Array.isArray(i.matches)&&i.matches.length>0||i.rejectedReasons&&Object.keys(i.rejectedReasons).length>0)&&n(`face`);for(let t of Array.isArray(e.identities)?e.identities:[]){let e=$(t?.source).toLowerCase(),r=$(t?.kind).toLowerCase();e===`lpr`||r===`vehicle`?n(`lpr`):(e===`face`||e===`propagated`)&&n(`face`)}return Wm(e).length&&n(`lpr`),(e.transcript||e.audioType||e.audioAlarm)&&n(`audio`),((Array.isArray(e.tags)?e.tags.map(e=>String(e).toLowerCase()):[]).some(e=>[`package`,`parcel`,`delivery`,`box`,`cardboard`].includes(e))||e.packageCount)&&n(`package`),t.length||t.push(`caption`),t}function Km(e,t,n){let r=$(t);if(r&&r!==e)return r;if(e&&n&&typeof n==`object`){let t=e=>typeof e==`string`?e.trim():e&&typeof e==`object`?$(e.name):``,r=t(n[e]);if(r)return r;let i=e=>e.replace(/[:-]/g,``).trim().toUpperCase(),a=i(e);for(let[e,r]of Object.entries(n))if(i(e)===a){let e=t(r);if(e)return e}}return e||`Unknown camera`}function qm(e,t,n){let r=$(e.cameraId),i=Um(e).label,a=$(e.eventId),o=e.historyId==null?`${Z(e.timestamp)}|${r}|${i}|${a||n}|${$(e.audioType)}`:String(e.historyId),s={...e,key:o,cameraName:Km(r,e.cameraName,t),categories:Gm(e)},c=Am(s.thumbnail);return c?s.thumbnail=c:delete s.thumbnail,s}function Jm(e,t,n){let r=[],i=new Set,a=(e,t)=>{if(!e||typeof e!=`object`)return;let a=qm(e,n,t);i.has(a.key)||(i.add(a.key),r.push(a))};return(t??[]).forEach(a),(e??[]).forEach((e,t)=>a(e,t+1e4)),r.sort((e,t)=>Z(t.timestamp)-Z(e.timestamp)),r}function Ym(e){let t={all:e.length,detection:0,caption:0,face:0,lpr:0,audio:0,package:0};for(let n of e)for(let e of n.categories)t[e]+=1;return t}function Xm(e,t){let n=t.trim().toLowerCase();return!n||[e.cameraName,e.cameraId,e.description,e.transcript,e.audioType&&jm(e.audioType),e.audioAlarm&&jm(e.audioAlarm),Um(e).label,...Array.isArray(e.tags)?e.tags:[],...Array.isArray(e.identities)?e.identities.map(e=>`${e?.name??``} ${e?.plate??``} ${e?.source??``}`):[],...Wm(e).map(e=>e?.plate||e?.text||``)].filter(Boolean).join(` `).toLowerCase().includes(n)}function Zm(e){let t=new Set,n=[];for(let r of Wm(e)){let e=$(r?.plate||r?.text);e&&!t.has(e)&&(t.add(e),n.push({plate:e,confidence:Z(r?.confidence)}))}return n}function Qm(e){let t=$(e.audioType||e.audioAlarm);if(!t)return null;let n=Z(e.audioConfidence),r=n>0?` · ${Math.round(n*100)}%`:e.leveldB==null?``:` · ${Z(e.leveldB)} dB`;return`${jm(t)}${r}`}function $m(e,t){let n=Mm(e.faces?.rejectedReasons);if(Object.values(n).some(e=>Z(e)>0))return Object.fromEntries(Object.entries(n).filter(([,e])=>Z(e)>0).map(([e,t])=>[e,Math.trunc(Z(t))]));let r={};for(let e of t)for(let[t,n]of Object.entries(Mm(e.faces?.rejectedReasons)))Z(n)>0&&(r[t]=(r[t]??0)+Math.trunc(Z(n)));return r}function eh(e,t){let n=Math.trunc(Z(e.avgLatencyMs)),r=Math.trunc(Z(e.lastLatencyMs));if(n>0||r>0)return{avg:n,last:r};let i=t.filter(e=>![`speechtotext`,`stt`,`audio`].includes($(e?.type||e?.kind).toLowerCase())&&Z(e?.elapsedMs)>0).map(e=>Z(e.elapsedMs));return i.length?{avg:Math.round(i.reduce((e,t)=>e+t,0)/i.length),last:Math.trunc(i[0])}:{avg:0,last:0}}function th(e){return $(e)||void 0}function nh(e){return Mm(e.packageDetector??e.packageDetection??e.packages)}function rh(e){let t=nh(e),n=(Array.isArray(e.pairedCameras)?e.pairedCameras:[]).reduce((e,t)=>e+Z(t?.packagesDetected),0);return Z(e.totalPackages,Z(t.totalPackages,Z(t.detections??t.eventsEmitted,n)))}function ih(e){let t=Array.isArray(e.pairedCameras)?e.pairedCameras:[];return Z(e.totalPlates,t.reduce((e,t)=>e+Z(t?.platesRecognized),0))}function ah(e,t){let n=e.toLowerCase();return n.includes(`openvino`)?`OpenVINO ${t||/\((\w+)\)/.exec(e)?.[1]||`GPU`}`.trim():n.includes(`cuda`)?`CUDA`:n.includes(`coreml`)?`CoreML`:n.includes(`tensorrt`)?`TensorRT`:n.startsWith(`cpu`)?`CPU`:e||`Ready`}function oh(e){return e.captionConsecutiveFailed===void 0?Z(e.completed)===0?Math.trunc(Z(e.failed)):0:Math.max(0,Math.trunc(Z(e.captionConsecutiveFailed)))}function sh(e){let t=(e??``).trim().match(/^(\d+)\.(\d+)/);if(!t)return!1;let n=Number(t[1]),r=Number(t[2]);return n<7||n===7&&r<4}function ch(e,t,n){let r=Mm(e.control),i=Mm(e.search),a=Mm(e.worker),o=Mm(e.vision),s=Mm(e.embeddings),c=Mm(e.aiport),l=Mm(e.faces),u=Mm(e.lpr),d=Mm(e.stt),f=Mm(e.enhance),p=r.enabled!==!1,m=Mm(r.commands),h=Object.values(m).reduce((e,t)=>e+Z(t),0),g=Object.entries(m).sort((e,t)=>Z(t[1])-Z(e[1])).slice(0,6).map(([e,t])=>`${e}: ${Q(t)}`).join(`, `),_={id:`control`,title:`Protect control`,port:`:7442`,...p?r.connected?{tone:`ok`,state:`Online`}:r.lastError?{tone:`error`,state:`Error`}:{tone:`warn`,state:`Waiting`}:{tone:`off`,state:`Off`},headline:p?$(r.consoleName)||$(e.controllerHost)||`Pending adoption`:void 0,headlineSub:p&&r.adopted?`Adopted`:void 0,chips:[],rows:p?[{label:`Port`,value:`7442`,title:`UCP4 control channel (WSS)`},{label:`Protect`,value:$(r.protectVersion)||`pending`},{label:`UCP4 commands`,value:Q(h),title:g},{label:`Controller`,value:$(e.controllerHost)||`—`}]:[],disabledHint:p?void 0:`device.enabled: true`,error:p?th(r.lastError):void 0,raw:e.control??{}},v=Array.isArray(c.pairedCameras)?c.pairedCameras:[],y=nh(c),b=rh(c),x=[];if(c.audioVadEnabled){let e=!!c.audioVad?.ready;x.push({label:`Silero VAD`,tone:e?`ok`:`neutral`,title:`Voice activity detection (${e?`ready`:`standby`})`})}let S=c.audioClassifier??c.yamnet;if(S&&S.enabled!==!1){let e=S.ready!==!1;x.push({label:`YAMNet`,tone:e?`info`:`neutral`,title:`Smart audio classifier (${e?`ready`:`loads on first audio`})`})}if(Object.keys(y).length&&y.enabled!==!1){let e=$(y.model)||`D-FINE`,t=/d-?fine/i.test(e)?`D-FINE packages`:`${Nm(e)[0]} packages`,n=y.ready!==!1;x.push({label:t,tone:n?`info`:`neutral`,title:`${e} (${n?`ready`:`loads on demand`})`})}let C=[{label:`Smart`,value:Q(c.totalSmartEvents)},{label:`Audio`,value:Q(c.totalAudioEvents)},{label:`Faces`,value:Q(c.totalFaces)},{label:`Plates`,value:Q(ih(c))}];(b>0||y.enabled)&&C.push({label:`Packages`,value:Q(b)});let w={id:`aiport`,title:`Virtual AI Port`,...c.enabled?c.connected?{tone:`ok`,state:`Online`}:c.lastError?{tone:`error`,state:`Error`}:{tone:`warn`,state:`Ready to adopt`}:{tone:`off`,state:`Off`},headline:c.enabled?`${v.length} camera${v.length===1?``:`s`} paired`:void 0,headlineSub:c.enabled&&$(c.model)||void 0,chips:c.enabled?x:[],rows:c.enabled?[{label:`MAC`,value:$(c.mac)||`—`}]:[],stats:c.enabled?C:void 0,disabledHint:c.enabled?void 0:`aiport.enabled: true`,error:th(c.lastError),raw:(({pairedCameras:e,...t})=>t)(c)},T=$(o.provider)||`disabled`,E=$(o.model)||`disabled`,D=T.toLowerCase()!==`disabled`&&E.toLowerCase()!==`disabled`,O=Math.trunc(Z(a.liveActive??a.active)),k=Math.trunc(Z(a.liveQueued??a.queued)),A=Math.trunc(Z(a.completed)),ee=Math.trunc(Z(a.failed)),j=eh(a,t),te=$(o.frameLayout||o.layout)||(Z(o.maxFrames)>0?`${Z(o.maxFrames)}-frame`:``),M=oh(a),N=th(o.lastError),ne=o.ready===!1||M>=3,re=sh(r.protectVersion),ie=D&&(o.protectAiSummary===!1||r.protectAiSettings?.aiSummary===!1),ae={id:`vision`,title:`Vision captions`,...D?ne?{tone:`error`,state:`Failing`}:O>0?{tone:`info`,state:`Running`}:{tone:`ok`,state:`Ready`}:{tone:`off`,state:`Disabled`},...D&&N?{error:N,errorLabel:`Vision backend error`}:D&&M>0&&$(a.captionLastError)?{error:$(a.captionLastError),errorLabel:ne?`${M} caption jobs failed in a row`:`Last caption job failed`}:{},headline:D?E:void 0,headlineMono:!0,chips:D?[{label:T,tone:`neutral`},...te?[{label:te,tone:`info`}]:[],...ie?[{label:`Protect AI Summary off`,tone:`neutral`,title:re?`Protect sent postVLM=false (AI Summary is off in Protect → Settings → Intelligence). Keystone still uploads captions; click the NeXT AI Summary icon in Protect's event player to view them, or enable AI Summary in Protect.`:`Protect sent postVLM=false (AI Summary is off under Settings → Intelligence → Basic Understanding). Keystone still uploads captions; click the NeXT AI Summary icon in Protect's event player to view them, or toggle Basic Understanding Off then On and click Apply Changes.`}]:[]]:[],rows:D?[{label:`Latency`,value:`${vm(j.avg)} avg · ${vm(j.last)} last`}]:[],stats:D?[{label:`Active`,value:Q(O),tone:O>0?`info`:void 0},{label:`Queued`,value:Q(k)},{label:`Done`,value:Q(A)},{label:`Failed`,value:Q(ee),tone:ee>0?`error`:void 0}]:void 0,disabledHint:D?void 0:`vision.provider, base_url, model`,raw:{...o,worker:a}},oe=s.enabled!==!1,se=$(s.provider)||`ready`,ce=$(s.device||s.openvinoDevice),le=ah(se,ce),ue=[];s.quantization&&ue.push({label:$(s.quantization),tone:`info`}),`textModelLoaded`in s&&ue.push({label:`text ${s.textModelLoaded?`loaded`:`lazy`}`,tone:s.textModelLoaded?`ok`:`neutral`,title:s.textModelLoaded?`Text encoder resident in memory`:`Text encoder loads on the first search`}),ce&&!le.toUpperCase().includes(ce.toUpperCase())&&ue.push({label:ce.toUpperCase(),tone:`info`});let de=Math.trunc(Z(a.retroactiveCompleted)),fe=Math.trunc(Z(a.retroactiveQueued)),pe=Math.trunc(Z(a.retroactiveFailed)),me=Math.trunc(Z(a.retroactiveImagesIndexed)),he=de+fe,ge=[{label:`Port`,value:`7443`,title:`Find Anything search channel (WSS)`},{label:`Queries`,value:`${Q(i.queriesServed)} text · ${Q(i.imageQueriesServed)} image`}],P;if(he>0||me>0){let e=de>0&&fe===0?100:he>0?Math.round(de/he*100):0,t=[`${Q(de)} events`,`${Q(me)} images`];fe&&t.push(`${Q(fe)} queued`),pe&&t.push(`${Q(pe)} failed`),P={label:`Retroactive backfill`,detail:t.join(` · `),pct:e}}else s.retroactiveProcessing&&ge.push({label:`Retroactive backfill`,value:`Idle`});let F={id:`search`,title:`Find Anything`,port:`:7443`,...oe?i.connected?{tone:`ok`,state:`Online`}:i.lastError?{tone:`error`,state:`Error`}:{tone:`warn`,state:`Waiting`}:{tone:`off`,state:`Disabled`},headline:oe?$(s.backend||`clip`).toUpperCase():void 0,headlineSub:oe?le:void 0,chips:oe?ue:[],rows:oe?ge:[],progress:oe?P:void 0,disabledHint:oe?void 0:`embeddings.enabled: true`,error:th(i.lastError),raw:{...s,search:i}},_e=Mm(l.gallery),ve=$m(e,n),ye={id:`faces`,title:`Face recognition`,...l.enabled?l.ready?{tone:`ok`,state:`Ready`}:l.lastError?{tone:`error`,state:`Error`}:{tone:`warn`,state:`Loading`}:{tone:`off`,state:`Off`},headline:l.enabled?`${Q(_e.people)} ${Z(_e.people)===1?`person`:`people`} enrolled`:void 0,headlineSub:l.enabled?`${Q(_e.templates)} refs`:void 0,chips:l.enabled?[...l.nativeProtect?[{label:`Native Protect`,tone:`info`,title:`Names flow into Protect's face library`}]:[],...l.detector?[{label:[l.detector,l.recognizer].filter(Boolean).join(` + `),tone:`neutral`}]:[]]:[],rows:l.enabled?[{label:`Matched`,value:`${Q(l.facesMatched)} of ${Q(l.eventsScanned)} scans`}]:[],people:l.enabled?Object.entries(Mm(_e.perPerson)).map(([e,t])=>({name:e,refs:Z(t)})):void 0,rejections:Object.entries(ve).sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,6).map(([e,t])=>({label:`${e} ${t}`,tone:`warn`,title:Em[e]??`Face rejected: ${e}`})),disabledHint:l.enabled?void 0:`faces.enabled: true`,error:th(l.lastError),raw:e.faces??{}},[be,xe]=Nm(u.detector),[Se,Ce]=Nm(u.ocr),we=Z(u.platesRecognized,Z(u.aiKeyPlates)),Te={id:`lpr`,title:`License plates`,...u.enabled?u.ready?{tone:`ok`,state:`Ready`}:u.lastError?{tone:`error`,state:`Error`}:{tone:`warn`,state:`Loading`}:{tone:`off`,state:`Off`},headline:u.enabled?`${Q(we)} plate${we===1?``:`s`} read`:void 0,chips:u.enabled?[...u.nativeProtect?[{label:`Native Protect`,tone:`info`}]:[],...be||Se?[{label:[be,Se].filter(Boolean).join(` + `),tone:`neutral`,title:[xe,Ce].filter(Boolean).join(` / `)}]:[]]:[],rows:u.enabled?[{label:`AI Key uploads`,value:Q(u.aiKeyUploads)},{label:`Last inference`,value:vm(u.lastInferMs)}]:[],disabledHint:u.enabled?void 0:`lpr.enabled: true`,error:th(u.lastError),raw:e.lpr??{}},Ee=Z(d.completed||d.transcriptions),De=!!d.enabled&&(d.protectEnabled===!1||r.protectAiSettings?.stt===!1),Oe={id:`stt`,title:`Speech to text`,...d.enabled?d.ready?De?{tone:`warn`,state:`Off in Protect`}:{tone:`ok`,state:`Ready`}:d.lastError?{tone:`error`,state:`Error`}:{tone:`warn`,state:`Loading`}:{tone:`off`,state:`Off`},headline:d.enabled?$(d.model)||`whisper`:void 0,headlineMono:!0,chips:d.enabled&&d.quantization?[{label:$(d.quantization),tone:`info`}]:[],rows:d.enabled?[{label:`Transcripts`,value:`${Q(Ee)} · ${Q(d.segments)} segments`},{label:`Latency`,value:`${vm(d.avgElapsedMs||d.lastElapsedMs)} avg`}]:[],disabledHint:d.enabled?void 0:`stt.enabled: true`,...De?{noticeLabel:`Disabled in UniFi Protect`,notice:re?`Protect is not sending Speech-to-Text jobs. Enable Speech-to-Text under Protect → Settings → Intelligence.`:`Protect is not sending Speech-to-Text jobs. In Protect → Settings → Intelligence → Basic Understanding, toggle it Off then On and click Apply Changes (or choose Selected Only to enable Speech to Text per camera).`}:{},error:th(d.lastError),raw:e.stt??{}},ke=Z(f.enhanced||a.enhanceCompleted);return[_,w,ae,F,ye,Te,Oe,{id:`enhance`,title:`Face enhance`,...f.enabled?f.lastError?{tone:`error`,state:`Error`}:{tone:`ok`,state:`Ready`}:{tone:`off`,state:`Off`},headline:f.enabled?$(f.backend||`gfpgan`).toUpperCase():void 0,headlineSub:f.enabled?f.modelLoaded?`Loaded`:`Loads on demand`:void 0,chips:f.enabled&&f.model?[{label:Nm(f.model)[0],tone:`neutral`,title:$(f.model)}]:[],rows:f.enabled?[{label:`Faces restored`,value:Q(ke)},{label:`Last run`,value:vm(f.lastElapsedMs)}]:[],disabledHint:f.enabled?void 0:`enhance.enabled: true`,error:th(f.lastError),raw:e.enhance??{}}].map(t=>dh(t,e.inference))}var lh={aiport:[`aiport:`],search:[`clip:`],faces:[`face:`],lpr:[`lpr`],stt:[`stt:`],enhance:[`enhance:`]};function uh(e,t){let n=lh[e]??[];return Object.entries(Mm(t)).filter(([e])=>n.some(t=>e.startsWith(t)))}function dh(e,t){if(e.tone===`off`)return e;let n=uh(e.id,t),r=n.filter(([,e])=>e.failing),i=n.filter(([,e])=>Z(e.consecutiveFailures)>0),a=(r.length?r:i).sort((e,t)=>Z(t[1].lastErrorAt)-Z(e[1].lastErrorAt))[0];if(!a)return e;let[o,s]=a,c=Z(s.consecutiveFailures);return{...e,...r.length?{tone:`error`,state:`Failing`}:e.tone===`error`?{}:{tone:`warn`,state:`Degraded`},error:$(s.lastError)||e.error,errorLabel:`${o} · ${c} failed run${c===1?``:`s`} in a row`}}function fh(e){let t=e.control??{};if(t.enabled===!1)return{subtitle:`Standalone Virtual AI Port for UniFi Protect`,adoption:e.aiport?.adopted?`AI Port adopted`:`Waiting for AI Port adoption in UniFi Protect`};let n=$(t.consoleName);return{subtitle:`Local AI Key for UniFi Protect`,adoption:t.adopted?n?`Adopted by ${n}`:`Adopted`:`Waiting for adoption in UniFi Protect`}}function ph(e){let t=e.filter(e=>e.tone!==`off`),n=t.filter(e=>e.tone===`error`),r=t.filter(e=>e.tone===`warn`),i=[...n,...r],a=`${t.length-i.length} of ${t.length} services healthy`;return n.length?{tone:`error`,title:n.length===1?`${n[0].title} is failing`:`${n.length} services are failing`,detail:a,attention:i}:r.length?{tone:`warn`,title:r.length===1?`${r[0].title} needs attention`:`${r.length} services need attention`,detail:a,attention:i}:{tone:`ok`,title:`All systems operational`,detail:a,attention:i}}var mh=[`person`,`vehicle`,`animal`,`face`,`licensePlate`,`package`];function hh(e){let t=Mm(e.aiport);return t.enabled?(Array.isArray(t.pairedCameras)?t.pairedCameras:[]).filter(e=>e&&typeof e==`object`).map(t=>{let n=$(t.deviceId),r=Km(n,t.name,e.cameras),i=Mm(t.channels),a=Object.keys(i).sort((e,t)=>Number(!e.startsWith(`video`))-Number(!t.startsWith(`video`))||e.localeCompare(t)).map(e=>({name:e,connected:!!i[e]?.connected,bytes:Z(i[e]?.bytesSent),stream:$(i[e]?.streamName)||e}));a.length||a.push({name:`relay`,connected:!!t.relayRunning,bytes:Z(t.bytesSent),stream:`relay`});let o=a.filter(e=>e.connected).length,s=new Set((Array.isArray(t.enabledTypes)?t.enabledTypes:[]).map(e=>String(e))),c=new Set([...s].map(e=>e.toLowerCase())),l=e=>s.has(e)||c.has(e.toLowerCase()),u={face:Z(t.facesDetected),licensePlate:Z(t.platesRecognized),package:Z(t.packagesDetected)},d={licensePlate:!!t.licensePlateEnabled,package:!!t.packageEnabled},f=mh.filter(e=>l(e)||d[e]||(u[e]??0)>0).map(e=>({key:e,count:u[e]??0})),p=[];(t.audioSpeakEnabled||t.audioVadRunning)&&p.push(`Speech`);for(let e of t.audioTypes??t.enabledAudioTypes??t.smartDetectAudioTypes??[]){let t=jm(e);p.includes(t)||p.push(t)}let m=Z(t.width),h=Z(t.height);return{id:n,name:r,showId:!!n&&r!==n,resolution:m&&h?`${m}×${h}`:`—`,fps:Z(t.fps),state:o===a.length?`live`:o>0?`partial`:`idle`,channels:a,bytes:Z(t.bytesSent,a.reduce((e,t)=>e+t.bytes,0)),hwaccelLabel:gh(t),detections:f,audio:p,frames:Z(t.framesAnalyzed),events:Z(t.eventsEmitted),audioEvents:Z(t.audioEventsEmitted)}}):[]}function gh(e){return e.hwaccelBackend===`videotoolbox`?`VideoToolbox`:e.hwaccelBackend===`vaapi`||e.hwaccelBackend===void 0&&e.vaapiActive?`VA-API`:null}function _h(e){return{count:e.length,streaming:e.filter(e=>e.state!==`idle`).length,bytes:e.reduce((e,t)=>e+t.bytes,0),frames:e.reduce((e,t)=>e+t.frames,0),events:e.reduce((e,t)=>e+t.events+t.audioEvents,0),bytesLabel:_m(e.reduce((e,t)=>e+t.bytes,0))}}var vh={"1h":{label:`Last hour`,hours:1},"24h":{label:`Last 24 hours`,hours:24},"7d":{label:`Last 7 days`,hours:168},"30d":{label:`Last 30 days`,hours:720}};function yh(e,t,n,r){let i=new URLSearchParams({range:e,limit:`50`});return t!==`all`&&i.set(`category`,t),n.trim()&&i.set(`q`,n.trim()),r&&i.set(`cursor`,r),`api/history?${i}`}function bh(e,t,n,r,i,a){let o=t-vh[n].hours*36e5,s=e.filter(({timestamp:e})=>e!=null&&e>=o&&e<=t),c=s.filter(e=>(r===`all`||e.categories.includes(r))&&Xm(e,i)),l=Number(a??0);return{items:c.slice(l,l+50),counts:Ym(s),cameraCounts:{},matched:c.length,nextCursor:l+50o&&a.push(e.slice(o,s)),a.push((0,z.jsx)(`mark`,{className:`bg-transparent font-semibold text-foreground underline decoration-info/50 underline-offset-2`,children:e.slice(s,s+n.length)},s)),o=s+n.length,s=r.indexOf(i,o);return o0?`OCR confidence ${Math.round(t*100)}%`:`License plate`,children:[e,t>0&&(0,z.jsxs)(`span`,{className:`font-normal tracking-normal text-muted-foreground`,children:[Math.round(t*100),`%`]})]})}function Th({item:e}){return(0,z.jsx)(z.Fragment,{children:(e.identities??[]).map((e,t)=>{let n=String(e?.name??``).trim();if(!n)return null;let r=String(e?.source??`face`).toLowerCase();if(r===`propagated`)return(0,z.jsxs)(Mp,{tone:`info`,title:e.fromCamera?`Propagated from ${e.fromCamera}`:`Propagated identity`,children:[(0,z.jsx)(be,{className:`size-3`}),n]},`${n}-${t}`);if(r===`lpr`)return(0,z.jsx)(Mp,{tone:`warn`,title:`Vehicle matched by license plate`,children:n},`${n}-${t}`);let i=Z(e?.similarity);return(0,z.jsx)(Mp,{tone:`ok`,title:`Matched by ${r}${i>0?` · ${Math.round(i*100)}% similarity`:``}`,children:n},`${n}-${t}`)})})}function Eh({item:e,query:t,now:n,fresh:r,onOpen:i}){let a=Um(e),o=Zm(e),s=Qm(e),c=String(e.transcript??``).trim(),l=String(e.description??``).trim(),u=(Array.isArray(e.tags)?e.tags:[]).map(String).filter(Boolean),d=Object.entries(e.faces?.rejectedReasons??{}),f=Z(e.timestamp);return(0,z.jsx)(`li`,{children:(0,z.jsxs)(`button`,{type:`button`,onClick:i,className:L(`group grid w-full grid-cols-[auto_minmax(0,1fr)_auto] items-start gap-3.5 px-4 py-3 text-left transition-colors hover:bg-muted/60 focus-visible:bg-muted focus-visible:outline-none sm:gap-4`,r&&`animate-arrive`),children:[(0,z.jsx)(Ch,{item:e}),(0,z.jsxs)(`div`,{className:`min-w-0 space-y-1`,children:[(0,z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,z.jsx)(`span`,{className:L(`text-xs font-medium`,xh[a.tone].text),children:a.label}),(0,z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:(0,z.jsx)(Sh,{text:e.cameraName,query:t})}),o.map(e=>(0,z.jsx)(wh,{...e},e.plate)),(0,z.jsx)(Th,{item:e}),s&&(0,z.jsx)(Mp,{tone:`warn`,children:s})]}),c?(0,z.jsxs)(`p`,{className:`line-clamp-2 text-sm text-foreground/90 italic`,children:[`“`,(0,z.jsx)(Sh,{text:c,query:t}),`”`]}):(0,z.jsx)(`p`,{className:L(`line-clamp-2 text-sm`,l?`text-foreground/90`:`text-muted-foreground`),children:l?(0,z.jsx)(Sh,{text:l,query:t}):`No description`}),(u.length>0||d.length>0)&&(0,z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground`,children:[u.length>0&&(0,z.jsxs)(`span`,{className:`truncate`,children:[u.slice(0,8).map((e,n)=>(0,z.jsxs)(`span`,{children:[n>0&&(0,z.jsx)(`span`,{className:`px-1 text-muted-foreground/50`,children:`·`}),(0,z.jsx)(Sh,{text:e,query:t})]},e)),u.length>8&&(0,z.jsxs)(`span`,{className:`pl-1 text-muted-foreground/70`,children:[`+`,u.length-8]})]}),d.length>0&&(0,z.jsxs)(`span`,{className:`text-warning`,children:[`Face rejected: `,d.map(([e,t])=>`${e} ×${Z(t)}`).join(`, `)]})]})]}),(0,z.jsxs)(`div`,{className:`flex flex-col items-end gap-0.5 pt-0.5 text-right`,children:[(0,z.jsx)(`time`,{dateTime:f>0&&f<=864e13?new Date(f).toISOString():void 0,title:xm(f),className:`font-mono text-xs tabular`,children:bm(f)}),(0,z.jsx)(`span`,{className:`text-xs text-muted-foreground tabular`,children:Cm(f,n)}),Z(e.elapsedMs)>0&&(0,z.jsx)(`span`,{className:`font-mono text-[11px] text-muted-foreground/80 tabular`,title:`Processing time`,children:vm(e.elapsedMs)})]})]})})}var Dh=[];function Oh({history:e,now:t,onOpen:n}){let{page:r,range:i,counts:a,category:o,query:s,setCategory:c,setQuery:l}=e,u=r?.items??Dh,d=(0,_.useRef)(null),[f,p]=(0,_.useState)(u),[m,h]=(0,_.useState)(()=>new Set);if(u!==f){let e=new Set(f.map(e=>e.key));h(new Set(u.filter(t=>!e.has(t.key)).map(e=>e.key))),p(u)}(0,_.useEffect)(()=>{let e=e=>{let t=e.target?.closest(`input, textarea, [contenteditable=true]`);e.key!==`/`||t||e.metaKey||e.ctrlKey||(e.preventDefault(),d.current?.focus())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let g=[];for(let e of u){let n=Z(e.timestamp),r=n>0?Tm(n):`unknown`,i=g[g.length-1];i&&i.key===r||(i={key:r,label:n>0?wm(n,t):`Unknown time`,items:[]},g.push(i)),i.items.push(e)}let v=r?`${Q(r.matched)}${r.matchede.setRange(t.target.value),className:`h-8 cursor-pointer rounded-md border bg-card px-2 text-sm font-medium`,children:Object.entries(vh).map(([e,{label:t}])=>(0,z.jsx)(`option`,{value:e,children:t},e))})]})}),(0,z.jsxs)(`div`,{className:`overflow-hidden rounded-lg border bg-card`,children:[(0,z.jsxs)(`div`,{className:`flex flex-col gap-3 border-b p-3 lg:flex-row lg:items-center lg:justify-between`,children:[(0,z.jsx)(`div`,{className:`-mx-3 overflow-x-auto px-3 md:mx-0 md:px-0`,children:(0,z.jsx)(hm,{type:`single`,variant:`outline`,size:`sm`,value:o,onValueChange:e=>e&&c(e),"aria-label":`Filter events`,children:Hm.map(e=>(0,z.jsxs)(gm,{value:e.key,className:`gap-1.5 px-2.5 text-[13px]`,children:[e.label,(0,z.jsx)(`span`,{className:`font-mono text-[11px] text-muted-foreground tabular`,children:a?Q(a[e.key]):`—`})]},e.key))})}),(0,z.jsxs)(om,{className:`h-8 lg:w-64`,children:[(0,z.jsx)(cm,{children:(0,z.jsx)(Je,{className:`size-3.5`})}),(0,z.jsx)(dm,{ref:d,value:s,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(l(``),e.currentTarget.blur())},id:`activity-search`,name:`q`,autoComplete:`off`,maxLength:512,placeholder:`Search cameras, captions, plates…`,"aria-label":`Search events`,type:`search`}),(0,z.jsx)(cm,{align:`inline-end`,children:s?(0,z.jsx)(um,{size:`icon-xs`,"aria-label":`Clear search`,onClick:()=>l(``),children:(0,z.jsx)(ot,{})}):(0,z.jsx)(fm,{children:`/`})})]})]}),e.incomplete&&(0,z.jsx)(`p`,{role:`status`,className:`border-b px-4 py-3 text-sm text-warning`,children:`Some activity in this period could not be saved. Event totals may be incomplete.`}),e.fallback===`store-unavailable`&&(0,z.jsxs)(`div`,{role:`status`,className:`flex items-center justify-between gap-3 border-b px-4 py-3 text-sm text-warning`,children:[`Saved history is unavailable. Showing recent activity.`,(0,z.jsx)(hp,{size:`sm`,variant:`outline`,onClick:e.refresh,children:`Retry`})]}),e.error&&(0,z.jsxs)(`div`,{role:`status`,className:`flex items-center justify-between gap-3 border-b px-4 py-3 text-sm text-warning`,children:[r?`Activity could not refresh. Showing the last update.`:`Could not load activity history.`,(0,z.jsx)(hp,{size:`sm`,variant:`outline`,onClick:e.refresh,children:`Retry`})]}),r?u.length===0?(0,z.jsx)($p,{className:`rounded-none py-14`,children:(0,z.jsxs)(em,{children:[(0,z.jsx)(nm,{variant:`icon`,children:(0,z.jsx)(ne,{strokeWidth:1.75})}),(0,z.jsx)(rm,{children:r.counts.all?`No matching events`:`No recorded activity in this time range`}),(0,z.jsx)(im,{children:r.counts.all?`Try another category or search term.`:i===`30d`?`No events are available for the last 30 days.`:`Choose a longer range to see earlier events.`})]})}):(0,z.jsx)(`div`,{children:g.map(e=>(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`p`,{className:`sticky top-14 z-10 border-b bg-card/95 px-4 py-1.5 text-[11.5px] font-medium text-muted-foreground backdrop-blur`,children:e.label}),(0,z.jsx)(`ul`,{className:`divide-y`,children:e.items.map(e=>(0,z.jsx)(Eh,{item:e,query:s,now:t,fresh:m.has(e.key),onOpen:()=>n(e)},e.key))})]},e.key))}):!e.error&&(0,z.jsx)(`p`,{role:`status`,className:`py-14 text-center text-sm text-muted-foreground`,children:`Loading activity…`}),(e.hasPrevious||r?.nextCursor)&&(0,z.jsxs)(`nav`,{"aria-label":`Activity pages`,className:`flex justify-end gap-2 border-t px-3 py-2`,children:[(0,z.jsxs)(hp,{variant:`outline`,size:`sm`,disabled:!e.hasPrevious,onClick:e.previous,children:[(0,z.jsx)(fe,{}),` Newer events`]}),(0,z.jsxs)(hp,{variant:`outline`,size:`sm`,disabled:!r?.nextCursor,onClick:e.next,children:[`Older events `,(0,z.jsx)(me,{})]})]})]})]})}function kh({className:e,...t}){return(0,z.jsx)(`div`,{"data-slot":`table-container`,className:`relative w-full overflow-x-auto`,children:(0,z.jsx)(`table`,{"data-slot":`table`,className:L(`w-full caption-bottom text-sm`,e),...t})})}function Ah({className:e,...t}){return(0,z.jsx)(`thead`,{"data-slot":`table-header`,className:L(`[&_tr]:border-b`,e),...t})}function jh({className:e,...t}){return(0,z.jsx)(`tbody`,{"data-slot":`table-body`,className:L(`[&_tr:last-child]:border-0`,e),...t})}function Mh({className:e,...t}){return(0,z.jsx)(`tr`,{"data-slot":`table-row`,className:L(`border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted`,e),...t})}function Nh({className:e,...t}){return(0,z.jsx)(`th`,{"data-slot":`table-head`,className:L(`h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0`,e),...t})}function Ph({className:e,...t}){return(0,z.jsx)(`td`,{"data-slot":`table-cell`,className:L(`p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0`,e),...t})}var Fh={person:{icon:nt,label:`Person`},vehicle:{icon:ie,label:`Vehicle`},animal:{icon:Pe,label:`Animal`},face:{icon:He,label:`Face`},licensePlate:{icon:Re,label:`License plate`},package:{icon:Ae,label:`Package`}};function Ih({cam:e}){return(0,z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1`,children:[e.detections.map(({key:e,count:t})=>{let n=Fh[e],r=n.icon;return(0,z.jsxs)(wp,{children:[(0,z.jsx)(Tp,{asChild:!0,children:(0,z.jsxs)(`span`,{className:L(`inline-flex h-6 items-center gap-1 rounded-md border bg-background px-1.5 text-muted-foreground`,t>0&&`border-info/30 bg-info-soft text-info`),children:[(0,z.jsx)(r,{className:`size-3.5`,strokeWidth:1.75}),t>0&&(0,z.jsx)(`span`,{className:`font-mono text-[11px] tabular`,children:Q(t)})]})}),(0,z.jsxs)(Ep,{children:[n.label,t>0?` · ${Q(t)} detected`:``]})]},e)}),e.audio.length>0&&(0,z.jsxs)(wp,{children:[(0,z.jsx)(Tp,{asChild:!0,children:(0,z.jsxs)(`span`,{className:`inline-flex h-6 items-center gap-1 rounded-md border bg-background px-1.5 text-muted-foreground`,children:[(0,z.jsx)(M,{className:`size-3.5`,strokeWidth:1.75}),(0,z.jsx)(`span`,{className:`text-[11px]`,children:e.audio.length})]})}),(0,z.jsxs)(Ep,{children:[`Audio: `,e.audio.join(`, `)]})]})]})}function Lh({cam:e}){return(0,z.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:e.channels.map(e=>(0,z.jsxs)(wp,{children:[(0,z.jsx)(Tp,{asChild:!0,children:(0,z.jsxs)(`span`,{className:L(`inline-flex h-6 items-center gap-1.5 rounded-md border bg-background px-2 font-mono text-[11px]`,!e.connected&&`text-muted-foreground`),children:[(0,z.jsx)(Ap,{tone:e.connected?`ok`:`off`}),e.name]})}),(0,z.jsxs)(Ep,{children:[e.connected?`Streaming`:`Idle`,` · `,_m(e.bytes),` relayed`,(0,z.jsx)(`span`,{className:`block font-mono opacity-70`,children:e.stream})]})]},e.name))})}var Rh={live:`All channels streaming`,partial:`Some channels idle`,idle:`Not streaming`};function zh({cameras:e,aiportEnabled:t,range:n,cameraCounts:r,incomplete:i}){let a=_h(e);return(0,z.jsxs)(`section`,{id:`cameras`,className:`scroll-mt-28`,children:[(0,z.jsx)(Zp,{title:`Cameras`,meta:e.length?`${a.streaming} of ${a.count} streaming · ${a.bytesLabel} relayed`:void 0}),e.length===0?(0,z.jsx)($p,{className:`border bg-card`,children:(0,z.jsxs)(em,{children:[(0,z.jsx)(nm,{variant:`icon`,children:(0,z.jsx)(oe,{strokeWidth:1.75})}),(0,z.jsx)(rm,{children:`No paired cameras`}),(0,z.jsx)(im,{children:t?`Adopt the virtual AI Port in UniFi Protect and pair ONVIF cameras to it. They’ll show up here.`:`The virtual AI Port is off. Set aiport.enabled: true to run smart detections on ONVIF cameras.`})]})}):(0,z.jsx)(`div`,{className:`overflow-hidden rounded-lg border bg-card`,children:(0,z.jsxs)(kh,{children:[(0,z.jsx)(Ah,{children:(0,z.jsxs)(Mh,{className:`hover:bg-transparent`,children:[(0,z.jsx)(Nh,{className:`h-10 pl-4 text-xs font-medium text-muted-foreground`,children:`Camera`}),(0,z.jsx)(Nh,{className:`hidden h-10 text-xs font-medium text-muted-foreground sm:table-cell`,children:`Stream`}),(0,z.jsx)(Nh,{className:`hidden h-10 text-xs font-medium text-muted-foreground lg:table-cell`,children:`Channels`}),(0,z.jsx)(Nh,{className:`h-10 text-xs font-medium text-muted-foreground`,children:`Detections`}),(0,z.jsx)(Nh,{className:`hidden h-10 text-right text-xs font-medium text-muted-foreground md:table-cell`,title:`Frames analyzed since Keystone started`,children:`Frames`}),(0,z.jsxs)(Nh,{className:`h-10 pr-4 text-right text-xs font-medium text-muted-foreground`,title:n?`AI Port events emitted · ${vh[n].label}`:`AI Port events emitted since startup`,children:[`Events `,(0,z.jsxs)(`span`,{className:`font-normal`,children:[`· `,n??`session`]})]})]})}),(0,z.jsx)(jh,{children:e.map(e=>(0,z.jsxs)(Mh,{className:`h-14`,children:[(0,z.jsx)(Ph,{className:`max-w-56 pl-4`,children:(0,z.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,z.jsxs)(wp,{children:[(0,z.jsx)(Tp,{asChild:!0,children:(0,z.jsx)(`span`,{className:`grid size-4 place-items-center`,children:(0,z.jsx)(Ap,{tone:e.state===`live`?`ok`:e.state===`partial`?`warn`:`off`})})}),(0,z.jsx)(Ep,{children:Rh[e.state]})]}),(0,z.jsxs)(`div`,{className:`min-w-0`,children:[(0,z.jsx)(`p`,{className:`truncate font-medium`,children:e.name}),e.showId&&(0,z.jsx)(`p`,{className:`truncate font-mono text-[11px] text-muted-foreground`,children:e.id})]})]})}),(0,z.jsx)(Ph,{className:`hidden sm:table-cell`,children:(0,z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,z.jsxs)(`span`,{className:`font-mono text-xs tabular`,children:[e.resolution,e.fps?(0,z.jsxs)(`span`,{className:`text-muted-foreground`,children:[` · `,e.fps,` fps`]}):null]}),e.hwaccelLabel&&(0,z.jsx)(Mp,{tone:`info`,title:`Hardware video decode via ${e.hwaccelLabel}`,children:e.hwaccelLabel})]})}),(0,z.jsx)(Ph,{className:`hidden lg:table-cell`,children:(0,z.jsx)(Lh,{cam:e})}),(0,z.jsx)(Ph,{children:(0,z.jsx)(Ih,{cam:e})}),(0,z.jsx)(Ph,{className:`hidden text-right font-mono text-xs tabular md:table-cell`,children:Q(e.frames)}),(0,z.jsxs)(Ph,{className:`pr-4 text-right font-mono text-xs tabular`,title:i?`Some events in this period could not be saved`:void 0,children:[i&&`≥`,n?r?Q(r[e.id]??0):`—`:Q(e.events+e.audioEvents)]})]},e.id||e.name))})]})})]})}function Bh({...e}){return(0,z.jsx)(Wr,{"data-slot":`collapsible`,...e})}function Vh({...e}){return(0,z.jsx)(Kr,{"data-slot":`collapsible-trigger`,...e})}function Hh({...e}){return(0,z.jsx)(Jr,{"data-slot":`collapsible-content`,...e})}function Uh({title:e,children:t}){return(0,z.jsxs)(`section`,{className:`space-y-2`,children:[(0,z.jsx)(`h3`,{className:`text-[13px] font-medium text-muted-foreground`,children:e}),t]})}function Wh({rows:e}){let t=e.filter(([,e])=>e!=null&&e!==``);return t.length?(0,z.jsx)(`dl`,{className:`divide-y rounded-lg border bg-card text-sm`,children:t.map(([e,t])=>(0,z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-3 py-2`,children:[(0,z.jsx)(`dt`,{className:`text-muted-foreground`,children:e}),(0,z.jsx)(`dd`,{className:`text-right font-mono text-xs tabular`,children:t})]},e))}):null}function Gh({item:e,onOpenChange:t}){return(0,z.jsx)(Fp,{open:!!e,onOpenChange:t,children:(0,z.jsx)(Rp,{className:`w-full gap-0 outline-none sm:max-w-lg`,onOpenAutoFocus:Sp,children:e&&(0,z.jsx)(Kh,{item:e})})})}function Kh({item:e}){let t=Um(e),n=Zm(e),r=Qm(e),i=String(e.transcript??``).trim(),a=String(e.description??``).trim(),o=(Array.isArray(e.tags)?e.tags:[]).map(String).filter(Boolean),s=(e.identities??[]).filter(e=>e&&String(e.name??``).trim()),c=e.faces,l=Object.entries(c?.rejectedReasons??{}),{thumbnail:u,categories:d,key:f,...p}=e;return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(zp,{className:`border-b`,children:(0,z.jsxs)(`div`,{className:`flex items-start gap-4 pr-8`,children:[(0,z.jsx)(Ch,{item:e,size:`lg`}),(0,z.jsxs)(`div`,{className:`min-w-0 space-y-1.5`,children:[(0,z.jsx)(`p`,{className:L(`text-xs font-medium`,xh[t.tone].text),children:t.label}),(0,z.jsx)(Vp,{className:`text-lg leading-tight tracking-[-0.02em]`,children:e.cameraName}),(0,z.jsx)(Hp,{className:`tabular`,children:xm(e.timestamp)}),(0,z.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 pt-0.5`,children:[n.map(e=>(0,z.jsx)(wh,{...e},e.plate)),(0,z.jsx)(Th,{item:e}),r&&(0,z.jsx)(Mp,{tone:`warn`,children:r})]})]})]})}),(0,z.jsxs)(`div`,{className:`flex-1 space-y-6 overflow-y-auto p-4`,children:[i?(0,z.jsx)(Uh,{title:`Transcript`,children:(0,z.jsxs)(`blockquote`,{className:`border-l-2 border-info/50 pl-3 text-[15px] leading-relaxed`,children:[`“`,i,`”`]})}):(0,z.jsx)(Uh,{title:`Description`,children:(0,z.jsx)(`p`,{className:L(`text-[15px] leading-relaxed`,!a&&`text-muted-foreground`),children:a||`No description`})}),o.length>0&&(0,z.jsx)(Uh,{title:`Tags`,children:(0,z.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:o.map(e=>(0,z.jsx)(Mp,{children:e},e))})}),s.length>0&&(0,z.jsx)(Uh,{title:`Identities`,children:(0,z.jsx)(`div`,{className:`divide-y rounded-lg border bg-card text-sm`,children:s.map((e,t)=>(0,z.jsxs)(`div`,{className:`flex items-center justify-between gap-3 px-3 py-2`,children:[(0,z.jsxs)(`div`,{className:`min-w-0`,children:[(0,z.jsx)(`p`,{className:`truncate font-medium`,children:e.name}),(0,z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[String(e.source??`face`),e.fromCamera?` from ${e.fromCamera}`:``,Z(e.secondsAgo)>0?` · ${Z(e.secondsAgo)}s earlier`:``]})]}),(0,z.jsxs)(`div`,{className:`text-right font-mono text-xs tabular`,children:[Z(e.similarity)>0&&(0,z.jsx)(`p`,{children:ym(e.similarity)}),Z(e.margin)>0&&(0,z.jsxs)(`p`,{className:`text-muted-foreground`,children:[`margin `,Z(e.margin).toFixed(2)]})]})]},`${e.name}-${t}`))})}),n.length>0&&(0,z.jsx)(Uh,{title:`License plates`,children:(0,z.jsx)(Wh,{rows:n.map(e=>[e.plate,e.confidence>0?ym(e.confidence):`—`])})}),c&&(Z(c.framesScanned)>0||Z(c.detections)>0)&&(0,z.jsxs)(Uh,{title:`Face scan`,children:[(0,z.jsx)(Wh,{rows:[[`Frames scanned`,Z(c.framesScanned)],[`Faces detected`,Z(c.detections)],[`Passed quality gate`,Z(c.qualityFaces)],[`Scan time`,Z(c.elapsedMs)>0?vm(c.elapsedMs):null]]}),l.length>0&&(0,z.jsx)(`ul`,{className:`space-y-1.5 pt-1`,children:l.map(([e,t])=>(0,z.jsxs)(`li`,{className:`flex gap-2 text-xs`,children:[(0,z.jsxs)(Mp,{tone:`warn`,children:[e,` ×`,Z(t)]}),(0,z.jsx)(`span`,{className:`pt-0.5 text-muted-foreground`,children:Em[e]??`Quality gate`})]},e))})]}),(0,z.jsx)(Uh,{title:`Processing`,children:(0,z.jsx)(Wh,{rows:[[`Total time`,Z(e.elapsedMs)>0?vm(e.elapsedMs):null],[`Objects indexed`,Z(e.indexedObjects)>0?Z(e.indexedObjects):null],[`Speech segments`,Z(e.sttSegments)>0?Z(e.sttSegments):null],[`Audio length`,Z(e.audioSeconds)>0?`${Z(e.audioSeconds).toFixed(1)}s`:null],[`Packages`,Z(e.packageCount)>0?Z(e.packageCount):null],[`Source`,e.source?String(e.source):null],[`Event ID`,e.eventId?String(e.eventId):null]]})}),(0,z.jsxs)(Bh,{children:[(0,z.jsxs)(Vh,{className:`group flex items-center gap-1 text-[13px] font-medium text-muted-foreground hover:text-foreground`,children:[(0,z.jsx)(ue,{className:`size-3.5 transition-transform group-data-[state=closed]:-rotate-90`}),`Raw event`]}),(0,z.jsx)(Hh,{className:`pt-2`,children:(0,z.jsx)(`div`,{className:`rounded-lg border bg-card px-3 py-1.5`,children:(0,z.jsx)(yp,{data:p})})})]})]}),(0,z.jsx)(Bp,{className:`border-t`,children:(0,z.jsx)(xp,{data:p})})]})}function qh({values:e,className:t,label:n}){let r=(0,_.useId)();if(e.length<2)return(0,z.jsx)(`div`,{className:L(`h-7`,t),"aria-hidden":`true`});let i=Math.max(...e,1),a=Math.min(...e,0),o=i-a||1,s=120/(e.length-1),c=e.map((e,t)=>[t*s,25-(e-a)/o*21]),l=c.map(([e,t],n)=>`${n?`L`:`M`}${e.toFixed(1)},${t.toFixed(1)}`).join(` `),u=`${l} L120,28 L0,28 Z`,d=c[c.length-1][1];return(0,z.jsxs)(`div`,{className:L(`relative h-7 w-full text-info`,t),role:`img`,"aria-label":n,children:[(0,z.jsxs)(`svg`,{viewBox:`0 0 120 28`,preserveAspectRatio:`none`,className:`absolute inset-0 size-full overflow-visible`,children:[(0,z.jsx)(`defs`,{children:(0,z.jsxs)(`linearGradient`,{id:r,x1:`0`,x2:`0`,y1:`0`,y2:`1`,children:[(0,z.jsx)(`stop`,{offset:`0%`,stopColor:`currentColor`,stopOpacity:`0.2`}),(0,z.jsx)(`stop`,{offset:`100%`,stopColor:`currentColor`,stopOpacity:`0`})]})}),(0,z.jsx)(`path`,{d:u,fill:`url(#${r})`}),(0,z.jsx)(`path`,{d:l,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,vectorEffect:`non-scaling-stroke`})]}),(0,z.jsx)(`span`,{className:`absolute size-1.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-current`,style:{left:`100%`,top:`${d/28*100}%`},"aria-hidden":`true`,children:(0,z.jsx)(`span`,{className:`absolute inset-0 rounded-full bg-current animate-ping-slow`})})]})}function Jh({label:e,value:t}){let[n,r]=(0,_.useState)(!1);return(0,z.jsxs)(wp,{open:n||void 0,children:[(0,z.jsx)(Tp,{asChild:!0,children:(0,z.jsxs)(`button`,{type:`button`,onClick:async()=>{try{await navigator.clipboard.writeText(t),r(!0),window.setTimeout(()=>r(!1),1400)}catch{}},className:`group inline-flex h-7 items-center gap-2 rounded-md border bg-card px-2.5 text-xs transition-colors hover:border-border-strong`,children:[(0,z.jsx)(`span`,{className:`text-muted-foreground`,children:e}),(0,z.jsx)(`span`,{className:`font-mono text-foreground`,children:t}),n?(0,z.jsx)(ce,{className:`size-3 text-success`}):(0,z.jsx)(ve,{className:`size-3 text-muted-foreground/60 transition-colors group-hover:text-muted-foreground`})]})}),(0,z.jsx)(Ep,{children:n?`Copied`:`Copy ${e}`})]})}var Yh={ok:ge,info:ge,warn:et,error:F,off:ge};function Xh({status:e,health:t,cameras:n,history:r,lastUpdated:i,generatedAt:a,demo:o,accel:s,now:c,onOpenService:l}){let u=((e.control??{}).protectVersion??``).trim(),d=Yh[t.tone],f=fh(e),p=[f.adoption];u&&p.push(`Protect ${u}`),p.push(t.detail),o?p.push(`sample data`):a?p.push(`snapshot from ${Sm(a)}`):i&&p.push(`updated ${Cm(i,c)}`);let m=[];return e.mac&&m.push({label:`MAC`,value:e.mac}),e.advertiseIp&&m.push({label:`IP`,value:e.advertiseIp}),e.controllerHost&&m.push({label:`Controller`,value:e.controllerHost}),(0,z.jsxs)(`section`,{id:`top`,className:`scroll-mt-20 pt-10 pb-2 sm:pt-14`,children:[(0,z.jsx)(`p`,{className:`text-[13px] font-medium text-muted-foreground`,children:f.subtitle}),(0,z.jsxs)(`h1`,{className:`mt-2 flex items-center gap-3 text-3xl font-semibold tracking-[-0.045em] text-balance sm:text-[40px] sm:leading-[1.1]`,children:[(0,z.jsx)(d,{className:L(`size-7 shrink-0 sm:size-8`,Dp[t.tone]),strokeWidth:2}),t.title]}),(0,z.jsx)(`p`,{className:`mt-3 max-w-[68ch] text-base text-muted-foreground`,children:p.join(` · `)}),t.attention.length>0&&(0,z.jsx)(`div`,{className:`mt-4 flex flex-wrap gap-2`,children:t.attention.map(e=>(0,z.jsxs)(`button`,{type:`button`,onClick:()=>l(e),className:`group inline-flex h-7 items-center gap-2 rounded-md border bg-card pr-1.5 pl-2 text-xs transition-colors hover:border-border-strong`,children:[(0,z.jsx)(jp,{tone:e.tone,className:`-ml-1 h-5`,children:e.state}),(0,z.jsx)(`span`,{className:`font-medium`,children:e.title}),(0,z.jsx)(me,{className:`size-3.5 text-muted-foreground transition-transform group-hover:translate-x-0.5`})]},e.id))}),m.length>0&&(0,z.jsxs)(`div`,{className:`mt-5 flex flex-wrap gap-2`,children:[m.map(e=>(0,z.jsx)(Jh,{...e},e.label)),(0,z.jsxs)(`span`,{className:L(`inline-flex h-7 items-center gap-1.5 rounded-md border bg-card px-2.5 font-mono text-xs md:hidden`,s.warning?`text-warning`:s.hardware?`text-info`:`text-muted-foreground`),children:[(0,z.jsx)(Se,{className:`size-3.5`,strokeWidth:1.75}),s.label]}),s.warning&&(0,z.jsx)(`p`,{className:`w-full rounded-md bg-warning-soft px-2.5 py-2 text-xs leading-relaxed text-warning md:hidden`,children:s.warning})]}),(0,z.jsx)($h,{status:e,cameras:n,history:r,snapshot:!!a})]})}function Zh({label:e,value:t,unit:n,sub:r,children:i,tone:a}){return(0,z.jsxs)(`div`,{className:`flex min-h-[116px] flex-col rounded-lg border bg-card px-5 pt-4 pb-4`,children:[(0,z.jsx)(`p`,{className:`text-[13px] font-medium text-muted-foreground`,children:e}),(0,z.jsxs)(`p`,{className:`mt-2.5 flex items-baseline gap-1.5 truncate`,children:[(0,z.jsx)(`span`,{className:`text-xl font-medium tracking-[-0.025em] tabular`,children:t}),n&&(0,z.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:n})]}),i,r&&(0,z.jsx)(`p`,{className:L(`mt-auto pt-1 text-[13px] text-muted-foreground tabular`,a&&Dp[a]),children:r})]})}function Qh(e,t){let n=[];for(let r=1;r0&&a>=0?a/i:0)}return n}function $h({status:e,cameras:t,history:n,snapshot:r}){let i=_h(t),a=Qh(n,`frames`),o=a.length?a[a.length-1]:null,s=e.worker??{},c=Z(s.completed),l=Z(s.failed),u=e.aiport??{};return(0,z.jsxs)(`div`,{className:`mt-8 grid grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-4`,children:[(0,z.jsx)(Zh,{label:`Cameras`,value:Q(i.count),unit:i.count?`paired`:void 0,sub:i.count?`${i.streaming} streaming · ${i.bytesLabel} relayed`:`No AI Port cameras yet`}),(0,z.jsx)(Zh,{label:`Frames analyzed`,value:o==null?Q(i.frames):o.toFixed(1),unit:o==null?void 0:`fps`,sub:o==null?r||!i.count?`Across ${i.count} camera${i.count===1?``:`s`}`:`Live rate appears after a few seconds`:`${Q(i.frames)} total`,children:a.length>=2&&(0,z.jsx)(qh,{values:a,className:`mt-2`,label:`Frames analyzed per second`})}),(0,z.jsx)(Zh,{label:`Captions`,value:Q(c),unit:`done`,tone:oh(s)>=3?`error`:void 0,sub:`${vm(s.avgLatencyMs)} avg${l?` · ${Q(l)} failed`:``}`}),(0,z.jsx)(Zh,{label:`Smart detections since startup`,value:Q(u.totalSmartEvents),sub:`${Q(u.totalAudioEvents)} audio · ${Q(u.totalFaces)} faces · ${Q(u.totalPlates)} plates`})]})}function eg({...e}){return(0,z.jsx)(sd,{"data-slot":`dropdown-menu`,...e})}function tg({...e}){return(0,z.jsx)(ld,{"data-slot":`dropdown-menu-trigger`,...e})}function ng({className:e,align:t=`start`,sideOffset:n=4,...r}){return(0,z.jsx)(ud,{children:(0,z.jsx)(fd,{"data-slot":`dropdown-menu-content`,sideOffset:n,align:t,className:L(`z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) min-w-32 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:overflow-hidden data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95`,e),...r})})}function rg({...e}){return(0,z.jsx)(md,{"data-slot":`dropdown-menu-radio-group`,...e})}function ig({className:e,children:t,inset:n,...r}){return(0,z.jsxs)(hd,{"data-slot":`dropdown-menu-radio-item`,"data-inset":n,className:L(`relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,e),...r,children:[(0,z.jsx)(`span`,{className:`pointer-events-none absolute right-2 flex items-center justify-center`,"data-slot":`dropdown-menu-radio-item-indicator`,children:(0,z.jsx)(gd,{children:(0,z.jsx)(ce,{})})}),t]})}function ag({className:e,inset:t,...n}){return(0,z.jsx)(pd,{"data-slot":`dropdown-menu-label`,"data-inset":t,className:L(`px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7`,e),...n})}function og({className:e,...t}){return(0,z.jsx)(_d,{"data-slot":`dropdown-menu-separator`,className:L(`-mx-1 my-1 h-px bg-border`,e),...t})}function sg({...e}){return(0,z.jsx)(Ed,{"data-slot":`popover`,...e})}function cg({...e}){return(0,z.jsx)(Od,{"data-slot":`popover-trigger`,...e})}function lg({className:e,align:t=`center`,sideOffset:n=4,...r}){return(0,z.jsx)(Md,{children:(0,z.jsx)(Pd,{"data-slot":`popover-content`,align:t,sideOffset:n,className:L(`z-50 flex w-72 origin-(--radix-popover-content-transform-origin) flex-col gap-2.5 rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95`,e),...r})})}function ug({className:e,orientation:t=`horizontal`,decorative:n=!0,...r}){return(0,z.jsx)(df,{"data-slot":`separator`,decorative:n,orientation:t,className:L(`shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch`,e),...r})}function dg(e,t){return e.map(e=>Z(e.timestamp)>0?{...e,timestamp:Z(e.timestamp)+t}:e)}function fg(e,t,n){let r=e.aiport?.pairedCameras;if(!Array.isArray(r)||!r.length)return e;let i=r.map((e,r)=>{let i=e.channels??{};if(!(Object.values(i).some(e=>e?.connected)||e.relayRunning))return e;let a=Z(e.fps,15)*(.45+.15*Math.sin(n/9+r*1.7)),o=Object.fromEntries(Object.entries(i).map(([e,n])=>[e,n?.connected?{...n,bytesSent:Z(n.bytesSent)+Math.round(t*18e4)}:n])),s=Object.values(o).reduce((e,t)=>e+Z(t?.bytesSent),0)-Object.values(i).reduce((e,t)=>e+Z(t?.bytesSent),0);return{...e,channels:o,framesAnalyzed:Z(e.framesAnalyzed)+Math.round(t*a),bytesSent:Z(e.bytesSent)+s}});return{...e,aiport:{...e.aiport,pairedCameras:i}}}function pg(e,t){let n=String(t.kind??t.type??``).toLowerCase(),r=n===`stt`||n===`speechtotext`,i=n===`audio`,a=!r&&!i,o=Zm(t).length,s=(t.identities??[]).filter(e=>String(e?.source??``).toLowerCase()===`face`).length,c=Math.max(Z(t.faces?.qualityFaces),s),l=!!(t.faces&&Z(t.faces.framesScanned)>0),u={...e.aiport};u.pairedCameras=(u.pairedCameras??[]).map(e=>!e.deviceId||e.deviceId!==t.cameraId||r?e:{...e,eventsEmitted:Z(e.eventsEmitted)+ +!!a,audioEventsEmitted:Z(e.audioEventsEmitted)+ +!!i,platesRecognized:Z(e.platesRecognized)+o,facesDetected:Z(e.facesDetected)+c,packagesDetected:Z(e.packagesDetected)+ +(n===`package`)}),a&&(u.totalSmartEvents=Z(u.totalSmartEvents)+1),i&&(u.totalAudioEvents=Z(u.totalAudioEvents)+1),n===`package`&&(u.totalPackages=Z(u.totalPackages)+1),o&&(u.totalPlates=Z(u.totalPlates)+o),c&&(u.totalFaces=Z(u.totalFaces)+c);let d={...e,aiport:u};if((n===``||n===`caption`)&&(d.worker={...e.worker,completed:Z(e.worker?.completed)+1}),r){let n=Z(e.stt?.completed??e.stt?.transcriptions)+1;d.stt={...e.stt,completed:n,transcriptions:n,segments:Z(e.stt?.segments)+Z(t.sttSegments)}}return o&&(d.lpr={...e.lpr,platesRecognized:Z(e.lpr?.platesRecognized)+o}),(l||s)&&(d.faces={...e.faces,eventsScanned:Z(e.faces?.eventsScanned)+1,facesMatched:Z(e.faces?.facesMatched)+s}),d}var mg=3e3,hg=8e3,gg=14,_g=4;function vg(){try{let e=document.getElementById(`keystone-initial-data`);if(e?.textContent){let t=JSON.parse(e.textContent);if(t&&typeof t==`object`)return t}}catch{}return{}}function yg(){return window.location.protocol===`http:`||window.location.protocol===`https:`}function bg(e){let t=Array.isArray(e.aiport?.pairedCameras)?e.aiport.pairedCameras:[];return{frames:t.reduce((e,t)=>e+Z(t?.framesAnalyzed),0),events:t.reduce((e,t)=>e+Z(t?.eventsEmitted)+Z(t?.audioEventsEmitted),0),captions:Z(e.worker?.completed)}}async function xg(e,t){let n=await fetch(e,{cache:`no-store`,signal:t});if(!n.ok)throw Error(`${e} → HTTP ${n.status}`);return await n.json()}function Sg(e,t,n){let r=e.status??{},i=Array.isArray(e.events)?e.events:[],a=Array.isArray(e.activity)?e.activity:[],o=Object.keys(r).length>0,s=Date.now();if(n){let t=Z(e.generatedAt)||Math.max(0,...[...i,...a].map(e=>Z(e.timestamp))),n=t>0?s-t:0,o=r,c=[];for(let e=gg;e>=0;e--){let t=s-e*mg;eCg(e)),n=yg()&&!t,r=!!(e.status&&Object.keys(e.status).length),[i]=(0,_.useState)(()=>Sg(e,n,t)),[a,o]=(0,_.useState)(i.status),[s,c]=(0,_.useState)(i.events),[l,u]=(0,_.useState)(i.activity),[d,f]=(0,_.useState)(n||!!t),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(r),[v,y]=(0,_.useState)(i.lastUpdated),[b,x]=(0,_.useState)(i.history),S=(0,_.useRef)(null),C=(0,_.useRef)(i.status),w=(0,_.useRef)(0),T=(0,_.useRef)(Array.isArray(t?.queue)?[...t.queue]:[]),E=(0,_.useRef)(!r),D=(0,_.useCallback)(async()=>{if(!n)return;S.current?.abort();let e=new AbortController;S.current=e;let t=window.setTimeout(()=>e.abort(),hg);try{let[t,n,r]=await Promise.all([xg(`api/status`,e.signal),xg(`api/events`,e.signal),xg(`api/activity`,e.signal)]);if(!t||typeof t!=`object`)throw Error(`Malformed /api/status payload`);let i=Date.now();o(t),c(Array.isArray(n?.events)?n.events:[]),u(Array.isArray(r?.activity)?r.activity:[]),y(i),m(!1),g(!0),x(e=>[...e,{t:i,...bg(t)}].slice(-40))}catch(t){if(e.signal.aborted&&S.current!==e)return;m(!0),t instanceof DOMException||console.warn(`Keystone poll failed:`,t)}finally{window.clearTimeout(t)}},[n]);(0,_.useEffect)(()=>{if(!n||!d)return;let e,t=()=>{document.visibilityState===`visible`&&D()},r=()=>{window.clearInterval(e),e=window.setInterval(t,mg)},i=()=>{document.visibilityState===`visible`?(D(),r()):window.clearInterval(e)},a=E.current?window.setTimeout(t,0):void 0;return E.current=!1,r(),document.addEventListener(`visibilitychange`,i),()=>{window.clearTimeout(a),window.clearInterval(e),document.removeEventListener(`visibilitychange`,i);let t=S.current;S.current=null,t?.abort()}},[n,d,D]),(0,_.useEffect)(()=>{C.current=a},[a]),(0,_.useEffect)(()=>{if(!t||!d)return;let e=window.setInterval(()=>{if(document.visibilityState!==`visible`)return;let e=Date.now();w.current+=1;let t=fg(C.current,mg/1e3,e/1e3);if(w.current%_g===2&&T.current.length){let n={...T.current.shift(),timestamp:e};t=pg(t,n),u(e=>[n,...e].slice(0,60))}C.current=t,o(t),y(e),x(n=>[...n,{t:e,...bg(t)}].slice(-40))},mg);return()=>window.clearInterval(e)},[t,d]);let O=(0,_.useCallback)(e=>{f(e),e&&D()},[D]),k;return k=t?d?`demo`:`paused`:n?d?p?`reconnecting`:h?`live`:`connecting`:`paused`:`snapshot`,{status:a,events:s,activity:l,connection:k,lastUpdated:v,generatedAt:Z(e.generatedAt)>0?Z(e.generatedAt):null,demo:t,history:b,live:d,setLive:O,refresh:D}}function Tg({className:e}){return(0,z.jsxs)(`svg`,{viewBox:`0 0 24 24`,className:L(`size-6 shrink-0`,e),"aria-hidden":`true`,children:[(0,z.jsx)(`rect`,{width:`24`,height:`24`,rx:`6`,className:`fill-foreground`}),(0,z.jsxs)(`g`,{transform:`translate(0 0.2)`,children:[(0,z.jsx)(`path`,{d:`M4 18.6L4 15.2A8 8 0 0 1 8.37 8.07L10.18 11.64A4 4 0 0 0 8 15.2L8 18.6Z`,className:`fill-background`}),(0,z.jsx)(`path`,{d:`M9.53 7.59A8 8 0 0 1 14.47 7.59L13.24 11.4A4 4 0 0 0 10.76 11.4Z`,className:`fill-mark-key`}),(0,z.jsx)(`path`,{d:`M15.63 8.07A8 8 0 0 1 20 15.2L20 18.6L16 18.6L16 15.2A4 4 0 0 0 13.82 11.64Z`,className:`fill-background`})]})]})}var Eg={live:{label:`Live`,tone:`ok`},demo:{label:`Demo`,tone:`info`},connecting:{label:`Connecting`,tone:`info`},reconnecting:{label:`Reconnecting`,tone:`warn`},paused:{label:`Paused`,tone:`off`},snapshot:{label:`Snapshot`,tone:`off`}};function Dg({connection:e,live:t,setLive:n,lastUpdated:r}){let i=Eg[e];if(e===`snapshot`)return(0,z.jsxs)(wp,{children:[(0,z.jsx)(Tp,{asChild:!0,children:(0,z.jsxs)(`span`,{className:`inline-flex h-7 items-center gap-2 rounded-md border px-2.5 text-xs font-medium text-muted-foreground`,children:[(0,z.jsx)(Ap,{tone:`off`}),`Snapshot`]})}),(0,z.jsx)(Ep,{children:`Static export. Open the served dashboard for live data.`})]});let a=Math.round(mg/1e3);return(0,z.jsxs)(wp,{children:[(0,z.jsx)(Tp,{asChild:!0,children:(0,z.jsxs)(hp,{variant:`outline`,size:`sm`,onClick:()=>n(!t),"aria-pressed":t,className:`gap-2 font-medium tabular`,children:[(0,z.jsx)(Ap,{tone:i.tone,pulse:e===`live`||e===`demo`}),i.label,t?(0,z.jsx)(Me,{className:`size-3 text-muted-foreground`}):(0,z.jsx)(Ie,{className:`size-3 text-muted-foreground`})]})}),(0,z.jsxs)(Ep,{children:[e===`demo`?`Sample data, animated in your browser · click to pause`:t?`Refreshing every ${a}s · click to pause`:`Paused · click to resume`,r&&e!==`demo`?` · updated ${bm(r)}`:``]})]})}function Og({accel:e}){return(0,z.jsxs)(sg,{children:[(0,z.jsx)(cg,{asChild:!0,children:(0,z.jsxs)(hp,{variant:`ghost`,size:`sm`,className:L(`gap-1.5 font-mono text-xs font-normal`,e.warning?`text-warning`:e.hardware?`text-info`:`text-muted-foreground`),children:[e.warning?(0,z.jsx)(et,{className:`size-3.5`,strokeWidth:1.75}):(0,z.jsx)(Se,{className:`size-3.5`,strokeWidth:1.75}),e.label]})}),(0,z.jsxs)(lg,{align:`end`,className:`max-h-[var(--radix-popover-content-available-height)] w-80 overflow-y-auto p-0`,children:[(0,z.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b px-4 py-3`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`p`,{className:`text-sm font-medium tracking-tight`,children:`Inference acceleration`}),(0,z.jsx)(`p`,{className:`font-mono text-xs text-muted-foreground`,children:e.detail})]}),e.precision&&(0,z.jsx)(Mp,{mono:!0,children:e.precision})]}),(e.warning||e.note)&&(0,z.jsx)(`p`,{className:L(`mx-3 mt-3 rounded-md px-2.5 py-2 text-xs leading-relaxed`,e.warning?`bg-warning-soft text-warning`:`bg-muted text-muted-foreground`),children:e.warning??e.note}),(e.devices.length>0||e.videoDecode)&&(0,z.jsxs)(`dl`,{className:`space-y-2 border-b px-4 py-3 text-xs`,children:[e.devices.length>0&&(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{className:`font-medium`,children:`Detected hardware`}),(0,z.jsx)(`dd`,{className:`text-muted-foreground`,children:e.devices.join(`, `)})]}),e.videoDecode&&(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`dt`,{className:`font-medium`,children:`Video decode`}),(0,z.jsx)(`dd`,{className:`text-muted-foreground`,children:e.videoDecode})]})]}),e.models.length?(0,z.jsx)(`ul`,{className:`p-1.5`,children:e.models.map(e=>(0,z.jsxs)(`li`,{className:`flex items-center justify-between gap-3 rounded-md px-2.5 py-1.5 text-sm hover:bg-muted`,children:[(0,z.jsx)(`span`,{className:L(!e.loaded&&`text-muted-foreground`),children:e.label}),(0,z.jsx)(Mp,{mono:!0,tone:e.loaded?e.hardware?`info`:`neutral`:`off`,children:e.provider})]},e.key))}):(0,z.jsx)(`p`,{className:`px-4 py-3 text-sm text-muted-foreground`,children:`This runtime doesn’t report per-model execution providers.`}),e.fallbacks.length>0&&(0,z.jsx)(`ul`,{"aria-label":`CPU fallbacks`,className:`space-y-2 border-t px-4 py-3 text-xs`,children:e.fallbacks.map(({model:e,requestedProvider:t,reason:n})=>(0,z.jsxs)(`li`,{className:`break-words`,children:[(0,z.jsxs)(`p`,{className:`font-medium`,children:[e,` `,(0,z.jsx)(Mp,{tone:`warn`,children:`CPU fallback`})]}),(0,z.jsxs)(`p`,{className:`mt-1 text-muted-foreground`,children:[t,`. `,n]})]},e))}),!!e.diagnostics?.length&&(0,z.jsx)(`ul`,{"aria-label":`Acceleration diagnostics`,className:`space-y-2 border-t px-4 py-3 text-xs leading-relaxed text-warning`,children:e.diagnostics.map(e=>(0,z.jsx)(`li`,{children:e},e))})]})]})}function kg({preference:e,setPreference:t}){return(0,z.jsxs)(eg,{children:[(0,z.jsx)(tg,{asChild:!0,children:(0,z.jsx)(hp,{variant:`ghost`,size:`icon-sm`,"aria-label":`Theme`,children:(0,z.jsx)(e===`dark`?Ee:e===`light`?Qe:we,{className:`size-4`,strokeWidth:1.75})})}),(0,z.jsxs)(ng,{align:`end`,className:`w-40`,children:[(0,z.jsx)(ag,{children:`Appearance`}),(0,z.jsx)(og,{}),(0,z.jsxs)(rg,{value:e,onValueChange:e=>t(e),children:[(0,z.jsxs)(ig,{value:`system`,children:[(0,z.jsx)(we,{strokeWidth:1.75}),` System`]}),(0,z.jsxs)(ig,{value:`light`,children:[(0,z.jsx)(Qe,{strokeWidth:1.75}),` Light`]}),(0,z.jsxs)(ig,{value:`dark`,children:[(0,z.jsx)(Ee,{strokeWidth:1.75}),` Dark`]})]})]})]})}function Ag(e){let[t,n]=(0,_.useState)(null),r=e.join(`|`);return(0,_.useEffect)(()=>{let e=r.split(`|`).map(e=>document.getElementById(e)).filter(e=>!!e);if(!e.length||!(`IntersectionObserver`in window))return;let t=new Map,i=new IntersectionObserver(r=>{for(let e of r)t.set(e.target.id,e.isIntersecting?e.intersectionRatio:0);let i=null,a=0;for(let n of e){let e=t.get(n.id)??0;e>a&&(i=n.id,a=e)}n(i)},{rootMargin:`-96px 0px -45% 0px`,threshold:[0,.1,.25,.5]});return e.forEach(e=>i.observe(e)),()=>i.disconnect()},[r]),t}function jg({sections:e}){let t=Ag(e.map(e=>e.id));return(0,z.jsx)(`nav`,{"aria-label":`Sections`,className:`ml-4 hidden h-full items-stretch md:flex`,children:e.map(e=>(0,z.jsxs)(`a`,{href:`#${e.id}`,"aria-current":t===e.id?`location`:void 0,className:L(`relative flex items-center gap-1.5 px-3 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground`,`after:absolute after:inset-x-3 after:bottom-[-1px] after:h-0.5 after:rounded-t after:bg-foreground after:opacity-0 after:transition-opacity`,t===e.id&&`text-foreground after:opacity-100`),children:[e.label,e.tone&&e.tone!==`ok`&&(0,z.jsx)(Ap,{tone:e.tone}),e.count!=null&&e.count>0&&(0,z.jsx)(`span`,{className:`font-mono text-[11px] text-muted-foreground tabular`,children:e.count})]},e.id))})}function Mg({appName:e,version:t,accel:n,connection:r,live:i,setLive:a,lastUpdated:o,refresh:s,theme:c,setTheme:l,sections:u}){return(0,z.jsx)(`header`,{className:`sticky top-0 z-40 border-b bg-background/85 backdrop-blur-md backdrop-saturate-150`,children:(0,z.jsxs)(`div`,{className:`mx-auto flex h-14 max-w-[1200px] items-center gap-3 px-4 sm:px-6`,children:[(0,z.jsxs)(`a`,{href:`#top`,className:`flex items-center gap-2.5 rounded-md outline-offset-4`,children:[(0,z.jsx)(Tg,{}),(0,z.jsx)(`span`,{className:`text-[15px] font-semibold tracking-[-0.03em]`,children:e})]}),(0,z.jsxs)(Mp,{mono:!0,className:`hidden sm:inline-flex`,children:[`v`,t]}),(0,z.jsx)(jg,{sections:u}),(0,z.jsxs)(`div`,{className:`ml-auto flex items-center gap-1.5`,children:[(0,z.jsx)(`div`,{className:`hidden md:block`,children:(0,z.jsx)(Og,{accel:n})}),(0,z.jsx)(ug,{orientation:`vertical`,className:`mx-1 hidden h-5 md:block`}),r===`reconnecting`&&(0,z.jsx)(hp,{variant:`ghost`,size:`icon-sm`,onClick:s,"aria-label":`Retry now`,children:(0,z.jsx)(Be,{className:`size-3.5`})}),(0,z.jsx)(Dg,{connection:r,live:i,setLive:a,lastUpdated:o}),(0,z.jsx)(kg,{preference:c,setPreference:l})]})]})})}var Ng=[`api/status`,`api/events`,`api/activity`,`healthz`];function Pg({appName:e,version:t,snapshot:n,demoLink:r}){let i=r!==void 0;return(0,z.jsx)(`footer`,{className:`border-t`,children:(0,z.jsxs)(`div`,{className:`mx-auto flex max-w-[1200px] flex-col gap-3 px-4 py-6 text-[13px] text-muted-foreground sm:flex-row sm:items-center sm:justify-between sm:px-6`,children:[(0,z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,z.jsx)(Tg,{className:`size-4 opacity-70`}),(0,z.jsxs)(`span`,{children:[e,t?` ${t}`:``,` · open-source local AI for UniFi Protect`]})]}),i&&(0,z.jsxs)(`p`,{children:[`Demo with sample data; nothing here is a real home.`,r&&(0,z.jsxs)(z.Fragment,{children:[` `,(0,z.jsx)(`a`,{href:r,className:`font-medium text-foreground underline-offset-4 hover:underline`,children:`Get Keystone →`})]})]}),!n&&!i&&(0,z.jsx)(`nav`,{"aria-label":`JSON endpoints`,className:`flex flex-wrap gap-x-4 gap-y-1 font-mono text-xs`,children:Ng.map(e=>(0,z.jsxs)(`a`,{href:e,className:`transition-colors hover:text-foreground`,children:[`/`,e]},e))})]})})}function Fg(e,t,n,r,i,a){let[o,s]=(0,_.useState)(null),c=e||o!==null,[l,u]=(0,_.useState)(`24h`),[d,f]=(0,_.useState)(`all`),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)([]),v=h.at(-1)??null,y=c?null:v,b=yh(l,d,p,y),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(null),[T,E]=(0,_.useState)(0),D=()=>E(e=>e+1);(0,_.useEffect)(()=>{if(e||o===`older-runtime`)return;let t=!1,n,r=null,c=async()=>{if(t||r)return;window.clearTimeout(n);let e=new AbortController;r=e;let u=window.setTimeout(()=>e.abort(),8e3);try{let n=await fetch(b,{signal:e.signal,cache:`no-store`});if(n.status===404||n.status===503){if(!t){let e=n.status===404?`older-runtime`:`store-unavailable`;e!==o&&(s(e),g([]),e===`store-unavailable`&&a())}return}if(!n.ok)throw Error(String(n.status));let r=await n.json();t||(o&&(s(null),g([])),S({url:b,range:l,page:r}),w(null))}catch{t||w(b)}finally{window.clearTimeout(u),r=null,!t&&i&&!y&&document.visibilityState===`visible`&&(n=window.setTimeout(c,mg))}},u=()=>{document.visibilityState===`visible`&&i&&!y?c():window.clearTimeout(n)},d=window.setTimeout(c,p.trim()?180:0);return document.addEventListener(`visibilitychange`,u),()=>{t=!0,window.clearTimeout(d),r?.abort(),window.clearTimeout(n),document.removeEventListener(`visibilitychange`,u)}},[e,o,b,l,i,y,p,T,a]);let O=(0,_.useMemo)(()=>c?bh(t,r,l,d,p,v):!x||x.url!==b?null:{...x.page,items:x.page.items.map((e,t)=>qm(e,n,t))},[c,t,r,l,d,p,v,x,b,n]);return{page:O,counts:O?.counts??(x?.range===l?x.page.counts:null),incomplete:!c&&x?.range===l&&!!x.page.incomplete,cameraCounts:x?.range===l?x.page.cameraCounts:null,error:!c&&C===b,fallback:o,range:l,category:d,query:p,setRange:e=>{u(e),g([])},setCategory:e=>{f(e),g([])},setQuery:e=>{m(e),g([])},hasPrevious:!!v,previous:()=>g(e=>e.slice(0,-1)),next:()=>{O?.nextCursor&&g([...h,O.nextCursor])},refresh:D}}var Ig=`keystone-theme`;function Lg(){try{let e=window.localStorage.getItem(Ig);if(e===`light`||e===`dark`||e===`system`)return e}catch{}return`system`}function Rg(e){let t=e===`dark`||e===`system`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches;document.documentElement.classList.toggle(`dark`,t)}function zg(){let[e,t]=(0,_.useState)(Lg);return(0,_.useEffect)(()=>{if(Rg(e),e!==`system`)return;let t=window.matchMedia(`(prefers-color-scheme: dark)`),n=()=>Rg(`system`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)},[e]),{preference:e,setPreference:(0,_.useCallback)(e=>{t(e);try{window.localStorage.setItem(Ig,e)}catch{}},[])}}function Bg(e=1e3){let[t,n]=(0,_.useState)(()=>Date.now());return(0,_.useEffect)(()=>{let t=window.setInterval(()=>n(Date.now()),e);return()=>window.clearInterval(t)},[e]),t}function Vg(){let e=wg(),{preference:t,setPreference:n}=zg(),r=Bg(1e3),{status:i,events:a,activity:o}=e,s=e.connection===`snapshot`&&e.generatedAt?e.generatedAt:r,c=(0,_.useMemo)(()=>Jm(a,o,i.cameras),[a,o,i.cameras]),l=!!e.demo||e.connection===`snapshot`,u=e.connection===`snapshot`?s:e.lastUpdated??s,d=Fg(l,c,i.cameras,u,e.live,e.refresh),f=(0,_.useMemo)(()=>ch(i,a,c),[i,a,c]),p=(0,_.useMemo)(()=>hh(i),[i]),m=(0,_.useMemo)(()=>ph(f),[f]),h=(0,_.useMemo)(()=>Bm(i),[i]),[g,v]=(0,_.useState)(null),[y,b]=(0,_.useState)(null),x=f.find(e=>e.id===g)??null,S=String(i.app||`Keystone`),C=String(i.control?.consoleName??``).trim();return(0,_.useEffect)(()=>{let e=m.tone===`error`?`● `:``;document.title=`${e}${S}${C?` · ${C}`:``}`},[S,C,m.tone]),(0,z.jsxs)(Cp,{delayDuration:200,children:[(0,z.jsxs)(`div`,{className:`min-h-svh`,children:[(0,z.jsx)(Mg,{appName:S,version:String(i.version||`—`),accel:h,connection:e.connection,live:e.live,setLive:e.setLive,lastUpdated:e.lastUpdated,refresh:()=>{e.refresh(),d.refresh()},theme:t,setTheme:n,sections:[{id:`services`,label:`Services`,tone:m.tone===`ok`?void 0:m.tone},{id:`cameras`,label:`Cameras`},{id:`activity`,label:`Activity`,count:d.counts?.all}]}),(0,z.jsxs)(`main`,{className:`mx-auto max-w-[1200px] space-y-12 px-4 pb-16 sm:px-6`,children:[(0,z.jsx)(Xh,{status:i,health:m,cameras:p,history:e.history,lastUpdated:e.lastUpdated,generatedAt:e.connection===`snapshot`?e.generatedAt:null,demo:!!e.demo,accel:h,now:s,onOpenService:e=>v(e.id)}),(0,z.jsx)(Xp,{services:f,onOpen:e=>v(e.id)}),(0,z.jsx)(zh,{cameras:p,aiportEnabled:!!i.aiport?.enabled,range:l||d.fallback?null:d.range,cameraCounts:d.cameraCounts,incomplete:d.incomplete}),(0,z.jsx)(Oh,{history:d,now:s,onOpen:b})]}),(0,z.jsx)(Pg,{appName:S,version:String(i.version||``),snapshot:e.connection===`snapshot`,demoLink:e.demo?e.demo.link??null:void 0})]}),(0,z.jsx)(Qp,{service:x,onOpenChange:e=>!e&&v(null)}),(0,z.jsx)(Gh,{item:y,onOpenChange:e=>!e&&b(null)})]})}(0,v.createRoot)(document.getElementById(`root`)).render((0,z.jsx)(_.StrictMode,{children:(0,z.jsx)(Vg,{})})); diff --git a/tests/test_aiport.py b/tests/test_aiport.py index 005b007..08d8a3a 100644 --- a/tests/test_aiport.py +++ b/tests/test_aiport.py @@ -18,7 +18,7 @@ from aiohttp import web from PIL import Image -from keystone import aiport +from keystone import aiport, hw_probe from keystone.aiport import AiPortService, PairedCameraState from keystone.aiport_detector import ( Detection, @@ -1081,7 +1081,10 @@ async def test_analyzer_hardware_reconnect_policy(tmp_path, monkeypatch, backend svc.config.acceleration.ffmpeg_hwaccel = backend if backend == "videotoolbox": monkeypatch.setattr(aiport.sys, "platform", "darwin") - monkeypatch.setattr(aiport, "probe_videotoolbox", lambda _path: True) + monkeypatch.setattr(hw_probe, "probe_videotoolbox", lambda _path: True) + else: + monkeypatch.setattr(aiport.sys, "platform", "linux") + monkeypatch.setattr(hw_probe, "probe_vaapi_ffmpeg", lambda _ffmpeg, _device: True) launch = asyncio.create_subprocess_exec hw = [] script = ( @@ -1121,11 +1124,11 @@ async def test_videotoolbox_auto_selection_and_status(tmp_path, monkeypatch): svc.config.acceleration.ffmpeg_hwaccel = "auto" monkeypatch.setattr(aiport.sys, "platform", "darwin") probe = Mock(return_value=True) - monkeypatch.setattr(aiport, "probe_videotoolbox", probe) - assert await svc._analyzer_hwaccel(cam) == "videotoolbox" + monkeypatch.setattr(hw_probe, "probe_videotoolbox", probe) + assert await svc._analyzer_hwaccel(cam) == ("videotoolbox", None) probe.assert_called_once_with(svc.config.ffmpeg_path) probe.return_value = False - assert await svc._analyzer_hwaccel(cam) is None + assert await svc._analyzer_hwaccel(cam) == (None, None) cam.hwaccel_backend = "videotoolbox" status = svc.status()["pairedCameras"][0] assert status["hwaccelBackend"] == "videotoolbox" @@ -1140,7 +1143,7 @@ async def test_videotoolbox_falls_back_after_decoder_stalls(tmp_path, monkeypatc svc, cam = _analyzer_camera(tmp_path) svc.config.acceleration.ffmpeg_hwaccel = "videotoolbox" monkeypatch.setattr(aiport.sys, "platform", "darwin") - monkeypatch.setattr(aiport, "probe_videotoolbox", lambda _path: True) + monkeypatch.setattr(hw_probe, "probe_videotoolbox", lambda _path: True) stderr = asyncio.StreamReader() stderr.feed_data(b"VideoToolbox hardware accelerator failed to decode picture\n") stderr.feed_eof() @@ -1168,7 +1171,7 @@ async def test_videotoolbox_retries_with_p010_before_using_software( svc, cam = _analyzer_camera(tmp_path) svc.config.acceleration.ffmpeg_hwaccel = "videotoolbox" monkeypatch.setattr(aiport.sys, "platform", "darwin") - monkeypatch.setattr(aiport, "probe_videotoolbox", lambda _path: True) + monkeypatch.setattr(hw_probe, "probe_videotoolbox", lambda _path: True) def decoder(*, pixel_format=None): stdout, stderr = asyncio.StreamReader(), asyncio.StreamReader() diff --git a/tests/test_enhancer.py b/tests/test_enhancer.py index 74e08da..a4c2182 100644 --- a/tests/test_enhancer.py +++ b/tests/test_enhancer.py @@ -9,6 +9,7 @@ from keystone import enhancer from keystone.config import EnhanceConfig +from keystone.ort_runtime import CPU_EP, OPENVINO_EP, guard_session def _crop(): @@ -63,7 +64,7 @@ def run(self, outputs, feeds): def load(path, **kwargs): assert kwargs["allow_openvino"] sessions.append(path) - return Session(), "CPUExecutionProvider" + return guard_session(Session(), label=kwargs["label"], provider=CPU_EP), CPU_EP monkeypatch.setattr(enhancer, "create_onnx_session", load) monkeypatch.setattr(enhancer, "ensure_enhance_model", lambda spec, path, **kw: path / spec.filename) @@ -95,8 +96,8 @@ def run(self, outputs, feeds): def load(path, *, allow_openvino, **kwargs): attempts.append(allow_openvino) - provider = "OpenVINOExecutionProvider(GPU)" if allow_openvino else "CPUExecutionProvider" - return Session(allow_openvino), provider + provider = f"{OPENVINO_EP}(GPU)" if allow_openvino else CPU_EP + return guard_session(Session(allow_openvino), label=kwargs["label"], provider=provider), provider monkeypatch.setattr(enhancer, "create_onnx_session", load) monkeypatch.setattr(enhancer, "ensure_enhance_model", lambda spec, path, **kw: path / spec.filename) @@ -104,4 +105,6 @@ def load(path, *, allow_openvino, **kwargs): for _ in range(2): runner.enhance_sync(data, kind="plate") assert attempts == [True, False] and runner.fallbacks == 0 - assert runner.status()["plateSrProvider"] == "CPUExecutionProvider" + assert runner.status()["plateSrProvider"] == CPU_EP + assert runner._sr_session.requested_provider == f"{OPENVINO_EP}(GPU)" + assert runner._sr_session.fallback_reason == "Inference failed: device failed at inference" diff --git a/tests/test_hw_probe.py b/tests/test_hw_probe.py new file mode 100644 index 0000000..0691d4f --- /dev/null +++ b/tests/test_hw_probe.py @@ -0,0 +1,239 @@ +"""Hardware diagnostics without host GPU access or installed vendor drivers.""" + +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from keystone import doctor, hw_probe, ort_runtime +from keystone.acceleration import acceleration_diagnostics +from keystone.config import AccelerationConfig + +CPU = ort_runtime.CPU_EP +OPENVINO = ort_runtime.OPENVINO_EP + + +@pytest.fixture +def linux_devices(tmp_path, monkeypatch): + dev = tmp_path / "dev" + dri = dev / "dri" + sysfs = tmp_path / "sys/class/drm" + dev.mkdir() + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.setattr(hw_probe, "_DRI", dri) + monkeypatch.setattr(hw_probe, "_DRM_SYSFS", sysfs) + monkeypatch.setattr(hw_probe, "_KFD", dev / "kfd") + monkeypatch.setattr(hw_probe, "_NVIDIA", dev / "nvidia0") + monkeypatch.setattr(hw_probe, "DEFAULT_VAAPI_DEVICE", str(dri / "renderD128")) + hw_probe.probe_render_nodes.cache_clear() + hw_probe._probe_vaapi_ffmpeg.cache_clear() + ort_runtime.probe_openvino_devices.cache_clear() + yield dev, sysfs + hw_probe.probe_render_nodes.cache_clear() + hw_probe._probe_vaapi_ffmpeg.cache_clear() + ort_runtime.probe_openvino_devices.cache_clear() + + +def _render_node(dev: Path, sysfs: Path, name: str, vendor: str | None) -> Path: + node = dev / "dri" / name + node.parent.mkdir(exist_ok=True) + node.touch() + if vendor is not None: + pci = sysfs / name / "device" + pci.mkdir(parents=True) + (pci / "vendor").write_text(vendor + "\n") + (pci / "device").write_text("0x1234\n") + return node + + +def test_linux_inventory_sorted_and_missing_sysfs(linux_devices, monkeypatch): + dev, sysfs = linux_devices + nvidia = _render_node(dev, sysfs, "renderD131", "0x10DE") + amd = _render_node(dev, sysfs, "renderD130", "0x1002") + intel = _render_node(dev, sysfs, "renderD129", "0x8086") + unknown = _render_node(dev, sysfs, "renderD132", None) + (dev / "kfd").touch() + (dev / "nvidia0").touch() + + def access(path, mode): + assert mode == os.R_OK | os.W_OK + return Path(path) != intel + + monkeypatch.setattr(os, "access", access) + nodes = hw_probe.probe_render_nodes() + assert [node.path for node in nodes] == list(map(str, (intel, amd, nvidia, unknown))) + assert [node.vendor for node in nodes] == ["Intel", "AMD", "NVIDIA", None] + assert [node.vendor_id for node in nodes] == ["0x8086", "0x1002", "0x10de", None] + assert [node.device_id for node in nodes] == ["0x1234", "0x1234", "0x1234", None] + assert [node.accessible for node in nodes] == [False, True, True, True] + assert nodes[0].gid == intel.stat().st_gid + assert hw_probe.probe_gpu_device_files() == (str(dev / "kfd"), str(dev / "nvidia0")) + + +def test_no_hardware_inventory_without_linux_devices(linux_devices, monkeypatch): + dev, sysfs = linux_devices + assert hw_probe.probe_render_nodes() == () + assert hw_probe.probe_gpu_device_files() == () + _render_node(dev, sysfs, "renderD128", "0x8086") + hw_probe.probe_render_nodes.cache_clear() + monkeypatch.setattr(sys, "platform", "darwin") + assert hw_probe.probe_render_nodes() == () + assert hw_probe.probe_gpu_device_files() == () + + +@pytest.mark.parametrize("failure", [None, "permission", "driver", "timeout", "executable"]) +def test_vaapi_ffmpeg_initializes_and_caches_result(linux_devices, monkeypatch, failure): + dev, sysfs = linux_devices + device = _render_node(dev, sysfs, "renderD128", "0x8086") + monkeypatch.setattr(os, "access", lambda *_: failure != "permission") + calls = [] + + def run(argv, **kwargs): + calls.append(argv) + assert kwargs["timeout"] == 5 and kwargs["check"] + assert argv[0] == "ffmpeg" + assert argv[argv.index("-init_hw_device") + 1] == f"vaapi=va:{device}" + if failure == "driver": + raise subprocess.CalledProcessError(1, argv) + if failure == "timeout": + raise subprocess.TimeoutExpired(argv, 5) + if failure == "executable": + raise FileNotFoundError("ffmpeg") + + monkeypatch.setattr(subprocess, "run", run) + assert not hw_probe.probe_vaapi_ffmpeg("ffmpeg", str(device.with_name("absent"))) + for _ in range(2): + assert hw_probe.probe_vaapi_ffmpeg("ffmpeg", str(device)) is (failure is None) + assert len(calls) == (0 if failure == "permission" else 1) + + +def test_vaapi_ffmpeg_recovers_after_transient_permission_or_timeout(linux_devices, monkeypatch): + dev, sysfs = linux_devices + device = _render_node(dev, sysfs, "renderD128", "0x8086") + accessible = False + monkeypatch.setattr(os, "access", lambda *_: accessible) + now = [100.0] + monkeypatch.setattr(hw_probe.time, "monotonic", lambda: now[0]) + outcomes = [subprocess.TimeoutExpired(["ffmpeg"], 5), None] + + def run(argv, **_kwargs): + outcome = outcomes.pop(0) + if outcome is not None: + raise outcome + + monkeypatch.setattr(subprocess, "run", run) + # Inaccessible device is not cached: recovers immediately once accessible. + assert not hw_probe.probe_vaapi_ffmpeg("ffmpeg", str(device)) + accessible = True + # Transient FFmpeg timeout is cached for the negative TTL, then retries and succeeds. + assert not hw_probe.probe_vaapi_ffmpeg("ffmpeg", str(device)) + assert not hw_probe.probe_vaapi_ffmpeg("ffmpeg", str(device)) + assert len(outcomes) == 1 + now[0] += hw_probe._VAAPI_FAILURE_TTL_S + 1.0 + assert hw_probe.probe_vaapi_ffmpeg("ffmpeg", str(device)) + assert not outcomes + + +def test_auto_vaapi_selects_an_alternate_only_for_missing_default(linux_devices, monkeypatch): + dev, sysfs = linux_devices + first = _render_node(dev, sysfs, "renderD129", "0x8086") + second = _render_node(dev, sysfs, "renderD130", "0x1002") + default = hw_probe.DEFAULT_VAAPI_DEVICE + calls = [] + + def probe(ffmpeg, node): + calls.append((ffmpeg, node)) + return Path(node) == second + + monkeypatch.setattr(hw_probe, "probe_vaapi_ffmpeg", probe) + assert hw_probe.probe_video_decode("ffmpeg", "auto", default) == ("vaapi", str(second)) + assert calls == [("ffmpeg", str(first)), ("ffmpeg", str(second))] + calls.clear() + assert hw_probe.probe_video_decode("ffmpeg", "auto", str(first)) == (None, None) + assert hw_probe.probe_video_decode("ffmpeg", "vaapi", default) == (None, None) + assert calls == [("ffmpeg", str(first)), ("ffmpeg", default)] + Path(default).touch() + calls.clear() + assert hw_probe.probe_video_decode("ffmpeg", "auto", default) == (None, None) + assert calls == [("ffmpeg", default)] + + +def test_openvino_probe_names_and_optional_runtime(linux_devices, monkeypatch): + calls = [] + + class Core: + available_devices = ["CPU", "GPU.0", "NPU"] + + def __init__(self): + calls.append("core") + + def get_property(self, device, prop): + assert prop == "FULL_DEVICE_NAME" + if device == "NPU": + raise RuntimeError("device query failed") + return {"CPU": "Intel CPU", "GPU.0": "Intel UHD Graphics 770"}[device] + + monkeypatch.setitem(sys.modules, "openvino", SimpleNamespace(Core=Core)) + for _ in range(2): + assert ort_runtime.probe_openvino_devices() == ( + ("CPU", "Intel CPU"), ("GPU.0", "Intel UHD Graphics 770"), ("NPU", "NPU"), + ) + assert calls == ["core"] + ort_runtime.probe_openvino_devices.cache_clear() + monkeypatch.setitem(sys.modules, "openvino", None) + assert ort_runtime.probe_openvino_devices() is None + + +def test_linux_diagnostics_identify_permissions_and_drivers(linux_devices, monkeypatch): + dev, sysfs = linux_devices + blocked = _render_node(dev, sysfs, "renderD128", "0x8086") + accessible = _render_node(dev, sysfs, "renderD129", "0x8086") + monkeypatch.setattr(os, "access", lambda node, _: Path(node) != blocked) + monkeypatch.setattr(subprocess, "run", lambda *a, **kw: pytest.fail("FFmpeg driver probe must be mocked")) + monkeypatch.setattr(hw_probe, "probe_vaapi_ffmpeg", lambda _ffmpeg, _node: False) + monkeypatch.setattr("keystone.acceleration.available_providers", lambda: (OPENVINO, CPU)) + monkeypatch.setattr("keystone.acceleration.probe_openvino_devices", lambda: (("CPU", "Intel CPU"),)) + config = AccelerationConfig(provider="openvino", ffmpeg_device=str(accessible)) + report = acceleration_diagnostics(config, "ffmpeg") + assert report["hardware"]["videoDecode"] == {"ready": False, "backend": "software", "device": None} + assert report["openvinoDevices"] == [{"id": "CPU", "name": "Intel CPU"}] + hints = report["diagnostics"] + assert len(hints) == 3 + assert str(blocked) in hints[0] and f"GID {blocked.stat().st_gid}" in hints[0] + assert "intel-opencl-icd" in hints[1] and "libze-intel-gpu1" in hints[1] + assert "intel-media-va-driver" in hints[2] and "mesa-va-drivers" in hints[2] + + +@pytest.mark.parametrize("explicit_vaapi", [True, False]) +def test_doctor_hardware_is_read_only_and_informational( + linux_devices, tmp_path, monkeypatch, capsys, explicit_vaapi +): + config = tmp_path / "config.yaml" + before = ( + "controller:\n host: 192.0.2.10\n" + "device:\n enabled: false\n discovery_enabled: false\n" + "aiport:\n enabled: true\n" + "web:\n enabled: false\n" + "acceleration:\n provider: cpu\n" + f" ffmpeg_hwaccel: {'vaapi' if explicit_vaapi else 'auto'}\n" + f" ffmpeg_device: {hw_probe.DEFAULT_VAAPI_DEVICE}\n" + ) + config.write_text(before) + monkeypatch.setitem(sys.modules, "onnxruntime", SimpleNamespace(get_available_providers=lambda: [CPU])) + monkeypatch.setitem(sys.modules, "openvino", None) + monkeypatch.setattr(doctor, "_probe_process", lambda *_args: "ok") + monkeypatch.setattr(doctor, "_tcp_open", lambda *_args: True) + monkeypatch.setattr(doctor, "_listener", lambda *_args: None) + assert doctor.command(str(config)) == 0 + assert config.read_text() == before + output = capsys.readouterr().out + assert "INFO Hardware acceleration" in output + assert "INFO Video decode: software" in output + assert f"INFO ONNX Runtime providers: {CPU}" in output + assert "INFO OpenVINO devices: none detected" in output + assert ("WARN No /dev/dri render nodes found" in output) is explicit_vaapi diff --git a/tests/test_low_ram_toggles.py b/tests/test_low_ram_toggles.py index 6fa9d48..63a39fd 100644 --- a/tests/test_low_ram_toggles.py +++ b/tests/test_low_ram_toggles.py @@ -429,6 +429,7 @@ async def test_analyzer_loop_uses_configured_width(tmp_path: Path, monkeypatch: cfg = Config(state_dir=tmp_path / "state") cfg.device.advertise_ip = "127.0.0.1" cfg.aiport.enabled = True + cfg.acceleration.ffmpeg_hwaccel = "none" cfg.aiport.analyze_max_width = 416 cfg.resolve_defaults() diff --git a/tests/test_ort_runtime.py b/tests/test_ort_runtime.py index 5545ff2..6ca34aa 100644 --- a/tests/test_ort_runtime.py +++ b/tests/test_ort_runtime.py @@ -15,15 +15,16 @@ import numpy as np import pytest +from aiohttp.test_utils import TestClient, TestServer from PIL import Image import keystone.aiport as aiport_mod +import keystone.hw_probe as hw_probe import keystone.ort_runtime as ort_runtime from keystone.aiport import ( AiPortService, PairedCameraState, build_analyzer_ffmpeg_args, - probe_vaapi_device, ) from keystone.aiport_detector import SmartDetectTracker, SnapshotRingBuffer, YoloxDetector from keystone.app import KeystoneRuntime @@ -53,9 +54,11 @@ create_onnx_session, extract_openvino_device, openvino_available, + probe_vaapi_device, probe_videotoolbox, ) from keystone.stt import WhisperOnnxTranscriber, whisper_model_files +from keystone.web_ui import create_status_app class _FakeOrtEnv: @@ -148,6 +151,14 @@ def _install_fake_ort(monkeypatch: pytest.MonkeyPatch, **kwargs: Any) -> _FakeOr return env +@pytest.fixture(autouse=True) +def _isolate_openvino_probe(monkeypatch): + monkeypatch.setitem(sys.modules, "openvino", None) + ort_runtime.probe_openvino_devices.cache_clear() + yield + ort_runtime.probe_openvino_devices.cache_clear() + + def _make_jpeg(size: tuple[int, int] = (64, 48), color: tuple[int, int, int] = (40, 120, 200)) -> bytes: buf = BytesIO() Image.new("RGB", size, color).save(buf, format="JPEG") @@ -166,7 +177,8 @@ def test_acceleration_config_defaults_and_env(tmp_path: Path, monkeypatch: pytes assert cfg.acceleration.openvino_cache_dir == str(tmp_path.resolve() / "ov_cache") assert cfg.acceleration.openvino_precision == "FP16" assert cfg.acceleration.openvino_gpu_large_allocations is True - assert cfg.acceleration.ffmpeg_hwaccel == "none" + assert cfg.acceleration.ffmpeg_hwaccel == "auto" + assert ort_runtime.normalize_ffmpeg_hwaccel("") == "auto" assert cfg.acceleration.ffmpeg_device == "/dev/dri/renderD128" yml = tmp_path / "cfg.yaml" @@ -537,6 +549,92 @@ def test_create_onnx_session_silent_cpu_fallback_label( assert label == CPU_EP +@pytest.mark.parametrize( + ("spec", "devices", "target", "fell_back"), + [ + ("AUTO:GPU,CPU", ["CPU"], "CPU", True), + ("AUTO:NPU,GPU,CPU", ["CPU"], "CPU", True), + ("AUTO", ["CPU"], "CPU", True), + ("CPU", ["CPU"], "CPU", False), + ("GPU", ["CPU"], None, True), + ("NPU", ["CPU", "GPU"], None, True), + ("GPU", ["CPU", "GPU.0"], "GPU", False), + ("GPU.1", ["CPU", "GPU.0"], None, True), + ("NPU", ["CPU", "NPU"], "NPU", False), + ("AUTO:GPU,CPU", ["CPU", "GPU"], "AUTO:GPU,CPU", False), + ("AUTO:NPU,GPU,CPU", ["CPU", "NPU"], "AUTO:NPU,CPU", False), + ("AUTO:NPU,GPU", ["CPU", "GPU"], "GPU", False), + ], +) +def test_openvino_device_resolution(monkeypatch, spec, devices, target, fell_back): + env = _install_fake_ort(monkeypatch) + monkeypatch.setitem(sys.modules, "openvino", types.SimpleNamespace(Core=lambda: types.SimpleNamespace( + available_devices=devices, get_property=lambda device, _: device, + ))) + session, provider = create_onnx_session( + "model.onnx", acceleration=AccelerationConfig(provider="openvino", openvino_device=spec), + ) + assert session.requested_provider == f"{OPENVINO_EP}({spec})" + assert session.fell_back == fell_back + assert bool(session.fallback_reason) == fell_back + if target is None: + assert provider == CPU_EP + assert env.calls[0]["providers"] == [CPU_EP] + else: + assert provider == f"{OPENVINO_EP}({target})" + options = env.calls[0]["provider_options"][0] + assert options["device_type"] == target + if target == "CPU": + assert "load_config" not in options and "precision" not in options + + +def test_openvino_ort_runtime_cpu_switch_is_reported(monkeypatch): + env = _install_fake_ort(monkeypatch) + session, provider = create_onnx_session("model.onnx", label="test:ov-runtime-switch") + assert provider.startswith(OPENVINO_EP) + + def run_on_cpu(*_args): + session.wrapped.get_providers = lambda: [CPU_EP] + return [np.array([42])] + + monkeypatch.setattr(session.wrapped, "run", run_on_cpu) + assert session.run(None, {})[0].item() == 42 + report = ort_runtime.inference_health()[session.label] + assert report["provider"] == CPU_EP and report["fellBack"] + assert report["requestedProvider"] == provider + assert "switched to CPU during inference" in report["fallbackReason"] + assert len(env.calls) == 1 + + +def test_clip_embedder_openvino_device_clears_after_runtime_cpu_fallback(monkeypatch, tmp_path): + from keystone.config import EmbeddingsConfig + from keystone.embedder import ClipOnnxEmbedder + + env = _install_fake_ort(monkeypatch) + emb = ClipOnnxEmbedder( + EmbeddingsConfig(model_dir=str(tmp_path)), + acceleration=AccelerationConfig(provider="openvino", openvino_device="GPU"), + ) + session, provider = create_onnx_session( + "vision.onnx", + acceleration=emb.acceleration, + label="clip:vision-fallback-status", + ) + assert provider == f"{OPENVINO_EP}(GPU)" + emb._vision_sess = session + assert emb.status()["openvinoDevice"] == "GPU" + + def run_on_cpu(*_args): + session.wrapped.get_providers = lambda: [CPU_EP] + return [np.ones((1, 768), dtype=np.float32)] + + monkeypatch.setattr(session.wrapped, "run", run_on_cpu) + session.run(None, {}) + assert emb.status()["provider"] == CPU_EP + assert emb.status()["openvinoDevice"] is None + assert len(env.calls) == 1 + + # --------------------------------------------------------------------------- # Subsystem wiring: CLIP, YOLOX, Face, LPR, Enhancer, Whisper STT, App status # --------------------------------------------------------------------------- @@ -832,10 +930,18 @@ def get_outputs(self) -> list[Any]: assert lpr.status()["ocrProvider"] == (CPU_EP if ep == MIGRAPHX_EP else expected) -def test_runtime_status_includes_acceleration_report( +async def test_runtime_status_includes_acceleration_report( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ): - _install_fake_ort(monkeypatch, available_providers=[OPENVINO_EP, CPU_EP]) + _install_fake_ort(monkeypatch, available_providers=[OPENVINO_EP, CUDA_EP, CPU_EP]) + monkeypatch.setitem(sys.modules, "openvino", types.SimpleNamespace(Core=lambda: types.SimpleNamespace( + available_devices=["CPU"], get_property=lambda *_: "Intel CPU", + ))) + monkeypatch.setattr(sys, "platform", "linux") + node = hw_probe.RenderNode("/dev/dri/renderD129", True, 104, "0x8086", "0x4680") + monkeypatch.setattr("keystone.acceleration.probe_render_nodes", lambda: (node,)) + monkeypatch.setattr("keystone.acceleration.probe_gpu_device_files", lambda: ()) + monkeypatch.setattr("keystone.acceleration.probe_video_decode", lambda *_: ("vaapi", node.path)) cfg = Config(state_dir=tmp_path) cfg.device.advertise_ip = "127.0.0.1" cfg.acceleration.provider = "auto" @@ -847,8 +953,26 @@ def test_runtime_status_includes_acceleration_report( cfg.enhance.enabled = True cfg.stt.enabled = True runtime = KeystoneRuntime(cfg) - status = runtime.get_status() + session, _ = create_onnx_session("clip.onnx", acceleration=cfg.acceleration, label="clip:vision") + runtime.embedder._vision_sess = session + async with TestClient(TestServer(create_status_app(runtime.get_status, list))) as client: + response = await client.get("/api/status") + assert response.status == 200 + status = await response.json() acc = status["acceleration"] + assert acc["cudaAvailable"] is True + assert acc["openvinoDevices"] == [{"id": "CPU", "name": "Intel CPU"}] + assert acc["hardware"]["videoDecode"] == {"ready": True, "backend": "vaapi", "device": node.path} + assert acc["hardware"]["renderNodes"] == [{ + "path": node.path, "accessible": True, "gid": 104, + "vendor": "Intel", "vendorId": "0x8086", "deviceId": "0x4680", + }] + assert "intel-opencl-icd" in acc["diagnostics"][0] + assert acc["activeProviders"]["embeddingsVision"] == f"{OPENVINO_EP}(CPU)" + fallback = acc["fallbacks"]["clip:vision"] + assert fallback["requestedProvider"] == f"{OPENVINO_EP}(AUTO:NPU,GPU,CPU)" + assert "no accelerator matching" in fallback["reason"] + assert status["inference"]["clip:vision"]["fellBack"] is True assert acc["provider"] == "auto" assert acc["openvinoAvailable"] is True assert acc["openvinoDevice"] == "AUTO:NPU,GPU,CPU" @@ -998,7 +1122,8 @@ async def test_aiport_vaapi_auto_probing_and_zero_frame_fallback( cfg.resolve_defaults() monkeypatch.setattr(aiport_mod.sys, "platform", "linux") - monkeypatch.setattr(aiport_mod, "probe_vaapi_device", lambda dev: dev == "/dev/dri/renderD128") + monkeypatch.setattr(hw_probe, "vaapi_candidates", lambda _mode, _device: ("/dev/dri/renderD129",)) + monkeypatch.setattr(hw_probe, "probe_vaapi_ffmpeg", lambda _ffmpeg, dev: dev == "/dev/dri/renderD129") svc = AiPortService(cfg, expected_fingerprint="0" * 64, detector=_FakeDetector()) # type: ignore[arg-type] cam = PairedCameraState(device_id="CAM_VAAPI", stream_url="rtsp://127.0.0.1/s1") cam.tracker = SmartDetectTracker(device_id="CAM_VAAPI", snapshots=SnapshotRingBuffer()) @@ -1023,6 +1148,7 @@ async def fake_exec(*args: str, **_kwargs: Any) -> _FakeProc: assert "-hwaccel" in captured_cmds[0] assert captured_cmds[0][captured_cmds[0].index("-hwaccel") + 1] == "vaapi" assert captured_cmds[0].index("-hwaccel") < captured_cmds[0].index("-i") + assert captured_cmds[0][captured_cmds[0].index("-hwaccel_device") + 1] == "/dev/dri/renderD129" assert "scale_vaapi" in captured_cmds[0][captured_cmds[0].index("-vf") + 1] assert "-hwaccel" not in captured_cmds[1] assert "scale_vaapi" not in captured_cmds[1][captured_cmds[1].index("-vf") + 1] @@ -1041,10 +1167,11 @@ async def test_aiport_vaapi_stays_disabled_when_probe_false( cfg.resolve_defaults() monkeypatch.setattr(aiport_mod.sys, "platform", "linux") - monkeypatch.setattr(aiport_mod, "probe_vaapi_device", lambda _dev: False) + monkeypatch.setattr(hw_probe, "vaapi_candidates", lambda _mode, device: (device,)) + monkeypatch.setattr(hw_probe, "probe_vaapi_ffmpeg", lambda _ffmpeg, _dev: False) svc = AiPortService(cfg, expected_fingerprint="0" * 64, detector=_FakeDetector()) # type: ignore[arg-type] cam = PairedCameraState(device_id="CAM_NO_DRI", stream_url="rtsp://127.0.0.1/s1") - assert await svc._analyzer_hwaccel(cam) is None + assert await svc._analyzer_hwaccel(cam) == (None, None) async def test_aiport_vaapi_preserved_after_successful_frames( @@ -1055,6 +1182,8 @@ async def test_aiport_vaapi_preserved_after_successful_frames( cfg.aiport.enabled = True cfg.acceleration.ffmpeg_hwaccel = "vaapi" cfg.resolve_defaults() + monkeypatch.setattr(aiport_mod.sys, "platform", "linux") + monkeypatch.setattr(hw_probe, "probe_vaapi_ffmpeg", lambda _ffmpeg, _device: True) svc = AiPortService(cfg, expected_fingerprint="0" * 64, detector=_FakeDetector()) # type: ignore[arg-type] cam = PairedCameraState(device_id="CAM_OK", stream_url="rtsp://127.0.0.1/s1") @@ -1093,6 +1222,8 @@ async def test_aiport_vaapi_exception_with_zero_frames_falls_back( cfg.aiport.enabled = True cfg.acceleration.ffmpeg_hwaccel = "vaapi" cfg.resolve_defaults() + monkeypatch.setattr(aiport_mod.sys, "platform", "linux") + monkeypatch.setattr(hw_probe, "probe_vaapi_ffmpeg", lambda _ffmpeg, _device: True) svc = AiPortService(cfg, expected_fingerprint="0" * 64, detector=_FakeDetector()) # type: ignore[arg-type] cam = PairedCameraState(device_id="CAM_EXC", stream_url="rtsp://127.0.0.1/s1") @@ -1201,6 +1332,8 @@ def enable_truncation(self, _n: int) -> None: assert emb.text_active_provider == "CPUExecutionProvider" assert emb._openvino_device is None assert "produced non-finite output" in caplog.text + assert emb._vision_sess.fell_back and emb._text_sess.fell_back + assert emb._vision_sess.requested_provider == provider @pytest.mark.parametrize( @@ -1488,7 +1621,12 @@ def run(_outputs, _feeds): assert session.run(None, {})[0].item() == 42.0 assert session.provider == CPU_EP assert len(env.calls) == (1 if failure in {"missing", "silent"} else 2) - assert ort_runtime.inference_health()[label]["provider"] == CPU_EP + report = ort_runtime.inference_health()[label] + assert report["provider"] == CPU_EP + assert session.fell_back and report["fellBack"] + assert report["requestedProvider"] == ep + assert report["fallbackReason"] + assert report["failures"] == 0 def test_videotoolbox_probe_caches_ffmpeg_capabilities(monkeypatch): @@ -1501,7 +1639,7 @@ def run(args, **kwargs): probe_videotoolbox.cache_clear() monkeypatch.setattr(ort_runtime.sys, "platform", "darwin") - monkeypatch.setattr(ort_runtime.subprocess, "run", run) + monkeypatch.setattr(hw_probe.subprocess, "run", run) try: assert probe_videotoolbox("/usr/bin/ffmpeg") assert probe_videotoolbox("/usr/bin/ffmpeg") diff --git a/tests/test_stt.py b/tests/test_stt.py index 90aed0d..78a7cbd 100644 --- a/tests/test_stt.py +++ b/tests/test_stt.py @@ -769,6 +769,9 @@ def test_openvino_int8_encoder_failure_keeps_cpu_fallback(tmp_path, monkeypatch, def test_rejected_fp16_decoder_retries_only_decoder(tmp_path, monkeypatch): from tokenizers import Tokenizer + from keystone.ort_runtime import CPU_EP, OPENVINO_EP, guard_session + + encoder = f"{OPENVINO_EP}(GPU)" t = WhisperOnnxTranscriber(SttConfig(model_dir=str(tmp_path), quantization="fp16")) (tmp_path / "generation_config.json").write_text("{}") monkeypatch.setattr(t, "_ensure_files_sync", lambda: None) @@ -776,9 +779,9 @@ def test_rejected_fp16_decoder_retries_only_decoder(tmp_path, monkeypatch): monkeypatch.setattr(Tokenizer, "from_file", lambda _: None) monkeypatch.setattr(t, "_init_vocab", lambda _: None) create = Mock(side_effect=[ - (Mock(), "OpenVINOExecutionProvider(GPU)"), + (guard_session(Mock(), label="stt:test:encoder", provider=encoder), encoder), RuntimeError("Subgraph output (logits) is an outer scope value being returned directly."), - (Mock(), "CPUExecutionProvider"), + (guard_session(Mock(), label="stt:test:decoder", provider=CPU_EP), CPU_EP), ]) monkeypatch.setattr(stt_mod, "create_onnx_session", create) t._load_sync() diff --git a/web/src/components/site-header.tsx b/web/src/components/site-header.tsx index 57b566a..0168e8d 100644 --- a/web/src/components/site-header.tsx +++ b/web/src/components/site-header.tsx @@ -126,7 +126,7 @@ function AccelerationPopover({ accel }: { accel: AccelView }) { {accel.label} - +

Inference acceleration

@@ -144,8 +144,24 @@ function AccelerationPopover({ accel }: { accel: AccelView }) { {accel.warning ?? accel.note}

)} + {(accel.devices.length > 0 || accel.videoDecode) && ( +
+ {accel.devices.length > 0 && ( +
+
Detected hardware
+
{accel.devices.join(", ")}
+
+ )} + {accel.videoDecode && ( +
+
Video decode
+
{accel.videoDecode}
+
+ )} +
+ )} {accel.models.length ? ( -
    +
      {accel.models.map((m) => (
    • )} + {accel.fallbacks.length > 0 && ( +
        + {accel.fallbacks.map(({ model, requestedProvider, reason }) => ( +
      • +

        {model} CPU fallback

        +

        {requestedProvider}. {reason}

        +
      • + ))} +
      + )} + {!!accel.diagnostics?.length && ( +
        + {accel.diagnostics.map((hint) =>
      • {hint}
      • )} +
      + )} ) diff --git a/web/src/lib/derive.test.ts b/web/src/lib/derive.test.ts index be6bb18..0b55bf8 100644 --- a/web/src/lib/derive.test.ts +++ b/web/src/lib/derive.test.ts @@ -115,7 +115,7 @@ describe("acceleration", () => { precision: "FP16", activeProviders: { embeddingsVision: "OpenVINOExecutionProvider(AUTO:GPU,CPU)" }, }, - })).toMatchObject({ label: "OpenVINO · AUTO:GPU,CPU", detail: "OpenVINO on AUTO:GPU,CPU", precision: "FP16", hardware: true }) + })).toMatchObject({ label: "OpenVINO · AUTO:GPU,CPU", detail: "OpenVINO automatic device selection (AUTO:GPU,CPU)", precision: "FP16", hardware: false }) expect(detectAcceleration({ acceleration: { provider: "auto", @@ -125,6 +125,76 @@ describe("acceleration", () => { })).toMatchObject({ label: "CPU", hardware: false }) }) + it("reports OpenVINO CPU fallback, device names, and diagnostics", () => { + const reason = "OpenVINO found CPU and no accelerator matching AUTO:GPU,CPU." + const view = detectAcceleration({ + acceleration: { + provider: "openvino", + openvinoDevice: "AUTO:GPU,CPU", + openvinoDevices: [{ id: "CPU", name: "Intel CPU" }], + diagnostics: ["Check intel-opencl-icd."], + activeProviders: { aiportDetector: "OpenVINOExecutionProvider(CPU)" }, + fallbacks: { "aiport:yolox_tiny": { requestedProvider: "OpenVINOExecutionProvider(AUTO:GPU,CPU)", reason } }, + hardware: { + renderNodes: [{ path: "/dev/dri/renderD129", gid: 104, accessible: true, vendor: "Intel", vendorId: "0x8086", deviceId: "0x4680" }], + gpuDeviceFiles: [], + videoDecode: { ready: true, backend: "vaapi", device: "/dev/dri/renderD129" }, + }, + }, + aiport: { pairedCameras: [{ hwaccelBackend: "vaapi" }] }, + }) + expect(view).toMatchObject({ + label: "OpenVINO · CPU", + hardware: false, + models: [{ provider: "OpenVINO · CPU", hardware: false }], + devices: ["Intel 0x4680"], + videoDecode: "VA-API · active on 1 camera", + fallbacks: [{ model: "aiport:yolox_tiny", requestedProvider: "OpenVINO · AUTO:GPU,CPU", reason }], + diagnostics: ["Check intel-opencl-icd."], + }) + }) + + it("shows verified OpenVINO devices and does not infer acceleration from settings", () => { + const activeProviders = { faceDetector: "OpenVINOExecutionProvider(GPU)" } + const openvinoDevices = [{ id: "GPU.0", name: "Intel UHD Graphics 770" }] + expect(detectAcceleration({ acceleration: { activeProviders, openvinoDevices } })).toMatchObject({ + devices: ["Intel UHD Graphics 770"], hardware: true, + }) + expect(detectAcceleration({ + acceleration: { + activeProviders, + openvinoDevices, + hardware: { + renderNodes: [ + { path: "/dev/dri/renderD128", accessible: true, gid: 109, vendor: "Intel", vendorId: "0x8086", deviceId: "0x4680" }, + ], + gpuDeviceFiles: [], + videoDecode: { ready: false, backend: "software", device: null }, + }, + }, + }).devices).toEqual(["Intel UHD Graphics 770"]) + expect(detectAcceleration({ + acceleration: { + activeProviders, + openvinoDevices, + hardware: { + renderNodes: [ + { path: "/dev/dri/renderD128", accessible: true, gid: 109, vendor: "Intel", vendorId: "0x8086", deviceId: "0x4680" }, + { path: "/dev/dri/renderD129", accessible: true, gid: 109, vendor: "Intel", vendorId: "0x8086", deviceId: "0x56a0" }, + ], + gpuDeviceFiles: [], + videoDecode: { ready: false, backend: "software", device: null }, + }, + }, + }).devices).toEqual(["Intel UHD Graphics 770", "Intel 0x4680", "Intel 0x56a0"]) + expect(detectAcceleration({ acceleration: { activeProviders, openvinoDevices: [] } })).toMatchObject({ + hardware: false, detail: "OpenVINO execution device unverified", + }) + expect(detectAcceleration({ + acceleration: { provider: "openvino", openvinoDevice: "GPU", activeProviders: { faceDetector: "CPUExecutionProvider" } }, + })).toMatchObject({ label: "CPU", hardware: false }) + }) + it("prefers the explicit label and lists per-model providers", () => { expect(detectAcceleration(status).label).toBe("OpenVINO · GPU") const live = detectAcceleration({ diff --git a/web/src/lib/derive.ts b/web/src/lib/derive.ts index 6b03c27..932ef6a 100644 --- a/web/src/lib/derive.ts +++ b/web/src/lib/derive.ts @@ -1,5 +1,6 @@ import { fmtBytes, fmtInt, fmtLatency, num } from "@/lib/format" import type { + AccelerationStatus, AiPortStatus, DetectorInfo, InferenceHealth, @@ -142,6 +143,7 @@ export function providerLabel(raw: unknown): string { export function providerIsHardware(raw: unknown): boolean { const s = str(raw).toLowerCase() if (!s || s === "unloaded" || s === "coreai" || s.startsWith("cpu")) return false + if (s.startsWith("openvino")) return /\((?:gpu|npu)(?:[._][\w.]+)?\)$/.test(s) return !s.includes("(cpu)") } @@ -158,6 +160,10 @@ export interface AccelView { /** Informational: recent automatic restarts after GPU losses. */ note?: string precision?: string + devices: string[] + videoDecode?: string + fallbacks: { model: string; requestedProvider: string; reason: string }[] + diagnostics?: string[] models: { key: string; label: string; provider: string; hardware: boolean; loaded: boolean }[] } @@ -184,8 +190,43 @@ const COREML_UNITS: Record = { CPUOnly: "CPU", } +function accelerationHardware(status: KeystoneStatus, accel: AccelerationStatus) { + const accelerators = accel.openvinoDevices?.filter(({ id }) => /^(?:GPU|NPU)(?:\.|$)/i.test(id)) ?? [] + const openvinoGpuCount = accelerators.filter(({ id }) => /^GPU(?:\.|$)/i.test(id)).length + const intelRenderCount = (accel.hardware?.renderNodes ?? []).filter((node) => node.vendor === "Intel").length + const suppressIntelRenderNodes = openvinoGpuCount > 0 && openvinoGpuCount >= intelRenderCount + const devices = new Set(accelerators.map(({ name }) => name)) + for (const node of accel.hardware?.renderNodes ?? []) { + if (node.vendor === "Intel" && suppressIntelRenderNodes) continue + devices.add([node.vendor, node.deviceId].filter(Boolean).join(" ") || node.path) + } + for (const path of accel.hardware?.gpuDeviceFiles ?? []) { + const vendor = path === "/dev/kfd" ? "AMD" : "NVIDIA" + if (!accel.hardware?.renderNodes.some((node) => node.vendor === vendor)) devices.add(vendor) + } + const video = accel.hardware?.videoDecode + let videoDecode + if (video?.ready) { + const backend = video.backend === "vaapi" ? "VA-API" : "VideoToolbox" + const active = status.aiport?.pairedCameras?.filter((cam) => cam.hwaccelBackend === video.backend).length ?? 0 + videoDecode = active > 0 ? `${backend} · active on ${active} ${active === 1 ? "camera" : "cameras"}` : `${backend} · available` + } else if (video) { + videoDecode = accel.ffmpegHwaccel === "none" ? "Software · hardware decode disabled" : "Software" + } + return { + devices: [...devices], + videoDecode, + fallbacks: Object.entries(accel.fallbacks ?? {}).map(([model, fallback]) => ({ + model, + requestedProvider: providerLabel(fallback.requestedProvider), + reason: fallback.reason, + })), + diagnostics: accel.diagnostics, + } +} + export function detectAcceleration(status: KeystoneStatus): AccelView { - const view = detectAccelerationBase(status) + const view = { ...detectAccelerationBase(status), ...accelerationHardware(status, status.acceleration ?? {}) } const wd = obj["gpuWatchdog"]>>( status.acceleration?.gpuWatchdog, ) @@ -217,17 +258,21 @@ export function detectAcceleration(status: KeystoneStatus): AccelView { return view } -function detectAccelerationBase(status: KeystoneStatus): AccelView { +function detectAccelerationBase(status: KeystoneStatus): Omit { const accel = obj>(status.acceleration) const emb = obj>(status.embeddings) const coremlCpuOnly = accel.coremlComputeUnits === "CPUOnly" const models = Object.entries(obj>(accel.activeProviders)).map(([key, provider]) => { const label = providerLabel(provider) + const target = /^OpenVINO · ((?:GPU|NPU)(?:[._][\w.]+)?)$/.exec(label)?.[1].split("_")[0] + const verified = !target || !accel.openvinoDevices || accel.openvinoDevices.some(({ id }) => + id === target || id.split(".")[0] === target, + ) return { key, label: MODEL_LABELS[key] ?? key, provider: label, - hardware: providerIsHardware(provider) && !(label === "CoreML" && coremlCpuOnly), + hardware: verified && providerIsHardware(provider) && !(label === "CoreML" && coremlCpuOnly), loaded: str(provider).toLowerCase() !== "unloaded", } }) @@ -246,7 +291,8 @@ function detectAccelerationBase(status: KeystoneStatus): AccelView { } } const coremlActive = models.some((m) => m.provider === "CoreML") - const openvinoActive = models.some((m) => m.provider.startsWith("OpenVINO")) + const openvinoModels = models.filter((m) => m.provider.startsWith("OpenVINO")) + const openvinoActive = openvinoModels.find((m) => m.hardware) ?? openvinoModels[0] const precision = str(coremlActive ? accel.coremlModelFormat : accel.precision) || undefined const base = { models, precision } @@ -270,9 +316,17 @@ function detectAccelerationBase(status: KeystoneStatus): AccelView { hardware: !coremlCpuOnly, } } - if (openvinoActive || lb.includes("openvino") || accel.openvino) { + if (openvinoActive) { + const label = openvinoActive.provider + const target = label.split(" · ")[1] + let detail = "OpenVINO execution device unverified" + if (target?.startsWith("AUTO")) detail = `OpenVINO automatic device selection (${target})` + if (target === "CPU" || openvinoActive.hardware) detail = `OpenVINO on ${target}` + return { ...base, label, detail, hardware: openvinoActive.hardware, precision: target === "CPU" ? undefined : precision } + } + if (!accel.activeProviders && (lb.includes("openvino") || accel.openvino)) { const d = (device || "AUTO").toUpperCase() - return { ...base, label: `OpenVINO · ${d}`, detail: `OpenVINO on ${d}`, hardware: d !== "CPU" } + return { ...base, label: `OpenVINO · ${d}`, detail: `OpenVINO on ${d}`, hardware: providerIsHardware(`OpenVINO(${d})`) } } if (models.some((m) => m.provider === "Core AI")) { return { ...base, label: "Core AI", detail: "CLIP vision encoder with GPU preference", hardware: false } @@ -290,7 +344,7 @@ function detectAccelerationBase(status: KeystoneStatus): AccelView { const lp = prov.toLowerCase() if (lp.includes("openvino")) { const d = (dev || "GPU").toUpperCase() - return { ...base, label: `OpenVINO · ${d}`, detail: `${prov} (${d})`, hardware: d !== "CPU" } + return { ...base, label: `OpenVINO · ${d}`, detail: `${prov} (${d})`, hardware: providerIsHardware(`OpenVINO(${d})`) } } if (lp.includes("cuda")) return { ...base, label: "CUDA · GPU", detail: prov, hardware: true } if (lp.includes("coreml")) return { ...base, label: "CoreML", detail: prov, hardware: true } diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts index 69ce0ee..5504b90 100644 --- a/web/src/lib/types.ts +++ b/web/src/lib/types.ts @@ -79,6 +79,11 @@ export interface EmbeddingsStatus { [key: string]: unknown } +export interface AccelerationFallback { + requestedProvider: string + reason: string +} + export interface AccelerationStatus { label?: string active?: string @@ -87,7 +92,24 @@ export interface AccelerationStatus { executionProvider?: string device?: string openvinoDevice?: string + openvinoDevices?: { id: string; name: string }[] openvino?: boolean + cudaAvailable?: boolean + ffmpegHwaccel?: string + hardware?: { + renderNodes: { + path: string + accessible: boolean + gid: number + vendor: string | null + vendorId: string | null + deviceId: string | null + }[] + gpuDeviceFiles: string[] + videoDecode: { ready: boolean; backend: "vaapi" | "videotoolbox" | "software"; device: string | null } + } + fallbacks?: Record + diagnostics?: string[] precision?: string coremlAvailable?: boolean coremlComputeUnits?: string @@ -229,6 +251,9 @@ export interface AiPortStatus { /** Run health of one ONNX model, keyed by session label (e.g. "face:scrfd_2.5g"). */ export interface InferenceHealth { provider?: string + requestedProvider?: string + fellBack?: boolean + fallbackReason?: string | null runs?: number failures?: number consecutiveFailures?: number