Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/single-select-dashboard-filters.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@hyperdx/common-utils': patch
'@hyperdx/api': patch
'@hyperdx/app': patch
---

feat: Allow configuring dashboard filters as single-select
24 changes: 24 additions & 0 deletions packages/api/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -3504,6 +3504,14 @@
"default": false,
"description": "Widens a required filter's block to every tile on the dashboard. False\n(the default) blocks only the tiles that read the filter: those\nreferencing its variableName, and those its broadcast applies to.\nIgnored unless minSelections is 1.\n",
"example": true
},
"maxSelections": {
"type": "integer",
"enum": [
1
],
"description": "Maximum number of values that can be selected at once. Set to 1 to make\nthe filter single-select. Omit the field for the default multi-select\nbehavior.\n",
"example": 1
}
}
},
Expand Down Expand Up @@ -3586,6 +3594,14 @@
"default": false,
"description": "Widens a required filter's block to every tile on the dashboard. False\n(the default) blocks only the tiles that read the filter: those\nreferencing its variableName, and those its broadcast applies to.\nIgnored unless minSelections is 1.\n",
"example": true
},
"maxSelections": {
"type": "integer",
"enum": [
1
],
"description": "Maximum number of values that can be selected at once. Set to 1 to make\nthe filter single-select. Omit the field for the default multi-select\nbehavior.\n",
"example": 1
}
}
},
Expand Down Expand Up @@ -3671,6 +3687,14 @@
"default": false,
"description": "Widens a required filter's block to every tile on the dashboard. False\n(the default) blocks only the tiles that read the filter: those\nreferencing its variableName, and those its broadcast applies to.\nIgnored unless minSelections is 1.\n",
"example": true
},
"maxSelections": {
"type": "integer",
"enum": [
1
],
"description": "Maximum number of values that can be selected at once. Set to 1 to make\nthe filter single-select. Omit the field for the default multi-select\nbehavior.\n",
"example": 1
}
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2709,6 +2709,47 @@ describe('MCP Dashboard Tools - clickstack_save_dashboard', () => {
}
});

it('round-trips a single-select filter through create and get', async () => {
const sourceId = ctx.traceSource._id.toString();
const createResult = await callTool(
ctx.client!,
'clickstack_save_dashboard',
{
name: 'Single-select filter',
tiles: [traceTile(sourceId)],
filters: [queryFilter({ maxSelections: 1 })],
},
);
expect(createResult.isError).toBeFalsy();
const created = JSON.parse(getFirstText(createResult));
expect(created.filters[0].maxSelections).toBe(1);

const getResult = await callTool(
ctx.client!,
'clickstack_get_dashboard',
{ id: created.id },
);
expect(
JSON.parse(getFirstText(getResult)).filters[0].maxSelections,
).toBe(1);
});

it.each([0, 2])('rejects maxSelections %s', async value => {
const sourceId = ctx.traceSource._id.toString();
const result = await callTool(
ctx.client!,
'clickstack_save_dashboard',
{
name: 'Bad maxSelections',
tiles: [traceTile(sourceId)],
filters: [queryFilter({ maxSelections: value })],
},
);

expect(result.isError).toBe(true);
expect(getFirstText(result)).toContain('maxSelections');
});

