Skip to content

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.

fix: added fix for widget warning/save modal states (#11356)

Abhi kumar5bd4cabbca4a
diff --git a/frontend/src/container/NewWidget/WidgetModals/DiscardChangesModal.tsx b/frontend/src/container/NewWidget/WidgetModals/DiscardChangesModal.tsx
new file mode 100644
index 0000000000..0021a7952e
--- /dev/null
+++ b/frontend/src/container/NewWidget/WidgetModals/DiscardChangesModal.tsx
@@ -0,0 +1,53 @@
+import { SolidAlertTriangle } from '@signozhq/icons';
+import { ConfirmDialog } from '@signozhq/ui/dialog';
+import { Typography } from '@signozhq/ui/typography';
+
+export interface DiscardChangesModalProps {
+ open: boolean;
+ isNewPanel: boolean;
+ panelTitle?: string;
+ dashboardTitle?: string;
+ onDiscard: () => void;
+ onClose: () => void;
+}
+
+export default function DiscardChangesModal({
+ open,
+ isNewPanel,
+ panelTitle,
+ dashboardTitle,
+ onDiscard,
+ onClose,
+}: DiscardChangesModalProps): JSX.Element {
+ const dashboardName = dashboardTitle ? (
+ <>
+ {' '}
+ to <strong>{dashboardTitle}</strong>
+ </>
+ ) : null;
+ const panelLabel = panelTitle ? <strong>{panelTitle}</strong> : 'this panel';
+
+ return (
+ <ConfirmDialog
+ open={open}
+ onOpenChange={(next): void => {
+ if (!next) {
+ onClose();
+ }
+ }}
+ title="Discard changes?"
+ titleIcon={<SolidAlertTriangle size={14} color="#fdd600" />}
+ confirmText="Discard"
+ confirmColor="destructive"
+ cancelText="Keep editing"
+ onConfirm={onDiscard}
+ onCancel={onClose}
+ >
+ {isNewPanel ? (
+ <Typography>This new panel won&apos;t be added{dashboardName}.</Typography>
+ ) : (
+ <Typography>Your unsaved edits to {panelLabel} will be lost.</Typography>
+ )}
+ </ConfirmDialog>
+ );
+}
diff --git a/frontend/src/container/NewWidget/__test__/utils.test.ts b/frontend/src/container/NewWidget/__test__/utils.test.ts
index 683d472572..45c310d54e 100644
--- a/frontend/src/container/NewWidget/__test__/utils.test.ts
+++ b/frontend/src/container/NewWidget/__test__/utils.test.ts
@@ -1,13 +1,17 @@
import {
+ initialAutocompleteData,
initialQueryBuilderFormValuesMap,
PANEL_TYPES,
} from 'constants/queryBuilder';
+import { cloneDeep } from 'lodash-es';
+import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
+import { MetricAggregation } from 'types/api/v5/queryRange';
import { EQueryType } from 'types/common/dashboard';
import { DataSource } from 'types/common/queryBuilder';
import type { PartialPanelTypes } from '../utils';
-import { handleQueryChange } from '../utils';
+import { getIsQueryModified, handleQueryChange } from '../utils';
const buildSupersetQuery = (extras?: Record<string, unknown>): Query => ({
queryType: EQueryType.QUERY_BUILDER,
@@ -37,6 +41,128 @@ const buildSupersetQuery = (extras?: Record<string, unknown>): Query => ({
},
});
+const buildMetricsQuery = (
+ overrides?: Partial<{
+ metricName: string;
+ aggregateAttributeKey: string;
+ legend: string;
+ groupByKey: string;
+ }>,
+): Query => ({
+ queryType: EQueryType.QUERY_BUILDER,
+ promql: [],
+ clickhouse_sql: [],
+ id: 'query-id',
+ unit: '',
+ builder: {
+ queryFormulas: [],
+ queryData: [
+ {
+ ...initialQueryBuilderFormValuesMap[DataSource.METRICS],
+ queryName: 'A',
+ aggregateAttribute: overrides?.aggregateAttributeKey
+ ? {
+ ...initialAutocompleteData,
+ key: overrides.aggregateAttributeKey,
+ type: 'tag',
+ dataType: DataTypes.Float64,
+ }
+ : cloneDeep(initialAutocompleteData),
+ aggregations: [
+ {
+ metricName: overrides?.metricName ?? 'system.cpu.load',
+ temporality: '',
+ timeAggregation: 'rate',
+ spaceAggregation: 'sum',
+ reduceTo: 'avg',
+ } as MetricAggregation,
+ ],
+ legend: overrides?.legend ?? '',
+ groupBy: overrides?.groupByKey
+ ? [
+ {
+ ...initialAutocompleteData,
+ key: overrides.groupByKey,
+ type: 'tag',
+ dataType: DataTypes.String,
+ },
+ ]
+ : [],
+ },
+ ],
+ queryTraceOperator: [],
+ },
+});
+
+describe('getIsQueryModified', () => {
+ it('returns false when baseline is null (new unsaved panel with no edits anchor)', () => {
+ const current = buildMetricsQuery();
+ expect(getIsQueryModified(current, null)).toBe(false);
+ });
+
+ it('returns false when baseline is undefined', () => {
+ const current = buildMetricsQuery();
+ expect(getIsQueryModified(current, undefined)).toBe(false);
+ });
+
+ it('returns false when current only differs by auto-backfilled aggregateAttribute', () => {
+ // saved widget query: aggregateAttribute is the v5-style empty initial value
+ // (stripped from persisted spec; spread back in as initialAutocompleteData on load)
+ const savedQuery = buildMetricsQuery({ metricName: 'system.cpu.load' });
+ // after MetricNameSelector edit-mode backfill, currentQuery has the populated
+ // aggregateAttribute while the rest of the query is identical
+ const currentQuery = buildMetricsQuery({
+ metricName: 'system.cpu.load',
+ aggregateAttributeKey: 'system.cpu.load',
+ });
+ expect(getIsQueryModified(currentQuery, savedQuery)).toBe(false);
+ });
+
+ it('returns true when the user edits the legend', () => {
+ const baseline = buildMetricsQuery({ metricName: 'system.cpu.load' });
+ const edited = buildMetricsQuery({
+ metricName: 'system.cpu.load',
+ legend: 'cpu-load',
+ });
+ expect(getIsQueryModified(edited, baseline)).toBe(true);
+ });
+
+ it('returns true when the user picks a different metric (aggregations diverges)', () => {
+ const baseline = buildMetricsQuery({ metricName: 'system.cpu.load' });
+ const edited = buildMetricsQuery({ metricName: 'system.memory.usage' });
+ expect(getIsQueryModified(edited, baseline)).toBe(true);
+ });
+
+ it('returns true when the user adds a groupBy', () => {
+ const baseline = buildMetricsQuery({ metricName: 'system.cpu.load' });
+ const edited = buildMetricsQuery({
+ metricName: 'system.cpu.load',
+ groupByKey: 'host.name',
+ });
+ expect(getIsQueryModified(edited, baseline)).toBe(true);
+ });
+
+ it('returns true on existing widget when current diverges from saved (Stage-and-Run silent-loss flow)', () => {
+ // After Edit → Stage and Run, stagedQuery is reset to match currentQuery.
+ // The dirty check must compare against the SAVED widget query, not stagedQuery.
+ const savedQuery = buildMetricsQuery({ metricName: 'system.cpu.load' });
+ const currentQuery = buildMetricsQuery({ metricName: 'system.memory.usage' });
+ expect(getIsQueryModified(currentQuery, savedQuery)).toBe(true);
+ });
+
+ it('returns false for a new panel where currentQuery still matches stagedQuery baseline', () => {
+ const stagedQuery = buildMetricsQuery();
+ const currentQuery = buildMetricsQuery();
+ expect(getIsQueryModified(currentQuery, stagedQuery)).toBe(false);
+ });
+
+ it('returns true for a new panel where currentQuery has been edited away from stagedQuery', () => {
+ const stagedQuery = buildMetricsQuery();
+ const currentQuery = buildMetricsQuery({ legend: 'custom' });
+ expect(getIsQueryModified(currentQuery, stagedQuery)).toBe(true);
+ });
+});
+
describe('handleQueryChange', () => {
it('sets list-specific fields when switching to LIST', () => {
const superset = buildSupersetQuery();
diff --git a/frontend/src/container/NewWidget/index.tsx b/frontend/src/container/NewWidget/index.tsx
index ea6dfc0bab..08adeb6aea 100644
--- a/frontend/src/container/NewWidget/index.tsx
+++ b/frontend/src/container/NewWidget/index.tsx
@@ -1,18 +1,17 @@
/* eslint-disable sonarjs/cognitive-complexity */
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { useTranslation } from 'react-i18next';
import { UseQueryResult } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import { generatePath } from 'react-router-dom';
-import { Check, SolidAlertTriangle, X } from '@signozhq/icons';
+import { Check, X } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import {
ResizableHandle,
ResizablePanel,
ResizablePanelGroup,
} from '@signozhq/ui/resizable';
-import { Flex, Modal, Space } from 'antd';
+import { Flex } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import logEvent from 'api/common/logEvent';
import { PrecisionOption, PrecisionOptionsEnum } from 'components/Graph/types';
@@ -69,7 +68,6 @@ import { GlobalReducer } from 'types/reducer/globalTime';
import { getGraphType, getGraphTypeForFormat } from 'utils/getGraphType';
import LeftContainer from './LeftContainer';
-import QueryTypeTag from './LeftContainer/QueryTypeTag';
import RightContainer from './RightContainer';
import { ThresholdProps } from './RightContainer/Threshold/types';
import TimeItems, { timePreferance } from './RightContainer/timeItems';
@@ -82,6 +80,7 @@ import {
placeWidgetAtBottom,
placeWidgetBetweenRows,
} from './utils';
+import DiscardChangesModal from './WidgetModals/DiscardChangesModal';
import './NewWidget.styles.scss';
@@ -98,8 +97,6 @@ function NewWidget({
const { dashboardVariables } = useDashboardVariables();
- const { t } = useTranslation(['dashboard']);
-
const { registerShortcut, deregisterShortcut } = useKeyboardHotkeys();
const {
@@ -110,11 +107,6 @@ function NewWidget({
setSupersetQuery,
} = useQueryBuilder();
- const isQueryModified = useMemo(
- () => getIsQueryModified(currentQuery, stagedQuery),
- [currentQuery, stagedQuery],
- );
-
const { selectedTime: globalSelectedInterval } = useSelector<
AppState,
GlobalReducer
@@ -139,6 +131,23 @@ function NewWidget({
const query = useUrlQuery();
+ // For existing widgets, compare currentQuery against the saved widget query
+ // (stable across Stage-and-Run cycles). For new panels with no saved baseline,
+ // fall back to stagedQuery so initial edits still trigger the warning.
+ const savedWidgetQuery = useMemo(() => {
+ const widgetId = query.get('widgetId');
+ const match = widgets?.find((w) => w.id === widgetId);
+ if (!match || match.panelTypes === PANEL_GROUP_TYPES.ROW) {
+ return null;
+ }
+ return (match as Widgets).query ?? null;
+ }, [widgets, query]);
+
+ const isQueryModified = useMemo(
+ () => getIsQueryModified(currentQuery, savedWidgetQuery ?? stagedQuery),
+ [currentQuery, savedWidgetQuery, stagedQuery],
+ );
+
const [isNewDashboard, setIsNewDashboard] = useState<boolean>(false);
const logEventCalledRef = useRef(false);
@@ -228,7 +237,6 @@ function NewWidget({
Record<string, string>
>(selectedWidget?.customLegendColors || {});
- const [saveModal, setSaveModal] = useState(false);
const [discardModal, setDiscardModal] = useState(false);
const [bucketWidth, setBucketWidth] = useState<number>(
@@ -340,7 +348,6 @@ function NewWidget({
]);
const closeModal = (): void => {
- setSaveModal(false);
setDiscardModal(false);
};
@@ -593,7 +600,7 @@ function NewWidget({
},
};
- updateDashboardMutation.mutateAsync(dashboard, {
+ return updateDashboardMutation.mutateAsync(dashboard, {
onSuccess: () => {
setToScrollWidgetId(selectedWidget?.id || '');
navigateToDashboardPage();
@@ -688,9 +695,9 @@ function NewWidget({
})),
}),
});
- setSaveModal(true);
+ onClickSaveHandler();
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [isNewPanel]);
+ }, [onClickSaveHandler]);
const isNewTraceLogsAvailable =
currentQuery.queryType === EQueryType.QUERY_BUILDER &&
@@ -951,57 +958,14 @@ function NewWidget({
</ResizablePanel>
</ResizablePanelGroup>
</PanelContainer>
- <Modal
- title={
- isQueryModified ? (
- <Space>
- <SolidAlertTriangle size={16} color="#fdd600" />
- Unsaved Changes
- </Space>
- ) : (
- 'Save Widget'
- )
- }
- focusTriggerAfterClose
- forceRender
- destroyOnClose
- closable
- onCancel={closeModal}
- onOk={onClickSaveHandler}
- confirmLoading={updateDashboardMutation.isLoading}
- centered
- open={saveModal}
- width={600}
- >
- {!isQueryModified ? (
- <Typography>
- {t('your_graph_build_with')}{' '}
- <QueryTypeTag queryType={currentQuery.queryType} />{' '}
- {t('dashboard_ok_confirm')}
- </Typography>
- ) : (
- <Typography>{t('dashboard_unsave_changes')} </Typography>
- )}
- </Modal>
- <Modal
- title={
- <Space>
- <SolidAlertTriangle size={16} color="#fdd600" />
- Unsaved Changes
- </Space>
- }
- focusTriggerAfterClose
- forceRender
- destroyOnClose
- closable
- onCancel={closeModal}
- onOk={discardChanges}
- centered
+ <DiscardChangesModal
open={discardModal}
- width={600}
- >
- <Typography>{t('dashboard_unsave_changes')}</Typography>
- </Modal>
+ isNewPanel={isNewPanel}
+ panelTitle={title}
+ dashboardTitle={dashboardData?.data?.title}
+ onDiscard={discardChanges}
+ onClose={closeModal}
+ />
</Container>
);
}
diff --git a/frontend/src/container/NewWidget/utils.ts b/frontend/src/container/NewWidget/utils.ts
index caf2672de6..7fc0057e7b 100644
--- a/frontend/src/container/NewWidget/utils.ts
+++ b/frontend/src/container/NewWidget/utils.ts
@@ -1,5 +1,4 @@
import { Layout } from 'react-grid-layout';
-import { omitIdFromQuery } from 'components/ExplorerCard/utils';
import { PrecisionOptionsEnum } from 'components/Graph/types';
import { YAxisCategoryNames } from 'components/YAxisUnitSelector/constants';
import {
@@ -26,16 +25,84 @@ import { DataSource } from 'types/common/queryBuilder';
import { getCategoryName } from './RightContainer/dataFormatCategories';
+// Asks "would saving the current panel change the persisted widget spec?".
+//
+// `adjustQueryForV5` is deliberately not reused here: in addition to stripping
+// the legacy v4 fields, it also resurrects them onto each metric
+// `aggregations[i]`. That migration step is correct on save but bleeds
+// asymmetrically across a comparator — the live query still carries the
+// legacy defaults from `initialQueryBuilderFormValuesMap` while a previously
+// saved widget had them stripped.
+const stripQueryDataForCompare = (
+ queryData: IBuilderQuery,
+): Record<string, unknown> => {
+ const {
+ aggregateAttribute: _aggregateAttribute,
+ aggregateOperator: _aggregateOperator,
+ timeAggregation: _timeAggregation,
+ spaceAggregation: _spaceAggregation,
+ reduceTo: _reduceTo,
+ filters: _filters,
+ ...retained
+ } = queryData ?? ({} as IBuilderQuery);
+
+ const groupBy = (retained.groupBy ?? []).map((entry) => {
+ const { id: _id, ...rest } = entry;
+ return rest;
+ });
+
+ return {
+ ...retained,
+ groupBy,
+ source: retained.source || '',
+ };
+};
+
+const normalizeForDirtyCheck = (query: Query): Record<string, unknown> => {
+ const { id: _id, unit, builder, ...rest } = query;
+ return {
+ ...rest,
+ // `id` is regenerated on every Stage and Run; `unit` flips between ''
+ // and undefined depending on whether the user has touched the selector.
+ unit: unit || '',
+ builder: {
+ ...builder,
+ queryData: (builder?.queryData ?? []).map(stripQueryDataForCompare),
+ },
+ };
+};
+
+// `lodash.isEqual` distinguishes `{a: undefined}` from `{}`; for the dirty
+// check those are the same. Initial-values spreads on the live query
+// frequently leave such explicit-undefined keys.
+const stripUndefined = (value: unknown): unknown => {
+ if (Array.isArray(value)) {
+ return value.map(stripUndefined);
+ }
+ if (value && typeof value === 'object') {
+ const out: Record<string, unknown> = {};
+ Object.entries(value as Record<string, unknown>).forEach(([k, v]) => {
+ if (v === undefined) {
+ return;
+ }
+ out[k] = stripUndefined(v);
+ });
+ return out;
+ }
+ return value;
+};
+
export const getIsQueryModified = (
currentQuery: Query,
- stagedQuery: Query | null,
+ baselineQuery: Query | null | undefined,
): boolean => {
- if (!stagedQuery) {
+ if (!baselineQuery) {
return false;
}
- const omitIdFromStageQuery = omitIdFromQuery(stagedQuery);
- const omitIdFromCurrentQuery = omitIdFromQuery(currentQuery);
- return !isEqual(omitIdFromStageQuery, omitIdFromCurrentQuery);
+ return !isEqual(
+ stripUndefined(normalizeForDirtyCheck(baselineQuery)),
+ stripUndefined(normalizeForDirtyCheck(currentQuery)),
+ );
};
export type PartialPanelTypes = {