:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
docs(dashboards): add agent skills and contributing docs for dashboard widgets (1/4) (#60516)
Matt Puacbd0249a47aa
diff --git a/.agents/skills/dashboard-widgets/SKILL.md b/.agents/skills/dashboard-widgets/SKILL.mdnew file mode 100644index 000000000000..9474c72afc0e--- /dev/null+++ b/.agents/skills/dashboard-widgets/SKILL.md@@ -0,0 +1,129 @@+---+name: dashboard-widgets+description: >+ Guides PostHog engineers through dashboard widget platform work in the repo — ship a+ new widget_type (WIDGET_REGISTRY, catalog, run_widgets, WidgetCard) or change an+ existing shipped type (config, query, layout, RBAC). Use when implementing or+ modifying dashboard widget types such as error_tracking_list or session_replay_list.+ New types require widget-intake spec confirmation before coding. Do not use for MCP+ batch-add of existing types or adding tiles to a dashboard.+---++# Managing dashboard widgets++For **PostHog engineers** working on dashboard **widget tiles** in the repo.++Human overview: [`products/dashboards/CONTRIBUTING.md`](../../../products/dashboards/CONTRIBUTING.md)++**In scope:** widget tiles (`widget_id` on `DashboardTile`) — ship new types or change shipped types.++**Out of scope:** adding an existing type to a dashboard (MCP `dashboard-widget-catalog-list` → `dashboard-widgets-batch-add`); insight tiles, text cards, button tiles.++## 1. Route first++| Request | Path | Start here |+| ---------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------ |+| New **`widget_type`** that does not exist | **Ship** | [§2 Ship a new type](#2-ship-a-new-widget_type) — intake mandatory |+| Change a **shipped** type (config, query, UI, layout, RBAC, deprecate) | **Update** | [§3 Update a shipped type](#3-update-a-shipped-type) — skip intake |+| Add existing type to a dashboard | — | MCP only — not this skill |++Shipped types (code truth): [architecture.md § Shipped types](references/architecture.md#shipped-types-source-of-truth).++## 2. Ship a new widget_type++### Intake — ask before coding++**Mandatory for new types only.** Read [widget-intake.md](references/widget-intake.md) and:++1. Infer from the request ([§2.2 defaults](#22-infer--defaults)).+2. Ask **one batched follow-up** for gaps — max 6 questions ([question bank](references/widget-intake.md#ask-when-not-stated)).+3. Post the [spec table](references/widget-intake.md#spec-fields-to-lock); get confirmation before checklist §1.++### 2.2 Infer — defaults++Apply silently; ask only when the request is silent on a [question-bank](references/widget-intake.md) row.++| Derive | Default |+| ------------------- | ----------------------------------------------------------------------------- |+| `widget_type` | Unique `snake_case` from label |+| `groupId` | Same as sibling in that product area |+| Copy spine | `error_tracking_list` / `frontend/widgets/error_tracking/` |+| Copy spine (replay) | `session_replay_list` when recordings, throttles, or session RBAC |+| Config | List: `limit`, `orderBy`, `orderDirection`, `dateRange`, `filterTestAccounts` |+| RBAC | Same `required_product_access` as sibling |+| Layout | Sibling `defaultLayout`; explicit `minH` for dense lists |+| Setup gating | Match sibling pattern |+| `sharedPlaceholder` | Platform default |++### 2.3 Execute++After spec confirmation → [checklist-new-widget-type.md](references/checklist-new-widget-type.md) **§1 → §8**. §5b / §9 after MVP tests green.++## 3. Update a shipped type++**Skip intake.** The `widget_type` already exists — identify it from the request or `EXPECTED_WIDGET_TYPES` in `widget_registry.py`.++1. Read [managing-existing-widgets.md](references/managing-existing-widgets.md) — use the **"What kind of change?"** routing table for primary files.+2. Confirm with the engineer: which shipped type, what changes, and whether stored tiles need backward-compatible config migration.+3. Follow linked references from that table (composition, layout, permissions, availability) — do not re-read the new-type checklist.++**Cannot change in place:** `widget_type` string on existing rows; stored `w`/`h` for tiles already on dashboards when catalog defaults change.++**New visualization kind** = ship a new type ([§2](#2-ship-a-new-widget_type)), not an update.++## 4. Platform invariants++Both paths:++1. **RBAC registry-driven** — no `widget_type` branches in `dashboard.py`. [permissions-and-sharing.md § Product RBAC](references/permissions-and-sharing.md#product-rbac)+2. **One `widget_type` everywhere** — registries + both catalogs + FE registry; variants share `groupId` only.+3. **Per-type code in product paths** — not in platform shells. [architecture.md § Platform files](references/architecture.md#platform-files--do-not-branch-per-type)+4. **WidgetCard compound pattern** — [composition.md](references/composition.md)+5. **Config PATCH = JSONField** — typed OpenAPI in `widget_openapi_serializers.py` only.++New `widget_type` strings need **no migration** — register registries + catalogs only.++## 5. Companion skills++| Skill | When |+| ------------------------------ | ----------------------------------------------------- |+| `improving-drf-endpoints` | `widget_openapi_serializers.py` or serializer changes |+| `writing-kea-logics` | `edit*WidgetModalLogic.ts` or `dashboardLogic.tsx` |+| `django-migrations` | `DashboardWidget` / `DashboardTile` schema only |+| `adopting-generated-api-types` | Tile PATCH in `frontend/utils.ts` |++## 6. Verify++**Ship (MVP):**++```bash+hogli test products/dashboards/backend/api/test/test_run_widgets.py+hogli test products/dashboards/backend/api/test/test_dashboard_widgets.py+hogli test products/dashboards/frontend/widgets/registry.test.tsx+```++**Ship (before PR):** [checklist §8](references/checklist-new-widget-type.md#8-tests) + `hogli build:openapi`.++**Update:** tests for the area you touched — at minimum:++```bash+hogli test products/dashboards/backend/api/test/test_run_widgets.py # if run_* / validate_* changed+hogli test products/dashboards/frontend/widgets/ # if Component / modal changed+hogli build:openapi # if config OpenAPI / serializers changed+```++See [managing-existing-widgets.md](references/managing-existing-widgets.md) routing table **Also check** column per change type.++## Reference appendix++| Topic | Doc |+| ----------------------- | ----------------------------------------------------------------------- |+| Intake (new types only) | [widget-intake.md](references/widget-intake.md) |+| New type checklist | [checklist-new-widget-type.md](references/checklist-new-widget-type.md) |+| Update shipped type | [managing-existing-widgets.md](references/managing-existing-widgets.md) |+| Architecture | [architecture.md](references/architecture.md) |+| WidgetCard / edit modal | [composition.md](references/composition.md) |+| Tile min/max | [layout-and-ux.md](references/layout-and-ux.md) |+| RBAC / sharing | [permissions-and-sharing.md](references/permissions-and-sharing.md) |+| Setup gates | [availability-and-gating.md](references/availability-and-gating.md) |+| MCP after ship | [mcp.md](references/mcp.md) |diff --git a/.agents/skills/dashboard-widgets/references/architecture.md b/.agents/skills/dashboard-widgets/references/architecture.mdnew file mode 100644index 000000000000..598c8f601584--- /dev/null+++ b/.agents/skills/dashboard-widgets/references/architecture.md@@ -0,0 +1,192 @@+# Dashboard widgets architecture++## Mental model++```text+Dashboard+ └── DashboardTile (layout, color, placement)+ └── widget_id → DashboardWidget (team-scoped content entity)+ ├── widget_type: str # no DB enum — validated in registry/serializer; typed as DashboardWidgetType in Python+ ├── config: JSON+ ├── name, description, audit fields+ └── team FK (tenant isolation)+```++| Layer | Location | Role |+| ----------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |+| Persistence | `products/dashboards/backend/models/dashboard_widget.py`, `dashboard_tile.py` | Exactly one content FK per tile: insight \| text \| button_tile \| widget (DB CHECK) |+| Backend runtime | `products/dashboards/backend/widgets/<type>.py` + `widget_registry.py` | Per-type validate/run; aggregator registry |+| Backend access | `products/dashboards/backend/widget_access.py` | `required_product_access` → RBAC check |+| Backend catalog | `products/dashboards/backend/widget_catalog.py` | Labels, grouping, `config_schema_hints` for REST/MCP |+| Data fetch | `GET .../dashboards/:id/run_widgets?tile_ids=` in `dashboard.py` | Batched per-tile results + per-tile errors (generic loop); emits **`dashboard_widget_delivery`** SLO per tile query |+| Frontend dispatch | `widgets/registry.tsx` | `DASHBOARD_WIDGET_REGISTRY` → `Component` + `EditModal` |+| Catalog / layout | `frontend/widget_types/` | Add modal, defaults, headers, RBAC map, grid sizing |+| Scene glue | `frontend/src/scenes/dashboard/` | Fetch, CRUD, copy/move, undo remove |++**New `widget_type` strings need no migration** — register in both backend and frontend registries + catalog.++## Naming++| Context | Convention | Example |+| -------------------------------------------- | ---------------------- | ------------------------------------------- |+| Product widget dirs under `widgets/` | `snake_case` | `widgets/error_tracking/` |+| Catalog keys / `widget_type` / registry keys | `snake_case` | `error_tracking_list` |+| Shared `widget_types/` modules | `snake_case` filenames | `configSchemas.ts`, `widgetAvailability.ts` |+| React component dirs under `components/` | `PascalCase` | `WidgetCard/`, `DashboardWidgetItem/` |+| MCP tool names | `kebab-case` | `dashboard-widgets-run` |++Colocate widget code in `widgets/<product>/` — do not scaffold empty `hooks/` or `logic/` dirs until kea is actually needed.++## Shipped types (source of truth)++**Do not hand-maintain type lists in this skill.** Canonical set:++- `EXPECTED_WIDGET_TYPES` / `WIDGET_REGISTRY` — `backend/widget_registry.py`+- `WIDGET_CATALOG` — `backend/widget_catalog.py`+- `DASHBOARD_WIDGET_CATALOG` — `frontend/widget_types/catalog.ts`+- OpenAPI config serializers — `backend/api/widget_openapi_serializers.py`++CI: `test_run_widgets.py` (registry + catalog + OpenAPI serializer count), `registry.test.tsx` (FE catalog ↔ registry).++Default pattern: copy `error_tracking_list` end-to-end (`frontend/widgets/error_tracking/`). Use `session_replay_list` when you need catalog `availability`, replay throttles, or session-recording RBAC.++Per-type add flow (ordered checklist): [checklist-new-widget-type.md](checklist-new-widget-type.md).++## Backend registry entry shape++Files: `products/dashboards/backend/widgets/<widget_type>.py` + `widget_registry.py`++```python+# widgets/your_type.py — validate + run for one widget_type+# widget_registry.py — aggregator only+WIDGET_REGISTRY: dict[str, WidgetRegistryEntry] = {+ "your_type": {+ "validate_config": validate_your_type_config,+ "query_fn": run_your_type_widget,+ "required_scopes": ["your_product:read"], # documentation only+ "required_product_access": "your_product", # RBAC gate via widget_access.py+ },+}+```++- `validate_<type>_config` / `run_<type>_widget` live in `widgets/<widget_type>.py` — call the **same** query runner the standalone product uses+- Registry wiring checklist: [checklist-new-widget-type.md §1–2](checklist-new-widget-type.md)+- Product RBAC: [permissions-and-sharing.md § Product RBAC](permissions-and-sharing.md#product-rbac)++## Frontend registry entry shape++File: `products/dashboards/frontend/widgets/registry.tsx`++```typescript+import { YourWidget } from './your_product/YourWidget'+import { EditYourWidgetModal } from './your_product/EditYourWidgetModal'++export const DASHBOARD_WIDGET_REGISTRY = {+ your_type: {+ Component: YourWidget,+ EditModal: EditYourWidgetModal,+ productAccess: 'your_product',+ parseConfigApiError: parseYourWidgetConfigApiError,+ },+} satisfies Record<DashboardWidgetCatalogKey, DashboardWidgetDefinition>+```++Checklist steps: [checklist-new-widget-type.md §7](checklist-new-widget-type.md#7-frontend-registry).++Catalog entry in `widget_types/catalog.ts` drives add modal, layouts, headers, previews, and **public/shared placeholder copy** — registry alone is not enough.++Optional catalog `availability` declares project setup prerequisites (exception autocapture, etc.). Gating runs at **tile render** via `WidgetRuntimeAvailabilityGuard`, not in the add modal — see [availability-and-gating.md](availability-and-gating.md).++## Widget type vs catalog group++| Field | Role |+| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `widget_type` | Unique ID everywhere: catalog key, `WIDGET_REGISTRY` key, DB column, `DASHBOARD_WIDGET_REGISTRY` key |+| `groupId` | Product area section in add-widget modal — **multiple `widget_type` entries can share one group** (e.g. `error_tracking_list` and another error-tracking variant both use `groupId: 'error_tracking'`) |+| `label` | Variant name within the group ("Top issues", "Recent recordings"); fallback card title |++Group display labels live in `DASHBOARD_WIDGET_GROUP_LABELS` — use `getDashboardWidgetGroupLabel(groupId)` in edit modals and card headers.++`getDashboardWidgetCatalogGroups()` in `AddWidgetModal.tsx` builds grouped picker sections from catalog entries. Card headers use `getDashboardWidgetGroupLabel(groupId)` for the product type chip (`DashboardWidgetItem` → `WidgetCardHeader`).++Adding a second variant in an existing group still requires a full new `widget_type` stack — only `groupId` is reused. See checklist §4b.++## Platform files — do not branch per type++| File | Role |+| -------------------------------- | --------------------------------------------------------------------------------------------------------------------- |+| `dashboard.py` `run_widgets` | Generic loop — `get_widget_registry_entry` + `get_widget_product_access_error` only |+| `DashboardWidgetItem.tsx` | Generic shell — RBAC via `userHasDashboardWidgetProductAccess`; unknown types: header fallback + body `ErrorBoundary` |+| `WidgetCard.tsx` / header / body | Shared compound chrome — no product imports |+| `dashboardLogic.tsx` | Generic fetch/CRUD — no `widget_type` switches for data |+| `widgetFetchUtils.ts` | Batched `run_widgets` only |++Import `Component` / `EditModal` directly in `registry.tsx` (no `React.lazy`). Each new type adds files under `backend/widgets/` and `frontend/widgets/<product>/` — not branches in the table above.++## CI type-safety nets++- BE: `EXPECTED_WIDGET_TYPES == WIDGET_REGISTRY.keys()` and `WIDGET_CATALOG` keys match+- BE: OpenAPI polymorphic config serializer count matches registry (`test_run_widgets.py`)+- FE: `DASHBOARD_WIDGET_REGISTRY satisfies Record<DashboardWidgetCatalogKey, …>`+- FE: `DASHBOARD_WIDGET_PREVIEWS` keyed by catalog; `registry.test.tsx` covers every catalog key+- Runtime: `getDashboardWidgetDefinition` → PostHog `captureException` on miss (deploy skew)++## Footguns++| Mistake | Fix |+| ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Nested per-type widget config serializer on dashboard PATCH | Keep tile `config` as `JSONField` on serializers — typed OpenAPI serializers belong in `widget_openapi_serializers.py` only |+| Registry entry without catalog entry | Catalog drives add modal, layouts, headers, previews — registry alone is not enough |+| Reused `widget_type` for a new variant | Each variant needs its own catalog key + full BE/FE stack; share `groupId` only |+| `gridChildren` used for widget body | RGL resize handles only — content goes in composed `WidgetCardBody` |+| Config API error parsing in `utils.ts` | Per-type **`parseConfigApiError`** on `DASHBOARD_WIDGET_REGISTRY` entry |+| Export vs public/shared confused | Export hides widget tiles; public/shared render **`WidgetCardSharedPlaceholderBody`** without `run_widgets` — [permissions-and-sharing.md](permissions-and-sharing.md) |++Easy-to-miss paths when adding a type: `backend/widget_layouts.py` (batch-add placement), `posthog/models/resource_transfer/visitors/dashboard_widget.py` (cross-project copy), `posthog/api/test/test_sharing.py` (shared payload).++## Scene integration (usually no changes for new types)++Only touch when the new type needs special fetch/CRUD behavior:++| File | Widget-related behavior |+| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `dashboardLogic.tsx` | `addWidgetTiles` (batch POST `.../widgets/batch/`), `refreshDashboardWidgets`, `updateWidgetTile`, `widgetResultsByTileId`, `dashboardWidgetsEnabled`, copy/move — **skips `run_widgets` on `DashboardPlacement.Public`** |+| `DashboardItems.tsx` | Renders `DashboardWidgetItem` when `dashboardWidgetsEnabled && isWidgetTileVisibleOnPlacement` (export hides widgets; public renders placeholders) |+| `DashboardHeaderActions.tsx` | Add widget entry |+| `DashboardModals.tsx` | `AddWidgetModal` (multi-select) |+| `tileLayouts.ts` | Widget default/min layout from catalog |+| `widgetFetchUtils.ts` | Batched `run_widgets` fetch (15 min client TTL) |+| `dashboardUtils.ts` | `getDashboardWidgetType`, `isWidgetTileVisibleOnPlacement` (export-only hide), template helpers |++## Add widget flows++| Surface | Mechanism |+| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| UI add modal | `AddWidgetModal` multi-select → `addWidgetTiles` → POST `.../dashboards/:id/widgets/batch/` |+| REST / MCP add | `POST .../dashboards/:id/widgets/batch/` — 1–10 tiles. New tiles land on the **bottom row** via `widget_layouts.stack_widget_layout_at_bottom`. See [mcp.md](mcp.md) |++## Analytics++First-time widget tile insert fires server-side events via `_report_dashboard_tile_added` in `dashboard.py`:++- **`dashboard tile added`** — generic tile event with `tile_type: "widget"`, `widget_type`, `dashboard_id`+- **`dashboard widget added`** — widget-specific event with `widget_type`, `dashboard_id`, `tile_id`, `widget_id`, plus request `source` (`web` | `mcp` | `api` | …) from `report_user_action`++Both fire on:++- PATCH dashboard `tiles[]` with a new widget tile (tests / legacy harness)+- POST `.../widgets/batch/` (UI `addWidgetTiles`, REST, MCP)++Config/metadata updates do not re-fire either event.++## Delivery SLO++Each successful/failed widget query in `_run_widget_query` emits **`dashboard_widget_delivery`** via `slo_operation` (`SloArea.ANALYTIC_PLATFORM`) with `widget_type`, `dashboard_id`, and `tile_id`. No per-type SLO wiring — shipping a new registry entry is enough. Access/validation failures before `query_fn` runs do not emit this SLO.++## Copy, move, duplicate++Cross-project transfer, cross-dashboard copy/move, and dashboard duplication all deep-clone widget rows (move reassigns the tile only). Details: [permissions-and-sharing.md](permissions-and-sharing.md).++## Reference implementation++Mirror `products/dashboards/frontend/widgets/error_tracking/` for end-to-end patterns.diff --git a/.agents/skills/dashboard-widgets/references/availability-and-gating.md b/.agents/skills/dashboard-widgets/references/availability-and-gating.mdnew file mode 100644index 000000000000..60d71e0b19b0--- /dev/null+++ b/.agents/skills/dashboard-widgets/references/availability-and-gating.md@@ -0,0 +1,115 @@+# Widget availability and gating++Project setup prerequisites (exception autocapture, session recording ingestion, etc.) — **not** RBAC. Product access (`productAccess`) is separate: it gates who can see widget data via `run_widgets` and locked tiles; availability gates whether the project is configured to produce data.++## Product rule: gate at render, never at add++Users **always** pick and add widgets in `AddWidgetModal` — no filtering, disabling, or hiding catalog entries based on availability.++When a prerequisite is unmet, the **dashboard tile body** shows setup UI instead of widget content. The tile still exists (header, layout, edit/remove menus work).++Do **not**:++- Hide or disable variants in the add-widget picker+- Block `POST .../widgets/batch/` or dashboard PATCH add paths+- Show availability checks only in the edit modal++## Two patterns (pick one per widget type)++| Pattern | When | Catalog `availability` | Tile render |+| --------------------------- | ------------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------ |+| **Catalog-driven guard** | Single team flag checkable in `widgetAvailability.ts` | Required | `WidgetRuntimeAvailabilityGuard` wraps `Component` (always wired in `DashboardWidgetItem`) |+| **Widget-layer setup gate** | Richer rules (multi-signal, ingestion polling, product logic) | **Omit** — guard is a no-op | Inline in widget `Component` (private gate + setup UI) |++Do not set catalog `availability` when the widget handles setup internally — the guard would use the wrong (simpler) check and double-gate.++Error tracking uses inline setup gating in `ErrorTrackingWidget.tsx` — checks `exceptionIngestionLogic` (events received **or** autocapture enabled), not just `autocapture_exceptions_opt_in`.++## Catalog `availability` shape++File: `products/dashboards/frontend/widget_types/catalog.ts`++```typescript+availability?: {+ requirement: WidgetAvailabilityRequirementId // e.g. 'exception_autocapture'+ unavailableTitle: string+ unavailableReason: string+ setupActionLabel: string+ docsHref?: string+}+```++Types and evaluators: `products/dashboards/frontend/widget_types/widgetAvailability.ts`++- `WidgetAvailabilityRequirementId` — extend here when adding a new generic requirement+- `isWidgetAvailabilityRequirementMet(requirement, team)` — exhaustive switch on team fields+- `getWidgetAvailabilityStatus(config, team)` / `useWidgetAvailability(config)` — `{ isAvailable, config }`++No `availability` key → guard renders children unchanged.++## Backend `availability_requirements` (MCP catalog)++File: `products/dashboards/backend/widget_catalog.py`++Each `WIDGET_CATALOG` entry includes **`availability_requirements`**: string ids agents see via `dashboard-widget-catalog-list` (e.g. `["session_replay_enabled"]`, `["exception_autocapture"]`).++- Set these even when FE **omits** catalog `availability` and the widget uses **inline setup gating** in its `Component` (`error_tracking_list` does both).+- FE catalog `availability.requirement` and BE `availability_requirements[0]` should use the same id when both are present.++## `WidgetRuntimeAvailabilityGuard` flow++File: `products/dashboards/frontend/components/WidgetRuntimeAvailabilityGuard/WidgetRuntimeAvailabilityGuard.tsx`++Always wraps the widget `Component` in `DashboardWidgetItem`:++```text+catalogEntry.availability+ → useWidgetAvailability()+ → isAvailable? render children (widget Component)+ → else render unavailableContentFallback ?? WidgetAvailabilitySetupPrompt+```++Props:++- `availability` — from `getDashboardWidgetCatalogEntry(widget_type)?.availability`+- `unavailableContentFallback` — optional override from `DashboardWidgetDefinition.unavailableContentFallback`+- `children` — widget `Component`++Default setup UI: `WidgetAvailabilitySetupPrompt` — generic `WidgetCardProductIntroduction` + CTA per `requirement` (admin-gated enable actions, docs link, product intent capture). Extend its `switch (availability.requirement)` when adding a new `WidgetAvailabilityRequirementId`.++## Widget-layer setup gate++When catalog `availability` is omitted, handle setup gating inside the widget `Component` as private subcomponents (e.g. `ErrorTrackingWidgetSetupGate` in `ErrorTrackingWidget.tsx`).++**Do not** modify product `SetupPrompt`, `ProductIntroduction`, or other shared lib components for widget layout. Reuse product **logic** (e.g. `exceptionIngestionLogic`) from the widget wrapper; compose `WidgetCardProductIntroduction` for tile-friendly setup UI.++## Error tracking reference implementation++| Piece | Path | Role |+| ------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |+| Widget | `widgets/error_tracking/ErrorTrackingWidget.tsx` | Setup gate + body + empty/loading states |+| Product prompt (reference only) | `products/error_tracking/frontend/components/SetupPrompt/SetupPrompt.tsx` | Standalone product surface — **do not import or extend for dashboard tiles** |+| Generic prompt (catalog guard) | `components/WidgetAvailabilitySetupPrompt/WidgetAvailabilitySetupPrompt.tsx` | Catalog-driven enable-exception-autocapture UI |+| Widget tile layout wrapper | `components/WidgetCardProductIntroduction/WidgetCardProductIntroduction.tsx` | Container-query responsive layout for setup prompts inside `WidgetCardBody` |++Loading state renders **outside** the setup wrapper so skeletons show while fetching.++## Adding a new generic requirement++1. Add id to `WidgetAvailabilityRequirementId` in `widgetAvailability.ts`+2. Implement check in `isWidgetAvailabilityRequirementMet` (team field or helper)+3. Add UI branch in `WidgetAvailabilitySetupPrompt` (enable action, docs, intents)+4. Set `availability` on catalog entry+5. Test: `widgetAvailability.test.ts`, `WidgetRuntimeAvailabilityGuard.test.tsx`++## Checklist: widget type needs setup gating++- [ ] **Simple team flag?** Set catalog `availability` + evaluator in `widgetAvailability.ts` + prompt branch in `WidgetAvailabilitySetupPrompt`. Optional `unavailableContentFallback` on registry for custom setup UI.+- [ ] **Richer product rules?** Omit catalog `availability`; add private setup gate + prompt UI inside `widgets/<product>/<Component>.tsx` (reuse product logic; do not modify product SetupPrompt)+- [ ] Confirm add modal still lists the widget unconditionally+- [ ] Setup UI replaces tile **body** only — header/menus unchanged+- [ ] Loading skeleton bypasses setup prompt+- [ ] Admin restriction on destructive enable actions (`useRestrictedArea`)+- [ ] Tests for met/unmet requirement at render time++See also: [checklist-new-widget-type.md](checklist-new-widget-type.md) §4 (catalog `availability` bullet), [composition.md](composition.md) (loading ownership).diff --git a/.agents/skills/dashboard-widgets/references/checklist-new-widget-type.md b/.agents/skills/dashboard-widgets/references/checklist-new-widget-type.mdnew file mode 100644index 000000000000..43778597463c--- /dev/null+++ b/.agents/skills/dashboard-widgets/references/checklist-new-widget-type.md@@ -0,0 +1,208 @@+# Checklist: new dashboard widget type++**Audience:** PostHog engineers shipping a type that does not exist yet.++1. Complete [widget-intake.md](widget-intake.md) — infer, batched questions, **spec confirmation** (mandatory).+2. Work **§1 → §8 below in order**. Do not skip step 2 (permissions).+3. **§5b, §9, §10** — after MVP tests green.++Default copy spine: `products/dashboards/frontend/widgets/error_tracking/` (`error_tracking_list`). Use `session_replay_list` when replay throttles, availability, or session RBAC apply.++## 1. Backend registry++Files: `products/dashboards/backend/widgets/<widget_type>.py` + `widget_registry.py`++- [ ] `validate_<type>_config(config) -> dict` in `widgets/<widget_type>.py` — normalize defaults; reject bad input with `DRFValidationError`+- [ ] Merge `merge_base_widget_config_fields(config)` for shared fields (`filterTestAccounts`)+- [ ] `run_<type>_widget(team, config) -> dict` — call the **same** query runner the standalone product uses (no parallel query path); pass `resolve_filter_test_accounts(config)` when the query supports it+- [ ] Register in `WIDGET_REGISTRY` with `required_scopes` (docs only) and `required_product_access` when RBAC-gated (must match catalog `productAccess`)+- [ ] Add type to `EXPECTED_WIDGET_TYPES` and `frontend/widget_types/expectedWidgetTypes.ts` (must equal `WIDGET_REGISTRY.keys()` — enforced in tests)+- [ ] Extend `DashboardWidgetType` (`Literal[...]`) with the new canonical `widget_type` string+- [ ] Use `DEFAULT_WIDGET_LIST_LIMIT` from `backend/constants.py` unless this type needs a different default+- [ ] Pass through time-scoped fields (`dateRange`) when the query is date-filtered — use `validate_widget_date_range` from `widgets/config.py`+- [ ] List widgets with `orderDirection`: mirror `z.enum(['ASC', 'DESC'])` from existing list schemas in `configSchemas.ts`+- [ ] Throttled product listings (session replay): wire the same throttle checks in `run_widgets` that the standalone API uses++See [architecture.md](architecture.md) for registry entry shape.++## 2. Backend `run_widgets` permissions — critical++Follow [permissions-and-sharing.md § Product RBAC](permissions-and-sharing.md#product-rbac). Checklist:++- [ ] Set `required_product_access` on the `WIDGET_REGISTRY` entry when RBAC-gated (must match catalog `productAccess`)+- [ ] Optional friendly denial in `PRODUCT_ACCESS_DENIED_MESSAGES` / catalog `product_access_denied_message`+- [ ] Return per-tile `{ tile_id, error }` — do not fail the whole request for one bad tile+- [ ] Catch query exceptions → per-tile error in response (see existing `dashboard_run_widgets_failed` logging)++## 3. Backend catalog (agents + REST)++File: `products/dashboards/backend/widget_catalog.py`++- [ ] Add entry to `WIDGET_CATALOG` with `group_id`, `group_label`, `label`, `description`, `config_schema_hints`, `required_product_access`+- [ ] **`config_schema_hints`** — structured hints for MCP/agents (mirror validate defaults). Per field: `type`, optional `min`/`max`, `choices`, `default`, `optional`, nested objects (e.g. `dateRange.date_from` with `choices` from `WIDGET_DATE_FROM_VALUES`). See `error_tracking_list` / `session_replay_list` entries in `widget_catalog.py`.+- [ ] **`availability_requirements`** — string ids for agent catalog (e.g. `["session_replay_enabled"]`). Set even when FE omits catalog `availability` and uses inline setup gating in the widget `Component` (ET still sets `["exception_autocapture"]` on BE).+- [ ] **`product_access_denied_message`** (optional) — friendly RBAC copy for catalog/MCP when generic fallback is not enough+- [ ] Keeps REST/MCP catalog in sync with frontend defaults; agents call `dashboard-widget-catalog-list` / `GET .../widget_catalog/`++## 4. Frontend catalog + config schema++- [ ] `widget_types/configSchemas.ts` — per-type Zod schema extending `baseWidgetConfigSchema`; list widgets also export a form schema via `widgetListFormSchema(orderBySchema)` (or extend shared list fields)+- [ ] `widget_types/catalog.ts` — add entry to `DASHBOARD_WIDGET_CATALOG` (catalog key = `widget_type`):+ - **`groupId`** — required; product area for add-modal grouping. Add label to `DASHBOARD_WIDGET_GROUP_LABELS` when introducing a new group+ - **`label`, `description`** — required; variant name within the group (e.g. "Top issues", "Recent recordings")+ - `defaultLayout` (`w`, `h`, `minW`, `minH`)+ - Do **not** set `headerLayout` / `headerMeta` unless overriding defaults — `getDashboardWidgetCatalogEntry()` resolves `dashboard_tile` + default meta+ - Optional: `headerTitle`, `titleHref`, `productAccess`, **`sharedPlaceholder`** (public/shared dashboard body copy when `run_widgets` is not loaded)+ - Optional: `availability` — simple team-flag prerequisite for `WidgetRuntimeAvailabilityGuard` (omit when the widget handles richer setup gating inline). Gate at **tile render** only (never in add modal). See [availability-and-gating.md](availability-and-gating.md).+- [ ] `widgets/<product>/<type>WidgetConfigValidation.ts` — thin wrapper around shared helpers in `widgets/widgetConfigValidation.ts` (no hand-rolled typeof guards for config fields)++No change to `AddWidgetModal` grouping for normal adds — `getDashboardWidgetCatalogGroups()` derives groups from catalog entries automatically.++### 4b. Adding a variant to an existing group++Use when the product area already has a widget and you need another visualization (e.g. a chart alongside a list widget in the same group).++- [ ] New **unique** catalog key / `widget_type` (e.g. `error_tracking_trends`) — not a config fork of the existing type+- [ ] Reuse sibling **`groupId`** exactly; label comes from `DASHBOARD_WIDGET_GROUP_LABELS[groupId]`+- [ ] Distinct **`label`**, **`description`**, **`defaultConfig`**, **`defaultLayout`** (and usually `headerTitle`)+- [ ] Full backend stack: new `widgets/<widget_type>.py`, `WIDGET_REGISTRY` entry with `required_product_access`, `EXPECTED_WIDGET_TYPES`, extend `DashboardWidgetType`+- [ ] Full frontend stack: new component (same `widgets/<product>/` dir), edit modal + kea logic, preview in `widgets/previews/` + `DASHBOARD_WIDGET_PREVIEWS` in `catalog.ts`, registry entry in `registry.tsx`, extend `DashboardWidgetProductAccess` + `WIDGET_PRODUCT_ACCESS_CHECKS` in `widgetProductAccess.ts` when RBAC-gated+- [ ] Tests: assert shared `groupId` in `registry.test.tsx` like existing ET variants++### 4c. First widget in a new product area++Use when introducing a new **`groupId`**, not just another variant in an existing group.++- [ ] Add **`groupId`** to `DASHBOARD_WIDGET_GROUP_LABELS` in `catalog.ts`; matching **`group_id`** / **`group_label`** in BE `WIDGET_CATALOG`+- [ ] Storybook title path: `'Dashboards/Dashboard Widgets/Widget types/<groupLabel>/<label>'`+- [ ] **UI + query reuse** — pick one pattern (do not fork query paths):++| Pattern | Backend `run_*` | Frontend UI | Shipped example |+| ----------------------- | --------------------------------------------------------- | ------------------------------------------------------- | --------------------- |+| Product module | Import query runner from `products/<product>/backend/…` | Import list/UI from `products/<product>/frontend/…` | `error_tracking_list` |+| Scenes / posthog helper | Import shared helper (e.g. `posthog.session_recordings…`) | Import from `scenes/<area>/…` when UI still lives there | `session_replay_list` |++- [ ] If importing **`products/<product>/frontend/…`**: add **`products.<product>`** to `tach.toml` → `products.dashboards` `depends_on`+- [ ] RBAC: extend `DashboardWidgetProductAccess`, `WIDGET_PRODUCT_ACCESS_CHECKS`, BE `required_product_access` (+ optional `PRODUCT_ACCESS_DENIED_MESSAGES` / catalog `product_access_denied_message`)+- [ ] Availability: new `WidgetAvailabilityRequirementId` in `widgetAvailability.ts` + BE `availability_requirements` string when catalog uses `availability`; optional branch in `WidgetAvailabilitySetupPrompt`+- [ ] Optional **`titleHref`** on catalog — product scene route for header "View" link (`urls.*` or scene path)+- [ ] Net-new product: see [`products/README.md`](../../../products/README.md) for product bootstrap before wiring the widget++## 5. Frontend widget component++Directory: `products/dashboards/frontend/widgets/<product>/` (snake_case product area — e.g. `error_tracking/` for `error_tracking_list`)++- [ ] Implement `Component` with `DashboardWidgetComponentProps` (`tileId`, `config`, `result`, `loading`, `error`, `onRefresh`, `onUpdateConfig`)+- [ ] Setup gating: catalog `availability` for simple team-flag checks, or private setup gate inside the widget `Component` for richer rules — do not modify product `SetupPrompt`+- [ ] **Own loading UI** — early-return with `WidgetLoadingState` (typed skeleton as `children` when helpful)+- [ ] Use `WidgetCardContent` for scrollable lists/tables; `WidgetCardBodyMessage` for empty states+- [ ] Do **not** render card chrome — `DashboardWidgetItem` + catalog handle headers/menus++Minimal skeleton:++```tsx+export function YourWidget({ result, loading, config }: DashboardWidgetComponentProps): JSX.Element {+ if (loading) {+ return (+ <WidgetLoadingState>+ <YourTypedSkeleton />+ </WidgetLoadingState>+ )+ }+ const rows = (result as YourResult)?.results ?? []+ if (rows.length === 0) {+ return <WidgetCardBodyMessage>No data found.</WidgetCardBodyMessage>+ }+ return (+ <WidgetCardContent>+ <YourList data={rows} />+ </WidgetCardContent>+ )+}+```++See [composition.md](composition.md) for WidgetCard rules.++## 5b. Storybook++File: `products/dashboards/frontend/widgets/<product>/<YourWidget>.stories.tsx`++Reference: `products/dashboards/frontend/widgets/error_tracking/ErrorTrackingWidget.stories.tsx`++- [ ] Storybook meta: **string literal** `title: 'Dashboards/Dashboard Widgets/Widget types/<groupLabel>/<label>'` (must match catalog — CSF rejects function calls), `layout: 'padded'`, `WidgetTileFrame` decorator (see `ErrorTrackingWidget.stories.tsx`; platform primitives in `WidgetCard.stories.tsx`)+- [ ] Compose stories with `WidgetCard` + `WidgetCardHeader` + `WidgetCardBody` + catalog header metadata — not the bare widget component+- [ ] Kea seed decorators: add helpers to `widgetCardStoryFixtures.tsx` — **do not** export decorators from `*.stories.tsx` (Storybook treats exports as stories). See [composition.md § Storybook](composition.md#storybook)+- [ ] Mock `DashboardWidgetComponentProps` via `args` — no Kea, no `run_widgets` fetch+- [ ] Export stories for each visual state the tile can show:+ - **Populated** — realistic `result` payload (shape matches `run_*` output)+ - **Loading** — `loading: true`, `result: null`+ - **Empty** — `loading: false`, empty `result` (e.g. `{ results: [] }`)+ - **Error** — when the component renders `error` (pass a string or error-shaped prop your component expects)+- [ ] Include `tileId`, `config` (defaults from catalog), and stub `onUpdateConfig` / `onRefresh` where the component needs them+- [ ] Add **`getWidgetOverviewDemoState`** case in `components/WidgetCard/widgetOverviewStoryFixtures.ts` (exhaustive switch — overview story breaks if missing)+- [ ] Optional: `Edit*WidgetModal.stories.tsx` — mirror `EditErrorTrackingWidgetModal.stories.tsx` / `EditSessionReplayWidgetModal.stories.tsx`++Run locally:++```sh+pnpm storybook+```++Repo rule: presentational widget components belong in Storybook (see `.cursor/rules/react-typescript.mdc`).++## 6. Edit modal + add-widget preview++- [ ] `EditModal` + `edit*WidgetModalLogic.ts` — Zod validate → `LemonField` errors; disable save while `saving` / invalid+- [ ] Compose `EditWidgetModalTileDetailsSection`, `EditWidgetModalFiltersSection`, and a type-specific `<section>` titled with `getDashboardWidgetGroupLabel(groupId)` — separate with `LemonDivider`; see [composition.md](composition.md)+- [ ] Spread shared kea **actions** from `editWidgetModalBuilders.ts`; **inline reducers** (typegen breaks on spread); inline typed `fieldErrors` / `activeFieldErrors` / `saveDisabledReason`+- [ ] Date-filtered widgets: date range select from `WIDGET_DATE_RANGE_SELECT_OPTIONS` in `configSchemas.ts`+- [ ] Wire per-type API error parsing: export `parse*WidgetConfigApiError` from `*WidgetConfigValidation.ts` and set **`parseConfigApiError`** on the `DASHBOARD_WIDGET_REGISTRY` entry (`parseDashboardWidgetConfigApiError` in `registry.tsx` → `updateDashboardWidgetTile`)+- [ ] Preview: component in `widgets/previews/`; register in `DASHBOARD_WIDGET_PREVIEWS` in `widget_types/catalog.ts` (reuse sample data from `widgetOverviewStoryFixtures.ts` when possible)++## 7. Frontend registry++File: `products/dashboards/frontend/widgets/registry.tsx` — entry shape in [architecture.md § Frontend registry entry shape](architecture.md#frontend-registry-entry-shape).++- [ ] Import `Component`, `EditModal`, and `parse*WidgetConfigApiError`; one keyed entry per `widget_type`+- [ ] When RBAC-gated: set `productAccess` on catalog + registry entry (must match backend `required_product_access`), extend `DashboardWidgetProductAccess` in `types.ts`, and add a matching entry in `WIDGET_PRODUCT_ACCESS_CHECKS` (`widgetProductAccess.ts`)+- [ ] Set **`sharedPlaceholder`** on the catalog entry when public/shared copy should differ from `DEFAULT_SHARED_DASHBOARD_WIDGET_PLACEHOLDER`++## 8. Tests++Run [SKILL.md § Verify](../SKILL.md#verify). Minimum for a new type:++- [ ] Assert `EXPECTED_WIDGET_TYPES == WIDGET_REGISTRY.keys()`+- [ ] `registry.test.tsx`: every catalog key registered; each entry has **`parseConfigApiError`**+- [ ] Test create/update config validation, activity logging, permission denial in `run_widgets`+- [ ] MCP: `services/mcp/tests/tools/dashboards.integration.test.ts` when catalog/OpenAPI surfaces change+- [ ] Analytics: first insert fires `dashboard tile added` and `dashboard widget added` with `widget_type` on PATCH and POST add paths (`test_dashboard_widgets.py`)+- [ ] No empty test scaffolds — every `.test.tsx` must assert real behavior++## 9. OpenAPI / generated types++Runtime validation stays in `validate_*_config`. OpenAPI/MCP schemas are separate.++### 9a. Dashboard serializers (`dashboard.py`)++After tile/widget serializer field changes:++```sh+hogli build:openapi+```++### 9b. Polymorphic widget config (`widget_openapi_serializers.py`)++When adding or changing config fields agents should see:++- [ ] Add or extend `*WidgetConfigSerializer` in `products/dashboards/backend/api/widget_openapi_serializers.py`+- [ ] Register it on `_DashboardWidgetConfigOpenApi` (`PolymorphicProxySerializer`)+- [ ] Run `hogli build:openapi` — regenerates `products/dashboards/frontend/generated/api.ts`, `api.schemas.ts` and MCP tool schemas. Do not edit generated files.++Invoke `improving-drf-endpoints` before editing serializers. Invoke `adopting-generated-api-types` when migrating manual API calls. Invoke `implementing-mcp-tools` when MCP snapshots or `tools.yaml` help text must list the new type.++## 10. Agent skill docs++Follow [skill-maintenance.md](skill-maintenance.md) when agent-facing behavior or contributor workflow changes — same PR as code.++- [ ] Update mapped reference docs from the change → doc table in `skill-maintenance.md`+- [ ] Run registry sync tests belowdiff --git a/.agents/skills/dashboard-widgets/references/composition.md b/.agents/skills/dashboard-widgets/references/composition.mdnew file mode 100644index 000000000000..fb25c0caff7d--- /dev/null+++ b/.agents/skills/dashboard-widgets/references/composition.md@@ -0,0 +1,192 @@+# WidgetCard composition++Follow the Quill `Card` pattern: **thin shell + compound subcomponents composed at the callsite**. `WidgetCard` is chrome only — no header/body props.++| File / export | Role |+| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `WidgetCard` | Thin tile shell: decorative resize handles, edit-mode edge overlay, RGL slot. **No product/header/body props** |+| `WidgetCardHeader` (+ internal title/actions helpers) | Layout router: `simple` vs `dashboard_tile`; exports `widgetCardShouldHideMoreButton` |+| `WidgetCardBody.tsx` | Body slot; locked/error shell states. Also exports `WidgetCardContent`, `WidgetCardBodyMessage`, `WidgetLoadingState`, `WidgetCardBodySkeleton`, **`WidgetCardSharedPlaceholderBody`** (public/shared placeholder) |+| `WidgetCardContent` | Scrollable column + optional footer (list/table widgets) — from `WidgetCardBody.tsx` |+| `WidgetCardBodyMessage` | Empty / inline status text — from `WidgetCardBody.tsx` |+| `WidgetLoadingState` / `WidgetCardBodySkeleton` | Widget-owned loading UI — from `WidgetCardBody.tsx` |+| `DashboardWidgetItem` | Production callsite — composes header + body, wires ⋯ menu, edit modal portal, product RBAC lock; **public** placement uses `WidgetCardSharedPlaceholderBody` instead of live widget body |++`WidgetCardHeaderDescription` is exported from `WidgetCardHeader.tsx` for tests only. Widget `Component`s never render card chrome — only body content primitives (`WidgetCardContent`, `WidgetCardBodyMessage`, …).++## Compound pattern++```tsx+<WidgetCard+ ref={ref}+ className={className}+ style={style}+ showResizeHandles={showResizeHandles}+ canEnterEditModeFromEdge={canEnterEditModeFromEdge}+ onEnterEditModeFromEdge={onEnterEditModeFromEdge}+ gridChildren={rglHandles} // react-grid-layout injects these+>+ <WidgetCardHeader+ layout={headerLayout}+ title={title}+ defaultTitle={defaultTitle}+ // …catalog-driven header fields+ shouldHideMoreButton={widgetCardShouldHideMoreButton(placement, showEditingControls)}+ moreButtonOverlay={…}+ />+ <WidgetCardBody locked={locked} error={error}>+ <WidgetComponent … />+ </WidgetCardBody>+</WidgetCard>+```++**Public / shared dashboard** — same header, but body is placeholder-only (no `run_widgets` data):++```tsx+{showSharedPlaceholder ? (+ <WidgetCardSharedPlaceholderBody+ copy={headerCatalogEntry.sharedPlaceholder ?? DEFAULT_SHARED_DASHBOARD_WIDGET_PLACEHOLDER}+ />+) : (+ <WidgetCardBody locked={locked} error={error} …>+ <WidgetComponent … />+ </WidgetCardBody>+)}+```++Render order inside `WidgetCard` (matches `InsightCard`):++1. `children` — composed header + body+2. `DashboardResizeHandles` when `showResizeHandles`+3. `EditModeEdgeOverlay` when edge-enter-edit is enabled+4. `gridChildren` — RGL `.react-resizable-handle` nodes++## Do++- Keep `WidgetCard` as the outermost node in `DashboardWidgetItem` — RGL injects `className`/`style` via `ref` on the card root+- Compose `WidgetCardHeader` + `WidgetCardBody` in `DashboardWidgetItem` (or story wrappers) — not inside `WidgetCard`+- Pass RGL handles via `gridChildren`, not `children`+- Let the widget `Component` decide skeleton vs content from `loading` prop+- Use `min-w-0` + `overflow-auto` chain (`WidgetCardContent` already scrolls vertically)+- Store time period in `config.dateRange` — options, edit modal, and header display: [layout-and-ux.md](layout-and-ux.md)+- Default header layout is `dashboard_tile` via `getDashboardWidgetCatalogEntry()` — only set `headerLayout` / `headerMeta` on a catalog entry when overriding defaults+- Edit title/description in the widget settings modal only (`EditWidgetModalTileDetailsSection`) — card header is read-only display++## Don't++- Add header/body props back to `WidgetCard` — that defeats the compound pattern+- Put loading placeholders in `WidgetCard` shell — breaks resize/empty-state behavior+- Put widget body content in `gridChildren` — RGL owns that slot for resize handles only+- Duplicate headers, menus, card chrome, or filter toggles inside the widget component — filters belong in the settings modal, not the ⋯ menu+- Register in `registry.tsx` without a matching `DASHBOARD_WIDGET_CATALOG` entry++## Header layouts (`catalog.ts`)++| Layout | Behavior |+| ---------------- | -------------------------------------------------------------------------------------- |+| `simple` | Single title row — prefer `dashboard_tile` for new types. Refresh via tile ⋯ menu only |+| `dashboard_tile` | Compact `CardMeta` style: type • date range + title + divider; Refresh in ⋯ menu |++Date range display is derived in `WidgetCardHeader` from `config.dateRange` + resolved catalog `headerMeta` (via `dateFilterToText`). Product type chip text comes from `getDashboardWidgetGroupLabel(groupId)`.++## Loading ownership++The widget `Component` receives `loading` from scene logic and must early-return with `WidgetLoadingState`. The shell (`DashboardWidgetItem` → composed `WidgetCardBody`) does not show skeletons for widget body content.++## RGL and overflow++- Widget content lives inside composed `WidgetCardBody`+- `gridChildren` is reserved for react-grid-layout resize handles only+- Wide tables: horizontal scroll **inside** `WidgetCardContent`, not the dashboard grid++## Storybook++Platform primitives under **Dashboards/Dashboard Widgets/**:++- `WidgetCard/` — `WidgetCard.stories.tsx` (header + body composition patterns)+- `Overview/` — `DashboardWidgetsOverview.stories.tsx` (all catalog types)++Shared frame/mocks: `widgetCardStoryFixtures.tsx`.++Per-type stories: `widgets/<product>/<Component>.stories.tsx` under **Widget types/<Group label>/<label>/** (e.g. `Error tracking/Top issues`).++- Meta `title` must be a **string literal** matching `DASHBOARD_WIDGET_GROUP_LABELS[groupId]` / `label` (CSF rejects dynamic titles)+- Compose with `WidgetCard` + `WidgetCardHeader` + `WidgetCardBody` + catalog header metadata — see `ErrorTrackingWidget.stories.tsx`+- Product setup state: Kea seed helpers live in `widgetCardStoryFixtures.tsx` (`withErrorTrackingProjectState`, etc.) — do not export decorators from `*.stories.tsx` (Storybook treats exports as stories)+- Stack decorators carefully: story-level `withErrorTrackingProjectState(false)` must not be overridden by a meta decorator that seeds `true`++## Unknown / deploy-skew widget types++When the FE catalog lacks a `widget_type` (partial deploy, unrebased stack):++- **Header** — `tryGetDashboardWidgetCatalogEntry` + `getUnknownDashboardWidgetCatalogFallback` so title and ⋯ menu (remove, duplicate, copy/move) still work+- **Body** — `ErrorBoundary` wraps `DashboardWidgetItemBody`, which calls `getDashboardWidgetCatalogEntry` (throws → full error UI)+- **Fetch errors** — do not pass `run_widgets` fetch `error` into `WidgetCardBody` for unknown types; no Refresh data action in ⋯ menu+- **Analytics** — `getDashboardWidgetDefinition` still dedupes a PostHog `captureException` per canonical type — add the registry entry++## Widget settings modal++Same compound pattern as `WidgetCard` — `LemonModal` shell with sections composed in each `Edit*WidgetModal` (no shared modal wrapper component).++| File / export | Role |+| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |+| `EditWidgetModalTileDetailsSection` | Tile name + description fields (saved with config in one PATCH via `buildWidgetTileMetadataPatch`) |+| `EditWidgetModalFiltersSection` | Shared `TestAccountFilter` section |+| `editWidgetModalBuilders.ts` | Shared kea **actions** and reducer templates; spread actions only — inline reducers per logic file |+| `editWidgetModalTileUtils.ts` | Tile name/description defaults + `buildWidgetTileMetadataPatch` |+| `edit*WidgetModalLogic.ts` | Per-type kea logic wired to validation + save listeners |+| `widgets/widgetConfigValidation.ts` | Shared Zod form/config helpers (`parseWidgetConfig`, `validateWidgetConfigInput`, `parseWidgetConfigApiError`) — per-type wrappers call this |+| `*WidgetConfigValidation.ts` | Per-type thin wrapper; export `parse*WidgetConfigApiError` wired as **`parseConfigApiError`** on the registry entry |++```tsx+<LemonModal … footer={/* Cancel + Save with saveDisabledReason / saving */}>+ <div className="flex flex-col gap-4">+ {showTileDetails ? (+ <EditWidgetModalTileDetailsSection+ tileName={tileName}+ tileDescription={tileDescription}+ defaultTitle={defaultTitle}+ saving={saving}+ setTileName={setTileName}+ setTileDescription={setTileDescription}+ />+ ) : null}+ {showTypeSettings ? (+ <>+ {showTileDetails ? <LemonDivider className="my-0" /> : null}+ <EditWidgetModalFiltersSection+ filterTestAccounts={filterTestAccounts}+ saving={saving}+ setFilterTestAccounts={setFilterTestAccounts}+ />+ <LemonDivider className="my-0" />+ <section className="flex flex-col gap-3">+ <h5 className="text-sm font-semibold m-0">+ {getDashboardWidgetGroupLabel('error_tracking')}+ </h5>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">+ {/* type-specific LemonField rows — date range, limit, orderBy, … */}+ </div>+ </section>+ </>+ ) : null}+ </div>+</LemonModal>+```++References: `EditErrorTrackingWidgetModal.tsx`, `EditSessionReplayWidgetModal.tsx`. Omit sections you do not need — gate with booleans like `showTileDetails` / product-specific setup flags.++### Kea edit-modal logic++- Spread **actions** from `editWidgetModalBuilders.ts` (`widgetEditModalListFieldActions`, `widgetEditModalTileActions`, `widgetEditModalFilterTestAccountsActions`)+- **Inline reducers** in each logic file — do not spread `widgetEditModal*Reducers` (kea typegen loses reducer types)+- Inline `setFieldErrors`, `clearFieldError`, `activeFieldErrors`, and `saveDisabledReason` with the per-type `*FieldErrors` type+- `setOrderBy` action accepts `string`; reducer casts to the config enum type+- `submit` listener: `validate*WidgetConfigInput` → `onSave(config, buildWidgetTileMetadataPatch(...))` — one PATCH for config + name + description+- Connect `filterTestAccountsDefaultsLogic` and initialize `filterTestAccounts` via `resolveWidgetFilterTestAccounts`++### Config validation++- Per-type config schema in `configSchemas.ts`; list widgets export a form schema via `widgetListFormSchema(orderBySchema)` (or a type-specific form schema extending the shared list fields)+- Per-type `*WidgetConfigValidation.ts` wraps shared helpers from `widgets/widgetConfigValidation.ts`+- Register **`parseConfigApiError`** on the `DASHBOARD_WIDGET_REGISTRY` entry (dispatched via `parseDashboardWidgetConfigApiError` in `registry.tsx` → `updateDashboardWidgetTile` in `utils.ts`)diff --git a/.agents/skills/dashboard-widgets/references/layout-and-ux.md b/.agents/skills/dashboard-widgets/references/layout-and-ux.mdnew file mode 100644index 000000000000..614cb9d5b390--- /dev/null+++ b/.agents/skills/dashboard-widgets/references/layout-and-ux.md@@ -0,0 +1,136 @@+# Layout and UX++## Grid sizing (overview)++Catalog `defaultLayout` drives default size and resize floors via `tileLayouts.ts`. Wide tables scroll inside `WidgetCardContent`, not the dashboard grid.++**Tile min/max size (the full guide):** [§ Tile min/max size](#tile-minmax-size-grid-rows--columns) below — only authoritative section for mins; other docs should link here.++## Tile min/max size (grid rows & columns)++Changing minimum tile size is **catalog + `tileLayouts.ts`**, not the widget `Component`. Agents often look in the wrong layer first — use this section.++### Mental model++```text+DASHBOARD_WIDGET_CATALOG[].defaultLayout ← you edit this+ ↓+tileLayouts.ts :: calculateLayouts() ← reads catalog per tile.widget.widget_type+ ↓+react-grid-layout minW / minH on each item ← enforced while resizing in edit mode+```++- Grid is **12 columns** wide (`w` / `minW` are column counts).+- Height is in **row units** (`h` / `minH`), not columns — users may say “3 rows tall” or “3 grid rows”.+- **Row height:** `BASE_ROW_HEIGHT = 80` px in `frontend/src/scenes/dashboard/DashboardItems.tsx`. Example: `minH: 3` → 240 px minimum tile height (plus margins).++### Single source of truth++Set mins on the catalog entry only:++```typescript+// products/dashboards/frontend/widget_types/catalog.ts+defaultLayout: { w: 6, h: 5, minW: 6, minH: 3 },+```++| Field | Meaning |+| -------------- | ----------------------------------------------------------------------------------- |+| `w`, `h` | Default size when **adding** a widget (`dashboardLogic.addWidgetTiles` reads these) |+| `minW`, `minH` | Smallest size allowed when **resizing** on the dashboard |++### How mins reach the grid++1. `calculateLayouts(tiles)` in `frontend/src/scenes/dashboard/tileLayouts.ts` runs on every dashboard load / tile change.+2. For widget tiles it calls `getWidgetCatalogLayout(widget_type)` → `DASHBOARD_WIDGET_CATALOG[key].defaultLayout`.+3. `getTileMinDimensions()` sets RGL `minW` / `minH` on each layout item.++**Persisted tile JSON** (`tile.layouts.sm`) stores `x`, `y`, `w`, `h` — not mins. Mins are **recomputed** from catalog each time, so a catalog `minH` change applies to existing dashboards without a migration.++### Fallbacks (when catalog omits mins)++| Constant | Value | Used when |+| ----------------------------- | ----- | ---------------------------------- |+| `MIN_WIDGET_TILE_WIDTH_COLS` | 6 | Widget tile, catalog has no `minW` |+| `MIN_WIDGET_TILE_HEIGHT_ROWS` | 4 | Widget tile, catalog has no `minH` |+| `MIN_TILE_HEIGHT_ROWS` | 2 | Insight tiles |+| `MIN_TEXT_TILE_HEIGHT_ROWS` | 1 | Text tiles |++If a new widget type omits `minH`, users can only shrink to **4 rows**, not 3. Always set explicit `minH` / `minW` on the catalog entry.++### What does **not** control dashboard min size++| Location | Why it’s unrelated |+| -------------------------------------------------- | --------------------------------------------------------------------- |+| Widget `Component` / SCSS | Body layout only; RGL sizes the outer tile |+| `widget_catalog.py` `get_default_widget_layouts()` | Backend add helper — returns `w`/`h` only, no mins |+| Storybook `widgetCardStoryFixtures` `TILE_HEIGHT` | Fixed frame for stories, not RGL |+| `DashboardWidgetsOverview.stories.tsx` heights | Overview showcase scale, separate from live mins |+| Changing `MIN_WIDGET_TILE_HEIGHT_ROWS` globally | Affects **unknown** widget types only; prefer per-type catalog `minH` |++### Change checklist++1. Edit `defaultLayout.minH` / `minW` in `widget_types/catalog.ts` for the `widget_type`.+2. Extend `frontend/src/scenes/dashboard/tileLayouts.test.ts` — parameterized case with `expectedMinH` / `expectedMinW` for that `widget_type` (see `error_tracking_list` / `session_replay_list` examples).+3. Run `hogli test frontend/src/scenes/dashboard/tileLayouts.test.ts`.+4. Manually resize the tile in dashboard **edit mode** to confirm the floor.+5. Optional: add a `MinimumSize` story — frame height `minH * 80` px, limit demo data so content fits.++### Storybook vs dashboard++- **Dashboard:** mins from catalog → `tileLayouts.ts` → RGL.+- **Storybook tile stories:** optional fixed frame (`widgetCardStoryFixtures` or per-story wrapper). A `MinimumSize` story documents the floor; it does not change production behavior.++## Add widget modal++- 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)+- REST/MCP add: `dashboard-widgets-batch-add` — same batch endpoint; one tile = single-element `widgets`. See [mcp.md](mcp.md)++## NEW badge (Add menu)++Surface the Widget entry as new in the Add menu:++- Populated dashboard: `DashboardHeaderActions` — `LemonMenu` item `tag: 'new'`+- Empty dashboard: `EmptyDashboardComponent` — inline `<LemonTag type="success" size="small">NEW</LemonTag>` on the Widget menu item++Do not add NEW badges on individual catalog variants inside `AddWidgetModal`.++## Config updates++- `updateWidgetTile` in `dashboardLogic` → `updateDashboardWidgetTile` (one PATCH) → `refreshDashboardWidgets` when config changed+- Widget settings modal: Zod validate → `LemonField` errors; disable save while `saving` / invalid+- Title, description, `filterTestAccounts`, and type-specific fields all live in the settings modal (`EditWidgetModal*` sections) — not inline on the card++## Remove and undo++- Remove: no confirm dialog — undo toast (`removeTileSuccess` in `dashboardLogic.tsx`)+- Copy: "widget removed" + Undo++## ⋯ menu parity (`DashboardWidgetItem`)++- View (if `titleHref`)+- Edit (opens widget settings modal)+- Duplicate+- Show/hide description (toggle visibility; edit text in settings modal)+- Dashboard section: copy/move to another dashboard, remove+- Refresh data — direct click with optional "Last computed" subtitle (`dashboard_tile` header layout; omitted for unknown widget types)++## Header layout choice++Prefer `headerLayout: 'dashboard_tile'` for new widgets — matches insight tile chrome; Refresh data is a direct ⋯ menu item (optional "Last computed" subtitle), same as insight tiles.++See [composition.md](composition.md) for header layout details.++## Date range in config++Store time period in `config.dateRange` (insight-shaped `{ date_from, date_to?, explicitDate? }`).++Supported relative `date_from` values (shortest first): `-1h`, `-3h`, `-24h`, `-7d`, `-14d`, `-30d`, `-90d` — defined in FE `configSchemas.ts` (`WIDGET_DATE_FROM_VALUES` / `WIDGET_DATE_RANGE_SELECT_OPTIONS`) and BE `backend/constants.py` (`WIDGET_DATE_FROM_VALUES`). Keep both in sync when adding or removing values; update BE `config_schema_hints` and `widget_openapi_serializers.py` too.++Format for display via `WidgetCardHeader` — reads `config.dateRange` + catalog `headerMeta` and formats with `dateFilterToText`.++## Description display++When `show_description` is enabled, the card header renders markdown under the title (`WidgetCardHeader` / `CardMeta`) with `max-h-24 overflow-y-auto`.diff --git a/.agents/skills/dashboard-widgets/references/managing-existing-widgets.md b/.agents/skills/dashboard-widgets/references/managing-existing-widgets.mdnew file mode 100644index 000000000000..595333d6132d--- /dev/null+++ b/.agents/skills/dashboard-widgets/references/managing-existing-widgets.md@@ -0,0 +1,85 @@+# Managing existing dashboard widgets++**SKILL route:** [SKILL.md §3 Update a shipped type](../SKILL.md#3-update-a-shipped-type) — skip [widget-intake.md](widget-intake.md).++Use when **changing** a shipped widget type — not when adding a new `widget_type` ([checklist-new-widget-type.md](checklist-new-widget-type.md)).++Reference implementation for patterns: `products/dashboards/frontend/widgets/error_tracking/` (`error_tracking_list`).++Before finishing, apply [skill-maintenance.md](skill-maintenance.md) for any doc updates required by your change.++## What you cannot change in place++- **`widget_type` is immutable** on an existing `DashboardWidget` row. To switch visualization kind, add a new tile (new type) and remove the old one.+- **Stored tile `w` / `h`** are not rewritten when catalog `defaultLayout` changes — only new adds and min/max enforcement on the next layout pass. See [layout-and-ux.md](layout-and-ux.md).++## What kind of change?++| Goal | Primary files | Also check |+| ------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |+| Widget query / `run_widgets` payload | `backend/widgets/<widget_type>.py`, `widget_registry.py` | `test_run_widgets.py`, frontend `Component` types, preview/overview fixtures, **`dashboard_widget_delivery`** SLO (automatic — no wiring) |+| Config fields (filters, limits, sort) | `configSchemas.ts`, `<type>WidgetConfigValidation.ts`, `Edit*WidgetModal.tsx`, backend `validate_*_config` | Registry **`parseConfigApiError`**, `widget_openapi_serializers.py`, BE `config_schema_hints`, `hogli build:openapi`, MCP schema snapshots |+| **`run_*` result shape** | `backend/widgets/<widget_type>.py`, widget `Component` | Story `result` args, `widgets/previews/`, `widgetOverviewStoryFixtures.ts` |+| Tile name / description UX | `Edit*WidgetModal.tsx`, `EditWidgetModalTileDetailsSection.tsx` | Mirror `EditErrorTrackingWidgetModal.tsx` field layout; activity log tests if serializer fields change |+| Default size when **adding** a tile | `catalog.ts` `defaultLayout.w` / `.h` | `dashboardLogic.addWidgetTiles` (reads catalog defaults) |+| **Min/max resize** on dashboard grid | `catalog.ts` `defaultLayout.minW` / `.minH` | [layout-and-ux.md](layout-and-ux.md) § Tile min/max size — **`tileLayouts.ts`**, `tileLayouts.test.ts` |+| Card header / date range display | `catalog.ts` (`headerLayout`, `headerMeta`, `headerTitle`, `titleHref`) | `WidgetCardHeader`, stories |+| Setup / availability gate | `catalog.ts` `availability`, `widgetAvailability.ts` | `WidgetRuntimeAvailabilityGuard`; BE `availability_requirements` for MCP catalog |+| RBAC lock on tile | `widget_registry.py` `required_product_access`, FE `catalog.ts` `productAccess` | `types.ts`, `widgetProductAccess.ts` (`WIDGET_PRODUCT_ACCESS_CHECKS`) |+| Add-modal preview | `widgets/previews/` + `DASHBOARD_WIDGET_PREVIEWS` in `widget_types/catalog.ts` | Reuse demo data from `widgetOverviewStoryFixtures.ts` when possible |+| Public/shared placeholder copy | `catalog.ts` **`sharedPlaceholder`** | `DashboardWidgetItem.test.tsx` public placement; `test_sharing.py` |+| Agent-facing catalog copy | `backend/widget_catalog.py` (`description`, `config_schema_hints`, `product_access_denied_message`) | `dashboard-widget-catalog-list` / `test_dashboard_widgets.py` catalog assertions |+| Storybook / overview fixtures | `WidgetCard/*.stories.tsx`, `widgetOverviewStoryFixtures.ts`, `Edit*WidgetModal.stories.tsx` | `getWidgetOverviewDemoState` exhaustive switch per catalog key |+| Deprecating / removing a type | See § Deprecating a widget type below | Orphan tiles fall back to unknown-type UI; keep BE runner until tiles are gone |++Registry parity table (all layers that must stay aligned): [CONTRIBUTING.md § Frontend / backend parity](../../../products/dashboards/CONTRIBUTING.md#frontend--backend-parity).++## Config schema migration (existing tiles)++When changing config shape on tiles already stored in Postgres:++1. **Backward-compatible (preferred)** — in `validate_*_config`, merge defaults, accept legacy keys, rename in-place, strip unknown keys. Existing tiles keep working without a data migration.+2. **Breaking** — treat as a new `widget_type` (or accept that old tiles may fail validation until users re-save from the edit modal).+3. **Touch every layer** for non-breaking adds/removals:+ - BE: `validate_*_config`, `config_schema_hints` in `widget_catalog.py`+ - FE: Zod in `configSchemas.ts`, edit modal fields, `*WidgetConfigValidation.ts`, registry **`parseConfigApiError`**+ - OpenAPI: `*WidgetConfigSerializer` in `widget_openapi_serializers.py` → `hogli build:openapi`+ - Stories/fixtures: component stories, edit modal stories, preview, `widgetOverviewStoryFixtures.ts`+4. **Relative date ranges** — if adding/removing `date_from` values, update both `backend/constants.py` (`WIDGET_DATE_FROM_VALUES`) and FE `configSchemas.ts` (`WIDGET_DATE_FROM_VALUES` / `WIDGET_DATE_RANGE_SELECT_OPTIONS`).++## Config update flow (runtime)++1. User opens ⋯ → **Edit** → `Edit*WidgetModal` validates with Zod → `onSave(config, metadataPatch?)` (metadata from `buildWidgetTileMetadataPatch`)+2. `DashboardItems` calls `useAsyncActions(dashboardLogic).updateWidgetTile` so the modal `await onSave(...)` waits for the PATCH+3. `dashboardLogic.updateWidgetTile` → `updateDashboardWidgetTile` → one `dashboardsPartialUpdate` with nested `widget` `{ config, name, description }` and optional `show_description`+4. When `config` changed, `refreshDashboardWidgets` re-runs `run_widgets` for that tile++Guard saves with `loading` / `disabledReason` on Save — never leave the button clickable mid-mutation.++## Edit modal layout++Type-specific edit-modal sections use a 2-column CSS grid (`grid grid-cols-1 sm:grid-cols-2 gap-4`) — copy `EditErrorTrackingWidgetModal.tsx` or `EditWidgetModalTileDetailsSection.tsx`.++- Full-width fields (name, description, test-account filter): put `WIDGET_SETTINGS_FIELD_FULL_WIDTH_CLASS` (`sm:col-span-2`) on the **grid child** — `LemonField.Pure` or a wrapper `<div>` — **not** on the inner `LemonInput` / `LemonTextArea`.+- Half-width fields (date range, sort, limit): omit `col-span-2`; use `fullWidth` on `LemonSelect` where needed.++Copy `EditErrorTrackingWidgetModal.tsx` Tile details + Filters sections when wiring a new edit modal.++## Changing min/max tile size++Follow [layout-and-ux.md § Tile min/max size](layout-and-ux.md#tile-minmax-size-grid-rows--columns) — catalog `defaultLayout.minW` / `minH` only; changing mins affects all tiles of that type on the next layout pass without rewriting Postgres `h`/`w`.++## Deprecating a widget type++There is no soft-delete for `widget_type` strings. Typical approach:++1. Stop listing the type in FE/BE catalogs and registries (or never ship removal until tiles are migrated).+2. **Keep** `run_*` + registry entry until no production tiles reference the type, **or** accept unknown-type fallback (header + body `ErrorBoundary`, no live data).+3. Update MCP tool schema snapshots and `services/mcp/tests/tools/dashboards.integration.test.ts` when removing from catalog.+4. Document removal in skill **Shipped types** table (checklist step 10).++Do not remove backend validation for a type that still has rows in `posthog_dashboardwidget`.++## Verify (updates)++Run [SKILL.md § Verify](../SKILL.md#verify) for every layer you touched. Prefer targeted paths under `products/dashboards/frontend/widgets/<product>/` and `test_run_widgets.py` when the change is narrow.diff --git a/.agents/skills/dashboard-widgets/references/mcp.md b/.agents/skills/dashboard-widgets/references/mcp.mdnew file mode 100644index 000000000000..685444aa357d--- /dev/null+++ b/.agents/skills/dashboard-widgets/references/mcp.md@@ -0,0 +1,55 @@+# Dashboard widgets MCP tools++Agents manage dashboard widget tiles through atomic MCP tools.++Tool config: `products/dashboards/mcp/tools.yaml` — regenerate MCP handlers after endpoint changes (`implementing-mcp-tools` skill).++## Tool map++| Goal | MCP tool | Notes |+| ------------------------------------- | ------------------------------------- | -------------------------------------------------------------------------------------------- |+| Discover widget types + config hints | `dashboard-widget-catalog-list` | Read-only catalog |+| Read dashboard tiles + widget config | `dashboard-get` | Widget tiles have `widget.widget_type` and `widget.config`; no live data |+| Add widget tile(s) | `dashboard-widgets-batch-add` | Atomic batch via `POST .../widgets/batch/` (1–10 tiles; one tile = single-element `widgets`) |+| Update widget tile(s) | `dashboard-update` | PATCH dashboard with `tiles[]`: each tile `id` + `widget.id` + fields to change |+| Run widget queries | `dashboard-widgets-run` | Query: `tile_ids` comma-separated from dashboard-get |+| Copy widget tile to another dashboard | `dashboard-tile-copy` | Deep-clones widget; destination is path dashboard ID |+| Move widget tile between dashboards | `dashboards-move-tile-partial-update` | Source dashboard is path `id`; pass `to_dashboard` and `tile.id` from dashboard-get |++There is no dedicated single-tile create or per-tile `PATCH .../widgets/:tile_id/` REST endpoint — the UI and MCP use batch add and dashboard PATCH respectively.++## Typical agent flow++1. `dashboard-widget-catalog-list` — pick `widget_type`, build `config` from `config_schema_hints`+2. `dashboard-widgets-batch-add` — add one or more tiles (up to 10 per request)+3. `dashboard-get` — confirm tile ID(s), widget row `id`, and layout+4. `dashboard-widgets-run` — fetch live widget data for `tile_ids` (private dashboards only — public/shared views do not call `run_widgets`)++For updates: `dashboard-update` with `tiles` containing `{ id, widget: { id, config?, name?, description? } }`, then `dashboard-widgets-run` when live data should refresh.++Multi-tile add from the UI uses `POST .../widgets/batch/` (`addWidgetTiles`), same as MCP batch add.++## REST equivalents++| MCP tool | Endpoint |+| ------------------------------------- | ------------------------------------------------------------- |+| `dashboard-widget-catalog-list` | `GET .../dashboards/widget_catalog/` |+| `dashboard-widgets-batch-add` | `POST .../dashboards/:id/widgets/batch/` (1–10 tiles, atomic) |+| `dashboard-update` (widget tiles) | `PATCH .../dashboards/:id` with `tiles[]` and nested `widget` |+| `dashboard-widgets-run` | `GET .../dashboards/:id/run_widgets/?tile_ids=` |+| `dashboard-tile-copy` | `POST .../dashboards/:id/copy_tile/` |+| `dashboards-move-tile-partial-update` | `PATCH .../dashboards/:id/move_tile/` |++UI multi-select add uses `POST .../widgets/batch/` (not PATCH dashboard `tiles[]` for create).++## Permissions++- Dashboard edit scope for add/update/copy/move+- Dashboard read scope for get, catalog, run+- Each widget type may require additional product access — check `required_product_access` on `dashboard-widget-catalog-list`; denied tiles return per-tile errors from run/add paths++## After shipping a new `widget_type`++1. Regenerate OpenAPI (`hogli build:openapi`) — updates MCP tool schemas that embed supported type lists+2. Run `hogli test services/mcp/tests/tools/dashboards.integration.test.ts`+3. Update unit schema snapshots if batch-add help text lists types: `hogli test services/mcp/tests/unit/tool-schema-snapshots.test.ts`diff --git a/.agents/skills/dashboard-widgets/references/permissions-and-sharing.md b/.agents/skills/dashboard-widgets/references/permissions-and-sharing.mdnew file mode 100644index 000000000000..be376a874d77--- /dev/null+++ b/.agents/skills/dashboard-widgets/references/permissions-and-sharing.md@@ -0,0 +1,66 @@+# Permissions and sharing++## Team scoping++- `DashboardWidget.team` required — all reads/writes filter by `team_id`+- Tile upsert validates existing widget IDs belong to the dashboard's team++## Two access layers (both must pass)++| Layer | Check |+| -------------- | ------------------------------------------------------------------------------------------ |+| Dashboard RBAC | `dashboard:read` / `dashboard:write`; access level on dashboard object |+| Product RBAC | See [Product RBAC](#product-rbac) below — frontend lock + backend `run_widgets` must agree |++## Product RBAC++Canonical rule (also SKILL.md rule 1):++- Backend: `required_product_access` on each `WIDGET_REGISTRY` entry → `get_widget_product_access_error` in `widget_access.py` for `run_widgets` and tile mutations+- Frontend: matching `productAccess` on catalog + registry; `userHasDashboardWidgetProductAccess` in `DashboardWidgetItem.tsx`; extend `DashboardWidgetProductAccess` and `WIDGET_PRODUCT_ACCESS_CHECKS` when adding a gated product+- **`required_scopes` on registry entries is documentation only** — never use it for enforcement+- **Never** add per-type `if widget_type == …` in `dashboard.py`++**Frontend `locked` alone is insufficient** — backend must enforce the same gate.++## Copy / move / duplicate++| Action | Widget support |+| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |+| Duplicate within same dashboard | Deep-clones widget row; `duplicateTileSuccess` triggers `refreshDashboardWidgets` for the new tile so data loads without a full page refresh |+| Copy to another dashboard | Deep-clones widget row + tile on destination (name gets `(Copy)` when set) |+| Move to another dashboard | Moves tile row; same `DashboardWidget` FK (widgets are not shared across dashboards) |+| Duplicate entire dashboard | Always deep-clones widget rows (even when `duplicate_tiles: false` for insights) |++Button tiles still cannot be copied or moved between dashboards.++## Cross-project copy++Transferring a dashboard between projects deep-clones widget rows. `DashboardWidgetVisitor` (`posthog/models/resource_transfer/visitors/dashboard_widget.py`) is `user_facing=True` (default) so widgets appear in transfer preview dependencies with `display_name` from widget `name` when set. `DashboardTile` visitor stays `user_facing=False`. Tests: `posthog/api/test/test_resource_transfer.py` (`test_preview_returns_dashboard_with_widget_tiles`).++## Shared / public / subscriptions++| Placement | Widget tile behavior |+| ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |+| Private dashboard | Full tile: `run_widgets` fetch, live `Component`, edit chrome when allowed |+| **Public / shared link** (`DashboardPlacement.Public`) | Tile **renders** with header metadata; **no** `run_widgets` fetch; body shows catalog **`sharedPlaceholder`** via `WidgetCardSharedPlaceholderBody` |+| Export (`DashboardPlacement.Export`) | Widget tiles **hidden** (`isWidgetTileVisibleOnPlacement` — export only) |+| Subscriptions / snapshots | Read-only — no edit modal, no mutations from tile chrome |++### Public shared dashboards (implementation)++- **`isWidgetTileVisibleOnPlacement`** (`dashboardUtils.ts`) — hides widgets on **export** only; public/shared still render tiles+- **`dashboardLogic.dashboardWidgetsEnabled`** — `true` on public when the dashboard has widget tiles (enables tile chrome + layout; still skips `refreshDashboardWidgets` when `placement === Public`)+- **`SharedDashboardWidgetMetadataSerializer`** (`dashboard.py`) — when tile serializer context has `is_shared`, widget payload is metadata-only (no audit/user fields beyond what the shared view needs)+- **Sharing path** — `posthog/api/sharing.py` sets `is_shared: True` on dashboard tile serializer context+- **Frontend placeholder** — `DashboardWidgetItem` branches on `placement === Public` → `WidgetCardSharedPlaceholderBody` with `headerCatalogEntry.sharedPlaceholder ?? DEFAULT_SHARED_DASHBOARD_WIDGET_PLACEHOLDER` from `catalog.ts`+- **`titleHref`** suppressed on public; ⋯ menu / edit controls hidden via existing placement helpers+- **Tests** — `posthog/api/test/test_sharing.py` (widget tiles in shared payload); `DashboardWidgetItem.test.tsx` (public placeholder)++When adding a type, set **`sharedPlaceholder`** `{ title, message }` on the catalog entry (product-specific copy). Omit only if generic fallback copy is acceptable.++## Activity logging++- `DashboardWidget` uses `ModelActivityMixin`; scope `"DashboardWidget"`+- `handle_dashboard_widget_change` in `dashboard.py` logs create/update/delete+- Do not store secrets in `config` — changes are loggeddiff --git a/.agents/skills/dashboard-widgets/references/skill-maintenance.md b/.agents/skills/dashboard-widgets/references/skill-maintenance.mdnew file mode 100644index 000000000000..a614552b856e--- /dev/null+++ b/.agents/skills/dashboard-widgets/references/skill-maintenance.md@@ -0,0 +1,91 @@+# Skill maintenance (keep docs in sync)++**Same PR as the code change** when agent-facing behavior or contributor workflow changes. Registry parity is CI-enforced in code tests — do not hand-maintain type lists in markdown.++## Doc architecture (avoid duplication)++One canonical home per topic — link elsewhere; do not copy tables or long prose.++| Topic | Canonical doc |+| ---------------------------- | ----------------------------------------------------------------------------------------------------------------- |+| Intake / spec questions | [widget-intake.md](widget-intake.md) |+| Add flow (files + order) | [checklist-new-widget-type.md](checklist-new-widget-type.md) |+| Model, naming, scaling rules | [architecture.md](architecture.md) |+| Product RBAC | [permissions-and-sharing.md § Product RBAC](permissions-and-sharing.md#product-rbac) |+| Tile min/max size | [layout-and-ux.md § Tile min/max size](layout-and-ux.md#tile-minmax-size-grid-rows--columns) |+| Registry entry shapes (code) | [architecture.md](architecture.md) |+| Update flow | [managing-existing-widgets.md](managing-existing-widgets.md) — [SKILL.md §3](../SKILL.md#3-update-a-shipped-type) |+| Verify commands | [SKILL.md §6 Verify](../SKILL.md#6-verify) |+| Human entry / nav | [`products/dashboards/CONTRIBUTING.md`](../../../products/dashboards/CONTRIBUTING.md) |++## When this applies++Load `/dashboard-widgets` and complete the maintenance checklist below when **any** of these change:++| Trigger path (glob) | Examples |+| ---------------------------------------------------------------- | ------------------------------------------------------------ |+| `products/dashboards/backend/widgets/**` | New `run_*`, config validation, query wiring |+| `products/dashboards/backend/widget_registry.py` | New/removed `widget_type` |+| `products/dashboards/backend/widget_catalog.py` | Labels, hints, availability strings |+| `products/dashboards/backend/api/widget_openapi_serializers.py` | Config OpenAPI shapes |+| `products/dashboards/backend/api/dashboard.py` | `run_widgets`, batch add, sharing serializers (generic only) |+| `products/dashboards/backend/widget_access.py` | RBAC denial copy |+| `products/dashboards/frontend/widgets/**` | Component, edit modal, registry, previews |+| `products/dashboards/frontend/widget_types/**` | Catalog, Zod schemas, availability |+| `products/dashboards/frontend/components/WidgetCard/**` | Shared tile chrome, placeholders, overview fixtures |+| `products/dashboards/frontend/components/DashboardWidgetItem/**` | Tile glue, public placement |+| `products/dashboards/mcp/tools.yaml` | Widget MCP tools |+| `frontend/src/scenes/dashboard/tileLayouts.ts` | Layout algorithm (only if behavior/docs change) |+| `posthog/api/test/test_sharing.py` | Shared dashboard widget payload expectations |+| `tach.toml` (`products.dashboards` `depends_on`) | New product import boundary |++Platform-only refactors with **no** behavior or agent-facing surface change may skip narrative updates — still run Verify tests.++## Change → doc map++| You changed | Update in this skill |+| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |+| New or removed **`widget_type`** | [checklist-new-widget-type.md](checklist-new-widget-type.md) if add flow shifted; [architecture.md](architecture.md) footguns if new invariant |+| Config fields / validation | [managing-existing-widgets.md](managing-existing-widgets.md) § Config schema migration |+| Public/shared/export behavior | [permissions-and-sharing.md](permissions-and-sharing.md); SKILL.md §4 invariants |+| Setup / availability gating | [availability-and-gating.md](availability-and-gating.md); BE `availability_requirements` note |+| Tile layout / mins / add placement | [layout-and-ux.md](layout-and-ux.md); [architecture.md](architecture.md) if REST/MCP add path changed |+| WidgetCard / edit modal composition | [composition.md](composition.md) |+| MCP tools or agent flows | [mcp.md](mcp.md) |+| New product area / tach / UI reuse pattern | [checklist-new-widget-type.md](checklist-new-widget-type.md) §4c |+| Human contributor entry point | [`products/dashboards/CONTRIBUTING.md`](../../../products/dashboards/CONTRIBUTING.md) registry table / Verify block |++Prefer **editing an existing reference** over adding a new file. Keep `SKILL.md` as the index — move detail into `references/`.++## Add checklist (new `widget_type`)++Minimum doc updates — full code checklist in [checklist-new-widget-type.md](checklist-new-widget-type.md):++1. [ ] [checklist-new-widget-type.md](checklist-new-widget-type.md) — update if the add flow or easy-to-miss paths changed+2. [ ] [architecture.md](architecture.md) — footguns or platform invariants if you discovered a new one worth documenting+3. [ ] `CONTRIBUTING.md` — if Verify commands or registry parity table changed++## Update checklist (existing type)++1. [ ] [managing-existing-widgets.md](managing-existing-widgets.md) — extend routing table or migration notes if the change is reusable+2. [ ] `mcp.md` — if agent workflow or tool semantics changed++## Remove / deprecate a type++1. [ ] Remove from registries first only when no tiles remain (or document unknown-type fallback)+2. [ ] Add note under [managing-existing-widgets.md](managing-existing-widgets.md) § Deprecating if process changed++## Verify doc + code together++```bash+hogli test products/dashboards/backend/api/test/test_run_widgets.py+hogli test products/dashboards/backend/api/test/test_dashboard_widgets.py+hogli test products/dashboards/frontend/widgets/registry.test.tsx+```++After OpenAPI/MCP changes, also run [SKILL.md §6 Verify](../SKILL.md#6-verify).++## What not to duplicate++- **Runtime truth** stays in code + tests (`EXPECTED_WIDGET_TYPES`, catalog keys, `registry.test.tsx`). Do not maintain parallel type lists in markdown.+- **Generated files** (`frontend/generated/*`, MCP schema JSON) — regen with `hogli build:openapi`, do not document field-by-field copies.diff --git a/.agents/skills/dashboard-widgets/references/widget-intake.md b/.agents/skills/dashboard-widgets/references/widget-intake.mdnew file mode 100644index 000000000000..a1c52a6db543--- /dev/null+++ b/.agents/skills/dashboard-widgets/references/widget-intake.md@@ -0,0 +1,120 @@+# Widget intake — questions before coding++Use when `/dashboard-widgets` **Path: Ship** ([SKILL.md §2](../SKILL.md#2-ship-a-new-widget_type)) — a **new `widget_type`**. Not for updates to shipped types.++## Agent workflow++1. Parse the request into [spec fields](#spec-fields-to-lock).+2. Apply [defaults from SKILL.md §2.2](../SKILL.md#22-infer--defaults).+3. Ask **one batched follow-up** for gaps — `AskQuestion` when available, else a numbered list. Max **6** questions; order: placement → query/UI → config → access.+4. Post the spec summary below and get explicit confirmation before checklist §1.++Do not open the checklist until the engineer confirms (or says "defaults fine").++## Always confirm (even when inferred)++Include in the spec recap — engineer signs off:++| Field | Why it matters |+| -------------------------- | ----------------------------------------------------- |+| **`widget_type`** | Immutable registry/DB key |+| **`groupId`** | Add-modal section; variants share group, not type |+| **Copy spine** | `error_tracking_list` vs `session_replay_list` |+| **Query runner** | Exact function `run_*` calls — no parallel query path |+| **Variant vs new product** | New `groupId` → checklist §4c |++## Ask when not stated++Skip rows already answered. Cap at 6 per round.++### Product placement++1. **Add-modal group** — Variant in an existing group (which sibling?) or first widget for a new product area?+2. **Label + description** — Picker name and one-line description (not the internal `widget_type`).++### Data and UI++3. **Visualization** — List/table (default), metric, chart, or custom? (Non-list → cannot fully copy list spine.)+4. **Query source of truth** — Which existing query runner should `run_*` call?+5. **UI reuse** — `products/<product>/frontend/`, `scenes/<area>/`, or net-new in `widgets/<product>/`?+6. **Result shape** — Same as sibling `{ results: [...] }` or different?++### Config and edit modal++7. **Editable config** — Limit, sort, date range, filter test accounts, product-specific filters?+8. **Defaults** — Default limit, sort, date range when tile is first added?+9. **Hardcoded for v1** — Anything that looks configurable but should stay fixed?++### Tile chrome and layout++10. **Default size** — Match sibling `defaultLayout` or different `w`/`h`?+11. **Minimum resize** — Explicit catalog `minH`? (Platform floor is 4 rows.)+12. **Header "View" link** — `titleHref` to a product scene?++### Access, setup, limits++13. **Product RBAC** — Same `productAccess` as sibling or different?+14. **Setup before data** — Project prerequisite? Catalog `availability` vs inline gate in `Component` ([availability-and-gating.md](availability-and-gating.md)).+15. **Listing throttles** — Same as standalone product API (replay pattern)?+16. **Denied access copy** — Generic lock or custom message?++### Sharing and agents++17. **Public/shared dashboards** — Default placeholder or custom **`sharedPlaceholder`**?+18. **MCP catalog copy** — Extra `config_schema_hints` beyond validate defaults?++### Defer to Phase 2 (mention, do not block v1)++Storybook, overview fixtures, OpenAPI/MCP regen — after MVP tests unless engineer asks.++## Spec fields to lock++Post this block for confirmation:++```text+widget_type:+groupId:+label / description:+copy_from: error_tracking_list | session_replay_list+run_* delegates to:+UI imports from:+config fields:+defaults:+defaultLayout (w, h, minW, minH):+productAccess:+setup gating: none | catalog availability | inline Component gate+availability_requirements (BE MCP):+sharedPlaceholder: default | custom+titleHref: none | <path>+throttles: none | same as <product API>+```++Example:++```text+widget_type: error_tracking_trends+groupId: error_tracking+label / description: Issue trends / Rolling trend of top issues+copy_from: error_tracking_list+run_* delegates to: products.error_tracking.backend... (same as list)+UI imports from: products/error_tracking/frontend/ (new chart wrapper)+config fields: limit, dateRange, filterTestAccounts+defaults: limit 10, dateRange -7d+defaultLayout: w 6 h 4 minH 3+productAccess: error_tracking (same as list)+setup gating: inline Component gate (match ET)+sharedPlaceholder: default+titleHref: /error-tracking+throttles: none+```++## When to skip the question batch++Request already specifies product area, visualization, query source, and variant vs new group. Still post the spec recap.++## Red flags — stop and clarify++- Same `widget_type`, different config → need a **new** type+- Filters in ⋯ menu → settings modal only ([composition.md](composition.md))+- Special case in `dashboard.py` → registry-driven ([permissions-and-sharing.md](permissions-and-sharing.md))+- Frontend only → invalid; every type needs `validate_*` + `run_*`diff --git a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambrindex 55786bfd1388..7b30c9147023 100644--- a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr+++ b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr@@ -364,10 +364,10 @@round(multiply(divide(plus(plus(plus(divide(sum(s.active_milliseconds), 1000), sum(s.click_count)), sum(s.keypress_count)), sum(s.console_error_count)), plus(plus(plus(plus(sum(s.mouse_activity_count), dateDiff('SECOND', start_time, end_time)), sum(s.console_error_count)), sum(s.console_log_count)), sum(s.console_warn_count))), 100), 2) AS activity_scoreFROM session_replay_events AS sWHERE and(equals(s.team_id, 99999), greaterOrEquals(s.min_first_timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')), globalIn(s.session_id,- (SELECT nullIf(nullIf(events.`$session_id`, ''), 'null') AS session_id+ (SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '') AS session_idFROM events- WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'email'), ''), 'null'), '^"|"$', ''), 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))- GROUP BY nullIf(nullIf(events.`$session_id`, ''), 'null')+ WHERE and(equals(events.team_id, 99999), notEmpty(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'email'), ''), 'null'), '^"|"$', ''), 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))+ GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '')HAVING 1ORDER BY min(toTimeZone(events.timestamp, 'UTC')) DESCLIMIT 1000000)))@@ -538,10 +538,10 @@round(multiply(divide(plus(plus(plus(divide(sum(s.active_milliseconds), 1000), sum(s.click_count)), sum(s.keypress_count)), sum(s.console_error_count)), plus(plus(plus(plus(sum(s.mouse_activity_count), dateDiff('SECOND', start_time, end_time)), sum(s.console_error_count)), sum(s.console_log_count)), sum(s.console_warn_count))), 100), 2) AS activity_scoreFROM session_replay_events AS sWHERE and(equals(s.team_id, 99999), greaterOrEquals(s.min_first_timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')), globalIn(s.session_id,- (SELECT nullIf(nullIf(events.`$session_id`, ''), 'null') AS session_id+ (SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '') AS session_idFROM events- WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'email'), ''), 'null'), '^"|"$', ''), 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))- GROUP BY nullIf(nullIf(events.`$session_id`, ''), 'null')+ WHERE and(equals(events.team_id, 99999), notEmpty(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'email'), ''), 'null'), '^"|"$', ''), 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))+ GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '')HAVING 1ORDER BY min(toTimeZone(events.timestamp, 'UTC')) DESCLIMIT 1000000)))@@ -727,7 +727,7 @@round(multiply(divide(plus(plus(plus(divide(sum(s.active_milliseconds), 1000), sum(s.click_count)), sum(s.keypress_count)), sum(s.console_error_count)), plus(plus(plus(plus(sum(s.mouse_activity_count), dateDiff('SECOND', start_time, end_time)), sum(s.console_error_count)), sum(s.console_log_count)), sum(s.console_warn_count))), 100), 2) AS activity_scoreFROM session_replay_events AS sWHERE and(equals(s.team_id, 99999), greaterOrEquals(s.min_first_timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')), globalIn(s.session_id,- (SELECT nullIf(nullIf(events.`$session_id`, ''), 'null') AS session_id+ (SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '') AS session_idFROM eventsLEFT OUTER JOIN(SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id@@ -744,8 +744,8 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)- WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(events__person.properties___email, 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))- GROUP BY nullIf(nullIf(events.`$session_id`, ''), 'null')+ WHERE and(equals(events.team_id, 99999), notEmpty(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(events__person.properties___email, 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))+ GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '')HAVING 1ORDER BY min(toTimeZone(events.timestamp, 'UTC')) DESCLIMIT 1000000)))@@ -931,7 +931,7 @@round(multiply(divide(plus(plus(plus(divide(sum(s.active_milliseconds), 1000), sum(s.click_count)), sum(s.keypress_count)), sum(s.console_error_count)), plus(plus(plus(plus(sum(s.mouse_activity_count), dateDiff('SECOND', start_time, end_time)), sum(s.console_error_count)), sum(s.console_log_count)), sum(s.console_warn_count))), 100), 2) AS activity_scoreFROM session_replay_events AS sWHERE and(equals(s.team_id, 99999), greaterOrEquals(s.min_first_timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')), globalIn(s.session_id,- (SELECT nullIf(nullIf(events.`$session_id`, ''), 'null') AS session_id+ (SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '') AS session_idFROM eventsLEFT OUTER JOIN(SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id@@ -948,8 +948,8 @@WHERE equals(person.team_id, 99999)GROUP BY person.idHAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)- WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(events__person.properties___email, 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))- GROUP BY nullIf(nullIf(events.`$session_id`, ''), 'null')+ WHERE and(equals(events.team_id, 99999), notEmpty(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(events__person.properties___email, 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))+ GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '')HAVING 1ORDER BY min(toTimeZone(events.timestamp, 'UTC')) DESCLIMIT 1000000)))@@ -1120,10 +1120,10 @@round(multiply(divide(plus(plus(plus(divide(sum(s.active_milliseconds), 1000), sum(s.click_count)), sum(s.keypress_count)), sum(s.console_error_count)), plus(plus(plus(plus(sum(s.mouse_activity_count), dateDiff('SECOND', start_time, end_time)), sum(s.console_error_count)), sum(s.console_log_count)), sum(s.console_warn_count))), 100), 2) AS activity_scoreFROM session_replay_events AS sWHERE and(equals(s.team_id, 99999), greaterOrEquals(s.min_first_timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')), globalIn(s.session_id,- (SELECT nullIf(nullIf(events.`$session_id`, ''), 'null') AS session_id+ (SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '') AS session_idFROM events- WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), equals(events.mat_pp_email, 'bla'), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))- GROUP BY nullIf(nullIf(events.`$session_id`, ''), 'null')+ WHERE and(equals(events.team_id, 99999), notEmpty(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'email'), ''), 'null'), '^"|"$', ''), 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))+ GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '')HAVING 1ORDER BY min(toTimeZone(events.timestamp, 'UTC')) DESCLIMIT 1000000)))@@ -1294,10 +1294,10 @@round(multiply(divide(plus(plus(plus(divide(sum(s.active_milliseconds), 1000), sum(s.click_count)), sum(s.keypress_count)), sum(s.console_error_count)), plus(plus(plus(plus(sum(s.mouse_activity_count), dateDiff('SECOND', start_time, end_time)), sum(s.console_error_count)), sum(s.console_log_count)), sum(s.console_warn_count))), 100), 2) AS activity_scoreFROM session_replay_events AS sWHERE and(equals(s.team_id, 99999), greaterOrEquals(s.min_first_timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')), globalIn(s.session_id,- (SELECT nullIf(nullIf(events.`$session_id`, ''), 'null') AS session_id+ (SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '') AS session_idFROM events- WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'email'), ''), 'null'), '^"|"$', ''), 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))- GROUP BY nullIf(nullIf(events.`$session_id`, ''), 'null')+ WHERE and(equals(events.team_id, 99999), notEmpty(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'email'), ''), 'null'), '^"|"$', ''), 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))+ GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '')HAVING 1ORDER BY min(toTimeZone(events.timestamp, 'UTC')) DESCLIMIT 1000000)))@@ -1384,9 +1384,9 @@round(multiply(divide(plus(plus(plus(divide(sum(s.active_milliseconds), 1000), sum(s.click_count)), sum(s.keypress_count)), sum(s.console_error_count)), plus(plus(plus(plus(sum(s.mouse_activity_count), dateDiff('SECOND', start_time, end_time)), sum(s.console_error_count)), sum(s.console_log_count)), sum(s.console_warn_count))), 100), 2) AS activity_scoreFROM session_replay_events AS sWHERE and(equals(s.team_id, 99999), globalIn(s.session_id,- (SELECT DISTINCT nullIf(nullIf(events.`$session_id`, ''), 'null') AS `$session_id`+ (SELECT DISTINCT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '') AS `$session_id`FROM events- WHERE and(equals(events.team_id, 99999), equals(events.person_id, '00000000-0000-0000-0000-000000000000'), lessOrEquals(events.timestamp, toDateTime64(toDateTime64('today', 6, 'UTC'), 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null'))))), greaterOrEquals(s.min_first_timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')))+ WHERE and(equals(events.team_id, 99999), equals(events.person_id, '00000000-0000-0000-0000-000000000000'), lessOrEquals(events.timestamp, toDateTime64(toDateTime64('today', 6, 'UTC'), 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), notEmpty(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', ''))))), greaterOrEquals(s.min_first_timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')))GROUP BY s.session_idHAVING and(ifNull(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), 0), ifNull(equals(max(s.is_deleted), 0), 0))ORDER BY start_time DESC,@@ -1470,9 +1470,9 @@round(multiply(divide(plus(plus(plus(divide(sum(s.active_milliseconds), 1000), sum(s.click_count)), sum(s.keypress_count)), sum(s.console_error_count)), plus(plus(plus(plus(sum(s.mouse_activity_count), dateDiff('SECOND', start_time, end_time)), sum(s.console_error_count)), sum(s.console_log_count)), sum(s.console_warn_count))), 100), 2) AS activity_scoreFROM session_replay_events AS sWHERE and(equals(s.team_id, 99999), globalIn(s.session_id,- (SELECT DISTINCT nullIf(nullIf(events.`$session_id`, ''), 'null') AS `$session_id`+ (SELECT DISTINCT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '') AS `$session_id`FROM events- WHERE and(equals(events.team_id, 99999), equals(events.person_id, '00000000-0000-0000-0000-000000000000'), lessOrEquals(events.timestamp, toDateTime64(toDateTime64('today', 6, 'UTC'), 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null'))))), greaterOrEquals(s.min_first_timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')))+ WHERE and(equals(events.team_id, 99999), equals(events.person_id, '00000000-0000-0000-0000-000000000000'), lessOrEquals(events.timestamp, toDateTime64(toDateTime64('today', 6, 'UTC'), 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), notEmpty(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', ''))))), greaterOrEquals(s.min_first_timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')))GROUP BY s.session_idHAVING and(ifNull(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), 0), ifNull(equals(max(s.is_deleted), 0), 0))ORDER BY start_time DESC,@@ -1562,7 +1562,7 @@round(multiply(divide(plus(plus(plus(divide(sum(s.active_milliseconds), 1000), sum(s.click_count)), sum(s.keypress_count)), sum(s.console_error_count)), plus(plus(plus(plus(sum(s.mouse_activity_count), dateDiff('SECOND', start_time, end_time)), sum(s.console_error_count)), sum(s.console_log_count)), sum(s.console_warn_count))), 100), 2) AS activity_scoreFROM session_replay_events AS sWHERE and(equals(s.team_id, 99999), globalIn(s.session_id,- (SELECT DISTINCT nullIf(nullIf(events.`$session_id`, ''), 'null') AS `$session_id`+ (SELECT DISTINCT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '') AS `$session_id`FROM eventsLEFT OUTER JOIN(SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id@@ -1570,7 +1570,7 @@WHERE equals(person_distinct_id_overrides.team_id, 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)- WHERE and(equals(events.team_id, 99999), ifNull(equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'), 0), lessOrEquals(events.timestamp, toDateTime64(toDateTime64('today', 6, 'UTC'), 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null'))))), greaterOrEquals(s.min_first_timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')))+ WHERE and(equals(events.team_id, 99999), ifNull(equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'), 0), lessOrEquals(events.timestamp, toDateTime64(toDateTime64('today', 6, 'UTC'), 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), notEmpty(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', ''))))), greaterOrEquals(s.min_first_timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')))GROUP BY s.session_idHAVING and(ifNull(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), 0), ifNull(equals(max(s.is_deleted), 0), 0))ORDER BY start_time DESC,@@ -1660,7 +1660,7 @@round(multiply(divide(plus(plus(plus(divide(sum(s.active_milliseconds), 1000), sum(s.click_count)), sum(s.keypress_count)), sum(s.console_error_count)), plus(plus(plus(plus(sum(s.mouse_activity_count), dateDiff('SECOND', start_time, end_time)), sum(s.console_error_count)), sum(s.console_log_count)), sum(s.console_warn_count))), 100), 2) AS activity_scoreFROM session_replay_events AS sWHERE and(equals(s.team_id, 99999), globalIn(s.session_id,- (SELECT DISTINCT nullIf(nullIf(events.`$session_id`, ''), 'null') AS `$session_id`+ (SELECT DISTINCT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '') AS `$session_id`FROM eventsLEFT OUTER JOIN(SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id@@ -1668,7 +1668,7 @@WHERE equals(person_distinct_id_overrides.team_id, 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)- WHERE and(equals(events.team_id, 99999), ifNull(equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'), 0), lessOrEquals(events.timestamp, toDateTime64(toDateTime64('today', 6, 'UTC'), 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null'))))), greaterOrEquals(s.min_first_timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')))+ WHERE and(equals(events.team_id, 99999), ifNull(equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'), 0), lessOrEquals(events.timestamp, toDateTime64(toDateTime64('today', 6, 'UTC'), 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), notEmpty(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', ''))))), greaterOrEquals(s.min_first_timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')))GROUP BY s.session_idHAVING and(ifNull(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), 0), ifNull(equals(max(s.is_deleted), 0), 0))ORDER BY start_time DESC,@@ -1758,7 +1758,7 @@round(multiply(divide(plus(plus(plus(divide(sum(s.active_milliseconds), 1000), sum(s.click_count)), sum(s.keypress_count)), sum(s.console_error_count)), plus(plus(plus(plus(sum(s.mouse_activity_count), dateDiff('SECOND', start_time, end_time)), sum(s.console_error_count)), sum(s.console_log_count)), sum(s.console_warn_count))), 100), 2) AS activity_scoreFROM session_replay_events AS sWHERE and(equals(s.team_id, 99999), globalIn(s.session_id,- (SELECT DISTINCT nullIf(nullIf(events.`$session_id`, ''), 'null') AS `$session_id`+ (SELECT DISTINCT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '') AS `$session_id`FROM eventsLEFT OUTER JOIN(SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id@@ -1766,7 +1766,7 @@WHERE equals(person_distinct_id_overrides.team_id, 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)- WHERE and(equals(events.team_id, 99999), ifNull(equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'), 0), lessOrEquals(events.timestamp, toDateTime64(toDateTime64('today', 6, 'UTC'), 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null'))))), greaterOrEquals(s.min_first_timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')))+ WHERE and(equals(events.team_id, 99999), ifNull(equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'), 0), lessOrEquals(events.timestamp, toDateTime64(toDateTime64('today', 6, 'UTC'), 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), notEmpty(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', ''))))), greaterOrEquals(s.min_first_timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')))GROUP BY s.session_idHAVING and(ifNull(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), 0), ifNull(equals(max(s.is_deleted), 0), 0))ORDER BY start_time DESC,@@ -1856,7 +1856,7 @@round(multiply(divide(plus(plus(plus(divide(sum(s.active_milliseconds), 1000), sum(s.click_count)), sum(s.keypress_count)), sum(s.console_error_count)), plus(plus(plus(plus(sum(s.mouse_activity_count), dateDiff('SECOND', start_time, end_time)), sum(s.console_error_count)), sum(s.console_log_count)), sum(s.console_warn_count))), 100), 2) AS activity_scoreFROM session_replay_events AS sWHERE and(equals(s.team_id, 99999), globalIn(s.session_id,- (SELECT DISTINCT nullIf(nullIf(events.`$session_id`, ''), 'null') AS `$session_id`+ (SELECT DISTINCT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', '') AS `$session_id`FROM eventsLEFT OUTER JOIN(SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id@@ -1864,7 +1864,7 @@WHERE equals(person_distinct_id_overrides.team_id, 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)- WHERE and(equals(events.team_id, 99999), ifNull(equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'), 0), lessOrEquals(events.timestamp, toDateTime64(toDateTime64('today', 6, 'UTC'), 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null'))))), greaterOrEquals(s.min_first_timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')))+ WHERE and(equals(events.team_id, 99999), ifNull(equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'), 0), lessOrEquals(events.timestamp, toDateTime64(toDateTime64('today', 6, 'UTC'), 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), notEmpty(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$session_id'), ''), 'null'), '^"|"$', ''))))), greaterOrEquals(s.min_first_timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')))GROUP BY s.session_idHAVING and(ifNull(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), 0), ifNull(equals(max(s.is_deleted), 0), 0))ORDER BY start_time DESC,diff --git a/products/dashboards/CONTRIBUTING.md b/products/dashboards/CONTRIBUTING.mdnew file mode 100644index 000000000000..d048a10b7633--- /dev/null+++ b/products/dashboards/CONTRIBUTING.md@@ -0,0 +1,68 @@+# Dashboard widgets++Embeddable dashboard tiles backed by `DashboardWidget` and rendered through the product-local frontend registry in `products/dashboards/frontend/`.++**In scope:** widget tiles (`widget_id` on `DashboardTile`).+**Out of scope:** insight tiles, text cards, and button tiles — separate models today.++Reference implementations: `products/dashboards/frontend/widgets/error_tracking/` (`error_tracking_list`), `products/dashboards/frontend/widgets/session_replay/` (`session_replay_list`).++## Architecture (sketch)++```text+DashboardTile (layout) → widget_id → DashboardWidget (team-scoped)+ widget_type + config → WIDGET_REGISTRY (BE) → run_widgets+ → DASHBOARD_WIDGET_CATALOG + registry.tsx (FE)+```++New `widget_type` strings need **no migration** — register backend + frontend + both catalogs.+Schema changes on `DashboardWidget` / `DashboardTile` use the dashboards migration chain — invoke `django-migrations` when touching those models.++Layer table, registry shapes, copy/move, analytics, and typing details: [`.agents/skills/dashboard-widgets/references/architecture.md`](../../.agents/skills/dashboard-widgets/references/architecture.md)++## Playbook++**Canonical guide:** [`.agents/skills/dashboard-widgets/`](../../.agents/skills/dashboard-widgets/) (`/dashboard-widgets` — ship new types or update shipped types; intake only for new types).++| Task | Doc |+| ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |+| Add a new widget type | [`SKILL.md` §2 Ship](../../.agents/skills/dashboard-widgets/SKILL.md#2-ship-a-new-widget_type) → intake, then checklist |+| First widget in a new product area | Same — checklist §4c |+| Update an existing widget type | [`SKILL.md` §3 Update](../../.agents/skills/dashboard-widgets/SKILL.md#3-update-a-shipped-type) → managing-existing-widgets |+| Tile min/max size on dashboard grid | [`references/layout-and-ux.md`](../../.agents/skills/dashboard-widgets/references/layout-and-ux.md) (§ Tile min/max size) |+| WidgetCard, loading, headers | [`references/composition.md`](../../.agents/skills/dashboard-widgets/references/composition.md) |+| RBAC, copy/move, shared dashboards | [`references/permissions-and-sharing.md`](../../.agents/skills/dashboard-widgets/references/permissions-and-sharing.md) |+| Architecture, naming, scaling rules | [`references/architecture.md`](../../.agents/skills/dashboard-widgets/references/architecture.md) |+| MCP / REST | [`references/mcp.md`](../../.agents/skills/dashboard-widgets/references/mcp.md) |+| Keep skill docs in sync | [`references/skill-maintenance.md`](../../.agents/skills/dashboard-widgets/references/skill-maintenance.md) |++**Critical rule:** product RBAC is registry-driven — see [permissions-and-sharing.md § Product RBAC](../../.agents/skills/dashboard-widgets/references/permissions-and-sharing.md#product-rbac).++## Frontend / backend parity++Four registries must stay aligned for every shipped `widget_type`:++| Registry | Location |+| -------------------------- | ------------------------------------------------------------------------------------------------------------------- |+| `EXPECTED_WIDGET_TYPES` | `backend/widget_registry.py` |+| `WIDGET_CATALOG` | `backend/widget_catalog.py` |+| `DASHBOARD_WIDGET_CATALOG` | `frontend/widget_types/catalog.ts` |+| OpenAPI widget config | `backend/api/widget_openapi_serializers.py` (per-type `*WidgetConfigSerializer` on `_DashboardWidgetConfigOpenApi`) |++Plus FE runtime registry: `DASHBOARD_WIDGET_REGISTRY` in `frontend/widgets/registry.tsx`.++Per-type add flow (ordered): [checklist-new-widget-type.md](../../.agents/skills/dashboard-widgets/references/checklist-new-widget-type.md). Platform invariants: [architecture.md](../../.agents/skills/dashboard-widgets/references/architecture.md).++## Verify++Full command list: [`.agents/skills/dashboard-widgets/SKILL.md` § Verify](../../.agents/skills/dashboard-widgets/SKILL.md#verify).++Minimum when adding a type:++```bash+hogli test products/dashboards/backend/api/test/test_run_widgets.py+hogli test products/dashboards/backend/api/test/test_dashboard_widgets.py+hogli test products/dashboards/frontend/widgets/registry.test.tsx+```++After serializer or `widget_openapi_serializers.py` changes: `hogli build:openapi` (do not edit `products/dashboards/frontend/generated/`).diff --git a/products/dashboards/backend/api/test/test_run_widgets.py b/products/dashboards/backend/api/test/test_run_widgets.pyindex ba04869b043c..12b0896b3a4b 100644--- a/products/dashboards/backend/api/test/test_run_widgets.py+++ b/products/dashboards/backend/api/test/test_run_widgets.py@@ -16,6 +16,7 @@ from posthog.rbac.user_access_control import AccessControlLevel, UserAccessContrfrom posthog.scopes import APIScopeObjectfrom posthog.session_recordings.models.session_recording import SessionRecording+from products.dashboards.backend.api import widget_openapi_serializers as widget_openapi_serializers_modulefrom products.dashboards.backend.constants import DEFAULT_WIDGET_LIST_LIMIT, MAX_WIDGETS_BATCH_SIZEfrom products.dashboards.backend.widget_catalog import WIDGET_CATALOGfrom products.dashboards.backend.widget_registry import EXPECTED_WIDGET_TYPES, WIDGET_REGISTRY, validate_widget_config@@ -36,6 +37,13 @@ class TestWidgetRegistry(APIBaseTest):for widget_type, entry in WIDGET_CATALOG.items():assert entry["widget_type"] == widget_type+ def test_openapi_widget_config_serializers_match_registry(self) -> None:+ openapi_serializers = widget_openapi_serializers_module._DashboardWidgetConfigOpenApi.serializers+ assert len(openapi_serializers) == len(EXPECTED_WIDGET_TYPES), (+ "Add a *WidgetConfigSerializer for each widget type in widget_openapi_serializers.py. "+ f"serializers={len(openapi_serializers)} expected={len(EXPECTED_WIDGET_TYPES)}"+ )+def test_validate_widget_config_unknown_type(self) -> None:with self.assertRaises(Exception):validate_widget_config("not_a_widget", {})