Compare commits

...
9 Commits
Author SHA1 Message Date
Josh Hawkins 7c73779075 fixes 2026-08-26 17:20:33 -05:00
Josh Hawkins df4e2bea8a docs 2026-08-26 16:57:06 -05:00
Josh Hawkins 16919e445f fix test 2026-08-26 16:38:54 -05:00
Josh Hawkins 6904de9332 button consistency 2026-08-26 16:33:32 -05:00
Josh Hawkins 15f2ba9f6c cover the account step's restart behavior 2026-08-26 12:05:52 -05:00
Josh Hawkins 2db72d956e add setup wizard account step e2e coverage 2026-08-26 12:01:57 -05:00
Josh Hawkins 9e04bc2d97 add an account step to the setup wizard 2026-08-26 12:01:57 -05:00
Josh Hawkins e0a869de25 share the setup wizard e2e helpers and mock users 2026-08-26 11:53:05 -05:00
Josh Hawkins c7a0c426ca render setup wizard steps by key 2026-08-26 11:50:44 -05:00
15 changed files with 624 additions and 118 deletions
+3 -1
View File
@@ -22,7 +22,9 @@ The following ports are available to access the Frigate web UI.
## Onboarding
On startup, an admin user and password are generated and printed in the logs. It is recommended to set a new password for the admin account after logging in for the first time under Settings > Users.
On startup, an admin user and password are generated and printed in the logs. It is recommended to set a new password for the admin account after logging in for the first time.
On a new install the [setup wizard](../guides/getting_started.md#configuring-frigate) offers this as its first step, along with creating accounts for anyone else who needs access. You can also do both at any time under <NavPath path="Settings > Users" />.
## Resetting admin password
+1 -1
View File
@@ -9,7 +9,7 @@ import NavPath from "@site/src/components/NavPath";
## Adding a camera with the Add Camera Wizard
The Add Camera Wizard is the recommended way to add a camera. Click **Add Camera** in <NavPath path="Settings > Global configuration > Camera management" />. The wizard connects to your camera, tests each stream, and writes the camera's configuration for you, including the [go2rtc](go2rtc.md) restream and the live view stream mapping, so a standard setup needs no hand-written YAML.
The Add Camera Wizard is the recommended way to add a camera. Click **Add Camera** in <NavPath path="Settings > Global configuration > Camera management" />, or use it from the [setup wizard](../guides/getting_started.md#configuring-frigate) on a new install. The wizard connects to your camera, tests each stream, and writes the camera's configuration for you, including the [go2rtc](go2rtc.md) restream and the live view stream mapping, so a standard setup needs no hand-written YAML.
### Step 1: Name and connection
+59 -8
View File
@@ -4,6 +4,7 @@ title: Getting started
---
import ConfigTabs from "@site/src/components/ConfigTabs";
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
import NavPath from "@site/src/components/NavPath";
@@ -132,21 +133,68 @@ services:
- "8554:8554" # RTSP feeds
```
Now you should be able to start Frigate by running `docker compose up -d` from within the folder containing `docker-compose.yml`. On startup, an admin user and password will be created and outputted in the logs. You can see this by running `docker logs frigate`. Frigate should now be accessible at `https://server_ip:8971` where you can login with the `admin` user and finish configuration using the Settings UI.
Now you should be able to start Frigate by running `docker compose up -d` from within the folder containing `docker-compose.yml`. On startup, an admin user and password will be created and outputted in the logs. You can see this by running `docker logs frigate`. Frigate should now be accessible at `https://server_ip:8971` where you can login with the `admin` user. With no cameras configured yet, the setup wizard runs on first login and walks you through the rest.
## Configuring Frigate
This section assumes that you already have an environment setup as described in [Installation](../frigate/installation.md). You should also configure your cameras according to the [camera setup guide](/frigate/camera_setup). Pay particular attention to the section on choosing a detect resolution.
### Step 1: Start Frigate
<Tabs
groupId="setup-method"
defaultValue="wizard"
values={[
{ label: "Setup wizard", value: "wizard" },
{ label: "Manual", value: "manual" },
]}
> <TabItem value="wizard">
The first time you open Frigate with no cameras configured, the setup wizard walks you through the basics. Every step can be skipped, everything it sets can be changed later in Settings, and once you finish or dismiss it, it doesn't come back.
:::note
Frigate only sees hardware that has been passed into the container. If you plan to use a GPU, a Coral, or another accelerator, add the device to your `docker-compose.yml` and restart before running the wizard, otherwise it won't appear in the detection or hardware acceleration steps. The Manual tab shows the device entries for an Intel or AMD GPU and for a Coral, and the [hardware acceleration](../configuration/hardware_acceleration_video.md) and [object detectors](../configuration/object_detectors.md) docs cover the rest.
:::
**Account**
Set a password for the `admin` account to replace the generated one from the logs, and add accounts for anyone else who needs access. This step is hidden if you have turned authentication off.
**Add a camera**
Opens the [Add Camera Wizard](../configuration/cameras.md#adding-a-camera-with-the-add-camera-wizard), which connects to the camera, tests each stream, and writes its configuration for you. You can add more than one before moving on.
**Object detection**
Lists the detection hardware Frigate found on your system, such as a Coral, an Intel GPU or NPU, or a discrete GPU, and configures the one you pick. NVIDIA and AMD GPUs need a model before detection can start, so the wizard offers your Frigate+ models if you have them, or lets you finish setup and add one later under <NavPath path="Settings > System > Detection models" />.
**Hardware acceleration**
Offers only the decoding methods your hardware supports. Auto picks one based on that hardware and the codec your camera sends, so a mixed h264 and h265 setup gets the right preset per camera.
**Recording**
Choose whether to record only when something is detected or around the clock, and how long to keep it.
The last screen summarizes what was set up. If a step changed something that needs a restart, the button restarts Frigate and returns you to the Live view once it is back.
The wizard configures the essentials only. Motion masks are not included and should be set up afterward, once you can identify the areas of the frame that trigger unwanted motion. See the [masks documentation](../configuration/masks.md). Zones, tracked object types, notifications, and MQTT are also configured in Settings.
</TabItem>
<TabItem value="manual">
On a new install the setup wizard opens first. Click **Skip setup and configure manually** on its welcome screen to dismiss it, and the steps below apply. The wizard won't come back once dismissed.
**Step 1: Start Frigate**
At this point you should be able to start Frigate and a basic config will be created automatically.
### Step 2: Add a camera
**Step 2: Add a camera**
Click the **Add Camera** button in <NavPath path="Settings > Global configuration > Camera management" /> to use the camera setup wizard to get your first camera added into Frigate. See [Adding a camera with the Add Camera Wizard](../configuration/cameras.md#adding-a-camera-with-the-add-camera-wizard) for a walkthrough of each step.
### Step 3: Configure hardware acceleration (recommended)
**Step 3: Configure hardware acceleration (recommended)**
Now that you have a working camera configuration, set up hardware acceleration to minimize the CPU required to decode your video streams. See the [hardware acceleration](../configuration/hardware_acceleration_video.md) docs for examples applicable to your hardware.
@@ -190,7 +238,7 @@ cameras:
</TabItem>
</ConfigTabs>
### Step 4: Configure detectors
**Step 4: Configure detectors**
By default, Frigate will use a single OpenVINO detector running on the CPU.
@@ -299,7 +347,7 @@ More details on available detectors can be found [here](../configuration/object_
Restart Frigate and you should start seeing detections for `person`. If you want to track other objects, they can be configured in <NavPath path="Settings > Global configuration > Objects" /> or via the [configuration file reference](../configuration/advanced/reference.md).
### Step 5: Setup motion masks
**Step 5: Setup motion masks**
Now that you have optimized your configuration for decoding the video stream, you will want to check to see where to implement motion masks. Click on the camera from the main dashboard, then select the gear icon in the top right, enable the [Debug view](/usage/live#the-single-camera-view), and finally enable the switch for Motion Boxes. Watch for areas that continuously trigger unwanted motion to be detected. Common areas to mask include camera timestamps and trees that frequently blow in the wind. The goal is to avoid wasting object detection cycles looking at these areas.
@@ -336,7 +384,7 @@ cameras:
coordinates: "0,461,3,0,1919,0,1919,843,1699,492,1344,458,1346,336,973,317,869,375,866,432"
```
### Step 6: Enable recordings
**Step 6: Enable recordings**
In order to review activity in the Frigate UI, recordings need to be enabled.
@@ -385,7 +433,10 @@ If you only plan to use Frigate for recording, it is still recommended to define
By default, Frigate will retain video of all tracked objects for 10 days. The full set of options for recording can be found [here](../configuration/advanced/reference.md).
### Step 7: Complete config
</TabItem>
</Tabs>
### Complete config
At this point you have a complete config with basic functionality.
+11
View File
@@ -47,6 +47,7 @@ export interface ApiMockOverrides {
recommended: string;
available?: { key: string; presets: Record<string, string> }[];
};
users?: { username: string; role: string }[];
}
export class ApiMocker {
@@ -200,6 +201,16 @@ export class ApiMocker {
}),
);
// Users. GET lists them; POST/PUT (create, password) just succeed, so
// tests assert on the intercepted request body instead of a response.
await this.page.route("**/api/users**", (route) =>
route.request().method() === "GET"
? route.fulfill({
json: overrides?.users ?? [{ username: "admin", role: "admin" }],
})
: route.fulfill({ json: { message: "ok" } }),
);
// Go2RTC streams
await this.page.route("**/api/go2rtc/streams**", (route) =>
route.fulfill({ json: {} }),
+51
View File
@@ -0,0 +1,51 @@
/**
* Shared setup-wizard e2e helpers.
*
* The wizard shows when config has no cameras, so a first run is mocked by
* serving a camera-less config until the returned callback is fired. Firing
* it is only needed by tests that care what the rest of the app sees; the
* wizard itself tracks added cameras from the camera dialog's own callback.
*/
import type { Page } from "@playwright/test";
import { expect } from "../fixtures/frigate-test";
import { configFactory } from "../fixtures/mock-data/config";
import type { ApiMockOverrides } from "./api-mocker";
export async function installFirstRun(
frigateApp: { installDefaults: (o?: ApiMockOverrides) => Promise<void> },
page: Page,
overrides?: ApiMockOverrides,
): Promise<() => void> {
await frigateApp.installDefaults(overrides);
const full = configFactory(overrides?.config);
let cameras: unknown = {};
await page.route("**/api/config", (route) => {
if (route.request().method() === "GET") {
return route.fulfill({ json: { ...full, cameras } });
}
return route.fulfill({ json: { success: true } });
});
return () => {
cameras = full.cameras;
};
}
export async function gotoDetectorStep(page: Page) {
await page.getByRole("button", { name: "Get Started" }).click();
// the account step sits between welcome and camera whenever auth is on,
// which the default mock config has it
await expect(
page.getByRole("heading", { name: "Secure your account" }),
).toBeVisible();
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("Add Your First Camera")).toBeVisible();
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("Object Detection")).toBeVisible();
}
+196
View File
@@ -0,0 +1,196 @@
/**
* Setup wizard account step -- HIGH tier.
*
* Covers the step's placement and gating, the password and user payloads it
* sends, the copy it shows when nobody is signed in (the internal port), and
* that skipping it writes nothing.
*/
import { test, expect } from "../../fixtures/frigate-test";
import type { Page } from "@playwright/test";
import { installFirstRun } from "../../helpers/setup-wizard";
type Sent = {
method: string;
url: string;
body: Record<string, unknown> | null;
};
async function captureUserCalls(page: Page): Promise<Sent[]> {
const sent: Sent[] = [];
await page.route("**/api/users**", (route) => {
const request = route.request();
if (request.method() === "GET") {
return route.fulfill({ json: [{ username: "admin", role: "admin" }] });
}
sent.push({
method: request.method(),
url: request.url(),
body: request.postDataJSON(),
});
return route.fulfill({ json: { message: "ok" } });
});
return sent;
}
async function gotoAccountStep(page: Page) {
await page.getByRole("button", { name: "Get Started" }).click();
await expect(
page.getByRole("heading", { name: "Secure your account" }),
).toBeVisible();
}
test.describe("setup wizard account @high @mobile", () => {
test("sets the admin password without an old password", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page);
const sent = await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoAccountStep(page);
await page.getByRole("button", { name: "Change password" }).click();
const dialog = page.getByRole("dialog");
await expect(dialog).toBeVisible();
// the dialog is in set-password mode, so it asks for no current password
await expect(
dialog.getByPlaceholder("Enter your current password"),
).toBeHidden();
await dialog
.getByPlaceholder("Enter new password", { exact: true })
.fill("a-long-enough-password");
await dialog
.getByPlaceholder("Re-enter new password")
.fill("a-long-enough-password");
await dialog.getByRole("button", { name: "Save" }).click();
await expect(page.getByText("Password set")).toBeVisible();
const passwordCall = sent.find((call) => call.method === "PUT");
expect(passwordCall?.url).toContain("/users/admin/password");
// admins are exempt from the current-password check, so it must not be sent
expect(passwordCall?.body).toEqual({ password: "a-long-enough-password" });
});
test("creates a user with a role", async ({ frigateApp, page }) => {
await installFirstRun(frigateApp, page);
const sent = await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoAccountStep(page);
await page.getByRole("button", { name: "Add user" }).click();
await page.getByPlaceholder("Enter username").fill("family");
await page
.getByPlaceholder("Enter password")
.fill("a-long-enough-password");
await page
.getByPlaceholder("Confirm Password")
.fill("a-long-enough-password");
await page.getByRole("button", { name: "Save" }).click();
const createCall = sent.find((call) => call.method === "POST");
expect(createCall?.body).toEqual({
username: "family",
password: "a-long-enough-password",
role: "viewer",
});
});
test("shows anonymous copy when nobody is signed in", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page, {
profile: { username: "anonymous", role: "admin", allowed_cameras: null },
});
await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoAccountStep(page);
await expect(page.getByText("doesn't require a login")).toBeVisible();
await expect(page.getByText("You're signed in as")).toBeHidden();
});
test("is absent when native auth is disabled", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page, {
config: { auth: { enabled: false } } as never,
});
await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await page.getByRole("button", { name: "Get Started" }).click();
// straight from welcome to the camera step, with no gap in the indicator
await expect(page.getByText("Add Your First Camera")).toBeVisible();
await expect(
page.getByRole("heading", { name: "Secure your account" }),
).toBeHidden();
});
test("skipping sends nothing", async ({ frigateApp, page }) => {
await installFirstRun(frigateApp, page);
const sent = await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoAccountStep(page);
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("Add Your First Camera")).toBeVisible();
expect(sent).toHaveLength(0);
});
test("an account change alone needs no restart", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page);
await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoAccountStep(page);
await page.getByRole("button", { name: "Change password" }).click();
const dialog = page.getByRole("dialog");
await dialog
.getByPlaceholder("Enter new password", { exact: true })
.fill("a-long-enough-password");
await dialog
.getByPlaceholder("Re-enter new password")
.fill("a-long-enough-password");
await dialog.getByRole("button", { name: "Save" }).click();
await expect(page.getByText("Password set")).toBeVisible();
await page.getByRole("button", { name: "Next" }).click();
await expect(page.getByText("Add Your First Camera")).toBeVisible();
await page.getByRole("button", { name: "Skip" }).click();
// every remaining step is passed without writing config: Skip on the
// detector, then Auto on hwaccel, which has nothing to derive and so
// saves nothing, then Skip on recording
await expect(page.getByText("Object Detection")).toBeVisible();
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("Hardware Acceleration")).toBeVisible();
await page.getByRole("button", { name: "Next" }).click();
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("You're done!")).toBeVisible();
await expect(
page.getByRole("button", { name: "Go to Live View" }),
).toBeVisible();
await expect(
page.getByText("Frigate needs to restart to apply your settings"),
).toBeHidden();
});
});
+11 -57
View File
@@ -9,8 +9,7 @@
import { test, expect } from "../../fixtures/frigate-test";
import type { Page } from "@playwright/test";
import { configFactory } from "../../fixtures/mock-data/config";
import type { ApiMockOverrides } from "../../helpers/api-mocker";
import { gotoDetectorStep, installFirstRun } from "../../helpers/setup-wizard";
const NVIDIA_HARDWARE = [
{
@@ -57,57 +56,12 @@ async function captureRestarts(page: Page): Promise<string[]> {
return calls;
}
/**
* Install mocks for a first run: the wizard shows when config has no cameras,
* so the config route starts empty and only reports cameras once the returned
* callback is fired, standing in for the camera the user adds.
*/
async function installFirstRun(
frigateApp: { installDefaults: (o?: ApiMockOverrides) => Promise<void> },
page: Page,
overrides?: ApiMockOverrides,
): Promise<() => void> {
await frigateApp.installDefaults(overrides);
const full = configFactory(overrides?.config);
let cameras: unknown = {};
await page.route("**/api/config", (route) => {
if (route.request().method() === "GET") {
return route.fulfill({ json: { ...full, cameras } });
}
return route.fulfill({ json: { success: true } });
});
return () => {
cameras = full.cameras;
};
}
async function gotoDetectorStep(page: Page, addCamera: () => void) {
await page.getByRole("button", { name: "Get Started" }).click();
await expect(page.getByText("Add Your First Camera")).toBeVisible();
// the camera step's Next only renders once its local addedCameras fills,
// which SetupCamera does by refetching config when the dialog closes, so
// opening and cancelling the dialog is what reveals Next
await page.getByRole("button", { name: "Add Camera" }).click();
addCamera();
await page.getByRole("button", { name: "Cancel" }).click();
await expect(page.getByRole("button", { name: "Next" })).toBeVisible({
timeout: 10_000,
});
await page.getByRole("button", { name: "Next" }).click();
await expect(page.getByText("Object Detection")).toBeVisible();
}
test.describe("setup wizard hardware @high @mobile", () => {
test("lists probed hardware and writes a models config", async ({
frigateApp,
page,
}) => {
const addCamera = await installFirstRun(frigateApp, page, {
await installFirstRun(frigateApp, page, {
hwaccel: {
recommended: "vaapi",
available: [
@@ -125,7 +79,7 @@ test.describe("setup wizard hardware @high @mobile", () => {
const saves = await captureSaves(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoDetectorStep(page, addCamera);
await gotoDetectorStep(page);
// the default hardware mock reports two Corals, an Intel GPU, and the CPU
await expect(
@@ -170,13 +124,13 @@ test.describe("setup wizard hardware @high @mobile", () => {
frigateApp,
page,
}) => {
const addCamera = await installFirstRun(frigateApp, page, {
await installFirstRun(frigateApp, page, {
hardware: NVIDIA_HARDWARE,
});
const saves = await captureSaves(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoDetectorStep(page, addCamera);
await gotoDetectorStep(page);
await expect(
page.getByRole("radio", { name: /NVIDIA GeForce RTX 3060/ }),
@@ -211,7 +165,7 @@ test.describe("setup wizard hardware @high @mobile", () => {
frigateApp,
page,
}) => {
const addCamera = await installFirstRun(frigateApp, page, {
await installFirstRun(frigateApp, page, {
hardware: NVIDIA_HARDWARE,
hwaccel: {
recommended: "nvidia",
@@ -221,7 +175,7 @@ test.describe("setup wizard hardware @high @mobile", () => {
await captureSaves(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoDetectorStep(page, addCamera);
await gotoDetectorStep(page);
await page
.getByRole("button", { name: "Continue without detection" })
.click();
@@ -247,7 +201,7 @@ test.describe("setup wizard hardware @high @mobile", () => {
frigateApp,
page,
}) => {
const addCamera = await installFirstRun(frigateApp, page, {
await installFirstRun(frigateApp, page, {
hwaccel: {
recommended: "jetson",
available: [
@@ -264,7 +218,7 @@ test.describe("setup wizard hardware @high @mobile", () => {
const saves = await captureSaves(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoDetectorStep(page, addCamera);
await gotoDetectorStep(page);
await page.getByRole("button", { name: "Next" }).click();
await expect(page.getByText("Hardware Acceleration")).toBeVisible();
@@ -284,11 +238,11 @@ test.describe("setup wizard hardware @high @mobile", () => {
frigateApp,
page,
}) => {
const addCamera = await installFirstRun(frigateApp, page);
await installFirstRun(frigateApp, page);
const saves = await captureSaves(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoDetectorStep(page, addCamera);
await gotoDetectorStep(page);
await page.getByRole("button", { name: "Next" }).click();
await expect(page.getByText("Hardware Acceleration")).toBeVisible();
+11
View File
@@ -2,6 +2,7 @@
"setupWizard": {
"steps": {
"welcome": "Welcome",
"account": "Account",
"camera": "Add Camera",
"hwaccel": "Acceleration",
"detector": "Detection",
@@ -14,6 +15,16 @@
"getStarted": "Get Started",
"skipSetup": "Skip setup and configure manually"
},
"account": {
"title": "Secure your account",
"descriptionSignedIn": "You're signed in as {{username}} using the temporary password from the Frigate logs. Set one you'll remember.",
"descriptionAnonymous": "You're accessing Frigate on a port that doesn't require a login. Set a password for the admin account so you can sign in on the secured port.",
"passwordSet": "Password set",
"changePassword": "Change password",
"addUser": "Add user",
"usersFailed": "Could not load the user list. You can still set the admin password.",
"userFailed": "Failed to add the user. Please try again."
},
"camera": {
"title": "Add Your First Camera",
"description": "Connect a camera to start monitoring. You can also add more cameras later in Settings.",
+12 -4
View File
@@ -6,7 +6,7 @@ import Sidebar from "@/components/navigation/Sidebar";
import { isDesktop, isMobile } from "react-device-detect";
import Statusbar from "./components/Statusbar";
import Bottombar from "./components/navigation/Bottombar";
import { Suspense, lazy, useEffect, useState } from "react";
import { Suspense, lazy, useContext, useEffect, useState } from "react";
import { Redirect } from "./components/navigation/Redirect";
import { cn } from "./lib/utils";
import { isPWA } from "./utils/isPWA";
@@ -15,6 +15,8 @@ import useSWR from "swr";
import { FrigateConfig } from "./types/frigateConfig";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { isRedirectingToLogin } from "@/api/auth-redirect";
import { AuthContext } from "@/context/auth-context";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { isSetupDismissed } from "@/utils/setupWizard";
const Live = lazy(() => import("@/pages/Live"));
@@ -57,14 +59,20 @@ function DefaultAppView() {
// decided once per load: adding the first camera part way through the
// wizard must not pull the wizard out from under the user
const [showWizard, setShowWizard] = useState<boolean>();
const { auth } = useContext(AuthContext);
const isAdmin = useIsAdmin();
useEffect(() => {
if (config && showWizard === undefined) {
// every step writes through admin only endpoints, and the role isn't
// known until the profile resolves
if (config && !auth.isLoading && showWizard === undefined) {
setShowWizard(
Object.keys(config.cameras ?? {}).length === 0 && !isSetupDismissed(),
isAdmin &&
Object.keys(config.cameras ?? {}).length === 0 &&
!isSetupDismissed(),
);
}
}, [config, showWizard]);
}, [config, auth.isLoading, isAdmin, showWizard]);
// Compute required roles for main routes, ensuring we have config first
// to prevent race condition where custom roles are temporarily unavailable
+194
View File
@@ -0,0 +1,194 @@
import ActivityIndicator from "@/components/indicators/activity-indicator";
import CreateUserDialog from "@/components/overlay/CreateUserDialog";
import SetPasswordDialog from "@/components/overlay/SetPasswordDialog";
import { Button } from "@/components/ui/button";
import { AuthContext } from "@/context/auth-context";
import axios from "axios";
import { useCallback, useContext, useState } from "react";
import { useTranslation } from "react-i18next";
import { FaCircleCheck } from "react-icons/fa6";
import { toast } from "sonner";
import useSWR from "swr";
type User = {
username: string;
role: string;
};
type SetupAccountProps = {
onNext: () => void;
onBack: () => void;
onSkip: () => void;
};
export default function SetupAccount({
onNext,
onBack,
onSkip,
}: SetupAccountProps) {
const { t } = useTranslation(["views/setup"]);
const { auth } = useContext(AuthContext);
const {
data: users,
isLoading,
error: usersError,
mutate: mutateUsers,
} = useSWR<User[]>("users", { revalidateOnFocus: false });
// the internal port has no signed in user, so the built-in admin is the
// account being secured
const adminUsername = auth.isAuthenticated
? (auth.user?.username ?? "admin")
: "admin";
const [showPassword, setShowPassword] = useState(false);
const [passwordError, setPasswordError] = useState<string | null>(null);
const [passwordSaving, setPasswordSaving] = useState(false);
const [passwordSet, setPasswordSet] = useState(false);
const [showCreate, setShowCreate] = useState(false);
const handleSavePassword = useCallback(
(password: string) => {
setPasswordSaving(true);
axios
.put(`users/${adminUsername}/password`, { password })
.then(() => {
setShowPassword(false);
setPasswordError(null);
setPasswordSet(true);
})
.catch((error) => {
setPasswordError(
error.response?.data?.message ||
error.response?.data?.detail ||
t("setupWizard.errors.saveFailed"),
);
})
.finally(() => setPasswordSaving(false));
},
[adminUsername, t],
);
const handleCreateUser = useCallback(
(username: string, password: string, role: string) =>
axios
.post("users", { username, password, role })
.then(() => {
setShowCreate(false);
mutateUsers();
})
.catch((error) => {
toast.error(
error.response?.data?.message ||
error.response?.data?.detail ||
t("setupWizard.account.userFailed"),
);
}),
[mutateUsers, t],
);
const otherUsers = (users ?? []).filter(
(user) => user.username !== adminUsername,
);
return (
<div className="flex flex-col gap-4 py-4">
<div>
<h2 className="text-xl font-semibold">
{t("setupWizard.account.title")}
</h2>
<p className="mt-1 text-sm text-muted-foreground">
{auth.isAuthenticated
? t("setupWizard.account.descriptionSignedIn", {
username: adminUsername,
})
: t("setupWizard.account.descriptionAnonymous")}
</p>
</div>
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between rounded-md border p-3">
<div className="flex flex-col gap-1">
<span className="text-sm font-medium">{adminUsername}</span>
{passwordSet && (
<span className="flex items-center gap-2 text-xs text-muted-foreground">
<FaCircleCheck className="size-3 text-success" />
{t("setupWizard.account.passwordSet")}
</span>
)}
</div>
<Button
type="button"
variant="outline"
onClick={() => setShowPassword(true)}
>
{t("setupWizard.account.changePassword")}
</Button>
</div>
{otherUsers.map((user) => (
<div
key={user.username}
className="flex items-center justify-between rounded-md border p-3"
>
<span className="text-sm font-medium">{user.username}</span>
<span className="text-xs text-muted-foreground">{user.role}</span>
</div>
))}
</div>
{isLoading && <ActivityIndicator />}
{usersError && (
<p className="rounded-md bg-muted p-3 text-xs text-muted-foreground">
{t("setupWizard.account.usersFailed")}
</p>
)}
<div className="flex flex-col items-center gap-3 py-4">
<Button
variant="select"
className="w-full"
onClick={() => setShowCreate(true)}
>
{t("setupWizard.account.addUser")}
</Button>
</div>
<div className="flex flex-col gap-3 pt-6 sm:flex-row sm:justify-end sm:gap-4">
<Button type="button" onClick={onBack}>
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end gap-3">
<Button type="button" onClick={onSkip}>
{t("setupWizard.actions.skip")}
</Button>
<Button type="button" variant="select" onClick={onNext}>
{t("setupWizard.actions.next")}
</Button>
</div>
</div>
{/* no username prop: passing one puts the dialog in current-password
mode, which the admin is exempt from and an anonymous internal port
user has no way to satisfy */}
<SetPasswordDialog
show={showPassword}
initialError={passwordError}
isLoading={passwordSaving}
onSave={handleSavePassword}
onCancel={() => {
setShowPassword(false);
setPasswordError(null);
}}
/>
<CreateUserDialog
show={showCreate}
onCreate={handleCreateUser}
onCancel={() => setShowCreate(false)}
/>
</div>
);
}
+17 -23
View File
@@ -2,8 +2,6 @@ import CameraWizardDialog from "@/components/settings/CameraWizardDialog";
import { Button } from "@/components/ui/button";
import { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import useSWR from "swr";
import { FrigateConfig } from "@/types/frigateConfig";
import { FaCircleCheck } from "react-icons/fa6";
type SetupCameraProps = {
@@ -19,30 +17,18 @@ export default function SetupCamera({ onNext, onBack }: SetupCameraProps) {
const [showWizard, setShowWizard] = useState(false);
const [addedCameras, setAddedCameras] = useState<string[]>([]);
const [detectCodecs, setDetectCodecs] = useState<Record<string, string>>({});
const { mutate: mutateConfig } = useSWR<FrigateConfig>("config", {
revalidateOnFocus: false,
});
const handleClose = useCallback(() => {
setShowWizard(false);
// the dialog's config save and go2rtc setup need a moment to land, and
// the SWR cache would serve the pre-save config
setTimeout(() => {
fetch(`${window.baseUrl || ""}api/config`)
.then((res) => res.json())
.then((freshConfig: FrigateConfig) => {
const cameraNames = Object.keys(freshConfig.cameras || {});
if (cameraNames.length > addedCameras.length) {
mutateConfig(freshConfig, { revalidate: false });
setAddedCameras(cameraNames);
}
})
.catch(() => {});
}, 1000);
}, [mutateConfig, addedCameras]);
}, []);
// the dialog fires this once its config write has succeeded, which is the
// only reliable signal that a camera was added
const handleCameraAdded = useCallback(
({ name, detectCodec }: { name: string; detectCodec?: string }) => {
setAddedCameras((previous) =>
previous.includes(name) ? previous : [...previous, name],
);
if (detectCodec) {
setDetectCodecs((previous) => ({ ...previous, [name]: detectCodec }));
}
@@ -51,9 +37,13 @@ export default function SetupCamera({ onNext, onBack }: SetupCameraProps) {
);
const handleNext = useCallback(() => {
onNext(addedCameras.length > 0 ? addedCameras : undefined, detectCodecs);
onNext(addedCameras, detectCodecs);
}, [onNext, addedCameras, detectCodecs]);
const handleSkip = useCallback(() => {
onNext();
}, [onNext]);
return (
<>
<div className="flex flex-col gap-4 py-4">
@@ -97,10 +87,14 @@ export default function SetupCamera({ onNext, onBack }: SetupCameraProps) {
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end gap-3">
{addedCameras.length > 0 && (
{addedCameras.length > 0 ? (
<Button type="button" variant="select" onClick={handleNext}>
{t("setupWizard.actions.next")}
</Button>
) : (
<Button type="button" variant="outline" onClick={handleSkip}>
{t("setupWizard.actions.skip")}
</Button>
)}
</div>
</div>
+1 -5
View File
@@ -251,11 +251,7 @@ export default function SetupDetector({
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end gap-3">
<Button
type="button"
variant="outline"
onClick={() => onSkip(selected.key)}
>
<Button type="button" onClick={() => onSkip(selected.key)}>
{t("setupWizard.actions.skip")}
</Button>
<Button
+1 -1
View File
@@ -238,7 +238,7 @@ export default function SetupHwAccel({
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end gap-3">
<Button type="button" variant="outline" onClick={onSkip}>
<Button type="button" onClick={onSkip}>
{t("setupWizard.actions.skip")}
</Button>
<Button
+1 -1
View File
@@ -169,7 +169,7 @@ export default function SetupRecording({
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end gap-3">
<Button type="button" variant="outline" onClick={onSkip}>
<Button type="button" onClick={onSkip}>
{t("setupWizard.actions.skip")}
</Button>
<Button
+55 -17
View File
@@ -1,4 +1,5 @@
import StepIndicator from "@/components/indicators/StepIndicator";
import SetupAccount from "@/components/setup/SetupAccount";
import SetupCamera from "@/components/setup/SetupCamera";
import SetupComplete from "@/components/setup/SetupComplete";
import SetupDetector from "@/components/setup/SetupDetector";
@@ -8,18 +9,30 @@ import SetupWelcome from "@/components/setup/SetupWelcome";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { useTheme } from "@/context/theme-provider";
import { FrigateConfig } from "@/types/frigateConfig";
import { dismissSetup } from "@/utils/setupWizard";
import { useCallback, useReducer } from "react";
import { useCallback, useMemo, useReducer } from "react";
import { useTranslation } from "react-i18next";
import { LuMoon, LuSun } from "react-icons/lu";
import useSWR from "swr";
const STEPS = [
"setupWizard.steps.welcome",
"setupWizard.steps.camera",
"setupWizard.steps.detector",
"setupWizard.steps.hwaccel",
"setupWizard.steps.recording",
"setupWizard.steps.complete",
type StepKey =
| "welcome"
| "account"
| "camera"
| "detector"
| "hwaccel"
| "recording"
| "complete";
const STEP_KEYS: StepKey[] = [
"welcome",
"account",
"camera",
"detector",
"hwaccel",
"recording",
"complete",
];
type WizardState = {
@@ -114,6 +127,23 @@ export default function SetupWizard() {
const [state, dispatch] = useReducer(wizardReducer, initialState);
const { theme, systemTheme, setTheme } = useTheme();
const { data: config } = useSWR<FrigateConfig>("config", {
revalidateOnFocus: false,
});
// with native auth off there are no users to manage, so the step would lie
const steps = useMemo(
() =>
config?.auth?.enabled === false
? STEP_KEYS.filter((key) => key !== "account")
: STEP_KEYS,
[config],
);
const stepLabels = useMemo(
() => steps.map((key) => `setupWizard.steps.${key}`),
[steps],
);
const isDark = (theme === "system" ? systemTheme : theme) === "dark";
const handleSkipSetup = useCallback(() => {
@@ -161,17 +191,25 @@ export default function SetupWizard() {
}, []);
const renderStep = () => {
switch (state.currentStep) {
case 0:
switch (steps[state.currentStep]) {
case "welcome":
return (
<SetupWelcome
onNext={() => dispatch({ type: "NEXT_STEP" })}
onSkip={handleSkipSetup}
/>
);
case 1:
case "account":
return (
<SetupAccount
onNext={handleSkipStep}
onBack={handleBack}
onSkip={handleSkipStep}
/>
);
case "camera":
return <SetupCamera onNext={handleCameraNext} onBack={handleBack} />;
case 2:
case "detector":
return (
<SetupDetector
cameraCount={state.cameraNames.length}
@@ -180,7 +218,7 @@ export default function SetupWizard() {
onSkip={handleDetectorSkip}
/>
);
case 3:
case "hwaccel":
return (
<SetupHwAccel
detectorHardwareKey={state.detectorHardwareKey}
@@ -190,7 +228,7 @@ export default function SetupWizard() {
onSkip={handleSkipStep}
/>
);
case 4:
case "recording":
return (
<SetupRecording
cameraNames={state.cameraNames}
@@ -199,7 +237,7 @@ export default function SetupWizard() {
onSkip={handleSkipStep}
/>
);
case 5:
case "complete":
return (
<SetupComplete
cameraNames={state.cameraNames}
@@ -228,10 +266,10 @@ export default function SetupWizard() {
{isDark ? <LuSun className="size-4" /> : <LuMoon className="size-4" />}
</Button>
<Card className="w-full max-w-lg">
<Card className="w-full max-w-lg bg-background_alt">
<CardContent className="p-6">
<StepIndicator
steps={STEPS}
steps={stepLabels}
currentStep={state.currentStep}
variant="dots"
translationNameSpace="views/setup"