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): papercut fixes for routing policies and planned downtime tables (#13320)
ashu8912efb2100e6943
diff --git a/frontend/src/components/OverflowBadges/ItemBadge.tsx b/frontend/src/components/OverflowBadges/ItemBadge.tsxnew file mode 100644index 0000000000..4ff178dd50--- /dev/null+++ b/frontend/src/components/OverflowBadges/ItemBadge.tsx@@ -0,0 +1,17 @@+import type { ReactNode } from 'react';+import { Badge } from '@signozhq/ui/badge';++interface ItemBadgeProps {+ children: ReactNode;+ testId?: string;+}++function ItemBadge({ children, testId }: ItemBadgeProps): JSX.Element {+ return (+ <Badge textTransform="none" variant="solid" color="secondary" testId={testId}>+ {children}+ </Badge>+ );+}++export default ItemBadge;diff --git a/frontend/src/components/OverflowBadges/OverflowBadges.module.scss b/frontend/src/components/OverflowBadges/OverflowBadges.module.scssnew file mode 100644index 0000000000..3bc8b01f85--- /dev/null+++ b/frontend/src/components/OverflowBadges/OverflowBadges.module.scss@@ -0,0 +1,32 @@+.badges {+ position: relative;+ display: flex;+ align-items: center;+ gap: var(--spacing-2);+ min-width: 0;+ overflow: hidden;+ white-space: nowrap;+}++.overflow {+ flex-shrink: 0;+ --badge-max-width: none;+}++/* Lays every badge out at its natural width, off-screen, to size the visible row. */+.measure {+ position: absolute;+ top: 0;+ left: 0;+ display: flex;+ width: max-content;+ visibility: hidden;+ pointer-events: none;+}++.extraBadges {+ display: flex;+ flex-wrap: wrap;+ gap: var(--spacing-2);+ max-width: 320px;+}diff --git a/frontend/src/components/OverflowBadges/OverflowBadges.tsx b/frontend/src/components/OverflowBadges/OverflowBadges.tsxnew file mode 100644index 0000000000..734c4cb152--- /dev/null+++ b/frontend/src/components/OverflowBadges/OverflowBadges.tsx@@ -0,0 +1,75 @@+import { type CSSProperties, useRef } from 'react';+import { Tooltip } from '@signozhq/ui/tooltip';++import ItemBadge from './ItemBadge';+import type { OverflowBadgeItem } from './types';+import { useOverflowBadgesLayout } from './useOverflowBadgesLayout';++import styles from './OverflowBadges.module.scss';++interface OverflowBadgesProps {+ items: OverflowBadgeItem[];+}++/**+ * A row of badges: as many as fit the width inline, the rest revealed on hover+ * of a "+N" badge. A lone badge too wide to fit truncates instead.+ */+function OverflowBadges({ items }: OverflowBadgesProps): JSX.Element {+ const containerRef = useRef<HTMLDivElement>(null);+ const measureRef = useRef<HTMLDivElement>(null);+ const { visibleCount, firstMaxWidth, isMeasuring } = useOverflowBadgesLayout(+ items,+ containerRef,+ measureRef,+ );++ const visible = items.slice(0, visibleCount);+ const extra = items.slice(visibleCount);+ // The app sets `--badge-max-width` globally, which outranks Badge's `maxWidth` prop.+ const containerStyle =+ firstMaxWidth === undefined+ ? undefined+ : ({ '--badge-max-width': `${firstMaxWidth}px` } as CSSProperties);++ return (+ <div ref={containerRef} className={styles.badges} style={containerStyle}>+ {visible.map(({ key, label }) => (+ <ItemBadge key={key} testId="overflow-badges-item">+ {label}+ </ItemBadge>+ ))}+ {extra.length > 0 && (+ <Tooltip+ side="bottom"+ title={+ <div className={styles.extraBadges}>+ {extra.map(({ key, label }) => (+ <ItemBadge key={key}>{label}</ItemBadge>+ ))}+ </div>+ }+ >+ {/* Stop the click so the "+N" badge doesn't trigger the row's click. */}+ <span+ role="presentation"+ className={styles.overflow}+ onClick={(e): void => e.stopPropagation()}+ >+ <ItemBadge testId="overflow-badges-more">+{extra.length}</ItemBadge>+ </span>+ </Tooltip>+ )}+ {isMeasuring && (+ <div ref={measureRef} className={styles.measure} aria-hidden>+ {items.map(({ key, label }) => (+ <ItemBadge key={key}>{label}</ItemBadge>+ ))}+ <ItemBadge>+{items.length}</ItemBadge>+ </div>+ )}+ </div>+ );+}++export default OverflowBadges;diff --git a/frontend/src/components/OverflowBadges/__tests__/OverflowBadges.test.tsx b/frontend/src/components/OverflowBadges/__tests__/OverflowBadges.test.tsxnew file mode 100644index 0000000000..2986af2958--- /dev/null+++ b/frontend/src/components/OverflowBadges/__tests__/OverflowBadges.test.tsx@@ -0,0 +1,74 @@+import { render, screen } from 'tests/test-utils';++import OverflowBadges from '../OverflowBadges';+import { computeOverflowBadgesLayout } from '../utils';++const items = ['alpha', 'beta', 'gamma', 'delta'].map((label) => ({+ key: label,+ label,+}));++describe('computeOverflowBadgesLayout', () => {+ it('fits as many badges as the width allows, keeping room for +N', () => {+ // 50 + 4 + 50 + 4 + 30 (+N) = 138 fits; a third badge would not.+ expect(+ computeOverflowBadgesLayout(140, 4, [50, 50, 50, 50], 30),+ ).toStrictEqual({ visibleCount: 2 });+ });++ it('shows every badge without +N when all fit', () => {+ expect(computeOverflowBadgesLayout(200, 4, [50, 50, 50], 30)).toStrictEqual({+ visibleCount: 3,+ });+ });++ it('truncates the first badge when even it does not fit', () => {+ expect(computeOverflowBadgesLayout(100, 4, [300, 50], 30)).toStrictEqual({+ visibleCount: 1,+ firstMaxWidth: 66,+ });+ });++ it('gives a lone too-wide badge the full width', () => {+ expect(computeOverflowBadgesLayout(100, 4, [300], 30)).toStrictEqual({+ visibleCount: 1,+ firstMaxWidth: 100,+ });+ });++ it('returns visibleCount 0 when badgeWidths is empty', () => {+ expect(computeOverflowBadgesLayout(100, 4, [], 30)).toStrictEqual({+ visibleCount: 0,+ });+ });+});++describe('OverflowBadges', () => {+ afterEach(() => {+ jest.restoreAllMocks();+ });++ it('collapses the badges that do not fit into +N', () => {+ jest.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(160);+ jest+ .spyOn(Element.prototype, 'getBoundingClientRect')+ .mockReturnValue({ width: 50 } as DOMRect);++ render(<OverflowBadges items={items} />);++ expect(screen.getAllByTestId('overflow-badges-item')).toHaveLength(2);+ expect(screen.getByTestId('overflow-badges-more')).toHaveTextContent('+2');+ });++ it('omits +N when every badge fits', () => {+ jest.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(1000);+ jest+ .spyOn(Element.prototype, 'getBoundingClientRect')+ .mockReturnValue({ width: 50 } as DOMRect);++ render(<OverflowBadges items={items} />);++ expect(screen.getAllByTestId('overflow-badges-item')).toHaveLength(4);+ expect(screen.queryByTestId('overflow-badges-more')).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/components/OverflowBadges/types.ts b/frontend/src/components/OverflowBadges/types.tsnew file mode 100644index 0000000000..fe40d04638--- /dev/null+++ b/frontend/src/components/OverflowBadges/types.ts@@ -0,0 +1,20 @@+import type { Key, ReactNode } from 'react';++export interface OverflowBadgeItem {+ key: Key;+ label: ReactNode;+}++export interface OverflowBadgesLayout {+ visibleCount: number;+ /** Set when even the first badge does not fit and must truncate. */+ firstMaxWidth?: number;+}++export interface OverflowBadgesMeasurement {+ /** The items these widths were measured for. */+ itemsKey: string;+ badgeWidths: number[];+ overflowWidth: number;+ gap: number;+}diff --git a/frontend/src/components/OverflowBadges/useOverflowBadgesLayout.ts b/frontend/src/components/OverflowBadges/useOverflowBadgesLayout.tsnew file mode 100644index 0000000000..2df24ed09f--- /dev/null+++ b/frontend/src/components/OverflowBadges/useOverflowBadgesLayout.ts@@ -0,0 +1,71 @@+import { type RefObject, useLayoutEffect, useMemo, useState } from 'react';++import type {+ OverflowBadgeItem,+ OverflowBadgesLayout,+ OverflowBadgesMeasurement,+} from './types';+import { computeOverflowBadgesLayout } from './utils';++/**+ * Fits the badges to the container's width, re-fitting on resize. Badge widths+ * are measured once per set of items, from a measuring row holding every badge+ * at its natural width followed by "+N", rendered only while `isMeasuring`.+ */+export function useOverflowBadgesLayout(+ items: OverflowBadgeItem[],+ containerRef: RefObject<HTMLElement>,+ measureRef: RefObject<HTMLElement>,+): OverflowBadgesLayout & { isMeasuring: boolean } {+ const itemsKey = items.map((item) => String(item.key)).join('\u0000');+ const [measurement, setMeasurement] =+ useState<OverflowBadgesMeasurement | null>(null);+ const [available, setAvailable] = useState(0);+ const isMeasuring = items.length > 0 && measurement?.itemsKey !== itemsKey;++ useLayoutEffect(() => {+ const container = containerRef.current;+ const measure = measureRef.current;+ if (!isMeasuring || !container || !measure) {+ return;+ }+ // Rounded up so sub-pixel widths never add up past the container.+ const badgeWidths = Array.from(measure.children, (el) =>+ Math.ceil(el.getBoundingClientRect().width),+ );+ const overflowWidth = badgeWidths.pop() ?? 0;+ setMeasurement({+ itemsKey,+ badgeWidths,+ overflowWidth,+ gap: parseFloat(getComputedStyle(container).columnGap) || 0,+ });+ }, [isMeasuring, itemsKey, containerRef, measureRef]);++ useLayoutEffect(() => {+ const container = containerRef.current;+ if (!container) {+ return undefined;+ }+ const update = (): void => setAvailable(container.clientWidth);+ update();+ const observer = new ResizeObserver(update);+ observer.observe(container);+ return (): void => observer.disconnect();+ }, [containerRef]);++ const layout = useMemo(+ (): OverflowBadgesLayout =>+ isMeasuring || !measurement || available === 0+ ? { visibleCount: items.length }+ : computeOverflowBadgesLayout(+ available,+ measurement.gap,+ measurement.badgeWidths,+ measurement.overflowWidth,+ ),+ [isMeasuring, measurement, available, items.length],+ );++ return { ...layout, isMeasuring };+}diff --git a/frontend/src/components/OverflowBadges/utils.ts b/frontend/src/components/OverflowBadges/utils.tsnew file mode 100644index 0000000000..26129de96d--- /dev/null+++ b/frontend/src/components/OverflowBadges/utils.ts@@ -0,0 +1,33 @@+import type { OverflowBadgesLayout } from './types';++/**+ * How many badges fit `available` px, keeping room for the "+N" badge while any+ * are left out. Always shows at least one, capped to truncate when too wide.+ */+export const computeOverflowBadgesLayout = (+ available: number,+ gap: number,+ badgeWidths: number[],+ overflowWidth: number,+): OverflowBadgesLayout => {+ if (badgeWidths.length === 0) {+ return { visibleCount: 0 };+ }++ let used = 0;+ let visibleCount = 0;+ for (let i = 0; i < badgeWidths.length; i++) {+ const next = used + (i > 0 ? gap : 0) + badgeWidths[i];+ const reserve = i < badgeWidths.length - 1 ? gap + overflowWidth : 0;+ if (next + reserve > available) {+ break;+ }+ used = next;+ visibleCount++;+ }+ if (visibleCount > 0) {+ return { visibleCount };+ }+ const reserve = badgeWidths.length > 1 ? gap + overflowWidth : 0;+ return { visibleCount: 1, firstMaxWidth: Math.max(available - reserve, 0) };+};diff --git a/frontend/src/components/TanStackTableView/TanStackHeaderRow.tsx b/frontend/src/components/TanStackTableView/TanStackHeaderRow.tsxindex 40120a27b5..efaba92ab9 100644--- a/frontend/src/components/TanStackTableView/TanStackHeaderRow.tsx+++ b/frontend/src/components/TanStackTableView/TanStackHeaderRow.tsx@@ -4,6 +4,7 @@ import type {TouchEvent as ReactTouchEvent,} from 'react';import { useCallback, useMemo } from 'react';+import { flushSync } from 'react-dom';import {ArrowDown,ArrowUp,@@ -31,7 +32,7 @@ type TanStackHeaderRowProps<TData = unknown> = {onRemoveColumn?: (columnId: string) => void;orderBy?: SortState | null;onSort?: (sort: SortState | null) => void;- /** Last column cannot be resized */+ /** The fill column and any after it cannot be resized */isLastColumn?: boolean;};@@ -89,6 +90,19 @@ function TanStackHeaderRow<TData>({): void => {event.preventDefault();event.stopPropagation();+ // TanStack starts the drag from the configured size, which an auto or+ // redistributed column does not render at.+ const renderedWidth = Math.round(+ event.currentTarget.closest('th')?.getBoundingClientRect().width ?? 0,+ );+ if (header && renderedWidth > 0 && renderedWidth !== header.getSize()) {+ flushSync(() => {+ header.getContext().table.setColumnSizing((sizing) => ({+ ...sizing,+ [header.column.id]: renderedWidth,+ }));+ });+ }resizeHandler?.(event);};const {diff --git a/frontend/src/components/TanStackTableView/TanStackTable.tsx b/frontend/src/components/TanStackTableView/TanStackTable.tsxindex 36ca78aee3..f0a9dd11cd 100644--- a/frontend/src/components/TanStackTableView/TanStackTable.tsx+++ b/frontend/src/components/TanStackTableView/TanStackTable.tsx@@ -53,7 +53,11 @@ import { useFlatItems } from './useFlatItems';import { useResetScroll } from './useResetScroll';import { useRowKeyData } from './useRowKeyData';import { useTableParams } from './useTableParams';-import { buildPageSizeItems, buildTanstackColumnDef } from './utils';+import {+ buildPageSizeItems,+ buildTanstackColumnDef,+ getFillColumnIndex,+} from './utils';import { VirtuosoTableColGroup } from './VirtuosoTableColGroup';import tableStyles from './TanStackTable.module.scss';@@ -428,6 +432,9 @@ function TanStackTableInner<TData, TItemKey = string>();const tableHeader = useCallback(() => {+ const fillColumnIndex = getFillColumnIndex(+ flatHeaders.map((header) => columnsById.get(header.id)),+ );return (<DndContextsensors={sensors}@@ -453,7 +460,7 @@ function TanStackTableInner<TData, TItemKey = string>(canRemoveColumn={canRemoveColumn}orderBy={orderBy}onSort={setOrderBy}- isLastColumn={index === flatHeaders.length - 1}+ isLastColumn={index >= fillColumnIndex}/>);})}diff --git a/frontend/src/components/TanStackTableView/VirtuosoTableColGroup.tsx b/frontend/src/components/TanStackTableView/VirtuosoTableColGroup.tsxindex 01a7d2c291..53fd8eef13 100644--- a/frontend/src/components/TanStackTableView/VirtuosoTableColGroup.tsx+++ b/frontend/src/components/TanStackTableView/VirtuosoTableColGroup.tsx@@ -1,7 +1,7 @@import type { Table } from '@tanstack/react-table';import type { TableColumnDef } from './types';-import { getColumnWidthStyle } from './utils';+import { getColumnWidthStyle, getFillColumnIndex } from './utils';export function VirtuosoTableColGroup<TData>({columns,@@ -13,6 +13,9 @@ export function VirtuosoTableColGroup<TData>({const visibleTanstackColumns = table.getVisibleFlatColumns();const columnDefsById = new Map(columns.map((c) => [c.id, c]));const columnSizing = table.getState().columnSizing;+ const fillColumnIndex = getFillColumnIndex(+ visibleTanstackColumns.map((c) => columnDefsById.get(c.id)),+ );return (<colgroup>@@ -22,7 +25,7 @@ export function VirtuosoTableColGroup<TData>({return <col key={tanstackCol.id} />;}const persistedWidth = columnSizing[tanstackCol.id];- const isLastColumn = index === visibleTanstackColumns.length - 1;+ const isLastColumn = index === fillColumnIndex;return (<colkey={tanstackCol.id}diff --git a/frontend/src/components/TanStackTableView/__tests__/TanStackTableColumnFill.test.tsx b/frontend/src/components/TanStackTableView/__tests__/TanStackTableColumnFill.test.tsxnew file mode 100644index 0000000000..901cfbd84a--- /dev/null+++ b/frontend/src/components/TanStackTableView/__tests__/TanStackTableColumnFill.test.tsx@@ -0,0 +1,51 @@+import { screen } from '@testing-library/react';++import type { TableColumnDef } from '../types';+import { defaultColumns, renderTanStackTable, type TestRow } from './testUtils';++jest.mock('hooks/useDarkMode', () => ({+ useIsDarkMode: (): boolean => false,+}));++const actionsColumn: TableColumnDef<TestRow> = {+ id: 'actions',+ header: 'Actions',+ cell: (): string => 'act',+ width: { fixed: '96px', passLastColumnFill: true },+};++const colWidths = (container: HTMLElement): string[] =>+ Array.from(container.querySelectorAll('colgroup col')).map(+ (col) => (col as HTMLElement).style.width,+ );++const isResizable = (headerText: string): boolean =>+ Boolean(+ screen+ .getByText(headerText)+ .closest('th')+ ?.querySelector('[title="Drag to resize column"]'),+ );++describe('TanStackTable column fill', () => {+ it('fills and locks the last column by default', () => {+ const { container } = renderTanStackTable();++ expect(colWidths(container).at(-1)).toBe('100%');+ expect(isResizable('Name')).toBe(true);+ expect(isResizable('Value')).toBe(false);+ });++ it('hands the fill to the previous column when the last passes it on', () => {+ const { container } = renderTanStackTable({+ props: { columns: [...defaultColumns, actionsColumn] },+ });++ const widths = colWidths(container);+ expect(widths.at(-2)).toBe('100%');+ expect(widths.at(-1)).toBe('96px');+ expect(isResizable('Name')).toBe(true);+ expect(isResizable('Value')).toBe(false);+ expect(isResizable('Actions')).toBe(false);+ });+});diff --git a/frontend/src/components/TanStackTableView/__tests__/utils.test.ts b/frontend/src/components/TanStackTableView/__tests__/utils.test.tsnew file mode 100644index 0000000000..20a7a67cb3--- /dev/null+++ b/frontend/src/components/TanStackTableView/__tests__/utils.test.ts@@ -0,0 +1,28 @@+import type { TableColumnDef } from '../types';+import { getFillColumnIndex } from '../utils';++const column = (+ id: string,+ width?: TableColumnDef<unknown>['width'],+): TableColumnDef<unknown> => ({+ id,+ header: id,+ cell: (): null => null,+ width,+});++describe('getFillColumnIndex', () => {+ it('fills the last column by default', () => {+ expect(getFillColumnIndex([column('a'), column('b')])).toBe(1);+ });++ it('fills the previous column when the last passes it on', () => {+ expect(+ getFillColumnIndex([+ column('a'),+ column('b'),+ column('actions', { fixed: '96px', passLastColumnFill: true }),+ ]),+ ).toBe(1);+ });+});diff --git a/frontend/src/components/TanStackTableView/types.ts b/frontend/src/components/TanStackTableView/types.tsindex 0ea7ac7300..529f0adb97 100644--- a/frontend/src/components/TanStackTableView/types.ts+++ b/frontend/src/components/TanStackTableView/types.ts@@ -74,6 +74,8 @@ export type TableColumnDef<default?: number | string;max?: number | string;ignoreLastColumnFill?: boolean;+ /** When last, hand the fill to the previous column instead of taking it. */+ passLastColumnFill?: boolean;};};diff --git a/frontend/src/components/TanStackTableView/utils.ts b/frontend/src/components/TanStackTableView/utils.tsindex 35d83d1354..e34aebedba 100644--- a/frontend/src/components/TanStackTableView/utils.ts+++ b/frontend/src/components/TanStackTableView/utils.ts@@ -63,6 +63,19 @@ export const getColumnWidthStyle = <TData>(};};+/**+ * Index of the column that fills spare width: the last one, or the one before+ * it when the last sets `width.passLastColumnFill`.+ */+export const getFillColumnIndex = <TData>(+ columns: (TableColumnDef<TData> | undefined)[],+): number => {+ const lastIndex = columns.length - 1;+ return columns[lastIndex]?.width?.passLastColumnFill+ ? lastIndex - 1+ : lastIndex;+};+const isSkeletonRow = (row: unknown): boolean => {const r = row as Record<string, unknown>;return typeof r?.id === 'string' && r.id.startsWith('skeleton-');diff --git a/frontend/src/container/PlannedDowntime/PlannedDowntime.module.scss b/frontend/src/container/PlannedDowntime/PlannedDowntime.module.scssindex 2683d159ba..62d986dda4 100644--- a/frontend/src/container/PlannedDowntime/PlannedDowntime.module.scss+++ b/frontend/src/container/PlannedDowntime/PlannedDowntime.module.scss@@ -121,13 +121,6 @@font-size: 13px;}-.badges {- display: flex;- gap: var(--spacing-2);- overflow: hidden;- white-space: nowrap;-}-.timeText {display: inline-block;white-space: nowrap;diff --git a/frontend/src/container/PlannedDowntime/PlannedDowntime.tsx b/frontend/src/container/PlannedDowntime/PlannedDowntime.tsxindex b6734ff6ce..fc50066630 100644--- a/frontend/src/container/PlannedDowntime/PlannedDowntime.tsx+++ b/frontend/src/container/PlannedDowntime/PlannedDowntime.tsx@@ -5,6 +5,7 @@ import React, {useMemo,useState,} from 'react';+import { useAppLocation } from 'lib/router/useAppLocation';import { navigate } from 'lib/router/navigation';import { Plus, Search } from '@signozhq/icons';import { Button } from '@signozhq/ui/button';@@ -53,6 +54,7 @@ export function PlannedDowntime(): JSX.Element {data: alertsData,isError,isLoading,+ isFetching: isFetchingAlerts,} = useListRules({query: { cacheTime: 0 },});@@ -60,6 +62,7 @@ export function PlannedDowntime(): JSX.Element {const [form] = Form.useForm();const { user } = useAppContext();const { showErrorModal } = useErrorModal();+ const location = useAppLocation();const urlQuery = useUrlQuery();const [initialValues, setInitialValues] =@@ -83,20 +86,31 @@ export function PlannedDowntime(): JSX.Element {}}, [form, isOpen]);- const [searchValue, setSearchValue] = React.useState<string>(- urlQuery.get('search') || '',- );+ const [searchValue, setSearchValue] = React.useState<string>(() => {+ const searchFromUrlQuery = urlQuery.get('search');+ if (searchFromUrlQuery) {+ return searchFromUrlQuery;+ }+ const search =+ (typeof window !== 'undefined' && window.location.search) ||+ location.search ||+ '';+ return new URLSearchParams(search).get('search') || '';+ });const [deleteData, setDeleteData] = useState<{ id: string; name: string }>();const [isEditMode, setEditMode] = useState<boolean>(false);const updateUrlWithSearch = useDebouncedFn((value) => {- const searchValue = value as string;- if (searchValue) {- urlQuery.set('search', searchValue);+ const nextSearch = value as string;+ const search =+ (typeof window !== 'undefined' && window.location.search) || location.search;+ const params = new URLSearchParams(search);+ if (nextSearch) {+ params.set('search', nextSearch);} else {- urlQuery.delete('search');+ params.delete('search');}- const url = `/alerts?${urlQuery.toString()}`;+ const url = `/alerts?${params.toString()}`;navigate(url, { replace: true });}, 300);@@ -127,9 +141,11 @@ export function PlannedDowntime(): JSX.Element {const canEdit = user?.role !== USER_ROLES.VIEWER;const { formatTimezoneAdjustedTimestamp } = useTimezone();+ const isAlertsLoading = isLoading || (!alertsData && isFetchingAlerts);const columns = React.useMemo(- () => getPlannedDowntimeColumns(formatTimezoneAdjustedTimestamp),- [formatTimezoneAdjustedTimestamp],+ () =>+ getPlannedDowntimeColumns(formatTimezoneAdjustedTimestamp, isAlertsLoading),+ [formatTimezoneAdjustedTimestamp, isAlertsLoading],);const handleCreate = useCallback((): void => {@@ -204,7 +220,7 @@ export function PlannedDowntime(): JSX.Element {<div className={styles.commandHeader}><div className={styles.headingBlock}><Typography.Title className={styles.title}>- Planned Downtime+ All planned downtimes</Typography.Title><span className={styles.countPill}>{totalDowntimes}</span></div>@@ -226,7 +242,7 @@ export function PlannedDowntime(): JSX.Element {disabledTooltip="You need edit permissions to create a planned downtime"testId="planned-downtime-create">- New downtime+ New Downtime</Button><TextToolTiptext="More details on how to schedule planned downtime"diff --git a/frontend/src/container/PlannedDowntime/__test__/PlannedDowntime.test.tsx b/frontend/src/container/PlannedDowntime/__test__/PlannedDowntime.test.tsxindex 3ba7963888..2e239790cf 100644--- a/frontend/src/container/PlannedDowntime/__test__/PlannedDowntime.test.tsx+++ b/frontend/src/container/PlannedDowntime/__test__/PlannedDowntime.test.tsx@@ -10,8 +10,7 @@ import {AlertmanagertypesRepeatTypeDTO,} from 'api/generated/services/sigNoz.schemas';import type { ErrorType } from 'api/generatedAPIInstance';-import { mockLocation } from 'container/RoutingPolicies/__tests__/testUtils';-import { mockAppLocation } from 'tests/router-mocks';+import { mockAppLocation, mockNavigate } from 'tests/router-mocks';import { render, userEvent } from 'tests/test-utils';import { USER_ROLES } from 'types/roles';@@ -102,8 +101,6 @@ const mockDowntimeQueryResult: Partial<DowntimeQueryResult> = {let mockUrlQuery: URLSearchParams;-mockAppLocation({ pathname: '/alerts' });-jest.mock('hooks/useUrlQuery', () => ({__esModule: true,default: (): URLSearchParams => mockUrlQuery,@@ -127,29 +124,44 @@ jest.mock('api/generated/services/downtimeschedules', () => ({isLoading: false,}),}));++let mockRulesState: {+ data?: { data: Array<{ id: number | string; alert: string }> };+ isError: boolean;+ isLoading: boolean;+ isFetching: boolean;+} = {+ data: { data: [] },+ isError: false,+ isLoading: false,+ isFetching: false,+};+jest.mock('api/generated/services/rules', () => ({- useListRules: (): {- data: { data: [] };- isError: false;- isLoading: false;- } => ({- data: { data: [] },- isError: false,- isLoading: false,- }),+ useListRules: (): typeof mockRulesState => mockRulesState,}));describe('PlannedDowntime Component', () => {beforeEach(() => {jest.clearAllMocks();mockUrlQuery = new URLSearchParams();- mockLocation('/alerts');+ mockAppLocation({+ pathname: '/alerts',+ search: '',+ });+ mockDowntimeQueryResult.data = MOCK_DOWNTIME_RESPONSE;+ mockRulesState = {+ data: { data: [] },+ isError: false,+ isLoading: false,+ isFetching: false,+ };});it('renders the header, search and create action', () => {renderPage();- expect(screen.getByText('Planned Downtime')).toBeInTheDocument();+ expect(screen.getByText('All planned downtimes')).toBeInTheDocument();expect(screen.getByTestId(SEARCH_TEST_ID)).toBeInTheDocument();expect(screen.getByTestId(CREATE_TEST_ID)).toHaveAttribute('aria-disabled',@@ -193,14 +205,14 @@ describe('PlannedDowntime Component', () => {expect(screen.getByText(MOCK_DOWNTIME_3_NAME)).toBeInTheDocument();});- it('shows the key schedule details and hides secondary columns by default', async () => {+ it('shows the key schedule details, timezone and duration, and hides secondary columns by default', async () => {renderPage();await screen.findByText(MOCK_DOWNTIME_1_NAME);expect(screen.getByText(/\(Asia\/Kolkata\)$/)).toBeInTheDocument();expect(screen.getByText('Weekly on Mon · 2h')).toBeInTheDocument();- expect(screen.queryByText('Asia/Kolkata')).not.toBeInTheDocument();- expect(screen.queryByText('2h')).not.toBeInTheDocument();+ expect(screen.getAllByText('Asia/Kolkata').length).toBeGreaterThan(0);+ expect(screen.getAllByText('2h').length).toBeGreaterThan(0);expect(screen.queryByText('Database maintenance')).not.toBeInTheDocument();expect(screen.queryByText('[email protected]')).not.toBeInTheDocument();expect(screen.queryByText('[email protected]')).not.toBeInTheDocument();@@ -219,7 +231,9 @@ describe('PlannedDowntime Component', () => {'Downtime','Status','Schedule',+ 'Timezone','Repeats',+ 'Duration','Alerts Silenced',]);});@@ -290,4 +304,116 @@ describe('PlannedDowntime Component', () => {await screen.findByText(MOCK_DOWNTIME_1_NAME);expect(screen.queryByTestId('downtime-actions-1')).not.toBeInTheDocument();});++ it('preserves existing query parameters such as sort and pagination when typing in search (Bug 54)', async () => {+ jest.useFakeTimers();+ mockAppLocation({+ pathname: '/alerts',+ search:+ '?tab=Configuration&subTab=planned-downtime&orderBy=name&order=asc&page=2&limit=20',+ });+ const navigateSpy = mockNavigate();++ renderPage();++ fireEvent.change(screen.getByTestId(SEARCH_TEST_ID), {+ target: { value: 'query' },+ });++ jest.advanceTimersByTime(350);++ expect(navigateSpy).toHaveBeenCalled();+ const callArg = navigateSpy.mock.calls[0][0];+ expect(callArg).toContain('tab=Configuration');+ expect(callArg).toContain('subTab=planned-downtime');+ expect(callArg).toContain('orderBy=name');+ expect(callArg).toContain('order=asc');+ expect(callArg).toContain('page=2');+ expect(callArg).toContain('limit=20');+ expect(callArg).toContain('search=query');++ jest.useRealTimers();+ });++ it('shows skeleton while alert rules are loading for scoped downtime (Bug 56)', async () => {+ mockRulesState = {+ data: undefined,+ isError: false,+ isLoading: true,+ isFetching: true,+ };+ const scopedDowntime = createMockDowntime({+ id: 'scoped-1',+ name: 'Scoped Downtime Loading',+ schedule: buildSchedule({ startTime: MOCK_DATE_1 }),+ alertIds: ['rule-1'],+ });+ mockDowntimeQueryResult.data = {+ data: [scopedDowntime],+ status: 'success',+ };++ renderPage();++ await screen.findByText('Scoped Downtime Loading');+ expect(screen.getByTestId('alerts-silenced-skeleton')).toBeInTheDocument();+ expect(screen.queryByText('All alert rules')).not.toBeInTheDocument();+ });++ it('shows "Unknown rule" when scoped rule IDs cannot be resolved (Bug 56)', async () => {+ mockRulesState = {+ data: { data: [] },+ isError: false,+ isLoading: false,+ isFetching: false,+ };+ const scopedDowntime = createMockDowntime({+ id: 'scoped-2',+ name: 'Scoped Downtime Deleted Rule',+ schedule: buildSchedule({ startTime: MOCK_DATE_1 }),+ alertIds: ['deleted-rule-id'],+ });+ mockDowntimeQueryResult.data = {+ data: [scopedDowntime],+ status: 'success',+ };++ renderPage();++ await screen.findByText('Scoped Downtime Deleted Rule');+ expect(screen.getByText('Unknown rule')).toBeInTheDocument();+ expect(screen.queryByText('All alert rules')).not.toBeInTheDocument();+ });++ it('shows resolved alert rule name when scoped rule ID exists', async () => {+ mockRulesState = {+ data: {+ data: [+ {+ id: 'rule-42',+ alert: 'Disk Space High',+ } as any,+ ],+ },+ isError: false,+ isLoading: false,+ isFetching: false,+ };+ const scopedDowntime = createMockDowntime({+ id: 'scoped-3',+ name: 'Scoped Downtime Resolved',+ schedule: buildSchedule({ startTime: MOCK_DATE_1 }),+ alertIds: ['rule-42'],+ });+ mockDowntimeQueryResult.data = {+ data: [scopedDowntime],+ status: 'success',+ };++ renderPage();++ await screen.findByText('Scoped Downtime Resolved');+ expect(screen.getByText('Disk Space High')).toBeInTheDocument();+ expect(screen.queryByText('All alert rules')).not.toBeInTheDocument();+ });});diff --git a/frontend/src/container/PlannedDowntime/table.config.tsx b/frontend/src/container/PlannedDowntime/table.config.tsxindex d56f81b1f1..a78b030eb6 100644--- a/frontend/src/container/PlannedDowntime/table.config.tsx+++ b/frontend/src/container/PlannedDowntime/table.config.tsx@@ -1,6 +1,8 @@import { Badge } from '@signozhq/ui/badge';+import { Skeleton } from '@signozhq/ui/skeleton';import { AlertmanagertypesMaintenanceStatusDTO } from 'api/generated/services/sigNoz.schemas';import type { TableColumnDef } from 'components/TanStackTableView';+import OverflowBadges from 'components/OverflowBadges/OverflowBadges';import TanStackTable from 'components/TanStackTableView';import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';import { toRelativeTime } from 'pages/AlertList/NotificationChannels/utils/relativeTime';@@ -31,8 +33,11 @@ const STATUS_BADGE: Record<},};+const COLUMN_WIDTH = { default: 'auto', min: '120px' };+export function getPlannedDowntimeColumns(formatTimezoneAdjustedTimestamp: (date: string, format: string) => string,+ isAlertsLoading?: boolean,): TableColumnDef<DowntimeSchedulesTableData>[] {const textCell = (value: string | undefined): JSX.Element => (<TanStackTable.Text title={value || undefined}>@@ -66,7 +71,7 @@ export function getPlannedDowntimeColumns(id: 'name',header: 'Downtime',accessorKey: 'name',- width: { default: '100%', min: '200px' },+ width: COLUMN_WIDTH,enableSort: true,enableResize: true,enableRemove: false,@@ -84,7 +89,7 @@ export function getPlannedDowntimeColumns(id: 'status',header: 'Status',accessorKey: 'status',- width: { default: '110px', min: '100px' },+ width: COLUMN_WIDTH,enableSort: true,enableResize: true,enableMove: false,@@ -103,7 +108,7 @@ export function getPlannedDowntimeColumns(id: 'window',header: 'Schedule',accessorFn: (row) => row.schedule?.startTime,- width: { default: '340px', min: '220px' },+ width: COLUMN_WIDTH,enableSort: true,enableResize: true,enableMove: false,@@ -113,8 +118,7 @@ export function getPlannedDowntimeColumns(id: 'timezone',header: 'Timezone',accessorFn: (row) => row.schedule?.timezone,- width: { default: '130px', min: '110px' },- defaultVisibility: false,+ width: COLUMN_WIDTH,enableSort: false,enableResize: true,enableMove: false,@@ -124,7 +128,7 @@ export function getPlannedDowntimeColumns(id: 'repeats',header: 'Repeats',accessorFn: (row) => row.schedule?.recurrence?.repeatType,- width: { default: '180px', min: '120px' },+ width: COLUMN_WIDTH,enableSort: false,enableResize: true,enableMove: false,@@ -134,8 +138,7 @@ export function getPlannedDowntimeColumns(id: 'duration',header: 'Duration',accessorFn: (row) => row.schedule?.recurrence?.duration,- width: { default: '110px', min: '90px' },- defaultVisibility: false,+ width: COLUMN_WIDTH,enableSort: false,enableResize: true,enableMove: false,@@ -146,42 +149,46 @@ export function getPlannedDowntimeColumns(id: 'alertsSilenced',header: 'Alerts Silenced',accessorKey: 'alertIds',- width: { default: '200px', min: '140px' },+ width: COLUMN_WIDTH,enableSort: false,enableResize: true,enableMove: false,- cell: ({ row }): JSX.Element =>- row.alertOptions.length ? (- <div- className={styles.badges}- title={row.alertOptions- .flatMap((alert) =>- typeof alert.label === 'string' ? [alert.label] : [],- )- .join(', ')}- >- {row.alertOptions.map((alert) => (- <Badge- key={alert.value}- textTransform="none"- variant="solid"- color="secondary"- >- {alert.label}- </Badge>- ))}- </div>- ) : (- <Badge textTransform="none" variant="solid" color="secondary">- All alert rules- </Badge>- ),+ cell: ({ row }): JSX.Element => {+ const hasScopedAlerts = Boolean(row.alertIds && row.alertIds.length > 0);+ if (!hasScopedAlerts) {+ return (+ <Badge textTransform="none" variant="solid" color="secondary">+ All alert rules+ </Badge>+ );+ }++ if (isAlertsLoading) {+ return (+ <Skeleton.Input+ testId="alerts-silenced-skeleton"+ active+ size="small"+ style={{ width: 100, height: 22 }}+ />+ );+ }++ return (+ <OverflowBadges+ items={row.alertOptions.map((alert) => ({+ key: String(alert.value),+ label: alert.label,+ }))}+ />+ );+ },},{id: 'description',header: 'Description',accessorKey: 'description',- width: { default: '200px', min: '120px' },+ width: COLUMN_WIDTH,defaultVisibility: false,enableSort: false,enableResize: true,@@ -192,7 +199,7 @@ export function getPlannedDowntimeColumns(id: 'createdBy',header: 'Created By',accessorKey: 'createdBy',- width: { default: '180px', min: '120px' },+ width: COLUMN_WIDTH,defaultVisibility: false,enableSort: false,enableResize: true,@@ -203,7 +210,7 @@ export function getPlannedDowntimeColumns(id: 'createdAt',header: 'Created At',accessorKey: 'createdAt',- width: { default: '150px', min: '120px' },+ width: COLUMN_WIDTH,defaultVisibility: false,enableSort: true,enableResize: true,@@ -214,7 +221,7 @@ export function getPlannedDowntimeColumns(id: 'updatedBy',header: 'Updated By',accessorKey: 'updatedBy',- width: { default: '180px', min: '120px' },+ width: COLUMN_WIDTH,defaultVisibility: false,enableSort: false,enableResize: true,@@ -225,7 +232,7 @@ export function getPlannedDowntimeColumns(id: 'updatedAt',header: 'Updated At',accessorKey: 'updatedAt',- width: { default: '150px', min: '120px' },+ width: COLUMN_WIDTH,defaultVisibility: false,enableSort: true,enableResize: true,diff --git a/frontend/src/container/PlannedDowntime/usePlannedDowntimeTable.ts b/frontend/src/container/PlannedDowntime/usePlannedDowntimeTable.tsindex 207b1022fe..7902e0406c 100644--- a/frontend/src/container/PlannedDowntime/usePlannedDowntimeTable.ts+++ b/frontend/src/container/PlannedDowntime/usePlannedDowntimeTable.ts@@ -5,7 +5,6 @@ import type { SortState } from 'components/TanStackTableView/types';import { useCalculatedPageSize } from 'components/TanStackTableView/useCalculatedPageSize';import { useTableParams } from 'components/TanStackTableView/useTableParams';-import { getAlertOptionsFromIds } from './PlannedDowntimeutils';import { DowntimeAlertOption, DowntimeSchedulesTableData } from './types';export const PLANNED_DOWNTIME_QUERY_PARAMS = {@@ -72,16 +71,38 @@ function usePlannedDowntimeTable(const filteredDowntimes = useMemo(() => {const search = searchValue.toLowerCase();+ const alertOptionsMap = new Map<string, DowntimeAlertOption>();+ alertOptions.forEach((option) => {+ if (option?.value != null) {+ alertOptionsMap.set(String(option.value), option);+ }+ });+return downtimes.filter((downtime) =>downtime.name.toLowerCase().includes(search) ||downtime.id === searchValue,)- .map((downtime) => ({- ...downtime,- alertOptions: getAlertOptionsFromIds(downtime.alertIds || [], alertOptions),- }));+ .map((downtime) => {+ const resolvedAlertOptions: DowntimeAlertOption[] = (+ downtime.alertIds || []+ ).map((id) => {+ const found = alertOptionsMap.get(String(id));+ if (found) {+ return found;+ }+ return {+ label: 'Unknown rule',+ value: id,+ };+ });++ return {+ ...downtime,+ alertOptions: resolvedAlertOptions,+ };+ });}, [downtimes, alertOptions, searchValue]);const pagedDowntimes = useMemo(() => {diff --git a/frontend/src/container/RoutingPolicies/RoutingPolicies.module.scss b/frontend/src/container/RoutingPolicies/RoutingPolicies.module.scssindex 2683d159ba..62d986dda4 100644--- a/frontend/src/container/RoutingPolicies/RoutingPolicies.module.scss+++ b/frontend/src/container/RoutingPolicies/RoutingPolicies.module.scss@@ -121,13 +121,6 @@font-size: 13px;}-.badges {- display: flex;- gap: var(--spacing-2);- overflow: hidden;- white-space: nowrap;-}-.timeText {display: inline-block;white-space: nowrap;diff --git a/frontend/src/container/RoutingPolicies/RoutingPolicies.tsx b/frontend/src/container/RoutingPolicies/RoutingPolicies.tsxindex d740526e74..9fc60016f8 100644--- a/frontend/src/container/RoutingPolicies/RoutingPolicies.tsx+++ b/frontend/src/container/RoutingPolicies/RoutingPolicies.tsx@@ -102,7 +102,7 @@ function RoutingPolicies(): JSX.Element {<div className={styles.commandHeader}><div className={styles.headingBlock}><Typography.Title className={styles.title}>- Routing Policies+ All routing policies</Typography.Title><span className={styles.countPill}>{routingPoliciesData.length}</span></div>@@ -124,7 +124,7 @@ function RoutingPolicies(): JSX.Element {disabledTooltip="You need edit permissions to create a routing policy"testId="routing-policies-create">- New routing policy+ New Routing Policy</Button><TextToolTiptext="More details on how to configure routing policies"diff --git a/frontend/src/container/RoutingPolicies/__tests__/RoutingPolicies.test.tsx b/frontend/src/container/RoutingPolicies/__tests__/RoutingPolicies.test.tsxindex 362ec980e7..767f80cf72 100644--- a/frontend/src/container/RoutingPolicies/__tests__/RoutingPolicies.test.tsx+++ b/frontend/src/container/RoutingPolicies/__tests__/RoutingPolicies.test.tsx@@ -50,7 +50,7 @@ describe('RoutingPolicies', () => {it('should render components properly', () => {render(<RoutingPolicies />);- expect(screen.getByText('Routing Policies')).toBeInTheDocument();+ expect(screen.getByText('All routing policies')).toBeInTheDocument();expect(screen.getByTestId(SEARCH_TEST_ID)).toBeInTheDocument();expect(screen.getByTestId(CREATE_TEST_ID)).toBeInTheDocument();expect(screen.getByTestId('routing-policy-list')).toBeInTheDocument();diff --git a/frontend/src/container/RoutingPolicies/__tests__/RoutingPoliciesList.test.tsx b/frontend/src/container/RoutingPolicies/__tests__/RoutingPoliciesList.test.tsxindex 9b7c1390b7..22d853427a 100644--- a/frontend/src/container/RoutingPolicies/__tests__/RoutingPoliciesList.test.tsx+++ b/frontend/src/container/RoutingPolicies/__tests__/RoutingPoliciesList.test.tsx@@ -71,7 +71,7 @@ describe('RoutingPolicyList', () => {const resizable = Array.from(document.querySelectorAll('th')).filter((th) => th.querySelector('[title="Drag to resize column"]')).map((th) => th.textContent?.trim());- expect(resizable).toStrictEqual(['Routing Policy', 'Expression', 'Channels']);+ expect(resizable).toStrictEqual(['Routing Policy', 'Channels', 'Expression']);});it('opens the policy on row click', async () => {diff --git a/frontend/src/container/RoutingPolicies/__tests__/useRoutingPolicies.test.tsx b/frontend/src/container/RoutingPolicies/__tests__/useRoutingPolicies.test.tsxindex 93996d1173..16b143905b 100644--- a/frontend/src/container/RoutingPolicies/__tests__/useRoutingPolicies.test.tsx+++ b/frontend/src/container/RoutingPolicies/__tests__/useRoutingPolicies.test.tsx@@ -202,6 +202,39 @@ describe('useRoutingPolicies', () => {expect(callArg).toContain('search=test+search');});+ it('should preserve existing query parameters such as sort and pagination when updating search (Bug 54)', async () => {+ const { result } = renderHookWithWrapper(+ '/alerts?tab=Configuration&subTab=routing-policies',+ );+ // nuqs writes sort and pagination to the URL before the router location catches up+ window.history.replaceState(+ null,+ '',+ '/alerts?tab=Configuration&subTab=routing-policies&orderBy=name&order=asc&page=2&limit=20',+ );++ try {+ act(() => {+ result.current.setSearchTerm('policy');+ });++ await waitFor(() => {+ expect(mockNavigate).toHaveBeenCalled();+ });+ } finally {+ window.history.replaceState(null, '', '/');+ }++ const callArg = mockNavigate.mock.calls[0][0];+ expect(callArg).toContain('tab=Configuration');+ expect(callArg).toContain('subTab=routing-policies');+ expect(callArg).toContain('orderBy=name');+ expect(callArg).toContain('order=asc');+ expect(callArg).toContain('page=2');+ expect(callArg).toContain('limit=20');+ expect(callArg).toContain('search=policy');+ });+it('should remove search param from URL when search is cleared', async () => {const { result } = renderHookWithWrapper('/alerts?search=existing');diff --git a/frontend/src/container/RoutingPolicies/table.config.tsx b/frontend/src/container/RoutingPolicies/table.config.tsxindex 5fdcc786da..4e158a8fde 100644--- a/frontend/src/container/RoutingPolicies/table.config.tsx+++ b/frontend/src/container/RoutingPolicies/table.config.tsx@@ -1,5 +1,5 @@-import { Badge } from '@signozhq/ui/badge';import type { TableColumnDef } from 'components/TanStackTableView';+import OverflowBadges from 'components/OverflowBadges/OverflowBadges';import TanStackTable from 'components/TanStackTableView';import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';import { toRelativeTime } from 'pages/AlertList/NotificationChannels/utils/relativeTime';@@ -7,6 +7,8 @@ import { toRelativeTime } from 'pages/AlertList/NotificationChannels/utils/relatimport styles from './RoutingPolicies.module.scss';import { RoutingPolicy } from './types';+const COLUMN_WIDTH = { default: 'auto', min: '120px' };+export function getRoutingPolicyColumns(formatTimezoneAdjustedTimestamp: (date: string, format: string) => string,): TableColumnDef<RoutingPolicy>[] {@@ -42,7 +44,7 @@ export function getRoutingPolicyColumns(id: 'name',header: 'Routing Policy',accessorKey: 'name',- width: { default: '100%', min: '220px' },+ width: COLUMN_WIDTH,enableSort: true,enableResize: true,enableRemove: false,@@ -56,51 +58,45 @@ export function getRoutingPolicyColumns(</TanStackTable.Text>),},- {- id: 'expression',- header: 'Expression',- accessorKey: 'expression',- width: { default: '260px', min: '160px' },- enableSort: false,- enableResize: true,- enableMove: false,- cell: ({ row }): JSX.Element => (- <TanStackTable.Text className={styles.expression} title={row.expression}>- {row.expression}- </TanStackTable.Text>- ),- },{id: 'channels',header: 'Channels',accessorKey: 'channels',- width: { default: '220px', min: '140px' },+ width: COLUMN_WIDTH,enableSort: false,enableResize: true,enableMove: false,cell: ({ row }): JSX.Element =>row.channels?.length ? (- <div className={styles.badges} title={row.channels.join(', ')}>- {row.channels.map((channel) => (- <Badge- key={channel}- textTransform="none"- variant="solid"- color="secondary"- >- {channel}- </Badge>- ))}- </div>+ <OverflowBadges+ items={row.channels.map((channel) => ({+ key: channel,+ label: channel,+ }))}+ />) : (<TanStackTable.Text>-</TanStackTable.Text>),},+ {+ id: 'expression',+ header: 'Expression',+ accessorKey: 'expression',+ width: COLUMN_WIDTH,+ enableSort: false,+ enableResize: true,+ enableMove: false,+ cell: ({ row }): JSX.Element => (+ <TanStackTable.Text className={styles.expression} title={row.expression}>+ {row.expression}+ </TanStackTable.Text>+ ),+ },{id: 'createdBy',header: 'Created By',accessorKey: 'createdBy',- width: { default: '180px', min: '120px' },+ width: COLUMN_WIDTH,defaultVisibility: false,enableSort: false,enableResize: true,@@ -111,7 +107,7 @@ export function getRoutingPolicyColumns(id: 'createdAt',header: 'Created At',accessorKey: 'createdAt',- width: { default: '150px', min: '120px' },+ width: COLUMN_WIDTH,defaultVisibility: false,enableSort: true,enableResize: true,@@ -122,7 +118,7 @@ export function getRoutingPolicyColumns(id: 'updatedBy',header: 'Updated By',accessorKey: 'updatedBy',- width: { default: '180px', min: '120px' },+ width: COLUMN_WIDTH,defaultVisibility: false,enableSort: false,enableResize: true,@@ -133,7 +129,7 @@ export function getRoutingPolicyColumns(id: 'updatedAt',header: 'Updated At',accessorKey: 'updatedAt',- width: { default: '150px', min: '120px' },+ width: COLUMN_WIDTH,defaultVisibility: false,enableSort: true,enableResize: true,diff --git a/frontend/src/container/RoutingPolicies/useRoutingPolicies.ts b/frontend/src/container/RoutingPolicies/useRoutingPolicies.tsindex 12ebe1c3a2..52a8fe567b 100644--- a/frontend/src/container/RoutingPolicies/useRoutingPolicies.ts+++ b/frontend/src/container/RoutingPolicies/useRoutingPolicies.ts@@ -1,5 +1,6 @@import { useCallback, useMemo, useState } from 'react';import { useQueryClient } from 'react-query';+import { useAppLocation } from 'lib/router/useAppLocation';import { navigate } from 'lib/router/navigation';import { toast } from '@signozhq/ui/sonner';import { GetRoutingPoliciesResponse } from 'api/routingPolicies/getRoutingPolicies';@@ -30,9 +31,20 @@ import './styles.scss';function useRoutingPolicies(): UseRoutingPoliciesReturn {const queryClient = useQueryClient();const urlQuery = useUrlQuery();+ const location = useAppLocation();// Local state- const [searchTerm, setSearchTerm] = useState(urlQuery.get('search') || '');+ const [searchTerm, setSearchTerm] = useState(() => {+ const searchFromUrlQuery = urlQuery.get('search');+ if (searchFromUrlQuery) {+ return searchFromUrlQuery;+ }+ const search =+ (typeof window !== 'undefined' && window.location.search) ||+ location.search ||+ '';+ return new URLSearchParams(search).get('search') || '';+ });const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);const [policyDetailsModalState, setPolicyDetailsModalState] =useState<PolicyDetailsModalState>({@@ -44,12 +56,15 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {const updateUrlWithSearch = useDebouncedFn((value) => {const searchValue = value as string;+ const search =+ (typeof window !== 'undefined' && window.location.search) || location.search;+ const params = new URLSearchParams(search);if (searchValue) {- urlQuery.set('search', searchValue);+ params.set('search', searchValue);} else {- urlQuery.delete('search');+ params.delete('search');}- const url = `/alerts?${urlQuery.toString()}`;+ const url = `/alerts?${params.toString()}`;navigate(url, { replace: true });}, 300);diff --git a/frontend/src/hooks/__tests__/useDebouncedFunction.test.ts b/frontend/src/hooks/__tests__/useDebouncedFunction.test.tsnew file mode 100644index 0000000000..95db6441d8--- /dev/null+++ b/frontend/src/hooks/__tests__/useDebouncedFunction.test.ts@@ -0,0 +1,43 @@+import { renderHook } from '@testing-library/react';++import useDebouncedFn from '../useDebouncedFunction';++describe('useDebouncedFn', () => {+ beforeEach(() => {+ jest.useFakeTimers();+ });++ afterEach(() => {+ jest.useRealTimers();+ });++ it('should debounce function execution', () => {+ const callback = jest.fn();+ const { result } = renderHook(() => useDebouncedFn(callback, 300));++ result.current('first');+ result.current('second');++ expect(callback).not.toHaveBeenCalled();++ jest.advanceTimersByTime(299);+ expect(callback).not.toHaveBeenCalled();++ jest.advanceTimersByTime(1);+ expect(callback).toHaveBeenCalledTimes(1);+ expect(callback).toHaveBeenCalledWith('second');+ });++ it('should cancel pending execution when unmounted (Bug 55)', () => {+ const callback = jest.fn();+ const { result, unmount } = renderHook(() => useDebouncedFn(callback, 300));++ result.current('pending');+ expect(callback).not.toHaveBeenCalled();++ unmount();++ jest.advanceTimersByTime(500);+ expect(callback).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/hooks/useDebouncedFunction.ts b/frontend/src/hooks/useDebouncedFunction.tsindex 69af19be90..d657be662c 100644--- a/frontend/src/hooks/useDebouncedFunction.ts+++ b/frontend/src/hooks/useDebouncedFunction.ts@@ -1,4 +1,4 @@-import { useMemo, useRef } from 'react';+import { useEffect, useMemo, useRef } from 'react';import debounce from 'lodash-es/debounce';export interface DebouncedFunc<T extends (...args: unknown[]) => unknown> {@@ -28,10 +28,19 @@ const useDebouncedFn = <T extends (...args: Array<unknown>) => unknown>(const fnRef = useRef(fn);fnRef.current = fn;- return useMemo(+ const debounced = useMemo(() => debounce(((...args) => fnRef.current(...args)) as T, wait, options),[options, wait],);++ useEffect(+ () => (): void => {+ debounced.cancel();+ },+ [debounced],+ );++ return debounced;};export default useDebouncedFn;diff --git a/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.tsx b/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.tsxindex d79b7c88da..9cf7c9434f 100644--- a/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.tsx+++ b/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.tsx@@ -111,7 +111,7 @@ export const NewDowntimeRecurring: Story = {await screen.findByRole('combobox', { name: 'Repeats every' }),);await userEvent.click(await screen.findByText('Weekly'));- await screen.findByText('Duration');+ await within(await screen.findByRole('dialog')).findByText('Duration');},};diff --git a/frontend/src/pages/AlertList/PlannedDowntime/stories/__story_mockdata__/plannedDowntime.ts b/frontend/src/pages/AlertList/PlannedDowntime/stories/__story_mockdata__/plannedDowntime.tsindex 313d960b1f..80a695b372 100644--- a/frontend/src/pages/AlertList/PlannedDowntime/stories/__story_mockdata__/plannedDowntime.ts+++ b/frontend/src/pages/AlertList/PlannedDowntime/stories/__story_mockdata__/plannedDowntime.ts@@ -47,7 +47,15 @@ const SEEDS: DowntimeSeed[] = [timezone: 'UTC',startsInMs: -2 * HOUR,lastsMs: 6 * HOUR,- alertIds: ['rule-5', 'rule-3'],+ alertIds: [+ 'rule-5',+ 'rule-3',+ 'rule-1',+ 'rule-2',+ 'rule-4',+ 'rule-6',+ 'rule-7',+ ],},{name: 'Nightly ETL window',diff --git a/frontend/src/pages/AlertList/RoutingPolicies/stories/__story_mockdata__/routingPolicies.ts b/frontend/src/pages/AlertList/RoutingPolicies/stories/__story_mockdata__/routingPolicies.tsindex 0710e17a3f..8a538862b0 100644--- a/frontend/src/pages/AlertList/RoutingPolicies/stories/__story_mockdata__/routingPolicies.ts+++ b/frontend/src/pages/AlertList/RoutingPolicies/stories/__story_mockdata__/routingPolicies.ts@@ -26,7 +26,7 @@ const SEEDS: PolicySeed[] = [name: 'Critical production to on-call',description: 'Anything critical in prod pages whoever is on call.',expression: 'severity = "critical" AND env = "prod"',- channels: [1, 0],+ channels: [1, 0, 3, 4, 2, 5],},{name: 'Payments team ownership',