Compare commits

...

17 Commits

Author SHA1 Message Date
Jatinderjit Singh
fef84df331 feat(alerts): return activeMute in rule API responses
Backend computes the active mute window per rule (joining with planned
maintenance schedules) in ListRules and GetRuleByID, so the frontend no
longer needs a separate downtime-schedules fetch to determine mute state.

- Add ActiveMuteInfo struct to Rule (id, name, description,
  effectiveStartTime, effectiveEndTime); computed by findActiveMuteForRule
- Handlers for ListRules/GetRuleByID now fetch MaintenanceStore schedules
  and pass them to NewRule
- Regenerate OpenAPI spec and frontend types (RuletypesActiveMuteInfoDTO)
- useActiveMute: drop useListDowntimeSchedules, read activeMute from
  useGetRuleByID (cache-hit on detail page; one request on list page)
- useMuteAlertRule: also invalidate rule queries after muting so activeMute
  refreshes without a separate schedules refetch
- ListAlert: remove useListDowntimeSchedules + findActiveMuteForRule,
  read record.activeMute.effectiveEndTime directly

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-25 20:56:47 +05:30
Jatinderjit Singh
98813660ed fix(alerts): send endTime as null for "Forever" mute
Previously, picking Forever set endTime to now + 10 years so the
schedule had a real (very distant) end. Send null instead so the
backend treats the mute as truly indefinite. The generated schema
narrows endTime to string, but the API accepts null — cast at the
call site with a comment.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 19:51:03 +05:30
Jatinderjit Singh
cd37fbfa71 fix(alerts): drop focus after closing mute popover via Esc / outside click
Pressing Escape promotes the most recent input to 'keyboard', so the
trigger button (Mute) showed a :focus-visible outline once the popover
closed. Blur the active element when closing via keyboard or outside
click so no leftover focus ring lingers. Tab-driven focus still shows
the indicator as expected.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 19:51:03 +05:30
Jatinderjit Singh
fca2da6b15 fix(alerts): close mute popover on outside click and Escape
Since the Popover uses trigger={[]} (controlled-only), antd no longer
attaches its own outside-click / Escape handlers. Add document-level
mousedown and keydown listeners while the popover is open, deferring
attachment by one tick so the click that opened it isn't counted as
an outside click.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 19:51:03 +05:30
Jatinderjit Singh
4a2907ad35 fix(alerts): show firing state + muted badge separately in rule list
Match the original handoff: Status column keeps showing the actual
rule state (Firing/OK/Pending/Disabled), and a separate inline
'MUTED · <countdown>' badge renders next to the rule name when an
active mute exists. Both signals stay visible.

- Revert Status.tsx to its original simple form (no muteEndTime).
- Extract the muted badge into MutedBadge.tsx and render it inline
  in the Alert Name column.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 19:51:03 +05:30
Jatinderjit Singh
6b04e17f64 fix(alerts): remove 'Muted/Disabled by <user>' from banners
Drop the createdBy/updatedBy attribution from both the muted and
disabled banners. MutedBanner keeps name + manage link;
DisabledBanner keeps the relative time.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 19:51:03 +05:30
Jatinderjit Singh
95864ebe58 fix(alerts): disable Mute pill when alert rule is disabled
Muting a disabled rule wouldn't change observable behavior — fires
aren't recorded, so there's nothing to suppress. Disabling the Mute
pill also brings cursor + hover affordances in line with the
non-interactive Active pill while muted: cursor: not-allowed and no
hover background (the SCSS already guards hover with :not(:disabled)).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 19:51:03 +05:30
Jatinderjit Singh
a0b9713a4f feat(alerts): add hover background to segmented pills
Surface clickable regions more clearly:
- Inactive pill hover: --bg-ink-200 background (dark) / --bg-vanilla-300
  (light mode).
- Active pill hovers darken slightly to their next shade — robin-600,
  amber-600, slate-200 — for tactile feedback without losing the
  state color.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 19:51:03 +05:30
Jatinderjit Singh
bded46ce95 fix(alerts): wrap segmented pill text in span for reliable color
The previous attempt set color on the .pill--active-muted block but
something in the cascade was leaving the bare text node light while
the icon (which had its own explicit rule) went dark. Wrap each pill's
label in <span class="alert-state-segmented__label"> and apply the
muted color to both the icon and label classes — both children now
have explicit color rules that don't depend on inheritance from the
button.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 19:51:03 +05:30
Jatinderjit Singh
b38d2963b5 fix(alerts): make muted segmented pill text legible
The base .alert-state-segmented__pill rule was winning over
.alert-state-segmented__pill--active-muted in the cascade for some
build configurations, leaving the "Mute" label rendered in
var(--bg-vanilla-400) (light gray) on amber. Bump specificity by
self-chaining the class (&.alert-state-segmented__pill--active-muted →
.pill.pill--active-muted) so the dark text color always wins, and
apply the color to the icon explicitly so it tracks the label.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 19:51:03 +05:30
Jatinderjit Singh
406800a2e5 Revert "fix(alerts): move toggle toast to per-call mutate callbacks"
This reverts commit 7dacb99536ca386a9b74d101f2f84fdd39ce6864.
2026-05-25 19:51:03 +05:30
Jatinderjit Singh
b10f45a59a Revert "fix(alerts): update rule cache directly instead of refetching"
This reverts commit adc9e0ff1162d7dcc1f82ccfd54ae3b1c428cc46.
2026-05-25 19:51:03 +05:30
Jatinderjit Singh
f75d166eb6 fix(alerts): update rule cache directly instead of refetching
invalidateGetRuleByID + refetchQueries caused EditRules to render its
<Spinner /> (isRefetching=true), which unmounted the whole form
subtree. The unmount cascade plus follow-up query resolutions (channels,
event, fields/keys) caused the success toast to briefly disappear and
re-enter from its animation again, visible as a flicker.

Patching the rule already returns the updated rule, so write it into
the query cache via setQueryData. The form sees the new state without
remounting, and the toast stays put.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 19:51:03 +05:30
Jatinderjit Singh
81f7694991 fix(alerts): move toggle toast to per-call mutate callbacks
Hook-level onSuccess on useMutation can re-fire when the
MutationObserver re-subscribes during context-driven re-renders (each
context update from setAlertRuleState re-renders all consumers of
useAlertRule, including ActionButtons, which re-instantiates the
mutation observer). Per-call callbacks passed to mutate() in
react-query v3 are guaranteed to run exactly once per mutate() call.

This was visible as the success toast appearing once per follow-up API
response after enable/disable.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 19:51:03 +05:30
Jatinderjit Singh
3858e70a4c fix(alerts): detach mute popover from segmented control anchor
Popover's Trigger wrapper could intercept clicks on the inner buttons,
causing the disable/enable toggle to fire twice (visible as a flickering
success toast). Render the segmented control standalone and anchor the
Popover to a separate invisible span positioned at the bottom-right of
the wrapper.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 19:51:03 +05:30
Jatinderjit Singh
9b87348839 fix(alerts): mute popover only opens via Mute pill, not Active/Disable
The Popover wrapper used trigger="click", which fired on any click in
the anchor (including Active and Disable pills). Switch to trigger={[]}
so the popover is controlled exclusively by the Mute handler.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 19:51:02 +05:30
Jatinderjit Singh
fda747f81e feat(alerts): add mute action wrapping planned downtime
Adds a Mute action on the alert rule page that creates a Planned
Downtime entry scoped to the rule, with a quick-duration popover and
full scheduler drawer.

