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
feat(dashboard-v2): export panels & dashboards from explorers (#12043)
Abhi kumar0655328fa940
diff --git a/frontend/src/container/ExplorerOptions/ExplorerOptions.tsx b/frontend/src/container/ExplorerOptions/ExplorerOptions.tsxindex 5a540217e1..4d548a8209 100644--- a/frontend/src/container/ExplorerOptions/ExplorerOptions.tsx+++ b/frontend/src/container/ExplorerOptions/ExplorerOptions.tsx@@ -53,6 +53,7 @@ import {defaultTraceSelectedColumns,} from 'container/OptionsMenu/constants';import { OptionsQuery } from 'container/OptionsMenu/types';+import { ExportDashboard } from 'hooks/dashboard/useExportDashboards';import { useGetSearchQueryParam } from 'hooks/queryBuilder/useGetSearchQueryParam';import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';import { useGetAllViews } from 'hooks/saveViews/useGetAllViews';@@ -66,7 +67,6 @@ import { mapCompositeQueryFromQuery } from 'lib/newQueryBuilder/queryBuilderMappimport { cloneDeep, isEqual, omit } from 'lodash-es';import { useAppContext } from 'providers/App/App';import { FormattingOptions } from 'providers/preferences/types';-import { Dashboard } from 'types/api/dashboard/getAll';import { Query } from 'types/api/queryBuilder/queryBuilderData';import { ViewProps } from 'types/api/saveViews/types';import { DataSource, StringOperators } from 'types/common/queryBuilder';@@ -1031,26 +1031,19 @@ function ExplorerOptions({/></div></Modal>- <Modal- footer={null}- onOk={onCancel(false)}- onCancel={onCancel(false)}+ <ExportPanelContaineropen={isExport}- centered- destroyOnClose- >- <ExportPanelContainer- query={isOneChartPerQuery ? queryToExport : query}- isLoading={isLoading}- onExport={(dashboard, isNewDashboard): void => {- if (isOneChartPerQuery && queryToExport) {- onExport(dashboard, isNewDashboard, queryToExport);- } else {- onExport(dashboard, isNewDashboard);- }- }}- />- </Modal>+ onClose={onCancel(false)}+ query={isOneChartPerQuery ? queryToExport : query}+ isLoading={isLoading}+ onExport={(dashboard, isNewDashboard): void => {+ if (isOneChartPerQuery && queryToExport) {+ onExport(dashboard, isNewDashboard, queryToExport);+ } else {+ onExport(dashboard, isNewDashboard);+ }+ }}+ /></div>);}@@ -1058,7 +1051,7 @@ function ExplorerOptions({export interface ExplorerOptionsProps {isLoading?: boolean;onExport: (- dashboard: Dashboard | null,+ dashboard: ExportDashboard | null,isNewDashboard?: boolean,queryToExport?: Query,) => void;diff --git a/frontend/src/container/ExplorerOptions/__tests__/ExplorerOptionWrapper.test.tsx b/frontend/src/container/ExplorerOptions/__tests__/ExplorerOptionWrapper.test.tsxindex f9792819f5..b5c473036b 100644--- a/frontend/src/container/ExplorerOptions/__tests__/ExplorerOptionWrapper.test.tsx+++ b/frontend/src/container/ExplorerOptions/__tests__/ExplorerOptionWrapper.test.tsx@@ -1,6 +1,7 @@import { useHistory } from 'react-router-dom';import { PANEL_TYPES } from 'constants/queryBuilder';import { MOCK_QUERY } from 'container/QueryTable/Drilldown/__tests__/mockTableData';+import { ExportDashboard } from 'hooks/dashboard/useExportDashboards';import { useUpdateDashboard } from 'hooks/dashboard/useUpdateDashboard';import { rest, server } from 'mocks-server/server';import { render, screen, userEvent, waitFor } from 'tests/test-utils';@@ -80,7 +81,7 @@ const renderExplorerOptionWrapper = (isLoading: false,onExport: jest.fn() as jest.MockedFunction<(- dashboard: Dashboard | null,+ dashboard: ExportDashboard | null,isNewDashboard?: boolean,queryToExport?: Query,) => void@@ -150,7 +151,7 @@ describe('ExplorerOptionWrapper', () => {const user = userEvent.setup({ pointerEventsCheck: 0 });const testOnExport = jest.fn() as jest.MockedFunction<(- dashboard: Dashboard | null,+ dashboard: ExportDashboard | null,isNewDashboard?: boolean,queryToExport?: Query,) => void@@ -179,15 +180,16 @@ describe('ExplorerOptionWrapper', () => {expect(screen.getByRole('dialog')).toBeInTheDocument();});- // Click the "New Dashboard" button- const newDashboardButton = screen.getByRole('button', {- name: /new dashboard/i,- });+ // Click the "New dashboard" button+ const newDashboardButton = screen.getByTestId('export-panel-new-dashboard');await user.click(newDashboardButton);// Wait for the API call to complete and onExport to be calledawait waitFor(() => {- expect(testOnExport).toHaveBeenCalledWith(mockNewDashboard, true);+ expect(testOnExport).toHaveBeenCalledWith(+ { id: NEW_DASHBOARD_ID, title: TEST_DASHBOARD_TITLE },+ true,+ );});});@@ -195,7 +197,7 @@ describe('ExplorerOptionWrapper', () => {const user = userEvent.setup({ pointerEventsCheck: 0 });const testOnExport = jest.fn() as jest.MockedFunction<(- dashboard: Dashboard | null,+ dashboard: ExportDashboard | null,isNewDashboard?: boolean,queryToExport?: Query,) => void@@ -229,13 +231,12 @@ describe('ExplorerOptionWrapper', () => {expect(screen.getByRole('dialog')).toBeInTheDocument();});- // Wait for dashboards to load and then click on the dashboard select dropdown+ // Wait for the dashboard select dropdown to render inside the dialog+ const modal = screen.getByRole('dialog');await waitFor(() => {- expect(screen.getByText('Select Dashboard')).toBeInTheDocument();+ expect(modal.querySelector('[role="combobox"]')).toBeTruthy();});- // Get the modal and find the dashboard select dropdown within it- const modal = screen.getByRole('dialog');const dashboardSelect = modal.querySelector('[role="combobox"]',) as HTMLElement;@@ -251,19 +252,21 @@ describe('ExplorerOptionWrapper', () => {const dashboardOption = screen.getByText(mockDashboard1.data.title);await user.click(dashboardOption);- // Wait for the selection to be made and the Export button to be enabled+ // Wait for the selection to be made and the export button to be enabledawait waitFor(() => {- const exportButton = screen.getByRole('button', { name: /export/i });- expect(exportButton).not.toBeDisabled();+ expect(screen.getByTestId('export-panel-export')).not.toBeDisabled();});- // Click the Export button- const exportButton = screen.getByRole('button', { name: /export/i });+ // Click the export button+ const exportButton = screen.getByTestId('export-panel-export');await user.click(exportButton);// Wait for onExport to be called with the selected dashboardawait waitFor(() => {- expect(testOnExport).toHaveBeenCalledWith(mockDashboard1, false);+ expect(testOnExport).toHaveBeenCalledWith(+ { id: 'dashboard-1', title: 'Dashboard 1' },+ false,+ );});});@@ -284,7 +287,7 @@ describe('ExplorerOptionWrapper', () => {// Create a real handleExport function similar to LogsExplorerViews// This should NOT call useUpdateDashboard (as per PR #8029)- const handleExport = (dashboard: Dashboard | null): void => {+ const handleExport = (dashboard: ExportDashboard | null): void => {if (!dashboard) {return;}@@ -326,13 +329,12 @@ describe('ExplorerOptionWrapper', () => {expect(screen.getByRole('dialog')).toBeInTheDocument();});- // Wait for dashboards to load and then click on the dashboard select dropdown+ // Wait for the dashboard select dropdown to render inside the dialog+ const modal = screen.getByRole('dialog');await waitFor(() => {- expect(screen.getByText('Select Dashboard')).toBeInTheDocument();+ expect(modal.querySelector('[role="combobox"]')).toBeTruthy();});- // Get the modal and find the dashboard select dropdown within it- const modal = screen.getByRole('dialog');const dashboardSelect = modal.querySelector('[role="combobox"]',) as HTMLElement;@@ -348,14 +350,13 @@ describe('ExplorerOptionWrapper', () => {const dashboardOption = screen.getByText(mockDashboard.data.title);await user.click(dashboardOption);- // Wait for the selection to be made and the Export button to be enabled+ // Wait for the selection to be made and the export button to be enabledawait waitFor(() => {- const exportButton = screen.getByRole('button', { name: /export/i });- expect(exportButton).not.toBeDisabled();+ expect(screen.getByTestId('export-panel-export')).not.toBeDisabled();});- // Click the Export button- const exportButton = screen.getByRole('button', { name: /export/i });+ // Click the export button+ const exportButton = screen.getByTestId('export-panel-export');await user.click(exportButton);// Wait for the handleExport function to be called and navigation to occur@@ -375,7 +376,7 @@ describe('ExplorerOptionWrapper', () => {it('should not show export buttons when component is disabled', () => {const testOnExport = jest.fn() as jest.MockedFunction<(- dashboard: Dashboard | null,+ dashboard: ExportDashboard | null,isNewDashboard?: boolean,queryToExport?: Query,) => voiddiff --git a/frontend/src/container/ExportPanel/ExportDashboardSelect.tsx b/frontend/src/container/ExportPanel/ExportDashboardSelect.tsxnew file mode 100644index 0000000000..f9ca14c58d--- /dev/null+++ b/frontend/src/container/ExportPanel/ExportDashboardSelect.tsx@@ -0,0 +1,74 @@+import { useMemo } from 'react';+// eslint-disable-next-line signoz/no-antd-components+import { Select, SelectProps } from 'antd';+import { ExportDashboard } from 'hooks/dashboard/useExportDashboards';++import { getSelectOptions } from './utils';+import styles from './ExportPanel.module.scss';++interface ExportDashboardSelectProps {+ dashboards: ExportDashboard[];+ value: string | null;+ /** The picked dashboard, pinned as an option so its label survives a later search. */+ selectedDashboard: ExportDashboard | null;+ loading?: boolean;+ disabled?: boolean;+ onChange: (dashboardId: string) => void;+ onSearch: (search: string) => void;+}++/**+ * Dashboard picker for the "Add to dashboard" dialog. Server-side search (`filterOption`+ * off, typing via `onSearch`); the selected dashboard is pinned as an option so its label+ * survives a narrowing search, and `getPopupContainer` keeps the overlay from clipping the+ * dropdown.+ */+function ExportDashboardSelect({+ dashboards,+ value,+ selectedDashboard,+ loading,+ disabled,+ onChange,+ onSearch,+}: ExportDashboardSelectProps): JSX.Element {+ const options = useMemo<SelectProps['options']>(() => {+ const base = getSelectOptions(dashboards) ?? [];+ if (+ selectedDashboard &&+ !base.some((option) => option.value === selectedDashboard.id)+ ) {+ return [+ { label: selectedDashboard.title, value: selectedDashboard.id },+ ...base,+ ];+ }+ return base;+ }, [dashboards, selectedDashboard]);++ return (+ <Select+ className={styles.dashboardSelect}+ placeholder="Select a dashboard"+ showSearch+ filterOption={false}+ loading={loading}+ disabled={disabled}+ value={value}+ onChange={onChange}+ onSearch={onSearch}+ data-testid="export-dashboard-select"+ options={options}+ getPopupContainer={(trigger): HTMLElement =>+ trigger.parentElement ?? document.body+ }+ />+ );+}++ExportDashboardSelect.defaultProps = {+ loading: false,+ disabled: false,+};++export default ExportDashboardSelect;diff --git a/frontend/src/container/ExportPanel/ExportPanel.module.scss b/frontend/src/container/ExportPanel/ExportPanel.module.scssnew file mode 100644index 0000000000..dc12df6e22--- /dev/null+++ b/frontend/src/container/ExportPanel/ExportPanel.module.scss@@ -0,0 +1,42 @@+.body {+ display: flex;+ flex-direction: column;+ gap: 20px;+}++.field {+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.label {+ font-size: 12px;+ color: var(--l2-foreground);+}++.dashboardSelect {+ width: 100%;+}++.newDashboard {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding-top: 16px;+ border-top: 1px solid var(--l2-border);+}++.hint {+ font-size: 13px;+ color: var(--l2-foreground);+}++.footer {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: 8px;+ width: 100%;+}diff --git a/frontend/src/container/ExportPanel/ExportPanelContainer.tsx b/frontend/src/container/ExportPanel/ExportPanelContainer.tsxindex 4cf4805058..2d86b6a5a0 100644--- a/frontend/src/container/ExportPanel/ExportPanelContainer.tsx+++ b/frontend/src/container/ExportPanel/ExportPanelContainer.tsx@@ -1,127 +1,159 @@-import { useCallback, useMemo, useState } from 'react';+import { useCallback, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useMutation } from 'react-query';-import { Button } from 'antd';+import { Plus } from '@signozhq/icons';+import { Button } from '@signozhq/ui/button';+import { DialogWrapper } from '@signozhq/ui/dialog';import { Typography } from '@signozhq/ui/typography';-import createDashboard from 'api/v1/dashboards/create';-import { ENTITY_VERSION_V5 } from 'constants/app';-import { useGetAllDashboard } from 'hooks/dashboard/useGetAllDashboard';-import { useErrorModal } from 'providers/ErrorModalProvider';-import APIError from 'types/api/error';--import { ExportPanelProps } from '.';+import { useCreateExportDashboard } from 'hooks/dashboard/useCreateExportDashboard';import {- DashboardSelect,- NewDashboardButton,- SelectWrapper,- Title,- Wrapper,-} from './styles';-import { filterOptions, getSelectOptions } from './utils';+ ExportDashboard,+ useExportDashboards,+} from 'hooks/dashboard/useExportDashboards';+import { Query } from 'types/api/queryBuilder/queryBuilderData';++import ExportDashboardSelect from './ExportDashboardSelect';+import styles from './ExportPanel.module.scss';++export interface ExportPanelProps {+ isLoading?: boolean;+ onExport: (+ dashboard: ExportDashboard | null,+ isNewDashboard?: boolean,+ ) => void;+ query: Query | null;+ /** Controlled open state of the dialog. */+ open: boolean;+ /** Called when the dialog requests to close (Cancel / overlay / Esc). */+ onClose: () => void;+}+/**+ * "Add to dashboard" dialog: export the panel into an existing dashboard or a newly+ * created one. Navigation is the caller's job via `onExport` (flag-aware V1/V2 editor).+ */function ExportPanelContainer({isLoading,onExport,+ open,+ onClose,}: ExportPanelProps): JSX.Element {const { t } = useTranslation(['dashboard']);- const [dashboardId, setDashboardId] = useState<string | null>(null);+ // Track the object, not just the id, so export survives a search that narrows it out.+ const [selectedDashboard, setSelectedDashboard] =+ useState<ExportDashboard | null>(null);+ const [searchText, setSearchText] = useState('');const {- data,+ dashboards,isLoading: isAllDashboardsLoading,- refetch,- } = useGetAllDashboard();+ isFetching: isDashboardsFetching,+ } = useExportDashboards(searchText);- const { showErrorModal } = useErrorModal();-- const { mutate: createNewDashboard, isLoading: createDashboardLoading } =- useMutation(createDashboard, {- onSuccess: (data) => {- if (data.data) {- onExport(data?.data, true);- }- refetch();- },- onError: (error) => {- showErrorModal(error as APIError);- },+ const { create: createNewDashboard, isLoading: createDashboardLoading } =+ useCreateExportDashboard({+ title: t('new_dashboard_title', { ns: 'dashboard' }),+ onCreated: (dashboard) => onExport(dashboard, true),});- const options = useMemo(() => getSelectOptions(data?.data || []), [data]);-- const handleExportClick = useCallback((): void => {- const currentSelectedDashboard = data?.data?.find(- ({ id }) => id === dashboardId,- );-- onExport(currentSelectedDashboard || null, false);- }, [data, dashboardId, onExport]);+ // Reset on close so each open starts fresh (the dialog stays mounted).+ useEffect(() => {+ if (!open) {+ setSelectedDashboard(null);+ setSearchText('');+ }+ }, [open]);const handleSelect = useCallback(- (selectedDashboardId: string): void => {- setDashboardId(selectedDashboardId);+ (dashboardId: string): void => {+ setSelectedDashboard(+ dashboards.find(({ id }) => id === dashboardId) ?? null,+ );},- [setDashboardId],+ [dashboards],);- const handleNewDashboard = useCallback(async () => {- try {- await createNewDashboard({- title: t('new_dashboard_title', {- ns: 'dashboard',- }),- uploadedGrafana: false,- version: ENTITY_VERSION_V5,- });- } catch (error) {- showErrorModal(error as APIError);- }- }, [createNewDashboard, t, showErrorModal]);-- const isDashboardLoading = isAllDashboardsLoading || createDashboardLoading;+ const handleExportClick = useCallback((): void => {+ onExport(selectedDashboard, false);+ }, [selectedDashboard, onExport]);- const isDisabled =- isAllDashboardsLoading || !options?.length || !dashboardId || isLoading;+ const isExportDisabled =+ isAllDashboardsLoading || !selectedDashboard || isLoading;return (- <Wrapper direction="vertical">- <Title>Export Panel</Title>-- <SelectWrapper direction="horizontal">- <DashboardSelect- placeholder="Select Dashboard"- options={options}- showSearch- loading={isDashboardLoading}- disabled={isDashboardLoading}- value={dashboardId}- onSelect={handleSelect}- filterOption={filterOptions}- />- <Button- type="primary"- loading={isLoading}- disabled={isDisabled}- onClick={handleExportClick}- >- Export- </Button>- </SelectWrapper>-- <Typography>- Or create dashboard with this panel -- <NewDashboardButton- disabled={createDashboardLoading}- loading={createDashboardLoading}- type="link"- onClick={handleNewDashboard}- >- New Dashboard- </NewDashboardButton>- </Typography>- </Wrapper>+ <DialogWrapper+ open={open}+ onOpenChange={(isOpen): void => {+ if (!isOpen) {+ onClose();+ }+ }}+ title="Add to dashboard"+ testId="export-panel-dialog"+ footer={+ <div className={styles.footer}>+ <Button+ variant="outlined"+ color="secondary"+ size="md"+ onClick={onClose}+ testId="export-panel-cancel"+ >+ Cancel+ </Button>+ <Button+ color="primary"+ size="md"+ loading={isLoading}+ disabled={isExportDisabled}+ onClick={handleExportClick}+ testId="export-panel-export"+ >+ Add to dashboard+ </Button>+ </div>+ }+ >+ <div className={styles.body}>+ <div className={styles.field}>+ <Typography.Text className={styles.label}>+ Select a dashboard+ </Typography.Text>+ <ExportDashboardSelect+ dashboards={dashboards}+ value={selectedDashboard?.id ?? null}+ selectedDashboard={selectedDashboard}+ loading={isDashboardsFetching}+ disabled={isAllDashboardsLoading || createDashboardLoading}+ onChange={handleSelect}+ onSearch={setSearchText}+ />+ </div>++ <div className={styles.newDashboard}>+ <Typography.Text className={styles.hint}>+ Or create a new dashboard with this panel+ </Typography.Text>+ <Button+ variant="outlined"+ color="secondary"+ size="md"+ prefix={<Plus size={14} />}+ loading={createDashboardLoading}+ disabled={createDashboardLoading}+ onClick={createNewDashboard}+ testId="export-panel-new-dashboard"+ >+ New dashboard+ </Button>+ </div>+ </div>+ </DialogWrapper>);}+ExportPanelContainer.defaultProps = {+ isLoading: false,+};+export default ExportPanelContainer;diff --git a/frontend/src/container/ExportPanel/index.tsx b/frontend/src/container/ExportPanel/index.tsxdeleted file mode 100644index 82fbe9fed3..0000000000--- a/frontend/src/container/ExportPanel/index.tsx+++ /dev/null@@ -1,49 +0,0 @@-import { useCallback, useState } from 'react';-import { Modal } from 'antd';-import { Dashboard } from 'types/api/dashboard/getAll';-import { Query } from 'types/api/queryBuilder/queryBuilderData';--import ExportPanelContainer from './ExportPanelContainer';--function ExportPanel({- isLoading,- onExport,- query,-}: ExportPanelProps): JSX.Element {- const [isExport, setIsExport] = useState<boolean>(false);-- const onModalToggle = useCallback((value: boolean) => {- setIsExport(value);- }, []);-- const onCancel = (value: boolean) => (): void => {- onModalToggle(value);- };-- return (- <Modal- footer={null}- onOk={onCancel(false)}- onCancel={onCancel(false)}- open={isExport}- centered- destroyOnClose- >- <ExportPanelContainer- query={query}- isLoading={isLoading}- onExport={onExport}- />- </Modal>- );-}--export interface ExportPanelProps {- isLoading?: boolean;- onExport: (dashboard: Dashboard | null, isNewDashboard?: boolean) => void;- query: Query | null;-}--ExportPanel.defaultProps = { isLoading: false };--export default ExportPanel;diff --git a/frontend/src/container/ExportPanel/styles.ts b/frontend/src/container/ExportPanel/styles.tsdeleted file mode 100644index 4935515aab..0000000000--- a/frontend/src/container/ExportPanel/styles.ts+++ /dev/null@@ -1,34 +0,0 @@-import { FunctionComponent } from 'react';-import { Button, Select, SelectProps, Space } from 'antd';-import { Typography } from '@signozhq/ui/typography';-import styled from 'styled-components';--export const DashboardSelect: FunctionComponent<SelectProps> = styled(- Select,-)<SelectProps>`- width: 100%;-`;--export const SelectWrapper = styled(Space)`- width: 100%;- margin-bottom: 1rem;-- .ant-space-item:first-child {- width: 100%;- max-width: 20rem;- }-`;--export const Wrapper = styled(Space)`- width: 100%;-`;--export const NewDashboardButton = styled(Button)`- &&& {- padding: 0 0.125rem;- }-`;--export const Title = styled(Typography.Text)`- font-size: 1rem;-`;diff --git a/frontend/src/container/ExportPanel/utils.ts b/frontend/src/container/ExportPanel/utils.tsindex 7f3a45d753..251ff33aa6 100644--- a/frontend/src/container/ExportPanel/utils.ts+++ b/frontend/src/container/ExportPanel/utils.ts@@ -1,16 +1,10 @@import { SelectProps } from 'antd';-import { Dashboard } from 'types/api/dashboard/getAll';+import { ExportDashboard } from 'hooks/dashboard/useExportDashboards';-export const getSelectOptions = (data: Dashboard[]): SelectProps['options'] =>- data.map(({ id, data }) => ({- label: data.title,+export const getSelectOptions = (+ data: ExportDashboard[],+): SelectProps['options'] =>+ data.map(({ id, title }) => ({+ label: title,value: id,}));--export const filterOptions: SelectProps['filterOption'] = (- input,- options,-): boolean =>- (options?.label?.toString() ?? '')- ?.toLowerCase()- .includes(input.toLowerCase());diff --git a/frontend/src/container/LogsExplorerViews/index.tsx b/frontend/src/container/LogsExplorerViews/index.tsxindex 427bd72c98..bc9bbeb117 100644--- a/frontend/src/container/LogsExplorerViews/index.tsx+++ b/frontend/src/container/LogsExplorerViews/index.tsx@@ -33,6 +33,8 @@ import {getQueryByPanelType,} from 'container/LogsExplorerViews/explorerUtils';import TimeSeriesView from 'container/TimeSeriesView/TimeSeriesView';+import { ExportDashboard } from 'hooks/dashboard/useExportDashboards';+import { useGetExportToDashboardLink } from 'hooks/dashboard/useGetExportToDashboardLink';import { useCopyLogLink } from 'hooks/logs/useCopyLogLink';import { useGetExplorerQueryRange } from 'hooks/queryBuilder/useGetExplorerQueryRange';import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';@@ -43,7 +45,6 @@ import { isEmpty, isUndefined } from 'lodash-es';import LiveLogs from 'pages/LiveLogs';import { AppState } from 'store/reducers';import { Warning } from 'types/api';-import { Dashboard } from 'types/api/dashboard/getAll';import APIError from 'types/api/error';import { ILog } from 'types/api/logs/log';import { Query, TagFilter } from 'types/api/queryBuilder/queryBuilderData';@@ -51,7 +52,6 @@ import { Filter } from 'types/api/v5/queryRange';import { QueryDataV3 } from 'types/api/widgets/getQuery';import { DataSource } from 'types/common/queryBuilder';import { GlobalReducer } from 'types/reducer/globalTime';-import { generateExportToDashboardLink } from 'utils/dashboard/generateExportToDashboardLink';import { v4 } from 'uuid';import LogsActionsContainer from './LogsActionsContainer';@@ -75,6 +75,7 @@ function LogsExplorerViewsContainer({handleChangeSelectedView: ChangeViewFunctionType;}): JSX.Element {const { safeNavigate } = useSafeNavigate();+ const getExportToDashboardLink = useGetExportToDashboardLink();const [showFrequencyChart, setShowFrequencyChart] = useState(() => getFromLocalstorage(LOCALSTORAGE.SHOW_FREQUENCY_CHART) === 'true',@@ -262,7 +263,7 @@ function LogsExplorerViewsContainer({}, [data?.payload]);const handleExport = useCallback(- (dashboard: Dashboard | null, isNewDashboard?: boolean): void => {+ (dashboard: ExportDashboard | null, isNewDashboard?: boolean): void => {if (!dashboard || !selectedPanelType) {return;}@@ -282,19 +283,26 @@ function LogsExplorerViewsContainer({logEvent('Logs Explorer: Add to dashboard successful', {panelType: selectedPanelType,isNewDashboard,- dashboardName: dashboard?.data?.title,+ dashboardName: dashboard?.title,});- const dashboardEditView = generateExportToDashboardLink({+ const dashboardEditView = getExportToDashboardLink({query: exportDefaultQuery,panelType: panelTypeParam,dashboardId: dashboard.id,widgetId,});- safeNavigate(dashboardEditView);+ if (dashboardEditView) {+ safeNavigate(dashboardEditView);+ }},- [safeNavigate, exportDefaultQuery, selectedPanelType],+ [+ safeNavigate,+ exportDefaultQuery,+ selectedPanelType,+ getExportToDashboardLink,+ ],);useEffect(() => {diff --git a/frontend/src/container/MeterExplorer/Explorer/Explorer.tsx b/frontend/src/container/MeterExplorer/Explorer/Explorer.tsxindex e2a5f75e0c..1b6382ba73 100644--- a/frontend/src/container/MeterExplorer/Explorer/Explorer.tsx+++ b/frontend/src/container/MeterExplorer/Explorer/Explorer.tsx@@ -13,12 +13,12 @@ import ExplorerOptionWrapper from 'container/ExplorerOptions/ExplorerOptionWrappimport RightToolbarActions from 'container/QueryBuilder/components/ToolbarActions/RightToolbarActions';import { QueryBuilderProps } from 'container/QueryBuilder/QueryBuilder.interfaces';import DateTimeSelector from 'container/TopNav/DateTimeSelectionV2';+import { ExportDashboard } from 'hooks/dashboard/useExportDashboards';import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';import { useSafeNavigate } from 'hooks/useSafeNavigate';import { Filter } from '@signozhq/icons';import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';-import { Dashboard } from 'types/api/dashboard/getAll';import { Query } from 'types/api/queryBuilder/queryBuilderData';import { DataSource } from 'types/common/queryBuilder';import { generateExportToDashboardLink } from 'utils/dashboard/generateExportToDashboardLink';@@ -81,7 +81,7 @@ function Explorer(): JSX.Element {const handleExport = useCallback((- dashboard: Dashboard | null,+ dashboard: ExportDashboard | null,_isNewDashboard?: boolean,queryToExport?: Query,): void => {diff --git a/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx b/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsxindex 66f298eeba..5f8b7d17f3 100644--- a/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx+++ b/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx@@ -14,6 +14,8 @@ import ExplorerOptionWrapper from 'container/ExplorerOptions/ExplorerOptionWrappimport RightToolbarActions from 'container/QueryBuilder/components/ToolbarActions/RightToolbarActions';import { QueryBuilderProps } from 'container/QueryBuilder/QueryBuilder.interfaces';import DateTimeSelector from 'container/TopNav/DateTimeSelectionV2';+import { ExportDashboard } from 'hooks/dashboard/useExportDashboards';+import { useGetExportToDashboardLink } from 'hooks/dashboard/useGetExportToDashboardLink';import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';import {@@ -31,11 +33,9 @@ import {} from 'pages/MetricsExplorer/aiActions';import { ExplorerViews } from 'pages/LogsExplorer/utils';import { Warning } from 'types/api';-import { Dashboard } from 'types/api/dashboard/getAll';import { Query } from 'types/api/queryBuilder/queryBuilderData';import { MetricAggregation } from 'types/api/v5/queryRange';import { DataSource } from 'types/common/queryBuilder';-import { generateExportToDashboardLink } from 'utils/dashboard/generateExportToDashboardLink';import { explorerViewToPanelType } from 'utils/explorerUtils';import { v4 as uuid } from 'uuid';@@ -63,6 +63,7 @@ function Explorer(): JSX.Element {redirectWithQueryBuilderData,} = useQueryBuilder();const { safeNavigate } = useSafeNavigate();+ const getExportToDashboardLink = useGetExportToDashboardLink();const { handleExplorerTabChange } = useHandleExplorerTabChange();const isAIAssistantEnabled = useIsAIAssistantEnabled();const [isMetricDetailsOpen, setIsMetricDetailsOpen] = useState(false);@@ -260,7 +261,7 @@ function Explorer(): JSX.Element {const handleExport = useCallback((- dashboard: Dashboard | null,+ dashboard: ExportDashboard | null,_isNewDashboard?: boolean,queryToExport?: Query,): void => {@@ -278,16 +279,18 @@ function Explorer(): JSX.Element {};}- const dashboardEditView = generateExportToDashboardLink({+ const dashboardEditView = getExportToDashboardLink({query,panelType: PANEL_TYPES.TIME_SERIES,dashboardId: dashboard.id,widgetId,});- safeNavigate(dashboardEditView);+ if (dashboardEditView) {+ safeNavigate(dashboardEditView);+ }},- [exportDefaultQuery, safeNavigate, yAxisUnit],+ [exportDefaultQuery, safeNavigate, yAxisUnit, getExportToDashboardLink],);const splitedQueries = useMemo(diff --git a/frontend/src/hooks/dashboard/__test__/useCreateExportDashboard.test.tsx b/frontend/src/hooks/dashboard/__test__/useCreateExportDashboard.test.tsxnew file mode 100644index 0000000000..ba30965bbf--- /dev/null+++ b/frontend/src/hooks/dashboard/__test__/useCreateExportDashboard.test.tsx@@ -0,0 +1,93 @@+import { ReactNode } from 'react';+import { QueryClient, QueryClientProvider } from 'react-query';+import { act, renderHook, waitFor } from '@testing-library/react';+import { createDashboardV2 } from 'api/generated/services/dashboard';+import createDashboardV1 from 'api/v1/dashboards/create';+import { ENTITY_VERSION_V5 } from 'constants/app';+import { useIsDashboardV2 } from 'hooks/useIsDashboardV2';+import { Dashboard } from 'types/api/dashboard/getAll';++import { useCreateExportDashboard } from '../useCreateExportDashboard';++jest.mock('hooks/useIsDashboardV2');+jest.mock('api/v1/dashboards/create');+jest.mock('api/generated/services/dashboard', () => ({+ createDashboardV2: jest.fn(),+}));+jest.mock('providers/ErrorModalProvider', () => ({+ useErrorModal: (): { showErrorModal: jest.Mock } => ({+ showErrorModal: jest.fn(),+ }),+}));++const mockUseIsDashboardV2 = useIsDashboardV2 as jest.MockedFunction<+ typeof useIsDashboardV2+>;+const mockCreateV1 = createDashboardV1 as jest.Mock;+const mockCreateV2 = createDashboardV2 as jest.Mock;++function wrapper({ children }: { children: ReactNode }): JSX.Element {+ const client = new QueryClient({+ defaultOptions: { mutations: { retry: false } },+ });+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>;+}++const TITLE = 'My dashboard';++beforeEach(() => {+ jest.clearAllMocks();+});++describe('useCreateExportDashboard', () => {+ it('creates via the V1 endpoint and returns the created dashboard when the flag is off', async () => {+ mockUseIsDashboardV2.mockReturnValue(false);+ const v1Dashboard = {+ id: 'v1-new',+ data: { title: TITLE },+ } as unknown as Dashboard;+ mockCreateV1.mockResolvedValue({ httpStatusCode: 200, data: v1Dashboard });+ const onCreated = jest.fn();++ const { result } = renderHook(+ () => useCreateExportDashboard({ title: TITLE, onCreated }),+ { wrapper },+ );++ act(() => result.current.create());++ await waitFor(() =>+ expect(onCreated).toHaveBeenCalledWith({ id: 'v1-new', title: TITLE }),+ );+ expect(mockCreateV1).toHaveBeenCalledWith({+ title: TITLE,+ uploadedGrafana: false,+ version: ENTITY_VERSION_V5,+ });+ expect(mockCreateV2).not.toHaveBeenCalled();+ });++ it('creates via the V2 Perses endpoint and normalizes the response when the flag is on', async () => {+ mockUseIsDashboardV2.mockReturnValue(true);+ mockCreateV2.mockResolvedValue({ data: { id: 'v2-new' } });+ const onCreated = jest.fn();++ const { result } = renderHook(+ () => useCreateExportDashboard({ title: TITLE, onCreated }),+ { wrapper },+ );++ act(() => result.current.create());++ await waitFor(() =>+ expect(onCreated).toHaveBeenCalledWith({ id: 'v2-new', title: TITLE }),+ );+ expect(mockCreateV2).toHaveBeenCalledWith(+ expect.objectContaining({+ schemaVersion: 'v6',+ spec: expect.objectContaining({ display: { name: TITLE } }),+ }),+ );+ expect(mockCreateV1).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/hooks/dashboard/__test__/useExportDashboards.test.ts b/frontend/src/hooks/dashboard/__test__/useExportDashboards.test.tsnew file mode 100644index 0000000000..d92c6d258d--- /dev/null+++ b/frontend/src/hooks/dashboard/__test__/useExportDashboards.test.ts@@ -0,0 +1,125 @@+import { renderHook } from '@testing-library/react';+import { useListDashboardsForUserV2 } from 'api/generated/services/dashboard';+import { useGetAllDashboard } from 'hooks/dashboard/useGetAllDashboard';+import { useIsDashboardV2 } from 'hooks/useIsDashboardV2';+import { Dashboard } from 'types/api/dashboard/getAll';++import { useExportDashboards } from '../useExportDashboards';++jest.mock('hooks/useIsDashboardV2');+jest.mock('hooks/dashboard/useGetAllDashboard');+jest.mock('api/generated/services/dashboard', () => ({+ useListDashboardsForUserV2: jest.fn(),+}));++const mockUseIsDashboardV2 = useIsDashboardV2 as jest.MockedFunction<+ typeof useIsDashboardV2+>;+const mockUseGetAllDashboard = useGetAllDashboard as jest.Mock;+const mockUseListV2 = useListDashboardsForUserV2 as jest.Mock;++const v1Refetch = jest.fn();+const v2Refetch = jest.fn();++const v1Dashboard = {+ id: 'v1-1',+ data: { title: 'V1 Dashboard' },+} as unknown as Dashboard;++const v1Other = {+ id: 'v1-2',+ data: { title: 'Other board' },+} as unknown as Dashboard;++beforeEach(() => {+ jest.clearAllMocks();+ mockUseGetAllDashboard.mockReturnValue({+ data: { data: [v1Dashboard, v1Other] },+ isLoading: false,+ isFetching: false,+ refetch: v1Refetch,+ });+ mockUseListV2.mockReturnValue({+ data: {+ data: {+ dashboards: [+ {+ id: 'v2-1',+ name: 'V2 Dashboard',+ spec: { display: { name: 'V2 Dashboard' } },+ },+ ],+ },+ },+ isLoading: false,+ isFetching: false,+ refetch: v2Refetch,+ });+});++describe('useExportDashboards', () => {+ it('returns the V1 list and disables the V2 query when the flag is off', () => {+ mockUseIsDashboardV2.mockReturnValue(false);++ const { result } = renderHook(() => useExportDashboards());++ expect(result.current.dashboards).toStrictEqual([+ { id: 'v1-1', title: 'V1 Dashboard' },+ { id: 'v1-2', title: 'Other board' },+ ]);+ expect(mockUseGetAllDashboard).toHaveBeenCalledWith({ enabled: true });+ expect(mockUseListV2).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ query: { enabled: false, keepPreviousData: true },+ }),+ );+ });++ it('filters the V1 list in memory by title (case-insensitive)', () => {+ mockUseIsDashboardV2.mockReturnValue(false);++ const { result } = renderHook(() => useExportDashboards('v1 dash'));++ expect(result.current.dashboards).toStrictEqual([+ { id: 'v1-1', title: 'V1 Dashboard' },+ ]);+ });++ it('returns the V2 list normalized to the export shape when the flag is on', () => {+ mockUseIsDashboardV2.mockReturnValue(true);++ const { result } = renderHook(() => useExportDashboards());++ expect(result.current.dashboards).toStrictEqual([+ { id: 'v2-1', title: 'V2 Dashboard' },+ ]);+ expect(mockUseGetAllDashboard).toHaveBeenCalledWith({ enabled: false });+ expect(mockUseListV2).toHaveBeenCalledWith(+ expect.objectContaining({ query: undefined }),+ expect.objectContaining({+ query: { enabled: true, keepPreviousData: true },+ }),+ );+ });++ it('passes the search term as a name-contains filter clause to the V2 query param', () => {+ mockUseIsDashboardV2.mockReturnValue(true);++ renderHook(() => useExportDashboards('payments'));++ expect(mockUseListV2).toHaveBeenCalledWith(+ expect.objectContaining({ query: "name CONTAINS 'payments'" }),+ expect.anything(),+ );+ });++ it('refetches the active source', () => {+ mockUseIsDashboardV2.mockReturnValue(true);+ const { result } = renderHook(() => useExportDashboards());++ result.current.refetch();+ expect(v2Refetch).toHaveBeenCalledTimes(1);+ expect(v1Refetch).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/hooks/dashboard/__test__/useGetExportToDashboardLink.test.ts b/frontend/src/hooks/dashboard/__test__/useGetExportToDashboardLink.test.tsnew file mode 100644index 0000000000..b4bdcc0f3d--- /dev/null+++ b/frontend/src/hooks/dashboard/__test__/useGetExportToDashboardLink.test.ts@@ -0,0 +1,45 @@+import { renderHook } from '@testing-library/react';+import { PANEL_TYPES } from 'constants/queryBuilder';+import { useIsDashboardV2 } from 'hooks/useIsDashboardV2';+import type { Query } from 'types/api/queryBuilder/queryBuilderData';++import { useGetExportToDashboardLink } from '../useGetExportToDashboardLink';++jest.mock('hooks/useIsDashboardV2');+const mockUseIsDashboardV2 = useIsDashboardV2 as jest.MockedFunction<+ typeof useIsDashboardV2+>;++const query = { id: 'q1', queryType: 'builder' } as unknown as Query;+const params = {+ dashboardId: 'dash-1',+ panelType: PANEL_TYPES.TIME_SERIES,+ query,+ widgetId: 'w1',+};++describe('useGetExportToDashboardLink', () => {+ it('builds a V1 new-widget link when the dashboard-v2 flag is off', () => {+ mockUseIsDashboardV2.mockReturnValue(false);++ const { result } = renderHook(() => useGetExportToDashboardLink());+ const link = result.current(params);++ expect(link?.startsWith('/dashboard/dash-1/new?')).toBe(true);+ expect(link).toContain('graphType=');+ expect(link).toContain('widgetId=w1');+ expect(link).toContain('compositeQuery=');+ });++ it('builds a V2 panel/new link (ignoring widgetId) when the flag is on', () => {+ mockUseIsDashboardV2.mockReturnValue(true);++ const { result } = renderHook(() => useGetExportToDashboardLink());+ const link = result.current(params);++ expect(link?.startsWith('/dashboard/dash-1/panel/new?')).toBe(true);+ expect(link).toContain('panelKind=signoz%2FTimeSeriesPanel');+ expect(link).not.toContain('widgetId');+ expect(link).toContain('compositeQuery=');+ });+});diff --git a/frontend/src/hooks/dashboard/useCreateExportDashboard.ts b/frontend/src/hooks/dashboard/useCreateExportDashboard.tsnew file mode 100644index 0000000000..f135247889--- /dev/null+++ b/frontend/src/hooks/dashboard/useCreateExportDashboard.ts@@ -0,0 +1,80 @@+import { useCallback } from 'react';+import { useMutation } from 'react-query';+import { createDashboardV2 } from 'api/generated/services/dashboard';+import createDashboardV1 from 'api/v1/dashboards/create';+import { ENTITY_VERSION_V5 } from 'constants/app';+import { useIsDashboardV2 } from 'hooks/useIsDashboardV2';+import { useErrorModal } from 'providers/ErrorModalProvider';+import APIError from 'types/api/error';++import type { ExportDashboard } from './useExportDashboards';++interface UseCreateExportDashboardParams {+ title: string;+ onCreated: (dashboard: ExportDashboard) => void;+}++interface UseCreateExportDashboardResult {+ create: () => void;+ isLoading: boolean;+}++/**+ * Flag-aware "create a new dashboard to export into". V2 uses the Perses-spec+ * `createDashboardV2`; V1 uses the legacy create. Both normalize to an `ExportDashboard`.+ */+export function useCreateExportDashboard({+ title,+ onCreated,+}: UseCreateExportDashboardParams): UseCreateExportDashboardResult {+ const isDashboardV2 = useIsDashboardV2();+ const { showErrorModal } = useErrorModal();++ const onError = useCallback(+ (error: unknown): void => showErrorModal(error as APIError),+ [showErrorModal],+ );++ const v1 = useMutation(createDashboardV1, {+ onSuccess: (data) => {+ if (data.data) {+ onCreated({ id: data.data.id, title: data.data.data.title ?? '' });+ }+ },+ onError,+ });++ const v2 = useMutation(+ () =>+ createDashboardV2({+ schemaVersion: 'v6',+ generateName: true,+ tags: null,+ spec: {+ display: { name: title },+ layouts: [],+ panels: {},+ variables: [],+ },+ }),+ {+ onSuccess: (created) => {+ onCreated({ id: created.data.id, title });+ },+ onError,+ },+ );++ const create = useCallback((): void => {+ if (isDashboardV2) {+ v2.mutate();+ } else {+ v1.mutate({ title, uploadedGrafana: false, version: ENTITY_VERSION_V5 });+ }+ }, [isDashboardV2, v1, v2, title]);++ return {+ create,+ isLoading: isDashboardV2 ? v2.isLoading : v1.isLoading,+ };+}diff --git a/frontend/src/hooks/dashboard/useExportDashboards.ts b/frontend/src/hooks/dashboard/useExportDashboards.tsnew file mode 100644index 0000000000..813c99aeb3--- /dev/null+++ b/frontend/src/hooks/dashboard/useExportDashboards.ts@@ -0,0 +1,90 @@+import { useCallback, useMemo } from 'react';+import { useListDashboardsForUserV2 } from 'api/generated/services/dashboard';+import { DashboardtypesListedDashboardForUserV2DTO } from 'api/generated/services/sigNoz.schemas';+import { useGetAllDashboard } from 'hooks/dashboard/useGetAllDashboard';+import useDebounce from 'hooks/useDebounce';+import { useIsDashboardV2 } from 'hooks/useIsDashboardV2';+import { Dashboard } from 'types/api/dashboard/getAll';++const V2_LIST_LIMIT = 1000;+const SEARCH_DEBOUNCE_MS = 300;++/** Neutral id+title the picker uses in place of the V1/V2 dashboard entity. */+export interface ExportDashboard {+ id: string;+ title: string;+}++export interface UseExportDashboardsResult {+ dashboards: ExportDashboard[];+ /** First load only — disables the picker until there are options. */+ isLoading: boolean;+ /** Any fetch incl. a search refetch — drives the picker spinner. */+ isFetching: boolean;+ refetch: () => void;+}++function fromV2(+ item: DashboardtypesListedDashboardForUserV2DTO,+): ExportDashboard {+ return { id: item.id, title: item.spec.display?.name || item.name };+}++function fromV1(dashboard: Dashboard): ExportDashboard {+ return { id: dashboard.id, title: dashboard.data.title ?? '' };+}++function filterByTitle(+ dashboards: ExportDashboard[],+ search: string,+): ExportDashboard[] {+ const term = search.trim().toLowerCase();+ if (!term) {+ return dashboards;+ }+ return dashboards.filter((dashboard) =>+ dashboard.title.toLowerCase().includes(term),+ );+}++// The V2 list `query` is a filter DSL (`key OP value`), not free text — wrap a typed term+// as a name-contains clause (single quotes escaped).+function toNameQuery(search: string): string | undefined {+ const term = search.trim();+ return term ? `name CONTAINS '${term.replace(/'/g, "\\'")}'` : undefined;+}++/** Flag-aware picker source: V2 searches server-side (debounced), V1 filters in memory. */+export function useExportDashboards(search = ''): UseExportDashboardsResult {+ const isDashboardV2 = useIsDashboardV2();+ const debouncedSearch = useDebounce(search, SEARCH_DEBOUNCE_MS);++ const v1 = useGetAllDashboard({ enabled: !isDashboardV2 });+ const v2 = useListDashboardsForUserV2(+ { limit: V2_LIST_LIMIT, query: toNameQuery(debouncedSearch) },+ { query: { enabled: isDashboardV2, keepPreviousData: true } },+ );++ const dashboards = useMemo<ExportDashboard[]>(+ () =>+ isDashboardV2+ ? (v2.data?.data?.dashboards ?? []).map(fromV2)+ : filterByTitle((v1.data?.data ?? []).map(fromV1), search),+ [isDashboardV2, v1.data, v2.data, search],+ );++ const refetch = useCallback((): void => {+ if (isDashboardV2) {+ void v2.refetch();+ } else {+ void v1.refetch();+ }+ }, [isDashboardV2, v1, v2]);++ return {+ dashboards,+ isLoading: isDashboardV2 ? v2.isLoading : v1.isLoading,+ isFetching: isDashboardV2 ? v2.isFetching : v1.isFetching,+ refetch,+ };+}diff --git a/frontend/src/hooks/dashboard/useGetExportToDashboardLink.ts b/frontend/src/hooks/dashboard/useGetExportToDashboardLink.tsnew file mode 100644index 0000000000..0dfcd4ea80--- /dev/null+++ b/frontend/src/hooks/dashboard/useGetExportToDashboardLink.ts@@ -0,0 +1,37 @@+import { useCallback } from 'react';+import type { PANEL_TYPES } from 'constants/queryBuilder';+import { useIsDashboardV2 } from 'hooks/useIsDashboardV2';+import { buildExportPanelLink } from 'pages/DashboardPageV2/DashboardContainer/PanelEditor/newPanelRoute';+import type { Query } from 'types/api/queryBuilder/queryBuilderData';+import { generateExportToDashboardLink } from 'utils/dashboard/generateExportToDashboardLink';++interface ExportToDashboardLinkParams {+ dashboardId: string;+ panelType: PANEL_TYPES;+ query: Query;+ widgetId: string;+}++/**+ * Flag-aware "Add to Dashboard" link builder for the explorers. V2 targets the panel+ * editor; V1 uses the legacy new-widget link. `null` (V2 only) when the panel type has no+ * V2 kind, so callers skip navigation.+ */+export function useGetExportToDashboardLink(): (+ params: ExportToDashboardLinkParams,+) => string | null {+ const isDashboardV2 = useIsDashboardV2();++ return useCallback(+ ({ dashboardId, panelType, query, widgetId }: ExportToDashboardLinkParams) =>+ isDashboardV2+ ? buildExportPanelLink({ dashboardId, panelType, query })+ : generateExportToDashboardLink({+ query,+ panelType,+ dashboardId,+ widgetId,+ }),+ [isDashboardV2],+ );+}diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/PanelTypeSwitcher/utils.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/PanelTypeSwitcher/utils.tsindex 068bfa8f74..a004515844 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/PanelTypeSwitcher/utils.ts+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/PanelTypeSwitcher/utils.ts@@ -2,7 +2,7 @@ import { TelemetrytypesSignalDTO } from 'api/generated/services/sigNoz.schemas';import { EQueryType } from 'types/common/dashboard';import {- isQueryTypeSupported,+ isQueryTypeSupportedByPanelKind,isSignalSupported,} from '../../../Panels/capabilities';import type { PanelKind } from '../../../Panels/types/panelKind';@@ -36,7 +36,7 @@ export function getPanelTypeDisabledReason({signal?: TelemetrytypesSignalDTO;label: string;}): string | undefined {- if (!isQueryTypeSupported(kind, queryType)) {+ if (!isQueryTypeSupportedByPanelKind(kind, queryType)) {return `${label} isn't available for ${QUERY_TYPE_LABEL[queryType]} queries`;}if (signal !== undefined && !isSignalSupported(kind, signal)) {diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/__tests__/newPanelRoute.test.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/__tests__/newPanelRoute.test.tsindex e45460d84f..8801c467ea 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/__tests__/newPanelRoute.test.ts+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/__tests__/newPanelRoute.test.ts@@ -1,4 +1,8 @@+import { PANEL_TYPES } from 'constants/queryBuilder';+import type { Query } from 'types/api/queryBuilder/queryBuilderData';+import {+ buildExportPanelLink,NEW_PANEL_ID,newPanelSearch,parseNewPanelKind,@@ -31,4 +35,57 @@ describe('newPanelRoute', () => {parseNewPanelKind(NEW_PANEL_ID, '?panelKind=NotARealPanel'),).toBeNull();});++ describe('buildExportPanelLink', () => {+ const query = { id: 'q1', queryType: 'builder' } as unknown as Query;++ const parseLink = (+ link: string | null,+ ): { path: string; params: URLSearchParams } => {+ if (link === null) {+ throw new Error('expected a link, got null');+ }+ const [path, search] = link.split('?');+ return { path, params: new URLSearchParams(search) };+ };++ it.each([+ [PANEL_TYPES.TIME_SERIES, 'signoz/TimeSeriesPanel'],+ [PANEL_TYPES.TABLE, 'signoz/TablePanel'],+ [PANEL_TYPES.LIST, 'signoz/ListPanel'],+ ])('maps export panel type %s to kind %s', (panelType, expectedKind) => {+ const link = buildExportPanelLink({+ dashboardId: 'dash-1',+ panelType,+ query,+ });+ const { path, params } = parseLink(link);+ expect(path).toBe('/dashboard/dash-1/panel/new');+ expect(params.get('panelKind')).toBe(expectedKind);+ expect(parseNewPanelKind(NEW_PANEL_ID, `?${params.toString()}`)).toBe(+ expectedKind,+ );+ });++ it('carries the query as a decodable compositeQuery param', () => {+ const link = buildExportPanelLink({+ dashboardId: 'dash-1',+ panelType: PANEL_TYPES.TIME_SERIES,+ query,+ });+ const { params } = parseLink(link);+ expect(JSON.parse(params.get('compositeQuery') as string)).toStrictEqual(+ query,+ );+ });++ it('returns null for a panel type with no V2 kind', () => {+ const link = buildExportPanelLink({+ dashboardId: 'dash-1',+ panelType: PANEL_TYPES.EMPTY_WIDGET,+ query,+ });+ expect(link).toBeNull();+ });+ });});diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/index.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/index.tsxindex 99d1f7faf4..6b223b473a 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/index.tsx+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/index.tsx@@ -83,7 +83,6 @@ function PanelEditorContainer({setSpec,isSpecDirty,panelDefinition,- defaultSignal,query,runQuery,isQueryDirty,@@ -169,10 +168,11 @@ function PanelEditorContainer({onChangeSpec: setSpec,});- // Seed a new List panel's default columns so the Columns control isn't empty.+ // Seed a new List panel's columns from the query's resolved signal (not the kind's+ // default logs signal) so a traces-List export gets traces columns, not logs.useSeedNewListColumns({enabled: isNew && isListPanel,- signal: defaultSignal,+ signal: listSignal,spec,onChangeSpec: setSpec,});diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/newPanelRoute.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/newPanelRoute.tsindex 8fab050caa..219c015ed6 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/newPanelRoute.ts+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/newPanelRoute.ts@@ -1,11 +1,17 @@+import { generatePath } from 'react-router-dom';+import { QueryParams } from 'constants/query';+import type { PANEL_TYPES } from 'constants/queryBuilder';+import ROUTES from 'constants/routes';+import type { Query } from 'types/api/queryBuilder/queryBuilderData';+import {PANEL_KIND_TO_PANEL_TYPE,+ PANEL_TYPE_TO_PANEL_KIND,type PanelKind,} from '../Panels/types/panelKind';-// New (unsaved) panels share a fixed id segment, carrying kind + target section-// in the query: `/panel/new?panelKind=signoz/ListPanel&layoutIndex=2`. The real-// id is generated on save.+// New (unsaved) panels use a fixed id segment, carrying kind + target section in the+// query (`/panel/new?panelKind=…&layoutIndex=…`); the real id is generated on save.export const NEW_PANEL_ID = 'new';const PANEL_KIND_PARAM = 'panelKind';const LAYOUT_INDEX_PARAM = 'layoutIndex';@@ -37,6 +43,34 @@ export function parseNewPanelKind(return kind && kind in PANEL_KIND_TO_PANEL_TYPE ? (kind as PanelKind) : null;}+/**+ * New-panel editor link that exports an explorer query into a V2 dashboard. Carries the+ * raw `Query` as `compositeQuery` encoded as the V1 link so `useGetCompositeQueryParam`+ * reads it identically (conversion happens in the editor). `null` when the panel type has+ * no V2 kind, so the caller skips the export instead of landing on an unrelated kind.+ */+export function buildExportPanelLink({+ dashboardId,+ panelType,+ query,+}: {+ dashboardId: string;+ panelType: PANEL_TYPES;+ query: Query;+}): string | null {+ const kind = PANEL_TYPE_TO_PANEL_KIND[panelType];+ if (!kind) {+ return null;+ }+ const path = generatePath(ROUTES.DASHBOARD_PANEL_EDITOR, {+ dashboardId,+ panelId: NEW_PANEL_ID,+ });+ return `${path}${newPanelSearch(kind)}&${+ QueryParams.compositeQuery+ }=${encodeURIComponent(JSON.stringify(query))}`;+}+/** Target section index for a new panel, or undefined when unset/invalid. */export function parseNewPanelLayoutIndex(search: string): number | undefined {const raw = new URLSearchParams(search).get(LAYOUT_INDEX_PARAM);diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/__tests__/capabilities.test.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/__tests__/capabilities.test.tsindex 0888040224..93e0424c7c 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/__tests__/capabilities.test.ts+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/__tests__/capabilities.test.ts@@ -7,7 +7,7 @@ import {getSupportedQueryTypes,getSupportedSignals,isPanelCombinationValid,- isQueryTypeSupported,+ isQueryTypeSupportedByPanelKind,isSignalSupported,resolveQueryType,} from '../capabilities';@@ -48,14 +48,24 @@ describe('panel capabilities guard', () => {});it('Table and Pie do not support PromQL', () => {- expect(isQueryTypeSupported('signoz/TablePanel', PROM)).toBe(false);- expect(isQueryTypeSupported('signoz/PieChartPanel', PROM)).toBe(false);+ expect(isQueryTypeSupportedByPanelKind('signoz/TablePanel', PROM)).toBe(+ false,+ );+ expect(isQueryTypeSupportedByPanelKind('signoz/PieChartPanel', PROM)).toBe(+ false,+ );});it('List only supports Query Builder', () => {- expect(isQueryTypeSupported('signoz/ListPanel', QUERY_BUILDER)).toBe(true);- expect(isQueryTypeSupported('signoz/ListPanel', CLICKHOUSE)).toBe(false);- expect(isQueryTypeSupported('signoz/ListPanel', PROM)).toBe(false);+ expect(+ isQueryTypeSupportedByPanelKind('signoz/ListPanel', QUERY_BUILDER),+ ).toBe(true);+ expect(isQueryTypeSupportedByPanelKind('signoz/ListPanel', CLICKHOUSE)).toBe(+ false,+ );+ expect(isQueryTypeSupportedByPanelKind('signoz/ListPanel', PROM)).toBe(+ false,+ );});});diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/capabilities.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/capabilities.tsindex 32897ab395..fa7bd109a7 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/capabilities.ts+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/Panels/capabilities.ts@@ -32,7 +32,7 @@ export function getSupportedQueryTypes(kind: PanelKind): EQueryType[] {return getPanelDefinition(kind).supportedQueryTypes;}-export function isQueryTypeSupported(+export function isQueryTypeSupportedByPanelKind(kind: PanelKind,queryType: EQueryType,): boolean {@@ -53,7 +53,7 @@ export function isPanelCombinationValid({queryType: EQueryType;signal?: TelemetrytypesSignalDTO;}): boolean {- if (!isQueryTypeSupported(kind, queryType)) {+ if (!isQueryTypeSupportedByPanelKind(kind, queryType)) {return false;}if (signal !== undefined && !isSignalSupported(kind, signal)) {diff --git a/frontend/src/pages/DashboardPageV2/PanelEditorPage/PanelEditorPage.tsx b/frontend/src/pages/DashboardPageV2/PanelEditorPage/PanelEditorPage.tsxindex 5c4fee213d..f50768ecdf 100644--- a/frontend/src/pages/DashboardPageV2/PanelEditorPage/PanelEditorPage.tsx+++ b/frontend/src/pages/DashboardPageV2/PanelEditorPage/PanelEditorPage.tsx@@ -1,4 +1,4 @@-import { useCallback, useMemo } from 'react';+import { useCallback, useMemo, useRef } from 'react';import {generatePath,Redirect,@@ -8,14 +8,12 @@ import {import { Typography } from '@signozhq/ui/typography';import Spinner from 'components/Spinner';import ROUTES from 'constants/routes';+import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';import { useSafeNavigate } from 'hooks/useSafeNavigate';import { useDashboardFetch } from '../DashboardContainer/hooks/useDashboardFetch';import { useDashboardEditGuard } from '../DashboardContainer/hooks/useDashboardEditGuard';import { useResolvedVariables } from '../DashboardContainer/hooks/useResolvedVariables';-import { getPanelDefinition } from '../DashboardContainer/Panels/registry';-import { buildPluginSpec } from '../DashboardContainer/Panels/utils/buildPluginSpec';-import { buildDefaultQueries } from '../DashboardContainer/Panels/utils/buildDefaultQueries';import PanelEditorContainer from '../DashboardContainer/PanelEditor';import type { PanelEditorHandoffState } from '../DashboardContainer/PanelEditor/panelEditorHandoff';import {@@ -27,6 +25,7 @@ import { createDefaultPanel } from '../DashboardContainer/patchOps';import { useDashboardStore } from '../DashboardContainer/store/useDashboardStore';import { useSeedVariableSelection } from '../DashboardContainer/VariablesBar/useSeedVariableSelection';import { withVariablesSearch } from '../DashboardContainer/VariablesBar/variablesUrlState';+import { buildNewPanelSeed } from './newPanelSeed';import styles from './PanelEditorPage.module.scss';/**@@ -73,17 +72,28 @@ function PanelEditorPage(): JSX.Element {// Feed variables to the query builder autocomplete inside the editor.useSyncVariablesForSuggestions(dashboard);+ // An explorer "Add to Dashboard" export rides the query in `compositeQuery` (V1+ // parity). Captured once at mount: the editor rewrites `compositeQuery` in the URL+ // as the user edits, and re-reading it would churn the draft (its reset target and+ // dirty baseline live in the initially-loaded panel).+ const exportCompositeQuery = useGetCompositeQueryParam();+ const exportCompositeQueryRef = useRef(exportCompositeQuery);+// A `panel/new?panelKind=…` route means "create": seed a default panel of that- // kind rather than looking one up. Persisted (with a real id) only on save.+ // kind rather than looking one up (seeded from the exported query when present).+ // Persisted (with a real id) only on save.const newKind = parseNewPanelKind(panelId, search);const existingPanel = dashboard?.spec.panels[panelId];const panel = useMemo(() => {if (newKind) {- return createDefaultPanel(+ // A `compositeQuery` at mount means the explorer routed an export here.+ const isExplorerExport = !!exportCompositeQueryRef.current;+ const { kind, pluginSpec, queries } = buildNewPanelSeed(newKind,- buildPluginSpec(getPanelDefinition(newKind).sections),- buildDefaultQueries(newKind),+ exportCompositeQueryRef.current,+ isExplorerExport,);+ return createDefaultPanel(kind, pluginSpec, queries);}if (!existingPanel) {return undefined;diff --git a/frontend/src/pages/DashboardPageV2/PanelEditorPage/newPanelSeed.test.ts b/frontend/src/pages/DashboardPageV2/PanelEditorPage/newPanelSeed.test.tsnew file mode 100644index 0000000000..f13bf94573--- /dev/null+++ b/frontend/src/pages/DashboardPageV2/PanelEditorPage/newPanelSeed.test.ts@@ -0,0 +1,134 @@+import type { Query } from 'types/api/queryBuilder/queryBuilderData';+import { EQueryType } from 'types/common/dashboard';++import { isQueryTypeSupportedByPanelKind } from '../DashboardContainer/Panels/capabilities';+import { getPanelDefinition } from '../DashboardContainer/Panels/registry';+import { SectionKind } from '../DashboardContainer/Panels/types/sections';+import { buildDefaultQueries } from '../DashboardContainer/Panels/utils/buildDefaultQueries';+import { buildPluginSpec } from '../DashboardContainer/Panels/utils/buildPluginSpec';+import { toPerses } from '../DashboardContainer/queryV5/persesQueryAdapters';+import { buildNewPanelSeed } from './newPanelSeed';++jest.mock('../DashboardContainer/queryV5/persesQueryAdapters', () => ({+ toPerses: jest.fn(),+}));+jest.mock('../DashboardContainer/Panels/utils/buildDefaultQueries', () => ({+ buildDefaultQueries: jest.fn(),+}));+jest.mock('../DashboardContainer/Panels/utils/buildPluginSpec', () => ({+ buildPluginSpec: jest.fn(),+}));+jest.mock('../DashboardContainer/Panels/registry', () => ({+ getPanelDefinition: jest.fn(),+}));+jest.mock('../DashboardContainer/Panels/capabilities', () => ({+ isQueryTypeSupportedByPanelKind: jest.fn(),+}));++const mockToPerses = toPerses as jest.Mock;+const mockBuildDefaultQueries = buildDefaultQueries as jest.Mock;+const mockBuildPluginSpec = buildPluginSpec as jest.Mock;+const mockGetPanelDefinition = getPanelDefinition as jest.Mock;+const mockIsQueryTypeSupported = isQueryTypeSupportedByPanelKind as jest.Mock;++const DEFAULT_QUERIES = [{ kind: 'default' }];+const CONVERTED_QUERIES = [{ kind: 'converted' }];+const BASE_SPEC = { visualization: { foo: 1 } };++const withUnit = [{ kind: SectionKind.Formatting, controls: { unit: true } }];+const withoutUnit = [+ { kind: SectionKind.Formatting, controls: { decimals: true } },+];++const q = (extra: Partial<Query> = {}): Query =>+ ({ queryType: 'builder', ...extra }) as unknown as Query;++describe('buildNewPanelSeed', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockBuildDefaultQueries.mockReturnValue(DEFAULT_QUERIES);+ mockBuildPluginSpec.mockReturnValue(BASE_SPEC);+ mockGetPanelDefinition.mockReturnValue({ sections: withUnit });+ mockIsQueryTypeSupported.mockReturnValue(true);+ });++ it('uses the kind default seed when it is not an explorer export', () => {+ const seed = buildNewPanelSeed('signoz/TimeSeriesPanel', null);++ expect(seed.kind).toBe('signoz/TimeSeriesPanel');+ expect(seed.queries).toBe(DEFAULT_QUERIES);+ expect(seed.pluginSpec).toStrictEqual(BASE_SPEC);+ expect(mockToPerses).not.toHaveBeenCalled();+ });++ it('converts the exported query into perses queries', () => {+ mockToPerses.mockReturnValue(CONVERTED_QUERIES);++ const seed = buildNewPanelSeed('signoz/TimeSeriesPanel', q(), true);++ expect(seed.kind).toBe('signoz/TimeSeriesPanel');+ expect(seed.queries).toBe(CONVERTED_QUERIES);+ expect(seed.pluginSpec).toStrictEqual(BASE_SPEC);+ });++ it('coerces a builder-only kind to Table for a ClickHouse query', () => {+ mockIsQueryTypeSupported.mockReturnValue(false);+ mockToPerses.mockReturnValue(CONVERTED_QUERIES);++ const seed = buildNewPanelSeed(+ 'signoz/ListPanel',+ q({ queryType: EQueryType.CLICKHOUSE }),+ true,+ );++ expect(seed.kind).toBe('signoz/TablePanel');+ expect(seed.queries).toBe(CONVERTED_QUERIES);+ });++ it('coerces a builder-only kind to TimeSeries for a PromQL query', () => {+ mockIsQueryTypeSupported.mockReturnValue(false);+ mockToPerses.mockReturnValue(CONVERTED_QUERIES);++ const seed = buildNewPanelSeed(+ 'signoz/ListPanel',+ q({ queryType: EQueryType.PROM }),+ true,+ );++ expect(seed.kind).toBe('signoz/TimeSeriesPanel');+ expect(seed.queries).toBe(CONVERTED_QUERIES);+ });++ it('falls back to the default seed when conversion yields nothing runnable', () => {+ mockToPerses.mockReturnValue([]);++ const seed = buildNewPanelSeed('signoz/ListPanel', q(), true);++ expect(seed.queries).toBe(DEFAULT_QUERIES);+ });++ it('preserves the exported unit when the kind supports a unit', () => {+ mockToPerses.mockReturnValue(CONVERTED_QUERIES);+ mockGetPanelDefinition.mockReturnValue({ sections: withUnit });++ const seed = buildNewPanelSeed(+ 'signoz/TimeSeriesPanel',+ q({ unit: 'ms' }),+ true,+ );++ expect(seed.pluginSpec).toStrictEqual({+ ...BASE_SPEC,+ formatting: { unit: 'ms' },+ });+ });++ it('drops the unit for a kind without a unit control', () => {+ mockToPerses.mockReturnValue(CONVERTED_QUERIES);+ mockGetPanelDefinition.mockReturnValue({ sections: withoutUnit });++ const seed = buildNewPanelSeed('signoz/TablePanel', q({ unit: 'ms' }), true);++ expect(seed.pluginSpec).toStrictEqual(BASE_SPEC);+ });+});diff --git a/frontend/src/pages/DashboardPageV2/PanelEditorPage/newPanelSeed.ts b/frontend/src/pages/DashboardPageV2/PanelEditorPage/newPanelSeed.tsnew file mode 100644index 0000000000..6336473f56--- /dev/null+++ b/frontend/src/pages/DashboardPageV2/PanelEditorPage/newPanelSeed.ts@@ -0,0 +1,89 @@+import type { DashboardtypesQueryDTO } from 'api/generated/services/sigNoz.schemas';+import type { Query } from 'types/api/queryBuilder/queryBuilderData';+import { EQueryType } from 'types/common/dashboard';++import { isQueryTypeSupportedByPanelKind } from '../DashboardContainer/Panels/capabilities';+import { getPanelDefinition } from '../DashboardContainer/Panels/registry';+import { PANEL_KIND_TO_PANEL_TYPE } from '../DashboardContainer/Panels/types/panelKind';+import type { PanelKind } from '../DashboardContainer/Panels/types/panelKind';+import { SectionKind } from '../DashboardContainer/Panels/types/sections';+import { buildDefaultQueries } from '../DashboardContainer/Panels/utils/buildDefaultQueries';+import {+ buildPluginSpec,+ type SeededPluginSpec,+} from '../DashboardContainer/Panels/utils/buildPluginSpec';+import { toPerses } from '../DashboardContainer/queryV5/persesQueryAdapters';++interface NewPanelSeed {+ /** May differ from the requested kind — see `resolveSeededPanelKind`. */+ kind: PanelKind;+ queries: DashboardtypesQueryDTO[];+ pluginSpec: SeededPluginSpec;+}++function kindSupportsUnit(kind: PanelKind): boolean {+ return getPanelDefinition(kind).sections.some(+ (section) =>+ section.kind === SectionKind.Formatting &&+ 'controls' in section &&+ section.controls.unit === true,+ );+}++/** Kind to fall back to for a query language a builder-only kind (List) can't hold. */+const FALLBACK_KIND_BY_QUERY_TYPE: Partial<Record<EQueryType, PanelKind>> = {+ [EQueryType.PROM]: 'signoz/TimeSeriesPanel',+ [EQueryType.CLICKHOUSE]: 'signoz/TablePanel',+};++/** Keep the requested kind if it can hold the query; otherwise coerce so it isn't dropped. */+function resolveSeededPanelKind(+ requestedKind: PanelKind,+ compositeQuery: Query,+): PanelKind {+ if (isQueryTypeSupportedByPanelKind(requestedKind, compositeQuery.queryType)) {+ return requestedKind;+ }+ return (+ FALLBACK_KIND_BY_QUERY_TYPE[compositeQuery.queryType] ?? 'signoz/TablePanel'+ );+}++/**+ * A blank "Add panel" gets the requested kind's default seed; an explorer "Add to+ * Dashboard" export instead seeds from `compositeQuery` (converted to perses queries,+ * carrying the query's `unit`).+ */+export function buildNewPanelSeed(+ requestedKind: PanelKind,+ compositeQuery: Query | null,+ isExplorerExport = false,+): NewPanelSeed {+ if (!isExplorerExport || !compositeQuery) {+ return {+ kind: requestedKind,+ queries: buildDefaultQueries(requestedKind),+ pluginSpec: buildPluginSpec(getPanelDefinition(requestedKind).sections),+ };+ }++ const kind = resolveSeededPanelKind(requestedKind, compositeQuery);+ const pluginSpec = buildPluginSpec(getPanelDefinition(kind).sections);++ const converted = toPerses(compositeQuery, PANEL_KIND_TO_PANEL_TYPE[kind]);+ const queries = converted.length > 0 ? converted : buildDefaultQueries(kind);++ // Explorers put the single `unit` on the query itself, not the panel spec.+ if (compositeQuery.unit && kindSupportsUnit(kind)) {+ return {+ kind,+ queries,+ pluginSpec: {+ ...pluginSpec,+ formatting: { ...pluginSpec.formatting, unit: compositeQuery.unit },+ },+ };+ }++ return { kind, queries, pluginSpec };+}diff --git a/frontend/src/pages/TracesExplorer/__test__/TracesExplorer.test.tsx b/frontend/src/pages/TracesExplorer/__test__/TracesExplorer.test.tsxindex f82f4f2a75..2b1db8d339 100644--- a/frontend/src/pages/TracesExplorer/__test__/TracesExplorer.test.tsx+++ b/frontend/src/pages/TracesExplorer/__test__/TracesExplorer.test.tsx@@ -759,19 +759,18 @@ describe('TracesExplorer -', () => {expect(createDashboardBtn).toBeInTheDocument();fireEvent.click(createDashboardBtn);- await expect(screen.findByText('Export Panel')).resolves.toBeInTheDocument();- const createDashboardModal = document.querySelector(- '.ant-modal-content',- ) as HTMLElement;+ const createDashboardModal = (await screen.findByRole(+ 'dialog',+ )) as HTMLElement;expect(createDashboardModal).toBeInTheDocument();// assert modal contentexpect(- within(createDashboardModal).getByText('Select Dashboard'),+ within(createDashboardModal).getByTestId('export-panel-new-dashboard'),).toBeInTheDocument();expect(- within(createDashboardModal).getByText('New Dashboard'),+ within(createDashboardModal).getByTestId('export-panel-export'),).toBeInTheDocument();});diff --git a/frontend/src/pages/TracesExplorer/index.tsx b/frontend/src/pages/TracesExplorer/index.tsxindex 761db83d3c..dcd2a61a10 100644--- a/frontend/src/pages/TracesExplorer/index.tsx+++ b/frontend/src/pages/TracesExplorer/index.tsx@@ -28,6 +28,8 @@ import { defaultSelectedColumns } from 'container/TracesExplorer/ListView/configimport QuerySection from 'container/TracesExplorer/QuerySection';import TableView from 'container/TracesExplorer/TableView';import TracesView from 'container/TracesExplorer/TracesView';+import { ExportDashboard } from 'hooks/dashboard/useExportDashboards';+import { useGetExportToDashboardLink } from 'hooks/dashboard/useGetExportToDashboardLink';import { useGetPanelTypesQueryParam } from 'hooks/queryBuilder/useGetPanelTypesQueryParam';import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';@@ -42,10 +44,8 @@ import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallimport { ExplorerViews } from 'pages/LogsExplorer/utils';import { TOOLBAR_VIEWS } from 'pages/TracesExplorer/constants';import { Warning } from 'types/api';-import { Dashboard } from 'types/api/dashboard/getAll';import { Query } from 'types/api/queryBuilder/queryBuilderData';import { DataSource } from 'types/common/queryBuilder';-import { generateExportToDashboardLink } from 'utils/dashboard/generateExportToDashboardLink';import {explorerViewToPanelType,getExplorerViewFromUrl,@@ -129,6 +129,7 @@ function TracesExplorer(): JSX.Element {const { handleExplorerTabChange } = useHandleExplorerTabChange();const { safeNavigate } = useSafeNavigate();+ const getExportToDashboardLink = useGetExportToDashboardLink();const handleChangeSelectedView = useCallback((view: ExplorerViews, querySearchParameters?: ICurrentQueryData): void => {@@ -193,7 +194,7 @@ function TracesExplorer(): JSX.Element {);const handleExport = useCallback(- (dashboard: Dashboard | null, isNewDashboard?: boolean): void => {+ (dashboard: ExportDashboard | null, isNewDashboard?: boolean): void => {if (!dashboard || !panelType) {return;}@@ -213,19 +214,27 @@ function TracesExplorer(): JSX.Element {logEvent('Traces Explorer: Add to dashboard successful', {panelType,isNewDashboard,- dashboardName: dashboard?.data?.title,+ dashboardName: dashboard?.title,});- const dashboardEditView = generateExportToDashboardLink({+ const dashboardEditView = getExportToDashboardLink({query,panelType: panelTypeParam,dashboardId: dashboard.id,widgetId,});- safeNavigate(dashboardEditView);+ if (dashboardEditView) {+ safeNavigate(dashboardEditView);+ }},- [exportDefaultQuery, panelType, safeNavigate, options],+ [+ exportDefaultQuery,+ panelType,+ safeNavigate,+ options,+ getExportToDashboardLink,+ ],);useShareBuilderUrl({ defaultValue: defaultQuery });