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.

feat(dashboards): add bulk deletion to dashboard lists and mcp (#117817)

Matt Pua83f1a2b0b667
diff --git a/.agents/skills/building-product-empty-states/SKILL.md b/.agents/skills/building-product-empty-states/SKILL.md
index 607494c634f2..a599c9ec5910 100644
--- a/.agents/skills/building-product-empty-states/SKILL.md
+++ b/.agents/skills/building-product-empty-states/SKILL.md
@@ -36,7 +36,7 @@ export const logsSetupLogic = createSetupDetectionLogic({
})
```
-`detect` composes freely: retry inside it with `retryWithBackoff`, return `unknown` for "cannot tell" (e.g. no access), return `waiting-for-data` from an opt-in flag + count check. When the query is a fresh event count, use `refresh: 'force_blocking'` - a cached pre-ingestion `[0,0]` would otherwise stick. `recheckActionTypes` re-detects immediately when app state changes elsewhere (a team-setting opt-in). `cacheHasData` remembers a has-data answer in localStorage so returning users skip the spinner and the query - use it for products with no boot-time probe. Add `revalidateCachedHasData` when the data can go away (entities users delete, recordings that expire, a lookback window): the cached answer still opens the gate at once, detection runs once in the background, and a `needs-setup` or `waiting-for-data` answer clears the cache so the next visit shows the empty state. It never replaces the mounted scene, so an open modal or a half-created entity survives. Plain `cacheHasData` is for ingested data that stays. Recheck actions stop re-detecting once the status is `has-data`, since their job is to flip the gate open after the first entity is created in place.
+`detect` composes freely: retry inside it with `retryWithBackoff`, return `unknown` for "cannot tell" (e.g. no access), return `waiting-for-data` from an opt-in flag + count check. When the query is a fresh event count, use `refresh: 'force_blocking'` - a cached pre-ingestion `[0,0]` would otherwise stick. `recheckActionTypes` re-detects immediately when app state changes elsewhere (a team-setting opt-in). `cacheHasData` remembers a has-data answer in localStorage so returning users skip the spinner and the query - use it for products with no boot-time probe. Add `revalidateCachedHasData` when the data can go away (entities users delete, recordings that expire, a lookback window): the cached answer still opens the gate at once, detection runs once in the background, and a `needs-setup` or `waiting-for-data` answer clears the cache so the next visit shows the empty state. It never replaces the mounted scene, so an open modal or a half-created entity survives. Plain `cacheHasData` is for ingested data that stays. Recheck actions stop re-detecting once the status is `has-data`, since their job is to flip the gate open after the first entity is created in place. For a creation-first product that must return to its empty state after its last entity is deleted, set `allowReturnToSetup: true`. Include successful creation, deletion, bulk deletion, and restore actions in `recheckActionTypes`. The factory then refreshes the count after those actions and clears its cached answer when the product becomes empty. Keep the default for data-based products so a background check cannot replace an active scene.
Products whose detection drives more than the gate (extra selectors, staged dashboards) keep a bespoke logic instead - template: `products/mcp_analytics/frontend/mcpAnalyticsOnboardingLogic.ts`. It must push the status from a listener and handle failure the same way the factory does:
diff --git a/.agents/skills/writing-pr-descriptions/SKILL.md b/.agents/skills/writing-pr-descriptions/SKILL.md
index 5b93efe503e9..296a437cdfc1 100644
--- a/.agents/skills/writing-pr-descriptions/SKILL.md
+++ b/.agents/skills/writing-pr-descriptions/SKILL.md
@@ -1,11 +1,14 @@
---
name: writing-pr-descriptions
description: >-
- Shapes a PR body into something a reviewer understands at a glance.
- Use ALWAYS before writing or editing a PR description, before `gh pr create` or `gh pr edit --body`, and when asked to improve an existing description.
- Captures the actor's underlying need in Problem without presupposing the solution, puts the visible effect first in Changes and the mechanism under it, routes each remaining fact to the form that carries it fastest (bullet, table, diagram, screenshot, collapsed block), cuts everything a reviewer does not need, then holds what survives to a checkable shape: one fact per bullet, sentences under 25 words, active voice, no idioms.
- Makes the body stand alone, so a reader who opens no files still knows the product intent and what the PR does, sizes the body to the change so a small PR reads as small, and makes every claim either linked to its evidence or labeled as unchecked.
- Not for commit messages (see AGENTS.md, "Commit types") or user-facing product copy (see `/writing-user-facing-copy`).
+ Shapes a PR body so a reviewer can understand the problem and change quickly.
+ Use ALWAYS before writing or editing a PR description, before `gh pr create` or `gh pr edit --body`, or when asked to improve a description.
+ States the actor's need in Problem, then the visible effect and mechanism in Changes.
+ Selects bullets, tables, diagrams, screenshots, or collapsed blocks for each fact.
+ Removes unnecessary detail and checks one fact per bullet, sentences under 25 words, active voice, and no idioms.
+ Keeps the body complete without the diff, scales its length to the change, and links evidence or marks claims as unchecked.
+ Checks the title and first lines of Problem and Changes.
+ Not for commit messages (see AGENTS.md, "Commit types") or product copy (see `/writing-user-facing-copy`).
---
# Writing PR descriptions
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e1846e4756da..3f30d035822e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5689,9 +5689,9 @@ snapshots:
lemon-ui-lemon-table--stealth--light:
hash: v1.k794b7964.dbe2591e22b2bf895b141a277539ea8870d1cebf5ef8aadc0ab68e32b5fb2c96.qjEP6YeZWMMAqJ-YaR5K2tNMsV70ha6tXsX1cTO1jOM
lemon-ui-lemon-table--with-bulk-selection-nothing-selected--dark:
- hash: v1.k794b7964.89b25f07a749e499550a1816d366329e6d1970aa92c0a7e6043c8dd642902190.GdwcvJKl-pAqv6GgN6O4Et8N_iyrlBTUEeWomwg0euE
+ hash: v1.k794b7964.8f5c6c3ea54cd4918a6f54a21ab2d40362ffa9efc13292826cdcbd41d88c2ca1.gwbFyweu4PnyMfgowhqod5OC8jiPGTJBxl0usix2WQo
lemon-ui-lemon-table--with-bulk-selection-nothing-selected--light:
- hash: v1.k794b7964.ee752c7b9d6dbaa1d6782879a5efba7d2237338633ee080b6a395d6a39b300f0.YYHkBJsjt0puMSmzxZdDdr-bRIGOLSzt8L_mHVqjOgo
+ hash: v1.k794b7964.24df670f87cef5c407f053873b5bb0058b0549ade778b3b9e25a82d6b8bf16b1.lVLrS1XiCLBYfflZOy4lWwrKaONh3394L9j6lV61boI
lemon-ui-lemon-table--with-bulk-selection-two-selected--dark:
hash: v1.k794b7964.19edf009382dbfe1179d1af4c7c8283bff59782fff7340ff7d2d537b40df54a1.LnwrXXKE7OWG0NSLfzxDhxMrLDlESP4t_tMHzNQpreA
lemon-ui-lemon-table--with-bulk-selection-two-selected--light:
@@ -9871,17 +9871,17 @@ snapshots:
scenes-app-data-management-definition-view--event-definition-metadata--wide--light:
hash: v1.k794b7964.bbebff9b92fa30583a75b6176cb5a68c42b0507fe804941f64c5e8333a81543a.Mq-LalWKlCD58ctQgsUpHHoyionRzSjgFS4fRSL_D-Y
scenes-app-data-management-event-definitions--default--dark:
- hash: v1.k794b7964.fd6a1b547b355c4ddfa3ea42920855cb501417cbfd0000978d6a1f302f733068.CUpF10Sg7nLZVzj4M_DsH0PaA1iqydLFbKSxm-mNJeE
+ hash: v1.k794b7964.57a8cc3dd49e0e59d361157e381f58071dba61c56ca530edaa40757922eceb78.1BgEfSXYBfS1K9_g4Oxn6LB-1hFGeajs9Hc9OEWRWYk
scenes-app-data-management-event-definitions--default--light:
- hash: v1.k794b7964.7967b8c148ed75ab6032a33749e7c1adfb08f473413dde886c2ced032c7e4bc7.bolACEsxWTGNA03AkueZObrPsIUQMoCyf1RF3PHlVo8
+ hash: v1.k794b7964.fa1910b9fa3a13d2ab50bd0b6bcc0a93fe2e02ac3b9d0b50aff51937929a8fde.CnETLoq86U1Yh3q3beVKtA6gpK7ZcbLQSLI4gLTOiQw
scenes-app-data-management-event-definitions--filtered-unverified-only--dark:
- hash: v1.k794b7964.5e76710734218e334f97b2174cfd5a14ef2ea610321f39fa46a78cdaa5199e08.S4EzMp8ItX6rFffJfbFRPlGRtEZJw_2QXwQzypDHG-Q
+ hash: v1.k794b7964.34c42644b0773f19ef3a3a81eebefbe88982ec1acffe835f9600fa3e1e2d79b8.z_A5gsfD1EenU4x2aSjT8KNvoBwvmAe9XWlYxycF56E
scenes-app-data-management-event-definitions--filtered-unverified-only--light:
- hash: v1.k794b7964.70995e107a1995fb8ecce8903791eb3b7cc494d7b594f2d3d7fe1b18ba32310d.v1xZHDQb1Fc6yD6lWYfNLkStI2A_wfpuynjd6BHqTWc
+ hash: v1.k794b7964.0d57cb8f4294292dfa934426169e2d70667d103934e4d686f62bb7d5ca414394.PdRLunaI-H8cw9oj5AhGfTZwas37tLa9cwWKInMFDB0
scenes-app-data-management-event-definitions--filtered-verified-only--dark:
- hash: v1.k794b7964.993c734914fd64eaf7fcfdaa566893e5540f2729e29c5e004d10517f6375427a.GyidWMB-a3KjVAHkk1wht6pXqb_kduBrJrVGwtigqNQ
+ hash: v1.k794b7964.5fcc4c5f30d1e909d3f2ae2a1e9bd5b9c54e917579a403acbbc75cc75aa89996.hjMD-38vlCj3JKBYSX5j-b6e6qeYOKUzWrusON0uGSs
scenes-app-data-management-event-definitions--filtered-verified-only--light:
- hash: v1.k794b7964.180955669218e75ff5a084dab00fdb9fab77ccb42eb733a411855fd4556b1dea.h2h9juy73JBAenuPFWqXU6wbcPdDl9lVRqmrb8Bzc1I
+ hash: v1.k794b7964.bc5b7ee30381f5ce5e97e5b74aba8a7f8b631c0be223a71dbc24885a9624cdb6.3epwi4y2crXKS0oeKB0__HIFSa0_0NB5tFs_WKQjcqI
scenes-app-data-management-property-definitions--default--dark:
hash: v1.k794b7964.8385cb12f59b35d4aa70d30748bdf8bc78fb14558840fc448dbc8a9373ceca7c.rprhfRTwSLBMpyVGLfjkYKJomlDpZk3z_lb85XDpKPU
scenes-app-data-management-property-definitions--default--light:
@@ -10775,13 +10775,13 @@ snapshots:
scenes-app-feature-flags--feature-flag-not-found--light:
hash: v1.k794b7964.9760899dc54ed1457b2f2790151da4dced7ce03ba2db211fc8987584331225f7.NwLOFpddIBI2MKFCF_nA7ICbR7JCJISgydgqg4pdPWg
scenes-app-feature-flags--feature-flags-list--dark:
- hash: v1.k794b7964.d89fe28a6ed950990ef3945db822482775f9b5dedc18e5b30785c26ca2c62523.Xx4-lykuSTuRLWUZkBzgAe8ZJfIRWP9QsbmVBxQjPsw
+ hash: v1.k794b7964.a087e78f1796f558317749366d298c4fae57e1cd70c71fbb847a044857d32ae5.Z4aXxGLFnh8STT3wzwSMS_xREn7xxXo8GPOiJ4_x--s
scenes-app-feature-flags--feature-flags-list--light:
- hash: v1.k794b7964.ad33870f5b7f4889085a6f2b6a893790607e6dbf2c250254e121e8d9b257363a.hioAjfQjRn52D7MigxTZBa0NyIewpgAv09-8nCifsNM
+ hash: v1.k794b7964.9ee4d2d17d2e30904e95417a18880fddb8901a67eeebadb88c59977be4da3499.7ukvP36WfqxLU9CYStToepJdMa38vSMLDdlw5htt2wo
scenes-app-feature-flags--feature-flags-list-with-rules-v-2-flag--dark:
- hash: v1.k794b7964.fac30975fe1422a694cff775d4a2876db4f7d50b810b6badf98dadf9afbd67c0.swyXN6EB5-pGe2FC95FLRh1JqveAl8r4DF97h56Cvtw
+ hash: v1.k794b7964.1727ef0eabfc4ce85f096027de08767cfb1d4a7df8524b865fce0db25ff31748.AZGib3Lsi5vEz7bWNkHr_Qa4LBmhuQwTuh4R5D-N8Zc
scenes-app-feature-flags--feature-flags-list-with-rules-v-2-flag--light:
- hash: v1.k794b7964.c4ef2d9634c7a7a45cff940ba307c2569ee5c027dbd25695b053bcf49d86155f.gixP5nQSZti4jcI7XMlS8AI3wvGruY-qYzGg0uS5jls
+ hash: v1.k794b7964.2c2272dbe48e8920e4897d2d2dbf76421458608e543b044ca9c595315e37d733.Khh6mk8764mGvOUEw1f8oSCav929-thJLIjoBCO-T2k
scenes-app-feature-flags--new-feature-flag--dark:
hash: v1.k794b7964.70df3db2b33bd03ae45c4aac90d5db824f0640857b9029abca867a170a5f82c5.6nQgIAyy17NzNkvmvJdJ50-JxIZRrUiXcYkx7O1ukyQ
scenes-app-feature-flags--new-feature-flag--light:
@@ -14083,9 +14083,9 @@ snapshots:
scenes-app-saved-insights--empty-state--light:
hash: v1.k794b7964.17b1a7279644a0f077b7af240abacbfba5119804f7415e0ff4a5bb42304a9175.A4sx2qMdjvE3fLJAAeY0L_4wiHTxLSeskjlRm0Z4QhQ
scenes-app-saved-insights--error-state--dark:
- hash: v1.k794b7964.97eca32497e04c403e975e4114a7a144c20ac2d32ab89f98aa247136ab2d0457.l3Iw0G-o40K5hWnI2rEHDZfJTzV282b0lm5fQvP14a0
+ hash: v1.k794b7964.0b40ddac2c37c754f6ff5d63377502b75c401d7bd2cbaee69aadc30ca8fc2a54.B8h9yooriWg_MkhWQ_kOzCVIucOm-cGeYCBjwWlPetc
scenes-app-saved-insights--error-state--light:
- hash: v1.k794b7964.6236e2139e033c4547aa3667b37627916d0d3b2d99cb346e98f2e18ccdd8ad14.huJk5GngTJ7oP9eYDf5S9kUO6OafLC9tKCYuxN-rbfE
+ hash: v1.k794b7964.0565c027e3f4486ba3d028e53f9afc6bfb3e63f0512a7ee3234604215de3b1f3.EzVsQ9cjARMpfneTgba7uAi47mATO2MWtPn4g5BfW6E
scenes-app-saved-insights--home--dark:
hash: v1.k794b7964.4f6cb09aac8b830ed0aa50bfa1b140bde7615871026a5ca1d4f3211e2aa40f3a.XTeHYdm_qcSPcX50vAgwIJnQcor1Rs6mhTsjyhdoLAE
scenes-app-saved-insights--home--light:
@@ -14103,13 +14103,13 @@ snapshots:
scenes-app-saved-insights--home-with-boolean-flag--light:
hash: v1.k794b7964.a95724c4cf917467e053fcd850bcc9dc63f7e603e8c2607863a3e1031bfb448b.jlj0ZBOaomnmubjHsNSO9vMRJxk3JTH43pM6zu_YIdI
scenes-app-saved-insights--list-view--dark:
- hash: v1.k794b7964.f20f4295f774b1892a3a9f52f2f4ebbeff75798bbc343b9874e1f6a95d410a4b.U6DhbwV1uNDFfQpUKmQ4F3kpvez3A0iemwOpgsZHo-g
+ hash: v1.k794b7964.87a635b42d5362c5eb23a783ae97c79125b56ad291a95fe160c7b075de5c4055.mjVdmGX-V-BQKFTIPoJ_KlSxTMUJ7CJb8Up3iVOKV8Q
scenes-app-saved-insights--list-view--light:
- hash: v1.k794b7964.069a9cc60f8d3b0bedfff67bf6f77d5e724d76237789496a296d74a304effbdf.1Cmm0yQPdz1n_UzfwHBCClBBRzubLBwirpm0sfdPAPU
+ hash: v1.k794b7964.c4b12f76d00fd200c601ce7e8f75827fcfd226b93dbc037e2061b692f9ebd024.7l-kzH57Pkx9EMx6m_YUO9F8K6kt__YeRH5Vi_rYN9Q
scenes-app-saved-insights--search-results--dark:
- hash: v1.k794b7964.7442501d5b602a95efa6bce64f1698b35d2f5da271d4babff23036e271877f23.OvYSpQS8fSSwMJi5V3Qc4QPqtT5Swfd1_7aqSFToRww
+ hash: v1.k794b7964.b2f12cfca81232dbad6ef40edc023ee4938ff6c0608a42113dbbfa233138c89b.t8arlwYqcN7Zu4cXkRX8nsGo-e3tCWHCJx1Btx_MAKw
scenes-app-saved-insights--search-results--light:
- hash: v1.k794b7964.d0814b477b35a38c48d6b91e582f6fb003d8fbc0fdb98228d78b278217c0bdc2.TG-NSX1eaZP7N0ch1KniCgIPVar96Pu92WjwNwhxvfk
+ hash: v1.k794b7964.959bcc3c418498c0f6d6f33f79f7d25d6c4121e81aac01d833fecc029cf3d2ae.x5GpoNRbycmilwwRtQaVXwsakgVYO_vztNfCb-exK3U
scenes-app-saved-insights-new-insight-menu--overlay--dark:
hash: v1.k794b7964.5a65f3fe94b288f66e436ecd8677bc2d1b3fe08ca885f03eae64bc8847b783ee.YfBWEDQwkl46pC03TjLQBVNXq96nOm91Lc0KcpIXegc
scenes-app-saved-insights-new-insight-menu--overlay--light:
@@ -14467,29 +14467,29 @@ snapshots:
scenes-app-sidepanels--side-panel-activity--light:
hash: v1.k794b7964.869e366f1f78c48d94168cb630269fc02413f305eb7894bd61cb7a5412bc0948.ar2nQN6oSk4m53MG0vKdRp7SGzmn01XkRTH1Us5YMfo
scenes-app-sidepanels--side-panel-discussion--dark:
- hash: v1.k794b7964.b3ba78fc87cc4765f994aa58082e37e0a4c2f80cac445fb67ae296fa2edff64b.2W4nRhSDi87_oqMTQNxBWuBg-hDFmCCNjsswUk7E46o
+ hash: v1.k794b7964.9d7549b20c9ed5a5e40b774ced309d9a579130128ebb8b76bf30b87ad5ca30c9._m_XzZ5r6AM9eoAuooBRLKo5Y8BlOr9Dtly-hmM3ZTg
scenes-app-sidepanels--side-panel-discussion--light:
- hash: v1.k794b7964.dc0df0e02d4aaf688bd811a5734da48d8d5a494e45db0fecbca1a50ec6ee136d.MCIIS0SbqN1rktl0jQa7c5hC49M59V4oNENaGzYEhUQ
+ hash: v1.k794b7964.a62988fbf27d646f2fdd6ef7c0c1a954a9818de0c261450a7ea6cfb2b4f6ecde.A1hxA8jQNNCz_ajgIi2iV7XJRkJCO0f7KsLqVSGRU2U
scenes-app-sidepanels--side-panel-exports--dark:
- hash: v1.k794b7964.18a539f4e19f3efeaa0cd7831bf7ea8a27012499c77654f70a5ecd1f3c488728.J6heb242mpOIAdA6Oz4kelL0NYBSb1wPBA09FGJRYRU
+ hash: v1.k794b7964.8fa7aa72f3d6d4b7aeeee008d6e8fae5d494540aaa845650bfc4b2451684e4ba.3OdXP1Nl4BoO95kO_nR5p6Wh2fea57KykU6XXRQB3Qw
scenes-app-sidepanels--side-panel-exports--light:
- hash: v1.k794b7964.efd210695202c618c0bdfc6776b7f4aa2c6f4d35a443972940d18a6fd1eb9d69.Kb6fTsroUp8D6eIFIhp2IQnNroKVZRU7hGdO0Itvp_A
+ hash: v1.k794b7964.918d3215cc5901ca73a755c93bcd746aacc38b77d7ea95e59733860d855386c4.wpKfFZagQI9V6_dTf_ONSqMldVTSttCAHQQsm734dJs
scenes-app-sidepanels--side-panel-info--dark:
hash: v1.k794b7964.23f3871d2a08f3d2c1d86506cad9e5ef5c61fe3cf63d99b54970221ce85b3e92.ooyWeLX1caf_SJbEuVVKGn9SbMh6T5tQIvq4HQpdOn4
scenes-app-sidepanels--side-panel-info--light:
hash: v1.k794b7964.7c91500a5f41b83e6d2961df7b3ffdfb616589ebf3dd14f6e1f6f5e698e85a20.5gaUtEn8goiAxCqTiokwWeb8vWn1IXdyyoIHIZjhHak
scenes-app-sidepanels--side-panel-max--dark:
- hash: v1.k794b7964.57c6236de543fccc554ee9d66b11ee364300dd30104cd09c13dd228f059a7f1f.8Rv_3EdkJt_VXQsogy4QCX9zF9AbFrcfIZCT19SyRcE
+ hash: v1.k794b7964.ff16988d4fb22f10d8f3271e7d1731b7aef494362723094600d0b960350a7782.47b2FlHiByqS3U3ScU05j1YswfK3ZnWfCnihjw6tM6g
scenes-app-sidepanels--side-panel-max--light:
- hash: v1.k794b7964.0cea5782a5eed79d5f71b8a97e61c39b1e55f4abbf4f38f7de8ec91e99f0c9b3.QTA881_fmtL3Hr1mypEnlb-mpqhmBWPKmu61fn6W4Ko
+ hash: v1.k794b7964.91cf2555ae4cffdd1ba1a90a7529d96d475b4b3e57702a6a7566f1cfeee6ddc7.W8ADP-FB4FsGzCAfK8XAGNDlv3Hva6v6lYlEdJLgZb4
scenes-app-sidepanels--side-panel-notebooks--dark:
- hash: v1.k794b7964.5623673e6d94170e07fd650aa9676691391b0c4c87c4691988311ac27555174e.byjXIXfNQ5MzjT5n-9RxGuoUMmjkOWzH20Z9LrxD-oo
+ hash: v1.k794b7964.d09af750ec686ef9be3f11a174297d38e54e64e01079362565a8b82982032a82.g9LaJxg483ewZIBefQ_Gce7DL6T7RNbzIkJafM5ZHu0
scenes-app-sidepanels--side-panel-notebooks--light:
- hash: v1.k794b7964.cfe0c2e2c8900f8074ec8a18d07c4bfa0ddc2d2f262ff898d183e583913f0fc8.IRKyezgaFnvwurVx2JWeiqJSHxuXnD1Fw1Kduzho1KE
+ hash: v1.k794b7964.78994c6dfde97cb3fa443230a4e2aa0053ea32e15beaa254cde6976b59a1a7e1.FSb1vF5Dk3dLdN0RF5sIdeYTBAO-UshC88tnBJiDtoY
scenes-app-sidepanels--side-panel-support--dark:
- hash: v1.k794b7964.7a9fd704dd418ef6c1139e55d82641332bc6b246cd8c645272b84ad3a3d0bbad.zwuP71CA0hut3ixufWVFArzdY_-QjGQxeKj6-RYL-js
+ hash: v1.k794b7964.a1d4f34402e18a5e7389f431dafeec3e929eeb49aa2f57a3ee31e30b0aab3d24.mj5wtEaAETRBBvjp2__uvauNOkWPs0WRuBiCm55tu0A
scenes-app-sidepanels--side-panel-support--light:
- hash: v1.k794b7964.1dedbccfe4b16a5b4655706d97eea88bcc8fe58b8d583037a80f4fd2acd460b7.86JJ0wDb_bYo6Zz2SIblvjpRnnKpurlkMkVqOdFF7ZA
+ hash: v1.k794b7964.da242d934624a8b7f8e992539f26569d84b2310d0ffa6e47574ed481a2df062f.BqtuyJYfWEFLJnU9yY770EIyD0xT1WxIrQ_BDMlQw8k
scenes-app-signals-artefactloglist--check-lifecycle--dark:
hash: v1.k794b7964.19c992f77d56b064d5196570d7ed96b44b8b716ed149c79cee4992751ec2f11e.pQV4XQtKFXBQNrPKy95ZzZ6Q_RF7u8CDnqSF90tOXRQ
scenes-app-signals-artefactloglist--check-lifecycle--light:
diff --git a/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.ts b/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.ts
index 19981ad4d681..d5b9d6b720e7 100644
--- a/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.ts
+++ b/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.ts
@@ -61,6 +61,8 @@ export interface SetupDetectionLogicOptions {
* and a query on every scene entry.
*/
cacheHasData?: boolean
+ /** Entity products can become empty when users delete their last item. Recheck mutations even after data exists. */
+ allowReturnToSetup?: boolean
/**
* With `cacheHasData`, re-run detection once in the background after a cached has-data
* answer, for data users can delete or that ages out of the probe's window. A no-data answer
@@ -163,6 +165,7 @@ export function createSetupDetectionLogic(options: SetupDetectionLogicOptions):
recheckActionTypes,
cacheHasData,
revalidateCachedHasData,
+ allowReturnToSetup,
} = options
return buildKea<SetupDetectionLogicType>([
path(options.path),
@@ -195,7 +198,7 @@ export function createSetupDetectionLogic(options: SetupDetectionLogicOptions):
(recheckActionTypes?.() ?? []).map((actionType) => [
actionType,
() => {
- if (values.currentProjectId && values.setupStatus !== 'has-data') {
+ if (values.currentProjectId && (allowReturnToSetup || values.setupStatus !== 'has-data')) {
actions.detectStatus()
}
},
@@ -215,7 +218,15 @@ export function createSetupDetectionLogic(options: SetupDetectionLogicOptions):
}
return
}
- actions.setDetectedStatus(detectedStatus)
+ if (allowReturnToSetup && isNoDataStatus(detectedStatus)) {
+ clearCachedHasData(values.currentTeamId, productKey)
+ productSetupStatusLogic({ productKey }).actions.applyDetectedStatus(
+ detectedStatus,
+ values.currentTeamId
+ )
+ } else {
+ actions.setDetectedStatus(detectedStatus)
+ }
onDetected?.(detectedStatus)
// Data never disappears once it exists, so the poll's job is done.
if (detectedStatus === 'has-data') {
diff --git a/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx b/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx
index 7644c961e3f7..2e161af86d43 100644
--- a/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx
@@ -16,9 +16,7 @@ export function BulkSelectionBar<T extends Record<string, any>, K extends BulkSe
config,
noun,
}: BulkSelectionBarProps<T, K>): JSX.Element | null {
- if (context.selectedCount === 0) {
- return null
- }
+ const isOpen = context.selectedCount > 0
const [singular, plural] = noun
const word = context.selectedCount === 1 ? singular : plural
@@ -39,5 +37,16 @@ export function BulkSelectionBar<T extends Record<string, any>, K extends BulkSe
</div>
)
- return config.barPortalTarget ? createPortal(bar, config.barPortalTarget) : bar
+ if (config.barPortalTarget) {
+ return isOpen ? createPortal(bar, config.barPortalTarget) : null
+ }
+
+ return (
+ <div
+ className={clsx('LemonTable__bulk-selection-reveal', isOpen && 'LemonTable__bulk-selection-reveal--open')}
+ aria-hidden={!isOpen}
+ >
+ <div className="min-h-0 overflow-hidden">{bar}</div>
+ </div>
+ )
}
diff --git a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.scss b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.scss
index 8ca1e9b66712..487e2bc68f9d 100644
--- a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.scss
+++ b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.scss
@@ -454,3 +454,19 @@ body:not(.storybook-test-runner) .LemonTable.LemonTable--sticky-header {
}
}
}
+
+.LemonTable__bulk-selection-reveal {
+ display: grid;
+ grid-template-rows: 0fr;
+ visibility: hidden;
+ transition: grid-template-rows 180ms ease-out;
+
+ &--open {
+ grid-template-rows: 1fr;
+ visibility: visible;
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ transition: none;
+ }
+}
diff --git a/frontend/src/models/dashboardsModel.test.ts b/frontend/src/models/dashboardsModel.test.ts
index 1a703bb7378e..d66665f9e6ab 100644
--- a/frontend/src/models/dashboardsModel.test.ts
+++ b/frontend/src/models/dashboardsModel.test.ts
@@ -8,6 +8,9 @@ import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { AccessControlLevel, DashboardBasicType } from '~/types'
+import * as generatedApi from 'products/dashboards/frontend/generated/api'
+import type { DashboardBulkDeleteResponseApi } from 'products/dashboards/frontend/generated/api.schemas'
+
import { dashboardsModel, mergeTileTextUpdatesIntoDashboard, nameCompareFunction } from './dashboardsModel'
const dashboards: Partial<DashboardBasicType>[] = [
@@ -112,6 +115,42 @@ describe('the dashboards model', () => {
}).toDispatchActions(['loadDashboardsSuccess'])
})
+ it('reloads every page after a failed bulk deletion', async () => {
+ await expectLogic(logic, () => logic.actions.loadDashboards()).toDispatchActions(['loadDashboardsSuccess'])
+ let failRequest: (error: Error) => void
+ const request = new Promise<DashboardBulkDeleteResponseApi>((_, reject) => {
+ failRequest = reject
+ })
+ const deleteSpy = jest.spyOn(generatedApi, 'dashboardsBulkDeleteCreate').mockReturnValueOnce(request)
+ useMocks({
+ get: {
+ '/api/environments/:team_id/dashboards/': ({ request }) => {
+ const offset = new URL(request.url).searchParams.get('offset')
+ return [
+ 200,
+ {
+ count: 2,
+ results: [{ ...basicDashboard, id: offset === '0' ? 5 : 6 }],
+ next: offset === '0' ? '/api/projects/1/dashboards/?offset=1' : null,
+ previous: null,
+ },
+ ]
+ },
+ },
+ })
+ try {
+ logic.actions.bulkDeleteDashboards({ ids: [3], onStillSelected: jest.fn() })
+ await expectLogic(logic, () => failRequest!(new Error('Lost response'))).toDispatchActions([
+ 'bulkDeleteDashboardsFailure',
+ 'reloadDashboardsSuccess',
+ ])
+ expect(Object.keys(logic.values.rawDashboards).sort()).toEqual(['5', '6'])
+ expect(logic.values.pagingDashboardsCompleted).toBe(true)
+ } finally {
+ deleteSpy.mockRestore()
+ }
+ })
+
describe('sorting dashboards', () => {
it('can sort dashboards correctly', async () => {
await expectLogic(logic, () => {
diff --git a/frontend/src/models/dashboardsModel.tsx b/frontend/src/models/dashboardsModel.tsx
index 9314e78ce2ab..2f8bb93f0430 100644
--- a/frontend/src/models/dashboardsModel.tsx
+++ b/frontend/src/models/dashboardsModel.tsx
@@ -2,6 +2,7 @@ import { MakeLogicType, actions, connect, kea, listeners, path, reducers, select
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import posthog from 'posthog-js'
+import { v4 as uuid } from 'uuid'
import api, { PaginatedResponse } from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
@@ -19,8 +20,15 @@ import { parentPath, reparentPath } from '~/layout/panel-layout/ProjectTree/util
import { tagsModel } from '~/models/tagsModel'
import { DashboardBasicType, DashboardTile, DashboardType, InsightShortId, InsightModel } from '~/types'
+import { dashboardsBulkDeleteCreate, dashboardsList } from 'products/dashboards/frontend/generated/api'
+import type { DashboardBulkDeleteResponseApi } from 'products/dashboards/frontend/generated/api.schemas'
+
import type { Node } from '../queries/schema/schema-general'
+export function getRemovedDashboardIds({ deleted, skipped }: DashboardBulkDeleteResponseApi): number[] {
+ return [...deleted, ...skipped.filter(({ reason }) => reason === 'Dashboard not found').map(({ id }) => id)]
+}
+
function reportDashboardPinToggled(dashboardId: number, pinned: boolean, source: DashboardEventSource): void {
posthog.capture(`dashboard pin toggled`, {
dashboard_id: dashboardId,
@@ -84,6 +92,8 @@ export function mergeTileTextUpdatesIntoDashboard(
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardsModelValues {
+ bulkDeleteResponse: DashboardBulkDeleteResponseApi | null
+ bulkDeleteResponseLoading: boolean
dashboard: DashboardType | null
dashboardLoading: boolean
dashboardsLoading: boolean
@@ -106,6 +116,41 @@ export interface dashboardsModelActions {
addDashboardSuccess: (dashboard: DashboardType) => {
dashboard: DashboardType
}
+ bulkDeleteDashboards: ({
+ ids,
+ deleteInsights,
+ onStillSelected,
+ }: {
+ deleteInsights?: boolean
+ ids: number[]
+ onStillSelected: (ids: number[]) => void
+ }) => {
+ ids: number[]
+ deleteInsights?: boolean
+ onStillSelected: (ids: number[]) => void
+ }
+ bulkDeleteDashboardsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ bulkDeleteDashboardsSuccess: (
+ bulkDeleteResponse: DashboardBulkDeleteResponseApi,
+ payload?: {
+ ids: number[]
+ deleteInsights?: boolean
+ onStillSelected: (ids: number[]) => void
+ }
+ ) => {
+ bulkDeleteResponse: DashboardBulkDeleteResponseApi
+ payload?: {
+ ids: number[]
+ deleteInsights?: boolean
+ onStillSelected: (ids: number[]) => void
+ }
+ }
dashboardsFullyLoaded: () => {
value: true
}
@@ -229,6 +274,43 @@ export interface dashboardsModelActions {
source: DashboardEventSource
}
}
+ reloadDashboards: (_: { ids: number[]; onStillSelected: (ids: number[]) => void }) => {
+ ids: number[]
+ onStillSelected: (ids: number[]) => void
+ }
+ reloadDashboardsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ reloadDashboardsSuccess: (
+ pagedDashboards: {
+ count: number
+ next: null
+ previous: null
+ results: DashboardBasicType[]
+ } | null,
+ payload?: {
+ ids: number[]
+ onStillSelected: (ids: number[]) => void
+ }
+ ) => {
+ pagedDashboards: {
+ count: number
+ next: null
+ previous: null
+ results: DashboardBasicType[]
+ } | null
+ payload?: {
+ ids: number[]
+ onStillSelected: (ids: number[]) => void
+ }
+ }
+ removeDashboardsFromCache: (ids: number[]) => {
+ ids: number[]
+ }
reparentDashboardFolders: (
oldPath: string,
newPath: string
@@ -351,6 +433,7 @@ export const dashboardsModel = kea<dashboardsModelType>([
})),
actions(() => ({
loadDashboardsIfNeeded: true,
+ removeDashboardsFromCache: (ids: number[]) => ({ ids }),
// we page through the dashboards and need to manually track when that is finished
dashboardsFullyLoaded: true,
delayedDeleteDashboard: (id: number) => ({ id }),
@@ -403,9 +486,58 @@ export const dashboardsModel = kea<dashboardsModelType>([
tileAddedToDashboard: (dashboardId: number) => ({ dashboardId }),
})),
loaders(({ values, actions }) => ({
+ bulkDeleteResponse: [
+ null as DashboardBulkDeleteResponseApi | null,
+ {
+ bulkDeleteDashboards: async ({
+ ids,
+ deleteInsights,
+ onStillSelected,
+ }: {
+ ids: number[]
+ deleteInsights?: boolean
+ onStillSelected: (ids: number[]) => void
+ }) => {
+ const toastId = lemonToast.loading('Deleting dashboards…', { toastId: uuid() })
+ try {
+ return await dashboardsBulkDeleteCreate(String(teamLogic.values.currentTeamId), {
+ ids,
+ delete_insights: deleteInsights ?? false,
+ })
+ } catch (error) {
+ actions.reloadDashboards({ ids, onStillSelected })
+ throw error
+ } finally {
+ lemonToast.dismiss(toastId)
+ }
+ },
+ },
+ ],
pagedDashboards: [
null as PaginatedResponse<DashboardBasicType> | null,
{
+ reloadDashboards: async (
+ _: { ids: number[]; onStillSelected: (ids: number[]) => void },
+ breakpoint
+ ) => {
+ const teamId = teamLogic.values.currentTeamId
+ const results: DashboardBasicType[] = []
+ let hasNextPage = true
+ while (hasNextPage) {
+ const page = await dashboardsList(String(teamId), {
+ limit: 2000,
+ offset: results.length,
+ exclude_generated: true,
+ })
+ breakpoint()
+ if (teamId !== teamLogic.values.currentTeamId) {
+ return null
+ }
+ results.push(...(page.results as unknown as DashboardBasicType[]))
+ hasNextPage = !!page.next
+ }
+ return { results, count: results.length, next: null, previous: null }
+ },
loadDashboards: async (url?: string) => {
// looking at a fully exported dashboard, return its contents
const exportedDashboard = window.POSTHOG_EXPORTED_DATA?.dashboard
@@ -585,6 +717,14 @@ export const dashboardsModel = kea<dashboardsModelType>([
rawDashboards: [
{} as Record<string, DashboardBasicType | DashboardType>,
{
+ removeDashboardsFromCache: (state, { ids }) => {
+ const removedIds = new Set(ids)
+ return Object.fromEntries(
+ Object.entries(state).filter(([, dashboard]) => !removedIds.has(dashboard.id))
+ )
+ },
+ reloadDashboardsSuccess: (state, { pagedDashboards }) =>
+ pagedDashboards ? idToKey(pagedDashboards.results) : state,
loadDashboardsSuccess: (state, { pagedDashboards }) => {
if (!pagedDashboards) {
return state
@@ -690,6 +830,42 @@ export const dashboardsModel = kea<dashboardsModelType>([
],
})),
listeners(({ actions, values }) => ({
+ bulkDeleteDashboardsSuccess: ({ bulkDeleteResponse }) => {
+ if (!bulkDeleteResponse) {
+ return
+ }
+ const { deleted, skipped } = bulkDeleteResponse
+ actions.removeDashboardsFromCache(getRemovedDashboardIds(bulkDeleteResponse))
+ if (deleted.length > 0) {
+ const noun = deleted.length === 1 ? 'dashboard' : 'dashboards'
+ lemonToast.success(`Deleted ${deleted.length} ${noun}.`)
+ }
+ if (skipped.length > 0) {
+ lemonToast.warning(
+ `${skipped.length} dashboards were skipped. They no longer exist or you cannot edit them.`
+ )
+ }
+ },
+ bulkDeleteDashboardsFailure: () => {
+ lemonToast.error('Could not delete dashboards. Refresh the list and try again.')
+ },
+ removeDashboardsFromCache: ({ ids }) => {
+ for (const id of ids) {
+ deleteFromTree('dashboard', String(id))
+ }
+ const currentTeam = teamLogic.values.currentTeam
+ if (currentTeam?.primary_dashboard && ids.includes(currentTeam.primary_dashboard)) {
+ teamLogic.actions.loadCurrentTeamSuccess({ ...currentTeam, primary_dashboard: null })
+ }
+ },
+ reloadDashboardsSuccess: ({ pagedDashboards, payload }) => {
+ if (!pagedDashboards) {
+ return
+ }
+ const remainingIds = new Set(pagedDashboards.results.map(({ id }) => id))
+ actions.removeDashboardsFromCache((payload?.ids ?? []).filter((id) => !remainingIds.has(id)))
+ actions.dashboardsFullyLoaded()
+ },
loadDashboardsIfNeeded: () => {
if (!values.pagingDashboardsCompleted && !values.pagedDashboardsLoading) {
actions.loadDashboards()
diff --git a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.test.tsx b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.test.tsx
index 818e27ea97bc..89cda4784b4f 100644
--- a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.test.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.test.tsx
@@ -4,6 +4,7 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { useActions, useValues } from 'kea'
import posthog from 'posthog-js'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -38,6 +39,7 @@ jest.mock('lib/lemon-ui/LemonTable', () => ({
describe('DashboardsTable move to folder', () => {
const moveDashboardsToFolder = jest.fn()
const setHomepage = jest.fn()
+ const bulkDeleteDashboards = jest.fn()
const clearSelection = jest.fn()
const setSelectedKeys = jest.fn()
@@ -52,6 +54,7 @@ describe('DashboardsTable move to folder', () => {
showDuplicateDashboardModal: jest.fn(),
showDeleteDashboardModal: jest.fn(),
moveDashboardsToFolder,
+ bulkDeleteDashboards,
setHomepage,
})
})
@@ -89,6 +92,21 @@ describe('DashboardsTable move to folder', () => {
)
}
+ it('keeps insights by default and passes the delete insights option on submit', () => {
+ const openForm = jest.spyOn(LemonDialog, 'openForm').mockImplementation(() => {})
+ renderTable([1, 2], [1, 2])
+ fireEvent.click(screen.getByText('Delete selected'))
+ const dialog = openForm.mock.calls[0][0]
+ expect(dialog.initialValues).toEqual({ deleteInsights: false })
+ dialog.onSubmit({ deleteInsights: true })
+ expect(bulkDeleteDashboards).toHaveBeenCalledWith({
+ ids: [1, 2],
+ deleteInsights: true,
+ onStillSelected: setSelectedKeys,
+ })
+ openForm.mockRestore()
+ })
+
it("sets only the current user's homepage from the row menu", () => {
const capture = jest.spyOn(posthog, 'capture')
renderTable([1, 2], [], [1, 2], undefined, 1, 2)
diff --git a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
index bc1aa9359ee2..45b2ae246ab0 100644
--- a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
@@ -1,14 +1,17 @@
import { useActions, useValues } from 'kea'
import posthog from 'posthog-js'
-import { IconFolder, IconHome, IconLock, IconPin, IconPinFilled, IconShare } from '@posthog/icons'
+import { IconFolder, IconHome, IconLock, IconPin, IconPinFilled, IconShare, IconTrash } from '@posthog/icons'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { BulkUpdateTagsButton } from 'lib/components/BulkActions/BulkUpdateTagsButton'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { More } from 'lib/lemon-ui/LemonButton/More'
+import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
+import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonRow } from 'lib/lemon-ui/LemonRow'
import { LemonTable, LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { atColumn, createdAtColumn, createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
@@ -84,8 +87,9 @@ export function DashboardsTable({
hideActions,
}: DashboardsTableProps): JSX.Element {
const { unpinDashboard, pinDashboard } = useActions(dashboardsModel)
- const { tableSortingChanged, setFilters, moveDashboardsToFolder } = useActions(dashboardsLogic)
- const { tableSorting, filters, filedDashboardIds } = useValues(dashboardsLogic)
+ const { tableSortingChanged, setFilters, moveDashboardsToFolder, bulkDeleteDashboards } =
+ useActions(dashboardsLogic)
+ const { tableSorting, filters, filedDashboardIds, bulkDeleteResponseLoading } = useValues(dashboardsLogic)
// Server-side fuzzy search ranks results by relevance; re-sorting alphabetically by name
// would push the exact match below partial matches. Suppress the persisted column sort
// while the user has an active search term.
@@ -370,7 +374,7 @@ export function DashboardsTable({
emptyState="No dashboards matching your filters!"
nouns={['dashboard', 'dashboards']}
bulkSelection={{
- barClassName: 'mb-2',
+ barClassName: 'mb-2 flex-wrap',
getKey: (dashboard: DashboardType): number => dashboard.id,
isRowSelectable: (dashboard: DashboardType) =>
accessLevelSatisfied(
@@ -397,6 +401,49 @@ export function DashboardsTable({
dashboardsModel.actions.loadDashboards()
}}
/>
+ <LemonButton
+ size="small"
+ type="primary"
+ status="danger"
+ icon={<IconTrash />}
+ loading={bulkDeleteResponseLoading || dashboardsLoading}
+ disabledReason={
+ ctx.selectedKeys.length > 100 ? 'Select at most 100 dashboards' : undefined
+ }
+ data-attr="dashboards-bulk-delete"
+ onClick={() => {
+ const ids = [...ctx.selectedKeys]
+ const noun = ids.length === 1 ? 'dashboard' : 'dashboards'
+ LemonDialog.openForm({
+ title: `Delete ${ids.length} ${noun}?`,
+ initialValues: { deleteInsights: false },
+ content: (
+ <LemonField
+ name="deleteInsights"
+ help="This only deletes insights that are not on any remaining dashboard."
+ >
+ {({ value, onChange }) => (
+ <LemonCheckbox
+ checked={!!value}
+ onChange={onChange}
+ label="Delete the selected dashboards' insights"
+ data-attr="bulk-delete-dashboard-insights-checkbox"
+ />
+ )}
+ </LemonField>
+ ),
+ onSubmit: ({ deleteInsights }) =>
+ bulkDeleteDashboards({
+ ids,
+ deleteInsights,
+ onStillSelected: ctx.setSelectedKeys,
+ }),
+ primaryButtonProps: { children: 'Delete dashboards', status: 'danger' },
+ })
+ }}
+ >
+ Delete selected
+ </LemonButton>
</>
),
}}
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
index bd709bbbeb7d..7aef9be53a43 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
@@ -20,6 +20,9 @@ import { dashboardsModel } from '~/models/dashboardsModel'
import { initKeaTests } from '~/test/init'
import { AppContext, DashboardType, UserBasicType } from '~/types'
+import * as generatedApi from 'products/dashboards/frontend/generated/api'
+import type { DashboardBulkDeleteResponseApi } from 'products/dashboards/frontend/generated/api.schemas'
+
import dashboardJson from '../__mocks__/dashboard.json'
let dashboardId = 1234
@@ -39,6 +42,81 @@ const scenes: any = { [Scene.Dashboards]: blankScene }
describe('dashboardsLogic', () => {
let logic: ReturnType<typeof dashboardsLogic.build>
+ it('removes deleted dashboards from the list and keeps skipped dashboards selected', async () => {
+ const [first, second] = allDashboards
+ useMocks({
+ post: {
+ '/api/projects/:team_id/dashboards/bulk_delete/': {
+ deleted: [first.id],
+ skipped: [{ id: second.id, reason: 'No permission' }],
+ },
+ },
+ })
+ const onStillSelected = jest.fn()
+ await expectLogic(logic, () =>
+ logic.actions.bulkDeleteDashboards({ ids: [first.id, second.id], onStillSelected })
+ ).toDispatchActions(['bulkDeleteDashboardsSuccess'])
+ expect(onStillSelected).toHaveBeenCalledWith([second.id])
+ expect(logic.values.dashboards.map(({ id }) => id)).not.toContain(first.id)
+ expect(logic.values.dashboards.map(({ id }) => id)).toContain(second.id)
+ })
+
+ it('reconciles bulk deletion after the dashboard scene unmounts', async () => {
+ const [first, second] = allDashboards
+ let finishRequest: (response: DashboardBulkDeleteResponseApi) => void
+ const request = new Promise<DashboardBulkDeleteResponseApi>((resolve) => {
+ finishRequest = resolve
+ })
+ const deleteSpy = jest.spyOn(generatedApi, 'dashboardsBulkDeleteCreate').mockReturnValueOnce(request)
+ try {
+ logic.actions.bulkDeleteDashboards({ ids: [first.id], onStillSelected: jest.fn() })
+ logic.unmount()
+ await expectLogic(dashboardsModel, () =>
+ finishRequest!({ deleted: [first.id], skipped: [] })
+ ).toDispatchActions(['bulkDeleteDashboardsSuccess', 'removeDashboardsFromCache'])
+ logic.mount()
+ expect(logic.values.dashboards.map(({ id }) => id)).not.toContain(first.id)
+ expect(logic.values.dashboards.map(({ id }) => id)).toContain(second.id)
+ } finally {
+ deleteSpy.mockRestore()
+ }
+ })
+
+ it.each([false, true])('removes stale search rows when refresh fails (bulk failure: %s)', async (bulkFails) => {
+ const [first, second] = allDashboards
+ useMocks({
+ get: {
+ '/api/environments/:team_id/dashboards/': { count: 2, results: [first, second], next: null },
+ },
+ })
+ await expectLogic(logic, () => logic.actions.setSearch('Test')).toDispatchActions([
+ 'loadSearchedDashboardsSuccess',
+ ])
+ useMocks({
+ get: {
+ '/api/environments/:team_id/dashboards/': ({ request }) => {
+ if (new URL(request.url).searchParams.get('search')) {
+ return [500, { detail: 'Search unavailable' }]
+ }
+ return [200, { count: 1, results: [second], next: null, previous: null }]
+ },
+ },
+ post: {
+ '/api/projects/:team_id/dashboards/bulk_delete/': () =>
+ bulkFails
+ ? [500, { detail: 'Response unavailable' }]
+ : [200, { deleted: [first.id], skipped: [{ id: second.id, reason: 'No permission' }] }],
+ },
+ })
+ const onStillSelected = jest.fn()
+ await expectLogic(logic, () =>
+ logic.actions.bulkDeleteDashboards({ ids: [first.id, second.id], onStillSelected })
+ ).toDispatchActions(['loadSearchedDashboardsFailure'])
+ expect(logic.values.searchedDashboards?.map(({ id }) => id)).toEqual([second.id])
+ expect(logic.values.dashboards.map(({ id }) => id)).toEqual([second.id])
+ expect(onStillSelected).toHaveBeenCalledWith([second.id])
+ })
+
const CURRENT_USER = { id: 178, uuid: 'USER_UUID' } as UserBasicType
const OTHER_USER = { id: 2, uuid: 'user2' } as UserBasicType
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
index 19afcb09d479..bf9925ed692a 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
@@ -16,10 +16,12 @@ import { userLogic } from 'scenes/userLogic'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
-import { dashboardsModel } from '~/models/dashboardsModel'
+import { dashboardsModel, getRemovedDashboardIds } from '~/models/dashboardsModel'
import { FileSystemEntry } from '~/queries/schema/schema-general'
import { ActivityScope, Breadcrumb, DashboardBasicType } from '~/types'
+import type { DashboardBulkDeleteResponseApi } from 'products/dashboards/frontend/generated/api.schemas'
+
import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { UserType } from '../../../types'
@@ -82,6 +84,8 @@ function urlSearchParamToString(value: unknown): string {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardsLogicValues {
+ bulkDeleteResponse: DashboardBulkDeleteResponseApi | null // dashboardsModel
+ bulkDeleteResponseLoading: boolean // dashboardsModel
featureFlags: FeatureFlagsSet // featureFlagLogic
user: UserType | null // userLogic
breadcrumbs: Breadcrumb[]
@@ -105,6 +109,57 @@ export interface dashboardsLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardsLogicActions {
+ bulkDeleteDashboards: (args_0: {
+ deleteInsights?: boolean
+ ids: number[]
+ onStillSelected: (ids: number[]) => void
+ }) => {
+ deleteInsights?: boolean
+ ids: number[]
+ onStillSelected: (ids: number[]) => void
+ } // dashboardsModel
+ bulkDeleteDashboardsSuccess: (
+ bulkDeleteResponse: DashboardBulkDeleteResponseApi,
+ payload?:
+ | {
+ deleteInsights?: boolean
+ ids: number[]
+ onStillSelected: (ids: number[]) => void
+ }
+ | undefined
+ ) => {
+ bulkDeleteResponse: DashboardBulkDeleteResponseApi
+ payload?: {
+ deleteInsights?: boolean
+ ids: number[]
+ onStillSelected: (ids: number[]) => void
+ }
+ } // dashboardsModel
+ reloadDashboardsSuccess: (
+ pagedDashboards: {
+ count: number
+ next: null
+ previous: null
+ results: DashboardBasicType[]
+ } | null,
+ payload?:
+ | {
+ ids: number[]
+ onStillSelected: (ids: number[]) => void
+ }
+ | undefined
+ ) => {
+ pagedDashboards: {
+ count: number
+ next: null
+ previous: null
+ results: DashboardBasicType[]
+ } | null
+ payload?: {
+ ids: number[]
+ onStillSelected: (ids: number[]) => void
+ }
+ } // dashboardsModel
reportDashboardMoveInitiated: (
method: 'bulk' | 'single',
count: number
@@ -248,8 +303,17 @@ export type dashboardsLogicType = MakeLogicType<
export const dashboardsLogic = kea<dashboardsLogicType>([
path(['scenes', 'dashboard', 'dashboardsLogic']),
connect(() => ({
- values: [userLogic, ['user'], featureFlagLogic, ['featureFlags']],
+ values: [
+ userLogic,
+ ['user'],
+ featureFlagLogic,
+ ['featureFlags'],
+ dashboardsModel,
+ ['bulkDeleteResponse', 'bulkDeleteResponseLoading'],
+ ],
actions: [
+ dashboardsModel,
+ ['bulkDeleteDashboards', 'bulkDeleteDashboardsSuccess', 'reloadDashboardsSuccess'],
moveToLogic,
['openMoveToModal'],
eventUsageLogic,
@@ -396,6 +460,19 @@ export const dashboardsLogic = kea<dashboardsLogicType>([
}),
reducers({
+ searchedDashboards: {
+ bulkDeleteDashboardsSuccess: (state, { bulkDeleteResponse }) => {
+ const removedIds = new Set(getRemovedDashboardIds(bulkDeleteResponse))
+ return state?.filter(({ id }) => !removedIds.has(id)) ?? null
+ },
+ reloadDashboardsSuccess: (state, { pagedDashboards }) => {
+ if (!pagedDashboards) {
+ return state
+ }
+ const remainingIds = new Set(pagedDashboards.results.map(({ id }) => id))
+ return state?.filter(({ id }) => remainingIds.has(id)) ?? null
+ },
+ },
tagResults: [
[] as string[],
{
@@ -652,6 +729,29 @@ export const dashboardsLogic = kea<dashboardsLogicType>([
},
})),
listeners(({ actions, values, cache }) => ({
+ bulkDeleteDashboardsSuccess: ({ bulkDeleteResponse, payload }) => {
+ const removedIds = new Set(getRemovedDashboardIds(bulkDeleteResponse))
+ payload?.onStillSelected(
+ bulkDeleteResponse.skipped.filter(({ id }) => !removedIds.has(id)).map(({ id }) => id)
+ )
+ actions.loadSearchedDashboards({
+ search: values.filters.search,
+ tags: values.filters.tags ?? [],
+ folder: values.filters.folder ?? null,
+ })
+ },
+ reloadDashboardsSuccess: ({ pagedDashboards, payload }) => {
+ if (!pagedDashboards) {
+ return
+ }
+ const remainingIds = new Set(pagedDashboards.results.map(({ id }) => id))
+ payload?.onStillSelected(payload.ids.filter((id) => remainingIds.has(id)))
+ actions.loadSearchedDashboards({
+ search: values.filters.search,
+ tags: values.filters.tags ?? [],
+ folder: values.filters.folder ?? null,
+ })
+ },
movedItem: ({ item, oldPath, newPath }) => {
if (item.type === 'folder') {
dashboardsModel.actions.reparentDashboardFolders(oldPath, newPath)
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index 4f1b5adb50a1..ae1a2ac50751 100644
--- a/posthog/api/test/dashboards/test_dashboard.py
+++ b/posthog/api/test/dashboards/test_dashboard.py
@@ -42,7 +42,7 @@ from posthog.models.signals import mute_selected_signals
from posthog.test.db_context_capturing import capture_db_queries
from posthog.test.insight_queries import browser_filtered_pageview_query, default_pageview_query, insight_query
from posthog.test.test_utils import create_group_type_mapping_without_created_at
-from posthog.user_permissions import UserPermissions
+from posthog.user_permissions import UserDashboardPermissions, UserPermissions
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.access_control.backend.models.access_control import AccessControl
@@ -1338,6 +1338,86 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
tile = DashboardTile.objects_including_soft_deleted.get(dashboard_id=dashboard_id, insight_id=insight_id)
assert tile.deleted is True
+ @parameterized.expand([(False,), (True,)])
+ @patch("products.dashboards.backend.api.dashboard.report_user_action")
+ def test_bulk_delete_insights_option_and_project_boundary(
+ self, delete_insights: bool, mock_report_user_action: MagicMock
+ ) -> None:
+ first_id, _ = self.dashboard_api.create_dashboard({"name": "First board"})
+ second_id, _ = self.dashboard_api.create_dashboard({"name": "Second board"})
+ insight_id, _ = self.dashboard_api.create_insight({"name": "Requests", "dashboards": [first_id, second_id]})
+ remaining_id, _ = self.dashboard_api.create_dashboard({"name": "Remaining board"})
+ shared_insight_id, _ = self.dashboard_api.create_insight(
+ {"name": "Shared requests", "dashboards": [first_id, second_id, remaining_id]}
+ )
+ other_team = Team.objects.create(organization=self.organization)
+ other_dashboard = Dashboard.objects.create(team=other_team, name="Other board")
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/dashboards/bulk_delete/",
+ {"ids": [first_id, second_id, first_id, other_dashboard.id], "delete_insights": delete_insights},
+ format="json",
+ )
+
+ assert response.status_code == 200
+ assert response.json() == {
+ "deleted": [first_id, second_id],
+ "skipped": [{"id": other_dashboard.id, "reason": "Dashboard not found"}],
+ }
+ bulk_events = [
+ call for call in mock_report_user_action.call_args_list if call.args[1] == "dashboards bulk deleted"
+ ]
+ assert len(bulk_events) == 1
+ assert bulk_events[0].args == (
+ self.user,
+ "dashboards bulk deleted",
+ {"requested_count": 3, "deleted_count": 2, "skipped_count": 1, "delete_insights": delete_insights},
+ )
+ assert bulk_events[0].kwargs == {"team": self.team, "request": mock.ANY}
+ assert Dashboard.objects.filter(team=self.team, id__in=[first_id, second_id]).count() == 0
+ assert Dashboard.objects.filter(team=other_team, id=other_dashboard.id).exists()
+ assert Insight.objects.filter(team=self.team, id=insight_id).exists() is not delete_insights
+ assert Insight.objects.filter(team=self.team, id=shared_insight_id).exists()
+ assert DashboardTile.objects.filter(dashboard_id=remaining_id, insight_id=shared_insight_id).exists()
+ assert not DashboardTile.objects.filter(dashboard_id__in=[first_id, second_id]).exists()
+ assert not FileSystem.objects.filter(
+ team=self.team, type="dashboard", ref__in=[str(first_id), str(second_id)]
+ ).exists()
+ assert (
+ ActivityLog.objects.filter(
+ team_id=self.team.id, scope="Dashboard", activity="deleted", item_id__in=[str(first_id), str(second_id)]
+ ).count()
+ == 2
+ )
+
+ @parameterized.expand([([],), ([0],), (list(range(1, 102)),)])
+ def test_bulk_delete_rejects_invalid_ids(self, ids: list[int]) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/dashboards/bulk_delete/", {"ids": ids}, format="json"
+ )
+ assert response.status_code == 400
+
+ def test_bulk_delete_checks_each_dashboard_permission(self) -> None:
+ first_id, _ = self.dashboard_api.create_dashboard({"name": "Editable board"})
+ second_id, _ = self.dashboard_api.create_dashboard({"name": "Restricted board"})
+ original_can_edit = UserPermissions.dashboard
+
+ def dashboard_permissions(permissions: UserPermissions, dashboard: Dashboard) -> UserDashboardPermissions:
+ if dashboard.id == second_id:
+ return MagicMock(can_edit=False)
+ return original_can_edit(permissions, dashboard)
+
+ with patch.object(UserPermissions, "dashboard", dashboard_permissions):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/dashboards/bulk_delete/",
+ {"ids": [first_id, second_id]},
+ format="json",
+ )
+ assert response.status_code == 200
+ assert response.json()["deleted"] == [first_id]
+ assert response.json()["skipped"][0]["id"] == second_id
+ assert Dashboard.objects.filter(team=self.team, id=second_id).exists()
+
def test_delete_dashboard_can_delete_tiles(self):
dashboard_one_id, _ = self.dashboard_api.create_dashboard({"filters": {"date_from": "-14d"}})
dashboard_two_id, _ = self.dashboard_api.create_dashboard({"filters": {"date_from": "-14d"}})
@@ -2094,14 +2174,10 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
@patch("products.dashboards.backend.api.dashboard.report_user_action")
def test_soft_delete_reports_dashboard_deleted(self, mock_report_user_action):
dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "to delete"})
- self.dashboard_api.create_insight({"dashboards": [dashboard_id]})
- self.dashboard_api.create_text_tile(dashboard_id)
mock_report_user_action.reset_mock()
self.dashboard_api.soft_delete(dashboard_id, "dashboards")
- # item_count (insight tiles) and tile_count (all tiles) are snapshotted pre-delete, so they survive
- # _delete_related_tiles: 1 insight tile, 2 tiles total (insight + text).
mock_report_user_action.assert_called_once_with(
self.user,
"dashboard deleted",
@@ -2110,11 +2186,7 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
"creation_mode": "default",
"dashboard_id": dashboard_id,
"has_description": False,
- "is_shared": False,
- "item_count": 1,
"pinned": False,
- "tags_count": 0,
- "tile_count": 2,
},
team=ANY,
request=ANY,
diff --git a/posthog/models/group_type_mapping.py b/posthog/models/group_type_mapping.py
index ed644a592317..22dacab841ce 100644
--- a/posthog/models/group_type_mapping.py
+++ b/posthog/models/group_type_mapping.py
@@ -20,6 +20,7 @@ import posthog.personhog_client.client as personhog_client
from posthog.models.utils import RootTeamMixin
from posthog.personhog_client import ReadConsistency, consistency_to_read_options
from posthog.personhog_client.client import personhog_call, require_personhog_client
+from posthog.personhog_client.proto import GetGroupTypeMappingsByProjectIdRequest
from posthog.rbac.decorators import field_access_control
from posthog.storage.hypercache import HyperCacheDependencyUnavailable
from posthog.utils import capture_exception_throttled, get_safe_cache, safe_cache_delete, safe_cache_set
@@ -725,6 +726,28 @@ def delete_group_type_mapping(instance: GroupTypeMapping, *, caller_tag: str | N
)
+def get_group_type_mapping_dashboard_ids(project_id: int) -> set[int] | None:
+ client = personhog_client.get_personhog_client()
+ if client is None:
+ return None
+
+ def _fetch() -> set[int]:
+ response = client.get_group_type_mappings_by_project_id(
+ GetGroupTypeMappingsByProjectIdRequest(
+ project_id=project_id,
+ read_options=consistency_to_read_options("strong"),
+ )
+ )
+ return {mapping.detail_dashboard_id for mapping in response.mappings if mapping.HasField("detail_dashboard_id")}
+
+ return personhog_call(
+ "get_group_type_mapping_dashboard_ids",
+ _fetch,
+ caller_tag="group_type_mapping/dashboard_bulk_delete",
+ reraise_as=DatabaseError,
+ )
+
+
def clear_dashboard_from_group_type_mapping(
team_id: int, dashboard_id: int, project_id: int | None = None, *, caller_tag: str | None = None
) -> None:
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index f2e9a9b86c2f..fdf474e8c35f 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -50,6 +50,7 @@ from rest_framework.utils.serializer_helpers import ReturnDict
from posthog.schema import InsightVizNode
from posthog.api.forbid_destroy_model import ForbidDestroyModel
+from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.monitoring import Feature, monitor
from posthog.api.openapi_parameters import make_filters_override_param, make_variables_override_param
from posthog.api.property_filter_access_gate import table_blocking_property_filters
@@ -82,6 +83,10 @@ from posthog.hogql_queries.apply_dashboard_filters import normalize_dashboard_fi
from posthog.hogql_queries.refresh_policy import ComputeSurface
from posthog.models.file_system.constants import DEFAULT_SURFACE, surface_q
from posthog.models.file_system.file_system import FileSystem, create_or_update_file, delete_file, join_path, split_path
+from posthog.models.group_type_mapping import (
+ clear_dashboard_from_group_type_mapping,
+ get_group_type_mapping_dashboard_ids,
+)
from posthog.models.quick_filter import QuickFilter
from posthog.models.tagged_item import TaggedItem
from posthog.models.team import Team
@@ -907,6 +912,32 @@ class UpdateDashboardWidgetsBatchRequestOpenApiSerializer(serializers.Serializer
)
+class DashboardBulkDeleteRequestSerializer(serializers.Serializer):
+ ids = serializers.ListField(
+ child=serializers.IntegerField(min_value=1),
+ allow_empty=False,
+ max_length=100,
+ help_text="Dashboard IDs to soft-delete. At most 100 IDs per request.",
+ )
+
+ delete_insights = serializers.BooleanField(
+ default=False,
+ help_text="Also delete insights that have no remaining dashboard after deletion. Defaults to false.",
+ )
+
+
+class DashboardBulkDeleteSkippedSerializer(serializers.Serializer):
+ id = serializers.IntegerField(help_text="ID of the dashboard that was skipped.")
+ reason = serializers.CharField(help_text="Reason the dashboard was skipped.")
+
+
+class DashboardBulkDeleteResponseSerializer(serializers.Serializer):
+ deleted = serializers.ListField(
+ child=serializers.IntegerField(), help_text="IDs of dashboards that were soft-deleted."
+ )
+ skipped = DashboardBulkDeleteSkippedSerializer(many=True, help_text="Dashboards that were not deleted.")
+
+
class CanEditDashboard(BasePermission):
message = "You don't have edit permissions for this dashboard."
@@ -2143,12 +2174,7 @@ class DashboardSerializer(DashboardMetadataSerializer):
if being_undeleted:
self._undo_delete_related_tiles(instance)
- # Soft-delete transition (false -> true). All channels (web/MCP/API) delete via this PATCH path,
- # so this is the single place to capture deletes. Snapshot tile counts before _delete_related_tiles
- # runs below — otherwise get_analytics_metadata()'s item_count would read 0 post-deletion.
being_deleted = not instance.deleted and validated_data.get("deleted", False)
- tile_count_at_deletion = instance.tiles.count() if being_deleted else None
- item_count_at_deletion = instance.tiles.exclude(insight=None).count() if being_deleted else None
initial_data = dict(self.initial_data)
@@ -2165,11 +2191,11 @@ class DashboardSerializer(DashboardMetadataSerializer):
TeamHomeTabDashboardConfig.objects.for_team(instance.team_id).filter(dashboard_id=instance.id).update(
dashboard=None
)
- from posthog.models.group_type_mapping import clear_dashboard_from_group_type_mapping
-
- clear_dashboard_from_group_type_mapping(
- team_id=instance.team_id, dashboard_id=instance.id, project_id=instance.team.project_id
- )
+ group_dashboard_ids = self.context.get("group_type_mapping_dashboard_ids")
+ if group_dashboard_ids is None or instance.id in group_dashboard_ids:
+ clear_dashboard_from_group_type_mapping(
+ team_id=instance.team_id, dashboard_id=instance.id, project_id=instance.team.project_id
+ )
request_filters = initial_data.get("filters")
if request_filters is not None:
@@ -2246,9 +2272,11 @@ class DashboardSerializer(DashboardMetadataSerializer):
user,
"dashboard deleted",
{
- **instance.get_analytics_metadata(),
- "item_count": item_count_at_deletion, # override post-delete 0 with pre-delete snapshot
- "tile_count": tile_count_at_deletion,
+ "dashboard_id": instance.pk,
+ "pinned": instance.pinned,
+ "created_at": instance.created_at,
+ "has_description": instance.description != "",
+ "creation_mode": instance.creation_mode,
},
team=instance.team,
request=self.context["request"],
@@ -2960,6 +2988,55 @@ class DashboardsViewSet(
"mcp-analytics": get_mcp_analytics_default_template,
}
+ @validated_request(
+ request_serializer=DashboardBulkDeleteRequestSerializer,
+ responses={200: DashboardBulkDeleteResponseSerializer},
+ description="Soft-delete up to 100 dashboards. Optionally delete insights with no remaining dashboard. Report missing or inaccessible dashboards as skipped.",
+ )
+ @action(methods=["POST"], detail=False, required_scopes=["dashboard:write"], renderer_classes=[SafeJSONRenderer])
+ def bulk_delete(self, request: ValidatedRequest, **kwargs: Any) -> Response:
+ ids: list[int] = list(dict.fromkeys(request.validated_data["ids"]))
+ dashboards = {dashboard.id: dashboard for dashboard in self.get_queryset().filter(id__in=ids)}
+ deleted: list[int] = []
+ skipped: list[dict[str, int | str]] = []
+ serializer_context = self.get_serializer_context()
+ serializer_context["group_type_mapping_dashboard_ids"] = get_group_type_mapping_dashboard_ids(
+ self.team.project_id
+ )
+ for dashboard_id in ids:
+ dashboard = dashboards.get(dashboard_id)
+ if dashboard is None:
+ skipped.append({"id": dashboard_id, "reason": "Dashboard not found"})
+ continue
+ try:
+ self.check_object_permissions(request, dashboard)
+ except exceptions.PermissionDenied:
+ skipped.append({"id": dashboard_id, "reason": "You do not have permission to edit this dashboard"})
+ continue
+ with transaction.atomic():
+ serializer = self.get_serializer(
+ dashboard,
+ data={"deleted": True, "delete_insights": request.validated_data["delete_insights"]},
+ partial=True,
+ context=serializer_context,
+ )
+ serializer.is_valid(raise_exception=True)
+ self.perform_update(serializer)
+ deleted.append(dashboard_id)
+ report_user_action(
+ request.user,
+ "dashboards bulk deleted",
+ {
+ "requested_count": len(ids),
+ "deleted_count": len(deleted),
+ "skipped_count": len(skipped),
+ "delete_insights": request.validated_data["delete_insights"],
+ },
+ team=self.team,
+ request=request,
+ )
+ return Response(DashboardBulkDeleteResponseSerializer(instance={"deleted": deleted, "skipped": skipped}).data)
+
@tracer.start_as_current_span("DashboardViewSet.get_serializer_context")
def get_serializer_context(self) -> dict[str, Any]:
context = super().get_serializer_context()
@@ -3057,6 +3134,9 @@ class DashboardsViewSet(
assert self.team.project_id is not None
queryset = self.queryset.filter(team__project_id=self.team.project_id)
+ if self.action == "bulk_delete":
+ return queryset.exclude(deleted=True).select_related("team")
+
# subscribe_nudge only reads the dashboard's pk and name, so skip the detail prefetch
# cascade (tiles → insights → their dashboards) and the folder/last-viewed annotations.
# Team scoping is preserved by the filter above; the CanEditDashboard object permission
diff --git a/products/dashboards/frontend/emptyState/dashboardsSetupLogic.test.ts b/products/dashboards/frontend/emptyState/dashboardsSetupLogic.test.ts
index 673548cdcca1..07e49513bd5e 100644
--- a/products/dashboards/frontend/emptyState/dashboardsSetupLogic.test.ts
+++ b/products/dashboards/frontend/emptyState/dashboardsSetupLogic.test.ts
@@ -49,6 +49,28 @@ describe('dashboardsSetupLogic', () => {
expect(productSetupStatusLogic({ productKey: ProductKey.DASHBOARDS }).values.status).toBe('has-data')
})
+ it.each(['single', 'bulk'] as const)(
+ 'returns to setup after the last visible dashboard is deleted through %s deletion',
+ async (method) => {
+ listSpy.mockResolvedValueOnce({ count: 1, results: [] }).mockImplementation(async (_, params) => ({
+ count: params?.exclude_generated ? 0 : 1,
+ results: [],
+ }))
+ const logic = dashboardsSetupLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(productSetupStatusLogic({ productKey: ProductKey.DASHBOARDS }).values.status).toBe('has-data')
+
+ if (method === 'bulk') {
+ dashboardsModel.actions.bulkDeleteDashboardsSuccess({ deleted: [1], skipped: [] })
+ } else {
+ dashboardsModel.actions.deleteDashboardSuccess({ id: 1, name: 'Last', deleted: true } as any)
+ }
+ await expectLogic(logic).toFinishAllListeners()
+ expect(productSetupStatusLogic({ productKey: ProductKey.DASHBOARDS }).values.status).toBe('needs-setup')
+ }
+ )
+
it('fails open to unknown when the count query fails before any answer', async () => {
listSpy.mockRejectedValue(new Error('network down'))
const logic = dashboardsSetupLogic()
diff --git a/products/dashboards/frontend/emptyState/dashboardsSetupLogic.ts b/products/dashboards/frontend/emptyState/dashboardsSetupLogic.ts
index 54f935f8637c..f6cd90a832d5 100644
--- a/products/dashboards/frontend/emptyState/dashboardsSetupLogic.ts
+++ b/products/dashboards/frontend/emptyState/dashboardsSetupLogic.ts
@@ -16,13 +16,18 @@ export const dashboardsSetupLogic = createSetupDetectionLogic({
path: ['products', 'dashboards', 'frontend', 'emptyState', 'dashboardsSetupLogic'],
detect: async () => {
const projectId = String(projectLogic.findMounted()?.values.currentProjectId)
- const response = await dashboardsList(projectId, { limit: 1 })
+ const response = await dashboardsList(projectId, { limit: 1, exclude_generated: true })
return response.count > 0 ? 'has-data' : 'needs-setup'
},
- // The empty state creates the first dashboard in a modal, and its "open after
- // creation" field defaults to off, so the usual path leaves the user on this scene
- // with no remount to re-run detection.
- recheckActionTypes: () => [dashboardsModel.actionTypes.addDashboardSuccess],
+ // Creation and deletion can leave this scene mounted, so its setup status must follow entity changes.
+ recheckActionTypes: () => [
+ dashboardsModel.actionTypes.addDashboardSuccess,
+ dashboardsModel.actionTypes.deleteDashboardSuccess,
+ dashboardsModel.actionTypes.restoreDashboardSuccess,
+ dashboardsModel.actionTypes.bulkDeleteDashboardsSuccess,
+ dashboardsModel.actionTypes.reloadDashboardsSuccess,
+ ],
+ allowReturnToSetup: true,
cacheHasData: true,
revalidateCachedHasData: true,
})
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index f572a556c931..43218235f40b 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -10890,6 +10890,31 @@ export interface UpdateDashboardWidgetsBatchResponseApi {
tiles: DashboardTileApi[]
}
+export interface DashboardBulkDeleteRequestApi {
+ /**
+ * Dashboard IDs to soft-delete. At most 100 IDs per request.
+ * @maxItems 100
+ * @items.minimum 1
+ */
+ ids: number[]
+ /** Also delete insights that have no remaining dashboard after deletion. Defaults to false. */
+ delete_insights?: boolean
+}
+
+export interface DashboardBulkDeleteSkippedApi {
+ /** ID of the dashboard that was skipped. */
+ id: number
+ /** Reason the dashboard was skipped. */
+ reason: string
+}
+
+export interface DashboardBulkDeleteResponseApi {
+ /** IDs of dashboards that were soft-deleted. */
+ deleted: number[]
+ /** Dashboards that were not deleted. */
+ skipped: DashboardBulkDeleteSkippedApi[]
+}
+
/**
* * `add` - add
* * `remove` - remove
diff --git a/products/dashboards/frontend/generated/api.ts b/products/dashboards/frontend/generated/api.ts
index 4f08e7c1327f..c87b9ac4cde1 100644
--- a/products/dashboards/frontend/generated/api.ts
+++ b/products/dashboards/frontend/generated/api.ts
@@ -17,6 +17,8 @@ import type {
CopyDashboardTileRequestApi,
CreateTextTileRequestApi,
DashboardApi,
+ DashboardBulkDeleteRequestApi,
+ DashboardBulkDeleteResponseApi,
DashboardSubscribeNudgeResponseApi,
DashboardTemplateApi,
DashboardTemplatesListParams,
@@ -891,6 +893,26 @@ export const dashboardsUpdateWidgetsBatch = async (
)
}
+export const getDashboardsBulkDeleteCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/dashboards/bulk_delete/`
+}
+
+/**
+ * Soft-delete up to 100 dashboards. Optionally delete insights with no remaining dashboard. Report missing or inaccessible dashboards as skipped.
+ */
+export const dashboardsBulkDeleteCreate = async (
+ projectId: string,
+ dashboardBulkDeleteRequestApi: DashboardBulkDeleteRequestApi,
+ options?: RequestInit
+): Promise<DashboardBulkDeleteResponseApi> => {
+ return apiMutator<DashboardBulkDeleteResponseApi>(getDashboardsBulkDeleteCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(dashboardBulkDeleteRequestApi),
+ })
+}
+
export const getDashboardsBulkUpdateTagsCreateUrl = (
projectId: string,
params?: DashboardsBulkUpdateTagsCreateParams
diff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.ts
index 6fdbcb833000..bf5bb27073a0 100644
--- a/products/dashboards/frontend/generated/api.zod.ts
+++ b/products/dashboards/frontend/generated/api.zod.ts
@@ -2480,6 +2480,25 @@ export const DashboardsUpdateWidgetsBatchBody = /* @__PURE__ */ zod
})
.describe('OpenAPI-only batch-update schema with widget_type-discriminated config shapes for agents.')
+/**
+ * Soft-delete up to 100 dashboards. Optionally delete insights with no remaining dashboard. Report missing or inaccessible dashboards as skipped.
+ */
+
+export const dashboardsBulkDeleteCreateBodyIdsMax = 100
+
+export const dashboardsBulkDeleteCreateBodyDeleteInsightsDefault = false
+
+export const DashboardsBulkDeleteCreateBody = /* @__PURE__ */ zod.object({
+ ids: zod
+ .array(zod.number().min(1))
+ .max(dashboardsBulkDeleteCreateBodyIdsMax)
+ .describe('Dashboard IDs to soft-delete. At most 100 IDs per request.'),
+ delete_insights: zod
+ .boolean()
+ .default(dashboardsBulkDeleteCreateBodyDeleteInsightsDefault)
+ .describe('Also delete insights that have no remaining dashboard after deletion. Defaults to false.'),
+})
+
/**
* Bulk update tags on multiple objects.
*
diff --git a/products/dashboards/mcp/tools.yaml b/products/dashboards/mcp/tools.yaml
index d3cf87c116f9..177028f2f693 100644
--- a/products/dashboards/mcp/tools.yaml
+++ b/products/dashboards/mcp/tools.yaml
@@ -662,6 +662,22 @@ tools:
id:
cast: string-int
feature_flag: dashboard-widgets
+ dashboards-bulk-delete:
+ operation: dashboards_bulk_delete_create
+ enabled: true
+ scopes:
+ - dashboard:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Delete dashboards in bulk
+ description: >
+ Soft-delete up to 100 dashboards by ID. Saved insights are kept by default. Set delete_insights to true to
+ also delete insights with no remaining dashboard. Returns deleted IDs and skipped IDs with reasons.
+ Dashboards that the caller cannot edit are skipped. To restore a dashboard, use the REST API: PATCH
+ /api/projects/{project_id}/dashboards/{id}/ with {"deleted": false}. The dashboard-update MCP tool does not
+ support restoring deleted dashboards.
dashboards-get-all:
operation: dashboards_list
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 6d9806aa9bd0..08ebc9ba1250 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -3692,6 +3692,20 @@
},
"feature_flag": "dashboard-widgets"
},
+ "dashboards-bulk-delete": {
+ "description": "Soft-delete up to 100 dashboards by ID. Saved insights are kept by default. Set delete_insights to true to also delete insights with no remaining dashboard. Returns deleted IDs and skipped IDs with reasons. Dashboards that the caller cannot edit are skipped. To restore a dashboard, use the REST API: PATCH /api/projects/{project_id}/dashboards/{id}/ with {\"deleted\": false}. The dashboard-update MCP tool does not support restoring deleted dashboards.",
+ "category": "Dashboards",
+ "feature": "dashboards",
+ "summary": "Delete dashboards in bulk",
+ "title": "Delete dashboards in bulk",
+ "required_scopes": ["dashboard:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"dashboards-get-all": {
"description": "List dashboards in the project. The optional `search` parameter runs a fuzzy match against name and description using Postgres trigram word similarity (handles typos, transpositions, and prefix-as-you-type) and returns results ranked by relevance — use it to find a specific dashboard by name rather than paging through every dashboard. `search` is capped at 200 characters; longer queries return a 400 error. Optional filters by tag and pinned status are also supported. Returns name, description, pinned status, tags, and creation metadata. Tiles and insights are not included — use dashboard-get to fetch a dashboard's tiles, then dashboard-insights-run to fetch the actual data for each insight.",
"category": "Dashboards",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 5b84a9a6f971..dc9f919a517d 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -3707,6 +3707,20 @@
},
"feature_flag": "dashboard-widgets"
},
+ "dashboards-bulk-delete": {
+ "description": "Soft-delete up to 100 dashboards by ID. Saved insights are kept by default. Set delete_insights to true to also delete insights with no remaining dashboard. Returns deleted IDs and skipped IDs with reasons. Dashboards that the caller cannot edit are skipped. To restore a dashboard, use the REST API: PATCH /api/projects/{project_id}/dashboards/{id}/ with {\"deleted\": false}. The dashboard-update MCP tool does not support restoring deleted dashboards.",
+ "category": "Dashboards",
+ "feature": "dashboards",
+ "summary": "Delete dashboards in bulk",
+ "title": "Delete dashboards in bulk",
+ "required_scopes": ["dashboard:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"dashboards-get-all": {
"description": "List dashboards in the project. The optional `search` parameter runs a fuzzy match against name and description using Postgres trigram word similarity (handles typos, transpositions, and prefix-as-you-type) and returns results ranked by relevance — use it to find a specific dashboard by name rather than paging through every dashboard. `search` is capped at 200 characters; longer queries return a 400 error. Optional filters by tag and pinned status are also supported. Returns name, description, pinned status, tags, and creation metadata. Tiles and insights are not included — use dashboard-get to fetch a dashboard's tiles, then dashboard-insights-run to fetch the actual data for each insight.",
"category": "Dashboards",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f83db674e5b3..fcde5e88a317 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -27843,6 +27843,31 @@ export namespace Schemas {
readonly search_match_type: SearchMatchTypeEnum | null;
}
+ export interface DashboardBulkDeleteRequest {
+ /**
+ * Dashboard IDs to soft-delete. At most 100 IDs per request.
+ * @maxItems 100
+ * @items.minimum 1
+ */
+ ids: number[];
+ /** Also delete insights that have no remaining dashboard after deletion. Defaults to false. */
+ delete_insights?: boolean;
+ }
+
+ export interface DashboardBulkDeleteSkipped {
+ /** ID of the dashboard that was skipped. */
+ id: number;
+ /** Reason the dashboard was skipped. */
+ reason: string;
+ }
+
+ export interface DashboardBulkDeleteResponse {
+ /** IDs of dashboards that were soft-deleted. */
+ deleted: number[];
+ /** Dashboards that were not deleted. */
+ skipped: DashboardBulkDeleteSkipped[];
+ }
+
/**
* OpenAPI-only shape for a dashboard's filters object (agents/MCP).
*
diff --git a/services/mcp/src/generated/dashboards/api.ts b/services/mcp/src/generated/dashboards/api.ts
index ae28342277e6..487185669478 100644
--- a/services/mcp/src/generated/dashboards/api.ts
+++ b/services/mcp/src/generated/dashboards/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 18 enabled ops
+ * PostHog API - MCP 19 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -3926,6 +3926,32 @@ export const DashboardsUpdateWidgetsBatchBody = () => zod
})
.describe('OpenAPI-only batch-update schema with widget_type-discriminated config shapes for agents.')
+/**
+ * Soft-delete up to 100 dashboards. Optionally delete insights with no remaining dashboard. Report missing or inaccessible dashboards as skipped.
+ */
+export const DashboardsBulkDeleteCreateParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const dashboardsBulkDeleteCreateBodyIdsMax = 100
+
+export const dashboardsBulkDeleteCreateBodyDeleteInsightsDefault = false
+
+export const DashboardsBulkDeleteCreateBody = () => zod.object({
+ ids: zod
+ .array(zod.number().min(1))
+ .max(dashboardsBulkDeleteCreateBodyIdsMax)
+ .describe('Dashboard IDs to soft-delete. At most 100 IDs per request.'),
+ delete_insights: zod
+ .boolean()
+ .default(dashboardsBulkDeleteCreateBodyDeleteInsightsDefault)
+ .describe('Also delete insights that have no remaining dashboard after deletion. Defaults to false.'),
+})
+
/**
* List registered dashboard widget types and per-type config_schema documentation for agents.
*/
diff --git a/services/mcp/src/tools/generated/dashboards.ts b/services/mcp/src/tools/generated/dashboards.ts
index c935b54f094c..eba7eab67d59 100644
--- a/services/mcp/src/tools/generated/dashboards.ts
+++ b/services/mcp/src/tools/generated/dashboards.ts
@@ -869,6 +869,35 @@ const dashboardWidgetsRun = (): ToolBase<
},
})
+const DashboardsBulkDeleteSchema = () => {
+ const DashboardsBulkDeleteCreateBody = orvalSchemas.DashboardsBulkDeleteCreateBody()
+ return DashboardsBulkDeleteCreateBody
+}
+
+const dashboardsBulkDelete = (): ToolBase<
+ ReturnType<typeof DashboardsBulkDeleteSchema>,
+ Schemas.DashboardBulkDeleteResponse
+> => ({
+ name: 'dashboards-bulk-delete',
+ schema: DashboardsBulkDeleteSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof DashboardsBulkDeleteSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.ids !== undefined) {
+ body['ids'] = params.ids
+ }
+ if (params.delete_insights !== undefined) {
+ body['delete_insights'] = params.delete_insights
+ }
+ const result = await context.api.request<Schemas.DashboardBulkDeleteResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/dashboards/bulk_delete/`,
+ body,
+ })
+ return result
+ },
+})
+
const DashboardsGetAllSchema = () => {
const DashboardsListQueryParams = orvalSchemas.DashboardsListQueryParams()
return DashboardsListQueryParams.omit({ format: true }).extend({
@@ -930,5 +959,6 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'dashboard-widgets-batch-add': dashboardWidgetsBatchAdd,
'dashboard-widgets-batch-update': dashboardWidgetsBatchUpdate,
'dashboard-widgets-run': dashboardWidgetsRun,
+ 'dashboards-bulk-delete': dashboardsBulkDelete,
'dashboards-get-all': dashboardsGetAll,
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboards-bulk-delete.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboards-bulk-delete.json
new file mode 100644
index 000000000000..4e01a0c5ecdc
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboards-bulk-delete.json
@@ -0,0 +1,21 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "delete_insights": {
+ "default": false,
+ "description": "Also delete insights that have no remaining dashboard after deletion. Defaults to false.",
+ "type": "boolean"
+ },
+ "ids": {
+ "description": "Dashboard IDs to soft-delete. At most 100 IDs per request.",
+ "items": {
+ "minimum": 1,
+ "type": "number"
+ },
+ "maxItems": 100,
+ "type": "array"
+ }
+ },
+ "required": ["ids"],
+ "type": "object"
+}