- AlertStateSegmented control replaces the Active/Disabled switch with a
  three-state pill (Active / Mute / Disable). Active is disabled while
  muted; un-mute happens via the Planned Downtimes page.
- MutePopover offers quick durations (15m, 1h, 4h, 1d, 1w, Forever) plus
  a Name field.
- MuteSchedulerDrawer exposes the full Planned Downtime form for custom
  windows and recurrence.
- MutedBanner / DisabledBanner render an informative banner under the
  header for the corresponding states.
- Alert rules list shows a muted badge with countdown for each rule that
  has an active downtime.
- Lookup is frontend-only via listDowntimeSchedules + ruleId filter,
  with no backend changes.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 19:51:02 +05:30
22 changed files with 1751 additions and 26 deletions

View File

@@ -5109,6 +5109,23 @@ components:
- start
- end
type: object
RuletypesActiveMuteInfo:
properties:
description:
type: string
effectiveEndTime:
format: date-time
nullable: true
type: string
effectiveStartTime:
format: date-time
nullable: true
type: string
id:
type: string
name:
type: string
type: object
RuletypesAlertCompositeQuery:
properties:
panelType:
@@ -5359,6 +5376,8 @@ components:
type: object
RuletypesRule:
properties:
activeMute:
$ref: '#/components/schemas/RuletypesActiveMuteInfo'
alert:
type: string
alertType:

View File

@@ -6082,6 +6082,31 @@ export interface RulestatehistorytypesGettableRuleStateWindowDTO {
state: RuletypesAlertStateDTO;
}
export interface RuletypesActiveMuteInfoDTO {
/**
* @type string
*/
description?: string;
/**
* @type string,null
* @format date-time
*/
effectiveEndTime?: string | null;
/**
* @type string,null
* @format date-time
*/
effectiveStartTime?: string | null;
/**
* @type string
*/
id?: string;
/**
* @type string
*/
name?: string;
}
export enum RuletypesPanelTypeDTO {
value = 'value',
table = 'table',
@@ -6406,6 +6431,7 @@ export type RuletypesRuleDTOAnnotations = { [key: string]: string };
export type RuletypesRuleDTOLabels = { [key: string]: string };
export interface RuletypesRuleDTO {
activeMute?: RuletypesActiveMuteInfoDTO;
/**
* @type string
*/

View File

@@ -43,6 +43,7 @@ import { isModifierKeyPressed } from 'utils/app';
import DeleteAlert from './DeleteAlert';
import { ColumnButton, SearchContainer } from './styles';
import MutedBadge from './TableComponents/MutedBadge';
import Status from './TableComponents/Status';
import ToggleAlertState from './ToggleAlertState';
import { alertActionLogEvent, filterAlerts } from './utils';
@@ -276,7 +277,14 @@ function ListAlert({ allAlertRules, refetch }: ListAlertProps): JSX.Element {
onEditHandler(record, { newTab: isModifierKeyPressed(e) });
};
return <Typography.Link onClick={onClickHandler}>{value}</Typography.Link>;
const muteEndTime = record.activeMute?.effectiveEndTime ?? undefined;
return (
<span className="alert-list-name-cell">
<Typography.Link onClick={onClickHandler}>{value}</Typography.Link>
<MutedBadge muteEndTime={muteEndTime} />
</span>
);
},
sortOrder: sortedInfo.columnKey === 'name' ? sortedInfo.order : null,
},

View File

@@ -0,0 +1,20 @@
.alert-list-name-cell {
display: inline-flex;
align-items: center;
gap: 8px;
}
.alert-list-muted-badge {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 7px;
font-size: 11px;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--bg-amber-500);
background: rgba(255, 205, 86, 0.12);
border: 1px solid rgba(255, 205, 86, 0.25);
border-radius: 4px;
}

View File

@@ -0,0 +1,46 @@
import { BellOff } from '@signozhq/icons';
import dayjs from 'dayjs';
import './MutedBadge.styles.scss';
const formatRemaining = (endTime: string | undefined): string | null => {
if (!endTime) {
return null;
}
const end = dayjs(endTime);
const now = dayjs();
const diffMs = end.diff(now);
if (diffMs <= 0) {
return null;
}
const totalMinutes = Math.floor(diffMs / 60000);
const days = Math.floor(totalMinutes / (60 * 24));
const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
const minutes = totalMinutes % 60;
if (days > 0) {
return `${days}d ${hours}h`;
}
if (hours > 0) {
return `${hours}h ${minutes}m`;
}
return `${minutes}m`;
};
interface MutedBadgeProps {
muteEndTime?: string;
}
function MutedBadge({ muteEndTime }: MutedBadgeProps): JSX.Element | null {
if (!muteEndTime) {
return null;
}
const remaining = formatRemaining(muteEndTime);
return (
<span className="alert-list-muted-badge">
<BellOff size={10} />
<span>MUTED{remaining ? ` · ${remaining}` : ''}</span>
</span>
);
}
export default MutedBadge;

View File

