: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
feat(dashboards): keep tile groups and display settings in templates (#123012)
Paul D'Ambraf4ff9132975d
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.test.ts b/frontend/src/scenes/dashboard/dashboardUtils.test.tsindex 4b4f9d45daa1..db14d689795f 100644--- a/frontend/src/scenes/dashboard/dashboardUtils.test.ts+++ b/frontend/src/scenes/dashboard/dashboardUtils.test.ts@@ -174,7 +174,7 @@ describe('dashboardToSaveableTemplate', () => {})})- it('preserves display attributes for every tile type', () => {+ it('preserves display attributes and tile groups for every tile type', () => {const dashboard = {name: 'My dashboard',description: '',@@ -191,6 +191,7 @@ describe('dashboardToSaveableTemplate', () => {layouts: {},color: null,transparent_background: true,+ group_key: 'plans',},{id: 2,@@ -212,21 +213,26 @@ describe('dashboardToSaveableTemplate', () => {layouts: {},color: null,transparent_background: false,+ group_key: 'plans',},],+ customization: { tile_spacing: 'tight', groups: { plans: { title: 'Plans', color: 'green' } } },} as unknown as DashboardType- expect(dashboardToSaveableTemplate(dashboard)?.tiles).toMatchObject([+ const template = dashboardToSaveableTemplate(dashboard)+ expect(template?.tiles).toMatchObject([{type: 'TEXT',body: 'Text',agent_context: 'Use paid plan events for this metric.',transparent_background: true,+ group_key: 'plans',},{ type: 'INSIGHT', transparent_background: false },{ type: 'BUTTON', transparent_background: true },- { type: 'WIDGET', transparent_background: false },+ { type: 'WIDGET', transparent_background: false, group_key: 'plans' },])+ expect(template?.customization).toEqual(dashboard.customization)expect(dashboardTemplateForExport(dashboardToSaveableTemplate(dashboard))?.tiles[0]).not.toHaveProperty('agent_context')diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.tsindex e58ffa5462f4..3accdf103b25 100644--- a/frontend/src/scenes/dashboard/dashboardUtils.ts+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts@@ -80,14 +80,18 @@ export function dashboardToSaveableTemplate(tiles: dashboard.tiles.filter((tile) => !tile.error).map((tile) => {+ const display = {+ layouts: tile.layouts,+ color: tile.color,+ transparent_background: tile.transparent_background,+ group_key: tile.group_key,+ }if (tile.text) {return {type: 'TEXT' as const,body: tile.text.body,agent_context: tile.text.agent_context,- layouts: tile.layouts,- color: tile.color,- transparent_background: tile.transparent_background,+ ...display,}}if (tile.insight) {@@ -96,9 +100,7 @@ export function dashboardToSaveableTemplate(name: tile.insight.name,description: tile.insight.description || '',query: tile.insight.query,- layouts: tile.layouts,- color: tile.color,- transparent_background: tile.transparent_background,+ ...display,}}if (tile.button_tile) {@@ -110,9 +112,7 @@ export function dashboardToSaveableTemplate(placement: tile.button_tile.placement,style: tile.button_tile.style,},- layouts: tile.layouts,- color: tile.color,- transparent_background: tile.transparent_background,+ ...display,}}if (tile.widget) {@@ -120,13 +120,12 @@ export function dashboardToSaveableTemplate(type: 'WIDGET' as const,widget_type: tile.widget.widget_type,config: tile.widget.config,- layouts: tile.layouts,- color: tile.color,- transparent_background: tile.transparent_background,+ ...display,}}throw new Error('Unknown tile type')}),+ customization: dashboard.customization,variables: [],}}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 94d90852b15f..458bdc455cfd 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -2848,6 +2848,7 @@ export type DashboardTemplateStoredInsightTile = {layouts?: Record<DashboardLayoutSize, TileLayout> | Record<string, never>color?: InsightColor | nulltransparent_background?: boolean | null+ group_key?: string | nullfilters?: Record<string, unknown>}@@ -2858,6 +2859,7 @@ export type DashboardTemplateStoredTextTile = {layouts?: Record<DashboardLayoutSize, TileLayout> | Record<string, never>color?: InsightColor | nulltransparent_background?: boolean | null+ group_key?: string | null}export type DashboardTemplateStoredButtonTile = {@@ -2871,6 +2873,7 @@ export type DashboardTemplateStoredButtonTile = {layouts?: Record<DashboardLayoutSize, TileLayout> | Record<string, never>color?: InsightColor | nulltransparent_background?: boolean | null+ group_key?: string | null}export type DashboardTemplateStoredWidgetTile = {@@ -2880,6 +2883,7 @@ export type DashboardTemplateStoredWidgetTile = {layouts?: Record<DashboardLayoutSize, TileLayout> | Record<string, never>color?: InsightColor | nulltransparent_background?: boolean | null+ group_key?: string | null}export type DashboardTemplateStoredTile =@@ -2905,6 +2909,7 @@ export interface DashboardTemplateType {dashboard_filters?: DashboardFiltertiles: DashboardTemplateStoredTile[]variables?: DashboardTemplateVariableType[]+ customization?: DashboardType['customization'] | nulltags?: string[]image_url?: stringscope?: DashboardTemplateScopediff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex f16a04e75414..c94eeb98d419 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -55,6 +55,7 @@ from products.dashboards.backend.api.dashboard import (DashboardTileErrorSerializer,serialize_tile_with_context,)+from products.dashboards.backend.constants import MAX_GROUP_KEY_LENGTH, MAX_GROUP_TITLE_LENGTH, MAX_GROUPSfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_templates import DashboardTemplatefrom products.dashboards.backend.models.dashboard_tile import ButtonTile, DashboardTile, Text@@ -3724,17 +3725,100 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):},]- def test_create_from_template_json_rejects_oversized_agent_context(self) -> None:+ @parameterized.expand([("template_json",), ("saved_template",)])+ def test_dashboard_from_template_keeps_tile_groups_and_customization(self, source: str) -> None:template: dict = {**valid_template,"tiles": [- {- "type": "TEXT",- "body": "hello world",- "agent_context": "x" * 10_001,- "layouts": {},- }+ {"type": "TEXT", "body": "grouped", "layouts": {}, "group_key": "plans"},+ {"type": "TEXT", "body": "loose", "layouts": {}},],+ "customization": {+ "tile_spacing": "tight",+ "groups": {"plans": {"title": "Plans", "color": "green"}},+ },+ }++ if source == "template_json":+ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboards/create_from_template_json",+ {"template": template},+ format="json",+ )+ assert response.status_code == 200, response.content+ dashboard_id = response.json()["id"]+ else:+ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboard_templates",+ {**template, "scope": "team"},+ format="json",+ )+ assert response.status_code == 201, response.content+ dashboard_id, _ = self.dashboard_api.create_dashboard(+ {"name": "from saved template", "use_template": template["template_name"]}+ )++ dashboard = self.dashboard_api.get_dashboard(dashboard_id, query_params={"refresh": False})+ assert dashboard["customization"] == {+ "tile_spacing": "tight",+ "groups": {"plans": {"title": "Plans", "color": "green", "collapsed": False}},+ "group_titles": {"plans": "Plans"},+ }+ assert {tile["text"]["body"]: tile["group_key"] for tile in dashboard["tiles"]} == {+ "grouped": "plans",+ "loose": None,+ }++ @parameterized.expand(+ [+ ("groups_empty", {"groups": {}}, {"tile_spacing": "tight"}),+ ("groups_null", {"groups": None}, {"tile_spacing": "tight"}),+ (+ "group_titles_keep_template_settings",+ {"group_titles": {"plans": "Renamed"}},+ {+ "tile_spacing": "tight",+ "groups": {"plans": {"title": "Renamed", "color": "green", "collapsed": False}},+ "group_titles": {"plans": "Renamed"},+ },+ ),+ ]+ )+ def test_dashboard_from_template_applies_requested_groups(+ self, _name: str, request_groups: dict, expected_customization: dict+ ) -> None:+ template = {+ **valid_template,+ "tiles": [{"type": "TEXT", "body": "grouped", "layouts": {}, "group_key": "plans"}],+ "customization": {"tile_spacing": "tight", "groups": {"plans": {"title": "Plans", "color": "green"}}},+ "scope": "team",+ }+ response = self.client.post(f"/api/projects/{self.team.id}/dashboard_templates", template, format="json")+ assert response.status_code == 201, response.content++ dashboard_id, _ = self.dashboard_api.create_dashboard(+ {"name": "from saved template", "use_template": template["template_name"], **request_groups}+ )++ dashboard = self.dashboard_api.get_dashboard(dashboard_id, query_params={"refresh": False})+ assert dashboard["customization"] == expected_customization++ @parameterized.expand(+ [+ ("oversized_agent_context", {"agent_context": "x" * 10_001}, None),+ ("long_tile_group_key", {"group_key": "k" * (MAX_GROUP_KEY_LENGTH + 1)}, None),+ ("too_many_groups", {}, {"groups": {f"group-{index}": {} for index in range(MAX_GROUPS + 1)}}),+ ("long_group_key", {}, {"groups": {"k" * (MAX_GROUP_KEY_LENGTH + 1): {"title": "Long"}}}),+ ("long_legacy_group_title", {}, {"group_titles": {"plans": "t" * (MAX_GROUP_TITLE_LENGTH + 1)}}),+ ]+ )+ def test_create_from_template_json_rejects_invalid_template(+ self, _name: str, tile_fields: dict, customization: dict | None+ ) -> None:+ template: dict = {+ **valid_template,+ "tiles": [{"type": "TEXT", "body": "hello world", "layouts": {}, **tile_fields}],+ "customization": customization,}dashboard_count = Dashboard.objects.count()text_count = Text.objects.count()diff --git a/posthog/helpers/dashboard_templates.py b/posthog/helpers/dashboard_templates.pyindex 0ecdf47a10c2..458eaaf72b50 100644--- a/posthog/helpers/dashboard_templates.py+++ b/posthog/helpers/dashboard_templates.py@@ -489,6 +489,7 @@ def dashboard_template_from_creation_payload(template: dict[str, Any]) -> Dashbotiles=template["tiles"],tags=template.get("tags"),variables=template.get("variables"),+ customization=template.get("customization"),)@@ -499,10 +500,20 @@ def create_from_template(*,user_access_control: UserAccessControl | None = None,) -> None:+ from products.dashboards.backend.customization import ( # noqa: PLC0415 — breaks posthog.models import cycle+ normalize_dashboard_customization,+ stored_customization,+ stored_group_key,+ )+if not dashboard.name or dashboard.name == "":dashboard.name = template.template_namedashboard.filters = template.dashboard_filtersdashboard.description = template.dashboard_description or ""+ dashboard.customization = {+ **stored_customization(template.customization),+ **normalize_dashboard_customization(dashboard.customization),+ }for template_tag in template.tags or []:tag, _ = Tag.objects.get_or_create(@@ -519,6 +530,7 @@ def create_from_template(query = template_tile.get("query", None)_create_tile_for_insight(dashboard,+ group_key=stored_group_key(template_tile.get("group_key")),name=template_tile.get("name"),query=query,description=template_tile.get("description"),@@ -530,6 +542,7 @@ def create_from_template(elif tile_type == "TEXT":_create_tile_for_text(dashboard,+ group_key=stored_group_key(template_tile.get("group_key")),color=template_tile.get("color"),layouts=template_tile.get("layouts"),body=template_tile.get("body"),@@ -540,6 +553,7 @@ def create_from_template(button = {**template_tile, **(template_tile.get("button_tile") or {})}_create_tile_for_button(dashboard,+ group_key=stored_group_key(template_tile.get("group_key")),color=template_tile.get("color"),layouts=template_tile.get("layouts"),url=button.get("url", ""),@@ -551,6 +565,7 @@ def create_from_template(elif tile_type == "WIDGET":_create_tile_for_widget(dashboard,+ group_key=stored_group_key(template_tile.get("group_key")),widget_type=template_tile.get("widget_type", ""),config=template_tile.get("config", {}),color=template_tile.get("color"),@@ -570,6 +585,8 @@ def _create_tile_for_text(color: Optional[str],agent_context: str | None = None,transparent_background: Optional[bool] = None,+ *,+ group_key: str | None = None,) -> None:if agent_context is not None and len(agent_context) > MAX_TEXT_TILE_AGENT_CONTEXT_LENGTH:raise ValueError(f"Agent context cannot exceed {MAX_TEXT_TILE_AGENT_CONTEXT_LENGTH} characters")@@ -583,6 +600,7 @@ def _create_tile_for_text(text=text,dashboard=dashboard,team_id=dashboard.team_id,+ group_key=group_key,layouts=layouts,color=color,transparent_background=transparent_background,@@ -598,6 +616,8 @@ def _create_tile_for_button(placement: str = "left",style: str = "primary",transparent_background: Optional[bool] = None,+ *,+ group_key: str | None = None,) -> None:button_tile = ButtonTile.objects.create(team=dashboard.team,@@ -610,6 +630,7 @@ def _create_tile_for_button(button_tile=button_tile,dashboard=dashboard,team_id=dashboard.team_id,+ group_key=group_key,layouts=layouts,color=color,transparent_background=transparent_background,@@ -626,6 +647,7 @@ def _create_tile_for_widget(user=None,*,user_access_control: UserAccessControl | None = None,+ group_key: str | None = None,) -> None:from products.dashboards.backend.widget_create import (prepare_widget_tile_create, # noqa: PLC0415 — breaks posthog.models import cycle@@ -650,6 +672,7 @@ def _create_tile_for_widget(widget=widget,dashboard=dashboard,team_id=dashboard.team_id,+ group_key=group_key,layouts=layouts or {},color=color,transparent_background=transparent_background,@@ -665,6 +688,8 @@ def _create_tile_for_insight(query: Optional[dict] = None,tags: Optional[list[str]] = None,user=None,+ *,+ group_key: str | None = None,) -> None:insight = Insight.objects.create(team=dashboard.team,@@ -687,6 +712,7 @@ def _create_tile_for_insight(insight=insight,dashboard=dashboard,team_id=dashboard.team_id,+ group_key=group_key,layouts=layouts,color=color,)diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex e99120e7a25b..72f4661d4573 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -5,7 +5,7 @@ import jsonimport uuidimport builtinsimport contextvars-from collections.abc import AsyncGenerator, Callable, Mapping+from collections.abc import AsyncGenerator, Callablefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom contextlib import nullcontextfrom enum import StrEnum@@ -143,7 +143,6 @@ from products.dashboards.backend.api.widget_openapi_serializers import ()from products.dashboards.backend.constants import (DASHBOARD_GRID_COLUMN_COUNT,- MAX_GROUP_KEY_LENGTH,MAX_GROUP_TITLE_LENGTH,MAX_GROUPS,MAX_TEXT_TILE_AGENT_CONTEXT_LENGTH,@@ -152,6 +151,15 @@ from products.dashboards.backend.constants import (RUN_INSIGHTS_MAX_TOTAL_CHARS,RUN_INSIGHTS_MIN_TILE_CHARS,)+from products.dashboards.backend.customization import (+ normalize_dashboard_customization,+ stored_customization,+ stored_groups,+ validate_template_groups,+ validated_group_key,+ validated_group_keys,+ without_default_settings,+)from products.dashboards.backend.facade.api import DashboardTileBasicSerializer, tile_ids_prefetchfrom products.dashboards.backend.models.dashboard import (DASHBOARD_GRID_COMPACTION_MODES,@@ -219,57 +227,6 @@ AGENT_CONTEXT_HELP_TEXT = ()-def _normalize_dashboard_customization(customization: Any) -> dict[str, Any]:- return customization.copy() if isinstance(customization, dict) else {}---def _normalized_group_key(group_key: str) -> str:- group_key = group_key.strip()- if "\x00" in group_key:- raise serializers.ValidationError("Group keys can't contain null characters.")- return group_key---_NO_DEFAULT = object()---def _is_stored_group_setting(field: str, setting: Any) -> bool:- if field == "title":- return bool(setting)- return setting != DASHBOARD_TILE_GROUP_DEFAULTS.get(field, _NO_DEFAULT)---def _without_default_settings(group: Mapping[str, Any]) -> dict[str, Any]:- return {field: setting for field, setting in group.items() if _is_stored_group_setting(field, setting)}---def _sparse_group(group_settings: Any) -> dict[str, Any] | None:- group = DashboardTileGroupSerializer(data=group_settings)- if not group.is_valid():- return None- return _without_default_settings(group.validated_data)---def _stored_groups(customization: Any) -> dict[str, dict[str, Any]]:- customization = _normalize_dashboard_customization(customization)- groups = customization.get("groups") if isinstance(customization.get("groups"), dict) else {}- titles = customization.get("group_titles") if isinstance(customization.get("group_titles"), dict) else {}- stored: dict[str, dict[str, Any]] = {}- for raw_key in {**groups, **titles}:- if not isinstance(raw_key, str):- continue- try:- group_key = _normalized_group_key(raw_key)- except serializers.ValidationError:- continue- group = _sparse_group(groups.get(raw_key, {}))- # Only a server from before `groups` writes `group_titles`, so a stored title there is the newer one.- title = _sparse_group({"title": titles[raw_key]}) if raw_key in titles else None- if group_key and (group is not None or title is not None):- stored[group_key] = {**(group or {}), **(title or {})}- return stored--def _with_groups(customization: dict[str, Any], groups: dict[str, dict[str, Any]] | None) -> dict[str, Any]:customization = {key: value for key, value in customization.items() if key not in ("groups", "group_titles")}if groups:@@ -280,7 +237,7 @@ def _with_groups(customization: dict[str, Any], groups: dict[str, dict[str, Any]def _with_group_titles(customization: dict[str, Any], titles: dict[str, str] | None) -> dict[str, Any]:groups = {key: {field: value for field, value in group.items() if field != "title"}- for key, group in _stored_groups(customization).items()+ for key, group in stored_groups(customization).items()}for key, title in (titles or {}).items():groups.setdefault(key, {})["title"] = title@@ -290,22 +247,6 @@ def _with_group_titles(customization: dict[str, Any], titles: dict[str, str] | Nreturn _with_groups(customization, groups)-def _validated_group_keys[T](value: dict[str, T]) -> dict[str, T]:- if len(value) > MAX_GROUPS:- raise serializers.ValidationError(f"A dashboard can have at most {MAX_GROUPS} groups.")- normalized: dict[str, T] = {}- for key, item in value.items():- group_key = _normalized_group_key(key)- if not group_key:- raise serializers.ValidationError("Group keys can't be empty.")- if len(group_key) > MAX_GROUP_KEY_LENGTH:- raise serializers.ValidationError(f"Group keys can have at most {MAX_GROUP_KEY_LENGTH} characters.")- if group_key in normalized:- raise serializers.ValidationError(f'Group key "{group_key}" is used more than once.')- normalized[group_key] = item- return normalized--class _GroupDictField(serializers.DictField):# DRF reads a dict field that form data omits as an empty dict, and an empty dict clears the stored groups.def get_value(self, dictionary: Any) -> Any:@@ -314,7 +255,7 @@ class _GroupDictField(serializers.DictField):def _effective_layout_compaction(customization: Any) -> str:- layout_compaction = _normalize_dashboard_customization(customization).get("layout_compaction")+ layout_compaction = normalize_dashboard_customization(customization).get("layout_compaction")return layout_compaction if layout_compaction in DASHBOARD_GRID_COMPACTION_MODES else "vertical"@@ -1425,7 +1366,7 @@ class DashboardCustomizationSerializer(serializers.Serializer):help_text=GROUPS_HELP_TEXT,)group_titles = serializers.DictField(- child=serializers.CharField(),+ child=serializers.CharField(max_length=MAX_GROUP_TITLE_LENGTH),required=False,help_text=GROUP_TITLES_HELP_TEXT,)@@ -1527,10 +1468,10 @@ class DashboardMetadataSerializer(DashboardBasicSerializer):def validate_groups(self, value: dict[str, dict[str, Any]] | None) -> dict[str, dict[str, Any]] | None:if value is None:return None- return {key: _without_default_settings(group) for key, group in _validated_group_keys(value).items()}+ return {key: without_default_settings(group) for key, group in validated_group_keys(value).items()}def validate_group_titles(self, value: dict[str, str] | None) -> dict[str, str] | None:- return None if value is None else _validated_group_keys(value)+ return None if value is None else validated_group_keys(value)def get_filters(self, dashboard: Dashboard) -> dict:request = self.context.get("request")@@ -1539,15 +1480,8 @@ class DashboardMetadataSerializer(DashboardBasicSerializer):@extend_schema_field(DashboardCustomizationSerializer)def get_customization(self, dashboard: Dashboard) -> dict[str, Any]:- customization = _normalize_dashboard_customization(dashboard.customization)- tile_spacing = customization.get("tile_spacing")- layout_compaction = customization.get("layout_compaction")- result: dict[str, Any] = {}- if isinstance(tile_spacing, str) and tile_spacing in DASHBOARD_GRID_SPACING_GAPS:- result["tile_spacing"] = tile_spacing- if isinstance(layout_compaction, str) and layout_compaction in DASHBOARD_GRID_COMPACTION_MODES:- result["layout_compaction"] = layout_compaction- groups = _stored_groups(customization)+ result = stored_customization(dashboard.customization)+ groups = result.get("groups", {})if groups:result["groups"] = {key: {**DASHBOARD_TILE_GROUP_DEFAULTS, **group} for key, group in groups.items()}titles = {key: group["title"] for key, group in groups.items() if "title" in group}@@ -1954,7 +1888,7 @@ class DashboardSerializer(DashboardMetadataSerializer):)if existing_dashboard:- validated_data["customization"] = _normalize_dashboard_customization(existing_dashboard.customization)+ validated_data["customization"] = normalize_dashboard_customization(existing_dashboard.customization)if grid_spacing is not None:validated_data["customization"] = {@@ -1966,10 +1900,16 @@ class DashboardSerializer(DashboardMetadataSerializer):**validated_data.get("customization", {}),"layout_compaction": layout_compaction,}- if has_groups:- validated_data["customization"] = _with_groups(validated_data.get("customization", {}), groups)- if has_group_titles:- validated_data["customization"] = _with_group_titles(validated_data.get("customization", {}), group_titles)++ def with_requested_groups(customization: dict[str, Any]) -> dict[str, Any]:+ if has_groups:+ customization = _with_groups(customization, groups)+ if has_group_titles:+ customization = _with_group_titles(customization, group_titles)+ return customization++ if (has_groups or has_group_titles) and not use_template:+ validated_data["customization"] = with_requested_groups(validated_data.get("customization", {}))with transaction.atomic():dashboard = Dashboard.objects.create(team_id=team_id, filters=filters, **validated_data)@@ -1991,6 +1931,12 @@ class DashboardSerializer(DashboardMetadataSerializer):exc_info=True,)raise serializers.ValidationError({"use_template": f"Invalid template provided: {use_template}"})+ # Group settings in the request apply on top of the template's groups, so they wait for the merge.+ if has_groups or has_group_titles:+ dashboard.customization = with_requested_groups(+ normalize_dashboard_customization(dashboard.customization)+ )+ dashboard.save(update_fields=["customization"])elif existing_dashboard:existing_tiles = (@@ -2193,18 +2139,18 @@ class DashboardSerializer(DashboardMetadataSerializer):layout_compaction = validated_data.pop("layout_compaction", None)if grid_spacing is not None or layout_compaction is not None:validated_data["customization"] = {- **_normalize_dashboard_customization(instance.customization),+ **normalize_dashboard_customization(instance.customization),**({"tile_spacing": grid_spacing} if grid_spacing is not None else {}),**({"layout_compaction": layout_compaction} if layout_compaction is not None else {}),}if "groups" in validated_data:validated_data["customization"] = _with_groups(- validated_data.get("customization", _normalize_dashboard_customization(instance.customization)),+ validated_data.get("customization", normalize_dashboard_customization(instance.customization)),validated_data.pop("groups"),)if "group_titles" in validated_data:validated_data["customization"] = _with_group_titles(- validated_data.get("customization", _normalize_dashboard_customization(instance.customization)),+ validated_data.get("customization", normalize_dashboard_customization(instance.customization)),validated_data.pop("group_titles"),)@@ -2406,7 +2352,7 @@ class DashboardSerializer(DashboardMetadataSerializer):def _validated_tile_marking(tile_fields: dict) -> dict:marking: dict = {}if "group_key" in tile_fields:- marking["group_key"] = DashboardSerializer._validated_group_key(tile_fields["group_key"])+ marking["group_key"] = validated_group_key(tile_fields["group_key"])if "badge" in tile_fields:if tile_fields["badge"] not in (None, *DashboardTileBadge.values):raise serializers.ValidationError(@@ -2415,22 +2361,6 @@ class DashboardSerializer(DashboardMetadataSerializer):marking["badge"] = tile_fields["badge"]return marking- @staticmethod- def _validated_group_key(group_key: Any) -> str | None:- if group_key is None:- return None- if not isinstance(group_key, str):- raise serializers.ValidationError({"group_key": "Group key must be a string or null."})- try:- group_key = _normalized_group_key(group_key)- except serializers.ValidationError as error:- raise serializers.ValidationError({"group_key": error.detail}) from error- if len(group_key) > MAX_GROUP_KEY_LENGTH:- raise serializers.ValidationError(- {"group_key": f"Group key can have at most {MAX_GROUP_KEY_LENGTH} characters."}- )- return group_key or None-@staticmethoddef _validate_tiles_before_saving(instance: Dashboard, tiles: list[dict]) -> None:for tile in tiles:@@ -4222,6 +4152,12 @@ class DashboardsViewSet(parser_classes=[DashboardTemplateCreationJSONSchemaParser],)def create_from_template_json(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ template_body = request.data["template"]+ if template_body.get("customization") is not None:+ customization = DashboardCustomizationSerializer(data=template_body["customization"])+ if not customization.is_valid():+ raise serializers.ValidationError({"customization": customization.errors})+ validate_template_groups(template_body.get("customization"), template_body.get("tiles"))dashboard = Dashboard.objects.create(team_id=self.team_id,created_by=cast(User, request.user),@@ -4229,7 +4165,7 @@ class DashboardsViewSet()try:- dashboard_template = dashboard_template_from_creation_payload(request.data["template"])+ dashboard_template = dashboard_template_from_creation_payload(template_body)creation_context = request.data.get("creation_context")create_from_template(dashboard,@@ -4238,7 +4174,6 @@ class DashboardsViewSet(user_access_control=UserAccessControl(user=cast(User, request.user), team=self.team),)- template_body = request.data["template"]raw_scope = template_body.get("scope")if raw_scope is None or raw_scope == "":template_scope_props: dict[str, str | None] = {"template_scope": None}diff --git a/products/dashboards/backend/api/dashboard_template_schema.json b/products/dashboards/backend/api/dashboard_template_schema.jsonindex ed313ec41e96..c6b51b7c34d5 100644--- a/products/dashboards/backend/api/dashboard_template_schema.json+++ b/products/dashboards/backend/api/dashboard_template_schema.json@@ -41,6 +41,11 @@"description": "Optional context for AI agents. Maximum 10000 characters.","type": ["string", "null"],"maxLength": 10000+ },+ "group_key": {+ "description": "Key of the tile group this tile joins. Tiles with the same key belong together.",+ "type": ["string", "null"],+ "maxLength": 100}}}@@ -86,6 +91,10 @@}]},+ "customization": {+ "description": "Display settings that the new dashboard starts with, such as tile spacing and tile groups",+ "type": ["object", "null"]+ },"tags": {"description": "The tags of the dashboard template","type": "array",diff --git a/products/dashboards/backend/api/dashboard_templates.py b/products/dashboards/backend/api/dashboard_templates.pyindex eee3c545bd06..ee1f459a8e2b 100644--- a/products/dashboards/backend/api/dashboard_templates.py+++ b/products/dashboards/backend/api/dashboard_templates.py@@ -33,6 +33,8 @@ from posthog.user_permissions import UserPermissionsfrom posthog.utils import str_to_boolfrom products.access_control.backend.facade.user_access_control import UserAccessControl+from products.dashboards.backend.api.dashboard import DashboardCustomizationSerializer+from products.dashboards.backend.customization import validate_template_groupsfrom products.dashboards.backend.models.dashboard_templates import DashboardTemplatelogger = structlog.get_logger(__name__)@@ -188,6 +190,14 @@ class NonPortableReferencesSerializer(serializers.Serializer):class DashboardTemplateSerializer(serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True)+ customization = DashboardCustomizationSerializer(+ required=False,+ allow_null=True,+ help_text=(+ "Display settings that a dashboard made from this template starts with: tile spacing, layout "+ "compaction, and the tile groups that tiles join through their group_key."+ ),+ )non_portable_references = serializers.SerializerMethodField(help_text=("Read-only. Project-specific references (actions, cohorts, data warehouse tables) embedded in this "@@ -206,6 +216,7 @@ class DashboardTemplateSerializer(serializers.ModelSerializer):"tags","tiles","variables",+ "customization","deleted","created_at","created_by",@@ -299,6 +310,7 @@ class DashboardTemplateSerializer(serializers.ModelSerializer):)attrs["scope"] = requested_scope+ validate_template_groups(attrs.get("customization"), attrs.get("tiles"))self._validate_unique_organization_template_name(attrs)return attrs@@ -380,6 +392,7 @@ class DashboardTemplateSerializer(serializers.ModelSerializer):validated_data.pop("team_id", None)validated_data.pop("tiles", None)validated_data.pop("variables", None)+ validated_data.pop("customization", None)validated_data.pop("dashboard_filters", None)validated_data.pop("is_featured", None)validated_data.pop("availability_contexts", None)@@ -610,6 +623,7 @@ class DashboardTemplateViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsdashboard_filters=source.dashboard_filters,tiles=source.tiles or [],variables=source.variables,+ customization=source.customization,tags=source.tags or [],scope=DashboardTemplate.Scope.ONLY_TEAM,is_featured=False,diff --git a/products/dashboards/backend/api/test/test_dashboard_groups.py b/products/dashboards/backend/api/test/test_dashboard_groups.pyindex ad0157b3c8ac..650e5a77da11 100644--- a/products/dashboards/backend/api/test/test_dashboard_groups.py+++ b/products/dashboards/backend/api/test/test_dashboard_groups.py@@ -4,7 +4,7 @@ from django.test import SimpleTestCasefrom parameterized import parameterized-from products.dashboards.backend.api.dashboard import _stored_groups+from products.dashboards.backend.customization import stored_groupsclass TestStoredGroups(SimpleTestCase):@@ -56,4 +56,4 @@ class TestStoredGroups(SimpleTestCase):@parameterized.expand(cases)def test_reads_stored_groups(self, _name: str, customization: Any, expected: dict) -> None:- assert _stored_groups(customization) == expected+ assert stored_groups(customization) == expecteddiff --git a/products/dashboards/backend/api/test/test_dashboard_templates.py b/products/dashboards/backend/api/test/test_dashboard_templates.pyindex 73833cb171ce..e233f920f3d3 100644--- a/products/dashboards/backend/api/test/test_dashboard_templates.py+++ b/products/dashboards/backend/api/test/test_dashboard_templates.py@@ -20,6 +20,7 @@ from products.dashboards.backend.api.dashboard_templates import (MAX_DASHBOARD_TEMPLATES_PER_ORGANIZATION,organization_dashboard_template_limit_detail,)+from products.dashboards.backend.constants import MAX_GROUP_KEY_LENGTH, MAX_GROUP_TITLE_LENGTH, MAX_GROUPSfrom products.dashboards.backend.models.dashboard_templates import DashboardTemplate@@ -77,7 +78,7 @@ def _listable_dashboard_template_db_count(team_pk: int) -> int:return DashboardTemplate.objects.filter(Q(scope=DashboardTemplate.Scope.GLOBAL) | Q(team_id=team_pk)).count()-variable_template = {+variable_template: dict[str, Any] = {"template_name": "Sign up conversion template with variables","dashboard_description": "Use this template to see how many users sign up after visiting your pricing page.","dashboard_filters": {},@@ -634,7 +635,12 @@ class TestDashboardTemplates(APIBaseTest):"description": "Optional context for AI agents. Maximum 10000 characters.","type": ["string", "null"],"maxLength": 10000,- }+ },+ "group_key": {+ "description": "Key of the tile group this tile joins. Tiles with the same key belong together.",+ "type": ["string", "null"],+ "maxLength": 100,+ },},},"minItems": 1,@@ -685,6 +691,10 @@ class TestDashboardTemplates(APIBaseTest):{"type": "null"},],},+ "customization": {+ "description": "Display settings that the new dashboard starts with, such as tile spacing and tile groups",+ "type": ["object", "null"],+ },"tags": {"description": "The tags of the dashboard template","type": "array",@@ -1214,6 +1224,55 @@ class TestCustomerDashboardTemplateAuthoring(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert response.json().get("attr") == field+ @parameterized.expand(+ [+ (+ f"{method}_{name}",+ method,+ body,+ attr,+ )+ for method in ("create", "update")+ for name, body, attr in [+ (+ "too_many_groups",+ {"customization": {"groups": {f"group-{index}": {} for index in range(MAX_GROUPS + 1)}}},+ "customization",+ ),+ (+ "long_group_key",+ {"customization": {"groups": {"k" * (MAX_GROUP_KEY_LENGTH + 1): {"title": "Long"}}}},+ "customization",+ ),+ (+ "long_tile_group_key",+ {"tiles": [{**variable_template["tiles"][0], "group_key": "k" * (MAX_GROUP_KEY_LENGTH + 1)}]},+ "tiles",+ ),+ (+ "long_legacy_group_title",+ {"customization": {"group_titles": {"plans": "t" * (MAX_GROUP_TITLE_LENGTH + 1)}}},+ "customization",+ ),+ ]+ ]+ )+ def test_rejects_groups_a_dashboard_cannot_hold(self, _name: str, method: str, body: dict, attr: str) -> None:+ self.user.is_staff = True+ self.user.save()+ if method == "create":+ response = self.client.post(+ f"/api/projects/{self.team.pk}/dashboard_templates", {**variable_template, **body}, format="json"+ )+ else:+ created = self.client.post(f"/api/projects/{self.team.pk}/dashboard_templates", variable_template)+ response = self.client.patch(+ f"/api/projects/{self.team.pk}/dashboard_templates/{created.json()['id']}", body, format="json"+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert response.json()["attr"].split("__")[0] == attr+def test_non_staff_cannot_patch_global_or_feature_flag_template(self) -> None:global_tpl = DashboardTemplate.objects.filter(scope=DashboardTemplate.Scope.GLOBAL).first()assert global_tpl is not None@@ -1491,7 +1550,13 @@ class TestDashboardTemplateCopyBetweenProjects(APIBaseTest):def test_copy_happy_path_creates_row_on_target_team(self) -> None:src = self.client.post(f"/api/projects/{self.team.pk}/dashboard_templates",- {**variable_template, "template_name": "Copy me inter-project", "scope": "team"},+ {+ **variable_template,+ "template_name": "Copy me inter-project",+ "scope": "team",+ "customization": {"groups": {"plans": {"title": "Plans"}}},+ },+ format="json",)assert src.status_code == status.HTTP_201_CREATED, src.contentsrc_id = src.json()["id"]@@ -1505,6 +1570,7 @@ class TestDashboardTemplateCopyBetweenProjects(APIBaseTest):assert data["is_featured"] is Falseassert data["image_url"] in (None, "")assert len(data["tiles"]) == len(variable_template["tiles"])+ assert data["customization"] == {"groups": {"plans": {"title": "Plans", "color": None}}}@patch("products.dashboards.backend.api.dashboard_templates.report_user_action")def test_copy_emits_distinct_analytics_event(self, mock_report: Any) -> None:diff --git a/products/dashboards/backend/customization.py b/products/dashboards/backend/customization.pynew file mode 100644index 000000000000..b7725ffe2a0b--- /dev/null+++ b/products/dashboards/backend/customization.py@@ -0,0 +1,139 @@+from collections.abc import Mapping+from typing import Any++from rest_framework import serializers++from products.dashboards.backend.constants import MAX_GROUP_KEY_LENGTH, MAX_GROUPS+from products.dashboards.backend.models.dashboard import DASHBOARD_GRID_COMPACTION_MODES, DASHBOARD_GRID_SPACING_GAPS+from products.dashboards.backend.widget_specs.openapi import DASHBOARD_TILE_GROUP_DEFAULTS, DashboardTileGroupSerializer+++def normalize_dashboard_customization(customization: Any) -> dict[str, Any]:+ return customization.copy() if isinstance(customization, dict) else {}+++def normalized_group_key(group_key: str) -> str:+ group_key = group_key.strip()+ if "\x00" in group_key:+ raise serializers.ValidationError("Group keys can't contain null characters.")+ return group_key+++def stored_group_key(group_key: Any) -> str | None:+ if not isinstance(group_key, str):+ return None+ try:+ group_key = normalized_group_key(group_key)+ except serializers.ValidationError:+ return None+ return group_key if group_key and len(group_key) <= MAX_GROUP_KEY_LENGTH else None+++def validated_group_key(group_key: Any) -> str | None:+ if group_key is None:+ return None+ if not isinstance(group_key, str):+ raise serializers.ValidationError({"group_key": "Group key must be a string or null."})+ try:+ group_key = normalized_group_key(group_key)+ except serializers.ValidationError as error:+ raise serializers.ValidationError({"group_key": error.detail}) from error+ if len(group_key) > MAX_GROUP_KEY_LENGTH:+ raise serializers.ValidationError(+ {"group_key": f"Group key can have at most {MAX_GROUP_KEY_LENGTH} characters."}+ )+ return group_key or None+++def validated_group_keys[T](value: dict[str, T]) -> dict[str, T]:+ if len(value) > MAX_GROUPS:+ raise serializers.ValidationError(f"A dashboard can have at most {MAX_GROUPS} groups.")+ normalized: dict[str, T] = {}+ for key, item in value.items():+ group_key = normalized_group_key(key)+ if not group_key:+ raise serializers.ValidationError("Group keys can't be empty.")+ if len(group_key) > MAX_GROUP_KEY_LENGTH:+ raise serializers.ValidationError(f"Group keys can have at most {MAX_GROUP_KEY_LENGTH} characters.")+ if group_key in normalized:+ raise serializers.ValidationError(f'Group key "{group_key}" is used more than once.')+ normalized[group_key] = item+ return normalized+++def _dict_or_empty(value: Any) -> dict[str, Any]:+ return value if isinstance(value, dict) else {}+++def validate_template_groups(customization: Any, tiles: Any) -> None:+ """Reject template groups that a dashboard made from the template could not hold."""+ customization = _dict_or_empty(customization)+ try:+ validated_group_keys(+ {**_dict_or_empty(customization.get("groups")), **_dict_or_empty(customization.get("group_titles"))}+ )+ except serializers.ValidationError as error:+ raise serializers.ValidationError({"customization": error.detail}) from error+ for tile in tiles if isinstance(tiles, list) else []:+ try:+ validated_group_key(_dict_or_empty(tile).get("group_key"))+ except serializers.ValidationError as error:+ detail = error.detail+ raise serializers.ValidationError(+ {"tiles": detail["group_key"] if isinstance(detail, dict) else detail}+ ) from error+++_NO_DEFAULT = object()+++def _is_stored_group_setting(field: str, setting: Any) -> bool:+ if field == "title":+ return bool(setting)+ return setting != DASHBOARD_TILE_GROUP_DEFAULTS.get(field, _NO_DEFAULT)+++def without_default_settings(group: Mapping[str, Any]) -> dict[str, Any]:+ return {field: setting for field, setting in group.items() if _is_stored_group_setting(field, setting)}+++def _sparse_group(group_settings: Any) -> dict[str, Any] | None:+ group = DashboardTileGroupSerializer(data=group_settings)+ if not group.is_valid():+ return None+ return without_default_settings(group.validated_data)+++def stored_groups(customization: Any) -> dict[str, dict[str, Any]]:+ customization = normalize_dashboard_customization(customization)+ groups = customization.get("groups") if isinstance(customization.get("groups"), dict) else {}+ titles = customization.get("group_titles") if isinstance(customization.get("group_titles"), dict) else {}+ stored: dict[str, dict[str, Any]] = {}+ for raw_key in {**groups, **titles}:+ if not isinstance(raw_key, str):+ continue+ try:+ group_key = normalized_group_key(raw_key)+ except serializers.ValidationError:+ continue+ group = _sparse_group(groups.get(raw_key, {}))+ # Only a server from before `groups` writes `group_titles`, so a stored title there is the newer one.+ title = _sparse_group({"title": titles[raw_key]}) if raw_key in titles else None+ if group_key and (group is not None or title is not None):+ stored[group_key] = {**(group or {}), **(title or {})}+ return stored+++def stored_customization(customization: Any) -> dict[str, Any]:+ customization = normalize_dashboard_customization(customization)+ tile_spacing = customization.get("tile_spacing")+ layout_compaction = customization.get("layout_compaction")+ stored: dict[str, Any] = {}+ if isinstance(tile_spacing, str) and tile_spacing in DASHBOARD_GRID_SPACING_GAPS:+ stored["tile_spacing"] = tile_spacing+ if isinstance(layout_compaction, str) and layout_compaction in DASHBOARD_GRID_COMPACTION_MODES:+ stored["layout_compaction"] = layout_compaction+ groups = stored_groups(customization)+ if groups:+ stored["groups"] = groups+ return storeddiff --git a/products/dashboards/backend/migrations/0028_dashboardtemplate_customization.py b/products/dashboards/backend/migrations/0028_dashboardtemplate_customization.pynew file mode 100644index 000000000000..41b81b10347b--- /dev/null+++ b/products/dashboards/backend/migrations/0028_dashboardtemplate_customization.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("dashboards", "0027_untrack_dashboard_restriction_level"),+ ]++ operations = [+ migrations.AddField(+ model_name="dashboardtemplate",+ name="customization",+ field=models.JSONField(blank=True, null=True),+ ),+ ]diff --git a/products/dashboards/backend/migrations/max_migration.txt b/products/dashboards/backend/migrations/max_migration.txtindex dbf724783a1a..72ec7a7a5272 100644--- a/products/dashboards/backend/migrations/max_migration.txt+++ b/products/dashboards/backend/migrations/max_migration.txt@@ -1 +1 @@-0027_untrack_dashboard_restriction_level+0028_dashboardtemplate_customizationdiff --git a/products/dashboards/backend/models/dashboard_templates.py b/products/dashboards/backend/models/dashboard_templates.pyindex 7a1532ee93c3..05dcb22938d2 100644--- a/products/dashboards/backend/models/dashboard_templates.py+++ b/products/dashboards/backend/models/dashboard_templates.py@@ -28,6 +28,7 @@ class DashboardTemplate(UUIDTModel, RootTeamMixin):dashboard_filters = models.JSONField(null=True, blank=True)tiles = models.JSONField(blank=True, null=True)variables = models.JSONField(null=True, blank=True)+ customization = models.JSONField(null=True, blank=True)tags: ArrayField = ArrayField(models.CharField(max_length=255), blank=True, null=True)created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 35a7c9b90b12..95619f62ab32 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -7,6 +7,106 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+/**+ * * `tight` - tight+ * * `condensed` - condensed+ * * `standard` - standard+ * * `relaxed` - relaxed+ * * `wide` - wide+ */+export type TileSpacingEnumApi = (typeof TileSpacingEnumApi)[keyof typeof TileSpacingEnumApi]++export const TileSpacingEnumApi = {+ Tight: 'tight',+ Condensed: 'condensed',+ Standard: 'standard',+ Relaxed: 'relaxed',+ Wide: 'wide',+} as const++/**+ * * `vertical` - vertical+ * * `horizontal` - horizontal+ * * `stable` - stable+ */+export type LayoutCompactionEnumApi = (typeof LayoutCompactionEnumApi)[keyof typeof LayoutCompactionEnumApi]++export const LayoutCompactionEnumApi = {+ Vertical: 'vertical',+ Horizontal: 'horizontal',+ Stable: 'stable',+} as const++/**+ * * `blue` - Blue+ * * `purple` - Purple+ * * `green` - Green+ * * `yellow` - Yellow+ * * `orange` - Orange+ * * `red` - Red+ */+export type DashboardTileGroupColorEnumApi =+ (typeof DashboardTileGroupColorEnumApi)[keyof typeof DashboardTileGroupColorEnumApi]++export const DashboardTileGroupColorEnumApi = {+ Blue: 'blue',+ Purple: 'purple',+ Green: 'green',+ Yellow: 'yellow',+ Orange: 'orange',+ Red: 'red',+} as const++export interface DashboardTileGroupApi {+ /**+ * Heading for the group. When it is blank or omitted, the heading shows the number of tiles.+ * @maxLength 200+ */+ title?: string+ /** Whether the group starts closed. Defaults to false. When a viewer opens or closes the group, their browser keeps that choice and it wins over this default. A closed group loads its tiles when a viewer opens it. */+ collapsed?: boolean+ /** Color of a dot before the group heading. Null or omitted shows no dot.+ *+ * * `blue` - Blue+ * * `purple` - Purple+ * * `green` - Green+ * * `yellow` - Yellow+ * * `orange` - Orange+ * * `red` - Red */+ color?: DashboardTileGroupColorEnumApi | null+}++/**+ * Settings for tile groups, keyed by the tiles' group_key. Each group shows as a band of its tiles under a heading that viewers can open and close. Viewers who do not have bands yet see only the group title above its tiles. A write replaces the whole map. Send an empty object or null to remove all group settings.+ */+export type DashboardCustomizationApiGroups = { [key: string]: DashboardTileGroupApi }++/**+ * Deprecated: use groups. Titles for tile groups, keyed by group_key. A write replaces all titles and keeps the other group settings. Send an empty object or null to clear titles. Do not send it with groups.+ */+export type DashboardCustomizationApiGroupTitles = { [key: string]: string }++export interface DashboardCustomizationApi {+ /** Named tile density preset.+ *+ * * `tight` - tight+ * * `condensed` - condensed+ * * `standard` - standard+ * * `relaxed` - relaxed+ * * `wide` - wide */+ tile_spacing?: TileSpacingEnumApi+ /** How tiles rearrange after a move or resize. vertical stacks tiles upward, horizontal stacks tiles to the left, and stable preserves positions while moving colliding tiles.+ *+ * * `vertical` - vertical+ * * `horizontal` - horizontal+ * * `stable` - stable */+ layout_compaction?: LayoutCompactionEnumApi+ /** Settings for tile groups, keyed by the tiles' group_key. Each group shows as a band of its tiles under a heading that viewers can open and close. Viewers who do not have bands yet see only the group title above its tiles. A write replaces the whole map. Send an empty object or null to remove all group settings. */+ groups?: DashboardCustomizationApiGroups+ /** Deprecated: use groups. Titles for tile groups, keyed by group_key. A write replaces all titles and keeps the other group settings. Send an empty object or null to clear titles. Do not send it with groups. */+ group_titles?: DashboardCustomizationApiGroupTitles+}+/*** * `engineering` - Engineering* * `data` - Data@@ -109,6 +209,8 @@ export interface DashboardTemplateApi {tags?: string[] | nulltiles?: unknownvariables?: unknown+ /** Display settings that a dashboard made from this template starts with: tile spacing, layout compaction, and the tile groups that tiles join through their group_key. */+ customization?: DashboardCustomizationApi | null/** @nullable */deleted?: boolean | null/** @nullable */@@ -162,6 +264,8 @@ export interface PatchedDashboardTemplateApi {tags?: string[] | nulltiles?: unknownvariables?: unknown+ /** Display settings that a dashboard made from this template starts with: tile spacing, layout compaction, and the tile groups that tiles join through their group_key. */+ customization?: DashboardCustomizationApi | null/** @nullable */deleted?: boolean | null/** @nullable */@@ -291,45 +395,6 @@ export type DashboardApiPersistedFilters = { [key: string]: unknown } | null*/export type DashboardApiPersistedVariables = { [key: string]: unknown } | null-/**- * * `blue` - Blue- * * `purple` - Purple- * * `green` - Green- * * `yellow` - Yellow- * * `orange` - Orange- * * `red` - Red- */-export type DashboardTileGroupColorEnumApi =- (typeof DashboardTileGroupColorEnumApi)[keyof typeof DashboardTileGroupColorEnumApi]--export const DashboardTileGroupColorEnumApi = {- Blue: 'blue',- Purple: 'purple',- Green: 'green',- Yellow: 'yellow',- Orange: 'orange',- Red: 'red',-} as const--export interface DashboardTileGroupApi {- /**- * Heading for the group. When it is blank or omitted, the heading shows the number of tiles.- * @maxLength 200- */- title?: string- /** Whether the group starts closed. Defaults to false. When a viewer opens or closes the group, their browser keeps that choice and it wins over this default. A closed group loads its tiles when a viewer opens it. */- collapsed?: boolean- /** Color of a dot before the group heading. Null or omitted shows no dot.- *- * * `blue` - Blue- * * `purple` - Purple- * * `green` - Green- * * `yellow` - Yellow- * * `orange` - Orange- * * `red` - Red */- color?: DashboardTileGroupColorEnumApi | null-}-/*** Settings for tile groups, keyed by the tiles' group_key. Each group shows as a band of its tiles under a heading that viewers can open and close. Viewers who do not have bands yet see only the group title above its tiles. A write replaces the whole map. Send an empty object or null to remove all group settings.* @nullable@@ -382,67 +447,6 @@ export interface BreakdownColorConfigApi {source?: BreakdownColorConfigSourceEnumApi | null}-/**- * * `tight` - tight- * * `condensed` - condensed- * * `standard` - standard- * * `relaxed` - relaxed- * * `wide` - wide- */-export type TileSpacingEnumApi = (typeof TileSpacingEnumApi)[keyof typeof TileSpacingEnumApi]--export const TileSpacingEnumApi = {- Tight: 'tight',- Condensed: 'condensed',- Standard: 'standard',- Relaxed: 'relaxed',- Wide: 'wide',-} as const--/**- * * `vertical` - vertical- * * `horizontal` - horizontal- * * `stable` - stable- */-export type LayoutCompactionEnumApi = (typeof LayoutCompactionEnumApi)[keyof typeof LayoutCompactionEnumApi]--export const LayoutCompactionEnumApi = {- Vertical: 'vertical',- Horizontal: 'horizontal',- Stable: 'stable',-} as const--/**- * Settings for tile groups, keyed by the tiles' group_key. Each group shows as a band of its tiles under a heading that viewers can open and close. Viewers who do not have bands yet see only the group title above its tiles. A write replaces the whole map. Send an empty object or null to remove all group settings.- */-export type DashboardCustomizationApiGroups = { [key: string]: DashboardTileGroupApi }--/**- * Deprecated: use groups. Titles for tile groups, keyed by group_key. A write replaces all titles and keeps the other group settings. Send an empty object or null to clear titles. Do not send it with groups.- */-export type DashboardCustomizationApiGroupTitles = { [key: string]: string }--export interface DashboardCustomizationApi {- /** Named tile density preset.- *- * * `tight` - tight- * * `condensed` - condensed- * * `standard` - standard- * * `relaxed` - relaxed- * * `wide` - wide */- tile_spacing?: TileSpacingEnumApi- /** How tiles rearrange after a move or resize. vertical stacks tiles upward, horizontal stacks tiles to the left, and stable preserves positions while moving colliding tiles.- *- * * `vertical` - vertical- * * `horizontal` - horizontal- * * `stable` - stable */- layout_compaction?: LayoutCompactionEnumApi- /** Settings for tile groups, keyed by the tiles' group_key. Each group shows as a band of its tiles under a heading that viewers can open and close. Viewers who do not have bands yet see only the group title above its tiles. A write replaces the whole map. Send an empty object or null to remove all group settings. */- groups?: DashboardCustomizationApiGroups- /** Deprecated: use groups. Titles for tile groups, keyed by group_key. A write replaces all titles and keeps the other group settings. Send an empty object or null to clear titles. Do not send it with groups. */- group_titles?: DashboardCustomizationApiGroupTitles-}-/*** Serializer mixin that handles tags for objects.*/diff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.tsindex 0b982a0bd74e..f497574dce90 100644--- a/products/dashboards/frontend/generated/api.zod.ts+++ b/products/dashboards/frontend/generated/api.zod.ts@@ -15,6 +15,10 @@ export const dashboardTemplatesCreateBodyDashboardDescriptionMax = 400export const dashboardTemplatesCreateBodyTagsItemMax = 255+export const dashboardTemplatesCreateBodyCustomizationOneGroupsTitleMax = 200++export const dashboardTemplatesCreateBodyCustomizationOneGroupTitlesMaxOne = 200+export const dashboardTemplatesCreateBodyImageUrlMax = 8201export const dashboardTemplatesCreateBodyAvailabilityContextsItemMax = 255@@ -26,6 +30,77 @@ export const DashboardTemplatesCreateBody = /* @__PURE__ */ zod.object({tags: zod.array(zod.string().max(dashboardTemplatesCreateBodyTagsItemMax)).nullish(),tiles: zod.unknown().optional(),variables: zod.unknown().optional(),+ customization: zod+ .union([+ zod.object({+ tile_spacing: zod+ .enum(['tight', 'condensed', 'standard', 'relaxed', 'wide'])+ .describe(+ '\* `tight` - tight\n\* `condensed` - condensed\n\* `standard` - standard\n\* `relaxed` - relaxed\n\* `wide` - wide'+ )+ .optional()+ .describe(+ 'Named tile density preset.\n\n\* `tight` - tight\n\* `condensed` - condensed\n\* `standard` - standard\n\* `relaxed` - relaxed\n\* `wide` - wide'+ ),+ layout_compaction: zod+ .enum(['vertical', 'horizontal', 'stable'])+ .describe('\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable')+ .optional()+ .describe(+ 'How tiles rearrange after a move or resize. vertical stacks tiles upward, horizontal stacks tiles to the left, and stable preserves positions while moving colliding tiles.\n\n\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable'+ ),+ groups: zod+ .record(+ zod.string(),+ zod.object({+ title: zod+ .string()+ .max(dashboardTemplatesCreateBodyCustomizationOneGroupsTitleMax)+ .optional()+ .describe(+ 'Heading for the group. When it is blank or omitted, the heading shows the number of tiles.'+ ),+ collapsed: zod+ .boolean()+ .optional()+ .describe(+ 'Whether the group starts closed. Defaults to false. When a viewer opens or closes the group, their browser keeps that choice and it wins over this default. A closed group loads its tiles when a viewer opens it.'+ ),+ color: zod+ .union([+ zod+ .enum(['blue', 'purple', 'green', 'yellow', 'orange', 'red'])+ .describe(+ '\* `blue` - Blue\n\* `purple` - Purple\n\* `green` - Green\n\* `yellow` - Yellow\n\* `orange` - Orange\n\* `red` - Red'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Color of a dot before the group heading. Null or omitted shows no dot.\n\n\* `blue` - Blue\n\* `purple` - Purple\n\* `green` - Green\n\* `yellow` - Yellow\n\* `orange` - Orange\n\* `red` - Red'+ ),+ })+ )+ .optional()+ .describe(+ "Settings for tile groups, keyed by the tiles' group_key. Each group shows as a band of its tiles under a heading that viewers can open and close. Viewers who do not have bands yet see only the group title above its tiles. A write replaces the whole map. Send an empty object or null to remove all group settings."+ ),+ group_titles: zod+ .record(+ zod.string(),+ zod.string().max(dashboardTemplatesCreateBodyCustomizationOneGroupTitlesMaxOne)+ )+ .optional()+ .describe(+ 'Deprecated: use groups. Titles for tile groups, keyed by group_key. A write replaces all titles and keeps the other group settings. Send an empty object or null to clear titles. Do not send it with groups.'+ ),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Display settings that a dashboard made from this template starts with: tile spacing, layout compaction, and the tile groups that tiles join through their group_key.'+ ),deleted: zod.boolean().nullish(),image_url: zod.string().max(dashboardTemplatesCreateBodyImageUrlMax).nullish(),scope: zod@@ -51,6 +126,10 @@ export const dashboardTemplatesUpdateBodyDashboardDescriptionMax = 400export const dashboardTemplatesUpdateBodyTagsItemMax = 255+export const dashboardTemplatesUpdateBodyCustomizationOneGroupsTitleMax = 200++export const dashboardTemplatesUpdateBodyCustomizationOneGroupTitlesMaxOne = 200+export const dashboardTemplatesUpdateBodyImageUrlMax = 8201export const dashboardTemplatesUpdateBodyAvailabilityContextsItemMax = 255@@ -62,6 +141,77 @@ export const DashboardTemplatesUpdateBody = /* @__PURE__ */ zod.object({tags: zod.array(zod.string().max(dashboardTemplatesUpdateBodyTagsItemMax)).nullish(),tiles: zod.unknown().optional(),variables: zod.unknown().optional(),+ customization: zod+ .union([+ zod.object({+ tile_spacing: zod+ .enum(['tight', 'condensed', 'standard', 'relaxed', 'wide'])+ .describe(+ '\* `tight` - tight\n\* `condensed` - condensed\n\* `standard` - standard\n\* `relaxed` - relaxed\n\* `wide` - wide'+ )+ .optional()+ .describe(+ 'Named tile density preset.\n\n\* `tight` - tight\n\* `condensed` - condensed\n\* `standard` - standard\n\* `relaxed` - relaxed\n\* `wide` - wide'+ ),+ layout_compaction: zod+ .enum(['vertical', 'horizontal', 'stable'])+ .describe('\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable')+ .optional()+ .describe(+ 'How tiles rearrange after a move or resize. vertical stacks tiles upward, horizontal stacks tiles to the left, and stable preserves positions while moving colliding tiles.\n\n\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable'+ ),+ groups: zod+ .record(+ zod.string(),+ zod.object({+ title: zod+ .string()+ .max(dashboardTemplatesUpdateBodyCustomizationOneGroupsTitleMax)+ .optional()+ .describe(+ 'Heading for the group. When it is blank or omitted, the heading shows the number of tiles.'+ ),+ collapsed: zod+ .boolean()+ .optional()+ .describe(+ 'Whether the group starts closed. Defaults to false. When a viewer opens or closes the group, their browser keeps that choice and it wins over this default. A closed group loads its tiles when a viewer opens it.'+ ),+ color: zod+ .union([+ zod+ .enum(['blue', 'purple', 'green', 'yellow', 'orange', 'red'])+ .describe(+ '\* `blue` - Blue\n\* `purple` - Purple\n\* `green` - Green\n\* `yellow` - Yellow\n\* `orange` - Orange\n\* `red` - Red'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Color of a dot before the group heading. Null or omitted shows no dot.\n\n\* `blue` - Blue\n\* `purple` - Purple\n\* `green` - Green\n\* `yellow` - Yellow\n\* `orange` - Orange\n\* `red` - Red'+ ),+ })+ )+ .optional()+ .describe(+ "Settings for tile groups, keyed by the tiles' group_key. Each group shows as a band of its tiles under a heading that viewers can open and close. Viewers who do not have bands yet see only the group title above its tiles. A write replaces the whole map. Send an empty object or null to remove all group settings."+ ),+ group_titles: zod+ .record(+ zod.string(),+ zod.string().max(dashboardTemplatesUpdateBodyCustomizationOneGroupTitlesMaxOne)+ )+ .optional()+ .describe(+ 'Deprecated: use groups. Titles for tile groups, keyed by group_key. A write replaces all titles and keeps the other group settings. Send an empty object or null to clear titles. Do not send it with groups.'+ ),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Display settings that a dashboard made from this template starts with: tile spacing, layout compaction, and the tile groups that tiles join through their group_key.'+ ),deleted: zod.boolean().nullish(),image_url: zod.string().max(dashboardTemplatesUpdateBodyImageUrlMax).nullish(),scope: zod@@ -87,6 +237,10 @@ export const dashboardTemplatesPartialUpdateBodyDashboardDescriptionMax = 400export const dashboardTemplatesPartialUpdateBodyTagsItemMax = 255+export const dashboardTemplatesPartialUpdateBodyCustomizationOneGroupsTitleMax = 200++export const dashboardTemplatesPartialUpdateBodyCustomizationOneGroupTitlesMaxOne = 200+export const dashboardTemplatesPartialUpdateBodyImageUrlMax = 8201export const dashboardTemplatesPartialUpdateBodyAvailabilityContextsItemMax = 255@@ -98,6 +252,77 @@ export const DashboardTemplatesPartialUpdateBody = /* @__PURE__ */ zod.object({tags: zod.array(zod.string().max(dashboardTemplatesPartialUpdateBodyTagsItemMax)).nullish(),tiles: zod.unknown().optional(),variables: zod.unknown().optional(),+ customization: zod+ .union([+ zod.object({+ tile_spacing: zod+ .enum(['tight', 'condensed', 'standard', 'relaxed', 'wide'])+ .describe(+ '\* `tight` - tight\n\* `condensed` - condensed\n\* `standard` - standard\n\* `relaxed` - relaxed\n\* `wide` - wide'+ )+ .optional()+ .describe(+ 'Named tile density preset.\n\n\* `tight` - tight\n\* `condensed` - condensed\n\* `standard` - standard\n\* `relaxed` - relaxed\n\* `wide` - wide'+ ),+ layout_compaction: zod+ .enum(['vertical', 'horizontal', 'stable'])+ .describe('\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable')+ .optional()+ .describe(+ 'How tiles rearrange after a move or resize. vertical stacks tiles upward, horizontal stacks tiles to the left, and stable preserves positions while moving colliding tiles.\n\n\* `vertical` - vertical\n\* `horizontal` - horizontal\n\* `stable` - stable'+ ),+ groups: zod+ .record(+ zod.string(),+ zod.object({+ title: zod+ .string()+ .max(dashboardTemplatesPartialUpdateBodyCustomizationOneGroupsTitleMax)+ .optional()+ .describe(+ 'Heading for the group. When it is blank or omitted, the heading shows the number of tiles.'+ ),+ collapsed: zod+ .boolean()+ .optional()+ .describe(+ 'Whether the group starts closed. Defaults to false. When a viewer opens or closes the group, their browser keeps that choice and it wins over this default. A closed group loads its tiles when a viewer opens it.'+ ),+ color: zod+ .union([+ zod+ .enum(['blue', 'purple', 'green', 'yellow', 'orange', 'red'])+ .describe(+ '\* `blue` - Blue\n\* `purple` - Purple\n\* `green` - Green\n\* `yellow` - Yellow\n\* `orange` - Orange\n\* `red` - Red'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Color of a dot before the group heading. Null or omitted shows no dot.\n\n\* `blue` - Blue\n\* `purple` - Purple\n\* `green` - Green\n\* `yellow` - Yellow\n\* `orange` - Orange\n\* `red` - Red'+ ),+ })+ )+ .optional()+ .describe(+ "Settings for tile groups, keyed by the tiles' group_key. Each group shows as a band of its tiles under a heading that viewers can open and close. Viewers who do not have bands yet see only the group title above its tiles. A write replaces the whole map. Send an empty object or null to remove all group settings."+ ),+ group_titles: zod+ .record(+ zod.string(),+ zod.string().max(dashboardTemplatesPartialUpdateBodyCustomizationOneGroupTitlesMaxOne)+ )+ .optional()+ .describe(+ 'Deprecated: use groups. Titles for tile groups, keyed by group_key. A write replaces all titles and keeps the other group settings. Send an empty object or null to clear titles. Do not send it with groups.'+ ),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Display settings that a dashboard made from this template starts with: tile spacing, layout compaction, and the tile groups that tiles join through their group_key.'+ ),deleted: zod.boolean().nullish(),image_url: zod.string().max(dashboardTemplatesPartialUpdateBodyImageUrlMax).nullish(),scope: zoddiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3d350dd26cc1..6fdab46c5a1a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -29561,6 +29561,8 @@ export namespace Schemas {tags?: string[] | null;tiles?: unknown;variables?: unknown;+ /** Display settings that a dashboard made from this template starts with: tile spacing, layout compaction, and the tile groups that tiles join through their group_key. */+ customization?: DashboardCustomization | null;/** @nullable */deleted?: boolean | null;/** @nullable */@@ -84406,6 +84408,8 @@ export namespace Schemas {tags?: string[] | null;tiles?: unknown;variables?: unknown;+ /** Display settings that a dashboard made from this template starts with: tile spacing, layout compaction, and the tile groups that tiles join through their group_key. */+ customization?: DashboardCustomization | null;/** @nullable */deleted?: boolean | null;/** @nullable */