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: alerts creation from dashboard and panel to happen in new tab (#9902)

Ashwin Bhatkal4882d7d52442
diff --git a/frontend/src/container/GridCardLayout/WidgetHeader/__tests__/WidgetHeader.test.tsx b/frontend/src/container/GridCardLayout/WidgetHeader/__tests__/WidgetHeader.test.tsx
index 0eaf386392..763578c9d1 100644
--- a/frontend/src/container/GridCardLayout/WidgetHeader/__tests__/WidgetHeader.test.tsx
+++ b/frontend/src/container/GridCardLayout/WidgetHeader/__tests__/WidgetHeader.test.tsx
@@ -24,6 +24,8 @@ const TABLE_WIDGET_TITLE = 'Table Widget';
const WIDGET_HEADER_SEARCH = 'widget-header-search';
const WIDGET_HEADER_SEARCH_INPUT = 'widget-header-search-input';
const TEST_WIDGET_TITLE_RESOLVED = 'Test Widget Title';
+const CREATE_ALERTS_TEXT = 'Create Alerts';
+const WIDGET_HEADER_OPTIONS_ID = 'widget-header-options';
const mockStore = configureStore([thunk]);
const createMockStore = (): ReturnType<typeof mockStore> =>
@@ -101,6 +103,9 @@ jest.mock('lucide-react', () => ({
CircleX: (): JSX.Element => <svg data-testid="lucide-circle-x" />,
TriangleAlert: (): JSX.Element => <svg data-testid="lucide-triangle-alert" />,
X: (): JSX.Element => <svg data-testid="lucide-x" />,
+ SquareArrowOutUpRight: (): JSX.Element => (
+ <svg data-testid="lucide-square-arrow-out-up-right" />
+ ),
}));
jest.mock('antd', () => ({
...jest.requireActual('antd'),
@@ -391,7 +396,7 @@ describe('WidgetHeader', () => {
/>,
);
- const moreOptionsIcon = screen.getByTestId('widget-header-options');
+ const moreOptionsIcon = screen.getByTestId(WIDGET_HEADER_OPTIONS_ID);
expect(moreOptionsIcon).toBeInTheDocument();
});
@@ -455,4 +460,66 @@ describe('WidgetHeader', () => {
expect(screen.getByTestId('threshold')).toBeInTheDocument();
});
+
+ describe('Create Alerts Menu Item', () => {
+ it('renders Create Alerts menu item with external link icon when included in headerMenuList', async () => {
+ render(
+ <WidgetHeader
+ title={TEST_WIDGET_TITLE}
+ widget={mockWidget}
+ onView={mockOnView}
+ queryResponse={mockQueryResponse}
+ isWarning={false}
+ isFetchingResponse={false}
+ tableProcessedDataRef={tableProcessedDataRef}
+ setSearchTerm={mockSetSearchTerm}
+ headerMenuList={[MenuItemKeys.CreateAlerts]}
+ />,
+ );
+
+ const moreOptionsIcon = await screen.findByTestId(WIDGET_HEADER_OPTIONS_ID);
+ expect(moreOptionsIcon).toBeInTheDocument();
+ await userEvent.hover(moreOptionsIcon);
+
+ await screen.findByText(CREATE_ALERTS_TEXT);
+
+ const externalLinkIcon = await screen.findByTestId(
+ 'lucide-square-arrow-out-up-right',
+ );
+ expect(externalLinkIcon).toBeInTheDocument();
+ });
+
+ it('Create Alerts menu item is enabled and clickable', async () => {
+ const mockCreateAlertsHandler = jest.fn();
+ const useCreateAlerts = jest.requireMock(
+ 'hooks/queryBuilder/useCreateAlerts',
+ ).default;
+ useCreateAlerts.mockReturnValue(mockCreateAlertsHandler);
+
+ render(
+ <WidgetHeader
+ title={TEST_WIDGET_TITLE}
+ widget={mockWidget}
+ onView={mockOnView}
+ queryResponse={mockQueryResponse}
+ isWarning={false}
+ isFetchingResponse={false}
+ tableProcessedDataRef={tableProcessedDataRef}
+ setSearchTerm={mockSetSearchTerm}
+ headerMenuList={[MenuItemKeys.CreateAlerts]}
+ />,
+ );
+
+ expect(useCreateAlerts).toHaveBeenCalledWith(mockWidget, 'dashboardView');
+
+ const moreOptionsIcon = await screen.findByTestId(WIDGET_HEADER_OPTIONS_ID);
+ await userEvent.hover(moreOptionsIcon);
+
+ const createAlertsMenuItem = await screen.findByText(CREATE_ALERTS_TEXT);
+
+ // Verify the menu item is clickable by actually clicking it
+ await userEvent.click(createAlertsMenuItem);
+ expect(mockCreateAlertsHandler).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/frontend/src/container/GridCardLayout/WidgetHeader/index.tsx b/frontend/src/container/GridCardLayout/WidgetHeader/index.tsx
index 04625c70ea..d2e20b43f7 100644
--- a/frontend/src/container/GridCardLayout/WidgetHeader/index.tsx
+++ b/frontend/src/container/GridCardLayout/WidgetHeader/index.tsx
@@ -26,7 +26,7 @@ import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQuery from 'hooks/useUrlQuery';
import { RowData } from 'lib/query/createTableColumnsFromQuery';
import { isEmpty } from 'lodash-es';
-import { CircleX, X } from 'lucide-react';
+import { CircleX, SquareArrowOutUpRight, X } from 'lucide-react';
import { unparse } from 'papaparse';
import { useAppContext } from 'providers/App/App';
import { ReactNode, useCallback, useMemo, useState } from 'react';
@@ -185,7 +185,18 @@ function WidgetHeader({
{
key: MenuItemKeys.CreateAlerts,
icon: <AlertOutlined />,
- label: MENUITEM_KEYS_VS_LABELS[MenuItemKeys.CreateAlerts],
+ label: (
+ <span
+ style={{
+ display: 'flex',
+ alignItems: 'baseline',
+ justifyContent: 'space-between',
+ }}
+ >
+ {MENUITEM_KEYS_VS_LABELS[MenuItemKeys.CreateAlerts]}
+ <SquareArrowOutUpRight size={10} />
+ </span>
+ ),
isVisible: headerMenuList?.includes(MenuItemKeys.CreateAlerts) || false,
disabled: false,
},
diff --git a/frontend/src/container/GridCardLayout/WidgetHeader/types.ts b/frontend/src/container/GridCardLayout/WidgetHeader/types.ts
index 65e355574c..cf37a57258 100644
--- a/frontend/src/container/GridCardLayout/WidgetHeader/types.ts
+++ b/frontend/src/container/GridCardLayout/WidgetHeader/types.ts
@@ -5,7 +5,7 @@ import { MenuItemKeys } from './contants';
export interface MenuItem {
key: MenuItemKeys;
icon: ReactNode;
- label: string;
+ label: ReactNode;
isVisible: boolean;
disabled: boolean;
danger?: boolean;
diff --git a/frontend/src/container/NewWidget/RightContainer/__tests__/RightContainer.test.tsx b/frontend/src/container/NewWidget/RightContainer/__tests__/RightContainer.test.tsx
new file mode 100644
index 0000000000..3d3fcc2d6a
--- /dev/null
+++ b/frontend/src/container/NewWidget/RightContainer/__tests__/RightContainer.test.tsx
@@ -0,0 +1,290 @@
+/* eslint-disable react/jsx-props-no-spreading */
+import { render as rtlRender, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { PANEL_TYPES } from 'constants/queryBuilder';
+import { AppContext } from 'providers/App/App';
+import { IAppContext } from 'providers/App/types';
+import { DashboardProvider } from 'providers/Dashboard/Dashboard';
+import { ErrorModalProvider } from 'providers/ErrorModalProvider';
+import { QueryBuilderProvider } from 'providers/QueryBuilder';
+import React from 'react';
+import { QueryClient, QueryClientProvider } from 'react-query';
+import { Provider } from 'react-redux';
+import { MemoryRouter } from 'react-router-dom';
+import configureStore from 'redux-mock-store';
+import thunk from 'redux-thunk';
+import { LegendPosition, Widgets } from 'types/api/dashboard/getAll';
+import { EQueryType } from 'types/common/dashboard';
+import { ROLES } from 'types/roles';
+
+import RightContainer, { RightContainerProps } from '../index';
+import { timeItems, timePreferance, timePreferenceType } from '../timeItems';
+
+const mockStore = configureStore([thunk]);
+const createMockStore = (): ReturnType<typeof mockStore> =>
+ mockStore({
+ app: {
+ role: 'ADMIN',
+ user: {
+ userId: 'test-user-id',
+ email: '[email protected]',
+ name: 'TestUser',
+ },
+ isLoggedIn: true,
+ org: [],
+ },
+ globalTime: {
+ minTime: '2023-01-01T00:00:00Z',
+ maxTime: '2023-01-02T00:00:00Z',
+ },
+ });
+
+const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ refetchOnWindowFocus: false,
+ retry: false,
+ },
+ },
+});
+
+const createMockAppContext = (): Partial<IAppContext> => ({
+ user: {
+ accessJwt: '',
+ refreshJwt: '',
+ id: '',
+ email: '',
+ displayName: '',
+ createdAt: 0,
+ organization: '',
+ orgId: '',
+ role: 'ADMIN' as ROLES,
+ },
+});
+
+const mockWidget: Widgets = {
+ id: 'test-widget-id',
+ title: 'Test Widget',
+ description: 'Test Description',
+ panelTypes: PANEL_TYPES.TIME_SERIES,
+ query: {
+ builder: {
+ queryData: [],
+ queryFormulas: [],
+ queryTraceOperator: [],
+ },
+ promql: [],
+ clickhouse_sql: [],
+ id: 'query-id',
+ queryType: 'builder' as EQueryType,
+ },
+ timePreferance: 'GLOBAL_TIME' as timePreferenceType,
+ opacity: '',
+ nullZeroValues: '',
+ yAxisUnit: '',
+ fillSpans: false,
+ softMin: null,
+ softMax: null,
+ selectedLogFields: [],
+ selectedTracesFields: [],
+};
+
+const render = (ui: React.ReactElement): ReturnType<typeof rtlRender> =>
+ rtlRender(
+ <MemoryRouter>
+ <QueryClientProvider client={queryClient}>
+ <Provider store={createMockStore()}>
+ <AppContext.Provider value={createMockAppContext() as IAppContext}>
+ <ErrorModalProvider>
+ <DashboardProvider>
+ <QueryBuilderProvider>{ui}</QueryBuilderProvider>
+ </DashboardProvider>
+ </ErrorModalProvider>
+ </AppContext.Provider>
+ </Provider>
+ </QueryClientProvider>
+ </MemoryRouter>,
+ );
+
+// eslint-disable-next-line sonarjs/no-duplicate-string
+jest.mock('hooks/queryBuilder/useCreateAlerts', () => ({
+ __esModule: true,
+ default: jest.fn(() => jest.fn()),
+}));
+
+jest.mock('lucide-react', () => ({
+ ...jest.requireActual('lucide-react'),
+ ConciergeBell: (): JSX.Element => <svg data-testid="lucide-concierge-bell" />,
+ SquareArrowOutUpRight: (): JSX.Element => (
+ <svg data-testid="lucide-square-arrow-out-up-right" />
+ ),
+ Plus: (): JSX.Element => <svg data-testid="lucide-plus" />,
+}));
+
+describe('RightContainer - Alerts Section', () => {
+ const defaultProps: RightContainerProps = {
+ title: 'Test Widget',
+ setTitle: jest.fn(),
+ description: 'Test Description',
+ setDescription: jest.fn(),
+ opacity: '1',
+ setOpacity: jest.fn(),
+ selectedNullZeroValue: '',
+ setSelectedNullZeroValue: jest.fn(),
+ selectedGraph: PANEL_TYPES.TIME_SERIES,
+ setSelectedTime: jest.fn(),
+ selectedTime: timeItems[0] as timePreferance,
+ yAxisUnit: '',
+ stackedBarChart: false,
+ setStackedBarChart: jest.fn(),
+ bucketWidth: 0,
+ bucketCount: 0,
+ combineHistogram: false,
+ setCombineHistogram: jest.fn(),
+ setBucketWidth: jest.fn(),
+ setBucketCount: jest.fn(),
+ setYAxisUnit: jest.fn(),
+ decimalPrecision: 2 as const,
+ setDecimalPrecision: jest.fn(),
+ setGraphHandler: jest.fn(),
+ thresholds: [],
+ setThresholds: jest.fn(),
+ selectedWidget: mockWidget,
+ isFillSpans: false,
+ setIsFillSpans: jest.fn(),
+ softMin: null,
+ softMax: null,
+ columnUnits: {},
+ setColumnUnits: jest.fn(),
+ setSoftMin: jest.fn(),
+ setSoftMax: jest.fn(),
+ isLogScale: false,
+ setIsLogScale: jest.fn(),
+ legendPosition: LegendPosition.BOTTOM,
+ setLegendPosition: jest.fn(),
+ customLegendColors: {},
+ setCustomLegendColors: jest.fn(),
+ queryResponse: undefined,
+ contextLinks: { linksData: [] },
+ setContextLinks: jest.fn(),
+ enableDrillDown: false,
+ };
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('renders alerts section for TIME_SERIES panel type', () => {
+ render(<RightContainer {...defaultProps} />);
+
+ const alertsSection = screen.getByText('Alerts').closest('section');
+ expect(alertsSection).toBeInTheDocument();
+ expect(alertsSection).toHaveClass('alerts');
+ });
+
+ it('renders alerts section with correct text and SquareArrowOutUpRight icon', () => {
+ render(<RightContainer {...defaultProps} />);
+
+ expect(
+ screen.getByTestId('lucide-square-arrow-out-up-right'),
+ ).toBeInTheDocument();
+ expect(screen.getByText('Alerts')).toBeInTheDocument();
+ });
+
+ it('calls onCreateAlertsHandler when alerts section is clicked', async () => {
+ const mockCreateAlertsHandler = jest.fn();
+ const useCreateAlerts = jest.requireMock('hooks/queryBuilder/useCreateAlerts')
+ .default;
+ useCreateAlerts.mockReturnValue(mockCreateAlertsHandler);
+
+ render(<RightContainer {...defaultProps} />);
+
+ const alertsSection = screen.getByText('Alerts').closest('section');
+ expect(alertsSection).toBeInTheDocument();
+
+ await userEvent.click(alertsSection as HTMLElement);
+
+ expect(mockCreateAlertsHandler).toHaveBeenCalledTimes(1);
+ });
+
+ it('passes correct parameters to useCreateAlerts hook', () => {
+ const useCreateAlerts = jest.requireMock('hooks/queryBuilder/useCreateAlerts')
+ .default;
+
+ render(<RightContainer {...defaultProps} />);
+
+ expect(useCreateAlerts).toHaveBeenCalledWith(mockWidget, 'panelView');
+ });
+
+ it('renders alerts section for VALUE panel type', () => {
+ render(
+ <RightContainer
+ {...defaultProps}
+ selectedGraph={PANEL_TYPES.VALUE}
+ selectedWidget={{ ...mockWidget, panelTypes: PANEL_TYPES.VALUE }}
+ />,
+ );
+
+ expect(screen.getByText('Alerts')).toBeInTheDocument();
+ });
+
+ it('renders alerts section for BAR panel type', () => {
+ render(
+ <RightContainer
+ {...defaultProps}
+ selectedGraph={PANEL_TYPES.BAR}
+ selectedWidget={{ ...mockWidget, panelTypes: PANEL_TYPES.BAR }}
+ />,
+ );
+
+ expect(screen.getByText('Alerts')).toBeInTheDocument();
+ });
+
+ it('does not render alerts section for TABLE panel type', () => {
+ render(
+ <RightContainer
+ {...defaultProps}
+ selectedGraph={PANEL_TYPES.TABLE}
+ selectedWidget={{ ...mockWidget, panelTypes: PANEL_TYPES.TABLE }}
+ />,
+ );
+
+ expect(screen.queryByText('Alerts')).not.toBeInTheDocument();
+ });
+
+ it('does not render alerts section for LIST panel type', () => {
+ render(
+ <RightContainer
+ {...defaultProps}
+ selectedGraph={PANEL_TYPES.LIST}
+ selectedWidget={{ ...mockWidget, panelTypes: PANEL_TYPES.LIST }}
+ />,
+ );
+
+ expect(screen.queryByText('Alerts')).not.toBeInTheDocument();
+ });
+
+ it('does not render alerts section for PIE panel type', () => {
+ render(
+ <RightContainer
+ {...defaultProps}
+ selectedGraph={PANEL_TYPES.PIE}
+ selectedWidget={{ ...mockWidget, panelTypes: PANEL_TYPES.PIE }}
+ />,
+ );
+
+ expect(screen.queryByText('Alerts')).not.toBeInTheDocument();
+ });
+
+ it('does not render alerts section for HISTOGRAM panel type', () => {
+ render(
+ <RightContainer
+ {...defaultProps}
+ selectedGraph={PANEL_TYPES.HISTOGRAM}
+ selectedWidget={{ ...mockWidget, panelTypes: PANEL_TYPES.HISTOGRAM }}
+ />,
+ );
+
+ expect(screen.queryByText('Alerts')).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/container/NewWidget/RightContainer/index.tsx b/frontend/src/container/NewWidget/RightContainer/index.tsx
index 8b14bd8504..ea0e2a8027 100644
--- a/frontend/src/container/NewWidget/RightContainer/index.tsx
+++ b/frontend/src/container/NewWidget/RightContainer/index.tsx
@@ -20,7 +20,13 @@ import GraphTypes, {
} from 'container/NewDashboard/ComponentsSlider/menuItems';
import useCreateAlerts from 'hooks/queryBuilder/useCreateAlerts';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
-import { ConciergeBell, LineChart, Plus, Spline } from 'lucide-react';
+import {
+ ConciergeBell,
+ LineChart,
+ Plus,
+ Spline,
+ SquareArrowOutUpRight,
+} from 'lucide-react';
import { useDashboard } from 'providers/Dashboard/Dashboard';
import {
Dispatch,
@@ -140,11 +146,7 @@ function RightContainer({
const selectedGraphType =
GraphTypes.find((e) => e.name === selectedGraph)?.display || '';
- const onCreateAlertsHandler = useCreateAlerts(
- selectedWidget,
- 'panelView',
- thresholds,
- );
+ const onCreateAlertsHandler = useCreateAlerts(selectedWidget, 'panelView');
const allowThreshold = panelTypeVsThreshold[selectedGraph];
const allowSoftMinMax = panelTypeVsSoftMinMax[selectedGraph];
@@ -530,6 +532,7 @@ function RightContainer({
<div className="left-section">
<ConciergeBell size={14} className="bell-icon" />
<Typography.Text className="alerts-text">Alerts</Typography.Text>
+ <SquareArrowOutUpRight size={10} className="info-icon" />
</div>
<Plus size={14} className="plus-icon" />
</section>
@@ -560,7 +563,7 @@ function RightContainer({
);
}
-interface RightContainerProps {
+export interface RightContainerProps {
title: string;
setTitle: Dispatch<SetStateAction<string>>;
description: string;
diff --git a/frontend/src/hooks/queryBuilder/useCreateAlerts.tsx b/frontend/src/hooks/queryBuilder/useCreateAlerts.tsx
index 0b539ced54..708f87e03b 100644
--- a/frontend/src/hooks/queryBuilder/useCreateAlerts.tsx
+++ b/frontend/src/hooks/queryBuilder/useCreateAlerts.tsx
@@ -6,10 +6,8 @@ import { ENTITY_VERSION_V5 } from 'constants/app';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import { MenuItemKeys } from 'container/GridCardLayout/WidgetHeader/contants';
-import { ThresholdProps } from 'container/NewWidget/RightContainer/Threshold/types';
import { useNotifications } from 'hooks/useNotifications';
import { getDashboardVariables } from 'lib/dashbaordVariables/getDashboardVariables';
-import history from 'lib/history';
import { mapQueryDataFromApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataFromApi';
import { useDashboard } from 'providers/Dashboard/Dashboard';
import { useCallback, useMemo } from 'react';
@@ -20,11 +18,7 @@ import { IDashboardVariable, Widgets } from 'types/api/dashboard/getAll';
import { GlobalReducer } from 'types/reducer/globalTime';
import { getGraphType } from 'utils/getGraphType';
-const useCreateAlerts = (
- widget?: Widgets,
- caller?: string,
- thresholds?: ThresholdProps[],
-): VoidFunction => {
+const useCreateAlerts = (widget?: Widgets, caller?: string): VoidFunction => {
const queryRangeMutation = useMutation(getSubstituteVars);
const { selectedTime: globalSelectedInterval } = useSelector<
@@ -83,9 +77,7 @@ const useCreateAlerts = (
QueryParams.panelTypes
}=${widget.panelTypes}&version=${ENTITY_VERSION_V5}`;
- history.push(url, {
- thresholds,
- });
+ window.open(url, '_blank', 'noreferrer');
},
onError: () => {
notifications.error({