Compare commits

...
Author SHA1 Message Date
dependabot[bot]andGitHub 8ea5eb6bd1 Bump i18next-http-backend from 3.0.1 to 3.0.5 in /web
Bumps [i18next-http-backend](https://github.com/i18next/i18next-http-backend) from 3.0.1 to 3.0.5.
- [Changelog](https://github.com/i18next/i18next-http-backend/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/i18next-http-backend/compare/v3.0.1...v3.0.5)

---
updated-dependencies:
- dependency-name: i18next-http-backend
  dependency-version: 3.0.5
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-22 18:08:47 +00:00
b7261c8e70 GenAI Tweaks (#22968)
* Add debug logs

* refresh embeddings maintainer genai clients on config update

---------

Co-authored-by: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com>
2026-04-22 09:55:54 -06:00
Josh HawkinsandGitHub ad9092d0da Tweaks (#22965)
* use ffmpeg to probe rtsp urls instead of cv2

cv2 is faster (no subprocess launch) and will continue to be used for recording segments

* tweak faq

* change unsaved color to orange

avoids confusion with validation errors (red)

* don't use any variant of orange as a profile color

avoids confusion with unsaved changes

* more unsaved color tweaks
2026-04-22 09:19:30 -06:00
Nicolas MowenandGitHub 20705a3e97 Update oneVPL (#22966) 2026-04-22 08:50:37 -06:00
Josh HawkinsandGitHub f4ac063b37 Add camera wizard improvements (#22963)
* warn in camera wizard when detect stream resolution cannot be determined

* add timeout and tcp fallback for rtsp urls only
2026-04-22 08:15:17 -05:00
Abhilash KishoreandGitHub 2dcaeb6809 fix: bump OpenVINO to 2025.4.x to resolve LXC container detector crash (#22859)
* fix: bump OpenVINO to 2025.4.x to resolve LXC container crash

* fix: replace openvino + onnxruntime with onnxruntime-openvino 1.24.*

onnxruntime-openvino 1.24.* bundles OpenVINO 2025.4.1, which fixes a
crash in constrained CPU environments (e.g. Proxmox LXC) where
lin_system_conf.cpp calls stoi("") on empty strings read from offline
CPU sysfs entries.

Consolidating to onnxruntime-openvino also ensures the OpenVINO runtime
and ONNX Runtime OpenVINO EP are always compatible versions.

* revert: restore onnxruntime, keep openvino bump

Reverting onnxruntime-openvino consolidation - onnxruntime is used with
multiple execution providers (CUDA, TensorRT, MIGraphX, CPU) and cannot
be replaced wholesale with the openvino-specific wheel.
2026-04-22 07:12:14 -06:00
Josh HawkinsandGitHub 962d36323b Improve frontend e2e tests (#22958)
CI / AMD64 Build (push) Waiting to run
CI / ARM Build (push) Waiting to run
CI / Jetson Jetpack 6 (push) Waiting to run
CI / AMD64 Extra Build (push) Blocked by required conditions
CI / ARM Extra Build (push) Blocked by required conditions
CI / Synaptics Build (push) Blocked by required conditions
CI / Assemble and push default build (push) Blocked by required conditions
* add mock data

* add helpers

* page objects

* updated specs

* remove PENDING_REWARITE

* formatting
2026-04-21 16:32:18 -06:00
Josh HawkinsandGitHub 3b81416299 Update Radix deps (#22957)
CI / AMD64 Extra Build (push) Blocked by required conditions
CI / ARM Extra Build (push) Blocked by required conditions
CI / Synaptics Build (push) Blocked by required conditions
CI / Assemble and push default build (push) Blocked by required conditions
CI / AMD64 Build (push) Waiting to run
CI / ARM Build (push) Waiting to run
CI / Jetson Jetpack 6 (push) Waiting to run
* Bump radix-ui packages to align react-dismissable-layer version and fix nested overlay pointer-events bug

* remove workarounds for radix pointer events issues on dropdown and context menus

* remove disablePortal from popover

* remove modal on popovers

* remove workarounds in restart dialog

* keep onCloseAutoFocus for face, classification, and ptz

these are necessary to prevent tooltips from re-showing and from the arrow keys from reopening the ptz presets menu

* add tests
2026-04-21 08:48:48 -06:00
Eduardo-JaramilloandGitHub 7d315c5e6b remove temporary DB cleanup check (#22950)
CI / ARM Build (push) Waiting to run
CI / Jetson Jetpack 6 (push) Waiting to run
CI / AMD64 Extra Build (push) Blocked by required conditions
CI / ARM Extra Build (push) Blocked by required conditions
CI / Synaptics Build (push) Blocked by required conditions
CI / Assemble and push default build (push) Blocked by required conditions
CI / AMD64 Build (push) Waiting to run
2026-04-21 05:11:01 -06:00
Nicolas MowenandGitHub 6cdf4fe3b8 Update intel runtimes to support Battlemage (#22943)
CI / ARM Extra Build (push) Blocked by required conditions
CI / Synaptics Build (push) Blocked by required conditions
CI / AMD64 Build (push) Waiting to run
CI / ARM Build (push) Waiting to run
CI / Jetson Jetpack 6 (push) Waiting to run
CI / AMD64 Extra Build (push) Blocked by required conditions
CI / Assemble and push default build (push) Blocked by required conditions
2026-04-20 08:23:15 -06:00
Josh HawkinsandGitHub 1a5d15ba81 Miscellaneous fixes (#22924)
* apply annotation offset to frigate+ submission frame time

* fix broken docs links with hash fragments that resolve wrong on reload

* undo

* use recording snapshot for frigate+ frame submission from VideoControls

rather than a canvas grab/paint, which may not always align with an ffmpeg snapshot due to keyframes

* add more docs links

- display docs link for main sections on collapsible fields

* dialog button consistency
2026-04-20 07:19:09 -06:00
icidiandGitHub 043c746a8b Improve readability by removing trailing digits caused by floating number conversion (#22934) 2026-04-20 06:35:48 -06:00
423ee2fe72 Feature: Share Timestamped URL for Camera Footage History (#22537)
* Initial copy timestamp url implementation

* revise url format

* Implement share timestamp dialog

* Use translations

* Add comments

* Add validations to shared link

* Switch to searchEffect implementation

* Add missing accessibility related dialog description

* Change URL format to unix timestamps

* Remove unnecessary useEffect

* Remove duplicated dialog title

* Fixes/improvements based off PR review comments

* Add missing cancel button & separators to dialog

* Make share description clearer

* Bugfix: guard against showing toasts twice
Because this effect ends up running multiple times

* Clamp future timestamps to now

* Revert "Bugfix: guard against showing toasts twice"

This reverts commit 99fa5e1dee.

* Use normal separator

Co-authored-by: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com>

* Fixes based off PR review comments

* Bugfix: Share dialog was not receiving the player timestamp after removing key that triggered remounts

* Defer `setRecording` and return true from hook for cleanup

* Remove timeout defer hack in favor of refactored hook

* Attempt to replay video muted on NotAllowedError

* Use separate persistent mute and temporary forced mute states

* Align cancel button with other dialogs

* Prevent wrapping on dialog title

* Remove extra "back" button on mobile drawer

* Fix back navigation when coming from direct shared timestamp links

* Use new timeformat hook

* Simplify dialog radio buttons

* Apply suggestions from code review

Co-authored-by: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com>

---------

Co-authored-by: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com>
2026-04-20 06:35:25 -06:00
Arun RajiahandGitHub d7f42735fc docs: add cctvQL to third-party extensions (#22930) 2026-04-19 07:05:43 -06:00
Josh HawkinsandGitHub cfb87f9744 Miscellaneous fixes (#22913)
CI / AMD64 Build (push) Has been cancelled
CI / ARM Build (push) Has been cancelled
CI / Jetson Jetpack 6 (push) Has been cancelled
CI / ARM Extra Build (push) Has been cancelled
CI / AMD64 Extra Build (push) Has been cancelled
CI / Synaptics Build (push) Has been cancelled
CI / Assemble and push default build (push) Has been cancelled
* add log when probing detect stream on startup

when users don't explicitly set detect.width and detect.height, we probe for them. sometimes the probe hangs (camera doesn't support UDP, like some Reolinks), so this log message will make that clearer

* add faq about probing detect stream

* fix stuck activity ring when tracked object transitions to stationary

* drop cache segments past retain cutoff regardless of retention mode

* add maintainer test
2026-04-18 07:10:50 -06:00
Josh HawkinsandGitHub 74fcd720d3 Add step + percent progress for exports (#22915)
CI / AMD64 Build (push) Waiting to run
CI / ARM Build (push) Waiting to run
CI / Jetson Jetpack 6 (push) Waiting to run
CI / ARM Extra Build (push) Blocked by required conditions
CI / Synaptics Build (push) Blocked by required conditions
CI / Assemble and push default build (push) Blocked by required conditions
CI / AMD64 Extra Build (push) Blocked by required conditions
* backend

* improve frontend Job typing

* progress frontend

* i18n

* tests
2026-04-17 12:18:12 -06:00
112 changed files with 5846 additions and 1488 deletions
+26 -15
View File
@@ -87,40 +87,47 @@ if [[ "${TARGETARCH}" == "amd64" ]]; then
# intel packages use zst compression so we need to update dpkg
apt-get install -y dpkg
# use intel apt intel packages
# use intel apt repo for libmfx1 (legacy QSV, pre-Gen12)
wget -qO - https://repositories.intel.com/gpu/intel-graphics.key | gpg --yes --dearmor --output /usr/share/keyrings/intel-graphics.gpg
echo "deb [arch=amd64 signed-by=/usr/share/keyrings/intel-graphics.gpg] https://repositories.intel.com/gpu/ubuntu jammy client" | tee /etc/apt/sources.list.d/intel-gpu-jammy.list
apt-get -qq update
# intel-media-va-driver-non-free is built from source in the
# intel-media-driver Dockerfile stage for Battlemage (Xe2) support
apt-get -qq install --no-install-recommends --no-install-suggests -y \
libmfx1 libmfxgen1 libvpl2
libmfx1
rm -f /usr/share/keyrings/intel-graphics.gpg
rm -f /etc/apt/sources.list.d/intel-gpu-jammy.list
# upgrade libva2, oneVPL runtime, and libvpl2 from trixie for Battlemage support
echo "deb http://deb.debian.org/debian trixie main" > /etc/apt/sources.list.d/trixie.list
apt-get -qq update
apt-get -qq install -y -t trixie libva2 libva-drm2 libzstd1
apt-get -qq install -y -t trixie libmfx-gen1.2 libvpl2
rm -f /etc/apt/sources.list.d/trixie.list
apt-get -qq update
apt-get -qq install -y ocl-icd-libopencl1
# install libtbb12 for NPU support
apt-get -qq install -y libtbb12
rm -f /usr/share/keyrings/intel-graphics.gpg
rm -f /etc/apt/sources.list.d/intel-gpu-jammy.list
# install legacy and standard intel icd and level-zero-gpu
# install legacy and standard intel compute packages
# see https://github.com/intel/compute-runtime/blob/master/LEGACY_PLATFORMS.md for more info
# needed core package
wget https://github.com/intel/compute-runtime/releases/download/25.13.33276.19/libigdgmm12_22.7.0_amd64.deb
dpkg -i libigdgmm12_22.7.0_amd64.deb
rm libigdgmm12_22.7.0_amd64.deb
wget https://github.com/intel/compute-runtime/releases/download/26.14.37833.4/libigdgmm12_22.9.0_amd64.deb
dpkg -i libigdgmm12_22.9.0_amd64.deb
rm libigdgmm12_22.9.0_amd64.deb
# legacy packages
# legacy compute-runtime packages
wget https://github.com/intel/compute-runtime/releases/download/24.35.30872.36/intel-opencl-icd-legacy1_24.35.30872.36_amd64.deb
wget https://github.com/intel/compute-runtime/releases/download/24.35.30872.36/intel-level-zero-gpu-legacy1_1.5.30872.36_amd64.deb
wget https://github.com/intel/intel-graphics-compiler/releases/download/igc-1.0.17537.24/intel-igc-opencl_1.0.17537.24_amd64.deb
wget https://github.com/intel/intel-graphics-compiler/releases/download/igc-1.0.17537.24/intel-igc-core_1.0.17537.24_amd64.deb
# standard packages
wget https://github.com/intel/compute-runtime/releases/download/25.13.33276.19/intel-opencl-icd_25.13.33276.19_amd64.deb
wget https://github.com/intel/compute-runtime/releases/download/25.13.33276.19/intel-level-zero-gpu_1.6.33276.19_amd64.deb
wget https://github.com/intel/intel-graphics-compiler/releases/download/v2.10.10/intel-igc-opencl-2_2.10.10+18926_amd64.deb
wget https://github.com/intel/intel-graphics-compiler/releases/download/v2.10.10/intel-igc-core-2_2.10.10+18926_amd64.deb
# standard compute-runtime packages
wget https://github.com/intel/compute-runtime/releases/download/26.14.37833.4/intel-opencl-icd_26.14.37833.4-0_amd64.deb
wget https://github.com/intel/compute-runtime/releases/download/26.14.37833.4/libze-intel-gpu1_26.14.37833.4-0_amd64.deb
wget https://github.com/intel/intel-graphics-compiler/releases/download/v2.32.7/intel-igc-opencl-2_2.32.7+21184_amd64.deb
wget https://github.com/intel/intel-graphics-compiler/releases/download/v2.32.7/intel-igc-core-2_2.32.7+21184_amd64.deb
# npu packages
wget https://github.com/oneapi-src/level-zero/releases/download/v1.28.2/level-zero_1.28.2+u22.04_amd64.deb
wget https://github.com/intel/linux-npu-driver/releases/download/v1.19.0/intel-driver-compiler-npu_1.19.0.20250707-16111289554_ubuntu22.04_amd64.deb
@@ -130,6 +137,10 @@ if [[ "${TARGETARCH}" == "amd64" ]]; then
dpkg -i *.deb
rm *.deb
apt-get -qq install -f -y
# Battlemage uses the xe kernel driver, but the VA-API driver is still iHD.
# The oneVPL runtime may look for a driver named after the kernel module.
ln -sf /usr/lib/x86_64-linux-gnu/dri/iHD_drv_video.so /usr/lib/x86_64-linux-gnu/dri/xe_drv_video.so
fi
if [[ "${TARGETARCH}" == "arm64" ]]; then
+1 -1
View File
@@ -42,7 +42,7 @@ opencv-python-headless == 4.11.0.*
opencv-contrib-python == 4.11.0.*
scipy == 1.16.*
# OpenVino & ONNX
openvino == 2025.3.*
openvino == 2025.4.*
onnxruntime == 1.22.*
# Embeddings
transformers == 4.45.*
@@ -17,6 +17,10 @@ Please use your own knowledge to assess and vet them before you install anything
The [Advanced Camera Card](https://card.camera/#/README) is a Home Assistant dashboard card with deep Frigate integration.
## [cctvQL](https://github.com/arunrajiah/cctvql)
[cctvQL](https://github.com/arunrajiah/cctvql) is a natural language query layer for Frigate and other CCTV systems. It connects to Frigate's REST API and MQTT broker to let you ask conversational questions about cameras and events (e.g. "Was there motion at the front door last night?"), with support for real-time event streaming, anomaly detection, PTZ control, alert rules, and a Home Assistant custom component.
## [Double Take](https://github.com/skrashevich/double-take)
[Double Take](https://github.com/skrashevich/double-take) provides an unified UI and API for processing and training images for facial recognition.
+14
View File
@@ -110,3 +110,17 @@ No. Frigate uses the TCP protocol to connect to your camera's RTSP URL. VLC auto
TCP ensures that all data packets arrive in the correct order. This is crucial for video recording, decoding, and stream processing, which is why Frigate enforces a TCP connection. UDP is faster but less reliable, as it does not guarantee packet delivery or order, and VLC does not have the same requirements as Frigate.
You can still configure Frigate to use UDP by using ffmpeg input args or the preset `preset-rtsp-udp`. See the [ffmpeg presets](/configuration/ffmpeg_presets) documentation.
### Frigate is slow to start up with a "probing detect stream" message in the logs
When `detect.width` and `detect.height` are not set, Frigate probes each camera's detect stream on startup (and when saving the config) to auto-detect its resolution. For RTSP streams Frigate probes with ffprobe and automatically retries over TCP if UDP doesn't respond, with a 5 second timeout per attempt. A camera that cannot be reached over either transport will add up to ~10 seconds to startup before Frigate falls through with default dimensions, which may show up as width `0` and height `0` in Camera Probe Info under System Metrics.
To skip the probe entirely and make startup instant, set `detect.width` and `detect.height` explicitly in your camera config:
```yaml
cameras:
my_camera:
detect:
width: 1280
height: 720
```
@@ -107,6 +107,14 @@ class ExportJobModel(BaseModel):
default=None,
description="Result metadata for completed jobs",
)
current_step: str = Field(
default="queued",
description="Current execution step (queued, preparing, encoding, encoding_retry, finalizing)",
)
progress_percent: float = Field(
default=0.0,
description="Progress percentage of the current step (0.0 - 100.0)",
)
ExportJobsResponse = List[ExportJobModel]
-16
View File
@@ -189,17 +189,6 @@ class FrigateApp:
except PermissionError:
logger.error("Unable to write to /config to save DB state")
def cleanup_timeline_db(db: SqliteExtDatabase) -> None:
db.execute_sql(
"DELETE FROM timeline WHERE source_id NOT IN (SELECT id FROM event);"
)
try:
with open(f"{CONFIG_DIR}/.timeline", "w") as f:
f.write(str(datetime.datetime.now().timestamp()))
except PermissionError:
logger.error("Unable to write to /config to save DB state")
# Migrate DB schema
migrate_db = SqliteExtDatabase(self.config.database.path)
@@ -216,11 +205,6 @@ class FrigateApp:
router.run()
# this is a temporary check to clean up user DB from beta
# will be removed before final release
if not os.path.exists(f"{CONFIG_DIR}/.timeline"):
cleanup_timeline_db(migrate_db)
# check if vacuum needs to be run
if os.path.exists(f"{CONFIG_DIR}/.vacuum"):
with open(f"{CONFIG_DIR}/.vacuum") as f:
+3
View File
@@ -730,6 +730,9 @@ class FrigateConfig(FrigateBaseModel):
)
if need_detect_dimensions:
logger.info(
f"detect.width and detect.height not set for {camera_config.name}, probing detect stream to determine resolution."
)
stream_info = {"width": 0, "height": 0, "fourcc": None}
try:
stream_info = stream_info_retriever.get_stream_info(
+4
View File
@@ -310,6 +310,10 @@ class EmbeddingMaintainer(threading.Thread):
self._handle_custom_classification_update(topic, payload)
return
if topic == "config/genai":
self.config.genai = payload
self.genai_manager.update_config(self.config)
# Broadcast to all processors — each decides if the topic is relevant
for processor in self.realtime_processors:
processor.update_config(topic, payload)
+26 -2
View File
@@ -113,6 +113,15 @@ class OllamaClient(GenAIClient):
schema = response_format.get("json_schema", {}).get("schema")
if schema:
ollama_options["format"] = self._clean_schema_for_ollama(schema)
logger.debug(
"Ollama generate request: model=%s, prompt_len=%s, image_count=%s, "
"has_format=%s, options=%s",
self.genai_config.model,
len(prompt),
len(images) if images else 0,
"format" in ollama_options,
{k: v for k, v in ollama_options.items() if k != "format"},
)
result = self.provider.generate(
self.genai_config.model,
prompt,
@@ -120,9 +129,24 @@ class OllamaClient(GenAIClient):
**ollama_options,
)
logger.debug(
f"Ollama tokens used: eval_count={result.get('eval_count')}, prompt_eval_count={result.get('prompt_eval_count')}"
"Ollama generate response: done=%s, done_reason=%s, eval_count=%s, "
"prompt_eval_count=%s, response_len=%s",
result.get("done"),
result.get("done_reason"),
result.get("eval_count"),
result.get("prompt_eval_count"),
len(result.get("response", "") or ""),
)
return str(result["response"]).strip()
response_text = str(result["response"]).strip()
if not response_text:
logger.warning(
"Ollama returned a blank response for model %s (done_reason=%s, "
"eval_count=%s). Check model output, ensure thinking is disabled.",
self.genai_config.model,
result.get("done_reason"),
result.get("eval_count"),
)
return response_text
except (
TimeoutException,
ResponseError,
+17 -1
View File
@@ -80,7 +80,23 @@ class OpenAIClient(GenAIClient):
and hasattr(result, "choices")
and len(result.choices) > 0
):
return str(result.choices[0].message.content.strip())
message = result.choices[0].message
content = message.content
if not content:
# When reasoning is enabled for some OpenAI backends the actual response
# is incorrectly placed in reasoning_content instead of content.
# This is buggy/incorrect behavior — reasoning should not be
# enabled for these models.
reasoning_content = getattr(message, "reasoning_content", None)
if reasoning_content:
logger.warning(
"Response content was empty but reasoning_content was provided; "
"reasoning appears to be enabled and should be disabled for this model."
)
content = reasoning_content
return str(content.strip()) if content else None
return None
except (TimeoutException, Exception) as e:
logger.warning("OpenAI returned an error: %s", str(e))
+118 -1
View File
@@ -7,11 +7,13 @@ import time
from dataclasses import dataclass
from pathlib import Path
from queue import Full, Queue
from typing import Any, Optional
from typing import Any, Callable, Optional
from peewee import DoesNotExist
from frigate.comms.inter_process import InterProcessRequestor
from frigate.config import FrigateConfig
from frigate.const import UPDATE_JOB_STATE
from frigate.jobs.job import Job
from frigate.models import Export
from frigate.record.export import PlaybackSourceEnum, RecordingExporter
@@ -23,6 +25,16 @@ logger = logging.getLogger(__name__)
# Prevents a runaway client from unbounded memory growth.
MAX_QUEUED_EXPORT_JOBS = 100
# Minimum interval between progress broadcasts. FFmpeg can emit progress
# events many times per second; we coalesce them so the WebSocket isn't
# flooded with redundant updates.
PROGRESS_BROADCAST_MIN_INTERVAL = 1.0
# Delay before removing a completed job from the in-memory map. Gives the
# frontend a chance to receive the final state via WebSocket before SWR
# polling takes over.
COMPLETED_JOB_CLEANUP_DELAY = 5.0
class ExportQueueFullError(RuntimeError):
"""Raised when the export queue is at capacity."""
@@ -43,6 +55,8 @@ class ExportJob(Job):
ffmpeg_input_args: Optional[str] = None
ffmpeg_output_args: Optional[str] = None
cpu_fallback: bool = False
current_step: str = "queued"
progress_percent: float = 0.0
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary for API responses.
@@ -64,6 +78,8 @@ class ExportJob(Job):
"end_time": self.end_time,
"error_message": self.error_message,
"results": self.results,
"current_step": self.current_step,
"progress_percent": self.progress_percent,
}
@@ -91,6 +107,38 @@ class ExportQueueWorker(threading.Thread):
self.manager.queue.task_done()
class JobStatePublisher:
"""Publishes a single job state payload to the dispatcher.
Each call opens a short-lived :py:class:`InterProcessRequestor`, sends
the payload, and closes the socket. The short-lived design avoids
REQ/REP state corruption that would arise from sharing a single REQ
socket across the API thread and worker threads (REQ sockets must
strictly alternate send/recv).
With the 1s broadcast throttle in place, socket creation overhead is
negligible. The class also exists so tests can substitute a no-op
instance instead of stubbing ZMQ — see ``BaseTestHttp.setUp``.
"""
def publish(self, payload: dict[str, Any]) -> None:
try:
requestor = InterProcessRequestor()
except Exception as err:
logger.warning("Failed to open job state requestor: %s", err)
return
try:
requestor.send_data(UPDATE_JOB_STATE, payload)
except Exception as err:
logger.debug("Job state broadcast failed: %s", err)
finally:
try:
requestor.stop()
except Exception:
pass
class ExportJobManager:
"""Concurrency-limited manager for queued export jobs."""
@@ -99,6 +147,7 @@ class ExportJobManager:
config: FrigateConfig,
max_concurrent: int,
max_queued: int = MAX_QUEUED_EXPORT_JOBS,
publisher: Optional[JobStatePublisher] = None,
) -> None:
self.config = config
self.max_concurrent = max(1, max_concurrent)
@@ -107,6 +156,68 @@ class ExportJobManager:
self.lock = threading.Lock()
self.workers: list[ExportQueueWorker] = []
self.started = False
self.publisher = publisher if publisher is not None else JobStatePublisher()
self._last_broadcast_monotonic: float = 0.0
self._broadcast_throttle_lock = threading.Lock()
def _broadcast_all_jobs(self, force: bool = False) -> None:
"""Publish aggregate export job state via the job_state WS topic.
When ``force`` is False, broadcasts within
``PROGRESS_BROADCAST_MIN_INTERVAL`` of the previous one are skipped
to avoid flooding the WebSocket with rapid progress updates.
``force`` bypasses the throttle and is used for status transitions
(enqueue/start/finish) where the frontend needs the latest state.
"""
now = time.monotonic()
with self._broadcast_throttle_lock:
if (
not force
and now - self._last_broadcast_monotonic
< PROGRESS_BROADCAST_MIN_INTERVAL
):
return
self._last_broadcast_monotonic = now
with self.lock:
active = [
j
for j in self.jobs.values()
if j.status in (JobStatusTypesEnum.queued, JobStatusTypesEnum.running)
]
any_running = any(j.status == JobStatusTypesEnum.running for j in active)
payload: dict[str, Any] = {
"job_type": "export",
"status": "running" if any_running else "queued",
"results": {"jobs": [j.to_dict() for j in active]},
}
try:
self.publisher.publish(payload)
except Exception as err:
logger.warning("Publisher raised during job state broadcast: %s", err)
def _make_progress_callback(self, job: ExportJob) -> Callable[[str, float], None]:
"""Build a callback the exporter can invoke during execution."""
def on_progress(step: str, percent: float) -> None:
job.current_step = step
job.progress_percent = percent
self._broadcast_all_jobs()
return on_progress
def _schedule_job_cleanup(self, job_id: str) -> None:
"""Drop a completed job from ``self.jobs`` after a short delay."""
def cleanup() -> None:
with self.lock:
self.jobs.pop(job_id, None)
timer = threading.Timer(COMPLETED_JOB_CLEANUP_DELAY, cleanup)
timer.daemon = True
timer.start()
def ensure_started(self) -> None:
"""Ensure worker threads are started exactly once."""
@@ -151,6 +262,8 @@ class ExportJobManager:
with self.lock:
self.jobs[job.id] = job
self._broadcast_all_jobs(force=True)
return job.id
def get_job(self, job_id: str) -> Optional[ExportJob]:
@@ -215,6 +328,7 @@ class ExportJobManager:
"""Execute a queued export job."""
job.status = JobStatusTypesEnum.running
job.start_time = time.time()
self._broadcast_all_jobs(force=True)
exporter = RecordingExporter(
self.config,
@@ -229,6 +343,7 @@ class ExportJobManager:
job.ffmpeg_input_args,
job.ffmpeg_output_args,
job.cpu_fallback,
on_progress=self._make_progress_callback(job),
)
try:
@@ -257,6 +372,8 @@ class ExportJobManager:
job.error_message = str(err)
finally:
job.end_time = time.time()
self._broadcast_all_jobs(force=True)
self._schedule_job_cleanup(job.id)
_job_manager: Optional[ExportJobManager] = None
+229 -14
View File
@@ -4,13 +4,14 @@ import datetime
import logging
import os
import random
import re
import shutil
import string
import subprocess as sp
import threading
from enum import Enum
from pathlib import Path
from typing import Optional
from typing import Callable, Optional
from peewee import DoesNotExist
@@ -36,6 +37,10 @@ logger = logging.getLogger(__name__)
DEFAULT_TIME_LAPSE_FFMPEG_ARGS = "-vf setpts=0.04*PTS -r 30"
TIMELAPSE_DATA_INPUT_ARGS = "-an -skip_frame nokey"
# Matches the setpts factor used in timelapse exports (e.g. setpts=0.04*PTS).
# Captures the floating-point factor so we can scale expected duration.
SETPTS_FACTOR_RE = re.compile(r"setpts=([0-9]*\.?[0-9]+)\*PTS")
# ffmpeg flags that can read from or write to arbitrary files
BLOCKED_FFMPEG_ARGS = frozenset(
{
@@ -116,6 +121,7 @@ class RecordingExporter(threading.Thread):
ffmpeg_input_args: Optional[str] = None,
ffmpeg_output_args: Optional[str] = None,
cpu_fallback: bool = False,
on_progress: Optional[Callable[[str, float], None]] = None,
) -> None:
super().__init__()
self.config = config
@@ -130,10 +136,213 @@ class RecordingExporter(threading.Thread):
self.ffmpeg_input_args = ffmpeg_input_args
self.ffmpeg_output_args = ffmpeg_output_args
self.cpu_fallback = cpu_fallback
self.on_progress = on_progress
# ensure export thumb dir
Path(os.path.join(CLIPS_DIR, "export")).mkdir(exist_ok=True)
def _emit_progress(self, step: str, percent: float) -> None:
"""Invoke the progress callback if one was supplied."""
if self.on_progress is None:
return
try:
self.on_progress(step, max(0.0, min(100.0, percent)))
except Exception:
logger.exception("Export progress callback failed")
def _expected_output_duration_seconds(self) -> float:
"""Compute the expected duration of the output video in seconds.
Users often request a wide time range (e.g. a full hour) when only
a few minutes of recordings actually live on disk for that span,
so the requested range overstates the work and progress would
plateau very early. We sum the actual saved seconds from the
Recordings/Previews tables and use that as the input duration.
Timelapse exports then scale this by the setpts factor.
"""
requested_duration = max(0.0, float(self.end_time - self.start_time))
recorded = self._sum_source_duration_seconds()
input_duration = (
recorded if recorded is not None and recorded > 0 else requested_duration
)
if not self.ffmpeg_output_args:
return input_duration
match = SETPTS_FACTOR_RE.search(self.ffmpeg_output_args)
if match is None:
return input_duration
try:
factor = float(match.group(1))
except ValueError:
return input_duration
if factor <= 0:
return input_duration
return input_duration * factor
def _sum_source_duration_seconds(self) -> Optional[float]:
"""Sum saved-video seconds inside [start_time, end_time].
Queries Recordings or Previews depending on the playback source,
clamps each segment to the requested range, and returns the total.
Returns ``None`` on any error so the caller can fall back to the
requested range duration without losing progress reporting.
"""
try:
if self.playback_source == PlaybackSourceEnum.recordings:
rows = (
Recordings.select(Recordings.start_time, Recordings.end_time)
.where(
Recordings.start_time.between(self.start_time, self.end_time)
| Recordings.end_time.between(self.start_time, self.end_time)
| (
(self.start_time > Recordings.start_time)
& (self.end_time < Recordings.end_time)
)
)
.where(Recordings.camera == self.camera)
.iterator()
)
else:
rows = (
Previews.select(Previews.start_time, Previews.end_time)
.where(
Previews.start_time.between(self.start_time, self.end_time)
| Previews.end_time.between(self.start_time, self.end_time)
| (
(self.start_time > Previews.start_time)
& (self.end_time < Previews.end_time)
)
)
.where(Previews.camera == self.camera)
.iterator()
)
except Exception:
logger.exception(
"Failed to sum source duration for export %s", self.export_id
)
return None
total = 0.0
try:
for row in rows:
clipped_start = max(float(row.start_time), float(self.start_time))
clipped_end = min(float(row.end_time), float(self.end_time))
if clipped_end > clipped_start:
total += clipped_end - clipped_start
except Exception:
logger.exception(
"Failed to read recording rows for export %s", self.export_id
)
return None
return total
def _inject_progress_flags(self, ffmpeg_cmd: list[str]) -> list[str]:
"""Insert FFmpeg progress reporting flags before the output path.
``-progress pipe:2`` writes structured key=value lines to stderr,
``-nostats`` suppresses the noisy default stats output.
"""
if not ffmpeg_cmd:
return ffmpeg_cmd
return ffmpeg_cmd[:-1] + ["-progress", "pipe:2", "-nostats", ffmpeg_cmd[-1]]
def _run_ffmpeg_with_progress(
self,
ffmpeg_cmd: list[str],
playlist_lines: str | list[str],
step: str = "encoding",
) -> tuple[int, str]:
"""Run an FFmpeg export command, parsing progress events from stderr.
Returns ``(returncode, captured_stderr)``. Stdout is left attached to
the parent process so we don't have to drain it (and risk a deadlock
if the buffer fills). Progress percent is computed against the
expected output duration; values are clamped to [0, 100] inside
:py:meth:`_emit_progress`.
"""
cmd = ["nice", "-n", str(PROCESS_PRIORITY_LOW)] + self._inject_progress_flags(
ffmpeg_cmd
)
if isinstance(playlist_lines, list):
stdin_payload = "\n".join(playlist_lines)
else:
stdin_payload = playlist_lines
expected_duration = self._expected_output_duration_seconds()
self._emit_progress(step, 0.0)
proc = sp.Popen(
cmd,
stdin=sp.PIPE,
stderr=sp.PIPE,
text=True,
encoding="ascii",
errors="replace",
)
assert proc.stdin is not None
assert proc.stderr is not None
try:
proc.stdin.write(stdin_payload)
except (BrokenPipeError, OSError):
# FFmpeg may have rejected the input early; still wait for it
# to terminate so the returncode is meaningful.
pass
finally:
try:
proc.stdin.close()
except (BrokenPipeError, OSError):
pass
captured: list[str] = []
try:
for raw_line in proc.stderr:
captured.append(raw_line)
line = raw_line.strip()
if not line:
continue
if line.startswith("out_time_us="):
if expected_duration <= 0:
continue
try:
out_time_us = int(line.split("=", 1)[1])
except (ValueError, IndexError):
continue
if out_time_us < 0:
continue
out_seconds = out_time_us / 1_000_000.0
percent = (out_seconds / expected_duration) * 100.0
self._emit_progress(step, percent)
elif line == "progress=end":
self._emit_progress(step, 100.0)
break
except Exception:
logger.exception("Failed reading FFmpeg progress for %s", self.export_id)
proc.wait()
# Drain any remaining stderr so callers can log it on failure.
try:
remaining = proc.stderr.read()
if remaining:
captured.append(remaining)
except Exception:
pass
return proc.returncode, "".join(captured)
def get_datetime_from_timestamp(self, timestamp: int) -> str:
# return in iso format
return datetime.datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
@@ -406,6 +615,7 @@ class RecordingExporter(threading.Thread):
logger.debug(
f"Beginning export for {self.camera} from {self.start_time} to {self.end_time}"
)
self._emit_progress("preparing", 0.0)
export_name = (
self.user_provided_name
or f"{self.camera.replace('_', ' ')} {self.get_datetime_from_timestamp(self.start_time)} {self.get_datetime_from_timestamp(self.end_time)}"
@@ -443,16 +653,23 @@ class RecordingExporter(threading.Thread):
except DoesNotExist:
return
p = sp.run(
["nice", "-n", str(PROCESS_PRIORITY_LOW)] + ffmpeg_cmd,
input="\n".join(playlist_lines),
encoding="ascii",
capture_output=True,
# When neither custom ffmpeg arg is set the default path uses
# `-c copy` (stream copy — no re-encoding). Report that as a
# distinct step so the UI doesn't mislabel a remux as encoding.
# The retry branch below always re-encodes because cpu_fallback
# requires custom args; it stays "encoding_retry".
is_stream_copy = (
self.ffmpeg_input_args is None and self.ffmpeg_output_args is None
)
initial_step = "copying" if is_stream_copy else "encoding"
returncode, stderr = self._run_ffmpeg_with_progress(
ffmpeg_cmd, playlist_lines, step=initial_step
)
# If export failed and cpu_fallback is enabled, retry without hwaccel
if (
p.returncode != 0
returncode != 0
and self.cpu_fallback
and self.ffmpeg_input_args is not None
and self.ffmpeg_output_args is not None
@@ -470,23 +687,21 @@ class RecordingExporter(threading.Thread):
video_path, use_hwaccel=False
)
p = sp.run(
["nice", "-n", str(PROCESS_PRIORITY_LOW)] + ffmpeg_cmd,
input="\n".join(playlist_lines),
encoding="ascii",
capture_output=True,
returncode, stderr = self._run_ffmpeg_with_progress(
ffmpeg_cmd, playlist_lines, step="encoding_retry"
)
if p.returncode != 0:
if returncode != 0:
logger.error(
f"Failed to export {self.playback_source.value} for command {' '.join(ffmpeg_cmd)}"
)
logger.error(p.stderr)
logger.error(stderr)
Path(video_path).unlink(missing_ok=True)
Export.delete().where(Export.id == self.export_id).execute()
Path(thumb_path).unlink(missing_ok=True)
return
else:
self._emit_progress("finalizing", 100.0)
Export.update({Export.in_progress: False}).where(
Export.id == self.export_id
).execute()
+6 -4
View File
@@ -464,10 +464,12 @@ class RecordingMaintainer(threading.Thread):
self.drop_segment(cache_path)
return None
# if it doesn't overlap with an review item, go ahead and drop the segment
# if it ends more than the configured pre_capture for the camera
# BUT only if continuous/motion is NOT enabled (otherwise wait for processing)
elif highest is None:
# if it doesn't overlap with a review item, drop the segment once it
# ends more than event_pre_capture before the most recently processed
# frame. at this point we've already decided not to keep it for
# continuous/motion retention (either disabled or segment_stats said
# discard), so waiting longer just fills the cache.
else:
camera_info = self.object_recordings_info[camera]
most_recently_processed_frame_time = (
camera_info[-1][0] if len(camera_info) > 0 else 0
+2 -2
View File
@@ -197,7 +197,7 @@ class StorageMaintainer(threading.Thread):
# check if need to delete retained segments
if deleted_segments_size < hourly_bandwidth:
logger.error(
f"Could not clear {hourly_bandwidth} MB, currently {deleted_segments_size} MB have been cleared. Retained recordings must be deleted."
f"Could not clear {hourly_bandwidth} MB, currently {deleted_segments_size:.2f} MB have been cleared. Retained recordings must be deleted."
)
recordings = (
Recordings.select(
@@ -225,7 +225,7 @@ class StorageMaintainer(threading.Thread):
# this file was not found so we must assume no space was cleaned up
pass
else:
logger.info(f"Cleaned up {deleted_segments_size} MB of recordings")
logger.info(f"Cleaned up {deleted_segments_size:.2f} MB of recordings")
logger.debug(f"Expiring {len(deleted_recordings)} recordings")
# delete up to 100,000 at a time
+15
View File
@@ -2,6 +2,7 @@ import datetime
import logging
import os
import unittest
from unittest.mock import patch
from fastapi import Request
from fastapi.testclient import TestClient
@@ -14,6 +15,7 @@ from frigate.api.fastapi_app import create_fastapi_app
from frigate.config import FrigateConfig
from frigate.const import BASE_DIR, CACHE_DIR
from frigate.debug_replay import DebugReplayManager
from frigate.jobs.export import JobStatePublisher
from frigate.models import Event, Recordings, ReviewSegment
from frigate.review.types import SeverityEnum
from frigate.test.const import TEST_DB, TEST_DB_CLEANUPS
@@ -44,6 +46,19 @@ class BaseTestHttp(unittest.TestCase):
self.db = SqliteQueueDatabase(TEST_DB)
self.db.bind(models)
# The export job manager broadcasts via JobStatePublisher on
# enqueue/start/finish. There is no dispatcher process bound to
# the IPC socket in tests, so a real publish() would block on
# recv_json forever. Replace publish with a no-op for the
# lifetime of this test; the lookup goes through the class so any
# already-instantiated publisher (the singleton manager's) picks
# up the no-op too.
publisher_patch = patch.object(
JobStatePublisher, "publish", lambda self, payload: None
)
publisher_patch.start()
self.addCleanup(publisher_patch.stop)
self.minimal_config = {
"mqtt": {"host": "mqtt"},
"cameras": {
+385
View File
@@ -0,0 +1,385 @@
"""Tests for export progress tracking, broadcast, and FFmpeg parsing."""
import io
import unittest
from unittest.mock import MagicMock, patch
from frigate.jobs.export import (
PROGRESS_BROADCAST_MIN_INTERVAL,
ExportJob,
ExportJobManager,
)
from frigate.record.export import PlaybackSourceEnum, RecordingExporter
from frigate.types import JobStatusTypesEnum
def _make_exporter(
end_minus_start: int = 100,
ffmpeg_input_args=None,
ffmpeg_output_args=None,
on_progress=None,
) -> RecordingExporter:
"""Build a RecordingExporter without invoking its real __init__ side
effects (which create directories and require a full FrigateConfig)."""
exporter = RecordingExporter.__new__(RecordingExporter)
exporter.config = MagicMock()
exporter.export_id = "test_export"
exporter.camera = "front"
exporter.user_provided_name = None
exporter.user_provided_image = None
exporter.start_time = 1_000
exporter.end_time = 1_000 + end_minus_start
exporter.playback_source = PlaybackSourceEnum.recordings
exporter.export_case_id = None
exporter.ffmpeg_input_args = ffmpeg_input_args
exporter.ffmpeg_output_args = ffmpeg_output_args
exporter.cpu_fallback = False
exporter.on_progress = on_progress
return exporter
class TestExportJobToDict(unittest.TestCase):
def test_to_dict_includes_progress_fields(self) -> None:
job = ExportJob(camera="front", request_start_time=0, request_end_time=10)
result = job.to_dict()
assert "current_step" in result
assert "progress_percent" in result
assert result["current_step"] == "queued"
assert result["progress_percent"] == 0.0
def test_to_dict_reflects_updated_progress(self) -> None:
job = ExportJob(camera="front", request_start_time=0, request_end_time=10)
job.current_step = "encoding"
job.progress_percent = 42.5
result = job.to_dict()
assert result["current_step"] == "encoding"
assert result["progress_percent"] == 42.5
class TestExpectedOutputDuration(unittest.TestCase):
def test_normal_export_uses_input_duration(self) -> None:
exporter = _make_exporter(end_minus_start=600)
assert exporter._expected_output_duration_seconds() == 600.0
def test_timelapse_uses_setpts_factor(self) -> None:
exporter = _make_exporter(
end_minus_start=1000,
ffmpeg_input_args="-y",
ffmpeg_output_args="-vf setpts=0.04*PTS -r 30",
)
# 1000s input * 0.04 = 40s of output
assert exporter._expected_output_duration_seconds() == 40.0
def test_unknown_factor_falls_back_to_input_duration(self) -> None:
exporter = _make_exporter(
end_minus_start=300,
ffmpeg_input_args="-y",
ffmpeg_output_args="-c:v libx264 -preset veryfast",
)
assert exporter._expected_output_duration_seconds() == 300.0
def test_zero_factor_falls_back_to_input_duration(self) -> None:
exporter = _make_exporter(
end_minus_start=300,
ffmpeg_input_args="-y",
ffmpeg_output_args="-vf setpts=0*PTS",
)
assert exporter._expected_output_duration_seconds() == 300.0
def test_uses_actual_recorded_seconds_when_available(self) -> None:
"""If the DB shows only 120s of saved recordings inside a 1h
requested range, progress should be computed against 120s."""
exporter = _make_exporter(end_minus_start=3600)
exporter._sum_source_duration_seconds = lambda: 120.0 # type: ignore[method-assign]
assert exporter._expected_output_duration_seconds() == 120.0
def test_actual_recorded_seconds_scaled_by_setpts(self) -> None:
"""Recorded duration must still be scaled by the timelapse factor."""
exporter = _make_exporter(
end_minus_start=3600,
ffmpeg_input_args="-y",
ffmpeg_output_args="-vf setpts=0.04*PTS -r 30",
)
exporter._sum_source_duration_seconds = lambda: 600.0 # type: ignore[method-assign]
# 600s * 0.04 = 24s of output
assert exporter._expected_output_duration_seconds() == 24.0
def test_db_failure_falls_back_to_requested_range(self) -> None:
exporter = _make_exporter(end_minus_start=300)
exporter._sum_source_duration_seconds = lambda: None # type: ignore[method-assign]
assert exporter._expected_output_duration_seconds() == 300.0
class TestProgressFlagInjection(unittest.TestCase):
def test_inserts_before_output_path(self) -> None:
exporter = _make_exporter()
cmd = ["ffmpeg", "-i", "input.m3u8", "-c", "copy", "/tmp/output.mp4"]
result = exporter._inject_progress_flags(cmd)
assert result == [
"ffmpeg",
"-i",
"input.m3u8",
"-c",
"copy",
"-progress",
"pipe:2",
"-nostats",
"/tmp/output.mp4",
]
def test_handles_empty_cmd(self) -> None:
exporter = _make_exporter()
assert exporter._inject_progress_flags([]) == []
class TestFfmpegProgressParsing(unittest.TestCase):
"""Verify percentage calculation from FFmpeg ``-progress`` output."""
def _run_with_stderr(
self,
stderr_text: str,
expected_duration_seconds: int = 90,
) -> list[tuple[str, float]]:
"""Helper: run _run_ffmpeg_with_progress against a mocked Popen
whose stderr emits the supplied text. Returns the list of
(step, percent) tuples that the on_progress callback received."""
captured: list[tuple[str, float]] = []
def on_progress(step: str, percent: float) -> None:
captured.append((step, percent))
exporter = _make_exporter(
end_minus_start=expected_duration_seconds,
on_progress=on_progress,
)
fake_proc = MagicMock()
fake_proc.stdin = io.StringIO()
fake_proc.stderr = io.StringIO(stderr_text)
fake_proc.returncode = 0
fake_proc.wait = MagicMock(return_value=0)
with patch("frigate.record.export.sp.Popen", return_value=fake_proc):
returncode, _stderr = exporter._run_ffmpeg_with_progress(
["ffmpeg", "-i", "x.m3u8", "/tmp/out.mp4"], "playlist", step="encoding"
)
assert returncode == 0
return captured
def test_parses_out_time_us_into_percent(self) -> None:
# 90s duration; 45s out_time => 50%
stderr = "out_time_us=45000000\nprogress=continue\n"
captured = self._run_with_stderr(stderr, expected_duration_seconds=90)
# The first call is the synchronous 0.0 emit before Popen runs.
assert captured[0] == ("encoding", 0.0)
assert any(percent == 50.0 for step, percent in captured if step == "encoding")
def test_progress_end_emits_100_percent(self) -> None:
stderr = "out_time_us=10000000\nprogress=end\n"
captured = self._run_with_stderr(stderr, expected_duration_seconds=90)
assert captured[-1] == ("encoding", 100.0)
def test_clamps_overshoot_at_100(self) -> None:
# 150s of output reported against 90s expected duration.
stderr = "out_time_us=150000000\nprogress=continue\n"
captured = self._run_with_stderr(stderr, expected_duration_seconds=90)
encoding_values = [p for s, p in captured if s == "encoding" and p > 0]
assert all(p <= 100.0 for p in encoding_values)
assert encoding_values[-1] == 100.0
def test_ignores_garbage_lines(self) -> None:
stderr = (
"frame= 120 fps= 30 q=23.0 size= 512kB\n"
"out_time_us=not-a-number\n"
"out_time_us=30000000\n"
"progress=continue\n"
)
captured = self._run_with_stderr(stderr, expected_duration_seconds=90)
# We expect 0.0 (from initial emit) plus the 30s/90s = 33.33...% step
encoding_percents = sorted({round(p, 2) for s, p in captured})
assert 0.0 in encoding_percents
assert any(abs(p - (30 / 90 * 100)) < 0.01 for p in encoding_percents)
class TestBroadcastAggregation(unittest.TestCase):
"""Verify ExportJobManager broadcast payload shape and throttling."""
def _make_manager(self) -> tuple[ExportJobManager, MagicMock]:
"""Build a manager with an injected mock publisher. Returns
``(manager, publisher)`` so tests can assert on broadcast payloads
without touching ZMQ at all."""
config = MagicMock()
publisher = MagicMock()
manager = ExportJobManager(
config, max_concurrent=2, max_queued=10, publisher=publisher
)
return manager, publisher
@staticmethod
def _last_payload(publisher: MagicMock) -> dict:
return publisher.publish.call_args.args[0]
def test_empty_jobs_broadcasts_empty_list(self) -> None:
manager, publisher = self._make_manager()
manager._broadcast_all_jobs(force=True)
publisher.publish.assert_called_once()
payload = self._last_payload(publisher)
assert payload["job_type"] == "export"
assert payload["status"] == "queued"
assert payload["results"]["jobs"] == []
def test_single_running_job_payload(self) -> None:
manager, publisher = self._make_manager()
job = ExportJob(camera="front", request_start_time=0, request_end_time=10)
job.status = JobStatusTypesEnum.running
job.current_step = "encoding"
job.progress_percent = 75.0
manager.jobs[job.id] = job
manager._broadcast_all_jobs(force=True)
payload = self._last_payload(publisher)
assert payload["status"] == "running"
assert len(payload["results"]["jobs"]) == 1
broadcast_job = payload["results"]["jobs"][0]
assert broadcast_job["current_step"] == "encoding"
assert broadcast_job["progress_percent"] == 75.0
def test_multiple_jobs_broadcast(self) -> None:
manager, publisher = self._make_manager()
for i, status in enumerate(
(JobStatusTypesEnum.queued, JobStatusTypesEnum.running)
):
job = ExportJob(
id=f"job_{i}",
camera="front",
request_start_time=0,
request_end_time=10,
)
job.status = status
manager.jobs[job.id] = job
manager._broadcast_all_jobs(force=True)
payload = self._last_payload(publisher)
assert payload["status"] == "running"
assert len(payload["results"]["jobs"]) == 2
def test_completed_jobs_are_excluded(self) -> None:
manager, publisher = self._make_manager()
active = ExportJob(id="active", camera="front")
active.status = JobStatusTypesEnum.running
finished = ExportJob(id="done", camera="front")
finished.status = JobStatusTypesEnum.success
manager.jobs[active.id] = active
manager.jobs[finished.id] = finished
manager._broadcast_all_jobs(force=True)
payload = self._last_payload(publisher)
ids = [j["id"] for j in payload["results"]["jobs"]]
assert ids == ["active"]
def test_throttle_skips_rapid_unforced_broadcasts(self) -> None:
manager, publisher = self._make_manager()
job = ExportJob(camera="front")
job.status = JobStatusTypesEnum.running
manager.jobs[job.id] = job
manager._broadcast_all_jobs(force=True)
# Immediately following non-forced broadcasts should be skipped.
for _ in range(5):
manager._broadcast_all_jobs(force=False)
assert publisher.publish.call_count == 1
def test_throttle_allows_broadcast_after_interval(self) -> None:
manager, publisher = self._make_manager()
job = ExportJob(camera="front")
job.status = JobStatusTypesEnum.running
manager.jobs[job.id] = job
with patch("frigate.jobs.export.time.monotonic") as mock_mono:
mock_mono.return_value = 100.0
manager._broadcast_all_jobs(force=True)
mock_mono.return_value = 100.0 + PROGRESS_BROADCAST_MIN_INTERVAL + 0.01
manager._broadcast_all_jobs(force=False)
assert publisher.publish.call_count == 2
def test_force_bypasses_throttle(self) -> None:
manager, publisher = self._make_manager()
job = ExportJob(camera="front")
job.status = JobStatusTypesEnum.running
manager.jobs[job.id] = job
manager._broadcast_all_jobs(force=True)
manager._broadcast_all_jobs(force=True)
assert publisher.publish.call_count == 2
def test_publisher_exceptions_do_not_propagate(self) -> None:
"""A failing publisher must not break the manager: broadcasts are
best-effort since the dispatcher may not be available (tests,
startup races)."""
manager, publisher = self._make_manager()
publisher.publish.side_effect = RuntimeError("comms down")
job = ExportJob(camera="front")
job.status = JobStatusTypesEnum.running
manager.jobs[job.id] = job
# Swallow our own RuntimeError if the manager doesn't; the real
# JobStatePublisher handles its own exceptions internally, so the
# manager can stay naive. But if something bubbles up it should
# not escape _broadcast_all_jobs — enforce that contract here.
try:
manager._broadcast_all_jobs(force=True)
except RuntimeError:
self.fail("_broadcast_all_jobs must tolerate publisher failures")
def test_progress_callback_updates_job_and_broadcasts(self) -> None:
manager, _publisher = self._make_manager()
job = ExportJob(camera="front")
job.status = JobStatusTypesEnum.running
manager.jobs[job.id] = job
callback = manager._make_progress_callback(job)
callback("encoding", 33.0)
assert job.current_step == "encoding"
assert job.progress_percent == 33.0
class TestSchedulesCleanup(unittest.TestCase):
def test_schedule_job_cleanup_removes_after_delay(self) -> None:
config = MagicMock()
manager = ExportJobManager(config, max_concurrent=1, max_queued=1)
job = ExportJob(id="cleanup_me", camera="front")
manager.jobs[job.id] = job
with patch("frigate.jobs.export.threading.Timer") as mock_timer:
manager._schedule_job_cleanup(job.id)
mock_timer.assert_called_once()
delay, fn = mock_timer.call_args.args
assert delay > 0
# Invoke the callback directly to confirm it removes the job.
fn()
assert job.id not in manager.jobs
if __name__ == "__main__":
unittest.main()
+41
View File
@@ -1,3 +1,4 @@
import datetime
import sys
import unittest
from unittest.mock import MagicMock, patch
@@ -74,6 +75,46 @@ class TestMaintainer(unittest.IsolatedAsyncioTestCase):
f"Expected a single warning for unexpected files, got {len(matching)}",
)
async def test_drops_quiet_segment_when_only_motion_retention(self):
# Regression: when motion retention is enabled but a segment has no
# motion and no review overlaps it, the segment must still be dropped.
# Otherwise it sits in cache forever, accumulates, and triggers the
# "Unable to keep up with recording segments in cache" warning every
# ~10s as the overflow trim in move_files discards the oldest one.
config = MagicMock(spec=FrigateConfig)
camera_config = MagicMock()
camera_config.record.enabled = True
camera_config.record.continuous.days = 0
camera_config.record.motion.days = 1
camera_config.record.event_pre_capture = 5
config.cameras = {"test_cam": camera_config}
stop_event = MagicMock()
maintainer = RecordingMaintainer(config, stop_event)
now = datetime.datetime.now(datetime.timezone.utc)
start_time = now - datetime.timedelta(seconds=20)
end_time = now - datetime.timedelta(seconds=10)
cache_path = "/tmp/cache/test_cam@20260417150000+0000.mp4"
maintainer.end_time_cache = {cache_path: (end_time, 10.0)}
# Single processed frame well past end_time with no motion/objects.
maintainer.object_recordings_info["test_cam"] = [(now.timestamp(), [], [], [])]
maintainer.audio_recordings_info["test_cam"] = []
maintainer.drop_segment = MagicMock()
maintainer.recordings_publisher = MagicMock()
result = await maintainer.validate_and_move_segment(
"test_cam",
reviews=[],
recording={"start_time": start_time, "cache_path": cache_path},
)
self.assertIsNone(result)
maintainer.drop_segment.assert_called_once_with(cache_path)
if __name__ == "__main__":
unittest.main()
+25 -6
View File
@@ -807,10 +807,15 @@ async def get_video_properties(
) -> dict[str, Any]:
async def probe_with_ffprobe(
url: str,
rtsp_transport: Optional[str] = None,
) -> tuple[bool, int, int, Optional[str], float]:
"""Fallback using ffprobe: returns (valid, width, height, codec, duration)."""
cmd = [
ffmpeg.ffprobe_path,
cmd = [ffmpeg.ffprobe_path]
if rtsp_transport:
cmd += ["-rtsp_transport", rtsp_transport]
cmd += [
"-rw_timeout",
"5000000",
"-v",
"quiet",
"-print_format",
@@ -872,12 +877,26 @@ async def get_video_properties(
cap.release()
return valid, width, height, fourcc, duration
# try cv2 first
has_video, width, height, fourcc, duration = probe_with_cv2(url)
is_rtsp = url.startswith("rtsp://")
# fallback to ffprobe if needed
if not has_video or (get_duration and duration < 0):
if is_rtsp:
# skip cv2 for RTSP: its FFmpeg backend has a hardcoded ~30s internal
# timeout that cannot be shortened per-call, and ffprobe bounded by
# -rw_timeout handles RTSP probing reliably
has_video, width, height, fourcc, duration = await probe_with_ffprobe(url)
else:
# try cv2 first for local files, HTTP, RTMP
has_video, width, height, fourcc, duration = probe_with_cv2(url)
# fallback to ffprobe if needed
if not has_video or (get_duration and duration < 0):
has_video, width, height, fourcc, duration = await probe_with_ffprobe(url)
# last resort for RTSP: try TCP transport, since default UDP may be blocked
if (not has_video or (get_duration and duration < 0)) and is_rtsp:
has_video, width, height, fourcc, duration = await probe_with_ffprobe(
url, rtsp_transport="tcp"
)
result: dict[str, Any] = {"has_valid_video": has_video}
if has_video:
@@ -0,0 +1,54 @@
/**
* Debug replay status factory.
*
* The Replay page polls /api/debug_replay/status every 1s via SWR.
* The no-session state shows an empty state; the active state
* renders the live camera image + debug toggles + objects/messages
* tabs. Used by replay.spec.ts.
*/
export type DebugReplayStatus = {
active: boolean;
replay_camera: string | null;
source_camera: string | null;
start_time: number | null;
end_time: number | null;
live_ready: boolean;
};
export function noSessionStatus(): DebugReplayStatus {
return {
active: false,
replay_camera: null,
source_camera: null,
start_time: null,
end_time: null,
live_ready: false,
};
}
export function activeSessionStatus(
opts: {
camera?: string;
sourceCamera?: string;
startTime?: number;
endTime?: number;
liveReady?: boolean;
} = {},
): DebugReplayStatus {
const {
camera = "front_door",
sourceCamera = "front_door",
startTime = Date.now() / 1000 - 3600,
endTime = Date.now() / 1000 - 1800,
liveReady = true,
} = opts;
return {
active: true,
replay_camera: camera,
source_camera: sourceCamera,
start_time: startTime,
end_time: endTime,
live_ready: liveReady,
};
}
+45
View File
@@ -0,0 +1,45 @@
/**
* Face library factories.
*
* The /api/faces endpoint returns a record keyed by collection name
* with the list of face image filenames. Grouped training attempts
* live under the "train" key with filenames of the form
* `${event_id}-${timestamp}-${label}-${score}.webp`.
*
* Used by face-library.spec.ts and chat.spec.ts (attachment chip).
*/
export type FacesMock = Record<string, string[]>;
export function basicFacesMock(): FacesMock {
return {
alice: ["alice-1.webp", "alice-2.webp"],
bob: ["bob-1.webp"],
charlie: ["charlie-1.webp"],
};
}
export function emptyFacesMock(): FacesMock {
return {};
}
/**
* Adds a grouped recent-recognition training attempt to an existing
* faces mock. The grouping key on the backend is the event id — so
* images with the same event-id prefix render as one dialog-able card.
*/
export function withGroupedTrainingAttempt(
base: FacesMock,
opts: {
eventId: string;
attempts: Array<{ timestamp: number; label: string; score: number }>;
},
): FacesMock {
const trainImages = opts.attempts.map(
(a) => `${opts.eventId}-${a.timestamp}-${a.label}-${a.score}.webp`,
);
return {
...base,
train: [...(base.train ?? []), ...trainImages],
};
}
+4 -3
View File
@@ -113,11 +113,12 @@ export class ApiMocker {
route.fulfill({ json: [] }),
);
// Sub-labels and attributes (for explore filters)
await this.page.route("**/api/sub_labels", (route) =>
// Sub-labels and attributes (for explore filters).
// Use trailing ** so query-string variants (e.g. ?split_joined=1) match.
await this.page.route("**/api/sub_labels**", (route) =>
route.fulfill({ json: [] }),
);
await this.page.route("**/api/labels", (route) =>
await this.page.route("**/api/labels**", (route) =>
route.fulfill({ json: ["person", "car"] }),
);
await this.page.route("**/api/*/attributes", (route) =>
+25
View File
@@ -0,0 +1,25 @@
/**
* Clipboard read helper for e2e tests.
*
* Clipboard API requires a browser permission in headless mode.
* grantClipboardPermissions() must be called before any readClipboard()
* attempt. Used by logs.spec.ts (Copy button) and config-editor.spec.ts
* (Copy button).
*/
import type { BrowserContext, Page } from "@playwright/test";
/**
* Grant clipboard-read + clipboard-write permissions on the context.
* Call in beforeEach or at the top of a test before the Copy action.
*/
export async function grantClipboardPermissions(
context: BrowserContext,
): Promise<void> {
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
}
/** Read the current clipboard contents via the page's navigator.clipboard. */
export async function readClipboard(page: Page): Promise<string> {
return page.evaluate(async () => await navigator.clipboard.readText());
}
+58
View File
@@ -0,0 +1,58 @@
/**
* Monaco editor DOM helpers for e2e tests.
*
* Monaco is imported as a module-local object in the app and is NOT
* exposed on window; we drive + read through the rendered DOM and
* keyboard instead. Used by config-editor.spec.ts only.
*/
import { expect, type Page } from "@playwright/test";
/**
* Returns the current visible text of the first Monaco editor on the
* page. Monaco virtualizes long files — this reads only the rendered
* lines. For short configs (our mocks) that's the full content.
*/
export async function getMonacoVisibleText(page: Page): Promise<string> {
return page.locator(".monaco-editor .view-lines").first().innerText();
}
/**
* Focus the editor and replace its full content with `value` via
* keyboard. Uses Ctrl+A (Cmd+A on macOS Playwright is equivalent)
* + Delete + type. Works cross-platform because Playwright normalizes.
*/
export async function replaceMonacoValue(
page: Page,
value: string,
): Promise<void> {
const editor = page.locator(".monaco-editor").first();
await editor.click();
await page.keyboard.press("ControlOrMeta+A");
await page.keyboard.press("Delete");
// Use `type` with zero delay — Monaco handles each key.
await page.keyboard.type(value, { delay: 0 });
}
/**
* Returns true when the editor shows at least one error-severity
* marker. Monaco renders error underlines as `.squiggly-error` in
* the `.view-overlays` layer.
*/
export async function hasErrorMarkers(page: Page): Promise<boolean> {
const count = await page.locator(".monaco-editor .squiggly-error").count();
return count > 0;
}
/**
* Poll until an error marker appears. Monaco schedules marker updates
* asynchronously after content changes (debounce + schema validation).
*/
export async function waitForErrorMarker(
page: Page,
timeoutMs: number = 10_000,
): Promise<void> {
await expect
.poll(() => hasErrorMarkers(page), { timeout: timeoutMs })
.toBe(true);
}
+41
View File
@@ -0,0 +1,41 @@
/**
* Overlay interaction helpers for Radix-based UI tests.
*
* These helpers exist to guard the class of bugs fixed by de-duping
* `@radix-ui/react-dismissable-layer` across the tree: body pointer-events
* getting stuck, dropdown typeahead breaking, tooltips re-popping after a
* dropdown closes, and related nested-overlay regressions.
*/
import { expect, type Page } from "@playwright/test";
/**
* Assert that `<body>` is interactive (no stuck `pointer-events: none`).
*
* Call after closing any overlay. This is the fast secondary assertion —
* test specs should also assert a user-visible behavior like "a button
* responded to a click" so the test fails on meaningful breakage rather
* than just a CSS invariant.
*/
export async function expectBodyInteractive(page: Page) {
const stuck = await page.evaluate(
() => document.body.style.pointerEvents === "none",
);
expect(stuck, "body.style.pointer-events stuck after overlay close").toBe(
false,
);
}
/**
* Wait until the `<body>` is no longer marked with `pointer-events: none`.
*
* Useful right after closing an overlay when Radix's cleanup runs in the
* next frame. Throws if the style does not clear within `timeoutMs`.
*/
export async function waitForBodyInteractive(page: Page, timeoutMs = 2000) {
await page.waitForFunction(
() => document.body.style.pointerEvents !== "none",
null,
{ timeout: timeoutMs },
);
}
+65
View File
@@ -0,0 +1,65 @@
/**
* WebSocket frame capture helper.
*
* The ws-mocker intercepts the /ws route, so Playwright's page-level
* `websocket` event never fires. This helper patches client-side
* WebSocket.prototype.send before any app code runs and mirrors every
* sent frame into a window-level array the test can read back.
*
* Used by live.spec.ts (feature toggles, PTZ preset commands) and
* config-editor.spec.ts (restart command via useRestart).
*/
import { expect, type Page } from "@playwright/test";
export type CapturedFrame = string;
declare global {
interface Window {
__sentWsFrames: CapturedFrame[];
}
}
/**
* Patch WebSocket.prototype.send to capture every outbound frame into
* window.__sentWsFrames. Must be called BEFORE page.goto().
*/
export async function installWsFrameCapture(page: Page): Promise<void> {
await page.addInitScript(() => {
window.__sentWsFrames = [];
const origSend = WebSocket.prototype.send;
WebSocket.prototype.send = function (data) {
try {
window.__sentWsFrames.push(
typeof data === "string" ? data : "(binary)",
);
} catch {
// ignore — best-effort tracing
}
return origSend.call(this, data);
};
});
}
/** Read all captured frames at call time. */
export async function readWsFrames(page: Page): Promise<CapturedFrame[]> {
return page.evaluate(() => window.__sentWsFrames ?? []);
}
/**
* Poll until at least one captured frame matches the predicate.
* Throws via expect if the frame never arrives within timeout.
*/
export async function waitForWsFrame(
page: Page,
matcher: (frame: CapturedFrame) => boolean,
opts: { timeout?: number; message?: string } = {},
): Promise<void> {
const { timeout = 2_000, message } = opts;
await expect
.poll(async () => (await readWsFrames(page)).some(matcher), {
timeout,
message,
})
.toBe(true);
}
+14 -1
View File
@@ -79,7 +79,20 @@ export class WsMocker {
this.send("model_state", JSON.stringify({}));
}
if (data.topic === "embeddingsReindexProgress") {
this.send("embeddings_reindex_progress", JSON.stringify(null));
// Send a completed reindex state so Explore renders when
// semantic_search.enabled is true. A null payload leaves the page
// in a permanent loading spinner because !reindexState is truthy.
this.send(
"embeddings_reindex_progress",
JSON.stringify({
status: "completed",
processed_objects: 0,
total_objects: 0,
thumbnails: 0,
descriptions: 0,
time_remaining: null,
}),
);
}
if (data.topic === "birdseyeLayout") {
this.send("birdseye_layout", JSON.stringify(null));
+55
View File
@@ -0,0 +1,55 @@
/**
* Live dashboard + single-camera page object.
*
* Encapsulates selectors and viewport-conditional openers for the
* Live route. Does NOT own assertions — specs call expect on the
* locators returned from these getters.
*/
import type { Locator, Page } from "@playwright/test";
import { BasePage } from "./base.page";
export class LivePage extends BasePage {
constructor(page: Page, isDesktop: boolean) {
super(page, isDesktop);
}
/** The camera card wrapper on the dashboard, keyed by camera name. */
cameraCard(name: string): Locator {
return this.page.locator(`[data-camera='${name}']`);
}
/** Back button on the single-camera view header (desktop text). */
get backButton(): Locator {
return this.page.getByText("Back", { exact: true });
}
/** History button on the single-camera view header (desktop text). */
get historyButton(): Locator {
return this.page.getByText("History", { exact: true });
}
/** All CameraFeatureToggle elements (active + inactive). */
get featureToggles(): Locator {
// Use div selector to exclude NavItem anchor elements that share the same classes.
return this.page.locator(
"div.flex.flex-col.items-center.justify-center.bg-selected, div.flex.flex-col.items-center.justify-center.bg-secondary",
);
}
/** Only the active (bg-selected) feature toggles. */
get activeFeatureToggles(): Locator {
// Use div selector to exclude NavItem anchor elements that share the same classes.
return this.page.locator(
"div.flex.flex-col.items-center.justify-center.bg-selected",
);
}
/** Open the right-click context menu on a camera card (desktop only). */
async openContextMenuOn(cameraName: string): Promise<Locator> {
await this.cameraCard(cameraName).first().click({ button: "right" });
return this.page
.locator('[role="menu"], [data-radix-menu-content]')
.first();
}
}
+52
View File
@@ -0,0 +1,52 @@
/**
* Review/events page object.
*
* Encapsulates severity tab, filter bar, calendar, and mobile filter
* drawer selectors. Does NOT own assertions.
*/
import type { Locator, Page } from "@playwright/test";
import { BasePage } from "./base.page";
export class ReviewPage extends BasePage {
constructor(page: Page, isDesktop: boolean) {
super(page, isDesktop);
}
get alertsTab(): Locator {
return this.page.getByLabel("Alerts");
}
get detectionsTab(): Locator {
return this.page.getByLabel("Detections");
}
get motionTab(): Locator {
return this.page.getByRole("radio", { name: "Motion" });
}
get camerasFilterTrigger(): Locator {
return this.page.getByRole("button", { name: /cameras/i }).first();
}
get calendarTrigger(): Locator {
return this.page.getByRole("button", { name: /24 hours|calendar|date/i });
}
get showReviewedToggle(): Locator {
return this.page.getByRole("button", { name: /reviewed/i });
}
get reviewItems(): Locator {
return this.page.locator(".review-item");
}
/** The filter popover content (desktop) or drawer (mobile). */
get filterOverlay(): Locator {
return this.page
.locator(
'[data-radix-popper-content-wrapper], [role="dialog"], [data-vaul-drawer]',
)
.first();
}
}
+2 -28
View File
@@ -14,10 +14,6 @@
*
* @mobile rule: every .spec.ts under specs/ (not specs/_meta/) must
* contain at least one test title or describe with the substring "@mobile".
*
* Specs in PENDING_REWRITE are exempt from all rules until they are
* rewritten with proper assertions and mobile coverage. Remove each
* entry when its spec is updated.
*/
import { readFileSync, readdirSync, statSync } from "node:fs";
@@ -28,24 +24,6 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
const SPECS_DIR = resolve(__dirname, "..", "specs");
const META_PREFIX = resolve(SPECS_DIR, "_meta");
// Specs exempt from lint rules until they are rewritten with proper
// assertions and mobile coverage. Remove each entry when its spec is updated.
const PENDING_REWRITE = new Set([
"auth.spec.ts",
"chat.spec.ts",
"classification.spec.ts",
"config-editor.spec.ts",
"explore.spec.ts",
"export.spec.ts",
"face-library.spec.ts",
"live.spec.ts",
"logs.spec.ts",
"navigation.spec.ts",
"replay.spec.ts",
"review.spec.ts",
"system.spec.ts",
]);
const BANNED_PATTERNS = [
{
name: "page.waitForTimeout",
@@ -62,14 +40,12 @@ const BANNED_PATTERNS = [
{
name: "conditional count() assertion",
regex: /\bif\s*\(\s*\(?\s*await\s+[^)]*\.count\s*\(\s*\)\s*\)?\s*[><=!]/,
advice:
"Assertions must be unconditional. Use expect(...).toHaveCount(n).",
advice: "Assertions must be unconditional. Use expect(...).toHaveCount(n).",
},
{
name: "vacuous textContent length assertion",
regex: /expect\([^)]*\.length\)\.toBeGreaterThan\(0\)/,
advice:
"Assert specific content, not that some text exists.",
advice: "Assert specific content, not that some text exists.",
},
];
@@ -89,8 +65,6 @@ function walk(dir) {
}
function lintFile(file) {
const basename = file.split("/").pop();
if (PENDING_REWRITE.has(basename)) return [];
if (file.includes("/specs/settings/")) return [];
const errors = [];
+64 -101
View File
@@ -1,147 +1,110 @@
/**
* Auth and cross-cutting tests -- HIGH tier.
* Auth and role tests -- HIGH tier.
*
* Tests protected route access for admin/viewer roles,
* access denied page rendering, viewer nav restrictions,
* and all routes smoke test.
* Admin access to /system, /config, /logs; viewer access denied
* markers (via i18n heading, not a data-testid we don't own);
* viewer nav restrictions; all-routes smoke.
*/
import { test, expect } from "../fixtures/frigate-test";
import { viewerProfile } from "../fixtures/mock-data/profile";
test.describe("Auth - Admin Access @high", () => {
test("admin can access /system and sees system tabs", async ({
frigateApp,
}) => {
test.describe("Auth — admin access @high", () => {
test("admin /system renders general tab", async ({ frigateApp }) => {
await frigateApp.goto("/system");
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible();
await frigateApp.page.waitForTimeout(3000);
// System page should have named tab buttons
await expect(frigateApp.page.getByLabel("Select general")).toBeVisible({
timeout: 5_000,
timeout: 15_000,
});
});
test("admin can access /config and Monaco editor loads", async ({
frigateApp,
}) => {
test("admin /config renders Monaco editor", async ({ frigateApp }) => {
await frigateApp.goto("/config");
await frigateApp.page.waitForTimeout(5000);
const editor = frigateApp.page.locator(
".monaco-editor, [data-keybinding-context]",
);
await expect(editor.first()).toBeVisible({ timeout: 10_000 });
await expect(
frigateApp.page
.locator(".monaco-editor, [data-keybinding-context]")
.first(),
).toBeVisible({ timeout: 15_000 });
});
test("admin can access /logs and sees service tabs", async ({
frigateApp,
}) => {
test("admin /logs renders frigate tab", async ({ frigateApp }) => {
await frigateApp.goto("/logs");
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible();
await expect(frigateApp.page.getByLabel("Select frigate")).toBeVisible({
timeout: 5_000,
});
});
test("admin sees Classification nav on desktop", async ({ frigateApp }) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
await frigateApp.goto("/");
await expect(
frigateApp.page.locator('a[href="/classification"]'),
).toBeVisible();
});
});
test.describe("Auth - Viewer Restrictions @high", () => {
test("viewer sees Access Denied on /system", async ({ frigateApp, page }) => {
await frigateApp.installDefaults({ profile: viewerProfile() });
await page.goto("/system");
await page.waitForTimeout(2000);
// Should show "Access Denied" text
await expect(page.getByText("Access Denied")).toBeVisible({
timeout: 5_000,
test.describe("Auth — viewer restrictions @high", () => {
for (const path of ["/system", "/config", "/logs"]) {
test(`viewer on ${path} sees AccessDenied`, async ({ frigateApp }) => {
await frigateApp.installDefaults({ profile: viewerProfile() });
await frigateApp.page.goto(path);
await frigateApp.page.waitForSelector("#pageRoot", { timeout: 10_000 });
await expect(
frigateApp.page.getByRole("heading", {
level: 2,
name: /access denied/i,
}),
).toBeVisible({ timeout: 10_000 });
});
}
test("viewer sees cameras on /", async ({ frigateApp }) => {
await frigateApp.installDefaults({ profile: viewerProfile() });
await frigateApp.page.goto("/");
await expect(
frigateApp.page.locator("[data-camera='front_door']"),
).toBeVisible({ timeout: 10_000 });
});
test("viewer sees Access Denied on /config", async ({ frigateApp, page }) => {
test("viewer sees severity tabs on /review", async ({ frigateApp }) => {
await frigateApp.installDefaults({ profile: viewerProfile() });
await page.goto("/config");
await page.waitForTimeout(2000);
await expect(page.getByText("Access Denied")).toBeVisible({
timeout: 5_000,
});
});
test("viewer sees Access Denied on /logs", async ({ frigateApp, page }) => {
await frigateApp.installDefaults({ profile: viewerProfile() });
await page.goto("/logs");
await page.waitForTimeout(2000);
await expect(page.getByText("Access Denied")).toBeVisible({
timeout: 5_000,
});
});
test("viewer can access Live page and sees cameras", async ({
frigateApp,
page,
}) => {
await frigateApp.installDefaults({ profile: viewerProfile() });
await page.goto("/");
await page.waitForSelector("#pageRoot", { timeout: 10_000 });
await expect(page.locator("[data-camera='front_door']")).toBeVisible({
await frigateApp.page.goto("/review");
await expect(frigateApp.page.getByLabel("Alerts")).toBeVisible({
timeout: 10_000,
});
});
test("viewer can access Review page and sees severity tabs", async ({
test("viewer can access all non-admin routes without AccessDenied", async ({
frigateApp,
page,
}) => {
await frigateApp.installDefaults({ profile: viewerProfile() });
await page.goto("/review");
await page.waitForSelector("#pageRoot", { timeout: 10_000 });
await expect(page.getByLabel("Alerts")).toBeVisible({ timeout: 5_000 });
});
test("viewer can access all main user routes without crash", async ({
frigateApp,
page,
}) => {
await frigateApp.installDefaults({ profile: viewerProfile() });
const routes = ["/", "/review", "/explore", "/export", "/settings"];
for (const route of routes) {
await page.goto(route);
await page.waitForSelector("#pageRoot", { timeout: 10_000 });
await frigateApp.page.goto(route);
await frigateApp.page.waitForSelector("#pageRoot", { timeout: 10_000 });
await expect(
frigateApp.page.getByRole("heading", {
level: 2,
name: /access denied/i,
}),
).toHaveCount(0);
}
});
});
test.describe("Auth - All Routes Smoke @high", () => {
test("all user routes render without crash", async ({ frigateApp }) => {
const routes = ["/", "/review", "/explore", "/export", "/settings"];
for (const route of routes) {
test.describe("Auth — viewer nav restrictions (desktop) @high", () => {
test.skip(({ frigateApp }) => frigateApp.isMobile, "Sidebar only on desktop");
test("viewer sidebar hides admin routes", async ({ frigateApp }) => {
await frigateApp.installDefaults({ profile: viewerProfile() });
await frigateApp.page.goto("/");
await frigateApp.page.waitForSelector("#pageRoot", { timeout: 10_000 });
for (const href of ["/system", "/config", "/logs"]) {
await expect(
frigateApp.page.locator(`aside a[href='${href}']`),
).toHaveCount(0);
}
});
});
test.describe("Auth — all routes smoke @high @mobile", () => {
test("every common route renders #pageRoot", async ({ frigateApp }) => {
for (const route of ["/", "/review", "/explore", "/export", "/settings"]) {
await frigateApp.goto(route);
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible({
timeout: 10_000,
});
}
});
test("admin routes render with specific content", async ({ frigateApp }) => {
// System page should have tab controls
await frigateApp.goto("/system");
await frigateApp.page.waitForTimeout(3000);
await expect(frigateApp.page.getByLabel("Select general")).toBeVisible({
timeout: 5_000,
});
// Logs page should have service tabs
await frigateApp.goto("/logs");
await expect(frigateApp.page.getByLabel("Select frigate")).toBeVisible({
timeout: 5_000,
});
});
});
+298 -21
View File
@@ -1,34 +1,311 @@
/**
* Chat page tests -- MEDIUM tier.
*
* Tests chat interface rendering, input area, and example prompt buttons.
* Starting state, NDJSON streaming contract (not SSE), assistant
* bubble grows as chunks arrive, error path, and mobile viewport.
*/
import { test, expect } from "../fixtures/frigate-test";
import { test, expect, type FrigateApp } from "../fixtures/frigate-test";
test.describe("Chat Page @medium", () => {
test("chat page renders without crash", async ({ frigateApp }) => {
await frigateApp.goto("/chat");
await frigateApp.page.waitForTimeout(2000);
await expect(frigateApp.page.locator("body")).toBeVisible();
});
/**
* Install a window.fetch override on the page so that POSTs to
* chat/completion resolve with a real ReadableStream that emits the
* given chunks over time. This is the only way to validate
* chunk-by-chunk rendering through Playwright — page.route() does not
* support streaming responses.
*
* Must be called BEFORE frigateApp.goto(). The override also exposes
* `__chatRequests` on window so tests can assert the outgoing body.
*/
async function installChatStreamOverride(
app: FrigateApp,
chunks: Array<Record<string, unknown>>,
opts: { chunkDelayMs?: number; status?: number } = {},
) {
const { chunkDelayMs = 40, status = 200 } = opts;
await app.page.addInitScript(
({ chunks, chunkDelayMs, status }) => {
(window as unknown as { __chatRequests: unknown[] }).__chatRequests = [];
const origFetch = window.fetch;
window.fetch = async (input, init) => {
const url =
typeof input === "string"
? input
: input instanceof URL
? input.toString()
: (input as Request).url;
if (url.includes("chat/completion")) {
const body =
init?.body instanceof String || typeof init?.body === "string"
? JSON.parse(init!.body as string)
: null;
(
window as unknown as { __chatRequests: unknown[] }
).__chatRequests.push({ url, body });
if (status !== 200) {
return new Response(JSON.stringify({ error: "boom" }), {
status,
});
}
const encoder = new TextEncoder();
const stream = new ReadableStream({
async start(controller) {
for (const chunk of chunks) {
await new Promise((r) => setTimeout(r, chunkDelayMs));
controller.enqueue(
encoder.encode(JSON.stringify(chunk) + "\n"),
);
}
controller.close();
},
});
return new Response(stream, { status: 200 });
}
return origFetch.call(window, input as RequestInfo, init);
};
},
{ chunks, chunkDelayMs, status },
);
}
test("chat page has interactive input or buttons", async ({ frigateApp }) => {
test.describe("Chat — starting state @medium", () => {
test("empty message list renders ChatStartingState with title and input", async ({
frigateApp,
}) => {
await frigateApp.goto("/chat");
await frigateApp.page.waitForTimeout(2000);
const interactive = frigateApp.page.locator("input, textarea, button");
const count = await interactive.count();
expect(count).toBeGreaterThan(0);
await expect(
frigateApp.page.getByRole("heading", { level: 1 }),
).toBeVisible({ timeout: 10_000 });
await expect(frigateApp.page.getByPlaceholder(/ask/i)).toBeVisible();
// Four quick-reply buttons from starting_requests.*
const quickReplies = frigateApp.page.locator(
"button:has-text('Show recent events'), button:has-text('Show camera status'), button:has-text('What happened'), button:has-text('Watch')",
);
await expect(quickReplies.first()).toBeVisible({ timeout: 5_000 });
});
});
test("chat input accepts text", async ({ frigateApp }) => {
test.describe("Chat — streaming @medium", () => {
test("submission POSTs to chat/completion with stream: true", async ({
frigateApp,
}) => {
await installChatStreamOverride(frigateApp, [
{ type: "content", delta: "Hel" },
{ type: "content", delta: "lo" },
]);
await frigateApp.goto("/chat");
await frigateApp.page.waitForTimeout(2000);
const input = frigateApp.page.locator("input, textarea").first();
if (await input.isVisible().catch(() => false)) {
await input.fill("What cameras detected a person today?");
const value = await input.inputValue();
expect(value.length).toBeGreaterThan(0);
}
const input = frigateApp.page.getByPlaceholder(/ask/i);
await expect(input).toBeVisible({ timeout: 10_000 });
await input.fill("hello chat");
await input.press("Enter");
await expect
.poll(
async () =>
frigateApp.page.evaluate(
() =>
(window as unknown as { __chatRequests: unknown[] })
.__chatRequests?.length ?? 0,
),
{ timeout: 5_000 },
)
.toBeGreaterThan(0);
const request = await frigateApp.page.evaluate(
() =>
(
window as unknown as {
__chatRequests: Array<{
url: string;
body: { stream: boolean; messages: Array<{ content: string }> };
}>;
}
).__chatRequests[0],
);
expect(request.body.stream).toBe(true);
expect(
request.body.messages[request.body.messages.length - 1].content,
).toBe("hello chat");
});
test("NDJSON content chunks accumulate in the assistant bubble", async ({
frigateApp,
}) => {
await installChatStreamOverride(
frigateApp,
[
{ type: "content", delta: "Hel" },
{ type: "content", delta: "lo, " },
{ type: "content", delta: "world!" },
],
{ chunkDelayMs: 50 },
);
await frigateApp.goto("/chat");
const input = frigateApp.page.getByPlaceholder(/ask/i);
await expect(input).toBeVisible({ timeout: 10_000 });
await input.fill("greet me");
await input.press("Enter");
await expect(frigateApp.page.getByText(/Hello, world!/i)).toBeVisible({
timeout: 10_000,
});
});
test("tool_calls chunks render a ToolCallsGroup", async ({ frigateApp }) => {
await installChatStreamOverride(frigateApp, [
{
type: "tool_calls",
tool_calls: [
{
id: "call_1",
name: "search_objects",
arguments: { label: "person" },
},
],
},
{ type: "content", delta: "Searching for people." },
]);
await frigateApp.goto("/chat");
const input = frigateApp.page.getByPlaceholder(/ask/i);
await expect(input).toBeVisible({ timeout: 10_000 });
await input.fill("find people");
await input.press("Enter");
// ToolCallsGroup normalizes "search_objects" → "Search Objects" via
// normalizeName(). Match the rendered display label instead.
await expect(frigateApp.page.getByText(/search objects/i)).toBeVisible({
timeout: 10_000,
});
await expect(
frigateApp.page.getByText(/searching for people/i),
).toBeVisible({ timeout: 5_000 });
});
});
test.describe("Chat — stop @medium", () => {
test("Stop button aborts an in-flight stream and freezes the partial message", async ({
frigateApp,
}) => {
// A long chunk sequence with big delays gives us time to hit Stop.
await installChatStreamOverride(
frigateApp,
[
{ type: "content", delta: "First chunk. " },
{ type: "content", delta: "Second chunk. " },
{ type: "content", delta: "Third chunk. " },
],
{ chunkDelayMs: 300 },
);
await frigateApp.goto("/chat");
const input = frigateApp.page.getByPlaceholder(/ask/i);
await expect(input).toBeVisible({ timeout: 10_000 });
await input.fill("slow response please");
await input.press("Enter");
// Wait for the first chunk to render
await expect(frigateApp.page.getByText(/First chunk\./)).toBeVisible({
timeout: 10_000,
});
// The Stop button is a destructive rounded button shown while isLoading.
// It contains only an FaStop SVG icon (no visible text). Find it by the
// destructive variant class or fall back to aria-label.
const stopBtn = frigateApp.page
.locator("button.bg-destructive, button[class*='destructive']")
.first();
await stopBtn.click({ timeout: 3_000 }).catch(async () => {
await frigateApp.page
.getByRole("button", { name: /stop|cancel/i })
.first()
.click();
});
// Third chunk should never appear.
await expect(frigateApp.page.getByText(/Third chunk\./)).toHaveCount(0);
});
});
test.describe("Chat — error @medium", () => {
test("non-OK response renders an error banner", async ({ frigateApp }) => {
await installChatStreamOverride(frigateApp, [], { status: 500 });
await frigateApp.goto("/chat");
const input = frigateApp.page.getByPlaceholder(/ask/i);
await expect(input).toBeVisible({ timeout: 10_000 });
await input.fill("trigger error");
await input.press("Enter");
// The error banner is a role="alert" paragraph; target by role so we
// don't collide with the user-message bubble that contains "trigger
// error" (which would match /error/ in strict mode).
await expect(
frigateApp.page.getByRole("alert").filter({
hasText: /boom|something went wrong/i,
}),
).toBeVisible({ timeout: 5_000 });
});
});
test.describe("Chat — attachment chip @medium", () => {
test("attaching an event renders a ChatAttachmentChip", async ({
frigateApp,
}) => {
// The chat starts with an empty message list (ChatStartingState).
// After sending a message, ChatEntry with the paperclip button appears.
// We use the stream override so the first message completes quickly.
await installChatStreamOverride(frigateApp, [
{ type: "content", delta: "Done." },
]);
await frigateApp.goto("/chat");
// Send a first message to transition out of ChatStartingState so the
// full ChatEntry (with the paperclip) is visible.
const input = frigateApp.page.getByPlaceholder(/ask/i);
await expect(input).toBeVisible({ timeout: 10_000 });
await input.fill("hello");
await input.press("Enter");
// Wait for the assistant response to complete so isLoading becomes false
// and the paperclip button is re-enabled.
await expect(frigateApp.page.getByText(/Done\./i)).toBeVisible({
timeout: 10_000,
});
// The paperclip button has aria-label from t("attachment_picker_placeholder")
// = "Attach an event".
const paperclip = frigateApp.page
.getByRole("button", { name: /attach an event/i })
.first();
await expect(paperclip).toBeVisible({ timeout: 5_000 });
await paperclip.click();
// The popover shows a paste input with placeholder "Or paste event ID".
const idInput = frigateApp.page
.locator('input[placeholder*="event" i], input[aria-label*="attach" i]')
.first();
await expect(idInput).toBeVisible({ timeout: 3_000 });
await idInput.fill("test-event-1");
await frigateApp.page
.getByRole("button", { name: /^attach$/i })
.first()
.click();
// The ChatAttachmentChip renders in the composer area. It shows an
// activity indicator while loading event data (event_ids API not mocked),
// so assert on the chip container being present in the composer.
await expect(
frigateApp.page.locator(
"[class*='inline-flex'][class*='rounded-lg'][class*='border']",
),
).toBeVisible({ timeout: 5_000 });
});
});
test.describe("Chat — mobile @medium @mobile", () => {
test.skip(({ frigateApp }) => !frigateApp.isMobile, "Mobile-only");
test("chat input is focusable at mobile viewport", async ({ frigateApp }) => {
await frigateApp.goto("/chat");
const input = frigateApp.page.getByPlaceholder(/ask/i);
await expect(input).toBeVisible({ timeout: 10_000 });
await input.focus();
await expect(input).toBeFocused();
});
});
+209 -14
View File
@@ -1,33 +1,228 @@
/**
* Classification page tests -- MEDIUM tier.
*
* Tests model selection view rendering and interactive elements.
* Model list driven by config.classification.custom + per-model
* dataset fetches. Admin-only access.
*/
import { test, expect } from "../fixtures/frigate-test";
import { viewerProfile } from "../fixtures/mock-data/profile";
test.describe("Classification @medium", () => {
test("classification page renders without crash", async ({ frigateApp }) => {
const CUSTOM_MODELS = {
object_classifier: {
name: "object_classifier",
object_config: { objects: ["person"], classification_type: "sub_label" },
},
state_classifier: {
name: "state_classifier",
state_config: { cameras: { front_door: { crop: [0, 0, 1, 1] } } },
},
};
async function installDatasetRoute(
app: { page: import("@playwright/test").Page },
name: string,
body: Record<string, unknown> = { categories: {} },
) {
await app.page.route(
new RegExp(`/api/classification/${name}/dataset`),
(route) => route.fulfill({ json: body }),
);
}
async function installTrainRoute(
app: { page: import("@playwright/test").Page },
name: string,
) {
await app.page.route(
new RegExp(`/api/classification/${name}/train`),
(route) => route.fulfill({ json: [] }),
);
}
test.describe("Classification — model list @medium", () => {
test("custom models render by name", async ({ frigateApp }) => {
await frigateApp.installDefaults({
config: { classification: { custom: CUSTOM_MODELS } },
});
await installDatasetRoute(frigateApp, "object_classifier");
await installDatasetRoute(frigateApp, "state_classifier");
await frigateApp.goto("/classification");
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible();
await expect(frigateApp.page.getByText("object_classifier")).toBeVisible({
timeout: 10_000,
});
});
test("classification page shows content and controls", async ({
frigateApp,
}) => {
test("empty custom map renders without crash", async ({ frigateApp }) => {
await frigateApp.installDefaults({
config: { classification: { custom: {} } },
});
await frigateApp.goto("/classification");
await frigateApp.page.waitForTimeout(2000);
const text = await frigateApp.page.textContent("#pageRoot");
expect(text?.length).toBeGreaterThan(0);
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible({
timeout: 10_000,
});
});
test("classification page has interactive elements", async ({
test("toggling to states view switches the rendered card set", async ({
frigateApp,
}) => {
await frigateApp.installDefaults({
config: { classification: { custom: CUSTOM_MODELS } },
});
await installDatasetRoute(frigateApp, "object_classifier");
await installDatasetRoute(frigateApp, "state_classifier");
await frigateApp.goto("/classification");
await frigateApp.page.waitForTimeout(2000);
const buttons = frigateApp.page.locator("#pageRoot button");
const count = await buttons.count();
expect(count).toBeGreaterThanOrEqual(0);
// Objects is default — object_classifier visible, state_classifier hidden.
await expect(frigateApp.page.getByText("object_classifier")).toBeVisible({
timeout: 10_000,
});
await expect(frigateApp.page.getByText("state_classifier")).toHaveCount(0);
// Click the "states" toggle. Radix ToggleGroup type="single" uses role="radio".
const statesToggle = frigateApp.page
.getByRole("radio", { name: /state/i })
.first();
await expect(statesToggle).toBeVisible({ timeout: 5_000 });
await statesToggle.click();
await expect(frigateApp.page.getByText("state_classifier")).toBeVisible({
timeout: 5_000,
});
await expect(frigateApp.page.getByText("object_classifier")).toHaveCount(0);
});
});
test.describe("Classification — model detail navigation @medium", () => {
test("clicking a model card opens ModelTrainingView", async ({
frigateApp,
}) => {
await frigateApp.installDefaults({
config: { classification: { custom: CUSTOM_MODELS } },
});
await installDatasetRoute(frigateApp, "object_classifier");
await installDatasetRoute(frigateApp, "state_classifier");
await installTrainRoute(frigateApp, "object_classifier");
await frigateApp.goto("/classification");
const objectCard = frigateApp.page.getByText("object_classifier").first();
await expect(objectCard).toBeVisible({ timeout: 10_000 });
await objectCard.click();
// ModelTrainingView renders a Back button (aria-label "Back").
// useOverlayState stores the selected model in window.history.state
// (not the URL), so we verify the state transition via the DOM.
await expect(
frigateApp.page.getByRole("button", { name: /back/i }),
).toBeVisible({ timeout: 5_000 });
// The model grid is no longer shown; state_classifier card is gone.
await expect(frigateApp.page.getByText("state_classifier")).toHaveCount(0);
});
});
test.describe("Classification — delete model (desktop) @medium", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Delete action menu is desktop-focused",
);
test("deleting a model fires DELETE + PUT /config/set", async ({
frigateApp,
}) => {
let deleteCalled = false;
let configSetCalled = false;
// installDefaults must run first because Playwright matches routes in
// LIFO order — routes registered after installDefaults take precedence
// over the generic catch-all registered inside it.
await frigateApp.installDefaults({
config: { classification: { custom: CUSTOM_MODELS } },
});
await installDatasetRoute(frigateApp, "object_classifier");
await installDatasetRoute(frigateApp, "state_classifier");
// Register spy routes after installDefaults so they win over the catch-all.
await frigateApp.page.route(
/\/api\/classification\/object_classifier$/,
async (route) => {
if (route.request().method() === "DELETE") {
deleteCalled = true;
await route.fulfill({ json: { success: true } });
return;
}
return route.fallback();
},
);
await frigateApp.page.route("**/api/config/set", async (route) => {
if (route.request().method() === "PUT") configSetCalled = true;
await route.fulfill({ json: { success: true, require_restart: false } });
});
await frigateApp.goto("/classification");
await expect(frigateApp.page.getByText("object_classifier")).toBeVisible({
timeout: 10_000,
});
// The card-level actions menu (FiMoreVertical three-dot icon) is a
// DropdownMenuTrigger with asChild on a BlurredIconButton div.
// Radix forwards aria-haspopup="menu" to the child element.
// Scope the selector to the model card grid to avoid hitting the
// settings sidebar trigger.
const cardGrid = frigateApp.page.locator(".grid.auto-rows-max");
await expect(cardGrid).toBeVisible({ timeout: 5_000 });
const trigger = cardGrid.locator('[aria-haspopup="menu"]').first();
await expect(trigger).toBeVisible({ timeout: 5_000 });
await trigger.click();
const deleteItem = frigateApp.page
.getByRole("menuitem", { name: /delete/i })
.first();
await expect(deleteItem).toBeVisible({ timeout: 5_000 });
await deleteItem.click();
// Confirm the AlertDialog.
const alert = frigateApp.page.getByRole("alertdialog");
await expect(alert).toBeVisible({ timeout: 5_000 });
await alert
.getByRole("button", { name: /delete|confirm/i })
.first()
.click();
await expect.poll(() => deleteCalled, { timeout: 5_000 }).toBe(true);
await expect.poll(() => configSetCalled, { timeout: 5_000 }).toBe(true);
});
});
test.describe("Classification — admin only @medium", () => {
test("viewer navigating to /classification is redirected to access-denied", async ({
frigateApp,
}) => {
await frigateApp.installDefaults({ profile: viewerProfile() });
await frigateApp.page.goto("/classification");
await frigateApp.page.waitForSelector("#pageRoot", { timeout: 10_000 });
await expect(frigateApp.page).toHaveURL(/\/unauthorized/, {
timeout: 10_000,
});
await expect(
frigateApp.page.getByRole("heading", {
level: 2,
name: /access denied/i,
}),
).toBeVisible({ timeout: 10_000 });
});
});
test.describe("Classification — mobile @medium @mobile", () => {
test.skip(({ frigateApp }) => !frigateApp.isMobile, "Mobile-only");
test("page renders at mobile viewport", async ({ frigateApp }) => {
await frigateApp.installDefaults({
config: { classification: { custom: CUSTOM_MODELS } },
});
await installDatasetRoute(frigateApp, "object_classifier");
await installDatasetRoute(frigateApp, "state_classifier");
await frigateApp.goto("/classification");
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible({
timeout: 10_000,
});
});
});
+266 -34
View File
@@ -1,44 +1,276 @@
/**
* Config Editor page tests -- MEDIUM tier.
* Config Editor tests -- MEDIUM tier.
*
* Tests Monaco editor loading, YAML content rendering,
* save button presence, and copy button interaction.
* Monaco load + value, Save (config/save?save_option=saveonly),
* Save error path, Save and Restart (WS frame via useRestart),
* Copy (clipboard), schema markers.
*/
import { test, expect } from "../fixtures/frigate-test";
import { installWsFrameCapture, waitForWsFrame } from "../helpers/ws-frames";
import { grantClipboardPermissions, readClipboard } from "../helpers/clipboard";
import {
getMonacoVisibleText,
replaceMonacoValue,
waitForErrorMarker,
} from "../helpers/monaco";
test.describe("Config Editor @medium", () => {
test("config editor loads Monaco editor with content", async ({
frigateApp,
}) => {
const SAMPLE_CONFIG =
"mqtt:\n host: mqtt\ncameras:\n front_door:\n enabled: true\n";
async function installSaveRoute(
app: { page: import("@playwright/test").Page },
status: number,
body: Record<string, unknown>,
): Promise<{
capturedUrl: () => string | null;
capturedBody: () => string | null;
}> {
let lastUrl: string | null = null;
let lastBody: string | null = null;
await app.page.route("**/api/config/save**", async (route) => {
lastUrl = route.request().url();
lastBody = route.request().postData();
await route.fulfill({ status, json: body });
});
return {
capturedUrl: () => lastUrl,
capturedBody: () => lastBody,
};
}
test.describe("Config Editor — Monaco @medium", () => {
test("editor loads with mocked configRaw content", async ({ frigateApp }) => {
await frigateApp.installDefaults({ configRaw: SAMPLE_CONFIG });
await frigateApp.goto("/config");
await frigateApp.page.waitForTimeout(5000);
// Monaco editor should render with a specific class
const editor = frigateApp.page.locator(
".monaco-editor, [data-keybinding-context]",
await expect(frigateApp.page.locator(".monaco-editor").first()).toBeVisible(
{ timeout: 15_000 },
);
// Assert via DOM-rendered visible text (Monaco virtualizes — works
// for short configs which covers our mocked content).
await expect
.poll(() => getMonacoVisibleText(frigateApp.page), { timeout: 10_000 })
.toContain("front_door");
});
});
test.describe("Config Editor — Save @medium", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Save button copy is desktop-visible (hidden md:block)",
);
test("clicking Save Only POSTs config/save?save_option=saveonly", async ({
frigateApp,
}) => {
await frigateApp.installDefaults({ configRaw: SAMPLE_CONFIG });
const capture = await installSaveRoute(frigateApp, 200, {
message: "Config saved",
});
await frigateApp.goto("/config");
await expect(frigateApp.page.locator(".monaco-editor").first()).toBeVisible(
{ timeout: 15_000 },
);
await frigateApp.page.getByLabel("Save Only").click();
await expect
.poll(() => capture.capturedUrl(), { timeout: 5_000 })
.toMatch(/config\/save\?save_option=saveonly/);
// Body is the raw YAML as text/plain
await expect
.poll(() => capture.capturedBody(), { timeout: 5_000 })
.toContain("front_door");
});
test("Save error shows the server message in the error area", async ({
frigateApp,
}) => {
await frigateApp.installDefaults({ configRaw: SAMPLE_CONFIG });
await installSaveRoute(frigateApp, 400, {
message: "Invalid field `cameras.front_door`",
});
await frigateApp.goto("/config");
await expect(frigateApp.page.locator(".monaco-editor").first()).toBeVisible(
{ timeout: 15_000 },
);
await frigateApp.page.getByLabel("Save Only").click();
await expect(frigateApp.page.getByText(/Invalid field/i)).toBeVisible({
timeout: 5_000,
});
});
});
test.describe("Config Editor — Save and Restart @medium", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Save and Restart button copy is desktop-visible",
);
test("Save and Restart opens dialog; confirm sends WS restart frame", async ({
frigateApp,
}) => {
await frigateApp.installDefaults({ configRaw: SAMPLE_CONFIG });
await installSaveRoute(frigateApp, 200, { message: "Saved" });
await installWsFrameCapture(frigateApp.page);
await frigateApp.goto("/config");
await expect(frigateApp.page.locator(".monaco-editor").first()).toBeVisible(
{ timeout: 15_000 },
);
await frigateApp.page.getByLabel("Save & Restart").click();
const dialog = frigateApp.page.getByRole("alertdialog");
await expect(dialog).toBeVisible({ timeout: 5_000 });
await dialog.getByRole("button", { name: /restart/i }).click();
await waitForWsFrame(
frigateApp.page,
(frame) => frame.includes('"restart"') || frame.includes("restart"),
{ message: "useRestart should send a WS frame on the restart topic" },
);
});
test("cancelling the restart dialog leaves body interactive", async ({
frigateApp,
}) => {
await frigateApp.installDefaults({ configRaw: SAMPLE_CONFIG });
await installSaveRoute(frigateApp, 200, { message: "Saved" });
await frigateApp.goto("/config");
await expect(frigateApp.page.locator(".monaco-editor").first()).toBeVisible(
{ timeout: 15_000 },
);
await frigateApp.page.getByLabel("Save & Restart").click();
const dialog = frigateApp.page.getByRole("alertdialog");
await expect(dialog).toBeVisible({ timeout: 5_000 });
await dialog.getByRole("button", { name: /cancel/i }).click();
await expect(dialog).not.toBeVisible({ timeout: 3_000 });
await expect(
frigateApp.page.locator(".monaco-editor").first(),
).toBeVisible();
});
});
test.describe("Config Editor — Copy @medium", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Copy button copy is desktop-visible",
);
test("Copy places the editor value in the clipboard", async ({
frigateApp,
context,
}) => {
await grantClipboardPermissions(context);
await frigateApp.installDefaults({ configRaw: SAMPLE_CONFIG });
await frigateApp.goto("/config");
await expect(frigateApp.page.locator(".monaco-editor").first()).toBeVisible(
{ timeout: 15_000 },
);
await frigateApp.page.getByLabel("Copy Config").click();
await expect
.poll(() => readClipboard(frigateApp.page), { timeout: 5_000 })
.toContain("front_door");
});
});
test.describe("Config Editor — schema markers @medium", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Schema validation assumes focused desktop editing",
);
test("invalid YAML renders at least one error marker in the DOM", async ({
frigateApp,
}) => {
await frigateApp.installDefaults({ configRaw: SAMPLE_CONFIG });
await frigateApp.goto("/config");
await expect(frigateApp.page.locator(".monaco-editor").first()).toBeVisible(
{ timeout: 15_000 },
);
// Replace editor contents with clearly invalid YAML via keyboard.
await replaceMonacoValue(
frigateApp.page,
"this is not: [yaml: and has {unbalanced",
);
// Monaco debounces marker evaluation; the .squiggly-error decoration
// appears asynchronously in the .view-overlays layer.
await waitForErrorMarker(frigateApp.page);
});
});
test.describe("Config Editor — Cmd+S keyboard shortcut @medium", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Keyboard save shortcut is desktop-only",
);
test("Cmd/Ctrl+S fires the same config/save POST as the Save button", async ({
frigateApp,
}) => {
await frigateApp.installDefaults({ configRaw: SAMPLE_CONFIG });
const capture = await installSaveRoute(frigateApp, 200, {
message: "Saved",
});
await frigateApp.goto("/config");
await expect(frigateApp.page.locator(".monaco-editor").first()).toBeVisible(
{ timeout: 15_000 },
);
// Focus the editor so Monaco's keybinding receives the shortcut.
await frigateApp.page.locator(".monaco-editor").first().click();
await frigateApp.page.keyboard.press("ControlOrMeta+s");
await expect
.poll(() => capture.capturedUrl(), { timeout: 5_000 })
.toMatch(/config\/save\?save_option=saveonly/);
});
});
test.describe("Config Editor — Safe Mode auto-validation @medium", () => {
test("safe-mode config auto-posts on mount and shows the inline error", async ({
frigateApp,
}) => {
// Thread safe_mode: true through the config override, then stub
// config/save to return a validation error. The page's
// initialValidationRef effect runs on mount and POSTs
// config/save?save_option=saveonly with the raw config; the 400
// surfaces through setError.
// installDefaults must come first so our specific route wins (LIFO).
await frigateApp.installDefaults({
config: { safe_mode: true } as unknown as Record<string, unknown>,
configRaw: "cameras:\n front_door:\n ffmpeg: {}\n",
});
let autoSaveCalled = false;
await frigateApp.page.route("**/api/config/save**", async (route) => {
autoSaveCalled = true;
await route.fulfill({
status: 400,
json: { message: "safe-mode validation failure" },
});
});
await frigateApp.goto("/config");
await expect(frigateApp.page.locator(".monaco-editor").first()).toBeVisible(
{ timeout: 15_000 },
);
await expect.poll(() => autoSaveCalled, { timeout: 10_000 }).toBe(true);
await expect(
frigateApp.page.getByText(/safe-mode validation failure/i),
).toBeVisible({ timeout: 5_000 });
});
});
test.describe("Config Editor — mobile @medium @mobile", () => {
test.skip(({ frigateApp }) => !frigateApp.isMobile, "Mobile-only");
test("editor renders at narrow viewport", async ({ frigateApp }) => {
await frigateApp.installDefaults({ configRaw: SAMPLE_CONFIG });
await frigateApp.goto("/config");
await expect(frigateApp.page.locator(".monaco-editor").first()).toBeVisible(
{ timeout: 15_000 },
);
await expect(editor.first()).toBeVisible({ timeout: 10_000 });
});
test("config editor has action buttons", async ({ frigateApp }) => {
await frigateApp.goto("/config");
await frigateApp.page.waitForTimeout(5000);
const buttons = frigateApp.page.locator("button");
const count = await buttons.count();
expect(count).toBeGreaterThan(0);
});
test("config editor button clicks do not crash", async ({ frigateApp }) => {
await frigateApp.goto("/config");
await frigateApp.page.waitForTimeout(5000);
// Find buttons with SVG icons (copy, save, etc.)
const iconButtons = frigateApp.page.locator("button:has(svg)");
const count = await iconButtons.count();
if (count > 0) {
// Click the first icon button (likely copy)
await iconButtons.first().click();
await frigateApp.page.waitForTimeout(500);
}
await expect(frigateApp.page.locator("body")).toBeVisible();
});
});
+240 -72
View File
@@ -1,97 +1,265 @@
/**
* Explore page tests -- HIGH tier.
*
* Tests search input with text entry and clearing, camera filter popover
* opening with camera names, and content rendering with mock events.
* Search input, Enter submission, camera filter popover (desktop),
* event grid rendering with mocked events, mobile filter drawer.
*
* DEVIATION NOTES (from original plan):
*
* 1. Search input: InputWithTags is only rendered when
* config.semantic_search.enabled is true. Tests that exercise the search
* input override the config accordingly, using model:"genai" (not in the
* JINA_EMBEDDING_MODELS list) so the page skips local model-state checks
* and renders without waiting for model-download WS messages.
*
* 2. Filter buttons (Cameras, Labels, More Filters): SearchFilterGroup is
* only rendered when hasExistingSearch is true. Tests navigate with a URL
* param (?labels=person) to surface the filter bar.
*
* 3. Cameras button: accessible name is "Cameras Filter" (aria-label), not
* "All Cameras" (inner text). Use getByLabel("Cameras Filter").
*
* 4. Labels: button accessible name is "Labels" (aria-label). With
* ?labels=person, the text shows "Person" rather than "All Labels".
* Use getByLabel("Labels").
*
* 5. Sub-labels / Zones: These live inside the "More Filters" dialog
* (SearchFilterDialog), not as standalone top-level buttons. The Zones
* test opens "More Filters" and asserts zone content from config.
*
* 6. similarity_search_id URL param: This param does not exist in the app.
* The correct entrypoint for similarity search is
* ?search_type=similarity&event_id=<id>. The test uses this URL and
* polls for the resulting API request.
*/
import { test, expect } from "../fixtures/frigate-test";
test.describe("Explore Page - Search @high", () => {
test("explore page renders with filter buttons", async ({ frigateApp }) => {
// Semantic search config override used by multiple tests. Using model:
// "genai" (not in JINA_EMBEDDING_MODELS) sets isGenaiEmbeddings=true, which
// skips local model-state checks and lets the page render without waiting for
// individual model download WS messages. The WS mocker returns a completed
// reindexState so !reindexState is false and the loading gate clears.
const SEMANTIC_SEARCH_CONFIG = {
semantic_search: { enabled: true, model: "genai" },
} as const;
// ---------------------------------------------------------------------------
// Search input (semantic_search must be enabled)
// ---------------------------------------------------------------------------
test.describe("Explore — search @high", () => {
test("search input accepts text and clears", async ({ frigateApp }) => {
// Enable semantic search so InputWithTags renders.
await frigateApp.installDefaults({ config: SEMANTIC_SEARCH_CONFIG });
await frigateApp.goto("/explore");
const searchInput = frigateApp.page.locator("input").first();
await expect(searchInput).toBeVisible({ timeout: 10_000 });
await searchInput.fill("person");
await expect(searchInput).toHaveValue("person");
await searchInput.fill("");
await expect(searchInput).toHaveValue("");
});
test("Enter submission does not crash the page", async ({ frigateApp }) => {
await frigateApp.installDefaults({ config: SEMANTIC_SEARCH_CONFIG });
await frigateApp.goto("/explore");
const searchInput = frigateApp.page.locator("input").first();
await expect(searchInput).toBeVisible({ timeout: 10_000 });
await searchInput.fill("car in driveway");
await searchInput.press("Enter");
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible();
const buttons = frigateApp.page.locator("#pageRoot button");
await expect(buttons.first()).toBeVisible({ timeout: 10_000 });
});
test("search input accepts text and can be cleared", async ({
frigateApp,
}) => {
await frigateApp.goto("/explore");
await frigateApp.page.waitForTimeout(1000);
const searchInput = frigateApp.page.locator("input").first();
if (await searchInput.isVisible()) {
await searchInput.fill("person");
await expect(searchInput).toHaveValue("person");
await searchInput.fill("");
await expect(searchInput).toHaveValue("");
}
});
test("search input submits on Enter", async ({ frigateApp }) => {
await frigateApp.goto("/explore");
await frigateApp.page.waitForTimeout(1000);
const searchInput = frigateApp.page.locator("input").first();
if (await searchInput.isVisible()) {
await searchInput.fill("car in driveway");
await searchInput.press("Enter");
await frigateApp.page.waitForTimeout(1000);
// Page should not crash after search submit
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible();
}
});
});
test.describe("Explore Page - Filters @high", () => {
test("camera filter button opens popover with camera names (desktop)", async ({
frigateApp,
}) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
await frigateApp.goto("/explore");
await frigateApp.page.waitForTimeout(1000);
const camerasBtn = frigateApp.page.getByRole("button", {
name: /cameras/i,
});
if (await camerasBtn.isVisible().catch(() => false)) {
await camerasBtn.click();
await frigateApp.page.waitForTimeout(500);
const popover = frigateApp.page.locator(
"[data-radix-popper-content-wrapper]",
);
await expect(popover.first()).toBeVisible({ timeout: 3_000 });
// Camera names from config should be in the popover
await expect(frigateApp.page.getByText("Front Door")).toBeVisible();
await frigateApp.page.keyboard.press("Escape");
}
// ---------------------------------------------------------------------------
// Filter bar — desktop only
// Filter buttons appear once hasExistingSearch is true (URL params present).
// ---------------------------------------------------------------------------
test.describe("Explore — filters (desktop) @high", () => {
test.skip(({ frigateApp }) => frigateApp.isMobile, "Desktop popovers");
test("Cameras popover lists configured cameras", async ({ frigateApp }) => {
// Navigate with a labels filter param so the filter bar renders.
await frigateApp.goto("/explore?labels=person");
// CamerasFilterButton has aria-label="Cameras Filter". Use getByLabel to
// match against the accessible name (not the inner "All Cameras" text).
const camerasBtn = frigateApp.page.getByLabel("Cameras Filter").first();
await expect(camerasBtn).toBeVisible({ timeout: 10_000 });
await camerasBtn.click();
// DropdownMenu on desktop wraps content in data-radix-popper-content-wrapper.
const popover = frigateApp.page.locator(
"[data-radix-popper-content-wrapper]",
);
await expect(popover.first()).toBeVisible({ timeout: 3_000 });
await expect(frigateApp.page.getByText("Front Door")).toBeVisible();
});
test("filter button opens and closes overlay cleanly", async ({
test("Labels filter lists labels from config", async ({ frigateApp }) => {
// Navigate with an existing search so the filter bar renders.
await frigateApp.goto("/explore?labels=person");
// GeneralFilterButton has aria-label="Labels". With ?labels=person the
// button text shows "Person" (the selected label), but the aria-label
// remains "Labels".
const labelsBtn = frigateApp.page.getByLabel("Labels").first();
await expect(labelsBtn).toBeVisible({ timeout: 10_000 });
await labelsBtn.click();
// PlatformAwareDialog renders on desktop as a dropdown/popover overlay.
const overlay = frigateApp.page.locator(
"[data-radix-popper-content-wrapper], [role='dialog'], [data-state='open']",
);
await expect(overlay.first()).toBeVisible({ timeout: 3_000 });
// "person" is already selected (it's in the URL); assert it appears in
// the overlay content.
await expect(overlay.first().getByText(/person/i)).toBeVisible();
await frigateApp.page.keyboard.press("Escape");
});
test("Sub-labels filter renders inside More Filters dialog", async ({
frigateApp,
}) => {
await frigateApp.goto("/explore");
await frigateApp.page.waitForTimeout(1000);
const firstButton = frigateApp.page.locator("#pageRoot button").first();
await expect(firstButton).toBeVisible({ timeout: 5_000 });
await firstButton.click();
await frigateApp.page.waitForTimeout(500);
// Sub-labels live inside SearchFilterDialog ("More Filters" button).
// With sub_labels mocked as [], the section still renders its heading.
await frigateApp.page.route("**/api/sub_labels**", (route) =>
route.fulfill({ json: [] }),
);
await frigateApp.goto("/explore?labels=person");
const moreBtn = frigateApp.page.getByLabel("More Filters").first();
await expect(moreBtn).toBeVisible({ timeout: 10_000 });
await moreBtn.click();
const overlay = frigateApp.page.locator(
"[data-radix-popper-content-wrapper], [role='dialog'], [data-state='open']",
);
await expect(overlay.first()).toBeVisible({ timeout: 3_000 });
// "Sub Labels" section heading always renders inside the dialog.
await expect(
frigateApp.page.getByText(/sub.?label/i).first(),
).toBeVisible();
await frigateApp.page.keyboard.press("Escape");
});
test("Zones filter lists configured zones inside More Filters dialog", async ({
frigateApp,
}) => {
// Override config to guarantee a known zone on front_door.
await frigateApp.installDefaults({
config: {
cameras: {
front_door: {
zones: {
front_yard: { coordinates: "0.1,0.1,0.9,0.1,0.9,0.9,0.1,0.9" },
},
},
},
},
});
await frigateApp.goto("/explore?labels=person");
const moreBtn = frigateApp.page.getByLabel("More Filters").first();
await expect(moreBtn).toBeVisible({ timeout: 10_000 });
await moreBtn.click();
const overlay = frigateApp.page.locator(
"[data-radix-popper-content-wrapper], [role='dialog'], [data-state='open']",
);
await expect(overlay.first()).toBeVisible({ timeout: 3_000 });
await expect(frigateApp.page.getByText(/front.?yard/i)).toBeVisible();
await frigateApp.page.keyboard.press("Escape");
await frigateApp.page.waitForTimeout(300);
// Page is still functional after open/close cycle
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible();
});
});
test.describe("Explore Page - Content @high", () => {
test("explore page shows content with mock events", async ({
// ---------------------------------------------------------------------------
// Content
// ---------------------------------------------------------------------------
test.describe("Explore — content @high", () => {
test("page renders with mock events", async ({ frigateApp }) => {
await frigateApp.goto("/explore");
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible({
timeout: 10_000,
});
await expect(
frigateApp.page.locator("#pageRoot button").first(),
).toBeVisible({ timeout: 10_000 });
});
test("empty events renders without crash", async ({ frigateApp }) => {
await frigateApp.installDefaults({ events: [] });
await frigateApp.goto("/explore");
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible({
timeout: 10_000,
});
});
test("search fires a /api/events request with the query", async ({
frigateApp,
}) => {
await frigateApp.installDefaults({ config: SEMANTIC_SEARCH_CONFIG });
const eventsRequests: string[] = [];
frigateApp.page.on("request", (req) => {
const url = req.url();
if (/\/api\/events/.test(url)) eventsRequests.push(url);
});
await frigateApp.goto("/explore");
await frigateApp.page.waitForTimeout(3000);
const pageText = await frigateApp.page.textContent("#pageRoot");
expect(pageText?.length).toBeGreaterThan(0);
const searchInput = frigateApp.page.locator("input").first();
await expect(searchInput).toBeVisible({ timeout: 10_000 });
const before = eventsRequests.length;
await searchInput.fill("person in driveway");
await searchInput.press("Enter");
await expect
.poll(() => eventsRequests.length > before, { timeout: 5_000 })
.toBe(true);
});
});
// ---------------------------------------------------------------------------
// Similarity search URL param
// ---------------------------------------------------------------------------
test.describe("Explore — similarity search (desktop) @high", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Similarity trigger is hover-based; desktop-focused",
);
test("URL similarity search params fetch events", async ({ frigateApp }) => {
const eventsRequests: string[] = [];
frigateApp.page.on("request", (req) => {
const url = req.url();
if (/\/api\/events/.test(url)) eventsRequests.push(url);
});
// The app uses search_type=similarity&event_id=<id> (not
// similarity_search_id). This exercises the same similarity search code
// path as clicking "Find Similar" on a thumbnail.
// Use a valid event-id format (timestamp.fractional-alphanumeric).
await frigateApp.goto(
"/explore?search_type=similarity&event_id=1712412000.000000-abc123",
);
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible({
timeout: 10_000,
});
// Poll to allow any pending SWR fetch to complete and be captured.
await expect
.poll(() => eventsRequests.length, { timeout: 5_000 })
.toBeGreaterThan(0);
});
});
// ---------------------------------------------------------------------------
// Mobile
// ---------------------------------------------------------------------------
test.describe("Explore — mobile @high @mobile", () => {
test.skip(({ frigateApp }) => !frigateApp.isMobile, "Mobile-only");
test("search input is focusable at mobile viewport", async ({
frigateApp,
}) => {
await frigateApp.installDefaults({ config: SEMANTIC_SEARCH_CONFIG });
await frigateApp.goto("/explore");
const searchInput = frigateApp.page.locator("input").first();
await expect(searchInput).toBeVisible({ timeout: 10_000 });
await searchInput.focus();
await expect(searchInput).toBeFocused();
});
});
+197
View File
@@ -732,3 +732,200 @@ test.describe("Multi-Review Export @high", () => {
});
});
});
test.describe("Export Page - Active Job Progress @medium", () => {
test("encoding job renders percent label and progress bar", async ({
frigateApp,
}) => {
// Override the default empty mock with an encoding job. Per-test
// page.route registrations win over those set by the api-mocker.
await frigateApp.page.route("**/api/jobs/export", (route) =>
route.fulfill({
json: [
{
id: "job-encoding",
job_type: "export",
status: "running",
camera: "front_door",
name: "Encoding Sample",
export_case_id: null,
request_start_time: 1775407931,
request_end_time: 1775408531,
start_time: 1775407932,
end_time: null,
error_message: null,
results: null,
current_step: "encoding",
progress_percent: 42,
},
],
}),
);
await frigateApp.goto("/export");
await expect(frigateApp.page.getByText("Encoding Sample")).toBeVisible();
// Step label and percent are rendered together as text near the
// progress bar (separated by a middle dot), not in a corner badge.
await expect(frigateApp.page.getByText(/Encoding\s*·\s*42%/)).toBeVisible();
});
test("queued job shows queued badge", async ({ frigateApp }) => {
await frigateApp.page.route("**/api/jobs/export", (route) =>
route.fulfill({
json: [
{
id: "job-queued",
job_type: "export",
status: "queued",
camera: "front_door",
name: "Queued Sample",
export_case_id: null,
request_start_time: 1775407931,
request_end_time: 1775408531,
start_time: null,
end_time: null,
error_message: null,
results: null,
current_step: "queued",
progress_percent: 0,
},
],
}),
);
await frigateApp.goto("/export");
await expect(frigateApp.page.getByText("Queued Sample")).toBeVisible();
await expect(
frigateApp.page.getByText("Queued", { exact: true }),
).toBeVisible();
});
test("active job hides matching in_progress export row", async ({
frigateApp,
}) => {
// The backend inserts the Export row with in_progress=True before
// FFmpeg starts encoding, so the same id appears in BOTH /jobs/export
// and /exports during the run. The page must show the rich progress
// card from the active jobs feed and suppress the binary-spinner
// ExportCard from the exports feed; otherwise the older binary
// spinner replaces the percent label as soon as SWR re-polls.
await frigateApp.page.route("**/api/jobs/export", (route) =>
route.fulfill({
json: [
{
id: "shared-id",
job_type: "export",
status: "running",
camera: "front_door",
name: "Shared Id Encoding",
export_case_id: null,
request_start_time: 1775407931,
request_end_time: 1775408531,
start_time: 1775407932,
end_time: null,
error_message: null,
results: null,
current_step: "encoding",
progress_percent: 67,
},
],
}),
);
await frigateApp.page.route("**/api/exports**", (route) => {
if (route.request().method() !== "GET") {
return route.fallback();
}
return route.fulfill({
json: [
{
id: "shared-id",
camera: "front_door",
name: "Shared Id Encoding",
date: 1775407931,
video_path: "/exports/shared-id.mp4",
thumb_path: "/exports/shared-id-thumb.jpg",
in_progress: true,
export_case_id: null,
},
],
});
});
await frigateApp.goto("/export");
// The progress label must be present — proving the rich card won.
await expect(frigateApp.page.getByText(/Encoding\s*·\s*67%/)).toBeVisible();
// And only ONE card should be visible for that id, not two.
const titles = frigateApp.page.getByText("Shared Id Encoding");
await expect(titles).toHaveCount(1);
});
test("stream copy job shows copying label", async ({ frigateApp }) => {
// Default (non-custom) exports use `-c copy`, which is a remux, not
// a real encode. The step label should read "Copying" so users
// aren't misled into thinking re-encoding is happening.
await frigateApp.page.route("**/api/jobs/export", (route) =>
route.fulfill({
json: [
{
id: "job-copying",
job_type: "export",
status: "running",
camera: "front_door",
name: "Copy Sample",
export_case_id: null,
request_start_time: 1775407931,
request_end_time: 1775408531,
start_time: 1775407932,
end_time: null,
error_message: null,
results: null,
current_step: "copying",
progress_percent: 80,
},
],
}),
);
await frigateApp.goto("/export");
await expect(frigateApp.page.getByText("Copy Sample")).toBeVisible();
await expect(frigateApp.page.getByText(/Copying\s*·\s*80%/)).toBeVisible();
});
test("encoding retry job shows retry label", async ({ frigateApp }) => {
await frigateApp.page.route("**/api/jobs/export", (route) =>
route.fulfill({
json: [
{
id: "job-retry",
job_type: "export",
status: "running",
camera: "front_door",
name: "Retry Sample",
export_case_id: null,
request_start_time: 1775407931,
request_end_time: 1775408531,
start_time: 1775407932,
end_time: null,
error_message: null,
results: null,
current_step: "encoding_retry",
progress_percent: 12,
},
],
}),
);
await frigateApp.goto("/export");
await expect(frigateApp.page.getByText("Retry Sample")).toBeVisible();
await expect(
frigateApp.page.getByText(/Encoding \(retry\)\s*·\s*12%/),
).toBeVisible();
});
});
+375 -17
View File
@@ -1,32 +1,390 @@
/**
* Face Library page tests -- MEDIUM tier.
* Face Library page tests -- HIGH tier.
*
* Tests face grid rendering, empty state, and interactive controls.
* Collection selector, face tiles, grouped recent-recognition dialog
* (migrated from radix-overlay-regressions.spec.ts), and mobile
* library selector.
*/
import { test, expect } from "../fixtures/frigate-test";
import { type Locator } from "@playwright/test";
import { test, expect, type FrigateApp } from "../fixtures/frigate-test";
import {
basicFacesMock,
emptyFacesMock,
withGroupedTrainingAttempt,
} from "../fixtures/mock-data/faces";
import {
expectBodyInteractive,
waitForBodyInteractive,
} from "../helpers/overlay-interaction";
test.describe("Face Library @medium", () => {
test("face library page renders without crash", async ({ frigateApp }) => {
const GROUPED_EVENT_ID = "1775487131.3863528-abc123";
function groupedFacesMock() {
return withGroupedTrainingAttempt(basicFacesMock(), {
eventId: GROUPED_EVENT_ID,
attempts: [
{ timestamp: 1775487131.3863528, label: "unknown", score: 0.95 },
{ timestamp: 1775487132.3863528, label: "unknown", score: 0.91 },
],
});
}
async function installGroupedFaces(app: FrigateApp) {
await app.api.install({
events: [
{
id: GROUPED_EVENT_ID,
label: "person",
sub_label: null,
camera: "front_door",
start_time: 1775487131.3863528,
end_time: 1775487161.3863528,
false_positive: false,
zones: ["front_yard"],
thumbnail: null,
has_clip: true,
has_snapshot: true,
retain_indefinitely: false,
plus_id: null,
model_hash: "abc123",
detector_type: "cpu",
model_type: "ssd",
data: {
top_score: 0.92,
score: 0.92,
region: [0.1, 0.1, 0.5, 0.8],
box: [0.2, 0.15, 0.45, 0.75],
area: 0.18,
ratio: 0.6,
type: "object",
path_data: [],
},
},
],
faces: groupedFacesMock(),
});
}
async function openGroupedFaceDialog(app: FrigateApp): Promise<Locator> {
await installGroupedFaces(app);
await app.goto("/faces");
const groupedImage = app.page
.locator('img[src*="clips/faces/train/"]')
.first();
const groupedCard = groupedImage.locator("xpath=..");
await expect(groupedImage).toBeVisible({ timeout: 5_000 });
await groupedCard.click();
const dialog = app.page
.getByRole("dialog")
.filter({ has: app.page.locator('img[src*="clips/faces/train/"]') })
.first();
await expect(dialog).toBeVisible({ timeout: 5_000 });
await expect(dialog.locator('img[src*="clips/faces/train/"]')).toHaveCount(2);
return dialog;
}
/**
* Opens the LibrarySelector dropdown (the single button at the top-left of
* the Face Library page) and returns the dropdown menu locator.
*
* The LibrarySelector is a single DropdownMenu whose trigger shows the
* current tab name + count (e.g. "Recent Recognitions (0)"). Named face
* collections (alice, bob, charlie) are items inside this dropdown.
*/
async function openLibraryDropdown(app: FrigateApp): Promise<Locator> {
// The trigger is the first button on the page with a parenthesised count.
const trigger = app.page
.getByRole("button")
.filter({ hasText: /\(\d+\)/ })
.first();
await expect(trigger).toBeVisible({ timeout: 10_000 });
await trigger.click();
const menu = app.page
.locator('[role="menu"], [data-radix-menu-content]')
.first();
await expect(menu).toBeVisible({ timeout: 5_000 });
return menu;
}
test.describe("Face Library — collection selector @high", () => {
test("selector shows named face collections", async ({ frigateApp }) => {
await frigateApp.installDefaults({ faces: basicFacesMock() });
await frigateApp.goto("/faces");
// Named collections appear in the LibrarySelector dropdown.
const menu = await openLibraryDropdown(frigateApp);
await expect(menu.getByText(/alice/i).first()).toBeVisible({
timeout: 5_000,
});
});
test("empty state renders when no faces exist", async ({ frigateApp }) => {
await frigateApp.installDefaults({ faces: emptyFacesMock() });
await frigateApp.goto("/faces");
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible();
await expect(
frigateApp.page.locator('img[src*="/clips/faces/"]'),
).toHaveCount(0);
});
test("face library shows empty state with no faces", async ({
frigateApp,
}) => {
test("tiles render for each named collection", async ({ frigateApp }) => {
await frigateApp.installDefaults({ faces: basicFacesMock() });
await frigateApp.goto("/faces");
await frigateApp.page.waitForTimeout(2000);
// With empty faces mock, should show empty state or content
const text = await frigateApp.page.textContent("#pageRoot");
expect(text?.length).toBeGreaterThan(0);
// Open the dropdown — collections list shows "alice (2)" and "bob (1)".
const menu = await openLibraryDropdown(frigateApp);
await expect(
menu.locator('[role="menuitem"]').filter({ hasText: /alice/i }).first(),
).toBeVisible({ timeout: 5_000 });
await expect(
menu.locator('[role="menuitem"]').filter({ hasText: /bob/i }).first(),
).toBeVisible();
});
});
test("face library has interactive buttons", async ({ frigateApp }) => {
test.describe("Face Library — delete flow (desktop) @high", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Delete action menu is desktop-focused",
);
test("deleting a collection fires POST /faces/<name>/delete", async ({
frigateApp,
}) => {
let deleteUrl: string | null = null;
let deleteBody: unknown = null;
// Install base mocks first, then register our more-specific route AFTER
// so it takes priority over the ApiMocker catch-all (Playwright LIFO order).
await frigateApp.installDefaults({ faces: basicFacesMock() });
await frigateApp.page.route(
/\/api\/faces\/[^/]+\/delete/,
async (route) => {
deleteUrl = route.request().url();
deleteBody = route.request().postDataJSON();
await route.fulfill({ json: { success: true } });
},
);
await frigateApp.goto("/faces");
// Open the LibrarySelector dropdown and click the trash icon next
// to the alice row. The trash icon is a ghost-variant Button inside
// the DropdownMenuItem — it becomes visible on hover/focus.
const menu = await openLibraryDropdown(frigateApp);
const aliceRow = menu
.locator('[role="menuitem"]')
.filter({ hasText: /alice/i })
.first();
await expect(aliceRow).toBeVisible({ timeout: 5_000 });
// Hover first to make hover-only opacity-0 buttons visible.
await aliceRow.hover();
// The icon buttons have no aria-label or title. The row renders exactly
// two buttons in fixed source order: [0] LuPencil (rename), [1] LuTrash2
// (delete). This order is determined by FaceLibrary.tsx and is stable.
const trashBtn = aliceRow.locator("button").nth(1);
await trashBtn.click();
// The delete confirmation is a Dialog (not AlertDialog) in this flow.
const dialog = frigateApp.page.getByRole("dialog");
await expect(dialog).toBeVisible({ timeout: 5_000 });
await dialog
.getByRole("button", { name: /delete/i })
.first()
.click();
await expect
.poll(() => deleteUrl, { timeout: 5_000 })
.toMatch(/\/faces\/alice\/delete/);
expect(deleteBody).toMatchObject({ ids: expect.any(Array) });
});
});
test.describe("Face Library — rename flow (desktop) @high", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Rename action menu is desktop-focused",
);
test("renaming a collection fires PUT /faces/<name>/rename", async ({
frigateApp,
}) => {
let renameUrl: string | null = null;
let renameBody: unknown = null;
// Install base mocks first, then register our more-specific route AFTER
// so it takes priority over the ApiMocker catch-all (Playwright LIFO order).
await frigateApp.installDefaults({ faces: basicFacesMock() });
await frigateApp.page.route(
/\/api\/faces\/[^/]+\/rename/,
async (route) => {
renameUrl = route.request().url();
renameBody = route.request().postDataJSON();
await route.fulfill({ json: { success: true } });
},
);
await frigateApp.goto("/faces");
// Open the LibrarySelector dropdown and click the pencil (rename) icon
// next to alice. The icon is a ghost Button inside the DropdownMenuItem.
const menu = await openLibraryDropdown(frigateApp);
const aliceRow = menu
.locator('[role="menuitem"]')
.filter({ hasText: /alice/i })
.first();
await expect(aliceRow).toBeVisible({ timeout: 5_000 });
await aliceRow.hover();
// The icon buttons have no aria-label or title. The row renders exactly
// two buttons in fixed source order: [0] LuPencil (rename), [1] LuTrash2
// (delete). This order is determined by FaceLibrary.tsx and is stable.
const pencilBtn = aliceRow.locator("button").nth(0);
await pencilBtn.click();
// TextEntryDialog — fill the input and confirm.
const dialog = frigateApp.page.getByRole("dialog");
await expect(dialog).toBeVisible({ timeout: 5_000 });
await dialog.locator("input").first().fill("alice_renamed");
await dialog
.getByRole("button", { name: /save|rename|confirm/i })
.first()
.click();
await expect
.poll(() => renameUrl, { timeout: 5_000 })
.toMatch(/\/faces\/alice\/rename/);
expect(renameBody).toEqual({ new_name: "alice_renamed" });
});
});
test.describe("Face Library — upload flow @high", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Upload button has no accessible text on mobile — icon-only on narrow viewports",
);
test("Upload button opens the upload dialog", async ({ frigateApp }) => {
await frigateApp.installDefaults({ faces: basicFacesMock() });
await frigateApp.goto("/faces");
// Navigate to the alice tab by opening the dropdown and clicking alice.
const menu = await openLibraryDropdown(frigateApp);
await menu
.locator('[role="menuitem"]')
.filter({ hasText: /alice/i })
.first()
.click();
// After switching to alice, the Upload Image button appears in the toolbar.
const uploadBtn = frigateApp.page
.getByRole("button")
.filter({ hasText: /upload/i })
.first();
await expect(uploadBtn).toBeVisible({ timeout: 5_000 });
await uploadBtn.click();
// UploadImageDialog renders a file input + confirm button.
const dialog = frigateApp.page.getByRole("dialog");
await expect(dialog).toBeVisible({ timeout: 5_000 });
await expect(dialog.locator('input[type="file"]')).toHaveCount(1);
});
});
test.describe("FaceSelectionDialog @high", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Grouped dropdown flow is desktop-only",
);
test("reclassify dropdown selects a name and closes cleanly", async ({
frigateApp,
}) => {
// Migrated from radix-overlay-regressions.spec.ts.
const dialog = await openGroupedFaceDialog(frigateApp);
const triggers = dialog.locator('[aria-haspopup="menu"]');
await expect(triggers).toHaveCount(2);
await triggers.first().click();
const menu = frigateApp.page
.locator('[role="menu"], [data-radix-menu-content]')
.first();
await expect(menu).toBeVisible({ timeout: 5_000 });
await menu.getByRole("menuitem", { name: /^bob$/i }).click();
await expect(menu).not.toBeVisible({ timeout: 3_000 });
await expect(dialog).toBeVisible();
const tooltipVisible = await frigateApp.page
.locator('[role="tooltip"]')
.filter({ hasText: /train face/i })
.isVisible()
.catch(() => false);
expect(
tooltipVisible,
"Train Face tooltip popped after dropdown closed — focus-restore regression",
).toBe(false);
});
test("second dropdown open accepts typeahead keyboard input", async ({
frigateApp,
}) => {
// Migrated from radix-overlay-regressions.spec.ts.
const dialog = await openGroupedFaceDialog(frigateApp);
const triggers = dialog.locator('[aria-haspopup="menu"]');
await expect(triggers).toHaveCount(2);
await triggers.first().click();
let menu = frigateApp.page
.locator('[role="menu"], [data-radix-menu-content]')
.first();
await expect(menu).toBeVisible({ timeout: 5_000 });
await menu.getByRole("menuitem", { name: /^bob$/i }).click();
await expect(menu).not.toBeVisible({ timeout: 3_000 });
await triggers.nth(1).click();
menu = frigateApp.page
.locator('[role="menu"], [data-radix-menu-content]')
.first();
await expect(menu).toBeVisible({ timeout: 5_000 });
await frigateApp.page.keyboard.press("c");
await expect
.poll(
async () =>
frigateApp.page.evaluate(
() =>
document.activeElement?.textContent?.trim().toLowerCase() ?? "",
),
{ timeout: 2_000 },
)
.toMatch(/^charlie/);
await frigateApp.page.keyboard.press("Escape");
await expect(menu).not.toBeVisible({ timeout: 3_000 });
});
});
test.describe("Face Library — mobile @high @mobile", () => {
test.skip(({ frigateApp }) => !frigateApp.isMobile, "Mobile-only");
test("mobile library selector dropdown closes cleanly on Escape", async ({
frigateApp,
}) => {
// Migrated from radix-overlay-regressions.spec.ts.
await installGroupedFaces(frigateApp);
await frigateApp.goto("/faces");
await frigateApp.page.waitForTimeout(2000);
const buttons = frigateApp.page.locator("#pageRoot button");
const count = await buttons.count();
expect(count).toBeGreaterThanOrEqual(0);
const selector = frigateApp.page
.getByRole("button")
.filter({ hasText: /\(\d+\)/ })
.first();
await expect(selector).toBeVisible({ timeout: 5_000 });
await selector.click();
const menu = frigateApp.page
.locator('[role="menu"], [data-radix-menu-content]')
.first();
await expect(menu).toBeVisible({ timeout: 3_000 });
await frigateApp.page.keyboard.press("Escape");
await expect(menu).not.toBeVisible({ timeout: 3_000 });
await waitForBodyInteractive(frigateApp.page);
await expectBodyInteractive(frigateApp.page);
});
});
+237 -201
View File
@@ -1,59 +1,47 @@
/**
* Live page tests -- CRITICAL tier.
*
* Tests camera dashboard rendering, camera card clicks, single camera view
* with named controls, feature toggle behavior, context menu, and mobile layout.
* Dashboard grid, single-camera controls, feature toggles (with WS
* frame assertions), context menu, birdseye, and mobile layout.
* Also absorbs the PTZ preset-dropdown regression tests from the
* now-deleted ptz-overlay.spec.ts.
*/
import { test, expect } from "../fixtures/frigate-test";
import { LivePage } from "../pages/live.page";
import { installWsFrameCapture, waitForWsFrame } from "../helpers/ws-frames";
import {
expectBodyInteractive,
waitForBodyInteractive,
} from "../helpers/overlay-interaction";
const PTZ_CAMERA = "front_door";
const PRESET_NAMES = ["home", "driveway", "front_porch"];
test.describe("Live Dashboard @critical", () => {
test("dashboard renders all configured cameras by name", async ({
test("every configured camera renders on the dashboard", async ({
frigateApp,
}) => {
await frigateApp.goto("/");
const live = new LivePage(frigateApp.page, !frigateApp.isMobile);
for (const cam of ["front_door", "backyard", "garage"]) {
await expect(
frigateApp.page.locator(`[data-camera='${cam}']`),
).toBeVisible({ timeout: 10_000 });
await expect(live.cameraCard(cam)).toBeVisible({ timeout: 10_000 });
}
});
test("clicking camera card opens single camera view via hash", async ({
test("clicking a camera card opens the single-camera view via hash", async ({
frigateApp,
}) => {
await frigateApp.goto("/");
const card = frigateApp.page.locator("[data-camera='front_door']").first();
await card.click({ timeout: 10_000 });
const live = new LivePage(frigateApp.page, !frigateApp.isMobile);
await live.cameraCard("front_door").first().click({ timeout: 10_000 });
await expect(frigateApp.page).toHaveURL(/#front_door/);
});
test("back button returns from single camera to dashboard", async ({
frigateApp,
}) => {
// First navigate to dashboard so there's history to go back to
await frigateApp.goto("/");
await frigateApp.page.waitForTimeout(1000);
// Click a camera to enter single view
const card = frigateApp.page.locator("[data-camera='front_door']").first();
await card.click({ timeout: 10_000 });
await frigateApp.page.waitForTimeout(2000);
// Now click Back to return to dashboard
const backBtn = frigateApp.page.getByText("Back", { exact: true });
if (await backBtn.isVisible().catch(() => false)) {
await backBtn.click();
await frigateApp.page.waitForTimeout(1000);
}
// Should be back on the dashboard with cameras visible
await expect(
frigateApp.page.locator("[data-camera='front_door']"),
).toBeVisible({ timeout: 10_000 });
});
test("birdseye view loads without crash", async ({ frigateApp }) => {
test("birdseye route renders without crash", async ({ frigateApp }) => {
await frigateApp.goto("/#birdseye");
await frigateApp.page.waitForTimeout(2000);
await expect(frigateApp.page.locator("body")).toBeVisible();
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible();
});
test("empty group shows fallback content", async ({ frigateApp }) => {
@@ -63,191 +51,239 @@ test.describe("Live Dashboard @critical", () => {
});
});
test.describe("Live Single Camera - Controls @critical", () => {
test("single camera view shows Back and History buttons (desktop)", async ({
test.describe("Live Single Camera — desktop controls @critical", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Desktop-only header controls",
);
test("single-camera view shows Back and History buttons", async ({
frigateApp,
}) => {
if (frigateApp.isMobile) {
test.skip(); // On mobile, buttons may show icons only
return;
}
await frigateApp.goto("/#front_door");
await frigateApp.page.waitForTimeout(2000);
// Back and History are visible text buttons in the header
await expect(
frigateApp.page.getByText("Back", { exact: true }),
).toBeVisible({ timeout: 5_000 });
await expect(
frigateApp.page.getByText("History", { exact: true }),
).toBeVisible();
const live = new LivePage(frigateApp.page, true);
await expect(live.backButton).toBeVisible({ timeout: 5_000 });
await expect(live.historyButton).toBeVisible();
});
test("single camera view shows feature toggle icons (desktop)", async ({
frigateApp,
}) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
test("feature toggles render (at least 3)", async ({ frigateApp }) => {
await frigateApp.goto("/#front_door");
await frigateApp.page.waitForTimeout(2000);
// Feature toggles are CameraFeatureToggle components rendered as divs
// with bg-selected (active) or bg-secondary (inactive) classes
// Count the toggles - should have at least detect, recording, snapshots
const toggles = frigateApp.page.locator(
".flex.flex-col.items-center.justify-center.bg-selected, .flex.flex-col.items-center.justify-center.bg-secondary",
);
const count = await toggles.count();
const live = new LivePage(frigateApp.page, true);
// Wait for the single-camera header to render before counting toggles.
await expect(live.backButton).toBeVisible({ timeout: 5_000 });
await expect(live.featureToggles.first()).toBeVisible({ timeout: 5_000 });
const count = await live.featureToggles.count();
expect(count).toBeGreaterThanOrEqual(3);
});
test("clicking a feature toggle changes its visual state (desktop)", async ({
test("clicking a feature toggle sends the matching WS frame", async ({
frigateApp,
}) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
await installWsFrameCapture(frigateApp.page);
await frigateApp.goto("/#front_door");
await frigateApp.page.waitForTimeout(2000);
// Find active toggles (bg-selected class = feature is ON)
const activeToggles = frigateApp.page.locator(
".flex.flex-col.items-center.justify-center.bg-selected",
const live = new LivePage(frigateApp.page, true);
// Wait for feature toggles to render (WS camera_activity must arrive first).
await expect(live.activeFeatureToggles.first()).toBeVisible({
timeout: 5_000,
});
const activeBefore = await live.activeFeatureToggles.count();
expect(activeBefore).toBeGreaterThan(0);
await live.activeFeatureToggles.first().click();
// The toggle dispatches a frame on <camera>/<feature>/set — match on
// front_door/ prefix + /set suffix (any feature).
await waitForWsFrame(
frigateApp.page,
(frame) => frame.includes("front_door/") && frame.includes("/set"),
{
message:
"feature toggle should dispatch a <camera>/<feature>/set frame",
},
);
const initialCount = await activeToggles.count();
if (initialCount > 0) {
// Click the first active toggle to disable it
await activeToggles.first().click();
await frigateApp.page.waitForTimeout(1000);
// After WS mock echoes back new state, count should decrease
const newCount = await activeToggles.count();
expect(newCount).toBeLessThan(initialCount);
}
});
test("settings gear button opens dropdown (desktop)", async ({
frigateApp,
}) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
await frigateApp.goto("/#front_door");
await frigateApp.page.waitForTimeout(2000);
// Find the gear icon button (last button-like element in header)
// The settings gear opens a dropdown with Stream, Play in background, etc.
const gearButtons = frigateApp.page.locator("button:has(svg)");
const count = await gearButtons.count();
// Click the last one (gear icon is typically last in the header)
if (count > 0) {
await gearButtons.last().click();
await frigateApp.page.waitForTimeout(500);
// A dropdown or drawer should appear
const overlay = frigateApp.page.locator(
'[role="menu"], [data-radix-menu-content], [role="dialog"]',
);
const visible = await overlay
.first()
.isVisible()
.catch(() => false);
if (visible) {
await frigateApp.page.keyboard.press("Escape");
}
}
});
test("keyboard shortcut f does not crash on desktop", async ({
frigateApp,
}) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
test("keyboard shortcut f does not crash", async ({ frigateApp }) => {
await frigateApp.goto("/");
await frigateApp.page.keyboard.press("f");
await frigateApp.page.waitForTimeout(500);
await expect(frigateApp.page.locator("body")).toBeVisible();
// Note: headless Chromium rejects fullscreen requests without a user
// gesture, so document.fullscreenElement cannot be asserted reliably
// in e2e. We assert the keypress doesn't crash the app; real
// fullscreen behavior is covered by manual testing.
});
test("settings gear opens a dropdown with Stream/Play menu items", async ({
frigateApp,
}) => {
await frigateApp.goto("/#front_door");
// Wait for the single-camera view to render — use the Back button
// as a deterministic marker.
const live = new LivePage(frigateApp.page, true);
await expect(live.backButton).toBeVisible({ timeout: 10_000 });
// The gear icon button is the last button-like element in the
// single-camera header. Clicking it opens a Radix dropdown.
const gearButtons = frigateApp.page.locator("button:has(svg)");
const count = await gearButtons.count();
expect(count).toBeGreaterThan(0);
await gearButtons.last().click();
const menu = frigateApp.page
.locator('[role="menu"], [data-radix-menu-content]')
.first();
await expect(menu).toBeVisible({ timeout: 3_000 });
await frigateApp.page.keyboard.press("Escape");
await expect(menu).not.toBeVisible({ timeout: 3_000 });
});
});
test.describe("Live Context Menu (desktop) @critical", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Right-click is desktop-only",
);
test("right-click opens the context menu", async ({ frigateApp }) => {
await frigateApp.goto("/");
const live = new LivePage(frigateApp.page, true);
const menu = await live.openContextMenuOn("front_door");
await expect(menu).toBeVisible({ timeout: 5_000 });
});
test("context menu closes on Escape and leaves body interactive", async ({
frigateApp,
}) => {
await frigateApp.goto("/");
const live = new LivePage(frigateApp.page, true);
const menu = await live.openContextMenuOn("front_door");
await expect(menu).toBeVisible({ timeout: 5_000 });
await frigateApp.page.keyboard.press("Escape");
await expect(menu).not.toBeVisible();
await waitForBodyInteractive(frigateApp.page);
await expectBodyInteractive(frigateApp.page);
});
});
test.describe("Live PTZ preset dropdown @critical", () => {
// Migrated from ptz-overlay.spec.ts. Guards:
// 1. After selecting a preset, the "Presets" tooltip must not re-pop.
// 2. Keyboard shortcuts after close should not re-open the dropdown.
test("selecting a preset closes menu cleanly and does not re-open on keyboard", async ({
frigateApp,
}) => {
test.skip(frigateApp.isMobile, "PTZ preset dropdown is desktop-only");
await frigateApp.api.install({
config: {
cameras: {
[PTZ_CAMERA]: { onvif: { host: "10.0.0.50" } },
},
},
});
await frigateApp.page.route(`**/api/${PTZ_CAMERA}/ptz/info`, (route) =>
route.fulfill({
json: {
name: PTZ_CAMERA,
features: ["pt", "zoom"],
presets: PRESET_NAMES,
profiles: [],
},
}),
);
await installWsFrameCapture(frigateApp.page);
await frigateApp.goto(`/#${PTZ_CAMERA}`);
const presetTrigger = frigateApp.page.getByRole("button", {
name: /presets/i,
});
await expect(presetTrigger.first()).toBeVisible({ timeout: 5_000 });
await presetTrigger.first().click();
const menu = frigateApp.page
.locator('[role="menu"], [data-radix-menu-content]')
.first();
await expect(menu).toBeVisible({ timeout: 3_000 });
await menu.getByRole("menuitem", { name: PRESET_NAMES[0] }).first().click();
await expect(menu).not.toBeVisible({ timeout: 3_000 });
await waitForWsFrame(
frigateApp.page,
(frame) =>
frame.includes(`"${PTZ_CAMERA}/ptz"`) &&
frame.includes(`preset_${PRESET_NAMES[0]}`),
);
await waitForBodyInteractive(frigateApp.page);
await expectBodyInteractive(frigateApp.page);
await expect
.poll(
async () =>
frigateApp.page
.locator('[role="tooltip"]')
.filter({ hasText: /presets/i })
.isVisible()
.catch(() => false),
{ timeout: 1_000 },
)
.toBe(false);
await frigateApp.page.keyboard.press("ArrowUp");
await frigateApp.page.keyboard.press("Space");
await frigateApp.page.keyboard.press("Enter");
await expect
.poll(() => menu.isVisible().catch(() => false), { timeout: 1_000 })
.toBe(false);
});
});
test.describe("Live mobile layout @critical @mobile", () => {
test("mobile dashboard has no sidebar and renders cameras", async ({
frigateApp,
}) => {
test.skip(!frigateApp.isMobile, "Mobile-only");
await frigateApp.goto("/");
await expect(frigateApp.page.locator("aside")).toHaveCount(0);
const live = new LivePage(frigateApp.page, false);
await expect(live.cameraCard("front_door")).toBeVisible({
timeout: 10_000,
});
});
test("mobile camera tap opens single view", async ({ frigateApp }) => {
test.skip(!frigateApp.isMobile, "Mobile-only");
await frigateApp.goto("/");
const live = new LivePage(frigateApp.page, false);
await live.cameraCard("front_door").first().click({ timeout: 10_000 });
await expect(frigateApp.page).toHaveURL(/#front_door/);
});
test("mobile onvif single-camera view loads without freezing body", async ({
frigateApp,
}) => {
test.skip(!frigateApp.isMobile, "Mobile-only");
// Migrated from ptz-overlay.spec.ts — dismissable-layer dedupe smoke test.
await frigateApp.api.install({
config: {
cameras: { [PTZ_CAMERA]: { onvif: { host: "10.0.0.50" } } },
},
});
await frigateApp.page.route(`**/api/${PTZ_CAMERA}/ptz/info`, (route) =>
route.fulfill({
json: {
name: PTZ_CAMERA,
features: ["pt", "zoom"],
presets: PRESET_NAMES,
profiles: [],
},
}),
);
await frigateApp.goto(`/#${PTZ_CAMERA}`);
await expectBodyInteractive(frigateApp.page);
await expect(frigateApp.page.locator("body")).toBeVisible();
});
});
test.describe("Live Single Camera - Mobile Controls @critical", () => {
test("mobile camera view has settings drawer trigger", async ({
frigateApp,
}) => {
if (!frigateApp.isMobile) {
test.skip();
return;
}
await frigateApp.goto("/#front_door");
await frigateApp.page.waitForTimeout(2000);
// On mobile, settings gear opens a drawer
// The button has aria-label with the camera name like "front_door Settings"
const buttons = frigateApp.page.locator("button:has(svg)");
const count = await buttons.count();
expect(count).toBeGreaterThan(0);
});
});
test.describe("Live Context Menu @critical", () => {
test("right-click on camera opens context menu on desktop", async ({
frigateApp,
}) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
await frigateApp.goto("/");
const card = frigateApp.page.locator("[data-camera='front_door']").first();
await card.waitFor({ state: "visible", timeout: 10_000 });
await card.click({ button: "right" });
const contextMenu = frigateApp.page.locator(
'[role="menu"], [data-radix-menu-content]',
);
await expect(contextMenu.first()).toBeVisible({ timeout: 5_000 });
});
test("context menu closes on escape", async ({ frigateApp }) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
await frigateApp.goto("/");
const card = frigateApp.page.locator("[data-camera='front_door']").first();
await card.waitFor({ state: "visible", timeout: 10_000 });
await card.click({ button: "right" });
await frigateApp.page.waitForTimeout(500);
await frigateApp.page.keyboard.press("Escape");
await frigateApp.page.waitForTimeout(300);
const contextMenu = frigateApp.page.locator(
'[role="menu"], [data-radix-menu-content]',
);
await expect(contextMenu).not.toBeVisible();
});
});
test.describe("Live Mobile Layout @critical", () => {
test("mobile renders cameras without sidebar", async ({ frigateApp }) => {
if (!frigateApp.isMobile) {
test.skip();
return;
}
await frigateApp.goto("/");
await expect(frigateApp.page.locator("aside")).not.toBeVisible();
await expect(
frigateApp.page.locator("[data-camera='front_door']"),
).toBeVisible({ timeout: 10_000 });
});
test("mobile camera click opens single camera view", async ({
frigateApp,
}) => {
if (!frigateApp.isMobile) {
test.skip();
return;
}
await frigateApp.goto("/");
const card = frigateApp.page.locator("[data-camera='front_door']").first();
await card.click({ timeout: 10_000 });
await expect(frigateApp.page).toHaveURL(/#front_door/);
});
});
+209 -62
View File
@@ -1,75 +1,222 @@
/**
* Logs page tests -- MEDIUM tier.
*
* Tests service tab switching by name, copy/download buttons,
* and websocket message feed tab.
* Service tabs (with real /logs/<service> JSON contract),
* log content render, Copy (clipboard), Download (assert
* ?download=true request fired), mobile tab selector.
*/
import { test, expect } from "../fixtures/frigate-test";
import { grantClipboardPermissions, readClipboard } from "../helpers/clipboard";
test.describe("Logs Page - Service Tabs @medium", () => {
test("logs page renders with named service tabs", async ({ frigateApp }) => {
function logsJsonBody(lines: string[]) {
return { lines, totalLines: lines.length };
}
test.describe("Logs — service tabs @medium", () => {
test("frigate tab renders by default with mocked log lines", async ({
frigateApp,
}) => {
await frigateApp.page.route(/\/api\/logs\/frigate(\?|$)/, (route) =>
route.fulfill({
json: logsJsonBody([
"[2026-04-06 10:00:00] INFO: Frigate started",
"[2026-04-06 10:00:01] INFO: Cameras loaded",
]),
}),
);
// Silence the streaming fetch so it doesn't hang the test.
await frigateApp.page.route(/\/api\/logs\/frigate\?stream=true/, (route) =>
route.fulfill({ status: 200, body: "" }),
);
await frigateApp.goto("/logs");
await expect(frigateApp.page.getByLabel("Select frigate")).toBeVisible({
timeout: 5_000,
});
await expect(frigateApp.page.getByText(/Frigate started/)).toBeVisible({
timeout: 10_000,
});
});
test("switching to go2rtc fires a GET to /logs/go2rtc", async ({
frigateApp,
}) => {
let go2rtcCalled = false;
await frigateApp.page.route(/\/api\/logs\/frigate(\?|$)/, (route) =>
route.fulfill({ json: logsJsonBody(["frigate line"]) }),
);
await frigateApp.page.route(/\/api\/logs\/go2rtc(\?|$)/, (route) => {
if (!route.request().url().includes("stream=true")) {
go2rtcCalled = true;
}
return route.fulfill({ json: logsJsonBody(["go2rtc line"]) });
});
await frigateApp.page.route(/\/api\/logs\/.*\?stream=true/, (route) =>
route.fulfill({ status: 200, body: "" }),
);
await frigateApp.goto("/logs");
await expect(frigateApp.page.getByLabel("Select frigate")).toBeVisible({
timeout: 5_000,
});
const go2rtcTab = frigateApp.page.getByLabel("Select go2rtc");
await expect(go2rtcTab).toBeVisible();
await go2rtcTab.click();
await expect.poll(() => go2rtcCalled, { timeout: 5_000 }).toBe(true);
await expect(go2rtcTab).toHaveAttribute("data-state", "on");
});
});
test.describe("Logs — actions @medium", () => {
test("Copy button writes current logs to clipboard", async ({
frigateApp,
context,
}) => {
await grantClipboardPermissions(context);
await frigateApp.page.route(/\/api\/logs\/frigate(\?|$)/, (route) =>
route.fulfill({
json: logsJsonBody([
"[2026-04-06 10:00:00] INFO: Frigate started",
"[2026-04-06 10:00:01] INFO: Cameras loaded",
]),
}),
);
await frigateApp.page.route(/\/api\/logs\/frigate\?stream=true/, (route) =>
route.fulfill({ status: 200, body: "" }),
);
await frigateApp.goto("/logs");
await expect(frigateApp.page.getByText(/Frigate started/)).toBeVisible({
timeout: 10_000,
});
const copyBtn = frigateApp.page.getByLabel("Copy to Clipboard");
await expect(copyBtn).toBeVisible({ timeout: 5_000 });
await copyBtn.click();
await expect
.poll(() => readClipboard(frigateApp.page), { timeout: 5_000 })
.toContain("Frigate started");
});
test("Download button fires GET /logs/<service>?download=true", async ({
frigateApp,
}) => {
let downloadCalled = false;
await frigateApp.page.route(/\/api\/logs\/frigate(\?|$)/, (route) => {
if (route.request().url().includes("download=true")) {
downloadCalled = true;
}
return route.fulfill({ json: logsJsonBody(["frigate line"]) });
});
await frigateApp.page.route(/\/api\/logs\/frigate\?stream=true/, (route) =>
route.fulfill({ status: 200, body: "" }),
);
await frigateApp.goto("/logs");
const downloadBtn = frigateApp.page.getByLabel("Download Logs");
await expect(downloadBtn).toBeVisible({ timeout: 5_000 });
await downloadBtn.click();
await expect.poll(() => downloadCalled, { timeout: 5_000 }).toBe(true);
});
});
test.describe("Logs — websocket tab @medium", () => {
test("switching to websocket tab renders WsMessageFeed container", async ({
frigateApp,
}) => {
await frigateApp.page.route(/\/api\/logs\/frigate(\?|$)/, (route) =>
route.fulfill({ json: logsJsonBody(["frigate line"]) }),
);
await frigateApp.page.route(/\/api\/logs\/frigate\?stream=true/, (route) =>
route.fulfill({ status: 200, body: "" }),
);
await frigateApp.goto("/logs");
const wsTab = frigateApp.page.getByLabel("Select websocket");
await expect(wsTab).toBeVisible({ timeout: 5_000 });
await wsTab.click();
await expect(wsTab).toHaveAttribute("data-state", "on", { timeout: 5_000 });
});
});
test.describe("Logs — streaming @medium", () => {
test("streamed log lines appear in the viewport", async ({ frigateApp }) => {
await frigateApp.page.route(/\/api\/logs\/frigate(\?|$)/, (route) => {
if (route.request().url().includes("stream=true")) {
// Intercepted below via addInitScript fetch override.
return route.fallback();
}
return route.fulfill({
json: logsJsonBody(["[2026-04-06 10:00:00] INFO: initial batch line"]),
});
});
// Override window.fetch so the /api/logs/frigate?stream=true request
// resolves with a real ReadableStream that emits chunks over time.
// This is the only way to validate streaming-append behavior through
// Playwright — route.fulfill() cannot return a stream.
// NOTE: The app calls fetch('api/logs/...') with a relative URL (no
// leading slash), so we match both relative and absolute forms.
await frigateApp.page.addInitScript(() => {
const origFetch = window.fetch;
window.fetch = async (input, init) => {
const url =
typeof input === "string"
? input
: input instanceof URL
? input.toString()
: (input as Request).url;
if (url.includes("api/logs/frigate") && url.includes("stream=true")) {
const encoder = new TextEncoder();
const stream = new ReadableStream({
async start(controller) {
await new Promise((r) => setTimeout(r, 30));
controller.enqueue(
encoder.encode(
"[2026-04-06 10:00:02] INFO: streamed line one\n",
),
);
await new Promise((r) => setTimeout(r, 30));
controller.enqueue(
encoder.encode(
"[2026-04-06 10:00:03] INFO: streamed line two\n",
),
);
controller.close();
},
});
return new Response(stream, { status: 200 });
}
return origFetch.call(window, input as RequestInfo, init);
};
});
await frigateApp.goto("/logs");
// The initial batch line is parsed by LogLineData and its content is
// rendered in a .log-content cell — assert against that element.
await expect(frigateApp.page.getByText("initial batch line")).toBeVisible({
timeout: 10_000,
});
await expect(frigateApp.page.getByText(/streamed line one/)).toBeVisible({
timeout: 10_000,
});
await expect(frigateApp.page.getByText(/streamed line two/)).toBeVisible({
timeout: 10_000,
});
});
});
test.describe("Logs — mobile @medium @mobile", () => {
test.skip(({ frigateApp }) => !frigateApp.isMobile, "Mobile-only");
test("service tabs render at mobile viewport", async ({ frigateApp }) => {
await frigateApp.page.route(/\/api\/logs\/frigate(\?|$)/, (route) =>
route.fulfill({ json: logsJsonBody(["frigate line"]) }),
);
await frigateApp.page.route(/\/api\/logs\/frigate\?stream=true/, (route) =>
route.fulfill({ status: 200, body: "" }),
);
await frigateApp.goto("/logs");
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible();
// Service tabs have aria-label="Select {service}"
await expect(frigateApp.page.getByLabel("Select frigate")).toBeVisible({
timeout: 5_000,
});
});
test("switching to go2rtc tab changes active tab", async ({ frigateApp }) => {
await frigateApp.goto("/logs");
await frigateApp.page.waitForTimeout(1000);
const go2rtcTab = frigateApp.page.getByLabel("Select go2rtc");
if (await go2rtcTab.isVisible().catch(() => false)) {
await go2rtcTab.click();
await frigateApp.page.waitForTimeout(1000);
await expect(go2rtcTab).toHaveAttribute("data-state", "on");
}
});
test("switching to websocket tab shows message feed", async ({
frigateApp,
}) => {
await frigateApp.goto("/logs");
await frigateApp.page.waitForTimeout(1000);
const wsTab = frigateApp.page.getByLabel("Select websocket");
if (await wsTab.isVisible().catch(() => false)) {
await wsTab.click();
await frigateApp.page.waitForTimeout(1000);
await expect(wsTab).toHaveAttribute("data-state", "on");
}
});
});
test.describe("Logs Page - Actions @medium", () => {
test("copy to clipboard button is present and clickable", async ({
frigateApp,
}) => {
await frigateApp.goto("/logs");
await frigateApp.page.waitForTimeout(1000);
const copyBtn = frigateApp.page.getByLabel("Copy to Clipboard");
if (await copyBtn.isVisible().catch(() => false)) {
await copyBtn.click();
await frigateApp.page.waitForTimeout(500);
// Should trigger clipboard copy (toast may appear)
}
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible();
});
test("download logs button is present", async ({ frigateApp }) => {
await frigateApp.goto("/logs");
await frigateApp.page.waitForTimeout(1000);
const downloadBtn = frigateApp.page.getByLabel("Download Logs");
if (await downloadBtn.isVisible().catch(() => false)) {
await expect(downloadBtn).toBeVisible();
}
});
test("logs page displays log content text", async ({ frigateApp }) => {
await frigateApp.goto("/logs");
await frigateApp.page.waitForTimeout(2000);
const text = await frigateApp.page.textContent("#pageRoot");
expect(text?.length).toBeGreaterThan(0);
});
});
+95 -156
View File
@@ -1,103 +1,78 @@
/**
* Navigation tests -- CRITICAL tier.
*
* Tests sidebar (desktop) and bottombar (mobile) navigation,
* conditional nav items, settings menus, and their actual behaviors.
* Covers sidebar (desktop) / bottombar (mobile) link set, conditional
* nav items (faces, chat, classification), settings menu navigation,
* unknown-route redirect to /, and mobile-specific nav behaviors.
*/
import { test, expect } from "../fixtures/frigate-test";
import { BasePage } from "../pages/base.page";
test.describe("Navigation @critical", () => {
test("app loads and renders page root", async ({ frigateApp }) => {
await frigateApp.goto("/");
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible();
});
const PRIMARY_ROUTES = ["/review", "/explore", "/export"] as const;
test("logo is visible and links to home", async ({ frigateApp }) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
await frigateApp.goto("/");
const base = new BasePage(frigateApp.page, true);
const logo = base.sidebar.locator('a[href="/"]').first();
await expect(logo).toBeVisible();
});
test("all primary nav links are present and navigate", async ({
test.describe("Navigation — primary links @critical", () => {
test("every primary link is visible and navigates", async ({
frigateApp,
}) => {
await frigateApp.goto("/");
const routes = ["/review", "/explore", "/export"];
for (const route of routes) {
for (const route of PRIMARY_ROUTES) {
await expect(
frigateApp.page.locator(`a[href="${route}"]`).first(),
).toBeVisible();
}
// Verify clicking each one actually navigates
const base = new BasePage(frigateApp.page, !frigateApp.isMobile);
for (const route of routes) {
for (const route of PRIMARY_ROUTES) {
await base.navigateTo(route);
await expect(frigateApp.page).toHaveURL(new RegExp(route));
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible();
}
});
test("desktop sidebar is visible, mobile bottombar is visible", async ({
frigateApp,
}) => {
await frigateApp.goto("/");
const base = new BasePage(frigateApp.page, !frigateApp.isMobile);
if (!frigateApp.isMobile) {
await expect(base.sidebar).toBeVisible();
} else {
await expect(base.sidebar).not.toBeVisible();
}
test("logo links home on desktop", async ({ frigateApp }) => {
test.skip(frigateApp.isMobile, "Sidebar logo is desktop-only");
await frigateApp.goto("/review");
await frigateApp.page.locator("aside a[href='/']").first().click();
await expect(frigateApp.page).toHaveURL(/\/$/);
});
test("navigate between all main pages without crash", async ({
frigateApp,
}) => {
await frigateApp.goto("/");
const base = new BasePage(frigateApp.page, !frigateApp.isMobile);
const pageRoot = frigateApp.page.locator("#pageRoot");
await base.navigateTo("/review");
await expect(pageRoot).toBeVisible({ timeout: 10_000 });
await base.navigateTo("/explore");
await expect(pageRoot).toBeVisible({ timeout: 10_000 });
await base.navigateTo("/export");
await expect(pageRoot).toBeVisible({ timeout: 10_000 });
await base.navigateTo("/review");
await expect(pageRoot).toBeVisible({ timeout: 10_000 });
});
test("unknown route redirects to home", async ({ frigateApp }) => {
test("unknown route redirects to /", async ({ frigateApp }) => {
await frigateApp.page.goto("/nonexistent-route");
await frigateApp.page.waitForTimeout(2000);
const url = frigateApp.page.url();
const hasPageRoot = await frigateApp.page
.locator("#pageRoot")
.isVisible()
.catch(() => false);
expect(url.endsWith("/") || hasPageRoot).toBeTruthy();
await frigateApp.page.waitForSelector("#pageRoot", { timeout: 10_000 });
await expect(frigateApp.page).toHaveURL(/\/$/);
await expect(
frigateApp.page.locator("[data-camera='front_door']"),
).toBeVisible({ timeout: 10_000 });
});
});
test.describe("Navigation - Conditional Items @critical", () => {
test("Faces nav hidden when face_recognition disabled", async ({
test.describe("Navigation — conditional items @critical", () => {
test("/faces is hidden when face_recognition.enabled is false", async ({
frigateApp,
}) => {
await frigateApp.goto("/");
await expect(frigateApp.page.locator('a[href="/faces"]')).not.toBeVisible();
await expect(
frigateApp.page.locator('a[href="/faces"]').first(),
).toHaveCount(0);
});
test("Chat nav hidden when genai model is none", async ({ frigateApp }) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
test("/faces is visible when face_recognition.enabled is true (desktop)", async ({
frigateApp,
}) => {
test.skip(frigateApp.isMobile, "Desktop sidebar");
await frigateApp.installDefaults({
config: { face_recognition: { enabled: true } },
});
await frigateApp.goto("/");
await expect(
frigateApp.page.locator('a[href="/faces"]').first(),
).toBeVisible();
});
test("/chat is hidden when genai.model is none (desktop)", async ({
frigateApp,
}) => {
test.skip(frigateApp.isMobile, "Desktop sidebar");
await frigateApp.installDefaults({
config: {
genai: {
@@ -109,119 +84,83 @@ test.describe("Navigation - Conditional Items @critical", () => {
},
});
await frigateApp.goto("/");
await expect(frigateApp.page.locator('a[href="/chat"]')).not.toBeVisible();
await expect(
frigateApp.page.locator('a[href="/chat"]').first(),
).toHaveCount(0);
});
test("Faces nav visible when face_recognition enabled on desktop", async ({
test("/chat is visible when genai.model is set (desktop)", async ({
frigateApp,
page,
}) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
await frigateApp.installDefaults({
config: { face_recognition: { enabled: true } },
});
await frigateApp.goto("/");
await expect(page.locator('a[href="/faces"]')).toBeVisible();
});
test("Chat nav visible when genai model set on desktop", async ({
frigateApp,
page,
}) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
test.skip(frigateApp.isMobile, "Desktop sidebar");
await frigateApp.installDefaults({
config: { genai: { enabled: true, model: "llava" } },
});
await frigateApp.goto("/");
await expect(page.locator('a[href="/chat"]')).toBeVisible();
await expect(
frigateApp.page.locator('a[href="/chat"]').first(),
).toBeVisible();
});
test("Classification nav visible for admin on desktop", async ({
test("/classification is visible for admin on desktop", async ({
frigateApp,
page,
}) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
test.skip(frigateApp.isMobile, "Desktop sidebar");
await frigateApp.goto("/");
await expect(page.locator('a[href="/classification"]')).toBeVisible();
await expect(
frigateApp.page.locator('a[href="/classification"]').first(),
).toBeVisible();
});
});
test.describe("Navigation - Settings Menu @critical", () => {
test("settings gear opens menu with navigation items (desktop)", async ({
frigateApp,
}) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
await frigateApp.goto("/");
// Settings gear is in the sidebar bottom section, a div with cursor-pointer
const sidebarBottom = frigateApp.page.locator("aside .mb-8");
const gearIcon = sidebarBottom
.locator("div[class*='cursor-pointer']")
.first();
await expect(gearIcon).toBeVisible({ timeout: 5_000 });
await gearIcon.click();
// Menu should open - look for the "Settings" menu item by aria-label
await expect(frigateApp.page.getByLabel("Settings")).toBeVisible({
timeout: 3_000,
});
});
test.describe("Navigation — settings menu (desktop) @critical", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Sidebar settings menu is desktop-only",
);
test("settings menu items navigate to correct routes (desktop)", async ({
frigateApp,
}) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
const targets = [
{ label: "Settings", url: "/settings" },
{ label: "System metrics", url: "/system" },
{ label: "System logs", url: "/logs" },
{ label: "Configuration Editor", url: "/config" },
];
for (const target of targets) {
const TARGETS = [
{ label: "Settings", url: /\/settings/ },
{ label: "System metrics", url: /\/system/ },
{ label: "System logs", url: /\/logs/ },
{ label: "Configuration Editor", url: /\/config/ },
];
for (const target of TARGETS) {
test(`menu → ${target.label} navigates`, async ({ frigateApp }) => {
await frigateApp.goto("/");
const gearIcon = frigateApp.page
const gear = frigateApp.page
.locator("aside .mb-8 div[class*='cursor-pointer']")
.first();
await gearIcon.click();
await frigateApp.page.waitForTimeout(300);
const menuItem = frigateApp.page.getByLabel(target.label);
if (await menuItem.isVisible().catch(() => false)) {
await menuItem.click();
await expect(frigateApp.page).toHaveURL(
new RegExp(target.url.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")),
);
}
await gear.click();
await frigateApp.page.getByLabel(target.label).click();
await expect(frigateApp.page).toHaveURL(target.url);
});
}
});
test.describe("Navigation — mobile @critical @mobile", () => {
test("mobile bottombar visible, sidebar not rendered", async ({
frigateApp,
}) => {
test.skip(!frigateApp.isMobile, "Mobile-only");
await frigateApp.goto("/");
await expect(frigateApp.page.locator("aside")).toHaveCount(0);
for (const route of PRIMARY_ROUTES) {
await expect(
frigateApp.page.locator(`a[href="${route}"]`).first(),
).toBeVisible();
}
});
test("account button in sidebar is clickable (desktop)", async ({
frigateApp,
}) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
test("mobile nav survives route change", async ({ frigateApp }) => {
test.skip(!frigateApp.isMobile, "Mobile-only");
await frigateApp.goto("/");
const sidebarBottom = frigateApp.page.locator("aside .mb-8");
const items = sidebarBottom.locator("div[class*='cursor-pointer']");
const count = await items.count();
if (count >= 2) {
await items.nth(1).click();
await frigateApp.page.waitForTimeout(500);
}
await expect(frigateApp.page.locator("body")).toBeVisible();
const reviewLink = frigateApp.page.locator('a[href="/review"]').first();
await reviewLink.click();
await expect(frigateApp.page).toHaveURL(/\/review/);
await expect(
frigateApp.page.locator('a[href="/review"]').first(),
).toBeVisible();
});
});
+292 -11
View File
@@ -1,23 +1,304 @@
/**
* Replay page tests -- LOW tier.
* Replay page tests -- MEDIUM tier.
*
* Tests replay page rendering and basic interactivity.
* /replay is the admin debug replay page (not a recordings player).
* Polls /api/debug_replay/status, renders a no-session state when
* inactive, and a live camera image + debug toggles + Stop controls
* when active.
*/
import { test, expect } from "../fixtures/frigate-test";
import {
activeSessionStatus,
noSessionStatus,
} from "../fixtures/mock-data/debug-replay";
test.describe("Replay Page @low", () => {
test("replay page renders without crash", async ({ frigateApp }) => {
async function installStatusRoute(
app: { page: import("@playwright/test").Page },
body: unknown,
) {
await app.page.route("**/api/debug_replay/status", (route) =>
route.fulfill({ json: body }),
);
}
test.describe("Replay — no active session @medium", () => {
test("empty state renders heading + Go to History button", async ({
frigateApp,
}) => {
await installStatusRoute(frigateApp, noSessionStatus());
await frigateApp.goto("/replay");
await frigateApp.page.waitForTimeout(2000);
await expect(frigateApp.page.locator("body")).toBeVisible();
await expect(
frigateApp.page.getByRole("heading", {
level: 2,
name: /No Active Replay Session/i,
}),
).toBeVisible({ timeout: 10_000 });
const goButton = frigateApp.page.getByRole("button", {
name: /Go to History|Go to Recordings/i,
});
await expect(goButton).toBeVisible();
});
test("replay page has interactive controls", async ({ frigateApp }) => {
test("clicking Go to History navigates to /review", async ({
frigateApp,
}) => {
await installStatusRoute(frigateApp, noSessionStatus());
await frigateApp.goto("/replay");
await frigateApp.page.waitForTimeout(2000);
const buttons = frigateApp.page.locator("button");
const count = await buttons.count();
expect(count).toBeGreaterThan(0);
await expect(
frigateApp.page.getByRole("heading", {
level: 2,
name: /No Active Replay Session/i,
}),
).toBeVisible({ timeout: 10_000 });
await frigateApp.page
.getByRole("button", { name: /Go to History|Go to Recordings/i })
.click();
await expect(frigateApp.page).toHaveURL(/\/review/);
});
});
test.describe("Replay — active session @medium", () => {
test("active status renders the Debug Replay side panel", async ({
frigateApp,
}) => {
await installStatusRoute(frigateApp, activeSessionStatus());
await frigateApp.goto("/replay");
await expect(
frigateApp.page.getByRole("heading", { level: 3, name: /Debug Replay/i }),
).toBeVisible({ timeout: 10_000 });
// Three tabs (Debug / Objects / Messages) in TabsList
await expect(frigateApp.page.locator('[role="tab"]')).toHaveCount(3);
});
test("debug toggles render with bbox ON by default", async ({
frigateApp,
}) => {
await installStatusRoute(frigateApp, activeSessionStatus());
await frigateApp.goto("/replay");
const bbox = frigateApp.page.locator("#debug-bbox");
await expect(bbox).toBeVisible({ timeout: 10_000 });
await expect(bbox).toHaveAttribute("aria-checked", "true");
});
test("clicking bbox toggle flips aria-checked", async ({ frigateApp }) => {
await installStatusRoute(frigateApp, activeSessionStatus());
await frigateApp.goto("/replay");
const bbox = frigateApp.page.locator("#debug-bbox");
await expect(bbox).toBeVisible({ timeout: 10_000 });
await expect(bbox).toHaveAttribute("aria-checked", "true");
await bbox.click();
await expect(bbox).toHaveAttribute("aria-checked", "false");
});
test("Configuration button opens the configuration dialog (desktop)", async ({
frigateApp,
}) => {
test.skip(frigateApp.isMobile, "Desktop: button has visible text label");
await installStatusRoute(frigateApp, activeSessionStatus());
await frigateApp.goto("/replay");
await expect(
frigateApp.page.getByRole("heading", { level: 3, name: /Debug Replay/i }),
).toBeVisible({ timeout: 10_000 });
// On desktop the span is visible and gives the button an accessible name.
await frigateApp.page
.getByRole("button", { name: /configuration/i })
.first()
.click();
const dialog = frigateApp.page.getByRole("dialog");
await expect(dialog).toBeVisible({ timeout: 5_000 });
});
test("Configuration button opens the configuration dialog (mobile)", async ({
frigateApp,
}) => {
test.skip(!frigateApp.isMobile, "Mobile: button is icon-only");
await installStatusRoute(frigateApp, activeSessionStatus());
await frigateApp.goto("/replay");
await expect(
frigateApp.page.getByRole("heading", { level: 3, name: /Debug Replay/i }),
).toBeVisible({ timeout: 10_000 });
// On mobile the Configuration button text span is hidden (md:inline).
// It is the first button inside the right-side action group div
// (the flex container that holds Config + Stop, sibling of the Back button).
const actionGroup = frigateApp.page.locator(
".flex.items-center.gap-2 button",
);
await actionGroup.first().click();
const dialog = frigateApp.page.getByRole("dialog");
await expect(dialog).toBeVisible({ timeout: 5_000 });
});
test("Objects tab renders with the camera_activity objects list", async ({
frigateApp,
}) => {
await installStatusRoute(frigateApp, activeSessionStatus());
await frigateApp.goto("/replay");
await expect(
frigateApp.page.getByRole("heading", { level: 3, name: /Debug Replay/i }),
).toBeVisible({ timeout: 10_000 });
// Send an activity payload with a person object on front_door.
// Must be called after goto() so the WS connection is established.
await frigateApp.ws.sendCameraActivity({
front_door: {
objects: [
{
label: "person",
score: 0.95,
box: [0.1, 0.1, 0.5, 0.8],
area: 0.2,
ratio: 0.6,
region: [0.05, 0.05, 0.6, 0.85],
current_zones: [],
id: "obj-person-1",
},
],
},
});
// Switch to Objects tab (labelled "Object List" in i18n).
const objectsTab = frigateApp.page.getByRole("tab", {
name: /object/i,
});
await objectsTab.click();
await expect(objectsTab).toHaveAttribute("data-state", "active", {
timeout: 3_000,
});
// The object row renders the label.
await expect(frigateApp.page.getByText(/person/i).first()).toBeVisible({
timeout: 5_000,
});
});
test("Messages tab renders WsMessageFeed container", async ({
frigateApp,
}) => {
await installStatusRoute(frigateApp, activeSessionStatus());
await frigateApp.goto("/replay");
await expect(
frigateApp.page.getByRole("heading", { level: 3, name: /Debug Replay/i }),
).toBeVisible({ timeout: 10_000 });
const messagesTab = frigateApp.page.getByRole("tab", {
name: /messages/i,
});
await messagesTab.click();
await expect(messagesTab).toHaveAttribute("data-state", "active", {
timeout: 3_000,
});
});
test("bbox info popover opens and closes cleanly", async ({ frigateApp }) => {
await installStatusRoute(frigateApp, activeSessionStatus());
await frigateApp.goto("/replay");
// The bbox row has an info icon popover trigger next to its label.
// The trigger is a div (not button) wrapping LuInfo with an sr-only
// "Info" span. Target it by the sr-only text content.
const infoTrigger = frigateApp.page
.locator("span.sr-only", { hasText: /info/i })
.first();
await expect(infoTrigger).toBeVisible({ timeout: 10_000 });
// Click the parent div (the actual trigger)
await infoTrigger.locator("..").click();
const popover = frigateApp.page.locator(
"[data-radix-popper-content-wrapper]",
);
await expect(popover.first()).toBeVisible({ timeout: 3_000 });
await frigateApp.page.keyboard.press("Escape");
await expect(popover.first()).not.toBeVisible({ timeout: 3_000 });
});
});
test.describe("Replay — stop flow (desktop) @medium", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Desktop button has accessible 'Stop Replay' name",
);
test("Stop Replay opens confirm dialog; confirm POSTs debug_replay/stop", async ({
frigateApp,
}) => {
await installStatusRoute(frigateApp, activeSessionStatus());
let stopCalled = false;
await frigateApp.page.route("**/api/debug_replay/stop", async (route) => {
if (route.request().method() === "POST") stopCalled = true;
await route.fulfill({ json: { success: true } });
});
await frigateApp.goto("/replay");
await expect(
frigateApp.page.getByRole("heading", { level: 3, name: /Debug Replay/i }),
).toBeVisible({ timeout: 10_000 });
await frigateApp.page
.getByRole("button", { name: /stop replay/i })
.first()
.click();
const dialog = frigateApp.page.getByRole("alertdialog");
await expect(dialog).toBeVisible({ timeout: 3_000 });
await dialog
.getByRole("button", { name: /stop|confirm/i })
.first()
.click();
await expect.poll(() => stopCalled, { timeout: 5_000 }).toBe(true);
});
});
test.describe("Replay — stop button (mobile) @medium @mobile", () => {
test.skip(
({ frigateApp }) => !frigateApp.isMobile,
"Mobile-only icon-button variant",
);
test("tapping the icon-only stop button opens the confirm dialog", async ({
frigateApp,
}) => {
await installStatusRoute(frigateApp, activeSessionStatus());
await frigateApp.goto("/replay");
await expect(
frigateApp.page.getByRole("heading", { level: 3, name: /Debug Replay/i }),
).toBeVisible({ timeout: 10_000 });
// On mobile the Stop button is an icon (LuSquare) inside an
// AlertDialogTrigger. It's the last button in the top bar's
// right-side action group (Back is on the left). Target by
// position within the top-bar flex container.
const topRightButtons = frigateApp.page
.locator(".min-h-12 button, .md\\:min-h-16 button")
.filter({ hasNot: frigateApp.page.getByLabel("Back") });
const lastButton = topRightButtons.last();
await expect(lastButton).toBeVisible({ timeout: 10_000 });
await lastButton.click();
const dialog = frigateApp.page.getByRole("alertdialog");
await expect(dialog).toBeVisible({ timeout: 3_000 });
await dialog.getByRole("button", { name: /cancel/i }).click();
await expect(dialog).not.toBeVisible({ timeout: 3_000 });
});
});
test.describe("Replay — mobile @medium @mobile", () => {
test.skip(({ frigateApp }) => !frigateApp.isMobile, "Mobile-only");
test("no-session state renders at mobile viewport", async ({
frigateApp,
}) => {
await installStatusRoute(frigateApp, noSessionStatus());
await frigateApp.goto("/replay");
await expect(
frigateApp.page.getByRole("heading", {
level: 2,
name: /No Active Replay Session/i,
}),
).toBeVisible({ timeout: 10_000 });
});
});
+188 -158
View File
@@ -1,200 +1,230 @@
/**
* Review/Events page tests -- CRITICAL tier.
*
* Tests severity tab switching by name (Alerts/Detections/Motion),
* filter popover opening with camera names, show reviewed toggle,
* calendar button, and filter button interactions.
* Severity tabs, filter popovers, calendar, show-reviewed toggle,
* timeline, and the nested-overlay regression migrated from
* radix-overlay-regressions.spec.ts.
*/
import { test, expect } from "../fixtures/frigate-test";
import { BasePage } from "../pages/base.page";
import { ReviewPage } from "../pages/review.page";
import {
expectBodyInteractive,
waitForBodyInteractive,
} from "../helpers/overlay-interaction";
test.describe("Review Page - Severity Tabs @critical", () => {
test("severity tabs render with Alerts, Detections, Motion", async ({
test.describe("Review — severity tabs @critical", () => {
test("tabs render with Alerts default-on", async ({ frigateApp }) => {
await frigateApp.goto("/review");
const review = new ReviewPage(frigateApp.page, !frigateApp.isMobile);
await expect(review.alertsTab).toBeVisible({ timeout: 10_000 });
await expect(review.detectionsTab).toBeVisible();
await expect(review.motionTab).toBeVisible();
await expect(review.alertsTab).toHaveAttribute("data-state", "on");
});
test("clicking Detections flips data-state", async ({ frigateApp }) => {
await frigateApp.goto("/review");
const review = new ReviewPage(frigateApp.page, !frigateApp.isMobile);
await expect(review.alertsTab).toBeVisible({ timeout: 10_000 });
await review.detectionsTab.click();
await expect(review.detectionsTab).toHaveAttribute("data-state", "on");
await expect(review.alertsTab).toHaveAttribute("data-state", "off");
});
test("clicking Motion flips data-state", async ({ frigateApp }) => {
await frigateApp.goto("/review");
const review = new ReviewPage(frigateApp.page, !frigateApp.isMobile);
await expect(review.alertsTab).toBeVisible({ timeout: 10_000 });
await review.motionTab.click();
await expect(review.motionTab).toHaveAttribute("data-state", "on");
});
test("switching back to Alerts works", async ({ frigateApp }) => {
await frigateApp.goto("/review");
const review = new ReviewPage(frigateApp.page, !frigateApp.isMobile);
await review.detectionsTab.click();
await expect(review.detectionsTab).toHaveAttribute("data-state", "on");
await review.alertsTab.click();
await expect(review.alertsTab).toHaveAttribute("data-state", "on");
});
test("switching tabs updates active data-state (client-side filter)", async ({
frigateApp,
}) => {
// The severity tabs filter the already-fetched review data client-side;
// they do not trigger a new /api/review network request. This test
// verifies the state-change assertion that the tab switch takes effect.
await frigateApp.goto("/review");
await expect(frigateApp.page.getByLabel("Alerts")).toBeVisible({
timeout: 10_000,
});
await expect(frigateApp.page.getByLabel("Detections")).toBeVisible();
// Motion uses role="radio" to distinguish from other Motion elements
await expect(
frigateApp.page.getByRole("radio", { name: "Motion" }),
).toBeVisible();
});
test("Alerts tab is active by default", async ({ frigateApp }) => {
await frigateApp.goto("/review");
await frigateApp.page.waitForTimeout(1000);
const alertsTab = frigateApp.page.getByLabel("Alerts");
await expect(alertsTab).toHaveAttribute("data-state", "on");
});
test("clicking Detections tab makes it active and deactivates Alerts", async ({
frigateApp,
}) => {
await frigateApp.goto("/review");
await frigateApp.page.waitForTimeout(1000);
const alertsTab = frigateApp.page.getByLabel("Alerts");
const detectionsTab = frigateApp.page.getByLabel("Detections");
await detectionsTab.click();
await frigateApp.page.waitForTimeout(500);
await expect(detectionsTab).toHaveAttribute("data-state", "on");
await expect(alertsTab).toHaveAttribute("data-state", "off");
});
test("clicking Motion tab makes it active", async ({ frigateApp }) => {
await frigateApp.goto("/review");
await frigateApp.page.waitForTimeout(1000);
const motionTab = frigateApp.page.getByRole("radio", { name: "Motion" });
await motionTab.click();
await frigateApp.page.waitForTimeout(500);
await expect(motionTab).toHaveAttribute("data-state", "on");
});
test("switching back to Alerts from Detections works", async ({
frigateApp,
}) => {
await frigateApp.goto("/review");
await frigateApp.page.waitForTimeout(1000);
await frigateApp.page.getByLabel("Detections").click();
await frigateApp.page.waitForTimeout(300);
await frigateApp.page.getByLabel("Alerts").click();
await frigateApp.page.waitForTimeout(300);
await expect(frigateApp.page.getByLabel("Alerts")).toHaveAttribute(
"data-state",
"on",
);
const review = new ReviewPage(frigateApp.page, !frigateApp.isMobile);
await expect(review.alertsTab).toBeVisible({ timeout: 10_000 });
await expect(review.alertsTab).toHaveAttribute("data-state", "on");
await review.detectionsTab.click();
await expect(review.detectionsTab).toHaveAttribute("data-state", "on");
await expect(review.alertsTab).toHaveAttribute("data-state", "off");
});
});
test.describe("Review Page - Filters @critical", () => {
test("All Cameras filter button opens popover with camera names", async ({
test.describe("Review — filters (desktop) @critical", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Filter bar differs on mobile",
);
test("Cameras popover lists configured camera names", async ({
frigateApp,
}) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
await frigateApp.goto("/review");
await frigateApp.page.waitForTimeout(1000);
const camerasBtn = frigateApp.page.getByRole("button", {
name: /cameras/i,
});
await expect(camerasBtn).toBeVisible({ timeout: 5_000 });
await camerasBtn.click();
await frigateApp.page.waitForTimeout(500);
// Popover should open with camera names from config
const popover = frigateApp.page.locator(
"[data-radix-popper-content-wrapper]",
);
await expect(popover.first()).toBeVisible({ timeout: 3_000 });
// Camera names should be present
const review = new ReviewPage(frigateApp.page, true);
await expect(review.camerasFilterTrigger).toBeVisible({ timeout: 5_000 });
await review.camerasFilterTrigger.click();
await expect(review.filterOverlay).toBeVisible({ timeout: 3_000 });
await expect(frigateApp.page.getByText("Front Door")).toBeVisible();
});
test("closing the Cameras popover with Escape leaves body interactive", async ({
frigateApp,
}) => {
// Migrated from radix-overlay-regressions.spec.ts.
await frigateApp.goto("/review");
const review = new ReviewPage(frigateApp.page, true);
await review.camerasFilterTrigger.click();
await expect(review.filterOverlay).toBeVisible({ timeout: 3_000 });
await frigateApp.page.keyboard.press("Escape");
await expect(review.filterOverlay).not.toBeVisible({ timeout: 3_000 });
await waitForBodyInteractive(frigateApp.page);
await expectBodyInteractive(frigateApp.page);
});
test("Labels are shown inside the General Filter dialog", async ({
frigateApp,
}) => {
// Labels are surfaced inside the "Filter" button's GeneralFilterContent
// dialog, not as a standalone top-level button. We open that dialog and
// confirm labels from the camera config are listed there.
await frigateApp.goto("/review");
const filterBtn = frigateApp.page
.getByRole("button", { name: /^filter$/i })
.first();
await expect(filterBtn).toBeVisible({ timeout: 5_000 });
await filterBtn.click();
const overlay = frigateApp.page.locator(
"[data-radix-popper-content-wrapper], [role='dialog']",
);
await expect(overlay.first()).toBeVisible({ timeout: 3_000 });
// The default mock config for front_door tracks "person"
await expect(overlay.first().getByText(/person/i)).toBeVisible();
await frigateApp.page.keyboard.press("Escape");
});
test("Show Reviewed toggle is clickable", async ({ frigateApp }) => {
await frigateApp.goto("/review");
await frigateApp.page.waitForTimeout(1000);
const showReviewed = frigateApp.page.getByRole("button", {
name: /reviewed/i,
test("Zones popover lists configured zones inside the General Filter dialog", async ({
frigateApp,
}) => {
// Override config to guarantee a known zone on front_door.
await frigateApp.installDefaults({
config: {
cameras: {
front_door: {
zones: {
front_yard: { coordinates: "0.1,0.1,0.9,0.1,0.9,0.9,0.1,0.9" },
},
},
},
},
});
if (await showReviewed.isVisible().catch(() => false)) {
await showReviewed.click();
await frigateApp.page.waitForTimeout(500);
// Toggle should change state
await expect(frigateApp.page.locator("body")).toBeVisible();
}
await frigateApp.goto("/review");
const filterBtn = frigateApp.page
.getByRole("button", { name: /^filter$/i })
.first();
await expect(filterBtn).toBeVisible({ timeout: 5_000 });
await filterBtn.click();
const overlay = frigateApp.page.locator(
"[data-radix-popper-content-wrapper], [role='dialog']",
);
await expect(overlay.first()).toBeVisible({ timeout: 3_000 });
await expect(overlay.first().getByText(/front.?yard/i)).toBeVisible();
await frigateApp.page.keyboard.press("Escape");
});
test("Last 24 Hours calendar button opens date picker", async ({
test("Calendar trigger opens a date picker popover", async ({
frigateApp,
}) => {
await frigateApp.goto("/review");
await frigateApp.page.waitForTimeout(1000);
const review = new ReviewPage(frigateApp.page, true);
await expect(review.calendarTrigger).toBeVisible({ timeout: 5_000 });
await review.calendarTrigger.click();
const calendarBtn = frigateApp.page.getByRole("button", {
name: /24 hours|calendar|date/i,
});
if (await calendarBtn.isVisible().catch(() => false)) {
await calendarBtn.click();
await frigateApp.page.waitForTimeout(500);
// Popover should open
const popover = frigateApp.page.locator(
"[data-radix-popper-content-wrapper]",
);
if (
await popover
.first()
.isVisible()
.catch(() => false)
) {
await frigateApp.page.keyboard.press("Escape");
}
}
// react-day-picker v9 renders a role="grid" calendar with day cells
// as buttons inside gridcells (e.g. "Wednesday, April 1st, 2026").
// The calendar is placed directly in the DOM (not always inside a
// Radix popper wrapper), so scope by the grid role instead.
const calendarGrid = frigateApp.page.locator('[role="grid"]').first();
await expect(calendarGrid).toBeVisible({ timeout: 3_000 });
const dayButton = calendarGrid.locator('[role="gridcell"] button').first();
await expect(dayButton).toBeVisible({ timeout: 3_000 });
await frigateApp.page.keyboard.press("Escape");
});
test("Filter button opens filter popover", async ({ frigateApp }) => {
await frigateApp.goto("/review");
await frigateApp.page.waitForTimeout(1000);
const filterBtn = frigateApp.page.getByRole("button", {
name: /^filter$/i,
});
if (await filterBtn.isVisible().catch(() => false)) {
await filterBtn.click();
await frigateApp.page.waitForTimeout(500);
// Popover or dialog should open
const popover = frigateApp.page.locator(
"[data-radix-popper-content-wrapper], [role='dialog']",
);
if (
await popover
.first()
.isVisible()
.catch(() => false)
) {
await frigateApp.page.keyboard.press("Escape");
}
}
});
});
test.describe("Review Page - Timeline @critical", () => {
test("review page has timeline with time markers (desktop)", async ({
test("Show Reviewed switch flips its checked state", async ({
frigateApp,
}) => {
if (frigateApp.isMobile) {
test.skip();
return;
}
// "Show Reviewed" is a Radix Switch (role=switch), not a button.
// It filters review data client-side; it does not trigger a new
// /api/review network request. Verify the switch state toggles.
await frigateApp.goto("/review");
await frigateApp.page.waitForTimeout(2000);
// Timeline renders time labels like "4:30 PM"
const pageText = await frigateApp.page.textContent("#pageRoot");
expect(pageText).toMatch(/[AP]M/);
const showReviewedSwitch = frigateApp.page.getByRole("switch", {
name: /show reviewed/i,
});
await expect(showReviewedSwitch).toBeVisible({ timeout: 5_000 });
// Record initial checked state and click to toggle
const initialChecked =
await showReviewedSwitch.getAttribute("aria-checked");
await showReviewedSwitch.click();
const flippedChecked = initialChecked === "true" ? "false" : "true";
await expect(showReviewedSwitch).toHaveAttribute(
"aria-checked",
flippedChecked,
);
});
});
test.describe("Review Page - Navigation @critical", () => {
test("navigate to review from live page works", async ({ frigateApp }) => {
test.describe("Review — timeline (desktop) @critical", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Timeline not shown on mobile",
);
test("timeline renders time markers", async ({ frigateApp }) => {
await frigateApp.goto("/review");
await expect
.poll(
async () => (await frigateApp.page.textContent("#pageRoot")) ?? "",
{ timeout: 10_000 },
)
.toMatch(/[AP]M|\d+:\d+/);
});
});
test.describe("Review — mobile @critical @mobile", () => {
test.skip(({ frigateApp }) => !frigateApp.isMobile, "Mobile-only");
test("severity tabs render on mobile", async ({ frigateApp }) => {
await frigateApp.goto("/review");
const review = new ReviewPage(frigateApp.page, false);
await expect(review.alertsTab).toBeVisible({ timeout: 10_000 });
await expect(review.detectionsTab).toBeVisible();
});
test("back navigation returns to Live", async ({ frigateApp }) => {
await frigateApp.goto("/");
const base = new BasePage(frigateApp.page, !frigateApp.isMobile);
const base = new BasePage(frigateApp.page, false);
await base.navigateTo("/review");
await expect(frigateApp.page).toHaveURL(/\/review/);
// Severity tabs should be visible
await expect(frigateApp.page.getByLabel("Alerts")).toBeVisible({
timeout: 10_000,
});
await base.navigateTo("/");
await expect(frigateApp.page).toHaveURL(/\/$/);
});
});
+175 -28
View File
@@ -1,15 +1,21 @@
/**
* System page tests -- MEDIUM tier.
* System page tests -- MEDIUM tier (promoted to cover migrated
* RestartDialog test from radix-overlay-regressions.spec.ts).
*
* Tests system page rendering with tabs and tab switching.
* Navigates to /system#general explicitly so useHashState resolves
* the tab state deterministically.
* Tab switching, version + last-refreshed display, and the
* RestartDialog cancel flow.
*/
import { test, expect } from "../fixtures/frigate-test";
import {
expectBodyInteractive,
waitForBodyInteractive,
} from "../helpers/overlay-interaction";
test.describe("System Page @medium", () => {
test("system page renders with tab buttons", async ({ frigateApp }) => {
test.describe("System — tabs @medium", () => {
test("general tab is active by default via #general hash", async ({
frigateApp,
}) => {
await frigateApp.goto("/system#general");
await expect(frigateApp.page.getByLabel("Select general")).toHaveAttribute(
"data-state",
@@ -20,7 +26,7 @@ test.describe("System Page @medium", () => {
await expect(frigateApp.page.getByLabel("Select cameras")).toBeVisible();
});
test("general tab is active when navigated via hash", async ({
test("Storage tab activates and deactivates General", async ({
frigateApp,
}) => {
await frigateApp.goto("/system#general");
@@ -29,18 +35,6 @@ test.describe("System Page @medium", () => {
"on",
{ timeout: 15_000 },
);
});
test("clicking Storage tab activates it and deactivates General", async ({
frigateApp,
}) => {
await frigateApp.goto("/system#general");
await expect(frigateApp.page.getByLabel("Select general")).toHaveAttribute(
"data-state",
"on",
{ timeout: 15_000 },
);
await frigateApp.page.getByLabel("Select storage").click();
await expect(frigateApp.page.getByLabel("Select storage")).toHaveAttribute(
"data-state",
@@ -53,29 +47,22 @@ test.describe("System Page @medium", () => {
);
});
test("clicking Cameras tab activates it and deactivates General", async ({
frigateApp,
}) => {
test("Cameras tab activates", async ({ frigateApp }) => {
await frigateApp.goto("/system#general");
await expect(frigateApp.page.getByLabel("Select general")).toHaveAttribute(
"data-state",
"on",
{ timeout: 15_000 },
);
await frigateApp.page.getByLabel("Select cameras").click();
await expect(frigateApp.page.getByLabel("Select cameras")).toHaveAttribute(
"data-state",
"on",
{ timeout: 5_000 },
);
await expect(frigateApp.page.getByLabel("Select general")).toHaveAttribute(
"data-state",
"off",
);
});
test("system page shows version and last refreshed", async ({
test("general tab shows version and last-refreshed", async ({
frigateApp,
}) => {
await frigateApp.goto("/system#general");
@@ -87,4 +74,164 @@ test.describe("System Page @medium", () => {
await expect(frigateApp.page.getByText("0.15.0-test")).toBeVisible();
await expect(frigateApp.page.getByText(/Last refreshed/)).toBeVisible();
});
test("storage tab renders content after switching", async ({
frigateApp,
}) => {
await frigateApp.goto("/system#general");
await expect(frigateApp.page.getByLabel("Select general")).toHaveAttribute(
"data-state",
"on",
{ timeout: 15_000 },
);
await frigateApp.page.getByLabel("Select storage").click();
await expect(frigateApp.page.getByLabel("Select storage")).toHaveAttribute(
"data-state",
"on",
{ timeout: 5_000 },
);
// On desktop, tab buttons render text labels so the word "storage"
// always appears in #pageRoot after switching. On mobile, tabs are
// icon-only, so we verify the general-tab content disappears instead
// (the storage tab's metrics section is hidden but general is gone).
if (!frigateApp.isMobile) {
await expect
.poll(
async () => (await frigateApp.page.textContent("#pageRoot")) ?? "",
{ timeout: 10_000 },
)
.toMatch(/storage|mount|disk|used|free/i);
} else {
// Mobile: tab activation (data-state "on") already asserted above.
// Additionally confirm general tab is no longer the active tab.
await expect(
frigateApp.page.getByLabel("Select general"),
).toHaveAttribute("data-state", "off", { timeout: 5_000 });
}
});
test("cameras tab renders each configured camera", async ({ frigateApp }) => {
await frigateApp.goto("/system#general");
await expect(frigateApp.page.getByLabel("Select general")).toHaveAttribute(
"data-state",
"on",
{ timeout: 15_000 },
);
await frigateApp.page.getByLabel("Select cameras").click();
await expect(frigateApp.page.getByLabel("Select cameras")).toHaveAttribute(
"data-state",
"on",
{ timeout: 5_000 },
);
// Cameras tab lists every camera from config/stats. The default
// mock has front_door, backyard, garage.
for (const cam of ["front_door", "backyard", "garage"]) {
await expect(
frigateApp.page
.getByText(new RegExp(cam.replace("_", ".?"), "i"))
.first(),
).toBeVisible({ timeout: 10_000 });
}
});
test("enrichments tab renders when semantic search is enabled", async ({
frigateApp,
}) => {
// Override config to guarantee the enrichments tab is present.
// System.tsx shows the tab when semantic_search.enabled === true.
await frigateApp.installDefaults({
config: { semantic_search: { enabled: true } },
});
await frigateApp.goto("/system#general");
await expect(frigateApp.page.getByLabel("Select general")).toHaveAttribute(
"data-state",
"on",
{ timeout: 15_000 },
);
const enrichTab = frigateApp.page.getByLabel(/select enrichments/i).first();
await expect(enrichTab).toBeVisible({ timeout: 5_000 });
await enrichTab.click();
await expect(enrichTab).toHaveAttribute("data-state", "on", {
timeout: 5_000,
});
});
});
test.describe("System — RestartDialog @medium", () => {
test.skip(
({ frigateApp }) => frigateApp.isMobile,
"Sidebar menu is desktop-only",
);
test("cancelling restart leaves body interactive", async ({ frigateApp }) => {
// Migrated from radix-overlay-regressions.spec.ts.
await frigateApp.goto("/");
const sidebarTriggers = frigateApp.page
.locator('[role="complementary"] [aria-haspopup="menu"]')
.or(frigateApp.page.locator('aside [aria-haspopup="menu"]'));
const triggerCount = await sidebarTriggers.count();
expect(triggerCount).toBeGreaterThan(0);
let opened = false;
for (let i = 0; i < triggerCount; i++) {
const trigger = sidebarTriggers.nth(i);
await trigger.click().catch(() => {});
const restartItem = frigateApp.page
.getByRole("menuitem", { name: /restart/i })
.first();
const visible = await expect(restartItem)
.toBeVisible({ timeout: 300 })
.then(() => true)
.catch(() => false);
if (visible) {
await restartItem.click();
opened = true;
break;
}
await frigateApp.page.keyboard.press("Escape").catch(() => {});
}
expect(opened).toBe(true);
const cancel = frigateApp.page.getByRole("button", { name: /cancel/i });
await expect(cancel).toBeVisible({ timeout: 3_000 });
await cancel.click();
await waitForBodyInteractive(frigateApp.page);
await expectBodyInteractive(frigateApp.page);
const postCancelTrigger = sidebarTriggers.first();
await postCancelTrigger.click();
await expect(
frigateApp.page
.locator('[role="menu"], [data-radix-menu-content]')
.first(),
).toBeVisible({ timeout: 3_000 });
});
});
test.describe("System — mobile @medium @mobile", () => {
test.skip(({ frigateApp }) => !frigateApp.isMobile, "Mobile-only");
test("tabs render at mobile viewport", async ({ frigateApp }) => {
await frigateApp.goto("/system#general");
await expect(frigateApp.page.getByLabel("Select general")).toBeVisible({
timeout: 15_000,
});
});
test("switching tabs works at mobile viewport", async ({ frigateApp }) => {
await frigateApp.goto("/system#general");
await expect(frigateApp.page.getByLabel("Select general")).toHaveAttribute(
"data-state",
"on",
{ timeout: 15_000 },
);
await frigateApp.page.getByLabel("Select storage").click();
await expect(frigateApp.page.getByLabel("Select storage")).toHaveAttribute(
"data-state",
"on",
{ timeout: 5_000 },
);
});
});
+486 -282
View File
@@ -12,14 +12,14 @@
"@cycjimmy/jsmpeg-player": "^6.1.2",
"@hookform/resolvers": "^3.10.0",
"@melloware/react-logviewer": "^6.1.2",
"@radix-ui/react-alert-dialog": "^1.1.6",
"@radix-ui/react-alert-dialog": "^1.1.15",
"@radix-ui/react-aspect-ratio": "^1.1.2",
"@radix-ui/react-checkbox": "^1.1.4",
"@radix-ui/react-collapsible": "^1.1.12",
"@radix-ui/react-context-menu": "^2.2.6",
"@radix-ui/react-context-menu": "^2.2.16",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.6",
"@radix-ui/react-hover-card": "^1.1.6",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-hover-card": "^1.1.15",
"@radix-ui/react-label": "^2.1.2",
"@radix-ui/react-popover": "^1.1.6",
"@radix-ui/react-progress": "^1.1.8",
@@ -49,7 +49,7 @@
"framer-motion": "^12.38.0",
"hls.js": "^1.6.15",
"i18next": "^24.2.0",
"i18next-http-backend": "^3.0.1",
"i18next-http-backend": "^3.0.5",
"idb-keyval": "^6.2.1",
"immer": "^10.1.1",
"js-yaml": "^4.1.1",
@@ -1515,17 +1515,17 @@
"license": "MIT"
},
"node_modules/@radix-ui/react-alert-dialog": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/@radix-ui/react-alert-dialog/-/react-alert-dialog-1.1.6.tgz",
"integrity": "sha512-p4XnPqgej8sZAAReCAKgz1REYZEBLR8hU9Pg27wFnCWIMc8g1ccCs0FjBcy05V15VTu8pAePw/VDYeOm/uZ6yQ==",
"version": "1.1.15",
"resolved": "https://registry.npmjs.org/@radix-ui/react-alert-dialog/-/react-alert-dialog-1.1.15.tgz",
"integrity": "sha512-oTVLkEw5GpdRe29BqJ0LSDFWI3qu0vR1M0mUkOQWDIUnY/QIkLpgDMWuKxP94c2NAC2LGcgVhG1ImF3jkZ5wXw==",
"license": "MIT",
"dependencies": {
"@radix-ui/primitive": "1.1.1",
"@radix-ui/react-compose-refs": "1.1.1",
"@radix-ui/react-context": "1.1.1",
"@radix-ui/react-dialog": "1.1.6",
"@radix-ui/react-primitive": "2.0.2",
"@radix-ui/react-slot": "1.1.2"
"@radix-ui/primitive": "1.1.3",
"@radix-ui/react-compose-refs": "1.1.2",
"@radix-ui/react-context": "1.1.2",
"@radix-ui/react-dialog": "1.1.15",
"@radix-ui/react-primitive": "2.1.3",
"@radix-ui/react-slot": "1.2.3"
},
"peerDependencies": {
"@types/react": "*",
@@ -1542,126 +1542,17 @@
}
}
},
"node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-dialog": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/@radix-ui/react-dialog/-/react-dialog-1.1.6.tgz",
"integrity": "sha512-/IVhJV5AceX620DUJ4uYVMymzsipdKBzo3edo+omeskCKGm9FRHM0ebIdbPnlQVJqyuHbuBltQUOG2mOTq2IYw==",
"license": "MIT",
"dependencies": {
"@radix-ui/primitive": "1.1.1",
"@radix-ui/react-compose-refs": "1.1.1",
"@radix-ui/react-context": "1.1.1",
"@radix-ui/react-dismissable-layer": "1.1.5",
"@radix-ui/react-focus-guards": "1.1.1",
"@radix-ui/react-focus-scope": "1.1.2",
"@radix-ui/react-id": "1.1.0",
"@radix-ui/react-portal": "1.1.4",
"@radix-ui/react-presence": "1.1.2",
"@radix-ui/react-primitive": "2.0.2",
"@radix-ui/react-slot": "1.1.2",
"@radix-ui/react-use-controllable-state": "1.1.0",
"aria-hidden": "^1.2.4",
"react-remove-scroll": "^2.6.3"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
"node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/primitive": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.3.tgz",
"integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==",
"license": "MIT"
},
"node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-dismissable-layer": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.1.5.tgz",
"integrity": "sha512-E4TywXY6UsXNRhFrECa5HAvE5/4BFcGyfTyK36gP+pAW1ed7UTK4vKwdr53gAJYwqbfCWC6ATvJa3J3R/9+Qrg==",
"license": "MIT",
"dependencies": {
"@radix-ui/primitive": "1.1.1",
"@radix-ui/react-compose-refs": "1.1.1",
"@radix-ui/react-primitive": "2.0.2",
"@radix-ui/react-use-callback-ref": "1.1.0",
"@radix-ui/react-use-escape-keydown": "1.1.0"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-focus-scope": {
"node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-context": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.1.2.tgz",
"integrity": "sha512-zxwE80FCU7lcXUGWkdt6XpTTCKPitG1XKOwViTxHVKIJhZl9MvIl2dVHeZENCWD9+EdWv05wlaEkRXUykU27RA==",
"resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.2.tgz",
"integrity": "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-compose-refs": "1.1.1",
"@radix-ui/react-primitive": "2.0.2",
"@radix-ui/react-use-callback-ref": "1.1.0"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-portal": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.1.4.tgz",
"integrity": "sha512-sn2O9k1rPFYVyKd5LAJfo96JlSGVFpa1fS6UuBJfrZadudiw5tAmru+n1x7aMRQ84qDM71Zh1+SzK5QwU0tJfA==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-primitive": "2.0.2",
"@radix-ui/react-use-layout-effect": "1.1.0"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-use-escape-keydown": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.1.0.tgz",
"integrity": "sha512-L7vwWlR1kTTQ3oh7g1O0CBF3YCyyTj8NmhLR+phShpyA50HCfBFKVJTpshm9PzLiKmehsrQzTYTpX9HvmC9rhw==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-use-callback-ref": "1.1.0"
},
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
@@ -1672,6 +1563,29 @@
}
}
},
"node_modules/@radix-ui/react-alert-dialog/node_modules/@radix-ui/react-primitive": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.3.tgz",
"integrity": "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-slot": "1.2.3"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-arrow": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.7.tgz",
@@ -2113,17 +2027,17 @@
}
},
"node_modules/@radix-ui/react-context-menu": {
"version": "2.2.6",
"resolved": "https://registry.npmjs.org/@radix-ui/react-context-menu/-/react-context-menu-2.2.6.tgz",
"integrity": "sha512-aUP99QZ3VU84NPsHeaFt4cQUNgJqFsLLOt/RbbWXszZ6MP0DpDyjkFZORr4RpAEx3sUBk+Kc8h13yGtC5Qw8dg==",
"version": "2.2.16",
"resolved": "https://registry.npmjs.org/@radix-ui/react-context-menu/-/react-context-menu-2.2.16.tgz",
"integrity": "sha512-O8morBEW+HsVG28gYDZPTrT9UUovQUlJue5YO836tiTJhuIWBm/zQHc7j388sHWtdH/xUZurK9olD2+pcqx5ww==",
"license": "MIT",
"dependencies": {
"@radix-ui/primitive": "1.1.1",
"@radix-ui/react-context": "1.1.1",
"@radix-ui/react-menu": "2.1.6",
"@radix-ui/react-primitive": "2.0.2",
"@radix-ui/react-use-callback-ref": "1.1.0",
"@radix-ui/react-use-controllable-state": "1.1.0"
"@radix-ui/primitive": "1.1.3",
"@radix-ui/react-context": "1.1.2",
"@radix-ui/react-menu": "2.1.16",
"@radix-ui/react-primitive": "2.1.3",
"@radix-ui/react-use-callback-ref": "1.1.1",
"@radix-ui/react-use-controllable-state": "1.2.2"
},
"peerDependencies": {
"@types/react": "*",
@@ -2140,6 +2054,99 @@
}
}
},
"node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/primitive": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.3.tgz",
"integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==",
"license": "MIT"
},
"node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-context": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.2.tgz",
"integrity": "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-primitive": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.3.tgz",
"integrity": "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-slot": "1.2.3"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-use-callback-ref": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz",
"integrity": "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-use-controllable-state": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.2.2.tgz",
"integrity": "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-use-effect-event": "0.0.2",
"@radix-ui/react-use-layout-effect": "1.1.1"
},
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-context-menu/node_modules/@radix-ui/react-use-layout-effect": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz",
"integrity": "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-dialog": {
"version": "1.1.15",
"resolved": "https://registry.npmjs.org/@radix-ui/react-dialog/-/react-dialog-1.1.15.tgz",
@@ -2197,21 +2204,6 @@
}
}
},
"node_modules/@radix-ui/react-dialog/node_modules/@radix-ui/react-focus-guards": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.3.tgz",
"integrity": "sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-dialog/node_modules/@radix-ui/react-id": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.1.tgz",
@@ -2398,18 +2390,18 @@
}
},
"node_modules/@radix-ui/react-dropdown-menu": {
"version": "2.1.6",
"resolved": "https://registry.npmjs.org/@radix-ui/react-dropdown-menu/-/react-dropdown-menu-2.1.6.tgz",
"integrity": "sha512-no3X7V5fD487wab/ZYSHXq3H37u4NVeLDKI/Ks724X/eEFSSEFYZxWgsIlr1UBeEyDaM29HM5x9p1Nv8DuTYPA==",
"version": "2.1.16",
"resolved": "https://registry.npmjs.org/@radix-ui/react-dropdown-menu/-/react-dropdown-menu-2.1.16.tgz",
"integrity": "sha512-1PLGQEynI/3OX/ftV54COn+3Sud/Mn8vALg2rWnBLnRaGtJDduNW/22XjlGgPdpcIbiQxjKtb7BkcjP00nqfJw==",
"license": "MIT",
"dependencies": {
"@radix-ui/primitive": "1.1.1",
"@radix-ui/react-compose-refs": "1.1.1",
"@radix-ui/react-context": "1.1.1",
"@radix-ui/react-id": "1.1.0",
"@radix-ui/react-menu": "2.1.6",
"@radix-ui/react-primitive": "2.0.2",
"@radix-ui/react-use-controllable-state": "1.1.0"
"@radix-ui/primitive": "1.1.3",
"@radix-ui/react-compose-refs": "1.1.2",
"@radix-ui/react-context": "1.1.2",
"@radix-ui/react-id": "1.1.1",
"@radix-ui/react-menu": "2.1.16",
"@radix-ui/react-primitive": "2.1.3",
"@radix-ui/react-use-controllable-state": "1.2.2"
},
"peerDependencies": {
"@types/react": "*",
@@ -2426,10 +2418,106 @@
}
}
},
"node_modules/@radix-ui/react-focus-guards": {
"node_modules/@radix-ui/react-dropdown-menu/node_modules/@radix-ui/primitive": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.3.tgz",
"integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==",
"license": "MIT"
},
"node_modules/@radix-ui/react-dropdown-menu/node_modules/@radix-ui/react-context": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.2.tgz",
"integrity": "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-dropdown-menu/node_modules/@radix-ui/react-id": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.1.tgz",
"integrity": "sha512-pSIwfrT1a6sIoDASCSpFwOasEwKTZWDw/iBdtnqKO7v6FeOzYJ7U53cPzYFVR3geGGXgVHaH+CdngrrAzqUGxg==",
"resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.1.tgz",
"integrity": "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-use-layout-effect": "1.1.1"
},
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-dropdown-menu/node_modules/@radix-ui/react-primitive": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.3.tgz",
"integrity": "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-slot": "1.2.3"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-dropdown-menu/node_modules/@radix-ui/react-use-controllable-state": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.2.2.tgz",
"integrity": "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-use-effect-event": "0.0.2",
"@radix-ui/react-use-layout-effect": "1.1.1"
},
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-dropdown-menu/node_modules/@radix-ui/react-use-layout-effect": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz",
"integrity": "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-focus-guards": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.3.tgz",
"integrity": "sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
@@ -2505,20 +2593,20 @@
}
},
"node_modules/@radix-ui/react-hover-card": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/@radix-ui/react-hover-card/-/react-hover-card-1.1.6.tgz",
"integrity": "sha512-E4ozl35jq0VRlrdc4dhHrNSV0JqBb4Jy73WAhBEK7JoYnQ83ED5r0Rb/XdVKw89ReAJN38N492BAPBZQ57VmqQ==",
"version": "1.1.15",
"resolved": "https://registry.npmjs.org/@radix-ui/react-hover-card/-/react-hover-card-1.1.15.tgz",
"integrity": "sha512-qgTkjNT1CfKMoP0rcasmlH2r1DAiYicWsDsufxl940sT2wHNEWWv6FMWIQXWhVdmC1d/HYfbhQx60KYyAtKxjg==",
"license": "MIT",
"dependencies": {
"@radix-ui/primitive": "1.1.1",
"@radix-ui/react-compose-refs": "1.1.1",
"@radix-ui/react-context": "1.1.1",
"@radix-ui/react-dismissable-layer": "1.1.5",
"@radix-ui/react-popper": "1.2.2",
"@radix-ui/react-portal": "1.1.4",
"@radix-ui/react-presence": "1.1.2",
"@radix-ui/react-primitive": "2.0.2",
"@radix-ui/react-use-controllable-state": "1.1.0"
"@radix-ui/primitive": "1.1.3",
"@radix-ui/react-compose-refs": "1.1.2",
"@radix-ui/react-context": "1.1.2",
"@radix-ui/react-dismissable-layer": "1.1.11",
"@radix-ui/react-popper": "1.2.8",
"@radix-ui/react-portal": "1.1.9",
"@radix-ui/react-presence": "1.1.5",
"@radix-ui/react-primitive": "2.1.3",
"@radix-ui/react-use-controllable-state": "1.2.2"
},
"peerDependencies": {
"@types/react": "*",
@@ -2535,17 +2623,35 @@
}
}
},
"node_modules/@radix-ui/react-hover-card/node_modules/@radix-ui/react-dismissable-layer": {
"node_modules/@radix-ui/react-hover-card/node_modules/@radix-ui/primitive": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.3.tgz",
"integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==",
"license": "MIT"
},
"node_modules/@radix-ui/react-hover-card/node_modules/@radix-ui/react-context": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.2.tgz",
"integrity": "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-hover-card/node_modules/@radix-ui/react-presence": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.1.5.tgz",
"integrity": "sha512-E4TywXY6UsXNRhFrECa5HAvE5/4BFcGyfTyK36gP+pAW1ed7UTK4vKwdr53gAJYwqbfCWC6ATvJa3J3R/9+Qrg==",
"resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.5.tgz",
"integrity": "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ==",
"license": "MIT",
"dependencies": {
"@radix-ui/primitive": "1.1.1",
"@radix-ui/react-compose-refs": "1.1.1",
"@radix-ui/react-primitive": "2.0.2",
"@radix-ui/react-use-callback-ref": "1.1.0",
"@radix-ui/react-use-escape-keydown": "1.1.0"
"@radix-ui/react-compose-refs": "1.1.2",
"@radix-ui/react-use-layout-effect": "1.1.1"
},
"peerDependencies": {
"@types/react": "*",
@@ -2562,14 +2668,13 @@
}
}
},
"node_modules/@radix-ui/react-hover-card/node_modules/@radix-ui/react-portal": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.1.4.tgz",
"integrity": "sha512-sn2O9k1rPFYVyKd5LAJfo96JlSGVFpa1fS6UuBJfrZadudiw5tAmru+n1x7aMRQ84qDM71Zh1+SzK5QwU0tJfA==",
"node_modules/@radix-ui/react-hover-card/node_modules/@radix-ui/react-primitive": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.3.tgz",
"integrity": "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-primitive": "2.0.2",
"@radix-ui/react-use-layout-effect": "1.1.0"
"@radix-ui/react-slot": "1.2.3"
},
"peerDependencies": {
"@types/react": "*",
@@ -2586,13 +2691,14 @@
}
}
},
"node_modules/@radix-ui/react-hover-card/node_modules/@radix-ui/react-use-escape-keydown": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.1.0.tgz",
"integrity": "sha512-L7vwWlR1kTTQ3oh7g1O0CBF3YCyyTj8NmhLR+phShpyA50HCfBFKVJTpshm9PzLiKmehsrQzTYTpX9HvmC9rhw==",
"node_modules/@radix-ui/react-hover-card/node_modules/@radix-ui/react-use-controllable-state": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.2.2.tgz",
"integrity": "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-use-callback-ref": "1.1.0"
"@radix-ui/react-use-effect-event": "0.0.2",
"@radix-ui/react-use-layout-effect": "1.1.1"
},
"peerDependencies": {
"@types/react": "*",
@@ -2604,6 +2710,21 @@
}
}
},
"node_modules/@radix-ui/react-hover-card/node_modules/@radix-ui/react-use-layout-effect": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz",
"integrity": "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-icons": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@radix-ui/react-icons/-/react-icons-1.3.2.tgz",
@@ -2678,27 +2799,27 @@
}
},
"node_modules/@radix-ui/react-menu": {
"version": "2.1.6",
"resolved": "https://registry.npmjs.org/@radix-ui/react-menu/-/react-menu-2.1.6.tgz",
"integrity": "sha512-tBBb5CXDJW3t2mo9WlO7r6GTmWV0F0uzHZVFmlRmYpiSK1CDU5IKojP1pm7oknpBOrFZx/YgBRW9oorPO2S/Lg==",
"version": "2.1.16",
"resolved": "https://registry.npmjs.org/@radix-ui/react-menu/-/react-menu-2.1.16.tgz",
"integrity": "sha512-72F2T+PLlphrqLcAotYPp0uJMr5SjP5SL01wfEspJbru5Zs5vQaSHb4VB3ZMJPimgHHCHG7gMOeOB9H3Hdmtxg==",
"license": "MIT",
"dependencies": {
"@radix-ui/primitive": "1.1.1",
"@radix-ui/react-collection": "1.1.2",
"@radix-ui/react-compose-refs": "1.1.1",
"@radix-ui/react-context": "1.1.1",
"@radix-ui/react-direction": "1.1.0",
"@radix-ui/react-dismissable-layer": "1.1.5",
"@radix-ui/react-focus-guards": "1.1.1",
"@radix-ui/react-focus-scope": "1.1.2",
"@radix-ui/react-id": "1.1.0",
"@radix-ui/react-popper": "1.2.2",
"@radix-ui/react-portal": "1.1.4",
"@radix-ui/react-presence": "1.1.2",
"@radix-ui/react-primitive": "2.0.2",
"@radix-ui/react-roving-focus": "1.1.2",
"@radix-ui/react-slot": "1.1.2",
"@radix-ui/react-use-callback-ref": "1.1.0",
"@radix-ui/primitive": "1.1.3",
"@radix-ui/react-collection": "1.1.7",
"@radix-ui/react-compose-refs": "1.1.2",
"@radix-ui/react-context": "1.1.2",
"@radix-ui/react-direction": "1.1.1",
"@radix-ui/react-dismissable-layer": "1.1.11",
"@radix-ui/react-focus-guards": "1.1.3",
"@radix-ui/react-focus-scope": "1.1.7",
"@radix-ui/react-id": "1.1.1",
"@radix-ui/react-popper": "1.2.8",
"@radix-ui/react-portal": "1.1.9",
"@radix-ui/react-presence": "1.1.5",
"@radix-ui/react-primitive": "2.1.3",
"@radix-ui/react-roving-focus": "1.1.11",
"@radix-ui/react-slot": "1.2.3",
"@radix-ui/react-use-callback-ref": "1.1.1",
"aria-hidden": "^1.2.4",
"react-remove-scroll": "^2.6.3"
},
@@ -2717,17 +2838,22 @@
}
}
},
"node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-dismissable-layer": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.1.5.tgz",
"integrity": "sha512-E4TywXY6UsXNRhFrECa5HAvE5/4BFcGyfTyK36gP+pAW1ed7UTK4vKwdr53gAJYwqbfCWC6ATvJa3J3R/9+Qrg==",
"node_modules/@radix-ui/react-menu/node_modules/@radix-ui/primitive": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.3.tgz",
"integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==",
"license": "MIT"
},
"node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-collection": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.7.tgz",
"integrity": "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw==",
"license": "MIT",
"dependencies": {
"@radix-ui/primitive": "1.1.1",
"@radix-ui/react-compose-refs": "1.1.1",
"@radix-ui/react-primitive": "2.0.2",
"@radix-ui/react-use-callback-ref": "1.1.0",
"@radix-ui/react-use-escape-keydown": "1.1.0"
"@radix-ui/react-compose-refs": "1.1.2",
"@radix-ui/react-context": "1.1.2",
"@radix-ui/react-primitive": "2.1.3",
"@radix-ui/react-slot": "1.2.3"
},
"peerDependencies": {
"@types/react": "*",
@@ -2744,15 +2870,62 @@
}
}
},
"node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-focus-scope": {
"node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-context": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@radix-ui/react-focus-scope/-/react-focus-scope-1.1.2.tgz",
"integrity": "sha512-zxwE80FCU7lcXUGWkdt6XpTTCKPitG1XKOwViTxHVKIJhZl9MvIl2dVHeZENCWD9+EdWv05wlaEkRXUykU27RA==",
"resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.2.tgz",
"integrity": "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-direction": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.1.tgz",
"integrity": "sha512-1UEWRX6jnOA2y4H5WczZ44gOOjTEmlqv1uNW4GAJEO5+bauCBhv8snY65Iw5/VOS/ghKN9gr2KjnLKxrsvoMVw==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-id": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.1.tgz",
"integrity": "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-compose-refs": "1.1.1",
"@radix-ui/react-primitive": "2.0.2",
"@radix-ui/react-use-callback-ref": "1.1.0"
"@radix-ui/react-use-layout-effect": "1.1.1"
},
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-presence": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.5.tgz",
"integrity": "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-compose-refs": "1.1.2",
"@radix-ui/react-use-layout-effect": "1.1.1"
},
"peerDependencies": {
"@types/react": "*",
@@ -2769,14 +2942,13 @@
}
}
},
"node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-portal": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/@radix-ui/react-portal/-/react-portal-1.1.4.tgz",
"integrity": "sha512-sn2O9k1rPFYVyKd5LAJfo96JlSGVFpa1fS6UuBJfrZadudiw5tAmru+n1x7aMRQ84qDM71Zh1+SzK5QwU0tJfA==",
"node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-primitive": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.3.tgz",
"integrity": "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-primitive": "2.0.2",
"@radix-ui/react-use-layout-effect": "1.1.0"
"@radix-ui/react-slot": "1.2.3"
},
"peerDependencies": {
"@types/react": "*",
@@ -2793,14 +2965,76 @@
}
}
},
"node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-use-escape-keydown": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.1.0.tgz",
"integrity": "sha512-L7vwWlR1kTTQ3oh7g1O0CBF3YCyyTj8NmhLR+phShpyA50HCfBFKVJTpshm9PzLiKmehsrQzTYTpX9HvmC9rhw==",
"node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-roving-focus": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.11.tgz",
"integrity": "sha512-7A6S9jSgm/S+7MdtNDSb+IU859vQqJ/QAtcYQcfFC6W8RS4IxIZDldLR0xqCFZ6DCyrQLjLPsxtTNch5jVA4lA==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-use-callback-ref": "1.1.0"
"@radix-ui/primitive": "1.1.3",
"@radix-ui/react-collection": "1.1.7",
"@radix-ui/react-compose-refs": "1.1.2",
"@radix-ui/react-context": "1.1.2",
"@radix-ui/react-direction": "1.1.1",
"@radix-ui/react-id": "1.1.1",
"@radix-ui/react-primitive": "2.1.3",
"@radix-ui/react-use-callback-ref": "1.1.1",
"@radix-ui/react-use-controllable-state": "1.2.2"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-use-callback-ref": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz",
"integrity": "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-use-controllable-state": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.2.2.tgz",
"integrity": "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-use-effect-event": "0.0.2",
"@radix-ui/react-use-layout-effect": "1.1.1"
},
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-use-layout-effect": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz",
"integrity": "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
@@ -2869,21 +3103,6 @@
}
}
},
"node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-focus-guards": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.3.tgz",
"integrity": "sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-id": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.1.tgz",
@@ -3717,21 +3936,6 @@
}
}
},
"node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-focus-guards": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.3.tgz",
"integrity": "sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-id": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.1.tgz",
@@ -6809,12 +7013,12 @@
}
},
"node_modules/cross-fetch": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-4.0.0.tgz",
"integrity": "sha512-e4a5N8lVvuLgAWgnCrLr2PP0YyDOTHa9H/Rj54dirp61qXnNq46m82bRhNqIA5VccJtWBvPTFRV3TtvHUKPB1g==",
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-4.1.0.tgz",
"integrity": "sha512-uKm5PU+MHTootlWEY+mZ4vvXoCn4fLQxT9dSc1sXVMSFkINTJVN8cAQROpwcKm8bJ/c7rgZVIBWzH5T78sNZZw==",
"license": "MIT",
"dependencies": {
"node-fetch": "^2.6.12"
"node-fetch": "^2.7.0"
}
},
"node_modules/cross-spawn": {
@@ -8672,12 +8876,12 @@
}
},
"node_modules/i18next-http-backend": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/i18next-http-backend/-/i18next-http-backend-3.0.1.tgz",
"integrity": "sha512-XT2lYSkbAtDE55c6m7CtKxxrsfuRQO3rUfHzj8ZyRtY9CkIX3aRGwXGTkUhpGWce+J8n7sfu3J0f2wTzo7Lw0A==",
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/i18next-http-backend/-/i18next-http-backend-3.0.5.tgz",
"integrity": "sha512-QaWHnsxieEDcqKe+vo/RFqpiIFRi/KBqlOSPcUlvinBaISCeiTRCbtrazHAjtHtsLC66oDsROAH8frWkQzfMMQ==",
"license": "MIT",
"dependencies": {
"cross-fetch": "4.0.0"
"cross-fetch": "4.1.0"
}
},
"node_modules/i18next-resources-for-ts": {
+5 -5
View File
@@ -26,14 +26,14 @@
"@cycjimmy/jsmpeg-player": "^6.1.2",
"@hookform/resolvers": "^3.10.0",
"@melloware/react-logviewer": "^6.1.2",
"@radix-ui/react-alert-dialog": "^1.1.6",
"@radix-ui/react-alert-dialog": "^1.1.15",
"@radix-ui/react-aspect-ratio": "^1.1.2",
"@radix-ui/react-checkbox": "^1.1.4",
"@radix-ui/react-collapsible": "^1.1.12",
"@radix-ui/react-context-menu": "^2.2.6",
"@radix-ui/react-context-menu": "^2.2.16",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.6",
"@radix-ui/react-hover-card": "^1.1.6",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-hover-card": "^1.1.15",
"@radix-ui/react-label": "^2.1.2",
"@radix-ui/react-popover": "^1.1.6",
"@radix-ui/react-progress": "^1.1.8",
@@ -63,7 +63,7 @@
"framer-motion": "^12.38.0",
"hls.js": "^1.6.15",
"i18next": "^24.2.0",
"i18next-http-backend": "^3.0.1",
"i18next-http-backend": "^3.0.5",
"idb-keyval": "^6.2.1",
"immer": "^10.1.1",
"js-yaml": "^4.1.1",
@@ -152,6 +152,14 @@
}
},
"recording": {
"shareTimestamp": {
"label": "Share Timestamp",
"title": "Share Timestamp",
"description": "Share a timestamped URL of current player position or choose a custom timestamp. Note that this is not a public share URL and is only accessible to users with access to Frigate and this camera.",
"custom": "Custom Timestamp",
"button": "Share Timestamp URL",
"shareTitle": "Frigate Review Timestamp: {{camera}}"
},
"confirmDelete": {
"title": "Confirm Delete",
"desc": {
+2 -1
View File
@@ -4,7 +4,8 @@
"noPreviewFoundFor": "No Preview Found for {{cameraName}}",
"submitFrigatePlus": {
"title": "Submit this frame to Frigate+?",
"submit": "Submit"
"submit": "Submit",
"previewError": "Could not load snapshot preview. The recording may not be available at this time."
},
"livePlayerRequiredIOSVersion": "iOS 17.1 or greater is required for this live stream type.",
"streamOffline": {
+3 -1
View File
@@ -45,7 +45,9 @@
},
"documentTitle": "Review - Frigate",
"recordings": {
"documentTitle": "Recordings - Frigate"
"documentTitle": "Recordings - Frigate",
"invalidSharedLink": "Unable to open timestamped recording link due to parsing error.",
"invalidSharedCamera": "Unable to open timestamped recording link due to an unknown or unauthorized camera."
},
"calendarFilter": {
"last24Hours": "Last 24 Hours"
+6 -1
View File
@@ -58,7 +58,12 @@
"jobCard": {
"defaultName": "{{camera}} export",
"queued": "Queued",
"running": "Running"
"running": "Running",
"preparing": "Preparing",
"copying": "Copying",
"encoding": "Encoding",
"encodingRetry": "Encoding (retry)",
"finalizing": "Finalizing"
},
"caseView": {
"noDescription": "No description",
@@ -415,6 +415,7 @@
"audioCodecGood": "Audio codec is {{codec}}.",
"resolutionHigh": "A resolution of {{resolution}} may cause increased resource usage.",
"resolutionLow": "A resolution of {{resolution}} may be too low for reliable detection of small objects.",
"resolutionUnknown": "The resolution of this stream could not be probed. This will cause issues on startup. You should manually set the detect resolution in Settings or your config.",
"noAudioWarning": "No audio detected for this stream, recordings will not have audio.",
"audioCodecRecordError": "The AAC audio codec is required to support audio in recordings.",
"audioCodecRequired": "An audio stream is required to support audio detection.",
+3 -3
View File
@@ -811,10 +811,10 @@ export function useTriggers(): { payload: TriggerStatus } {
return { payload: parsed };
}
export function useJobStatus(
export function useJobStatus<TResults = unknown>(
jobType: string,
revalidateOnFocus: boolean = true,
): { payload: Job | null } {
): { payload: Job<TResults> | null } {
const {
value: { payload },
send: sendCommand,
@@ -846,7 +846,7 @@ export function useJobStatus(
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [revalidateOnFocus]);
return { payload: currentJob as Job | null };
return { payload: currentJob as Job<TResults> | null };
}
export function useWsMessageSubscribe(callback: (msg: WsFeedMessage) => void) {
+54 -9
View File
@@ -1,6 +1,7 @@
import ActivityIndicator from "../indicators/activity-indicator";
import { Button } from "../ui/button";
import { useCallback, useMemo, useRef, useState } from "react";
import { Progress } from "../ui/progress";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { isMobile } from "react-device-detect";
import { FiMoreVertical } from "react-icons/fi";
import { Skeleton } from "../ui/skeleton";
@@ -128,6 +129,14 @@ export function ExportCard({
exportedRecording.thumb_path.length > 0,
);
// Resync the skeleton state whenever the backing export changes. The
// list keys by id now, so in practice the component remounts instead
// of receiving new props — but this keeps the card honest if a parent
// ever reuses the instance across different exports.
useEffect(() => {
setLoading(exportedRecording.thumb_path.length > 0);
}, [exportedRecording.thumb_path]);
// selection
const cardRef = useRef<HTMLDivElement | null>(null);
@@ -257,7 +266,7 @@ export function ExportCard({
)}
{!exportedRecording.in_progress && !selectionMode && (
<div className="absolute bottom-2 right-3 z-40">
<DropdownMenu modal={false}>
<DropdownMenu>
<DropdownMenuTrigger>
<BlurredIconButton
aria-label={t("tooltip.editName")}
@@ -392,8 +401,35 @@ export function ActiveExportJobCard({
camera: cameraName,
});
}, [cameraName, job.name, t]);
const statusLabel =
job.status === "queued" ? t("jobCard.queued") : t("jobCard.running");
const step = job.current_step
? job.current_step
: job.status === "queued"
? "queued"
: "preparing";
const percent = Math.round(job.progress_percent ?? 0);
const stepLabel = useMemo(() => {
switch (step) {
case "queued":
return t("jobCard.queued");
case "preparing":
return t("jobCard.preparing");
case "copying":
return t("jobCard.copying");
case "encoding":
return t("jobCard.encoding");
case "encoding_retry":
return t("jobCard.encodingRetry");
case "finalizing":
return t("jobCard.finalizing");
default:
return t("jobCard.running");
}
}, [step, t]);
const hasDeterminateProgress =
step === "copying" || step === "encoding" || step === "encoding_retry";
return (
<div
@@ -402,11 +438,20 @@ export function ActiveExportJobCard({
className,
)}
>
<div className="absolute right-3 top-3 z-30 rounded-full bg-selected/90 px-2 py-1 text-xs text-selected-foreground">
{statusLabel}
</div>
<div className="flex flex-col items-center gap-3 px-6 text-center">
<ActivityIndicator />
<div className="flex w-full max-w-xs flex-col items-center gap-2 space-y-2 px-6 text-center">
<div className="text-xs text-muted-foreground">
{stepLabel}
{hasDeterminateProgress && ` · ${percent}%`}
</div>
{step === "queued" ? (
<ActivityIndicator className="size-5" />
) : hasDeterminateProgress ? (
<Progress value={percent} className="h-2 w-full" />
) : (
<div className="relative h-2 w-full overflow-hidden rounded-full bg-secondary">
<div className="absolute inset-y-0 left-0 w-1/2 animate-pulse bg-primary" />
</div>
)}
<div className="text-sm font-medium text-primary">{displayName}</div>
</div>
</div>
+1 -1
View File
@@ -275,7 +275,7 @@ export default function ReviewCard({
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<ContextMenu key={event.id} modal={false}>
<ContextMenu key={event.id}>
<ContextMenuTrigger asChild>{content}</ContextMenuTrigger>
<ContextMenuContent>
<ContextMenuItem>
@@ -322,7 +322,7 @@ export default function Step1NameAndDefine({
<FormLabel className="text-primary-variant">
{t("wizard.step1.classificationType")}
</FormLabel>
<Popover modal={true}>
<Popover>
<PopoverTrigger asChild>
<Button
variant="ghost"
@@ -405,7 +405,7 @@ export default function Step1NameAndDefine({
? t("wizard.step1.states")
: t("wizard.step1.classes")}
</FormLabel>
<Popover modal={true}>
<Popover>
<PopoverTrigger asChild>
<Button variant="ghost" size="sm" className="h-4 w-4 p-0">
<LuInfo className="size-3" />
@@ -238,11 +238,7 @@ export default function Step2StateArea({
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium">{t("wizard.step2.cameras")}</h3>
{availableCameras.length > 0 ? (
<Popover
open={isPopoverOpen}
onOpenChange={setIsPopoverOpen}
modal={true}
>
<Popover open={isPopoverOpen} onOpenChange={setIsPopoverOpen}>
<PopoverTrigger asChild>
<Button
type="button"
@@ -31,6 +31,8 @@ const ffmpeg: SectionConfigOverrides = {
"inputs.output_args": "/configuration/ffmpeg_presets#output-args-presets",
"output_args.record": "/configuration/ffmpeg_presets#output-args-presets",
"inputs.roles": "/configuration/cameras/#setting-up-camera-inputs",
apple_compatibility:
"/configuration/camera_specific#h265-cameras-via-safari",
},
restartRequired: [],
fieldOrder: [
@@ -27,10 +27,12 @@ const lpr: SectionConfigOverrides = {
],
fieldDocs: {
enhancement: "/configuration/license_plate_recognition#enhancement",
debug_save_plates:
"/configuration/license_plate_recognition/#how-do-i-debug-lpr-issues",
},
restartRequired: [],
fieldOrder: ["enabled", "min_area", "enhancement", "expire_time"],
hiddenFields: [],
hiddenFields: ["expire_time"],
advancedFields: ["expire_time", "enhancement"],
overrideFields: ["enabled", "min_area", "enhancement"],
},
@@ -3,6 +3,11 @@ import type { SectionConfigOverrides } from "./types";
const onvif: SectionConfigOverrides = {
base: {
sectionDocs: "/configuration/cameras#setting-up-camera-ptz-controls",
fieldDocs: {
autotracking: "/configuration/autotracking",
"autotracking.calibrate_on_startup":
"/configuration/autotracking#calibration",
},
fieldOrder: [
"host",
"port",
@@ -45,6 +45,10 @@ const review: SectionConfigOverrides = {
fieldDocs: {
"alerts.labels": "/configuration/review/#alerts-and-detections",
"detections.labels": "/configuration/review/#alerts-and-detections",
genai: "/configuration/genai/genai_review",
"genai.image_source": "/configuration/genai/genai_review#image-source",
"genai.additional_concerns":
"/configuration/genai/genai_review#additional-concerns",
},
restartRequired: [],
fieldOrder: ["alerts", "detections", "genai", "genai.enabled"],
@@ -218,7 +218,7 @@ export default function CameraReviewClassification({
<Label
className={cn(
"flex flex-row items-center text-base",
alertsZonesModified && "text-danger",
alertsZonesModified && "text-unsaved",
)}
>
<Trans ns="views/settings">cameraReview.review.alerts</Trans>
@@ -286,7 +286,7 @@ export default function CameraReviewClassification({
<Label
className={cn(
"flex flex-row items-center text-base",
detectionsZonesModified && "text-danger",
detectionsZonesModified && "text-unsaved",
)}
>
<Trans ns="views/settings">
@@ -1012,7 +1012,7 @@ export function ConfigSection({
>
{hasChanges && (
<div className="flex items-center gap-2">
<span className="text-sm text-danger">
<span className="text-sm text-unsaved">
{t("unsavedChanges", {
ns: "views/settings",
defaultValue: "You have unsaved changes",
@@ -1299,7 +1299,7 @@ export function ConfigSection({
{hasChanges && (
<Badge
variant="secondary"
className="cursor-default bg-danger text-xs text-white hover:bg-danger"
className="cursor-default bg-unsaved text-xs text-black hover:bg-unsaved"
>
{t("button.modified", {
ns: "common",
@@ -154,7 +154,7 @@ export function KnownPlatesField(props: FieldProps) {
<div className="flex items-center justify-between">
<div>
<CardTitle
className={cn("text-sm", isModified && "text-danger")}
className={cn("text-sm", isModified && "text-unsaved")}
>
{title}
</CardTitle>
@@ -142,7 +142,7 @@ export function ReplaceRulesField(props: FieldProps) {
<div className="flex items-center justify-between">
<div>
<CardTitle
className={cn("text-sm", isModified && "text-danger")}
className={cn("text-sm", isModified && "text-unsaved")}
>
{title}
</CardTitle>
@@ -497,7 +497,7 @@ export function FieldTemplate(props: FieldTemplateProps) {
htmlFor={id}
className={cn(
"text-sm font-medium",
isModified && "text-danger",
isModified && "text-unsaved",
hasFieldErrors && "text-destructive",
)}
>
@@ -516,7 +516,7 @@ export function FieldTemplate(props: FieldTemplateProps) {
return (
<Label
htmlFor={id}
className={cn("text-sm font-medium", isModified && "text-danger")}
className={cn("text-sm font-medium", isModified && "text-unsaved")}
>
{finalLabel}
{required && <span className="ml-1 text-destructive">*</span>}
@@ -535,7 +535,7 @@ export function FieldTemplate(props: FieldTemplateProps) {
htmlFor={id}
className={cn(
"text-sm font-medium",
isModified && "text-danger",
isModified && "text-unsaved",
hasFieldErrors && "text-destructive",
)}
>
@@ -9,11 +9,13 @@ import {
import { Children, useState, useEffect, useRef } from "react";
import type { ReactNode } from "react";
import RestartRequiredIndicator from "@/components/indicators/RestartRequiredIndicator";
import { LuChevronDown, LuChevronRight } from "react-icons/lu";
import { LuChevronDown, LuChevronRight, LuExternalLink } from "react-icons/lu";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { cn } from "@/lib/utils";
import { getTranslatedLabel } from "@/utils/i18n";
import { requiresRestartForFieldPath } from "@/utils/configUtil";
import { useDocDomain } from "@/hooks/use-doc-domain";
import { ConfigFormContext } from "@/types/configForm";
import {
buildTranslationPath,
@@ -178,6 +180,7 @@ export function ObjectFieldTemplate(props: ObjectFieldTemplateProps) {
"views/settings",
"common",
]);
const { getLocaleDocUrl } = useDocDomain();
const objectRequiresRestart = requiresRestartForFieldPath(
fieldPath,
restartRequired,
@@ -300,6 +303,17 @@ export function ObjectFieldTemplate(props: ObjectFieldTemplateProps) {
schemaDescription;
inferredDescription = inferredDescription ?? fallbackDescription;
const pathStringSegments =
path?.filter((segment): segment is string => typeof segment === "string") ??
[];
const fieldDocsKey = translationPath || pathStringSegments.join(".");
const fieldDocsPath = fieldDocsKey
? formContext?.fieldDocs?.[fieldDocsKey]
: undefined;
const fieldDocsUrl = fieldDocsPath
? getLocaleDocUrl(fieldDocsPath)
: undefined;
const renderGroupedFields = (items: (typeof properties)[number][]) => {
if (!items.length) {
return null;
@@ -453,7 +467,7 @@ export function ObjectFieldTemplate(props: ObjectFieldTemplateProps) {
<CardTitle
className={cn(
"flex items-center text-sm",
hasModifiedDescendants && "text-danger",
hasModifiedDescendants && "text-unsaved",
)}
>
{inferredLabel}
@@ -466,6 +480,20 @@ export function ObjectFieldTemplate(props: ObjectFieldTemplateProps) {
{inferredDescription}
</p>
)}
{fieldDocsUrl && (
<div className="mt-1 flex items-center text-xs text-primary-variant">
<Link
to={fieldDocsUrl}
target="_blank"
rel="noopener noreferrer"
className="inline"
onClick={(e) => e.stopPropagation()}
>
{t("readTheDocumentation", { ns: "common" })}
<LuExternalLink className="ml-2 inline-flex size-3" />
</Link>
</div>
)}
</div>
{isOpen ? (
<LuChevronDown className="h-4 w-4 shrink-0" />
@@ -592,7 +592,7 @@ export function CameraGroupRow({
{isMobile && !isReadOnly && (
<>
<DropdownMenu modal={!isDesktop}>
<DropdownMenu>
<DropdownMenuTrigger>
<HiOutlineDotsVertical className="size-5" />
</DropdownMenuTrigger>
@@ -136,7 +136,6 @@ export function CamerasFilterButton({
return (
<DropdownMenu
modal={false}
open={open}
onOpenChange={(open) => {
if (!open) {
+54 -34
View File
@@ -30,6 +30,7 @@ type ExportActionGroupProps = {
cases?: ExportCase[];
currentCaseId?: string;
mutate: () => void;
deleteExports: (ids: string[]) => Promise<void>;
};
export default function ExportActionGroup({
selectedExports,
@@ -38,6 +39,7 @@ export default function ExportActionGroup({
cases,
currentCaseId,
mutate,
deleteExports,
}: ExportActionGroupProps) {
const { t } = useTranslation(["views/exports", "common"]);
const isAdmin = useIsAdmin();
@@ -50,27 +52,24 @@ export default function ExportActionGroup({
const onDelete = useCallback(() => {
const ids = selectedExports.map((e) => e.id);
axios
.post("exports/delete", { ids })
.then((resp) => {
if (resp.status === 200) {
toast.success(t("bulkToast.success.delete"), {
position: "top-center",
});
setSelectedExports([]);
mutate();
}
deleteExports(ids)
.then(() => {
toast.success(t("bulkToast.success.delete"), {
position: "top-center",
});
setSelectedExports([]);
})
.catch((error) => {
const errorMessage =
error.response?.data?.message ||
error.response?.data?.detail ||
error?.response?.data?.message ||
error?.response?.data?.detail ||
"Unknown error";
toast.error(t("bulkToast.error.deleteFailed", { errorMessage }), {
position: "top-center",
});
toast.error(
t("bulkToast.error.deleteFailed", { errorMessage: errorMessage }),
{ position: "top-center" },
);
});
}, [selectedExports, setSelectedExports, mutate, t]);
}, [selectedExports, setSelectedExports, deleteExports, t]);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [bypassDialog, setBypassDialog] = useState(false);
@@ -92,36 +91,54 @@ export default function ExportActionGroup({
const [removeDialogOpen, setRemoveDialogOpen] = useState(false);
const [deleteExportsOnRemove, setDeleteExportsOnRemove] = useState(false);
const [isRemovingFromCase, setIsRemovingFromCase] = useState(false);
const handleRemoveFromCase = useCallback(() => {
const ids = selectedExports.map((e) => e.id);
const deleting = deleteExportsOnRemove;
setIsRemovingFromCase(true);
const request = deleteExportsOnRemove
? axios.post("exports/delete", { ids })
: axios.post("exports/reassign", { ids, export_case_id: null });
const request = deleting
? deleteExports(ids)
: axios
.post("exports/reassign", { ids, export_case_id: null })
.then(() => {
mutate();
});
request
.then((resp) => {
if (resp.status === 200) {
toast.success(t("bulkToast.success.remove"), {
position: "top-center",
});
setSelectedExports([]);
mutate();
setRemoveDialogOpen(false);
setDeleteExportsOnRemove(false);
}
.then(() => {
const successKey = deleting
? "bulkToast.success.delete"
: "bulkToast.success.remove";
toast.success(t(successKey), { position: "top-center" });
setSelectedExports([]);
setRemoveDialogOpen(false);
setDeleteExportsOnRemove(false);
})
.catch((error) => {
const errorMessage =
error.response?.data?.message ||
error.response?.data?.detail ||
error?.response?.data?.message ||
error?.response?.data?.detail ||
"Unknown error";
toast.error(t("bulkToast.error.reassignFailed", { errorMessage }), {
const errorKey = deleting
? "bulkToast.error.deleteFailed"
: "bulkToast.error.reassignFailed";
toast.error(t(errorKey, { errorMessage: errorMessage }), {
position: "top-center",
});
})
.finally(() => {
setIsRemovingFromCase(false);
});
}, [selectedExports, deleteExportsOnRemove, setSelectedExports, mutate, t]);
}, [
selectedExports,
deleteExportsOnRemove,
setSelectedExports,
mutate,
deleteExports,
t,
]);
// ── Case picker ─────────────────────────────────────────────────
@@ -243,6 +260,7 @@ export default function ExportActionGroup({
<AlertDialog
open={removeDialogOpen}
onOpenChange={(open) => {
if (isRemovingFromCase) return;
if (!open) {
setRemoveDialogOpen(false);
setDeleteExportsOnRemove(false);
@@ -274,15 +292,17 @@ export default function ExportActionGroup({
id="bulk-delete-exports-switch"
checked={deleteExportsOnRemove}
onCheckedChange={setDeleteExportsOnRemove}
disabled={isRemovingFromCase}
/>
</div>
<AlertDialogFooter>
<AlertDialogCancel>
<AlertDialogCancel disabled={isRemovingFromCase}>
{t("button.cancel", { ns: "common" })}
</AlertDialogCancel>
<AlertDialogAction
className={buttonVariants({ variant: "destructive" })}
onClick={handleRemoveFromCase}
disabled={isRemovingFromCase}
>
{t("button.delete", { ns: "common" })}
</AlertDialogAction>
+1 -1
View File
@@ -81,7 +81,7 @@ export default function AccountSettings({ className }: AccountSettingsProps) {
};
return (
<Container modal={!isDesktop}>
<Container>
<Tooltip>
<Trigger asChild>
<TooltipTrigger asChild>
+1 -1
View File
@@ -205,7 +205,7 @@ export default function GeneralSettings({ className }: GeneralSettingsProps) {
return (
<>
<Container modal={!isDesktop}>
<Container>
<Trigger>
<Tooltip>
<TooltipTrigger asChild>
+1 -1
View File
@@ -272,7 +272,7 @@ export default function LiveContextMenu({
return (
<div className={cn("w-full", className)}>
<ContextMenu key={camera} modal={false} onOpenChange={handleOpenChange}>
<ContextMenu key={camera} onOpenChange={handleOpenChange}>
<ContextMenuTrigger>{children}</ContextMenuTrigger>
<ContextMenuContent>
<div className="flex flex-col items-start gap-1 py-1 pl-2">
@@ -258,13 +258,13 @@ export default function SearchResultActions({
</AlertDialogContent>
</AlertDialog>
{isContextMenu ? (
<ContextMenu modal={false}>
<ContextMenu>
<ContextMenuTrigger>{children}</ContextMenuTrigger>
<ContextMenuContent>{menuItems}</ContextMenuContent>
</ContextMenu>
) : (
<>
<DropdownMenu modal={false}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<BlurredIconButton aria-label={t("itemMenu.more.aria")}>
<FiMoreVertical className="size-5" />
@@ -11,16 +11,18 @@ import { FaFilm } from "react-icons/fa6";
type ActionsDropdownProps = {
onDebugReplayClick: () => void;
onExportClick: () => void;
onShareTimestampClick: () => void;
};
export default function ActionsDropdown({
onDebugReplayClick,
onExportClick,
}: ActionsDropdownProps) {
onShareTimestampClick,
}: Readonly<ActionsDropdownProps>) {
const { t } = useTranslation(["components/dialog", "views/replay", "common"]);
return (
<DropdownMenu modal={false}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
className="flex items-center gap-2"
@@ -37,6 +39,9 @@ export default function ActionsDropdown({
<DropdownMenuItem onClick={onExportClick}>
{t("menu.export", { ns: "common" })}
</DropdownMenuItem>
<DropdownMenuItem onClick={onShareTimestampClick}>
{t("recording.shareTimestamp.label", { ns: "components/dialog" })}
</DropdownMenuItem>
<DropdownMenuItem onClick={onDebugReplayClick}>
{t("title", { ns: "views/replay" })}
</DropdownMenuItem>
@@ -127,7 +127,7 @@ export function CustomTimeSelector({
{formattedStart}
</Button>
</PopoverTrigger>
<PopoverContent className="flex flex-col items-center" disablePortal>
<PopoverContent className="flex flex-col items-center">
<TimezoneAwareCalendar
timezone={config?.ui.timezone}
selectedDay={new Date(startTime * 1000)}
@@ -193,7 +193,7 @@ export function CustomTimeSelector({
{formattedEnd}
</Button>
</PopoverTrigger>
<PopoverContent className="flex flex-col items-center" disablePortal>
<PopoverContent className="flex flex-col items-center">
<TimezoneAwareCalendar
timezone={config?.ui.timezone}
selectedDay={new Date(endTime * 1000)}
@@ -113,18 +113,19 @@ export function DebugReplayContent({
{isDesktop && <SelectSeparator className="my-4 bg-secondary" />}
<DialogFooter
className={isDesktop ? "" : "mt-3 flex flex-col-reverse gap-4"}
className={isDesktop ? "" : "mt-3 flex flex-col-reverse gap-2"}
>
<div
className={`cursor-pointer p-2 text-center ${isDesktop ? "" : "w-full"}`}
<Button
className={isDesktop ? "" : "w-full"}
aria-label={t("button.cancel", { ns: "common" })}
variant="outline"
onClick={onCancel}
>
{t("button.cancel", { ns: "common" })}
</div>
</Button>
<Button
className={isDesktop ? "" : "w-full"}
variant="select"
size="sm"
disabled={isStarting}
onClick={() => {
if (selectedOption === "timeline") {
+6 -5
View File
@@ -1043,20 +1043,21 @@ export function ExportContent({
{isDesktop && <SelectSeparator className="my-4 bg-secondary" />}
<DialogFooter
className={isDesktop ? "" : "mt-3 flex flex-col-reverse gap-4"}
className={isDesktop ? "" : "mt-3 flex flex-col-reverse gap-2"}
>
<div
className={`cursor-pointer p-2 text-center ${isDesktop ? "" : "w-full"}`}
<Button
className={isDesktop ? "" : "w-full"}
aria-label={t("button.cancel", { ns: "common" })}
variant="outline"
onClick={onCancel}
>
{t("button.cancel", { ns: "common" })}
</div>
</Button>
{activeTab === "export" ? (
<Button
className={isDesktop ? "" : "w-full"}
aria-label={t("export.selectOrExport")}
variant="select"
size="sm"
disabled={isStartingExport}
onClick={async () => {
if (selectedOption == "timeline") {
@@ -2,7 +2,7 @@ import { useCallback, useState } from "react";
import { Drawer, DrawerContent, DrawerTrigger } from "../ui/drawer";
import { Button } from "../ui/button";
import { FaArrowDown, FaCalendarAlt, FaCog, FaFilter } from "react-icons/fa";
import { LuBug } from "react-icons/lu";
import { LuBug, LuShare2 } from "react-icons/lu";
import { TimeRange } from "@/types/timeline";
import { ExportContent, ExportPreviewDialog, ExportTab } from "./ExportDialog";
import {
@@ -27,6 +27,7 @@ import { isMobile } from "react-device-detect";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { StartExportResponse } from "@/types/export";
import { ShareTimestampContent } from "./ShareTimestampDialog";
type DrawerMode =
| "none"
@@ -34,13 +35,15 @@ type DrawerMode =
| "export"
| "calendar"
| "filter"
| "debug-replay";
| "debug-replay"
| "share-timestamp";
const DRAWER_FEATURES = [
"export",
"calendar",
"filter",
"debug-replay",
"share-timestamp",
] as const;
export type DrawerFeatures = (typeof DRAWER_FEATURES)[number];
const DEFAULT_DRAWER_FEATURES: DrawerFeatures[] = [
@@ -48,6 +51,7 @@ const DEFAULT_DRAWER_FEATURES: DrawerFeatures[] = [
"calendar",
"filter",
"debug-replay",
"share-timestamp",
];
type MobileReviewSettingsDrawerProps = {
@@ -68,6 +72,7 @@ type MobileReviewSettingsDrawerProps = {
debugReplayRange?: TimeRange;
setDebugReplayMode?: (mode: ExportMode) => void;
setDebugReplayRange?: (range: TimeRange | undefined) => void;
onShareTimestamp?: (timestamp: number) => void;
onUpdateFilter: (filter: ReviewFilter) => void;
setRange: (range: TimeRange | undefined) => void;
setMode: (mode: ExportMode) => void;
@@ -91,6 +96,7 @@ export default function MobileReviewSettingsDrawer({
debugReplayRange,
setDebugReplayMode = () => {},
setDebugReplayRange = () => {},
onShareTimestamp = () => {},
onUpdateFilter,
setRange,
setMode,
@@ -100,6 +106,7 @@ export default function MobileReviewSettingsDrawer({
"views/recording",
"components/dialog",
"views/replay",
"common",
]);
const navigate = useNavigate();
const [drawerMode, setDrawerMode] = useState<DrawerMode>("none");
@@ -108,6 +115,15 @@ export default function MobileReviewSettingsDrawer({
"1" | "5" | "custom" | "timeline"
>("1");
const [isDebugReplayStarting, setIsDebugReplayStarting] = useState(false);
const [selectedShareOption, setSelectedShareOption] = useState<
"current" | "custom"
>("current");
const [shareTimestampAtOpen, setShareTimestampAtOpen] = useState(
Math.floor(currentTime),
);
const [customShareTimestamp, setCustomShareTimestamp] = useState(
Math.floor(currentTime),
);
// exports
@@ -323,6 +339,27 @@ export default function MobileReviewSettingsDrawer({
{t("export")}
</Button>
)}
{features.includes("share-timestamp") && (
<Button
className="flex w-full items-center justify-center gap-2"
aria-label={t("recording.shareTimestamp.label", {
ns: "components/dialog",
})}
onClick={() => {
const initialTimestamp = Math.floor(currentTime);
setShareTimestampAtOpen(initialTimestamp);
setCustomShareTimestamp(initialTimestamp);
setSelectedShareOption("current");
setDrawerMode("share-timestamp");
}}
>
<LuShare2 className="size-5 rounded-md bg-secondary-foreground stroke-secondary p-1" />
{t("recording.shareTimestamp.label", {
ns: "components/dialog",
})}
</Button>
)}
{features.includes("calendar") && (
<Button
className="flex w-full items-center justify-center gap-2"
@@ -535,6 +572,28 @@ export default function MobileReviewSettingsDrawer({
}}
/>
);
} else if (drawerMode == "share-timestamp") {
content = (
<div className="w-full">
<div className="relative h-8 w-full">
<div className="absolute left-1/2 -translate-x-1/2 text-muted-foreground">
{t("recording.shareTimestamp.title", { ns: "components/dialog" })}
</div>
</div>
<ShareTimestampContent
currentTime={shareTimestampAtOpen}
selectedOption={selectedShareOption}
setSelectedOption={setSelectedShareOption}
customTimestamp={customShareTimestamp}
setCustomTimestamp={setCustomShareTimestamp}
onShareTimestamp={(timestamp) => {
onShareTimestamp(timestamp);
setDrawerMode("none");
}}
onCancel={() => setDrawerMode("select")}
/>
</div>
);
}
return (
@@ -14,7 +14,7 @@ import {
import useKeyboardListener from "@/hooks/use-keyboard-listener";
import { CameraPtzInfo } from "@/types/ptz";
import React, { useCallback } from "react";
import { isDesktop, isMobile } from "react-device-detect";
import { isMobile } from "react-device-detect";
import { BsThreeDotsVertical } from "react-icons/bs";
import {
FaAngleDown,
@@ -292,7 +292,7 @@ export default function PtzControlPanel({
</Tooltip>
)}
{(ptz?.presets?.length ?? 0) > 0 && (
<DropdownMenu modal={!isDesktop}>
<DropdownMenu>
<Tooltip>
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
@@ -0,0 +1,366 @@
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Drawer, DrawerContent } from "@/components/ui/drawer";
import { Label } from "@/components/ui/label";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Separator } from "@/components/ui/separator";
import { useFormattedTimestamp, useTimeFormat } from "@/hooks/use-date-utils";
import { cn } from "@/lib/utils";
import { FrigateConfig } from "@/types/frigateConfig";
import { getUTCOffset } from "@/utils/dateUtil";
import { useCallback, useMemo, useState } from "react";
import useSWR from "swr";
import { TimezoneAwareCalendar } from "./ReviewActivityCalendar";
import { FaCalendarAlt } from "react-icons/fa";
import { isDesktop, isIOS, isMobile } from "react-device-detect";
import { useTranslation } from "react-i18next";
type ShareTimestampDialogProps = {
currentTime: number;
open: boolean;
onOpenChange: (open: boolean) => void;
selectedOption: "current" | "custom";
setSelectedOption: (option: "current" | "custom") => void;
customTimestamp: number;
setCustomTimestamp: (timestamp: number) => void;
onShareTimestamp: (timestamp: number) => void;
};
export default function ShareTimestampDialog({
currentTime,
open,
onOpenChange,
selectedOption,
setSelectedOption,
customTimestamp,
setCustomTimestamp,
onShareTimestamp,
}: Readonly<ShareTimestampDialogProps>) {
const { t } = useTranslation(["components/dialog"]);
const handleOpenChange = useCallback(
(nextOpen: boolean) => onOpenChange(nextOpen),
[onOpenChange],
);
const content = (
<ShareTimestampContent
currentTime={currentTime}
selectedOption={selectedOption}
setSelectedOption={setSelectedOption}
customTimestamp={customTimestamp}
setCustomTimestamp={setCustomTimestamp}
onShareTimestamp={(timestamp) => {
onShareTimestamp(timestamp);
onOpenChange(false);
}}
onCancel={() => onOpenChange(false)}
/>
);
if (isMobile) {
return (
<Drawer open={open} onOpenChange={handleOpenChange}>
<DrawerContent className="mx-4 rounded-lg px-4 pb-4 md:rounded-2xl">
{content}
</DrawerContent>
</Drawer>
);
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="sm:rounded-lg md:rounded-2xl">
<DialogHeader>
<DialogTitle className="whitespace-nowrap">
{t("recording.shareTimestamp.title", { ns: "components/dialog" })}
</DialogTitle>
<DialogDescription className="sr-only">
{t("recording.shareTimestamp.description", {
ns: "components/dialog",
})}
</DialogDescription>
</DialogHeader>
{content}
</DialogContent>
</Dialog>
);
}
type ShareTimestampContentProps = {
currentTime: number;
selectedOption: "current" | "custom";
setSelectedOption: (option: "current" | "custom") => void;
customTimestamp: number;
setCustomTimestamp: (timestamp: number) => void;
onShareTimestamp: (timestamp: number) => void;
onCancel?: () => void;
};
export function ShareTimestampContent({
currentTime,
selectedOption,
setSelectedOption,
customTimestamp,
setCustomTimestamp,
onShareTimestamp,
onCancel,
}: Readonly<ShareTimestampContentProps>) {
const { t } = useTranslation(["common", "components/dialog"]);
const { data: config } = useSWR<FrigateConfig>("config");
const timeFormat = useTimeFormat(config);
const currentTimestampLabel = useFormattedTimestamp(
currentTime,
timeFormat == "24hour"
? t("time.formattedTimestamp.24hour")
: t("time.formattedTimestamp.12hour"),
config?.ui.timezone,
);
const selectedTimestamp =
selectedOption === "current" ? currentTime : customTimestamp;
return (
<div className="w-full">
<div className="space-y-1">
<div className="text-sm text-muted-foreground">
{t("recording.shareTimestamp.description", {
ns: "components/dialog",
})}
</div>
</div>
{isDesktop && <Separator className="my-4 bg-secondary" />}
<RadioGroup
className="mt-4 flex flex-col gap-4"
value={selectedOption}
onValueChange={(value) =>
setSelectedOption(value as "current" | "custom")
}
>
<div className="flex items-center gap-2">
<RadioGroupItem
className={
selectedOption == "current"
? "bg-selected from-selected/50 to-selected/90 text-selected"
: "bg-secondary from-secondary/50 to-secondary/90 text-secondary"
}
id="share-current"
value="current"
/>
<Label className="cursor-pointer text-sm" htmlFor="share-current">
{currentTimestampLabel}
</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem
className={
selectedOption == "custom"
? "bg-selected from-selected/50 to-selected/90 text-selected"
: "bg-secondary from-secondary/50 to-secondary/90 text-secondary"
}
id="share-custom"
value="custom"
/>
<div className="space-y-3">
<Label className="cursor-pointer text-sm" htmlFor="share-custom">
{t("recording.shareTimestamp.custom", {
ns: "components/dialog",
})}
</Label>
{selectedOption === "custom" && (
<CustomTimestampSelector
timestamp={customTimestamp}
setTimestamp={setCustomTimestamp}
label={t("recording.shareTimestamp.custom", {
ns: "components/dialog",
})}
/>
)}
</div>
</div>
</RadioGroup>
{isDesktop && <Separator className="my-4 bg-secondary" />}
<DialogFooter
className={cn("mt-4", !isDesktop && "flex flex-col-reverse gap-2")}
>
{onCancel && (
<Button
className={cn(!isDesktop && "w-full")}
aria-label={t("button.cancel", { ns: "common" })}
variant="outline"
onClick={onCancel}
>
{t("button.cancel", { ns: "common" })}
</Button>
)}
<Button
className={cn(!isDesktop && "w-full")}
variant="select"
onClick={() => onShareTimestamp(Math.floor(selectedTimestamp))}
>
{t("recording.shareTimestamp.button", { ns: "components/dialog" })}
</Button>
</DialogFooter>
</div>
);
}
type CustomTimestampSelectorProps = {
timestamp: number;
setTimestamp: (timestamp: number) => void;
label: string;
};
function CustomTimestampSelector({
timestamp,
setTimestamp,
label,
}: Readonly<CustomTimestampSelectorProps>) {
const { t } = useTranslation(["common"]);
const { data: config } = useSWR<FrigateConfig>("config");
const timeFormat = useTimeFormat(config);
const timezoneOffset = useMemo(
() =>
config?.ui.timezone
? Math.round(getUTCOffset(new Date(), config.ui.timezone))
: undefined,
[config?.ui.timezone],
);
const localTimeOffset = useMemo(
() =>
Math.round(
getUTCOffset(
new Date(),
Intl.DateTimeFormat().resolvedOptions().timeZone,
),
),
[],
);
const offsetDeltaSeconds = useMemo(() => {
if (timezoneOffset === undefined) {
return 0;
}
// the picker edits a timestamp in the configured UI timezone,
// but the stored value remains a unix timestamp
return (timezoneOffset - localTimeOffset) * 60;
}, [timezoneOffset, localTimeOffset]);
const displayTimestamp = useMemo(
() => timestamp + offsetDeltaSeconds,
[timestamp, offsetDeltaSeconds],
);
const formattedTimestamp = useFormattedTimestamp(
displayTimestamp,
timeFormat == "24hour"
? t("time.formattedTimestamp.24hour")
: t("time.formattedTimestamp.12hour"),
);
const clock = useMemo(() => {
const date = new Date(displayTimestamp * 1000);
return `${date.getHours().toString().padStart(2, "0")}:${date.getMinutes().toString().padStart(2, "0")}:${date.getSeconds().toString().padStart(2, "0")}`;
}, [displayTimestamp]);
const [selectorOpen, setSelectorOpen] = useState(false);
const setFromDisplayDate = useCallback(
(date: Date) => {
// convert the edited display time back into the underlying Unix timestamp
setTimestamp(date.getTime() / 1000 - offsetDeltaSeconds);
},
[offsetDeltaSeconds, setTimestamp],
);
return (
<div
className={cn(
"flex items-center rounded-lg bg-secondary text-secondary-foreground",
isDesktop ? "gap-2 px-2" : "pl-2",
)}
>
<FaCalendarAlt />
<div className="flex flex-wrap items-center">
<Popover
open={selectorOpen}
onOpenChange={(open) => {
if (!open) {
setSelectorOpen(false);
}
}}
>
<PopoverTrigger asChild>
<Button
className={cn("text-primary", !isDesktop && "text-xs")}
aria-label={label}
variant={selectorOpen ? "select" : "default"}
size="sm"
onClick={() => setSelectorOpen(true)}
>
{formattedTimestamp}
</Button>
</PopoverTrigger>
<PopoverContent className="flex flex-col items-center">
<TimezoneAwareCalendar
timezone={config?.ui.timezone}
selectedDay={new Date(displayTimestamp * 1000)}
onSelect={(day) => {
if (!day) {
return;
}
const nextTimestamp = new Date(displayTimestamp * 1000);
nextTimestamp.setFullYear(
day.getFullYear(),
day.getMonth(),
day.getDate(),
);
setFromDisplayDate(nextTimestamp);
}}
/>
<div className="my-3 h-px w-full bg-secondary" />
<input
className="text-md mx-4 w-full border border-input bg-background p-1 text-secondary-foreground hover:bg-accent hover:text-accent-foreground dark:[color-scheme:dark]"
id="shareTimestamp"
type="time"
value={clock}
step={isIOS ? "60" : "1"}
onChange={(e) => {
const nextClock = e.target.value;
const [hour, minute, second] = isIOS
? [...nextClock.split(":"), "00"]
: nextClock.split(":");
const nextTimestamp = new Date(displayTimestamp * 1000);
nextTimestamp.setHours(
Number.parseInt(hour),
Number.parseInt(minute),
Number.parseInt(second ?? "0"),
0,
);
setFromDisplayDate(nextTimestamp);
}}
/>
</PopoverContent>
</Popover>
</div>
</div>
);
}
@@ -241,7 +241,7 @@ function AnnotationSettings({
return (
<div className="ml-2">
<Overlay modal={isDesktop} open={open} onOpenChange={handleOpenChange}>
<Overlay open={open} onOpenChange={handleOpenChange}>
<Trigger asChild>
<Button
type="button"
@@ -269,7 +269,6 @@ function AnnotationSettings({
: "mx-1 max-h-[75dvh] overflow-hidden rounded-t-2xl px-4 pb-4"
}
{...contentProps}
{...(isDesktop ? { disablePortal: true } : {})}
data-annotation-popover
>
<AnnotationSettingsPane
@@ -636,6 +636,13 @@ export function TrackingDetails({
return axios.post(`/${event.camera}/plus/${currentTime}`);
}, [event.camera, currentTime]);
const getSnapshotUrlForPlus = useCallback(() => {
if (!currentTime) {
return undefined;
}
return `${apiHost}api/${event.camera}/recordings/${currentTime}/snapshot.jpg?height=500`;
}, [apiHost, event.camera, currentTime]);
if (!config) {
return <ActivityIndicator />;
}
@@ -683,6 +690,7 @@ export function TrackingDetails({
onTimeUpdate={handleTimeUpdate}
onSeekToTime={handleSeekToTime}
onUploadFrame={onUploadFrameToPlus}
getSnapshotUrl={getSnapshotUrlForPlus}
onPlaying={() => setIsVideoLoading(false)}
setFullResolution={setFullResolution}
toggleFullscreen={toggleFullscreen}
@@ -867,6 +875,7 @@ export function TrackingDetails({
getZoneColor={getZoneColor}
effectiveTime={effectiveTime}
isTimelineActive={isWithinEventRange}
annotationOffset={annotationOffset}
/>
</div>
);
@@ -890,6 +899,7 @@ type LifecycleIconRowProps = {
getZoneColor: (zoneName: string) => number[] | undefined;
effectiveTime?: number;
isTimelineActive?: boolean;
annotationOffset: number;
};
function LifecycleIconRow({
@@ -900,6 +910,7 @@ function LifecycleIconRow({
getZoneColor,
effectiveTime,
isTimelineActive,
annotationOffset,
}: LifecycleIconRowProps) {
const { t } = useTranslation(["views/explore", "components/player"]);
const { data: config } = useSWR<FrigateConfig>("config");
@@ -1206,7 +1217,7 @@ function LifecycleIconRow({
className="cursor-pointer"
onSelect={async () => {
const resp = await axios.post(
`/${item.camera}/plus/${item.timestamp}`,
`/${item.camera}/plus/${item.timestamp + annotationOffset / 1000}`,
);
if (resp && resp.status == 200) {
@@ -38,12 +38,6 @@ export default function RestartDialog({
const [restartingSheetOpen, setRestartingSheetOpen] = useState(false);
const [countdown, setCountdown] = useState(60);
const clearBodyPointerEvents = () => {
if (typeof document !== "undefined") {
document.body.style.pointerEvents = "";
}
};
useEffect(() => {
setRestartDialogOpen(isOpen);
}, [isOpen]);
@@ -85,16 +79,10 @@ export default function RestartDialog({
if (!open) {
setRestartDialogOpen(false);
onClose();
clearBodyPointerEvents();
}
}}
>
<AlertDialogContent
onCloseAutoFocus={(event) => {
event.preventDefault();
clearBodyPointerEvents();
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t("restart.title")}</AlertDialogTitle>
<AlertDialogDescription className="sr-only">
+39 -5
View File
@@ -53,6 +53,7 @@ type HlsVideoPlayerProps = {
onSeekToTime?: (timestamp: number, play?: boolean) => void;
setFullResolution?: React.Dispatch<React.SetStateAction<VideoResolutionType>>;
onUploadFrame?: (playTime: number) => Promise<AxiosResponse> | undefined;
getSnapshotUrl?: (playTime: number) => string | undefined;
toggleFullscreen?: () => void;
onError?: (error: RecordingPlayerError) => void;
isDetailMode?: boolean;
@@ -78,6 +79,7 @@ export default function HlsVideoPlayer({
onSeekToTime,
setFullResolution,
onUploadFrame,
getSnapshotUrl,
toggleFullscreen,
onError,
isDetailMode = false,
@@ -216,7 +218,11 @@ export default function HlsVideoPlayer({
const [tallCamera, setTallCamera] = useState(false);
const [isPlaying, setIsPlaying] = useState(true);
const [muted, setMuted] = useUserPersistence("hlsPlayerMuted", true);
const [persistedMuted, setPersistedMuted] = useUserPersistence(
"hlsPlayerMuted",
true,
);
const [temporaryMuted, setTemporaryMuted] = useState(false);
const [volume, setVolume] = useOverlayState("playerVolume", 1.0);
const [defaultPlaybackRate] = useUserPersistence("playbackRate", 1);
const [playbackRate, setPlaybackRate] = useOverlayState(
@@ -232,6 +238,16 @@ export default function HlsVideoPlayer({
height: number;
}>({ width: 0, height: 0 });
const muted = persistedMuted || temporaryMuted;
const onSetMuted = useCallback(
(muted: boolean) => {
setTemporaryMuted(false);
setPersistedMuted(muted);
},
[setPersistedMuted],
);
useEffect(() => {
if (!isDesktop) {
return;
@@ -297,7 +313,7 @@ export default function HlsVideoPlayer({
fullscreen: supportsFullscreen,
}}
setControlsOpen={setControlsOpen}
setMuted={(muted) => setMuted(muted)}
setMuted={onSetMuted}
playbackRate={playbackRate ?? 1}
hotKeys={hotKeys}
onPlayPause={onPlayPause}
@@ -317,6 +333,13 @@ export default function HlsVideoPlayer({
videoRef.current.playbackRate = rate;
}
}}
getSnapshotUrl={() => {
const frameTime = getVideoTime();
if (!frameTime || !getSnapshotUrl) {
return undefined;
}
return getSnapshotUrl(frameTime);
}}
onUploadFrame={async () => {
const frameTime = getVideoTime();
@@ -404,9 +427,20 @@ export default function HlsVideoPlayer({
: undefined
}
onVolumeChange={() => {
setVolume(videoRef.current?.volume ?? 1.0, true);
if (!frigateControls) {
setMuted(videoRef.current?.muted);
if (!videoRef.current) {
return;
}
setVolume(videoRef.current.volume ?? 1.0, true);
if (frigateControls) {
if (videoRef.current.muted && !persistedMuted) {
setTemporaryMuted(true);
} else if (!videoRef.current.muted && temporaryMuted) {
setTemporaryMuted(false);
}
} else {
setPersistedMuted(videoRef.current.muted);
}
}}
onPlay={() => {
+36 -8
View File
@@ -1,5 +1,6 @@
import { useCallback, useMemo, useRef, useState } from "react";
import { isDesktop, isMobileOnly, isSafari } from "react-device-detect";
import { LuFolderX } from "react-icons/lu";
import { isMobileOnly, isSafari } from "react-device-detect";
import { LuPause, LuPlay } from "react-icons/lu";
import {
DropdownMenu,
@@ -71,6 +72,7 @@ type VideoControlsProps = {
onSeek: (diff: number) => void;
onSetPlaybackRate: (rate: number) => void;
onUploadFrame?: () => void;
getSnapshotUrl?: () => string | undefined;
toggleFullscreen?: () => void;
containerRef?: React.MutableRefObject<HTMLDivElement | null>;
};
@@ -92,6 +94,7 @@ export default function VideoControls({
onSeek,
onSetPlaybackRate,
onUploadFrame,
getSnapshotUrl,
toggleFullscreen,
containerRef,
}: VideoControlsProps) {
@@ -243,7 +246,6 @@ export default function VideoControls({
)}
{features.playbackRate && (
<DropdownMenu
modal={!isDesktop}
onOpenChange={(open) => {
if (setControlsOpen) {
setControlsOpen(open);
@@ -288,6 +290,7 @@ export default function VideoControls({
}
}}
onUploadFrame={onUploadFrame}
getSnapshotUrl={getSnapshotUrl}
containerRef={containerRef}
fullscreen={fullscreen}
/>
@@ -306,6 +309,7 @@ type FrigatePlusUploadButtonProps = {
onOpen: () => void;
onClose: () => void;
onUploadFrame: () => void;
getSnapshotUrl?: () => string | undefined;
containerRef?: React.MutableRefObject<HTMLDivElement | null>;
fullscreen?: boolean;
};
@@ -314,12 +318,14 @@ function FrigatePlusUploadButton({
onOpen,
onClose,
onUploadFrame,
getSnapshotUrl,
containerRef,
fullscreen,
}: FrigatePlusUploadButtonProps) {
const { t } = useTranslation(["components/player"]);
const [videoImg, setVideoImg] = useState<string>();
const [previewUrl, setPreviewUrl] = useState<string>();
const [previewError, setPreviewError] = useState(false);
return (
<AlertDialog
@@ -334,6 +340,13 @@ function FrigatePlusUploadButton({
className="size-5 cursor-pointer"
onClick={() => {
onOpen();
setPreviewError(false);
const snapshotUrl = getSnapshotUrl?.();
if (snapshotUrl) {
setPreviewUrl(snapshotUrl);
return;
}
if (video) {
const videoSize = [video.clientWidth, video.clientHeight];
@@ -345,7 +358,7 @@ function FrigatePlusUploadButton({
if (context) {
context.drawImage(video, 0, 0, videoSize[0], videoSize[1]);
setVideoImg(canvas.toDataURL("image/webp"));
setPreviewUrl(canvas.toDataURL("image/webp"));
}
}
}}
@@ -362,14 +375,29 @@ function FrigatePlusUploadButton({
<AlertDialogHeader>
<AlertDialogTitle>{t("submitFrigatePlus.title")}</AlertDialogTitle>
</AlertDialogHeader>
<img className="aspect-video w-full object-contain" src={videoImg} />
{previewError ? (
<div className="flex aspect-video w-full flex-col items-center justify-center gap-2 text-center text-muted-foreground">
<LuFolderX className="size-12" />
<span>{t("submitFrigatePlus.previewError")}</span>
</div>
) : (
<img
className="aspect-video w-full object-contain"
src={previewUrl}
onError={() => setPreviewError(true)}
/>
)}
<AlertDialogFooter>
<AlertDialogAction className="bg-selected" onClick={onUploadFrame}>
{t("submitFrigatePlus.submit")}
</AlertDialogAction>
<AlertDialogCancel>
{t("button.cancel", { ns: "common" })}
</AlertDialogCancel>
<AlertDialogAction
className="bg-selected text-white"
onClick={onUploadFrame}
disabled={previewError}
>
{t("submitFrigatePlus.submit")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
@@ -6,6 +6,7 @@ import {
calculateInpointOffset,
calculateSeekPosition,
} from "@/utils/videoUtil";
import { playWithTemporaryMuteFallback } from "@/utils/videoUtil.ts";
type PlayerMode = "playback" | "scrubbing";
@@ -107,7 +108,7 @@ export class DynamicVideoController {
return new Promise((resolve) => {
const onSeekedHandler = () => {
this.playerController.removeEventListener("seeked", onSeekedHandler);
this.playerController.play();
playWithTemporaryMuteFallback(this.playerController);
resolve(undefined);
};
@@ -181,6 +181,21 @@ export default function DynamicVideoPlayer({
[camera, controller],
);
const getSnapshotUrlForPlus = useCallback(
(playTime: number) => {
if (!controller) {
return undefined;
}
const time = controller.getProgress(playTime);
if (!time) {
return undefined;
}
return `${apiHost}api/${camera}/recordings/${time}/snapshot.jpg?height=500`;
},
[apiHost, camera, controller],
);
// state of playback player
const recordingParams = useMemo(
@@ -312,6 +327,7 @@ export default function DynamicVideoPlayer({
}}
setFullResolution={setFullResolution}
onUploadFrame={onUploadFrameToPlus}
getSnapshotUrl={getSnapshotUrlForPlus}
toggleFullscreen={toggleFullscreen}
onError={(error) => {
if (error == "stalled" && !isScrubbing) {
+2 -2
View File
@@ -19,7 +19,7 @@ import { LuCopy, LuPencil } from "react-icons/lu";
import { FaDrawPolygon, FaObjectGroup } from "react-icons/fa";
import { BsPersonBoundingBox } from "react-icons/bs";
import { HiOutlineDotsVertical, HiTrash } from "react-icons/hi";
import { isDesktop, isMobile } from "react-device-detect";
import { isMobile } from "react-device-detect";
import { toRGBColorString } from "@/utils/canvasUtil";
import { Polygon, PolygonType } from "@/types/canvas";
import { useCallback, useMemo, useState } from "react";
@@ -524,7 +524,7 @@ export default function PolygonItem({
{isMobile && (
<>
<DropdownMenu modal={!isDesktop}>
<DropdownMenu>
<DropdownMenuTrigger>
<HiOutlineDotsVertical className="size-5" />
</DropdownMenuTrigger>
@@ -41,7 +41,7 @@ export function ProfileSectionDropdown({
: null;
return (
<DropdownMenu modal={false}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
{iconOnly ? (
<Button variant="outline" size="sm">
@@ -377,7 +377,7 @@ export default function Step1NameCamera({
);
return selectedBrand &&
selectedBrand.value != "other" ? (
<Popover modal={true}>
<Popover>
<PopoverTrigger asChild>
<Button
variant="ghost"
@@ -415,10 +415,7 @@ export default function Step3StreamConfig({
</Button>
</div>
</PopoverTrigger>
<PopoverContent
className="w-[--radix-popover-trigger-width] p-2"
disablePortal
>
<PopoverContent className="w-[--radix-popover-trigger-width] p-2">
<Command>
<CommandInput
placeholder={t(
@@ -600,7 +597,7 @@ export default function Step3StreamConfig({
<Label className="text-sm font-medium text-primary-variant">
{t("cameraWizard.step3.roles")}
</Label>
<Popover modal={true}>
<Popover>
<PopoverTrigger asChild>
<Button variant="ghost" size="sm" className="h-4 w-4 p-0">
<LuInfo className="size-3" />
@@ -670,7 +667,7 @@ export default function Step3StreamConfig({
<Label className="text-sm font-medium text-primary-variant">
{t("cameraWizard.step3.featuresTitle")}
</Label>
<Popover modal={true}>
<Popover>
<PopoverTrigger asChild>
<Button variant="ghost" size="sm" className="h-4 w-4 p-0">
<LuInfo className="size-3" />
@@ -607,23 +607,38 @@ function StreamIssues({
}
}
if (stream.roles.includes("detect") && stream.resolution) {
const [width, height] = stream.resolution.split("x").map(Number);
if (!isNaN(width) && !isNaN(height) && width > 0 && height > 0) {
const minDimension = Math.min(width, height);
const maxDimension = Math.max(width, height);
if (stream.roles.includes("detect") && stream.testResult) {
const probedResolution = stream.testResult.resolution;
let probedWidth = 0;
let probedHeight = 0;
if (probedResolution) {
const [w, h] = probedResolution.split("x").map(Number);
if (!isNaN(w) && !isNaN(h)) {
probedWidth = w;
probedHeight = h;
}
}
if (probedWidth <= 0 || probedHeight <= 0) {
result.push({
type: "error",
message: t("cameraWizard.step4.issues.resolutionUnknown"),
});
} else {
const minDimension = Math.min(probedWidth, probedHeight);
const maxDimension = Math.max(probedWidth, probedHeight);
if (minDimension > 1080) {
result.push({
type: "warning",
message: t("cameraWizard.step4.issues.resolutionHigh", {
resolution: stream.resolution,
resolution: probedResolution,
}),
});
} else if (maxDimension < 640) {
result.push({
type: "error",
message: t("cameraWizard.step4.issues.resolutionLow", {
resolution: stream.resolution,
resolution: probedResolution,
}),
});
}
-2
View File
@@ -351,7 +351,6 @@ function TopicFilterButton({
return (
<DropdownMenu
modal={false}
open={open}
onOpenChange={(open) => {
if (!open) setCurrentTopics(selectedTopics);
@@ -517,7 +516,6 @@ function WsCamerasFilterButton({
return (
<DropdownMenu
modal={false}
open={open}
onOpenChange={(open) => {
if (!open) setCurrentCameras(selectedCameras);
+5 -3
View File
@@ -137,9 +137,11 @@ export function useCameraActivity(
}
}
newObjects[updatedEventIndex].label = label;
newObjects[updatedEventIndex].stationary =
updatedEvent.after.stationary;
newObjects[updatedEventIndex] = {
...newObjects[updatedEventIndex],
label,
stationary: updatedEvent.after.stationary,
};
}
}
+59 -4
View File
@@ -21,6 +21,10 @@ import {
getBeginningOfDayTimestamp,
getEndOfDayTimestamp,
} from "@/utils/dateUtil";
import {
parseRecordingReviewLink,
RECORDING_REVIEW_LINK_PARAM,
} from "@/utils/recordingReviewUrl";
import EventView from "@/views/events/EventView";
import MotionSearchView from "@/views/motion-search/MotionSearchView";
import { RecordingView } from "@/views/recording/RecordingView";
@@ -28,6 +32,7 @@ import { useFrigateReviews } from "@/api/ws";
import axios from "axios";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import useSWR from "swr";
export default function Events() {
@@ -128,6 +133,14 @@ export default function Events() {
const [notificationTab, setNotificationTab] =
useState<TimelineType>("timeline");
const getReviewDayBounds = useCallback((date: Date) => {
const now = Date.now() / 1000;
return {
after: getBeginningOfDayTimestamp(date),
before: Math.min(getEndOfDayTimestamp(date), now),
};
}, []);
useSearchEffect("tab", (tab: string) => {
if (tab === "timeline" || tab === "events" || tab === "detail") {
setNotificationTab(tab as TimelineType);
@@ -143,10 +156,7 @@ export default function Events() {
const startTime = resp.data.start_time - REVIEW_PADDING;
const date = new Date(startTime * 1000);
setReviewFilter({
after: getBeginningOfDayTimestamp(date),
before: getEndOfDayTimestamp(date),
});
setReviewFilter(getReviewDayBounds(date));
setRecording(
{
camera: resp.data.camera,
@@ -234,6 +244,51 @@ export default function Events() {
[recording, setRecording, setReviewFilter],
);
useSearchEffect(RECORDING_REVIEW_LINK_PARAM, (reviewLinkValue: string) => {
if (!config) {
return false;
}
const reviewLink = parseRecordingReviewLink(reviewLinkValue);
if (!reviewLink) {
toast.error(t("recordings.invalidSharedLink"), {
position: "top-center",
});
return true;
}
const validCamera =
config.cameras[reviewLink.camera] &&
allowedCameras.includes(reviewLink.camera);
if (!validCamera) {
toast.error(t("recordings.invalidSharedCamera"), {
position: "top-center",
});
return true;
}
setReviewFilter({
...reviewFilter,
...getReviewDayBounds(new Date(reviewLink.timestamp * 1000)),
});
setRecording(
{
camera: reviewLink.camera,
startTime: reviewLink.timestamp,
// severity not actually applicable here, but the type requires it
// this pattern is also used LiveCameraView to enter recording view
severity: "alert",
timelineType: notificationTab,
navigationSource: "shared-link",
},
true,
);
return true;
});
// review paging
const [beforeTs, setBeforeTs] = useState(Math.ceil(Date.now() / 1000));
+125 -32
View File
@@ -1,4 +1,5 @@
import { baseUrl } from "@/api/baseUrl";
import { useJobStatus } from "@/api/ws";
import {
ActiveExportJobCard,
CaseCard,
@@ -87,23 +88,45 @@ function Exports() {
// Data
const { data: cases, mutate: updateCases } = useSWR<ExportCase[]>("cases");
const { data: activeExportJobs } = useSWR<ExportJob[]>("jobs/export", {
refreshInterval: (latestJobs) => ((latestJobs ?? []).length > 0 ? 2000 : 0),
});
// Keep polling exports while there are queued/running jobs OR while any
// existing export is still marked in_progress. Without the second clause,
// a stale in_progress=true snapshot can stick if the activeExportJobs poll
// clears before the rawExports poll fires — SWR cancels the pending
// rawExports refresh and the UI freezes on spinners until a manual reload.
// The HTTP fetch hydrates the page on first paint and on focus. Once the
// WebSocket is connected, the `job_state` topic delivers progress updates
// in real time, so periodic polling here would only add noise.
const { data: pollExportJobs, mutate: updateActiveJobs } = useSWR<
ExportJob[]
>("jobs/export", { refreshInterval: 0 });
const { payload: exportJobState } = useJobStatus<{ jobs: ExportJob[] }>(
"export",
);
const wsExportJobs = useMemo<ExportJob[]>(
() => exportJobState?.results?.jobs ?? [],
[exportJobState],
);
// Merge: a job present in the WS payload is authoritative (it has the
// freshest progress); the SWR snapshot fills in jobs that haven't yet
// arrived over the socket (e.g. before the first WS message after a
// page load). Once we've seen at least one WS message, we trust the WS
// payload as the complete active set.
const hasWsState = exportJobState !== null;
const activeExportJobs = useMemo<ExportJob[]>(() => {
if (hasWsState) {
return wsExportJobs;
}
return pollExportJobs ?? [];
}, [hasWsState, wsExportJobs, pollExportJobs]);
// Keep polling exports while any existing export is still marked
// in_progress so the UI flips from spinner to playable card without a
// manual reload. Once active jobs disappear from the WS feed we also
// mutate() below to fetch newly-completed exports immediately.
const { data: rawExports, mutate: updateExports } = useSWR<Export[]>(
exportSearchParams && Object.keys(exportSearchParams).length > 0
? ["exports", exportSearchParams]
: "exports",
{
refreshInterval: (latestExports) => {
if ((activeExportJobs?.length ?? 0) > 0) {
return 2000;
}
if ((latestExports ?? []).some((exp) => exp.in_progress)) {
return 2000;
}
@@ -112,22 +135,40 @@ function Exports() {
},
);
// When one or more active jobs disappear from the WS feed, refresh the
// exports list so newly-finished items appear without waiting for focus-
// based SWR revalidation. Clear the HTTP jobs snapshot once the live set is
// empty so a stale poll result does not resurrect completed jobs.
const previousActiveJobIdsRef = useRef<Set<string>>(new Set());
useEffect(() => {
const previousIds = previousActiveJobIdsRef.current;
const currentIds = new Set(activeExportJobs.map((job) => job.id));
const removedJob = Array.from(previousIds).some(
(id) => !currentIds.has(id),
);
if (removedJob) {
updateExports();
updateCases();
}
if (previousIds.size > 0 && currentIds.size === 0) {
updateActiveJobs([], false);
}
previousActiveJobIdsRef.current = currentIds;
}, [activeExportJobs, updateExports, updateCases, updateActiveJobs]);
const visibleActiveJobs = useMemo<ExportJob[]>(() => {
const existingExportIds = new Set((rawExports ?? []).map((exp) => exp.id));
const filteredCameras = exportFilter?.cameras;
return (activeExportJobs ?? []).filter((job) => {
if (existingExportIds.has(job.id)) {
return false;
}
if (filteredCameras && filteredCameras.length > 0) {
return filteredCameras.includes(job.camera);
}
return true;
});
}, [activeExportJobs, exportFilter?.cameras, rawExports]);
}, [activeExportJobs, exportFilter?.cameras]);
const activeJobsByCase = useMemo<{ [caseId: string]: ExportJob[] }>(() => {
const grouped: { [caseId: string]: ExportJob[] } = {};
@@ -144,9 +185,26 @@ function Exports() {
return grouped;
}, [visibleActiveJobs]);
// The backend inserts the Export row with in_progress=True before the
// FFmpeg encode kicks off, so the same id is briefly present in BOTH
// rawExports and the active job list. The ActiveExportJobCard renders
// step + percent; the ExportCard would render a binary spinner. To
// avoid that downgrade, hide the rawExport entry while there's a
// matching active job — once the job leaves the active list the
// exports SWR refresh kicks in and the regular card takes over.
const activeJobIds = useMemo<Set<string>>(
() => new Set(visibleActiveJobs.map((job) => job.id)),
[visibleActiveJobs],
);
const visibleExports = useMemo<Export[]>(
() => (rawExports ?? []).filter((exp) => !activeJobIds.has(exp.id)),
[activeJobIds, rawExports],
);
const exportsByCase = useMemo<{ [caseId: string]: Export[] }>(() => {
const grouped: { [caseId: string]: Export[] } = {};
(rawExports ?? []).forEach((exp) => {
visibleExports.forEach((exp) => {
const caseId = exp.export_case ?? exp.export_case_id ?? "none";
if (!grouped[caseId]) {
grouped[caseId] = [];
@@ -155,7 +213,7 @@ function Exports() {
grouped[caseId].push(exp);
});
return grouped;
}, [rawExports]);
}, [visibleExports]);
const filteredCases = useMemo<ExportCase[]>(() => {
if (!cases) return [];
@@ -184,6 +242,34 @@ function Exports() {
updateCases();
}, [updateExports, updateCases]);
// Deletes one or more exports and keeps the UI in sync. SWR's default
// mutate() keeps the stale list visible until the revalidation GET
// returns, which can be seconds for large batches — long enough for
// users to click on a card whose underlying file is already gone.
// Strip the deleted ids from the cache up front, then fire the POST,
// then revalidate to reconcile with server truth.
const deleteExports = useCallback(
async (ids: string[]): Promise<void> => {
const idSet = new Set(ids);
const removeDeleted = (current: Export[] | undefined) =>
current ? current.filter((exp) => !idSet.has(exp.id)) : current;
await updateExports(removeDeleted, { revalidate: false });
try {
await axios.post("exports/delete", { ids });
await updateExports();
await updateCases();
} catch (err) {
// On failure, pull fresh state from the server so any items that
// weren't actually deleted reappear in the UI.
await updateExports();
throw err;
}
},
[updateExports, updateCases],
);
// Search
const [search, setSearch] = useState("");
@@ -208,7 +294,9 @@ function Exports() {
return false;
}
setSelected(rawExports.find((exp) => exp.id == id));
// Use visibleExports so deep links to a still-encoding id don't try
// to open a player against a half-written video file.
setSelected(visibleExports.find((exp) => exp.id == id));
return true;
});
@@ -260,7 +348,7 @@ function Exports() {
const currentExports = selectedCaseId
? exportsByCase[selectedCaseId] || []
: exports;
const visibleExports = currentExports.filter((e) => {
const selectable = currentExports.filter((e) => {
if (e.in_progress) return false;
if (!search) return true;
return e.name
@@ -268,8 +356,8 @@ function Exports() {
.replaceAll("_", " ")
.includes(search.toLowerCase());
});
if (selectedExports.length < visibleExports.length) {
setSelectedExports(visibleExports);
if (selectedExports.length < selectable.length) {
setSelectedExports(selectable);
} else {
setSelectedExports([]);
}
@@ -293,15 +381,19 @@ function Exports() {
return;
}
axios
.post("exports/delete", { ids: [deleteClip.file] })
.then((response) => {
if (response.status == 200) {
setDeleteClip(undefined);
mutate();
}
deleteExports([deleteClip.file])
.then(() => setDeleteClip(undefined))
.catch((error) => {
const errorMessage =
error?.response?.data?.message ||
error?.response?.data?.detail ||
"Unknown error";
toast.error(
t("bulkToast.error.deleteFailed", { errorMessage: errorMessage }),
{ position: "top-center" },
);
});
}, [deleteClip, mutate]);
}, [deleteClip, deleteExports, t]);
const onHandleRename = useCallback(
(id: string, update: string) => {
@@ -629,6 +721,7 @@ function Exports() {
cases={cases}
currentCaseId={selectedCaseId}
mutate={mutate}
deleteExports={deleteExports}
/>
) : (
<>
@@ -893,7 +986,7 @@ function AllExportsView({
))}
{filteredExports.map((item) => (
<ExportCard
key={item.name}
key={item.id}
className=""
exportedRecording={item}
isSelected={selectedExports.some((e) => e.id === item.id)}
+1 -1
View File
@@ -594,7 +594,7 @@ function LibrarySelector({
forbiddenErrorMessage={t("description.nameCannotContainHash")}
/>
<DropdownMenu modal={false}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button className="flex justify-between smart-capitalize">
{pageTitle}
+2 -3
View File
@@ -1435,7 +1435,7 @@ export default function Settings() {
/>
)}
{showUnsavedDot && (
<span className="inline-block size-2 rounded-full bg-danger" />
<span className="inline-block size-2 rounded-full bg-unsaved" />
)}
</div>
)}
@@ -1516,7 +1516,7 @@ export default function Settings() {
<div className="sticky bottom-0 z-50 mt-2 bg-background p-4">
<div className="flex flex-col items-center gap-2">
<div className="flex items-center gap-2">
<span className="text-sm text-danger">
<span className="text-sm text-unsaved">
{t("unsavedChanges", {
ns: "views/settings",
defaultValue: "You have unsaved changes",
@@ -2018,7 +2018,6 @@ function CameraSelectButton({
return (
<DropdownMenu
modal={false}
open={open}
onOpenChange={(open: boolean) => {
if (!open) {
+10
View File
@@ -59,6 +59,14 @@ export type StartExportResponse = {
status?: string | null;
};
export type ExportJobStep =
| "queued"
| "preparing"
| "copying"
| "encoding"
| "encoding_retry"
| "finalizing";
export type ExportJob = {
id: string;
job_type: string;
@@ -77,6 +85,8 @@ export type ExportJob = {
video_path?: string;
thumb_path?: string;
} | null;
current_step?: ExportJobStep;
progress_percent?: number;
};
export type CameraActivitySegment = {
+1
View File
@@ -40,6 +40,7 @@ export type RecordingStartingPoint = {
startTime: number;
severity: ReviewSeverity;
timelineType?: TimelineType;
navigationSource?: "shared-link";
};
export type RecordingPlayerError = "stalled" | "startup";
+2 -2
View File
@@ -146,11 +146,11 @@ export type MediaSyncResults = {
totals: MediaSyncTotals;
};
export type Job = {
export type Job<TResults = unknown> = {
id: string;
job_type: string;
status: string;
results?: MediaSyncResults;
results?: TResults;
start_time?: number;
end_time?: number;
error_message?: string;
+10 -10
View File
@@ -79,11 +79,11 @@ const PROFILE_COLORS: ProfileColor[] = [
bgMuted: "bg-green-400/20",
},
{
bg: "bg-amber-400",
text: "text-amber-400",
dot: "bg-amber-400",
border: "border-amber-400",
bgMuted: "bg-amber-400/20",
bg: "bg-fuchsia-500",
text: "text-fuchsia-500",
dot: "bg-fuchsia-500",
border: "border-fuchsia-500",
bgMuted: "bg-fuchsia-500/20",
},
{
bg: "bg-slate-400",
@@ -93,11 +93,11 @@ const PROFILE_COLORS: ProfileColor[] = [
bgMuted: "bg-slate-400/20",
},
{
bg: "bg-orange-300",
text: "text-orange-300",
dot: "bg-orange-300",
border: "border-orange-300",
bgMuted: "bg-orange-300/20",
bg: "bg-stone-500",
text: "text-stone-500",
dot: "bg-stone-500",
border: "border-stone-500",
bgMuted: "bg-stone-500/20",
},
{
bg: "bg-blue-300",

Some files were not shown because too many files have changed in this diff Show More