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): Add new widgets to end of dashboard (#63824)

Matt Puab43b6121cb7b
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 3f2fe467c1ca..c01be04caf91 100644
--- a/.agents/skills/manage-dashboard-widgets/references/layout-and-ux.md
+++ b/.agents/skills/manage-dashboard-widgets/references/layout-and-ux.md
@@ -85,7 +85,7 @@ If a new widget type omits `minH`, users can only shrink to **4 rows**, not 3. A
- Title: **Add widget**; description: **Bring context from your different PostHog products into one dashboard.**
- `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 append on the **bottom row** of the dashboard (batch adds pack horizontally, then wrap)
+- 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.
- 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/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index 0912a8f3674d..f0f81a3387b1 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -57,6 +57,7 @@ export function DashboardItems(): JSX.Element {
dashboardWidgetsEnabled,
widgetResultsByTileId,
widgetRefreshStatus,
+ scrollToBottomSignal,
} = useValues(dashboardLogic)
const { layoutZoom = 1 } = useValues(dashboardLogic)
const {
@@ -94,6 +95,7 @@ export function DashboardItems(): JSX.Element {
const scrollAnimationRef = useRef<number | null>(null)
const scrollContainerRef = useRef<HTMLElement | null>(null)
const scrollContainerRectRef = useRef<DOMRect | null>(null)
+ const lastScrollSignalRef = useRef(scrollToBottomSignal)
useEffect(() => {
return () => {
@@ -107,6 +109,27 @@ export function DashboardItems(): JSX.Element {
scrollContainerRectRef.current = null
}
}, [])
+
+ // Scroll the dashboard to the bottom when the logic requests it (e.g. after adding tiles).
+ // Two animation frames let React commit and react-grid-layout grow the container before we measure.
+ useEffect(() => {
+ if (scrollToBottomSignal === lastScrollSignalRef.current) {
+ return
+ }
+ lastScrollSignalRef.current = scrollToBottomSignal
+
+ let secondFrame = 0
+ const firstFrame = requestAnimationFrame(() => {
+ secondFrame = requestAnimationFrame(() => {
+ const scrollContainer = document.getElementById('main-content')
+ scrollContainer?.scrollTo({ top: scrollContainer.scrollHeight, behavior: 'smooth' })
+ })
+ })
+ return () => {
+ cancelAnimationFrame(firstFrame)
+ cancelAnimationFrame(secondFrame)
+ }
+ }, [scrollToBottomSignal])
const className = clsx({
'dashboard-view-mode': !layoutEditMode,
'dashboard-edit-mode': layoutEditMode,
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index 398424a2158d..fc8eba3047d9 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -292,6 +292,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
toggleAddWidgetSelectedType: (widgetType: string) => ({ widgetType }),
clearAddWidgetSelectedTypes: true,
addWidgetTileFinished: true,
+ /** One-shot signal asking the view to scroll the dashboard to the bottom (e.g. after adding tiles). */
+ requestScrollToBottom: true,
/** Update a single refresh status. */
setRefreshStatus: (shortId: InsightShortId, loading = false, queued = false) => ({ shortId, loading, queued }),
/** Update multiple refresh statuses. */
@@ -1320,6 +1322,13 @@ export const dashboardLogic = kea<dashboardLogicType>([
addWidgetTileFinished: () => false,
},
],
+ // Incremented on each scroll-to-bottom request; the view effects on the change.
+ scrollToBottomSignal: [
+ 0,
+ {
+ requestScrollToBottom: (state) => state + 1,
+ },
+ ],
addWidgetModalOpen: [
false,
{
@@ -2577,6 +2586,10 @@ export const dashboardLogic = kea<dashboardLogicType>([
} as DashboardType<InsightModel>)
if (dashboard) {
dashboardsModel.actions.updateDashboardSuccess(dashboard)
+
+ // New tiles are stacked at the bottom (backend), so ask the view to scroll
+ // down once they've rendered to reveal what was just added.
+ actions.requestScrollToBottom()
}
}
diff --git a/products/dashboards/backend/api/test/test_dashboard_widgets.py b/products/dashboards/backend/api/test/test_dashboard_widgets.py
index 7e37ecfd0415..0a35c7207141 100644
--- a/products/dashboards/backend/api/test/test_dashboard_widgets.py
+++ b/products/dashboards/backend/api/test/test_dashboard_widgets.py
@@ -915,10 +915,11 @@ class TestDashboardWidgets(APIBaseTest):
assert len(tiles) == 2
assert tiles[0]["widget"]["widget_type"] == "error_tracking_list"
assert tiles[1]["widget"]["widget_type"] == "error_tracking_list"
+ # Batch adds stack downward so vertical compaction keeps each tile at the bottom.
assert tiles[0]["layouts"]["sm"]["y"] == 0
assert tiles[0]["layouts"]["sm"]["x"] == 0
- assert tiles[1]["layouts"]["sm"]["y"] == 0
- assert tiles[1]["layouts"]["sm"]["x"] == 6
+ assert tiles[1]["layouts"]["sm"]["y"] == 5
+ assert tiles[1]["layouts"]["sm"]["x"] == 0
@override_settings(IN_UNIT_TESTING=True)
def test_batch_create_widget_tiles_rejects_empty_list(self) -> None:
diff --git a/products/dashboards/backend/test/test_widget_layouts.py b/products/dashboards/backend/test/test_widget_layouts.py
index 78bdf884ee76..32abd492506a 100644
--- a/products/dashboards/backend/test/test_widget_layouts.py
+++ b/products/dashboards/backend/test/test_widget_layouts.py
@@ -1,55 +1,77 @@
+from parameterized import parameterized
+
from products.dashboards.backend.widget_layouts import stack_widget_layout_at_bottom
class TestWidgetLayouts:
"""Backend placement only reads `layouts.sm`.
- New widgets append to the bottom row of the dashboard (below the tallest tile),
- packing batch adds horizontally on that row. Mobile (`xs`) placement is still
- derived on the frontend; the backend mirrors sm → xs for API/schema completeness.
+ New widgets are placed at the bottom, anchored to the tallest column so the grid's
+ vertical compaction keeps them there; batch adds stack downward. Mobile (`xs`)
+ placement is still derived on the frontend; the backend mirrors sm → xs for
+ API/schema completeness.
"""
- def test_stack_widget_layout_at_bottom_appends_below_tallest_tile(self) -> None:
- existing = [
- {"x": 0, "y": 0, "w": 6, "h": 4},
- {"x": 6, "y": 0, "w": 6, "h": 11},
+ @parameterized.expand(
+ [
+ # Tall column on the right: the new tile must span it (x=6), otherwise vertical
+ # compaction would lift an x=0 tile up into the short left column's gap.
+ (
+ [{"x": 0, "y": 0, "w": 6, "h": 4}, {"x": 6, "y": 0, "w": 6, "h": 11}],
+ {"x": 6, "y": 11, "w": 6, "h": 5},
+ ),
+ # Tall column on the left: anchoring at x=0 already spans it, so it stays put.
+ (
+ [{"x": 0, "y": 0, "w": 6, "h": 10}, {"x": 6, "y": 0, "w": 6, "h": 4}],
+ {"x": 0, "y": 10, "w": 6, "h": 5},
+ ),
]
-
+ )
+ def test_stack_widget_layout_at_bottom_anchors_to_tallest_column(
+ self, existing: list[dict], expected_sm: dict
+ ) -> None:
layouts = stack_widget_layout_at_bottom(
widget_type="error_tracking_list",
existing_sm_layouts=existing,
)
- assert layouts["sm"] == {"x": 0, "y": 11, "w": 6, "h": 5}
+ assert layouts["sm"] == expected_sm
assert layouts["xs"] == layouts["sm"]
- def test_stack_widget_layout_at_bottom_packs_batch_on_same_row(self) -> None:
+ def test_stack_widget_layout_at_bottom_stacks_batch_below_tallest_column(self) -> None:
+ # Batch adds stack downward in the tallest column's span so vertical compaction
+ # keeps every new tile at the bottom (a horizontal row would drift up on a staircase).
existing = [
{"x": 0, "y": 0, "w": 6, "h": 4},
- {"x": 6, "y": 0, "w": 6, "h": 9},
- {"x": 0, "y": 4, "w": 3, "h": 2},
- {"x": 3, "y": 4, "w": 3, "h": 5},
- {"x": 0, "y": 9, "w": 12, "h": 2},
- {"x": 0, "y": 11, "w": 4, "h": 3},
- {"x": 4, "y": 11, "w": 8, "h": 7},
- ]
- pending = [
- {"x": 0, "y": 18, "w": 6, "h": 4},
- {"x": 0, "y": 22, "w": 6, "h": 3},
+ {"x": 6, "y": 0, "w": 6, "h": 11},
]
- layouts = stack_widget_layout_at_bottom(
+ first = stack_widget_layout_at_bottom(
+ widget_type="error_tracking_list",
+ existing_sm_layouts=existing,
+ )
+ second = stack_widget_layout_at_bottom(
+ widget_type="error_tracking_list",
+ existing_sm_layouts=existing,
+ pending_sm_layouts=[first["sm"]],
+ )
+ third = stack_widget_layout_at_bottom(
widget_type="error_tracking_list",
existing_sm_layouts=existing,
- pending_sm_layouts=pending,
+ pending_sm_layouts=[first["sm"], second["sm"]],
)
- assert layouts["sm"] == {"x": 6, "y": 18, "w": 6, "h": 5}
+ assert first["sm"] == {"x": 6, "y": 11, "w": 6, "h": 5}
+ assert second["sm"] == {"x": 6, "y": 16, "w": 6, "h": 5}
+ assert third["sm"] == {"x": 6, "y": 21, "w": 6, "h": 5}
- def test_stack_widget_layout_at_bottom_ignores_short_column_gaps(self) -> None:
+ def test_stack_widget_layout_at_bottom_narrow_tile_anchors_to_tallest_column(self) -> None:
+ # Tallest column is in the middle (x=8); a narrow new tile must overlap it so
+ # compaction can't pull it above the true bottom.
existing = [
- {"x": 0, "y": 0, "w": 6, "h": 10},
- {"x": 6, "y": 0, "w": 6, "h": 4},
+ {"x": 0, "y": 0, "w": 6, "h": 3},
+ {"x": 6, "y": 0, "w": 6, "h": 5},
+ {"x": 8, "y": 5, "w": 4, "h": 9},
]
layouts = stack_widget_layout_at_bottom(
@@ -57,9 +79,12 @@ class TestWidgetLayouts:
existing_sm_layouts=existing,
)
- assert layouts["sm"] == {"x": 0, "y": 10, "w": 6, "h": 5}
+ placement = layouts["sm"]
+ assert placement["y"] == 14
+ # column span must include the tallest column (8)
+ assert placement["x"] <= 8 < placement["x"] + placement["w"]
- def test_stack_widget_layout_at_bottom_packs_batch_side_by_side(self) -> None:
+ def test_stack_widget_layout_at_bottom_stacks_batch_on_empty_dashboard(self) -> None:
first = stack_widget_layout_at_bottom(
widget_type="error_tracking_list",
existing_sm_layouts=[],
@@ -71,22 +96,4 @@ class TestWidgetLayouts:
)
assert first["sm"] == {"x": 0, "y": 0, "w": 6, "h": 5}
- assert second["sm"] == {"x": 6, "y": 0, "w": 6, "h": 5}
-
- def test_stack_widget_layout_at_bottom_wraps_to_next_row_when_bottom_row_full(self) -> None:
- existing = [
- {"x": 0, "y": 0, "w": 6, "h": 5},
- {"x": 6, "y": 0, "w": 6, "h": 5},
- ]
- pending = [
- {"x": 0, "y": 0, "w": 6, "h": 5},
- {"x": 6, "y": 0, "w": 6, "h": 5},
- ]
-
- layouts = stack_widget_layout_at_bottom(
- widget_type="error_tracking_list",
- existing_sm_layouts=existing,
- pending_sm_layouts=pending,
- )
-
- assert layouts["sm"] == {"x": 0, "y": 5, "w": 6, "h": 5}
+ assert second["sm"] == {"x": 0, "y": 5, "w": 6, "h": 5}
diff --git a/products/dashboards/backend/widget_layouts.py b/products/dashboards/backend/widget_layouts.py
index e6acd833d9a8..50ebc2e426b6 100644
--- a/products/dashboards/backend/widget_layouts.py
+++ b/products/dashboards/backend/widget_layouts.py
@@ -6,43 +6,17 @@ from products.dashboards.backend.constants import DASHBOARD_GRID_COLUMN_COUNT
from products.dashboards.backend.widget_catalog import get_default_widget_layouts
-def _rectangles_overlap(
- x1: int,
- y1: int,
- w1: int,
- h1: int,
- x2: int,
- y2: int,
- w2: int,
- h2: int,
-) -> bool:
- return x1 < x2 + w2 and x1 + w1 > x2 and y1 < y2 + h2 and y1 + h1 > y2
-
-
-def _layout_overlaps_any(
- sm_layouts: list[dict[str, Any]],
- x: int,
- y: int,
- w: int,
- h: int,
-) -> bool:
+def _column_heights(sm_layouts: list[dict[str, Any]]) -> list[int]:
+ """Per-column bottom edge (max y + h). The overall dashboard bottom is ``max(...)``."""
+ heights = [0] * DASHBOARD_GRID_COLUMN_COUNT
for layout in sm_layouts:
- lx = int(layout.get("x", 0))
+ lx = max(0, int(layout.get("x", 0)))
ly = int(layout.get("y", 0))
lw = max(1, min(int(layout.get("w", 1)), DASHBOARD_GRID_COLUMN_COUNT))
lh = max(1, int(layout.get("h", 1)))
- if _rectangles_overlap(x, y, w, h, lx, ly, lw, lh):
- return True
- return False
-
-
-def _dashboard_bottom_y(sm_layouts: list[dict[str, Any]]) -> int:
- bottom_y = 0
- for layout in sm_layouts:
- y = int(layout.get("y", 0))
- h = max(1, int(layout.get("h", 1)))
- bottom_y = max(bottom_y, y + h)
- return bottom_y
+ for column in range(lx, min(lx + lw, DASHBOARD_GRID_COLUMN_COUNT)):
+ heights[column] = max(heights[column], ly + lh)
+ return heights
def _find_bottom_row_placement(
@@ -52,23 +26,24 @@ def _find_bottom_row_placement(
width: int,
height: int,
) -> dict[str, int]:
- """Place a widget on the bottom row of the dashboard, packing batch adds horizontally."""
+ """Place a widget at the bottom of the dashboard, anchored to the tallest column.
+
+ The grid compacts vertically on render, so a tile only stays at the bottom if its
+ column span includes the column that defines the bottom — otherwise compaction lifts
+ it up into a shorter column's gap (the "lands in the middle" bug). Batch adds stack
+ downward: each tile counts the previously placed ones (``pending_sm_layouts``), so the
+ second lands below the first, and so on — a horizontal row can't survive compaction on
+ a staircased dashboard.
+ """
w = max(1, min(width, DASHBOARD_GRID_COLUMN_COUNT))
h = max(1, height)
- pending = pending_sm_layouts or []
- all_layouts = [*existing_sm_layouts, *pending]
-
- if pending:
- placement_y = int(pending[0].get("y", 0))
- else:
- placement_y = _dashboard_bottom_y(existing_sm_layouts)
-
- for x in range(0, DASHBOARD_GRID_COLUMN_COUNT - w + 1):
- if not _layout_overlaps_any(all_layouts, x, placement_y, w, h):
- return {"x": x, "y": placement_y, "w": w, "h": h}
+ all_layouts = [*existing_sm_layouts, *(pending_sm_layouts or [])]
- next_y = _dashboard_bottom_y(all_layouts)
- return {"x": 0, "y": next_y, "w": w, "h": h}
+ heights = _column_heights(all_layouts)
+ placement_y = max(heights)
+ tallest_column = next(column for column, column_height in enumerate(heights) if column_height == placement_y)
+ x = min(tallest_column, DASHBOARD_GRID_COLUMN_COUNT - w)
+ return {"x": x, "y": placement_y, "w": w, "h": h}
def stack_widget_layout_at_bottom(