From fcae8250551eb652e6290cf072c3d8b7cf40f6a7 Mon Sep 17 00:00:00 2001
From: seeARMS <3957773+seeARMS@users.noreply.github.com>
Date: Thu, 3 Dec 2026 19:44:15 -0800
Subject: [PATCH 1/2] Surface Protect 7.4 Basic Understanding setting state and
update docs (#87)
UniFi Protect 7.4 folds Object Indexing, AI Summary, and Speech to Text
into the single Settings -> Intelligence -> Basic Understanding card
("Basic Object Recognition"), and gates Deep Understanding to internal
Ubiquiti accounts. On a fresh adoption, Basic Understanding renders as
On (All) because Object Indexing defaults to enabled while AI Summary
and Speech to Text still default to disabled underneath, silently
blocking Protect from dispatching speechToText jobs.
- Keep Keystone in Basic Understanding (supportDeepMode=false,
supportVlm=false, aiMode="basic", legacy dispatch) and reject
unsupported non-basic modelMode requests cleanly without clobbering
stored changeAiInferAgentSettings feature toggles.
- Track Protect-reported enableSTT and recognizeKeyFrames postVLM
booleans in ControlService, log actionable Protect 7.4+ instructions
on transition to disabled, and expose sanitized protectAiSettings /
stt.protectEnabled / vision.protectAiSummary in /api/status.
- Update the status dashboard to mark Speech to text as "Off in
Protect" (with setup guidance) when Protect reports enableSTT=false,
and show a neutral chip on Vision captions when Protect sends
postVLM=false.
- Update README, Home Assistant docs, Unraid template, and setup
wizards with Protect 7.4 Basic Understanding instructions and the
NeXT AI Summary event-player toggle.
---
README.md | 18 ++---
config.example.yaml | 2 +-
home-assistant/keystone/DOCS.md | 8 +--
scripts/install.sh | 5 ++
scripts/setup-compose.py | 5 ++
src/keystone/app.py | 18 ++++-
src/keystone/control.py | 76 +++++++++++++++++++-
src/keystone/ui/index.html | 34 ++++-----
tests/test_control.py | 118 +++++++++++++++++++++++++++++++-
unraid/keystone.xml | 4 +-
web/src/components/services.tsx | 20 ++++++
web/src/lib/derive.test.ts | 36 ++++++++++
web/src/lib/derive.ts | 34 ++++++++-
web/src/lib/types.ts | 12 ++++
14 files changed, 351 insertions(+), 39 deletions(-)
diff --git a/README.md b/README.md
index 79add61..c762302 100644
--- a/README.md
+++ b/README.md
@@ -15,7 +15,7 @@ Protect adopts Keystone in **UniFi Protect → UniFi Devices** as a virtual AI K
**Works with both UniFi and third-party cameras.** UniFi cameras with smart detections (G4 and newer) get plain-English search and event descriptions, and G4/G5 cameras also get face and license plate recognition. Third-party ONVIF cameras (Reolink, Amcrest, or Nest through Scrypted) and older UniFi cameras without smart detections pair with the optional virtual AI Port to get all of that plus Protect's smart detections.
-> Unofficial community project; not affiliated with or endorsed by Ubiquiti Inc. No vendor firmware, proprietary binaries, or vendor model weights are included. Tested on **UniFi Protect 7.3.74 and 7.4.112**.
+> Unofficial community project; not affiliated with or endorsed by Ubiquiti Inc. No vendor firmware, proprietary binaries, or vendor model weights are included. Tested on **UniFi Protect 7.3.74, 7.4.112, and 7.4.114**.

@@ -204,9 +204,9 @@ The **Home Assistant OS app** starts with Speech-to-Text, License Plate Recognit
| Feature | Default | Turn on in `config.yaml` | Turn on in UniFi Protect |
| --- | --- | --- | --- |
-| **Find Anything search** | **On** | Already enabled (`embeddings.enabled: true`) | **Settings → Intelligence → Basic Object Recognition**, plus Smart Detections on each camera |
-| **Event descriptions** | **Needs vision model** *(off if URL left blank)* | Set `vision.provider`, `vision.base_url`, and `vision.model` | **Settings → Intelligence → AI Summary** |
-| **Speech-to-Text** *(event transcripts)* | Off | `stt.enabled: true` | **Settings → Intelligence → Speech-to-Text**, plus Speech audio detection on cameras with a mic |
+| **Find Anything search** | **On** | Already enabled (`embeddings.enabled: true`) | **Settings → Intelligence → Basic Understanding** *(7.3: Basic Object Recognition)*, plus Smart Detections on each camera |
+| **Event descriptions** | **Needs vision model** *(off if URL left blank)* | Set `vision.provider`, `vision.base_url`, and `vision.model` | **Settings → Intelligence → Basic Understanding** *(7.3: AI Summary; see Protect 7.4 note below)* |
+| **Speech-to-Text** *(event transcripts)* | Off | `stt.enabled: true` | **Settings → Intelligence → Basic Understanding** *(7.3: Speech-to-Text; see Protect 7.4 note below)*, plus Speech audio detection on cameras with a mic |
| **Face recognition** | Off | `faces.enabled: true` | G4/G5 cameras: **Legacy Camera Enhancement → Face Recognition**
Paired ONVIF cameras: **Face** smart detection |
| **License plates** | Off | `lpr.enabled: true` | G4/G5 cameras: **Legacy Camera Enhancement → License Plate Recognition**
Paired ONVIF cameras: **License Plate** smart detection |
| **Enhance Face** | Off | `enhance.enabled: true` | **Enhance** button on face crops in Protect |
@@ -215,7 +215,9 @@ The **Home Assistant OS app** starts with Speech-to-Text, License Plate Recognit
After editing `config.yaml`, restart Keystone (`docker compose restart`, `systemctl restart keystone`, `sudo launchctl kickstart -k system/com.seearms.keystone` for a macOS system LaunchDaemon, `brew services restart keystone` for a Homebrew user service, or restart the Unraid container). For system LaunchDaemons, rerun `install-daemons` with your original flags if AI Port settings changed. Protect picks up newly enabled features automatically — no re-adoption needed.
-> **Tip:** Not seeing descriptions or transcripts? Open the Keystone dashboard (`:8088`). Every service card shows whether it's **Ready**, **Off / Disabled** (with the config key to turn it on), or reporting an error. Note also that **Speech-to-Text** transcribes spoken audio from camera microphones into text — Keystone does not generate spoken audio narration of descriptions.
+> **Protect 7.4+ (`Basic Understanding`):** UniFi Protect 7.4 combined **Object Indexing**, **AI Summary**, and **Speech to Text** into a single **Settings → Intelligence → Basic Understanding** (*"Basic Object Recognition"*) card — there are no separate AI Summary or Speech-to-Text toggles. On a fresh adoption, **Basic Understanding** can appear **On (All)** even though **AI Summary** and **Speech to Text** are still off underneath (Protect will not send `speechToText` jobs until Speech to Text is enabled). To turn all three on for all supported cameras, toggle **Basic Understanding** **Off**, then back **On**, and click **Apply Changes** — or switch it to **Selected Only** to reveal and toggle the individual **Object Indexing**, **Speech to Text**, and **AI Summary** icons per camera.
+>
+> **Tip:** Not seeing descriptions or transcripts? Open the Keystone dashboard (`:8088`). Every service card shows whether it's **Ready**, **Off / Disabled** (with the config key to turn it on), **Off in Protect** (when Protect itself has Speech-to-Text turned off), or reporting an error. In Protect's event player, click the **NeXT AI Summary** sparkle icon in the player toolbar to open saved event descriptions (it starts collapsed until clicked once). Note also that **Speech-to-Text** transcribes spoken audio from camera microphones into text — Keystone does not generate spoken audio narration of descriptions.
Resetting adoption ("Connected to another console" / "Reassign this device")
@@ -249,7 +251,7 @@ Pass `--target aikey` or `--target aiport` to reset only one virtual device, or
### Event descriptions (Ollama, LM Studio, oMLX, OpenAI, Anthropic)
-To turn on event descriptions, point `vision` in `config.yaml` at a vision-capable model, then turn on **AI Summary** under **Protect → Settings → Intelligence**.
+To turn on event descriptions, point `vision` in `config.yaml` at a vision-capable model, then enable **Basic Understanding** (toggle **Off → On** and **Apply Changes**, or enable the **AI Summary** icon under **Selected Only**; on Protect 7.3, enable **AI Summary**) under **Protect → Settings → Intelligence**. To read saved descriptions in Protect, open an event and click the **NeXT AI Summary** sparkle button in the player toolbar (Protect remembers it open afterward).
- **Ollama (default provider):** keep `vision.provider: ollama` and set `vision.base_url` (for example `http://192.0.2.20:11434`) and `vision.model` (default `qwen3.5:9b`, or `qwen3.5:4b` for smaller GPUs).
- **LM Studio, oMLX, llama.cpp, or vLLM:** set `provider: openai-compatible`, use the server's `/v1` base URL, and set `model` to the exact model ID it serves:
@@ -315,7 +317,7 @@ stt:
model: whisper-base # whisper-tiny | whisper-base | whisper-small
```
-Restart Keystone, then enable **Speech-to-Text** under **Protect → Settings → Intelligence** (and Speech audio detection on audio-capable cameras). Runs locally on CPU with no extra packages; cameras without a microphone return an empty transcript instead of stalling.
+Restart Keystone, then enable Speech-to-Text under **Protect → Settings → Intelligence** (on Protect 7.4+, toggle **Basic Understanding** **Off → On** and click **Apply Changes**, or switch to **Selected Only** and toggle the **Speech to Text** icon per camera; on Protect 7.3, enable **Speech-to-Text**) plus **Speech** audio detection on audio-capable cameras. Runs locally on CPU with no extra packages; cameras without a microphone return an empty transcript instead of stalling.
### License plate recognition
@@ -547,7 +549,7 @@ Reasoning models count their thinking against `max_tokens`, so a short caption b
### Architecture & protocol compatibility
-- **AI Key (`UP-AI-KEY`, `0xa5f0`)**: Advertises via Ubiquiti UDP `10001` discovery, serves `/api/info`, `/api/adopt`, and `/api/readopt` over HTTPS (`:8080`), authenticates to Protect via mTLS with pinned controller SHA-256 certificates, handles UCP4 control commands (`:7442`), and syncs rotated passwords to PostgreSQL (`unifi-protect` role) for Protect 7.3+ `isSearchHost` vector search.
+- **AI Key (`UP-AI-KEY`, `0xa5f0`)**: Advertises via Ubiquiti UDP `10001` discovery, serves `/api/info`, `/api/adopt`, and `/api/readopt` over HTTPS (`:8080`), authenticates to Protect via mTLS with pinned controller SHA-256 certificates, handles UCP4 control commands (`:7442`), and syncs rotated passwords to PostgreSQL (`unifi-protect` role) for Protect 7.3+ `isSearchHost` vector search. Keystone intentionally stays in **Basic Understanding** (`supportDeepMode: false`, `supportVlm: false`, `aiMode: "basic"`, legacy dispatch without `aiSched`): Protect 7.4+'s **Deep Understanding** mode is restricted to internal Ubiquiti accounts and replaces `recognizeKeyFrames`/CLIP search with a separate session-describe pipeline.
- **Vision pipeline**: Samples 3 chronological frames (`±1.0s` around each event's `keyMoment`, widened to `±2.0s` on clips `≥ 15s`, at `960px`) for motion-aware VLM captions and maps outputs plus class-filtered attributes onto Protect's 5,375-tag `ramTags` vocabulary. Optionally injects per-camera spatial hints (`cameras:` in `config.yaml`) and multi-view, episode-chained chronological cross-camera sightings (`vision.cross_camera_context_seconds`, default `90s`, strong similarity `0.62`, cross-view floor `0.35`, up to `3` sightings) so distant, rear, indoor, or IR angles benefit from earlier clearer cameras across vehicles, people, animals, and deliveries. Interactive on-demand summaries (`RequestAI` → `:7968/on_demand_inference`) narrow long exports to a 4-second window and run a fast 1-frame `640px` pass to stay inside Protect's UI timeout.
- **Find Anything (`:7443`)**: Runs local **CLIP ViT-L/14** (768-dim ONNX) for object crop indexing, `NL_PARSE` text queries (with relative time-window parsing), `IMAGE_SEARCH`, and optional CLIP reverification. Protect 7.4's release notes say detection confidence verification has been removed, so expect reverification jobs only from Protect 7.3.
- **Speech-to-Text (`speechToText`, featureFlags `supportTts` & `supportStt`)**: Fetches Protect's audio-only MP4 export (`skipVideo=true`, retrying transient `404`s), decodes 16 kHz mono audio with FFmpeg, transcribes with Whisper (log-mel + timestamp-constrained greedy decoding on onnxruntime, with no-speech and leading-silence gating), and POSTs `{camera, event, stt: [{startMs, endMs, text}]}` to `/internal/aiprocessors/speech-to-text`. Segment timestamps use Unix epoch milliseconds for synchronized event playback; queued/active jobs are reported to Protect as `UI_AUTO_STT`.
diff --git a/config.example.yaml b/config.example.yaml
index 873fd59..d5c2ce1 100644
--- a/config.example.yaml
+++ b/config.example.yaml
@@ -196,7 +196,7 @@ enhance:
jpeg_quality: 92
idle_unload_seconds: 300 # Free the model's RAM after 5 idle minutes (0 = keep resident)
-# Native Protect Speech-to-Text (event transcripts; Protect featureFlag "supportTts").
+# Native Protect Speech-to-Text (event transcripts; Protect featureFlags "supportTts" & "supportStt").
# Off by default. The onnx backend runs OpenAI Whisper locally on CPU with the existing
# onnxruntime/numpy/tokenizers deps; weights are pinned + SHA-256 verified on first use.
stt:
diff --git a/home-assistant/keystone/DOCS.md b/home-assistant/keystone/DOCS.md
index a32d5de..3502fa8 100644
--- a/home-assistant/keystone/DOCS.md
+++ b/home-assistant/keystone/DOCS.md
@@ -12,7 +12,7 @@
1. In Home Assistant, go to **Settings → Apps → Install app → ⋮ → Repositories** and add `https://github.com/seeARMS/keystone`.
2. Select **Keystone → Install**. Open **Configuration**, enter the Protect console's IPv4 address, and review the [feature switches](#feature-switches) before starting. Keep the vision URL blank with the default Ollama provider to skip event descriptions. Save your changes.
3. Start Keystone from **Info** and watch the **Log** tab for startup and model downloads. In **UniFi Protect → UniFi Devices**, find the **AI Key** at your Home Assistant OS host's IP and select **Adopt**. Initial credentials are `ubnt` / `ubnt` if prompted. Protect rotates them during adoption.
-4. In Protect, enable **Settings → Intelligence → Basic Object Recognition** and Smart Detections on the camera you want to search. Trigger a new smart detection, then search for it with **Find Anything**. The first query may take longer while the text model loads. Older events are outside this initial test because historical indexing is off by default.
+4. In Protect, enable **Settings → Intelligence → Basic Understanding** *(Protect 7.3: Basic Object Recognition)* and Smart Detections on the camera you want to search. On Protect 7.4+, **Basic Understanding** bundles Object Indexing, AI Summary, and Speech to Text in one card and can appear **On (All)** right after adoption while AI Summary and Speech to Text are still off underneath — toggle **Basic Understanding** **Off**, then back **On**, and click **Apply Changes** (or switch to **Selected Only** to pick features per camera). Trigger a new smart detection, then search for it with **Find Anything**. The first query may take longer while the text model loads. Older events are outside this initial test because historical indexing is off by default.
If you use Home Assistant Container, run Keystone separately using [Docker Compose](https://github.com/seeARMS/keystone#docker-compose).
@@ -26,7 +26,7 @@ If you use Home Assistant Container, run Keystone separately using [Docker Compo
| `vision_model` | A vision-capable model served by the endpoint. Ollama defaults to `qwen3.5:9b`. Enter the exact model ID for other providers when enabling descriptions. |
| `vision_api_key` | Required for OpenAI and Anthropic. For an authenticated local endpoint, choose `openai-compatible` and enter its bearer token. |
-Run or host the vision model separately and ensure its endpoint is reachable from Home Assistant OS. After saving a vision configuration and restarting Keystone, enable **AI Summary** in **Protect → Settings → Intelligence**. Search remains local regardless of which vision provider you choose. Event descriptions send selected frames to the configured vision endpoint.
+Run or host the vision model separately and ensure its endpoint is reachable from Home Assistant OS. After saving a vision configuration and restarting Keystone, enable **AI Summary** in **Protect → Settings → Intelligence** (on Protect 7.4+, toggle **Basic Understanding** **Off → On** and click **Apply Changes**, or turn on the **AI Summary** icon under **Selected Only**). Open an event and click the **NeXT AI Summary** icon in the player toolbar to view saved descriptions. Search remains local regardless of which vision provider you choose. Event descriptions send selected frames to the configured vision endpoint.
### Feature switches
@@ -34,7 +34,7 @@ All five switches start on. Change them on Keystone's **Configuration** tab, sel
| Switch | Protect setup |
| --- | --- |
-| **Speech-to-Text** (`speech_to_text`) | Enable **Settings → Intelligence → Speech-to-Text** and turn on **Speech** audio detection for cameras with microphones. |
+| **Speech-to-Text** (`speech_to_text`) | Enable **Settings → Intelligence → Basic Understanding** *(7.4+: toggle Off → On and Apply Changes, or enable the **Speech to Text** icon under **Selected Only**; 7.3: Speech-to-Text)* and turn on **Speech** audio detection for cameras with microphones. |
| **License Plate Recognition** (`license_plate_recognition`) | On G4/G5 cameras, enable **Legacy Camera Enhancement → License Plate Recognition**. For cameras paired to the AI Port, enable **License Plate** smart detection. |
| **Enhance Face** (`enhance_face`) | Select **Enhance** on a face crop in Protect. |
| **Face Recognition** (`face_recognition`) | On G4/G5 cameras, enable **Legacy Camera Enhancement → Face Recognition**. For cameras paired to the AI Port, enable **Face** smart detection. |
@@ -61,7 +61,7 @@ Home Assistant's usual web port is `8123/TCP`. If a reverse proxy or another ser
- **The app fails to start:** Open its **Log** tab and check the configuration error or the specific port that failed to bind. A PostgreSQL app listening on `5432/TCP` or a reverse proxy on `8080/TCP` can prevent startup.
- **Protect cannot discover Keystone:** Confirm both hosts share a broadcast domain and UDP `10001` is available. For a routed setup, use Protect's IP adoption with the Home Assistant OS host's IP and allow the connections above. Preserve the Protect console's real source IP for PostgreSQL access.
-- **Protect adopts Keystone but Find Anything returns no results:** Check the app log for model download or search connection errors. Confirm the console can reach `5432/TCP`, Basic Object Recognition is enabled, and the camera has generated a new smart detection since adoption.
+- **Protect adopts Keystone but Find Anything returns no results:** Check the app log for model download or search connection errors. Confirm the console can reach `5432/TCP`, Basic Understanding (Basic Object Recognition) is enabled, and the camera has generated a new smart detection since adoption.
## Update, back up and verify persistence
diff --git a/scripts/install.sh b/scripts/install.sh
index 10a436b..99e0971 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -597,6 +597,11 @@ if c.aiport.enabled:
step = 2
if intel:
print(f" {step}. Open Settings → Intelligence and enable: {', '.join(intel)}.")
+ if vision_on or c.stt.enabled:
+ print(
+ " (On Protect 7.4+, these live inside Basic Understanding — toggle it Off then On "
+ "and click Apply Changes, or switch to Selected Only to pick features per camera.)"
+ )
if not vision_on:
print(f" (Event descriptions are disabled until you configure vision.* in {config_path} and enable AI Summary.)")
step += 1
diff --git a/scripts/setup-compose.py b/scripts/setup-compose.py
index 12a6993..fe4e9e9 100644
--- a/scripts/setup-compose.py
+++ b/scripts/setup-compose.py
@@ -563,6 +563,11 @@ def print_summary(
if features.get("aiport"):
print(" Also adopt the AI Port and pair your ONVIF / legacy UniFi cameras to it.")
print(f" 3. In Protect → Settings → Intelligence, enable: {', '.join(intel)}.")
+ if vision_on or features.get("stt"):
+ print(
+ " (On Protect 7.4+, these live inside Basic Understanding — toggle it Off then On "
+ "and click Apply Changes, or switch to Selected Only to pick features per camera.)"
+ )
if not vision_on:
print(
" (Event descriptions are disabled until you configure vision.* in config.yaml and enable AI Summary.)"
diff --git a/src/keystone/app.py b/src/keystone/app.py
index ec7addd..05979b0 100644
--- a/src/keystone/app.py
+++ b/src/keystone/app.py
@@ -113,6 +113,7 @@ def get_status(self) -> dict[str, Any]:
ai_key = self.config.device.enabled
console_info = (self.store.state.get("console_info") or {}) if self.store else {}
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 {}
return {
"app": APP_NAME,
"version": APP_VERSION,
@@ -130,6 +131,7 @@ def get_status(self) -> dict[str, Any]:
"lastError": self.control.last_error if self.control else None,
"consoleName": console_info.get("consoleName"),
"protectVersion": console_info.get("protectVersion"),
+ "protectAiSettings": protect_ai,
"commands": dict(self.control.command_counts) if self.control else {},
},
"search": {
@@ -152,6 +154,11 @@ def get_status(self) -> dict[str, Any]:
"baseUrl": self.config.vision.base_url,
"frameLayout": self.config.vision.frame_layout,
"maxFrames": self.config.vision.max_frames,
+ **(
+ {"protectAiSummary": protect_ai["aiSummary"]}
+ if "aiSummary" in protect_ai
+ else {}
+ ),
}
if ai_key
else {
@@ -169,7 +176,7 @@ def get_status(self) -> dict[str, Any]:
"inference": inference_health(),
"faces": self.faces.status() if self.faces else {"enabled": False},
"enhance": self.enhancer.status() if self.enhancer else {"enabled": False},
- "stt": self._stt_status(),
+ "stt": self._stt_status(protect_ai),
"lpr": self._lpr_status(),
"embeddings": (
{
@@ -260,13 +267,20 @@ def _lpr_status(self) -> dict[str, Any]:
"aiKeyUploads": worker.get("lprUploads", 0),
}
- def _stt_status(self) -> dict[str, Any]:
+ def _stt_status(self, protect_ai: dict[str, bool] | None = None) -> dict[str, Any]:
if self.stt is None:
return {"enabled": False}
worker = self.worker.status() if self.worker else {}
+ if protect_ai is None:
+ protect_ai = self.control.protect_ai_settings if self.control else {}
return {
"enabled": True,
**self.stt.status(),
+ **(
+ {"protectEnabled": protect_ai["stt"]}
+ if "stt" in protect_ai
+ else {}
+ ),
"queued": worker.get("sttQueued", 0),
"active": worker.get("sttActive", 0),
"completed": worker.get("sttCompleted", 0),
diff --git a/src/keystone/control.py b/src/keystone/control.py
index c9f4b6b..1d770d0 100644
--- a/src/keystone/control.py
+++ b/src/keystone/control.py
@@ -55,6 +55,14 @@
"UI_TASK_NUM",
)
+_PROTECT_AI_SETTING_KEYS: tuple[tuple[str, str], ...] = (
+ ("enableRAM", "ram"),
+ ("enableSTT", "stt"),
+ ("enableFaceRecognize", "faceRecognition"),
+ ("enableLprRecognize", "lpr"),
+ ("enableFaceEnhance", "faceEnhance"),
+)
+
# Protect 7.3.74 runRetroactiveProcessing dispatches min(remaining, 50 * aiprocessors -
# UI_TASK_NUM) multipleImages jobs per batch and waits 10s whenever that budget is <= 0.
PROTECT_RETRO_BUDGET_PER_PROCESSOR = 50
@@ -172,6 +180,8 @@ def __init__(
self.last_error: str | None = None
self.connections = 0
self.command_counts: dict[str, int] = {}
+ self._last_protect_stt_enabled: bool | None = None
+ self._last_post_vlm: bool | None = None
@property
def control_url(self) -> str:
@@ -204,8 +214,29 @@ def retroactive_enabled(self) -> bool:
emb = self.config.embeddings
return bool(emb.enabled and emb.backend.lower() == "clip" and emb.retroactive_processing)
+ @property
+ def _vision_enabled(self) -> bool:
+ return self.config.vision.provider.lower() != "disabled" and bool(self.config.vision.model)
+
+ @property
+ def protect_ai_settings(self) -> dict[str, bool]:
+ """Sanitized snapshot of Protect-side AI feature toggles reported to this AI Key."""
+ if not self.store.adopted:
+ return {}
+ out: dict[str, bool] = {}
+ state = getattr(self.store, "state", None)
+ raw = state.get("changeAiInferAgentSettings") if isinstance(state, dict) else None
+ if isinstance(raw, dict):
+ for protect_key, out_key in _PROTECT_AI_SETTING_KEYS:
+ val = raw.get(protect_key)
+ if isinstance(val, bool):
+ out[out_key] = val
+ if self._last_post_vlm is not None:
+ out["aiSummary"] = self._last_post_vlm
+ return out
+
def get_info(self) -> dict[str, Any]:
- vision_on = self.config.vision.provider.lower() != "disabled" and bool(self.config.vision.model)
+ vision_on = self._vision_enabled
emb_on = self.config.embeddings.enabled
clip_on = emb_on and self.config.embeddings.backend.lower() == "clip"
flags: dict[str, Any] = {
@@ -233,6 +264,9 @@ def get_info(self) -> dict[str, Any]:
"supportTts": {"enabled": bool(self.config.stt.enabled), "version": "v1"},
"supportStt": {"enabled": bool(self.config.stt.enabled), "version": "v1"},
"supportPersonReId": {"enabled": clip_on, "version": "v1"},
+ # Stay in Basic Understanding (legacy dispatch, aiSched omitted/0): Protect 7.4+ gates
+ # Deep Understanding to internal Ubiquiti accounts and deep mode replaces
+ # recognizeKeyFrames/CLIP search with a separate dedup/describe/embed pipeline.
"supportDeepMode": False,
"supportVlm": False,
"aiMode": "basic",
@@ -714,7 +748,32 @@ async def _dispatch_command(self, action: str, body: dict[str, Any]) -> dict[str
if action in {"firmwareState", "sshService"}:
return {}
- if action in {"updateLcmSettings", "changeAiInferAgentSettings", "networkStatus"}:
+ if action == "changeAiInferAgentSettings":
+ if "modelMode" in body and body.get("modelMode") != "basic":
+ raise CommandError(95, f"Unsupported AI mode: {body.get('modelMode')!r}")
+ async with self._lock:
+ existing = self.store.state.get(action)
+ merged = dict(existing) if isinstance(existing, dict) else {}
+ merged.update(body)
+ self.store.state[action] = merged
+ self.store.save()
+ enable_stt = body.get("enableSTT")
+ if isinstance(enable_stt, bool):
+ if self.config.stt.enabled and not enable_stt and self._last_protect_stt_enabled is not False:
+ LOG.warning(
+ "Protect reports Speech-to-Text disabled (enableSTT=false) while "
+ "stt.enabled=true; Protect will not dispatch speechToText tasks until "
+ "enabled in Protect → Settings → Intelligence (on Protect 7.4+, Basic "
+ "Understanding can show On/All while Speech to Text is still off "
+ "underneath — toggle Basic Understanding Off then On and click Apply "
+ "Changes, or switch it to Selected Only to enable Speech to Text per camera)"
+ )
+ elif self.config.stt.enabled and enable_stt and self._last_protect_stt_enabled is False:
+ LOG.info("Protect enabled Speech-to-Text (enableSTT=true)")
+ self._last_protect_stt_enabled = enable_stt
+ return body
+
+ if action in {"updateLcmSettings", "networkStatus"}:
async with self._lock:
self.store.state[action] = body
self.store.save()
@@ -763,6 +822,19 @@ async def _dispatch_command(self, action: str, body: dict[str, Any]) -> dict[str
return body
if action == "recognizeKeyFrames":
+ post_vlm = body.get("postVLM")
+ if isinstance(post_vlm, bool):
+ if self._vision_enabled and not post_vlm and self._last_post_vlm is not False:
+ LOG.info(
+ "Protect sent recognizeKeyFrames with postVLM=false (AI Summary is off "
+ "in Protect); Keystone still captions and uploads descriptions (click "
+ "the NeXT AI Summary icon in Protect's event player to view them). On "
+ "Protect 7.4+, toggle Settings → Intelligence → Basic Understanding Off "
+ "then On and click Apply Changes (or use Selected Only) to enable AI Summary"
+ )
+ elif self._vision_enabled and post_vlm and self._last_post_vlm is False:
+ LOG.info("Protect enabled AI Summary on recognizeKeyFrames (postVLM=true)")
+ self._last_post_vlm = post_vlm
return await self.job_handler({"command": "recognizeKeyFrames", "payload": body})
if action == "speechToText":
diff --git a/src/keystone/ui/index.html b/src/keystone/ui/index.html
index ba0700e..3f21305 100644
--- a/src/keystone/ui/index.html
+++ b/src/keystone/ui/index.html
@@ -22,20 +22,20 @@
if (dark) document.documentElement.classList.add("dark")
})()
-
+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,R.jsx)(z.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]=yr({prop:n,onChange:i,defaultProp:r??!1,caller:hf});return(0,R.jsx)(z.button,{type:`button`,"aria-pressed":o,"data-state":o?`on`:`off`,"data-disabled":e.disabled?``:void 0,...a,ref:t,onClick:B(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]=Vn(yf,[Bl]),Cf=Bl(),wf=_.forwardRef(vf(function(e,t){let{type:n,...r}=e;if(n===bf.Single)return(0,R.jsx)(Df,{role:`radiogroup`,...r,ref:t});if(n===bf.Multiple)return(0,R.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]=yr({prop:n,defaultProp:r??``,onChange:i,caller:yf});return(0,R.jsx)(Tf,{scope:e.__scopeToggleGroup,type:bf.Single,value:_.useMemo(()=>o?[o]:[],[o]),onItemActivate:s,onItemDeactivate:_.useCallback(()=>s(``),[s]),children:(0,R.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]=yr({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,R.jsx)(Tf,{scope:e.__scopeToggleGroup,type:bf.Multiple,value:o,onItemActivate:c,onItemDeactivate:l,children:(0,R.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=ni(o),d={dir:u,...c};return(0,R.jsx)(kf,{scope:n,rovingFocus:i,disabled:r,children:i?(0,R.jsx)(Gl,{asChild:!0,...l,orientation:a,dir:u,loop:s,children:(0,R.jsx)(z.div,{...d,ref:t})}):(0,R.jsx)(z.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,R.jsx)(Jl,{asChild:!0,...i,focusable:!o,active:a,ref:c,children:(0,R.jsx)(Pf,{...s,ref:t})}):(0,R.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,R.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]=Vn(`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,R.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=Lr(),h=_.useRef(0),g=o??c.disableHoverableContent,v=s??c.delayDuration,y=_.useRef(!1),[b,x]=yr({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,R.jsx)(ul,{...l,children:(0,R.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=L(t,_.useRef(null),a.onTriggerChange),l=_.useRef(!1),u=_.useRef(!1),d=_.useCallback(()=>l.current=!1,[]);return _.useEffect(()=>()=>document.removeEventListener(`pointerup`,d),[d]),(0,R.jsx)(fl,{asChild:!0,...s,children:(0,R.jsx)(z.button,{"aria-describedby":a.open?pp(r,a.contentId):r,"data-state":a.stateAttribute,...i,ref:c,onPointerMove:B(e.onPointerMove,e=>{e.pointerType!==`touch`&&!u.current&&!o.isPointerInTransitRef.current&&(a.onTriggerEnter(),u.current=!0)}),onPointerLeave:B(e.onPointerLeave,()=>{a.onTriggerLeave(),u.current=!1}),onPointerDown:B(e.onPointerDown,()=>{a.open&&a.onClose(),l.current=!0,document.addEventListener(`pointerup`,d,{once:!0})}),onFocus:B(e.onFocus,()=>{l.current||a.onOpen()}),onBlur:B(e.onBlur,a.onClose),onClick:B(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,R.jsx)(Qf,{scope:t,forceMount:n,children:(0,R.jsx)(Dr,{present:n||a.open,children:(0,R.jsx)(Ui,{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,R.jsx)(Dr,{present:r||o.open,children:o.disableHoverableContent?(0,R.jsx)(ap,{side:i,...a,ref:t}):(0,R.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=L(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,R.jsx)(ap,{...e,ref:a})},`TooltipContentHoverable`)),ip=hn(`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=L(t,p);Ai(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 Un(()=>(h(a),()=>{h(void 0)}),[a,h]),(0,R.jsx)(mi,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:e=>e.preventDefault(),onDismiss:d,children:(0,R.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,R.jsx)(ip,{children:r}),i?(0,R.jsx)(Ln,{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,R.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=an(`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?pn:`button`;return(0,R.jsx)(a,{"data-slot":`button`,"data-variant":t,"data-size":n,className:I(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,R.jsx)(`span`,{className:`text-muted-foreground/70`,children:`—`});if(typeof e==`boolean`)return(0,R.jsx)(`span`,{className:e?`text-success`:`text-muted-foreground`,children:e?`true`:`false`});if(typeof e==`number`)return(0,R.jsx)(`span`,{className:`tabular`,children:Number.isInteger(e)?e.toLocaleString(`en-US`):e});if(Array.isArray(e))return e.length?(0,R.jsx)(`span`,{className:`[overflow-wrap:anywhere]`,children:e.map(e=>typeof e==`object`?JSON.stringify(e):String(e)).join(`, `)}):(0,R.jsx)(`span`,{className:`text-muted-foreground/70`,children:`[]`});if(typeof e==`object`){let t=JSON.stringify(e);return(0,R.jsx)(`span`,{className:I(`[overflow-wrap:anywhere]`,t===`{}`&&`text-muted-foreground/70`),children:t})}return(0,R.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,R.jsx)(`dl`,{className:I(`text-sm`,t>0&&`ml-1 border-l pl-3`),children:n.map(([e,n])=>gp(n)&&Object.keys(n).length?(0,R.jsxs)(`div`,{className:`py-1.5`,children:[(0,R.jsx)(`dt`,{className:`mb-1 text-[13px] font-medium text-foreground`,children:_p(e)}),(0,R.jsx)(`dd`,{children:(0,R.jsx)(yp,{data:n,depth:t+1})})]},e):(0,R.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 border-b border-dashed py-1.5 last:border-b-0`,children:[(0,R.jsx)(`dt`,{className:`shrink-0 text-muted-foreground`,title:e,children:_p(e)}),(0,R.jsx)(`dd`,{className:`min-w-0 text-right font-mono text-xs`,children:(0,R.jsx)(vp,{value:n})})]},e))}):(0,R.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,R.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,R.jsx)(le,{className:`text-success`}):(0,R.jsx)(ye,{}),i?`Copied`:t]})}function xp({data:e}){return(0,R.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,R.jsx)(Wf,{"data-slot":`tooltip-provider`,delayDuration:e,...t})}function wp({...e}){return(0,R.jsx)(Jf,{"data-slot":`tooltip`,...e})}function Tp({...e}){return(0,R.jsx)(Xf,{"data-slot":`tooltip-trigger`,...e})}function Ep({className:e,sideOffset:t=0,children:n,...r}){return(0,R.jsx)(ep,{children:(0,R.jsxs)(np,{"data-slot":`tooltip-content`,sideOffset:t,className:I(`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,R.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,R.jsxs)(`span`,{className:I(`relative inline-flex size-1.5 shrink-0`,n),"aria-hidden":`true`,children:[t&&(0,R.jsx)(`span`,{className:I(`absolute inset-0 rounded-full animate-ping-slow`,kp[e])}),(0,R.jsx)(`span`,{className:I(`relative inline-flex size-full rounded-full`,kp[e])})]})}function jp({tone:e,children:t,pulse:n,className:r}){return(0,R.jsxs)(`span`,{className:I(`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,R.jsx)(Ap,{tone:e,pulse:n}),t]})}function Mp({tone:e=`neutral`,mono:t=!1,className:n,children:r,title:i}){let a=(0,R.jsx)(`span`,{className:I(`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,R.jsxs)(wp,{children:[(0,R.jsx)(Tp,{asChild:!0,children:a}),(0,R.jsx)(Ep,{className:`max-w-72`,children:i})]}):a}function Np({chips:e,className:t}){return e.length?(0,R.jsx)(`div`,{className:I(`flex flex-wrap gap-1.5`,t),children:e.map(e=>(0,R.jsx)(Mp,{tone:e.tone,title:e.title,children:e.label},e.label))}):null}function Pp({className:e,value:t,...n}){return(0,R.jsx)(Yd,{"data-slot":`progress`,className:I(`relative flex h-1 w-full items-center overflow-x-hidden rounded-full bg-muted`,e),...n,children:(0,R.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,R.jsx)(xo,{"data-slot":`sheet`,...e})}function Ip({...e}){return(0,R.jsx)(To,{"data-slot":`sheet-portal`,...e})}function Lp({className:e,...t}){return(0,R.jsx)(Do,{"data-slot":`sheet-overlay`,className:I(`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,R.jsxs)(Ip,{children:[(0,R.jsx)(Lp,{}),(0,R.jsxs)(jo,{"data-slot":`sheet-content`,"data-side":n,className:I(`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,R.jsx)(Ro,{"data-slot":`sheet-close`,asChild:!0,children:(0,R.jsxs)(hp,{variant:`ghost`,className:`absolute top-3 right-3`,size:`icon-sm`,children:[(0,R.jsx)(st,{}),(0,R.jsx)(`span`,{className:`sr-only`,children:`Close`})]})})]})]})}function zp({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`sheet-header`,className:I(`flex flex-col gap-0.5 p-4`,e),...t})}function Bp({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`sheet-footer`,className:I(`mt-auto flex flex-col gap-2 p-4`,e),...t})}function Vp({className:e,...t}){return(0,R.jsx)(Fo,{"data-slot":`sheet-title`,className:I(`font-heading text-base font-medium text-foreground`,e),...t})}function Hp({className:e,...t}){return(0,R.jsx)(Io,{"data-slot":`sheet-description`,className:I(`text-sm text-muted-foreground`,e),...t})}var Up={control:{icon:ke,blurb:`Keystone presents itself to UniFi Protect as an AI Key over the UCP4 control channel.`},aiport:{icon:Ze,blurb:`A virtual AI Port X. Protect relays paired cameras over FLV and Keystone runs smart detections locally.`},vision:{icon:re,blurb:`A vision-language model writes the event descriptions and tags shown in Protect.`},search:{icon:Ge,blurb:`CLIP image and text embeddings back Protect’s Find Anything search.`},faces:{icon:Ue,blurb:`Detects faces in event frames and matches them against your local gallery.`},lpr:{icon:ze,blurb:`Finds and reads license plates locally, then reports them back to Protect.`},stt:{icon:j,blurb:`Transcribes speech clips locally with Whisper.`},enhance:{icon:at,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,R.jsxs)(`div`,{className:`rounded-md bg-danger-soft px-2.5 py-2 text-danger`,children:[(0,R.jsxs)(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[(0,R.jsx)(`p`,{className:`min-w-0 truncate text-[11.5px] font-medium`,title:t,children:t??`Last error`}),n&&(0,R.jsx)(bp,{text:e,label:`Copy error`,size:`xs`,className:`h-6 bg-card text-foreground`})]}),n?(0,R.jsx)(`pre`,{className:`max-h-80 overflow-auto font-mono text-[11.5px] leading-relaxed whitespace-pre-wrap [overflow-wrap:anywhere]`,children:e}):(0,R.jsx)(`p`,{ref:r,className:`line-clamp-3 font-mono text-[11.5px] leading-relaxed [overflow-wrap:anywhere]`,children:e}),i&&(0,R.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,R.jsxs)(`div`,{className:`rounded-md bg-warning-soft px-2.5 py-2 text-warning`,children:[(0,R.jsx)(`p`,{className:`mb-1 min-w-0 truncate text-[11.5px] font-medium`,title:t,children:t??`Notice`}),(0,R.jsx)(`p`,{ref:r,className:I(`text-[12px] leading-relaxed [overflow-wrap:anywhere]`,!n&&`line-clamp-3`),children:e}),i&&(0,R.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,R.jsxs)(R.Fragment,{children:[e.headline&&(0,R.jsxs)(`p`,{className:`flex min-w-0 items-baseline gap-2`,children:[(0,R.jsx)(`span`,{className:I(`truncate text-lg font-medium tracking-[-0.025em]`,e.headlineMono&&`font-mono text-base tracking-normal`),children:e.headline}),e.headlineSub&&(0,R.jsx)(`span`,{className:`shrink-0 truncate text-[13px] text-muted-foreground`,children:e.headlineSub})]}),(0,R.jsx)(Np,{chips:e.chips}),e.stats&&(0,R.jsxs)(`div`,{className:I(`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,R.jsxs)(`div`,{className:`min-w-0 bg-card px-2 py-2`,children:[(0,R.jsx)(`p`,{className:I(`truncate text-[15px] font-medium tabular`,e.tone&&Dp[e.tone]),children:e.value}),(0,R.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,R.jsx)(`div`,{className:`bg-card`},`pad-${t}`))]}),e.progress&&(0,R.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,R.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-[13px]`,children:[(0,R.jsx)(`span`,{className:`text-muted-foreground`,children:e.progress.label}),(0,R.jsxs)(`span`,{className:`font-mono text-xs tabular`,children:[e.progress.pct,`%`]})]}),(0,R.jsx)(Pp,{value:e.progress.pct,className:`h-1`}),(0,R.jsx)(`p`,{className:`font-mono text-[11.5px] text-muted-foreground`,children:e.progress.detail})]}),e.rows.length>0&&(0,R.jsx)(`dl`,{className:`text-[13px]`,children:e.rows.map(e=>(0,R.jsxs)(`div`,{className:`flex items-baseline justify-between gap-3 py-0.5`,title:e.title,children:[(0,R.jsx)(`dt`,{className:`shrink-0 text-muted-foreground`,children:e.label}),(0,R.jsx)(`dd`,{className:`truncate font-mono text-xs tabular`,children:e.value})]},e.label))}),e.people&&e.people.length>0&&(0,R.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,R.jsx)(`div`,{className:`flex -space-x-1.5`,children:e.people.slice(0,6).map(e=>(0,R.jsxs)(wp,{children:[(0,R.jsx)(Tp,{asChild:!0,children:(0,R.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,R.jsxs)(Ep,{children:[e.name,` · `,e.refs,` reference`,e.refs===1?``:`s`]})]},e.name))}),(0,R.jsx)(`span`,{className:`truncate text-xs text-muted-foreground`,children:e.people.map(e=>e.name).join(`, `)})]}),e.rejections&&e.rejections.length>0&&(0,R.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,R.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Rejected`}),(0,R.jsx)(Np,{chips:e.rejections})]}),e.disabledHint&&(0,R.jsxs)(`p`,{className:`text-[13px] text-muted-foreground`,children:[`Disabled. Enable with `,(0,R.jsx)(`code`,{className:`rounded bg-muted px-1 py-0.5 font-mono text-[11.5px]`,children:e.disabledHint})]}),e.notice&&(0,R.jsx)(qp,{notice:e.notice,label:e.noticeLabel,expanded:t}),e.error&&(0,R.jsx)(Kp,{error:e.error,label:e.errorLabel,expanded:t})]})}function Yp({s:e,onOpen:t}){let n=Up[e.id].icon;return(0,R.jsxs)(`button`,{type:`button`,onClick:t,className:I(`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,R.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,R.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2.5`,children:[(0,R.jsx)(`span`,{className:I(`grid size-8 shrink-0 place-items-center rounded-md border bg-background text-muted-foreground`,e.tone===`off`&&`opacity-60`),children:(0,R.jsx)(n,{className:`size-4`,strokeWidth:1.75})}),(0,R.jsx)(`p`,{className:`min-w-0 truncate text-sm font-medium tracking-[-0.01em]`,children:e.title})]}),(0,R.jsx)(jp,{tone:e.tone,pulse:e.tone===`info`,children:e.state})]}),(0,R.jsx)(Jp,{s:e}),(0,R.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,R.jsx)(he,{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,R.jsxs)(`section`,{id:`services`,className:`scroll-mt-28`,children:[(0,R.jsx)(Zp,{title:`Services`,meta:`${n} of ${e.length} enabled`}),(0,R.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 sm:gap-4 xl:grid-cols-4`,children:e.map(e=>(0,R.jsx)(Yp,{s:e,onOpen:()=>t(e)},e.id))})]})}function Zp({title:e,meta:t,children:n}){return(0,R.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1`,children:[(0,R.jsx)(`h2`,{className:`text-2xl font-semibold tracking-[-0.035em]`,children:e}),t&&(0,R.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,R.jsx)(Fp,{open:!!n,onOpenChange:t,children:(0,R.jsx)(Rp,{className:`w-full gap-0 outline-none sm:max-w-md`,onOpenAutoFocus:Sp,children:n&&r&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(zp,{className:`border-b`,children:[(0,R.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,R.jsx)(`span`,{className:`grid size-8 place-items-center rounded-md border bg-background text-muted-foreground`,children:(0,R.jsx)(r,{className:`size-4`,strokeWidth:1.75})}),(0,R.jsx)(Vp,{className:`text-base tracking-[-0.02em]`,children:n.title}),n.port&&(0,R.jsx)(Mp,{mono:!0,children:n.port}),(0,R.jsx)(jp,{tone:n.tone,className:`mr-8 ml-auto`,children:n.state})]}),(0,R.jsx)(Hp,{children:Up[n.id].blurb})]}),(0,R.jsxs)(`div`,{className:`flex-1 space-y-6 overflow-y-auto p-4`,children:[(0,R.jsx)(`div`,{className:`space-y-3`,children:(0,R.jsx)(Jp,{s:n,expanded:!0})}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`p`,{className:`mb-2 text-[13px] font-medium text-muted-foreground`,children:`Raw status`}),(0,R.jsx)(`div`,{className:`rounded-lg border bg-card px-3 py-1.5`,children:(0,R.jsx)(yp,{data:n.raw??{}})})]})]}),(0,R.jsx)(Bp,{className:`border-t`,children:(0,R.jsx)(xp,{data:n.raw})})]})})})}function $p({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`empty`,className:I(`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,R.jsx)(`div`,{"data-slot":`empty-header`,className:I(`flex max-w-sm flex-col items-center gap-2`,e),...t})}var tm=an(`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,R.jsx)(`div`,{"data-slot":`empty-icon`,"data-variant":t,className:I(tm({variant:t,className:e})),...n})}function rm({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`empty-title`,className:I(`font-heading text-sm font-medium tracking-tight`,e),...t})}function im({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`empty-description`,className:I(`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,R.jsx)(`input`,{type:t,"data-slot":`input`,className:I(`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,R.jsx)(`div`,{"data-slot":`input-group`,role:`group`,className:I(`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=an(`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,R.jsx)(`div`,{role:`group`,"data-slot":`input-group-addon`,"data-align":t,className:I(sm({align:t}),e),onClick:e=>{e.target.closest(`button`)||e.currentTarget.parentElement?.querySelector(`input`)?.focus()},...n})}var lm=an(`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,R.jsx)(hp,{type:t,"data-size":r,variant:n,className:I(lm({size:r}),e),...i})}function dm({className:e,...t}){return(0,R.jsx)(am,{"data-slot":`input-group-control`,className:I(`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,R.jsx)(`kbd`,{"data-slot":`kbd`,className:I(`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=an(`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,R.jsx)(wf,{"data-slot":`toggle-group`,"data-variant":t,"data-size":n,"data-spacing":r,"data-orientation":i,style:{"--gap":r},className:I(`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,R.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,R.jsx)(Nf,{"data-slot":`toggle-group-item`,"data-variant":a.variant||n,"data-size":a.size||r,"data-spacing":a.spacing,className:I(`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,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)),ee=Math.trunc(Z(a.liveQueued??a.queued)),k=Math.trunc(Z(a.completed)),te=Math.trunc(Z(a.failed)),A=$m(a,t),ne=$(o.frameLayout||o.layout)||(Z(o.maxFrames)>0?`${Z(o.maxFrames)}-frame`:``),j=ah(a),M=j>=3,re=D&&(o.protectAiSummary===!1||r.protectAiSettings?.aiSummary===!1),ie={id:`vision`,title:`Vision captions`,...D?M?{tone:`error`,state:`Failing`}:O>0?{tone:`info`,state:`Running`}:{tone:`ok`,state:`Ready`}:{tone:`off`,state:`Disabled`},...D&&j>0&&$(a.captionLastError)?{error:$(a.captionLastError),errorLabel:M?`${j} caption jobs failed in a row`:`Last caption job failed`}:{},headline:D?E:void 0,headlineMono:!0,chips:D?[{label:T,tone:`neutral`},...ne?[{label:ne,tone:`info`}]:[],...re?[{label:`Protect AI Summary off`,tone:`neutral`,title:`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(A.avg)} avg · ${vm(A.last)} last`}]:[],stats:D?[{label:`Active`,value:Q(O),tone:O>0?`info`:void 0},{label:`Queued`,value:Q(ee)},{label:`Done`,value:Q(k)},{label:`Failed`,value:Q(te),tone:te>0?`error`:void 0}]:void 0,disabledHint:D?void 0:`vision.provider, base_url, model`,raw:{...o,worker:a}},ae=s.enabled!==!1,oe=$(s.provider)||`ready`,se=$(s.device||s.openvinoDevice),ce=ih(oe,se),le=[];s.quantization&&le.push({label:$(s.quantization),tone:`info`}),`textModelLoaded`in s&&le.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`}),se&&!ce.toUpperCase().includes(se.toUpperCase())&&le.push({label:se.toUpperCase(),tone:`info`});let ue=Math.trunc(Z(a.retroactiveCompleted)),de=Math.trunc(Z(a.retroactiveQueued)),fe=Math.trunc(Z(a.retroactiveFailed)),pe=Math.trunc(Z(a.retroactiveImagesIndexed)),me=ue+de,he=[{label:`Port`,value:`7443`,title:`Find Anything search channel (WSS)`},{label:`Queries`,value:`${Q(i.queriesServed)} text · ${Q(i.imageQueriesServed)} image`}],ge;if(me>0||pe>0){let e=ue>0&&de===0?100:me>0?Math.round(ue/me*100):0,t=[`${Q(ue)} events`,`${Q(pe)} images`];de&&t.push(`${Q(de)} queued`),fe&&t.push(`${Q(fe)} failed`),ge={label:`Retroactive backfill`,detail:t.join(` · `),pct:e}}else s.retroactiveProcessing&&he.push({label:`Retroactive backfill`,value:`Idle`});let _e={id:`search`,title:`Find Anything`,port:`:7443`,...ae?i.connected?{tone:`ok`,state:`Online`}:i.lastError?{tone:`error`,state:`Error`}:{tone:`warn`,state:`Waiting`}:{tone:`off`,state:`Disabled`},headline:ae?$(s.backend||`clip`).toUpperCase():void 0,headlineSub:ae?ce:void 0,chips:ae?le:[],rows:ae?he:[],progress:ae?ge:void 0,disabledHint:ae?void 0:`embeddings.enabled: true`,error:eh(i.lastError),raw:{...s,search:i}},N=Mm(l.gallery),P=Qm(e,n),ve={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(N.people)} ${Z(N.people)===1?`person`:`people`} enrolled`:void 0,headlineSub:l.enabled?`${Q(N.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(N.perPerson)).map(([e,t])=>({name:e,refs:Z(t)})):void 0,rejections:Object.entries(P).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??{}},[ye,be]=Nm(u.detector),[xe,Se]=Nm(u.ocr),Ce=Z(u.platesRecognized,Z(u.aiKeyPlates)),we={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(Ce)} plate${Ce===1?``:`s`} read`:void 0,chips:u.enabled?[...u.nativeProtect?[{label:`Native Protect`,tone:`info`}]:[],...ye||xe?[{label:[ye,xe].filter(Boolean).join(` + `),tone:`neutral`,title:[be,Se].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??{}},Te=Z(d.completed||d.transcriptions),Ee=!!d.enabled&&(d.protectEnabled===!1||r.protectAiSettings?.stt===!1),De={id:`stt`,title:`Speech to text`,...d.enabled?d.ready?Ee?{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(Te)} · ${Q(d.segments)} segments`},{label:`Latency`,value:`${vm(d.avgElapsedMs||d.lastElapsedMs)} avg`}]:[],disabledHint:d.enabled?void 0:`stt.enabled: true`,...Ee?{noticeLabel:`Disabled in UniFi Protect`,notice:`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??{}},Oe=Z(f.enhanced||a.enhanceCompleted);return[_,w,ie,_e,ve,we,De,{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(Oe)},{label:`Last run`,value:vm(f.lastElapsedMs)}]:[],disabledHint:f.enabled?void 0:`enhance.enabled: true`,error:eh(f.lastError),raw:e.enhance??{}}].map(t=>lh(t,e.inference))}var sh={aiport:[`aiport:`],search:[`clip:`],faces:[`face:`],lpr:[`lpr`],stt:[`stt:`],enhance:[`enhance:`]};function ch(e,t){let n=sh[e]??[];return Object.entries(Mm(t)).filter(([e])=>n.some(t=>e.startsWith(t)))}function lh(e,t){if(e.tone===`off`)return e;let n=ch(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 uh(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 dh(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 fh=[`person`,`vehicle`,`animal`,`face`,`licensePlate`,`package`];function ph(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=fh.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:mh(t),detections:f,audio:p,frames:Z(t.framesAnalyzed),events:Z(t.eventsEmitted),audioEvents:Z(t.audioEventsEmitted)}}):[]}function mh(e){return e.hwaccelBackend===`videotoolbox`?`VideoToolbox`:e.hwaccelBackend===`vaapi`||e.hwaccelBackend===void 0&&e.vaapiActive?`VA-API`:null}function hh(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 gh={"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 _h(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 vh(e,t,n,r,i,a){let o=t-gh[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,R.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,R.jsxs)(`span`,{className:`font-normal tracking-normal text-muted-foreground`,children:[Math.round(t*100),`%`]})]})}function Ch({item:e}){return(0,R.jsx)(R.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,R.jsxs)(Mp,{tone:`info`,title:e.fromCamera?`Propagated from ${e.fromCamera}`:`Propagated identity`,children:[(0,R.jsx)(xe,{className:`size-3`}),n]},`${n}-${t}`);if(r===`lpr`)return(0,R.jsx)(Mp,{tone:`warn`,title:`Vehicle matched by license plate`,children:n},`${n}-${t}`);let i=Z(e?.similarity);return(0,R.jsx)(Mp,{tone:`ok`,title:`Matched by ${r}${i>0?` · ${Math.round(i*100)}% similarity`:``}`,children:n},`${n}-${t}`)})})}function wh({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,R.jsx)(`li`,{children:(0,R.jsxs)(`button`,{type:`button`,onClick:i,className:I(`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,R.jsx)(xh,{item:e}),(0,R.jsxs)(`div`,{className:`min-w-0 space-y-1`,children:[(0,R.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,R.jsx)(`span`,{className:I(`text-xs font-medium`,yh[a.tone].text),children:a.label}),(0,R.jsx)(`span`,{className:`truncate text-sm font-medium`,children:(0,R.jsx)(bh,{text:e.cameraName,query:t})}),o.map(e=>(0,R.jsx)(Sh,{...e},e.plate)),(0,R.jsx)(Ch,{item:e}),s&&(0,R.jsx)(Mp,{tone:`warn`,children:s})]}),c?(0,R.jsxs)(`p`,{className:`line-clamp-2 text-sm text-foreground/90 italic`,children:[`“`,(0,R.jsx)(bh,{text:c,query:t}),`”`]}):(0,R.jsx)(`p`,{className:I(`line-clamp-2 text-sm`,l?`text-foreground/90`:`text-muted-foreground`),children:l?(0,R.jsx)(bh,{text:l,query:t}):`No description`}),(u.length>0||d.length>0)&&(0,R.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground`,children:[u.length>0&&(0,R.jsxs)(`span`,{className:`truncate`,children:[u.slice(0,8).map((e,n)=>(0,R.jsxs)(`span`,{children:[n>0&&(0,R.jsx)(`span`,{className:`px-1 text-muted-foreground/50`,children:`·`}),(0,R.jsx)(bh,{text:e,query:t})]},e)),u.length>8&&(0,R.jsxs)(`span`,{className:`pl-1 text-muted-foreground/70`,children:[`+`,u.length-8]})]}),d.length>0&&(0,R.jsxs)(`span`,{className:`text-warning`,children:[`Face rejected: `,d.map(([e,t])=>`${e} ×${Z(t)}`).join(`, `)]})]})]}),(0,R.jsxs)(`div`,{className:`flex flex-col items-end gap-0.5 pt-0.5 text-right`,children:[(0,R.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,R.jsx)(`span`,{className:`text-xs text-muted-foreground tabular`,children:Cm(f,n)}),Z(e.elapsedMs)>0&&(0,R.jsx)(`span`,{className:`font-mono text-[11px] text-muted-foreground/80 tabular`,title:`Processing time`,children:vm(e.elapsedMs)})]})]})})}var Th=[];function Eh({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??Th,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(gh).map(([e,{label:t}])=>(0,R.jsx)(`option`,{value:e,children:t},e))})]})}),(0,R.jsxs)(`div`,{className:`overflow-hidden rounded-lg border bg-card`,children:[(0,R.jsxs)(`div`,{className:`flex flex-col gap-3 border-b p-3 lg:flex-row lg:items-center lg:justify-between`,children:[(0,R.jsx)(`div`,{className:`-mx-3 overflow-x-auto px-3 md:mx-0 md:px-0`,children:(0,R.jsx)(hm,{type:`single`,variant:`outline`,size:`sm`,value:o,onValueChange:e=>e&&c(e),"aria-label":`Filter events`,children:Vm.map(e=>(0,R.jsxs)(gm,{value:e.key,className:`gap-1.5 px-2.5 text-[13px]`,children:[e.label,(0,R.jsx)(`span`,{className:`font-mono text-[11px] text-muted-foreground tabular`,children:a?Q(a[e.key]):`—`})]},e.key))})}),(0,R.jsxs)(om,{className:`h-8 lg:w-64`,children:[(0,R.jsx)(cm,{children:(0,R.jsx)(Ye,{className:`size-3.5`})}),(0,R.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,R.jsx)(cm,{align:`inline-end`,children:s?(0,R.jsx)(um,{size:`icon-xs`,"aria-label":`Clear search`,onClick:()=>l(``),children:(0,R.jsx)(st,{})}):(0,R.jsx)(fm,{children:`/`})})]})]}),e.incomplete&&(0,R.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,R.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,R.jsx)(hp,{size:`sm`,variant:`outline`,onClick:e.refresh,children:`Retry`})]}),e.error&&(0,R.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,R.jsx)(hp,{size:`sm`,variant:`outline`,onClick:e.refresh,children:`Retry`})]}),r?u.length===0?(0,R.jsx)($p,{className:`rounded-none py-14`,children:(0,R.jsxs)(em,{children:[(0,R.jsx)(nm,{variant:`icon`,children:(0,R.jsx)(re,{strokeWidth:1.75})}),(0,R.jsx)(rm,{children:r.counts.all?`No matching events`:`No recorded activity in this time range`}),(0,R.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,R.jsx)(`div`,{children:g.map(e=>(0,R.jsxs)(`div`,{children:[(0,R.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,R.jsx)(`ul`,{className:`divide-y`,children:e.items.map(e=>(0,R.jsx)(wh,{item:e,query:s,now:t,fresh:m.has(e.key),onOpen:()=>n(e)},e.key))})]},e.key))}):!e.error&&(0,R.jsx)(`p`,{role:`status`,className:`py-14 text-center text-sm text-muted-foreground`,children:`Loading activity…`}),(e.hasPrevious||r?.nextCursor)&&(0,R.jsxs)(`nav`,{"aria-label":`Activity pages`,className:`flex justify-end gap-2 border-t px-3 py-2`,children:[(0,R.jsxs)(hp,{variant:`outline`,size:`sm`,disabled:!e.hasPrevious,onClick:e.previous,children:[(0,R.jsx)(pe,{}),` Newer events`]}),(0,R.jsxs)(hp,{variant:`outline`,size:`sm`,disabled:!r?.nextCursor,onClick:e.next,children:[`Older events `,(0,R.jsx)(he,{})]})]})]})]})}function Dh({className:e,...t}){return(0,R.jsx)(`div`,{"data-slot":`table-container`,className:`relative w-full overflow-x-auto`,children:(0,R.jsx)(`table`,{"data-slot":`table`,className:I(`w-full caption-bottom text-sm`,e),...t})})}function Oh({className:e,...t}){return(0,R.jsx)(`thead`,{"data-slot":`table-header`,className:I(`[&_tr]:border-b`,e),...t})}function kh({className:e,...t}){return(0,R.jsx)(`tbody`,{"data-slot":`table-body`,className:I(`[&_tr:last-child]:border-0`,e),...t})}function Ah({className:e,...t}){return(0,R.jsx)(`tr`,{"data-slot":`table-row`,className:I(`border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted`,e),...t})}function jh({className:e,...t}){return(0,R.jsx)(`th`,{"data-slot":`table-head`,className:I(`h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0`,e),...t})}function Mh({className:e,...t}){return(0,R.jsx)(`td`,{"data-slot":`table-cell`,className:I(`p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0`,e),...t})}var Nh={person:{icon:rt,label:`Person`},vehicle:{icon:ae,label:`Vehicle`},animal:{icon:Fe,label:`Animal`},face:{icon:Ue,label:`Face`},licensePlate:{icon:ze,label:`License plate`},package:{icon:je,label:`Package`}};function Ph({cam:e}){return(0,R.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1`,children:[e.detections.map(({key:e,count:t})=>{let n=Nh[e],r=n.icon;return(0,R.jsxs)(wp,{children:[(0,R.jsx)(Tp,{asChild:!0,children:(0,R.jsxs)(`span`,{className:I(`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,R.jsx)(r,{className:`size-3.5`,strokeWidth:1.75}),t>0&&(0,R.jsx)(`span`,{className:`font-mono text-[11px] tabular`,children:Q(t)})]})}),(0,R.jsxs)(Ep,{children:[n.label,t>0?` · ${Q(t)} detected`:``]})]},e)}),e.audio.length>0&&(0,R.jsxs)(wp,{children:[(0,R.jsx)(Tp,{asChild:!0,children:(0,R.jsxs)(`span`,{className:`inline-flex h-6 items-center gap-1 rounded-md border bg-background px-1.5 text-muted-foreground`,children:[(0,R.jsx)(j,{className:`size-3.5`,strokeWidth:1.75}),(0,R.jsx)(`span`,{className:`text-[11px]`,children:e.audio.length})]})}),(0,R.jsxs)(Ep,{children:[`Audio: `,e.audio.join(`, `)]})]})]})}function Fh({cam:e}){return(0,R.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:e.channels.map(e=>(0,R.jsxs)(wp,{children:[(0,R.jsx)(Tp,{asChild:!0,children:(0,R.jsxs)(`span`,{className:I(`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,R.jsx)(Ap,{tone:e.connected?`ok`:`off`}),e.name]})}),(0,R.jsxs)(Ep,{children:[e.connected?`Streaming`:`Idle`,` · `,_m(e.bytes),` relayed`,(0,R.jsx)(`span`,{className:`block font-mono opacity-70`,children:e.stream})]})]},e.name))})}var Ih={live:`All channels streaming`,partial:`Some channels idle`,idle:`Not streaming`};function Lh({cameras:e,aiportEnabled:t,range:n,cameraCounts:r,incomplete:i}){let a=hh(e);return(0,R.jsxs)(`section`,{id:`cameras`,className:`scroll-mt-28`,children:[(0,R.jsx)(Zp,{title:`Cameras`,meta:e.length?`${a.streaming} of ${a.count} streaming · ${a.bytesLabel} relayed`:void 0}),e.length===0?(0,R.jsx)($p,{className:`border bg-card`,children:(0,R.jsxs)(em,{children:[(0,R.jsx)(nm,{variant:`icon`,children:(0,R.jsx)(se,{strokeWidth:1.75})}),(0,R.jsx)(rm,{children:`No paired cameras`}),(0,R.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,R.jsx)(`div`,{className:`overflow-hidden rounded-lg border bg-card`,children:(0,R.jsxs)(Dh,{children:[(0,R.jsx)(Oh,{children:(0,R.jsxs)(Ah,{className:`hover:bg-transparent`,children:[(0,R.jsx)(jh,{className:`h-10 pl-4 text-xs font-medium text-muted-foreground`,children:`Camera`}),(0,R.jsx)(jh,{className:`hidden h-10 text-xs font-medium text-muted-foreground sm:table-cell`,children:`Stream`}),(0,R.jsx)(jh,{className:`hidden h-10 text-xs font-medium text-muted-foreground lg:table-cell`,children:`Channels`}),(0,R.jsx)(jh,{className:`h-10 text-xs font-medium text-muted-foreground`,children:`Detections`}),(0,R.jsx)(jh,{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,R.jsxs)(jh,{className:`h-10 pr-4 text-right text-xs font-medium text-muted-foreground`,title:n?`AI Port events emitted · ${gh[n].label}`:`AI Port events emitted since startup`,children:[`Events `,(0,R.jsxs)(`span`,{className:`font-normal`,children:[`· `,n??`session`]})]})]})}),(0,R.jsx)(kh,{children:e.map(e=>(0,R.jsxs)(Ah,{className:`h-14`,children:[(0,R.jsx)(Mh,{className:`max-w-56 pl-4`,children:(0,R.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,R.jsxs)(wp,{children:[(0,R.jsx)(Tp,{asChild:!0,children:(0,R.jsx)(`span`,{className:`grid size-4 place-items-center`,children:(0,R.jsx)(Ap,{tone:e.state===`live`?`ok`:e.state===`partial`?`warn`:`off`})})}),(0,R.jsx)(Ep,{children:Ih[e.state]})]}),(0,R.jsxs)(`div`,{className:`min-w-0`,children:[(0,R.jsx)(`p`,{className:`truncate font-medium`,children:e.name}),e.showId&&(0,R.jsx)(`p`,{className:`truncate font-mono text-[11px] text-muted-foreground`,children:e.id})]})]})}),(0,R.jsx)(Mh,{className:`hidden sm:table-cell`,children:(0,R.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,R.jsxs)(`span`,{className:`font-mono text-xs tabular`,children:[e.resolution,e.fps?(0,R.jsxs)(`span`,{className:`text-muted-foreground`,children:[` · `,e.fps,` fps`]}):null]}),e.hwaccelLabel&&(0,R.jsx)(Mp,{tone:`info`,title:`Hardware video decode via ${e.hwaccelLabel}`,children:e.hwaccelLabel})]})}),(0,R.jsx)(Mh,{className:`hidden lg:table-cell`,children:(0,R.jsx)(Fh,{cam:e})}),(0,R.jsx)(Mh,{children:(0,R.jsx)(Ph,{cam:e})}),(0,R.jsx)(Mh,{className:`hidden text-right font-mono text-xs tabular md:table-cell`,children:Q(e.frames)}),(0,R.jsxs)(Mh,{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 Rh({...e}){return(0,R.jsx)(Gr,{"data-slot":`collapsible`,...e})}function zh({...e}){return(0,R.jsx)(qr,{"data-slot":`collapsible-trigger`,...e})}function Bh({...e}){return(0,R.jsx)(Yr,{"data-slot":`collapsible-content`,...e})}function Vh({title:e,children:t}){return(0,R.jsxs)(`section`,{className:`space-y-2`,children:[(0,R.jsx)(`h3`,{className:`text-[13px] font-medium text-muted-foreground`,children:e}),t]})}function Hh({rows:e}){let t=e.filter(([,e])=>e!=null&&e!==``);return t.length?(0,R.jsx)(`dl`,{className:`divide-y rounded-lg border bg-card text-sm`,children:t.map(([e,t])=>(0,R.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-3 py-2`,children:[(0,R.jsx)(`dt`,{className:`text-muted-foreground`,children:e}),(0,R.jsx)(`dd`,{className:`text-right font-mono text-xs tabular`,children:t})]},e))}):null}function Uh({item:e,onOpenChange:t}){return(0,R.jsx)(Fp,{open:!!e,onOpenChange:t,children:(0,R.jsx)(Rp,{className:`w-full gap-0 outline-none sm:max-w-lg`,onOpenAutoFocus:Sp,children:e&&(0,R.jsx)(Wh,{item:e})})})}function Wh({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,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(zp,{className:`border-b`,children:(0,R.jsxs)(`div`,{className:`flex items-start gap-4 pr-8`,children:[(0,R.jsx)(xh,{item:e,size:`lg`}),(0,R.jsxs)(`div`,{className:`min-w-0 space-y-1.5`,children:[(0,R.jsx)(`p`,{className:I(`text-xs font-medium`,yh[t.tone].text),children:t.label}),(0,R.jsx)(Vp,{className:`text-lg leading-tight tracking-[-0.02em]`,children:e.cameraName}),(0,R.jsx)(Hp,{className:`tabular`,children:xm(e.timestamp)}),(0,R.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 pt-0.5`,children:[n.map(e=>(0,R.jsx)(Sh,{...e},e.plate)),(0,R.jsx)(Ch,{item:e}),r&&(0,R.jsx)(Mp,{tone:`warn`,children:r})]})]})]})}),(0,R.jsxs)(`div`,{className:`flex-1 space-y-6 overflow-y-auto p-4`,children:[i?(0,R.jsx)(Vh,{title:`Transcript`,children:(0,R.jsxs)(`blockquote`,{className:`border-l-2 border-info/50 pl-3 text-[15px] leading-relaxed`,children:[`“`,i,`”`]})}):(0,R.jsx)(Vh,{title:`Description`,children:(0,R.jsx)(`p`,{className:I(`text-[15px] leading-relaxed`,!a&&`text-muted-foreground`),children:a||`No description`})}),o.length>0&&(0,R.jsx)(Vh,{title:`Tags`,children:(0,R.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:o.map(e=>(0,R.jsx)(Mp,{children:e},e))})}),s.length>0&&(0,R.jsx)(Vh,{title:`Identities`,children:(0,R.jsx)(`div`,{className:`divide-y rounded-lg border bg-card text-sm`,children:s.map((e,t)=>(0,R.jsxs)(`div`,{className:`flex items-center justify-between gap-3 px-3 py-2`,children:[(0,R.jsxs)(`div`,{className:`min-w-0`,children:[(0,R.jsx)(`p`,{className:`truncate font-medium`,children:e.name}),(0,R.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,R.jsxs)(`div`,{className:`text-right font-mono text-xs tabular`,children:[Z(e.similarity)>0&&(0,R.jsx)(`p`,{children:ym(e.similarity)}),Z(e.margin)>0&&(0,R.jsxs)(`p`,{className:`text-muted-foreground`,children:[`margin `,Z(e.margin).toFixed(2)]})]})]},`${e.name}-${t}`))})}),n.length>0&&(0,R.jsx)(Vh,{title:`License plates`,children:(0,R.jsx)(Hh,{rows:n.map(e=>[e.plate,e.confidence>0?ym(e.confidence):`—`])})}),c&&(Z(c.framesScanned)>0||Z(c.detections)>0)&&(0,R.jsxs)(Vh,{title:`Face scan`,children:[(0,R.jsx)(Hh,{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,R.jsx)(`ul`,{className:`space-y-1.5 pt-1`,children:l.map(([e,t])=>(0,R.jsxs)(`li`,{className:`flex gap-2 text-xs`,children:[(0,R.jsxs)(Mp,{tone:`warn`,children:[e,` ×`,Z(t)]}),(0,R.jsx)(`span`,{className:`pt-0.5 text-muted-foreground`,children:Em[e]??`Quality gate`})]},e))})]}),(0,R.jsx)(Vh,{title:`Processing`,children:(0,R.jsx)(Hh,{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,R.jsxs)(Rh,{children:[(0,R.jsxs)(zh,{className:`group flex items-center gap-1 text-[13px] font-medium text-muted-foreground hover:text-foreground`,children:[(0,R.jsx)(de,{className:`size-3.5 transition-transform group-data-[state=closed]:-rotate-90`}),`Raw event`]}),(0,R.jsx)(Bh,{className:`pt-2`,children:(0,R.jsx)(`div`,{className:`rounded-lg border bg-card px-3 py-1.5`,children:(0,R.jsx)(yp,{data:p})})})]})]}),(0,R.jsx)(Bp,{className:`border-t`,children:(0,R.jsx)(xp,{data:p})})]})}function Gh({values:e,className:t,label:n}){let r=(0,_.useId)();if(e.length<2)return(0,R.jsx)(`div`,{className:I(`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,R.jsxs)(`div`,{className:I(`relative h-7 w-full text-info`,t),role:`img`,"aria-label":n,children:[(0,R.jsxs)(`svg`,{viewBox:`0 0 120 28`,preserveAspectRatio:`none`,className:`absolute inset-0 size-full overflow-visible`,children:[(0,R.jsx)(`defs`,{children:(0,R.jsxs)(`linearGradient`,{id:r,x1:`0`,x2:`0`,y1:`0`,y2:`1`,children:[(0,R.jsx)(`stop`,{offset:`0%`,stopColor:`currentColor`,stopOpacity:`0.2`}),(0,R.jsx)(`stop`,{offset:`100%`,stopColor:`currentColor`,stopOpacity:`0`})]})}),(0,R.jsx)(`path`,{d:u,fill:`url(#${r})`}),(0,R.jsx)(`path`,{d:l,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,vectorEffect:`non-scaling-stroke`})]}),(0,R.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,R.jsx)(`span`,{className:`absolute inset-0 rounded-full bg-current animate-ping-slow`})})]})}function Kh({label:e,value:t}){let[n,r]=(0,_.useState)(!1);return(0,R.jsxs)(wp,{open:n||void 0,children:[(0,R.jsx)(Tp,{asChild:!0,children:(0,R.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,R.jsx)(`span`,{className:`text-muted-foreground`,children:e}),(0,R.jsx)(`span`,{className:`font-mono text-foreground`,children:t}),n?(0,R.jsx)(le,{className:`size-3 text-success`}):(0,R.jsx)(ye,{className:`size-3 text-muted-foreground/60 transition-colors group-hover:text-muted-foreground`})]})}),(0,R.jsx)(Ep,{children:n?`Copied`:`Copy ${e}`})]})}var qh={ok:_e,info:_e,warn:tt,error:P,off:_e};function Jh({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=qh[t.tone],f=uh(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,R.jsxs)(`section`,{id:`top`,className:`scroll-mt-20 pt-10 pb-2 sm:pt-14`,children:[(0,R.jsx)(`p`,{className:`text-[13px] font-medium text-muted-foreground`,children:f.subtitle}),(0,R.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,R.jsx)(d,{className:I(`size-7 shrink-0 sm:size-8`,Dp[t.tone]),strokeWidth:2}),t.title]}),(0,R.jsx)(`p`,{className:`mt-3 max-w-[68ch] text-base text-muted-foreground`,children:p.join(` · `)}),t.attention.length>0&&(0,R.jsx)(`div`,{className:`mt-4 flex flex-wrap gap-2`,children:t.attention.map(e=>(0,R.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,R.jsx)(jp,{tone:e.tone,className:`-ml-1 h-5`,children:e.state}),(0,R.jsx)(`span`,{className:`font-medium`,children:e.title}),(0,R.jsx)(he,{className:`size-3.5 text-muted-foreground transition-transform group-hover:translate-x-0.5`})]},e.id))}),m.length>0&&(0,R.jsxs)(`div`,{className:`mt-5 flex flex-wrap gap-2`,children:[m.map(e=>(0,R.jsx)(Kh,{...e},e.label)),(0,R.jsxs)(`span`,{className:I(`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,R.jsx)(Ce,{className:`size-3.5`,strokeWidth:1.75}),s.label]}),s.warning&&(0,R.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,R.jsx)(Zh,{status:e,cameras:n,history:r,snapshot:!!a})]})}function Yh({label:e,value:t,unit:n,sub:r,children:i,tone:a}){return(0,R.jsxs)(`div`,{className:`flex min-h-[116px] flex-col rounded-lg border bg-card px-5 pt-4 pb-4`,children:[(0,R.jsx)(`p`,{className:`text-[13px] font-medium text-muted-foreground`,children:e}),(0,R.jsxs)(`p`,{className:`mt-2.5 flex items-baseline gap-1.5 truncate`,children:[(0,R.jsx)(`span`,{className:`text-xl font-medium tracking-[-0.025em] tabular`,children:t}),n&&(0,R.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:n})]}),i,r&&(0,R.jsx)(`p`,{className:I(`mt-auto pt-1 text-[13px] text-muted-foreground tabular`,a&&Dp[a]),children:r})]})}function Xh(e,t){let n=[];for(let r=1;r0&&a>=0?a/i:0)}return n}function Zh({status:e,cameras:t,history:n,snapshot:r}){let i=hh(t),a=Xh(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,R.jsxs)(`div`,{className:`mt-8 grid grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-4`,children:[(0,R.jsx)(Yh,{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,R.jsx)(Yh,{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,R.jsx)(Gh,{values:a,className:`mt-2`,label:`Frames analyzed per second`})}),(0,R.jsx)(Yh,{label:`Captions`,value:Q(c),unit:`done`,tone:ah(s)>=3?`error`:void 0,sub:`${vm(s.avgLatencyMs)} avg${l?` · ${Q(l)} failed`:``}`}),(0,R.jsx)(Yh,{label:`Smart detections since startup`,value:Q(u.totalSmartEvents),sub:`${Q(u.totalAudioEvents)} audio · ${Q(u.totalFaces)} faces · ${Q(u.totalPlates)} plates`})]})}function Qh({...e}){return(0,R.jsx)(sd,{"data-slot":`dropdown-menu`,...e})}function $h({...e}){return(0,R.jsx)(ld,{"data-slot":`dropdown-menu-trigger`,...e})}function eg({className:e,align:t=`start`,sideOffset:n=4,...r}){return(0,R.jsx)(ud,{children:(0,R.jsx)(fd,{"data-slot":`dropdown-menu-content`,sideOffset:n,align:t,className:I(`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 tg({...e}){return(0,R.jsx)(md,{"data-slot":`dropdown-menu-radio-group`,...e})}function ng({className:e,children:t,inset:n,...r}){return(0,R.jsxs)(hd,{"data-slot":`dropdown-menu-radio-item`,"data-inset":n,className:I(`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,R.jsx)(`span`,{className:`pointer-events-none absolute right-2 flex items-center justify-center`,"data-slot":`dropdown-menu-radio-item-indicator`,children:(0,R.jsx)(gd,{children:(0,R.jsx)(le,{})})}),t]})}function rg({className:e,inset:t,...n}){return(0,R.jsx)(pd,{"data-slot":`dropdown-menu-label`,"data-inset":t,className:I(`px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7`,e),...n})}function ig({className:e,...t}){return(0,R.jsx)(_d,{"data-slot":`dropdown-menu-separator`,className:I(`-mx-1 my-1 h-px bg-border`,e),...t})}function ag({...e}){return(0,R.jsx)(Ed,{"data-slot":`popover`,...e})}function og({...e}){return(0,R.jsx)(Od,{"data-slot":`popover-trigger`,...e})}function sg({className:e,align:t=`center`,sideOffset:n=4,...r}){return(0,R.jsx)(Md,{children:(0,R.jsx)(Pd,{"data-slot":`popover-content`,align:t,sideOffset:n,className:I(`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 cg({className:e,orientation:t=`horizontal`,decorative:n=!0,...r}){return(0,R.jsx)(df,{"data-slot":`separator`,decorative:n,orientation:t,className:I(`shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch`,e),...r})}function lg(e,t){return e.map(e=>Z(e.timestamp)>0?{...e,timestamp:Z(e.timestamp)+t}:e)}function ug(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 dg(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 fg=3e3,pg=8e3,mg=14,hg=4;function gg(){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 _g(){return window.location.protocol===`http:`||window.location.protocol===`https:`}function vg(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 yg(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 bg(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=mg;e>=0;e--){let t=s-e*fg;exg(e)),n=_g()&&!t,r=!!(e.status&&Object.keys(e.status).length),[i]=(0,_.useState)(()=>bg(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(),pg);try{let[t,n,r]=await Promise.all([yg(`api/status`,e.signal),yg(`api/events`,e.signal),yg(`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,...vg(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,fg)},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=ug(C.current,fg/1e3,e/1e3);if(w.current%hg===2&&T.current.length){let n={...T.current.shift(),timestamp:e};t=dg(t,n),u(e=>[n,...e].slice(0,60))}C.current=t,o(t),y(e),x(n=>[...n,{t:e,...vg(t)}].slice(-40))},fg);return()=>window.clearInterval(e)},[t,d]);let O=(0,_.useCallback)(e=>{f(e),e&&D()},[D]),ee;return ee=t?d?`demo`:`paused`:n?d?p?`reconnecting`:h?`live`:`connecting`:`paused`:`snapshot`,{status:a,events:s,activity:l,connection:ee,lastUpdated:v,generatedAt:Z(e.generatedAt)>0?Z(e.generatedAt):null,demo:t,history:b,live:d,setLive:O,refresh:D}}function Cg({className:e}){return(0,R.jsxs)(`svg`,{viewBox:`0 0 24 24`,className:I(`size-6 shrink-0`,e),"aria-hidden":`true`,children:[(0,R.jsx)(`rect`,{width:`24`,height:`24`,rx:`6`,className:`fill-foreground`}),(0,R.jsxs)(`g`,{transform:`translate(0 0.2)`,children:[(0,R.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,R.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,R.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 wg={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 Tg({connection:e,live:t,setLive:n,lastUpdated:r}){let i=wg[e];if(e===`snapshot`)return(0,R.jsxs)(wp,{children:[(0,R.jsx)(Tp,{asChild:!0,children:(0,R.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,R.jsx)(Ap,{tone:`off`}),`Snapshot`]})}),(0,R.jsx)(Ep,{children:`Static export. Open the served dashboard for live data.`})]});let a=Math.round(fg/1e3);return(0,R.jsxs)(wp,{children:[(0,R.jsx)(Tp,{asChild:!0,children:(0,R.jsxs)(hp,{variant:`outline`,size:`sm`,onClick:()=>n(!t),"aria-pressed":t,className:`gap-2 font-medium tabular`,children:[(0,R.jsx)(Ap,{tone:i.tone,pulse:e===`live`||e===`demo`}),i.label,t?(0,R.jsx)(Ne,{className:`size-3 text-muted-foreground`}):(0,R.jsx)(Le,{className:`size-3 text-muted-foreground`})]})}),(0,R.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 Eg({accel:e}){return(0,R.jsxs)(ag,{children:[(0,R.jsx)(og,{asChild:!0,children:(0,R.jsxs)(hp,{variant:`ghost`,size:`sm`,className:I(`gap-1.5 font-mono text-xs font-normal`,e.warning?`text-warning`:e.hardware?`text-info`:`text-muted-foreground`),children:[e.warning?(0,R.jsx)(tt,{className:`size-3.5`,strokeWidth:1.75}):(0,R.jsx)(Ce,{className:`size-3.5`,strokeWidth:1.75}),e.label]})}),(0,R.jsxs)(sg,{align:`end`,className:`w-80 p-0`,children:[(0,R.jsxs)(`div`,{className:`flex items-start justify-between gap-3 border-b px-4 py-3`,children:[(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`p`,{className:`text-sm font-medium tracking-tight`,children:`Inference acceleration`}),(0,R.jsx)(`p`,{className:`font-mono text-xs text-muted-foreground`,children:e.detail})]}),e.precision&&(0,R.jsx)(Mp,{mono:!0,children:e.precision})]}),(e.warning||e.note)&&(0,R.jsx)(`p`,{className:I(`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,R.jsx)(`ul`,{className:`max-h-80 overflow-y-auto p-1.5`,children:e.models.map(e=>(0,R.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,R.jsx)(`span`,{className:I(!e.loaded&&`text-muted-foreground`),children:e.label}),(0,R.jsx)(Mp,{mono:!0,tone:e.loaded?e.hardware?`info`:`neutral`:`off`,children:e.provider})]},e.key))}):(0,R.jsx)(`p`,{className:`px-4 py-3 text-sm text-muted-foreground`,children:`This runtime doesn’t report per-model execution providers.`})]})]})}function Dg({preference:e,setPreference:t}){return(0,R.jsxs)(Qh,{children:[(0,R.jsx)($h,{asChild:!0,children:(0,R.jsx)(hp,{variant:`ghost`,size:`icon-sm`,"aria-label":`Theme`,children:(0,R.jsx)(e===`dark`?De:e===`light`?$e:Te,{className:`size-4`,strokeWidth:1.75})})}),(0,R.jsxs)(eg,{align:`end`,className:`w-40`,children:[(0,R.jsx)(rg,{children:`Appearance`}),(0,R.jsx)(ig,{}),(0,R.jsxs)(tg,{value:e,onValueChange:e=>t(e),children:[(0,R.jsxs)(ng,{value:`system`,children:[(0,R.jsx)(Te,{strokeWidth:1.75}),` System`]}),(0,R.jsxs)(ng,{value:`light`,children:[(0,R.jsx)($e,{strokeWidth:1.75}),` Light`]}),(0,R.jsxs)(ng,{value:`dark`,children:[(0,R.jsx)(De,{strokeWidth:1.75}),` Dark`]})]})]})]})}function Og(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 kg({sections:e}){let t=Og(e.map(e=>e.id));return(0,R.jsx)(`nav`,{"aria-label":`Sections`,className:`ml-4 hidden h-full items-stretch md:flex`,children:e.map(e=>(0,R.jsxs)(`a`,{href:`#${e.id}`,"aria-current":t===e.id?`location`:void 0,className:I(`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,R.jsx)(Ap,{tone:e.tone}),e.count!=null&&e.count>0&&(0,R.jsx)(`span`,{className:`font-mono text-[11px] text-muted-foreground tabular`,children:e.count})]},e.id))})}function Ag({appName:e,version:t,accel:n,connection:r,live:i,setLive:a,lastUpdated:o,refresh:s,theme:c,setTheme:l,sections:u}){return(0,R.jsx)(`header`,{className:`sticky top-0 z-40 border-b bg-background/85 backdrop-blur-md backdrop-saturate-150`,children:(0,R.jsxs)(`div`,{className:`mx-auto flex h-14 max-w-[1200px] items-center gap-3 px-4 sm:px-6`,children:[(0,R.jsxs)(`a`,{href:`#top`,className:`flex items-center gap-2.5 rounded-md outline-offset-4`,children:[(0,R.jsx)(Cg,{}),(0,R.jsx)(`span`,{className:`text-[15px] font-semibold tracking-[-0.03em]`,children:e})]}),(0,R.jsxs)(Mp,{mono:!0,className:`hidden sm:inline-flex`,children:[`v`,t]}),(0,R.jsx)(kg,{sections:u}),(0,R.jsxs)(`div`,{className:`ml-auto flex items-center gap-1.5`,children:[(0,R.jsx)(`div`,{className:`hidden md:block`,children:(0,R.jsx)(Eg,{accel:n})}),(0,R.jsx)(cg,{orientation:`vertical`,className:`mx-1 hidden h-5 md:block`}),r===`reconnecting`&&(0,R.jsx)(hp,{variant:`ghost`,size:`icon-sm`,onClick:s,"aria-label":`Retry now`,children:(0,R.jsx)(Ve,{className:`size-3.5`})}),(0,R.jsx)(Tg,{connection:r,live:i,setLive:a,lastUpdated:o}),(0,R.jsx)(Dg,{preference:c,setPreference:l})]})]})})}var jg=[`api/status`,`api/events`,`api/activity`,`healthz`];function Mg({appName:e,version:t,snapshot:n,demoLink:r}){let i=r!==void 0;return(0,R.jsx)(`footer`,{className:`border-t`,children:(0,R.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,R.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,R.jsx)(Cg,{className:`size-4 opacity-70`}),(0,R.jsxs)(`span`,{children:[e,t?` ${t}`:``,` · open-source local AI for UniFi Protect`]})]}),i&&(0,R.jsxs)(`p`,{children:[`Demo with sample data; nothing here is a real home.`,r&&(0,R.jsxs)(R.Fragment,{children:[` `,(0,R.jsx)(`a`,{href:r,className:`font-medium text-foreground underline-offset-4 hover:underline`,children:`Get Keystone →`})]})]}),!n&&!i&&(0,R.jsx)(`nav`,{"aria-label":`JSON endpoints`,className:`flex flex-wrap gap-x-4 gap-y-1 font-mono text-xs`,children:jg.map(e=>(0,R.jsxs)(`a`,{href:e,className:`transition-colors hover:text-foreground`,children:[`/`,e]},e))})]})})}function Ng(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=_h(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,fg))}},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?vh(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 Pg=`keystone-theme`;function Fg(){try{let e=window.localStorage.getItem(Pg);if(e===`light`||e===`dark`||e===`system`)return e}catch{}return`system`}function Ig(e){let t=e===`dark`||e===`system`&&window.matchMedia(`(prefers-color-scheme: dark)`).matches;document.documentElement.classList.toggle(`dark`,t)}function Lg(){let[e,t]=(0,_.useState)(Fg);return(0,_.useEffect)(()=>{if(Ig(e),e!==`system`)return;let t=window.matchMedia(`(prefers-color-scheme: dark)`),n=()=>Ig(`system`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)},[e]),{preference:e,setPreference:(0,_.useCallback)(e=>{t(e);try{window.localStorage.setItem(Pg,e)}catch{}},[])}}function Rg(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 zg(){let e=Sg(),{preference:t,setPreference:n}=Lg(),r=Rg(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=Ng(l,c,i.cameras,u,e.live,e.refresh),f=(0,_.useMemo)(()=>oh(i,a,c),[i,a,c]),p=(0,_.useMemo)(()=>ph(i),[i]),m=(0,_.useMemo)(()=>dh(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,R.jsxs)(Cp,{delayDuration:200,children:[(0,R.jsxs)(`div`,{className:`min-h-svh`,children:[(0,R.jsx)(Ag,{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,R.jsxs)(`main`,{className:`mx-auto max-w-[1200px] space-y-12 px-4 pb-16 sm:px-6`,children:[(0,R.jsx)(Jh,{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,R.jsx)(Xp,{services:f,onOpen:e=>v(e.id)}),(0,R.jsx)(Lh,{cameras:p,aiportEnabled:!!i.aiport?.enabled,range:l||d.fallback?null:d.range,cameraCounts:d.cameraCounts,incomplete:d.incomplete}),(0,R.jsx)(Eh,{history:d,now:s,onOpen:b})]}),(0,R.jsx)(Mg,{appName:S,version:String(i.version||``),snapshot:e.connection===`snapshot`,demoLink:e.demo?e.demo.link??null:void 0})]}),(0,R.jsx)(Qp,{service:x,onOpenChange:e=>!e&&v(null)}),(0,R.jsx)(Uh,{item:y,onOpenChange:e=>!e&&b(null)})]})}(0,v.createRoot)(document.getElementById(`root`)).render((0,R.jsx)(_.StrictMode,{children:(0,R.jsx)(zg,{})}));
diff --git a/tests/test_control.py b/tests/test_control.py
index 239bf8a..b67a7af 100644
--- a/tests/test_control.py
+++ b/tests/test_control.py
@@ -15,7 +15,7 @@
from cryptography.hazmat.primitives import serialization
from keystone.config import Config
-from keystone.control import ControlService, DeviceStateStore
+from keystone.control import CommandError, ControlService, DeviceStateStore
from keystone.discovery import DISCOVERY_MCAST_GROUP, DiscoveryService, DiscoveryTarget
from keystone.tls import (
build_client_ssl_context,
@@ -744,3 +744,119 @@ def _req(path: str, payload: dict, remote: str = "192.0.2.10"):
assert resp_bad_proto.status == 400
assert "invalid adoption payload" in caplog.text
assert "secret-token-should-not-log" not in caplog.text
+
+
+async def test_protect_ai_settings_merge_warnings_and_basic_mode_guard(
+ tmp_path: Path, caplog: pytest.LogCaptureFixture
+):
+ from keystone.app import KeystoneRuntime
+
+ cfg = Config(state_dir=tmp_path / "state")
+ cfg.controller.host = "127.0.0.1"
+ cfg.device.advertise_ip = "127.0.0.1"
+ cfg.stt.enabled = True
+ cfg.vision.provider = "ollama"
+ cfg.vision.model = "qwen3.5:9b"
+ cfg.resolve_defaults()
+
+ store = DeviceStateStore(cfg.state_dir)
+ dispatched: list[dict] = []
+
+ async def fake_job(job: dict) -> dict:
+ dispatched.append(job)
+ return {"status": "queued"}
+
+ ctrl = ControlService(
+ cfg,
+ store,
+ client_ssl_context=None, # type: ignore[arg-type]
+ expected_fingerprint="0" * 64,
+ job_handler=fake_job,
+ queue_status=lambda: {},
+ )
+
+ # Unadopted device never surfaces stale Protect-side settings.
+ assert ctrl.protect_ai_settings == {}
+
+ store.state["adopted"] = True
+ store.save()
+
+ caplog.set_level("INFO", logger="keystone.control")
+
+ # Protect 7.4 pushes enableSTT=false on fresh adoption behind Basic Understanding (On/All).
+ push = {
+ "deepModeSupported": True,
+ "enableFaceEnhance": True,
+ "enableFaceRecognize": False,
+ "enableLprRecognize": False,
+ "enableRAM": True,
+ "enableSTT": False,
+ "region": "US",
+ }
+ assert await ctrl._dispatch_command("changeAiInferAgentSettings", push) == push
+ assert ctrl.protect_ai_settings == {
+ "ram": True,
+ "stt": False,
+ "faceRecognition": False,
+ "lpr": False,
+ "faceEnhance": True,
+ }
+ stt_warnings = [r for r in caplog.records if r.levelname == "WARNING" and "enableSTT=false" in r.message]
+ assert len(stt_warnings) == 1
+ assert "Basic Understanding" in stt_warnings[0].message
+
+ # Repeated enableSTT=false pushes do not spam the warning log.
+ assert await ctrl._dispatch_command("changeAiInferAgentSettings", push) == push
+ assert len([r for r in caplog.records if r.levelname == "WARNING" and "enableSTT=false" in r.message]) == 1
+
+ # Syncing modelMode="basic" is acknowledged and must not clobber enable* settings.
+ assert await ctrl._dispatch_command("changeAiInferAgentSettings", {"modelMode": "basic"}) == {
+ "modelMode": "basic"
+ }
+ assert ctrl.protect_ai_settings["stt"] is False
+ assert ctrl.protect_ai_settings["ram"] is True
+
+ # Deep mode is rejected cleanly because Keystone stays in Basic Understanding.
+ with pytest.raises(CommandError) as exc_info:
+ await ctrl._dispatch_command("changeAiInferAgentSettings", {"modelMode": "deep"})
+ assert exc_info.value.code == 95
+ ff = ctrl.get_info()["featureFlags"]
+ assert ff["aiMode"] == "basic"
+ assert ff["supportDeepMode"] is False
+ assert ff["supportVlm"] is False
+
+ # recognizeKeyFrames with postVLM=false records aiSummary=False and still dispatches the job.
+ caplog.clear()
+ await ctrl._dispatch_command(
+ "recognizeKeyFrames",
+ {"camera": "cam1", "event": "ev1", "ramType": "video", "postVLM": False},
+ )
+ assert len(dispatched) == 1
+ assert ctrl.protect_ai_settings["aiSummary"] is False
+ assert any("postVLM=false" in r.message for r in caplog.records)
+
+ # /api/status surfaces protectAiSettings, stt.protectEnabled, and vision.protectAiSummary.
+ fake_stt = SimpleNamespace(status=lambda: {"ready": True, "model": "whisper-base"})
+ runtime = KeystoneRuntime(cfg, stt=fake_stt) # type: ignore[arg-type]
+ runtime.store = store
+ runtime.control = ctrl
+ status = runtime.get_status()
+ assert status["control"]["protectAiSettings"]["stt"] is False
+ assert status["control"]["protectAiSettings"]["aiSummary"] is False
+ assert status["stt"]["protectEnabled"] is False
+ assert status["vision"]["protectAiSummary"] is False
+
+ # Turning both on in Protect clears the disabled flags.
+ caplog.clear()
+ await ctrl._dispatch_command("changeAiInferAgentSettings", {**push, "enableSTT": True})
+ await ctrl._dispatch_command(
+ "recognizeKeyFrames",
+ {"camera": "cam1", "event": "ev2", "ramType": "video", "postVLM": True},
+ )
+ assert ctrl.protect_ai_settings["stt"] is True
+ assert ctrl.protect_ai_settings["aiSummary"] is True
+ assert any("enableSTT=true" in r.message for r in caplog.records)
+ assert any("postVLM=true" in r.message for r in caplog.records)
+ status_on = runtime.get_status()
+ assert status_on["stt"]["protectEnabled"] is True
+ assert status_on["vision"]["protectAiSummary"] is True
diff --git a/unraid/keystone.xml b/unraid/keystone.xml
index cc09bb2..5aa6512 100644
--- a/unraid/keystone.xml
+++ b/unraid/keystone.xml
@@ -11,7 +11,7 @@
https://github.com/seeARMS/keystone
A free, virtual AI Key and AI Port for UniFi Protect. Keystone brings plain-English Find Anything search, event descriptions, speech transcripts, license plate reading, face recognition, Enhance Face, and smart detections for third-party cameras into Protect.
-Give the container its own IP address on your LAN (Network Type br0 with a fixed IP), since Protect expects Keystone's ports, including 443 and 8080, at one address. Set your Protect controller's IP below, pick which features you want, then adopt the AI Key in UniFi Protect under UniFi Devices and enable Basic Object Recognition, AI Summary (if you set a vision server), and Speech-to-Text under Protect → Settings → Intelligence.
+Give the container its own IP address on your LAN (Network Type br0 with a fixed IP), since Protect expects Keystone's ports, including 443 and 8080, at one address. Set your Protect controller's IP below, pick which features you want, then adopt the AI Key in UniFi Protect under UniFi Devices and enable Basic Understanding (on Protect 7.4+, toggle Basic Understanding Off then On and click Apply Changes, or use Selected Only; on Protect 7.3, enable Basic Object Recognition, AI Summary, and Speech-to-Text) under Protect → Settings → Intelligence.
Find Anything, Speech-to-Text, License Plates, and Enhance Face are on by default in this template; Face Recognition (InsightFace non-commercial weights) and the virtual AI Port are opt-in below. Event descriptions require a vision server (Ollama, OpenAI-compatible, OpenAI, or Anthropic); set Vision provider to disabled (or leave the vision URL blank with the default Ollama provider) to skip descriptions while Find Anything search still works.
@@ -29,7 +29,7 @@ This image includes the PostgreSQL search database Protect uses for Find Anythin
- true
+ true
true
true
false
diff --git a/web/src/components/services.tsx b/web/src/components/services.tsx
index 6b9890b..6481768 100644
--- a/web/src/components/services.tsx
+++ b/web/src/components/services.tsx
@@ -114,6 +114,24 @@ function ErrorNote({ error, label, expanded }: { error: string; label?: string;
)
}
+function NoticeNote({ notice, label, expanded }: { notice: string; label?: string; expanded: boolean }) {
+ const [previewRef, clipped] = useIsClamped(!expanded)
+ return (
+
+
+ {label ?? "Notice"}
+
+
+ {notice}
+
+ {clipped &&
View full note
}
+
+ )
+}
+
function ServiceBody({ s, expanded = false }: { s: ServiceView; expanded?: boolean }) {
return (
<>
@@ -203,6 +221,7 @@ function ServiceBody({ s, expanded = false }: { s: ServiceView; expanded?: boole
Disabled. Enable with {s.disabledHint}
)}
+ {s.notice && }
{s.error && }
>
)
@@ -217,6 +236,7 @@ function ServiceCard({ s, onOpen }: { s: ServiceView; onOpen: () => void }) {
className={cn(
"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",
s.tone === "error" && "border-danger/40 hover:border-danger/60",
+ s.tone === "warn" && s.notice && "border-warning/40 hover:border-warning/60",
)}
>
diff --git a/web/src/lib/derive.test.ts b/web/src/lib/derive.test.ts
index a86168c..642b3e7 100644
--- a/web/src/lib/derive.test.ts
+++ b/web/src/lib/derive.test.ts
@@ -305,6 +305,42 @@ describe("services", () => {
})
})
+ it("flags Speech to text when Protect disables enableSTT and notes postVLM=false on Vision", () => {
+ const sttOff: KeystoneStatus = {
+ ...status,
+ control: { ...status.control, protectAiSettings: { ram: true, stt: false, aiSummary: false } },
+ stt: { ...status.stt, enabled: true, ready: true, protectEnabled: false },
+ vision: { ...status.vision, protectAiSummary: false },
+ }
+ const speech = service("stt", sttOff)
+ expect(speech).toMatchObject({
+ tone: "warn",
+ state: "Off in Protect",
+ noticeLabel: "Disabled in UniFi Protect",
+ })
+ expect(speech.notice).toContain("Basic Understanding")
+
+ const vision = service("vision", sttOff)
+ expect(vision).toMatchObject({ tone: "ok", state: "Ready" })
+ expect(vision.chips.map((c) => c.label)).toContain("Protect AI Summary off")
+
+ const feed = mergeFeed(events, activity, sttOff.cameras)
+ const health = overallHealth(deriveServices(sttOff, events, feed))
+ expect(health).toMatchObject({ tone: "warn", title: "Speech to text needs attention" })
+ expect(health.attention.map((s) => s.id)).toEqual(["stt"])
+
+ const sttOn: KeystoneStatus = {
+ ...status,
+ control: { ...status.control, protectAiSettings: { ram: true, stt: true, aiSummary: true } },
+ stt: { ...status.stt, enabled: true, ready: true, protectEnabled: true },
+ vision: { ...status.vision, protectAiSummary: true },
+ }
+ const speechOn = service("stt", sttOn)
+ expect(speechOn).toMatchObject({ tone: "ok", state: "Ready" })
+ expect(speechOn.notice).toBeUndefined()
+ expect(service("vision", sttOn).chips.map((c) => c.label)).not.toContain("Protect AI Summary off")
+ })
+
it("rolls subsystem tones up into one headline", () => {
const feed = mergeFeed(events, activity, status.cameras)
expect(overallHealth(deriveServices(status, events, feed))).toMatchObject({
diff --git a/web/src/lib/derive.ts b/web/src/lib/derive.ts
index 6c9f10a..60016d9 100644
--- a/web/src/lib/derive.ts
+++ b/web/src/lib/derive.ts
@@ -47,6 +47,8 @@ export interface ServiceView {
people?: { name: string; refs: number }[]
rejections?: Chip[]
disabledHint?: string
+ notice?: string
+ noticeLabel?: string
error?: string
/** Heading for `error`: "Last error" (may predate a recovery) or the failing model. */
errorLabel?: string
@@ -683,6 +685,8 @@ export function deriveServices(
const layout = str(vis.frameLayout || vis.layout) || (num(vis.maxFrames) > 0 ? `${num(vis.maxFrames)}-frame` : "")
const streak = captionFailureStreak(wrk)
const visionFailing = streak >= JOB_FAILING_AFTER
+ const protectAiSummaryOff =
+ vOn && (vis.protectAiSummary === false || ctrl.protectAiSettings?.aiSummary === false)
const vision: ServiceView = {
id: "vision",
title: "Vision captions",
@@ -703,7 +707,22 @@ export function deriveServices(
: {}),
headline: vOn ? vModel : undefined,
headlineMono: true,
- chips: vOn ? [{ label: vProvider, tone: "neutral" }, ...(layout ? [{ label: layout, tone: "info" as const }] : [])] : [],
+ chips: vOn
+ ? [
+ { label: vProvider, tone: "neutral" },
+ ...(layout ? [{ label: layout, tone: "info" as const }] : []),
+ ...(protectAiSummaryOff
+ ? [
+ {
+ label: "Protect AI Summary off",
+ tone: "neutral" as const,
+ title:
+ "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: vOn ? [{ label: "Latency", value: `${fmtLatency(lat.avg)} avg · ${fmtLatency(lat.last)} last` }] : [],
stats: vOn
? [
@@ -842,13 +861,17 @@ export function deriveServices(
// Speech to text
const sttDone = num(stt.completed || stt.transcriptions)
+ const sttOffInProtect =
+ Boolean(stt.enabled) && (stt.protectEnabled === false || ctrl.protectAiSettings?.stt === false)
const speech: ServiceView = {
id: "stt",
title: "Speech to text",
...(!stt.enabled
? { tone: "off" as const, state: "Off" }
: stt.ready
- ? { tone: "ok" as const, state: "Ready" }
+ ? sttOffInProtect
+ ? { tone: "warn" as const, state: "Off in Protect" }
+ : { tone: "ok" as const, state: "Ready" }
: stt.lastError
? { tone: "error" as const, state: "Error" }
: { tone: "warn" as const, state: "Loading" }),
@@ -862,6 +885,13 @@ export function deriveServices(
]
: [],
disabledHint: stt.enabled ? undefined : "stt.enabled: true",
+ ...(sttOffInProtect
+ ? {
+ noticeLabel: "Disabled in UniFi Protect",
+ notice:
+ "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: errorText(stt.lastError),
raw: status.stt ?? {},
}
diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts
index 9e76101..384ca95 100644
--- a/web/src/lib/types.ts
+++ b/web/src/lib/types.ts
@@ -4,6 +4,15 @@
export type Dict = Record
+export interface ProtectAiSettings {
+ ram?: boolean
+ stt?: boolean
+ faceRecognition?: boolean
+ lpr?: boolean
+ faceEnhance?: boolean
+ aiSummary?: boolean
+}
+
export interface ControlStatus {
enabled?: boolean
adopted?: boolean
@@ -12,6 +21,7 @@ export interface ControlStatus {
lastError?: string | null
consoleName?: string
protectVersion?: string
+ protectAiSettings?: ProtectAiSettings
commands?: Record
}
@@ -52,6 +62,7 @@ export interface VisionStatus {
maxFrames?: number
frameLayout?: string
layout?: string
+ protectAiSummary?: boolean
}
export interface EmbeddingsStatus {
@@ -124,6 +135,7 @@ export interface LprStatus {
export interface SttStatus {
enabled?: boolean
ready?: boolean
+ protectEnabled?: boolean
model?: string
quantization?: string
completed?: number
From 2d8a3a70768df251eccb8139c25629951a3ae78f Mon Sep 17 00:00:00 2001
From: seeARMS <3957773+seeARMS@users.noreply.github.com>
Date: Thu, 3 Dec 2026 20:00:27 -0800
Subject: [PATCH 2/2] Address handoff review findings for Protect 7.4 setting
diagnostics
---
scripts/install.sh | 2 ++
scripts/setup-compose.py | 2 ++
src/keystone/app.py | 4 +--
src/keystone/control.py | 29 +++++++++++++------
src/keystone/ui/index.html | 32 ++++++++++-----------
tests/test_control.py | 57 +++++++++++++++++++++++++++++++++++++
tests/test_setup_scripts.py | 33 ++++++++++++++++++++-
web/src/lib/derive.test.ts | 12 ++++++++
web/src/lib/derive.ts | 19 ++++++++++---
9 files changed, 157 insertions(+), 33 deletions(-)
diff --git a/scripts/install.sh b/scripts/install.sh
index 99e0971..2602444 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -602,6 +602,8 @@ if intel:
" (On Protect 7.4+, these live inside Basic Understanding — toggle it Off then On "
"and click Apply Changes, or switch to Selected Only to pick features per camera.)"
)
+ else:
+ print(" (On Protect 7.4+, this lives inside Basic Understanding → Object Indexing.)")
if not vision_on:
print(f" (Event descriptions are disabled until you configure vision.* in {config_path} and enable AI Summary.)")
step += 1
diff --git a/scripts/setup-compose.py b/scripts/setup-compose.py
index fe4e9e9..91a6d81 100644
--- a/scripts/setup-compose.py
+++ b/scripts/setup-compose.py
@@ -568,6 +568,8 @@ def print_summary(
" (On Protect 7.4+, these live inside Basic Understanding — toggle it Off then On "
"and click Apply Changes, or switch to Selected Only to pick features per camera.)"
)
+ else:
+ print(" (On Protect 7.4+, this lives inside Basic Understanding → Object Indexing.)")
if not vision_on:
print(
" (Event descriptions are disabled until you configure vision.* in config.yaml and enable AI Summary.)"
diff --git a/src/keystone/app.py b/src/keystone/app.py
index 05979b0..ef9abec 100644
--- a/src/keystone/app.py
+++ b/src/keystone/app.py
@@ -267,12 +267,10 @@ def _lpr_status(self) -> dict[str, Any]:
"aiKeyUploads": worker.get("lprUploads", 0),
}
- def _stt_status(self, protect_ai: dict[str, bool] | None = None) -> dict[str, Any]:
+ def _stt_status(self, protect_ai: dict[str, bool]) -> dict[str, Any]:
if self.stt is None:
return {"enabled": False}
worker = self.worker.status() if self.worker else {}
- if protect_ai is None:
- protect_ai = self.control.protect_ai_settings if self.control else {}
return {
"enabled": True,
**self.stt.status(),
diff --git a/src/keystone/control.py b/src/keystone/control.py
index 1d770d0..ea13300 100644
--- a/src/keystone/control.py
+++ b/src/keystone/control.py
@@ -181,7 +181,7 @@ def __init__(
self.connections = 0
self.command_counts: dict[str, int] = {}
self._last_protect_stt_enabled: bool | None = None
- self._last_post_vlm: bool | None = None
+ self._post_vlm_by_camera: dict[str, bool] = {}
@property
def control_url(self) -> str:
@@ -218,21 +218,27 @@ def retroactive_enabled(self) -> bool:
def _vision_enabled(self) -> bool:
return self.config.vision.provider.lower() != "disabled" and bool(self.config.vision.model)
+ @property
+ def _post_vlm_summary(self) -> bool | None:
+ if not self._post_vlm_by_camera:
+ return None
+ return any(self._post_vlm_by_camera.values())
+
@property
def protect_ai_settings(self) -> dict[str, bool]:
"""Sanitized snapshot of Protect-side AI feature toggles reported to this AI Key."""
if not self.store.adopted:
return {}
out: dict[str, bool] = {}
- state = getattr(self.store, "state", None)
- raw = state.get("changeAiInferAgentSettings") if isinstance(state, dict) else None
+ raw = self.store.state.get("changeAiInferAgentSettings")
if isinstance(raw, dict):
for protect_key, out_key in _PROTECT_AI_SETTING_KEYS:
val = raw.get(protect_key)
if isinstance(val, bool):
out[out_key] = val
- if self._last_post_vlm is not None:
- out["aiSummary"] = self._last_post_vlm
+ post_vlm = self._post_vlm_summary
+ if post_vlm is not None:
+ out["aiSummary"] = post_vlm
return out
def get_info(self) -> dict[str, Any]:
@@ -409,6 +415,9 @@ async def _http_adopt(self, request: web.Request) -> web.Response:
if is_readopt:
self.store.state["adopted"] = False
+ self.store.state.pop("changeAiInferAgentSettings", None)
+ self._last_protect_stt_enabled = None
+ self._post_vlm_by_camera.clear()
self.store.state["management"] = {
"hosts": [f"{self.config.controller.host}:{self.config.controller.control_port}"],
"protocol": "wss",
@@ -824,7 +833,10 @@ async def _dispatch_command(self, action: str, body: dict[str, Any]) -> dict[str
if action == "recognizeKeyFrames":
post_vlm = body.get("postVLM")
if isinstance(post_vlm, bool):
- if self._vision_enabled and not post_vlm and self._last_post_vlm is not False:
+ prev_summary = self._post_vlm_summary
+ self._post_vlm_by_camera[str(body.get("camera") or "")] = post_vlm
+ new_summary = self._post_vlm_summary
+ if self._vision_enabled and new_summary is False and prev_summary is not False:
LOG.info(
"Protect sent recognizeKeyFrames with postVLM=false (AI Summary is off "
"in Protect); Keystone still captions and uploads descriptions (click "
@@ -832,9 +844,8 @@ async def _dispatch_command(self, action: str, body: dict[str, Any]) -> dict[str
"Protect 7.4+, toggle Settings → Intelligence → Basic Understanding Off "
"then On and click Apply Changes (or use Selected Only) to enable AI Summary"
)
- elif self._vision_enabled and post_vlm and self._last_post_vlm is False:
- LOG.info("Protect enabled AI Summary on recognizeKeyFrames (postVLM=true)")
- self._last_post_vlm = post_vlm
+ elif self._vision_enabled and new_summary is True and prev_summary is False:
+ LOG.info("Protect sent recognizeKeyFrames with postVLM=true (AI Summary enabled)")
return await self.job_handler({"command": "recognizeKeyFrames", "payload": body})
if action == "speechToText":
diff --git a/src/keystone/ui/index.html b/src/keystone/ui/index.html
index 3f21305..7cc72a9 100644
--- a/src/keystone/ui/index.html
+++ b/src/keystone/ui/index.html
@@ -22,20 +22,20 @@
if (dark) document.documentElement.classList.add("dark")
})()
-
+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=M>=3,ne=oh(r.protectVersion),re=D&&(o.protectAiSummary===!1||r.protectAiSettings?.aiSummary===!1),ie={id:`vision`,title:`Vision captions`,...D?N?{tone:`error`,state:`Failing`}:O>0?{tone:`info`,state:`Running`}:{tone:`ok`,state:`Ready`}:{tone:`off`,state:`Disabled`},...D&&M>0&&$(a.captionLastError)?{error:$(a.captionLastError),errorLabel:N?`${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`}]:[],...re?[{label:`Protect AI Summary off`,tone:`neutral`,title:ne?`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}},ae=s.enabled!==!1,oe=$(s.provider)||`ready`,se=$(s.device||s.openvinoDevice),ce=ih(oe,se),le=[];s.quantization&&le.push({label:$(s.quantization),tone:`info`}),`textModelLoaded`in s&&le.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`}),se&&!ce.toUpperCase().includes(se.toUpperCase())&&le.push({label:se.toUpperCase(),tone:`info`});let ue=Math.trunc(Z(a.retroactiveCompleted)),de=Math.trunc(Z(a.retroactiveQueued)),fe=Math.trunc(Z(a.retroactiveFailed)),pe=Math.trunc(Z(a.retroactiveImagesIndexed)),me=ue+de,he=[{label:`Port`,value:`7443`,title:`Find Anything search channel (WSS)`},{label:`Queries`,value:`${Q(i.queriesServed)} text · ${Q(i.imageQueriesServed)} image`}],ge;if(me>0||pe>0){let e=ue>0&&de===0?100:me>0?Math.round(ue/me*100):0,t=[`${Q(ue)} events`,`${Q(pe)} images`];de&&t.push(`${Q(de)} queued`),fe&&t.push(`${Q(fe)} failed`),ge={label:`Retroactive backfill`,detail:t.join(` · `),pct:e}}else s.retroactiveProcessing&&he.push({label:`Retroactive backfill`,value:`Idle`});let P={id:`search`,title:`Find Anything`,port:`:7443`,...ae?i.connected?{tone:`ok`,state:`Online`}:i.lastError?{tone:`error`,state:`Error`}:{tone:`warn`,state:`Waiting`}:{tone:`off`,state:`Disabled`},headline:ae?$(s.backend||`clip`).toUpperCase():void 0,headlineSub:ae?ce:void 0,chips:ae?le:[],rows:ae?he:[],progress:ae?ge:void 0,disabledHint:ae?void 0:`embeddings.enabled: true`,error:eh(i.lastError),raw:{...s,search:i}},F=Mm(l.gallery),_e=Qm(e,n),ve={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(F.people)} ${Z(F.people)===1?`person`:`people`} enrolled`:void 0,headlineSub:l.enabled?`${Q(F.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(F.perPerson)).map(([e,t])=>({name:e,refs:Z(t)})):void 0,rejections:Object.entries(_e).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??{}},[ye,be]=Nm(u.detector),[xe,Se]=Nm(u.ocr),Ce=Z(u.platesRecognized,Z(u.aiKeyPlates)),we={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(Ce)} plate${Ce===1?``:`s`} read`:void 0,chips:u.enabled?[...u.nativeProtect?[{label:`Native Protect`,tone:`info`}]:[],...ye||xe?[{label:[ye,xe].filter(Boolean).join(` + `),tone:`neutral`,title:[be,Se].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??{}},Te=Z(d.completed||d.transcriptions),Ee=!!d.enabled&&(d.protectEnabled===!1||r.protectAiSettings?.stt===!1),De={id:`stt`,title:`Speech to text`,...d.enabled?d.ready?Ee?{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(Te)} · ${Q(d.segments)} segments`},{label:`Latency`,value:`${vm(d.avgElapsedMs||d.lastElapsedMs)} avg`}]:[],disabledHint:d.enabled?void 0:`stt.enabled: true`,...Ee?{noticeLabel:`Disabled in UniFi Protect`,notice:ne?`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??{}},Oe=Z(f.enhanced||a.enhanceCompleted);return[_,w,ie,P,ve,we,De,{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(Oe)},{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,{})}));
diff --git a/tests/test_control.py b/tests/test_control.py
index b67a7af..3c4fa59 100644
--- a/tests/test_control.py
+++ b/tests/test_control.py
@@ -860,3 +860,60 @@ async def fake_job(job: dict) -> dict:
status_on = runtime.get_status()
assert status_on["stt"]["protectEnabled"] is True
assert status_on["vision"]["protectAiSummary"] is True
+
+ # In Selected Only mode, an event from another camera with postVLM=false must not flip
+ # console-wide aiSummary back to False or log a misleading transition while cam1 has it on.
+ caplog.clear()
+ await ctrl._dispatch_command(
+ "recognizeKeyFrames",
+ {"camera": "cam2", "event": "ev3", "ramType": "video", "postVLM": False},
+ )
+ assert ctrl.protect_ai_settings["aiSummary"] is True
+ assert not caplog.records
+
+ # If the enabled camera itself switches to postVLM=false, aiSummary transitions to False once.
+ await ctrl._dispatch_command(
+ "recognizeKeyFrames",
+ {"camera": "cam1", "event": "ev4", "ramType": "video", "postVLM": False},
+ )
+ assert ctrl.protect_ai_settings["aiSummary"] is False
+ assert any("postVLM=false" in r.message for r in caplog.records)
+
+ # Re-adoption clears prior Protect settings so timeSync and a mode-only update do not
+ # republish stale flags from the previous adoption.
+ await ctrl._dispatch_command("changeAiInferAgentSettings", {**push, "enableSTT": False})
+ assert ctrl.protect_ai_settings["stt"] is False
+ ctrl._set_password(cfg.device.username, "rotated-pw")
+
+ class _Transport:
+ def get_extra_info(self, key: str, default=None):
+ return ("127.0.0.1", 54321) if key == "peername" else default
+
+ readopt_req = make_mocked_request(
+ "POST",
+ "/api/readopt",
+ headers={"Content-Type": "application/json"},
+ transport=_Transport(), # type: ignore[arg-type]
+ )
+ readopt_req.json = lambda: asyncio.sleep( # type: ignore[method-assign]
+ 0,
+ result={
+ "username": cfg.device.username,
+ "password": "rotated-pw",
+ "protocol": "wss",
+ "token": "new-tok",
+ "hosts": ["127.0.0.1:7442"],
+ },
+ )
+
+ resp = await ctrl._http_adopt(readopt_req)
+ assert resp.status == 200
+ assert ctrl.protect_ai_settings == {}
+
+ ctrl._time_sync_id = "ts-readopt"
+ ctrl._pending_token = "new-tok"
+ await ctrl._handle_response({"id": "ts-readopt", "errorCode": 0}, {})
+ assert store.adopted is True
+ assert ctrl.protect_ai_settings == {}
+ await ctrl._dispatch_command("changeAiInferAgentSettings", {"modelMode": "basic"})
+ assert ctrl.protect_ai_settings == {}
diff --git a/tests/test_setup_scripts.py b/tests/test_setup_scripts.py
index a32ddae..5399000 100644
--- a/tests/test_setup_scripts.py
+++ b/tests/test_setup_scripts.py
@@ -225,7 +225,7 @@ def test_compose_rerun_preserves_existing_files(setup_compose, tmp_path):
@pytest.mark.parametrize(("vision_env", "provider", "base_url"), VISION_ENV_CASES)
def test_compose_setup_from_env(
- setup_compose, tmp_path, monkeypatch, vision_env, provider, base_url
+ setup_compose, tmp_path, monkeypatch, capsys, vision_env, provider, base_url
):
with monkeypatch.context() as setup_vars:
setup_vars.setenv("KEYSTONE_CONTROLLER_IP", CONTROLLER)
@@ -233,6 +233,12 @@ def test_compose_setup_from_env(
setup_vars.setenv(name, value)
setup_compose.main()
+ output = capsys.readouterr().out
+ if provider == "disabled":
+ assert "Basic Understanding → Object Indexing" in output
+ else:
+ assert "Basic Understanding — toggle it Off then On" in output
+
# Read the generated YAML without load_config's runtime environment override.
config = load_config(tmp_path / "config.yaml")
assert config.controller.host == CONTROLLER
@@ -758,9 +764,34 @@ def test_install_post_start_summary_reflects_config(tmp_path):
assert "✗ Face recognition" in result.stdout
assert "✗ Virtual AI Port" in result.stdout
assert "Basic Object Recognition, Speech-to-Text" in result.stdout
+ assert "Basic Understanding — toggle it Off then On" in result.stdout
assert "Legacy Camera Enhancement → License Plate Recognition" in result.stdout
assert "ssh -L 8088:127.0.0.1:8088 root@192.0.2.50" in result.stdout
+ # Find Anything-only install still surfaces the Protect 7.4 Basic Understanding path.
+ config_path.write_text(
+ f"state_dir: {tmp_path / 'state'}\n"
+ f'controller:\n host: "{CONTROLLER}"\n'
+ 'device:\n advertise_ip: "192.0.2.11"\n'
+ "vision:\n provider: disabled\n"
+ "stt:\n enabled: false\n",
+ encoding="utf-8",
+ )
+ result_fa = subprocess.run(
+ ["bash", "-euo", "pipefail", "-c", f"{start}{tail}"],
+ env={
+ **os.environ,
+ "PYTHONPATH": str(REPO / "src"),
+ "VENV": str(fake_venv),
+ "CONFIG": str(config_path),
+ "ip": "192.0.2.50",
+ },
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ assert "Basic Understanding → Object Indexing" in result_fa.stdout
+
# C6: existing install with embeddings disabled, native_protect disabled, and LAN dashboard.
config_path.write_text(
f"state_dir: {tmp_path / 'state'}\n"
diff --git a/web/src/lib/derive.test.ts b/web/src/lib/derive.test.ts
index 642b3e7..abf6776 100644
--- a/web/src/lib/derive.test.ts
+++ b/web/src/lib/derive.test.ts
@@ -339,6 +339,18 @@ describe("services", () => {
expect(speechOn).toMatchObject({ tone: "ok", state: "Ready" })
expect(speechOn.notice).toBeUndefined()
expect(service("vision", sttOn).chips.map((c) => c.label)).not.toContain("Protect AI Summary off")
+
+ // Protect 7.3 consoles have separate AI Summary / Speech-to-Text toggles, not Basic Understanding.
+ const legacyOff: KeystoneStatus = {
+ ...sttOff,
+ control: { ...sttOff.control, protectVersion: "7.3.74" },
+ }
+ const legacySpeech = service("stt", legacyOff)
+ expect(legacySpeech.notice).toContain("Settings → Intelligence")
+ expect(legacySpeech.notice).not.toContain("Basic Understanding")
+ const legacyChip = service("vision", legacyOff).chips.find((c) => c.label === "Protect AI Summary off")
+ expect(legacyChip?.title).toContain("Settings → Intelligence")
+ expect(legacyChip?.title).not.toContain("Basic Understanding")
})
it("rolls subsystem tones up into one headline", () => {
diff --git a/web/src/lib/derive.ts b/web/src/lib/derive.ts
index 60016d9..29a8443 100644
--- a/web/src/lib/derive.ts
+++ b/web/src/lib/derive.ts
@@ -574,6 +574,14 @@ export function captionFailureStreak(worker: WorkerStatus): number {
return num(worker.completed) === 0 ? Math.trunc(num(worker.failed)) : 0
}
+function isPre74Protect(version: string | undefined): boolean {
+ const match = (version ?? "").trim().match(/^(\d+)\.(\d+)/)
+ if (!match) return false
+ const major = Number(match[1])
+ const minor = Number(match[2])
+ return major < 7 || (major === 7 && minor < 4)
+}
+
export function deriveServices(
status: KeystoneStatus,
events: FeedEvent[],
@@ -685,6 +693,7 @@ export function deriveServices(
const layout = str(vis.frameLayout || vis.layout) || (num(vis.maxFrames) > 0 ? `${num(vis.maxFrames)}-frame` : "")
const streak = captionFailureStreak(wrk)
const visionFailing = streak >= JOB_FAILING_AFTER
+ const legacyProtect = isPre74Protect(ctrl.protectVersion)
const protectAiSummaryOff =
vOn && (vis.protectAiSummary === false || ctrl.protectAiSettings?.aiSummary === false)
const vision: ServiceView = {
@@ -716,8 +725,9 @@ export function deriveServices(
{
label: "Protect AI Summary off",
tone: "neutral" as const,
- title:
- "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.",
+ title: legacyProtect
+ ? "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.",
},
]
: []),
@@ -888,8 +898,9 @@ export function deriveServices(
...(sttOffInProtect
? {
noticeLabel: "Disabled in UniFi Protect",
- notice:
- "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).",
+ notice: legacyProtect
+ ? "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: errorText(stt.lastError),