Show Frigate+ rate limits in the UI

Tell the user Frigate+ is rate limiting requests, and how long to wait
when the server said, instead of a generic failure:

- submitting a tracked object or false positive (explore and the review
  dialog), a frame from the player, or a frame from tracking details
- validating the API key in Frigate+ settings
- the Frigate+ model list in detection model settings and the setup
  wizard

The frame upload from the player also showed failures with a success
toast, and since axios rejects on error statuses it never reached that
branch at all, so failed uploads showed nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
frigate-agents[bot]
2026-11-23 23:18:29 +00:00
co-authored by Claude Opus 5.5
parent 34658593a7
commit d4f6a9fd91
11 changed files with 212 additions and 47 deletions
+33
View File
@@ -342,4 +342,37 @@ test.describe("Explore — Frigate+ submission (desktop) @high", () => {
dialog.getByRole("button", { name: "Yes", exact: true }),
).toBeVisible();
});
test("a rate limited submission says how long to wait", async ({
frigateApp,
}) => {
await frigateApp.installDefaults({ config: { plus: { enabled: true } } });
const page = frigateApp.page;
await page.route("**/api/events/*/plus", (route) =>
route.fulfill({
status: 429,
headers: { "Retry-After": "90" },
json: { success: false, retry_after: 90 },
}),
);
await frigateApp.goto("/explore?labels=person");
const firstResult = page.locator("[data-start]").first();
await expect(firstResult).toBeVisible({ timeout: 10_000 });
await firstResult.click();
const dialog = page.getByRole("dialog");
await dialog.getByRole("button", { name: "Yes", exact: true }).click();
await expect(
page.getByText(
"Frigate+ is rate limiting requests. Try again in 1 minute, 30 seconds.",
),
).toBeVisible();
// the object can be submitted again once the wait is over
await expect(
dialog.getByRole("button", { name: "Yes", exact: true }),
).toBeVisible();
});
});
@@ -459,6 +459,36 @@ test.describe("Detection models settings @high", () => {
);
});
test("a Frigate+ rate limit says how long to wait", async ({
frigateApp,
}) => {
await installRoutes(
frigateApp.page,
[
{
scene: "default",
devices: ["openvino:GPU.0"],
path: "plus://abc123",
plus: PLUS_MODEL,
},
],
true,
);
// registered last, so it takes precedence over the models route above
await frigateApp.page.route("**/api/plus/models", (route) =>
route.fulfill({
status: 429,
headers: { "Retry-After": "120" },
json: { success: false, retry_after: 120 },
}),
);
await openPage(frigateApp);
await expect(frigateApp.page.locator("#pageRoot")).toContainText(
"Frigate+ is rate limiting requests. Try again in 2 minutes.",
);
});
test("picking a Frigate+ model stays on the tab and saves a plus path", async ({
frigateApp,
}) => {
+4
View File
@@ -327,6 +327,10 @@
"copyDetails": "Copy details",
"copyFailed": "Could not copy details to clipboard"
},
"plusRateLimited": {
"retryIn": "Frigate+ is rate limiting requests. Try again in {{duration}}.",
"retryLater": "Frigate+ is rate limiting requests. Try again later."
},
"selectItem": "Select {{item}}",
"readTheDocumentation": "Read the documentation",
"information": {
@@ -14,6 +14,7 @@ import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import type { FrigateConfig } from "@/types/frigateConfig";
import { describeSupportedDetectors } from "@/utils/plusModels";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
export type FrigatePlusModel = {
id: string;
@@ -65,20 +66,26 @@ export function ModelSourcePicker({
// metadata of whatever model was saved before it
const selectedId = plusModelId(path) ?? plus?.id;
const { data: availableModels, isLoading } = useSWR<
Record<string, FrigatePlusModel>
>(plusEnabled ? "/plus/models" : null, {
fetcher: async (url) => {
const res = await axios.get(url, { withCredentials: true });
return res.data.reduce(
(obj: Record<string, FrigatePlusModel>, model: FrigatePlusModel) => {
obj[model.id] = model;
return obj;
},
{},
);
const { getRateLimitMessage } = usePlusRateLimit();
const {
data: availableModels,
error: modelsError,
isLoading,
} = useSWR<Record<string, FrigatePlusModel>>(
plusEnabled ? "/plus/models" : null,
{
fetcher: async (url) => {
const res = await axios.get(url, { withCredentials: true });
return res.data.reduce(
(obj: Record<string, FrigatePlusModel>, model: FrigatePlusModel) => {
obj[model.id] = model;
return obj;
},
{},
);
},
},
});
);
const [showIncompatible, setShowIncompatible] = useState(false);
const showIncompatibleId = useId();
@@ -101,6 +108,7 @@ export function ModelSourcePicker({
const isCompatible = (model: FrigatePlusModel) =>
!detector || model.supportedDetectors.includes(detector);
const rateLimitMessage = getRateLimitMessage(modelsError);
const allEntries = Object.entries(availableModels ?? {});
const hasIncompatible = allEntries.some(([, model]) => !isCompatible(model));
@@ -163,7 +171,8 @@ export function ModelSourcePicker({
<SelectGroup>
{entries.length === 0 ? (
<div className="px-4 py-3 text-center text-sm text-muted-foreground">
{t("frigatePlus.modelInfo.noModelsAvailable")}
{rateLimitMessage ??
t("frigatePlus.modelInfo.noModelsAvailable")}
</div>
) : (
entries.map(([id, model]) => (
@@ -184,6 +193,9 @@ export function ModelSourcePicker({
</SelectGroup>
</SelectContent>
</Select>
{rateLimitMessage && (
<p className="text-xs text-danger">{rateLimitMessage}</p>
)}
<p className="text-xs text-muted-foreground">
<Trans ns="views/settings">frigatePlus.modelInfo.modelSelect</Trans>
</p>
@@ -87,6 +87,7 @@ import TextEntryDialog from "@/components/overlay/dialog/TextEntryDialog";
import AttributeSelectDialog from "@/components/overlay/dialog/AttributeSelectDialog";
import { Trans, useTranslation } from "react-i18next";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
import { getTranslatedLabel } from "@/utils/i18n";
import { CameraNameLabel } from "@/components/camera/FriendlyNameLabel";
import { DialogPortal } from "@radix-ui/react-dialog";
@@ -699,6 +700,7 @@ function ObjectDetailsTab({
"views/faceLibrary",
"components/dialog",
]);
const { getRateLimitMessage } = usePlusRateLimit();
const apiHost = useApiHost();
const hasCustomClassificationModels = useMemo(
@@ -1286,7 +1288,7 @@ function ObjectDetailsTab({
revalidate: false,
},
);
} catch {
} catch (error) {
if (displayedIdRef.current === eventId) {
setState("reviewing");
}
@@ -1294,12 +1296,13 @@ function ObjectDetailsTab({
// the toast is not object specific, so it is always shown to avoid
// silently dropping a failed submission
toast.error(
t("explore.plus.review.toast.error", { ns: "components/dialog" }),
getRateLimitMessage(error) ??
t("explore.plus.review.toast.error", { ns: "components/dialog" }),
{ position: "top-center" },
);
}
},
[search, mutate, mapSearchResults, isEventsKey, t],
[search, mutate, mapSearchResults, isEventsKey, t, getRateLimitMessage],
);
const popoverContainerRef = useRef<HTMLDivElement | null>(null);
@@ -54,6 +54,7 @@ import { useApiHost } from "@/api";
import ImageLoadingIndicator from "@/components/indicators/ImageLoadingIndicator";
import ObjectTrackOverlay from "../ObjectTrackOverlay";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
import { VideoResolutionType } from "@/types/live";
import { VodManifest } from "@/types/playback";
@@ -934,6 +935,7 @@ function LifecycleIconRow({
annotationOffset,
}: LifecycleIconRowProps) {
const { t } = useTranslation(["views/explore", "components/player"]);
const { getRateLimitMessage } = usePlusRateLimit();
const { data: config } = useSWR<FrigateConfig>("config");
const [isOpen, setIsOpen] = useState(false);
const [showAdvancedScores, setShowAdvancedScores] = useState(false);
@@ -1251,11 +1253,12 @@ function LifecycleIconRow({
position: "top-center",
},
);
} catch {
} catch (error) {
toast.error(
t("toast.error.submitFrigatePlusFailed", {
ns: "components/player",
}),
getRateLimitMessage(error) ??
t("toast.error.submitFrigatePlusFailed", {
ns: "components/player",
}),
{
position: "top-center",
},
@@ -22,6 +22,7 @@ import { baseUrl } from "@/api/baseUrl";
import { getTranslatedLabel } from "@/utils/i18n";
import useImageLoaded from "@/hooks/use-image-loaded";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
export type FrigatePlusDialogProps = {
upload?: Event;
@@ -37,6 +38,7 @@ export function FrigatePlusDialog({
onEventUploaded,
}: FrigatePlusDialogProps) {
const { t, i18n } = useTranslation(["components/dialog"]);
const { getRateLimitMessage } = usePlusRateLimit();
type SubmissionState = "reviewing" | "uploading" | "submitted";
const [state, setState] = useState<SubmissionState>(
@@ -63,14 +65,15 @@ export function FrigatePlusDialog({
setState("submitted");
onEventUploaded();
} catch {
} catch (error) {
setState("reviewing");
toast.error(t("explore.plus.review.toast.error"), {
position: "top-center",
});
toast.error(
getRateLimitMessage(error) ?? t("explore.plus.review.toast.error"),
{ position: "top-center" },
);
}
},
[upload, onEventUploaded, t],
[upload, onEventUploaded, t, getRateLimitMessage],
);
const [imgRef, imgLoaded, onImgLoad] = useImageLoaded();
+19 -9
View File
@@ -22,6 +22,7 @@ import { ASPECT_VERTICAL_LAYOUT, RecordingPlayerError } from "@/types/record";
import { useTranslation } from "react-i18next";
import ObjectTrackOverlay from "@/components/overlay/ObjectTrackOverlay";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
// Android native hls does not seek correctly
const USE_NATIVE_HLS = false;
@@ -109,6 +110,7 @@ export default function HlsVideoPlayer({
transformedOverlay,
}: HlsVideoPlayerProps) {
const { t } = useTranslation("components/player");
const { getRateLimitMessage } = usePlusRateLimit();
const { data: config } = useSWR<FrigateConfig>("config");
const isAdmin = useIsAdmin();
@@ -525,18 +527,26 @@ export default function HlsVideoPlayer({
onUploadFrame={async () => {
const frameTime = getVideoTime();
if (frameTime && onUploadFrame) {
if (!frameTime || !onUploadFrame) {
return;
}
try {
const resp = await onUploadFrame(frameTime);
if (resp && resp.status == 200) {
toast.success(t("toast.success.submittedFrigatePlus"), {
position: "top-center",
});
} else {
toast.success(t("toast.error.submitFrigatePlusFailed"), {
position: "top-center",
});
if (resp?.status !== 200) {
throw new Error();
}
toast.success(t("toast.success.submittedFrigatePlus"), {
position: "top-center",
});
} catch (error) {
toast.error(
getRateLimitMessage(error) ??
t("toast.error.submitFrigatePlusFailed"),
{ position: "top-center" },
);
}
}}
onSnapshot={onSnapshot ? handleSnapshot : undefined}
+13 -8
View File
@@ -10,6 +10,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import { useDocDomain } from "@/hooks/use-doc-domain";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
import type { FrigateConfig } from "@/types/frigateConfig";
import type { DetectionHardware } from "@/types/hardware";
import { recommendedDetectorCount } from "@/utils/detectionHardware";
@@ -79,15 +80,16 @@ export default function SetupDetector({
const needsModel = MODEL_REQUIRED_DETECTORS.includes(selected.detector);
const { data: plusModels } = useSWR<FrigatePlusModel[]>(
plusEnabled && needsModel ? "/plus/models" : null,
{
fetcher: async (url) => {
const res = await axios.get(url, { withCredentials: true });
return res.data;
},
const { getRateLimitMessage } = usePlusRateLimit();
const { data: plusModels, error: plusModelsError } = useSWR<
FrigatePlusModel[]
>(plusEnabled && needsModel ? "/plus/models" : null, {
fetcher: async (url) => {
const res = await axios.get(url, { withCredentials: true });
return res.data;
},
);
});
const plusRateLimitMessage = getRateLimitMessage(plusModelsError);
const [plusModelId, setPlusModelId] = useState("");
const compatiblePlusModels = useMemo(
@@ -217,6 +219,9 @@ export default function SetupDetector({
<p>
{t("setupWizard.detector.modelRequired", { name: selected.name })}
</p>
{plusEnabled && plusRateLimitMessage && (
<p className="text-danger">{plusRateLimitMessage}</p>
)}
{plusEnabled ? (
<Select value={plusModelId} onValueChange={setPlusModelId}>
<SelectTrigger className="max-w-xs">
+49
View File
@@ -0,0 +1,49 @@
import axios from "axios";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { useDateLocale } from "@/hooks/use-date-locale";
import { formatSecondsToDuration } from "@/utils/dateUtil";
/**
* The wait Frigate+ asked for when a request failed because of its rate limit.
*
* @returns the seconds to wait, null when rate limited without a known wait,
* or undefined when the error is not a rate limit
*/
export function getPlusRetryAfter(error: unknown): number | null | undefined {
if (!axios.isAxiosError(error) || error.response?.status !== 429) {
return undefined;
}
const retryAfter = error.response.data?.retry_after;
return typeof retryAfter === "number" ? retryAfter : null;
}
/** Messages telling the user Frigate+ is rate limiting requests. */
export function usePlusRateLimit() {
const { t } = useTranslation(["common"]);
const dateLocale = useDateLocale();
const formatRateLimit = useCallback(
(retryAfter: number | null | undefined) =>
retryAfter && retryAfter > 0
? t("plusRateLimited.retryIn", {
ns: "common",
duration: formatSecondsToDuration(retryAfter, dateLocale),
})
: t("plusRateLimited.retryLater", { ns: "common" }),
[t, dateLocale],
);
// undefined when the error is not a rate limit, so callers can fall back
// to their own error message
const getRateLimitMessage = useCallback(
(error: unknown) => {
const retryAfter = getPlusRetryAfter(error);
return retryAfter === undefined ? undefined : formatRateLimit(retryAfter);
},
[formatRateLimit],
);
return { formatRateLimit, getRateLimitMessage };
}
@@ -20,10 +20,17 @@ import { isReplayCamera } from "@/utils/cameraUtil";
import type { SettingsPageProps } from "@/views/settings/SingleSectionPage";
import { getPrimaryModel } from "@/utils/modelUtil";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
type PlusKeyStatus = "valid" | "invalid" | "unreachable" | "not_set";
type PlusKeyStatus =
"valid" | "invalid" | "unreachable" | "rate_limited" | "not_set";
type PlusValidateResponse = { success: boolean; status: PlusKeyStatus };
type PlusValidateResponse = {
success: boolean;
status: PlusKeyStatus;
// seconds until Frigate+ accepts requests again, when rate limited
retry_after?: number | null;
};
export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
const { t } = useTranslation("views/settings");
@@ -34,6 +41,8 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
const [isValidating, setIsValidating] = useState(false);
const [keyStatus, setKeyStatus] = useState<PlusKeyStatus>();
const [retryAfter, setRetryAfter] = useState<number | null>(null);
const { formatRateLimit } = usePlusRateLimit();
const validateKey = useCallback(async () => {
setIsValidating(true);
@@ -41,6 +50,7 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
try {
const response = await axios.post<PlusValidateResponse>("plus/validate");
setKeyStatus(response.data.status);
setRetryAfter(response.data.retry_after ?? null);
} catch {
setKeyStatus("unreachable");
} finally {
@@ -124,7 +134,8 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
<div className="flex items-center gap-2">
{keyStatus === "valid" ? (
<CheckCircle2 className="size-5 shrink-0 text-green-500" />
) : keyStatus === "unreachable" ? (
) : keyStatus === "unreachable" ||
keyStatus === "rate_limited" ? (
<AlertTriangle className="size-5 shrink-0 text-yellow-500" />
) : (
<XCircle className="size-5 shrink-0 text-red-500" />
@@ -134,7 +145,9 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
? t("frigatePlus.apiKey.serverValid")
: keyStatus === "unreachable"
? t("frigatePlus.apiKey.serverUnreachable")
: t("frigatePlus.apiKey.serverInvalid")}
: keyStatus === "rate_limited"
? formatRateLimit(retryAfter)
: t("frigatePlus.apiKey.serverInvalid")}
</span>
</div>
)}