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(dashboard-v2): open the View modal and editor on the panel's own query (#12345)
Abhi kumar9197cb8b3b7d
diff --git a/frontend/src/container/DashboardContainer/visualization/charts/utils/__tests__/sortByMeanDesc.test.ts b/frontend/src/container/DashboardContainer/visualization/charts/utils/__tests__/sortByMeanDesc.test.tsnew file mode 100644index 0000000000..d0670300f5--- /dev/null+++ b/frontend/src/container/DashboardContainer/visualization/charts/utils/__tests__/sortByMeanDesc.test.ts@@ -0,0 +1,66 @@+import { sortByMeanDesc } from '../sortByMeanDesc';++interface Item {+ name: string;+ values: (number | null)[];+}++const item = (name: string, values: (number | null)[]): Item => ({+ name,+ values,+});++const sorted = (items: Item[]): string[] =>+ sortByMeanDesc(items, {+ getValues: (entry) => entry.values,+ getKey: (entry) => entry.name,+ }).map((entry) => entry.name);++describe('sortByMeanDesc', () => {+ it('orders items by descending mean', () => {+ expect(+ sorted([item('a', [1, 1]), item('b', [10, 20]), item('c', [5, 5])]),+ ).toStrictEqual(['b', 'c', 'a']);+ });++ it('sinks items with no finite values to the bottom', () => {+ expect(+ sorted([item('a', []), item('b', [NaN, Infinity]), item('c', [1])]),+ ).toStrictEqual(['c', 'a', 'b']);+ });++ it('ignores non-finite and null values when averaging', () => {+ // Mean over the finite values only is 10, so NaN must not poison it to last place.+ expect(+ sorted([item('a', [2, 2]), item('b', [10, NaN]), item('c', [4, null])]),+ ).toStrictEqual(['b', 'c', 'a']);+ });++ it('produces the same order whichever order the items arrive in', () => {+ const a = item('a', [5]);+ const b = item('b', [5]);+ const c = item('c', [9]);++ expect(sorted([a, b, c])).toStrictEqual(sorted([c, b, a]));+ expect(sorted([b, a, c])).toStrictEqual(['c', 'a', 'b']);+ });++ it('tiebreaks equal means on the key', () => {+ expect(sorted([item('b', [1]), item('a', [1])])).toStrictEqual(['a', 'b']);+ });++ it('tiebreaks on the key for items that have no finite values either', () => {+ expect(sorted([item('b', []), item('a', [NaN])])).toStrictEqual(['a', 'b']);+ });++ it('does not mutate the input array', () => {+ const items = [item('a', [1]), item('b', [9])];++ expect(sorted(items)).toStrictEqual(['b', 'a']);+ expect(items.map((entry) => entry.name)).toStrictEqual(['a', 'b']);+ });++ it('returns an empty array for no items', () => {+ expect(sorted([])).toStrictEqual([]);+ });+});diff --git a/frontend/src/container/DashboardContainer/visualization/charts/utils/sortByMeanDesc.ts b/frontend/src/container/DashboardContainer/visualization/charts/utils/sortByMeanDesc.tsnew file mode 100644index 0000000000..a92965661d--- /dev/null+++ b/frontend/src/container/DashboardContainer/visualization/charts/utils/sortByMeanDesc.ts@@ -0,0 +1,45 @@+type MeanInput = number | null | undefined;++function finiteMean(values: Iterable<MeanInput>): number | null {+ let sum = 0;+ let count = 0;+ for (const value of values) {+ if (typeof value === 'number' && Number.isFinite(value)) {+ sum += value;+ count += 1;+ }+ }+ return count > 0 ? sum / count : null;+}++export interface SortByMeanDescOptions<T> {+ /** Numeric values of an item; non-finite entries are ignored. */+ getValues: (item: T) => Iterable<MeanInput>;+ /** Stable identity of an item, used to break ties on equal means. */+ getKey: (item: T) => string;+}++/**+ * Orders series by descending mean, on a copy (V1 parity: `utils/getSortedSeriesData`). The wire+ * order can't stand in for it: the backend returns series in Go map-iteration order.+ *+ * Call this before building the uPlot config and aligned data — those two and click attribution+ * all index the list positionally, and uPlot draws a stacked bar's segments in series-index order.+ */+export function sortByMeanDesc<T>(+ items: T[],+ { getValues, getKey }: SortByMeanDescOptions<T>,+): T[] {+ return items+ .map((item) => ({ item, mean: finiteMean(getValues(item)) }))+ .sort((a, b) => {+ if (a.mean !== null && b.mean !== null && a.mean !== b.mean) {+ return b.mean - a.mean;+ }+ if ((a.mean === null) !== (b.mean === null)) {+ return a.mean === null ? 1 : -1;+ }+ return getKey(a.item).localeCompare(getKey(b.item));+ })+ .map(({ item }) => item);+}diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/__tests__/panelEditorUrlQuery.promql.test.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/__tests__/panelEditorUrlQuery.promql.test.tsxnew file mode 100644index 0000000000..b648411385--- /dev/null+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/__tests__/panelEditorUrlQuery.promql.test.tsx@@ -0,0 +1,164 @@+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { useState } from 'react';+import { QueryClient, QueryClientProvider } from 'react-query';+// eslint-disable-next-line no-restricted-imports+import { Provider as ReduxProvider } from 'react-redux';+import { MemoryRouter, Route, useHistory, useParams } from 'react-router-dom';+import { CompatRouter } from 'react-router-dom-v5-compat';+import { TooltipProvider } from '@signozhq/ui/tooltip';+import {+ type DashboardtypesPanelDTO,+ TelemetrytypesSignalDTO,+} from 'api/generated/services/sigNoz.schemas';+import { PANEL_TYPES } from 'constants/queryBuilder';+import { QueryBuilderProvider } from 'providers/QueryBuilder';+import configureStore from 'redux-mock-store';+import appStore from 'store';++import { useOpenPanelEditor } from '../../hooks/useOpenPanelEditor';+import { usePanelEditorQuerySync } from '../hooks/usePanelEditorQuerySync';+import PanelEditorQueryBuilder from '../PanelEditorQueryBuilder/PanelEditorQueryBuilder';++// jest.config maps the real hook to a no-op mock; this suite needs real navigation.+jest.mock('hooks/useSafeNavigate', () => {+ const { useHistory: useRouterHistory } =+ jest.requireActual('react-router-dom');+ return {+ useSafeNavigate: (): unknown => {+ const history = useRouterHistory();+ return {+ safeNavigate: (to: string): void => history.push(to),+ };+ },+ };+});++jest.mock('../../store/useDashboardStore', () => ({+ useDashboardStore: (selector: (s: unknown) => unknown): unknown =>+ selector({ dashboardId: 'dash-1' }),+}));++function makePromPanel(name: string, promql: string): DashboardtypesPanelDTO {+ return {+ kind: 'Panel',+ spec: {+ display: { name },+ plugin: { kind: 'signoz/TimeSeriesPanel', spec: {} },+ queries: [+ {+ kind: 'time_series',+ spec: {+ plugin: {+ kind: 'signoz/PromQLQuery',+ spec: { name: 'A', query: promql, legend: '', disabled: false },+ },+ },+ },+ ],+ },+ } as unknown as DashboardtypesPanelDTO;+}++const PANELS: Record<string, DashboardtypesPanelDTO> = {+ A: makePromPanel('Panel A', 'up{job="alpha"}'),+ B: makePromPanel('Panel B', 'up{job="bravo"}'),+};++const noop = (): void => {};++/** Stands in for the editor route: the same draft + builder sync `PanelEditorContainer` runs. */+function EditorRoute(): JSX.Element {+ const { panelId } = useParams<{ panelId: string }>();+ const [panel] = useState(PANELS[panelId]);++ usePanelEditorQuerySync({+ draft: panel,+ panelType: PANEL_TYPES.TIME_SERIES,+ setSpec: noop,+ refetch: noop,+ signal: TelemetrytypesSignalDTO.metrics,+ savedQueries: panel.spec.queries,+ });++ return (+ <PanelEditorQueryBuilder+ panelKind="signoz/TimeSeriesPanel"+ signal={TelemetrytypesSignalDTO.metrics}+ isLoadingQueries={false}+ onStageRunQuery={noop}+ onCancelQuery={noop}+ />+ );+}++function Harness(): JSX.Element {+ const openPanelEditor = useOpenPanelEditor();+ const history = useHistory();++ return (+ <>+ <button+ type="button"+ data-testid="edit-a"+ onClick={(): void => openPanelEditor('A', { panel: PANELS.A })}+ >+ edit A+ </button>+ <button+ type="button"+ data-testid="edit-b"+ onClick={(): void => openPanelEditor('B', { panel: PANELS.B })}+ >+ edit B+ </button>+ <button+ type="button"+ data-testid="back"+ onClick={(): void => history.push('/dashboard/dash-1')}+ >+ back+ </button>+ <Route+ path="/dashboard/:dashboardId/panel/:panelId"+ component={EditorRoute}+ />+ </>+ );+}++const renderHarness = (): void => {+ render(+ <MemoryRouter initialEntries={['/dashboard/dash-1']}>+ <CompatRouter>+ <QueryClientProvider client={new QueryClient()}>+ <ReduxProvider store={configureStore([])(appStore.getState())}>+ <TooltipProvider>+ <QueryBuilderProvider>+ <Harness />+ </QueryBuilderProvider>+ </TooltipProvider>+ </ReduxProvider>+ </QueryClientProvider>+ </CompatRouter>+ </MemoryRouter>,+ );+};++describe('Panel editor route, PromQL panels', () => {+ it('opens on the edited panel query, not the previously edited one', async () => {+ const user = userEvent.setup({ pointerEventsCheck: 0 });+ renderHarness();++ await user.click(screen.getByTestId('edit-a'));+ expect(screen.getByTestId('promql-query-input')).toHaveValue(+ 'up{job="alpha"}',+ );++ await user.click(screen.getByTestId('back'));+ await user.click(screen.getByTestId('edit-b'));+ expect(screen.getByTestId('promql-query-input')).toHaveValue(+ 'up{job="bravo"}',+ );+ });+});diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/kinds/BarChartPanel/Renderer.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/kinds/BarChartPanel/Renderer.tsxindex 5688e07814..5f7ce16165 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/kinds/BarChartPanel/Renderer.tsx+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/kinds/BarChartPanel/Renderer.tsx@@ -27,6 +27,7 @@ import { stepClickTimeRange } from '../../utils/drilldown/chartClickTimeRange';import { enrichChartClick } from '../../utils/drilldown/enrichChartClick';import { getBuilderQueries } from '../../utils/getBuilderQueries';import { getPanelTimeRange } from '../../utils/getPanelTimeRange';+import { sortSeriesByMeanDesc } from '../../utils/sortSeriesByMean';import { buildBarChartConfig } from './utils/buildConfig';import { ChartClickData } from 'lib/uPlotV2/plugins/TooltipPlugin/types';@@ -70,7 +71,12 @@ function BarPanelRenderer({const flatSeries = useMemo(() =>- flattenTimeSeries(getTimeSeriesResults(data.response), data.legendMap ?? {}),+ sortSeriesByMeanDesc(+ flattenTimeSeries(+ getTimeSeriesResults(data.response),+ data.legendMap ?? {},+ ),+ ),[data.response, data.legendMap],);diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/kinds/TimeSeriesPanel/Renderer.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/kinds/TimeSeriesPanel/Renderer.tsxindex 95d762934f..e3e6d87855 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/kinds/TimeSeriesPanel/Renderer.tsx+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/kinds/TimeSeriesPanel/Renderer.tsx@@ -27,6 +27,7 @@ import { stepClickTimeRange } from '../../utils/drilldown/chartClickTimeRange';import { enrichChartClick } from '../../utils/drilldown/enrichChartClick';import { getBuilderQueries } from '../../utils/getBuilderQueries';import { getPanelTimeRange } from '../../utils/getPanelTimeRange';+import { sortSeriesByMeanDesc } from '../../utils/sortSeriesByMean';import { buildTimeSeriesConfig } from './utils/buildConfig';import { ChartClickData } from 'lib/uPlotV2/plugins/TooltipPlugin/types';@@ -71,7 +72,12 @@ function TimeSeriesPanelRenderer({const flatSeries = useMemo(() =>- flattenTimeSeries(getTimeSeriesResults(data.response), data.legendMap ?? {}),+ sortSeriesByMeanDesc(+ flattenTimeSeries(+ getTimeSeriesResults(data.response),+ data.legendMap ?? {},+ ),+ ),[data.response, data.legendMap],);diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/utils/__tests__/sortSeriesByMean.test.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/utils/__tests__/sortSeriesByMean.test.tsnew file mode 100644index 0000000000..99904d8f24--- /dev/null+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/utils/__tests__/sortSeriesByMean.test.ts@@ -0,0 +1,95 @@+import type { PanelSeries } from 'pages/DashboardPageV2/DashboardContainer/queryV5/types';++import { sortSeriesByMeanDesc } from '../sortSeriesByMean';++function makeSeries(+ queryName: string,+ values: number[],+ overrides: Partial<PanelSeries> = {},+): PanelSeries {+ return {+ queryName,+ legend: '',+ labels: {},+ kind: 'series',+ values: values.map((value, index) => ({+ timestamp: (index + 1) * 1_000,+ value,+ })),+ aggregation: { index: 0, alias: '' },+ ...overrides,+ };+}++const names = (series: PanelSeries[]): string[] =>+ series.map((item) => item.queryName);++describe('sortSeriesByMeanDesc', () => {+ it('orders series by descending mean', () => {+ const sorted = sortSeriesByMeanDesc([+ makeSeries('A', [1, 1]),+ makeSeries('B', [10, 20]),+ makeSeries('C', [5, 5]),+ ]);++ expect(names(sorted)).toStrictEqual(['B', 'C', 'A']);+ });++ it('sinks series with no finite points to the bottom', () => {+ const sorted = sortSeriesByMeanDesc([+ makeSeries('A', []),+ makeSeries('B', [NaN, Infinity]),+ makeSeries('C', [1]),+ ]);++ expect(names(sorted)).toStrictEqual(['C', 'A', 'B']);+ });++ it('ignores non-finite points when averaging', () => {+ const sorted = sortSeriesByMeanDesc([+ makeSeries('A', [2, 2]),+ // Mean over finite points only is 10, so NaN must not poison it to last place.+ makeSeries('B', [10, NaN]),+ ]);++ expect(names(sorted)).toStrictEqual(['B', 'A']);+ });++ it('produces the same order regardless of input order', () => {+ const a = makeSeries('A', [5]);+ const b = makeSeries('B', [5]);+ const c = makeSeries('C', [9]);++ expect(names(sortSeriesByMeanDesc([a, b, c]))).toStrictEqual(+ names(sortSeriesByMeanDesc([c, b, a])),+ );+ expect(names(sortSeriesByMeanDesc([b, a, c]))).toStrictEqual(['C', 'A', 'B']);+ });++ it('tiebreaks equal means on labels when the query name matches', () => {+ const forward = sortSeriesByMeanDesc([+ makeSeries('A', [1], { labels: { host: 'b' } }),+ makeSeries('A', [1], { labels: { host: 'a' } }),+ ]);+ const reversed = sortSeriesByMeanDesc([+ makeSeries('A', [1], { labels: { host: 'a' } }),+ makeSeries('A', [1], { labels: { host: 'b' } }),+ ]);++ expect(forward.map((item) => item.labels.host)).toStrictEqual(['a', 'b']);+ expect(reversed.map((item) => item.labels.host)).toStrictEqual(['a', 'b']);+ });++ it('does not mutate the input array', () => {+ const input = [makeSeries('A', [1]), makeSeries('B', [9])];++ const sorted = sortSeriesByMeanDesc(input);++ expect(names(input)).toStrictEqual(['A', 'B']);+ expect(names(sorted)).toStrictEqual(['B', 'A']);+ });++ it('returns an empty array for no series', () => {+ expect(sortSeriesByMeanDesc([])).toStrictEqual([]);+ });+});diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/utils/getPanelBuilderQuery.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/utils/getPanelBuilderQuery.tsnew file mode 100644index 0000000000..9f6d791ff1--- /dev/null+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/utils/getPanelBuilderQuery.ts@@ -0,0 +1,23 @@+import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';+import { initialQueriesMap } from 'constants/queryBuilder';+import type { Query } from 'types/api/queryBuilder/queryBuilderData';++import { getPanelDefinition } from '../registry';+import { PANEL_KIND_TO_PANEL_TYPE } from '../types/panelKind';+import { fromPerses } from '../../queryV5/persesQueryAdapters';++/**+ * The panel's saved query as a builder `Query` — what the editor route and the View+ * modal put in `compositeQuery` when they open. Matches the seed+ * `usePanelEditorQuerySync` computes from the panel.+ */+export function getPanelBuilderQuery(panel: DashboardtypesPanelDTO): Query {+ const kind = panel.spec.plugin.kind;+ const [defaultSignal] = getPanelDefinition(kind).supportedSignals;+ // A query-less panel seeds from the kind's first supported signal — `fromPerses`'s+ // metrics default isn't authorable in every kind (e.g. List).+ if (panel.spec.queries.length === 0 && defaultSignal) {+ return initialQueriesMap[defaultSignal];+ }+ return fromPerses(panel.spec.queries, PANEL_KIND_TO_PANEL_TYPE[kind]);+}diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/utils/sortSeriesByMean.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/utils/sortSeriesByMean.tsnew file mode 100644index 0000000000..b6be2e7ac4--- /dev/null+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/utils/sortSeriesByMean.ts@@ -0,0 +1,18 @@+import { sortByMeanDesc } from 'container/DashboardContainer/visualization/charts/utils/sortByMeanDesc';+import type { PanelSeries } from 'pages/DashboardPageV2/DashboardContainer/queryV5/types';++function seriesKey(series: PanelSeries): string {+ const labels = Object.keys(series.labels)+ .sort()+ .map((name) => `${name}=${series.labels[name]}`)+ .join(',');+ return `${series.queryName}|${series.aggregation.index}|${series.kind}|${labels}`;+}++/** `sortByMeanDesc` over flattened V5 series; call it before building the config and chart data. */+export function sortSeriesByMeanDesc(series: PanelSeries[]): PanelSeries[] {+ return sortByMeanDesc(series, {+ getValues: (item) => item.values.map((point) => point.value),+ getKey: seriesKey,+ });+}diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/__tests__/usePanelActionItems.test.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/__tests__/usePanelActionItems.test.tsxindex 0b9d9c4998..81c8576c7a 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/__tests__/usePanelActionItems.test.tsx+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/__tests__/usePanelActionItems.test.tsx@@ -240,7 +240,10 @@ describe('usePanelActionItems', () => {(i) => 'key' in i && i.key === 'edit-panel',);(edit as { onClick: () => void }).onClick();- expect(mockOpenEditor).toHaveBeenCalledWith('panel-1');+ // The panel rides along so its saved query lands in the editor URL.+ expect(mockOpenEditor).toHaveBeenCalledWith('panel-1', {+ panel: mockPanel,+ });});it('"Move to section" offers a single "Dashboard (root)" target', () => {@@ -394,7 +397,9 @@ describe('usePanelActionItems', () => {(i) => 'key' in i && i.key === 'view-panel',);(view as { onClick: () => void }).onClick();- expect(mockOpenView).toHaveBeenCalledWith('panel-1');+ // The panel goes along so the opener can seed the shared query builder before+ // the modal mounts (otherwise it renders the previously-viewed panel's query).+ expect(mockOpenView).toHaveBeenCalledWith('panel-1', baseArgs.panel);});it('create-alert seeds an alert from this panel', () => {diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/usePanelActionItems.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/usePanelActionItems.tsxindex 566c034d58..6ba8277fe7 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/usePanelActionItems.tsx+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/usePanelActionItems.tsx@@ -130,7 +130,7 @@ export function usePanelActionItems({key: 'view-panel',label: 'View',icon: <Fullscreen size={14} />,- onClick: (): void => openView(panelId),+ onClick: (): void => openView(panelId, panel),});}if (canEdit && canEditWidget && panelCapabilities.edit) {@@ -139,7 +139,7 @@ export function usePanelActionItems({label: label('Edit panel'),icon: <PenLine size={14} />,disabled: isLocked,- onClick: (): void => openPanelEditor(panelId),+ onClick: (): void => openPanelEditor(panelId, { panel }),});}if (canEdit && canEditWidget && panelCapabilities.clone) {diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.addons.test.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.addons.test.tsxnew file mode 100644index 0000000000..22a2303aaa--- /dev/null+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.addons.test.tsx@@ -0,0 +1,253 @@+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import type { ReactElement } from 'react';+import { QueryClient, QueryClientProvider } from 'react-query';+// eslint-disable-next-line no-restricted-imports+import { Provider as ReduxProvider } from 'react-redux';+import { MemoryRouter } from 'react-router-dom';+import { CompatRouter } from 'react-router-dom-v5-compat';+import { TooltipProvider } from '@signozhq/ui/tooltip';+import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';+import { QueryBuilderProvider } from 'providers/QueryBuilder';+import configureStore from 'redux-mock-store';+import appStore from 'store';++import ViewPanelModal from '../ViewPanelModal/ViewPanelModal';+import { useViewPanel } from '../hooks/useViewPanel';++// CodeMirror (the where-clause editor) needs real DOM measurement APIs.+beforeAll(() => {+ const rect = {+ width: 100,+ height: 20,+ top: 0,+ left: 0,+ right: 100,+ bottom: 20,+ x: 0,+ y: 0,+ toJSON: (): unknown => rect,+ } as DOMRect;+ const rects = { length: 1, item: (): DOMRect => rect, 0: rect };+ document.createRange = (): Range =>+ ({+ getClientRects: (): unknown => rects,+ getBoundingClientRect: (): DOMRect => rect,+ setStart: (): void => {},+ setEnd: (): void => {},+ startContainer: document.body,+ endContainer: document.body,+ startOffset: 0,+ endOffset: 0,+ collapsed: true,+ commonAncestorContainer: document.body,+ }) as unknown as Range;+ Element.prototype.getBoundingClientRect = (): DOMRect => rect;+});++// jest.config maps the real hook to a no-op mock; this suite needs real navigation.+jest.mock('hooks/useSafeNavigate', () => {+ const { useHistory } = jest.requireActual('react-router-dom');+ return {+ useSafeNavigate: (): unknown => {+ const history = useHistory();+ return {+ safeNavigate: (to: string, opts?: { replace?: boolean }): void => {+ if (opts?.replace) {+ history.replace(to);+ } else {+ history.push(to);+ }+ },+ };+ },+ };+});++jest.mock('api/querySuggestions/getKeySuggestions', () => ({+ getKeySuggestions: jest+ .fn()+ .mockResolvedValue({ data: { data: { keys: {} } } }),+}));+jest.mock('api/querySuggestions/getValueSuggestion', () => ({+ getValueSuggestions: jest.fn().mockResolvedValue({+ data: { data: { values: { stringValues: [], numberValues: [] } } },+ }),+}));++jest.mock(+ 'pages/DashboardPageV2/DashboardContainer/hooks/usePanelQuery',+ () => ({+ usePanelQuery: (): unknown => ({+ data: undefined,+ isFetching: false,+ isPreviousData: false,+ error: null,+ refetch: jest.fn(),+ cancelQuery: jest.fn(),+ pagination: undefined,+ }),+ }),+);++jest.mock(+ 'pages/DashboardPageV2/DashboardContainer/store/useDashboardStore',+ () => ({+ useDashboardStore: (selector: (s: unknown) => unknown): unknown =>+ selector({ dashboardId: 'dash-1' }),+ }),+);++jest.mock(+ 'pages/DashboardPageV2/DashboardContainer/PanelEditor/PreviewPane/PreviewPane',+ () =>+ function MockPreviewPane(): ReactElement {+ return <div data-testid="preview-pane" />;+ },+);++jest.mock('../hooks/useDrilldown', () => ({+ useDrilldown: (): unknown => ({+ enableDrillDown: false,+ onPanelClick: jest.fn(),+ contextMenuProps: {+ coordinates: null,+ popoverPosition: null,+ items: null,+ onClose: jest.fn(),+ },+ }),+}));++jest.mock('../hooks/usePanelInteractions', () => ({+ usePanelInteractions: (): unknown => ({+ onDragSelect: jest.fn(),+ dashboardPreference: { syncMode: 0 },+ }),+}));++jest.mock(+ '../ViewPanelModal/ViewPanelModalHeader',+ () =>+ function MockViewPanelModalHeader(): ReactElement {+ return <div data-testid="view-panel-header" />;+ },+);++function makePanel(+ name: string,+ extras: Record<string, unknown>,+): DashboardtypesPanelDTO {+ return {+ kind: 'Panel',+ spec: {+ display: { name },+ plugin: { kind: 'signoz/TimeSeriesPanel', spec: {} },+ queries: [+ {+ kind: 'time_series',+ spec: {+ plugin: {+ kind: 'signoz/BuilderQuery',+ spec: {+ name: 'A',+ signal: 'logs',+ disabled: false,+ filter: { expression: "service = 'x'" },+ aggregations: [{ expression: 'count()' }],+ ...extras,+ },+ },+ },+ },+ ],+ },+ } as unknown as DashboardtypesPanelDTO;+}++const PANELS: Record<string, DashboardtypesPanelDTO> = {+ plain: makePanel('Plain panel', {}),+ grouped: makePanel('Grouped panel', {+ groupBy: [{ name: 'host.name', fieldDataType: 'string' }],+ having: { expression: 'count() > 5' },+ }),+};++function Harness(): JSX.Element {+ const { expandedPanelId, openView, closeView } = useViewPanel();+ return (+ <>+ <button+ type="button"+ data-testid="open-plain"+ onClick={(): void => openView('plain', PANELS.plain)}+ >+ open plain+ </button>+ <button+ type="button"+ data-testid="open-grouped"+ onClick={(): void => openView('grouped', PANELS.grouped)}+ >+ open grouped+ </button>+ <button type="button" data-testid="close" onClick={closeView}>+ close+ </button>+ <ViewPanelModal+ open={!!expandedPanelId}+ panel={expandedPanelId ? PANELS[expandedPanelId] : undefined}+ panelId={expandedPanelId ?? undefined}+ onClose={closeView}+ />+ </>+ );+}++const renderHarness = (): void => {+ render(+ <MemoryRouter initialEntries={['/dashboard/dash-1']}>+ <CompatRouter>+ <QueryClientProvider client={new QueryClient()}>+ <ReduxProvider store={configureStore([])(appStore.getState())}>+ <TooltipProvider>+ <QueryBuilderProvider>+ <Harness />+ </QueryBuilderProvider>+ </TooltipProvider>+ </ReduxProvider>+ </QueryClientProvider>+ </CompatRouter>+ </MemoryRouter>,+ );+};++// QueryAddOns picks which rows are visible once on mount and never re-seeds, so unlike+// the field values these never recover from a context swap that lands after mount.+describe('View modal, builder add-on rows', () => {+ it('shows the opened panel add-ons, not the previous panel ones', async () => {+ const user = userEvent.setup({ pointerEventsCheck: 0, delay: null });+ renderHarness();++ await user.click(screen.getByTestId('open-grouped'));+ expect(screen.getByTestId('group-by-content')).toBeInTheDocument();+ expect(screen.getByTestId('having-content')).toBeInTheDocument();++ await user.click(screen.getByTestId('close'));+ await user.click(screen.getByTestId('open-plain'));+ expect(screen.queryByTestId('group-by-content')).not.toBeInTheDocument();+ expect(screen.queryByTestId('having-content')).not.toBeInTheDocument();+ });++ it('shows add-ons the opened panel has after a panel without them', async () => {+ const user = userEvent.setup({ pointerEventsCheck: 0, delay: null });+ renderHarness();++ await user.click(screen.getByTestId('open-plain'));+ await user.click(screen.getByTestId('close'));+ await user.click(screen.getByTestId('open-grouped'));++ expect(screen.getByTestId('group-by-content')).toBeInTheDocument();+ expect(screen.getByTestId('having-content')).toBeInTheDocument();+ });+});diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.promql.test.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.promql.test.tsxnew file mode 100644index 0000000000..99b115019d--- /dev/null+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.promql.test.tsx@@ -0,0 +1,187 @@+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import type { ReactElement } from 'react';+import { QueryClient, QueryClientProvider } from 'react-query';+// eslint-disable-next-line no-restricted-imports+import { Provider as ReduxProvider } from 'react-redux';+import { MemoryRouter } from 'react-router-dom';+import { CompatRouter } from 'react-router-dom-v5-compat';+import { TooltipProvider } from '@signozhq/ui/tooltip';+import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';+import { QueryBuilderProvider } from 'providers/QueryBuilder';+import configureStore from 'redux-mock-store';+import appStore from 'store';++import ViewPanelModal from '../ViewPanelModal/ViewPanelModal';+import { useViewPanel } from '../hooks/useViewPanel';++// jest.config maps the real hook to a no-op mock; this suite needs real navigation.+jest.mock('hooks/useSafeNavigate', () => {+ const { useHistory } = jest.requireActual('react-router-dom');+ return {+ useSafeNavigate: (): unknown => {+ const history = useHistory();+ return {+ safeNavigate: (to: string, opts?: { replace?: boolean }): void => {+ if (opts?.replace) {+ history.replace(to);+ } else {+ history.push(to);+ }+ },+ };+ },+ };+});++jest.mock(+ 'pages/DashboardPageV2/DashboardContainer/hooks/usePanelQuery',+ () => ({+ usePanelQuery: (): unknown => ({+ data: undefined,+ isFetching: false,+ isPreviousData: false,+ error: null,+ refetch: jest.fn(),+ cancelQuery: jest.fn(),+ pagination: undefined,+ }),+ }),+);++jest.mock(+ 'pages/DashboardPageV2/DashboardContainer/store/useDashboardStore',+ () => ({+ useDashboardStore: (selector: (s: unknown) => unknown): unknown =>+ selector({ dashboardId: 'dash-1' }),+ }),+);++jest.mock(+ 'pages/DashboardPageV2/DashboardContainer/PanelEditor/PreviewPane/PreviewPane',+ () =>+ function MockPreviewPane(): ReactElement {+ return <div data-testid="preview-pane" />;+ },+);++jest.mock('../hooks/useDrilldown', () => ({+ useDrilldown: (): unknown => ({+ enableDrillDown: false,+ onPanelClick: jest.fn(),+ contextMenuProps: {+ coordinates: null,+ popoverPosition: null,+ items: null,+ onClose: jest.fn(),+ },+ }),+}));++jest.mock('../hooks/usePanelInteractions', () => ({+ usePanelInteractions: (): unknown => ({+ onDragSelect: jest.fn(),+ dashboardPreference: { syncMode: 0 },+ }),+}));++jest.mock(+ '../ViewPanelModal/ViewPanelModalHeader',+ () =>+ function MockViewPanelModalHeader(): ReactElement {+ return <div data-testid="view-panel-header" />;+ },+);++function makePromPanel(name: string, promql: string): DashboardtypesPanelDTO {+ return {+ kind: 'Panel',+ spec: {+ display: { name },+ plugin: { kind: 'signoz/TimeSeriesPanel', spec: {} },+ queries: [+ {+ kind: 'time_series',+ spec: {+ plugin: {+ kind: 'signoz/PromQLQuery',+ spec: { name: 'A', query: promql, legend: '', disabled: false },+ },+ },+ },+ ],+ },+ } as unknown as DashboardtypesPanelDTO;+}++const PANELS: Record<string, DashboardtypesPanelDTO> = {+ A: makePromPanel('Panel A', 'up{job="alpha"}'),+ B: makePromPanel('Panel B', 'up{job="bravo"}'),+};++function Harness(): JSX.Element {+ const { expandedPanelId, openView, closeView } = useViewPanel();+ return (+ <>+ <button+ type="button"+ data-testid="open-a"+ onClick={(): void => openView('A', PANELS.A)}+ >+ open A+ </button>+ <button+ type="button"+ data-testid="open-b"+ onClick={(): void => openView('B', PANELS.B)}+ >+ open B+ </button>+ <button type="button" data-testid="close" onClick={closeView}>+ close+ </button>+ <ViewPanelModal+ open={!!expandedPanelId}+ panel={expandedPanelId ? PANELS[expandedPanelId] : undefined}+ panelId={expandedPanelId ?? undefined}+ onClose={closeView}+ />+ </>+ );+}++const renderHarness = (): void => {+ render(+ <MemoryRouter initialEntries={['/dashboard/dash-1']}>+ <CompatRouter>+ <QueryClientProvider client={new QueryClient()}>+ <ReduxProvider store={configureStore([])(appStore.getState())}>+ <TooltipProvider>+ <QueryBuilderProvider>+ <Harness />+ </QueryBuilderProvider>+ </TooltipProvider>+ </ReduxProvider>+ </QueryClientProvider>+ </CompatRouter>+ </MemoryRouter>,+ );+};++describe('View modal, PromQL panels', () => {+ it('shows the opened panel query, not the previously viewed one', async () => {+ const user = userEvent.setup({ pointerEventsCheck: 0, delay: null });+ renderHarness();++ await user.click(screen.getByTestId('open-a'));+ expect(screen.getByTestId('promql-query-input')).toHaveValue(+ 'up{job="alpha"}',+ );++ await user.click(screen.getByTestId('close'));+ await user.click(screen.getByTestId('open-b'));+ expect(screen.getByTestId('promql-query-input')).toHaveValue(+ 'up{job="bravo"}',+ );+ });+});diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.test.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.test.tsxnew file mode 100644index 0000000000..cc1eb4448a--- /dev/null+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.test.tsx@@ -0,0 +1,285 @@+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter, useLocation } from 'react-router-dom';+import { CompatRouter } from 'react-router-dom-v5-compat';+import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';+import { QueryParams } from 'constants/query';+import { PANEL_TYPES } from 'constants/queryBuilder';+import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';+import { fromPerses } from 'pages/DashboardPageV2/DashboardContainer/queryV5/persesQueryAdapters';+import { QueryBuilderProvider } from 'providers/QueryBuilder';+import type { Query } from 'types/api/queryBuilder/queryBuilderData';++import { useViewPanelMode } from '../ViewPanelModal/useViewPanelMode';+import { useViewPanel } from '../hooks/useViewPanel';++// jest.config maps the real hook to a no-op mock; this suite needs real navigation.+jest.mock('hooks/useSafeNavigate', () => {+ const { useHistory } = jest.requireActual('react-router-dom');+ return {+ useSafeNavigate: (): unknown => {+ const history = useHistory();+ return {+ safeNavigate: (to: string, opts?: { replace?: boolean }): void => {+ if (opts?.replace) {+ history.replace(to);+ } else {+ history.push(to);+ }+ },+ };+ },+ };+});++jest.mock(+ 'pages/DashboardPageV2/DashboardContainer/hooks/usePanelQuery',+ () => ({+ usePanelQuery: (): unknown => ({+ data: undefined,+ isFetching: false,+ isPreviousData: false,+ error: null,+ refetch: jest.fn(),+ cancelQuery: jest.fn(),+ pagination: undefined,+ }),+ }),+);++jest.mock(+ 'pages/DashboardPageV2/DashboardContainer/store/useDashboardStore',+ () => ({+ useDashboardStore: (selector: (s: unknown) => unknown): unknown =>+ selector({ dashboardId: 'dash-1' }),+ }),+);++function makePanel(name: string, expression: string): DashboardtypesPanelDTO {+ return {+ kind: 'Panel',+ spec: {+ display: { name },+ plugin: { kind: 'signoz/TimeSeriesPanel', spec: {} },+ queries: [+ {+ kind: 'time_series',+ spec: {+ plugin: {+ kind: 'signoz/BuilderQuery',+ spec: {+ name: 'A',+ signal: 'logs',+ disabled: false,+ filter: { expression },+ aggregations: [{ expression: 'count()' }],+ },+ },+ },+ },+ ],+ },+ } as unknown as DashboardtypesPanelDTO;+}++const PANELS: Record<string, DashboardtypesPanelDTO> = {+ A: makePanel('Panel A', "service = 'alpha'"),+ B: makePanel('Panel B', "service = 'bravo'"),+};++const panelOf = (json: string): string => {+ if (json.includes('alpha')) {+ return 'A';+ }+ if (json.includes('bravo')) {+ return 'B';+ }+ return 'none';+};++/** Every render of the open modal, so a single stale frame can't hide. */+const renders: { current: string; draft: string; filterItems: number }[] = [];++const stagedIds: (string | undefined)[] = [];++function ModalBody({ panelId }: { panelId: string }): JSX.Element {+ const { currentQuery } = useQueryBuilder();+ const { draft } = useViewPanelMode({+ panel: PANELS[panelId],+ panelId,+ time: { startMs: 0, endMs: 1000 },+ });+ renders.push({+ current: panelOf(JSON.stringify(currentQuery)),+ draft: panelOf(JSON.stringify(draft.spec.queries)),+ filterItems: currentQuery.builder.queryData[0]?.filters?.items.length ?? 0,+ });+ return <div data-testid="modal-body" />;+}++function SearchProbe(): JSX.Element {+ return <div data-testid="search">{useLocation().search}</div>;+}++function StagedQueryProbe(): null {+ const { stagedQuery } = useQueryBuilder();+ if (stagedIds.at(-1) !== stagedQuery?.id) {+ stagedIds.push(stagedQuery?.id);+ }+ return null;+}++const drilldownQuery = (base: Query): Query => ({+ ...base,+ builder: {+ ...base.builder,+ queryData: base.builder.queryData.map((q) => ({+ ...q,+ filter: { expression: "service = 'bravo' AND host = 'h1'" },+ })),+ },+});++function Harness(): JSX.Element {+ const { expandedPanelId, openView, openViewWithQuery, closeView } =+ useViewPanel();+ return (+ <>+ <button+ type="button"+ data-testid="open-a"+ onClick={(): void => openView('A', PANELS.A)}+ >+ open A+ </button>+ <button+ type="button"+ data-testid="open-b"+ onClick={(): void => openView('B', PANELS.B)}+ >+ open B+ </button>+ <button+ type="button"+ data-testid="drilldown-b"+ onClick={(): void =>+ openViewWithQuery(+ 'B',+ drilldownQuery(+ fromPerses(PANELS.B.spec.queries, PANEL_TYPES.TIME_SERIES),+ ),+ PANEL_TYPES.TIME_SERIES,+ )+ }+ >+ drilldown B+ </button>+ <button type="button" data-testid="close" onClick={closeView}>+ close+ </button>+ <StagedQueryProbe />+ <SearchProbe />+ {expandedPanelId && <ModalBody panelId={expandedPanelId} />}+ </>+ );+}++const renderHarness = (): void => {+ render(+ <MemoryRouter initialEntries={['/dashboard/dash-1']}>+ <CompatRouter>+ <QueryBuilderProvider>+ <Harness />+ </QueryBuilderProvider>+ </CompatRouter>+ </MemoryRouter>,+ );+};++describe('useViewPanel', () => {+ beforeEach(() => {+ renders.length = 0;+ stagedIds.length = 0;+ });++ // The builder context is global and outlives the modal; its fields seed themselves+ // on mount, so a late swap leaves them on the previously-viewed panel.+ it('seeds the builder with the opened panel before the modal renders', async () => {+ const user = userEvent.setup({ pointerEventsCheck: 0 });+ renderHarness();++ await user.click(screen.getByTestId('open-a'));+ await user.click(screen.getByTestId('close'));++ renders.length = 0;+ await user.click(screen.getByTestId('open-b'));++ expect(renders.length).toBeGreaterThan(0);+ expect(renders.every((r) => r.current === 'B')).toBe(true);+ });++ it("carries the opened panel's query in the URL", async () => {+ const user = userEvent.setup({ pointerEventsCheck: 0 });+ renderHarness();++ await user.click(screen.getByTestId('open-b'));++ const search = new URLSearchParams(+ screen.getByTestId('search').textContent ?? '',+ );+ expect(search.get(QueryParams.expandedWidgetId)).toBe('B');+ const carried = search.get(QueryParams.compositeQuery);+ expect(panelOf(decodeURIComponent(carried as string))).toBe('B');+ expect(search.get(QueryParams.graphType)).toBeNull();+ });++ // The edit session commits any staged query on mount, so a staged query left over+ // from the previous panel would make this panel's preview fetch the old query.+ it('never lets the previous panel query reach the new panel draft', async () => {+ const user = userEvent.setup({ pointerEventsCheck: 0 });+ renderHarness();++ await user.click(screen.getByTestId('open-a'));+ await user.click(screen.getByTestId('close'));++ renders.length = 0;+ await user.click(screen.getByTestId('open-b'));++ expect(renders.every((r) => r.draft === 'B')).toBe(true);+ });++ // The drilldown URL carries the query's own id, so a staged query with that id makes+ // the provider skip hydration — losing the normalisation that fills `filters.items`.+ it('still lets the provider hydrate a drilldown query from the URL', async () => {+ const user = userEvent.setup({ pointerEventsCheck: 0 });+ renderHarness();++ await user.click(screen.getByTestId('open-a'));+ await user.click(screen.getByTestId('close'));++ renders.length = 0;+ await user.click(screen.getByTestId('drilldown-b'));++ expect(renders.every((r) => r.current === 'B')).toBe(true);+ expect(renders.at(-1)?.filterItems).toBeGreaterThan(0);+ });++ // `useSyncTimeOnStagedQueryChange` (dashboard toolbar) re-anchors global time when one+ // non-null staged id replaces another, refetching every panel behind the modal.+ it.each([['open-b'], ['drilldown-b']])(+ 'never swaps one staged query for another (%s)',+ async (trigger) => {+ const user = userEvent.setup({ pointerEventsCheck: 0 });+ renderHarness();++ await user.click(screen.getByTestId('open-a'));+ await user.click(screen.getByTestId('close'));+ await user.click(screen.getByTestId(trigger));++ const swapsWithoutNull = stagedIds.some(+ (id, i) => i > 0 && id !== undefined && stagedIds[i - 1] !== undefined,+ );+ expect(swapsWithoutNull).toBe(false);+ },+ );+});diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/useViewPanel.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/useViewPanel.tsindex 0160bea12b..61bc3e0992 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/useViewPanel.ts+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/useViewPanel.ts@@ -1,11 +1,14 @@import { useCallback } from 'react';import { useLocation } from 'react-router-dom';import logEvent from 'api/common/logEvent';+import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';import { QueryParams } from 'constants/query';import type { PANEL_TYPES } from 'constants/queryBuilder';+import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';import { useSafeNavigate } from 'hooks/useSafeNavigate';import useUrlQuery from 'hooks/useUrlQuery';import { DashboardDetailEvents } from 'pages/DashboardPageV2/constants/events';+import { getPanelBuilderQuery } from 'pages/DashboardPageV2/DashboardContainer/Panels/utils/getPanelBuilderQuery';import type { Query } from 'types/api/queryBuilder/queryBuilderData';import { clearViewPanelHandoff } from '../ViewPanelModal/viewPanelHandoffStore';@@ -13,8 +16,8 @@ import { clearViewPanelHandoff } from '../ViewPanelModal/viewPanelHandoffStore';export interface UseViewPanelApi {/** Panel id currently expanded in the View modal; null when none is open. */expandedPanelId: string | null;- /** Open the View modal on the saved panel (clears any leftover in-modal query/kind). */- openView: (panelId: string) => void;+ /** Open the View modal on the saved panel, its query carried in `compositeQuery`. */+ openView: (panelId: string, panel: DashboardtypesPanelDTO) => void;/*** Open the View modal pre-seeded with a drilldown query + kind, persisted in the URL so it* survives refresh (V1 parity); the modal hydrates its draft from these on mount.@@ -30,30 +33,38 @@ export interface UseViewPanelApi {/*** Drives the panel View modal off the URL (V1 parity): `expandedWidgetId` holds the open- * panel, and a drilldown additionally seeds `compositeQuery` + `graphType`. URL-backed state- * is shareable, survives refresh, and the browser back-button closes it.+ * panel and `compositeQuery` the query it opens on, which a drilldown retargets along with+ * `graphType`. URL-backed state is shareable, survives refresh, and browser Back closes it.*/export function useViewPanel(): UseViewPanelApi {const { safeNavigate } = useSafeNavigate();const { pathname } = useLocation();const urlQuery = useUrlQuery();+ const { resetQuery } = useQueryBuilder();const expandedPanelId = urlQuery.get(QueryParams.expandedWidgetId);const openView = useCallback(- (panelId: string): void => {+ (panelId: string, panel: DashboardtypesPanelDTO): void => {// Copy before mutating: useUrlQuery returns a memoized instance.const next = new URLSearchParams(urlQuery);next.set(QueryParams.expandedWidgetId, panelId);- // Drop leftover in-modal query/kind + the editor's handoff so a plain View opens- // on the saved panel, not stale state the modal would otherwise hydrate from.- next.delete(QueryParams.compositeQuery);+ // Only a drilldown retargets the panel type.next.delete(QueryParams.graphType);clearViewPanelHandoff();+ const query = getPanelBuilderQuery(panel);+ next.set(+ QueryParams.compositeQuery,+ encodeURIComponent(JSON.stringify(query)),+ );+ // The provider applies the URL in an effect, a tick after the builder's fields have+ // mounted and read the query they keep. `resetQuery` — not `initQueryBuilderData`:+ // swapping one staged id for another re-anchors global time and refetches the grid.+ resetQuery(query);void logEvent(DashboardDetailEvents.PanelViewed, { panelId });safeNavigate(`${pathname}?${next.toString()}`);},- [pathname, safeNavigate, urlQuery],+ [pathname, safeNavigate, urlQuery, resetQuery],);const openViewWithQuery = useCallback(@@ -63,6 +74,10 @@ export function useViewPanel(): UseViewPanelApi {next.set(QueryParams.graphType, panelType);// A grid drilldown opens on the saved panel, never a stale editor handoff.clearViewPanelHandoff();+ // As in `openView`. Clearing the staged query matters twice over here: the URL+ // below carries this query's own id, and a staged query with a matching id+ // makes the provider skip the hydration that normalises legacy filter fields.+ resetQuery(query);// Same encoding the query builder uses (see `useGetCompositeQueryParam`): the URL// value is `encodeURIComponent(JSON.stringify(query))`, decoded once on read.next.set(@@ -71,7 +86,7 @@ export function useViewPanel(): UseViewPanelApi {);safeNavigate(`${pathname}?${next.toString()}`);},- [pathname, safeNavigate, urlQuery],+ [pathname, safeNavigate, urlQuery, resetQuery],);const closeView = useCallback((): void => {diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/__tests__/useOpenPanelEditor.test.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/__tests__/useOpenPanelEditor.test.tsxindex abbc527d19..5641527dec 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/__tests__/useOpenPanelEditor.test.tsx+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/__tests__/useOpenPanelEditor.test.tsx@@ -1,5 +1,7 @@import { renderHook } from '@testing-library/react';+import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';import { NANO_SECOND_MULTIPLIER } from 'store/globalTime';+import { EQueryType } from 'types/common/dashboard';import { useOpenPanelEditor } from '../useOpenPanelEditor';@@ -81,6 +83,37 @@ describe('useOpenPanelEditor', () => {);});+ it("carries the panel's saved query into the editor URL", () => {+ mockGlobalTime = { selectedTime: '6h', minTime: 0, maxTime: 0 };+ const panel = {+ kind: 'Panel',+ spec: {+ display: { name: 'Panel A' },+ plugin: { kind: 'signoz/TimeSeriesPanel', spec: {} },+ queries: [+ {+ kind: 'time_series',+ spec: {+ plugin: {+ kind: 'signoz/PromQLQuery',+ spec: { name: 'A', query: 'up{job="alpha"}', disabled: false },+ },+ },+ },+ ],+ },+ } as unknown as DashboardtypesPanelDTO;++ const { result } = renderHook(() => useOpenPanelEditor());+ result.current('panel-9', { panel });++ const [url] = mockSafeNavigate.mock.calls[0];+ const carried = new URLSearchParams(url.split('?')[1]).get('compositeQuery');+ const parsed = JSON.parse(decodeURIComponent(carried as string));+ expect(parsed.queryType).toBe(EQueryType.PROM);+ expect(parsed.promql[0].query).toBe('up{job="alpha"}');+ });+it('merges search with the time window (leading ? tolerated)', () => {mockGlobalTime = { selectedTime: '6h', minTime: 0, maxTime: 0 };const { result } = renderHook(() => useOpenPanelEditor());diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useOpenPanelEditor.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useOpenPanelEditor.tsindex faebe60e7d..33e7a186a0 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useOpenPanelEditor.ts+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useOpenPanelEditor.ts@@ -1,9 +1,13 @@import { useCallback } from 'react';import { generatePath } from 'react-router-dom';+import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';+import { QueryParams } from 'constants/query';import ROUTES from 'constants/routes';+import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';import { useSafeNavigate } from 'hooks/useSafeNavigate';import type { PanelEditorHandoffState } from '../PanelEditor/panelEditorHandoff';+import { getPanelBuilderQuery } from '../Panels/utils/getPanelBuilderQuery';import { useDashboardStore } from '../store/useDashboardStore';import { useTimeSearchParams } from './useTimeSearchParams';import logEvent from '@/api/common/logEvent';@@ -13,6 +17,8 @@ interface OpenPanelEditorOptions {handoffState?: PanelEditorHandoffState;/** Extra query merged into the editor URL (leading `?` optional). */search?: string;+ /** The panel being edited — its query rides in the URL as `compositeQuery`. */+ panel?: DashboardtypesPanelDTO;}/** Opens the V2 panel editor, carrying the active time window in the URL. */@@ -23,6 +29,7 @@ export function useOpenPanelEditor(): (const { safeNavigate } = useSafeNavigate();const timeSearch = useTimeSearchParams();const dashboardId = useDashboardStore((s) => s.dashboardId);+ const { resetQuery } = useQueryBuilder();return useCallback((panelId: string, options?: OpenPanelEditorOptions): void => {@@ -39,12 +46,24 @@ export function useOpenPanelEditor(): (new URLSearchParams(timeSearch).forEach((value, key) => {params.set(key, value);});+ if (options?.panel) {+ const query = getPanelBuilderQuery(options.panel);+ // Single-encoded: `useGetCompositeQueryParam` decodes once on top of the decode+ // `URLSearchParams` already does.+ params.set(+ QueryParams.compositeQuery,+ encodeURIComponent(JSON.stringify(query)),+ );+ // The provider applies the URL in an effect, a tick after the builder's fields+ // have mounted and read the query they keep (PromQL inputs, add-on rows).+ resetQuery(query);+ }const search = params.toString();safeNavigate(search ? `${path}?${search}` : path,options?.handoffState ? { state: options.handoffState } : undefined,);},- [safeNavigate, dashboardId, timeSearch],+ [safeNavigate, dashboardId, timeSearch, resetQuery],);}