Skip to content

: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.

fix(dashboards): place new widgets below layout-less tiles (#64114)

Matt Puad0a6fdefc6c0
diff --git a/.agents/skills/manage-dashboard-widgets/references/layout-and-ux.md b/.agents/skills/manage-dashboard-widgets/references/layout-and-ux.md
index c01be04caf91..ea052234718d 100644
--- a/.agents/skills/manage-dashboard-widgets/references/layout-and-ux.md
+++ b/.agents/skills/manage-dashboard-widgets/references/layout-and-ux.md
@@ -86,6 +86,7 @@ If a new widget type omits `minH`, users can only shrink to **4 rows**, not 3. A
- `AddWidgetModal` supports **multi-select** — pick one or more catalog variants, then "Add N widgets"
- `dashboardLogic.addWidgetTiles` → `POST .../widgets/batch/` (1–10 tiles)
- Backend placement: `widget_layouts.stack_widget_layout_at_bottom` — new tiles land at the **bottom**, anchored to the tallest column so the grid's vertical compaction keeps them there; batch adds stack downward (a horizontal row would drift up on a staircased dashboard). On add, `dashboardLogic` scrolls `#main-content` to the bottom so the new tile is visible.
+- Placement counts **layout-less tiles** too: `collect_dashboard_sm_layouts_for_dashboard` synthesizes a bottom placement for every tile with `layouts = {}` (e.g. an insight added via the insight API — positioned by the frontend on render, persisted only on a layout save). Without this the backend under-counts the height and drops the widget into a mid-page gap (the "lands in the 2nd row" bug).
- REST/MCP add: `dashboard-widgets-batch-add` — same batch endpoint; one tile = single-element `widgets`. See [mcp.md](mcp.md)
## NEW badge (Add menu)
diff --git a/products/dashboards/backend/api/test/test_dashboard_widgets.py b/products/dashboards/backend/api/test/test_dashboard_widgets.py
index 0a35c7207141..d5c21013f3ce 100644
--- a/products/dashboards/backend/api/test/test_dashboard_widgets.py
+++ b/products/dashboards/backend/api/test/test_dashboard_widgets.py
@@ -23,6 +23,7 @@ from products.dashboards.backend.models.dashboard_templates import DashboardTemp
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.dashboards.backend.models.dashboard_widget import DashboardWidget
from products.dashboards.backend.widget_registry import EXPECTED_WIDGET_TYPES
+from products.product_analytics.backend.models.insight import Insight
class TestDashboardWidgets(APIBaseTest):
@@ -921,6 +922,44 @@ class TestDashboardWidgets(APIBaseTest):
assert tiles[1]["layouts"]["sm"]["y"] == 5
assert tiles[1]["layouts"]["sm"]["x"] == 0
+ @parameterized.expand(
+ [
+ # (persisted_sm_layouts, layoutless_count, expected_y)
+ # Insights added to a dashboard get `layouts = {}` until a layout save; the backend
+ # must still count them so a new widget lands below, not in a mid-page gap.
+ # Layout-less tiles pack two-per-row at 6×5 (y boundaries every 2 tiles).
+ ("one_layoutless", [], 1, 5),
+ ("two_layoutless", [], 2, 5),
+ ("three_layoutless", [], 3, 10),
+ ("five_layoutless", [], 5, 15),
+ # Persisted full-width header (h=2) + one layout-less tile packed below it (y=2,h=5 → 7).
+ ("mixed_persisted_and_layoutless", [{"x": 0, "y": 0, "w": 12, "h": 2}], 1, 7),
+ ]
+ )
+ @override_settings(IN_UNIT_TESTING=True)
+ def test_widget_lands_below_tiles_with_no_persisted_layout(
+ self, _name: str, persisted_sm_layouts: list[dict], layoutless_count: int, expected_y: int
+ ) -> None:
+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})
+ dashboard = Dashboard.objects.get(id=dashboard_id)
+ for sm in persisted_sm_layouts:
+ insight = Insight.objects.create(team=self.team, name="persisted")
+ DashboardTile.objects.create(dashboard=dashboard, team_id=self.team.id, insight=insight, layouts={"sm": sm})
+ for _ in range(layoutless_count):
+ insight = Insight.objects.create(team=self.team, name="layoutless")
+ DashboardTile.objects.create(dashboard=dashboard, team_id=self.team.id, insight=insight, layouts={})
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/dashboards/{dashboard_id}/widgets/batch/",
+ {"widgets": [{"widget_type": "error_tracking_list", "config": {"limit": 5}}]},
+ )
+ assert response.status_code == status.HTTP_201_CREATED
+
+ # The widget must land below the tallest column, not in a mid-page gap.
+ sm = response.json()["tiles"][0]["layouts"]["sm"]
+ assert sm["y"] == expected_y
+ assert sm["x"] == 0
+
@override_settings(IN_UNIT_TESTING=True)
def test_batch_create_widget_tiles_rejects_empty_list(self) -> None:
dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})
diff --git a/products/dashboards/backend/widget_layouts.py b/products/dashboards/backend/widget_layouts.py
index 50ebc2e426b6..f59f9d8445eb 100644
--- a/products/dashboards/backend/widget_layouts.py
+++ b/products/dashboards/backend/widget_layouts.py
@@ -1,10 +1,17 @@
from __future__ import annotations
+import json
from typing import Any
from products.dashboards.backend.constants import DASHBOARD_GRID_COLUMN_COUNT
from products.dashboards.backend.widget_catalog import get_default_widget_layouts
+# Fallback size for a tile that has no persisted layout. Matches the dominant frontend
+# default (`tileLayouts.ts` 6×5) and the widget catalog default, so synthetic placements
+# approximate the rendered height closely enough to keep new widgets below everything.
+_DEFAULT_TILE_WIDTH = 6
+_DEFAULT_TILE_HEIGHT = 5
+
def _column_heights(sm_layouts: list[dict[str, Any]]) -> list[int]:
"""Per-column bottom edge (max y + h). The overall dashboard bottom is ``max(...)``."""
@@ -74,11 +81,55 @@ def collect_dashboard_sm_layouts(dashboard_tiles: list[Any]) -> list[dict[str, A
return sm_layouts
+def _pack_at_bottom(column_heights: list[int], width: int, height: int) -> dict[str, int]:
+ """Lowest-segment greedy placement, mirroring the dirty-tile packing in
+ ``frontend/src/scenes/dashboard/tileLayouts.ts``: pick the leftmost ``width``-wide
+ segment with the lowest top, ties keeping the leftmost."""
+ w = max(1, min(width, DASHBOARD_GRID_COLUMN_COUNT))
+ h = max(1, height)
+ best_x = 0
+ best_y = max(column_heights[0:w])
+ for x in range(1, DASHBOARD_GRID_COLUMN_COUNT - w + 1):
+ segment_top = max(column_heights[x : x + w])
+ if segment_top < best_y:
+ best_x = x
+ best_y = segment_top
+ return {"x": best_x, "y": best_y, "w": w, "h": h}
+
+
def collect_dashboard_sm_layouts_for_dashboard(dashboard: Any) -> list[dict[str, Any]]:
+ """Existing ``sm`` layouts, plus a synthetic bottom placement for every tile that has
+ no persisted layout, so widget placement counts the dashboard's true rendered height.
+
+ Tiles added to a dashboard without a layout (e.g. an insight added via the insight API)
+ default to ``layouts = {}``; the frontend stacks them at the bottom on render but only
+ persists that on a layout save. Reading only persisted ``sm`` layouts would under-count
+ the height and drop new widgets into a mid-page gap (the "lands in the 2nd row" bug)."""
sm_layouts: list[dict[str, Any]] = []
- for layouts in dashboard.tiles.filter(deleted=False).values_list("layouts", flat=True):
- if isinstance(layouts, dict):
- sm_layout = layouts.get("sm")
- if isinstance(sm_layout, dict):
- sm_layouts.append(sm_layout)
+ layoutless_count = 0
+ # `deleted` is nullable with no default, so live tiles carry NULL — `filter(deleted=False)`
+ # would miss them (NULL never equals False). Exclude only explicit deletes.
+ for layouts in dashboard.tiles.exclude(deleted=True).values_list("layouts", flat=True):
+ if isinstance(layouts, str):
+ try:
+ layouts = json.loads(layouts)
+ except (ValueError, TypeError):
+ layouts = None
+ sm_layout = layouts.get("sm") if isinstance(layouts, dict) else None
+ if isinstance(sm_layout, dict):
+ sm_layouts.append(sm_layout)
+ else:
+ layoutless_count += 1
+
+ if layoutless_count == 0:
+ return sm_layouts
+
+ # Stack layout-less tiles at the bottom (mirroring the frontend) so they contribute
+ # to the height a new widget is placed below.
+ column_heights = _column_heights(sm_layouts)
+ for _ in range(layoutless_count):
+ placement = _pack_at_bottom(column_heights, _DEFAULT_TILE_WIDTH, _DEFAULT_TILE_HEIGHT)
+ sm_layouts.append(placement)
+ for column in range(placement["x"], placement["x"] + placement["w"]):
+ column_heights[column] = placement["y"] + placement["h"]
return sm_layouts