Skip to content
Open
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/dashboard-filter-all-option-static-list.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@hyperdx/api': minor
'@hyperdx/app': minor
'@hyperdx/common-utils': minor
---

feat: add an "All" option to static list dashboard filters. Turn on "Include "All" option" in the filter's settings, and its dropdown offers "All", which selects every option. With "All" selected, `$variable` and `$__filter` use every option and `$__conditionalAll` expands to `1=1`, matching Grafana. The external API and MCP accept `allowAll` on static list filters and `all: true` on saved filter values.
13 changes: 13 additions & 0 deletions packages/api/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -1029,6 +1029,14 @@
"example": [
"hdx-oss-dev-api"
]
},
"all": {
"type": "boolean",
"enum": [
true
],
"description": "Set to true to select \"All\"; `values` is then ignored, so send an empty array. Only allowed for filters that set allowAll.\n",
"example": true
}
}
},
Expand Down Expand Up @@ -4378,6 +4386,11 @@
"dev"
]
},
"allowAll": {
"type": "boolean",
"description": "Adds an \"All\" choice to the dropdown, which selects every option.\nOnly allowed on multi-select filters (not with maxSelections 1).\nWith \"All\" selected, `$variableName` and `$__filter` use every\noption, and `$__conditionalAll` expands to 1=1.\n",
"example": true
},
"isBroadcastEnabled": {
"type": "boolean",
"enum": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2638,6 +2638,33 @@ describe('MCP Dashboard Tools - clickstack_save_dashboard', () => {
});
});

it('round-trips allowAll and a saved "all" value', async () => {
const sourceId = ctx.traceSource._id.toString();
const allValue = { type: 'variable', name: 'env', values: [], all: true };

const createResult = await callTool(
ctx.client!,
'clickstack_save_dashboard',
{
name: 'All option round-trip',
tiles: [traceTile(sourceId)],
filters: [staticFilter({ allowAll: true })],
savedFilterValues: [allValue],
},
);
expect(createResult.isError).toBeFalsy();
const created = JSON.parse(getFirstText(createResult));

const getResult = await callTool(
ctx.client!,
'clickstack_get_dashboard',
{ id: created.id },
);
const fetched = JSON.parse(getFirstText(getResult));
expect(fetched.filters[0].allowAll).toBe(true);
expect(fetched.savedFilterValues).toEqual([allValue]);
});

