SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
fix(dashboard-v2): variable selection (default reset + multiselect commit-on-close) (#12254)
Ashwin Bhatkalaabe59103d79
diff --git a/frontend/src/components/NewSelect/CustomMultiSelect.tsx b/frontend/src/components/NewSelect/CustomMultiSelect.tsxindex 3b4a7586d1..72ece7b7dc 100644--- a/frontend/src/components/NewSelect/CustomMultiSelect.tsx+++ b/frontend/src/components/NewSelect/CustomMultiSelect.tsx@@ -713,6 +713,19 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({}};+ // Row buttons select without letting the wrapping checkbox also toggle:+ // stop propagation, run the selection, then drop the active/chip focus.+ const selectFromButton = (+ e: React.MouseEvent,+ source: 'option' | 'checkbox',+ ): void => {+ e.stopPropagation();+ e.preventDefault();+ handleItemSelection(source);+ setActiveChipIndex(-1);+ setActiveIndex(-1);+ };+return (<divkey={option.value || `option-${index}`}@@ -726,13 +739,6 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({selected: isSelected,active: isActive,})}- onClick={(e): void => {- e.stopPropagation();- e.preventDefault();- handleItemSelection('option');- setActiveChipIndex(-1);- setActiveIndex(-1);- }}onKeyDown={(e): void => {if ((e.key === 'Enter' || e.key === SPACEKEY) && isActive) {e.stopPropagation();@@ -752,13 +758,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({<Checkboxvalue={isSelected}className="option-checkbox"- onClick={(e): void => {- e.stopPropagation();- e.preventDefault();- handleItemSelection('checkbox');- setActiveChipIndex(-1);- setActiveIndex(-1);- }}+ onClick={(e): void => selectFromButton(e, 'checkbox')}><div className="option-content"><Typography.Text truncate={1} className="option-label-text">@@ -768,11 +768,19 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({<div className="option-badge">{capitalize(option.type)}</div>)}{option.value && ensureValidOption(option.value) && (- <Button type="text" className="only-btn">+ <Button+ type="text"+ className="only-btn"+ onClick={(e): void => selectFromButton(e, 'option')}+ >{currentToggleTagValue({ option: option.value })}</Button>)}- <Button type="text" className="toggle-btn">+ <Button+ type="text"+ className="toggle-btn"+ onClick={(e): void => selectFromButton(e, 'checkbox')}+ >Toggle</Button></div>diff --git a/frontend/src/components/NewSelect/__test__/CustomMultiSelect.comprehensive.test.tsx b/frontend/src/components/NewSelect/__test__/CustomMultiSelect.comprehensive.test.tsxindex 6b29585308..cb0767acf2 100644--- a/frontend/src/components/NewSelect/__test__/CustomMultiSelect.comprehensive.test.tsx+++ b/frontend/src/components/NewSelect/__test__/CustomMultiSelect.comprehensive.test.tsx@@ -656,6 +656,28 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {});});+ it('UI-03b: clicking "Only" selects just that value', async () => {+ renderWithVirtuoso(+ <CustomMultiSelect+ options={mockOptions}+ onChange={mockOnChange}+ value={['frontend']}+ />,+ );++ const combobox = screen.getByRole('combobox');+ await user.click(combobox);++ // "Only" renders for each non-selected row (hidden until hover via CSS,+ // which jsdom doesn't apply, so it's clickable here).+ const onlyButtons = await screen.findAllByText('Only');+ mockOnChange.mockClear();+ await user.click(onlyButtons[0]);++ expect(mockOnChange).toHaveBeenCalledTimes(1);+ expect(mockOnChange.mock.calls[0][0]).toStrictEqual(['backend']);+ });+it('UI-04: Should display values with loading info at bottom', async () => {renderWithVirtuoso(<CustomMultiSelect options={mockOptions} onChange={mockOnChange} loading />,@@ -1449,7 +1471,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {expect(mockOnChange).toHaveBeenCalledWith(['custom-value'],- [{ label: 'custom-value', value: 'custom-value' }],+ [{ label: 'custom-value', value: 'custom-value', type: 'custom' }],);});});diff --git a/frontend/src/components/NewSelect/__test__/prioritizeOrder.check.test.ts b/frontend/src/components/NewSelect/__test__/prioritizeOrder.check.test.tsnew file mode 100644index 0000000000..8adbf5be6b--- /dev/null+++ b/frontend/src/components/NewSelect/__test__/prioritizeOrder.check.test.ts@@ -0,0 +1,21 @@+import { prioritizeOrAddOptionForMultiSelect } from '../utils';++describe('prioritizeOrAddOptionForMultiSelect ordering', () => {+ it('hoists selected then preserves the given (sorted) order in each group', () => {+ const sorted = ['apple', 'banana', 'cherry', 'date', 'elderberry'].map(+ (v) => ({ label: v, value: v }),+ );+ // selection given in a non-sorted order on purpose+ const result = prioritizeOrAddOptionForMultiSelect(sorted, [+ 'date',+ 'banana',+ ]);+ expect(result.map((o) => o.value)).toStrictEqual([+ 'banana',+ 'date',+ 'apple',+ 'cherry',+ 'elderberry',+ ]);+ });+});diff --git a/frontend/src/components/NewSelect/styles.scss b/frontend/src/components/NewSelect/styles.scssindex 0c334d0ff7..4d17d5ceb5 100644--- a/frontend/src/components/NewSelect/styles.scss+++ b/frontend/src/components/NewSelect/styles.scss@@ -458,7 +458,9 @@ $custom-border-color: #2c3044;.option-item {padding: 8px 12px;- cursor: pointer;+ // Not the whole row — only the checkbox and the action buttons get the+ // pointer (set below), so inert areas don't look clickable.+ cursor: default;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;@@ -494,6 +496,13 @@ $custom-border-color: #2c3044;.option-checkbox {width: 100%;+ cursor: default;++ // The checkbox button is the only pointer target on the left; the label+ // still toggles on click but keeps a default cursor.+ > button {+ cursor: pointer;+ }// @signozhq/ui Checkbox renders children inside a <label> that is// content-sized by default. Make it fill the row (min-width: 0 lets it@@ -535,9 +544,9 @@ $custom-border-color: #2c3044;}}- // Size the buttons to the row's resting content height (20px) and fully- // override antd's default 32px Button box, so revealing them on hover- // never changes the row height.+ // "Only"/"All" is the primary action — a filled pill that reads as a+ // button; "Toggle" is a secondary hint in plain text. Sized to the row's+ // resting height so revealing them on hover never shifts it..only-btn,.toggle-btn {display: none;@@ -545,14 +554,39 @@ $custom-border-color: #2c3044;justify-content: center;height: 18px;min-height: 0;- padding: 0 6px;font-size: 12px;line-height: 1;- border: none;box-shadow: none;+ }- &:hover {- background-color: unset;+ .only-btn {+ padding: 4px 8px;+ // Black interior + a visible border so the pill stands out clearly+ // against the near-black row when revealed on hover.+ border: 1px solid var(--l3-border);+ border-radius: 3px;+ background-color: var(--bg-ink-500, #0b0c0e);+ color: var(--l1-foreground);+ cursor: pointer;+ }++ .toggle-btn {+ padding: 0 6px;+ border: none;+ background-color: transparent;+ color: var(--l2-foreground);+ cursor: pointer;+ }++ // Toggle appears over the checkbox area; "Only/All" takes over the row+ // content and hides Toggle there (higher specificity wins).+ &:hover {+ .toggle-btn {+ display: flex;+ }++ .option-badge {+ display: none;}}@@ -560,6 +594,7 @@ $custom-border-color: #2c3044;.only-btn {display: flex;}+.toggle-btn {display: none;}@@ -569,15 +604,6 @@ $custom-border-color: #2c3044;}}}-- .option-checkbox:hover {- .toggle-btn {- display: flex;- }- .option-badge {- display: none;- }- }}.loading-container {diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/VariableForm/useVariableForm.test.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/VariableForm/useVariableForm.test.tsnew file mode 100644index 0000000000..d6bac0cbc2--- /dev/null+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/VariableForm/useVariableForm.test.ts@@ -0,0 +1,147 @@+import { act, renderHook, type RenderHookResult } from '@testing-library/react';++import {+ DYNAMIC_SIGNALS,+ emptyVariableFormModel,+ VARIABLE_SORT,+ type VariableFormModel,+} from '../variableFormModel';+import { useVariableForm, type UseVariableForm } from './useVariableForm';++// Mock the store (its full slice graph is huge to transform and irrelevant here;+// the hook only reads dashboardId + variableValues for the Test-Run payload).+jest.mock('../../../store/useDashboardStore', () => ({+ useDashboardStore: (selector: (state: unknown) => unknown): unknown =>+ selector({ dashboardId: undefined, variableValues: {} }),+}));++function initial(overrides?: Partial<VariableFormModel>): VariableFormModel {+ return {+ ...emptyVariableFormModel(),+ type: 'QUERY',+ name: 'svc',+ defaultValue: 'foo',+ ...overrides,+ };+}++const args = (+ init: VariableFormModel,+): Parameters<typeof useVariableForm>[0] => ({+ initial: init,+ siblings: [],+ isNew: false,+ onSave: jest.fn(),+});++// The hook resets its form state whenever the `initial` reference changes (open a+// different variable), so the args must be stable across re-renders — otherwise a+// fresh `initial` each render would loop the reset effect. Real callers memoize+// `initial`; mirror that here by building the props once and closing over them.+const renderForm = (+ props: Parameters<typeof useVariableForm>[0],+): RenderHookResult<UseVariableForm, unknown> =>+ renderHook(() => useVariableForm(props));++describe('useVariableForm default reset — QUERY (on Test Run)', () => {+ it('keeps the default when only the sort order changes', () => {+ const { result } = renderForm(args(initial()));++ act(() => result.current.setRawPreview(['foo', 'bar']));+ expect(result.current.defaultValue).toBe('foo');++ // order-only change doesn't touch the preview values, so it must not reset+ act(() => result.current.set({ sort: VARIABLE_SORT.DESC }));+ expect(result.current.defaultValue).toBe('foo');+ });++ it('resets the default when a Test Run returns values that no longer contain it', () => {+ const { result } = renderForm(args(initial()));++ act(() => result.current.setRawPreview(['foo', 'bar']));+ expect(result.current.defaultValue).toBe('foo');++ act(() => result.current.setRawPreview(['bar', 'baz']));+ expect(result.current.defaultValue).toBe('');+ });++ it('keeps the default when a Test Run still contains it', () => {+ const { result } = renderForm(args(initial()));++ act(() => result.current.setRawPreview(['foo', 'bar']));+ act(() => result.current.setRawPreview(['foo', 'baz', 'qux']));+ expect(result.current.defaultValue).toBe('foo');+ });++ it('keeps the default when a re-run yields the same values (no actual change)', () => {+ const { result } = renderForm(args(initial({ defaultValue: 'bar' })));++ act(() => result.current.setRawPreview(['foo', 'bar']));+ // same set again — re-running an unchanged query must not disturb the default+ act(() => result.current.setRawPreview(['foo', 'bar']));+ expect(result.current.defaultValue).toBe('bar');+ });+});++describe('useVariableForm default reset — DYNAMIC (on attribute/signal change)', () => {+ const dynamic = (overrides?: Partial<VariableFormModel>): VariableFormModel =>+ initial({+ type: 'DYNAMIC',+ dynamicAttribute: 'service.name',+ dynamicSignal: DYNAMIC_SIGNALS[1],+ ...overrides,+ });++ it('does not reset on the passive edit-open auto-fetch', () => {+ // The auto-fetch populates the preview without going through onDynamicChange,+ // so opening an existing variable must never clear its saved default.+ const { result } = renderForm(args(dynamic({ defaultValue: 'zzz' })));++ act(() => result.current.setRawPreview(['foo', 'bar']));+ expect(result.current.defaultValue).toBe('zzz');+ });++ it('resets when the attribute changes', () => {+ const { result } = renderForm(args(dynamic()));++ act(() => result.current.onDynamicChange({ dynamicAttribute: 'host.name' }));+ expect(result.current.defaultValue).toBe('');+ });++ it('resets when the signal changes', () => {+ const { result } = renderForm(args(dynamic()));++ act(() =>+ result.current.onDynamicChange({ dynamicSignal: DYNAMIC_SIGNALS[2] }),+ );+ expect(result.current.defaultValue).toBe('');+ });++ it('keeps the default when the attribute is set to the same value', () => {+ const { result } = renderForm(args(dynamic()));++ act(() =>+ result.current.onDynamicChange({ dynamicAttribute: 'service.name' }),+ );+ expect(result.current.defaultValue).toBe('foo');+ });+});++describe('useVariableForm default reset — CUSTOM (on options edit)', () => {+ const custom = (overrides?: Partial<VariableFormModel>): VariableFormModel =>+ initial({ type: 'CUSTOM', ...overrides });++ it('resets when the edited options no longer contain the default', () => {+ const { result } = renderForm(args(custom()));++ act(() => result.current.onCustomChange('bar, baz'));+ expect(result.current.defaultValue).toBe('');+ });++ it('keeps the default when the edited options still contain it', () => {+ const { result } = renderForm(args(custom()));++ act(() => result.current.onCustomChange('foo, bar, baz'));+ expect(result.current.defaultValue).toBe('foo');+ });+});diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/VariableForm/useVariableForm.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/VariableForm/useVariableForm.tsindex 000691e859..8036bd7a8f 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/VariableForm/useVariableForm.ts+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/DashboardSettings/Variables/VariableForm/useVariableForm.ts@@ -1,4 +1,4 @@-import { useEffect, useMemo, useState } from 'react';+import { useEffect, useMemo, useRef, useState } from 'react';import logEvent from 'api/common/logEvent';import { commaValuesParser } from 'lib/dashboardVariables/customCommaValuesParser';import { DashboardDetailEvents } from 'pages/DashboardPageV2/constants/events';@@ -92,6 +92,35 @@ export function useVariableForm({[rawPreview, model.sort],);+ // QUERY: drop a now-invalid default when the user re-runs the query and the+ // returned values actually change. The query preview is populated only by the+ // manual "Test Run" (never on edit-open), so keying off `rawPreview` here is+ // effectively "on run"; the signature guard skips a re-run that yields the same+ // values so a still-valid default is left untouched. DYNAMIC/CUSTOM resets are+ // handled in their change handlers instead (see below).+ const lastQueryPreviewRef = useRef<string | null>(null);+ useEffect(() => {+ lastQueryPreviewRef.current = null;+ }, [initial]);++ useEffect(() => {+ if (model.type !== 'QUERY' || rawPreview.length === 0) {+ return;+ }+ const optionValues = rawPreview.map(String);+ const signature = JSON.stringify(optionValues);+ if (signature === lastQueryPreviewRef.current) {+ return;+ }++ lastQueryPreviewRef.current = signature;++ // Clear a now-invalid default; resolution falls back to the first option/ALL.+ setDefaultValue((current) =>+ current && !optionValues.includes(current) ? '' : current,+ );+ }, [rawPreview, model.type]);+const existingNames = useMemo(() => siblings.map((v) => v.name), [siblings]);const existingDynamicAttributes = useMemo(@@ -140,12 +169,28 @@ export function useVariableForm({const onCustomChange = (value: string): void => {set({ customValue: value });- setRawPreview(commaValuesParser(value));+ const parsed = commaValuesParser(value);+ setRawPreview(parsed);++ const optionValues = parsed.map(String);+ setDefaultValue((current) =>+ current && !optionValues.includes(current) ? '' : current,+ );};// In add mode, mirror the selected attribute into the name until the user// edits the name themselves (matches the V1 dynamic-variable behaviour).const onDynamicChange = (patch: Partial<VariableFormModel>): void => {+ const attributeChanged =+ patch.dynamicAttribute !== undefined &&+ patch.dynamicAttribute !== model.dynamicAttribute;+ const signalChanged =+ patch.dynamicSignal !== undefined &&+ patch.dynamicSignal !== model.dynamicSignal;+ if (attributeChanged || signalChanged) {+ setDefaultValue('');+ }+if (isNew && !nameTouched && patch.dynamicAttribute) {set({ ...patch, name: patch.dynamicAttribute });} else {diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/VariablesBar.module.scss b/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/VariablesBar.module.scssindex 58c26acbff..c3378e7e02 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/VariablesBar.module.scss+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/VariablesBar.module.scss@@ -95,6 +95,38 @@max-height: none !important;overflow: hidden !important;}++ // Let the first tag shrink and truncate so the layout stays [tag…][+N]. Without+ // this the "+N" overflow item wins the row's space and the (longer) first tag+ // gets offset/clipped — visible after switching a value from ALL to a subset.+ :global(.ant-select-selection-overflow-item) {+ min-width: 0;+ }++ :global(.ant-select-selection-item) {+ min-width: 0;+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+ }++ // The shared .custom-multiselect forces the search box to a 60px floor+ // (min-width: 60px !important). In this narrow variable pill that reserved+ // width is what offsets/clips the tag row, so collapse it here — the extra+ // selectors out-specify the shared rule's !important. It still expands to fit+ // what the user types while the dropdown is open.+ :global(.ant-select-selector .ant-select-selection-search) {+ min-width: 0 !important;+ flex: 0 1 auto;+ }++ :global(+ .ant-select-selector+ .ant-select-selection-search+ .ant-select-selection-search-input+ ) {+ min-width: 0 !important;+ }}.overflowTooltip {diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/components/VariableSelector/VariableSelector.module.scss b/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/components/VariableSelector/VariableSelector.module.scssindex e44c345bc1..520e897ecf 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/components/VariableSelector/VariableSelector.module.scss+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/components/VariableSelector/VariableSelector.module.scss@@ -1,7 +1,7 @@.variableItem {position: relative;display: flex;- width: 160px;+ width: 180px;flex-direction: column;padding-top: 7px;}diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/components/selectors/ValueSelector.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/components/selectors/ValueSelector.tsxindex 9c2214eaa3..8786120314 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/components/selectors/ValueSelector.tsx+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/components/selectors/ValueSelector.tsx@@ -1,10 +1,11 @@-import { useMemo } from 'react';+import { useMemo, useState } from 'react';import logEvent from 'api/common/logEvent';import { CustomMultiSelect, CustomSelect } from 'components/NewSelect';import type { OptionData } from 'components/NewSelect/types';import { DashboardDetailEvents } from 'pages/DashboardPageV2/constants/events';import type { VariableSelection } from '../../selectionTypes';+import { areSelectionsEqual } from '../../utils/resolveVariableSelection';import styles from '../../VariablesBar.module.scss';interface ValueSelectorProps {@@ -16,17 +17,13 @@ interface ValueSelectorProps {loading?: boolean;selection: VariableSelection;onChange: (selection: VariableSelection) => void;+ emptyFallback: VariableSelection;testId?: string;/** Option-fetch error surfaced in the dropdown, with a retry action. */errorMessage?: string | null;onRetry?: () => void;}-/**- * Single/multi value picker for Custom/Query/Dynamic variables. Reuses the- * shared NewSelect components, which provide search, the "ALL" option and- * apply-on-close batching (so multi-select edits don't cascade per toggle).- */function ValueSelector({options,variableType,@@ -35,6 +32,7 @@ function ValueSelector({loading,selection,onChange,+ emptyFallback,testId,errorMessage,onRetry,@@ -44,56 +42,92 @@ function ValueSelector({[options],);+ // All-selected → the full option set so CustomMultiSelect engages its "all"+ // path (overlay when closed, every option checked when open). The scalar+ // sentinel would instead render a literal `__ALL__` row.+ const committedValues = useMemo<string[]>(+ () =>+ selection.allSelected+ ? options+ : (Array.isArray(selection.value) ? selection.value : []).map(String),+ [selection, options],+ );++ // Buffer edits while the dropdown is open; the committed selection is shown+ // when closed. This defers the dependent cascade to a single commit-on-close.+ const [isOpen, setIsOpen] = useState(false);+ const [draft, setDraft] = useState<string[]>(committedValues);++ const commit = (values: string[]): void => {+ // CustomMultiSelect emits the full value set when ALL is picked.+ const isAll =+ showAllOption &&+ options.length > 0 &&+ options.every((option) => values.includes(option));+ const next: VariableSelection =+ values.length === 0 ? emptyFallback : { value: values, allSelected: isAll };++ // Closing without actually changing the selection must not re-fire onChange —+ // that would needlessly re-cascade to dependent variables/panels.+ if (areSelectionsEqual(next, selection)) {+ return;+ }++ void logEvent(+ DashboardDetailEvents.VariableValueSelected,+ { variableType, multiSelect: true, selectionCount: values.length },+ 'track',+ true,+ );+ onChange(next);+ };+if (multiSelect) {- // All-selected → hand CustomMultiSelect the full option set so it engages its- // "all" path (overlay when closed, every option checked when open). Passing the- // scalar sentinel instead makes it render a literal `__ALL__` row.- const value = selection.allSelected- ? options- : (Array.isArray(selection.value) ? selection.value : []).map(String);return (<CustomMultiSelectclassName={styles.control}data-testid={testId}options={optionData}- value={value}+ value={isOpen ? draft : committedValues}loading={loading}errorMessage={errorMessage}onRetry={onRetry}showSearch+ allowClearplaceholder="Select value"- maxTagCount={2}- maxTagTextLength={20}+ maxTagCount={1}+ maxTagTextLength={10}+ maxTagPlaceholder={(omitted): string => `+${omitted.length}`}// Offer ALL only once options load, else a concrete value reads as "all".enableAllSelection={showAllOption && options.length > 0}+ onDropdownVisibleChange={(open): void => {+ if (open) {+ setDraft(committedValues);+ setIsOpen(true);+ return;+ }++ setIsOpen(false);+ commit(draft);+ }}onChange={(next): void => {const values = Array.isArray(next)? next.map(String): next? [String(next)]: [];- void logEvent(- DashboardDetailEvents.VariableValueSelected,- { variableType, multiSelect: true, selectionCount: values.length },- 'track',- true,- );- if (values.length === 0) {- onChange({ value: [], allSelected: false });- return;- }- // CustomMultiSelect emits the full value set when ALL is picked.- const isAll =- showAllOption &&- options.length > 0 &&- options.every((option) => values.includes(option));- onChange({ value: values, allSelected: isAll });+ setDraft(values);}}onClear={(): void => {void logEvent(DashboardDetailEvents.VariableMultiSelectCleared, {variableType,});- onChange({ value: [], allSelected: false });+ setDraft([]);+ // A clear on the closed control falls back to the default immediately;+ // while open it just empties the draft (committed on close).+ if (!isOpen) {+ onChange(emptyFallback);+ }}}/>);diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/components/selectors/VariableValueControl.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/components/selectors/VariableValueControl.tsxindex 9c1a69a674..7821d44938 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/components/selectors/VariableValueControl.tsx+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/components/selectors/VariableValueControl.tsx@@ -1,3 +1,5 @@+import { useMemo } from 'react';+import {VARIABLE_TYPE_EVENT_LABEL,type VariableFormModel,@@ -6,6 +8,10 @@ import type {VariableSelection,VariableSelectionMap,} from '../../selectionTypes';+import {+ reconcileWithOptions,+ resolveDefaultSelection,+} from '../../utils/resolveVariableSelection';import { useAutoSelect } from '../../hooks/useAutoSelect';import ValueSelector from './ValueSelector';import { useVariableOptions } from '../../hooks/useVariableOptions';@@ -44,6 +50,12 @@ function VariableValueControl({useAutoSelect(variable, options, selection, onAutoSelect);+ // The selection to fall back to when the multi-select closes empty+ const emptyFallback = useMemo<VariableSelection>(() => {+ const seed = resolveDefaultSelection(variable);+ return reconcileWithOptions(variable, seed, options) ?? seed;+ }, [variable, options]);+return (<ValueSelectoroptions={options}@@ -55,6 +67,7 @@ function VariableValueControl({onRetry={onRetry}selection={selection}onChange={onChange}+ emptyFallback={emptyFallback}testId={`variable-select-${variable.name}`}/>);diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/utils/resolveVariableSelection.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/utils/resolveVariableSelection.tsindex e9753d0e9f..dc03baf487 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/utils/resolveVariableSelection.ts+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/VariablesBar/utils/resolveVariableSelection.ts@@ -184,3 +184,20 @@ export function configuredDefaultValue(}return configuredDefault(model.defaultValue);}++/** Normalize a selection's value to an order-independent key of its members. */+function valueSetKey(value: SelectedVariableValue): string {+ const list = Array.isArray(value) ? value : value == null ? [] : [value];+ return list.map(String).sort().join('||');+}++/** True when two selections carry the same ALL flag and the same value set. */+export function areSelectionsEqual(+ a: VariableSelection,+ b: VariableSelection,+): boolean {+ return (+ !!a.allSelected === !!b.allSelected &&+ valueSetKey(a.value) === valueSetKey(b.value)+ );+}