SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
fix(alerts): ensure edit alert name is updated correctly and not override after save (#11348)
Vinicius Lourenço475755018936
diff --git a/frontend/src/container/CreateAlertV2/CreateAlertHeader/CreateAlertHeader.tsx b/frontend/src/container/CreateAlertV2/CreateAlertHeader/CreateAlertHeader.tsxindex f5fb1d90b7..256ab56347 100644--- a/frontend/src/container/CreateAlertV2/CreateAlertHeader/CreateAlertHeader.tsx+++ b/frontend/src/container/CreateAlertV2/CreateAlertHeader/CreateAlertHeader.tsx@@ -9,6 +9,7 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';import { useSafeNavigate } from 'hooks/useSafeNavigate';import useUrlQuery from 'hooks/useUrlQuery';import { RotateCcw } from '@signozhq/icons';+import { useAlertRuleOptional } from 'providers/Alert';import { Labels } from 'types/api/alerts/def';import { useCreateAlertState } from '../context';@@ -18,6 +19,7 @@ import './styles.scss';function CreateAlertHeader(): JSX.Element {const { alertState, setAlertState, isEditMode } = useCreateAlertState();+ const alertRuleContext = useAlertRuleOptional();const { currentQuery } = useQueryBuilder();const { safeNavigate } = useSafeNavigate();@@ -74,9 +76,13 @@ function CreateAlertHeader(): JSX.Element {<Inputtype="text"value={alertState.name}- onChange={(e): void =>- setAlertState({ type: 'SET_ALERT_NAME', payload: e.target.value })- }+ onChange={(e): void => {+ const newName = e.target.value;+ setAlertState({ type: 'SET_ALERT_NAME', payload: newName });+ if (isEditMode && alertRuleContext?.setAlertRuleName) {+ alertRuleContext.setAlertRuleName(newName);+ }+ }}className="alert-header__input title"placeholder="Enter alert rule name"data-testid="alert-name-input"diff --git a/frontend/src/container/CreateAlertV2/Footer/Footer.tsx b/frontend/src/container/CreateAlertV2/Footer/Footer.tsxindex 2f1096295d..ddf867e85a 100644--- a/frontend/src/container/CreateAlertV2/Footer/Footer.tsx+++ b/frontend/src/container/CreateAlertV2/Footer/Footer.tsx@@ -20,6 +20,11 @@ import {} from './utils';import './styles.scss';+import {+ invalidateGetRuleByID,+ invalidateListRules,+} from 'api/generated/services/rules';+import { useQueryClient } from 'react-query';function Footer(): JSX.Element {const {@@ -115,6 +120,7 @@ function Footer(): JSX.Element {testAlertRule,]);+ const queryClient = useQueryClient();const handleSaveAlert = useCallback((): void => {const payload = buildCreateThresholdAlertRulePayload({alertType,@@ -133,6 +139,9 @@ function Footer(): JSX.Element {},{onSuccess: () => {+ void invalidateGetRuleByID(queryClient, { id: ruleId });+ void invalidateListRules(queryClient);+toast.success('Alert rule updated successfully');safeNavigate('/alerts');},diff --git a/frontend/src/container/CreateAlertV2/Footer/__tests__/Footer.test.tsx b/frontend/src/container/CreateAlertV2/Footer/__tests__/Footer.test.tsxindex 93f9a779f1..78ab6f474a 100644--- a/frontend/src/container/CreateAlertV2/Footer/__tests__/Footer.test.tsx+++ b/frontend/src/container/CreateAlertV2/Footer/__tests__/Footer.test.tsx@@ -7,6 +7,7 @@ import { createMockAlertContextState } from 'container/CreateAlertV2/EvaluationSimport * as createAlertState from '../../context';import Footer from '../Footer';+import MockQueryClientProvider from 'providers/test/MockQueryClientProvider';// Mock the hooks used by Footer componentjest.mock('hooks/queryBuilder/useQueryBuilder', () => ({@@ -64,6 +65,12 @@ const mockAlertContextState = createMockAlertContextState({},});+const WrappedFooter = (): JSX.Element => (+ <MockQueryClientProvider>+ <Footer />+ </MockQueryClientProvider>+);+jest.spyOn(createAlertState, 'useCreateAlertState').mockReturnValue(mockAlertContextState);@@ -97,20 +104,20 @@ describe('Footer', () => {});it('should render the component with 3 buttons', () => {- render(<Footer />);+ render(<WrappedFooter />);expect(screen.getByText(SAVE_ALERT_RULE_TEXT)).toBeInTheDocument();expect(screen.getByText(TEST_NOTIFICATION_TEXT)).toBeInTheDocument();expect(screen.getByText(DISCARD_TEXT)).toBeInTheDocument();});it('discard action works correctly', () => {- render(<Footer />);+ render(<WrappedFooter />);fireEvent.click(screen.getByText(DISCARD_TEXT));expect(mockDiscardAlertRule).toHaveBeenCalled();});it('save alert rule action works correctly', () => {- render(<Footer />);+ render(<WrappedFooter />);fireEvent.click(screen.getByText(SAVE_ALERT_RULE_TEXT));expect(mockCreateAlertRule).toHaveBeenCalled();});@@ -120,13 +127,13 @@ describe('Footer', () => {...mockAlertContextState,isEditMode: true,});- render(<Footer />);+ render(<WrappedFooter />);fireEvent.click(screen.getByText(SAVE_ALERT_RULE_TEXT));expect(mockUpdateAlertRule).toHaveBeenCalled();});it('test notification action works correctly', () => {- render(<Footer />);+ render(<WrappedFooter />);fireEvent.click(screen.getByText(TEST_NOTIFICATION_TEXT));expect(mockTestAlertRule).toHaveBeenCalled();});@@ -136,7 +143,7 @@ describe('Footer', () => {...mockAlertContextState,isCreatingAlertRule: true,});- render(<Footer />);+ render(<WrappedFooter />);expect(screen.getByRole('button', { name: /save alert rule/i }),@@ -152,7 +159,7 @@ describe('Footer', () => {...mockAlertContextState,isUpdatingAlertRule: true,});- render(<Footer />);+ render(<WrappedFooter />);// Target the button elements directly instead of the text spans inside themexpect(@@ -169,7 +176,7 @@ describe('Footer', () => {...mockAlertContextState,isTestingAlertRule: true,});- render(<Footer />);+ render(<WrappedFooter />);// Target the button elements directly instead of the text spans inside themexpect(@@ -189,7 +196,7 @@ describe('Footer', () => {name: '',},});- render(<Footer />);+ render(<WrappedFooter />);expect(screen.getByRole('button', { name: /save alert rule/i }),@@ -217,7 +224,7 @@ describe('Footer', () => {},});- render(<Footer />);+ render(<WrappedFooter />);expect(screen.getByRole('button', { name: /save alert rule/i }),@@ -245,7 +252,7 @@ describe('Footer', () => {},});- render(<Footer />);+ render(<WrappedFooter />);expect(screen.getByRole('button', { name: /save alert rule/i }),@@ -261,7 +268,7 @@ describe('Footer', () => {...mockAlertContextState,isTestingAlertRule: true,});- render(<Footer />);+ render(<WrappedFooter />);// When testing alert rule, the play icon is replaced with a loader iconexpect(@@ -276,7 +283,7 @@ describe('Footer', () => {...mockAlertContextState,isUpdatingAlertRule: true,});- render(<Footer />);+ render(<WrappedFooter />);// When updating alert rule, the check icon is replaced with a loader iconexpect(@@ -291,7 +298,7 @@ describe('Footer', () => {...mockAlertContextState,isCreatingAlertRule: true,});- render(<Footer />);+ render(<WrappedFooter />);// When creating alert rule, the check icon is replaced with a loader iconexpect(diff --git a/frontend/src/container/FormAlertRules/index.tsx b/frontend/src/container/FormAlertRules/index.tsxindex 4b63373001..7c218f6119 100644--- a/frontend/src/container/FormAlertRules/index.tsx+++ b/frontend/src/container/FormAlertRules/index.tsx@@ -38,6 +38,7 @@ import { mapQueryDataFromApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapimport { mapQueryDataToApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataToApi';import { isEmpty, isEqual } from 'lodash-es';import Tabs2 from 'periscope/components/Tabs2';+import { useAlertRuleOptional } from 'providers/Alert';import { useAppContext } from 'providers/App/App';import { useErrorModal } from 'providers/ErrorModalProvider';import { AppState } from 'store/reducers';@@ -92,7 +93,6 @@ const ALERT_SETUP_GUIDE_URLS: Record<AlertTypes, string> = {'https://signoz.io/docs/alerts-management/anomaly-based-alerts/?utm_source=product&utm_medium=alert-creation-page',};-// eslint-disable-next-line sonarjs/cognitive-complexityfunction FormAlertRules({alertType,formInstance,@@ -160,6 +160,32 @@ function FormAlertRules({const [alertDef, setAlertDef] = useState<AlertDef>(initialValue);const [yAxisUnit, setYAxisUnit] = useState<string>(currentQuery.unit || '');+ const alertRuleContext = useAlertRuleOptional();+ const providerAlertName = alertRuleContext?.alertRuleName;+ useEffect(() => {+ if (providerAlertName) {+ setAlertDef((prev) => {+ if (prev.alert === providerAlertName) {+ return prev;+ }+ return { ...prev, alert: providerAlertName };+ });+ formInstance.setFieldsValue({ alert: providerAlertName });+ }+ }, [providerAlertName, formInstance]);++ // Wrap setAlertDef to sync alert name to provider when user types+ const handleSetAlertDef = useCallback(+ (newDef: AlertDef) => {+ setAlertDef(newDef);+ // Sync alert name change to provider for header display+ if (newDef.alert !== alertDef.alert && alertRuleContext?.setAlertRuleName) {+ alertRuleContext.setAlertRuleName(newDef.alert);+ }+ },+ [alertDef.alert, alertRuleContext],+ );+const alertTypeFromURL = urlQuery.get(QueryParams.ruleType);const [detectionMethod, setDetectionMethod] = useState<string | null>(null);@@ -680,7 +706,7 @@ function FormAlertRules({const renderBasicInfo = (): JSX.Element => (<BasicInfoalertDef={alertDef}- setAlertDef={setAlertDef}+ setAlertDef={handleSetAlertDef}isNewRule={isNewRule}/>);diff --git a/frontend/src/pages/AlertDetails/AlertDetails.tsx b/frontend/src/pages/AlertDetails/AlertDetails.tsxindex 230f5e5bc9..1bdfd8454f 100644--- a/frontend/src/pages/AlertDetails/AlertDetails.tsx+++ b/frontend/src/pages/AlertDetails/AlertDetails.tsx@@ -13,6 +13,7 @@ import { CreateAlertProvider } from 'container/CreateAlertV2/context';import { getCreateAlertLocalStateFromAlertDef } from 'container/CreateAlertV2/utils';import useUrlQuery from 'hooks/useUrlQuery';import history from 'lib/history';+import { useAlertRule } from 'providers/Alert';import { AlertTypes } from 'types/api/alerts/alertTypes';import { NEW_ALERT_SCHEMA_VERSION } from 'types/api/alerts/alertTypesV2';import { fromRuleDTOToPostableRuleV2 } from 'types/api/alerts/convert';@@ -27,6 +28,7 @@ function AlertDetails(): JSX.Element {const { pathname } = useLocation();const { routes } = useRouteTabUtils();const params = useUrlQuery();+ const { alertRuleName } = useAlertRule();const { isLoading, isError, ruleId, isValidRuleId, alertDetailsResponse } =useGetAlertRuleDetails();@@ -36,7 +38,7 @@ function AlertDetails(): JSX.Element {}, [params]);const getDocumentTitle = useMemo(() => {- const alertTitle = alertDetailsResponse?.data?.alert;+ const alertTitle = alertRuleName ?? alertDetailsResponse?.data?.alert;if (alertTitle) {return alertTitle;}@@ -47,7 +49,7 @@ function AlertDetails(): JSX.Element {return document.title;}return 'Alert Not Found';- }, [alertDetailsResponse?.data?.alert, isTestAlert, isLoading]);+ }, [alertRuleName, alertDetailsResponse?.data?.alert, isTestAlert, isLoading]);useEffect(() => {document.title = getDocumentTitle;diff --git a/frontend/src/pages/AlertDetails/AlertHeader/ActionButtons/ActionButtons.tsx b/frontend/src/pages/AlertDetails/AlertHeader/ActionButtons/ActionButtons.tsxindex daea997f19..b49a8bedfa 100644--- a/frontend/src/pages/AlertDetails/AlertHeader/ActionButtons/ActionButtons.tsx+++ b/frontend/src/pages/AlertDetails/AlertHeader/ActionButtons/ActionButtons.tsx@@ -33,13 +33,12 @@ const menuItemStyleV2: CSSProperties = {function AlertActionButtons({ruleId,alertDetails,- setUpdatedName,}: {ruleId: string;alertDetails: AlertHeaderProps['alertDetails'];- setUpdatedName: (name: string) => void;}): JSX.Element {- const { alertRuleState, setAlertRuleState } = useAlertRule();+ const { alertRuleState, setAlertRuleState, alertRuleName, setAlertRuleName } =+ useAlertRule();const [intermediateName, setIntermediateName] = useState<string>(alertDetails.alert,);@@ -53,7 +52,7 @@ function AlertActionButtons({const { handleAlertDelete } = useAlertRuleDelete({ ruleId });const { handleAlertUpdate, isLoading } = useAlertRuleUpdate({alertDetails: alertDetails as unknown as AlertDef,- setUpdatedName,+ setAlertRuleName,intermediateName,});@@ -113,6 +112,12 @@ function AlertActionButtons({}}, [setAlertRuleState, alertRuleState, alertDetails.state]);+ useEffect(() => {+ if (alertRuleName !== undefined) {+ setIntermediateName(alertRuleName);+ }+ }, [alertRuleName]);+// on unmount remove the alert state// eslint-disable-next-line react-hooks/exhaustive-depsuseEffect(() => (): void => setAlertRuleState(undefined), []);diff --git a/frontend/src/pages/AlertDetails/AlertHeader/AlertHeader.tsx b/frontend/src/pages/AlertDetails/AlertHeader/AlertHeader.tsxindex 8403852bf8..4a3696902f 100644--- a/frontend/src/pages/AlertDetails/AlertHeader/AlertHeader.tsx+++ b/frontend/src/pages/AlertDetails/AlertHeader/AlertHeader.tsx@@ -1,4 +1,4 @@-import { useMemo, useState } from 'react';+import { useEffect, useMemo } from 'react';import type { RuletypesRuleDTO } from 'api/generated/services/sigNoz.schemas';import CreateAlertV2Header from 'container/CreateAlertV2/CreateAlertHeader';import LineClampedText from 'periscope/components/LineClampedText/LineClampedText';@@ -20,8 +20,17 @@ export type AlertHeaderProps = {};function AlertHeader({ alertDetails }: AlertHeaderProps): JSX.Element {const { state, alert: alertName, labels } = alertDetails;- const { alertRuleState } = useAlertRule();- const [updatedName, setUpdatedName] = useState(alertName);+ const { alertRuleState, alertRuleName, setAlertRuleName } = useAlertRule();++ useEffect(() => {+ if (alertRuleName === undefined && alertName) {+ setAlertRuleName(alertName);+ }+ }, [alertRuleName, alertName, setAlertRuleName]);++ useEffect(() => (): void => setAlertRuleName(undefined), [setAlertRuleName]);++ const displayName = alertRuleName ?? alertName;const labelsWithoutSeverity = useMemo(() => {if (labels) {@@ -40,7 +49,7 @@ function AlertHeader({ alertDetails }: AlertHeaderProps): JSX.Element {<div className="alert-title-wrapper"><AlertState state={alertRuleState ?? state ?? ''} /><div className="alert-title">- <LineClampedText text={updatedName || alertName} />+ <LineClampedText text={displayName || ''} /></div></div></div>@@ -64,7 +73,6 @@ function AlertHeader({ alertDetails }: AlertHeaderProps): JSX.Element {<AlertActionButtonsalertDetails={alertDetails}ruleId={alertDetails?.id || ''}- setUpdatedName={setUpdatedName}/></div></div>diff --git a/frontend/src/pages/AlertDetails/hooks.tsx b/frontend/src/pages/AlertDetails/hooks.tsxindex 9facd099c9..31117bc2b4 100644--- a/frontend/src/pages/AlertDetails/hooks.tsx+++ b/frontend/src/pages/AlertDetails/hooks.tsx@@ -12,7 +12,9 @@ import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';import {createRule,deleteRuleByID,+ getGetRuleByIDQueryKey,invalidateGetRuleByID,+ invalidateListRules,updateRuleByID,useGetRuleByID,useListRules,@@ -490,11 +492,11 @@ export const useAlertRuleDuplicate = ({};export const useAlertRuleUpdate = ({alertDetails,- setUpdatedName,+ setAlertRuleName,intermediateName,}: {alertDetails: AlertDef;- setUpdatedName: (name: string) => void;+ setAlertRuleName: (name: string | undefined) => void;intermediateName: string;}): {handleAlertUpdate: () => void;@@ -502,17 +504,29 @@ export const useAlertRuleUpdate = ({} => {const { notifications } = useNotifications();const { showErrorModal } = useErrorModal();+ const queryClient = useQueryClient();const { mutate: updateAlertRule, isLoading } = useMutation([REACT_QUERY_KEY.UPDATE_ALERT_RULE, alertDetails.id],(args: { data: AlertDef; id: string }) =>updateRuleByID({ id: args.id }, toPostableRuleDTOFromAlertDef(args.data)),{- onMutate: () => setUpdatedName(intermediateName),- onSuccess: () =>- notifications.success({ message: 'Alert renamed successfully' }),+ onMutate: () => setAlertRuleName(intermediateName),+ onSuccess: () => {+ const ruleId = alertDetails.id || '';+ const ruleQueryKey = getGetRuleByIDQueryKey({ id: ruleId });+ const existingRule = queryClient.getQueryData<GetRuleByID200>(ruleQueryKey);+ if (existingRule) {+ queryClient.setQueryData<GetRuleByID200>(ruleQueryKey, {+ ...existingRule,+ data: { ...existingRule.data, alert: intermediateName },+ });+ }+ void invalidateListRules(queryClient);+ notifications.success({ message: 'Alert renamed successfully' });+ },onError: (error) => {- setUpdatedName(alertDetails.alert);+ setAlertRuleName(alertDetails.alert);showErrorModal(convertToApiError(error as AxiosError<RenderErrorResponseDTO>) as APIError,);@@ -551,7 +565,6 @@ export const useAlertRuleDelete = ({history.push(ROUTES.LIST_ALL_ALERT);},- // eslint-disable-next-line sonarjs/no-identical-functionsonError: (error) =>showErrorModal(convertToApiError(error as AxiosError<RenderErrorResponseDTO>) as APIError,diff --git a/frontend/src/providers/Alert.tsx b/frontend/src/providers/Alert.tsxindex d6b666f13a..a7f7ff7013 100644--- a/frontend/src/providers/Alert.tsx+++ b/frontend/src/providers/Alert.tsx@@ -9,6 +9,8 @@ import React, {interface AlertRuleContextType {alertRuleState: string | undefined;setAlertRuleState: React.Dispatch<React.SetStateAction<string | undefined>>;+ alertRuleName: string | undefined;+ setAlertRuleName: React.Dispatch<React.SetStateAction<string | undefined>>;}const AlertRuleContext = createContext<AlertRuleContextType | undefined>(@@ -23,13 +25,18 @@ function AlertRuleProvider({const [alertRuleState, setAlertRuleState] = useState<string | undefined>(undefined,);+ const [alertRuleName, setAlertRuleName] = useState<string | undefined>(+ undefined,+ );const value = React.useMemo(() => ({alertRuleState,setAlertRuleState,+ alertRuleName,+ setAlertRuleName,}),- [alertRuleState],+ [alertRuleState, alertRuleName],);return (@@ -47,4 +54,7 @@ export const useAlertRule = (): AlertRuleContextType => {return context;};+export const useAlertRuleOptional = (): AlertRuleContextType | undefined =>+ useContext(AlertRuleContext);+export default AlertRuleProvider;