describe('required filters', () => {
const queryFilter = (overrides: Record<string, unknown> = {}) => ({
type: 'QUERY_EXPRESSION' as const,
Expand Down
28 changes: 28 additions & 0 deletions packages/api/src/mcp/__tests__/dashboards/variables.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,34 @@ describe('resolveDashboardVariables', () => {
});
});

it('expands a simulated "All" to every option of a static filter', () => {
expect(
resolveDashboardVariables(
[staticFilter({ allowAll: true })],
[{ name: 'env', values: [], all: true }],
),
).toEqual({
variables: [
{
name: 'env',
expression: undefined,
values: ['dev', 'prod', 'staging'],
all: true,
},
],
});
});

it('rejects a simulated "All" on a filter that does not offer it', () => {
const resolved = resolveDashboardVariables(
[staticFilter()],
[{ name: 'env', values: [], all: true }],
);

if (!('error' in resolved)) throw new Error('expected an error');
expect(resolved.error).toContain('does not offer "All"');
});

it('rejects a value outside a static filter options', () => {
const resolved = resolveDashboardVariables(
[staticFilter()],
Expand Down
13 changes: 8 additions & 5 deletions packages/api/src/mcp/prompts/dashboards/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -982,9 +982,10 @@ For configType: "sql" tiles, write ClickHouse SQL with template macros:
$__filter(<expression>, $<var>) Matches the expression against the variable's selected
values (e.g \`<expression> IN ('a', 'b')\`). Expands to
1=1 when nothing is selected.
$__conditionalAll(<cond>, $<var>) Applies the condition only while the variable has a
selection, and expands to 1=1 otherwise. Use it for
operators IN cannot express, such as NOT IN or LIKE.
$__conditionalAll(<cond>, $<var>) Applies the condition only while specific values are
selected, and expands to 1=1 when nothing or "All" is
selected. Use it for operators IN cannot express, such
as NOT IN or LIKE.
The variable argument carries the leading $, exactly as a bare reference would.

QUERY PARAMETERS (ClickHouse parameterized syntax):
Expand Down Expand Up @@ -1201,9 +1202,10 @@ Query-expression filter shape:
variableName The token tiles reference. Must match [a-zA-Z][a-zA-Z0-9_]* and be at most 64 characters, and must be unique across the dashboard's variable-enabled filters. Defaults to the display name with whitespace turned into underscores and remaining illegal characters dropped, so "Service Name" becomes $Service_Name and a label with nothing token-safe in it (a non-ASCII name, for instance) must set this field explicitly. Rejected when isVariableEnabled is not true.

Static filter shape:
{ type: "STATIC_LIST", name, options, variableName? }
{ type: "STATIC_LIST", name, options, allowAll?, variableName? }

options 1-1000 unique, non-empty strings the dropdown offers, in display order.
allowAll Set true to add an "All" choice to the dropdown, which selects every option. Multi-select filters only (rejected with maxSelections: 1). With "All" selected, $variableName and $__filter use every option, and $__conditionalAll expands to 1=1.

No expression, sourceId, where, or appliesToSourceIds: the list is hand-authored, nothing is queried. It has no mode flags either. A static filter is always variable-only, so tiles must reference $variableName for the selection to have any effect. Pass the column explicitly in macros ($__filter(<expression>, $<variableName>)); the one-argument $__filter($var) form fails because the filter has no expression of its own.

Expand Down Expand Up @@ -1280,7 +1282,7 @@ THREE WAYS TO REFERENCE A VARIABLE
The one-argument form $__filter($service) reuses the filter's own expression, but it fails when the filter does not carry one, so pass the expression explicitly whenever the tile's column differs from the filter's.

$__conditionalAll(<condition>, $<variableName>)
Applies the condition verbatim while something is selected, and 1=1 otherwise. Use it for anything IN cannot express. The condition itself should reference the variable.
Applies the condition verbatim while specific values are selected, and 1=1 when nothing or "All" (allowAll filters) is selected. Use it for anything IN cannot express. The condition itself should reference the variable.
where: "$__conditionalAll(ServiceName NOT IN ($service), $service)"

$variableName / \${variableName} / \${variableName:format}
Expand Down Expand Up @@ -1350,6 +1352,7 @@ VALIDATING
clickstack_query_tile and clickstack_query_tiles expand variables with an EMPTY selection by default, which is what a freshly-opened dashboard looks like. Optionally, pass variableValues to check that a tile narrows correctly once something is picked:
variableValues: [{ name: "service", values: ["checkout"] }]
For a STATIC_LIST filter's variable, every supplied value must be one of the filter's declared options; the dashboard UI can never select anything else, so other values are rejected.
For a filter with allowAll, simulate "All" with { name, values: [], all: true }.
Both tools report variable problems under "warnings". Alerts on a tile always evaluate with every variable empty, so a tile carrying an alert must stay correct with nothing selected.

== TABLE TILE LINKING (config.onClick) ==
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 @@ -1777,6 +1777,12 @@ const mcpStaticListFilterSchema = z
options: StaticListDashboardFilterSchema.shape.options.describe(
'The values the dropdown offers, in display order, without duplicates.',
),
allowAll: StaticListDashboardFilterSchema.shape.allowAll.describe(
'Set true to add an "All" choice to the dropdown, which selects every ' +
'option. Multi-select filters only (rejected with maxSelections: 1). ' +
'With "All" selected, $variableName and $__filter use every option, ' +
'and $__conditionalAll expands to 1=1.',
),
})
.describe(
'A variable-only dashboard filter whose dropdown offers a hand-authored options ' +
Expand Down Expand Up @@ -2163,6 +2169,10 @@ const mcpVariableSavedFilterValueSchema =
values: variableValueShape.values.describe(
'Selected values for the variable, e.g. ["api", "web"].',
),
all: variableValueShape.all.describe(
'Set true to save "All" as the selection; `values` is then ignored ' +
'(pass []). Only for filters that set allowAll.',
),
});

const adhocValueShape = externalAdhocSavedFilterValueSchema.shape;
Expand Down
44 changes: 39 additions & 5 deletions packages/api/src/mcp/tools/dashboards/variables.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
filterSupportsAllValue,
getDashboardVariableDeclarations,
getDashboardVariableFilters,
getFilterVariableName,
Expand All @@ -19,6 +20,7 @@ import type {
SourceKind,
} from '@hyperdx/common-utils/dist/types';
import { isFilterSingleSelect } from '@hyperdx/common-utils/dist/variables';
import { expandAllSelections } from '@hyperdx/common-utils/dist/variableSelection';
import { z } from 'zod/v3';

import type { McpContext } from '@/mcp/tools/types';
Expand Down Expand Up @@ -63,6 +65,13 @@ export const mcpVariableValuesParam = z
'For a DATA_SOURCE or CONNECTION variable, pass one source or connection ID; it ' +
"overrides the dashboard's saved selection.",
),
all: z
.literal(true)
.optional()
.describe(
'Set true to simulate "All" on a filter that sets allowAll; ' +
'`values` is then ignored (pass []).',
),
}),
)
.describe(
Expand Down Expand Up @@ -117,11 +126,30 @@ export function resolveDashboardVariables(
};
}

// Only filters that opt in offer "All", so the dashboard can't produce it elsewhere
const allCapableNames = new Set(
getDashboardVariableFilters(filters)
.filter(({ filter }) => filterSupportsAllValue(filter))
.map(({ name }) => name),
);
const allErrors = variableValues
.filter(({ name, all }) => all && !allCapableNames.has(name))
.map(
({ name }) =>
`Variable "${name}" belongs to a filter that does not offer "All"; ` +
'pass specific values, or set allowAll on the filter.',
);
if (allErrors.length > 0) {
return { error: allErrors.join('\n') };
}
// `values` is ignored for "All", so it isn't checked below
const explicitValues = variableValues.filter(({ all }) => !all);

// A static filter's dropdown can only ever offer its declared options, so a
// simulated selection outside them can never occur in the UI — reject it as
// a typo rather than running a query the dashboard cannot produce.
const staticOptionsByName = buildStaticOptionsByName(filters);
const optionErrors = variableValues.flatMap(({ name, values }) => {
const optionErrors = explicitValues.flatMap(({ name, values }) => {
const options = staticOptionsByName.get(name);
if (!options) return [];
const invalid = values.filter(value => !options.includes(value));
Expand All @@ -141,7 +169,7 @@ export function resolveDashboardVariables(
const singleSelectNames = new Set(
variables.filter(isFilterSingleSelect).map(variable => variable.name),
);
const singleSelectErrors = variableValues
const singleSelectErrors = explicitValues
.filter(
({ name, values }) => values.length > 1 && singleSelectNames.has(name),
)
Expand All @@ -155,12 +183,18 @@ export function resolveDashboardVariables(
}

// Override the default empty selection with the given variableValues
for (const { name, values } of variableValues) {
for (const { name, values, all } of variableValues) {
const variable = byName.get(name);
if (variable) variable.values = values;
if (!variable) continue;
if (all) {
variable.all = true;
variable.values = [];
} else {
variable.values = values;
}
}

return { variables };
return { variables: expandAllSelections(variables, staticOptionsByName) };
}

/** The team's sources and connections that a reference variable may select. */
Expand Down
68 changes: 68 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 @@ -1203,6 +1203,74 @@ describe('dashboard router', () => {
});
});

describe('"All" option', () => {
const makeStaticFilter = (overrides = {}) => ({
id: new Types.ObjectId().toString(),
type: 'STATIC_LIST' as const,
name: 'Environment',
options: ['prod', 'staging'],
isBroadcastEnabled: false,
isVariableEnabled: true,
variableName: 'env',
...overrides,
});
const allValue = { type: 'variable', name: 'env', values: [], all: true };

it('persists allowAll and a saved "all" value', async () => {
const filter = makeStaticFilter({ allowAll: true });

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

const stored = await Dashboard.findById(created.body.id).lean();
expect(stored?.filters).toEqual([filter]);
expect(stored?.savedFilterValues).toEqual([allValue]);
});

it('drops a saved "all" value for a filter without allowAll', async () => {
const created = await agent
.post('/dashboards')
.send({
...MOCK_DASHBOARD,
filters: [makeStaticFilter()],
savedFilterValues: [allValue],
})
.expect(200);

const stored = await Dashboard.findById(created.body.id).lean();
expect(stored?.savedFilterValues).toEqual([]);
});

it('saves a dashboard whose saved "all" value went stale', async () => {
const filter = makeStaticFilter({ allowAll: true });
const created = await agent
.post('/dashboards')
.send({
...MOCK_DASHBOARD,
filters: [filter],
savedFilterValues: [allValue],
})
.expect(200);

await agent
.patch(`/dashboards/${created.body.id}`)
.send({
...created.body,
filters: [{ ...filter, allowAll: false }],
})
.expect(200);

const stored = await Dashboard.findById(created.body.id).lean();
expect(stored?.savedFilterValues).toEqual([]);
});
});

describe('required filters', () => {
const makeFilter = (overrides = {}) => ({
id: new Types.ObjectId().toString(),
Expand Down
16 changes: 16 additions & 0 deletions packages/api/src/routers/api/dashboards.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { dropUnsupportedAllValues } from '@hyperdx/common-utils/dist/dashboardFilterValues';
import {
getVariableReferenceError,
validateDashboardFilterModes,
Expand Down Expand Up @@ -190,6 +191,12 @@ router.post(
// client-supplied value would otherwise persist and hand the caller's
// dashboard to the provisioner.
const dashboard = _.omit(req.body, 'provisioned');
if (dashboard.savedFilterValues) {
dashboard.savedFilterValues = dropUnsupportedAllValues(
dashboard.filters ?? [],
dashboard.savedFilterValues,
);
}

const filterError =
getVariableReferenceError(req.body.tiles, req.body.filters) ??
Expand Down Expand Up @@ -237,6 +244,15 @@ router.patch(
// Nulls survive: the schema's optional fields are `.nullable()`, and a
// null still signals field removal downstream.
const updates = DashboardWithoutIdSchema.partial().parse(req.body);
// Dropped rather than rejected: the UI resends the stored defaults on
// every save, so a stale "all" left after allowAll is turned off would
// otherwise block every later edit.
if (updates.savedFilterValues) {
updates.savedFilterValues = dropUnsupportedAllValues(
updates.filters ?? dashboard.filters ?? [],
updates.savedFilterValues,
);
}

const filterError =
// Only references this update adds are checked, so a filter edit
Expand Down
Loading
Loading