mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-06-02 07:00:32 +00:00
Settings UI fixes (#23237)
* detector UI fixes - derive detector and model from memo rather than using two drain useeffects - sanitize save payload through sanitizeSectionData to prevent yaml validation issues * increase display duration for restart required toasts * mimic logic in detector section for save all button also, increase toast duration for restart required toasts * fixes and tweaks - use section hidden fields for sanitization instead of duplicating code - use parent hooks so save all, pending data, and the status dots work correctly
This commit is contained in:
parent
620923c27e
commit
d968f00500
@ -1583,6 +1583,8 @@
|
||||
"resetError": "Failed to reset settings",
|
||||
"saveAllSuccess_one": "Saved {{count}} section successfully.",
|
||||
"saveAllSuccess_other": "All {{count}} sections saved successfully.",
|
||||
"saveAllSuccessRestartRequired_one": "Saved {{count}} section successfully. Restart Frigate to apply your changes.",
|
||||
"saveAllSuccessRestartRequired_other": "All {{count}} sections saved successfully. Restart Frigate to apply your changes.",
|
||||
"saveAllPartial_one": "{{successCount}} of {{totalCount}} section saved. {{failCount}} failed.",
|
||||
"saveAllPartial_other": "{{successCount}} of {{totalCount}} sections saved. {{failCount}} failed.",
|
||||
"saveAllFailure": "Failed to save all sections."
|
||||
|
||||
@ -743,6 +743,7 @@ export function ConfigSection({
|
||||
"Settings saved successfully. Restart Frigate to apply your changes.",
|
||||
}),
|
||||
{
|
||||
duration: 10000,
|
||||
action: (
|
||||
<a onClick={() => setRestartDialogOpen(true)}>
|
||||
<Button>
|
||||
|
||||
@ -90,9 +90,12 @@ import { RJSFSchema } from "@rjsf/utils";
|
||||
import {
|
||||
buildConfigDataForPath,
|
||||
flattenOverrides,
|
||||
getSectionConfig,
|
||||
parseProfileFromSectionPath,
|
||||
prepareSectionSavePayload,
|
||||
PROFILE_ELIGIBLE_SECTIONS,
|
||||
resolveHiddenFieldEntries,
|
||||
sanitizeSectionData,
|
||||
} from "@/utils/configUtil";
|
||||
import type { ProfileState, ProfilesApiResponse } from "@/types/profile";
|
||||
import { getProfileColor } from "@/utils/profileColors";
|
||||
@ -786,24 +789,22 @@ export default function Settings() {
|
||||
[],
|
||||
);
|
||||
|
||||
// Show save/undo all buttons only when changes span multiple sections
|
||||
// or the single changed section is not the one currently being viewed
|
||||
// Show save/undo all buttons only when at least one pending change lives
|
||||
// outside the currently visible page. Map each pending key to its menu key
|
||||
// (e.g. both `detectors` and `model` collapse to `systemDetectorsAndModel`)
|
||||
// so a composite page with two pending config-sections still counts as one.
|
||||
const showSaveAllButtons = useMemo(() => {
|
||||
const pendingKeys = Object.keys(pendingDataBySection);
|
||||
if (pendingKeys.length === 0) return false;
|
||||
if (pendingKeys.length >= 2) return true;
|
||||
|
||||
// Exactly one pending section — check if it matches the current view
|
||||
const key = pendingKeys[0];
|
||||
const menuKey = pendingKeyToMenuKey(key);
|
||||
if (menuKey !== pageToggle) return true;
|
||||
|
||||
// For camera-scoped keys, also check if the camera matches
|
||||
if (key.includes("::")) {
|
||||
const cameraName = key.slice(0, key.indexOf("::"));
|
||||
return cameraName !== selectedCamera;
|
||||
for (const key of pendingKeys) {
|
||||
const menuKey = pendingKeyToMenuKey(key);
|
||||
if (menuKey !== pageToggle) return true;
|
||||
if (key.includes("::")) {
|
||||
const cameraName = key.slice(0, key.indexOf("::"));
|
||||
if (cameraName !== selectedCamera) return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}, [pendingDataBySection, pendingKeyToMenuKey, pageToggle, selectedCamera]);
|
||||
|
||||
@ -821,8 +822,119 @@ export default function Settings() {
|
||||
let failCount = 0;
|
||||
let anyNeedsRestart = false;
|
||||
const savedKeys: string[] = [];
|
||||
// Pending entries that have been successfully PUT — cleared in one batch
|
||||
// after `mutate("config")` resolves
|
||||
const keysToClear: string[] = [];
|
||||
|
||||
const pendingKeys = Object.keys(pendingDataBySection);
|
||||
// `detectors` and `model` are owned by DetectorsAndModelSettingsView,
|
||||
// which saves them atomically (single combined PUT with a pre-clear when
|
||||
// detector keys change or the Plus/Custom tab flips). Doing the same here
|
||||
// keeps Save All consistent with the page's own Save button
|
||||
const hasPendingDetectors = "detectors" in pendingDataBySection;
|
||||
const hasPendingModel = "model" in pendingDataBySection;
|
||||
if (hasPendingDetectors || hasPendingModel) {
|
||||
try {
|
||||
const pendingDetectors = hasPendingDetectors
|
||||
? pendingDataBySection.detectors
|
||||
: undefined;
|
||||
const pendingModel = hasPendingModel
|
||||
? pendingDataBySection.model
|
||||
: undefined;
|
||||
|
||||
// Hidden-field lists come from the section configs themselves so
|
||||
// they stay in sync with what the embedded forms strip on render
|
||||
const detectorHiddenFields = resolveHiddenFieldEntries(
|
||||
getSectionConfig("detectors", "global").hiddenFields,
|
||||
config,
|
||||
);
|
||||
const modelHiddenFields = resolveHiddenFieldEntries(
|
||||
getSectionConfig("model", "global").hiddenFields,
|
||||
config,
|
||||
);
|
||||
const sanitizedDetectors =
|
||||
pendingDetectors !== undefined
|
||||
? sanitizeSectionData(pendingDetectors, detectorHiddenFields)
|
||||
: undefined;
|
||||
const sanitizedModel =
|
||||
pendingModel !== undefined
|
||||
? sanitizeSectionData(pendingModel, modelHiddenFields)
|
||||
: undefined;
|
||||
|
||||
// Pre-clear conditions: detector keys differ from saved config (rename
|
||||
// or add/remove), OR the model save flips between Plus and Custom modes
|
||||
let detectorKeysChanged = false;
|
||||
if (sanitizedDetectors && typeof sanitizedDetectors === "object") {
|
||||
const pendingKeySet = Object.keys(
|
||||
sanitizedDetectors as JsonObject,
|
||||
).sort();
|
||||
const savedKeySet = Object.keys(config.detectors ?? {}).sort();
|
||||
detectorKeysChanged =
|
||||
JSON.stringify(pendingKeySet) !== JSON.stringify(savedKeySet);
|
||||
}
|
||||
let modelTabChanged = false;
|
||||
if (sanitizedModel && typeof sanitizedModel === "object") {
|
||||
const newPath = (sanitizedModel as { path?: string }).path;
|
||||
const oldPath = config.model?.path;
|
||||
const newIsPlus =
|
||||
typeof newPath === "string" && newPath.startsWith("plus://");
|
||||
const oldIsPlus =
|
||||
typeof oldPath === "string" && oldPath.startsWith("plus://");
|
||||
modelTabChanged = newIsPlus !== oldIsPlus;
|
||||
}
|
||||
|
||||
if (detectorKeysChanged || modelTabChanged) {
|
||||
try {
|
||||
await axios.put("config/set", {
|
||||
requires_restart: 0,
|
||||
config_data: { detectors: null, model: null },
|
||||
});
|
||||
} catch {
|
||||
// best-effort cleanup; the merge-write below will surface any
|
||||
// real error.
|
||||
}
|
||||
}
|
||||
|
||||
const combinedConfigData: Record<string, unknown> = {};
|
||||
if (sanitizedDetectors !== undefined) {
|
||||
combinedConfigData.detectors = sanitizedDetectors;
|
||||
}
|
||||
if (sanitizedModel !== undefined) {
|
||||
combinedConfigData.model = sanitizedModel;
|
||||
}
|
||||
|
||||
await axios.put("config/set", {
|
||||
requires_restart: 0,
|
||||
config_data: combinedConfigData,
|
||||
});
|
||||
|
||||
if (hasPendingDetectors) {
|
||||
keysToClear.push("detectors");
|
||||
savedKeys.push("detectors");
|
||||
}
|
||||
if (hasPendingModel) {
|
||||
keysToClear.push("model");
|
||||
savedKeys.push("model");
|
||||
}
|
||||
|
||||
if (hasPendingDetectors || hasPendingModel) {
|
||||
successCount++;
|
||||
anyNeedsRestart = true;
|
||||
}
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(
|
||||
"Save All – error saving detectors/model atomically",
|
||||
error,
|
||||
);
|
||||
if (hasPendingDetectors || hasPendingModel) {
|
||||
failCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const pendingKeys = Object.keys(pendingDataBySection).filter(
|
||||
(key) => key !== "detectors" && key !== "model",
|
||||
);
|
||||
|
||||
for (const key of pendingKeys) {
|
||||
const pendingData = pendingDataBySection[key];
|
||||
@ -836,11 +948,8 @@ export default function Settings() {
|
||||
});
|
||||
|
||||
if (!payload) {
|
||||
// No actual overrides — clear the pending entry
|
||||
setPendingDataBySection((prev) => {
|
||||
const { [key]: _, ...rest } = prev;
|
||||
return rest;
|
||||
});
|
||||
// No actual overrides — schedule the pending entry for clearing
|
||||
keysToClear.push(key);
|
||||
successCount++;
|
||||
continue;
|
||||
}
|
||||
@ -859,11 +968,8 @@ export default function Settings() {
|
||||
anyNeedsRestart = true;
|
||||
}
|
||||
|
||||
// Clear pending entry on success
|
||||
setPendingDataBySection((prev) => {
|
||||
const { [key]: _, ...rest } = prev;
|
||||
return rest;
|
||||
});
|
||||
// Defer clearing the pending entry until after mutate("config") resolves
|
||||
keysToClear.push(key);
|
||||
savedKeys.push(key);
|
||||
successCount++;
|
||||
} catch (error) {
|
||||
@ -873,10 +979,22 @@ export default function Settings() {
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh config from server once
|
||||
// Refresh config from server once — must complete before clearing the
|
||||
// pending entries so consumers don't observe a moment where pending is
|
||||
// empty AND config is still stale
|
||||
await mutate("config");
|
||||
mutate("config/raw_paths");
|
||||
|
||||
if (keysToClear.length > 0) {
|
||||
setPendingDataBySection((prev) => {
|
||||
const next = { ...prev };
|
||||
for (const key of keysToClear) {
|
||||
delete next[key];
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
// Clear hasChanges in sidebar for all successfully saved sections
|
||||
if (savedKeys.length > 0) {
|
||||
setSectionStatusByKey((prev) => {
|
||||
@ -900,11 +1018,12 @@ export default function Settings() {
|
||||
if (failCount === 0) {
|
||||
if (anyNeedsRestart) {
|
||||
toast.success(
|
||||
t("toast.saveAllSuccess", {
|
||||
t("toast.saveAllSuccessRestartRequired", {
|
||||
ns: "views/settings",
|
||||
count: successCount,
|
||||
}),
|
||||
{
|
||||
duration: 10000,
|
||||
action: (
|
||||
<a onClick={() => setRestartDialogOpen(true)}>
|
||||
<Button>
|
||||
|
||||
@ -50,6 +50,11 @@ import {
|
||||
import { ConfigSectionTemplate } from "@/components/config-form/sections";
|
||||
import { ConfigMessageBanner } from "@/components/config-form/ConfigMessageBanner";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import {
|
||||
getSectionConfig,
|
||||
resolveHiddenFieldEntries,
|
||||
sanitizeSectionData,
|
||||
} from "@/utils/configUtil";
|
||||
|
||||
type ModelTab = "plus" | "custom";
|
||||
|
||||
@ -107,6 +112,8 @@ const TYPE_MODEL_DEFAULTS: Record<string, ConfigSectionData> = {
|
||||
|
||||
const STATUS_BAR_KEY = "detectors_and_model";
|
||||
|
||||
const EMPTY_PENDING: Record<string, ConfigSectionData> = {};
|
||||
|
||||
const deriveInitialState = (config: FrigateConfig): PageState => {
|
||||
const plusModelId = config.model?.plus?.id;
|
||||
const modelPath = config.model?.path;
|
||||
@ -150,6 +157,11 @@ const deriveInitialState = (config: FrigateConfig): PageState => {
|
||||
|
||||
export default function DetectorsAndModelSettingsView({
|
||||
setUnsavedChanges,
|
||||
pendingDataBySection,
|
||||
onPendingDataChange,
|
||||
onSectionStatusChange,
|
||||
isSavingAll,
|
||||
onSectionSavingChange,
|
||||
}: SettingsPageProps) {
|
||||
const { t } = useTranslation(["views/settings", "common"]);
|
||||
const { getLocaleDocUrl } = useDocDomain();
|
||||
@ -157,15 +169,17 @@ export default function DetectorsAndModelSettingsView({
|
||||
const { mutate: globalMutate } = useSWRConfig();
|
||||
const { addMessage, removeMessage } = useContext(StatusBarMessagesContext)!;
|
||||
|
||||
const [snapshot, setSnapshot] = useState<PageState | null>(null);
|
||||
// track the saved config
|
||||
const snapshot = useMemo<PageState | null>(
|
||||
() => (config ? deriveInitialState(config) : null),
|
||||
[config],
|
||||
);
|
||||
const [state, setState] = useState<PageState | null>(null);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [resetKey, setResetKey] = useState(0);
|
||||
const [restartDialogOpen, setRestartDialogOpen] = useState(false);
|
||||
const { send: sendRestart } = useRestart();
|
||||
const [childPending, setChildPending] = useState<
|
||||
Record<string, ConfigSectionData>
|
||||
>({});
|
||||
const childPending = pendingDataBySection ?? EMPTY_PENDING;
|
||||
const [detectorStatus, setDetectorStatus] = useState<SectionStatus>({
|
||||
hasChanges: false,
|
||||
isOverridden: false,
|
||||
@ -208,13 +222,38 @@ export default function DetectorsAndModelSettingsView({
|
||||
|
||||
const isFilterActive = !showBaseModels || !showFineTunedModels;
|
||||
|
||||
const detectorHiddenFields = useMemo(
|
||||
() =>
|
||||
resolveHiddenFieldEntries(
|
||||
getSectionConfig("detectors", "global").hiddenFields,
|
||||
config,
|
||||
),
|
||||
[config],
|
||||
);
|
||||
const modelHiddenFields = useMemo(
|
||||
() =>
|
||||
resolveHiddenFieldEntries(
|
||||
getSectionConfig("model", "global").hiddenFields,
|
||||
config,
|
||||
),
|
||||
[config],
|
||||
);
|
||||
|
||||
const liveDetectors = useMemo(
|
||||
() => childPending["detectors"] ?? snapshot?.detectors,
|
||||
[childPending, snapshot],
|
||||
);
|
||||
const liveCustomModel = useMemo(
|
||||
() => childPending["model"] ?? snapshot?.customModel,
|
||||
[childPending, snapshot],
|
||||
);
|
||||
|
||||
const currentDetectorType = useMemo(() => {
|
||||
if (!state) return undefined;
|
||||
const values = Object.values(state.detectors ?? {});
|
||||
const values = Object.values(liveDetectors ?? {});
|
||||
if (values.length === 0) return undefined;
|
||||
const first = values[0] as { type?: string } | undefined;
|
||||
return first?.type;
|
||||
}, [state]);
|
||||
}, [liveDetectors]);
|
||||
|
||||
// fill in defaults when detector type changes
|
||||
const prevDetectorTypeRef = useRef<string | undefined>(undefined);
|
||||
@ -226,28 +265,25 @@ export default function DetectorsAndModelSettingsView({
|
||||
if (!newType || !(newType in TYPE_MODEL_DEFAULTS)) return;
|
||||
|
||||
const defaults = TYPE_MODEL_DEFAULTS[newType];
|
||||
setChildPending((prev) => {
|
||||
const next: Record<string, ConfigSectionData> = {
|
||||
...prev,
|
||||
model: defaults,
|
||||
onPendingDataChange?.("model", undefined, defaults);
|
||||
|
||||
if (newType === "openvino") {
|
||||
const detectorsCurrent = (childPending.detectors ??
|
||||
state?.detectors ??
|
||||
{}) as {
|
||||
[key: string]: { device?: string };
|
||||
};
|
||||
if (newType === "openvino") {
|
||||
const detectorsCurrent = (prev.detectors ?? state?.detectors ?? {}) as {
|
||||
[key: string]: { device?: string };
|
||||
};
|
||||
const entries = Object.entries(detectorsCurrent);
|
||||
if (entries.length > 0) {
|
||||
const [firstKey, firstValue] = entries[0];
|
||||
if (!firstValue?.device) {
|
||||
next.detectors = {
|
||||
...detectorsCurrent,
|
||||
[firstKey]: { ...firstValue, device: "CPU" },
|
||||
} as ConfigSectionData;
|
||||
}
|
||||
const entries = Object.entries(detectorsCurrent);
|
||||
if (entries.length > 0) {
|
||||
const [firstKey, firstValue] = entries[0];
|
||||
if (!firstValue?.device) {
|
||||
onPendingDataChange?.("detectors", undefined, {
|
||||
...detectorsCurrent,
|
||||
[firstKey]: { ...firstValue, device: "CPU" },
|
||||
} as ConfigSectionData);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [currentDetectorType]);
|
||||
|
||||
@ -271,72 +307,121 @@ export default function DetectorsAndModelSettingsView({
|
||||
|
||||
const plusModelMissing = state?.modelTab === "plus" && !state?.plusModelId;
|
||||
|
||||
const handleChildPendingChange = useCallback(
|
||||
(
|
||||
sectionKey: string,
|
||||
_cameraName: string | undefined,
|
||||
data: ConfigSectionData | null,
|
||||
) => {
|
||||
setChildPending((prev) => {
|
||||
if (data === null) {
|
||||
if (!(sectionKey in prev)) return prev;
|
||||
const { [sectionKey]: _drop, ...rest } = prev;
|
||||
return rest;
|
||||
}
|
||||
return { ...prev, [sectionKey]: data };
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleDetectorStatusChange = useCallback(
|
||||
(status: SectionStatus) => setDetectorStatus(status),
|
||||
[],
|
||||
(status: SectionStatus) => {
|
||||
setDetectorStatus(status);
|
||||
onSectionStatusChange?.("detectors", "global", status);
|
||||
},
|
||||
[onSectionStatusChange],
|
||||
);
|
||||
|
||||
// BaseSection drives `modelStatus` only when the Custom tab is mounted
|
||||
const handleModelStatusChange = useCallback(
|
||||
(status: SectionStatus) => setModelStatus(status),
|
||||
[],
|
||||
);
|
||||
|
||||
// report the *combined* model-section status to the parent
|
||||
useEffect(() => {
|
||||
const detectorsPending = childPending["detectors"];
|
||||
setState((prev) => {
|
||||
if (!prev || !snapshot) return prev;
|
||||
// When the embedded form un-modifies (data returns to baseline) it clears
|
||||
// its entry from childPending — fall back to snapshot so state.detectors
|
||||
// doesn't keep a stale value the user has visually reverted.
|
||||
return {
|
||||
...prev,
|
||||
detectors: detectorsPending ?? snapshot.detectors,
|
||||
};
|
||||
if (!state || !snapshot) return;
|
||||
const tabChanged = state.modelTab !== snapshot.modelTab;
|
||||
const plusIdChanged =
|
||||
state.modelTab === "plus" && state.plusModelId !== snapshot.plusModelId;
|
||||
const pageLevelDirty = tabChanged || plusIdChanged;
|
||||
onSectionStatusChange?.("model", "global", {
|
||||
hasChanges: modelStatus.hasChanges || pageLevelDirty,
|
||||
isOverridden: modelStatus.isOverridden,
|
||||
overrideSource: modelStatus.overrideSource,
|
||||
hasValidationErrors: modelStatus.hasValidationErrors,
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [childPending["detectors"]]);
|
||||
}, [state, snapshot, modelStatus, onSectionStatusChange]);
|
||||
|
||||
// Tab toggle and Plus-model selection are page-local UI, but Save All and the
|
||||
// sidebar dot live on `pendingDataBySection["model"]` and section status from
|
||||
// the parent. These handlers mirror Plus-tab changes into both so a Plus-only
|
||||
// edit (no custom-form typing) is still dirty and survives navigation.
|
||||
const handleModelTabChange = useCallback(
|
||||
(newTab: ModelTab) => {
|
||||
setState((prev) => (prev ? { ...prev, modelTab: newTab } : prev));
|
||||
if (!snapshot) return;
|
||||
|
||||
if (newTab === "plus") {
|
||||
if (state?.plusModelId) {
|
||||
onPendingDataChange?.("model", undefined, {
|
||||
path: `plus://${state.plusModelId}`,
|
||||
} as ConfigSectionData);
|
||||
} else {
|
||||
// No Plus model selected — clear any stale pending so the save
|
||||
// action is correctly disabled until the user picks one.
|
||||
onPendingDataChange?.("model", undefined, null);
|
||||
}
|
||||
} else {
|
||||
// Switching to Custom: if pending["model"] still holds a plus path
|
||||
// from a previous Plus selection, swap it for the snapshot's custom
|
||||
// model so Save All writes the correct payload. Don't overwrite
|
||||
// genuine custom-form edits the user typed earlier.
|
||||
const currentPath = (
|
||||
pendingDataBySection?.["model"] as { path?: string } | undefined
|
||||
)?.path;
|
||||
if (
|
||||
typeof currentPath === "string" &&
|
||||
currentPath.startsWith("plus://")
|
||||
) {
|
||||
onPendingDataChange?.(
|
||||
"model",
|
||||
undefined,
|
||||
snapshot.customModel as ConfigSectionData,
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
[state?.plusModelId, snapshot, pendingDataBySection, onPendingDataChange],
|
||||
);
|
||||
|
||||
const handlePlusModelIdChange = useCallback(
|
||||
(newId: string) => {
|
||||
setState((prev) => (prev ? { ...prev, plusModelId: newId } : prev));
|
||||
onPendingDataChange?.("model", undefined, {
|
||||
path: `plus://${newId}`,
|
||||
} as ConfigSectionData);
|
||||
},
|
||||
[onPendingDataChange],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const modelPending = childPending["model"];
|
||||
setState((prev) => {
|
||||
if (!prev || !snapshot) return prev;
|
||||
return {
|
||||
...prev,
|
||||
customModel: modelPending ?? snapshot.customModel,
|
||||
};
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [childPending["model"]]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!config || snapshot !== null) return;
|
||||
if (!config || state !== null) return;
|
||||
const initial = deriveInitialState(config);
|
||||
setSnapshot(initial);
|
||||
setState(initial);
|
||||
}, [config, snapshot]);
|
||||
|
||||
// Restore Plus-tab UI state from any prior pending edits the user made
|
||||
// before navigating away. `pendingDataBySection["model"]` is the source of
|
||||
// truth for Save All; infer modelTab/plusModelId from it so the UI lines up.
|
||||
const pendingModel = pendingDataBySection?.["model"] as
|
||||
| { path?: string }
|
||||
| undefined;
|
||||
const pendingPath = pendingModel?.path;
|
||||
if (typeof pendingPath === "string" && pendingPath.startsWith("plus://")) {
|
||||
setState({
|
||||
...initial,
|
||||
modelTab: "plus",
|
||||
plusModelId: pendingPath.slice("plus://".length) || undefined,
|
||||
});
|
||||
} else if (pendingModel && initial.modelTab === "plus") {
|
||||
// There's a pending custom-model edit while the saved tab was Plus —
|
||||
// means the user already switched to Custom before navigating away.
|
||||
setState({ ...initial, modelTab: "custom" });
|
||||
} else {
|
||||
setState(initial);
|
||||
}
|
||||
}, [config, state, pendingDataBySection]);
|
||||
|
||||
const isDirty = useMemo(() => {
|
||||
if (!state || !snapshot) return false;
|
||||
return JSON.stringify(state) !== JSON.stringify(snapshot);
|
||||
}, [state, snapshot]);
|
||||
if (state.modelTab !== snapshot.modelTab) return true;
|
||||
if (state.plusModelId !== snapshot.plusModelId) return true;
|
||||
if ("detectors" in childPending) return true;
|
||||
if ("model" in childPending) return true;
|
||||
return false;
|
||||
}, [state, snapshot, childPending]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isDirty) {
|
||||
@ -362,24 +447,38 @@ export default function DetectorsAndModelSettingsView({
|
||||
|
||||
const tabChanged = state.modelTab !== snapshot.modelTab;
|
||||
|
||||
// Strip computed/merged fields that the backend populates in /config
|
||||
// responses but doesn't accept back on /config/set.
|
||||
const sanitizedDetectors = sanitizeSectionData(
|
||||
liveDetectors ?? {},
|
||||
detectorHiddenFields,
|
||||
);
|
||||
const sanitizedCustomModel = sanitizeSectionData(
|
||||
liveCustomModel ?? {},
|
||||
modelHiddenFields,
|
||||
);
|
||||
|
||||
const modelPayload =
|
||||
state.modelTab === "plus"
|
||||
? { path: `plus://${state.plusModelId}` }
|
||||
: state.customModel;
|
||||
: sanitizedCustomModel;
|
||||
|
||||
const detectorKeysChanged =
|
||||
JSON.stringify(Object.keys(state.detectors).sort()) !==
|
||||
JSON.stringify(Object.keys(liveDetectors ?? {}).sort()) !==
|
||||
JSON.stringify(Object.keys(snapshot.detectors).sort());
|
||||
|
||||
setIsSaving(true);
|
||||
onSectionSavingChange?.(true);
|
||||
let preCleared = false;
|
||||
try {
|
||||
// Pre-clear both `detectors` and `model` together when a renaming
|
||||
// Pre-clear both `detectors` and `model` together when renaming
|
||||
if (tabChanged || detectorKeysChanged) {
|
||||
try {
|
||||
await axios.put("config/set", {
|
||||
requires_restart: 0,
|
||||
config_data: { detectors: null, model: null },
|
||||
});
|
||||
preCleared = true;
|
||||
} catch {
|
||||
// best-effort cleanup
|
||||
}
|
||||
@ -388,7 +487,7 @@ export default function DetectorsAndModelSettingsView({
|
||||
await axios.put("config/set", {
|
||||
requires_restart: 0,
|
||||
config_data: {
|
||||
detectors: state.detectors,
|
||||
detectors: sanitizedDetectors,
|
||||
model: modelPayload,
|
||||
},
|
||||
});
|
||||
@ -396,9 +495,11 @@ export default function DetectorsAndModelSettingsView({
|
||||
await globalMutate("config");
|
||||
await globalMutate("config/raw_paths");
|
||||
|
||||
// Re-derive snapshot from the freshly saved state so isDirty resets.
|
||||
setSnapshot({ ...state });
|
||||
setChildPending({});
|
||||
// `snapshot` is derived from `config` via useMemo, so the awaited mutate
|
||||
// above has already refreshed it. Just clear the pending entries — that
|
||||
// resets isDirty since state should now match snapshot.
|
||||
onPendingDataChange?.("detectors", undefined, null);
|
||||
onPendingDataChange?.("model", undefined, null);
|
||||
setResetKey((k) => k + 1);
|
||||
|
||||
addMessage(
|
||||
@ -410,6 +511,7 @@ export default function DetectorsAndModelSettingsView({
|
||||
|
||||
toast.success(t("detectorsAndModel.toast.saveSuccess"), {
|
||||
position: "top-center",
|
||||
duration: 10000,
|
||||
action: (
|
||||
<Button onClick={() => setRestartDialogOpen(true)}>
|
||||
{t("restart.button", { ns: "components/dialog" })}
|
||||
@ -425,24 +527,60 @@ export default function DetectorsAndModelSettingsView({
|
||||
err.response?.data?.detail ||
|
||||
t("detectorsAndModel.toast.saveError");
|
||||
toast.error(message, { position: "top-center" });
|
||||
// Re-sync the config cache in case the two-step PUT left the backend
|
||||
// ahead of the frontend (e.g. step 1 cleared `model` but step 2 failed).
|
||||
|
||||
if (preCleared) {
|
||||
const restoreModel =
|
||||
snapshot.modelTab === "plus" && snapshot.plusModelId
|
||||
? { path: `plus://${snapshot.plusModelId}` }
|
||||
: sanitizeSectionData(snapshot.customModel, modelHiddenFields);
|
||||
try {
|
||||
await axios.put("config/set", {
|
||||
requires_restart: 0,
|
||||
config_data: {
|
||||
detectors: sanitizeSectionData(
|
||||
snapshot.detectors,
|
||||
detectorHiddenFields,
|
||||
),
|
||||
model: restoreModel,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
// best-effort
|
||||
}
|
||||
}
|
||||
|
||||
// Re-sync the config cache to reflect whatever state the backend
|
||||
// landed on after the failure (and any restore attempt).
|
||||
await globalMutate("config");
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
onSectionSavingChange?.(false);
|
||||
}
|
||||
}, [state, snapshot, globalMutate, addMessage, t]);
|
||||
}, [
|
||||
state,
|
||||
snapshot,
|
||||
liveDetectors,
|
||||
liveCustomModel,
|
||||
detectorHiddenFields,
|
||||
modelHiddenFields,
|
||||
globalMutate,
|
||||
onSectionSavingChange,
|
||||
addMessage,
|
||||
onPendingDataChange,
|
||||
t,
|
||||
]);
|
||||
|
||||
const onUndo = useCallback(() => {
|
||||
if (snapshot) {
|
||||
setState(snapshot);
|
||||
setChildPending({});
|
||||
onPendingDataChange?.("detectors", undefined, null);
|
||||
onPendingDataChange?.("model", undefined, null);
|
||||
// Force the embedded forms to re-mount so their internal dirty/baseline
|
||||
// state is rebuilt from the current config — clearing childPending alone
|
||||
// state is rebuilt from the current config — clearing pending alone
|
||||
// doesn't reset BaseSection's internal tracking.
|
||||
setResetKey((k) => k + 1);
|
||||
}
|
||||
}, [snapshot]);
|
||||
}, [snapshot, onPendingDataChange]);
|
||||
|
||||
if (!config || !state) {
|
||||
return <ActivityIndicator />;
|
||||
@ -451,6 +589,7 @@ export default function DetectorsAndModelSettingsView({
|
||||
const saveDisabled =
|
||||
!isDirty ||
|
||||
isSaving ||
|
||||
isSavingAll ||
|
||||
detectorStatus.hasValidationErrors ||
|
||||
(state.modelTab === "custom" && modelStatus.hasValidationErrors) ||
|
||||
plusMismatch ||
|
||||
@ -497,7 +636,7 @@ export default function DetectorsAndModelSettingsView({
|
||||
showTitle={false}
|
||||
embedded
|
||||
pendingDataBySection={childPending}
|
||||
onPendingDataChange={handleChildPendingChange}
|
||||
onPendingDataChange={onPendingDataChange}
|
||||
onStatusChange={handleDetectorStatusChange}
|
||||
/>
|
||||
</SettingsGroupCard>
|
||||
@ -522,9 +661,7 @@ export default function DetectorsAndModelSettingsView({
|
||||
<Tabs
|
||||
value={state.modelTab}
|
||||
onValueChange={(value) =>
|
||||
setState((prev) =>
|
||||
prev ? { ...prev, modelTab: value as ModelTab } : prev,
|
||||
)
|
||||
handleModelTabChange(value as ModelTab)
|
||||
}
|
||||
>
|
||||
<TabsList className="mb-4">
|
||||
@ -548,11 +685,7 @@ export default function DetectorsAndModelSettingsView({
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<Select
|
||||
value={state.plusModelId}
|
||||
onValueChange={(value) =>
|
||||
setState((prev) =>
|
||||
prev ? { ...prev, plusModelId: value } : prev,
|
||||
)
|
||||
}
|
||||
onValueChange={handlePlusModelIdChange}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
{state.plusModelId &&
|
||||
@ -712,7 +845,7 @@ export default function DetectorsAndModelSettingsView({
|
||||
showTitle={false}
|
||||
embedded
|
||||
pendingDataBySection={childPending}
|
||||
onPendingDataChange={handleChildPendingChange}
|
||||
onPendingDataChange={onPendingDataChange}
|
||||
onStatusChange={handleModelStatusChange}
|
||||
/>
|
||||
</TabsContent>
|
||||
@ -726,7 +859,7 @@ export default function DetectorsAndModelSettingsView({
|
||||
showTitle={false}
|
||||
embedded
|
||||
pendingDataBySection={childPending}
|
||||
onPendingDataChange={handleChildPendingChange}
|
||||
onPendingDataChange={onPendingDataChange}
|
||||
onStatusChange={handleModelStatusChange}
|
||||
/>
|
||||
)}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user