:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(dashboards): reject breakdown colors the dashboard cannot use (#96310)
Thomas Obermüllera77e3eebb7be
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex 431c239b12b2..42cd84e9d4d0 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -2262,6 +2262,33 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):duplicated_dashboard = Dashboard.objects.get(id=response["id"])self.assertEqual(duplicated_dashboard.breakdown_colors, breakdown_colors)+ @parameterized.expand(+ [+ ("object_keyed_by_breakdown_value", {"Chrome": "preset-1"}, "breakdown_colors"),+ # Belongs at the endpoint, not in the field matrix: the update is a PATCH, so DRF+ # resolves the entry's required keys against the serializer's partial flag. An error+ # inside an entry names the entry and the key, so the attr carries a path.+ ("entry_missing_the_color_token", [{"breakdownValue": "Chrome"}], "breakdown_colors__0__colorToken"),+ ]+ )+ def test_dashboard_rejects_breakdown_colors_that_cannot_apply(+ self, _name: str, value: object, expected_attr: str+ ) -> None:+ # Wiring guard: the viewset has to reject the value rather than store it. The shape matrix+ # lives in products/dashboards/backend/api/test/test_dashboard_filters_validation.py, which+ # needs no database.+ dashboard = Dashboard.objects.create(team=self.team, name="Dashboard", created_by=self.user)++ _, response = self.dashboard_api.update_dashboard(+ dashboard.pk,+ {"breakdown_colors": value},+ expected_status=status.HTTP_400_BAD_REQUEST,+ )++ self.assertEqual(response["attr"], expected_attr)+ dashboard.refresh_from_db()+ self.assertEqual(dashboard.breakdown_colors, [])+def test_dashboard_duplication_copies_variables(self):"""Test that variables are copied during duplication"""variable = InsightVariable.objects.create(diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 2242ef59f340..bb81d73446f0 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -113,6 +113,7 @@ from products.dashboards.backend.api.dashboard_template_json_schema_parser imporfrom products.dashboards.backend.api.widget_openapi_serializers import (WIDGET_BATCH_ADD_OPENAPI_HELP,AddDashboardWidgetRequestOpenApi,+ BreakdownColorConfigSerializer,DashboardWidgetConfigField,PatchedDashboardOpenApiSerializer,UpdateDashboardWidgetRequestOpenApi,@@ -1211,6 +1212,28 @@ class DashboardCustomizationSerializer(serializers.Serializer):)+class BreakdownColorsField(serializers.ListField):+ # The child serializer decides whether an entry is valid, but it does not decide what gets+ # stored or returned. It rewrites an entry rather than describing it: it drops a key it does not+ # declare and adds a null for a declared key the entry omits. So both directions validate the+ # entries and then use them as given.+ #+ # This matters in both directions because the dashboard saves the whole color list back. Letting+ # the child shape a write would drop a key the frontend persists before this serializer learns+ # about it, and the loss would only surface as colors disappearing after a later save.+ #+ # The write validates through an unbound list, not through `self.child`. DRF resolves `required`+ # against the root serializer's partial flag, and a dashboard PATCH is partial, so a bound child+ # skips a missing key instead of failing it, and this field would store the entry as given. An+ # unbound list is its own root, so the required keys hold on a PATCH too.+ def to_internal_value(self, data: Any) -> Any:+ serializers.ListField(child=BreakdownColorConfigSerializer()).to_internal_value(data)+ return data++ def to_representation(self, data: Any) -> Any:+ return data++class DashboardMetadataSerializer(DashboardBasicSerializer):filters = serializers.SerializerMethodField()variables = serializers.SerializerMethodField()@@ -1219,7 +1242,15 @@ class DashboardMetadataSerializer(DashboardBasicSerializer):effective_restriction_level = serializers.SerializerMethodField()access_control_version = serializers.SerializerMethodField()is_shared = serializers.BooleanField(source="is_sharing_enabled", read_only=True, required=False)- breakdown_colors = serializers.JSONField(required=False, help_text="Custom color mapping for breakdown values.")+ breakdown_colors = BreakdownColorsField(+ child=BreakdownColorConfigSerializer(),+ required=False,+ allow_null=True,+ help_text=(+ "Colors pinned to specific breakdown values across the dashboard's tiles. "+ "A list of entries, not an object keyed by breakdown value. Send an empty list to clear them."+ ),+ )data_color_theme_id = serializers.IntegerField(required=False, allow_null=True, help_text="ID of the color theme used for chart visualizations.")diff --git a/products/dashboards/backend/api/test/test_dashboard_filters_validation.py b/products/dashboards/backend/api/test/test_dashboard_filters_validation.pyindex 71f1c0d5390b..f653f00d62b8 100644--- a/products/dashboards/backend/api/test/test_dashboard_filters_validation.py+++ b/products/dashboards/backend/api/test/test_dashboard_filters_validation.py@@ -1,5 +1,6 @@from django.test import SimpleTestCase+from parameterized import parameterizedfrom rest_framework import serializersfrom products.dashboards.backend.api.dashboard import DashboardSerializer@@ -61,3 +62,97 @@ class TestDashboardTileFiltersOverridesValidation(SimpleTestCase):def test_allows_clearing_tile_filters_overrides(self):result = DashboardSerializer._extract_display_defaults({"filters_overrides": None})assert result["filters_overrides"] is None+++class TestDashboardBreakdownColorsValidation(SimpleTestCase):+ def _field(self, partial: bool) -> serializers.Field:+ # Read the field off the serializer rather than building one, so the cases bind to the shape+ # the endpoint actually validates against.+ #+ # Both modes, because DRF resolves `required` against the root serializer's partial flag+ # and a dashboard PATCH is partial.+ return DashboardSerializer(partial=partial).fields["breakdown_colors"]++ @parameterized.expand(+ [+ # Both keys decide which value gets which color, so an entry without them can never+ # apply. Callers wrote all of these while the field accepted any JSON.+ ("entry_under_snake_case_keys", [{"breakdown_value": "good", "color": "#36a854"}]),+ ("hex_color_under_the_wrong_key", [{"breakdownValue": "good", "color": "#36a854"}]),+ ("entry_missing_the_color_token", [{"breakdownValue": "Chrome"}]),+ ("entry_missing_the_breakdown_value", [{"colorToken": "preset-1"}]),+ ("bare_breakdown_values", ["Chrome", "Firefox"]),+ ("empty_entry", [{}]),+ # A token names a slot in the color theme, so any other string resolves to nothing.+ # getColorFromToken parses the N out of `preset-N`, and a hex value yields+ # theme['preset-NaN'].+ ("hex_color_token", [{"breakdownValue": "Chrome", "colorToken": "#3fb950"}]),+ ("unresolvable_color_token", [{"breakdownValue": "Chrome", "colorToken": "blue"}]),+ ("color_token_slot_zero", [{"breakdownValue": "Chrome", "colorToken": "preset-0"}]),+ ("color_token_non_ascii_digits", [{"breakdownValue": "Chrome", "colorToken": "preset-١"}]),+ # The two shapes that crashed the dashboard scene on every load.+ ("object_keyed_by_breakdown_value", {"Chrome": "preset-1"}),+ ("empty_object", {}),+ ]+ )+ def test_rejects(self, _name: str, value: object) -> None:+ for partial in (False, True):+ with self.subTest(partial=partial), self.assertRaises(serializers.ValidationError):+ self._field(partial=partial).run_validation(value)++ @parameterized.expand(+ [+ ("minimal_entry", [{"breakdownValue": "Chrome", "colorToken": "preset-1"}]),+ (+ "every_key",+ [+ {+ "breakdownValue": "Chrome",+ "colorToken": "preset-1",+ "breakdownType": "event",+ "breakdownProperty": "event::$browser",+ "source": "manual",+ }+ ],+ ),+ # A cleared color keeps its entry with a null token, so the key is required but a value+ # for it is not.+ ("null_color_token", [{"breakdownValue": "Chrome", "colorToken": None}]),+ # A breakdown value can legitimately be the empty string.+ ("blank_breakdown_value", [{"breakdownValue": "", "colorToken": "preset-1"}]),+ # A theme may carry more slots than the default palette, and the token wraps past its+ # end, so the pattern must not cap the index.+ ("color_token_past_the_default_palette", [{"breakdownValue": "Chrome", "colorToken": "preset-99"}]),+ (+ "null_breakdown_property",+ [{"breakdownValue": "Chrome", "colorToken": "preset-1", "breakdownProperty": None}],+ ),+ ("null_source", [{"breakdownValue": "Chrome", "colorToken": "preset-1", "source": None}]),+ # Clearing every color, and the nullable column's own value.+ ("empty_list", []),+ ("null", None),+ ]+ )+ def test_accepts(self, _name: str, value: object) -> None:+ for partial in (False, True):+ with self.subTest(partial=partial):+ assert self._field(partial=partial).run_validation(value) == value++ @parameterized.expand([("write", "run_validation"), ("read", "to_representation")])+ def test_keeps_a_key_the_child_serializer_does_not_declare_on(self, _name: str, method: str) -> None:+ # The child serializer rewrites an entry rather than describing it, so neither direction may+ # run entries through it. Without this, `somethingAddedLater` disappears and the entry gains+ # an explicit null `breakdownProperty`, which is data loss on a perfectly valid entry.+ #+ # Both directions matter because the dashboard saves the whole color list back, so a key+ # dropped on write is gone from a round trip even when the read preserves it.+ entries = [+ {+ "breakdownValue": "Chrome",+ "colorToken": "preset-1",+ "source": "manual",+ "somethingAddedLater": "kept",+ }+ ]++ assert getattr(self._field(partial=False), method)(entries) == entriesdiff --git a/products/dashboards/backend/api/widget_openapi_serializers.py b/products/dashboards/backend/api/widget_openapi_serializers.pyindex a5f605b5576a..d5ab3b752331 100644--- a/products/dashboards/backend/api/widget_openapi_serializers.py+++ b/products/dashboards/backend/api/widget_openapi_serializers.py@@ -10,6 +10,7 @@ from products.dashboards.backend.widget_specs.openapi import (WIDGET_BATCH_ADD_OPENAPI_HELP,WIDGET_CONFIG_SERIALIZERS,AddDashboardWidgetRequestOpenApi,+ BreakdownColorConfigSerializer,DashboardPatchTileOpenApiSerializer,DashboardPatchWidgetOpenApiSerializer,DashboardWidgetConfigField,@@ -22,6 +23,7 @@ from products.dashboards.backend.widget_specs.openapi import (__all__ = ["AddDashboardWidgetRequestOpenApi",+ "BreakdownColorConfigSerializer","DashboardPatchTileOpenApiSerializer","DashboardPatchWidgetOpenApiSerializer","DashboardWidgetConfigField",diff --git a/products/dashboards/backend/widget_specs/openapi.py b/products/dashboards/backend/widget_specs/openapi.pyindex 24630e08b16d..7acb94fec8cc 100644--- a/products/dashboards/backend/widget_specs/openapi.py+++ b/products/dashboards/backend/widget_specs/openapi.py@@ -273,6 +273,55 @@ class DashboardFiltersOpenApiSerializer(serializers.Serializer):)+class BreakdownColorConfigSerializer(serializers.Serializer):+ breakdownValue = serializers.CharField(+ allow_blank=True,+ help_text="The breakdown value this color applies to, as it appears in the chart legend.",+ )+ # A token names a slot in the dashboard's color theme, not a color. getColorFromToken parses the+ # N out and indexes the theme with it, so any other string yields theme['preset-NaN'], which is+ # undefined. The pattern rather than a fixed range, because a theme may carry more slots than the+ # default palette and the token wraps past its end.+ #+ # The slot starts at 1 and its digits must be ASCII. getColorFromToken wraps the index as+ # ((N - 1) % slots) + 1, so `preset-0` reads theme['preset-0'], and JavaScript parseInt reads+ # another script's digits as NaN.+ colorToken = serializers.RegexField(+ r"^preset-[1-9][0-9]*$",+ allow_null=True,+ help_text=(+ "Palette slot to color the value with, as `preset-1` upwards. Not a CSS color: a hex "+ "value is rejected. Null leaves the value on its default color."+ ),+ )+ breakdownType = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="Breakdown type the value came from, such as `event`, `person`, `session`, or `cohort`.",+ )+ # Null means the same as omitted for both keys below: the frontend reads+ # `breakdownProperty != null` for property scoping, and treats an entry with no source as a+ # manual pin. So an explicit null must not fail a write.+ breakdownProperty = serializers.CharField(+ required=False,+ allow_null=True,+ help_text=(+ "Breakdown property the color is scoped to, so the color applies only to tiles that break "+ "down by that property. Omit to apply it under every property."+ ),+ )+ # `source` is also the name of a Field attribute on the Serializer base class, which mypy reads as+ # a shadowed assignment. SerializerMetaclass pops every declared field out of the class namespace,+ # so the base attribute survives and the entry key stays `source`, which is what the frontend+ # persists.+ source = serializers.ChoiceField( # type: ignore[assignment]+ choices=["auto", "manual"],+ required=False,+ allow_null=True,+ help_text="`manual` for a color a person picked, `auto` for one the dashboard assigned.",+ )++class PatchedDashboardOpenApiSerializer(serializers.Serializer):"""OpenAPI-only PATCH body for dashboards (agents/MCP).@@ -287,9 +336,14 @@ class PatchedDashboardOpenApiSerializer(serializers.Serializer):required=False,help_text="Dashboard-level filters (date range and properties) applied across all tiles as the source of truth.",)- breakdown_colors = serializers.JSONField(+ breakdown_colors = serializers.ListField(+ child=BreakdownColorConfigSerializer(),required=False,- help_text="Custom color mapping for breakdown values.",+ allow_null=True,+ help_text=(+ "Colors pinned to specific breakdown values across the dashboard's tiles. "+ "A list of entries, not an object keyed by breakdown value. Send an empty list to clear them."+ ),)data_color_theme_id = serializers.IntegerField(required=False,diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex ddd2163681d3..89549e813f5d 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -422,6 +422,44 @@ export type DashboardApiPersistedVariables = { [key: string]: unknown } | nullexport type DashboardApiTilesItem = { [key: string]: unknown }+/**+ * * `auto` - auto+ * * `manual` - manual+ */+export type BreakdownColorConfigSourceEnumApi =+ (typeof BreakdownColorConfigSourceEnumApi)[keyof typeof BreakdownColorConfigSourceEnumApi]++export const BreakdownColorConfigSourceEnumApi = {+ Auto: 'auto',+ Manual: 'manual',+} as const++export interface BreakdownColorConfigApi {+ /** The breakdown value this color applies to, as it appears in the chart legend. */+ breakdownValue: string+ /**+ * Palette slot to color the value with, as `preset-1` upwards. Not a CSS color: a hex value is rejected. Null leaves the value on its default color.+ * @nullable+ * @pattern ^preset-[1-9][0-9]*$+ */+ colorToken: string | null+ /**+ * Breakdown type the value came from, such as `event`, `person`, `session`, or `cohort`.+ * @nullable+ */+ breakdownType?: string | null+ /**+ * Breakdown property the color is scoped to, so the color applies only to tiles that break down by that property. Omit to apply it under every property.+ * @nullable+ */+ breakdownProperty?: string | null+ /** `manual` for a color a person picked, `auto` for one the dashboard assigned.+ *+ * * `auto` - auto+ * * `manual` - manual */+ source?: BreakdownColorConfigSourceEnumApi | null+}+/*** * `tight` - tight* * `condensed` - condensed@@ -508,8 +546,11 @@ export interface DashboardApi {readonly filters: DashboardApiFilters/** @nullable */readonly variables: DashboardApiVariables- /** Custom color mapping for breakdown values. */- breakdown_colors?: unknown+ /**+ * Colors pinned to specific breakdown values across the dashboard's tiles. A list of entries, not an object keyed by breakdown value. Send an empty list to clear them.+ * @nullable+ */+ breakdown_colors?: BreakdownColorConfigApi[] | null/*** ID of the color theme used for chart visualizations.* @nullable@@ -1112,8 +1153,11 @@ export interface PatchedPatchedDashboardOpenApiApi {pinned?: boolean/** Dashboard-level filters (date range and properties) applied across all tiles as the source of truth. */filters?: DashboardFiltersOpenApiApi- /** Custom color mapping for breakdown values. */- breakdown_colors?: unknown+ /**+ * Colors pinned to specific breakdown values across the dashboard's tiles. A list of entries, not an object keyed by breakdown value. Send an empty list to clear them.+ * @nullable+ */+ breakdown_colors?: BreakdownColorConfigApi[] | null/*** ID of the color theme used for chart visualizations.* @nullablediff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.tsindex eb89dc663acd..afbce5c3b6d8 100644--- a/products/dashboards/frontend/generated/api.zod.ts+++ b/products/dashboards/frontend/generated/api.zod.ts@@ -271,6 +271,7 @@ export const DashboardTemplatesCopyBetweenProjectsCreateBody = /* @__PURE__ */ zexport const dashboardsCreateBodyNameMax = 400+export const dashboardsCreateBodyBreakdownColorsItemColorTokenRegExp = new RegExp('^preset-[1-9][0-9]\*$')export const dashboardsCreateBodyDeleteInsightsDefault = falseexport const DashboardsCreateBody = /* @__PURE__ */ zod@@ -280,7 +281,46 @@ export const DashboardsCreateBody = /* @__PURE__ */ zodpinned: zod.boolean().optional(),last_accessed_at: zod.iso.datetime({ offset: true }).nullish(),deleted: zod.boolean().optional(),- breakdown_colors: zod.unknown().optional().describe('Custom color mapping for breakdown values.'),+ breakdown_colors: zod+ .array(+ zod.object({+ breakdownValue: zod+ .string()+ .describe('The breakdown value this color applies to, as it appears in the chart legend.'),+ colorToken: zod+ .string()+ .regex(dashboardsCreateBodyBreakdownColorsItemColorTokenRegExp)+ .nullable()+ .describe(+ 'Palette slot to color the value with, as `preset-1` upwards. Not a CSS color: a hex value is rejected. Null leaves the value on its default color.'+ ),+ breakdownType: zod+ .string()+ .nullish()+ .describe(+ 'Breakdown type the value came from, such as `event`, `person`, `session`, or `cohort`.'+ ),+ breakdownProperty: zod+ .string()+ .nullish()+ .describe(+ 'Breakdown property the color is scoped to, so the color applies only to tiles that break down by that property. Omit to apply it under every property.'+ ),+ source: zod+ .union([+ zod.enum(['auto', 'manual']).describe('\* `auto` - auto\n\* `manual` - manual'),+ zod.null(),+ ])+ .optional()+ .describe(+ '`manual` for a color a person picked, `auto` for one the dashboard assigned.\n\n\* `auto` - auto\n\* `manual` - manual'+ ),+ })+ )+ .nullish()+ .describe(+ "Colors pinned to specific breakdown values across the dashboard's tiles. A list of entries, not an object keyed by breakdown value. Send an empty list to clear them."+ ),data_color_theme_id: zod.number().nullish().describe('ID of the color theme used for chart visualizations.'),tags: zod.array(zod.unknown()).optional(),restriction_level: zod@@ -334,6 +374,7 @@ export const DashboardsCollaboratorsCreateBody = /* @__PURE__ */ zod.object({export const dashboardsUpdateBodyNameMax = 400+export const dashboardsUpdateBodyBreakdownColorsItemColorTokenRegExp = new RegExp('^preset-[1-9][0-9]\*$')export const dashboardsUpdateBodyDeleteInsightsDefault = falseexport const DashboardsUpdateBody = /* @__PURE__ */ zod@@ -343,7 +384,46 @@ export const DashboardsUpdateBody = /* @__PURE__ */ zodpinned: zod.boolean().optional(),last_accessed_at: zod.iso.datetime({ offset: true }).nullish(),deleted: zod.boolean().optional(),- breakdown_colors: zod.unknown().optional().describe('Custom color mapping for breakdown values.'),+ breakdown_colors: zod+ .array(+ zod.object({+ breakdownValue: zod+ .string()+ .describe('The breakdown value this color applies to, as it appears in the chart legend.'),+ colorToken: zod+ .string()+ .regex(dashboardsUpdateBodyBreakdownColorsItemColorTokenRegExp)+ .nullable()+ .describe(+ 'Palette slot to color the value with, as `preset-1` upwards. Not a CSS color: a hex value is rejected. Null leaves the value on its default color.'+ ),+ breakdownType: zod+ .string()+ .nullish()+ .describe(+ 'Breakdown type the value came from, such as `event`, `person`, `session`, or `cohort`.'+ ),+ breakdownProperty: zod+ .string()+ .nullish()+ .describe(+ 'Breakdown property the color is scoped to, so the color applies only to tiles that break down by that property. Omit to apply it under every property.'+ ),+ source: zod+ .union([+ zod.enum(['auto', 'manual']).describe('\* `auto` - auto\n\* `manual` - manual'),+ zod.null(),+ ])+ .optional()+ .describe(+ '`manual` for a color a person picked, `auto` for one the dashboard assigned.\n\n\* `auto` - auto\n\* `manual` - manual'+ ),+ })+ )+ .nullish()+ .describe(+ "Colors pinned to specific breakdown values across the dashboard's tiles. A list of entries, not an object keyed by breakdown value. Send an empty list to clear them."+ ),data_color_theme_id: zod.number().nullish().describe('ID of the color theme used for chart visualizations.'),tags: zod.array(zod.unknown()).optional(),restriction_level: zod@@ -388,6 +468,8 @@ export const DashboardsUpdateBody = /* @__PURE__ */ zodexport const dashboardsPartialUpdateBodyNameMax = 400+export const dashboardsPartialUpdateBodyBreakdownColorsItemColorTokenRegExp = new RegExp('^preset-[1-9][0-9]\*$')+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneLimitDefault = 25export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneLimitMax = 50@@ -479,7 +561,46 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod.describe('Dashboard-level filters (date range and properties) applied across all tiles as the source of truth.'),- breakdown_colors: zod.unknown().optional().describe('Custom color mapping for breakdown values.'),+ breakdown_colors: zod+ .array(+ zod.object({+ breakdownValue: zod+ .string()+ .describe('The breakdown value this color applies to, as it appears in the chart legend.'),+ colorToken: zod+ .string()+ .regex(dashboardsPartialUpdateBodyBreakdownColorsItemColorTokenRegExp)+ .nullable()+ .describe(+ 'Palette slot to color the value with, as `preset-1` upwards. Not a CSS color: a hex value is rejected. Null leaves the value on its default color.'+ ),+ breakdownType: zod+ .string()+ .nullish()+ .describe(+ 'Breakdown type the value came from, such as `event`, `person`, `session`, or `cohort`.'+ ),+ breakdownProperty: zod+ .string()+ .nullish()+ .describe(+ 'Breakdown property the color is scoped to, so the color applies only to tiles that break down by that property. Omit to apply it under every property.'+ ),+ source: zod+ .union([+ zod.enum(['auto', 'manual']).describe('\* `auto` - auto\n\* `manual` - manual'),+ zod.null(),+ ])+ .optional()+ .describe(+ '`manual` for a color a person picked, `auto` for one the dashboard assigned.\n\n\* `auto` - auto\n\* `manual` - manual'+ ),+ })+ )+ .nullish()+ .describe(+ "Colors pinned to specific breakdown values across the dashboard's tiles. A list of entries, not an object keyed by breakdown value. Send an empty list to clear them."+ ),data_color_theme_id: zod.number().nullish().describe('ID of the color theme used for chart visualizations.'),tags: zod.array(zod.string()).optional(),restriction_level: zod@@ -3476,6 +3597,9 @@ export const DashboardsBulkUpdateTagsCreateBody = /* @__PURE__ */ zod.object({export const dashboardsCreateFromTemplateJsonCreateBodyNameMax = 400+export const dashboardsCreateFromTemplateJsonCreateBodyBreakdownColorsItemColorTokenRegExp = new RegExp(+ '^preset-[1-9][0-9]\*$'+)export const dashboardsCreateFromTemplateJsonCreateBodyDeleteInsightsDefault = falseexport const DashboardsCreateFromTemplateJsonCreateBody = /* @__PURE__ */ zod@@ -3485,7 +3609,46 @@ export const DashboardsCreateFromTemplateJsonCreateBody = /* @__PURE__ */ zodpinned: zod.boolean().optional(),last_accessed_at: zod.iso.datetime({ offset: true }).nullish(),deleted: zod.boolean().optional(),- breakdown_colors: zod.unknown().optional().describe('Custom color mapping for breakdown values.'),+ breakdown_colors: zod+ .array(+ zod.object({+ breakdownValue: zod+ .string()+ .describe('The breakdown value this color applies to, as it appears in the chart legend.'),+ colorToken: zod+ .string()+ .regex(dashboardsCreateFromTemplateJsonCreateBodyBreakdownColorsItemColorTokenRegExp)+ .nullable()+ .describe(+ 'Palette slot to color the value with, as `preset-1` upwards. Not a CSS color: a hex value is rejected. Null leaves the value on its default color.'+ ),+ breakdownType: zod+ .string()+ .nullish()+ .describe(+ 'Breakdown type the value came from, such as `event`, `person`, `session`, or `cohort`.'+ ),+ breakdownProperty: zod+ .string()+ .nullish()+ .describe(+ 'Breakdown property the color is scoped to, so the color applies only to tiles that break down by that property. Omit to apply it under every property.'+ ),+ source: zod+ .union([+ zod.enum(['auto', 'manual']).describe('\* `auto` - auto\n\* `manual` - manual'),+ zod.null(),+ ])+ .optional()+ .describe(+ '`manual` for a color a person picked, `auto` for one the dashboard assigned.\n\n\* `auto` - auto\n\* `manual` - manual'+ ),+ })+ )+ .nullish()+ .describe(+ "Colors pinned to specific breakdown values across the dashboard's tiles. A list of entries, not an object keyed by breakdown value. Send an empty list to clear them."+ ),data_color_theme_id: zod.number().nullish().describe('ID of the color theme used for chart visualizations.'),tags: zod.array(zod.unknown()).optional(),restriction_level: zod@@ -3535,6 +3698,9 @@ export const DashboardsCreateFromTemplateJsonCreateBody = /* @__PURE__ */ zod*/export const dashboardsCreateUnlistedDashboardCreateBodyNameMax = 400+export const dashboardsCreateUnlistedDashboardCreateBodyBreakdownColorsItemColorTokenRegExp = new RegExp(+ '^preset-[1-9][0-9]\*$'+)export const dashboardsCreateUnlistedDashboardCreateBodyDeleteInsightsDefault = falseexport const DashboardsCreateUnlistedDashboardCreateBody = /* @__PURE__ */ zod@@ -3544,7 +3710,46 @@ export const DashboardsCreateUnlistedDashboardCreateBody = /* @__PURE__ */ zodpinned: zod.boolean().optional(),last_accessed_at: zod.iso.datetime({ offset: true }).nullish(),deleted: zod.boolean().optional(),- breakdown_colors: zod.unknown().optional().describe('Custom color mapping for breakdown values.'),+ breakdown_colors: zod+ .array(+ zod.object({+ breakdownValue: zod+ .string()+ .describe('The breakdown value this color applies to, as it appears in the chart legend.'),+ colorToken: zod+ .string()+ .regex(dashboardsCreateUnlistedDashboardCreateBodyBreakdownColorsItemColorTokenRegExp)+ .nullable()+ .describe(+ 'Palette slot to color the value with, as `preset-1` upwards. Not a CSS color: a hex value is rejected. Null leaves the value on its default color.'+ ),+ breakdownType: zod+ .string()+ .nullish()+ .describe(+ 'Breakdown type the value came from, such as `event`, `person`, `session`, or `cohort`.'+ ),+ breakdownProperty: zod+ .string()+ .nullish()+ .describe(+ 'Breakdown property the color is scoped to, so the color applies only to tiles that break down by that property. Omit to apply it under every property.'+ ),+ source: zod+ .union([+ zod.enum(['auto', 'manual']).describe('\* `auto` - auto\n\* `manual` - manual'),+ zod.null(),+ ])+ .optional()+ .describe(+ '`manual` for a color a person picked, `auto` for one the dashboard assigned.\n\n\* `auto` - auto\n\* `manual` - manual'+ ),+ })+ )+ .nullish()+ .describe(+ "Colors pinned to specific breakdown values across the dashboard's tiles. A list of entries, not an object keyed by breakdown value. Send an empty list to clear them."+ ),data_color_theme_id: zod.number().nullish().describe('ID of the color theme used for chart visualizations.'),tags: zod.array(zod.unknown()).optional(),restriction_level: zoddiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex db0a766485c1..ca3f2ad2e9ce 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14167,6 +14167,44 @@ export namespace Schemas {state: string | null;}+ /**+ * * `auto` - auto+ * * `manual` - manual+ */+ export type BreakdownColorConfigSourceEnum = typeof BreakdownColorConfigSourceEnum[keyof typeof BreakdownColorConfigSourceEnum];+++ export const BreakdownColorConfigSourceEnum = {+ Auto: 'auto',+ Manual: 'manual',+ } as const;++ export interface BreakdownColorConfig {+ /** The breakdown value this color applies to, as it appears in the chart legend. */+ breakdownValue: string;+ /**+ * Palette slot to color the value with, as `preset-1` upwards. Not a CSS color: a hex value is rejected. Null leaves the value on its default color.+ * @nullable+ * @pattern ^preset-[1-9][0-9]*$+ */+ colorToken: string | null;+ /**+ * Breakdown type the value came from, such as `event`, `person`, `session`, or `cohort`.+ * @nullable+ */+ breakdownType?: string | null;+ /**+ * Breakdown property the color is scoped to, so the color applies only to tiles that break down by that property. Omit to apply it under every property.+ * @nullable+ */+ breakdownProperty?: string | null;+ /** `manual` for a color a person picked, `auto` for one the dashboard assigned.+ *+ * * `auto` - auto+ * * `manual` - manual */+ source?: BreakdownColorConfigSourceEnum | null;+ }+export interface BreakdownItem {label: string;value: string | number;@@ -21445,8 +21483,11 @@ export namespace Schemas {readonly filters: DashboardFilters;/** @nullable */readonly variables: DashboardVariables;- /** Custom color mapping for breakdown values. */- breakdown_colors?: unknown;+ /**+ * Colors pinned to specific breakdown values across the dashboard's tiles. A list of entries, not an object keyed by breakdown value. Send an empty list to clear them.+ * @nullable+ */+ breakdown_colors?: BreakdownColorConfig[] | null;/*** ID of the color theme used for chart visualizations.* @nullable@@ -66279,8 +66320,11 @@ export namespace Schemas {pinned?: boolean;/** Dashboard-level filters (date range and properties) applied across all tiles as the source of truth. */filters?: DashboardFiltersOpenApi;- /** Custom color mapping for breakdown values. */- breakdown_colors?: unknown;+ /**+ * Colors pinned to specific breakdown values across the dashboard's tiles. A list of entries, not an object keyed by breakdown value. Send an empty list to clear them.+ * @nullable+ */+ breakdown_colors?: BreakdownColorConfig[] | null;/*** ID of the color theme used for chart visualizations.* @nullablediff --git a/services/mcp/src/generated/dashboards/api.ts b/services/mcp/src/generated/dashboards/api.tsindex 371e9ac7796f..23b280bfafee 100644--- a/services/mcp/src/generated/dashboards/api.ts+++ b/services/mcp/src/generated/dashboards/api.ts@@ -100,6 +100,7 @@ export const DashboardsCreateQueryParams = () => zod.object({export const dashboardsCreateBodyNameMax = 400+export const dashboardsCreateBodyBreakdownColorsItemColorTokenRegExp = new RegExp('^preset-[1-9][0-9]\*$')export const dashboardsCreateBodyDeleteInsightsDefault = falseexport const DashboardsCreateBody = () => zod@@ -107,7 +108,46 @@ export const DashboardsCreateBody = () => zodname: zod.string().max(dashboardsCreateBodyNameMax).nullish(),description: zod.string().optional(),pinned: zod.boolean().optional(),- breakdown_colors: zod.unknown().optional().describe('Custom color mapping for breakdown values.'),+ breakdown_colors: zod+ .array(+ zod.object({+ breakdownValue: zod+ .string()+ .describe('The breakdown value this color applies to, as it appears in the chart legend.'),+ colorToken: zod+ .string()+ .regex(dashboardsCreateBodyBreakdownColorsItemColorTokenRegExp)+ .nullable()+ .describe(+ 'Palette slot to color the value with, as `preset-1` upwards. Not a CSS color: a hex value is rejected. Null leaves the value on its default color.'+ ),+ breakdownType: zod+ .string()+ .nullish()+ .describe(+ 'Breakdown type the value came from, such as `event`, `person`, `session`, or `cohort`.'+ ),+ breakdownProperty: zod+ .string()+ .nullish()+ .describe(+ 'Breakdown property the color is scoped to, so the color applies only to tiles that break down by that property. Omit to apply it under every property.'+ ),+ source: zod+ .union([+ zod.enum(['auto', 'manual']).describe('\* `auto` - auto\n\* `manual` - manual'),+ zod.null(),+ ])+ .optional()+ .describe(+ '`manual` for a color a person picked, `auto` for one the dashboard assigned.\n\n\* `auto` - auto\n\* `manual` - manual'+ ),+ })+ )+ .nullish()+ .describe(+ "Colors pinned to specific breakdown values across the dashboard's tiles. A list of entries, not an object keyed by breakdown value. Send an empty list to clear them."+ ),data_color_theme_id: zod.number().nullish().describe('ID of the color theme used for chart visualizations.'),tags: zod.array(zod.unknown()).optional(),restriction_level: zod@@ -200,6 +240,8 @@ export const DashboardsPartialUpdateQueryParams = () => zod.object({export const dashboardsPartialUpdateBodyNameMax = 400+export const dashboardsPartialUpdateBodyBreakdownColorsItemColorTokenRegExp = new RegExp('^preset-[1-9][0-9]\*$')+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneLimitDefault = 25export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneOneLimitMax = 50@@ -289,7 +331,46 @@ export const DashboardsPartialUpdateBody = () => zod.describe('Dashboard-level filters (date range and properties) applied across all tiles as the source of truth.'),- breakdown_colors: zod.unknown().optional().describe('Custom color mapping for breakdown values.'),+ breakdown_colors: zod+ .array(+ zod.object({+ breakdownValue: zod+ .string()+ .describe('The breakdown value this color applies to, as it appears in the chart legend.'),+ colorToken: zod+ .string()+ .regex(dashboardsPartialUpdateBodyBreakdownColorsItemColorTokenRegExp)+ .nullable()+ .describe(+ 'Palette slot to color the value with, as `preset-1` upwards. Not a CSS color: a hex value is rejected. Null leaves the value on its default color.'+ ),+ breakdownType: zod+ .string()+ .nullish()+ .describe(+ 'Breakdown type the value came from, such as `event`, `person`, `session`, or `cohort`.'+ ),+ breakdownProperty: zod+ .string()+ .nullish()+ .describe(+ 'Breakdown property the color is scoped to, so the color applies only to tiles that break down by that property. Omit to apply it under every property.'+ ),+ source: zod+ .union([+ zod.enum(['auto', 'manual']).describe('\* `auto` - auto\n\* `manual` - manual'),+ zod.null(),+ ])+ .optional()+ .describe(+ '`manual` for a color a person picked, `auto` for one the dashboard assigned.\n\n\* `auto` - auto\n\* `manual` - manual'+ ),+ })+ )+ .nullish()+ .describe(+ "Colors pinned to specific breakdown values across the dashboard's tiles. A list of entries, not an object keyed by breakdown value. Send an empty list to clear them."+ ),data_color_theme_id: zod.number().nullish().describe('ID of the color theme used for chart visualizations.'),tags: zod.array(zod.string()).optional(),restriction_level: zoddiff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create.jsonindex ac9648c9041b..d8590ca3667a 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create.json@@ -2,7 +2,72 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"breakdown_colors": {- "description": "Custom color mapping for breakdown values."+ "anyOf": [+ {+ "items": {+ "properties": {+ "breakdownProperty": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Breakdown property the color is scoped to, so the color applies only to tiles that break down by that property. Omit to apply it under every property."+ },+ "breakdownType": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Breakdown type the value came from, such as `event`, `person`, `session`, or `cohort`."+ },+ "breakdownValue": {+ "description": "The breakdown value this color applies to, as it appears in the chart legend.",+ "type": "string"+ },+ "colorToken": {+ "anyOf": [+ {+ "pattern": "^preset-[1-9][0-9]*$",+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Palette slot to color the value with, as `preset-1` upwards. Not a CSS color: a hex value is rejected. Null leaves the value on its default color."+ },+ "source": {+ "anyOf": [+ {+ "description": "* `auto` - auto\n* `manual` - manual",+ "enum": ["auto", "manual"],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "`manual` for a color a person picked, `auto` for one the dashboard assigned.\n\n* `auto` - auto\n* `manual` - manual"+ }+ },+ "required": ["breakdownValue", "colorToken"],+ "type": "object"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "description": "Colors pinned to specific breakdown values across the dashboard's tiles. A list of entries, not an object keyed by breakdown value. Send an empty list to clear them."},"data_color_theme_id": {"anyOf": [diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.jsonindex 4320b4bed1a1..59bb7d092e57 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json@@ -2,7 +2,72 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"breakdown_colors": {- "description": "Custom color mapping for breakdown values."+ "anyOf": [+ {+ "items": {+ "properties": {+ "breakdownProperty": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Breakdown property the color is scoped to, so the color applies only to tiles that break down by that property. Omit to apply it under every property."+ },+ "breakdownType": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Breakdown type the value came from, such as `event`, `person`, `session`, or `cohort`."+ },+ "breakdownValue": {+ "description": "The breakdown value this color applies to, as it appears in the chart legend.",+ "type": "string"+ },+ "colorToken": {+ "anyOf": [+ {+ "pattern": "^preset-[1-9][0-9]*$",+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Palette slot to color the value with, as `preset-1` upwards. Not a CSS color: a hex value is rejected. Null leaves the value on its default color."+ },+ "source": {+ "anyOf": [+ {+ "description": "* `auto` - auto\n* `manual` - manual",+ "enum": ["auto", "manual"],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "`manual` for a color a person picked, `auto` for one the dashboard assigned.\n\n* `auto` - auto\n* `manual` - manual"+ }+ },+ "required": ["breakdownValue", "colorToken"],+ "type": "object"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "description": "Colors pinned to specific breakdown values across the dashboard's tiles. A list of entries, not an object keyed by breakdown value. Send an empty list to clear them."},"data_color_theme_id": {"anyOf": [diff --git a/services/mcp/tests/unit/dashboard-update-schema.test.ts b/services/mcp/tests/unit/dashboard-update-schema.test.tsindex 27ef6de8a4f4..75d8e46a627b 100644--- a/services/mcp/tests/unit/dashboard-update-schema.test.ts+++ b/services/mcp/tests/unit/dashboard-update-schema.test.ts@@ -30,7 +30,7 @@ describe('dashboard-update schema', () => {it('accepts optional dashboard PATCH write params', () => {const result = tool.schema.safeParse({id: 1,- breakdown_colors: { series_a: '#ff0000' },+ breakdown_colors: [{ breakdownValue: 'Chrome', breakdownType: 'event', colorToken: 'preset-1' }],data_color_theme_id: 2,quick_filter_ids: ['00000000-0000-4000-8000-000000000001'],use_template: '',@@ -41,4 +41,20 @@ describe('dashboard-update schema', () => {expect(result.success).toBe(true)})++ // The schema used to accept any JSON for this field, and its description read as a color+ // mapping, so agents sent a dictionary of breakdown values to hex colors. The dashboard cannot+ // read that shape.+ it.each([+ ['an object keyed by breakdown value', { series_a: '#ff0000' }],+ ['entries under other key names', [{ breakdown_value: 'good', color: '#36a854' }]],+ ['an entry without a color token', [{ breakdownValue: 'Chrome' }]],+ ['a hex value where a palette slot belongs', [{ breakdownValue: 'Chrome', colorToken: '#3fb950' }]],+ // Also proves the generated schema carries the serializer's token pattern.+ ['palette slot zero', [{ breakdownValue: 'Chrome', colorToken: 'preset-0' }]],+ ])('rejects breakdown_colors as %s', (_name, breakdownColors) => {+ const result = tool.schema.safeParse({ id: 1, breakdown_colors: breakdownColors })++ expect(result.success).toBe(false)+ })})