:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(web_analytics): add heatmap MCP tools and assessment skill (#61503)
Paul D'Ambra42b5e5176901
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 2caf25d7cfde..5278cd4b0547 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -477,6 +477,7 @@ SPECTACULAR_SETTINGS = {"AutonomyPriorityEnum": "products.signals.backend.models.AutonomyPriority","UserInterviewSearchDocumentTypeEnum": "products.user_interviews.backend.facade.enums.SEARCH_DOCUMENT_TYPES","BatchExportRunStatusEnum": "products.batch_exports.backend.models.batch_export.BatchExportRun.Status",+ "HeatmapType": "products.web_analytics.backend.models.heatmap_saved.SavedHeatmap.Type",# --- Inline value lists (type-hint enums, no x-spec-enum-id) ---"PropertyGroupOperator": ["AND", "OR"],"PropertyFilterTypeEnum": [diff --git a/products/posthog_ai/skills/querying-posthog-data/SKILL.md b/products/posthog_ai/skills/querying-posthog-data/SKILL.mdindex ae16aa8068a2..de7a467381a0 100644--- a/products/posthog_ai/skills/querying-posthog-data/SKILL.md+++ b/products/posthog_ai/skills/querying-posthog-data/SKILL.md@@ -43,6 +43,7 @@ Schema reference for PostHog's core system models, organized by domain:- [Data Modeling Endpoints](./references/models-endpoints.md)- [Error Tracking](./references/models-error-tracking.md)- [Flags & Experiments](./references/models-flags-experiments.md)+- [Heatmaps (`heatmaps` data + `system.heatmaps_saved`)](./references/models-heatmaps.md)- [Hog Flows](./references/models-hog-flows.md)- [Hog Functions](./references/models-hog-functions.md)- [Integrations](./references/models-integrations.md)diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-heatmaps.md b/products/posthog_ai/skills/querying-posthog-data/references/models-heatmaps.mdnew file mode 100644index 000000000000..87862da4117a--- /dev/null+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-heatmaps.md@@ -0,0 +1,58 @@+# Heatmaps++## Heatmap interactions (`heatmaps`)++Every click, rageclick, mouse move, and scroll-depth sample captured by the SDK when `heatmaps_opt_in` is on for the team.+This is a first-class HogQL table (no `system.` prefix). Coordinates are stored scaled _down_ by `scale_factor` (always 16) — **multiply** `x`/`y`/`viewport_*` by `scale_factor` to recover CSS pixels (e.g. `y * scale_factor`). Retained for 90 days.++### Columns++Column | Type | Nullable | Description+`session_id` | varchar | NOT NULL | Session the interaction belongs to (join to `session_recordings.session_id`)+`team_id` | integer | NOT NULL | Team this interaction belongs to+`distinct_id` | varchar | NOT NULL | Person who interacted+`timestamp` | DateTime64 | NOT NULL | When the interaction happened+`x` | integer | NOT NULL | Horizontal position, stored scaled down by `scale_factor` (multiply to get CSS px)+`y` | integer | NOT NULL | Vertical position, stored scaled down by `scale_factor` (multiply to get CSS px)+`scale_factor` | integer | NOT NULL | Factor the coordinates were divided by at ingestion (always 16); multiply stored values by it to recover CSS pixels+`viewport_width` | integer | NOT NULL | Viewport width, stored scaled down by `scale_factor` (multiply to get CSS px)+`viewport_height` | integer | NOT NULL | Viewport height, stored scaled down by `scale_factor` (multiply to get CSS px)+`pointer_target_fixed` | boolean | NOT NULL | Whether the clicked element is fixed-position+`current_url` | varchar | NOT NULL | Full URL of the page the interaction happened on+`type` | varchar | NOT NULL | `click`, `rageclick`, `mousemove`, or `scrolldepth`++### Example: top click hotspots on a page (last 7 days)++```sql+SELECT+ round(x / viewport_width, 2) AS rel_x,+ y * scale_factor AS client_y,+ count() AS clicks+FROM heatmaps+WHERE current_url = 'https://example.com/pricing'+ AND type = 'click'+ AND timestamp >= now() - INTERVAL 7 DAY+GROUP BY rel_x, client_y+ORDER BY clicks DESC+LIMIT 20+```++### Example: rageclick volume by page++```sql+SELECT current_url, count() AS rageclicks+FROM heatmaps+WHERE type = 'rageclick' AND timestamp >= now() - INTERVAL 7 DAY+GROUP BY current_url+ORDER BY rageclicks DESC+LIMIT 20+```++### Important notes++- Heatmaps store coordinates, not element identity. To learn _what_ sits at a hotspot, cross-reference `$autocapture` events on the same `current_url` (their `elements_chain` / `$el_text` name the elements).+- `scrolldepth` rows encode reach down the page: `(y + viewport_height) * scale_factor` is how far the person scrolled.++## Saved heatmaps++Saved heatmaps (a pinned page URL plus rendered screenshots to overlay data on) are an operational catalog, not an analytics table — manage them through the MCP heatmap tools (`heatmaps-saved-list`, `heatmaps-saved-get`, `heatmaps-saved-create`, `heatmaps-saved-update`, `heatmaps-saved-regenerate`) rather than via SQL. The rendered screenshot itself isn't exposed over MCP; the user views it in the PostHog UI.diff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.pyindex 676f363d2959..f75ec780e0ae 100644--- a/products/web_analytics/backend/api/heatmaps_api.py+++ b/products/web_analytics/backend/api/heatmaps_api.py@@ -7,6 +7,8 @@ from django.db.models import Qfrom django.http import HttpResponseimport posthoganalytics+from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_fieldfrom rest_framework import request, response, serializers, status, viewsetsfrom posthog.schema import DateRange, HogQLFilters, HogQLQueryResponse, ProductKey@@ -117,24 +119,80 @@ LIMIT {limit}OFFSET {offset}"""+# Above/below-the-fold summary for positional (non-scrolldepth) interactions. Fixed-position+# elements move with the viewport so they're never "below the fold" — excluded from both the+# numerator and the denominator. `y` and `viewport_height` are stored in the same scaled units,+# so `y > viewport_height` means the interaction sat below the user's initial viewport.+FOLD_SUMMARY_QUERY = """+SELECT+ countIf(NOT pointer_target_fixed) AS total,+ countIf(y > viewport_height AND NOT pointer_target_fixed) AS below_fold,+ round(quantile(0.5)(viewport_height * scale_factor)) AS median_viewport_height+FROM heatmaps+WHERE {predicates}+"""+class HeatmapsRequestSerializer(serializers.Serializer):- viewport_width_min = serializers.IntegerField(required=False)- viewport_width_max = serializers.IntegerField(required=False)- type = serializers.CharField(required=False, default="click")- date_from = serializers.CharField(required=False, default="-7d")- date_to = serializers.CharField(required=False)- url_exact = serializers.CharField(required=False)- url_pattern = serializers.CharField(required=False)+ viewport_width_min = serializers.IntegerField(+ required=False,+ help_text="Only include interactions captured at a viewport at least this wide, in CSS pixels. "+ "Use with viewport_width_max to isolate a device class (e.g. 360-768 for mobile).",+ )+ viewport_width_max = serializers.IntegerField(+ required=False,+ help_text="Only include interactions captured at a viewport at most this wide, in CSS pixels.",+ )+ type = serializers.CharField(+ required=False,+ default="click",+ help_text="The interaction type to return. One of: 'click' (default), 'rageclick', 'mousemove', "+ "or 'scrolldepth'. Scrolldepth returns scroll buckets instead of x/y coordinates.",+ )+ date_from = serializers.CharField(+ required=False,+ default="-7d",+ help_text="Start of the window. Relative (e.g. '-7d', '-30d', '-1mStart') or an absolute 'YYYY-MM-DD' date. "+ "Defaults to '-7d'. Heatmap data is retained for 90 days.",+ )+ date_to = serializers.CharField(+ required=False,+ help_text="End of the window, inclusive. Relative or absolute 'YYYY-MM-DD'. Defaults to today.",+ )+ url_exact = serializers.CharField(+ required=False,+ help_text="Match a single page by exact URL (trailing slash is ignored). Mutually exclusive with url_pattern.",+ )+ url_pattern = serializers.CharField(+ required=False,+ help_text="Match pages by regex against the full current_url (anchored automatically). Use this to aggregate "+ "across query strings or path segments. Mutually exclusive with url_exact.",+ )aggregation = serializers.ChoiceField(required=False,choices=["unique_visitors", "total_count"],- help_text="How to aggregate the response",+ help_text="How to aggregate counts: 'total_count' (every interaction, default) or 'unique_visitors' "+ "(distinct people).",default="total_count",)- filter_test_accounts = serializers.BooleanField(required=False, default=None, allow_null=True)- hide_zero_coordinates = serializers.BooleanField(required=False, default=True)- cohort_ids = serializers.CharField(required=False, allow_null=True, allow_blank=True)+ filter_test_accounts = serializers.BooleanField(+ required=False,+ default=None,+ allow_null=True,+ help_text="When true, exclude sessions from internal/test accounts using the project's test-account filters.",+ )+ hide_zero_coordinates = serializers.BooleanField(+ required=False,+ default=True,+ help_text="When true (default), drop interactions recorded at the (0, 0) origin, which are usually noise.",+ )+ cohort_ids = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="JSON array of cohort IDs (e.g. '[123, 456]') to restrict results to people in those cohorts. "+ "Feature-flagged; ignored when the cohort filter is not enabled for the caller.",+ )def validate_cohort_ids(self, value: str | None) -> list[int]:if value is None or value == "":@@ -226,8 +284,34 @@ class HeatmapResponseItemSerializer(serializers.Serializer):pointer_target_fixed = serializers.BooleanField(required=True)+class HeatmapFoldSummarySerializer(serializers.Serializer):+ total_count = serializers.IntegerField(+ help_text="Number of non-fixed interactions of this type on the page in the window (the population the "+ "above/below-the-fold split applies to; fixed-position elements are excluded since they're always on screen)."+ )+ below_fold_count = serializers.IntegerField(+ help_text="How many of those interactions happened below the user's initial viewport — i.e. they had to "+ "scroll to reach them."+ )+ pct_below_fold = serializers.FloatField(+ help_text="Percentage of non-fixed interactions that were below the initial viewport (0-100). A high value "+ "means engaged content sits off the first screen and is a candidate to move up."+ )+ median_viewport_height = serializers.IntegerField(+ allow_null=True,+ help_text="Median viewport height in CSS pixels across the matched interactions — the typical fold line to "+ "recommend against. Null when there are no interactions.",+ )++class HeatmapsResponseSerializer(serializers.Serializer):results = HeatmapResponseItemSerializer(many=True)+ fold = HeatmapFoldSummarySerializer(+ required=False,+ allow_null=True,+ help_text="Above/below-the-fold summary for the returned interactions. Present for "+ "click/rageclick/mousemove; omitted for scrolldepth.",+ )class HeatmapScrollDepthResponseItemSerializer(serializers.Serializer):@@ -241,10 +325,19 @@ class HeatmapsScrollDepthResponseSerializer(serializers.Serializer):class HeatmapEventsRequestSerializer(HeatmapsRequestSerializer):- # JSON string of coordinate points: [{"x": 0.5, "y": 100}, ...]- points = serializers.CharField(required=True)- limit = serializers.IntegerField(required=False, default=50, min_value=1, max_value=100)- offset = serializers.IntegerField(required=False, default=0, min_value=0)+ points = serializers.CharField(+ required=True,+ help_text='JSON array of the heatmap coordinates to drill into, e.g. \'[{"x": 0.5, "y": 100}]\'. '+ "Each point needs 'x' (relative x, 0..1) and 'y' (absolute client-y pixels) matching values returned "+ "by the heatmaps list endpoint; an optional 'target_fixed' boolean matches fixed-position elements. "+ "Returns the individual session interactions behind those spots.",+ )+ limit = serializers.IntegerField(+ required=False, default=50, min_value=1, max_value=100, help_text="Maximum interactions to return (1-100)."+ )+ offset = serializers.IntegerField(+ required=False, default=0, min_value=0, help_text="Number of interactions to skip, for pagination."+ )def validate_points(self, value: str) -> list[dict]:try:@@ -282,7 +375,18 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):throttle_classes = [ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle]serializer_class = HeatmapsResponseSerializer-+ # list() returns a bespoke aggregated payload, not a paged queryset — opt out of the+ # project-global LimitOffsetPagination so the schema doesn't advertise a Paginated+ # envelope or phantom limit/offset params the endpoint ignores.+ pagination_class = None++ @extend_schema(+ parameters=[HeatmapsRequestSerializer],+ responses={200: HeatmapsResponseSerializer},+ description="Aggregated heatmap interactions for a page. For type 'click'/'rageclick'/'mousemove' each result "+ "is a point with relative x, absolute client-y, and a count. For type 'scrolldepth' the response is "+ "scroll-depth buckets instead (cumulative reach down the page).",+ )def list(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:request_serializer = HeatmapsRequestSerializer(data=request.query_params, context={"team": self.team})request_serializer.is_valid(raise_exception=True)@@ -316,8 +420,26 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):if is_scrolldepth_query:return self._return_scroll_depth_response(results)- else:- return self._return_heatmap_coordinates_response(results)++ fold = self._compute_fold_summary(exprs)+ return self._return_heatmap_coordinates_response(results, fold)++ def _compute_fold_summary(self, exprs: List[ast.Expr]) -> dict[str, Any]: # noqa: UP006+ stmt = parse_select(FOLD_SUMMARY_QUERY, {"predicates": ast.And(exprs=exprs)})+ context = HogQLContext(team_id=self.team.pk, limit_top_select=False)+ result = execute_hogql_query(query=stmt, team=self.team, limit_context=LimitContext.HEATMAPS, context=context)+ row = result.results[0] if result.results else None+ total = int(row[0]) if row else 0+ below = int(row[1]) if row else 0+ # quantile over an empty set returns NaN (which is != itself); coerce to None.+ raw_median = row[2] if row else None+ median = int(raw_median) if raw_median is not None and raw_median == raw_median else None+ return {+ "total_count": total,+ "below_fold_count": below,+ "pct_below_fold": round(100 * below / total, 1) if total else 0.0,+ "median_viewport_height": median,+ }def _choose_aggregation(self, aggregation, is_scrolldepth_query):aggregation_value = "count(*) as cnt" if aggregation == "total_count" else "count(distinct distinct_id) as cnt"@@ -403,7 +525,9 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):return predicate_expressions@staticmethod- def _return_heatmap_coordinates_response(query_response: HogQLQueryResponse) -> response.Response:+ def _return_heatmap_coordinates_response(+ query_response: HogQLQueryResponse, fold: dict[str, Any]+ ) -> response.Response:data = [{"pointer_target_fixed": item[0],@@ -414,7 +538,7 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):for item in query_response.results or []]- response_serializer = HeatmapsResponseSerializer(data={"results": data})+ response_serializer = HeatmapsResponseSerializer(data={"results": data, "fold": fold})response_serializer.is_valid(raise_exception=True)resp = response.Response(response_serializer.data, status=status.HTTP_200_OK)@@ -441,6 +565,13 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):resp["Vary"] = "Accept, Accept-Encoding, Query-String"return resp+ @extend_schema(+ parameters=[HeatmapEventsRequestSerializer],+ responses={200: HeatmapEventsResponseSerializer},+ description="Drill into the individual session interactions behind one or more heatmap coordinates. "+ "Pass the 'points' you want to inspect (from the heatmaps list response) to get the underlying "+ "per-session events, so you can jump to the session recordings that produced a hotspot.",+ )@action(methods=["GET"], detail=False)def events(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:request_serializer = HeatmapEventsRequestSerializer(data=request.query_params, context={"team": self.team})@@ -535,9 +666,18 @@ class LegacyHeatmapViewSet(HeatmapViewSet):# Heatmap Screenshot functionality+class HeatmapSnapshotMetadataSerializer(serializers.Serializer):+ width = serializers.IntegerField(help_text="Viewport width (CSS pixels) this screenshot was rendered at.")+ has_content = serializers.BooleanField(+ help_text="Whether the rendered image for this width is ready to fetch from the content endpoint."+ )++class HeatmapScreenshotResponseSerializer(serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True)- snapshots = serializers.SerializerMethodField()+ snapshots = serializers.SerializerMethodField(+ help_text="Per-width render metadata. Fetch the actual image bytes for a width from the content endpoint."+ )class Meta:model = SavedHeatmap@@ -568,7 +708,20 @@ class HeatmapScreenshotResponseSerializer(serializers.ModelSerializer):"updated_at","exception",]+ extra_kwargs = {+ "short_id": {"help_text": "Short, URL-safe identifier used as the lookup key for saved-heatmap routes."},+ "name": {"help_text": "Human-readable label for the saved heatmap."},+ "url": {"help_text": "The page URL this saved heatmap renders and overlays data on."},+ "data_url": {"help_text": "URL whose heatmap data is overlaid on the screenshot (defaults to 'url')."},+ "target_widths": {"help_text": "Viewport widths (CSS pixels) the screenshot is rendered at."},+ "type": {"help_text": "Render mode: 'screenshot', 'iframe', or 'recording'."},+ "status": {"help_text": "Screenshot generation status: 'processing', 'completed', or 'failed'."},+ "has_content": {"help_text": "Whether at least one rendered image is ready to fetch."},+ "deleted": {"help_text": "Soft-delete flag; deleted heatmaps are hidden from the list."},+ "exception": {"help_text": "Error detail when screenshot generation failed, otherwise null."},+ }+ @extend_schema_field(HeatmapSnapshotMetadataSerializer(many=True))def get_snapshots(self, obj: SavedHeatmap) -> list[dict]:# Expose metadata of generated snapshots (width + readiness)snaps = []@@ -599,6 +752,24 @@ class HeatmapScreenshotViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):def safely_get_queryset(self, queryset):return queryset.filter(team=self.team)+ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="width",+ type=OpenApiTypes.INT,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Viewport width (CSS pixels) to fetch. Defaults to 1024. If no exact render exists for "+ "this width the closest available one is returned.",+ )+ ],+ responses={+ (200, "image/jpeg"): OpenApiTypes.BINARY,+ 202: HeatmapScreenshotResponseSerializer,+ },+ description="Fetch the rendered screenshot image (JPEG bytes) for a saved heatmap at a given viewport width. "+ "Returns 202 with the saved-heatmap metadata while the screenshot is still being generated.",+ )@action(methods=["GET"], detail=True)def content(self, request: request.Request, *args: Any, **kwargs: Any) -> HttpResponse:screenshot = self.get_object()@@ -671,20 +842,56 @@ class SavedHeatmapRequestSerializer(serializers.ModelSerializer):model = SavedHeatmapfields = ["name", "url", "data_url", "widths", "type", "deleted"]extra_kwargs = {- "name": {"required": False, "allow_null": True},- "url": {"required": True},- "data_url": {"required": False, "allow_null": True},- "type": {"required": False, "default": SavedHeatmap.Type.SCREENSHOT},- "deleted": {"required": False},+ "name": {"required": False, "allow_null": True, "help_text": "Human-readable label for the saved heatmap."},+ "url": {+ "required": True,+ "help_text": "Exact page URL to render and overlay heatmap data on. Wildcards are not allowed.",+ },+ "data_url": {+ "required": False,+ "allow_null": True,+ "help_text": "URL whose heatmap data is overlaid on the screenshot. Defaults to 'url' when omitted.",+ },+ "type": {+ "required": False,+ "default": SavedHeatmap.Type.SCREENSHOT,+ "help_text": "Render mode: 'screenshot' (renders the page headlessly, default), 'iframe', "+ "or 'recording'. Only 'screenshot' generates image bytes.",+ },+ "deleted": {"required": False, "help_text": "Set true to soft-delete the saved heatmap."},}+class SavedHeatmapListQuerySerializer(serializers.Serializer):+ type = serializers.CharField(+ required=False, help_text="Filter by render mode: 'screenshot', 'iframe', or 'recording'."+ )+ status = serializers.CharField(+ required=False, help_text="Filter by generation status: 'processing', 'completed', or 'failed'."+ )+ search = serializers.CharField(required=False, help_text="Case-insensitive substring match on URL or name.")+ created_by = serializers.IntegerField(required=False, help_text="Filter by the creating user's ID.")+ order = serializers.CharField(+ required=False, help_text="Field to order by, e.g. '-updated_at' (default) or 'created_at'."+ )+ limit = serializers.IntegerField(required=False, default=100, help_text="Maximum saved heatmaps to return.")+ offset = serializers.IntegerField(required=False, default=0, help_text="Number to skip, for pagination.")+++class SavedHeatmapListResponseSerializer(serializers.Serializer):+ results = HeatmapScreenshotResponseSerializer(many=True)+ count = serializers.IntegerField(help_text="Total number of saved heatmaps matching the filters.")++class SavedHeatmapViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.GenericViewSet):scope_object = "heatmap"throttle_classes = [ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle]serializer_class = HeatmapScreenshotResponseSerializerqueryset = SavedHeatmap.objects.all()lookup_field = "short_id"+ # list() returns its own {results, count} shape (paginated via the query serializer), so+ # opt out of the project-global LimitOffsetPagination to avoid a double-wrapped schema.+ pagination_class = Nonedef get_throttles(self):if self.action == "create":@@ -695,7 +902,17 @@ class SavedHeatmapViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Gdef safely_get_queryset(self, queryset):return queryset.filter(team=self.team)+ @extend_schema(+ parameters=[SavedHeatmapListQuerySerializer],+ responses={200: SavedHeatmapListResponseSerializer},+ description="List saved heatmaps for the project. A saved heatmap pins a page URL and a set of viewport "+ "widths, and (for type 'screenshot') renders the page so heatmap data can be overlaid on it.",+ )def list(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:+ query_serializer = SavedHeatmapListQuerySerializer(data=request.query_params)+ query_serializer.is_valid(raise_exception=True)+ params = query_serializer.validated_data+qs = (self.safely_get_queryset(self.get_queryset()).filter(deleted=False)@@ -703,39 +920,39 @@ class SavedHeatmapViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.G.order_by("-updated_at"))- type_param = request.query_params.get("type")- status_param = request.query_params.get("status")- search = request.query_params.get("search")- created_by_param = request.query_params.get("created_by")- order = request.query_params.get("order")-- if type_param:- qs = qs.filter(type=type_param)- if status_param:- qs = qs.filter(status=status_param)- if search:- qs = qs.filter(Q(url__icontains=search) | Q(name__icontains=search))- if created_by_param:+ if params.get("type"):+ qs = qs.filter(type=params["type"])+ if params.get("status"):+ qs = qs.filter(status=params["status"])+ if params.get("search"):+ qs = qs.filter(Q(url__icontains=params["search"]) | Q(name__icontains=params["search"]))+ if params.get("created_by"):+ qs = qs.filter(created_by_id=params["created_by"])+ if params.get("order"):try:- qs = qs.filter(created_by_id=int(created_by_param))- except (ValueError, TypeError):+ qs = qs.order_by(params["order"])+ except FieldError:return response.Response(- {"error": "Invalid created_by parameter, must be an integer"}, status=status.HTTP_400_BAD_REQUEST+ {"error": f"Invalid order field: {params['order']}"}, status=status.HTTP_400_BAD_REQUEST)- if order:- try:- qs = qs.order_by(order)- except FieldError:- return response.Response({"error": f"Invalid order field: {order}"}, status=status.HTTP_400_BAD_REQUEST)- limit = int(request.query_params.get("limit", 100))- offset = int(request.query_params.get("offset", 0))+ # Clamp at the boundary rather than via serializer min/max so the OpenAPI+ # contract (and generated clients) stay unchanged while the page stays bounded.+ limit = max(1, min(params["limit"], 500))+ offset = max(0, params["offset"])count = qs.count()results = qs[offset : offset + limit]data = HeatmapScreenshotResponseSerializer(results, many=True).datareturn response.Response({"results": data, "count": count}, status=status.HTTP_200_OK)+ @extend_schema(+ request=SavedHeatmapRequestSerializer,+ responses={201: HeatmapScreenshotResponseSerializer},+ description="Create a saved heatmap for a page URL. For type 'screenshot' (the default) this enqueues a "+ "headless render of the page at each target width; poll the saved heatmap or its content endpoint until "+ "status is 'completed'. Provide 'widths' to control which viewport widths are rendered.",+ )def create(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:serializer = SavedHeatmapRequestSerializer(data=request.data)serializer.is_valid(raise_exception=True)@@ -777,6 +994,10 @@ class SavedHeatmapViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Greturn response.Response(HeatmapScreenshotResponseSerializer(screenshot).data, status=status.HTTP_201_CREATED)+ @extend_schema(+ responses={200: HeatmapScreenshotResponseSerializer},+ description="Get a single saved heatmap by its short_id, including per-width render status.",+ )def retrieve(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:obj = self.get_object()@@ -789,6 +1010,12 @@ class SavedHeatmapViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Greturn response.Response(HeatmapScreenshotResponseSerializer(obj).data, status=status.HTTP_200_OK)+ @extend_schema(+ request=None,+ responses={200: HeatmapScreenshotResponseSerializer, 400: OpenApiResponse(description="Not a screenshot")},+ description="Re-run screenshot generation for a saved heatmap of type 'screenshot'. Clears existing renders "+ "and re-renders at every target width; status returns to 'processing'.",+ )@action(methods=["POST"], detail=True)def regenerate(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:obj = self.get_object()@@ -807,6 +1034,12 @@ class SavedHeatmapViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.GHeatmapSnapshot.objects.filter(heatmap=obj).delete()generate_heatmap_screenshot.delay(obj.id)+ @extend_schema(+ request=SavedHeatmapRequestSerializer,+ responses={200: HeatmapScreenshotResponseSerializer},+ description="Update a saved heatmap (e.g. rename, change widths, or soft-delete via 'deleted'). Changing the "+ "URL of a 'screenshot' heatmap triggers a re-render.",+ )def partial_update(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:obj = self.get_object()old_url = obj.urldiff --git a/products/web_analytics/backend/test/__snapshots__/test_heatmaps_api.ambr b/products/web_analytics/backend/test/__snapshots__/test_heatmaps_api.ambrindex fc97d9057d45..9a599522e2a3 100644--- a/products/web_analytics/backend/test/__snapshots__/test_heatmaps_api.ambr+++ b/products/web_analytics/backend/test/__snapshots__/test_heatmaps_api.ambr@@ -31,6 +31,28 @@'''# ---# name: TestSessionRecordings.test_can_filter_by_exact_url.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), equals(trim(TRAILING '/'+ FROM heatmaps.current_url), trim(TRAILING '/'+ FROM 'http://example.com')), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_can_filter_by_exact_url.2'''/* user_id:0 request:_snapshot_ */SELECT pointer_target_fixed AS pointer_target_fixed,@@ -61,6 +83,28 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_filter_by_exact_url.3+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), equals(trim(TRAILING '/'+ FROM heatmaps.current_url), trim(TRAILING '/'+ FROM 'http://example.com/about')), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_filter_by_test_accounts'''/* user_id:0 request:_snapshot_ */@@ -94,6 +138,29 @@'''# ---# name: TestSessionRecordings.test_can_filter_by_test_accounts.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))), in(heatmaps.session_id,+ (SELECT DISTINCT events.`$session_id` AS `$session_id`+ FROM events+ WHERE and(equals(events.team_id, 99999), notEmpty(events.`$session_id`), and(less(events.timestamp, toDateTime64('today', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2023-03-08 00:00:00.000000', 6, 'UTC')), ifNull(notILike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$host'), ''), 'null'), '^"|"$', '')), '%127.0.0.1%'), 1))))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_can_filter_by_test_accounts.2'''/* user_id:0 request:_snapshot_ */SELECT pointer_target_fixed AS pointer_target_fixed,@@ -122,6 +189,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_filter_by_test_accounts.3+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com*'''/* user_id:0 request:_snapshot_ */@@ -152,6 +239,26 @@'''# ---# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com*.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com*.2'''/* user_id:0 request:_snapshot_ */SELECT pointer_target_fixed AS pointer_target_fixed,@@ -180,6 +287,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com*.3+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com.+$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products*'''/* user_id:0 request:_snapshot_ */@@ -210,6 +337,26 @@'''# ---# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products*.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products*.2'''/* user_id:0 request:_snapshot_ */SELECT pointer_target_fixed AS pointer_target_fixed,@@ -238,6 +385,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products*.3+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com/products.+$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products/*/parts/*'''/* user_id:0 request:_snapshot_ */@@ -268,6 +435,26 @@'''# ---# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products/*/parts/*.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products/*/parts/*.2'''/* user_id:0 request:_snapshot_ */SELECT pointer_target_fixed AS pointer_target_fixed,@@ -296,6 +483,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products/*/parts/*.3+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com/products/.+/parts/.+$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products/*/reviews/*'''/* user_id:0 request:_snapshot_ */@@ -326,6 +533,26 @@'''# ---# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products/*/reviews/*.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products/*/reviews/*.2'''/* user_id:0 request:_snapshot_ */SELECT pointer_target_fixed AS pointer_target_fixed,@@ -354,6 +581,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products/*/reviews/*.3+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com/products/.+/reviews/.+$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products/1*'''/* user_id:0 request:_snapshot_ */@@ -384,6 +631,26 @@'''# ---# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products/1*.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products/1*.2'''/* user_id:0 request:_snapshot_ */SELECT pointer_target_fixed AS pointer_target_fixed,@@ -412,6 +679,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products/1*.3+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com/products/1.+$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products/1*/parts/*'''/* user_id:0 request:_snapshot_ */@@ -442,6 +729,26 @@'''# ---# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products/1*/parts/*.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products/1*/parts/*.2'''/* user_id:0 request:_snapshot_ */SELECT pointer_target_fixed AS pointer_target_fixed,@@ -470,6 +777,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_filter_by_url_pattern_http://example.com/products/1*/parts/*.3+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com/products/1.+/parts/.+$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_filter_by_url_pattern_where_end_is_anchored'''/* user_id:0 request:_snapshot_ */@@ -499,6 +826,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_filter_by_url_pattern_where_end_is_anchored.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), match(heatmaps.current_url, '^http://example.com$'), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_filter_by_viewport_0_min_150'''/* user_id:0 request:_snapshot_ */@@ -528,6 +875,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_filter_by_viewport_0_min_150.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), ifNull(greaterOrEquals(heatmaps.viewport_width, round(divide(150, 16))), 0), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_filter_by_viewport_1_min_161'''/* user_id:0 request:_snapshot_ */@@ -557,6 +924,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_filter_by_viewport_1_min_161.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), ifNull(greaterOrEquals(heatmaps.viewport_width, round(divide(161, 16))), 0), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_filter_by_viewport_2_min_177'''/* user_id:0 request:_snapshot_ */@@ -586,6 +973,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_filter_by_viewport_2_min_177.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), ifNull(greaterOrEquals(heatmaps.viewport_width, round(divide(177, 16))), 0), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_filter_by_viewport_3_min_201'''/* user_id:0 request:_snapshot_ */@@ -615,6 +1022,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_filter_by_viewport_3_min_201.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), ifNull(greaterOrEquals(heatmaps.viewport_width, round(divide(201, 16))), 0), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_filter_by_viewport_4_min_161_and_max_192'''/* user_id:0 request:_snapshot_ */@@ -644,6 +1071,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_filter_by_viewport_4_min_161_and_max_192.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), ifNull(greaterOrEquals(heatmaps.viewport_width, round(divide(161, 16))), 0), ifNull(lessOrEquals(heatmaps.viewport_width, round(divide(192, 16))), 0), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_get_all_data_response'''/* user_id:0 request:_snapshot_ */@@ -673,6 +1120,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_get_all_data_response.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_get_count_by_aggregation'''/* user_id:0 request:_snapshot_ */@@ -703,6 +1170,26 @@'''# ---# name: TestSessionRecordings.test_can_get_count_by_aggregation.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_can_get_count_by_aggregation.2'''/* user_id:0 request:_snapshot_ */SELECT pointer_target_fixed AS pointer_target_fixed,@@ -731,6 +1218,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_get_count_by_aggregation.3+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_get_empty_response'''/* user_id:0 request:_snapshot_ */@@ -760,6 +1267,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_get_empty_response.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2024-05-03'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_get_filter_by_click'''/* user_id:0 request:_snapshot_ */@@ -790,6 +1317,26 @@'''# ---# name: TestSessionRecordings.test_can_get_filter_by_click.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_can_get_filter_by_click.2'''/* user_id:0 request:_snapshot_ */SELECT pointer_target_fixed AS pointer_target_fixed,@@ -818,6 +1365,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_get_filter_by_click.3+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'rageclick'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_get_filter_by_date_from'''/* user_id:0 request:_snapshot_ */@@ -847,6 +1414,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_get_filter_by_date_from.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_get_filter_by_relative_date'''/* user_id:0 request:_snapshot_ */@@ -877,6 +1464,26 @@'''# ---# name: TestSessionRecordings.test_can_get_filter_by_relative_date.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus(toDate('2023-03-14'), toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_can_get_filter_by_relative_date.2'''/* user_id:0 request:_snapshot_ */SELECT pointer_target_fixed AS pointer_target_fixed,@@ -905,6 +1512,26 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_can_get_filter_by_relative_date.3+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-15'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus(toDate('2023-03-15'), toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordings.test_can_get_scrolldepth_counts'''/* user_id:0 request:_snapshot_ */diff --git a/products/web_analytics/backend/test/test_heatmap_screenshots.py b/products/web_analytics/backend/test/test_heatmap_screenshots.pyindex 763ea47598e8..9ab2dd0acebb 100644--- a/products/web_analytics/backend/test/test_heatmap_screenshots.py+++ b/products/web_analytics/backend/test/test_heatmap_screenshots.py@@ -5,6 +5,7 @@ from unittest.mock import patchfrom django.utils import timezone+from parameterized import parameterizedfrom rest_framework.test import APIClientfrom posthog.jwt import PosthogJwtAudience, encode_jwt@@ -79,6 +80,20 @@ class TestHeatmapsAPI(APIBaseTest):found = next(x for x in r.data["results"] if x["url"] == "https://a.example")self.assertEqual(found["created_by"]["id"], self.user.id)+ @parameterized.expand(+ [+ ("non_integer_limit", {"limit": "abc"}, 400),+ ("non_integer_offset", {"offset": "xyz"}, 400),+ ("non_integer_created_by", {"created_by": "nope"}, 400),+ ("valid_limit", {"limit": 5}, 200),+ ("oversized_limit_does_not_500", {"limit": 100000000}, 200),+ ]+ )+ def test_saved_list_validates_and_bounds_pagination(self, _name, query, expected_status):+ SavedHeatmap.objects.create(team=self.team, url="https://a.example", created_by=self.user)+ r = self.client.get(f"/api/environments/{self.team.id}/saved/", query)+ assert r.status_code == expected_status+def test_team_isolation_for_content(self):other_team = Team.objects.create_with_data(organization=self.organization, initiating_user=self.user, name="Other Team"diff --git a/products/web_analytics/backend/test/test_heatmaps_api.py b/products/web_analytics/backend/test/test_heatmaps_api.pyindex 409e42745be4..78c252a9be63 100644--- a/products/web_analytics/backend/test/test_heatmaps_api.py+++ b/products/web_analytics/backend/test/test_heatmaps_api.py@@ -92,6 +92,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)current_url: str | None = None,distinct_id: str = "user_distinct_id",team_id: int | None = None,+ pointer_target_fixed: bool = True,) -> None:if team_id is None:team_id = self.team.pk@@ -113,7 +114,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)"viewport_width": round(viewport_width / 16),"viewport_height": round(viewport_height / 16),"type": type,- "pointer_target_fixed": True,+ "pointer_target_fixed": pointer_target_fixed,"current_url": current_url if current_url else "http://posthog.com",},)@@ -147,7 +148,18 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)def test_can_get_empty_response(self) -> None:response = self.client.get("/api/heatmap/?date_from=2024-05-03")assert response.status_code == 200- self.assertEqual(response.data, {"results": []})+ self.assertEqual(+ response.data,+ {+ "results": [],+ "fold": {+ "total_count": 0,+ "below_fold_count": 0,+ "pct_below_fold": 0.0,+ "median_viewport_height": None,+ },+ },+ )@freezegun.freeze_time("2025-03-31")@snapshot_clickhouse_queries@@ -157,6 +169,24 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)self._assert_heatmap_single_result_count({"date_from": "2023-03-08"}, 2)+ @freezegun.freeze_time("2025-03-31")+ def test_returns_below_the_fold_summary(self) -> None:+ # Non-fixed clicks against a 640px-tall viewport: one above the fold, two below it.+ self._create_heatmap_event("s1", "click", viewport_height=640, y=320, pointer_target_fixed=False)+ self._create_heatmap_event("s2", "click", viewport_height=640, y=960, pointer_target_fixed=False)+ self._create_heatmap_event("s3", "click", viewport_height=640, y=1280, pointer_target_fixed=False)+ # A fixed-position click below the fold is always on screen — excluded from the fold summary.+ self._create_heatmap_event("s4", "click", viewport_height=640, y=960, pointer_target_fixed=True)++ response = self.client.get("/api/heatmap/?date_from=2023-03-08&type=click")+ assert response.status_code == 200+ assert response.data["fold"] == {+ "total_count": 3,+ "below_fold_count": 2,+ "pct_below_fold": 66.7,+ "median_viewport_height": 640,+ }+@freezegun.freeze_time("2025-03-31")def test_cannot_query_across_teams(self) -> None:self._create_heatmap_event("session_1", "click")diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.tsindex f23e873497e9..29ad52d81d49 100644--- a/products/web_analytics/frontend/generated/api.schemas.ts+++ b/products/web_analytics/frontend/generated/api.schemas.ts@@ -7,35 +7,14 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/-export interface HeatmapResponseItemApi {- count: number- pointer_y: number- pointer_relative_x: number- pointer_target_fixed: boolean-}--export interface HeatmapsResponseApi {- results: HeatmapResponseItemApi[]-}--export interface PaginatedHeatmapsResponseListApi {- count: number- /** @nullable */- next?: string | null- /** @nullable */- previous?: string | null- results: HeatmapsResponseApi[]-}-/*** * `screenshot` - Screenshot* `iframe` - Iframe* `recording` - Recording*/-export type HeatmapScreenshotResponseTypeEnumApi =- (typeof HeatmapScreenshotResponseTypeEnumApi)[keyof typeof HeatmapScreenshotResponseTypeEnumApi]+export type HeatmapTypeApi = (typeof HeatmapTypeApi)[keyof typeof HeatmapTypeApi]-export const HeatmapScreenshotResponseTypeEnumApi = {+export const HeatmapTypeApi = {Screenshot: 'screenshot',Iframe: 'iframe',Recording: 'recording',@@ -55,6 +34,13 @@ export const HeatmapScreenshotResponseStatusEnumApi = {Failed: 'failed',} as const+export interface HeatmapSnapshotMetadataApi {+ /** Viewport width (CSS pixels) this screenshot was rendered at. */+ width: number+ /** Whether the rendered image for this width is ready to fetch from the content endpoint. */+ has_content: boolean+}+/*** * `engineering` - Engineering* `data` - Data@@ -110,75 +96,171 @@ export interface UserBasicApi {role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null}-export type HeatmapScreenshotResponseApiSnapshotsItem = { [key: string]: unknown }-export interface HeatmapScreenshotResponseApi {readonly id: string+ /** Short, URL-safe identifier used as the lookup key for saved-heatmap routes. */readonly short_id: string/**+ * Human-readable label for the saved heatmap.* @maxLength 400* @nullable*/name?: string | null- /** @maxLength 2000 */+ /**+ * The page URL this saved heatmap renders and overlays data on.+ * @maxLength 2000+ */url: string/**- * URL for fetching heatmap data+ * URL whose heatmap data is overlaid on the screenshot (defaults to 'url').* @maxLength 2000* @nullable*/data_url?: string | null+ /** Viewport widths (CSS pixels) the screenshot is rendered at. */target_widths?: unknown- type?: HeatmapScreenshotResponseTypeEnumApi+ /** Render mode: 'screenshot', 'iframe', or 'recording'.++ * `screenshot` - Screenshot+ * `iframe` - Iframe+ * `recording` - Recording */+ type?: HeatmapTypeApi+ /** Screenshot generation status: 'processing', 'completed', or 'failed'.++ * `processing` - Processing+ * `completed` - Completed+ * `failed` - Failed */readonly status: HeatmapScreenshotResponseStatusEnumApi+ /** Whether at least one rendered image is ready to fetch. */readonly has_content: boolean- readonly snapshots: readonly HeatmapScreenshotResponseApiSnapshotsItem[]+ /** Per-width render metadata. Fetch the actual image bytes for a width from the content endpoint. */+ readonly snapshots: readonly HeatmapSnapshotMetadataApi[]+ /** Soft-delete flag; deleted heatmaps are hidden from the list. */deleted?: booleanreadonly created_by: UserBasicApireadonly created_at: stringreadonly updated_at: string- /** @nullable */+ /**+ * Error detail when screenshot generation failed, otherwise null.+ * @nullable+ */readonly exception: string | null}-export interface PaginatedHeatmapScreenshotResponseListApi {+export interface HeatmapResponseItemApi {count: number+ pointer_y: number+ pointer_relative_x: number+ pointer_target_fixed: boolean+}++export interface HeatmapFoldSummaryApi {+ /** Number of non-fixed interactions of this type on the page in the window (the population the above/below-the-fold split applies to; fixed-position elements are excluded since they're always on screen). */+ total_count: number+ /** How many of those interactions happened below the user's initial viewport — i.e. they had to scroll to reach them. */+ below_fold_count: number+ /** Percentage of non-fixed interactions that were below the initial viewport (0-100). A high value means engaged content sits off the first screen and is a candidate to move up. */+ pct_below_fold: number+ /**+ * Median viewport height in CSS pixels across the matched interactions — the typical fold line to recommend against. Null when there are no interactions.+ * @nullable+ */+ median_viewport_height: number | null+}++export interface HeatmapsResponseApi {+ results: HeatmapResponseItemApi[]+ /** Above/below-the-fold summary for the returned interactions. Present for click/rageclick/mousemove; omitted for scrolldepth. */+ fold?: HeatmapFoldSummaryApi | null+}++export interface HeatmapEventItemApi {/** @nullable */- next?: string | null- /** @nullable */- previous?: string | null+ session_id?: string | null+ distinct_id: string+ timestamp: string+ pointer_relative_x: number+ pointer_y: number+ current_url: string+ type: string+}++export interface HeatmapEventsResponseApi {+ results: HeatmapEventItemApi[]+ total_count: number+ has_more: boolean+}++export interface SavedHeatmapListResponseApi {results: HeatmapScreenshotResponseApi[]+ /** Total number of saved heatmaps matching the filters. */+ count: number}-export type PatchedHeatmapScreenshotResponseApiSnapshotsItem = { [key: string]: unknown }+export interface SavedHeatmapRequestApi {+ /**+ * Human-readable label for the saved heatmap.+ * @maxLength 400+ * @nullable+ */+ name?: string | null+ /**+ * Exact page URL to render and overlay heatmap data on. Wildcards are not allowed.+ * @maxLength 2000+ */+ url: string+ /**+ * URL whose heatmap data is overlaid on the screenshot. Defaults to 'url' when omitted.+ * @maxLength 2000+ * @nullable+ */+ data_url?: string | null+ /**+ * Viewport widths (px, 100-3000) to render the heatmap screenshot at — one render per width. Defaults to [320, 375, 425, 768, 1024, 1440, 1920] when omitted. At most 16 widths.+ * @maxItems 16+ */+ widths?: number[]+ /** Render mode: 'screenshot' (renders the page headlessly, default), 'iframe', or 'recording'. Only 'screenshot' generates image bytes.++ * `screenshot` - Screenshot+ * `iframe` - Iframe+ * `recording` - Recording */+ type?: HeatmapTypeApi+ /** Set true to soft-delete the saved heatmap. */+ deleted?: boolean+}-export interface PatchedHeatmapScreenshotResponseApi {- readonly id?: string- readonly short_id?: string+export interface PatchedSavedHeatmapRequestApi {/**+ * Human-readable label for the saved heatmap.* @maxLength 400* @nullable*/name?: string | null- /** @maxLength 2000 */+ /**+ * Exact page URL to render and overlay heatmap data on. Wildcards are not allowed.+ * @maxLength 2000+ */url?: string/**- * URL for fetching heatmap data+ * URL whose heatmap data is overlaid on the screenshot. Defaults to 'url' when omitted.* @maxLength 2000* @nullable*/data_url?: string | null- target_widths?: unknown- type?: HeatmapScreenshotResponseTypeEnumApi- readonly status?: HeatmapScreenshotResponseStatusEnumApi- readonly has_content?: boolean- readonly snapshots?: readonly PatchedHeatmapScreenshotResponseApiSnapshotsItem[]+ /**+ * Viewport widths (px, 100-3000) to render the heatmap screenshot at — one render per width. Defaults to [320, 375, 425, 768, 1024, 1440, 1920] when omitted. At most 16 widths.+ * @maxItems 16+ */+ widths?: number[]+ /** Render mode: 'screenshot' (renders the page headlessly, default), 'iframe', or 'recording'. Only 'screenshot' generates image bytes.++ * `screenshot` - Screenshot+ * `iframe` - Iframe+ * `recording` - Recording */+ type?: HeatmapTypeApi+ /** Set true to soft-delete the saved heatmap. */deleted?: boolean- readonly created_by?: UserBasicApi- readonly created_at?: string- readonly updated_at?: string- /** @nullable */- readonly exception?: string | null}/**@@ -321,26 +403,193 @@ export interface PatchedWebAnalyticsFilterPresetApi {readonly last_modified_by?: UserBasicApi}+export type HeatmapScreenshotsContentRetrieveParams = {+ /**+ * Viewport width (CSS pixels) to fetch. Defaults to 1024. If no exact render exists for this width the closest available one is returned.+ */+ width?: number+}+export type HeatmapsListParams = {/**- * Number of results to return per page.+ * How to aggregate counts: 'total_count' (every interaction, default) or 'unique_visitors' (distinct people).++* `unique_visitors` - unique_visitors+* `total_count` - total_count+ * @minLength 1+ */+ aggregation?: HeatmapsListAggregation+ /**+ * JSON array of cohort IDs (e.g. '[123, 456]') to restrict results to people in those cohorts. Feature-flagged; ignored when the cohort filter is not enabled for the caller.+ * @nullable+ */+ cohort_ids?: string | null+ /**+ * Start of the window. Relative (e.g. '-7d', '-30d', '-1mStart') or an absolute 'YYYY-MM-DD' date. Defaults to '-7d'. Heatmap data is retained for 90 days.+ * @minLength 1+ */+ date_from?: string+ /**+ * End of the window, inclusive. Relative or absolute 'YYYY-MM-DD'. Defaults to today.+ * @minLength 1+ */+ date_to?: string+ /**+ * When true, exclude sessions from internal/test accounts using the project's test-account filters.+ * @nullable+ */+ filter_test_accounts?: boolean | null+ /**+ * When true (default), drop interactions recorded at the (0, 0) origin, which are usually noise.+ */+ hide_zero_coordinates?: boolean+ /**+ * The interaction type to return. One of: 'click' (default), 'rageclick', 'mousemove', or 'scrolldepth'. Scrolldepth returns scroll buckets instead of x/y coordinates.+ * @minLength 1+ */+ type?: string+ /**+ * Match a single page by exact URL (trailing slash is ignored). Mutually exclusive with url_pattern.+ * @minLength 1+ */+ url_exact?: string+ /**+ * Match pages by regex against the full current_url (anchored automatically). Use this to aggregate across query strings or path segments. Mutually exclusive with url_exact.+ * @minLength 1+ */+ url_pattern?: string+ /**+ * Only include interactions captured at a viewport at most this wide, in CSS pixels.+ */+ viewport_width_max?: number+ /**+ * Only include interactions captured at a viewport at least this wide, in CSS pixels. Use with viewport_width_max to isolate a device class (e.g. 360-768 for mobile).+ */+ viewport_width_min?: number+}++export type HeatmapsListAggregation = (typeof HeatmapsListAggregation)[keyof typeof HeatmapsListAggregation]++export const HeatmapsListAggregation = {+ UniqueVisitors: 'unique_visitors',+ TotalCount: 'total_count',+} as const++export type HeatmapsEventsRetrieveParams = {+ /**+ * How to aggregate counts: 'total_count' (every interaction, default) or 'unique_visitors' (distinct people).++* `unique_visitors` - unique_visitors+* `total_count` - total_count+ * @minLength 1+ */+ aggregation?: HeatmapsEventsRetrieveAggregation+ /**+ * JSON array of cohort IDs (e.g. '[123, 456]') to restrict results to people in those cohorts. Feature-flagged; ignored when the cohort filter is not enabled for the caller.+ * @nullable+ */+ cohort_ids?: string | null+ /**+ * Start of the window. Relative (e.g. '-7d', '-30d', '-1mStart') or an absolute 'YYYY-MM-DD' date. Defaults to '-7d'. Heatmap data is retained for 90 days.+ * @minLength 1+ */+ date_from?: string+ /**+ * End of the window, inclusive. Relative or absolute 'YYYY-MM-DD'. Defaults to today.+ * @minLength 1+ */+ date_to?: string+ /**+ * When true, exclude sessions from internal/test accounts using the project's test-account filters.+ * @nullable+ */+ filter_test_accounts?: boolean | null+ /**+ * When true (default), drop interactions recorded at the (0, 0) origin, which are usually noise.+ */+ hide_zero_coordinates?: boolean+ /**+ * Maximum interactions to return (1-100).+ * @minimum 1+ * @maximum 100*/limit?: number/**- * The initial index from which to return the results.+ * Number of interactions to skip, for pagination.+ * @minimum 0*/offset?: number+ /**+ * JSON array of the heatmap coordinates to drill into, e.g. '[{"x": 0.5, "y": 100}]'. Each point needs 'x' (relative x, 0..1) and 'y' (absolute client-y pixels) matching values returned by the heatmaps list endpoint; an optional 'target_fixed' boolean matches fixed-position elements. Returns the individual session interactions behind those spots.+ * @minLength 1+ */+ points: string+ /**+ * The interaction type to return. One of: 'click' (default), 'rageclick', 'mousemove', or 'scrolldepth'. Scrolldepth returns scroll buckets instead of x/y coordinates.+ * @minLength 1+ */+ type?: string+ /**+ * Match a single page by exact URL (trailing slash is ignored). Mutually exclusive with url_pattern.+ * @minLength 1+ */+ url_exact?: string+ /**+ * Match pages by regex against the full current_url (anchored automatically). Use this to aggregate across query strings or path segments. Mutually exclusive with url_exact.+ * @minLength 1+ */+ url_pattern?: string+ /**+ * Only include interactions captured at a viewport at most this wide, in CSS pixels.+ */+ viewport_width_max?: number+ /**+ * Only include interactions captured at a viewport at least this wide, in CSS pixels. Use with viewport_width_max to isolate a device class (e.g. 360-768 for mobile).+ */+ viewport_width_min?: number}+export type HeatmapsEventsRetrieveAggregation =+ (typeof HeatmapsEventsRetrieveAggregation)[keyof typeof HeatmapsEventsRetrieveAggregation]++export const HeatmapsEventsRetrieveAggregation = {+ UniqueVisitors: 'unique_visitors',+ TotalCount: 'total_count',+} as const+export type SavedListParams = {/**- * Number of results to return per page.+ * Filter by the creating user's ID.+ */+ created_by?: number+ /**+ * Maximum saved heatmaps to return.*/limit?: number/**- * The initial index from which to return the results.+ * Number to skip, for pagination.*/offset?: number+ /**+ * Field to order by, e.g. '-updated_at' (default) or 'created_at'.+ * @minLength 1+ */+ order?: string+ /**+ * Case-insensitive substring match on URL or name.+ * @minLength 1+ */+ search?: string+ /**+ * Filter by generation status: 'processing', 'completed', or 'failed'.+ * @minLength 1+ */+ status?: string+ /**+ * Filter by render mode: 'screenshot', 'iframe', or 'recording'.+ * @minLength 1+ */+ type?: string}export type WebAnalyticsWeeklyDigestParams = {diff --git a/products/web_analytics/frontend/generated/api.ts b/products/web_analytics/frontend/generated/api.tsindex a2a471abeadd..337616b048c6 100644--- a/products/web_analytics/frontend/generated/api.ts+++ b/products/web_analytics/frontend/generated/api.ts@@ -9,13 +9,17 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ HeatmapEventsResponseApi,HeatmapScreenshotResponseApi,+ HeatmapScreenshotsContentRetrieveParams,+ HeatmapsEventsRetrieveParams,HeatmapsListParams,- PaginatedHeatmapScreenshotResponseListApi,- PaginatedHeatmapsResponseListApi,+ HeatmapsResponseApi,PaginatedWebAnalyticsFilterPresetListApi,- PatchedHeatmapScreenshotResponseApi,+ PatchedSavedHeatmapRequestApi,PatchedWebAnalyticsFilterPresetApi,+ SavedHeatmapListResponseApi,+ SavedHeatmapRequestApi,SavedListParams,WebAnalyticsFilterPresetApi,WebAnalyticsFilterPresetsListParams,@@ -40,19 +44,42 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]}: DistributeReadOnlyOverUnions<T>-export const getHeatmapScreenshotsContentRetrieveUrl = (projectId: string, id: string) => {- return `/api/projects/${projectId}/heatmap_screenshots/${id}/content/`+export const getHeatmapScreenshotsContentRetrieveUrl = (+ projectId: string,+ id: string,+ params?: HeatmapScreenshotsContentRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/heatmap_screenshots/${id}/content/?${stringifiedParams}`+ : `/api/projects/${projectId}/heatmap_screenshots/${id}/content/`}+/**+ * Fetch the rendered screenshot image (JPEG bytes) for a saved heatmap at a given viewport width. Returns 202 with the saved-heatmap metadata while the screenshot is still being generated.+ */export const heatmapScreenshotsContentRetrieve = async (projectId: string,id: string,+ params?: HeatmapScreenshotsContentRetrieveParams,options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getHeatmapScreenshotsContentRetrieveUrl(projectId, id), {- ...options,- method: 'GET',- })+): Promise<Blob | HeatmapScreenshotResponseApi> => {+ return apiMutator<Blob | HeatmapScreenshotResponseApi>(+ getHeatmapScreenshotsContentRetrieveUrl(projectId, id, params),+ {+ ...options,+ method: 'GET',+ }+ )}export const getHeatmapsListUrl = (projectId: string, params?: HeatmapsListParams) => {@@ -71,23 +98,45 @@ export const getHeatmapsListUrl = (projectId: string, params?: HeatmapsListParam: `/api/projects/${projectId}/heatmaps/`}+/**+ * Aggregated heatmap interactions for a page. For type 'click'/'rageclick'/'mousemove' each result is a point with relative x, absolute client-y, and a count. For type 'scrolldepth' the response is scroll-depth buckets instead (cumulative reach down the page).+ */export const heatmapsList = async (projectId: string,params?: HeatmapsListParams,options?: RequestInit-): Promise<PaginatedHeatmapsResponseListApi> => {- return apiMutator<PaginatedHeatmapsResponseListApi>(getHeatmapsListUrl(projectId, params), {+): Promise<HeatmapsResponseApi[]> => {+ return apiMutator<HeatmapsResponseApi[]>(getHeatmapsListUrl(projectId, params), {...options,method: 'GET',})}-export const getHeatmapsEventsRetrieveUrl = (projectId: string) => {- return `/api/projects/${projectId}/heatmaps/events/`+export const getHeatmapsEventsRetrieveUrl = (projectId: string, params: HeatmapsEventsRetrieveParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/heatmaps/events/?${stringifiedParams}`+ : `/api/projects/${projectId}/heatmaps/events/`}-export const heatmapsEventsRetrieve = async (projectId: string, options?: RequestInit): Promise<void> => {- return apiMutator<void>(getHeatmapsEventsRetrieveUrl(projectId), {+/**+ * Drill into the individual session interactions behind one or more heatmap coordinates. Pass the 'points' you want to inspect (from the heatmaps list response) to get the underlying per-session events, so you can jump to the session recordings that produced a hotspot.+ */+export const heatmapsEventsRetrieve = async (+ projectId: string,+ params: HeatmapsEventsRetrieveParams,+ options?: RequestInit+): Promise<HeatmapEventsResponseApi> => {+ return apiMutator<HeatmapEventsResponseApi>(getHeatmapsEventsRetrieveUrl(projectId, params), {...options,method: 'GET',})@@ -109,12 +158,15 @@ export const getSavedListUrl = (projectId: string, params?: SavedListParams) =>: `/api/projects/${projectId}/saved/`}+/**+ * List saved heatmaps for the project. A saved heatmap pins a page URL and a set of viewport widths, and (for type 'screenshot') renders the page so heatmap data can be overlaid on it.+ */export const savedList = async (projectId: string,params?: SavedListParams,options?: RequestInit-): Promise<PaginatedHeatmapScreenshotResponseListApi> => {- return apiMutator<PaginatedHeatmapScreenshotResponseListApi>(getSavedListUrl(projectId, params), {+): Promise<SavedHeatmapListResponseApi[]> => {+ return apiMutator<SavedHeatmapListResponseApi[]>(getSavedListUrl(projectId, params), {...options,method: 'GET',})@@ -124,16 +176,19 @@ export const getSavedCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/saved/`}+/**+ * Create a saved heatmap for a page URL. For type 'screenshot' (the default) this enqueues a headless render of the page at each target width; poll the saved heatmap or its content endpoint until status is 'completed'. Provide 'widths' to control which viewport widths are rendered.+ */export const savedCreate = async (projectId: string,- heatmapScreenshotResponseApi: NonReadonly<HeatmapScreenshotResponseApi>,+ savedHeatmapRequestApi: SavedHeatmapRequestApi,options?: RequestInit): Promise<HeatmapScreenshotResponseApi> => {return apiMutator<HeatmapScreenshotResponseApi>(getSavedCreateUrl(projectId), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(heatmapScreenshotResponseApi),+ body: JSON.stringify(savedHeatmapRequestApi),})}@@ -141,6 +196,9 @@ export const getSavedRetrieveUrl = (projectId: string, shortId: string) => {return `/api/projects/${projectId}/saved/${shortId}/`}+/**+ * Get a single saved heatmap by its short_id, including per-width render status.+ */export const savedRetrieve = async (projectId: string,shortId: string,@@ -156,17 +214,20 @@ export const getSavedPartialUpdateUrl = (projectId: string, shortId: string) =>return `/api/projects/${projectId}/saved/${shortId}/`}+/**+ * Update a saved heatmap (e.g. rename, change widths, or soft-delete via 'deleted'). Changing the URL of a 'screenshot' heatmap triggers a re-render.+ */export const savedPartialUpdate = async (projectId: string,shortId: string,- patchedHeatmapScreenshotResponseApi?: NonReadonly<PatchedHeatmapScreenshotResponseApi>,+ patchedSavedHeatmapRequestApi?: PatchedSavedHeatmapRequestApi,options?: RequestInit): Promise<HeatmapScreenshotResponseApi> => {return apiMutator<HeatmapScreenshotResponseApi>(getSavedPartialUpdateUrl(projectId, shortId), {...options,method: 'PATCH',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(patchedHeatmapScreenshotResponseApi),+ body: JSON.stringify(patchedSavedHeatmapRequestApi),})}@@ -188,17 +249,17 @@ export const getSavedRegenerateCreateUrl = (projectId: string, shortId: string)return `/api/projects/${projectId}/saved/${shortId}/regenerate/`}+/**+ * Re-run screenshot generation for a saved heatmap of type 'screenshot'. Clears existing renders and re-renders at every target width; status returns to 'processing'.+ */export const savedRegenerateCreate = async (projectId: string,shortId: string,- heatmapScreenshotResponseApi: NonReadonly<HeatmapScreenshotResponseApi>,options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getSavedRegenerateCreateUrl(projectId, shortId), {+): Promise<HeatmapScreenshotResponseApi> => {+ return apiMutator<HeatmapScreenshotResponseApi>(getSavedRegenerateCreateUrl(projectId, shortId), {...options,method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(heatmapScreenshotResponseApi),})}diff --git a/products/web_analytics/frontend/generated/api.zod.ts b/products/web_analytics/frontend/generated/api.zod.tsindex f375e8df5fc4..2a2333bd4ee1 100644--- a/products/web_analytics/frontend/generated/api.zod.ts+++ b/products/web_analytics/frontend/generated/api.zod.ts@@ -9,58 +9,97 @@*/import * as zod from 'zod'+/**+ * Create a saved heatmap for a page URL. For type 'screenshot' (the default) this enqueues a headless render of the page at each target width; poll the saved heatmap or its content endpoint until status is 'completed'. Provide 'widths' to control which viewport widths are rendered.+ */export const savedCreateBodyNameMax = 400export const savedCreateBodyUrlMax = 2000export const savedCreateBodyDataUrlMax = 2000+export const savedCreateBodyWidthsItemMin = 100+export const savedCreateBodyWidthsItemMax = 3000++export const savedCreateBodyWidthsMax = 16++export const savedCreateBodyTypeDefault = `screenshot`+export const SavedCreateBody = /* @__PURE__ */ zod.object({- name: zod.string().max(savedCreateBodyNameMax).nullish(),- url: zod.url().max(savedCreateBodyUrlMax),- data_url: zod.url().max(savedCreateBodyDataUrlMax).nullish().describe('URL for fetching heatmap data'),- target_widths: zod.unknown().optional(),+ name: zod.string().max(savedCreateBodyNameMax).nullish().describe('Human-readable label for the saved heatmap.'),+ url: zod+ .url()+ .max(savedCreateBodyUrlMax)+ .describe('Exact page URL to render and overlay heatmap data on. Wildcards are not allowed.'),+ data_url: zod+ .url()+ .max(savedCreateBodyDataUrlMax)+ .nullish()+ .describe("URL whose heatmap data is overlaid on the screenshot. Defaults to 'url' when omitted."),+ widths: zod+ .array(zod.number().min(savedCreateBodyWidthsItemMin).max(savedCreateBodyWidthsItemMax))+ .max(savedCreateBodyWidthsMax)+ .optional()+ .describe(+ 'Viewport widths (px, 100-3000) to render the heatmap screenshot at — one render per width. Defaults to [320, 375, 425, 768, 1024, 1440, 1920] when omitted. At most 16 widths.'+ ),type: zod.enum(['screenshot', 'iframe', 'recording'])- .optional()- .describe('\* `screenshot` - Screenshot\n\* `iframe` - Iframe\n\* `recording` - Recording'),- deleted: zod.boolean().optional(),+ .describe('\* `screenshot` - Screenshot\n\* `iframe` - Iframe\n\* `recording` - Recording')+ .default(savedCreateBodyTypeDefault)+ .describe(+ "Render mode: 'screenshot' (renders the page headlessly, default), 'iframe', or 'recording'. Only 'screenshot' generates image bytes.\n\n\* `screenshot` - Screenshot\n\* `iframe` - Iframe\n\* `recording` - Recording"+ ),+ deleted: zod.boolean().optional().describe('Set true to soft-delete the saved heatmap.'),})+/**+ * Update a saved heatmap (e.g. rename, change widths, or soft-delete via 'deleted'). Changing the URL of a 'screenshot' heatmap triggers a re-render.+ */export const savedPartialUpdateBodyNameMax = 400export const savedPartialUpdateBodyUrlMax = 2000export const savedPartialUpdateBodyDataUrlMax = 2000-export const SavedPartialUpdateBody = /* @__PURE__ */ zod.object({- name: zod.string().max(savedPartialUpdateBodyNameMax).nullish(),- url: zod.url().max(savedPartialUpdateBodyUrlMax).optional(),- data_url: zod.url().max(savedPartialUpdateBodyDataUrlMax).nullish().describe('URL for fetching heatmap data'),- target_widths: zod.unknown().optional(),- type: zod- .enum(['screenshot', 'iframe', 'recording'])- .optional()- .describe('\* `screenshot` - Screenshot\n\* `iframe` - Iframe\n\* `recording` - Recording'),- deleted: zod.boolean().optional(),-})--export const savedRegenerateCreateBodyNameMax = 400+export const savedPartialUpdateBodyWidthsItemMin = 100+export const savedPartialUpdateBodyWidthsItemMax = 3000-export const savedRegenerateCreateBodyUrlMax = 2000+export const savedPartialUpdateBodyWidthsMax = 16-export const savedRegenerateCreateBodyDataUrlMax = 2000+export const savedPartialUpdateBodyTypeDefault = `screenshot`-export const SavedRegenerateCreateBody = /* @__PURE__ */ zod.object({- name: zod.string().max(savedRegenerateCreateBodyNameMax).nullish(),- url: zod.url().max(savedRegenerateCreateBodyUrlMax),- data_url: zod.url().max(savedRegenerateCreateBodyDataUrlMax).nullish().describe('URL for fetching heatmap data'),- target_widths: zod.unknown().optional(),+export const SavedPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(savedPartialUpdateBodyNameMax)+ .nullish()+ .describe('Human-readable label for the saved heatmap.'),+ url: zod+ .url()+ .max(savedPartialUpdateBodyUrlMax)+ .optional()+ .describe('Exact page URL to render and overlay heatmap data on. Wildcards are not allowed.'),+ data_url: zod+ .url()+ .max(savedPartialUpdateBodyDataUrlMax)+ .nullish()+ .describe("URL whose heatmap data is overlaid on the screenshot. Defaults to 'url' when omitted."),+ widths: zod+ .array(zod.number().min(savedPartialUpdateBodyWidthsItemMin).max(savedPartialUpdateBodyWidthsItemMax))+ .max(savedPartialUpdateBodyWidthsMax)+ .optional()+ .describe(+ 'Viewport widths (px, 100-3000) to render the heatmap screenshot at — one render per width. Defaults to [320, 375, 425, 768, 1024, 1440, 1920] when omitted. At most 16 widths.'+ ),type: zod.enum(['screenshot', 'iframe', 'recording'])- .optional()- .describe('\* `screenshot` - Screenshot\n\* `iframe` - Iframe\n\* `recording` - Recording'),- deleted: zod.boolean().optional(),+ .describe('\* `screenshot` - Screenshot\n\* `iframe` - Iframe\n\* `recording` - Recording')+ .default(savedPartialUpdateBodyTypeDefault)+ .describe(+ "Render mode: 'screenshot' (renders the page headlessly, default), 'iframe', or 'recording'. Only 'screenshot' generates image bytes.\n\n\* `screenshot` - Screenshot\n\* `iframe` - Iframe\n\* `recording` - Recording"+ ),+ deleted: zod.boolean().optional().describe('Set true to soft-delete the saved heatmap.'),})export const webAnalyticsFilterPresetsCreateBodyNameMax = 400diff --git a/products/web_analytics/mcp/tools.yaml b/products/web_analytics/mcp/tools.yamlindex 6b752f6a51a2..57417a153bd7 100644--- a/products/web_analytics/mcp/tools.yaml+++ b/products/web_analytics/mcp/tools.yaml@@ -12,29 +12,130 @@ tools:heatmap-screenshots-content-retrieve:operation: heatmap_screenshots_content_retrieveenabled: false- heatmaps-events-retrieve:+ heatmaps-events:operation: heatmaps_events_retrieve- enabled: false+ enabled: true+ scopes:+ - heatmap:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get sessions behind heatmap coordinates+ description: >+ Drill into the individual session interactions behind one or more heatmap coordinates. Pass `points` as a+ JSON array of the spots you want to inspect (the `pointer_relative_x` / `pointer_y` values from+ `heatmaps-list`), plus the same page/date filters. Returns the underlying per-session interactions so you+ can open the session recordings that produced a hotspot.+ feature_flag: heatmaps-mcpheatmaps-list:operation: heatmaps_list- enabled: false- saved-create:+ enabled: true+ scopes:+ - heatmap:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List heatmap interactions for a page+ description: >+ Aggregated heatmap interactions captured on a page. Filter by `url_exact` (one page) or `url_pattern` (regex+ across pages), a date window (`date_from`/`date_to`, data is retained 90 days), and optionally a viewport+ range (`viewport_width_min`/`viewport_width_max`, CSS px) to isolate a device class. Set `type` to 'click'+ (default), 'rageclick', 'mousemove', or 'scrolldepth'. For clicks each result is a point —+ `pointer_relative_x` (0..1 across the viewport), `pointer_y` (absolute pixels down the page), and a `count`;+ 'scrolldepth' returns reach buckets instead. For the click types the response also includes a `fold` summary+ — `pct_below_fold` (share of non-fixed interactions that landed below the user's initial viewport, i.e.+ required scrolling), `below_fold_count`, `total_count`, and the `median_viewport_height` (the typical fold+ line in CSS px) — so a high `pct_below_fold` flags engaged content sitting off the first screen. `rageclick`+ hotspots and shallow scroll depth are the strongest signals that something on the page is confusing or+ buried. Heatmaps only know coordinates, not what was clicked — cross-reference autocapture events on the+ same URL to name the elements, and use `heatmaps-events` to jump to the sessions behind a hotspot.+ feature_flag: heatmaps-mcp+ heatmaps-saved-create:operation: saved_create- enabled: false- saved-destroy:- operation: saved_destroy- enabled: false- saved-list:+ enabled: true+ scopes:+ - heatmap:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Create a saved heatmap+ description: >+ Create a saved heatmap for a page URL. For type 'screenshot' (the default) this enqueues a headless render+ of the page at each target width — poll `heatmaps-saved-get` until `status` is 'completed'; the rendered+ page (with data overlaid) is then viewable by the user in the PostHog UI. Provide `widths` (CSS px,+ 100-3000) to control which viewports are rendered, or omit it for sensible defaults. The URL must be exact —+ wildcards are not allowed.+ exclude_params:+ - deleted+ feature_flag: heatmaps-mcp+ heatmaps-saved-get:+ operation: saved_retrieve+ enabled: true+ scopes:+ - heatmap:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get a saved heatmap+ description: >+ Get a single saved heatmap by its `short_id`, including per-width render `status`. Poll this after+ `heatmaps-saved-create` until `status` is 'completed'; the rendered page is then viewable by the user in the+ PostHog UI.+ feature_flag: heatmaps-mcp+ heatmaps-saved-list:operation: saved_list- enabled: false- saved-partial-update:- operation: saved_partial_update- enabled: false- saved-regenerate-create:+ enabled: true+ scopes:+ - heatmap:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List saved heatmaps+ description: >+ List saved heatmaps for the project. A saved heatmap pins a page URL plus a set of viewport widths and (for+ type 'screenshot') renders the page so heatmap data can be overlaid on it. Filter by `type`, `status`,+ `created_by`, or a `search` substring on URL/name. The rendered page (screenshot with data overlaid) is+ viewable by the user in the PostHog UI.+ feature_flag: heatmaps-mcp+ heatmaps-saved-regenerate:operation: saved_regenerate_create- enabled: false- saved-retrieve:- operation: saved_retrieve+ enabled: true+ scopes:+ - heatmap:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: false+ title: Regenerate a saved heatmap screenshot+ description: >+ Re-run screenshot generation for a saved heatmap of type 'screenshot' by its `short_id`. Clears the existing+ renders and re-renders at every target width; `status` returns to 'processing'. Use when a page has changed+ or a render failed.+ feature_flag: heatmaps-mcp+ heatmaps-saved-update:+ operation: saved_partial_update+ enabled: true+ scopes:+ - heatmap:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Update a saved heatmap+ description: >+ Update a saved heatmap by its `short_id`. Send only the fields to change — rename via `name`, change+ `widths`, or soft-delete by setting `deleted: true` (deletion goes through this update, not a destroy call).+ Changing the `url` of a 'screenshot' heatmap triggers a fresh render.+ feature_flag: heatmaps-mcp+ saved-destroy:+ operation: saved_destroyenabled: falseweb-analytics-filter-presets-create:operation: web_analytics_filter_presets_creatediff --git a/products/web_analytics/skills/assessing-heatmaps/SKILL.md b/products/web_analytics/skills/assessing-heatmaps/SKILL.mdnew file mode 100644index 000000000000..c842e395766f--- /dev/null+++ b/products/web_analytics/skills/assessing-heatmaps/SKILL.md@@ -0,0 +1,143 @@+---+name: assessing-heatmaps+description: "Assesses what a page's heatmap is telling you and recommends concrete changes. Pulls click / rageclick / scroll-depth data for a URL, names the hot elements by cross-referencing autocapture events on the same page, and can create a saved heatmap the user opens in PostHog, then summarizes the behavior and proposes improvements.\nTRIGGER when: user asks what a heatmap shows, why people aren't clicking something, where users rage-click, how far they scroll, what to change on a page based on heatmap/click data, or to 'analyze/assess/review the heatmap' for a URL.\nDO NOT TRIGGER when: the user only wants to create a saved heatmap screenshot with no analysis (use heatmaps-saved-create directly), or is asking about session replay in general (use investigating-replay)."+---++# Assessing heatmaps++A heatmap answers "where do people interact with this page?" — clicks, rage clicks, mouse movement, and how+far down they scroll. The data is pure geometry: `pointer_relative_x` (0..1 across the viewport), `pointer_y`+(absolute pixels down the page), and a count per spot. **It does not know what was clicked.** Turning+"lots of clicks at (0.5, 220)" into "lots of clicks on the Pricing nav link" is the whole job, and it comes+from cross-referencing autocapture on the same URL.++## Core principle: coordinates + meaning++You can't see the page — there is no screenshot in your context. A good assessment fuses two sources and+leans on autocapture to supply the layout/identity you can't see:++1. **Heatmap data** — where interactions land and how far people scroll (`heatmaps-list`).+2. **Autocapture** — what element sits under the hot spots, by element text / selector on the same page. This+ is what turns coordinates into meaning; without it you only have dots.++When the user wants to _see_ the heatmap, create a saved heatmap (Step 4) — that renders the page with the+data overlaid for them to open in PostHog. You reason from the data; they look at the picture.++## The flow++### Step 1: Pin the page and window++You need an exact `url_exact` (one page) or a `url_pattern` (regex, to aggregate across query strings). Confirm+the URL with the user if ambiguous. Default to the last 7 days; widen to 30 if volume is low. Heatmap data is+retained for 90 days.++### Step 2: Pull the data++Call `heatmaps-list` once per signal you care about (or query the `heatmaps` table directly via SQL — see the+querying-posthog-data skill, `models-heatmaps`):++- `type: "click"` — the primary "what draws attention" map.+- `type: "rageclick"` — repeated frustrated clicks. **The single strongest "something is broken or+ misleading" signal.** Any meaningful rageclick cluster deserves a callout.+- `type: "scrolldepth"` — how far people get. Use it to find the fold and spot CTAs that sit below where most+ people ever scroll.++Use `aggregation: "unique_visitors"` when you care about how many people (not how many clicks); `total_count`+exaggerates a few heavy clickers.++### Step 2b: Above the fold — read the `fold` summary++For the click types, `heatmaps-list` returns a `fold` object alongside `results`:++- `pct_below_fold` — share of non-fixed interactions that landed **below the user's initial viewport** (they+ had to scroll to reach them). This is one of the highest-value findings: content people actively click that+ sits below the fold is a prime candidate to move up.+- `below_fold_count` / `total_count` — the raw counts behind the percentage (fixed-position elements are+ excluded, since they're always on screen).+- `median_viewport_height` — the typical fold line in CSS pixels, to recommend against.++Report it concretely, e.g. "the fold is ~600px for most visitors, yet 35% of clicks land below it, so users+scroll before interacting — that content is a candidate for the first screen." **Segment by device** with+`viewport_width_min`/`viewport_width_max` (desktop and mobile have very different folds) and read `fold` per+band rather than blending them.++Need a distribution rather than a single percentage (e.g. clicks bucketed by how far below the fold)? Drop to+SQL on the raw `heatmaps` table, which has `y` and `viewport_height` in the same scaled units — see the+querying-posthog-data skill, `models-heatmaps`.++### Step 3: Name the hot elements (autocapture overlap)++For each notable cluster, find what's actually there. Query autocapture on the same URL — either via the+`exploring-autocapture-events` skill or directly:++```sql+SELECT properties.$el_text AS text, count() AS clicks+FROM events+WHERE event = '$autocapture'+ AND properties.$current_url = 'https://example.com/pricing'+ AND timestamp >= now() - INTERVAL 7 DAY+GROUP BY text+ORDER BY clicks DESC+LIMIT 25+```++`elements_chain` gives the selector/DOM path when you need to disambiguate two elements with the same text.+Match autocapture's top elements to the heatmap's hot coordinates: clicks concentrated on something that is+**not** a link or button (plain text, an image, a disabled control) is a classic "users expect this to be+clickable" finding.++### Step 4: Give the user a heatmap to look at (optional)++You can't see the page, but the user can. When a visual would help them follow your findings, create a saved+heatmap so they can open the rendered page with the data overlaid in PostHog:++1. `heatmaps-saved-create` with the page `url` (type defaults to `screenshot`). This enqueues a headless+ render — it is asynchronous. Pass `widths` matching the viewport band you analyzed in Step 2.+2. Poll `heatmaps-saved-get` (by the returned `short_id`) until `status` is `completed`, then tell the user+ it's ready to view in PostHog.++This is for the human's benefit — your own reasoning still comes from the Step 2 data and the Step 3+autocapture identity, not from the picture.++### Step 5: Drill into hotspots (when you need the "why")++For a surprising cluster, `heatmaps-events` returns the individual sessions behind specific `points`. Hand the+session IDs to the `investigating-replay` skill to watch what people actually did.++### Step 6: Summarize and recommend++Produce a short, concrete report:++- **What the heatmap shows** — top engaged elements, dead zones, scroll reach, and the above/below-the-fold+ click split (e.g. "viewport is ~600px for most visitors, yet 35% of clicks land below it").+- **Problems**, ranked by signal strength — rage-click clusters first, then clicks on non-interactive+ elements, then important CTAs sitting below the scroll cliff, then ignored primary actions.+- **Recommendations** tied to evidence — move/raise a CTA above the fold, make a clicked-but-dead element a+ real link, cut competing elements near a rage-click cluster, etc. Every recommendation should cite the+ signal it came from.++## Reading the signals++| Signal | Likely meaning | Typical recommendation |+| ---------------------------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------- |+| Rage clicks on an element | Broken, slow, or looks-clickable-but-isn't | Fix the handler, add feedback, or make it actually interactive |+| Many clicks on non-link text/image | Users expect it to be clickable | Make it a link/button, or remove the affordance |+| Primary CTA gets few clicks | Buried, low-contrast, or out-competed | Raise it, increase contrast, reduce nearby noise |+| Scroll cliff before key content | Content/CTA is below where people stop | Move it up or add a reason to scroll |+| High % of clicks below the fold | Engaged content sits below the initial viewport — users scroll before interacting | Move the most-clicked elements onto the first screen |+| Hot clicks on nav, cold body | Page isn't delivering; people bail to nav | Re-evaluate the page's core content |++## Gotchas++- **Heatmaps must be opted in** (`Team.heatmaps_opt_in`). If `heatmaps-list` returns nothing for a page that+ clearly gets traffic, capture may be off or the URL is wrong — check both before concluding "no+ engagement".+- **Coordinates are scaled** by a factor of 16 in storage; the API already returns CSS-pixel `pointer_y` and+ relative x, so use the API/tool values directly rather than the raw table columns.+- **You can't see the screenshot.** The saved-heatmap render is for the user to open in PostHog; don't claim+ to have looked at the page. Ground every layout claim in autocapture identity + coordinates, not vision.+- **Saved-heatmap rendering is async.** After `heatmaps-saved-create`, poll `heatmaps-saved-get` until+ `status` is `completed` before telling the user it's viewable. Only `screenshot`-type heatmaps render an+ image; `iframe` and `recording` types do not.+- **Mind the viewport.** A desktop click map and a mobile one are different pages' worth of behavior — filter+ with `viewport_width_min`/`viewport_width_max` rather than blending them.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 48cce9e0c26c..d14aa7e76be5 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -2438,6 +2438,111 @@"readOnlyHint": true}},+ "heatmaps-events": {+ "description": "Drill into the individual session interactions behind one or more heatmap coordinates. Pass `points` as a JSON array of the spots you want to inspect (the `pointer_relative_x` / `pointer_y` values from `heatmaps-list`), plus the same page/date filters. Returns the underlying per-session interactions so you can open the session recordings that produced a hotspot.",+ "category": "Web analytics",+ "feature": "web_analytics",+ "summary": "Get sessions behind heatmap coordinates",+ "title": "Get sessions behind heatmap coordinates",+ "required_scopes": ["heatmap:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "heatmaps-mcp"+ },+ "heatmaps-list": {+ "description": "Aggregated heatmap interactions captured on a page. Filter by `url_exact` (one page) or `url_pattern` (regex across pages), a date window (`date_from`/`date_to`, data is retained 90 days), and optionally a viewport range (`viewport_width_min`/`viewport_width_max`, CSS px) to isolate a device class. Set `type` to 'click' (default), 'rageclick', 'mousemove', or 'scrolldepth'. For clicks each result is a point — `pointer_relative_x` (0..1 across the viewport), `pointer_y` (absolute pixels down the page), and a `count`; 'scrolldepth' returns reach buckets instead. For the click types the response also includes a `fold` summary — `pct_below_fold` (share of non-fixed interactions that landed below the user's initial viewport, i.e. required scrolling), `below_fold_count`, `total_count`, and the `median_viewport_height` (the typical fold line in CSS px) — so a high `pct_below_fold` flags engaged content sitting off the first screen. `rageclick` hotspots and shallow scroll depth are the strongest signals that something on the page is confusing or buried. Heatmaps only know coordinates, not what was clicked — cross-reference autocapture events on the same URL to name the elements, and use `heatmaps-events` to jump to the sessions behind a hotspot.",+ "category": "Web analytics",+ "feature": "web_analytics",+ "summary": "List heatmap interactions for a page",+ "title": "List heatmap interactions for a page",+ "required_scopes": ["heatmap:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "heatmaps-mcp"+ },+ "heatmaps-saved-create": {+ "description": "Create a saved heatmap for a page URL. For type 'screenshot' (the default) this enqueues a headless render of the page at each target width — poll `heatmaps-saved-get` until `status` is 'completed'; the rendered page (with data overlaid) is then viewable by the user in the PostHog UI. Provide `widths` (CSS px, 100-3000) to control which viewports are rendered, or omit it for sensible defaults. The URL must be exact — wildcards are not allowed.",+ "category": "Web analytics",+ "feature": "web_analytics",+ "summary": "Create a saved heatmap",+ "title": "Create a saved heatmap",+ "required_scopes": ["heatmap:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "heatmaps-mcp"+ },+ "heatmaps-saved-get": {+ "description": "Get a single saved heatmap by its `short_id`, including per-width render `status`. Poll this after `heatmaps-saved-create` until `status` is 'completed'; the rendered page is then viewable by the user in the PostHog UI.",+ "category": "Web analytics",+ "feature": "web_analytics",+ "summary": "Get a saved heatmap",+ "title": "Get a saved heatmap",+ "required_scopes": ["heatmap:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "heatmaps-mcp"+ },+ "heatmaps-saved-list": {+ "description": "List saved heatmaps for the project. A saved heatmap pins a page URL plus a set of viewport widths and (for type 'screenshot') renders the page so heatmap data can be overlaid on it. Filter by `type`, `status`, `created_by`, or a `search` substring on URL/name. The rendered page (screenshot with data overlaid) is viewable by the user in the PostHog UI.",+ "category": "Web analytics",+ "feature": "web_analytics",+ "summary": "List saved heatmaps",+ "title": "List saved heatmaps",+ "required_scopes": ["heatmap:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "heatmaps-mcp"+ },+ "heatmaps-saved-regenerate": {+ "description": "Re-run screenshot generation for a saved heatmap of type 'screenshot' by its `short_id`. Clears the existing renders and re-renders at every target width; `status` returns to 'processing'. Use when a page has changed or a render failed.",+ "category": "Web analytics",+ "feature": "web_analytics",+ "summary": "Regenerate a saved heatmap screenshot",+ "title": "Regenerate a saved heatmap screenshot",+ "required_scopes": ["heatmap:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "heatmaps-mcp"+ },+ "heatmaps-saved-update": {+ "description": "Update a saved heatmap by its `short_id`. Send only the fields to change — rename via `name`, change `widths`, or soft-delete by setting `deleted: true` (deletion goes through this update, not a destroy call). Changing the `url` of a 'screenshot' heatmap triggers a fresh render.",+ "category": "Web analytics",+ "feature": "web_analytics",+ "summary": "Update a saved heatmap",+ "title": "Update a saved heatmap",+ "required_scopes": ["heatmap:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "heatmaps-mcp"+ },"hog-flows-logs-retrieve": {"description": "Retrieve execution logs for a specific workflow by ID. Returns log entries with timestamp, level (DEBUG, LOG, INFO, WARN, ERROR), and message. Use to debug why a workflow is failing or not producing expected results. Supports filtering by log level, text search, time range (after/before), and pagination via limit.","category": "Workflows",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 9d097746b9be..631a4d0df5db 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -2678,6 +2678,111 @@"readOnlyHint": true}},+ "heatmaps-events": {+ "description": "Drill into the individual session interactions behind one or more heatmap coordinates. Pass `points` as a JSON array of the spots you want to inspect (the `pointer_relative_x` / `pointer_y` values from `heatmaps-list`), plus the same page/date filters. Returns the underlying per-session interactions so you can open the session recordings that produced a hotspot.",+ "category": "Web analytics",+ "feature": "web_analytics",+ "summary": "Get sessions behind heatmap coordinates",+ "title": "Get sessions behind heatmap coordinates",+ "required_scopes": ["heatmap:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "heatmaps-mcp"+ },+ "heatmaps-list": {+ "description": "Aggregated heatmap interactions captured on a page. Filter by `url_exact` (one page) or `url_pattern` (regex across pages), a date window (`date_from`/`date_to`, data is retained 90 days), and optionally a viewport range (`viewport_width_min`/`viewport_width_max`, CSS px) to isolate a device class. Set `type` to 'click' (default), 'rageclick', 'mousemove', or 'scrolldepth'. For clicks each result is a point — `pointer_relative_x` (0..1 across the viewport), `pointer_y` (absolute pixels down the page), and a `count`; 'scrolldepth' returns reach buckets instead. For the click types the response also includes a `fold` summary — `pct_below_fold` (share of non-fixed interactions that landed below the user's initial viewport, i.e. required scrolling), `below_fold_count`, `total_count`, and the `median_viewport_height` (the typical fold line in CSS px) — so a high `pct_below_fold` flags engaged content sitting off the first screen. `rageclick` hotspots and shallow scroll depth are the strongest signals that something on the page is confusing or buried. Heatmaps only know coordinates, not what was clicked — cross-reference autocapture events on the same URL to name the elements, and use `heatmaps-events` to jump to the sessions behind a hotspot.",+ "category": "Web analytics",+ "feature": "web_analytics",+ "summary": "List heatmap interactions for a page",+ "title": "List heatmap interactions for a page",+ "required_scopes": ["heatmap:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "heatmaps-mcp"+ },+ "heatmaps-saved-create": {+ "description": "Create a saved heatmap for a page URL. For type 'screenshot' (the default) this enqueues a headless render of the page at each target width — poll `heatmaps-saved-get` until `status` is 'completed'; the rendered page (with data overlaid) is then viewable by the user in the PostHog UI. Provide `widths` (CSS px, 100-3000) to control which viewports are rendered, or omit it for sensible defaults. The URL must be exact — wildcards are not allowed.",+ "category": "Web analytics",+ "feature": "web_analytics",+ "summary": "Create a saved heatmap",+ "title": "Create a saved heatmap",+ "required_scopes": ["heatmap:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "heatmaps-mcp"+ },+ "heatmaps-saved-get": {+ "description": "Get a single saved heatmap by its `short_id`, including per-width render `status`. Poll this after `heatmaps-saved-create` until `status` is 'completed'; the rendered page is then viewable by the user in the PostHog UI.",+ "category": "Web analytics",+ "feature": "web_analytics",+ "summary": "Get a saved heatmap",+ "title": "Get a saved heatmap",+ "required_scopes": ["heatmap:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "heatmaps-mcp"+ },+ "heatmaps-saved-list": {+ "description": "List saved heatmaps for the project. A saved heatmap pins a page URL plus a set of viewport widths and (for type 'screenshot') renders the page so heatmap data can be overlaid on it. Filter by `type`, `status`, `created_by`, or a `search` substring on URL/name. The rendered page (screenshot with data overlaid) is viewable by the user in the PostHog UI.",+ "category": "Web analytics",+ "feature": "web_analytics",+ "summary": "List saved heatmaps",+ "title": "List saved heatmaps",+ "required_scopes": ["heatmap:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "heatmaps-mcp"+ },+ "heatmaps-saved-regenerate": {+ "description": "Re-run screenshot generation for a saved heatmap of type 'screenshot' by its `short_id`. Clears the existing renders and re-renders at every target width; `status` returns to 'processing'. Use when a page has changed or a render failed.",+ "category": "Web analytics",+ "feature": "web_analytics",+ "summary": "Regenerate a saved heatmap screenshot",+ "title": "Regenerate a saved heatmap screenshot",+ "required_scopes": ["heatmap:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "heatmaps-mcp"+ },+ "heatmaps-saved-update": {+ "description": "Update a saved heatmap by its `short_id`. Send only the fields to change — rename via `name`, change `widths`, or soft-delete by setting `deleted: true` (deletion goes through this update, not a destroy call). Changing the `url` of a 'screenshot' heatmap triggers a fresh render.",+ "category": "Web analytics",+ "feature": "web_analytics",+ "summary": "Update a saved heatmap",+ "title": "Update a saved heatmap",+ "required_scopes": ["heatmap:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "heatmaps-mcp"+ },"hog-flows-logs-retrieve": {"description": "Retrieve execution logs for a specific workflow by ID. Returns log entries with timestamp, level (DEBUG, LOG, INFO, WARN, ERROR), and message. Use to debug why a workflow is failing or not producing expected results. Supports filtering by log level, text search, time range (after/before), and pagination via limit.","category": "Workflows",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ee4a852616a4..04d4dd9da197 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18276,6 +18276,37 @@ export namespace Schemas {readonly resolved_at: string | null;}+ export interface HeatmapEventItem {+ /** @nullable */+ session_id?: string | null;+ distinct_id: string;+ timestamp: string;+ pointer_relative_x: number;+ pointer_y: number;+ current_url: string;+ type: string;+ }++ export interface HeatmapEventsResponse {+ results: HeatmapEventItem[];+ total_count: number;+ has_more: boolean;+ }++ export interface HeatmapFoldSummary {+ /** Number of non-fixed interactions of this type on the page in the window (the population the above/below-the-fold split applies to; fixed-position elements are excluded since they're always on screen). */+ total_count: number;+ /** How many of those interactions happened below the user's initial viewport — i.e. they had to scroll to reach them. */+ below_fold_count: number;+ /** Percentage of non-fixed interactions that were below the initial viewport (0-100). A high value means engaged content sits off the first screen and is a candidate to move up. */+ pct_below_fold: number;+ /**+ * Median viewport height in CSS pixels across the matched interactions — the typical fold line to recommend against. Null when there are no interactions.+ * @nullable+ */+ median_viewport_height: number | null;+ }+export interface HeatmapResponseItem {count: number;pointer_y: number;@@ -18283,17 +18314,15 @@ export namespace Schemas {pointer_target_fixed: boolean;}- export type HeatmapScreenshotResponseSnapshotsItem = { [key: string]: unknown };-/*** * `screenshot` - Screenshot* `iframe` - Iframe* `recording` - Recording*/- export type HeatmapScreenshotResponseTypeEnum = typeof HeatmapScreenshotResponseTypeEnum[keyof typeof HeatmapScreenshotResponseTypeEnum];+ export type HeatmapType = typeof HeatmapType[keyof typeof HeatmapType];- export const HeatmapScreenshotResponseTypeEnum = {+ export const HeatmapType = {Screenshot: 'screenshot',Iframe: 'iframe',Recording: 'recording',@@ -18313,37 +18342,68 @@ export namespace Schemas {Failed: 'failed',} as const;+ export interface HeatmapSnapshotMetadata {+ /** Viewport width (CSS pixels) this screenshot was rendered at. */+ width: number;+ /** Whether the rendered image for this width is ready to fetch from the content endpoint. */+ has_content: boolean;+ }+export interface HeatmapScreenshotResponse {readonly id: string;+ /** Short, URL-safe identifier used as the lookup key for saved-heatmap routes. */readonly short_id: string;/**+ * Human-readable label for the saved heatmap.* @maxLength 400* @nullable*/name?: string | null;- /** @maxLength 2000 */+ /**+ * The page URL this saved heatmap renders and overlays data on.+ * @maxLength 2000+ */url: string;/**- * URL for fetching heatmap data+ * URL whose heatmap data is overlaid on the screenshot (defaults to 'url').* @maxLength 2000* @nullable*/data_url?: string | null;+ /** Viewport widths (CSS pixels) the screenshot is rendered at. */target_widths?: unknown;- type?: HeatmapScreenshotResponseTypeEnum;+ /** Render mode: 'screenshot', 'iframe', or 'recording'.++ * `screenshot` - Screenshot+ * `iframe` - Iframe+ * `recording` - Recording */+ type?: HeatmapType;+ /** Screenshot generation status: 'processing', 'completed', or 'failed'.++ * `processing` - Processing+ * `completed` - Completed+ * `failed` - Failed */readonly status: HeatmapScreenshotResponseStatusEnum;+ /** Whether at least one rendered image is ready to fetch. */readonly has_content: boolean;- readonly snapshots: readonly HeatmapScreenshotResponseSnapshotsItem[];+ /** Per-width render metadata. Fetch the actual image bytes for a width from the content endpoint. */+ readonly snapshots: readonly HeatmapSnapshotMetadata[];+ /** Soft-delete flag; deleted heatmaps are hidden from the list. */deleted?: boolean;readonly created_by: UserBasic;readonly created_at: string;readonly updated_at: string;- /** @nullable */+ /**+ * Error detail when screenshot generation failed, otherwise null.+ * @nullable+ */readonly exception: string | null;}export interface HeatmapsResponse {results: HeatmapResponseItem[];+ /** Above/below-the-fold summary for the returned interactions. Present for click/rageclick/mousemove; omitted for scrolldepth. */+ fold?: HeatmapFoldSummary | null;}export type HideViewedRecordings = typeof HideViewedRecordings[keyof typeof HideViewedRecordings];@@ -23442,24 +23502,6 @@ export namespace Schemas {results: HealthIssue[];}- export interface PaginatedHeatmapScreenshotResponseList {- count: number;- /** @nullable */- next?: string | null;- /** @nullable */- previous?: string | null;- results: HeatmapScreenshotResponse[];- }-- export interface PaginatedHeatmapsResponseList {- count: number;- /** @nullable */- next?: string | null;- /** @nullable */- previous?: string | null;- results: HeatmapsResponse[];- }-export interface PaginatedHogFlowMinimalList {count: number;/** @nullable */@@ -28705,37 +28747,6 @@ export namespace Schemas {readonly resolved_at?: string | null;}- export type PatchedHeatmapScreenshotResponseSnapshotsItem = { [key: string]: unknown };-- export interface PatchedHeatmapScreenshotResponse {- readonly id?: string;- readonly short_id?: string;- /**- * @maxLength 400- * @nullable- */- name?: string | null;- /** @maxLength 2000 */- url?: string;- /**- * URL for fetching heatmap data- * @maxLength 2000- * @nullable- */- data_url?: string | null;- target_widths?: unknown;- type?: HeatmapScreenshotResponseTypeEnum;- readonly status?: HeatmapScreenshotResponseStatusEnum;- readonly has_content?: boolean;- readonly snapshots?: readonly PatchedHeatmapScreenshotResponseSnapshotsItem[];- deleted?: boolean;- readonly created_by?: UserBasic;- readonly created_at?: string;- readonly updated_at?: string;- /** @nullable */- readonly exception?: string | null;- }-/*** Variable: {key, type: string|number|boolean, default}.*/@@ -30793,6 +30804,39 @@ export namespace Schemas {readonly updated_at?: string;}+ export interface PatchedSavedHeatmapRequest {+ /**+ * Human-readable label for the saved heatmap.+ * @maxLength 400+ * @nullable+ */+ name?: string | null;+ /**+ * Exact page URL to render and overlay heatmap data on. Wildcards are not allowed.+ * @maxLength 2000+ */+ url?: string;+ /**+ * URL whose heatmap data is overlaid on the screenshot. Defaults to 'url' when omitted.+ * @maxLength 2000+ * @nullable+ */+ data_url?: string | null;+ /**+ * Viewport widths (px, 100-3000) to render the heatmap screenshot at — one render per width. Defaults to [320, 375, 425, 768, 1024, 1440, 1920] when omitted. At most 16 widths.+ * @maxItems 16+ */+ widths?: number[];+ /** Render mode: 'screenshot' (renders the page headlessly, default), 'iframe', or 'recording'. Only 'screenshot' generates image bytes.++ * `screenshot` - Screenshot+ * `iframe` - Iframe+ * `recording` - Recording */+ type?: HeatmapType;+ /** Set true to soft-delete the saved heatmap. */+ deleted?: boolean;+ }+export interface PatchedScheduledChange {readonly id?: number;readonly team_id?: number;@@ -36797,6 +36841,45 @@ export namespace Schemas {readonly updated_at: string;}+ export interface SavedHeatmapListResponse {+ results: HeatmapScreenshotResponse[];+ /** Total number of saved heatmaps matching the filters. */+ count: number;+ }++ export interface SavedHeatmapRequest {+ /**+ * Human-readable label for the saved heatmap.+ * @maxLength 400+ * @nullable+ */+ name?: string | null;+ /**+ * Exact page URL to render and overlay heatmap data on. Wildcards are not allowed.+ * @maxLength 2000+ */+ url: string;+ /**+ * URL whose heatmap data is overlaid on the screenshot. Defaults to 'url' when omitted.+ * @maxLength 2000+ * @nullable+ */+ data_url?: string | null;+ /**+ * Viewport widths (px, 100-3000) to render the heatmap screenshot at — one render per width. Defaults to [320, 375, 425, 768, 1024, 1440, 1920] when omitted. At most 16 widths.+ * @maxItems 16+ */+ widths?: number[];+ /** Render mode: 'screenshot' (renders the page headlessly, default), 'iframe', or 'recording'. Only 'screenshot' generates image bytes.++ * `screenshot` - Screenshot+ * `iframe` - Iframe+ * `recording` - Recording */+ type?: HeatmapType;+ /** Set true to soft-delete the saved heatmap. */+ deleted?: boolean;+ }+export interface ScoreDefinitionCreate {/*** Human-readable scorer name.@@ -41568,17 +41651,161 @@ export namespace Schemas {offset?: number;};+ export type EnvironmentsHeatmapScreenshotsContentRetrieveParams = {+ /**+ * Viewport width (CSS pixels) to fetch. Defaults to 1024. If no exact render exists for this width the closest available one is returned.+ */+ width?: number;+ };+export type EnvironmentsHeatmapsListParams = {/**- * Number of results to return per page.+ * How to aggregate counts: 'total_count' (every interaction, default) or 'unique_visitors' (distinct people).++ * `unique_visitors` - unique_visitors+ * `total_count` - total_count+ * @minLength 1+ */+ aggregation?: EnvironmentsHeatmapsListAggregation;+ /**+ * JSON array of cohort IDs (e.g. '[123, 456]') to restrict results to people in those cohorts. Feature-flagged; ignored when the cohort filter is not enabled for the caller.+ * @nullable+ */+ cohort_ids?: string | null;+ /**+ * Start of the window. Relative (e.g. '-7d', '-30d', '-1mStart') or an absolute 'YYYY-MM-DD' date. Defaults to '-7d'. Heatmap data is retained for 90 days.+ * @minLength 1+ */+ date_from?: string;+ /**+ * End of the window, inclusive. Relative or absolute 'YYYY-MM-DD'. Defaults to today.+ * @minLength 1+ */+ date_to?: string;+ /**+ * When true, exclude sessions from internal/test accounts using the project's test-account filters.+ * @nullable+ */+ filter_test_accounts?: boolean | null;+ /**+ * When true (default), drop interactions recorded at the (0, 0) origin, which are usually noise.+ */+ hide_zero_coordinates?: boolean;+ /**+ * The interaction type to return. One of: 'click' (default), 'rageclick', 'mousemove', or 'scrolldepth'. Scrolldepth returns scroll buckets instead of x/y coordinates.+ * @minLength 1+ */+ type?: string;+ /**+ * Match a single page by exact URL (trailing slash is ignored). Mutually exclusive with url_pattern.+ * @minLength 1+ */+ url_exact?: string;+ /**+ * Match pages by regex against the full current_url (anchored automatically). Use this to aggregate across query strings or path segments. Mutually exclusive with url_exact.+ * @minLength 1+ */+ url_pattern?: string;+ /**+ * Only include interactions captured at a viewport at most this wide, in CSS pixels.+ */+ viewport_width_max?: number;+ /**+ * Only include interactions captured at a viewport at least this wide, in CSS pixels. Use with viewport_width_max to isolate a device class (e.g. 360-768 for mobile).+ */+ viewport_width_min?: number;+ };++ export type EnvironmentsHeatmapsListAggregation = typeof EnvironmentsHeatmapsListAggregation[keyof typeof EnvironmentsHeatmapsListAggregation];+++ export const EnvironmentsHeatmapsListAggregation = {+ UniqueVisitors: 'unique_visitors',+ TotalCount: 'total_count',+ } as const;++ export type EnvironmentsHeatmapsEventsRetrieveParams = {+ /**+ * How to aggregate counts: 'total_count' (every interaction, default) or 'unique_visitors' (distinct people).++ * `unique_visitors` - unique_visitors+ * `total_count` - total_count+ * @minLength 1+ */+ aggregation?: EnvironmentsHeatmapsEventsRetrieveAggregation;+ /**+ * JSON array of cohort IDs (e.g. '[123, 456]') to restrict results to people in those cohorts. Feature-flagged; ignored when the cohort filter is not enabled for the caller.+ * @nullable+ */+ cohort_ids?: string | null;+ /**+ * Start of the window. Relative (e.g. '-7d', '-30d', '-1mStart') or an absolute 'YYYY-MM-DD' date. Defaults to '-7d'. Heatmap data is retained for 90 days.+ * @minLength 1+ */+ date_from?: string;+ /**+ * End of the window, inclusive. Relative or absolute 'YYYY-MM-DD'. Defaults to today.+ * @minLength 1+ */+ date_to?: string;+ /**+ * When true, exclude sessions from internal/test accounts using the project's test-account filters.+ * @nullable+ */+ filter_test_accounts?: boolean | null;+ /**+ * When true (default), drop interactions recorded at the (0, 0) origin, which are usually noise.+ */+ hide_zero_coordinates?: boolean;+ /**+ * Maximum interactions to return (1-100).+ * @minimum 1+ * @maximum 100*/limit?: number;/**- * The initial index from which to return the results.+ * Number of interactions to skip, for pagination.+ * @minimum 0*/offset?: number;+ /**+ * JSON array of the heatmap coordinates to drill into, e.g. '[{"x": 0.5, "y": 100}]'. Each point needs 'x' (relative x, 0..1) and 'y' (absolute client-y pixels) matching values returned by the heatmaps list endpoint; an optional 'target_fixed' boolean matches fixed-position elements. Returns the individual session interactions behind those spots.+ * @minLength 1+ */+ points: string;+ /**+ * The interaction type to return. One of: 'click' (default), 'rageclick', 'mousemove', or 'scrolldepth'. Scrolldepth returns scroll buckets instead of x/y coordinates.+ * @minLength 1+ */+ type?: string;+ /**+ * Match a single page by exact URL (trailing slash is ignored). Mutually exclusive with url_pattern.+ * @minLength 1+ */+ url_exact?: string;+ /**+ * Match pages by regex against the full current_url (anchored automatically). Use this to aggregate across query strings or path segments. Mutually exclusive with url_exact.+ * @minLength 1+ */+ url_pattern?: string;+ /**+ * Only include interactions captured at a viewport at most this wide, in CSS pixels.+ */+ viewport_width_max?: number;+ /**+ * Only include interactions captured at a viewport at least this wide, in CSS pixels. Use with viewport_width_max to isolate a device class (e.g. 360-768 for mobile).+ */+ viewport_width_min?: number;};+ export type EnvironmentsHeatmapsEventsRetrieveAggregation = typeof EnvironmentsHeatmapsEventsRetrieveAggregation[keyof typeof EnvironmentsHeatmapsEventsRetrieveAggregation];+++ export const EnvironmentsHeatmapsEventsRetrieveAggregation = {+ UniqueVisitors: 'unique_visitors',+ TotalCount: 'total_count',+ } as const;+export type EnvironmentsHogFlowTemplatesListParams = {/*** Number of results to return per page.@@ -43621,13 +43848,37 @@ export namespace Schemas {export type EnvironmentsSavedListParams = {/**- * Number of results to return per page.+ * Filter by the creating user's ID.+ */+ created_by?: number;+ /**+ * Maximum saved heatmaps to return.*/limit?: number;/**- * The initial index from which to return the results.+ * Number to skip, for pagination.*/offset?: number;+ /**+ * Field to order by, e.g. '-updated_at' (default) or 'created_at'.+ * @minLength 1+ */+ order?: string;+ /**+ * Case-insensitive substring match on URL or name.+ * @minLength 1+ */+ search?: string;+ /**+ * Filter by generation status: 'processing', 'completed', or 'failed'.+ * @minLength 1+ */+ status?: string;+ /**+ * Filter by render mode: 'screenshot', 'iframe', or 'recording'.+ * @minLength 1+ */+ type?: string;};export type EnvironmentsSessionRecordingExternalReferencesListParams = {@@ -46965,17 +47216,161 @@ export namespace Schemas {offset?: number;};+ export type HeatmapScreenshotsContentRetrieveParams = {+ /**+ * Viewport width (CSS pixels) to fetch. Defaults to 1024. If no exact render exists for this width the closest available one is returned.+ */+ width?: number;+ };+export type HeatmapsListParams = {/**- * Number of results to return per page.+ * How to aggregate counts: 'total_count' (every interaction, default) or 'unique_visitors' (distinct people).++ * `unique_visitors` - unique_visitors+ * `total_count` - total_count+ * @minLength 1+ */+ aggregation?: HeatmapsListAggregation;+ /**+ * JSON array of cohort IDs (e.g. '[123, 456]') to restrict results to people in those cohorts. Feature-flagged; ignored when the cohort filter is not enabled for the caller.+ * @nullable+ */+ cohort_ids?: string | null;+ /**+ * Start of the window. Relative (e.g. '-7d', '-30d', '-1mStart') or an absolute 'YYYY-MM-DD' date. Defaults to '-7d'. Heatmap data is retained for 90 days.+ * @minLength 1+ */+ date_from?: string;+ /**+ * End of the window, inclusive. Relative or absolute 'YYYY-MM-DD'. Defaults to today.+ * @minLength 1+ */+ date_to?: string;+ /**+ * When true, exclude sessions from internal/test accounts using the project's test-account filters.+ * @nullable+ */+ filter_test_accounts?: boolean | null;+ /**+ * When true (default), drop interactions recorded at the (0, 0) origin, which are usually noise.+ */+ hide_zero_coordinates?: boolean;+ /**+ * The interaction type to return. One of: 'click' (default), 'rageclick', 'mousemove', or 'scrolldepth'. Scrolldepth returns scroll buckets instead of x/y coordinates.+ * @minLength 1+ */+ type?: string;+ /**+ * Match a single page by exact URL (trailing slash is ignored). Mutually exclusive with url_pattern.+ * @minLength 1+ */+ url_exact?: string;+ /**+ * Match pages by regex against the full current_url (anchored automatically). Use this to aggregate across query strings or path segments. Mutually exclusive with url_exact.+ * @minLength 1+ */+ url_pattern?: string;+ /**+ * Only include interactions captured at a viewport at most this wide, in CSS pixels.+ */+ viewport_width_max?: number;+ /**+ * Only include interactions captured at a viewport at least this wide, in CSS pixels. Use with viewport_width_max to isolate a device class (e.g. 360-768 for mobile).+ */+ viewport_width_min?: number;+ };++ export type HeatmapsListAggregation = typeof HeatmapsListAggregation[keyof typeof HeatmapsListAggregation];+++ export const HeatmapsListAggregation = {+ UniqueVisitors: 'unique_visitors',+ TotalCount: 'total_count',+ } as const;++ export type HeatmapsEventsRetrieveParams = {+ /**+ * How to aggregate counts: 'total_count' (every interaction, default) or 'unique_visitors' (distinct people).++ * `unique_visitors` - unique_visitors+ * `total_count` - total_count+ * @minLength 1+ */+ aggregation?: HeatmapsEventsRetrieveAggregation;+ /**+ * JSON array of cohort IDs (e.g. '[123, 456]') to restrict results to people in those cohorts. Feature-flagged; ignored when the cohort filter is not enabled for the caller.+ * @nullable+ */+ cohort_ids?: string | null;+ /**+ * Start of the window. Relative (e.g. '-7d', '-30d', '-1mStart') or an absolute 'YYYY-MM-DD' date. Defaults to '-7d'. Heatmap data is retained for 90 days.+ * @minLength 1+ */+ date_from?: string;+ /**+ * End of the window, inclusive. Relative or absolute 'YYYY-MM-DD'. Defaults to today.+ * @minLength 1+ */+ date_to?: string;+ /**+ * When true, exclude sessions from internal/test accounts using the project's test-account filters.+ * @nullable+ */+ filter_test_accounts?: boolean | null;+ /**+ * When true (default), drop interactions recorded at the (0, 0) origin, which are usually noise.+ */+ hide_zero_coordinates?: boolean;+ /**+ * Maximum interactions to return (1-100).+ * @minimum 1+ * @maximum 100*/limit?: number;/**- * The initial index from which to return the results.+ * Number of interactions to skip, for pagination.+ * @minimum 0*/offset?: number;+ /**+ * JSON array of the heatmap coordinates to drill into, e.g. '[{"x": 0.5, "y": 100}]'. Each point needs 'x' (relative x, 0..1) and 'y' (absolute client-y pixels) matching values returned by the heatmaps list endpoint; an optional 'target_fixed' boolean matches fixed-position elements. Returns the individual session interactions behind those spots.+ * @minLength 1+ */+ points: string;+ /**+ * The interaction type to return. One of: 'click' (default), 'rageclick', 'mousemove', or 'scrolldepth'. Scrolldepth returns scroll buckets instead of x/y coordinates.+ * @minLength 1+ */+ type?: string;+ /**+ * Match a single page by exact URL (trailing slash is ignored). Mutually exclusive with url_pattern.+ * @minLength 1+ */+ url_exact?: string;+ /**+ * Match pages by regex against the full current_url (anchored automatically). Use this to aggregate across query strings or path segments. Mutually exclusive with url_exact.+ * @minLength 1+ */+ url_pattern?: string;+ /**+ * Only include interactions captured at a viewport at most this wide, in CSS pixels.+ */+ viewport_width_max?: number;+ /**+ * Only include interactions captured at a viewport at least this wide, in CSS pixels. Use with viewport_width_max to isolate a device class (e.g. 360-768 for mobile).+ */+ viewport_width_min?: number;};+ export type HeatmapsEventsRetrieveAggregation = typeof HeatmapsEventsRetrieveAggregation[keyof typeof HeatmapsEventsRetrieveAggregation];+++ export const HeatmapsEventsRetrieveAggregation = {+ UniqueVisitors: 'unique_visitors',+ TotalCount: 'total_count',+ } as const;+export type HogFlowTemplatesListParams = {/*** Number of results to return per page.@@ -49293,13 +49688,37 @@ export namespace Schemas {export type SavedListParams = {/**- * Number of results to return per page.+ * Filter by the creating user's ID.+ */+ created_by?: number;+ /**+ * Maximum saved heatmaps to return.*/limit?: number;/**- * The initial index from which to return the results.+ * Number to skip, for pagination.*/offset?: number;+ /**+ * Field to order by, e.g. '-updated_at' (default) or 'created_at'.+ * @minLength 1+ */+ order?: string;+ /**+ * Case-insensitive substring match on URL or name.+ * @minLength 1+ */+ search?: string;+ /**+ * Filter by generation status: 'processing', 'completed', or 'failed'.+ * @minLength 1+ */+ status?: string;+ /**+ * Filter by render mode: 'screenshot', 'iframe', or 'recording'.+ * @minLength 1+ */+ type?: string;};export type ScheduledChangesListParams = {diff --git a/services/mcp/src/generated/web_analytics/api.ts b/services/mcp/src/generated/web_analytics/api.tsindex 5cc318243f58..85761b0c8331 100644--- a/services/mcp/src/generated/web_analytics/api.ts+++ b/services/mcp/src/generated/web_analytics/api.ts@@ -3,11 +3,355 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 1 enabled ops+ * PostHog API - MCP 8 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'+/**+ * Aggregated heatmap interactions for a page. For type 'click'/'rageclick'/'mousemove' each result is a point with relative x, absolute client-y, and a count. For type 'scrolldepth' the response is scroll-depth buckets instead (cumulative reach down the page).+ */+export const HeatmapsListParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const heatmapsListQueryAggregationDefault = `total_count`+export const heatmapsListQueryDateFromDefault = `-7d`++export const heatmapsListQueryHideZeroCoordinatesDefault = true+export const heatmapsListQueryTypeDefault = `click`++export const HeatmapsListQueryParams = /* @__PURE__ */ zod.object({+ aggregation: zod+ .enum(['unique_visitors', 'total_count'])+ .default(heatmapsListQueryAggregationDefault)+ .describe(+ "How to aggregate counts: 'total_count' (every interaction, default) or 'unique_visitors' (distinct people).\n\n* `unique_visitors` - unique_visitors\n* `total_count` - total_count"+ ),+ cohort_ids: zod+ .string()+ .nullish()+ .describe(+ "JSON array of cohort IDs (e.g. '[123, 456]') to restrict results to people in those cohorts. Feature-flagged; ignored when the cohort filter is not enabled for the caller."+ ),+ date_from: zod+ .string()+ .min(1)+ .default(heatmapsListQueryDateFromDefault)+ .describe(+ "Start of the window. Relative (e.g. '-7d', '-30d', '-1mStart') or an absolute 'YYYY-MM-DD' date. Defaults to '-7d'. Heatmap data is retained for 90 days."+ ),+ date_to: zod+ .string()+ .min(1)+ .optional()+ .describe("End of the window, inclusive. Relative or absolute 'YYYY-MM-DD'. Defaults to today."),+ filter_test_accounts: zod+ .boolean()+ .nullish()+ .describe("When true, exclude sessions from internal/test accounts using the project's test-account filters."),+ hide_zero_coordinates: zod+ .boolean()+ .default(heatmapsListQueryHideZeroCoordinatesDefault)+ .describe('When true (default), drop interactions recorded at the (0, 0) origin, which are usually noise.'),+ type: zod+ .string()+ .min(1)+ .default(heatmapsListQueryTypeDefault)+ .describe(+ "The interaction type to return. One of: 'click' (default), 'rageclick', 'mousemove', or 'scrolldepth'. Scrolldepth returns scroll buckets instead of x/y coordinates."+ ),+ url_exact: zod+ .string()+ .min(1)+ .optional()+ .describe('Match a single page by exact URL (trailing slash is ignored). Mutually exclusive with url_pattern.'),+ url_pattern: zod+ .string()+ .min(1)+ .optional()+ .describe(+ 'Match pages by regex against the full current_url (anchored automatically). Use this to aggregate across query strings or path segments. Mutually exclusive with url_exact.'+ ),+ viewport_width_max: zod+ .number()+ .optional()+ .describe('Only include interactions captured at a viewport at most this wide, in CSS pixels.'),+ viewport_width_min: zod+ .number()+ .optional()+ .describe(+ 'Only include interactions captured at a viewport at least this wide, in CSS pixels. Use with viewport_width_max to isolate a device class (e.g. 360-768 for mobile).'+ ),+})++/**+ * Drill into the individual session interactions behind one or more heatmap coordinates. Pass the 'points' you want to inspect (from the heatmaps list response) to get the underlying per-session events, so you can jump to the session recordings that produced a hotspot.+ */+export const HeatmapsEventsRetrieveParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const heatmapsEventsRetrieveQueryAggregationDefault = `total_count`+export const heatmapsEventsRetrieveQueryDateFromDefault = `-7d`++export const heatmapsEventsRetrieveQueryHideZeroCoordinatesDefault = true+export const heatmapsEventsRetrieveQueryLimitDefault = 50+export const heatmapsEventsRetrieveQueryLimitMax = 100++export const heatmapsEventsRetrieveQueryOffsetDefault = 0+export const heatmapsEventsRetrieveQueryOffsetMin = 0++export const heatmapsEventsRetrieveQueryTypeDefault = `click`++export const HeatmapsEventsRetrieveQueryParams = /* @__PURE__ */ zod.object({+ aggregation: zod+ .enum(['unique_visitors', 'total_count'])+ .default(heatmapsEventsRetrieveQueryAggregationDefault)+ .describe(+ "How to aggregate counts: 'total_count' (every interaction, default) or 'unique_visitors' (distinct people).\n\n* `unique_visitors` - unique_visitors\n* `total_count` - total_count"+ ),+ cohort_ids: zod+ .string()+ .nullish()+ .describe(+ "JSON array of cohort IDs (e.g. '[123, 456]') to restrict results to people in those cohorts. Feature-flagged; ignored when the cohort filter is not enabled for the caller."+ ),+ date_from: zod+ .string()+ .min(1)+ .default(heatmapsEventsRetrieveQueryDateFromDefault)+ .describe(+ "Start of the window. Relative (e.g. '-7d', '-30d', '-1mStart') or an absolute 'YYYY-MM-DD' date. Defaults to '-7d'. Heatmap data is retained for 90 days."+ ),+ date_to: zod+ .string()+ .min(1)+ .optional()+ .describe("End of the window, inclusive. Relative or absolute 'YYYY-MM-DD'. Defaults to today."),+ filter_test_accounts: zod+ .boolean()+ .nullish()+ .describe("When true, exclude sessions from internal/test accounts using the project's test-account filters."),+ hide_zero_coordinates: zod+ .boolean()+ .default(heatmapsEventsRetrieveQueryHideZeroCoordinatesDefault)+ .describe('When true (default), drop interactions recorded at the (0, 0) origin, which are usually noise.'),+ limit: zod+ .number()+ .min(1)+ .max(heatmapsEventsRetrieveQueryLimitMax)+ .default(heatmapsEventsRetrieveQueryLimitDefault)+ .describe('Maximum interactions to return (1-100).'),+ offset: zod+ .number()+ .min(heatmapsEventsRetrieveQueryOffsetMin)+ .default(heatmapsEventsRetrieveQueryOffsetDefault)+ .describe('Number of interactions to skip, for pagination.'),+ points: zod+ .string()+ .min(1)+ .describe(+ "JSON array of the heatmap coordinates to drill into, e.g. '[{\"x\": 0.5, \"y\": 100}]'. Each point needs 'x' (relative x, 0..1) and 'y' (absolute client-y pixels) matching values returned by the heatmaps list endpoint; an optional 'target_fixed' boolean matches fixed-position elements. Returns the individual session interactions behind those spots."+ ),+ type: zod+ .string()+ .min(1)+ .default(heatmapsEventsRetrieveQueryTypeDefault)+ .describe(+ "The interaction type to return. One of: 'click' (default), 'rageclick', 'mousemove', or 'scrolldepth'. Scrolldepth returns scroll buckets instead of x/y coordinates."+ ),+ url_exact: zod+ .string()+ .min(1)+ .optional()+ .describe('Match a single page by exact URL (trailing slash is ignored). Mutually exclusive with url_pattern.'),+ url_pattern: zod+ .string()+ .min(1)+ .optional()+ .describe(+ 'Match pages by regex against the full current_url (anchored automatically). Use this to aggregate across query strings or path segments. Mutually exclusive with url_exact.'+ ),+ viewport_width_max: zod+ .number()+ .optional()+ .describe('Only include interactions captured at a viewport at most this wide, in CSS pixels.'),+ viewport_width_min: zod+ .number()+ .optional()+ .describe(+ 'Only include interactions captured at a viewport at least this wide, in CSS pixels. Use with viewport_width_max to isolate a device class (e.g. 360-768 for mobile).'+ ),+})++/**+ * List saved heatmaps for the project. A saved heatmap pins a page URL and a set of viewport widths, and (for type 'screenshot') renders the page so heatmap data can be overlaid on it.+ */+export const SavedListParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const savedListQueryLimitDefault = 100+export const savedListQueryOffsetDefault = 0++export const SavedListQueryParams = /* @__PURE__ */ zod.object({+ created_by: zod.number().optional().describe("Filter by the creating user's ID."),+ limit: zod.number().default(savedListQueryLimitDefault).describe('Maximum saved heatmaps to return.'),+ offset: zod.number().default(savedListQueryOffsetDefault).describe('Number to skip, for pagination.'),+ order: zod.string().min(1).optional().describe("Field to order by, e.g. '-updated_at' (default) or 'created_at'."),+ search: zod.string().min(1).optional().describe('Case-insensitive substring match on URL or name.'),+ status: zod+ .string()+ .min(1)+ .optional()+ .describe("Filter by generation status: 'processing', 'completed', or 'failed'."),+ type: zod.string().min(1).optional().describe("Filter by render mode: 'screenshot', 'iframe', or 'recording'."),+})++/**+ * Create a saved heatmap for a page URL. For type 'screenshot' (the default) this enqueues a headless render of the page at each target width; poll the saved heatmap or its content endpoint until status is 'completed'. Provide 'widths' to control which viewport widths are rendered.+ */+export const SavedCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const savedCreateBodyNameMax = 400++export const savedCreateBodyUrlMax = 2000++export const savedCreateBodyDataUrlMax = 2000++export const savedCreateBodyWidthsItemMin = 100+export const savedCreateBodyWidthsItemMax = 3000++export const savedCreateBodyWidthsMax = 16++export const savedCreateBodyTypeDefault = `screenshot`++export const SavedCreateBody = /* @__PURE__ */ zod.object({+ name: zod.string().max(savedCreateBodyNameMax).nullish().describe('Human-readable label for the saved heatmap.'),+ url: zod+ .url()+ .max(savedCreateBodyUrlMax)+ .describe('Exact page URL to render and overlay heatmap data on. Wildcards are not allowed.'),+ data_url: zod+ .url()+ .max(savedCreateBodyDataUrlMax)+ .nullish()+ .describe("URL whose heatmap data is overlaid on the screenshot. Defaults to 'url' when omitted."),+ widths: zod+ .array(zod.number().min(savedCreateBodyWidthsItemMin).max(savedCreateBodyWidthsItemMax))+ .max(savedCreateBodyWidthsMax)+ .optional()+ .describe(+ 'Viewport widths (px, 100-3000) to render the heatmap screenshot at — one render per width. Defaults to [320, 375, 425, 768, 1024, 1440, 1920] when omitted. At most 16 widths.'+ ),+ type: zod+ .enum(['screenshot', 'iframe', 'recording'])+ .describe('* `screenshot` - Screenshot\n* `iframe` - Iframe\n* `recording` - Recording')+ .default(savedCreateBodyTypeDefault)+ .describe(+ "Render mode: 'screenshot' (renders the page headlessly, default), 'iframe', or 'recording'. Only 'screenshot' generates image bytes.\n\n* `screenshot` - Screenshot\n* `iframe` - Iframe\n* `recording` - Recording"+ ),+})++/**+ * Get a single saved heatmap by its short_id, including per-width render status.+ */+export const SavedRetrieveParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+ short_id: zod.string(),+})++/**+ * Update a saved heatmap (e.g. rename, change widths, or soft-delete via 'deleted'). Changing the URL of a 'screenshot' heatmap triggers a re-render.+ */+export const SavedPartialUpdateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+ short_id: zod.string(),+})++export const savedPartialUpdateBodyNameMax = 400++export const savedPartialUpdateBodyUrlMax = 2000++export const savedPartialUpdateBodyDataUrlMax = 2000++export const savedPartialUpdateBodyWidthsItemMin = 100+export const savedPartialUpdateBodyWidthsItemMax = 3000++export const savedPartialUpdateBodyWidthsMax = 16++export const SavedPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(savedPartialUpdateBodyNameMax)+ .nullish()+ .describe('Human-readable label for the saved heatmap.'),+ url: zod+ .url()+ .max(savedPartialUpdateBodyUrlMax)+ .optional()+ .describe('Exact page URL to render and overlay heatmap data on. Wildcards are not allowed.'),+ data_url: zod+ .url()+ .max(savedPartialUpdateBodyDataUrlMax)+ .nullish()+ .describe("URL whose heatmap data is overlaid on the screenshot. Defaults to 'url' when omitted."),+ widths: zod+ .array(zod.number().min(savedPartialUpdateBodyWidthsItemMin).max(savedPartialUpdateBodyWidthsItemMax))+ .max(savedPartialUpdateBodyWidthsMax)+ .optional()+ .describe(+ 'Viewport widths (px, 100-3000) to render the heatmap screenshot at — one render per width. Defaults to [320, 375, 425, 768, 1024, 1440, 1920] when omitted. At most 16 widths.'+ ),+ type: zod+ .enum(['screenshot', 'iframe', 'recording'])+ .describe('* `screenshot` - Screenshot\n* `iframe` - Iframe\n* `recording` - Recording')+ .optional()+ .describe(+ "Render mode: 'screenshot' (renders the page headlessly, default), 'iframe', or 'recording'. Only 'screenshot' generates image bytes.\n\n* `screenshot` - Screenshot\n* `iframe` - Iframe\n* `recording` - Recording"+ ),+ deleted: zod.boolean().optional().describe('Set true to soft-delete the saved heatmap.'),+})++/**+ * Re-run screenshot generation for a saved heatmap of type 'screenshot'. Clears existing renders and re-renders at every target width; status returns to 'processing'.+ */+export const SavedRegenerateCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+ short_id: zod.string(),+})+/*** Summarizes a project's web analytics over a lookback window (default 7 days): unique visitors, pageviews, sessions, bounce rate, and average session duration with period-over-period comparisons, plus the top 5 pages, top 5 traffic sources, and goal conversions.* @summary Summarize web analyticsdiff --git a/services/mcp/src/tools/generated/web_analytics.ts b/services/mcp/src/tools/generated/web_analytics.tsindex ca6fef86eeee..62716ecefa6c 100644--- a/services/mcp/src/tools/generated/web_analytics.ts+++ b/services/mcp/src/tools/generated/web_analytics.ts@@ -2,9 +2,208 @@import { z } from 'zod'import type { Schemas } from '@/api/generated'-import { WebAnalyticsWeeklyDigestQueryParams } from '@/generated/web_analytics/api'+import {+ HeatmapsEventsRetrieveQueryParams,+ HeatmapsListQueryParams,+ SavedCreateBody,+ SavedListQueryParams,+ SavedPartialUpdateBody,+ SavedPartialUpdateParams,+ SavedRegenerateCreateParams,+ SavedRetrieveParams,+ WebAnalyticsWeeklyDigestQueryParams,+} from '@/generated/web_analytics/api'+import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'+const HeatmapsEventsSchema = HeatmapsEventsRetrieveQueryParams++const heatmapsEvents = (): ToolBase<typeof HeatmapsEventsSchema, Schemas.HeatmapEventsResponse> => ({+ name: 'heatmaps-events',+ schema: HeatmapsEventsSchema,+ handler: async (context: Context, params: z.infer<typeof HeatmapsEventsSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.HeatmapEventsResponse>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/heatmaps/events/`,+ query: {+ aggregation: params.aggregation,+ cohort_ids: params.cohort_ids,+ date_from: params.date_from,+ date_to: params.date_to,+ filter_test_accounts: params.filter_test_accounts,+ hide_zero_coordinates: params.hide_zero_coordinates,+ limit: params.limit,+ offset: params.offset,+ points: params.points,+ type: params.type,+ url_exact: params.url_exact,+ url_pattern: params.url_pattern,+ viewport_width_max: params.viewport_width_max,+ viewport_width_min: params.viewport_width_min,+ },+ })+ return result+ },+})++const HeatmapsListSchema = HeatmapsListQueryParams++const heatmapsList = (): ToolBase<typeof HeatmapsListSchema, WithPostHogUrl<Schemas.HeatmapsResponse[]>> => ({+ name: 'heatmaps-list',+ schema: HeatmapsListSchema,+ handler: async (context: Context, params: z.infer<typeof HeatmapsListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.HeatmapsResponse[]>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/heatmaps/`,+ query: {+ aggregation: params.aggregation,+ cohort_ids: params.cohort_ids,+ date_from: params.date_from,+ date_to: params.date_to,+ filter_test_accounts: params.filter_test_accounts,+ hide_zero_coordinates: params.hide_zero_coordinates,+ type: params.type,+ url_exact: params.url_exact,+ url_pattern: params.url_pattern,+ viewport_width_max: params.viewport_width_max,+ viewport_width_min: params.viewport_width_min,+ },+ })+ return await withPostHogUrl(context, result, '/web')+ },+})++const HeatmapsSavedCreateSchema = SavedCreateBody++const heatmapsSavedCreate = (): ToolBase<typeof HeatmapsSavedCreateSchema, Schemas.HeatmapScreenshotResponse> => ({+ name: 'heatmaps-saved-create',+ schema: HeatmapsSavedCreateSchema,+ handler: async (context: Context, params: z.infer<typeof HeatmapsSavedCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ if (params.url !== undefined) {+ body['url'] = params.url+ }+ if (params.data_url !== undefined) {+ body['data_url'] = params.data_url+ }+ if (params.widths !== undefined) {+ body['widths'] = params.widths+ }+ if (params.type !== undefined) {+ body['type'] = params.type+ }+ const result = await context.api.request<Schemas.HeatmapScreenshotResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/saved/`,+ body,+ })+ return result+ },+})++const HeatmapsSavedGetSchema = SavedRetrieveParams.omit({ project_id: true })++const heatmapsSavedGet = (): ToolBase<typeof HeatmapsSavedGetSchema, Schemas.HeatmapScreenshotResponse> => ({+ name: 'heatmaps-saved-get',+ schema: HeatmapsSavedGetSchema,+ handler: async (context: Context, params: z.infer<typeof HeatmapsSavedGetSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.HeatmapScreenshotResponse>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/saved/${encodeURIComponent(String(params.short_id))}/`,+ })+ return result+ },+})++const HeatmapsSavedListSchema = SavedListQueryParams++const heatmapsSavedList = (): ToolBase<+ typeof HeatmapsSavedListSchema,+ WithPostHogUrl<Schemas.SavedHeatmapListResponse[]>+> => ({+ name: 'heatmaps-saved-list',+ schema: HeatmapsSavedListSchema,+ handler: async (context: Context, params: z.infer<typeof HeatmapsSavedListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.SavedHeatmapListResponse[]>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/saved/`,+ query: {+ created_by: params.created_by,+ limit: params.limit,+ offset: params.offset,+ order: params.order,+ search: params.search,+ status: params.status,+ type: params.type,+ },+ })+ return await withPostHogUrl(context, result, '/web')+ },+})++const HeatmapsSavedRegenerateSchema = SavedRegenerateCreateParams.omit({ project_id: true })++const heatmapsSavedRegenerate = (): ToolBase<+ typeof HeatmapsSavedRegenerateSchema,+ Schemas.HeatmapScreenshotResponse+> => ({+ name: 'heatmaps-saved-regenerate',+ schema: HeatmapsSavedRegenerateSchema,+ handler: async (context: Context, params: z.infer<typeof HeatmapsSavedRegenerateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.HeatmapScreenshotResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/saved/${encodeURIComponent(String(params.short_id))}/regenerate/`,+ })+ return result+ },+})++const HeatmapsSavedUpdateSchema = SavedPartialUpdateParams.omit({ project_id: true }).extend(+ SavedPartialUpdateBody.shape+)++const heatmapsSavedUpdate = (): ToolBase<typeof HeatmapsSavedUpdateSchema, Schemas.HeatmapScreenshotResponse> => ({+ name: 'heatmaps-saved-update',+ schema: HeatmapsSavedUpdateSchema,+ handler: async (context: Context, params: z.infer<typeof HeatmapsSavedUpdateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ if (params.url !== undefined) {+ body['url'] = params.url+ }+ if (params.data_url !== undefined) {+ body['data_url'] = params.data_url+ }+ if (params.widths !== undefined) {+ body['widths'] = params.widths+ }+ if (params.type !== undefined) {+ body['type'] = params.type+ }+ if (params.deleted !== undefined) {+ body['deleted'] = params.deleted+ }+ const result = await context.api.request<Schemas.HeatmapScreenshotResponse>({+ method: 'PATCH',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/saved/${encodeURIComponent(String(params.short_id))}/`,+ body,+ })+ return result+ },+})+const WebAnalyticsWeeklyDigestSchema = WebAnalyticsWeeklyDigestQueryParamsconst webAnalyticsWeeklyDigest = (): ToolBase<typeof WebAnalyticsWeeklyDigestSchema, Schemas.WeeklyDigestResponse> => ({@@ -25,5 +224,12 @@ const webAnalyticsWeeklyDigest = (): ToolBase<typeof WebAnalyticsWeeklyDigestSch})export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'heatmaps-events': heatmapsEvents,+ 'heatmaps-list': heatmapsList,+ 'heatmaps-saved-create': heatmapsSavedCreate,+ 'heatmaps-saved-get': heatmapsSavedGet,+ 'heatmaps-saved-list': heatmapsSavedList,+ 'heatmaps-saved-regenerate': heatmapsSavedRegenerate,+ 'heatmaps-saved-update': heatmapsSavedUpdate,'web-analytics-weekly-digest': webAnalyticsWeeklyDigest,}diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 4b271ba4dd1a..62b8c613438a 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -711,9 +711,10 @@ describe('Tool Filtering - Feature Flags', () => {'tasks','promoted-product','dashboard-widgets',+ 'heatmaps-mcp',]))- expect(flags).toHaveLength(12)+ expect(flags).toHaveLength(13)})// Exercise the real predicate (toolPassesFlagGate) over hand-rolled entries