Camera profile support (#22482)

* add CameraProfileConfig model for named config overrides

* add profiles field to CameraConfig

* add active_profile field to FrigateConfig

Runtime-only field excluded from YAML serialization, tracks which
profile is currently active.

* add ProfileManager for profile activation and persistence

Handles snapshotting base configs, applying profile overrides via
deep_merge + apply_section_update, publishing ZMQ updates, and
persisting active profile to /config/.active_profile.

* add profile API endpoints (GET /profiles, GET/PUT /profile)

* add MQTT and dispatcher integration for profiles

- Subscribe to frigate/profile/set MQTT topic
- Publish profile/state and profiles/available on connect
- Add _on_profile_command handler to dispatcher
- Broadcast active profile state on WebSocket connect

* wire ProfileManager into app startup and FastAPI

- Create ProfileManager after dispatcher init
- Restore persisted profile on startup
- Pass dispatcher and profile_manager to FastAPI app

* add tests for invalid profile values and keys

Tests that Pydantic rejects: invalid field values (fps: "not_a_number"),
unknown section keys (ffmpeg in profile), invalid nested values, and
invalid profiles in full config parsing.

* formatting

* fix CameraLiveConfig JSON serialization error on profile activation

refactor _publish_updates to only publish ZMQ updates for
sections that actually changed, not all sections on affected cameras.

* consolidate

* add enabled field to camera profiles for enabling/disabling cameras

* add zones support to camera profiles

* add frontend profile types, color utility, and config save support

* add profile state management and save preview support

* add profileName prop to BaseSection for profile-aware config editing

* add profile section dropdown and wire into camera settings pages

* add per-profile camera enable/disable to Camera Management view

* add profiles summary page with card-based layout and fix backend zone comparison bug

* add active profile badge to settings toolbar

* i18n

* add red dot for any pending changes including profiles

* profile support for mask and zone editor

* fix hidden field validation errors caused by lodash wildcard and schema gaps

lodash unset does not support wildcard (*) segments, so hidden fields like
filters.*.mask were never stripped from form data, leaving null raw_coordinates
that fail RJSF anyOf validation. Add unsetWithWildcard helper and also strip
hidden fields from the JSON schema itself as defense-in-depth.

* add face_recognition and lpr to profile-eligible sections

* move profile dropdown from section panes to settings header

* add profiles enable toggle and improve empty state

* formatting

* tweaks

* tweak colors and switch

* fix profile save diff, masksAndZones delete, and config sync

* ui tweaks

* ensure profile manager gets updated config

* rename profile settings to ui settings

* refactor profilesview and add dots/border colors when overridden

* implement an update_config method for profile manager

* fix mask deletion

* more unique colors

* add top-level profiles config section with friendly names

* implement profile friendly names and improve profile UI

- Add ProfileDefinitionConfig type and profiles field to FrigateConfig
- Use ProfilesApiResponse type with friendly_name support throughout
- Replace Record<string, unknown> with proper JsonObject/JsonValue types
- Add profile creation form matching zone pattern (Zod + NameAndIdFields)
- Add pencil icon for renaming profile friendly names in ProfilesView
- Move Profiles menu item to first under Camera Configuration
- Add activity indicators on save/rename/delete buttons
- Display friendly names in CameraManagementView profile selector
- Fix duplicate colored dots in management profile dropdown
- Fix i18n namespace for overridden base config tooltips
- Move profile override deletion from dropdown trash icon to footer
  button with confirmation dialog, matching Reset to Global pattern
- Remove Add Profile from section header dropdown to prevent saving
  camera overrides before top-level profile definition exists
- Clean up newProfiles state after API profile deletion
- Refresh profiles SWR cache after saving profile definitions

* remove profile badge in settings and add profiles to main menu

* use icon only on mobile

* change color order

* docs

* show activity indicator on trash icon while deleting a profile

* tweak language

* immediately create profiles on backend instead of deferring to Save All

* hide restart-required fields when editing a profile section

fields that require a restart cannot take effect via profile switching,
so they are merged into hiddenFields when profileName is set

* show active profile indicator in desktop status bar

* fix profile config inheritance bug where Pydantic defaults override base values

The /config API was dumping profile overrides with model_dump() which included
all Pydantic defaults. When the frontend merged these over
the camera's base config, explicitly-set base values were
lost. Now profile overrides are re-dumped with exclude_unset=True so only
user-specified fields are returned.

Also fixes the Save All path generating spurious deletion markers for
restart-required fields that are hidden during profile
editing but not excluded from the raw data sanitization in
prepareSectionSavePayload.

* docs tweaks

* docs tweak

* formatting

* formatting

* fix typing

* fix test pollution

test_maintainer was injecting MagicMock() into sys.modules["frigate.config.camera.updater"] at module load time and never restoring it. When the profile tests later imported CameraConfigUpdateEnum and CameraConfigUpdateTopic from that module, they got mock objects instead of the real dataclass/enum, so equality comparisons always failed

* remove

* fix settings showing profile-merged values when editing base config

When a profile is active, the in-memory config contains effective
(profile-merged) values. The settings UI was displaying these merged
values even when the "Base Config" view was selected.

Backend: snapshot pre-profile base configs in ProfileManager and expose
them via a `base_config` key in the /api/config camera response when a
profile is active. The top-level sections continue to reflect the
effective running config.

Frontend: read from `base_config` when available in BaseSection,
useConfigOverride, useAllCameraOverrides, and prepareSectionSavePayload.
Include formData labels in Object/Audio switches widgets so that labels
added only by a profile override remain visible when editing that profile.

* use rasterized_mask as field

makes it easier to exclude from the schema with exclude=True
prevents leaking of the field when using model_dump for profiles

* fix zones

- Fix zone colors not matching across profiles by falling back to base zone color when profile zone data lacks a color field
- Use base_config for base-layer values in masks/zones view so profile-merged values don't pollute the base config editing view
- Handle zones separately in profile manager snapshot/restore since ZoneConfig requires special serialization (color as private attr, contour generation)
- Inherit base zone color and generate contours for profile zone overrides in profile manager

* formatting

* don't require restart for camera enabled change for profiles

* publish camera state when changing profiles

* formatting

* remove available profiles from mqtt

* improve typing
This commit is contained in:
Josh Hawkins
2026-03-19 09:47:57 -05:00
committed by GitHub
parent a05f35c747
commit c93dad9bd9
47 changed files with 4591 additions and 458 deletions
+148 -21
View File
@@ -6,6 +6,7 @@
import get from "lodash/get";
import cloneDeep from "lodash/cloneDeep";
import merge from "lodash/merge";
import unset from "lodash/unset";
import isEqual from "lodash/isEqual";
import mergeWith from "lodash/mergeWith";
@@ -68,6 +69,63 @@ export const globalCameraDefaultSections = new Set([
"ffmpeg",
]);
// ---------------------------------------------------------------------------
// Profile helpers
// ---------------------------------------------------------------------------
/**
* Get the base (pre-profile) value for a camera section.
*
* When a profile is active the API populates `base_config` with original
* section values. This helper returns that value when available, falling
* back to the top-level (effective) value otherwise.
*/
export function getBaseCameraSectionValue(
config: FrigateConfig | undefined,
cameraName: string | undefined,
sectionPath: string,
): unknown {
if (!config || !cameraName) return undefined;
const cam = config.cameras?.[cameraName];
if (!cam) return undefined;
const base = cam.base_config?.[sectionPath];
return base !== undefined ? base : get(cam, sectionPath);
}
/** Sections that can appear inside a camera profile definition. */
export const PROFILE_ELIGIBLE_SECTIONS = new Set([
"audio",
"birdseye",
"detect",
"face_recognition",
"lpr",
"motion",
"notifications",
"objects",
"record",
"review",
"snapshots",
]);
/**
* Parse a section path that may encode a profile reference.
*
* Examples:
* "detect" → { isProfile: false, actualSection: "detect" }
* "profiles.armed.detect" → { isProfile: true, profileName: "armed", actualSection: "detect" }
*/
export function parseProfileFromSectionPath(sectionPath: string): {
isProfile: boolean;
profileName?: string;
actualSection: string;
} {
const match = sectionPath.match(/^profiles\.([^.]+)\.(.+)$/);
if (match) {
return { isProfile: true, profileName: match[1], actualSection: match[2] };
}
return { isProfile: false, actualSection: sectionPath };
}
// ---------------------------------------------------------------------------
// buildOverrides — pure recursive diff of current vs stored config & defaults
// ---------------------------------------------------------------------------
@@ -168,6 +226,26 @@ export function buildOverrides(
// Normalize raw config data (strip internal fields) and remove any paths
// listed in `hiddenFields` so they are not included in override computation.
// lodash `unset` treats `*` as a literal key. This helper expands wildcard
// segments so that e.g. `"filters.*.mask"` unsets `filters.<each key>.mask`.
function unsetWithWildcard(obj: Record<string, unknown>, path: string): void {
if (!path.includes("*")) {
unset(obj, path);
return;
}
const segments = path.split(".");
const starIndex = segments.indexOf("*");
const prefix = segments.slice(0, starIndex).join(".");
const suffix = segments.slice(starIndex + 1).join(".");
const parent = prefix ? get(obj, prefix) : obj;
if (parent && typeof parent === "object") {
for (const key of Object.keys(parent as Record<string, unknown>)) {
const fullPath = suffix ? `${key}.${suffix}` : key;
unsetWithWildcard(parent as Record<string, unknown>, fullPath);
}
}
}
export function sanitizeSectionData(
data: ConfigSectionData,
hiddenFields?: string[],
@@ -179,7 +257,7 @@ export function sanitizeSectionData(
const cleaned = cloneDeep(normalized) as ConfigSectionData;
hiddenFields.forEach((path) => {
if (!path) return;
unset(cleaned, path);
unsetWithWildcard(cleaned as Record<string, unknown>, path);
});
return cleaned;
}
@@ -315,7 +393,7 @@ export function requiresRestartForFieldPath(
export interface SectionSavePayload {
basePath: string;
sanitizedOverrides: Record<string, unknown>;
sanitizedOverrides: JsonObject;
updateTopic: string | undefined;
needsRestart: boolean;
pendingDataKey: string;
@@ -421,23 +499,57 @@ export function prepareSectionSavePayload(opts: {
level = "global";
}
// Resolve section config
const sectionConfig = getSectionConfig(sectionPath, level);
// Detect profile-encoded section paths (e.g., "profiles.armed.detect")
const profileInfo = parseProfileFromSectionPath(sectionPath);
const schemaSection = profileInfo.actualSection;
// Resolve section schema
const sectionSchema = extractSectionSchema(fullSchema, sectionPath, level);
// Resolve section config using the actual section name (not the profile path)
const sectionConfig = getSectionConfig(schemaSection, level);
// Resolve section schema using the actual section name
const sectionSchema = extractSectionSchema(fullSchema, schemaSection, level);
if (!sectionSchema) return null;
const modifiedSchema = modifySchemaForSection(
sectionPath,
schemaSection,
level,
sectionSchema,
);
// Compute rawFormData (the current stored value for this section)
// For profiles, merge base camera config with profile overrides (matching
// what BaseSection displays in the form) so the diff only contains actual
// user changes, not every field from the merged view.
let rawSectionValue: unknown;
if (level === "camera" && cameraName) {
rawSectionValue = get(config.cameras?.[cameraName], sectionPath);
if (profileInfo.isProfile) {
const baseValue = getBaseCameraSectionValue(
config,
cameraName,
profileInfo.actualSection,
);
const profileOverrides = get(config.cameras?.[cameraName], sectionPath);
if (
profileOverrides &&
typeof profileOverrides === "object" &&
baseValue &&
typeof baseValue === "object"
) {
rawSectionValue = merge(
cloneDeep(baseValue),
cloneDeep(profileOverrides),
);
} else {
rawSectionValue = baseValue;
}
} else {
// Use base (pre-profile) value so the diff matches what the form shows
rawSectionValue = getBaseCameraSectionValue(
config,
cameraName,
sectionPath,
);
}
} else {
rawSectionValue = get(config, sectionPath);
}
@@ -446,10 +558,21 @@ export function prepareSectionSavePayload(opts: {
? {}
: rawSectionValue;
// For profile sections, also hide restart-required fields to match
// effectiveHiddenFields in BaseSection (prevents spurious deletion markers
// for fields that are hidden from the form during profile editing).
let hiddenFieldsForSanitize = sectionConfig.hiddenFields;
if (profileInfo.isProfile && sectionConfig.restartRequired?.length) {
const base = sectionConfig.hiddenFields ?? [];
hiddenFieldsForSanitize = [
...new Set([...base, ...sectionConfig.restartRequired]),
];
}
// Sanitize raw form data
const rawData = sanitizeSectionData(
rawFormData as ConfigSectionData,
sectionConfig.hiddenFields,
hiddenFieldsForSanitize,
);
// Compute schema defaults
@@ -457,7 +580,7 @@ export function prepareSectionSavePayload(opts: {
? applySchemaDefaults(modifiedSchema, {})
: {};
const effectiveDefaults = getEffectiveDefaultsForSection(
sectionPath,
schemaSection,
level,
modifiedSchema ?? undefined,
schemaDefaults,
@@ -466,7 +589,7 @@ export function prepareSectionSavePayload(opts: {
// Build overrides
const overrides = buildOverrides(pendingData, rawData, effectiveDefaults);
const sanitizedOverrides = sanitizeOverridesForSection(
sectionPath,
schemaSection,
level,
overrides,
);
@@ -474,7 +597,7 @@ export function prepareSectionSavePayload(opts: {
if (
!sanitizedOverrides ||
typeof sanitizedOverrides !== "object" ||
Object.keys(sanitizedOverrides as Record<string, unknown>).length === 0
Object.keys(sanitizedOverrides as JsonObject).length === 0
) {
return null;
}
@@ -485,9 +608,11 @@ export function prepareSectionSavePayload(opts: {
? `cameras.${cameraName}.${sectionPath}`
: sectionPath;
// Compute updateTopic
// Compute updateTopic — profile definitions don't trigger hot-reload
let updateTopic: string | undefined;
if (level === "camera" && cameraName) {
if (profileInfo.isProfile) {
updateTopic = undefined;
} else if (level === "camera" && cameraName) {
const topic = cameraUpdateTopicMap[sectionPath];
updateTopic = topic ? `config/cameras/${cameraName}/${topic}` : undefined;
} else if (globalCameraDefaultSections.has(sectionPath)) {
@@ -497,16 +622,18 @@ export function prepareSectionSavePayload(opts: {
updateTopic = `config/${sectionPath}`;
}
// Restart detection
const needsRestart = requiresRestartForOverrides(
sanitizedOverrides,
sectionConfig.restartRequired,
true,
);
// Restart detection — profile definitions never need restart
const needsRestart = profileInfo.isProfile
? false
: requiresRestartForOverrides(
sanitizedOverrides,
sectionConfig.restartRequired,
true,
);
return {
basePath,
sanitizedOverrides: sanitizedOverrides as Record<string, unknown>,
sanitizedOverrides: sanitizedOverrides as JsonObject,
updateTopic,
needsRestart,
pendingDataKey,
+124
View File
@@ -0,0 +1,124 @@
import type { ProfileColor } from "@/types/profile";
const PROFILE_COLORS: ProfileColor[] = [
{
bg: "bg-pink-400",
text: "text-pink-400",
dot: "bg-pink-400",
border: "border-pink-400",
bgMuted: "bg-pink-400/20",
},
{
bg: "bg-violet-500",
text: "text-violet-500",
dot: "bg-violet-500",
border: "border-violet-500",
bgMuted: "bg-violet-500/20",
},
{
bg: "bg-lime-500",
text: "text-lime-500",
dot: "bg-lime-500",
border: "border-lime-500",
bgMuted: "bg-lime-500/20",
},
{
bg: "bg-teal-400",
text: "text-teal-400",
dot: "bg-teal-400",
border: "border-teal-400",
bgMuted: "bg-teal-400/20",
},
{
bg: "bg-sky-400",
text: "text-sky-400",
dot: "bg-sky-400",
border: "border-sky-400",
bgMuted: "bg-sky-400/20",
},
{
bg: "bg-emerald-400",
text: "text-emerald-400",
dot: "bg-emerald-400",
border: "border-emerald-400",
bgMuted: "bg-emerald-400/20",
},
{
bg: "bg-indigo-400",
text: "text-indigo-400",
dot: "bg-indigo-400",
border: "border-indigo-400",
bgMuted: "bg-indigo-400/20",
},
{
bg: "bg-rose-400",
text: "text-rose-400",
dot: "bg-rose-400",
border: "border-rose-400",
bgMuted: "bg-rose-400/20",
},
{
bg: "bg-cyan-300",
text: "text-cyan-300",
dot: "bg-cyan-300",
border: "border-cyan-300",
bgMuted: "bg-cyan-300/20",
},
{
bg: "bg-purple-400",
text: "text-purple-400",
dot: "bg-purple-400",
border: "border-purple-400",
bgMuted: "bg-purple-400/20",
},
{
bg: "bg-green-400",
text: "text-green-400",
dot: "bg-green-400",
border: "border-green-400",
bgMuted: "bg-green-400/20",
},
{
bg: "bg-amber-400",
text: "text-amber-400",
dot: "bg-amber-400",
border: "border-amber-400",
bgMuted: "bg-amber-400/20",
},
{
bg: "bg-slate-400",
text: "text-slate-400",
dot: "bg-slate-400",
border: "border-slate-400",
bgMuted: "bg-slate-400/20",
},
{
bg: "bg-orange-300",
text: "text-orange-300",
dot: "bg-orange-300",
border: "border-orange-300",
bgMuted: "bg-orange-300/20",
},
{
bg: "bg-blue-300",
text: "text-blue-300",
dot: "bg-blue-300",
border: "border-blue-300",
bgMuted: "bg-blue-300/20",
},
];
/**
* Get a deterministic color for a profile name.
*
* Colors are assigned based on sorted position among all profile names,
* so the same profile always gets the same color regardless of context.
*/
export function getProfileColor(
profileName: string,
allProfileNames: string[],
): ProfileColor {
const sorted = [...allProfileNames].sort();
const index = sorted.indexOf(profileName);
return PROFILE_COLORS[(index >= 0 ? index : 0) % PROFILE_COLORS.length];
}