Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat(dashboards-v2): context-link editor with variable + URL-param support (list + modal) (#11950)

Abhi kumare2588e6fff09
diff --git a/frontend/.oxlintrc.json b/frontend/.oxlintrc.json
index 91d527b9c5..b7bc78ace9 100644
--- a/frontend/.oxlintrc.json
+++ b/frontend/.oxlintrc.json
@@ -293,6 +293,8 @@
// Forces subpath imports (@signozhq/ui/<component>) instead of the eagerly-loaded barrel
"signoz/no-css-module-bracket-access": "warn",
// Prevents bracket access on CSS modules (styles['kebab-case']) which fails with camelCaseOnly config
+ "signoz/no-dashboard-fetch-outside-root": "error",
+ // Forces useDashboardFetchRequired() outside the root V2 pages (allowlisted in overrides below)
"no-restricted-globals": [
"error",
{
@@ -558,6 +560,18 @@
"rules": {
"signoz/no-zustand-getstate-in-hooks": "off"
}
+ },
+ {
+ // Root V2 pages own the dashboard fetch lifecycle; useDashboardFetchRequired wraps it.
+ // Everywhere else must use useDashboardFetchRequired().
+ "files": [
+ "src/pages/DashboardPageV2/DashboardPageV2.tsx",
+ "src/pages/DashboardPageV2/PanelEditorPage/PanelEditorPage.tsx",
+ "src/pages/DashboardPageV2/DashboardContainer/hooks/useDashboardFetchRequired.ts"
+ ],
+ "rules": {
+ "signoz/no-dashboard-fetch-outside-root": "off"
+ }
}
]
}
diff --git a/frontend/plugins/rules/no-dashboard-fetch-outside-root.mjs b/frontend/plugins/rules/no-dashboard-fetch-outside-root.mjs
new file mode 100644
index 0000000000..871c4e296a
--- /dev/null
+++ b/frontend/plugins/rules/no-dashboard-fetch-outside-root.mjs
@@ -0,0 +1,48 @@
+/**
+ * Rule: no-dashboard-fetch-outside-root
+ *
+ * `useDashboardFetch` owns the V2 dashboard fetch and exposes its loading/error/refetch
+ * lifecycle. That lifecycle is a root-page concern: DashboardPageV2 and PanelEditorPage
+ * gate their subtree on a resolved dashboard before mounting anything below them.
+ *
+ * Every other component therefore renders inside an already-loaded subtree and must use
+ * `useDashboardFetchRequired`, which reuses the same react-query cache entry but guarantees
+ * a non-undefined dashboard (throwing otherwise) — so consumers don't re-handle states the
+ * root page already owns.
+ *
+ * This rule flags `useDashboardFetch` imports. It is disabled via an override in
+ * .oxlintrc.json for the two root pages and for useDashboardFetchRequired.ts (which wraps it).
+ */
+
+const FETCH_HOOK = 'useDashboardFetch';
+
+export default {
+ meta: {
+ type: 'suggestion',
+ docs: {
+ description:
+ 'Disallow useDashboardFetch outside the root dashboard pages; use useDashboardFetchRequired instead',
+ category: 'Dashboard V2',
+ },
+ schema: [],
+ messages: {
+ useRequired:
+ 'Use useDashboardFetchRequired() instead of useDashboardFetch — the latter is reserved for the root pages (DashboardPageV2, PanelEditorPage) that own the fetch lifecycle. Components below them render inside a loaded subtree and should assume a guaranteed dashboard.',
+ },
+ },
+
+ create(context) {
+ return {
+ ImportDeclaration(node) {
+ node.specifiers.forEach((specifier) => {
+ if (
+ specifier.type === 'ImportSpecifier' &&
+ specifier.imported.name === FETCH_HOOK
+ ) {
+ context.report({ node: specifier, messageId: 'useRequired' });
+ }
+ });
+ },
+ };
+ },
+};
diff --git a/frontend/plugins/signoz.mjs b/frontend/plugins/signoz.mjs
index 5672157f6c..e237fa8324 100644
--- a/frontend/plugins/signoz.mjs
+++ b/frontend/plugins/signoz.mjs
@@ -12,6 +12,7 @@ import noRawAbsolutePath from './rules/no-raw-absolute-path.mjs';
import noAntdComponents from './rules/no-antd-components.mjs';
import noSignozhqUiBarrel from './rules/no-signozhq-ui-barrel.mjs';
import noCssModuleBracketAccess from './rules/no-css-module-bracket-access.mjs';
+import noDashboardFetchOutsideRoot from './rules/no-dashboard-fetch-outside-root.mjs';
export default {
meta: {
@@ -25,5 +26,6 @@ export default {
'no-antd-components': noAntdComponents,
'no-signozhq-ui-barrel': noSignozhqUiBarrel,
'no-css-module-bracket-access': noCssModuleBracketAccess,
+ 'no-dashboard-fetch-outside-root': noDashboardFetchOutsideRoot,
},
};
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/ContextLinkDialog.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/ContextLinkDialog.tsx
new file mode 100644
index 0000000000..284e584e21
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/ContextLinkDialog.tsx
@@ -0,0 +1,259 @@
+import { useEffect, useState } from 'react';
+import { Plus, Trash2 } from '@signozhq/icons';
+import { Button } from '@signozhq/ui/button';
+import { DialogWrapper } from '@signozhq/ui/dialog';
+import { Switch } from '@signozhq/ui/switch';
+import { Typography } from '@signozhq/ui/typography';
+import { Input } from 'antd';
+import type { DashboardLinkDTO } from 'api/generated/services/sigNoz.schemas';
+
+import type { UrlParam, VariableItem } from './types';
+import {
+ getUrlParams,
+ insertVariableAtCursor,
+ isValidContextLinkUrl,
+ updateUrlWithParams,
+} from './utils';
+import VariablesPopover from './VariablesPopover';
+
+import styles from './ContextLinksSection.module.scss';
+
+interface ContextLinkDialogProps {
+ open: boolean;
+ /** The link being edited, or null when adding a new one. */
+ initialLink: DashboardLinkDTO | null;
+ variables: VariableItem[];
+ onOpenChange: (open: boolean) => void;
+ onSave: (link: DashboardLinkDTO) => void;
+}
+
+const URL_ERROR = 'URL must start with http(s)://, /, or {{variable}}/';
+
+const cursorOf = (e: { target: EventTarget }): number =>
+ (e.target as HTMLInputElement).selectionStart ?? 0;
+
+/**
+ * Modal editor for a single context link (V1 parity): label + URL with `{{variable}}`
+ * autocomplete + validation, a key/value URL-parameters editor, and an "open in new tab"
+ * toggle. The URL is the source of truth; parameter rows are its query string projected
+ * out (blank-key rows live only in local state until they get a key). Save is gated on a
+ * non-empty, well-formed URL. `renderVariables` is set so consumers interpolate the URL.
+ */
+function ContextLinkDialog({
+ open,
+ initialLink,
+ variables,
+ onOpenChange,
+ onSave,
+}: ContextLinkDialogProps): JSX.Element {
+ const [name, setName] = useState('');
+ const [url, setUrlState] = useState('');
+ const [targetBlank, setTargetBlank] = useState(true);
+ const [params, setParams] = useState<UrlParam[]>([]);
+
+ // Seed the draft each time the dialog opens for a (possibly different) link.
+ useEffect(() => {
+ if (open) {
+ setName(initialLink?.name ?? '');
+ setUrlState(initialLink?.url ?? '');
+ setTargetBlank(initialLink?.targetBlank ?? true);
+ setParams(getUrlParams(initialLink?.url ?? ''));
+ }
+ }, [open, initialLink]);
+
+ const setUrl = (next: string): void => {
+ setUrlState(next);
+ setParams(getUrlParams(next));
+ };
+
+ const applyParams = (next: UrlParam[]): void => {
+ setParams(next);
+ setUrlState(updateUrlWithParams(url, next));
+ };
+
+ const patchParam = (index: number, patch: Partial<UrlParam>): void =>
+ applyParams(params.map((p, i) => (i === index ? { ...p, ...patch } : p)));
+
+ const addParam = (): void => {
+ const last = params[params.length - 1];
+ if (!last || last.key.trim() || last.value.trim()) {
+ setParams([...params, { key: '', value: '' }]);
+ }
+ };
+
+ const urlInvalid = !isValidContextLinkUrl(url);
+ const canSave = !!url.trim() && !urlInvalid;
+
+ const handleSave = (): void => {
+ if (canSave) {
+ onSave({ name, url, targetBlank, renderVariables: true });
+ }
+ };
+
+ return (
+ <DialogWrapper
+ open={open}
+ onOpenChange={onOpenChange}
+ title={initialLink ? 'Edit context link' : 'Add a context link'}
+ width="wide"
+ testId="context-link-dialog"
+ footer={
+ <>
+ <Button
+ type="button"
+ variant="outlined"
+ color="secondary"
+ data-testid="context-link-cancel"
+ onClick={(): void => onOpenChange(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="button"
+ variant="solid"
+ color="primary"
+ disabled={!canSave}
+ data-testid="context-link-save"
+ onClick={handleSave}
+ >
+ Save
+ </Button>
+ </>
+ }
+ >
+ <div className={styles.form}>
+ <div className={styles.formField}>
+ <Typography.Text className={styles.formLabel}>Label</Typography.Text>
+ <Input
+ data-testid="context-link-label"
+ placeholder="View trace details: {{_traceId}}"
+ value={name}
+ onChange={(e): void => setName(e.target.value)}
+ />
+ </div>
+
+ <div className={styles.formField}>
+ <Typography.Text className={styles.formLabel}>
+ URL <span className={styles.required}>*</span>
+ </Typography.Text>
+ <VariablesPopover
+ variables={variables}
+ onVariableSelect={(token, cursor): void =>
+ setUrl(insertVariableAtCursor(url, token, cursor))
+ }
+ >
+ {({ setIsOpen, setCursorPosition }): JSX.Element => (
+ <Input
+ data-testid="context-link-url"
+ placeholder="https://… or /path?var={{variable}}"
+ value={url}
+ status={urlInvalid ? 'error' : undefined}
+ autoComplete="off"
+ onChange={(e): void => {
+ setCursorPosition(e.target.selectionStart ?? 0);
+ setUrl(e.target.value);
+ }}
+ onFocus={(): void => setIsOpen(true)}
+ onClick={(e): void => setCursorPosition(cursorOf(e))}
+ onKeyUp={(e): void => setCursorPosition(cursorOf(e))}
+ />
+ )}
+ </VariablesPopover>
+ {urlInvalid && (
+ <Typography.Text
+ className={styles.urlError}
+ data-testid="context-link-url-error"
+ >
+ {URL_ERROR}
+ </Typography.Text>
+ )}
+ </div>
+
+ {params.length > 0 && (
+ <div className={styles.formField}>
+ <Typography.Text className={styles.formLabel}>
+ URL parameters
+ </Typography.Text>
+ <div className={styles.params}>
+ {params.map((param, index) => (
+ <div
+ className={styles.paramRow}
+ // Parameter rows have no stable id; index is the row identity here.
+ // eslint-disable-next-line react/no-array-index-key
+ key={index}
+ >
+ <Input
+ data-testid={`context-link-param-key-${index}`}
+ placeholder="Key"
+ value={param.key}
+ onChange={(e): void => patchParam(index, { key: e.target.value })}
+ />
+ <VariablesPopover
+ variables={variables}
+ onVariableSelect={(token, cursor): void =>
+ patchParam(index, {
+ value: insertVariableAtCursor(param.value, token, cursor),
+ })
+ }
+ >
+ {({ setIsOpen, setCursorPosition }): JSX.Element => (
+ <Input
+ data-testid={`context-link-param-value-${index}`}
+ placeholder="Value"
+ value={param.value}
+ onChange={(e): void => {
+ setCursorPosition(e.target.selectionStart ?? 0);
+ patchParam(index, { value: e.target.value });
+ }}
+ onFocus={(): void => setIsOpen(true)}
+ onClick={(e): void => setCursorPosition(cursorOf(e))}
+ onKeyUp={(e): void => setCursorPosition(cursorOf(e))}
+ />
+ )}
+ </VariablesPopover>
+ <Button
+ type="button"
+ variant="ghost"
+ color="destructive"
+ size="icon"
+ aria-label={`Remove parameter ${index + 1}`}
+ data-testid={`context-link-param-remove-${index}`}
+ onClick={(): void =>
+ applyParams(params.filter((_, i) => i !== index))
+ }
+ >
+ <Trash2 size={14} />
+ </Button>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ <Button
+ type="button"
+ variant="dashed"
+ color="secondary"
+ prefix={<Plus size={12} />}
+ data-testid="context-link-add-param"
+ onClick={addParam}
+ >
+ Add URL parameter
+ </Button>
+
+ <div className={styles.newTab}>
+ <Switch
+ testId="context-link-newtab"
+ value={targetBlank}
+ onChange={setTargetBlank}
+ />
+ <Typography.Text className={styles.newTabLabel}>
+ Open in new tab
+ </Typography.Text>
+ </div>
+ </div>
+ </DialogWrapper>
+ );
+}
+
+export default ContextLinkDialog;
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/ContextLinkListItem.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/ContextLinkListItem.tsx
new file mode 100644
index 0000000000..9da6193833
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/ContextLinkListItem.tsx
@@ -0,0 +1,62 @@
+import { Pencil, Trash2 } from '@signozhq/icons';
+import { Button } from '@signozhq/ui/button';
+import { Typography } from '@signozhq/ui/typography';
+import type { DashboardLinkDTO } from 'api/generated/services/sigNoz.schemas';
+
+import styles from './ContextLinksSection.module.scss';
+
+interface ContextLinkListItemProps {
+ link: DashboardLinkDTO;
+ index: number;
+ onEdit: () => void;
+ onRemove: () => void;
+}
+
+/** A saved context link in the section list: its label + URL, with edit / delete actions. */
+function ContextLinkListItem({
+ link,
+ index,
+ onEdit,
+ onRemove,
+}: ContextLinkListItemProps): JSX.Element {
+ const label = link.name?.trim() || link.url || 'Untitled link';
+
+ return (
+ <div className={styles.listItem} data-testid={`context-link-item-${index}`}>
+ <div className={styles.listItemText}>
+ <Typography.Text className={styles.listItemLabel}>{label}</Typography.Text>
+ {!!link.url && (
+ <Typography.Text className={styles.listItemUrl}>
+ {link.url}
+ </Typography.Text>
+ )}
+ </div>
+ <div className={styles.listItemActions}>
+ <Button
+ type="button"
+ variant="ghost"
+ color="secondary"
+ size="icon"
+ aria-label={`Edit link ${index + 1}`}
+ data-testid={`context-link-edit-${index}`}
+ onClick={onEdit}
+ >
+ <Pencil size={14} />
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ color="destructive"
+ size="icon"
+ aria-label={`Remove link ${index + 1}`}
+ data-testid={`context-link-remove-${index}`}
+ onClick={onRemove}
+ >
+ <Trash2 size={14} />
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+export default ContextLinkListItem;
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/ContextLinksSection.module.scss b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/ContextLinksSection.module.scss
index 9556886e12..4751f94532 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/ContextLinksSection.module.scss
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/ContextLinksSection.module.scss
@@ -1,32 +1,99 @@
.list {
display: flex;
flex-direction: column;
- gap: 12px;
+ gap: 8px;
}
-.row {
+/* --- Saved-link list item --- */
+.listItem {
display: flex;
- flex-direction: column;
+ align-items: center;
+ justify-content: space-between;
gap: 8px;
- padding: 10px;
+ padding: 8px 10px;
border: 1px solid var(--l2-border);
border-radius: 6px;
}
-.rowFooter {
+.listItemText {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 0;
+}
+
+.listItemLabel,
+.listItemUrl {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ max-width: 100%;
+}
+
+.listItemLabel {
+ font-size: 13px;
+ color: var(--text-vanilla-100);
+}
+
+.listItemUrl {
+ font-size: 11px;
+ color: var(--text-vanilla-400);
+}
+
+.listItemActions {
display: flex;
align-items: center;
- justify-content: space-between;
+ gap: 2px;
+ flex-shrink: 0;
+}
+
+/* --- Dialog form --- */
+.form {
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+}
+
+.formField {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+.formLabel {
+ font-size: 12px;
+ color: var(--l2-foreground);
+}
+
+.required {
+ color: var(--bg-cherry-400);
+}
+
+.urlError {
+ font-size: 11px;
+ color: var(--bg-cherry-400);
+}
+
+.params {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.paramRow {
+ display: grid;
+ grid-template-columns: 1fr 1fr auto;
+ align-items: center;
+ gap: 6px;
}
.newTab {
display: flex;
align-items: center;
gap: 8px;
- cursor: pointer;
}
.newTabLabel {
font-size: 12px;
- color: var(--text-vanilla-400);
+ color: var(--l2-foreground);
}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/ContextLinksSection.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/ContextLinksSection.tsx
index a9af752261..d5d0d2745d 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/ContextLinksSection.tsx
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/ContextLinksSection.tsx
@@ -1,83 +1,63 @@
-import { Plus, Trash2 } from '@signozhq/icons';
+import { useState } from 'react';
+import { Plus } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
-import { Switch } from '@signozhq/ui/switch';
-import { Typography } from '@signozhq/ui/typography';
-import { Input } from 'antd';
import type { DashboardLinkDTO } from 'api/generated/services/sigNoz.schemas';
import type {
SectionEditorProps,
SectionKind,
} from 'pages/DashboardPageV2/DashboardContainer/Panels/types/sections';
+import ContextLinkDialog from './ContextLinkDialog';
+import ContextLinkListItem from './ContextLinkListItem';
+import { useContextLinkVariables } from './useContextLinkVariables';
+
import styles from './ContextLinksSection.module.scss';
/**
- * Edits the panel's context links (`spec.links`): a list of label + URL rows with an
- * "open in new tab" toggle, plus add/remove. Atomic section — no per-kind sub-controls.
- * URLs may reference dashboard/query variables; that interpolation is resolved at render
- * time, so this editor just captures the raw strings.
+ * Edits the panel's context links (`spec.links`) as a list of saved links, each added or
+ * edited through a modal ({@link ContextLinkDialog}) that carries V1's full authoring UX
+ * (variable autocomplete, URL-parameters editor, validation).
*/
function ContextLinksSection({
value,
onChange,
}: SectionEditorProps<SectionKind.ContextLinks>): JSX.Element {
const links = value ?? [];
+ const variables = useContextLinkVariables();
- const updateAt = (index: number, patch: Partial<DashboardLinkDTO>): void =>
- onChange(
- links.map((link, i) => (i === index ? { ...link, ...patch } : link)),
- );
-
- const addLink = (): void =>
- onChange([...links, { name: '', url: '', targetBlank: true }]);
+ // `index === null` while adding a new link; a number while editing an existing one.
+ const [dialog, setDialog] = useState<{ open: boolean; index: number | null }>({
+ open: false,
+ index: null,
+ });
const removeAt = (index: number): void =>
onChange(links.filter((_, i) => i !== index));
+ const handleSave = (link: DashboardLinkDTO): void => {
+ onChange(
+ dialog.index === null
+ ? [...links, link]
+ : links.map((existing, i) => (i === dialog.index ? link : existing)),
+ );
+ setDialog((d) => ({ ...d, open: false }));
+ };
+
+ const editingLink =
+ dialog.index !== null ? (links[dialog.index] ?? null) : null;
+
return (
<div className={styles.list}>
{links.map((link, index) => (
- // Links have no stable id on the wire; index is the row identity here.
- // eslint-disable-next-line react/no-array-index-key
- <div className={styles.row} key={index}>
- <Input
- data-testid={`context-link-label-${index}`}
- placeholder="Label"
- value={link.name ?? ''}
- onChange={(e): void => updateAt(index, { name: e.target.value })}
- />
- <Input
- data-testid={`context-link-url-${index}`}
- placeholder="https://… or /path?var=$variable"
- value={link.url ?? ''}
- onChange={(e): void => updateAt(index, { url: e.target.value })}
- />
- <div className={styles.rowFooter}>
- <div className={styles.newTab}>
- <Switch
- testId={`context-link-newtab-${index}`}
- value={link.targetBlank ?? false}
- onChange={(checked: boolean): void =>
- updateAt(index, { targetBlank: checked })
- }
- />
- <Typography.Text className={styles.newTabLabel}>
- Open in new tab
- </Typography.Text>
- </div>
- <Button
- type="button"
- variant="ghost"
- color="destructive"
- size="icon"
- aria-label={`Remove link ${index + 1}`}
- data-testid={`context-link-remove-${index}`}
- onClick={(): void => removeAt(index)}
- >
- <Trash2 size={14} />
- </Button>
- </div>
- </div>
+ <ContextLinkListItem
+ // Links have no stable id on the wire; index is the row identity here.
+ // eslint-disable-next-line react/no-array-index-key
+ key={index}
+ link={link}
+ index={index}
+ onEdit={(): void => setDialog({ open: true, index })}
+ onRemove={(): void => removeAt(index)}
+ />
))}
<Button
@@ -86,10 +66,18 @@ function ContextLinksSection({
color="secondary"
prefix={<Plus size={14} />}
data-testid="panel-editor-v2-add-link"
- onClick={addLink}
+ onClick={(): void => setDialog({ open: true, index: null })}
>
- Add link
+ Add Context Link
</Button>
+
+ <ContextLinkDialog
+ open={dialog.open}
+ initialLink={editingLink}
+ variables={variables}
+ onOpenChange={(open): void => setDialog((d) => ({ ...d, open }))}
+ onSave={handleSave}
+ />
</div>
);
}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/VariablesPopover.module.scss b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/VariablesPopover.module.scss
new file mode 100644
index 0000000000..eb2f90abe4
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/VariablesPopover.module.scss
@@ -0,0 +1,64 @@
+.container {
+ width: 100%;
+}
+
+.anchor {
+ width: 100%;
+}
+
+.content {
+ z-index: 1100;
+ padding: 4px 0;
+ max-height: 300px;
+ overflow-y: auto;
+ overflow-x: hidden;
+ min-width: var(--radix-popover-trigger-width);
+}
+
+.empty {
+ padding: 8px 12px;
+ color: var(--text-vanilla-400);
+ font-size: 12px;
+ font-style: italic;
+}
+
+.item {
+ --button-display: flex;
+ --button-justify-content: flex-start;
+ --button-height: auto;
+ --button-padding: 8px 12px;
+ --button-border-radius: 0;
+ --button-font-size: 13px;
+ --button-line-height: 1.4;
+
+ width: 100%;
+ overflow: hidden;
+}
+
+.row {
+ display: flex;
+ flex: 1 1 auto;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ min-width: 0;
+}
+
+.name,
+.source {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.name {
+ flex: 1 1 auto;
+ text-align: start;
+}
+
+.source {
+ color: var(--l3-foreground);
+ font-size: 12px;
+ flex: 0 1 auto;
+}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/VariablesPopover.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/VariablesPopover.tsx
new file mode 100644
index 0000000000..ebe751a4e5
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/VariablesPopover.tsx
@@ -0,0 +1,117 @@
+// Uses Popover (not DropdownMenu): DropdownMenuTrigger preventDefaults pointerdown,
+// which steals input focus and dismisses on every keystroke. PopoverAnchor is a passive
+// positioning element that leaves the wrapped input fully interactive.
+import { ReactNode, useRef, useState } from 'react';
+import { Button } from '@signozhq/ui/button';
+import { Popover, PopoverAnchor, PopoverContent } from '@signozhq/ui/popover';
+import { Typography } from '@signozhq/ui/typography';
+
+import type { VariableItem } from './types';
+
+import styles from './VariablesPopover.module.scss';
+
+interface VariablesPopoverRenderProps {
+ setIsOpen: (open: boolean) => void;
+ setCursorPosition: (position: number | null) => void;
+}
+
+interface VariablesPopoverProps {
+ variables: VariableItem[];
+ /** Called with the braces-wrapped token (e.g. `{{env}}`) and the tracked cursor offset. */
+ onVariableSelect: (token: string, cursorPosition?: number) => void;
+ children: (props: VariablesPopoverRenderProps) => ReactNode;
+}
+
+/**
+ * Autocomplete for context-link variables. Wraps an input (via the render-prop) and
+ * shows the available `{{variables}}` grouped by source; picking one inserts it at the
+ * tracked cursor. The consumer drives `setIsOpen` (on focus) and `setCursorPosition`.
+ */
+function VariablesPopover({
+ variables,
+ onVariableSelect,
+ children,
+}: VariablesPopoverProps): JSX.Element {
+ const [isOpen, setIsOpen] = useState(false);
+ const [cursorPosition, setCursorPosition] = useState<number | null>(null);
+ const anchorRef = useRef<HTMLDivElement>(null);
+
+ const handleOpenChange = (open: boolean): void => {
+ // Accept "close" events (outside-click, Esc) but ignore opens — opening is driven
+ // by the input's onFocus in the consumer.
+ if (!open) {
+ setIsOpen(false);
+ }
+ };
+
+ // Keep the popover open while the pointer/focus is inside the anchored input.
+ const keepOpenIfInsideAnchor = (event: {
+ target: EventTarget | null;
+ }): void => {
+ const target = event.target as Node | null;
+ if (
+ target &&
+ anchorRef.current?.contains(target) &&
+ 'preventDefault' in event
+ ) {
+ (event as Event).preventDefault();
+ }
+ };
+
+ return (
+ <div className={styles.container}>
+ <Popover open={isOpen} onOpenChange={handleOpenChange} modal={false}>
+ <PopoverAnchor asChild>
+ <div className={styles.anchor} ref={anchorRef}>
+ {children({ setIsOpen, setCursorPosition })}
+ </div>
+ </PopoverAnchor>
+ <PopoverContent
+ align="start"
+ sideOffset={4}
+ // Render inside the anchor (not a body portal): the editor lives in a modal
+ // DialogWrapper, and radix's modal sets pointer-events:none on everything
+ // portalled outside it, which would make the suggestions unclickable.
+ withPortal={false}
+ className={styles.content}
+ onOpenAutoFocus={(e): void => e.preventDefault()}
+ onCloseAutoFocus={(e): void => e.preventDefault()}
+ onInteractOutside={keepOpenIfInsideAnchor}
+ onFocusOutside={keepOpenIfInsideAnchor}
+ >
+ {variables.length === 0 ? (
+ <div className={styles.empty}>No variables available</div>
+ ) : (
+ variables.map((v) => (
+ <Button
+ key={`${v.source}-${v.name}`}
+ type="button"
+ variant="ghost"
+ color="secondary"
+ size="md"
+ className={styles.item}
+ aria-label={`Insert {{${v.name}}}`}
+ testId={`context-link-variable-${v.name}`}
+ // Prevent the input from losing focus when clicking an item.
+ onMouseDown={(e): void => e.preventDefault()}
+ onClick={(): void => {
+ onVariableSelect(`{{${v.name}}}`, cursorPosition ?? undefined);
+ setIsOpen(false);
+ }}
+ >
+ <div className={styles.row}>
+ <Typography.Text
+ className={styles.name}
+ >{`{{${v.name}}}`}</Typography.Text>
+ <Typography.Text className={styles.source}>{v.source}</Typography.Text>
+ </div>
+ </Button>
+ ))
+ )}
+ </PopoverContent>
+ </Popover>
+ </div>
+ );
+}
+
+export default VariablesPopover;
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/__tests__/ContextLinksSection.test.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/__tests__/ContextLinksSection.test.tsx
index be2f15e1fb..9a1ffb2bac 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/__tests__/ContextLinksSection.test.tsx
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/__tests__/ContextLinksSection.test.tsx
@@ -3,47 +3,92 @@ import type { DashboardLinkDTO } from 'api/generated/services/sigNoz.schemas';
import ContextLinksSection from '../ContextLinksSection';
+// The variable-source hook reads the query-builder provider + store; stub it so the
+// editor can be exercised in isolation (its own suite covers the sourcing logic).
+jest.mock('../useContextLinkVariables', () => ({
+ useContextLinkVariables: (): unknown => [
+ { name: 'timestamp_start', source: 'Global timestamp' },
+ { name: 'env', source: 'Dashboard variable' },
+ ],
+}));
+
const LINKS: DashboardLinkDTO[] = [
{ name: 'Docs', url: 'https://signoz.io', targetBlank: true },
];
+const lastCall = (fn: jest.Mock): DashboardLinkDTO[] =>
+ fn.mock.calls[fn.mock.calls.length - 1][0];
+
describe('ContextLinksSection', () => {
it('renders only the add button when there are no links', () => {
render(<ContextLinksSection value={undefined} onChange={jest.fn()} />);
expect(screen.getByTestId('panel-editor-v2-add-link')).toBeInTheDocument();
- expect(screen.queryByTestId('context-link-label-0')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('context-link-item-0')).not.toBeInTheDocument();
+ });
+
+ it('renders existing links as list items showing the label', () => {
+ render(<ContextLinksSection value={LINKS} onChange={jest.fn()} />);
+
+ expect(screen.getByTestId('context-link-item-0')).toHaveTextContent('Docs');
+ // The editor is a modal — no inline fields until it's opened.
+ expect(screen.queryByTestId('context-link-url')).not.toBeInTheDocument();
});
- it('appends a blank link (open-in-new-tab on) when Add link is clicked', () => {
+ it('adds a link through the dialog (Save gated on a valid URL)', async () => {
const onChange = jest.fn();
render(<ContextLinksSection value={[]} onChange={onChange} />);
fireEvent.click(screen.getByTestId('panel-editor-v2-add-link'));
+ const save = await screen.findByTestId('context-link-save');
+ expect(save).toBeDisabled();
+
+ fireEvent.change(screen.getByTestId('context-link-url'), {
+ target: { value: 'https://signoz.io' },
+ });
+ fireEvent.change(screen.getByTestId('context-link-label'), {
+ target: { value: 'Docs' },
+ });
+ expect(save).not.toBeDisabled();
+
+ fireEvent.click(save);
expect(onChange).toHaveBeenCalledWith([
- { name: '', url: '', targetBlank: true },
+ {
+ name: 'Docs',
+ url: 'https://signoz.io',
+ targetBlank: true,
+ renderVariables: true,
+ },
]);
});
- it('renders existing links and edits a label through onChange', () => {
+ it('edits an existing link through the dialog', async () => {
const onChange = jest.fn();
render(<ContextLinksSection value={LINKS} onChange={onChange} />);
- expect(screen.getByTestId('context-link-label-0')).toHaveValue('Docs');
- expect(screen.getByTestId('context-link-url-0')).toHaveValue(
+ fireEvent.click(screen.getByTestId('context-link-edit-0'));
+
+ const label = await screen.findByTestId('context-link-label');
+ expect(label).toHaveValue('Docs');
+ expect(screen.getByTestId('context-link-url')).toHaveValue(
'https://signoz.io',
);
- fireEvent.change(screen.getByTestId('context-link-label-0'), {
- target: { value: 'Runbook' },
- });
+ fireEvent.change(label, { target: { value: 'Runbook' } });
+ fireEvent.click(screen.getByTestId('context-link-save'));
+
expect(onChange).toHaveBeenCalledWith([
- { name: 'Runbook', url: 'https://signoz.io', targetBlank: true },
+ {
+ name: 'Runbook',
+ url: 'https://signoz.io',
+ targetBlank: true,
+ renderVariables: true,
+ },
]);
});
- it('removes a link through onChange', () => {
+ it('removes a link from the list', () => {
const onChange = jest.fn();
render(<ContextLinksSection value={LINKS} onChange={onChange} />);
@@ -51,4 +96,52 @@ describe('ContextLinksSection', () => {
expect(onChange).toHaveBeenCalledWith([]);
});
+
+ it('shows a validation error only for a malformed URL', async () => {
+ render(<ContextLinksSection value={[]} onChange={jest.fn()} />);
+ fireEvent.click(screen.getByTestId('panel-editor-v2-add-link'));
+
+ const urlInput = await screen.findByTestId('context-link-url');
+
+ fireEvent.change(urlInput, { target: { value: 'not-a-url' } });
+ expect(screen.getByTestId('context-link-url-error')).toBeInTheDocument();
+ expect(screen.getByTestId('context-link-save')).toBeDisabled();
+
+ fireEvent.change(urlInput, { target: { value: '/valid/path' } });
+ expect(
+ screen.queryByTestId('context-link-url-error'),
+ ).not.toBeInTheDocument();
+ });
+
+ it('adds a URL parameter and writes it into the URL query string', async () => {
+ const onChange = jest.fn();
+ render(<ContextLinksSection value={[]} onChange={onChange} />);
+ fireEvent.click(screen.getByTestId('panel-editor-v2-add-link'));
+
+ fireEvent.change(await screen.findByTestId('context-link-url'), {
+ target: { value: '/logs' },
+ });
+ fireEvent.click(screen.getByTestId('context-link-add-param'));
+ fireEvent.change(screen.getByTestId('context-link-param-key-0'), {
+ target: { value: 'env' },
+ });
+ fireEvent.click(screen.getByTestId('context-link-save'));
+
+ expect(lastCall(onChange)).toStrictEqual([
+ { name: '', url: '/logs?env=', targetBlank: true, renderVariables: true },
+ ]);
+ });
+
+ it('inserts a {{variable}} into the URL from the autocomplete popover', async () => {
+ render(<ContextLinksSection value={[]} onChange={jest.fn()} />);
+ fireEvent.click(screen.getByTestId('panel-editor-v2-add-link'));
+
+ const urlInput = await screen.findByTestId('context-link-url');
+ fireEvent.focus(urlInput);
+ fireEvent.click(
+ await screen.findByTestId('context-link-variable-timestamp_start'),
+ );
+
+ expect(urlInput).toHaveValue('{{timestamp_start}}');
+ });
});
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/__tests__/useContextLinkVariables.test.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/__tests__/useContextLinkVariables.test.tsx
new file mode 100644
index 0000000000..cd2631b200
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/__tests__/useContextLinkVariables.test.tsx
@@ -0,0 +1,83 @@
+import { renderHook } from '@testing-library/react';
+
+import { useContextLinkVariables } from '../useContextLinkVariables';
+
+const mockUseGetDashboardV2 = jest.fn();
+const mockUseQueryBuilder = jest.fn();
+
+jest.mock(
+ 'pages/DashboardPageV2/DashboardContainer/store/useDashboardStore',
+ () => ({
+ useDashboardStore: (
+ selector: (s: { dashboardId: string }) => unknown,
+ ): unknown => selector({ dashboardId: 'dash-1' }),
+ }),
+);
+
+jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
+ useQueryBuilder: (): unknown => mockUseQueryBuilder(),
+}));
+
+jest.mock('api/generated/services/dashboard', () => ({
+ useGetDashboardV2: (): unknown => mockUseGetDashboardV2(),
+}));
+
+// dtoToFormModel is exercised by its own suite; here we only need it to surface a name.
+jest.mock(
+ 'pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/variableAdapters',
+ () => ({
+ dtoToFormModel: (dto: { name: string }): { name: string } => ({
+ name: dto.name,
+ }),
+ }),
+);
+
+describe('useContextLinkVariables', () => {
+ beforeEach(() => {
+ mockUseQueryBuilder.mockReturnValue({
+ currentQuery: {
+ builder: {
+ queryData: [
+ { groupBy: [{ key: 'service.name' }, { key: 'env' }] },
+ // Duplicate across queries — must dedupe.
+ { groupBy: [{ key: 'service.name' }] },
+ ],
+ },
+ },
+ });
+ mockUseGetDashboardV2.mockReturnValue({
+ data: {
+ data: { spec: { variables: [{ name: 'region' }, { name: 'tier' }] } },
+ },
+ });
+ });
+
+ it('orders globals, then _prefixed query fields (deduped), then dashboard vars', () => {
+ const { result } = renderHook(() => useContextLinkVariables());
+
+ expect(result.current).toStrictEqual([
+ { name: 'timestamp_start', source: 'Global timestamp' },
+ { name: 'timestamp_end', source: 'Global timestamp' },
+ { name: '_service.name', source: 'Query variable' },
+ { name: '_env', source: 'Query variable' },
+ { name: 'region', source: 'Dashboard variable' },
+ { name: 'tier', source: 'Dashboard variable' },
+ ]);
+ });
+
+ it('still returns the global timestamps when there are no queries or variables', () => {
+ mockUseQueryBuilder.mockReturnValue({
+ currentQuery: { builder: { queryData: [] } },
+ });
+ // Loaded dashboard with no variables — useDashboardFetchRequired guarantees the
+ // dashboard is present, so the empty case is an empty spec, not `undefined`.
+ mockUseGetDashboardV2.mockReturnValue({ data: { data: { spec: {} } } });
+
+ const { result } = renderHook(() => useContextLinkVariables());
+
+ expect(result.current).toStrictEqual([
+ { name: 'timestamp_start', source: 'Global timestamp' },
+ { name: 'timestamp_end', source: 'Global timestamp' },
+ ]);
+ });
+});
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/__tests__/utils.test.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/__tests__/utils.test.ts
new file mode 100644
index 0000000000..248338ff58
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/__tests__/utils.test.ts
@@ -0,0 +1,68 @@
+import {
+ getUrlParams,
+ insertVariableAtCursor,
+ isValidContextLinkUrl,
+ updateUrlWithParams,
+} from '../utils';
+
+describe('ContextLinksSection utils', () => {
+ describe('isValidContextLinkUrl', () => {
+ it.each([
+ ['', true],
+ ['https://signoz.io', true],
+ ['http://localhost:3301/trace', true],
+ ['/trace/{{_traceId}}', true],
+ ['{{host}}/trace', true],
+ ['trace/{{_traceId}}', false],
+ ['ftp://signoz.io', false],
+ ])('validates %p as %p', (url, expected) => {
+ expect(isValidContextLinkUrl(url)).toBe(expected);
+ });
+ });
+
+ describe('insertVariableAtCursor', () => {
+ it('inserts at the cursor position', () => {
+ expect(insertVariableAtCursor('/trace/', '{{id}}', 7)).toBe('/trace/{{id}}');
+ expect(insertVariableAtCursor('ab', '{{x}}', 1)).toBe('a{{x}}b');
+ });
+
+ it('appends when no cursor position is given', () => {
+ expect(insertVariableAtCursor('/trace/', '{{id}}')).toBe('/trace/{{id}}');
+ });
+ });
+
+ describe('getUrlParams', () => {
+ it('returns [] when there is no query string', () => {
+ expect(getUrlParams('/trace/{{id}}')).toStrictEqual([]);
+ });
+
+ it('parses and decodes key/value pairs', () => {
+ expect(getUrlParams('/logs?service={{svc}}&env=prod')).toStrictEqual([
+ { key: 'service', value: '{{svc}}' },
+ { key: 'env', value: 'prod' },
+ ]);
+ });
+
+ it('double-decodes over-encoded values', () => {
+ // %257B%257B == encodeURIComponent('%7B%7B') == encodeURIComponent('{{')
+ expect(getUrlParams('/logs?q=%257B%257Bx%257D%257D')).toStrictEqual([
+ { key: 'q', value: '{{x}}' },
+ ]);
+ });
+ });
+
+ describe('updateUrlWithParams', () => {
+ it('rebuilds the query string and drops empty keys', () => {
+ expect(
+ updateUrlWithParams('/logs?old=1', [
+ { key: 'service', value: '{{svc}}' },
+ { key: '', value: 'ignored' },
+ ]),
+ ).toBe('/logs?service=%7B%7Bsvc%7D%7D');
+ });
+
+ it('drops the query string entirely when no valid params remain', () => {
+ expect(updateUrlWithParams('/logs?a=b', [])).toBe('/logs');
+ });
+ });
+});
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/types.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/types.ts
new file mode 100644
index 0000000000..c125b52111
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/types.ts
@@ -0,0 +1,29 @@
+/**
+ * Where a context-link variable comes from — shown as the right-hand label in the popover.
+ *
+ * - `Global timestamp` — the dashboard's selected time range: `timestamp_start` /
+ * `timestamp_end`. Always available, independent of the panel or its queries.
+ * - `Query variable` — a `groupBy` field from the panel's own queries, `_`-prefixed
+ * (e.g. `_service_name`). Resolved at click time from the data point the user clicked,
+ * so it reflects the current query definition and changes as the queries are edited.
+ * - `Dashboard variable` — a user-defined dashboard variable from Dashboard Settings
+ * (e.g. `env`, `region`). Shared across every panel and driven by the dashboard's
+ * variable selectors rather than by an individual query.
+ */
+export type VariableSource =
+ | 'Global timestamp'
+ | 'Query variable'
+ | 'Dashboard variable';
+
+/** One entry in the context-link variable autocomplete. */
+export interface VariableItem {
+ /** Bare variable name without braces, e.g. `timestamp_start`, `_service_name`, `env`. */
+ name: string;
+ source: VariableSource;
+}
+
+/** A single decoded key/value pair parsed from (or written back to) a URL query string. */
+export interface UrlParam {
+ key: string;
+ value: string;
+}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/useContextLinkVariables.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/useContextLinkVariables.ts
new file mode 100644
index 0000000000..e8bc6a515a
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/useContextLinkVariables.ts
@@ -0,0 +1,60 @@
+import { useMemo } from 'react';
+import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
+import { dtoToFormModel } from 'pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/variableAdapters';
+import { useDashboardFetchRequired } from 'pages/DashboardPageV2/DashboardContainer/hooks/useDashboardFetchRequired';
+
+import type { VariableItem } from './types';
+
+// Global time-range variables, always available (V1 parity: `timestamp_start` / `_end`).
+const GLOBAL_TIMESTAMP_VARIABLES: VariableItem[] = [
+ { name: 'timestamp_start', source: 'Global timestamp' },
+ { name: 'timestamp_end', source: 'Global timestamp' },
+];
+
+/**
+ * Variables offered by the context-link autocomplete, ordered as in V1: global
+ * timestamps, then per-query `groupBy` fields (prefixed `_`), then dashboard variables.
+ *
+ * Self-contained — the editor renders inside the query-builder provider and the
+ * DashboardContainer, so every source is read here rather than threaded through the
+ * section registry. The dashboard fetch dedupes against the editor page's own query.
+ */
+export function useContextLinkVariables(): VariableItem[] {
+ const { currentQuery } = useQueryBuilder();
+
+ const { variables: variableDtos } = useDashboardFetchRequired();
+
+ const dashboardVariableNames = useMemo(
+ () =>
+ variableDtos
+ .map((dto) => dtoToFormModel(dto).name)
+ .filter((name): name is string => !!name),
+ [variableDtos],
+ );
+
+ // `_`-prefixed to match V1 and avoid colliding with dashboard-variable names.
+ const fieldVariableNames = useMemo(() => {
+ const names = new Set<string>();
+ (currentQuery?.builder?.queryData ?? []).forEach((query) => {
+ (query.groupBy ?? []).forEach((field) => {
+ if (field.key) {
+ names.add(`_${field.key}`);
+ }
+ });
+ });
+ return Array.from(names);
+ }, [currentQuery?.builder?.queryData]);
+
+ return useMemo(
+ () => [
+ ...GLOBAL_TIMESTAMP_VARIABLES,
+ ...fieldVariableNames.map(
+ (name): VariableItem => ({ name, source: 'Query variable' }),
+ ),
+ ...dashboardVariableNames.map(
+ (name): VariableItem => ({ name, source: 'Dashboard variable' }),
+ ),
+ ],
+ [fieldVariableNames, dashboardVariableNames],
+ );
+}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/utils.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/utils.ts
new file mode 100644
index 0000000000..2e09e85983
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/PanelEditor/ConfigPane/sections/ContextLinksSection/utils.ts
@@ -0,0 +1,78 @@
+import type { UrlParam } from './types';
+
+// A link URL must be absolute (http/https), root-relative (`/path`), or start with a
+// leading `{{var}}/` segment (a variable that resolves to a host/path at click-time).
+const CONTEXT_LINK_URL_PATTERN = /^(https?:\/\/|\/|{{.*}}\/)/;
+
+/**
+ * Whether the URL is well-formed for a context link. Empty is treated as valid so the
+ * editor doesn't nag while a row is still being filled in — emptiness is a separate concern.
+ */
+export function isValidContextLinkUrl(url: string): boolean {
+ if (!url) {
+ return true;
+ }
+ return CONTEXT_LINK_URL_PATTERN.test(url);
+}
+
+/** Inserts `variable` into `current` at `cursorPosition`, or appends when it's unknown. */
+export function insertVariableAtCursor(
+ current: string,
+ variable: string,
+ cursorPosition?: number,
+): string {
+ if (cursorPosition === undefined) {
+ return current + variable;
+ }
+ return (
+ current.slice(0, cursorPosition) + variable + current.slice(cursorPosition)
+ );
+}
+
+// Values may be double-encoded on the wire; decode a second time only when it changes
+// the string, so already-single-encoded values are left intact.
+function decodeForDisplay(value: string): string {
+ const decoded = decodeURIComponent(value);
+ try {
+ const doubleDecoded = decodeURIComponent(decoded);
+ return doubleDecoded !== decoded ? doubleDecoded : decoded;
+ } catch {
+ return decoded;
+ }
+}
+
+/** Parses the `?a=b&c=d` query string of a URL into decoded key/value rows. */
+export function getUrlParams(url: string): UrlParam[] {
+ const [, queryString] = url.split('?');
+ if (!queryString) {
+ return [];
+ }
+
+ const params: UrlParam[] = [];
+ queryString.split('&').forEach((pair) => {
+ const [key, value] = pair.split('=');
+ if (key) {
+ params.push({
+ key: decodeURIComponent(key),
+ value: decodeForDisplay(value || ''),
+ });
+ }
+ });
+ return params;
+}
+
+/** Rewrites `url`'s query string from `params`, dropping rows with an empty key. */
+export function updateUrlWithParams(url: string, params: UrlParam[]): string {
+ const [baseUrl] = url.split('?');
+ const queryString = params
+ .filter((param) => param.key.trim() !== '')
+ .map(
+ (param) =>
+ `${encodeURIComponent(param.key.trim())}=${encodeURIComponent(
+ param.value,
+ )}`,
+ )
+ .join('&');
+
+ return queryString ? `${baseUrl}?${queryString}` : baseUrl;
+}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/__tests__/useDashboardFetchRequired.test.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/__tests__/useDashboardFetchRequired.test.tsx
new file mode 100644
index 0000000000..e5ad2776b8
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/__tests__/useDashboardFetchRequired.test.tsx
@@ -0,0 +1,58 @@
+import { renderHook } from '@testing-library/react';
+
+import { useDashboardFetchRequired } from '../useDashboardFetchRequired';
+
+const mockUseGetDashboardV2 = jest.fn();
+
+jest.mock(
+ 'pages/DashboardPageV2/DashboardContainer/store/useDashboardStore',
+ () => ({
+ useDashboardStore: (
+ selector: (s: { dashboardId: string }) => unknown,
+ ): unknown => selector({ dashboardId: 'dash-1' }),
+ }),
+);
+
+jest.mock('api/generated/services/dashboard', () => ({
+ useGetDashboardV2: (): unknown => mockUseGetDashboardV2(),
+}));
+
+describe('useDashboardFetchRequired', () => {
+ it('returns the loaded dashboard and its variables', () => {
+ const dashboard = {
+ spec: { variables: [{ name: 'region' }, { name: 'tier' }] },
+ };
+ mockUseGetDashboardV2.mockReturnValue({ data: { data: dashboard } });
+
+ const { result } = renderHook(() => useDashboardFetchRequired());
+
+ expect(result.current.dashboard).toBe(dashboard);
+ expect(result.current.variables).toStrictEqual([
+ { name: 'region' },
+ { name: 'tier' },
+ ]);
+ });
+
+ it('normalizes variables to an empty array when the spec has none', () => {
+ mockUseGetDashboardV2.mockReturnValue({ data: { data: { spec: {} } } });
+
+ const { result } = renderHook(() => useDashboardFetchRequired());
+
+ expect(result.current.variables).toStrictEqual([]);
+ });
+
+ it('throws when used outside a loaded dashboard subtree', () => {
+ mockUseGetDashboardV2.mockReturnValue({ data: undefined });
+
+ // Suppress React's expected render-error logging for this case.
+ const consoleError = jest
+ .spyOn(console, 'error')
+ .mockImplementation(() => undefined);
+
+ expect(() => renderHook(() => useDashboardFetchRequired())).toThrow(
+ /outside a loaded dashboard subtree/,
+ );
+
+ consoleError.mockRestore();
+ });
+});
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useDashboardFetch.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useDashboardFetch.ts
new file mode 100644
index 0000000000..a7361b72ae
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useDashboardFetch.ts
@@ -0,0 +1,40 @@
+import {
+ getDashboardV2,
+ useGetDashboardV2,
+} from 'api/generated/services/dashboard';
+import type { GetDashboardV2QueryError } from 'api/generated/services/dashboard';
+import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
+
+// Instantiation expression pins `TData`/`TError` to the hook's defaults; a plain
+// `ReturnType<typeof useGetDashboardV2>` collapses the generics to `unknown`.
+type GetDashboardV2Query = ReturnType<
+ typeof useGetDashboardV2<
+ Awaited<ReturnType<typeof getDashboardV2>>,
+ GetDashboardV2QueryError
+ >
+>;
+
+export interface UseDashboardFetchResult {
+ dashboard: DashboardtypesGettableDashboardV2DTO | undefined;
+ isLoading: GetDashboardV2Query['isLoading'];
+ isError: GetDashboardV2Query['isError'];
+ error: GetDashboardV2Query['error'];
+ refetch: GetDashboardV2Query['refetch'];
+}
+
+/**
+ * Canonical fetch-only loader for a V2 dashboard by id — shared so the page, panel
+ * editor, and config sections resolve to one react-query cache entry. Exposes just the
+ * raw `dashboard` plus lifecycle; spec derivation (e.g. `variables`) lives in
+ * `useDashboardFetchRequired`, where the dashboard is guaranteed present.
+ */
+export function useDashboardFetch(
+ dashboardId: string,
+): UseDashboardFetchResult {
+ const { data, isLoading, isError, error, refetch } = useGetDashboardV2({
+ id: dashboardId,
+ });
+ const dashboard = data?.data;
+
+ return { dashboard, isLoading, isError, error, refetch };
+}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useDashboardFetchRequired.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useDashboardFetchRequired.ts
new file mode 100644
index 0000000000..8663f37238
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useDashboardFetchRequired.ts
@@ -0,0 +1,47 @@
+import { useMemo } from 'react';
+import type {
+ DashboardtypesGettableDashboardV2DTO,
+ DashboardtypesVariableDTO,
+} from 'api/generated/services/sigNoz.schemas';
+import { useDashboardStore } from 'pages/DashboardPageV2/DashboardContainer/store/useDashboardStore';
+
+import { useDashboardFetch } from './useDashboardFetch';
+import type { UseDashboardFetchResult } from './useDashboardFetch';
+
+export interface UseDashboardFetchRequiredResult {
+ /** Guaranteed present — the hook throws otherwise. */
+ dashboard: DashboardtypesGettableDashboardV2DTO;
+ /** Always an array, so callers skip `?? []` guards. */
+ variables: DashboardtypesVariableDTO[];
+ refetch: UseDashboardFetchResult['refetch'];
+}
+
+/**
+ * Dashboard accessor for components rendered inside a loaded dashboard subtree. The
+ * root pages own the fetch and gate on a resolved dashboard before mounting their
+ * subtree, so this reuses the shared react-query cache entry and throws if the
+ * dashboard is missing — turning a silent `undefined` into a loud programmer error. It
+ * also derives spec collections (`variables`) since the dashboard is guaranteed here.
+ *
+ * Prefer this over `useDashboardFetch` outside the two root pages; the
+ * `signoz/no-dashboard-fetch-outside-root` lint rule enforces the split.
+ */
+export function useDashboardFetchRequired(): UseDashboardFetchRequiredResult {
+ const dashboardId = useDashboardStore((s) => s.dashboardId);
+ const { dashboard, refetch } = useDashboardFetch(dashboardId);
+
+ const variables = useMemo(
+ () => dashboard?.spec?.variables ?? [],
+ [dashboard?.spec?.variables],
+ );
+
+ if (!dashboard) {
+ throw new Error(
+ 'useDashboardFetchRequired was used outside a loaded dashboard subtree — the ' +
+ 'dashboard is undefined. Only call it below a root page that gates rendering ' +
+ 'on useDashboardFetch (DashboardPageV2 / PanelEditorPage).',
+ );
+ }
+
+ return { dashboard, variables, refetch };
+}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardPageV2.tsx b/frontend/src/pages/DashboardPageV2/DashboardPageV2.tsx
index b56f821b46..67cad389fa 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardPageV2.tsx
+++ b/frontend/src/pages/DashboardPageV2/DashboardPageV2.tsx
@@ -1,20 +1,17 @@
import { useParams } from 'react-router-dom';
import { Typography } from '@signozhq/ui/typography';
-import { useGetDashboardV2 } from 'api/generated/services/dashboard';
import Spinner from 'components/Spinner';
import DashboardContainer from './DashboardContainer';
+import { useDashboardFetch } from './DashboardContainer/hooks/useDashboardFetch';
import styles from './DashboardPageV2.module.scss';
function DashboardPageV2(): JSX.Element {
const { dashboardId } = useParams<{ dashboardId: string }>();
- const { data, isLoading, isError, error, refetch } = useGetDashboardV2({
- id: dashboardId,
- });
-
- const dashboard = data?.data;
+ const { dashboard, isLoading, isError, error, refetch } =
+ useDashboardFetch(dashboardId);
if (isLoading) {
return <Spinner tip="Loading dashboard..." />;
diff --git a/frontend/src/pages/DashboardPageV2/PanelEditorPage/PanelEditorPage.tsx b/frontend/src/pages/DashboardPageV2/PanelEditorPage/PanelEditorPage.tsx
index 1fc16bf5b6..1d500733c4 100644
--- a/frontend/src/pages/DashboardPageV2/PanelEditorPage/PanelEditorPage.tsx
+++ b/frontend/src/pages/DashboardPageV2/PanelEditorPage/PanelEditorPage.tsx
@@ -6,12 +6,12 @@ import {
useParams,
} from 'react-router-dom';
import { Typography } from '@signozhq/ui/typography';
-import { useGetDashboardV2 } from 'api/generated/services/dashboard';
import Spinner from 'components/Spinner';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
+import { useDashboardFetch } from '../DashboardContainer/hooks/useDashboardFetch';
import { getPanelDefinition } from '../DashboardContainer/Panels/registry';
import { buildPluginSpec } from '../DashboardContainer/Panels/utils/buildPluginSpec';
import { buildDefaultQueries } from '../DashboardContainer/Panels/utils/buildDefaultQueries';
@@ -40,10 +40,8 @@ function PanelEditorPage(): JSX.Element {
// instead of the saved panel. Lost on refresh/new-tab, which falls back to saved.
const handoffSpec = (state as PanelEditorHandoffState | null)?.editSpec;
- const { data, isLoading, isError, error } = useGetDashboardV2({
- id: dashboardId,
- });
- const dashboard = data?.data;
+ const { dashboard, isLoading, isError, error } =
+ useDashboardFetch(dashboardId);
// 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.