Merge branch 'dev' into feature/share-review-timestamp

This commit is contained in:
Otto
2026-04-17 17:35:28 +03:00
committed by GitHub
88 changed files with 9947 additions and 1060 deletions
+116
View File
@@ -0,0 +1,116 @@
/**
* Global allowlist of regex patterns that the error collector ignores.
*
* Each entry MUST include a comment explaining what it silences and why.
* The allowlist is filtered at collection time, so failure messages list
* only unfiltered errors.
*
* Per-spec additions go through the `expectedErrors` test fixture parameter
* (see error-collector.ts), not by editing this file. That keeps allowlist
* drift visible per-PR rather than buried in shared infrastructure.
*
* NOTE ON CONSOLE vs REQUEST ERRORS:
* When a network request returns a 5xx response, the browser emits two
* events that the error collector captures:
* [request] "500 Internal Server Error <url>" — from onResponse (URL included)
* [console] "Failed to load resource: ..." — from onConsole (URL NOT included)
*
* The request-level message includes the URL, so those patterns are specific.
* The console-level message text (from ConsoleMessage.text()) does NOT include
* the URL — the URL is stored separately in e.url. Therefore the console
* pattern for HTTP 500s cannot be URL-discriminated, and a single pattern
* covers all such browser echoes. This is safe because every such console
* error is already caught (and specifically matched) by its paired [request]
* entry below.
*/
export const GLOBAL_ALLOWLIST: RegExp[] = [
// -------------------------------------------------------------------------
// Browser echo of HTTP 5xx responses (console mirror of [request] events).
//
// Whenever the browser receives a 5xx response it emits a console error:
// "Failed to load resource: the server responded with a status of 500
// (Internal Server Error)"
// The URL is NOT part of ConsoleMessage.text() — it is stored separately.
// Every console error of this form is therefore paired with a specific
// [request] 500 entry below that names the exact endpoint. Allowlisting
// this pattern here silences the browser echo; the request-level entries
// enforce specificity.
// -------------------------------------------------------------------------
/Failed to load resource: the server responded with a status of 500/,
// -------------------------------------------------------------------------
// Mock infrastructure gaps — API endpoints not yet covered by ApiMocker.
//
// These produce 500s because Vite's preview server has no handler for them.
// Each is a TODO(real-bug): the mock should be extended so these endpoints
// return sensible fixture data in tests.
//
// Only [request] patterns are listed here; the paired [console] mirror is
// covered by the "Failed to load resource" entry above.
// -------------------------------------------------------------------------
// TODO(real-bug): ApiMocker registers "**/api/reviews**" (plural) but the
// app fetches /api/review (singular) for the review list and timeline.
// Affects: review.spec.ts, navigation.spec.ts, live.spec.ts, auth.spec.ts.
// Fix: add route handlers for /api/review and /api/review/** in api-mocker.ts.
/500 Internal Server Error.*\/api\/review(\?|\/|$)/,
// TODO(real-bug): /api/stats/history is not mocked; the system page fetches
// it for the detector/process history charts.
// Fix: add route handler for /api/stats/history in api-mocker.ts.
/500 Internal Server Error.*\/api\/stats\/history/,
// TODO(real-bug): /api/event_ids is not mocked; the explore/search page
// fetches it to resolve event IDs for display.
// Fix: add route handler for /api/event_ids in api-mocker.ts.
/500 Internal Server Error.*\/api\/event_ids/,
// TODO(real-bug): /api/sub_labels?split_joined=1 returns 500; the mock
// registers "**/api/sub_labels" which may not match when a query string is
// present, or route registration order causes the catch-all to win first.
// Fix: change the mock route to "**/api/sub_labels**" in api-mocker.ts.
/500 Internal Server Error.*\/api\/sub_labels/,
// TODO(real-bug): MediaMocker handles /api/*/latest.jpg but the app also
// requests /api/*/latest.webp (webp format) for camera snapshots.
// Affects: live.spec.ts, review.spec.ts, auth.spec.ts, navigation.spec.ts.
// Fix: add route handler for /api/*/latest.webp in MediaMocker.install().
/500 Internal Server Error.*\/api\/[^/]+\/latest\.webp/,
/failed: net::ERR_ABORTED.*\/api\/[^/]+\/latest\.webp/,
// -------------------------------------------------------------------------
// Mock infrastructure gap — WebSocket streams.
//
// Playwright's page.route() does not intercept WebSocket connections.
// The jsmpeg live-stream WS connections to /live/jsmpeg/* always fail
// with a 500 handshake error because the Vite preview server has no WS
// handler. TODO(real-bug): add WsMocker support for jsmpeg WebSocket
// connections, or suppress the connection attempt in the test environment.
// Affects: live.spec.ts (single camera view), auth.spec.ts.
// -------------------------------------------------------------------------
/WebSocket connection to '.*\/live\/jsmpeg\/.*' failed/,
// -------------------------------------------------------------------------
// Benign — lazy-loaded chunk aborts during navigation.
//
// When a test navigates away from a page while the browser is still
// fetching lazily-split JS/CSS asset chunks, the in-flight fetch is
// cancelled (net::ERR_ABORTED). This is normal browser behaviour on
// navigation and does not indicate a real error; the assets load fine
// on a stable connection.
// -------------------------------------------------------------------------
/failed: net::ERR_ABORTED.*\/assets\//,
// -------------------------------------------------------------------------
// Real app bug — Radix UI DialogContent missing accessible title.
//
// TODO(real-bug): A dialog somewhere in the app renders <DialogContent>
// without a <DialogTitle>, violating Radix UI's accessibility contract.
// The warning originates from the bundled main-*.js. Investigate which
// dialog component is missing the title and add a VisuallyHidden DialogTitle.
// Likely candidate: face-library or search-detail dialog in explore page.
// See: https://radix-ui.com/primitives/docs/components/dialog
// -------------------------------------------------------------------------
/`DialogContent` requires a `DialogTitle`/,
];
+122
View File
@@ -0,0 +1,122 @@
/**
* Collects console errors, page errors, and failed network requests
* during a Playwright test, with regex-based allowlist filtering.
*
* Usage:
* const collector = installErrorCollector(page, [...GLOBAL_ALLOWLIST]);
* // ... run test ...
* collector.assertClean(); // throws if any non-allowlisted error
*
* The collector is wired into the `frigateApp` fixture so every test
* gets it for free. Tests that intentionally trigger an error pass
* additional regexes via the `expectedErrors` fixture parameter.
*/
import type { Page, Request, Response, ConsoleMessage } from "@playwright/test";
export type CollectedError = {
kind: "console" | "pageerror" | "request";
message: string;
url?: string;
stack?: string;
};
export type ErrorCollector = {
errors: CollectedError[];
assertClean(): void;
};
function isAllowlisted(message: string, allowlist: RegExp[]): boolean {
return allowlist.some((pattern) => pattern.test(message));
}
function firstStackFrame(stack: string | undefined): string | undefined {
if (!stack) return undefined;
const lines = stack
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
// Skip the error message line (line 0); return the first "at ..." frame
return lines.find((l) => l.startsWith("at "));
}
function isSameOrigin(url: string, baseURL: string | undefined): boolean {
if (!baseURL) return true;
try {
return new URL(url).origin === new URL(baseURL).origin;
} catch {
return false;
}
}
export function installErrorCollector(
page: Page,
allowlist: RegExp[],
): ErrorCollector {
const errors: CollectedError[] = [];
const baseURL = (
page.context() as unknown as { _options?: { baseURL?: string } }
)._options?.baseURL;
const onConsole = (msg: ConsoleMessage) => {
if (msg.type() !== "error") return;
const text = msg.text();
if (isAllowlisted(text, allowlist)) return;
errors.push({
kind: "console",
message: text,
url: msg.location().url,
});
};
const onPageError = (err: Error) => {
const text = err.message;
if (isAllowlisted(text, allowlist)) return;
errors.push({
kind: "pageerror",
message: text,
stack: firstStackFrame(err.stack),
});
};
const onResponse = (response: Response) => {
const status = response.status();
if (status < 500) return;
const url = response.url();
if (!isSameOrigin(url, baseURL)) return;
const text = `${status} ${response.statusText()} ${url}`;
if (isAllowlisted(text, allowlist)) return;
errors.push({ kind: "request", message: text, url });
};
const onRequestFailed = (request: Request) => {
const url = request.url();
if (!isSameOrigin(url, baseURL)) return;
const failure = request.failure();
const text = `failed: ${failure?.errorText ?? "unknown"} ${url}`;
if (isAllowlisted(text, allowlist)) return;
errors.push({ kind: "request", message: text, url });
};
page.on("console", onConsole);
page.on("pageerror", onPageError);
page.on("response", onResponse);
page.on("requestfailed", onRequestFailed);
return {
errors,
assertClean() {
if (errors.length === 0) return;
const formatted = errors
.map((e, i) => {
const stack = e.stack ? `\n ${e.stack}` : "";
const url = e.url && e.url !== e.message ? ` (${e.url})` : "";
return ` ${i + 1}. [${e.kind}] ${e.message}${url}${stack}`;
})
.join("\n");
throw new Error(
`Page emitted ${errors.length} unexpected error${errors.length === 1 ? "" : "s"}:\n${formatted}`,
);
},
};
}
+41 -1
View File
@@ -6,6 +6,11 @@
* @playwright/test directly. The `frigateApp` fixture provides a
* fully mocked Frigate frontend ready for interaction.
*
* The fixture also installs the error collector (see error-collector.ts).
* Any console error, page error, or same-origin failed request that is
* not on the global allowlist or the test's `expectedErrors` list will
* fail the test in the fixture's teardown.
*
* CRITICAL: All route/WS handlers are registered before page.goto()
* to prevent AuthProvider from redirecting to login.html.
*/
@@ -17,6 +22,8 @@ import {
type ApiMockOverrides,
} from "../helpers/api-mocker";
import { WsMocker } from "../helpers/ws-mocker";
import { installErrorCollector, type ErrorCollector } from "./error-collector";
import { GLOBAL_ALLOWLIST } from "./error-allowlist";
export class FrigateApp {
public api: ApiMocker;
@@ -67,10 +74,43 @@ export class FrigateApp {
type FrigateFixtures = {
frigateApp: FrigateApp;
/**
* Per-test additional allowlist regex patterns. Tests that intentionally
* trigger errors (e.g. error-state tests that hit a mocked 500) declare
* their expected errors here so the collector ignores them.
*
* Default is `[]` — most tests should not need this.
*/
expectedErrors: RegExp[];
errorCollector: ErrorCollector;
};
export const test = base.extend<FrigateFixtures>({
frigateApp: async ({ page }, use, testInfo) => {
expectedErrors: [[], { option: true }],
errorCollector: async ({ page, expectedErrors }, use, testInfo) => {
const collector = installErrorCollector(page, [
...GLOBAL_ALLOWLIST,
...expectedErrors,
]);
await use(collector);
if (process.env.E2E_STRICT_ERRORS === "1") {
collector.assertClean();
} else if (collector.errors.length > 0) {
// Soft mode: attach errors to the test report so they're visible
// without failing the run.
await testInfo.attach("collected-errors.txt", {
body: collector.errors
.map((e) => `[${e.kind}] ${e.message}${e.url ? ` (${e.url})` : ""}`)
.join("\n"),
contentType: "text/plain",
});
}
},
frigateApp: async ({ page, errorCollector }, use, testInfo) => {
// Reference the collector so its `use()` runs and teardown fires
void errorCollector;
const app = new FrigateApp(page, testInfo.project.name);
await app.installDefaults();
await use(app);
+20 -8
View File
@@ -82,14 +82,26 @@ export class ApiMocker {
route.fulfill({ json: stats }),
);
// Reviews
await this.page.route("**/api/reviews**", (route) => {
const url = route.request().url();
if (url.includes("summary")) {
return route.fulfill({ json: reviewSummary });
}
return route.fulfill({ json: reviews });
});
// Reviews. The real backend exposes /review (singular) for the main
// list and /review/summary for the summary — the previous plural glob
// (**/api/reviews**) never matched either endpoint, so review-dependent
// tests silently ran without data. The POST mutations at /reviews/viewed
// and /reviews/delete (plural) still fall through to the generic
// mutation catch-all further down the file.
await this.page.route(/\/api\/review\/summary/, (route) =>
route.fulfill({ json: reviewSummary }),
);
await this.page.route(/\/api\/review(\?|$)/, (route) =>
route.fulfill({ json: reviews }),
);
// Export jobs. The Exports page polls this every 2s while any export
// is in_progress; without a mock route it falls through to the preview
// server which returns 500 and makes the page flap between loading and
// rendered state, breaking tests that navigate to /export.
await this.page.route("**/api/jobs/export", (route) =>
route.fulfill({ json: [] }),
);
// Recordings summary
await this.page.route("**/api/recordings/summary**", (route) =>
+56
View File
@@ -0,0 +1,56 @@
/**
* Per-test mock overrides for driving empty / loading / error states.
*
* Playwright route handlers are LIFO: the most recently registered handler
* matching a URL takes precedence. The frigateApp fixture installs default
* mocks before the test body runs, so these helpers — called inside the
* test body — register AFTER the defaults and therefore win.
*
* Always call these BEFORE the navigation that triggers the request.
*
* Example:
* await mockEmpty(page, "**\/api\/exports**");
* await frigateApp.goto("/export");
* // Page now renders the empty state
*/
import type { Page } from "@playwright/test";
/** Return an empty array for the matched endpoint. */
export async function mockEmpty(
page: Page,
urlPattern: string | RegExp,
): Promise<void> {
await page.route(urlPattern, (route) => route.fulfill({ json: [] }));
}
/** Return an HTTP error for the matched endpoint. Default status 500. */
export async function mockError(
page: Page,
urlPattern: string | RegExp,
status = 500,
): Promise<void> {
await page.route(urlPattern, (route) =>
route.fulfill({
status,
json: { success: false, message: "Mocked error" },
}),
);
}
/**
* Delay the response by `ms` milliseconds before fulfilling with the
* provided body. Use to assert loading-state UI is visible during the
* delay window.
*/
export async function mockDelay(
page: Page,
urlPattern: string | RegExp,
ms: number,
body: unknown = [],
): Promise<void> {
await page.route(urlPattern, async (route) => {
await new Promise((resolve) => setTimeout(resolve, ms));
await route.fulfill({ json: body });
});
}
+53
View File
@@ -79,4 +79,57 @@ export class BasePage {
async waitForPageLoad() {
await this.page.waitForSelector("#pageRoot", { timeout: 10_000 });
}
/**
* Open the mobile-only export pane / sheet that slides up from the
* bottom on the export page. No-op on desktop. Returns the pane locator
* so the caller can assert against its contents.
*/
async openMobilePane(): Promise<Locator> {
if (this.isDesktop) {
// Return the desktop equivalent (the main content area itself)
return this.pageRoot;
}
// Look for any element that opens a sheet/dialog on tap.
// Specific views override this with their own selector.
const pane = this.page.locator('[role="dialog"]').first();
return pane;
}
/**
* Open a side drawer (e.g. mobile filter drawer). View-specific page
* objects should override this with their actual trigger selector.
* The default implementation looks for a button labelled "Open menu"
* or "Filters" and clicks it, then returns the drawer locator.
*/
async openDrawer(): Promise<Locator> {
if (this.isDesktop) {
return this.pageRoot;
}
const trigger = this.page
.getByRole("button", { name: /menu|filter/i })
.first();
if (await trigger.count()) {
await trigger.click();
}
return this.page.locator('[role="dialog"], [data-state="open"]').first();
}
/**
* Open a bottom sheet (vaul). View-specific page objects should
* override this with their actual trigger selector.
*/
async openBottomSheet(): Promise<Locator> {
if (this.isDesktop) {
return this.pageRoot;
}
return this.page.locator("[vaul-drawer]").first();
}
/** Close any currently-open mobile overlay (drawer, sheet, dialog). */
async closeMobileOverlay(): Promise<void> {
if (this.isDesktop) return;
// Press Escape — Radix dialogs and vaul both close on Escape
await this.page.keyboard.press("Escape");
}
}
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env node
/**
* Lint script for e2e specs. Bans lenient test patterns and requires
* a @mobile-tagged test in every spec under specs/ (excluding _meta/).
*
* Banned patterns:
* - page.waitForTimeout( — use expect().toPass() or waitFor instead
* - if (await ... .isVisible()) — assertions must be unconditional
* - if ((await ... .count()) > 0) — same as above
* - expect(... .length).toBeGreaterThan(0) on textContent results
*
* Escape hatch: append `// e2e-lint-allow` on any line to silence the
* check for that line. Use sparingly and explain why in a comment above.
*
* @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";
import { join, relative, resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
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",
regex: /\bwaitForTimeout\s*\(/,
advice:
"Use expect.poll(), expect(...).toPass(), or waitFor() with a real condition.",
},
{
name: "conditional isVisible() assertion",
regex: /\bif\s*\(\s*await\s+[^)]*\.isVisible\s*\(/,
advice:
"Assertions must be unconditional. Use expect(...).toBeVisible() instead.",
},
{
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).",
},
{
name: "vacuous textContent length assertion",
regex: /expect\([^)]*\.length\)\.toBeGreaterThan\(0\)/,
advice:
"Assert specific content, not that some text exists.",
},
];
function walk(dir) {
const entries = readdirSync(dir);
const out = [];
for (const entry of entries) {
const full = join(dir, entry);
const st = statSync(full);
if (st.isDirectory()) {
out.push(...walk(full));
} else if (entry.endsWith(".spec.ts")) {
out.push(full);
}
}
return out;
}
function lintFile(file) {
const basename = file.split("/").pop();
if (PENDING_REWRITE.has(basename)) return [];
if (file.includes("/specs/settings/")) return [];
const errors = [];
const text = readFileSync(file, "utf8");
const lines = text.split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line.includes("e2e-lint-allow")) continue;
for (const pat of BANNED_PATTERNS) {
if (pat.regex.test(line)) {
errors.push({
file,
line: i + 1,
col: 1,
rule: pat.name,
message: `${pat.name}: ${pat.advice}`,
source: line.trim(),
});
}
}
}
// @mobile rule: skip _meta
const isMeta = file.startsWith(META_PREFIX);
if (!isMeta) {
if (!/@mobile\b/.test(text)) {
errors.push({
file,
line: 1,
col: 1,
rule: "missing @mobile test",
message:
'Spec must contain at least one test or describe tagged with "@mobile".',
source: "",
});
}
}
return errors;
}
function main() {
const files = walk(SPECS_DIR);
const allErrors = [];
for (const f of files) {
allErrors.push(...lintFile(f));
}
if (allErrors.length === 0) {
console.log(`e2e:lint: ${files.length} spec files OK`);
process.exit(0);
}
for (const err of allErrors) {
const rel = relative(process.cwd(), err.file);
console.error(`${rel}:${err.line}:${err.col} ${err.rule}`);
console.error(` ${err.message}`);
if (err.source) console.error(` > ${err.source}`);
}
console.error(
`\ne2e:lint: ${allErrors.length} error${allErrors.length === 1 ? "" : "s"} in ${files.length} files`,
);
process.exit(1);
}
main();
+112
View File
@@ -0,0 +1,112 @@
/**
* Self-tests for the error collector fixture itself.
*
* These guard against future regressions in the safety net. Each test
* deliberately triggers (or avoids triggering) an error to verify the
* collector behaves correctly. Tests that expect to fail use the
* `expectedErrors` fixture parameter to allowlist their own errors.
*/
import { test, expect } from "../../fixtures/frigate-test";
// test.use applies to a whole describe block in Playwright, so each test
// that needs a custom allowlist gets its own describe.
test.describe("Error Collector — clean @meta", () => {
test("clean page passes", async ({ frigateApp }) => {
await frigateApp.goto("/");
// No errors triggered. The fixture teardown should not throw.
});
});
test.describe("Error Collector — unallowlisted console error fails @meta", () => {
test("console.error fails the test when not allowlisted", async ({
page,
frigateApp,
}) => {
test.skip(
process.env.E2E_STRICT_ERRORS !== "1",
"Requires E2E_STRICT_ERRORS=1 to assert failure",
);
test.fail(); // We expect the fixture teardown to throw
await frigateApp.goto("/");
await page.evaluate(() => {
// eslint-disable-next-line no-console
console.error("UNEXPECTED_DELIBERATE_TEST_ERROR_xyz123");
});
});
});
test.describe("Error Collector — allowlisted console error passes @meta", () => {
test.use({ expectedErrors: [/ALLOWED_DELIBERATE_TEST_ERROR_xyz123/] });
test("console.error is silenced when allowlisted via expectedErrors", async ({
page,
frigateApp,
}) => {
await frigateApp.goto("/");
await page.evaluate(() => {
// eslint-disable-next-line no-console
console.error("ALLOWED_DELIBERATE_TEST_ERROR_xyz123");
});
});
});
test.describe("Error Collector — uncaught pageerror fails @meta", () => {
test("uncaught pageerror fails the test", async ({ page, frigateApp }) => {
test.skip(
process.env.E2E_STRICT_ERRORS !== "1",
"Requires E2E_STRICT_ERRORS=1 to assert failure",
);
test.fail();
await frigateApp.goto("/");
await page.evaluate(() => {
setTimeout(() => {
throw new Error("UNCAUGHT_DELIBERATE_TEST_ERROR_xyz789");
}, 0);
});
// Wait a frame to let the throw propagate before fixture teardown.
// The marker below silences the e2e:lint banned-pattern check on this line.
await page.waitForTimeout(100); // e2e-lint-allow: deliberate; need to await async throw
});
});
test.describe("Error Collector — 5xx fails @meta", () => {
test("same-origin 5xx response fails the test", async ({
page,
frigateApp,
}) => {
test.skip(
process.env.E2E_STRICT_ERRORS !== "1",
"Requires E2E_STRICT_ERRORS=1 to assert failure",
);
test.fail();
await page.route("**/api/version", (route) =>
route.fulfill({ status: 500, body: "boom" }),
);
await frigateApp.goto("/");
await page.evaluate(() => fetch("/api/version").catch(() => {}));
// Give the response listener a microtask to fire
await expect.poll(async () => true).toBe(true);
});
});
test.describe("Error Collector — allowlisted 5xx passes @meta", () => {
// Use a single alternation regex so test.use() receives a 1-element array.
// Playwright's isFixtureTuple() treats any [value, object] pair as a fixture
// tuple, so a 2-element array whose second item is a RegExp would be
// misinterpreted as [defaultValue, options]. Both the request collector
// error ("500 … /api/version") and the browser console error
// ("Failed to load resource … 500") are matched by the alternation below.
test.use({
expectedErrors: [/500.*\/api\/version|Failed to load resource.*500/],
});
test("allowlisted 5xx passes", async ({ page, frigateApp }) => {
await page.route("**/api/version", (route) =>
route.fulfill({ status: 500, body: "boom" }),
);
await frigateApp.goto("/");
await page.evaluate(() => fetch("/api/version").catch(() => {}));
});
});
@@ -0,0 +1,73 @@
/**
* Self-tests for the mock override helpers. Verifies each helper
* intercepts the matched URL and returns the expected payload/status.
*/
import { test, expect } from "../../fixtures/frigate-test";
import { mockEmpty, mockError, mockDelay } from "../../helpers/mock-overrides";
test.describe("Mock Overrides — empty @meta", () => {
test("mockEmpty returns []", async ({ page, frigateApp }) => {
await mockEmpty(page, "**/api/__meta_test__");
await frigateApp.goto("/");
const result = await page.evaluate(async () => {
const r = await fetch("/api/__meta_test__");
return { status: r.status, body: await r.json() };
});
expect(result.status).toBe(200);
expect(result.body).toEqual([]);
});
});
test.describe("Mock Overrides — error default @meta", () => {
// Match both the collected request error and the browser's console echo.
// Using a single alternation regex avoids Playwright's isFixtureTuple
// collision with multi-element RegExp arrays.
test.use({
expectedErrors: [/500.*__meta_test__|Failed to load resource.*500/],
});
test("mockError returns 500 by default", async ({ page, frigateApp }) => {
await mockError(page, "**/api/__meta_test__");
await frigateApp.goto("/");
const status = await page.evaluate(async () => {
const r = await fetch("/api/__meta_test__");
return r.status;
});
expect(status).toBe(500);
});
});
test.describe("Mock Overrides — error custom status @meta", () => {
// The browser emits a "Failed to load resource" console.error for 404s,
// which the error collector catches even though 404 is not a 5xx.
test.use({
expectedErrors: [/Failed to load resource.*404|404.*__meta_test_404__/],
});
test("mockError accepts a custom status", async ({ page, frigateApp }) => {
await mockError(page, "**/api/__meta_test_404__", 404);
await frigateApp.goto("/");
const status = await page.evaluate(async () => {
const r = await fetch("/api/__meta_test_404__");
return r.status;
});
expect(status).toBe(404);
});
});
test.describe("Mock Overrides — delay @meta", () => {
test("mockDelay delays response by the requested ms", async ({
page,
frigateApp,
}) => {
await mockDelay(page, "**/api/__meta_test_delay__", 300, ["delayed"]);
await frigateApp.goto("/");
const elapsed = await page.evaluate(async () => {
const start = performance.now();
await fetch("/api/__meta_test_delay__");
return performance.now() - start;
});
expect(elapsed).toBeGreaterThanOrEqual(250);
});
});
+710 -50
View File
@@ -1,74 +1,734 @@
/**
* Export page tests -- HIGH tier.
*
* Tests export card rendering with mock data, search filtering,
* and delete confirmation dialog.
*/
import { test, expect } from "../fixtures/frigate-test";
test.describe("Export Page - Cards @high", () => {
test("export page renders export cards from mock data", async ({
test.describe("Export Page - Overview @high", () => {
test("renders uncategorized exports and case cards from mock data", async ({
frigateApp,
}) => {
await frigateApp.goto("/export");
await frigateApp.page.waitForTimeout(2000);
// Should show export names from our mock data
await expect(
frigateApp.page.getByText("Front Door - Person Alert"),
).toBeVisible({ timeout: 10_000 });
).toBeVisible();
await expect(
frigateApp.page.getByText("Backyard - Car Detection"),
frigateApp.page.getByText("Garage - In Progress"),
).toBeVisible();
await expect(
frigateApp.page.getByText("Package Theft Investigation"),
).toBeVisible();
});
test("export page shows in-progress indicator", async ({ frigateApp }) => {
test("search filters uncategorized exports", async ({ frigateApp }) => {
await frigateApp.goto("/export");
await frigateApp.page.waitForTimeout(2000);
// "Garage - In Progress" export should be visible
await expect(frigateApp.page.getByText("Garage - In Progress")).toBeVisible(
{ timeout: 10_000 },
);
const searchInput = frigateApp.page.getByPlaceholder(/search/i).first();
await searchInput.fill("Front Door");
await expect(
frigateApp.page.getByText("Front Door - Person Alert"),
).toBeVisible();
await expect(
frigateApp.page.getByText("Backyard - Car Detection"),
).toBeHidden();
await expect(
frigateApp.page.getByText("Garage - In Progress"),
).toBeHidden();
});
test("export page shows case grouping", async ({ frigateApp }) => {
test("new case button opens the create case dialog", async ({
frigateApp,
}) => {
await frigateApp.goto("/export");
await frigateApp.page.waitForTimeout(3000);
// Cases may render differently depending on API response shape
const pageText = await frigateApp.page.textContent("#pageRoot");
expect(pageText?.length).toBeGreaterThan(0);
await frigateApp.page.getByRole("button", { name: "New Case" }).click();
await expect(
frigateApp.page.getByRole("dialog").filter({ hasText: "Create Case" }),
).toBeVisible();
await expect(frigateApp.page.getByPlaceholder("Case name")).toBeVisible();
});
});
test.describe("Export Page - Search @high", () => {
test("search input filters export list", async ({ frigateApp }) => {
test.describe("Export Page - Case Detail @high", () => {
test("opening a case shows its detail view and associated export", async ({
frigateApp,
}) => {
await frigateApp.goto("/export");
await frigateApp.page.waitForTimeout(2000);
const searchInput = frigateApp.page.locator(
'#pageRoot input[type="text"], #pageRoot input',
await frigateApp.page
.getByText("Package Theft Investigation")
.first()
.click();
await expect(
frigateApp.page.getByRole("heading", {
name: "Package Theft Investigation",
}),
).toBeVisible();
await expect(
frigateApp.page.getByText("Backyard - Car Detection"),
).toBeVisible();
await expect(
frigateApp.page.getByRole("button", { name: "Add Export" }),
).toBeVisible();
await expect(
frigateApp.page.getByRole("button", { name: "Edit Case" }),
).toBeVisible();
await expect(
frigateApp.page.getByRole("button", { name: "Delete Case" }),
).toBeVisible();
});
test("edit case opens a prefilled dialog", async ({ frigateApp }) => {
await frigateApp.goto("/export");
await frigateApp.page
.getByText("Package Theft Investigation")
.first()
.click();
await frigateApp.page.getByRole("button", { name: "Edit Case" }).click();
const dialog = frigateApp.page
.getByRole("dialog")
.filter({ hasText: "Edit Case" });
await expect(dialog).toBeVisible();
await expect(dialog.locator("input")).toHaveValue(
"Package Theft Investigation",
);
if (
(await searchInput.count()) > 0 &&
(await searchInput.first().isVisible())
) {
// Type a search term that matches one export
await searchInput.first().fill("Front Door");
await frigateApp.page.waitForTimeout(500);
// "Front Door - Person Alert" should still be visible
await expect(
frigateApp.page.getByText("Front Door - Person Alert"),
).toBeVisible();
await expect(dialog.locator("textarea")).toHaveValue(
"Review of suspicious activity near the front porch",
);
});
test("add export shows completed uncategorized exports for assignment", async ({
frigateApp,
}) => {
await frigateApp.goto("/export");
await frigateApp.page
.getByText("Package Theft Investigation")
.first()
.click();
await frigateApp.page.getByRole("button", { name: "Add Export" }).click();
const dialog = frigateApp.page
.getByRole("dialog")
.filter({ hasText: "Add Export to Package Theft Investigation" });
await expect(dialog).toBeVisible();
// Completed, uncategorized exports are selectable
await expect(dialog.getByText("Front Door - Person Alert")).toBeVisible();
// In-progress exports are intentionally hidden by AssignExportDialog
// (see Exports.tsx filteredExports) — they can't be assigned until
// they finish, so they should not show in the picker.
await expect(dialog.getByText("Garage - In Progress")).toBeHidden();
});
test("delete case opens a confirmation dialog", async ({ frigateApp }) => {
await frigateApp.goto("/export");
await frigateApp.page
.getByText("Package Theft Investigation")
.first()
.click();
await frigateApp.page.getByRole("button", { name: "Delete Case" }).click();
const dialog = frigateApp.page
.getByRole("alertdialog")
.filter({ hasText: "Delete Case" });
await expect(dialog).toBeVisible();
await expect(dialog.getByText(/Package Theft Investigation/)).toBeVisible();
});
test("delete case can also delete its exports", async ({ frigateApp }) => {
let deleteRequestUrl: string | null = null;
let deleteCaseCompleted = false;
const initialCases = [
{
id: "case-001",
name: "Package Theft Investigation",
description: "Review of suspicious activity near the front porch",
created_at: 1775407931.3863528,
updated_at: 1775483531.3863528,
},
];
const initialExports = [
{
id: "export-001",
camera: "front_door",
name: "Front Door - Person Alert",
date: 1775490731.3863528,
video_path: "/exports/export-001.mp4",
thumb_path: "/exports/export-001-thumb.jpg",
in_progress: false,
export_case_id: null,
},
{
id: "export-002",
camera: "backyard",
name: "Backyard - Car Detection",
date: 1775483531.3863528,
video_path: "/exports/export-002.mp4",
thumb_path: "/exports/export-002-thumb.jpg",
in_progress: false,
export_case_id: "case-001",
},
{
id: "export-003",
camera: "garage",
name: "Garage - In Progress",
date: 1775492531.3863528,
video_path: "/exports/export-003.mp4",
thumb_path: "/exports/export-003-thumb.jpg",
in_progress: true,
export_case_id: null,
},
];
await frigateApp.page.route(/\/api\/cases(?:$|\?|\/)/, async (route) => {
const request = route.request();
if (request.method() === "DELETE") {
deleteRequestUrl = request.url();
deleteCaseCompleted = true;
return route.fulfill({ json: { success: true } });
}
if (request.method() === "GET") {
return route.fulfill({
json: deleteCaseCompleted ? [] : initialCases,
});
}
return route.fallback();
});
await frigateApp.page.route("**/api/exports**", async (route) => {
if (route.request().method() !== "GET") {
return route.fallback();
}
return route.fulfill({
json: deleteCaseCompleted
? initialExports.filter((exp) => exp.export_case_id !== "case-001")
: initialExports,
});
});
await frigateApp.goto("/export");
await frigateApp.page
.getByText("Package Theft Investigation")
.first()
.click();
await frigateApp.page.getByRole("button", { name: "Delete Case" }).click();
const dialog = frigateApp.page
.getByRole("alertdialog")
.filter({ hasText: "Delete Case" });
await expect(dialog).toBeVisible();
const deleteExportsSwitch = dialog.getByRole("switch", {
name: "Also delete exports",
});
await expect(deleteExportsSwitch).toHaveAttribute("aria-checked", "false");
await expect(
dialog.getByText(
"Exports will remain available as uncategorized exports.",
),
).toBeVisible();
await deleteExportsSwitch.click();
await expect(deleteExportsSwitch).toHaveAttribute("aria-checked", "true");
await expect(
dialog.getByText("All exports in this case will be permanently deleted."),
).toBeVisible();
await dialog.getByRole("button", { name: /^delete$/i }).click();
await expect
.poll(() => deleteRequestUrl)
.toContain("/api/cases/case-001?delete_exports=true");
await expect(dialog).toBeHidden();
await expect(
frigateApp.page.getByRole("heading", {
name: "Package Theft Investigation",
}),
).toBeHidden();
await expect(
frigateApp.page.getByText("Backyard - Car Detection"),
).toBeHidden();
await expect(
frigateApp.page.getByText("Front Door - Person Alert"),
).toBeVisible();
});
});
test.describe("Export Page - Empty State @high", () => {
test("renders the empty state when there are no exports or cases", async ({
frigateApp,
}) => {
await frigateApp.page.route("**/api/export**", (route) =>
route.fulfill({ json: [] }),
);
await frigateApp.page.route("**/api/exports**", (route) =>
route.fulfill({ json: [] }),
);
await frigateApp.page.route("**/api/cases", (route) =>
route.fulfill({ json: [] }),
);
await frigateApp.page.route("**/api/cases**", (route) =>
route.fulfill({ json: [] }),
);
await frigateApp.goto("/export");
await expect(frigateApp.page.getByText("No exports found")).toBeVisible();
});
});
test.describe("Export Page - Mobile @high @mobile", () => {
test("mobile can open an export preview dialog", async ({ frigateApp }) => {
test.skip(!frigateApp.isMobile, "Mobile-only assertion");
await frigateApp.goto("/export");
await frigateApp.page
.getByText("Front Door - Person Alert")
.first()
.click();
const dialog = frigateApp.page
.getByRole("dialog")
.filter({ hasText: "Front Door - Person Alert" });
await expect(dialog).toBeVisible();
await expect(dialog.locator("video")).toBeVisible();
});
});
test.describe("Multi-Review Export @high", () => {
// Two alert reviews close enough to "now" to fall within the
// default last-24-hours review window. Using numeric timestamps
// because the TS ReviewSegment type expects numbers even though
// the backend pydantic model serializes datetime as ISO strings —
// the app reads these as numbers for display math.
const now = Date.now() / 1000;
const mockReviews = [
{
id: "mex-review-001",
camera: "front_door",
start_time: now - 600,
end_time: now - 580,
has_been_reviewed: false,
severity: "alert",
thumb_path: "/clips/front_door/mex-review-001-thumb.jpg",
data: {
audio: [],
detections: ["person-001"],
objects: ["person"],
sub_labels: [],
significant_motion_areas: [],
zones: ["front_yard"],
},
},
{
id: "mex-review-002",
camera: "backyard",
start_time: now - 1200,
end_time: now - 1170,
has_been_reviewed: false,
severity: "alert",
thumb_path: "/clips/backyard/mex-review-002-thumb.jpg",
data: {
audio: [],
detections: ["car-002"],
objects: ["car"],
sub_labels: [],
significant_motion_areas: [],
zones: ["driveway"],
},
},
];
// 51 alert reviews, all front_door, spaced 5 minutes apart. Used by the
// over-limit test to trigger Ctrl+A select-all and verify the Export
// button is hidden at 51 selected.
const oversizedReviews = Array.from({ length: 51 }, (_, i) => ({
id: `mex-oversized-${i.toString().padStart(3, "0")}`,
camera: "front_door",
start_time: now - 60 * 60 - i * 300,
end_time: now - 60 * 60 - i * 300 + 20,
has_been_reviewed: false,
severity: "alert",
thumb_path: `/clips/front_door/mex-oversized-${i}-thumb.jpg`,
data: {
audio: [],
detections: [`person-${i}`],
objects: ["person"],
sub_labels: [],
significant_motion_areas: [],
zones: ["front_yard"],
},
}));
const mockSummary = {
last24Hours: {
reviewed_alert: 0,
reviewed_detection: 0,
total_alert: 2,
total_detection: 0,
},
};
async function routeReviews(
page: import("@playwright/test").Page,
reviews: unknown[],
) {
// Intercept the actual `/api/review` endpoint (singular — the
// default api-mocker only registers `/api/reviews**` (plural)
// which does not match the real request URL).
await page.route(/\/api\/review(\?|$)/, (route) =>
route.fulfill({ json: reviews }),
);
await page.route(/\/api\/review\/summary/, (route) =>
route.fulfill({ json: mockSummary }),
);
}
test.beforeEach(async ({ frigateApp }) => {
await routeReviews(frigateApp.page, mockReviews);
// Empty cases list by default so the dialog defaults to "new case".
// Individual tests override this to populate existing cases.
await frigateApp.page.route("**/api/cases", (route) =>
route.fulfill({ json: [] }),
);
});
async function selectTwoReviews(frigateApp: {
page: import("@playwright/test").Page;
}) {
// Every review card has className `review-item` on its wrapper
// (see EventView.tsx). Cards also have data-start attributes that
// we can key off if needed.
const reviewItems = frigateApp.page.locator(".review-item");
await reviewItems.first().waitFor({ state: "visible", timeout: 10_000 });
// Meta-click the first two items to enter multi-select mode.
// PreviewThumbnailPlayer reads e.metaKey to decide multi-select.
await reviewItems.nth(0).click({ modifiers: ["Meta"] });
await reviewItems.nth(1).click();
}
test("selecting two reviews reveals the export button", async ({
frigateApp,
}) => {
test.skip(frigateApp.isMobile, "Desktop multi-select flow");
await frigateApp.goto("/review");
await selectTwoReviews(frigateApp);
// Action group replaces the filter bar once items are selected
await expect(frigateApp.page.getByText(/2.*selected/i)).toBeVisible({
timeout: 5_000,
});
const exportButton = frigateApp.page.getByRole("button", {
name: /export/i,
});
await expect(exportButton).toBeVisible();
});
test("clicking export opens the multi-review dialog with correct title", async ({
frigateApp,
}) => {
test.skip(frigateApp.isMobile, "Desktop multi-select flow");
await frigateApp.goto("/review");
await selectTwoReviews(frigateApp);
await frigateApp.page
.getByRole("button", { name: /export/i })
.first()
.click();
const dialog = frigateApp.page
.getByRole("dialog")
.filter({ hasText: /Export 2 reviews/i });
await expect(dialog).toBeVisible({ timeout: 5_000 });
// The dialog uses a Select trigger for case selection (admins). The
// default "None" value is shown on the trigger.
await expect(dialog.locator("button[role='combobox']")).toBeVisible();
await expect(dialog.getByText(/None/)).toBeVisible();
});
test("starting an export posts the expected payload and navigates to the case", async ({
frigateApp,
}) => {
test.skip(frigateApp.isMobile, "Desktop multi-select flow");
let capturedPayload: unknown = null;
await frigateApp.page.route("**/api/exports/batch", async (route) => {
capturedPayload = route.request().postDataJSON();
await route.fulfill({
status: 202,
json: {
export_case_id: "new-case-xyz",
export_ids: ["front_door_a", "backyard_b"],
results: [
{
camera: "front_door",
export_id: "front_door_a",
success: true,
status: "queued",
error: null,
item_index: 0,
},
{
camera: "backyard",
export_id: "backyard_b",
success: true,
status: "queued",
error: null,
item_index: 1,
},
],
},
});
});
await frigateApp.goto("/review");
await selectTwoReviews(frigateApp);
await frigateApp.page
.getByRole("button", { name: /export/i })
.first()
.click();
const dialog = frigateApp.page
.getByRole("dialog")
.filter({ hasText: /Export 2 reviews/i });
await expect(dialog).toBeVisible({ timeout: 5_000 });
// Select "Create new case" from the case dropdown (default is "None")
await dialog.locator("button[role='combobox']").click();
await frigateApp.page
.getByRole("option", { name: /Create new case/i })
.click();
const nameInput = dialog.locator("input").first();
await nameInput.fill("E2E Incident");
await dialog.getByRole("button", { name: /export 2 reviews/i }).click();
// Wait for the POST to fire
await expect.poll(() => capturedPayload, { timeout: 5_000 }).not.toBeNull();
const payload = capturedPayload as {
items: Array<{
camera: string;
start_time: number;
end_time: number;
image_path?: string;
client_item_id?: string;
}>;
new_case_name?: string;
export_case_id?: string;
};
expect(payload.items).toHaveLength(2);
expect(payload.new_case_name).toBe("E2E Incident");
// When creating a new case, we must NOT also send export_case_id —
// the two fields are mutually exclusive on the backend.
expect(payload.export_case_id).toBeUndefined();
expect(payload.items.map((i) => i.camera).sort()).toEqual([
"backyard",
"front_door",
]);
// Each item must preserve REVIEW_PADDING (4s) on the edges —
// i.e. the padded window is 8s longer than the original review.
// The mock reviews above have 20s and 30s raw durations, so the
// expected padded durations are 28s and 38s.
const paddedDurations = payload.items
.map((i) => i.end_time - i.start_time)
.sort((a, b) => a - b);
expect(paddedDurations).toEqual([28, 38]);
// Thumbnails should be passed through per item
for (const item of payload.items) {
expect(item.image_path).toMatch(/mex-review-\d+-thumb\.jpg$/);
}
await expect(frigateApp.page.locator("#pageRoot")).toBeVisible();
});
});
expect(payload.items.map((item) => item.client_item_id)).toEqual([
"mex-review-001",
"mex-review-002",
]);
test.describe("Export Page - Controls @high", () => {
test("export page filter controls are present", async ({ frigateApp }) => {
await frigateApp.goto("/export");
await frigateApp.page.waitForTimeout(1000);
const buttons = frigateApp.page.locator("#pageRoot button");
const count = await buttons.count();
expect(count).toBeGreaterThan(0);
await expect(frigateApp.page).toHaveURL(/caseId=new-case-xyz/, {
timeout: 5_000,
});
});
test("mobile opens a drawer (not a dialog) for the multi-review export flow", async ({
frigateApp,
}) => {
test.skip(!frigateApp.isMobile, "Mobile-only Drawer assertion");
await frigateApp.goto("/review");
await selectTwoReviews(frigateApp);
await frigateApp.page
.getByRole("button", { name: /export/i })
.first()
.click();
// On mobile the component renders a shadcn Drawer, which uses
// role="dialog" but sets data-vaul-drawer. Desktop renders a
// shadcn Dialog with role="dialog" but no data-vaul-drawer.
// The title and submit button both contain "Export 2 reviews", so
// assert each element distinctly: the title is a heading and the
// submit button has role="button".
const drawer = frigateApp.page.locator("[data-vaul-drawer]");
await expect(drawer).toBeVisible({ timeout: 5_000 });
await expect(
drawer.getByRole("heading", { name: /Export 2 reviews/i }),
).toBeVisible();
await expect(
drawer.getByRole("button", { name: /export 2 reviews/i }),
).toBeVisible();
});
test("hides export button when more than 50 reviews are selected", async ({
frigateApp,
}) => {
test.skip(frigateApp.isMobile, "Desktop select-all keyboard flow");
// Override the default 2-review mock with 51 reviews before
// navigation. Playwright matches routes last-registered-first so
// this takes precedence over the beforeEach.
await routeReviews(frigateApp.page, oversizedReviews);
await frigateApp.goto("/review");
// Wait for any review item to render before firing the shortcut
await frigateApp.page
.locator(".review-item")
.first()
.waitFor({ state: "visible", timeout: 10_000 });
// Ctrl+A triggers onSelectAllReviews (see EventView.tsx useKeyboardListener)
await frigateApp.page.keyboard.press("Control+a");
// The action group should show "51 selected" but no Export button.
// Mark-as-reviewed is still there so the action bar is rendered.
// Scope the "Mark as reviewed" lookup to its exact aria-label because
// the page can render other "mark as reviewed" controls elsewhere
// (e.g. on individual cards) that would trip strict-mode matching.
await expect(frigateApp.page.getByText(/51.*selected/i)).toBeVisible({
timeout: 5_000,
});
await expect(
frigateApp.page.getByRole("button", { name: "Mark as reviewed" }),
).toBeVisible();
await expect(
frigateApp.page.getByRole("button", { name: /^export$/i }),
).toHaveCount(0);
});
test("attaching to an existing case sends export_case_id without new_case_name", async ({
frigateApp,
}) => {
test.skip(frigateApp.isMobile, "Desktop multi-select flow");
// Seed one existing case so the dialog can offer the "existing" branch.
// The fixture mocks the user as admin (adminProfile()), so useIsAdmin()
// is true and the dialog renders the "Existing case" radio.
await frigateApp.page.route("**/api/cases", (route) =>
route.fulfill({
json: [
{
id: "existing-case-abc",
name: "Incident #42",
description: "",
created_at: now - 3600,
updated_at: now - 3600,
},
],
}),
);
let capturedPayload: unknown = null;
await frigateApp.page.route("**/api/exports/batch", async (route) => {
capturedPayload = route.request().postDataJSON();
await route.fulfill({
status: 202,
json: {
export_case_id: "existing-case-abc",
export_ids: ["front_door_a", "backyard_b"],
results: [
{
camera: "front_door",
export_id: "front_door_a",
success: true,
status: "queued",
error: null,
item_index: 0,
},
{
camera: "backyard",
export_id: "backyard_b",
success: true,
status: "queued",
error: null,
item_index: 1,
},
],
},
});
});
await frigateApp.goto("/review");
await selectTwoReviews(frigateApp);
await frigateApp.page
.getByRole("button", { name: /export/i })
.first()
.click();
const dialog = frigateApp.page
.getByRole("dialog")
.filter({ hasText: /Export 2 reviews/i });
await expect(dialog).toBeVisible({ timeout: 5_000 });
// Open the Case Select dropdown and pick the seeded case directly.
// The dialog now uses a single Select listing existing cases above
// the "Create new case" option — no radio toggle needed.
const selectTrigger = dialog.locator("button[role='combobox']").first();
await selectTrigger.waitFor({ state: "visible", timeout: 5_000 });
await selectTrigger.click();
// The dropdown portal renders outside the dialog
await frigateApp.page.getByRole("option", { name: /Incident #42/ }).click();
await dialog.getByRole("button", { name: /export 2 reviews/i }).click();
await expect.poll(() => capturedPayload, { timeout: 5_000 }).not.toBeNull();
const payload = capturedPayload as {
items: unknown[];
new_case_name?: string;
new_case_description?: string;
export_case_id?: string;
};
expect(payload.export_case_id).toBe("existing-case-abc");
expect(payload.new_case_name).toBeUndefined();
expect(payload.new_case_description).toBeUndefined();
expect(payload.items).toHaveLength(2);
// Navigate should hit /export. useSearchEffect consumes the caseId
// query param and strips it once the case is found in the cases list,
// so we assert on the path, not the query string.
await expect(frigateApp.page).toHaveURL(/\/export(\?|$)/, {
timeout: 5_000,
});
});
});
+2 -1
View File
@@ -7,7 +7,8 @@
"dev": "vite --host",
"postinstall": "patch-package",
"build": "tsc && vite build --base=/BASE_PATH/",
"lint": "eslint --ext .jsx,.js,.tsx,.ts --ignore-path .gitignore .",
"lint": "eslint --ext .jsx,.js,.tsx,.ts --ignore-path .gitignore . && npm run e2e:lint",
"e2e:lint": "node e2e/scripts/lint-specs.mjs",
"lint:fix": "eslint --ext .jsx,.js,.tsx,.ts --ignore-path .gitignore --fix .",
"preview": "vite preview",
"prettier:write": "prettier -u -w --ignore-path .gitignore \"*.{ts,tsx,js,jsx,css,html}\"",
+55 -2
View File
@@ -50,24 +50,77 @@
"placeholder": "Name the Export"
},
"case": {
"newCaseOption": "Create new case",
"newCaseNamePlaceholder": "New case name",
"newCaseDescriptionPlaceholder": "Case description",
"label": "Case",
"nonAdminHelp": "A new case will be created for these exports.",
"placeholder": "Select a case"
},
"select": "Select",
"export": "Export",
"queueing": "Queueing Export...",
"selectOrExport": "Select or Export",
"tabs": {
"export": "Single Camera",
"multiCamera": "Multi-Camera"
},
"multiCamera": {
"timeRange": "Time range",
"selectFromTimeline": "Select from Timeline",
"cameraSelection": "Cameras",
"cameraSelectionHelp": "Cameras with tracked objects in this time range are pre-selected",
"checkingActivity": "Checking camera activity...",
"noCameras": "No cameras available",
"detectionCount_one": "1 tracked object",
"detectionCount_other": "{{count}} tracked objects",
"nameLabel": "Export name",
"namePlaceholder": "Optional base name for these exports",
"queueingButton": "Queueing Exports...",
"exportButton_one": "Export 1 Camera",
"exportButton_other": "Export {{count}} Cameras"
},
"multi": {
"title_one": "Export 1 review",
"title_other": "Export {{count}} reviews",
"description": "Export each selected review. All exports will be grouped under a single case.",
"descriptionNoCase": "Export each selected review.",
"caseNamePlaceholder": "Review export - {{date}}",
"exportButton_one": "Export 1 review",
"exportButton_other": "Export {{count}} reviews",
"exportingButton": "Exporting...",
"toast": {
"started_one": "Started 1 export. Opening the case now.",
"started_other": "Started {{count}} exports. Opening the case now.",
"startedNoCase_one": "Started 1 export.",
"startedNoCase_other": "Started {{count}} exports.",
"partial": "Started {{successful}} of {{total}} exports. Failed: {{failedItems}}",
"failed": "Failed to start {{total}} exports. Failed: {{failedItems}}"
}
},
"toast": {
"success": "Successfully started export. View the file in the exports page.",
"queued": "Export queued. View progress in the exports page.",
"view": "View",
"batchSuccess_one": "Started 1 export. Opening the case now.",
"batchSuccess_other": "Started {{count}} exports. Opening the case now.",
"batchPartial": "Started {{successful}} of {{total}} exports. Failed cameras: {{failedCameras}}",
"batchFailed": "Failed to start {{total}} exports. Failed cameras: {{failedCameras}}",
"batchQueuedSuccess_one": "Queued 1 export. Opening the case now.",
"batchQueuedSuccess_other": "Queued {{count}} exports. Opening the case now.",
"batchQueuedPartial": "Queued {{successful}} of {{total}} exports. Failed cameras: {{failedCameras}}",
"batchQueueFailed": "Failed to queue {{total}} exports. Failed cameras: {{failedCameras}}",
"error": {
"failed": "Failed to start export: {{error}}",
"failed": "Failed to queue export: {{error}}",
"endTimeMustAfterStartTime": "End time must be after start time",
"noVaildTimeSelected": "No valid time range selected"
}
},
"fromTimeline": {
"saveExport": "Save Export",
"previewExport": "Preview Export"
"queueingExport": "Queueing Export...",
"previewExport": "Preview Export",
"useThisRange": "Use This Range"
}
},
"streaming": {
+17
View File
@@ -12,6 +12,23 @@
"result": "Result",
"arguments": "Arguments:",
"response": "Response:",
"attachment_chip_label": "{{label}} on {{camera}}",
"attachment_chip_remove": "Remove attachment",
"open_in_explore": "Open in Explore",
"attach_event_aria": "Attach event {{eventId}}",
"attachment_picker_paste_label": "Or paste event ID",
"attachment_picker_attach": "Attach",
"attachment_picker_placeholder": "Attach an event",
"quick_reply_find_similar": "Find similar sightings",
"quick_reply_tell_me_more": "Tell me more about this",
"quick_reply_when_else": "When else was it seen?",
"quick_reply_find_similar_text": "Find similar sightings to this.",
"quick_reply_tell_me_more_text": "Tell me more about this one.",
"quick_reply_when_else_text": "When else was this seen?",
"anchor": "Reference",
"similarity_score": "Similarity",
"no_similar_objects_found": "No similar objects found.",
"semantic_search_required": "Semantic search must be enabled to find similar objects.",
"send": "Send",
"suggested_requests": "Try asking:",
"starting_requests": {
+86 -2
View File
@@ -20,14 +20,30 @@
"downloadVideo": "Download video",
"editName": "Edit name",
"deleteExport": "Delete export",
"assignToCase": "Add to case"
"assignToCase": "Add to case",
"removeFromCase": "Remove from case"
},
"toolbar": {
"newCase": "New Case",
"addExport": "Add Export",
"editCase": "Edit Case",
"deleteCase": "Delete Case"
},
"toast": {
"error": {
"renameExportFailed": "Failed to rename export: {{errorMessage}}",
"assignCaseFailed": "Failed to update case assignment: {{errorMessage}}"
"assignCaseFailed": "Failed to update case assignment: {{errorMessage}}",
"caseSaveFailed": "Failed to save case: {{errorMessage}}",
"caseDeleteFailed": "Failed to delete case: {{errorMessage}}"
}
},
"deleteCase": {
"label": "Delete Case",
"desc": "Are you sure you want to delete {{caseName}}?",
"descKeepExports": "Exports will remain available as uncategorized exports.",
"descDeleteExports": "All exports in this case will be permanently deleted.",
"deleteExports": "Also delete exports"
},
"caseDialog": {
"title": "Add to case",
"description": "Choose an existing case or create a new one.",
@@ -35,5 +51,73 @@
"newCaseOption": "Create new case",
"nameLabel": "Case name",
"descriptionLabel": "Description"
},
"caseCard": {
"emptyCase": "No exports yet"
},
"jobCard": {
"defaultName": "{{camera}} export",
"queued": "Queued",
"running": "Running"
},
"caseView": {
"noDescription": "No description",
"createdAt": "Created {{value}}",
"exportCount_one": "1 export",
"exportCount_other": "{{count}} exports",
"cameraCount_one": "1 camera",
"cameraCount_other": "{{count}} cameras",
"showMore": "Show more",
"showLess": "Show less",
"emptyTitle": "This case is empty",
"emptyDescription": "Add existing uncategorized exports to keep the case organized.",
"emptyDescriptionNoExports": "There are no uncategorized exports available to add yet."
},
"caseEditor": {
"createTitle": "Create Case",
"editTitle": "Edit Case",
"namePlaceholder": "Case name",
"descriptionPlaceholder": "Add notes or context for this case"
},
"addExportDialog": {
"title": "Add Export to {{caseName}}",
"searchPlaceholder": "Search uncategorized exports",
"empty": "No uncategorized exports match this search.",
"addButton_one": "Add 1 Export",
"addButton_other": "Add {{count}} Exports",
"adding": "Adding..."
},
"selected_one": "{{count}} selected",
"selected_other": "{{count}} selected",
"bulkActions": {
"addToCase": "Add to Case",
"moveToCase": "Move to Case",
"removeFromCase": "Remove from Case",
"delete": "Delete",
"deleteNow": "Delete Now"
},
"bulkDelete": {
"title": "Delete Exports",
"desc_one": "Are you sure you want to delete {{count}} export?",
"desc_other": "Are you sure you want to delete {{count}} exports?"
},
"bulkRemoveFromCase": {
"title": "Remove from Case",
"desc_one": "Remove {{count}} export from this case?",
"desc_other": "Remove {{count}} exports from this case?",
"descKeepExports": "Exports will be moved to uncategorized.",
"descDeleteExports": "Exports will be permanently deleted.",
"deleteExports": "Delete exports instead"
},
"bulkToast": {
"success": {
"delete": "Successfully deleted exports",
"reassign": "Successfully updated case assignment",
"remove": "Successfully removed exports from case"
},
"error": {
"deleteFailed": "Failed to delete exports: {{errorMessage}}",
"reassignFailed": "Failed to update case assignment: {{errorMessage}}"
}
}
}
+20 -5
View File
@@ -7,6 +7,7 @@ import useStats, { useAutoFrigateStats } from "@/hooks/use-stats";
import { cn } from "@/lib/utils";
import type { ProfilesApiResponse } from "@/types/profile";
import { getProfileColor } from "@/utils/profileColors";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { useContext, useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import useSWR from "swr";
@@ -18,6 +19,7 @@ import { Link } from "react-router-dom";
export default function Statusbar() {
const { t } = useTranslation(["views/system"]);
const isAdmin = useIsAdmin();
const { messages, addMessage, clearMessages } = useContext(
StatusBarMessagesContext,
@@ -154,9 +156,23 @@ export default function Statusbar() {
</Link>
);
})}
{activeProfile && (
<Link to="/settings?page=profiles">
<div className="flex cursor-pointer items-center gap-2 text-sm hover:underline">
{activeProfile &&
(isAdmin ? (
<Link to="/settings?page=profiles">
<div className="flex cursor-pointer items-center gap-2 text-sm hover:underline">
<span
className={cn(
"size-2 shrink-0 rounded-full",
activeProfile.color.dot,
)}
/>
<span className="max-w-[150px] truncate">
{activeProfile.friendlyName}
</span>
</div>
</Link>
) : (
<div className="flex items-center gap-2 text-sm">
<span
className={cn(
"size-2 shrink-0 rounded-full",
@@ -167,8 +183,7 @@ export default function Statusbar() {
{activeProfile.friendlyName}
</span>
</div>
</Link>
)}
))}
</div>
<div className="no-scrollbar flex h-full max-w-[50%] items-center gap-2 overflow-x-auto">
{Object.entries(messages).length === 0 ? (
+124 -11
View File
@@ -1,6 +1,6 @@
import ActivityIndicator from "../indicators/activity-indicator";
import { Button } from "../ui/button";
import { useCallback, useMemo, useState } from "react";
import { useCallback, useMemo, useRef, useState } from "react";
import { isMobile } from "react-device-detect";
import { FiMoreVertical } from "react-icons/fi";
import { Skeleton } from "../ui/skeleton";
@@ -13,7 +13,7 @@ import {
} from "../ui/dialog";
import { Input } from "../ui/input";
import useKeyboardListener from "@/hooks/use-keyboard-listener";
import { DeleteClipType, Export, ExportCase } from "@/types/export";
import { DeleteClipType, Export, ExportCase, ExportJob } from "@/types/export";
import { baseUrl } from "@/api/baseUrl";
import { cn } from "@/lib/utils";
import { shareOrCopy } from "@/utils/browserUtil";
@@ -27,7 +27,10 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "../ui/dropdown-menu";
import { FaFolder } from "react-icons/fa";
import { FaFolder, FaVideo } from "react-icons/fa";
import { HiSquare2Stack } from "react-icons/hi2";
import { useCameraFriendlyName } from "@/hooks/use-camera-friendly-name";
import useContextMenu from "@/hooks/use-contextmenu";
type CaseCardProps = {
className: string;
@@ -41,10 +44,15 @@ export function CaseCard({
exports,
onSelect,
}: CaseCardProps) {
const { t } = useTranslation(["views/exports"]);
const firstExport = useMemo(
() => exports.find((exp) => exp.thumb_path && exp.thumb_path.length > 0),
[exports],
);
const cameraCount = useMemo(
() => new Set(exports.map((exp) => exp.camera)).size,
[exports],
);
return (
<div
@@ -61,10 +69,30 @@ export function CaseCard({
alt=""
/>
)}
{!firstExport && (
<div className="absolute inset-0 bg-gradient-to-br from-secondary via-secondary/80 to-muted" />
)}
<div className="pointer-events-none absolute inset-x-0 bottom-0 z-10 h-16 bg-gradient-to-t from-black/60 to-transparent" />
<div className="absolute bottom-2 left-2 z-20 flex items-center justify-start gap-2 text-white">
<FaFolder />
<div className="capitalize">{exportCase.name}</div>
<div className="absolute right-1 top-1 z-40 flex items-center gap-2 rounded-lg bg-black/50 px-2 py-1 text-xs text-white">
<div className="flex items-center gap-1">
<HiSquare2Stack className="size-3" />
<div>{exports.length}</div>
</div>
<div className="flex items-center gap-1">
<FaVideo className="size-3" />
<div>{cameraCount}</div>
</div>
</div>
<div className="absolute inset-x-2 bottom-2 z-20 text-white">
<div className="flex items-center justify-start gap-2">
<FaFolder />
<div className="truncate smart-capitalize">{exportCase.name}</div>
</div>
{exports.length === 0 && (
<div className="mt-1 text-xs text-white/80">
{t("caseCard.emptyCase")}
</div>
)}
</div>
</div>
);
@@ -73,18 +101,26 @@ export function CaseCard({
type ExportCardProps = {
className: string;
exportedRecording: Export;
isSelected?: boolean;
selectionMode?: boolean;
onSelect: (selected: Export) => void;
onContextSelect?: (selected: Export) => void;
onRename: (original: string, update: string) => void;
onDelete: ({ file, exportName }: DeleteClipType) => void;
onAssignToCase?: (selected: Export) => void;
onRemoveFromCase?: (selected: Export) => void;
};
export function ExportCard({
className,
exportedRecording,
isSelected,
selectionMode,
onSelect,
onContextSelect,
onRename,
onDelete,
onAssignToCase,
onRemoveFromCase,
}: ExportCardProps) {
const { t } = useTranslation(["views/exports"]);
const isAdmin = useIsAdmin();
@@ -92,6 +128,15 @@ export function ExportCard({
exportedRecording.thumb_path.length > 0,
);
// selection
const cardRef = useRef<HTMLDivElement | null>(null);
useContextMenu(cardRef, () => {
if (!exportedRecording.in_progress && onContextSelect) {
onContextSelect(exportedRecording);
}
});
// editing name
const [editName, setEditName] = useState<{
@@ -180,13 +225,18 @@ export function ExportCard({
</Dialog>
<div
ref={cardRef}
className={cn(
"relative flex aspect-video cursor-pointer items-center justify-center rounded-lg bg-black md:rounded-2xl",
className,
)}
onClick={() => {
onClick={(e) => {
if (!exportedRecording.in_progress) {
onSelect(exportedRecording);
if ((selectionMode || e.ctrlKey || e.metaKey) && onContextSelect) {
onContextSelect(exportedRecording);
} else {
onSelect(exportedRecording);
}
}
}}
>
@@ -205,7 +255,7 @@ export function ExportCard({
)}
</>
)}
{!exportedRecording.in_progress && (
{!exportedRecording.in_progress && !selectionMode && (
<div className="absolute bottom-2 right-3 z-40">
<DropdownMenu modal={false}>
<DropdownMenuTrigger>
@@ -254,6 +304,18 @@ export function ExportCard({
{t("tooltip.assignToCase")}
</DropdownMenuItem>
)}
{isAdmin && onRemoveFromCase && (
<DropdownMenuItem
className="cursor-pointer"
aria-label={t("tooltip.removeFromCase")}
onClick={(e) => {
e.stopPropagation();
onRemoveFromCase(exportedRecording);
}}
>
{t("tooltip.removeFromCase")}
</DropdownMenuItem>
)}
{isAdmin && (
<DropdownMenuItem
className="cursor-pointer"
@@ -292,10 +354,61 @@ export function ExportCard({
<Skeleton className="absolute inset-0 aspect-video rounded-lg md:rounded-2xl" />
)}
<ImageShadowOverlay />
<div className="absolute bottom-2 left-3 flex items-end text-white smart-capitalize">
{exportedRecording.name.replaceAll("_", " ")}
<div
className={cn(
"pointer-events-none absolute inset-0 z-10 size-full rounded-lg outline outline-[3px] -outline-offset-[2.8px] md:rounded-2xl",
isSelected
? "shadow-selected outline-selected"
: "outline-transparent duration-500",
)}
/>
<div className="absolute bottom-2 left-3 right-12 z-30 text-white">
<div className="truncate smart-capitalize">
{exportedRecording.name.replaceAll("_", " ")}
</div>
</div>
</div>
</>
);
}
type ActiveExportJobCardProps = {
className?: string;
job: ExportJob;
};
export function ActiveExportJobCard({
className = "",
job,
}: ActiveExportJobCardProps) {
const { t } = useTranslation(["views/exports", "common"]);
const cameraName = useCameraFriendlyName(job.camera);
const displayName = useMemo(() => {
if (job.name && job.name.length > 0) {
return job.name.replaceAll("_", " ");
}
return t("jobCard.defaultName", {
camera: cameraName,
});
}, [cameraName, job.name, t]);
const statusLabel =
job.status === "queued" ? t("jobCard.queued") : t("jobCard.running");
return (
<div
className={cn(
"relative flex aspect-video items-center justify-center overflow-hidden rounded-lg border border-dashed border-border bg-secondary/40 md:rounded-2xl",
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="text-sm font-medium text-primary">{displayName}</div>
</div>
</div>
);
}
+1 -1
View File
@@ -81,7 +81,7 @@ export default function ReviewCard({
axios
.post(
`export/${event.camera}/start/${event.start_time + REVIEW_PADDING}/end/${endTime}`,
`export/${event.camera}/start/${event.start_time - REVIEW_PADDING}/end/${endTime}`,
{ playback: "realtime" },
)
.then((response) => {
@@ -0,0 +1,111 @@
import { useApiHost } from "@/api";
import { useCameraFriendlyName } from "@/hooks/use-camera-friendly-name";
import { useTranslation } from "react-i18next";
import useSWR from "swr";
import { LuX, LuExternalLink } from "react-icons/lu";
import { Button } from "@/components/ui/button";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { cn } from "@/lib/utils";
import { getTranslatedLabel } from "@/utils/i18n";
type ChatAttachmentChipProps = {
eventId: string;
mode: "composer" | "bubble";
onRemove?: () => void;
};
/**
* Small horizontal chip rendering an event as an "attachment": a thumbnail,
* a friendly label like "Person on driveway", an optional remove X (composer
* mode), and an external-link icon that opens the event in Explore.
*/
export function ChatAttachmentChip({
eventId,
mode,
onRemove,
}: ChatAttachmentChipProps) {
const apiHost = useApiHost();
const { t } = useTranslation(["views/chat"]);
const { data: eventData } = useSWR<{ label: string; camera: string }[]>(
`event_ids?ids=${eventId}`,
);
const evt = eventData?.[0];
const cameraName = useCameraFriendlyName(evt?.camera);
const displayLabel = evt
? t("attachment_chip_label", {
label: getTranslatedLabel(evt.label),
camera: cameraName,
})
: eventId;
return (
<div
className={cn(
"inline-flex max-w-full items-center gap-2 rounded-lg border border-border bg-background/80 p-1.5 pr-2",
mode === "bubble" && "border-primary-foreground/30 bg-transparent",
)}
>
<div className="relative size-10 shrink-0 overflow-hidden rounded-md">
<img
className="size-full object-cover"
src={`${apiHost}api/events/${eventId}/thumbnail.webp`}
alt=""
loading="lazy"
onError={(e) => {
(e.currentTarget as HTMLImageElement).style.visibility = "hidden";
}}
/>
</div>
{evt ? (
<span
className={cn(
"truncate text-xs",
mode === "bubble"
? "text-primary-foreground/90"
: "text-foreground",
)}
>
{displayLabel}
</span>
) : (
<ActivityIndicator className="size-4" />
)}
<Tooltip>
<TooltipTrigger asChild>
<a
href={`/explore?event_id=${eventId}`}
target="_blank"
rel="noopener noreferrer"
className={cn(
"flex size-6 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground",
mode === "bubble" &&
"text-primary-foreground/70 hover:text-primary-foreground",
)}
onClick={(e) => e.stopPropagation()}
aria-label={t("open_in_explore")}
>
<LuExternalLink className="size-3.5" />
</a>
</TooltipTrigger>
<TooltipContent>{t("open_in_explore")}</TooltipContent>
</Tooltip>
{mode === "composer" && onRemove && (
<Button
variant="ghost"
size="icon"
className="size-6 shrink-0 text-muted-foreground hover:text-foreground"
onClick={onRemove}
aria-label={t("attachment_chip_remove")}
>
<LuX className="size-3.5" />
</Button>
)}
</div>
);
}
@@ -1,42 +1,97 @@
import { useApiHost } from "@/api";
import { useTranslation } from "react-i18next";
import { LuExternalLink } from "react-icons/lu";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
type ChatEvent = { id: string; score?: number };
type ChatEventThumbnailsRowProps = {
events: { id: string }[];
events: ChatEvent[];
anchor?: { id: string } | null;
onAttach?: (eventId: string) => void;
};
/**
* Horizontal scroll row of event thumbnail images for chat (e.g. after search_objects).
* Renders nothing when events is empty.
* Horizontal scroll row of event thumbnail images for chat.
* Optionally renders an anchor thumbnail with a "reference" badge above the
* results, and per-event similarity scores when provided.
* Clicking a thumbnail calls onAttach; a small external-link overlay opens
* the event in Explore.
* Renders nothing when there is nothing to show.
*/
export function ChatEventThumbnailsRow({
events,
anchor = null,
onAttach,
}: ChatEventThumbnailsRowProps) {
const apiHost = useApiHost();
const { t } = useTranslation(["views/chat"]);
if (events.length === 0) return null;
if (events.length === 0 && !anchor) return null;
const renderThumb = (event: ChatEvent, isAnchor = false) => (
<div
key={event.id}
className={cn(
"relative aspect-square size-32 shrink-0 overflow-hidden rounded-lg",
isAnchor && "ring-2 ring-primary",
)}
>
<button
type="button"
className="block size-full"
onClick={() => onAttach?.(event.id)}
aria-label={t("attach_event_aria", { eventId: event.id })}
>
<img
className="size-full object-cover"
src={`${apiHost}api/events/${event.id}/thumbnail.webp`}
alt=""
loading="lazy"
/>
</button>
<Tooltip>
<TooltipTrigger asChild>
<a
href={`/explore?event_id=${event.id}`}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
className="absolute right-1 top-1 flex size-6 items-center justify-center rounded bg-black/60 text-white hover:bg-black/80"
aria-label={t("open_in_explore")}
>
<LuExternalLink className="size-3" />
</a>
</TooltipTrigger>
<TooltipContent>{t("open_in_explore")}</TooltipContent>
</Tooltip>
{isAnchor && (
<span className="pointer-events-none absolute left-1 top-1 rounded bg-primary px-1 text-[10px] text-primary-foreground">
{t("anchor")}
</span>
)}
</div>
);
return (
<div className="flex min-w-0 max-w-full flex-col gap-1 self-start">
<div className="scrollbar-container min-w-0 overflow-x-auto">
<div className="flex w-max gap-2">
{events.map((event) => (
<a
key={event.id}
href={`/explore?event_id=${event.id}`}
target="_blank"
rel="noopener noreferrer"
className="relative aspect-square size-32 shrink-0 overflow-hidden rounded-lg"
>
<img
className="size-full object-cover"
src={`${apiHost}api/events/${event.id}/thumbnail.webp`}
alt=""
loading="lazy"
/>
</a>
))}
<div className="flex min-w-0 max-w-full flex-col gap-2 self-start">
{anchor && (
<div className="scrollbar-container min-w-0 overflow-x-auto">
<div className="flex w-max gap-2">{renderThumb(anchor, true)}</div>
</div>
</div>
)}
{events.length > 0 && (
<div className="scrollbar-container min-w-0 overflow-x-auto">
<div className="flex w-max gap-2">
{events.map((event) => renderThumb(event))}
</div>
</div>
)}
</div>
);
}
+20 -6
View File
@@ -15,6 +15,8 @@ import {
TooltipTrigger,
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { ChatAttachmentChip } from "@/components/chat/ChatAttachmentChip";
import { parseAttachedEvent } from "@/utils/chatUtil";
type MessageBubbleProps = {
role: "user" | "assistant";
@@ -126,6 +128,10 @@ export function MessageBubble({
);
}
const { eventId: attachedEventId, body: displayContent } = isUser
? parseAttachedEvent(content)
: { eventId: null, body: content };
return (
<div
className={cn(
@@ -140,9 +146,20 @@ export function MessageBubble({
)}
>
{isUser ? (
content
<div className="flex flex-col gap-2">
{attachedEventId && (
<ChatAttachmentChip eventId={attachedEventId} mode="bubble" />
)}
<div className="whitespace-pre-wrap">{displayContent}</div>
</div>
) : (
<>
<div
className={cn(
"[&>*:last-child]:inline",
!isComplete &&
"after:ml-0.5 after:inline-block after:h-4 after:w-2 after:animate-cursor-blink after:rounded-sm after:bg-foreground after:align-middle after:content-['']",
)}
>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
@@ -168,10 +185,7 @@ export function MessageBubble({
>
{content}
</ReactMarkdown>
{!isComplete && (
<span className="ml-1 inline-block h-4 w-0.5 animate-pulse bg-foreground align-middle" />
)}
</>
</div>
)}
</div>
<div className="flex items-center gap-0.5">
@@ -0,0 +1,114 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { LuPaperclip } from "react-icons/lu";
import { useApiHost } from "@/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
const EVENT_ID_RE = /^[A-Za-z0-9._-]+$/;
type ChatPaperclipButtonProps = {
recentEventIds: string[];
onAttach: (eventId: string) => void;
disabled?: boolean;
};
/**
* Paperclip button with a popover for picking an event to attach.
* Shows a grid of recent thumbnails (from the latest assistant message) and a
* "paste event ID" fallback input.
*/
export function ChatPaperclipButton({
recentEventIds,
onAttach,
disabled = false,
}: ChatPaperclipButtonProps) {
const apiHost = useApiHost();
const { t } = useTranslation(["views/chat"]);
const [open, setOpen] = useState(false);
const [pasteId, setPasteId] = useState("");
const handlePickThumbnail = (eventId: string) => {
onAttach(eventId);
setOpen(false);
setPasteId("");
};
const handlePasteSubmit = () => {
const trimmed = pasteId.trim();
if (!trimmed || !EVENT_ID_RE.test(trimmed)) return;
onAttach(trimmed);
setOpen(false);
setPasteId("");
};
const handlePasteKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
e.preventDefault();
handlePasteSubmit();
}
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="icon"
className="size-10 shrink-0 rounded-full"
disabled={disabled}
aria-label={t("attachment_picker_placeholder")}
>
<LuPaperclip className="size-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-72" align="start">
<div className="flex flex-col gap-3">
{recentEventIds.length > 0 && (
<div className="grid grid-cols-4 gap-2">
{recentEventIds.slice(0, 8).map((id) => (
<button
key={id}
type="button"
onClick={() => handlePickThumbnail(id)}
className="relative aspect-square overflow-hidden rounded-md ring-offset-background hover:ring-2 hover:ring-primary"
aria-label={t("attach_event_aria", { eventId: id })}
>
<img
className="size-full object-cover"
src={`${apiHost}api/events/${id}/thumbnail.webp`}
alt=""
loading="lazy"
/>
</button>
))}
</div>
)}
<div className="flex items-center gap-2">
<Input
placeholder={t("attachment_picker_paste_label")}
value={pasteId}
onChange={(e) => setPasteId(e.target.value)}
onKeyDown={handlePasteKeyDown}
className="h-8 text-xs"
/>
<Button
size="sm"
variant="select"
className="h-8"
disabled={!pasteId.trim() || !EVENT_ID_RE.test(pasteId.trim())}
onClick={handlePasteSubmit}
>
{t("attachment_picker_attach")}
</Button>
</div>
</div>
</PopoverContent>
</Popover>
);
}
@@ -0,0 +1,49 @@
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
type QuickReply = { labelKey: string; textKey: string };
const REPLIES: QuickReply[] = [
{
labelKey: "quick_reply_find_similar",
textKey: "quick_reply_find_similar_text",
},
{
labelKey: "quick_reply_tell_me_more",
textKey: "quick_reply_tell_me_more_text",
},
{ labelKey: "quick_reply_when_else", textKey: "quick_reply_when_else_text" },
];
type ChatQuickRepliesProps = {
onSend: (text: string) => void;
disabled?: boolean;
};
/**
* Row of pill buttons shown in the composer while an attachment is pending.
* Clicking a pill immediately calls onSend with the canned text.
*/
export function ChatQuickReplies({
onSend,
disabled = false,
}: ChatQuickRepliesProps) {
const { t } = useTranslation(["views/chat"]);
return (
<div className="flex w-full flex-wrap gap-2">
{REPLIES.map((reply) => (
<Button
key={reply.labelKey}
variant="outline"
size="sm"
className="h-7 rounded-full px-3 text-xs"
disabled={disabled}
onClick={() => onSend(t(reply.textKey))}
>
{t(reply.labelKey)}
</Button>
))}
</div>
);
}
@@ -56,6 +56,11 @@ const record: SectionConfigOverrides = {
},
camera: {
restartRequired: [],
hiddenFields: [
"enabled_in_config",
"sync_recordings",
"export.max_concurrent",
],
},
};
@@ -89,6 +89,7 @@ export function CameraGroupSelector({ className }: CameraGroupSelectorProps) {
const { t } = useTranslation(["components/camera"]);
const { data: config } = useSWR<FrigateConfig>("config");
const allowedCameras = useAllowedCameras();
const hasFullCameraAccess = useHasFullCameraAccess();
const isAdmin = useIsAdmin();
// tooltip
@@ -125,7 +126,7 @@ export function CameraGroupSelector({ className }: CameraGroupSelectorProps) {
const allGroups = Object.entries(config.camera_groups);
// If custom role, filter out groups where user has no accessible cameras
if (!isAdmin) {
if (!hasFullCameraAccess) {
return allGroups
.filter(([, groupConfig]) => {
// Check if user has access to at least one camera in this group
@@ -137,7 +138,7 @@ export function CameraGroupSelector({ className }: CameraGroupSelectorProps) {
}
return allGroups.sort((a, b) => a[1].order - b[1].order);
}, [config, allowedCameras, isAdmin]);
}, [config, allowedCameras, hasFullCameraAccess]);
// add group
@@ -0,0 +1,384 @@
import { useCallback, useMemo, useState } from "react";
import axios from "axios";
import { Button, buttonVariants } from "../ui/button";
import { isDesktop } from "react-device-detect";
import { HiTrash } from "react-icons/hi";
import { LuFolderPlus, LuFolderX } from "react-icons/lu";
import { Export, ExportCase } from "@/types/export";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "../ui/alert-dialog";
import { Label } from "../ui/label";
import { Switch } from "../ui/switch";
import useKeyboardListener from "@/hooks/use-keyboard-listener";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { useIsAdmin } from "@/hooks/use-is-admin";
import OptionAndInputDialog from "../overlay/dialog/OptionAndInputDialog";
type ExportActionGroupProps = {
selectedExports: Export[];
setSelectedExports: (exports: Export[]) => void;
context: "uncategorized" | "case";
cases?: ExportCase[];
currentCaseId?: string;
mutate: () => void;
};
export default function ExportActionGroup({
selectedExports,
setSelectedExports,
context,
cases,
currentCaseId,
mutate,
}: ExportActionGroupProps) {
const { t } = useTranslation(["views/exports", "common"]);
const isAdmin = useIsAdmin();
const onClearSelected = useCallback(() => {
setSelectedExports([]);
}, [setSelectedExports]);
// ── Delete ──────────────────────────────────────────────────────
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();
}
})
.catch((error) => {
const errorMessage =
error.response?.data?.message ||
error.response?.data?.detail ||
"Unknown error";
toast.error(t("bulkToast.error.deleteFailed", { errorMessage }), {
position: "top-center",
});
});
}, [selectedExports, setSelectedExports, mutate, t]);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [bypassDialog, setBypassDialog] = useState(false);
useKeyboardListener(["Shift"], (_, modifiers) => {
setBypassDialog(modifiers.shift);
return false;
});
const handleDelete = useCallback(() => {
if (bypassDialog) {
onDelete();
} else {
setDeleteDialogOpen(true);
}
}, [bypassDialog, onDelete]);
// ── Remove from case ────────────────────────────────────────────
const [removeDialogOpen, setRemoveDialogOpen] = useState(false);
const [deleteExportsOnRemove, setDeleteExportsOnRemove] = useState(false);
const handleRemoveFromCase = useCallback(() => {
const ids = selectedExports.map((e) => e.id);
const request = deleteExportsOnRemove
? axios.post("exports/delete", { ids })
: axios.post("exports/reassign", { ids, export_case_id: null });
request
.then((resp) => {
if (resp.status === 200) {
toast.success(t("bulkToast.success.remove"), {
position: "top-center",
});
setSelectedExports([]);
mutate();
setRemoveDialogOpen(false);
setDeleteExportsOnRemove(false);
}
})
.catch((error) => {
const errorMessage =
error.response?.data?.message ||
error.response?.data?.detail ||
"Unknown error";
toast.error(t("bulkToast.error.reassignFailed", { errorMessage }), {
position: "top-center",
});
});
}, [selectedExports, deleteExportsOnRemove, setSelectedExports, mutate, t]);
// ── Case picker ─────────────────────────────────────────────────
const [casePickerOpen, setCasePickerOpen] = useState(false);
const caseOptions = useMemo(
() => [
...(cases ?? [])
.filter((c) => c.id !== currentCaseId)
.map((c) => ({
value: c.id,
label: c.name,
}))
.sort((a, b) => a.label.localeCompare(b.label)),
{
value: "new",
label: t("caseDialog.newCaseOption"),
},
],
[cases, currentCaseId, t],
);
const handleAssignToCase = useCallback(
async (caseId: string) => {
const ids = selectedExports.map((e) => e.id);
try {
await axios.post("exports/reassign", {
ids,
export_case_id: caseId,
});
toast.success(t("bulkToast.success.reassign"), {
position: "top-center",
});
setSelectedExports([]);
mutate();
} catch (error) {
const apiError = error as {
response?: { data?: { message?: string; detail?: string } };
};
const errorMessage =
apiError.response?.data?.message ||
apiError.response?.data?.detail ||
"Unknown error";
toast.error(t("bulkToast.error.reassignFailed", { errorMessage }), {
position: "top-center",
});
throw error;
}
},
[selectedExports, setSelectedExports, mutate, t],
);
const handleCreateNewCase = useCallback(
async (name: string, description: string) => {
const ids = selectedExports.map((e) => e.id);
try {
const createResp = await axios.post("cases", { name, description });
const newCaseId: string | undefined = createResp.data?.id;
if (newCaseId) {
await axios.post("exports/reassign", {
ids,
export_case_id: newCaseId,
});
}
toast.success(t("bulkToast.success.reassign"), {
position: "top-center",
});
setSelectedExports([]);
mutate();
} catch (error) {
const apiError = error as {
response?: { data?: { message?: string; detail?: string } };
};
const errorMessage =
apiError.response?.data?.message ||
apiError.response?.data?.detail ||
"Unknown error";
toast.error(t("bulkToast.error.reassignFailed", { errorMessage }), {
position: "top-center",
});
throw error;
}
},
[selectedExports, setSelectedExports, mutate, t],
);
return (
<>
{/* Delete confirmation dialog */}
<AlertDialog
open={deleteDialogOpen}
onOpenChange={() => setDeleteDialogOpen(!deleteDialogOpen)}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t("bulkDelete.title")}</AlertDialogTitle>
</AlertDialogHeader>
<AlertDialogDescription>
{t("bulkDelete.desc", { count: selectedExports.length })}
</AlertDialogDescription>
<AlertDialogFooter>
<AlertDialogCancel>
{t("button.cancel", { ns: "common" })}
</AlertDialogCancel>
<AlertDialogAction
className={buttonVariants({ variant: "destructive" })}
onClick={onDelete}
>
{t("button.delete", { ns: "common" })}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Remove from case dialog */}
{context === "case" && (
<AlertDialog
open={removeDialogOpen}
onOpenChange={(open) => {
if (!open) {
setRemoveDialogOpen(false);
setDeleteExportsOnRemove(false);
}
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t("bulkRemoveFromCase.title")}
</AlertDialogTitle>
<AlertDialogDescription>
{t("bulkRemoveFromCase.desc", {
count: selectedExports.length,
})}{" "}
{deleteExportsOnRemove
? t("bulkRemoveFromCase.descDeleteExports")
: t("bulkRemoveFromCase.descKeepExports")}
</AlertDialogDescription>
</AlertDialogHeader>
<div className="flex items-center justify-start gap-6">
<Label
htmlFor="bulk-delete-exports-switch"
className="cursor-pointer text-sm"
>
{t("bulkRemoveFromCase.deleteExports")}
</Label>
<Switch
id="bulk-delete-exports-switch"
checked={deleteExportsOnRemove}
onCheckedChange={setDeleteExportsOnRemove}
/>
</div>
<AlertDialogFooter>
<AlertDialogCancel>
{t("button.cancel", { ns: "common" })}
</AlertDialogCancel>
<AlertDialogAction
className={buttonVariants({ variant: "destructive" })}
onClick={handleRemoveFromCase}
>
{t("button.delete", { ns: "common" })}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)}
{/* Case picker dialog */}
<OptionAndInputDialog
open={casePickerOpen}
title={t("caseDialog.title")}
description={t("caseDialog.description")}
setOpen={setCasePickerOpen}
options={caseOptions}
nameLabel={t("caseDialog.nameLabel")}
descriptionLabel={t("caseDialog.descriptionLabel")}
initialValue={caseOptions[0]?.value}
newValueKey="new"
onSave={handleAssignToCase}
onCreateNew={handleCreateNewCase}
/>
{/* Action bar */}
<div className="flex w-full items-center justify-end gap-2">
<div className="mx-1 flex items-center justify-center text-sm text-muted-foreground">
<div className="p-1">
{t("selected", { count: selectedExports.length })}
</div>
<div className="p-1">{"|"}</div>
<div
className="cursor-pointer p-2 text-primary hover:rounded-lg hover:bg-secondary"
onClick={onClearSelected}
>
{t("button.unselect", { ns: "common" })}
</div>
</div>
{isAdmin && (
<div className="flex items-center gap-1 md:gap-2">
{/* Add to Case / Move to Case */}
<Button
className="flex items-center gap-2 p-2"
aria-label={
context === "case"
? t("bulkActions.moveToCase")
: t("bulkActions.addToCase")
}
size="sm"
onClick={() => setCasePickerOpen(true)}
>
<LuFolderPlus className="text-secondary-foreground" />
{isDesktop && (
<div className="text-primary">
{context === "case"
? t("bulkActions.moveToCase")
: t("bulkActions.addToCase")}
</div>
)}
</Button>
{/* Remove from Case (case context only) */}
{context === "case" && (
<Button
className="flex items-center gap-2 p-2"
aria-label={t("bulkActions.removeFromCase")}
size="sm"
onClick={() => setRemoveDialogOpen(true)}
>
<LuFolderX className="text-secondary-foreground" />
{isDesktop && (
<div className="text-primary">
{t("bulkActions.removeFromCase")}
</div>
)}
</Button>
)}
{/* Delete */}
<Button
className="flex items-center gap-2 p-2"
aria-label={t("button.delete", { ns: "common" })}
size="sm"
onClick={handleDelete}
>
<HiTrash className="text-secondary-foreground" />
{isDesktop && (
<div className="text-primary">
{bypassDialog
? t("bulkActions.deleteNow")
: t("bulkActions.delete")}
</div>
)}
</Button>
</div>
)}
</div>
</>
);
}
@@ -6,6 +6,7 @@ import { isDesktop } from "react-device-detect";
import { FaCompactDisc } from "react-icons/fa";
import { HiTrash } from "react-icons/hi";
import { ReviewSegment } from "@/types/review";
import { MAX_BATCH_EXPORT_ITEMS } from "@/types/export";
import {
AlertDialog,
AlertDialogAction,
@@ -20,6 +21,7 @@ import useKeyboardListener from "@/hooks/use-keyboard-listener";
import { Trans, useTranslation } from "react-i18next";
import { toast } from "sonner";
import { useIsAdmin } from "@/hooks/use-is-admin";
import MultiExportDialog from "../overlay/MultiExportDialog";
type ReviewActionGroupProps = {
selectedReviews: ReviewSegment[];
@@ -164,6 +166,29 @@ export default function ReviewActionGroup({
)}
</Button>
)}
{selectedReviews.length >= 2 &&
selectedReviews.length <= MAX_BATCH_EXPORT_ITEMS && (
<MultiExportDialog
selectedReviews={selectedReviews}
onStarted={() => {
onClearSelected();
pullLatestData();
}}
>
<Button
className="flex items-center gap-2 p-2"
aria-label={t("recording.button.export")}
size="sm"
>
<FaCompactDisc className="text-secondary-foreground" />
{isDesktop && (
<div className="text-primary">
{t("recording.button.export")}
</div>
)}
</Button>
</MultiExportDialog>
)}
<Button
className="flex items-center gap-2 p-2"
aria-label={
File diff suppressed because it is too large Load Diff
@@ -4,7 +4,7 @@ import { Button } from "../ui/button";
import { FaArrowDown, FaCalendarAlt, FaCog, FaFilter } from "react-icons/fa";
import { LuBug, LuShare2 } from "react-icons/lu";
import { TimeRange } from "@/types/timeline";
import { ExportContent, ExportPreviewDialog } from "./ExportDialog";
import { ExportContent, ExportPreviewDialog, ExportTab } from "./ExportDialog";
import {
DebugReplayContent,
SaveDebugReplayOverlay,
@@ -26,6 +26,7 @@ import SaveExportOverlay from "./SaveExportOverlay";
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 =
@@ -109,6 +110,7 @@ export default function MobileReviewSettingsDrawer({
]);
const navigate = useNavigate();
const [drawerMode, setDrawerMode] = useState<DrawerMode>("none");
const [exportTab, setExportTab] = useState<ExportTab>("export");
const [selectedReplayOption, setSelectedReplayOption] = useState<
"1" | "5" | "custom" | "timeline"
>("1");
@@ -129,67 +131,112 @@ export default function MobileReviewSettingsDrawer({
const [selectedCaseId, setSelectedCaseId] = useState<string | undefined>(
undefined,
);
const onStartExport = useCallback(() => {
const [singleNewCaseName, setSingleNewCaseName] = useState("");
const [singleNewCaseDescription, setSingleNewCaseDescription] = useState("");
const [isStartingExport, setIsStartingExport] = useState(false);
const onStartExport = useCallback(async () => {
if (isStartingExport) {
return false;
}
if (!range) {
toast.error(t("toast.error.noValidTimeSelected"), {
position: "top-center",
});
return;
toast.error(
t("export.toast.error.noVaildTimeSelected", {
ns: "components/dialog",
}),
{
position: "top-center",
},
);
return false;
}
if (range.before < range.after) {
toast.error(t("toast.error.endTimeMustAfterStartTime"), {
position: "top-center",
});
return;
toast.error(
t("export.toast.error.endTimeMustAfterStartTime", {
ns: "components/dialog",
}),
{
position: "top-center",
},
);
return false;
}
axios
.post(
setIsStartingExport(true);
try {
let exportCaseId: string | undefined = selectedCaseId;
if (selectedCaseId === "new" && singleNewCaseName.trim().length > 0) {
const caseResp = await axios.post("cases", {
name: singleNewCaseName.trim(),
description: singleNewCaseDescription.trim() || undefined,
});
exportCaseId = caseResp.data?.id;
} else if (selectedCaseId === "new" || selectedCaseId === "none") {
exportCaseId = undefined;
}
await axios.post<StartExportResponse>(
`export/${camera}/start/${Math.round(range.after)}/end/${Math.round(range.before)}`,
{
playback: "realtime",
source: "recordings",
name,
export_case_id: selectedCaseId || undefined,
export_case_id: exportCaseId,
},
)
.then((response) => {
if (response.status == 200) {
toast.success(
t("export.toast.success", { ns: "components/dialog" }),
{
position: "top-center",
action: (
<a href="/export" target="_blank" rel="noopener noreferrer">
<Button>
{t("export.toast.view", { ns: "components/dialog" })}
</Button>
</a>
),
},
);
setName("");
setSelectedCaseId(undefined);
setRange(undefined);
setMode("none");
}
})
.catch((error) => {
const errorMessage =
error.response?.data?.message ||
error.response?.data?.detail ||
"Unknown error";
toast.error(
t("export.toast.error.failed", {
ns: "components/dialog",
errorMessage,
}),
{
position: "top-center",
},
);
);
toast.success(t("export.toast.queued", { ns: "components/dialog" }), {
position: "top-center",
action: (
<a href="/export" target="_blank" rel="noopener noreferrer">
<Button>
{t("export.toast.view", { ns: "components/dialog" })}
</Button>
</a>
),
});
}, [camera, name, range, selectedCaseId, setRange, setName, setMode, t]);
setName("");
setSelectedCaseId(undefined);
setSingleNewCaseName("");
setSingleNewCaseDescription("");
setRange(undefined);
setMode("none");
return true;
} catch (error) {
const apiError = error as {
response?: { data?: { message?: string; detail?: string } };
};
const errorMessage =
apiError.response?.data?.message ||
apiError.response?.data?.detail ||
"Unknown error";
toast.error(
t("export.toast.error.failed", {
ns: "components/dialog",
error: errorMessage,
}),
{
position: "top-center",
},
);
return false;
} finally {
setIsStartingExport(false);
}
}, [
camera,
isStartingExport,
name,
range,
selectedCaseId,
singleNewCaseDescription,
singleNewCaseName,
setRange,
setMode,
t,
]);
const onStartDebugReplay = useCallback(async () => {
if (
@@ -283,6 +330,7 @@ export default function MobileReviewSettingsDrawer({
className="flex w-full items-center justify-center gap-2"
aria-label={t("export")}
onClick={() => {
setExportTab("export");
setDrawerMode("export");
setMode("select");
}}
@@ -368,14 +416,21 @@ export default function MobileReviewSettingsDrawer({
range={range}
name={name}
selectedCaseId={selectedCaseId}
singleNewCaseName={singleNewCaseName}
singleNewCaseDescription={singleNewCaseDescription}
activeTab={exportTab}
isStartingExport={isStartingExport}
onStartExport={onStartExport}
setActiveTab={setExportTab}
setName={setName}
setSelectedCaseId={setSelectedCaseId}
setSingleNewCaseName={setSingleNewCaseName}
setSingleNewCaseDescription={setSingleNewCaseDescription}
setRange={setRange}
setMode={(mode) => {
setMode(mode);
if (mode == "timeline") {
if (mode == "timeline" || mode == "timeline_multi") {
setDrawerMode("none");
}
}}
@@ -383,6 +438,9 @@ export default function MobileReviewSettingsDrawer({
setMode("none");
setRange(undefined);
setSelectedCaseId(undefined);
setSingleNewCaseName("");
setSingleNewCaseDescription("");
setExportTab("export");
setDrawerMode("select");
}}
/>
@@ -542,9 +600,29 @@ export default function MobileReviewSettingsDrawer({
<>
<SaveExportOverlay
className="pointer-events-none absolute left-1/2 top-8 z-50 -translate-x-1/2"
show={mode == "timeline"}
onSave={() => onStartExport()}
onCancel={() => setMode("none")}
show={mode == "timeline" || mode == "timeline_multi"}
hidePreview={mode == "timeline_multi"}
isSaving={isStartingExport}
saveLabel={
mode == "timeline_multi"
? t("export.fromTimeline.useThisRange", { ns: "components/dialog" })
: undefined
}
onSave={() => {
if (mode == "timeline_multi") {
setExportTab("multi");
setDrawerMode("export");
setMode("select");
return;
}
void onStartExport();
}}
onCancel={() => {
setExportTab("export");
setRange(undefined);
setMode("none");
}}
onPreview={() => setShowExportPreview(true)}
/>
<SaveDebugReplayOverlay
@@ -0,0 +1,405 @@
import { useCallback, useMemo, useState } from "react";
import { isDesktop } from "react-device-detect";
import axios from "axios";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import useSWR from "swr";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "../ui/dialog";
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
} from "../ui/drawer";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Label } from "../ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectSeparator,
SelectTrigger,
SelectValue,
} from "../ui/select";
import { Textarea } from "../ui/textarea";
import {
BatchExportBody,
BatchExportResponse,
BatchExportResult,
ExportCase,
} from "@/types/export";
import { FrigateConfig } from "@/types/frigateConfig";
import { REVIEW_PADDING, ReviewSegment } from "@/types/review";
import { resolveCameraName } from "@/hooks/use-camera-friendly-name";
import { useDateLocale } from "@/hooks/use-date-locale";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { formatUnixTimestampToDateTime } from "@/utils/dateUtil";
type MultiExportDialogProps = {
selectedReviews: ReviewSegment[];
onStarted: () => void;
children: React.ReactNode;
};
const NONE_CASE_OPTION = "none";
const NEW_CASE_OPTION = "new";
export default function MultiExportDialog({
selectedReviews,
onStarted,
children,
}: MultiExportDialogProps) {
const { t } = useTranslation(["components/dialog", "common"]);
const locale = useDateLocale();
const navigate = useNavigate();
const isAdmin = useIsAdmin();
const { data: config } = useSWR<FrigateConfig>("config");
// Only admins can attach exports to an existing case (enforced server-side
// by POST /exports/batch). Skip fetching the case list entirely for
// non-admins — they can only ever use the "Create new case" branch.
const { data: cases } = useSWR<ExportCase[]>(isAdmin ? "cases" : null);
const [open, setOpen] = useState(false);
const [caseSelection, setCaseSelection] = useState<string>(NONE_CASE_OPTION);
const [newCaseName, setNewCaseName] = useState("");
const [newCaseDescription, setNewCaseDescription] = useState("");
const [isExporting, setIsExporting] = useState(false);
const count = selectedReviews.length;
// Resolve a failed batch result back to a human-readable label via the
// client-provided review id when available. Falls back to item_index and
// finally camera name for defensive compatibility.
const formatFailureLabel = useCallback(
(result: BatchExportResult): string => {
const cameraName = resolveCameraName(config, result.camera);
if (result.client_item_id) {
const review = selectedReviews.find(
(item) => item.id === result.client_item_id,
);
if (review) {
const time = formatUnixTimestampToDateTime(review.start_time, {
date_style: "short",
time_style: "short",
locale,
});
return `${cameraName} • ${time}`;
}
}
if (
typeof result.item_index === "number" &&
result.item_index >= 0 &&
result.item_index < selectedReviews.length
) {
const review = selectedReviews[result.item_index];
const time = formatUnixTimestampToDateTime(review.start_time, {
date_style: "short",
time_style: "short",
locale,
});
return `${cameraName} • ${time}`;
}
return cameraName;
},
[config, locale, selectedReviews],
);
const defaultCaseName = useMemo(() => {
const formattedDate = formatUnixTimestampToDateTime(Date.now() / 1000, {
date_style: "medium",
time_style: "short",
locale,
});
return t("export.multi.caseNamePlaceholder", {
ns: "components/dialog",
date: formattedDate,
});
}, [t, locale]);
const resetState = useCallback(() => {
setCaseSelection(NONE_CASE_OPTION);
setNewCaseName("");
setNewCaseDescription("");
setIsExporting(false);
}, []);
const handleOpenChange = useCallback(
(next: boolean) => {
if (!next) {
resetState();
} else {
// Freshly reset each time so the default name reflects "now"
setCaseSelection(NONE_CASE_OPTION);
setNewCaseName(defaultCaseName);
setNewCaseDescription("");
setIsExporting(false);
}
setOpen(next);
},
[defaultCaseName, resetState],
);
const existingCases = useMemo(() => {
return (cases ?? []).slice().sort((a, b) => a.name.localeCompare(b.name));
}, [cases]);
const isNewCase = caseSelection === NEW_CASE_OPTION;
const canSubmit = useMemo(() => {
if (isExporting) return false;
if (count === 0) return false;
if (!isAdmin) return true;
if (isNewCase) {
return newCaseName.trim().length > 0;
}
return caseSelection.length > 0;
}, [caseSelection, count, isAdmin, isExporting, isNewCase, newCaseName]);
const handleSubmit = useCallback(async () => {
if (!canSubmit) return;
const items = selectedReviews.map((review) => ({
camera: review.camera,
start_time: review.start_time - REVIEW_PADDING,
end_time: (review.end_time ?? Date.now() / 1000) + REVIEW_PADDING,
image_path: review.thumb_path || undefined,
client_item_id: review.id,
}));
const payload: BatchExportBody = { items };
if (isAdmin && caseSelection !== NONE_CASE_OPTION) {
if (isNewCase) {
payload.new_case_name = newCaseName.trim();
payload.new_case_description = newCaseDescription.trim() || undefined;
} else {
payload.export_case_id = caseSelection;
}
}
setIsExporting(true);
try {
const response = await axios.post<BatchExportResponse>(
"exports/batch",
payload,
);
const results = response.data.results ?? [];
const successful = results.filter((r) => r.success);
const failed = results.filter((r) => !r.success);
if (successful.length > 0 && failed.length === 0) {
toast.success(
t(
isAdmin
? "export.multi.toast.started"
: "export.multi.toast.startedNoCase",
{
ns: "components/dialog",
count: successful.length,
},
),
{ position: "top-center" },
);
} else if (successful.length > 0 && failed.length > 0) {
// Resolve each failure to its review via item_index so same-camera
// items are disambiguated by time. Falls back to camera-only if the
// server didn't populate item_index.
const failedLabels = failed.map(formatFailureLabel).join(", ");
toast.success(
t("export.multi.toast.partial", {
ns: "components/dialog",
successful: successful.length,
total: results.length,
failedItems: failedLabels,
}),
{ position: "top-center" },
);
} else {
const failedLabels = failed.map(formatFailureLabel).join(", ");
toast.error(
t("export.multi.toast.failed", {
ns: "components/dialog",
total: results.length,
failedItems: failedLabels,
}),
{ position: "top-center" },
);
}
if (successful.length > 0) {
onStarted();
setOpen(false);
resetState();
if (response.data.export_case_id) {
navigate(`/export?caseId=${response.data.export_case_id}`);
}
}
} catch (error) {
const apiError = error as {
response?: { data?: { message?: string; detail?: string } };
};
const errorMessage =
apiError.response?.data?.message ||
apiError.response?.data?.detail ||
"Unknown error";
toast.error(
t("export.toast.error.failed", {
ns: "components/dialog",
error: errorMessage,
}),
{ position: "top-center" },
);
} finally {
setIsExporting(false);
}
}, [
canSubmit,
caseSelection,
formatFailureLabel,
isAdmin,
isNewCase,
navigate,
newCaseDescription,
newCaseName,
onStarted,
resetState,
selectedReviews,
t,
]);
// New-case inputs: rendered below the Select when caseSelection === "new",
// or rendered standalone for non-admins (who never see the Select since
// they cannot attach to an existing case).
const newCaseInputs = (
<div className="space-y-2 pt-1">
<Input
className="text-md"
placeholder={t("export.case.newCaseNamePlaceholder")}
value={newCaseName}
onChange={(event) => setNewCaseName(event.target.value)}
maxLength={100}
autoFocus={isDesktop}
/>
<Textarea
className="text-md"
placeholder={t("export.case.newCaseDescriptionPlaceholder")}
value={newCaseDescription}
onChange={(event) => setNewCaseDescription(event.target.value)}
rows={2}
/>
</div>
);
const body = (
<div className="flex flex-col gap-4">
{isAdmin && (
<div className="space-y-2">
<Label className="text-sm text-secondary-foreground">
{t("export.case.label")}
</Label>
<Select
value={caseSelection}
onValueChange={(value) => setCaseSelection(value)}
>
<SelectTrigger>
<SelectValue placeholder={t("export.case.placeholder")} />
</SelectTrigger>
<SelectContent>
<SelectItem value={NONE_CASE_OPTION}>
{t("label.none", { ns: "common" })}
</SelectItem>
{existingCases.map((caseItem) => (
<SelectItem key={caseItem.id} value={caseItem.id}>
{caseItem.name}
</SelectItem>
))}
<SelectSeparator />
<SelectItem value={NEW_CASE_OPTION}>
{t("export.case.newCaseOption")}
</SelectItem>
</SelectContent>
</Select>
{isNewCase && newCaseInputs}
</div>
)}
</div>
);
const footer = (
<>
<Button
variant="outline"
onClick={() => handleOpenChange(false)}
disabled={isExporting}
>
{t("button.cancel", { ns: "common" })}
</Button>
<Button
variant="select"
onClick={handleSubmit}
disabled={!canSubmit}
aria-label={t("export.multi.exportButton", { count: count })}
>
{isExporting
? t("export.multi.exportingButton")
: t("export.multi.exportButton", { count: count })}
</Button>
</>
);
if (isDesktop) {
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>{children}</DialogTrigger>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>
{t("export.multi.title", { count: count })}
</DialogTitle>
<DialogDescription>
{isAdmin
? t("export.multi.description")
: t("export.multi.descriptionNoCase")}
</DialogDescription>
</DialogHeader>
{body}
<DialogFooter className="gap-2">{footer}</DialogFooter>
</DialogContent>
</Dialog>
);
}
return (
<Drawer open={open} onOpenChange={handleOpenChange}>
<DrawerTrigger asChild>{children}</DrawerTrigger>
<DrawerContent className="px-4 pb-6">
<DrawerHeader className="px-0">
<DrawerTitle>{t("export.multi.title", { count: count })}</DrawerTitle>
<DrawerDescription>
{isAdmin
? t("export.multi.description")
: t("export.multi.descriptionNoCase")}
</DrawerDescription>
</DrawerHeader>
{body}
<div className="mt-4 flex flex-col-reverse gap-2">{footer}</div>
</DrawerContent>
</Drawer>
);
}
@@ -7,6 +7,9 @@ import { useTranslation } from "react-i18next";
type SaveExportOverlayProps = {
className: string;
show: boolean;
hidePreview?: boolean;
saveLabel?: string;
isSaving?: boolean;
onPreview: () => void;
onSave: () => void;
onCancel: () => void;
@@ -14,6 +17,9 @@ type SaveExportOverlayProps = {
export default function SaveExportOverlay({
className,
show,
hidePreview = false,
saveLabel,
isSaving = false,
onPreview,
onSave,
onCancel,
@@ -32,29 +38,36 @@ export default function SaveExportOverlay({
className="flex items-center gap-1 text-primary"
aria-label={t("button.cancel", { ns: "common" })}
size="sm"
disabled={isSaving}
onClick={onCancel}
>
<LuX />
{t("button.cancel", { ns: "common" })}
</Button>
{!hidePreview && (
<Button
className="flex items-center gap-1"
aria-label={t("export.fromTimeline.previewExport")}
size="sm"
disabled={isSaving}
onClick={onPreview}
>
<LuVideo />
{t("export.fromTimeline.previewExport")}
</Button>
)}
<Button
className="flex items-center gap-1"
aria-label={t("export.fromTimeline.previewExport")}
size="sm"
onClick={onPreview}
>
<LuVideo />
{t("export.fromTimeline.previewExport")}
</Button>
<Button
className="flex items-center gap-1"
aria-label={t("export.fromTimeline.saveExport")}
aria-label={saveLabel || t("export.fromTimeline.saveExport")}
variant="select"
size="sm"
disabled={isSaving}
onClick={onSave}
>
<FaCompactDisc />
{t("export.fromTimeline.saveExport")}
{isSaving
? t("export.fromTimeline.queueingExport")
: saveLabel || t("export.fromTimeline.saveExport")}
</Button>
</div>
</div>
@@ -6,7 +6,7 @@ import {
ThreatLevel,
THREAT_LEVEL_LABELS,
} from "@/types/review";
import React, { useEffect, useMemo, useState } from "react";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { isDesktop } from "react-device-detect";
import { useTranslation } from "react-i18next";
import { MdAutoAwesome } from "react-icons/md";
@@ -95,11 +95,12 @@ export function GenAISummaryDialog({
const Trigger = isDesktop ? DialogTrigger : DrawerTrigger;
const Content = isDesktop ? DialogContent : DrawerContent;
const onOpenRef = useRef(onOpen);
onOpenRef.current = onOpen;
useEffect(() => {
if (onOpen) {
onOpen(open);
}
}, [open, onOpen]);
onOpenRef.current?.(open);
}, [open]);
if (!aiAnalysis) {
return null;
@@ -8,6 +8,7 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
Select,
SelectContent,
@@ -15,9 +16,10 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { cn } from "@/lib/utils";
import { isMobile } from "react-device-detect";
import { useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
type Option = {
@@ -35,8 +37,8 @@ type OptionAndInputDialogProps = {
nameLabel: string;
descriptionLabel: string;
setOpen: (open: boolean) => void;
onSave: (value: string) => void;
onCreateNew: (name: string, description: string) => void;
onSave: (value: string) => Promise<void>;
onCreateNew: (name: string, description: string) => Promise<void>;
};
export default function OptionAndInputDialog({
@@ -69,10 +71,12 @@ export default function OptionAndInputDialog({
}
}, [open, initialValue, firstOption]);
const [isLoading, setIsLoading] = useState(false);
const isNew = selectedValue === newValueKey;
const disableSave = !selectedValue || (isNew && name.trim().length === 0);
const disableSave =
!selectedValue || (isNew && name.trim().length === 0) || isLoading;
const handleSave = () => {
const handleSave = useCallback(async () => {
if (!selectedValue) {
return;
}
@@ -80,13 +84,26 @@ export default function OptionAndInputDialog({
const trimmedName = name.trim();
const trimmedDescription = descriptionValue.trim();
if (isNew) {
onCreateNew(trimmedName, trimmedDescription);
} else {
onSave(selectedValue);
setIsLoading(true);
try {
if (isNew) {
await onCreateNew(trimmedName, trimmedDescription);
} else {
await onSave(selectedValue);
}
setOpen(false);
} finally {
setIsLoading(false);
}
setOpen(false);
};
}, [
selectedValue,
name,
descriptionValue,
isNew,
onCreateNew,
onSave,
setOpen,
]);
return (
<Dialog open={open} defaultOpen={false} onOpenChange={setOpen}>
@@ -127,15 +144,21 @@ export default function OptionAndInputDialog({
<label className="text-sm font-medium text-secondary-foreground">
{nameLabel}
</label>
<Input value={name} onChange={(e) => setName(e.target.value)} />
<Input
className="text-md"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="space-y-1">
<label className="text-sm font-medium text-secondary-foreground">
{descriptionLabel}
</label>
<Input
<Textarea
className="text-md"
value={descriptionValue}
onChange={(e) => setDescriptionValue(e.target.value)}
rows={2}
/>
</div>
</div>
@@ -145,6 +168,7 @@ export default function OptionAndInputDialog({
<Button
type="button"
variant="outline"
disabled={isLoading}
onClick={() => {
setOpen(false);
}}
@@ -155,9 +179,13 @@ export default function OptionAndInputDialog({
type="button"
variant="select"
disabled={disableSave}
onClick={handleSave}
onClick={() => void handleSave()}
>
{t("button.save")}
{isLoading ? (
<ActivityIndicator className="size-4" />
) : (
t("button.save")
)}
</Button>
</DialogFooter>
</DialogContent>
+1 -1
View File
@@ -19,7 +19,7 @@ const Toaster = ({ ...props }: ToasterProps) => {
cancelButton:
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
closeButton:
"group-[.toast]:bg-secondary border-primary border-[1px]",
"group-[.toast]:bg-secondary group-[.toast]:text-primary group-[.toast]:border-primary group-[.toast]:border-[1px]",
success:
"group toast group-[.toaster]:bg-success group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
error:
+8 -3
View File
@@ -11,15 +11,20 @@ import useDeepMemo from "./use-deep-memo";
import { capitalizeAll, capitalizeFirstLetter } from "@/utils/stringUtil";
import { isReplayCamera } from "@/utils/cameraUtil";
import { useFrigateStats } from "@/api/ws";
import { useIsAdmin } from "./use-is-admin";
import { useTranslation } from "react-i18next";
export default function useStats(stats: FrigateStats | undefined) {
const { t } = useTranslation(["views/system"]);
const { data: config } = useSWR<FrigateConfig>("config");
const { data: debugReplayStatus } = useSWR("debug_replay/status", {
revalidateOnFocus: false,
});
const isAdmin = useIsAdmin();
const { data: debugReplayStatus } = useSWR(
isAdmin ? "debug_replay/status" : null,
{
revalidateOnFocus: false,
},
);
const memoizedStats = useDeepMemo(stats);
+135 -25
View File
@@ -1,17 +1,22 @@
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { FaArrowUpLong } from "react-icons/fa6";
import { FaArrowUpLong, FaStop } from "react-icons/fa6";
import { LuCircleAlert } from "react-icons/lu";
import { useTranslation } from "react-i18next";
import { useState, useCallback, useRef, useEffect } from "react";
import { useState, useCallback, useRef, useEffect, useMemo } from "react";
import axios from "axios";
import { ChatEventThumbnailsRow } from "@/components/chat/ChatEventThumbnailsRow";
import { MessageBubble } from "@/components/chat/ChatMessage";
import { ToolCallsGroup } from "@/components/chat/ToolCallsGroup";
import { ChatStartingState } from "@/components/chat/ChatStartingState";
import { ChatAttachmentChip } from "@/components/chat/ChatAttachmentChip";
import { ChatQuickReplies } from "@/components/chat/ChatQuickReplies";
import { ChatPaperclipButton } from "@/components/chat/ChatPaperclipButton";
import type { ChatMessage } from "@/types/chat";
import {
getEventIdsFromSearchObjectsToolCalls,
getFindSimilarObjectsFromToolCalls,
prependAttachment,
streamChatCompletion,
} from "@/utils/chatUtil";
@@ -21,7 +26,9 @@ export default function ChatPage() {
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [attachedEventId, setAttachedEventId] = useState<string | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const abortRef = useRef<AbortController | null>(null);
useEffect(() => {
document.title = t("documentTitle");
@@ -64,22 +71,59 @@ export default function ChatPage() {
...(axios.defaults.headers.common as Record<string, string>),
};
await streamChatCompletion(url, headers, apiMessages, {
updateMessages: (updater) => setMessages(updater),
onError: (message) => setError(message),
onDone: () => setIsLoading(false),
defaultErrorMessage: t("error"),
});
const controller = new AbortController();
abortRef.current = controller;
await streamChatCompletion(
url,
headers,
apiMessages,
{
updateMessages: (updater) => setMessages(updater),
onError: (message) => setError(message),
onDone: () => {
abortRef.current = null;
setIsLoading(false);
},
defaultErrorMessage: t("error"),
},
controller.signal,
);
},
[isLoading, t],
);
const sendMessage = useCallback(() => {
const text = input.trim();
if (!text || isLoading) return;
setInput("");
submitConversation([...messages, { role: "user", content: text }]);
}, [input, isLoading, messages, submitConversation]);
const recentEventIds = useMemo(() => {
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i];
if (msg.role !== "assistant" || !msg.toolCalls) continue;
const similar = getFindSimilarObjectsFromToolCalls(msg.toolCalls);
if (similar) return similar.results.map((e) => e.id);
const events = getEventIdsFromSearchObjectsToolCalls(msg.toolCalls);
if (events.length > 0) return events.map((e) => e.id);
}
return [];
}, [messages]);
const sendMessage = useCallback(
(textOverride?: string) => {
const text = (textOverride ?? input).trim();
if (!text || isLoading) return;
const wireText = attachedEventId
? prependAttachment(text, attachedEventId)
: text;
setInput("");
setAttachedEventId(null);
submitConversation([...messages, { role: "user", content: wireText }]);
},
[attachedEventId, input, isLoading, messages, submitConversation],
);
const stopGeneration = useCallback(() => {
abortRef.current?.abort();
abortRef.current = null;
setIsLoading(false);
}, []);
const handleEditSubmit = useCallback(
(messageIndex: number, newContent: string) => {
@@ -92,6 +136,10 @@ export default function ChatPage() {
[messages, submitConversation],
);
const handleClearAttachment = useCallback(() => {
setAttachedEventId(null);
}, []);
return (
<div className="flex size-full justify-center p-2 md:p-4">
<div className="flex size-full flex-col xl:w-[50%] 3xl:w-[35%]">
@@ -161,10 +209,27 @@ export default function ChatPage() {
{msg.role === "assistant" &&
isComplete &&
(() => {
const similar = getFindSimilarObjectsFromToolCalls(
msg.toolCalls,
);
if (similar) {
return (
<ChatEventThumbnailsRow
events={similar.results}
anchor={similar.anchor}
onAttach={setAttachedEventId}
/>
);
}
const events = getEventIdsFromSearchObjectsToolCalls(
msg.toolCalls,
);
return <ChatEventThumbnailsRow events={events} />;
return (
<ChatEventThumbnailsRow
events={events}
onAttach={setAttachedEventId}
/>
);
})()}
</div>
);
@@ -188,6 +253,11 @@ export default function ChatPage() {
sendMessage={sendMessage}
isLoading={isLoading}
placeholder={t("placeholder")}
attachedEventId={attachedEventId}
onClearAttachment={handleClearAttachment}
onAttach={setAttachedEventId}
onStop={stopGeneration}
recentEventIds={recentEventIds}
/>
)}
</div>
@@ -198,9 +268,14 @@ export default function ChatPage() {
type ChatEntryProps = {
input: string;
setInput: (value: string) => void;
sendMessage: () => void;
sendMessage: (textOverride?: string) => void;
isLoading: boolean;
placeholder: string;
attachedEventId: string | null;
onClearAttachment: () => void;
onAttach: (eventId: string) => void;
onStop: () => void;
recentEventIds: string[];
};
function ChatEntry({
@@ -209,6 +284,11 @@ function ChatEntry({
sendMessage,
isLoading,
placeholder,
attachedEventId,
onClearAttachment,
onAttach,
onStop,
recentEventIds,
}: ChatEntryProps) {
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
@@ -218,8 +298,28 @@ function ChatEntry({
};
return (
<div className="mt-2 flex w-full flex-col items-center justify-center rounded-xl bg-secondary p-3">
<div className="mt-2 flex w-full flex-col items-stretch justify-center gap-2 rounded-xl bg-secondary p-3">
{attachedEventId && (
<div className="flex items-center">
<ChatAttachmentChip
eventId={attachedEventId}
mode="composer"
onRemove={onClearAttachment}
/>
</div>
)}
{attachedEventId && (
<ChatQuickReplies
onSend={(text) => sendMessage(text)}
disabled={isLoading}
/>
)}
<div className="flex w-full flex-row items-center gap-2">
<ChatPaperclipButton
recentEventIds={recentEventIds}
onAttach={onAttach}
disabled={isLoading || attachedEventId != null}
/>
<Input
className="w-full flex-1 border-transparent bg-transparent shadow-none focus-visible:ring-0 dark:bg-transparent"
placeholder={placeholder}
@@ -228,14 +328,24 @@ function ChatEntry({
onKeyDown={handleKeyDown}
aria-busy={isLoading}
/>
<Button
variant="select"
className="size-10 shrink-0 rounded-full"
disabled={!input.trim() || isLoading}
onClick={sendMessage}
>
<FaArrowUpLong size="16" />
</Button>
{isLoading ? (
<Button
variant="destructive"
className="size-10 shrink-0 rounded-full"
onClick={onStop}
>
<FaStop className="size-3" />
</Button>
) : (
<Button
variant="select"
className="size-10 shrink-0 rounded-full"
disabled={!input.trim()}
onClick={() => sendMessage()}
>
<FaArrowUpLong className="size-4" />
</Button>
)}
</div>
</div>
);
+35 -1
View File
@@ -28,6 +28,7 @@ import {
import EventView from "@/views/events/EventView";
import MotionSearchView from "@/views/motion-search/MotionSearchView";
import { RecordingView } from "@/views/recording/RecordingView";
import { useFrigateReviews } from "@/api/ws";
import axios from "axios";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -381,6 +382,32 @@ export default function Events() {
};
}, [reviews]);
// update review items in place when a review segment ends
const reviewUpdate = useFrigateReviews();
const [endedReviews, setEndedReviews] = useState(
new Map<string, ReviewSegment>(),
);
useEffect(() => {
if (reviewUpdate?.type === "end" && reviews) {
updateSegments(
(data) => {
if (!data) return data;
return data.map((seg) =>
seg.id === reviewUpdate.after.id ? reviewUpdate.after : seg,
);
},
{ revalidate: false, populateCache: true },
);
setEndedReviews((prev) =>
new Map(prev).set(reviewUpdate.after.id, reviewUpdate.after),
);
}
// reviews is intentionally excluded - only used to guard against
// updating the SWR cache before data has loaded
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [reviewUpdate, updateSegments]);
const currentItems = useMemo(() => {
if (!reviewItems || !severity) {
return null;
@@ -407,6 +434,13 @@ export default function Events() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [severity, reviewFilter, showReviewed, reviewItems?.all.length]);
// overlay end_time updates onto currentItems without re-running
// the has_been_reviewed filter, so hover-reviewed items stay visible
const displayItems = useMemo(() => {
if (!currentItems || endedReviews.size === 0) return currentItems;
return currentItems.map((seg) => endedReviews.get(seg.id) ?? seg);
}, [currentItems, endedReviews]);
// review summary
const { data: reviewSummary, mutate: updateSummary } = useSWR<ReviewSummary>(
@@ -658,7 +692,7 @@ export default function Events() {
) : (
<EventView
reviewItems={reviewItems}
currentReviewItems={currentItems}
currentReviewItems={displayItems}
reviewSummary={reviewSummary}
recordingsSummary={recordingsSummary}
relevantPreviews={allPreviews}
+875 -75
View File
File diff suppressed because it is too large Load Diff
+77 -1
View File
@@ -6,7 +6,8 @@ export type Export = {
video_path: string;
thumb_path: string;
in_progress: boolean;
export_case?: string;
export_case?: string | null;
export_case_id?: string | null;
};
export type ExportCase = {
@@ -17,6 +18,81 @@ export type ExportCase = {
updated_at: number;
};
export type BatchExportBody = {
items: BatchExportItem[];
export_case_id?: string;
new_case_name?: string;
new_case_description?: string;
};
export const MAX_BATCH_EXPORT_ITEMS = 50;
export type BatchExportItem = {
camera: string;
start_time: number;
end_time: number;
image_path?: string;
friendly_name?: string;
client_item_id?: string;
};
export type BatchExportResult = {
camera: string;
export_id?: string | null;
success: boolean;
status?: string | null;
error?: string | null;
item_index?: number | null;
client_item_id?: string | null;
};
export type BatchExportResponse = {
export_case_id?: string | null;
export_ids: string[];
results: BatchExportResult[];
};
export type StartExportResponse = {
success: boolean;
message: string;
export_id?: string | null;
status?: string | null;
};
export type ExportJob = {
id: string;
job_type: string;
status: string;
camera: string;
name?: string | null;
export_case_id?: string | null;
request_start_time: number;
request_end_time: number;
start_time?: number | null;
end_time?: number | null;
error_message?: string | null;
results?: {
export_id?: string;
export_case_id?: string | null;
video_path?: string;
thumb_path?: string;
} | null;
};
export type CameraActivitySegment = {
/** Fractional start position within the time range, 0-1 inclusive. */
start: number;
/** Fractional end position within the time range, 0-1 inclusive. */
end: number;
};
export type CameraActivity = {
camera: string;
count: number;
hasDetections: boolean;
segments: CameraActivitySegment[];
};
export type DeleteClipType = {
file: string;
exportName: string;
+1 -1
View File
@@ -2,7 +2,7 @@
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type FilterType = { [searchKey: string]: any };
export type ExportMode = "select" | "timeline" | "none";
export type ExportMode = "select" | "timeline" | "timeline_multi" | "none";
export type FilterList = {
labels?: string[];
+80 -5
View File
@@ -25,6 +25,7 @@ export async function streamChatCompletion(
headers: Record<string, string>,
apiMessages: { role: string; content: string }[],
callbacks: StreamChatCallbacks,
signal?: AbortSignal,
): Promise<void> {
const {
updateMessages,
@@ -38,6 +39,7 @@ export async function streamChatCompletion(
method: "POST",
headers,
body: JSON.stringify({ messages: apiMessages, stream: true }),
signal,
});
if (!res.ok) {
@@ -152,11 +154,15 @@ export async function streamChatCompletion(
return next;
});
}
} catch {
onError(defaultErrorMessage);
updateMessages((prev) =>
prev.filter((m) => !(m.role === "assistant" && m.content === "")),
);
} catch (err) {
if (err instanceof DOMException && err.name === "AbortError") {
// User stopped generation — not an error
} else {
onError(defaultErrorMessage);
updateMessages((prev) =>
prev.filter((m) => !(m.role === "assistant" && m.content === "")),
);
}
} finally {
onDone();
}
@@ -191,3 +197,72 @@ export function getEventIdsFromSearchObjectsToolCalls(
}
return results;
}
const ATTACHED_EVENT_MARKER = /^\[attached_event:([A-Za-z0-9._-]+)\]\s*\n?/;
export function parseAttachedEvent(content: string): {
eventId: string | null;
body: string;
} {
if (!content) return { eventId: null, body: content };
const match = content.match(ATTACHED_EVENT_MARKER);
if (!match) return { eventId: null, body: content };
const body = content.slice(match[0].length).replace(/^\n+/, "");
return { eventId: match[1], body };
}
export function prependAttachment(body: string, eventId: string): string {
return `[attached_event:${eventId}]\n\n${body}`;
}
export type FindSimilarObjectsResult = {
anchor: { id: string } | null;
results: { id: string; score?: number }[];
};
/**
* Parse find_similar_objects tool call response(s) into anchor + ranked results.
* Returns null if no find_similar_objects call is present so the caller can
* decide whether to render.
*/
export function getFindSimilarObjectsFromToolCalls(
toolCalls: ToolCall[] | undefined,
): FindSimilarObjectsResult | null {
if (!toolCalls?.length) return null;
for (const tc of toolCalls) {
if (tc.name !== "find_similar_objects" || !tc.response?.trim()) continue;
try {
const parsed = JSON.parse(tc.response) as {
anchor?: { id?: unknown };
results?: unknown;
};
const anchorId =
parsed.anchor && typeof parsed.anchor.id === "string"
? parsed.anchor.id
: null;
const anchor = anchorId ? { id: anchorId } : null;
const results: { id: string; score?: number }[] = [];
if (Array.isArray(parsed.results)) {
for (const item of parsed.results) {
if (
item &&
typeof item === "object" &&
"id" in item &&
typeof (item as { id: unknown }).id === "string"
) {
const entry: { id: string; score?: number } = {
id: (item as { id: string }).id,
};
const rawScore = (item as { score?: unknown }).score;
if (typeof rawScore === "number") entry.score = rawScore;
results.push(entry);
}
}
}
return { anchor, results };
} catch {
// ignore parse errors
}
}
return null;
}
@@ -270,7 +270,10 @@ export default function MotionSearchView({
);
useEffect(() => {
if (exportMode !== "timeline" || exportRange) {
if (
(exportMode !== "timeline" && exportMode !== "timeline_multi") ||
exportRange
) {
return;
}
@@ -955,9 +958,25 @@ export default function MotionSearchView({
<SaveExportOverlay
className="pointer-events-none absolute inset-x-0 top-0 z-30"
show={exportMode === "timeline" && Boolean(exportRange)}
show={
(exportMode === "timeline" || exportMode === "timeline_multi") &&
Boolean(exportRange)
}
hidePreview={exportMode === "timeline_multi"}
saveLabel={
exportMode === "timeline_multi"
? t("export.fromTimeline.useThisRange", { ns: "components/dialog" })
: undefined
}
onPreview={handleExportPreview}
onSave={handleExportSave}
onSave={() => {
if (exportMode === "timeline_multi") {
setExportMode("select");
return;
}
handleExportSave();
}}
onCancel={handleExportCancel}
/>
@@ -976,7 +995,10 @@ export default function MotionSearchView({
noRecordingRanges={noRecordings ?? []}
contentRef={contentRef}
onHandlebarDraggingChange={(dragging) => setScrubbing(dragging)}
showExportHandles={exportMode === "timeline" && Boolean(exportRange)}
showExportHandles={
(exportMode === "timeline" || exportMode === "timeline_multi") &&
Boolean(exportRange)
}
exportStartTime={exportRange?.after}
exportEndTime={exportRange?.before}
setExportStartTime={setExportStartTime}
@@ -1408,7 +1430,11 @@ export default function MotionSearchView({
onControllerReady={(controller) => {
mainControllerRef.current = controller;
}}
isScrubbing={scrubbing || exportMode == "timeline"}
isScrubbing={
scrubbing ||
exportMode == "timeline" ||
exportMode == "timeline_multi"
}
supportsFullscreen={supportsFullScreen}
setFullResolution={setFullResolution}
toggleFullscreen={toggleFullscreen}
+2 -1
View File
@@ -896,6 +896,7 @@ export function RecordingView({
isScrubbing={
scrubbing ||
exportMode == "timeline" ||
exportMode == "timeline_multi" ||
debugReplayMode == "timeline"
}
supportsFullscreen={supportsFullScreen}
@@ -974,7 +975,7 @@ export function RecordingView({
activeReviewItem={activeReviewItem}
currentTime={currentTime}
exportRange={
exportMode == "timeline"
exportMode == "timeline" || exportMode == "timeline_multi"
? exportRange
: debugReplayMode == "timeline"
? debugReplayRange
+5
View File
@@ -49,6 +49,7 @@ module.exports = {
scale4: "scale4 3s ease-in-out infinite",
"timeline-zoom-in": "timeline-zoom-in 0.3s ease-out",
"timeline-zoom-out": "timeline-zoom-out 0.3s ease-out",
"cursor-blink": "cursor-blink 1s step-end infinite",
},
aspectRatio: {
wide: "32 / 9",
@@ -189,6 +190,10 @@ module.exports = {
"50%": { transform: "translateY(0%)", opacity: "0.5" },
"100%": { transform: "translateY(0)", opacity: "1" },
},
"cursor-blink": {
"0%, 100%": { opacity: "1" },
"50%": { opacity: "0" },
},
},
screens: {
xs: "480px",