@@ -12,6 +12,20 @@
margin-right: 4px;
}
}
.alert-state-segmented-wrapper {
position: relative;
display: inline-flex;
}
.alert-state-segmented-anchor {
position: absolute;
right: 0;
bottom: 0;
width: 0;
height: 0;
pointer-events: none;
}
.dropdown-menu {
border-radius: 4px;
box-shadow: none;

View File

@@ -1,7 +1,6 @@
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Color } from '@signozhq/design-tokens';
import { Divider, Dropdown, MenuProps, Tooltip } from 'antd';
import { Switch } from '@signozhq/ui/switch';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { Copy, Ellipsis, PenLine, Trash2 } from '@signozhq/icons';
import {
@@ -17,6 +16,13 @@ import { NEW_ALERT_SCHEMA_VERSION } from 'types/api/alerts/alertTypesV2';
import { AlertDef } from 'types/api/alerts/def';
import { AlertHeaderProps } from '../AlertHeader';
import AlertStateSegmented, {
AlertSegmentedState,
} from '../MuteAlert/AlertStateSegmented';
import MutePopover from '../MuteAlert/MutePopover';
import MuteSchedulerDrawer from '../MuteAlert/MuteSchedulerDrawer';
import { useActiveMute } from '../MuteAlert/useActiveMute';
import { useMuteAlertRule } from '../MuteAlert/useMuteAlertRule';
import RenameModal from './RenameModal';
import './ActionButtons.styles.scss';
@@ -123,19 +129,77 @@ function AlertActionButtons({
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => (): void => setAlertRuleState(undefined), []);
const toggleAlertRule = useCallback(() => {
setIsAlertRuleDisabled((prev) => !prev);
handleAlertStateToggle();
}, [handleAlertStateToggle]);
const { activeMute, refetch: refetchActiveMute } = useActiveMute(ruleId);
const segmentedState: AlertSegmentedState = useMemo(() => {
if (isAlertRuleDisabled) {
return 'disabled';
}
if (activeMute) {
return 'muted';
}
return 'active';
}, [isAlertRuleDisabled, activeMute]);
const [isMutePopoverOpen, setIsMutePopoverOpen] = useState<boolean>(false);
const [isMuteDrawerOpen, setIsMuteDrawerOpen] = useState<boolean>(false);
const { mute, isLoading: isMuting } = useMuteAlertRule({
ruleId,
onSuccess: () => {
setIsMutePopoverOpen(false);
setIsMuteDrawerOpen(false);
refetchActiveMute();
},
});
const handleActiveClick = useCallback(() => {
// If currently disabled, re-enable. Otherwise (already active) no-op.
// When muted, the segmented control disables this button.
if (isAlertRuleDisabled) {
setIsAlertRuleDisabled(false);
handleAlertStateToggle();
}
}, [isAlertRuleDisabled, handleAlertStateToggle]);
const handleMuteClick = useCallback(() => {
if (segmentedState === 'active') {
setIsMutePopoverOpen(true);
}
}, [segmentedState]);
const handleDisableClick = useCallback(() => {
if (!isAlertRuleDisabled) {
setIsAlertRuleDisabled(true);
handleAlertStateToggle();
}
}, [isAlertRuleDisabled, handleAlertStateToggle]);
const ruleDisplayName = alertRuleName ?? alertDetails.alert;
return (
<>
<div className="alert-action-buttons">
<Tooltip title={isAlertRuleDisabled ? 'Enable alert' : 'Disable alert'}>
{isAlertRuleDisabled !== undefined && (
<Switch onChange={toggleAlertRule} value={!isAlertRuleDisabled} />
)}
</Tooltip>
{isAlertRuleDisabled !== undefined && (
<div className="alert-state-segmented-wrapper">
<AlertStateSegmented
state={segmentedState}
onActive={handleActiveClick}
onMute={handleMuteClick}
onDisable={handleDisableClick}
/>
<MutePopover
open={isMutePopoverOpen}
onOpenChange={setIsMutePopoverOpen}
ruleName={ruleDisplayName}
isLoading={isMuting}
onSubmit={mute}
onOpenCustomWindow={(): void => setIsMuteDrawerOpen(true)}
anchor={<span className="alert-state-segmented-anchor" />}
/>
</div>
)}
<CopyToClipboard textToCopy={window.location.href} />
<Divider type="vertical" />
@@ -152,6 +216,14 @@ function AlertActionButtons({
</Dropdown>
</div>
<MuteSchedulerDrawer
open={isMuteDrawerOpen}
onClose={(): void => setIsMuteDrawerOpen(false)}
ruleName={ruleDisplayName}
isLoading={isMuting}
onSubmit={mute}
/>
<RenameModal
isOpen={isRenameAlertOpen}
setIsOpen={setIsRenameAlertOpen}

View File

@@ -1,3 +1,13 @@
.alert-info-wrapper {
display: flex;
flex-direction: column;
gap: 4px;
}
.alert-info__banner {
padding: 0 16px;
}
.alert-info {
display: flex;
justify-content: space-between;

View File

@@ -12,6 +12,9 @@ import AlertActionButtons from './ActionButtons/ActionButtons';
import AlertLabels from './AlertLabels/AlertLabels';
import AlertSeverity from './AlertSeverity/AlertSeverity';
import AlertState from './AlertState/AlertState';
import DisabledBanner from './MuteAlert/DisabledBanner';
import MutedBanner from './MuteAlert/MutedBanner';
import { useActiveMute } from './MuteAlert/useActiveMute';
import './AlertHeader.styles.scss';
@@ -43,6 +46,13 @@ function AlertHeader({ alertDetails }: AlertHeaderProps): JSX.Element {
const isV2Alert = alertDetails.schemaVersion === NEW_ALERT_SCHEMA_VERSION;
const ruleId = alertDetails?.id || '';
const { activeMute } = useActiveMute(ruleId);
const effectiveState = alertRuleState ?? state ?? '';
const isDisabled = effectiveState === 'disabled';
const showMutedBanner = !isDisabled && Boolean(activeMute);
const showDisabledBanner = isDisabled;
const CreateAlertV1Header = (
<div className="alert-info__info-wrapper">
<div className="top-section">
@@ -67,14 +77,23 @@ function AlertHeader({ alertDetails }: AlertHeaderProps): JSX.Element {
);
return (
<div className="alert-info">
{isV2Alert ? <CreateAlertV2Header /> : CreateAlertV1Header}
<div className="alert-info__action-buttons">
<AlertActionButtons
alertDetails={alertDetails}
ruleId={alertDetails?.id || ''}
/>
<div className="alert-info-wrapper">
<div className="alert-info">
{isV2Alert ? <CreateAlertV2Header /> : CreateAlertV1Header}
<div className="alert-info__action-buttons">
<AlertActionButtons alertDetails={alertDetails} ruleId={ruleId} />
</div>
</div>
{showMutedBanner && activeMute && (
<div className="alert-info__banner">
<MutedBanner activeMute={activeMute} />
</div>
)}
{showDisabledBanner && (
<div className="alert-info__banner">
<DisabledBanner rule={alertDetails as RuletypesRuleDTO} />
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,102 @@
.alert-state-segmented {
display: inline-flex;
align-items: center;
gap: 2px;
padding: 3px;
background: var(--bg-ink-300);
border: 1px solid var(--bg-slate-300);
border-radius: 999px;
&__pill {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 12px;
font-size: 12px;
font-weight: 500;
line-height: 1;
color: var(--bg-vanilla-400);
background: transparent;
border: 0;
border-radius: 999px;
cursor: pointer;
transition:
background 140ms,
color 140ms;
&:hover:not(:disabled) {
color: var(--bg-vanilla-100);
background: var(--bg-ink-200);
}
&:disabled {
cursor: not-allowed;
}
&:focus-visible {
outline: 2px solid var(--bg-robin-500);
outline-offset: 2px;
}
&--active-active {
background: var(--bg-robin-500);
color: var(--bg-vanilla-100);
&:hover:not(:disabled) {
background: var(--bg-robin-600);
color: var(--bg-vanilla-100);
}
}
&.alert-state-segmented__pill--active-muted {
background: var(--bg-amber-500);
color: #1a1407;
.alert-state-segmented__icon,
.alert-state-segmented__label {
color: #1a1407;
}
&:hover:not(:disabled) {
background: var(--bg-amber-600);
}
}
&--active-disabled {
background: var(--bg-slate-100);
color: var(--bg-vanilla-100);
&:hover:not(:disabled) {
background: var(--bg-slate-200);
color: var(--bg-vanilla-100);
}
}
}
&__dot {
width: 6px;
height: 6px;
background: var(--bg-vanilla-100);
border-radius: 999px;
}
&__icon {
flex-shrink: 0;
}
}
.lightMode {
.alert-state-segmented {
background: var(--bg-vanilla-200);
border-color: var(--bg-slate-500);
&__pill {
color: var(--bg-ink-300);
&:hover:not(:disabled) {
color: var(--bg-ink-500);
background: var(--bg-vanilla-300);
}
}
}
}

View File

@@ -0,0 +1,86 @@
import { forwardRef } from 'react';
import { BellOff } from '@signozhq/icons';
import classNames from 'classnames';
import './AlertStateSegmented.styles.scss';
export type AlertSegmentedState = 'active' | 'muted' | 'disabled';
export interface AlertStateSegmentedProps {
state: AlertSegmentedState;
onActive: () => void;
onMute: () => void;
onDisable: () => void;
disabled?: boolean;
}
const AlertStateSegmented = forwardRef<
HTMLDivElement,
AlertStateSegmentedProps
>(function AlertStateSegmented(props, ref): JSX.Element {
const { state, onActive, onMute, onDisable, disabled } = props;
const isMuted = state === 'muted';
const isDisabled = state === 'disabled';
return (
<div
className="alert-state-segmented"
role="tablist"
aria-label="Alert rule state"
ref={ref}
>
<button
type="button"
role="tab"
aria-selected={state === 'active'}
aria-label="Active"
className={classNames('alert-state-segmented__pill', {
'alert-state-segmented__pill--active-active': state === 'active',
})}
onClick={onActive}
// Per spec: when muted, un-muting must happen via Planned Downtimes,
// so the Active pill is non-interactive while muted.
disabled={disabled || isMuted}
>
{state === 'active' && (
<span className="alert-state-segmented__dot" aria-hidden />
)}
<span className="alert-state-segmented__label">Active</span>
</button>
<button
type="button"
role="tab"
aria-selected={state === 'muted'}
aria-label="Mute"
className={classNames('alert-state-segmented__pill', {
'alert-state-segmented__pill--active-muted': state === 'muted',
})}
onClick={onMute}
// Muting a disabled rule wouldn't change observable behavior, so the
// Mute pill is non-interactive while disabled.
disabled={disabled || isDisabled}
>
{state === 'muted' && (
<BellOff size={12} className="alert-state-segmented__icon" />
)}
<span className="alert-state-segmented__label">Mute</span>
</button>
<button
type="button"
role="tab"
aria-selected={state === 'disabled'}
aria-label="Disable"
className={classNames('alert-state-segmented__pill', {
'alert-state-segmented__pill--active-disabled': state === 'disabled',
})}
onClick={onDisable}
disabled={disabled}
>
<span className="alert-state-segmented__label">Disable</span>
</button>
</div>
);
});
export default AlertStateSegmented;

View File

@@ -0,0 +1,43 @@
import { CircleOff } from '@signozhq/icons';
import type { RuletypesRuleDTO } from 'api/generated/services/sigNoz.schemas';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import './StateBanners.styles.scss';
dayjs.extend(relativeTime);
interface DisabledBannerProps {
rule: RuletypesRuleDTO;
}
function DisabledBanner({ rule }: DisabledBannerProps): JSX.Element {
const updatedAt = rule.updatedAt ? dayjs(rule.updatedAt) : null;
return (
<div className="state-banner state-banner--disabled" role="status">
<div className="state-banner__icon-disc state-banner__icon-disc--disabled">
<CircleOff size={18} color="var(--bg-slate-50)" />
</div>
<div className="state-banner__body">
<div className="state-banner__title">
<span>Rule disabled</span>
<span className="state-banner__pill state-banner__pill--disabled">
NOT EVALUATING
</span>
</div>
<div className="state-banner__meta">
<span>Evaluation paused no fires will be recorded.</span>
{updatedAt && (
<>
{' · '}
<span>{updatedAt.fromNow()}</span>
</>
)}
</div>
</div>
</div>
);
}
export default DisabledBanner;

View File

@@ -0,0 +1,193 @@
.mute-popover-overlay {
.ant-popover-inner {
padding: 0;
background: var(--bg-ink-400);
border: 1px solid var(--bg-slate-300);
border-radius: 10px;
box-shadow: 0 12px 48px rgba(0, 0, 0, 0.55);
}
.ant-popover-inner-content {
padding: 0;
}
}
.mute-popover {
width: 320px;
padding: 14px;
font-family: 'Inter', sans-serif;
color: var(--bg-vanilla-100);
&__header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 6px;
}
&__title {
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 13px;
font-weight: 600;
color: var(--bg-vanilla-100);
}
&__close {
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
padding: 0;
color: var(--bg-vanilla-400);
background: transparent;
border: 0;
border-radius: 4px;
cursor: pointer;
transition:
color 140ms,
background 140ms;
&:hover {
color: var(--bg-vanilla-100);
background: var(--bg-ink-300);
}
}
&__hint {
margin: 0 0 12px 0;
font-size: 12px;
line-height: 1.45;
color: var(--bg-vanilla-400);
strong {
color: var(--bg-vanilla-100);
font-weight: 600;
}
}
&__grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-bottom: 8px;
}
&__cell {
padding: 9px 0;
font-size: 12.5px;
color: var(--bg-vanilla-100);
background: var(--bg-ink-300);
border: 1px solid var(--bg-slate-300);
border-radius: 6px;
cursor: pointer;
transition:
background 140ms,
border-color 140ms,
color 140ms;
&:hover:not(&--selected) {
background: rgba(78, 116, 248, 0.08);
border-color: var(--bg-robin-500);
}
&--selected {
background: var(--bg-robin-500);
border-color: var(--bg-robin-500);
color: var(--bg-vanilla-100);
}
}
&__custom {
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
width: 100%;
padding: 8px 12px;
font-size: 12.5px;
color: var(--bg-vanilla-100);
background: transparent;
border: 1px dashed var(--bg-slate-200);
border-radius: 6px;
cursor: pointer;
transition:
border-color 140ms,
background 140ms;
&:hover {
border-color: var(--bg-robin-500);
background: rgba(78, 116, 248, 0.06);
}
}
&__divider {
height: 1px;
margin: 12px 0;
background: var(--bg-slate-300);
}
&__label {
display: block;
margin-bottom: 6px;
font-size: 12px;
color: var(--bg-vanilla-400);
}
&__input.ant-input {
padding: 8px 10px;
font-size: 12.5px;
background: var(--bg-ink-300);
border: 1px solid var(--bg-slate-300);
border-radius: 6px;
color: var(--bg-vanilla-100);
}
&__footer {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 12px;
}
&__btn {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
font-size: 12.5px;
font-weight: 500;
border-radius: 6px;
cursor: pointer;
transition:
background 140ms,
color 140ms;
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
&--ghost {
color: var(--bg-vanilla-400);
background: transparent;
border: 1px solid transparent;
&:hover:not(:disabled) {
color: var(--bg-vanilla-100);
background: var(--bg-ink-300);
}
}
&--primary {
color: var(--bg-vanilla-100);
background: var(--bg-robin-500);
border: 1px solid var(--bg-robin-500);
&:hover:not(:disabled) {
background: var(--bg-robin-600);
}
}
}
}

View File

@@ -0,0 +1,256 @@
import { useEffect, useState } from 'react';
import { BellOff, Calendar, X } from '@signozhq/icons';
import { Input, Popover } from 'antd';
import classNames from 'classnames';
import dayjs from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
import type { MutePayload } from './useMuteAlertRule';
import './MutePopover.styles.scss';
dayjs.extend(utc);
dayjs.extend(timezone);
type QuickDuration = {
label: string;
value: string;
minutes: number | null; // null = forever
};
export const QUICK_DURATIONS: QuickDuration[] = [
{ label: '15 min', value: '15m', minutes: 15 },
{ label: '1 hour', value: '1h', minutes: 60 },
{ label: '4 hours', value: '4h', minutes: 240 },
{ label: '1 day', value: '1d', minutes: 60 * 24 },
{ label: '1 week', value: '1w', minutes: 60 * 24 * 7 },
{ label: 'Forever', value: 'forever', minutes: null },
];
const DEFAULT_DURATION_VALUE = '4h';
export const buildMutePayloadFromQuickDuration = (
durationValue: string,
name: string,
): MutePayload | null => {
const duration = QUICK_DURATIONS.find((d) => d.value === durationValue);
if (!duration) {
return null;
}
const now = dayjs();
const startTime = now.toISOString();
// duration.minutes === null → "Forever"; send endTime as null so the
// backend treats the mute as indefinite.
const endTime =
duration.minutes === null
? null
: now.add(duration.minutes, 'minute').toISOString();
return {
name,
startTime,
endTime,
timezone: dayjs.tz.guess?.() || 'UTC',
};
};
const getDefaultMuteName = (ruleName: string | undefined): string =>
ruleName ? `Muted: ${ruleName}` : 'Muted alert';
interface MutePopoverProps {
open: boolean;
onOpenChange: (open: boolean) => void;
anchor: React.ReactNode;
ruleName: string | undefined;
isLoading: boolean;
onSubmit: (payload: MutePayload) => Promise<void> | void;
onOpenCustomWindow: () => void;
}
function MutePopover(props: MutePopoverProps): JSX.Element {
const {
open,
onOpenChange,
anchor,
ruleName,
isLoading,
onSubmit,
onOpenCustomWindow,
} = props;
const [selected, setSelected] = useState<string>(DEFAULT_DURATION_VALUE);
const [name, setName] = useState<string>(getDefaultMuteName(ruleName));
useEffect(() => {
if (open) {
setSelected(DEFAULT_DURATION_VALUE);
setName(getDefaultMuteName(ruleName));
}
}, [open, ruleName]);
// Close on outside click / Escape. We use trigger={[]} on the Popover so
// antd doesn't handle these — without this hook, the popover only closes
// via Cancel / × / Mute submit.
useEffect(() => {
if (!open) {
return undefined;
}
// Drop focus so the trigger button doesn't show a :focus-visible
// outline after the popover closes via Escape / outside click.
const closeAndBlur = (): void => {
(document.activeElement as HTMLElement | null)?.blur();
onOpenChange(false);
};
const handleMouseDown = (e: MouseEvent): void => {
const target = e.target as HTMLElement | null;
if (target?.closest('.mute-popover-overlay')) {
return;
}
closeAndBlur();
};
const handleKey = (e: KeyboardEvent): void => {
if (e.key === 'Escape') {
closeAndBlur();
}
};
// Defer attaching listeners until after the click that opened the
// popover has finished bubbling — otherwise it counts as an outside
// click and we close immediately.
const timer = window.setTimeout(() => {
document.addEventListener('mousedown', handleMouseDown);
document.addEventListener('keydown', handleKey);
}, 0);
return (): void => {
window.clearTimeout(timer);
document.removeEventListener('mousedown', handleMouseDown);
document.removeEventListener('keydown', handleKey);
};
}, [open, onOpenChange]);
const selectedDuration = QUICK_DURATIONS.find((d) => d.value === selected);
const primaryLabel =
selectedDuration?.minutes === null
? 'Mute indefinitely'
: `Mute for ${selectedDuration?.label.toLowerCase() ?? '4 hours'}`;
const handleSubmit = async (): Promise<void> => {
const payload = buildMutePayloadFromQuickDuration(selected, name.trim());
if (!payload || !payload.name) {
return;
}
await onSubmit(payload);
};
const content = (
<div
className="mute-popover"
onKeyDown={(e): void => {
if (e.key === 'Escape') {
onOpenChange(false);
}
}}
>
<div className="mute-popover__header">
<div className="mute-popover__title">
<BellOff size={14} />
<span>Mute notifications</span>
</div>
<button
type="button"
aria-label="Close"
className="mute-popover__close"
onClick={(): void => onOpenChange(false)}
>
<X size={14} />
</button>
</div>
<p className="mute-popover__hint">
Rule keeps evaluating in the background. You&apos;ll still see fires in{' '}
<strong>History</strong> just no pages, Slack, or email.
</p>
<div className="mute-popover__grid">
{QUICK_DURATIONS.map((d) => (
<button
type="button"
key={d.value}
className={classNames('mute-popover__cell', {
'mute-popover__cell--selected': selected === d.value,
})}
onClick={(): void => setSelected(d.value)}
>
{d.label}
</button>
))}
</div>
<button
type="button"
className="mute-popover__custom"
onClick={(): void => {
onOpenChange(false);
onOpenCustomWindow();
}}
>
<Calendar size={14} />
Custom window
</button>
<div className="mute-popover__divider" />
<label className="mute-popover__label" htmlFor="mute-popover-name">
Name
</label>
<Input
id="mute-popover-name"
className="mute-popover__input"
placeholder="e.g. Deployment window"
value={name}
onChange={(e): void => setName(e.target.value)}
maxLength={120}
/>
<div className="mute-popover__footer">
<button
type="button"
className="mute-popover__btn mute-popover__btn--ghost"
onClick={(): void => onOpenChange(false)}
disabled={isLoading}
>
Cancel
</button>
<button
type="button"
className="mute-popover__btn mute-popover__btn--primary"
onClick={handleSubmit}
disabled={isLoading || !name.trim()}
>
<BellOff size={12} />
{primaryLabel}
</button>
</div>
</div>
);
return (
<Popover
open={open}
onOpenChange={onOpenChange}
trigger={[]}
placement="bottomRight"
arrow={false}
destroyTooltipOnHide
overlayClassName="mute-popover-overlay"
content={content}
>
{anchor}
</Popover>
);
}
export default MutePopover;

View File

@@ -0,0 +1,115 @@
.mute-scheduler-drawer {
.ant-drawer-body {
padding: 24px 28px;
background: var(--bg-ink-500);
}
.ant-drawer-header {
display: none;
}
&__header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
&__title {
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 16px;
font-weight: 600;
color: var(--bg-vanilla-100);
}
&__close {
position: absolute;
top: 18px;
right: 24px;
width: 28px;
height: 28px;
font-size: 18px;
line-height: 1;
color: var(--bg-vanilla-400);
background: transparent;
border: 0;
border-radius: 4px;
cursor: pointer;
transition:
background 140ms,
color 140ms;
&:hover {
color: var(--bg-vanilla-100);
background: var(--bg-ink-300);
}
}
&__subtitle {
margin: 8px 0 14px 0;
font-size: 12.5px;
line-height: 1.55;
color: var(--bg-vanilla-400);
strong {
color: var(--bg-vanilla-100);
font-weight: 600;
}
}
&__divider {
height: 1px;
margin: 0 0 16px 0;
background: var(--bg-slate-300);
}
&__form {
.ant-form-item-label > label {
font-size: 12px;
color: var(--bg-vanilla-400);
}
}
&__row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
&__date {
width: 100%;
}
&__callout {
display: flex;
align-items: flex-start;
gap: 8px;
margin: 4px 0 18px 0;
padding: 10px;
background: rgba(35, 196, 248, 0.06);
border: 1px solid rgba(35, 196, 248, 0.2);
border-radius: 6px;
p {
margin: 0;
font-size: 12px;
line-height: 1.5;
color: var(--bg-vanilla-400);
strong {
color: var(--bg-vanilla-100);
font-weight: 600;
}
}
}
&__footer {
display: flex;
justify-content: flex-end;
gap: 8px;
padding-top: 16px;
margin-top: 6px;
border-top: 1px solid var(--bg-slate-300);
}
}

View File

@@ -0,0 +1,247 @@
import { useEffect, useMemo, useState } from 'react';
import { BellOff, Check, Info } from '@signozhq/icons';
import { Button, DatePicker, Drawer, Form, Input, Select } from 'antd';
import type { DefaultOptionType } from 'antd/es/select';
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
import {
recurrenceOptions,
recurrenceOptionWithSubmenu,
recurrenceWeeklyOptions,
} from 'container/PlannedDowntime/PlannedDowntimeutils';
import dayjs from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
import { ALL_TIME_ZONES } from 'utils/timeZoneUtil';
import type { MutePayload } from './useMuteAlertRule';
import './MuteSchedulerDrawer.styles.scss';
dayjs.extend(utc);
dayjs.extend(timezone);
const DATE_FORMAT = DATE_TIME_FORMATS.ORDINAL_DATETIME;
const TZ_OPTIONS: DefaultOptionType[] = ALL_TIME_ZONES.map((tz) => ({
label: tz,
value: tz,
key: tz,
}));
const DURATION_UNIT_OPTIONS = [
{ label: 'Mins', value: 'm' },
{ label: 'Hours', value: 'h' },
];
type MuteSchedulerFormData = {
name: string;
startTime: dayjs.Dayjs | null;
endTime: dayjs.Dayjs | null;
repeatType: string;
repeatOn?: string[];
duration?: number;
timezone: string;
};
interface MuteSchedulerDrawerProps {
open: boolean;
onClose: () => void;
ruleName: string | undefined;
isLoading: boolean;
onSubmit: (payload: MutePayload) => Promise<void> | void;
}
function MuteSchedulerDrawer(props: MuteSchedulerDrawerProps): JSX.Element {
const { open, onClose, ruleName, isLoading, onSubmit } = props;
const [form] = Form.useForm<MuteSchedulerFormData>();
const [recurrenceType, setRecurrenceType] = useState<string>(
recurrenceOptions.doesNotRepeat.value,
);
const [durationUnit, setDurationUnit] = useState<string>('m');
const defaultName = useMemo(
() => (ruleName ? `Muted: ${ruleName}` : 'Muted alert'),
[ruleName],
);
useEffect(() => {
if (open) {
const guess = (dayjs as any).tz?.guess?.() || 'UTC';
form.setFieldsValue({
name: defaultName,
startTime: dayjs(),
endTime: dayjs().add(1, 'hour'),
repeatType: recurrenceOptions.doesNotRepeat.value,
timezone: guess,
});
setRecurrenceType(recurrenceOptions.doesNotRepeat.value);
setDurationUnit('m');
}
}, [open, defaultName, form]);
const handleFinish = async (values: MuteSchedulerFormData): Promise<void> => {
const isRecurring =
values.repeatType &&
values.repeatType !== recurrenceOptions.doesNotRepeat.value;
const payload: MutePayload = {
name: values.name.trim(),
startTime: values.startTime?.format() || dayjs().format(),
endTime: values.endTime ? values.endTime.format() : null,
timezone: values.timezone,
recurrence: isRecurring
? {
duration: values.duration ? `${values.duration}${durationUnit}` : '',
repeatOn: values.repeatOn as any,
repeatType: values.repeatType as any,
startTime: values.startTime?.format() || dayjs().format(),
endTime: values.endTime ? values.endTime.format() : undefined,
}
: undefined,
};
await onSubmit(payload);
};
const requiredRule = [{ required: true }];
return (
<Drawer
width={460}
open={open}
onClose={onClose}
placement="right"
closable={false}
destroyOnClose
className="mute-scheduler-drawer"
rootClassName="mute-scheduler-drawer-root"
>
<div className="mute-scheduler-drawer__header">
<div className="mute-scheduler-drawer__title">
<BellOff size={18} color="var(--bg-amber-500)" />
<span>Mute this alert rule</span>
</div>
<button
type="button"
className="mute-scheduler-drawer__close"
aria-label="Close"
onClick={onClose}
>
×
</button>
</div>
<p className="mute-scheduler-drawer__subtitle">
Creates a planned silence for <strong>{ruleName || 'this rule'}</strong>
rule continues to evaluate; notifications are suppressed for the window
below.
</p>
<div className="mute-scheduler-drawer__divider" />
<Form<MuteSchedulerFormData>
form={form}
layout="vertical"
onFinish={handleFinish}
onValuesChange={(_, all): void => {
if (all.repeatType !== recurrenceType) {
setRecurrenceType(all.repeatType);
}
}}
className="mute-scheduler-drawer__form"
autoComplete="off"
>
<Form.Item label="Name" name="name" rules={requiredRule}>
<Input placeholder="e.g. Deployment window" maxLength={120} />
</Form.Item>
<Form.Item label="Starts" name="startTime" rules={requiredRule}>
<DatePicker
className="mute-scheduler-drawer__date"
showTime
showNow={false}
format={(date): string => date.format(DATE_FORMAT)}
/>
</Form.Item>
<Form.Item
label="Ends"
name="endTime"
required={recurrenceType === recurrenceOptions.doesNotRepeat.value}
rules={[
{
required: recurrenceType === recurrenceOptions.doesNotRepeat.value,
},
]}
>
<DatePicker
className="mute-scheduler-drawer__date"
showTime
showNow={false}
format={(date): string => date.format(DATE_FORMAT)}
/>
</Form.Item>
<div className="mute-scheduler-drawer__row">
<Form.Item label="Repeats every" name="repeatType" rules={requiredRule}>
<Select placeholder="Select" options={recurrenceOptionWithSubmenu} />
</Form.Item>
<Form.Item label="Timezone" name="timezone" rules={requiredRule}>
<Select placeholder="Select timezone" showSearch options={TZ_OPTIONS} />
</Form.Item>
</div>
{recurrenceType === recurrenceOptions.weekly.value && (
<Form.Item label="Weekly occurrence" name="repeatOn" rules={requiredRule}>
<Select
placeholder="Select days"
mode="multiple"
options={Object.values(recurrenceWeeklyOptions)}
/>
</Form.Item>
)}
{recurrenceType &&
recurrenceType !== recurrenceOptions.doesNotRepeat.value && (
<Form.Item label="Duration" name="duration" rules={requiredRule}>
<Input
type="number"
min={1}
placeholder="Enter duration"
addonAfter={
<Select
value={durationUnit}
onChange={(v): void => setDurationUnit(v)}
options={DURATION_UNIT_OPTIONS}
/>
}
onWheel={(e): void => e.currentTarget.blur()}
/>
</Form.Item>
)}
<div className="mute-scheduler-drawer__callout">
<Info size={14} color="var(--bg-aqua-500)" />
<p>
The rule will <strong>keep evaluating</strong> and firing alerts to the
History tab. Only notifications (Slack, PagerDuty, email) are silenced.
</p>
</div>
<div className="mute-scheduler-drawer__footer">
<Button type="text" onClick={onClose} disabled={isLoading}>
Cancel
</Button>
<Button
type="primary"
htmlType="submit"
loading={isLoading}
icon={<Check size={14} />}
>
Mute alert
</Button>
</div>
</Form>
</Drawer>
);
}
export default MuteSchedulerDrawer;

View File

@@ -0,0 +1,115 @@
import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { BellOff } from '@signozhq/icons';
import ROUTES from 'constants/routes';
import dayjs from 'dayjs';
import type { ActiveMute } from './useActiveMute';
import './StateBanners.styles.scss';
const PLANNED_DOWNTIMES_URL = `${ROUTES.LIST_ALL_ALERT}?tab=Configuration&subTab=planned-downtime`;
const formatRemaining = (endTime: string | undefined): string | null => {
if (!endTime) {
return null;
}
const end = dayjs(endTime);
const now = dayjs();
const diffMs = end.diff(now);
if (diffMs <= 0) {
return null;
}
const totalMinutes = Math.floor(diffMs / 60000);
const days = Math.floor(totalMinutes / (60 * 24));
const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
const minutes = totalMinutes % 60;
if (days > 0) {
return `${days}d ${hours}h LEFT`;
}
if (hours > 0) {
return `${hours}h ${minutes}m LEFT`;
}
return `${minutes}m LEFT`;
};
const isIndefinite = (endTime: string | undefined): boolean => {
if (!endTime) {
return true;
}
// If end is more than 5 years away, treat as indefinite (matches "Forever" sentinel).
return dayjs(endTime).diff(dayjs(), 'year') >= 5;
};
interface MutedBannerProps {
activeMute: ActiveMute;
}
function MutedBanner({ activeMute }: MutedBannerProps): JSX.Element {
const endTime = activeMute.effectiveEndTime ?? undefined;
const indefinite = isIndefinite(endTime);
const [remaining, setRemaining] = useState<string | null>(
indefinite ? null : formatRemaining(endTime),
);
useEffect(() => {
if (indefinite) {
return undefined;
}
const interval = setInterval(() => {
setRemaining(formatRemaining(endTime));
}, 60_000);
return (): void => clearInterval(interval);
}, [endTime, indefinite]);
const titleText = useMemo(() => {
if (indefinite) {
return 'Notifications muted indefinitely';
}
if (!endTime) {
return 'Notifications muted';
}
return `Notifications muted until ${dayjs(endTime).format('MMM D, h:mm A')}`;
}, [endTime, indefinite]);
const reason = activeMute.description || activeMute.name;
return (
<div className="state-banner state-banner--muted" role="status">
<div className="state-banner__icon-disc state-banner__icon-disc--muted">
<BellOff size={18} color="var(--bg-amber-500)" />
</div>
<div className="state-banner__body">
<div className="state-banner__title">
<span>{titleText}</span>
{!indefinite && remaining && (
<span className="state-banner__pill state-banner__pill--muted">
{remaining}
</span>
)}
</div>
<div className="state-banner__meta">
<span>
Rule is still evaluating fires will appear in <strong>History</strong>.
</span>
{reason && (
<>
{' · '}
<span>
Name: <strong>{reason}</strong>
</span>
</>
)}
{' · '}
<Link to={PLANNED_DOWNTIMES_URL} className="state-banner__link">
Manage in Planned Downtimes
</Link>
</div>
</div>
</div>
);
}
export default MutedBanner;

View File

@@ -0,0 +1,98 @@
.state-banner {
display: flex;
gap: 14px;
align-items: center;
margin-top: 16px;
padding: 12px 16px;
border-radius: 8px;
font-family: 'Inter', sans-serif;
&--muted {
background: linear-gradient(
90deg,
rgba(255, 205, 86, 0.1),
rgba(255, 205, 86, 0.04)
);
border: 1px solid rgba(255, 205, 86, 0.25);
}
&--disabled {
background: rgba(98, 104, 124, 0.06);
border: 1px solid var(--bg-slate-200);
}
&__icon-disc {
display: flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border-radius: 999px;
flex-shrink: 0;
&--muted {
background: rgba(255, 205, 86, 0.15);
}
&--disabled {
background: rgba(98, 104, 124, 0.15);
}
}
&__body {
flex: 1;
min-width: 0;
}
&__title {
display: flex;
align-items: center;
gap: 8px;
font-size: 13.5px;
font-weight: 600;
color: var(--bg-vanilla-100);
font-variant-numeric: tabular-nums;
}
&__pill {
display: inline-flex;
align-items: center;
padding: 2px 7px;
font-size: 11px;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
border-radius: 4px;
&--muted {
color: var(--bg-amber-500);
background: rgba(255, 205, 86, 0.12);
}
&--disabled {
color: var(--bg-slate-50);
background: rgba(98, 104, 124, 0.18);
}
}
&__meta {
margin-top: 4px;
font-size: 12px;
line-height: 1.5;
color: var(--bg-vanilla-400);
strong {
color: var(--bg-vanilla-100);
font-weight: 600;
}
}
&__link {
color: var(--bg-robin-500);
&:hover {
color: var(--bg-robin-400);
text-decoration: underline;
}
}
}

View File

@@ -0,0 +1,37 @@
import { useMemo } from 'react';
import { useGetRuleByID } from 'api/generated/services/rules';
import type { RuletypesActiveMuteInfoDTO } from 'api/generated/services/sigNoz.schemas';
export type ActiveMute = RuletypesActiveMuteInfoDTO;
type UseActiveMuteResult = {
activeMute: ActiveMute | undefined;
isLoading: boolean;
isFetching: boolean;
refetch: () => void;
};
export const useActiveMute = (
ruleId: string | undefined,
): UseActiveMuteResult => {
const { data, isLoading, isFetching, refetch } = useGetRuleByID(
{ id: ruleId || '' },
{
query: {
enabled: Boolean(ruleId),
refetchOnWindowFocus: false,
},
},
);
const activeMute = useMemo(() => data?.data?.activeMute ?? undefined, [data]);
return {
activeMute,
isLoading,
isFetching,
refetch: () => {
void refetch();
},
};
};

View File

@@ -0,0 +1,92 @@
import { useCallback } from 'react';
import { useMutation, useQueryClient } from 'react-query';
import {
createDowntimeSchedule,
getListDowntimeSchedulesQueryKey,
} from 'api/generated/services/downtimeschedules';
import {
getGetRuleByIDQueryKey,
getListRulesQueryKey,
} from 'api/generated/services/rules';
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
import type {
AlertmanagertypesPostablePlannedMaintenanceDTO,
AlertmanagertypesRecurrenceDTO,
RenderErrorResponseDTO,
} from 'api/generated/services/sigNoz.schemas';
import { AxiosError } from 'axios';
import { useNotifications } from 'hooks/useNotifications';
import { useErrorModal } from 'providers/ErrorModalProvider';
import APIError from 'types/api/error';
export type MutePayload = {
name: string;
startTime: string;
endTime?: string | null;
timezone: string;
recurrence?: AlertmanagertypesRecurrenceDTO;
};
type UseMuteAlertRuleArgs = {
ruleId: string;
onSuccess?: () => void;
};
type UseMuteAlertRuleResult = {
mute: (payload: MutePayload) => Promise<void>;
isLoading: boolean;
};
export const useMuteAlertRule = ({
ruleId,
onSuccess,
}: UseMuteAlertRuleArgs): UseMuteAlertRuleResult => {
const { notifications } = useNotifications();
const { showErrorModal } = useErrorModal();
const queryClient = useQueryClient();
const { mutateAsync, isLoading } = useMutation(
['createMuteDowntime', ruleId],
(payload: AlertmanagertypesPostablePlannedMaintenanceDTO) =>
createDowntimeSchedule(payload),
{
onSuccess: () => {
void queryClient.invalidateQueries(getListDowntimeSchedulesQueryKey());
void queryClient.invalidateQueries(getGetRuleByIDQueryKey({ id: ruleId }));
void queryClient.invalidateQueries(getListRulesQueryKey());
notifications.success({ message: 'Alert muted' });
onSuccess?.();
},
onError: (error) => {
showErrorModal(
convertToApiError(error as AxiosError<RenderErrorResponseDTO>) as APIError,
);
},
},
);
const mute = useCallback(
async (payload: MutePayload): Promise<void> => {
if (!ruleId) {
return;
}
const body: AlertmanagertypesPostablePlannedMaintenanceDTO = {
name: payload.name,
alertIds: [ruleId],
schedule: {
startTime: payload.startTime,
// null = no end ("Forever"). The generated type narrows endTime to
// string, but the API accepts null to mean indefinite.
endTime:
payload.endTime === null ? (null as unknown as string) : payload.endTime,
timezone: payload.timezone,
recurrence: payload.recurrence,
},
};
await mutateAsync(body);
},
[mutateAsync, ruleId],
);
return { mute, isLoading };
};

View File

@@ -29,15 +29,23 @@ func (handler *handler) ListRules(rw http.ResponseWriter, req *http.Request) {
ctx, cancel := context.WithTimeout(req.Context(), 30*time.Second)
defer cancel()
claims, err := authtypes.ClaimsFromContext(ctx)
if err != nil {
render.Error(rw, err)
return
}
rules, err := handler.ruler.ListRuleStates(ctx)
if err != nil {
render.Error(rw, err)
return
}
schedules, _ := handler.ruler.MaintenanceStore().ListPlannedMaintenance(ctx, claims.OrgID)
view := make([]*ruletypes.Rule, 0, len(rules.Rules))
for _, rule := range rules.Rules {
view = append(view, ruletypes.NewRule(rule))
view = append(view, ruletypes.NewRule(rule, schedules))
}
render.Success(rw, http.StatusOK, view)
@@ -47,6 +55,12 @@ func (handler *handler) GetRuleByID(rw http.ResponseWriter, req *http.Request) {
ctx, cancel := context.WithTimeout(req.Context(), 30*time.Second)
defer cancel()
claims, err := authtypes.ClaimsFromContext(ctx)
if err != nil {
render.Error(rw, err)
return
}
id, err := valuer.NewUUID(mux.Vars(req)["id"])
if err != nil {
render.Error(rw, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "id is not a valid uuid-v7"))
@@ -59,7 +73,9 @@ func (handler *handler) GetRuleByID(rw http.ResponseWriter, req *http.Request) {
return
}
render.Success(rw, http.StatusOK, ruletypes.NewRule(rule))
schedules, _ := handler.ruler.MaintenanceStore().ListPlannedMaintenance(ctx, claims.OrgID)
render.Success(rw, http.StatusOK, ruletypes.NewRule(rule, schedules))
}
func (handler *handler) CreateRule(rw http.ResponseWriter, req *http.Request) {
@@ -79,7 +95,7 @@ func (handler *handler) CreateRule(rw http.ResponseWriter, req *http.Request) {
return
}
render.Success(rw, http.StatusCreated, ruletypes.NewRule(rule))
render.Success(rw, http.StatusCreated, ruletypes.NewRule(rule, nil))
}
func (handler *handler) UpdateRuleByID(rw http.ResponseWriter, req *http.Request) {
@@ -150,7 +166,7 @@ func (handler *handler) PatchRuleByID(rw http.ResponseWriter, req *http.Request)
return
}
render.Success(rw, http.StatusOK, ruletypes.NewRule(rule))
render.Success(rw, http.StatusOK, ruletypes.NewRule(rule, nil))
}
func (handler *handler) TestRule(rw http.ResponseWriter, req *http.Request) {

View File

@@ -642,23 +642,114 @@ func (g *GettableRule) MarshalJSON() ([]byte, error) {
}
}
// ActiveMuteInfo holds the currently active mute window for an alert rule.
type ActiveMuteInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
EffectiveStartTime *time.Time `json:"effectiveStartTime,omitempty"`
EffectiveEndTime *time.Time `json:"effectiveEndTime,omitempty"`
}
// findActiveMuteForRule returns the active mute window for a rule, if any.
// Scope expressions are intentionally skipped here because we operate at the
// rule level (no alert labels available), matching the frontend's behaviour.
func findActiveMuteForRule(ruleID string, schedules []*alertmanagertypes.PlannedMaintenance) *ActiveMuteInfo {
if len(schedules) == 0 || ruleID == "" {
return nil
}
now := time.Now()
type candidate struct {
m *alertmanagertypes.PlannedMaintenance
end *time.Time
}
var candidates []candidate
for _, m := range schedules {
if m.Schedule == nil {
continue
}
// Empty RuleIDs means the window applies to all rules.
if len(m.RuleIDs) > 0 {
found := false
for _, id := range m.RuleIDs {
if id == ruleID {
found = true
break
}
}
if !found {
continue
}
}
if !m.IsActive(now) {
continue
}
var end *time.Time
if m.Schedule.Recurrence != nil {
end = m.Schedule.Recurrence.EndTime
} else if !m.Schedule.EndTime.IsZero() {
t := m.Schedule.EndTime
end = &t
}
candidates = append(candidates, candidate{m: m, end: end})
}
if len(candidates) == 0 {
return nil
}
// Sort by soonest end so the most specific window wins; nil (forever) sorts last.
slices.SortFunc(candidates, func(a, b candidate) int {
if a.end == nil && b.end == nil {
return 0
}
if a.end == nil {
return 1
}
if b.end == nil {
return -1
}
return a.end.Compare(*b.end)
})
w := candidates[0]
info := &ActiveMuteInfo{
ID: w.m.ID.StringValue(),
Name: w.m.Name,
Description: w.m.Description,
}
if w.m.Schedule.Recurrence != nil {
t := w.m.Schedule.Recurrence.StartTime
info.EffectiveStartTime = &t
} else if !w.m.Schedule.StartTime.IsZero() {
t := w.m.Schedule.StartTime
info.EffectiveStartTime = &t
}
info.EffectiveEndTime = w.end
return info
}
// Rule is the v2 API read model for an alerting rule. It aligns audit fields
// with the canonical types.TimeAuditable / types.UserAuditable shape used by
// PlannedMaintenance and other entities. v1 handlers keep serializing
// GettableRule directly for back-compat with existing SDK / Terraform clients.
type Rule struct {
Id string `json:"id" required:"true"`
State AlertState `json:"state" required:"true"`
Id string `json:"id" required:"true"`
State AlertState `json:"state" required:"true"`
ActiveMute *ActiveMuteInfo `json:"activeMute,omitempty"`
PostableRule
types.TimeAuditable
types.UserAuditable
}
func NewRule(g *GettableRule) *Rule {
func NewRule(g *GettableRule, schedules []*alertmanagertypes.PlannedMaintenance) *Rule {
r := &Rule{
Id: g.Id,
State: g.State,
PostableRule: g.PostableRule,
ActiveMute: findActiveMuteForRule(g.Id, schedules),
}
r.CreatedAt = g.CreatedAt
r.UpdatedAt = g.UpdatedAt