it.each([2, -1, 1.5])('rejects minSelections %s', async value => {
const sourceId = ctx.traceSource._id.toString();
const result = await callTool(
Expand Down
29 changes: 29 additions & 0 deletions packages/api/src/mcp/__tests__/dashboards/variables.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,35 @@ describe('resolveDashboardVariables', () => {
expect(resolved.error).toContain('Available variables: (none)');
});

it('rejects several values for a single-select variable', () => {
const resolved = resolveDashboardVariables(
[staticFilter({ maxSelections: 1 })],
[{ name: 'env', values: ['prod', 'staging'] }],
);

if (!('error' in resolved)) throw new Error('expected an error');
expect(resolved.error).toContain('"env"');
expect(resolved.error).toContain('single-select');
});

it('applies one value to a single-select variable', () => {
expect(
resolveDashboardVariables(
[staticFilter({ maxSelections: 1 })],
[{ name: 'env', values: ['prod'] }],
),
).toEqual({
variables: [
{
name: 'env',
expression: undefined,
values: ['prod'],
maxSelections: 1,
},
],
});
});

it('declares a variable for a static filter', () => {
expect(resolveDashboardVariables([staticFilter()], undefined)).toEqual({
variables: [{ name: 'env', expression: undefined, values: [] }],
Expand Down
2 changes: 2 additions & 0 deletions packages/api/src/mcp/prompts/dashboards/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ Apply these before calling clickstack_save_dashboard. Each rule is enforced by t

9e. MAKE A FILTER REQUIRED ONLY WHEN AN UNSCOPED VIEW IS MEANINGLESS. minSelections: 1 blocks the tiles that read the filter - the ones referencing its $variableName, and the ones its broadcast applies to - until the user picks a value. isGlobalRequirement: true widens that to every tile on the dashboard. Consider pairing either form with savedFilterValues so the dashboard opens on a sensible default rather than blocked.

9f. MAKE A FILTER SINGLE-SELECT WHEN A TILE ONLY MAKES SENSE FOR ONE VALUE. maxSelections: 1 limits the dropdown to one value at a time, for example a host picker feeding a per-host detail view.

10. UPDATE IS REPLACE, NOT MERGE. clickstack_save_dashboard with an id overwrites tiles, containers, and filters in their entirety. Call clickstack_get_dashboard first when you only want to add or rename one entry; do not send a partial set or you will silently drop everything you omitted.

11. GROUP RELATED TILES INTO CONTAINERS. REQUIRED at five or more tiles, no exceptions. An ungrouped wall of nine or ten tiles is a readability failure even when each tile is correct in isolation. Containers are the right way to introduce structure; markdown tiles for section labels are not.
Expand Down
10 changes: 10 additions & 0 deletions packages/api/src/mcp/tools/dashboards/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1319,6 +1319,16 @@ const mcpDashboardFilterBaseShape = {
'Widens a REQUIRED filter (minSelections: 1) to block EVERY tile on the dashboard, ' +
'not just the ones that read it. Ignored unless minSelections is 1.',
),
maxSelections: z
.number()
.int()
.min(1)
.max(1)
.optional()
.describe(
'Set to 1 to make this filter SINGLE-SELECT: the user can pick at most one ' +
'value. Omit for the normal multi-select behavior.',
),
};

const mcpQueryExpressionFilterSchema = z
Expand Down
18 changes: 18 additions & 0 deletions packages/api/src/mcp/tools/dashboards/variables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
getDashboardVariableDeclarations,
getDashboardVariableFilters,
getFilterVariableName,
isFilterSingleSelect,
isFilterVariableEnabled,
isStaticListFilter,
} from '@hyperdx/common-utils/dist/filters';
Expand Down Expand Up @@ -101,6 +102,23 @@ export function resolveDashboardVariables(
return { error: optionErrors.join('\n') };
}

// The dashboard can never hold several values for a single-select variable.
const singleSelectNames = new Set(
variables.filter(isFilterSingleSelect).map(variable => variable.name),
);
const singleSelectErrors = variableValues
.filter(
({ name, values }) => values.length > 1 && singleSelectNames.has(name),
)
.map(
({ name }) =>
`Variable "${name}" belongs to a single-select filter (maxSelections: 1) ` +
'and accepts at most one value.',
);
if (singleSelectErrors.length > 0) {
return { error: singleSelectErrors.join('\n') };
}

// Override the default empty selection with the given variableValues
for (const { name, values } of variableValues) {
byName.get(name)!.values = values;
Expand Down
21 changes: 21 additions & 0 deletions packages/api/src/routers/api/__tests__/dashboard.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1210,6 +1210,27 @@ describe('dashboard router', () => {
.expect(400);
});

it('persists maxSelections on create', async () => {
const filter = makeFilter({ maxSelections: 1 });

const created = await agent
.post('/dashboards')
.send({ ...MOCK_DASHBOARD, filters: [filter] })
.expect(200);

expect(created.body.filters).toEqual([filter]);
});

it.each([0, 2, 1.5, '1'])('rejects maxSelections %s', async value => {
await agent
.post('/dashboards')
.send({
...MOCK_DASHBOARD,
filters: [makeFilter({ maxSelections: value })],
})
.expect(400);
});

it('persists a dashboard-wide requirement', async () => {
const filter = makeFilter({
minSelections: 1,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6117,6 +6117,37 @@ describe('External API v2 Dashboards - new format', () => {
});
});

describe('single-select filters', () => {
const variants = [
['QUERY_EXPRESSION', filterInput],
['STATIC_LIST', staticFilterInput],
['PROMETHEUS_LABEL', promqlFilterInput],
] as const;

it.each(variants)(
'accepts a single-select %s filter',
async (_type, makeFilter) => {
const response = await sendFilters([
makeFilter({ maxSelections: 1 }),
]);
expect(response.status).toBe(200);
expect(response.body.data.filters[0].maxSelections).toBe(1);
},
);

it('omits the key from responses for a multi-select filter', async () => {
const response = await sendFilters([filterInput()]);
expect(response.status).toBe(200);
expect(response.body.data.filters[0]).not.toHaveProperty(
'maxSelections',
);
});

it.each([0, 2, 1.5, '1'])('rejects maxSelections %s', async value => {
await expectFilters([filterInput({ maxSelections: value })], 400);
});
});

describe('static-list filters', () => {
it('accepts a static-list filter and round-trips it through GET', async () => {
const response = await sendFilters([staticFilterInput()]);
Expand Down
24 changes: 24 additions & 0 deletions packages/api/src/routers/external-api/v2/dashboards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2055,6 +2055,14 @@ const EXTERNAL_DASHBOARD_PROJECTION = {
* referencing its variableName, and those its broadcast applies to.
* Ignored unless minSelections is 1.
* example: true
* maxSelections:
* type: integer
* enum: [1]
* description: |
* Maximum number of values that can be selected at once. Set to 1 to make
* the filter single-select. Omit the field for the default multi-select
* behavior.
* example: 1
*
* StaticListFilterInput:
* type: object
Expand Down Expand Up @@ -2141,6 +2149,14 @@ const EXTERNAL_DASHBOARD_PROJECTION = {
* referencing its variableName, and those its broadcast applies to.
* Ignored unless minSelections is 1.
* example: true
* maxSelections:
* type: integer
* enum: [1]
* description: |
* Maximum number of values that can be selected at once. Set to 1 to make
* the filter single-select. Omit the field for the default multi-select
* behavior.
* example: 1
*
* PrometheusLabelFilterInput:
* type: object
Expand Down Expand Up @@ -2228,6 +2244,14 @@ const EXTERNAL_DASHBOARD_PROJECTION = {
* referencing its variableName, and those its broadcast applies to.
* Ignored unless minSelections is 1.
* example: true
* maxSelections:
* type: integer
* enum: [1]
* description: |
* Maximum number of values that can be selected at once. Set to 1 to make
* the filter single-select. Omit the field for the default multi-select
* behavior.
* example: 1
*
* Filter:
* allOf:
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/DashboardFilters.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
getPendingFilterValuesVariables,
isFilterGlobalRequirement,
isFilterRequired,
isFilterSingleSelect,
isFilterVariableEnabled,
isQueryExpressionFilter,
isStaticListFilter,
Expand Down Expand Up @@ -186,6 +187,7 @@ const DashboardFilterSelect = ({
loading={isLoading}
// A static list renders in the order its author wrote it.
sort={!isStaticListFilter(filter)}
isMultiSelect={!isFilterSingleSelect(filter)}
onChange={onChange}
data-testid={`dashboard-filter-select-${filter.name}`}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,14 @@ export const DashboardFilterEditForm = ({
{showRequiredFilterOptions && (
<Stack gap="xs">
<Divider my="xs" />
<CheckBoxControlled
Comment thread
pulpdrew marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — Single-select checkbox sits behind showRequiredFilterOptions, but that prop is documented as covering required-filter options only

The prop doc at line 69-70 (and in DashboardFiltersModal/index.tsx:19) says it controls 'the options for marking a filter as required', yet it now also hides the single-select option. Rename it (e.g. showSelectionLimitOptions) or give single-select its own flag, so a caller like ServicesDashboardPage can control the two separately.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

control={control}
name="isSingleSelect"
size="xs"
label="Single select"
description="Only one value can be selected at a time."
data-testid="filter-single-select-checkbox"
/>
<CheckBoxControlled
control={control}
name="isRequired"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,29 @@ describe('DashboardFiltersModal', () => {
expect(screen.getByTestId('filter-required-checkbox')).toBeChecked();
});

it('saves a single-select filter and reopens it checked', async () => {
const { onSaveFilter, user } = renderModal();

await user.click(screen.getByTestId('add-filter-button'));
await selectFilterType(user, 'Static values');
await user.type(screen.getByTestId('filter-name-input'), 'Environment');
await user.type(screen.getByTestId('filter-options-input'), 'prod{Enter}');
await user.click(screen.getByTestId('filter-single-select-checkbox'));
await user.click(screen.getByTestId('save-filter-button'));

await waitFor(() => expect(onSaveFilter).toHaveBeenCalledTimes(1));
const saved: DashboardFilter = onSaveFilter.mock.calls[0][0];
expect(saved.maxSelections).toBe(1);
expect(saved.minSelections).toBeUndefined();

renderModal({ filters: [saved] });
await user.click(
screen.getAllByTestId(`edit-filter-button-${saved.name}`)[0],
);

expect(screen.getByTestId('filter-single-select-checkbox')).toBeChecked();
});

it('offers the requirement scope, unchecked, once the filter is required', async () => {
const { user } = renderModal();

Expand Down
Loading
Loading