Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(max): add assess_heatmap tool mirroring the heatmaps skill (#62491)

Paul D'Ambrab0f8a659c5d6
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index f72be3620c12..96f0415347df 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -3853,6 +3853,7 @@
"archive_llm_skill",
"diagnose_proxy",
"web_analytics_doctor",
+ "assess_heatmap",
"marketing_diagnose_setup",
"marketing_explain_conversion_goal",
"marketing_list_conversion_goals",
diff --git a/frontend/src/queries/schema/schema-assistant-messages.ts b/frontend/src/queries/schema/schema-assistant-messages.ts
index 158103759396..d1cb3dae6c0b 100644
--- a/frontend/src/queries/schema/schema-assistant-messages.ts
+++ b/frontend/src/queries/schema/schema-assistant-messages.ts
@@ -507,6 +507,7 @@ export type AssistantTool =
| 'archive_llm_skill'
| 'diagnose_proxy'
| 'web_analytics_doctor'
+ | 'assess_heatmap'
| 'marketing_diagnose_setup'
| 'marketing_explain_conversion_goal'
| 'marketing_list_conversion_goals'
diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsx
index 53b334d4b22e..546a7a951b55 100644
--- a/frontend/src/scenes/max/max-constants.tsx
+++ b/frontend/src/scenes/max/max-constants.tsx
@@ -791,6 +791,16 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {
return toolCall.status === 'completed' ? 'Diagnosed web analytics' : 'Diagnosing web analytics...'
},
},
+ assess_heatmap: {
+ name: 'Assess a heatmap',
+ description:
+ 'Assess a heatmap for a page — click, rageclick, and scroll-depth data plus the elements under the hot spots — and recommend concrete changes',
+ product: Scene.WebAnalytics,
+ icon: iconForType('web_analytics'),
+ displayFormatter: (toolCall) => {
+ return toolCall.status === 'completed' ? 'Assessed heatmap' : 'Assessing heatmap...'
+ },
+ },
marketing_diagnose_setup: {
name: 'Diagnose marketing analytics',
description:
diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsScene.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsScene.tsx
index 1dbc6603685b..780b54328b6c 100644
--- a/frontend/src/scenes/web-analytics/WebAnalyticsScene.tsx
+++ b/frontend/src/scenes/web-analytics/WebAnalyticsScene.tsx
@@ -25,6 +25,16 @@ export function WebAnalyticsScene(): JSX.Element {
'Diagnose my reverse proxy setup',
],
})
+ useMaxTool({
+ identifier: 'assess_heatmap',
+ active: true,
+ context: {},
+ suggestions: [
+ 'Assess the heatmap for my pricing page',
+ 'Why are people not clicking my main CTA?',
+ 'Where do users rage-click on my homepage?',
+ ],
+ })
const { showFocusMode } = useValues(webAnalyticsLogic)
return (
diff --git a/posthog/schema.py b/posthog/schema.py
index c5a171c6eebc..fc2f8f2bbe53 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -800,6 +800,7 @@ class AssistantTool(StrEnum):
ARCHIVE_LLM_SKILL = "archive_llm_skill"
DIAGNOSE_PROXY = "diagnose_proxy"
WEB_ANALYTICS_DOCTOR = "web_analytics_doctor"
+ ASSESS_HEATMAP = "assess_heatmap"
MARKETING_DIAGNOSE_SETUP = "marketing_diagnose_setup"
MARKETING_EXPLAIN_CONVERSION_GOAL = "marketing_explain_conversion_goal"
MARKETING_LIST_CONVERSION_GOALS = "marketing_list_conversion_goals"
diff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.py
index 083ba90f14f4..b93f69a5e051 100644
--- a/products/web_analytics/backend/api/heatmaps_api.py
+++ b/products/web_analytics/backend/api/heatmaps_api.py
@@ -134,6 +134,22 @@ WHERE {predicates}
"""
+def parse_fold_summary_row(row: Any) -> dict[str, Any]:
+ """Shape a single FOLD_SUMMARY_QUERY result row (or None for an empty result) into the
+ fold-summary payload. Shared so every caller applies the same NaN coercion and pct math."""
+ 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,
+ }
+
+
class HeatmapsRequestSerializer(serializers.Serializer):
viewport_width_min = serializers.IntegerField(
required=False,
@@ -430,17 +446,7 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
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,
- }
+ return parse_fold_summary_row(row)
def _choose_aggregation(self, aggregation, is_scrolldepth_query):
aggregation_value = "count(*) as cnt" if aggregation == "total_count" else "count(distinct distinct_id) as cnt"
diff --git a/products/web_analytics/backend/max_tools.py b/products/web_analytics/backend/max_tools.py
index 3d3f967fc26d..fe6fd1254c57 100644
--- a/products/web_analytics/backend/max_tools.py
+++ b/products/web_analytics/backend/max_tools.py
@@ -1,6 +1,7 @@
import json
import asyncio
import logging
+from datetime import date
from typing import Any, Literal
from langchain_core.prompts import ChatPromptTemplate
@@ -8,6 +9,13 @@ from pydantic import BaseModel, Field
from posthog.schema import WebAnalyticsAssistantFilters
+from posthog.hogql import ast
+from posthog.hogql.ast import Constant
+from posthog.hogql.constants import LimitContext
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.parser import parse_expr, parse_select
+from posthog.hogql.query import execute_hogql_query
+
from posthog.clickhouse.query_tagging import Product, tags_context
from posthog.dags.common.owners import JobOwners
from posthog.models import Team, User
@@ -20,6 +28,15 @@ from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP
from posthog.temporal.health_checks.processing import _process_batch_detection
from posthog.temporal.health_checks.registry import HEALTH_CHECKS, ensure_registry_loaded, get_detect_fn
+from products.web_analytics.backend.api.heatmaps_api import (
+ DEFAULT_QUERY,
+ FOLD_SUMMARY_QUERY,
+ SCROLL_DEPTH_QUERY,
+ HeatmapsRequestSerializer,
+ HeatmapViewSet,
+ parse_fold_summary_row,
+)
+
from ee.hogai.chat_agent.taxonomy.agent import TaxonomyAgent
from ee.hogai.chat_agent.taxonomy.format import enrich_props_with_descriptions, format_properties_xml
from ee.hogai.chat_agent.taxonomy.nodes import TaxonomyAgentNode, TaxonomyAgentToolsNode
@@ -361,3 +378,400 @@ def _format_doctor_issue(issue: HealthIssue) -> list[str]:
if unproxied:
lines.append(f" - unproxied hosts: {', '.join(unproxied)}")
return lines
+
+
+ASSESS_HEATMAP_DESCRIPTION = """
+- Assess what a page's heatmap is telling you and recommend concrete changes. Pulls click, rageclick, and
+ scroll-depth data for a URL, reads the above/below-the-fold split, and names the elements under the hot
+ spots by cross-referencing autocapture clicks on the same page.
+- When to use the tool:
+ * When the user asks what a heatmap shows, or to "analyze" / "assess" / "review" the heatmap for a page
+ * When the user asks why people aren't clicking something, where users rage-click, how far they scroll, or
+ what to change on a page based on heatmap or click data
+- Do NOT use the tool:
+ * When the user only wants to create a saved heatmap screenshot with no analysis
+ * When the user is asking about session replay in general (use the replay tools instead)
+- You must pass an exact `page_url` (full URL including scheme and host). Confirm it with the user if ambiguous.
+""".strip()
+
+
+class AssessHeatmapArgs(BaseModel):
+ page_url: str = Field(
+ description="The exact page URL to assess, including scheme and host "
+ "(e.g. 'https://posthog.com/pricing'). The trailing slash is ignored.",
+ )
+ date_from: str = Field(
+ default="-7d",
+ description="Start of the window. Relative (e.g. '-7d', '-30d') or absolute 'YYYY-MM-DD'. "
+ "Defaults to the last 7 days; widen to '-30d' if volume is low. Heatmap data is retained for 90 days.",
+ )
+ date_to: str | None = Field(
+ default=None,
+ description="End of the window, inclusive. Relative or absolute 'YYYY-MM-DD'. Defaults to today.",
+ )
+ viewport_width_min: int | None = Field(
+ default=None,
+ description="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); desktop and mobile "
+ "have very different folds, so prefer assessing one band at a time.",
+ )
+ viewport_width_max: int | None = Field(
+ default=None,
+ description="Only include interactions captured at a viewport at most this wide, in CSS pixels.",
+ )
+
+
+class AssessHeatmapTool(MaxTool):
+ name: str = "assess_heatmap"
+ description: str = ASSESS_HEATMAP_DESCRIPTION
+ args_schema: type[BaseModel] = AssessHeatmapArgs
+
+ def get_required_resource_access(
+ self,
+ ) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ return [("web_analytics", "viewer")]
+
+ async def _arun_impl(
+ self,
+ page_url: str,
+ date_from: str = "-7d",
+ date_to: str | None = None,
+ viewport_width_min: int | None = None,
+ viewport_width_max: int | None = None,
+ ) -> tuple[str, dict[str, Any]]:
+ data = await database_sync_to_async(_gather_heatmap_data)(
+ self._team,
+ page_url=page_url,
+ date_from=date_from,
+ date_to=date_to,
+ viewport_width_min=viewport_width_min,
+ viewport_width_max=viewport_width_max,
+ )
+ content = _format_heatmap_report(page_url, data)
+ return content, data
+
+
+# Heatmaps store coordinates as pure geometry — they don't know what was clicked. Cross-referencing
+# autocapture clicks on the same URL is what turns "lots of clicks at (0.5, 220)" into "lots of clicks on
+# the Pricing link". Grouping by visible text collapses repeats; `any(elements_chain)` keeps one
+# representative DOM path for reference (it does not split same-text elements apart). The viewport
+# filter mirrors the band applied to the heatmap signals so element identity lines up with the hotspots.
+AUTOCAPTURE_ELEMENTS_QUERY = """
+SELECT
+ properties.$el_text AS el_text,
+ any(elements_chain) AS chain,
+ count() AS clicks
+FROM events
+WHERE event = '$autocapture'
+ AND trimRight(properties.$current_url, '/') = trimRight({url}, '/')
+ AND timestamp >= {date_from}
+ AND timestamp <= {date_to} + interval 1 day
+ AND notEmpty(properties.$el_text)
+ AND {viewport_filter}
+GROUP BY el_text
+ORDER BY clicks DESC
+LIMIT 25
+"""
+
+_TOP_POINTS = 15
+_TOP_ELEMENTS = 15
+
+
+def _gather_heatmap_data(
+ team: Team,
+ *,
+ page_url: str,
+ date_from: str,
+ date_to: str | None,
+ viewport_width_min: int | None,
+ viewport_width_max: int | None,
+) -> dict[str, Any]:
+ if not team.heatmaps_opt_in:
+ return {"opted_in": False}
+
+ def predicates(heatmap_type: str) -> tuple[dict[str, Any], list[ast.Expr]]:
+ return _heatmap_predicates(
+ team,
+ type=heatmap_type,
+ page_url=page_url,
+ date_from=date_from,
+ date_to=date_to,
+ vmin=viewport_width_min,
+ vmax=viewport_width_max,
+ )
+
+ click_validated, click_exprs = predicates("click")
+ # Drop (0, 0) origin noise the same way the heatmaps endpoint does for positional types.
+ click_exprs.append(parse_expr("NOT (x = 0 AND y = 0)"))
+
+ _rage_validated, rage_exprs = predicates("rageclick")
+ rage_exprs.append(parse_expr("NOT (x = 0 AND y = 0)"))
+
+ _scroll_validated, scroll_exprs = predicates("scrolldepth")
+
+ resolved_from: date = click_validated["date_from"]
+ resolved_to: date = click_validated.get("date_to") or date.today()
+
+ return {
+ "opted_in": True,
+ "page_url": page_url,
+ "date_from": resolved_from.isoformat(),
+ "date_to": resolved_to.isoformat(),
+ "viewport_width_min": viewport_width_min,
+ "viewport_width_max": viewport_width_max,
+ "clicks": _coordinate_points(team, click_exprs),
+ "fold": _fold_summary(team, click_exprs),
+ "rageclicks": _coordinate_points(team, rage_exprs),
+ "scrolldepth": _scroll_buckets(team, scroll_exprs),
+ "elements": _autocapture_elements(
+ team, page_url, resolved_from, resolved_to, viewport_width_min, viewport_width_max
+ ),
+ }
+
+
+def _heatmap_predicates(
+ team: Team,
+ *,
+ type: str,
+ page_url: str,
+ date_from: str,
+ date_to: str | None,
+ vmin: int | None,
+ vmax: int | None,
+) -> tuple[dict[str, Any], list[ast.Expr]]:
+ """Validate request params the same way the heatmaps endpoint does, then build its filter expressions.
+
+ Reuses `HeatmapsRequestSerializer` (date parsing, url handling) and the endpoint's static placeholder /
+ predicate builders so this tool and the API stay in lockstep on what "the heatmap for a page" means.
+ """
+ request_data: dict[str, Any] = {"type": type, "url_exact": page_url, "date_from": date_from}
+ if date_to is not None:
+ request_data["date_to"] = date_to
+ if vmin is not None:
+ request_data["viewport_width_min"] = vmin
+ if vmax is not None:
+ request_data["viewport_width_max"] = vmax
+
+ serializer = HeatmapsRequestSerializer(data=request_data, context={"team": team})
+ serializer.is_valid(raise_exception=True)
+ validated = dict(serializer.validated_data)
+ # Strip the non-predicate fields the serializer always includes — only the
+ # remaining keys map to heatmap filter predicates.
+ validated.pop("aggregation", None)
+ validated.pop("hide_zero_coordinates", None)
+ validated.pop("filter_test_accounts", None)
+
+ placeholders = HeatmapViewSet._build_placeholders(validated)
+ exprs = HeatmapViewSet._predicate_expressions(placeholders)
+ return validated, exprs
+
+
+def _execute(team: Team, stmt: ast.SelectQuery | ast.SelectSetQuery) -> Any:
+ context = HogQLContext(team_id=team.pk, limit_top_select=False)
+ with tags_context(product=Product.MAX_AI, team_id=team.pk, org_id=team.organization_id):
+ return execute_hogql_query(query=stmt, team=team, limit_context=LimitContext.HEATMAPS, context=context)
+
+
+def _coordinate_points(team: Team, exprs: list[ast.Expr]) -> list[dict[str, Any]]:
+ stmt = parse_select(
+ DEFAULT_QUERY,
+ {"aggregation_count": parse_expr("count(*) as cnt"), "predicates": ast.And(exprs=exprs)},
+ )
+ result = _execute(team, stmt)
+ points = [
+ {
+ "pointer_target_fixed": bool(item[0]),
+ "pointer_relative_x": item[1],
+ "pointer_y": item[2],
+ "count": item[3],
+ }
+ for item in result.results or []
+ ]
+ points.sort(key=lambda p: p["count"], reverse=True)
+ return points[:_TOP_POINTS]
+
+
+def _fold_summary(team: Team, exprs: list[ast.Expr]) -> dict[str, Any]:
+ stmt = parse_select(FOLD_SUMMARY_QUERY, {"predicates": ast.And(exprs=exprs)})
+ result = _execute(team, stmt)
+ row = result.results[0] if result.results else None
+ return parse_fold_summary_row(row)
+
+
+def _scroll_buckets(team: Team, exprs: list[ast.Expr]) -> list[dict[str, Any]]:
+ stmt = parse_select(
+ SCROLL_DEPTH_QUERY,
+ {"aggregation_count": parse_expr("count(*)"), "predicates": ast.And(exprs=exprs)},
+ )
+ result = _execute(team, stmt)
+ return [
+ {"scroll_depth_bucket": int(item[0]), "bucket_count": int(item[1]), "cumulative_count": int(item[2])}
+ for item in result.results or []
+ ]
+
+
+def _autocapture_elements(
+ team: Team,
+ page_url: str,
+ date_from: date,
+ date_to: date,
+ vmin: int | None,
+ vmax: int | None,
+) -> list[dict[str, Any]]:
+ # Apply the same viewport band as the heatmap signals. $viewport_width is raw CSS pixels (not the
+ # /16-scaled heatmap column), coerced like elsewhere in web analytics. A no-op `1 = 1` when unbounded.
+ viewport_exprs: list[ast.Expr] = []
+ if vmin is not None:
+ viewport_exprs.append(
+ parse_expr("toIntOrZero(toString(properties.$viewport_width)) >= {v}", {"v": Constant(value=vmin)})
+ )
+ if vmax is not None:
+ viewport_exprs.append(
+ parse_expr("toIntOrZero(toString(properties.$viewport_width)) <= {v}", {"v": Constant(value=vmax)})
+ )
+ viewport_filter: ast.Expr = ast.And(exprs=viewport_exprs) if viewport_exprs else parse_expr("1 = 1")
+
+ stmt = parse_select(
+ AUTOCAPTURE_ELEMENTS_QUERY,
+ {
+ "url": Constant(value=page_url),
+ "date_from": Constant(value=date_from),
+ "date_to": Constant(value=date_to),
+ "viewport_filter": viewport_filter,
+ },
+ )
+ result = _execute(team, stmt)
+ return [{"text": item[0], "elements_chain": item[1], "clicks": int(item[2])} for item in result.results or []]
+
+
+def _scroll_reach(buckets: list[dict[str, Any]]) -> dict[str, Any] | None:
+ if not buckets:
+ return None
+ total = max((b["cumulative_count"] for b in buckets), default=0)
+ if not total:
+ return None
+ ascending = sorted(buckets, key=lambda b: b["scroll_depth_bucket"])
+ # The deepest bucket still reached by at least `pct` of the population. `None` (not 0,
+ # a real depth) when no bucket clears the threshold, so the report can say so honestly.
+ reach: dict[int, int | None] = {}
+ for pct in (75, 50, 25):
+ deepest: int | None = None
+ for b in ascending:
+ if b["cumulative_count"] / total * 100 >= pct:
+ deepest = b["scroll_depth_bucket"]
+ reach[pct] = deepest
+ return {"total": total, "reach": reach, "max_depth": ascending[-1]["scroll_depth_bucket"]}
+
+
+def _format_heatmap_report(page_url: str, data: dict[str, Any]) -> str:
+ if not data.get("opted_in"):
+ return (
+ f"Heatmaps aren't enabled for this project, so there's no data to assess for {page_url}. "
+ "Turn on heatmap capture in the project's web analytics / autocapture settings "
+ "(`Team.heatmaps_opt_in`), then check back once interactions have been recorded."
+ )
+
+ clicks = data["clicks"]
+ rageclicks = data["rageclicks"]
+ fold = data["fold"]
+ elements = data["elements"]
+
+ lines = [f"Heatmap assessment for **{page_url}** ({data['date_from']} → {data['date_to']}):", ""]
+
+ band = _viewport_band(data.get("viewport_width_min"), data.get("viewport_width_max"))
+ if band:
+ lines.append(band)
+ lines.append("")
+
+ if not clicks and not rageclicks and fold["total_count"] == 0 and not data["scrolldepth"]:
+ lines.append(
+ "No heatmap interactions matched this page in the window. Either the URL is off, the page gets "
+ "little traffic, or capture isn't recording it — verify the exact URL and that the page is being "
+ "visited before concluding there's no engagement. You can widen the window with date_from='-30d'."
+ )
+ return "\n".join(lines)
+
+ # Fold / scroll reach — the highest-value layout signal.
+ lines.append("**Scroll & fold**")
+ if fold["median_viewport_height"]:
+ lines.append(f"- Typical fold (median viewport height): ~{fold['median_viewport_height']}px")
+ if fold["total_count"]:
+ lines.append(
+ f"- {fold['pct_below_fold']}% of clicks landed below the fold "
+ f"({fold['below_fold_count']} of {fold['total_count']} non-fixed clicks) — content people actively "
+ "click that sits below the initial viewport is a candidate to move up."
+ )
+ reach = _scroll_reach(data["scrolldepth"])
+ if reach:
+ r = reach["reach"]
+
+ def _depth(px: int | None) -> str:
+ return f"≥{px}px" if px is not None else "n/a"
+
+ lines.append(
+ f"- Scroll reach: 75% of visitors reached {_depth(r[75])}, 50% reached {_depth(r[50])}, "
+ f"25% reached {_depth(r[25])} (deepest bucket {reach['max_depth']}px)."
+ )
+ lines.append("")
+
+ # Rage clicks — the strongest "something is broken or misleading" signal.
+ lines.append("**Rage clicks**")
+ if rageclicks:
+ total_rage = sum(p["count"] for p in rageclicks)
+ lines.append(
+ f"- {total_rage} rage-click interaction(s) across {len(rageclicks)} spot(s) — repeated frustrated "
+ "clicking. Treat any meaningful cluster as broken, slow, or looks-clickable-but-isn't."
+ )
+ for p in rageclicks[:5]:
+ lines.append(f" - {p['count']}× at x≈{p['pointer_relative_x']}, y≈{p['pointer_y']}px")
+ else:
+ lines.append("- None detected. 👍")
+ lines.append("")
+
+ # Click hotspots.
+ lines.append("**Top click hotspots** (relative x is 0–1 across the viewport; y is pixels down the page)")
+ if clicks:
+ for p in clicks[:_TOP_POINTS]:
+ fixed = " (fixed-position)" if p["pointer_target_fixed"] else ""
+ lines.append(f"- {p['count']}× at x≈{p['pointer_relative_x']}, y≈{p['pointer_y']}px{fixed}")
+ else:
+ lines.append("- No click data for this page in the window.")
+ lines.append("")
+
+ # Autocapture identity — what actually sits under the clicks.
+ lines.append("**What's under the clicks** (top autocapture elements on this page, by click count)")
+ if elements:
+ for el in elements[:_TOP_ELEMENTS]:
+ text = (el["text"] or "").strip().replace("\n", " ")
+ label = f'"{text}"' if text else "(no text)"
+ lines.append(f"- {el['clicks']}× {label}")
+ lines.append("")
+ lines.append(
+ "Match these elements to the hot coordinates above. 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."
+ )
+ else:
+ lines.append(
+ "- No autocapture clicks on this page in the window, so element identity is unavailable. The "
+ "coordinates above show where people interact, but not what they hit."
+ )
+ lines.append("")
+
+ lines.append(
+ "Use this to recommend concrete changes, 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. Tie every recommendation to the signal it came from. You're reasoning from "
+ "coordinates plus autocapture identity — you can't see the page, so don't claim to."
+ )
+ return "\n".join(lines)
+
+
+def _viewport_band(vmin: int | None, vmax: int | None) -> str | None:
+ if vmin is None and vmax is None:
+ return None
+ if vmin is not None and vmax is not None:
+ return f"_Filtered to viewports {vmin}–{vmax}px wide._"
+ if vmin is not None:
+ return f"_Filtered to viewports ≥{vmin}px wide._"
+ return f"_Filtered to viewports ≤{vmax}px wide._"
diff --git a/products/web_analytics/backend/test/test_assess_heatmap_tool.py b/products/web_analytics/backend/test/test_assess_heatmap_tool.py
new file mode 100644
index 000000000000..a3c6e2753f85
--- /dev/null
+++ b/products/web_analytics/backend/test/test_assess_heatmap_tool.py
@@ -0,0 +1,153 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.web_analytics.backend.max_tools import AssessHeatmapTool, _scroll_reach, _viewport_band
+
+from ee.hogai.utils.types import AssistantState
+
+
+class _FakeResult:
+ def __init__(self, results):
+ self.results = results
+
+
+class TestAssessHeatmapTool(APIBaseTest):
+ def _create_tool(self) -> AssessHeatmapTool:
+ return AssessHeatmapTool(
+ team=self.team,
+ user=self.user,
+ state=AssistantState(messages=[]),
+ )
+
+ async def _opt_in(self) -> None:
+ self.team.heatmaps_opt_in = True
+ await self.team.asave()
+
+ def test_declares_web_analytics_viewer_access(self):
+ tool = self._create_tool()
+ assert tool.get_required_resource_access() == [("web_analytics", "viewer")]
+
+ async def test_reports_when_heatmaps_not_opted_in(self):
+ self.team.heatmaps_opt_in = False
+ await self.team.asave()
+
+ tool = self._create_tool()
+ content, artifact = await tool._arun_impl(page_url="https://posthog.com/pricing")
+
+ assert artifact == {"opted_in": False}
+ assert "aren't enabled" in content
+ assert "heatmaps_opt_in" in content
+
+ @patch("products.web_analytics.backend.max_tools._execute")
+ async def test_formats_full_report(self, mock_execute):
+ await self._opt_in()
+ # Calls happen in this order: click coords, click fold, rageclick coords, scroll buckets, autocapture.
+ mock_execute.side_effect = [
+ _FakeResult([(False, 0.5, 220, 100), (False, 0.2, 80, 40)]),
+ _FakeResult([(120, 42, 600)]),
+ _FakeResult([(False, 0.8, 300, 12)]),
+ _FakeResult([(0, 50, 100), (100, 30, 50), (200, 20, 20)]),
+ _FakeResult([("Pricing", "a.nav-link", 80), ("Read the docs", "span", 20)]),
+ ]
+
+ tool = self._create_tool()
+ content, artifact = await tool._arun_impl(page_url="https://posthog.com/pricing")
+
+ # Fold split is the headline layout signal.
+ assert "35.0% of clicks landed below the fold" in content
+ assert "~600px" in content
+ # Rage clicks called out.
+ assert "12 rage-click interaction(s)" in content
+ # Top hotspot surfaced.
+ assert "100× at x≈0.5, y≈220px" in content
+ # Autocapture identity included.
+ assert '"Pricing"' in content
+ # Scroll reach summarised.
+ assert "Scroll reach" in content
+
+ assert artifact["opted_in"] is True
+ assert len(artifact["clicks"]) == 2
+ assert artifact["clicks"][0]["count"] == 100
+ assert artifact["fold"]["pct_below_fold"] == 35.0
+ assert artifact["rageclicks"][0]["count"] == 12
+ assert artifact["elements"][0]["text"] == "Pricing"
+
+ @patch("products.web_analytics.backend.max_tools._execute")
+ async def test_reports_no_interactions(self, mock_execute):
+ await self._opt_in()
+ mock_execute.side_effect = [
+ _FakeResult([]), # clicks
+ _FakeResult([(0, 0, None)]), # fold (empty)
+ _FakeResult([]), # rageclicks
+ _FakeResult([]), # scrolldepth
+ _FakeResult([]), # autocapture
+ ]
+
+ tool = self._create_tool()
+ content, _artifact = await tool._arun_impl(page_url="https://posthog.com/unknown")
+
+ assert "No heatmap interactions matched this page" in content
+
+ @patch("products.web_analytics.backend.max_tools._execute")
+ async def test_no_rage_clicks_is_called_out_positively(self, mock_execute):
+ await self._opt_in()
+ mock_execute.side_effect = [
+ _FakeResult([(False, 0.5, 220, 100)]), # clicks
+ _FakeResult([(100, 10, 600)]), # fold
+ _FakeResult([]), # rageclicks — none
+ _FakeResult([(0, 50, 50)]), # scrolldepth
+ _FakeResult([("Pricing", "a", 80)]), # autocapture
+ ]
+
+ tool = self._create_tool()
+ content, _artifact = await tool._arun_impl(page_url="https://posthog.com/pricing")
+
+ assert "None detected" in content
+
+
+class TestScrollReachAndViewportBand(SimpleTestCase):
+ def test_scroll_reach_none_for_empty_or_zero(self):
+ assert _scroll_reach([]) is None
+ assert _scroll_reach([{"scroll_depth_bucket": 0, "bucket_count": 0, "cumulative_count": 0}]) is None
+
+ def test_scroll_reach_thresholds(self):
+ # cumulative is "people who reached at least this depth": 100 at 0px, 50 at 100px, 20 at 200px.
+ buckets = [
+ {"scroll_depth_bucket": 0, "bucket_count": 50, "cumulative_count": 100},
+ {"scroll_depth_bucket": 100, "bucket_count": 30, "cumulative_count": 50},
+ {"scroll_depth_bucket": 200, "bucket_count": 20, "cumulative_count": 20},
+ ]
+ result = _scroll_reach(buckets)
+ assert result is not None
+ assert result["total"] == 100
+ assert result["max_depth"] == 200
+ # Deepest bucket still reached by >= pct of the population.
+ # 75%: only 0px (100%); 50%: 100px (50%); 25%: 100px (200px is 20% < 25%).
+ assert result["reach"] == {75: 0, 50: 100, 25: 100}
+
+ def test_scroll_reach_threshold_unmet_is_none(self):
+ # Every bucket sits below the 75% line except via the shallowest, which always holds 100%.
+ # Construct a case where the 25% line is genuinely unreachable for deeper buckets.
+ buckets = [
+ {"scroll_depth_bucket": 300, "bucket_count": 80, "cumulative_count": 80},
+ {"scroll_depth_bucket": 600, "bucket_count": 10, "cumulative_count": 10},
+ ]
+ result = _scroll_reach(buckets)
+ assert result is not None
+ # total = 80; 600px is 10/80 = 12.5% (< 25/50/75), so every threshold resolves to 300px.
+ assert result["reach"] == {75: 300, 50: 300, 25: 300}
+
+ @parameterized.expand(
+ [
+ (None, None, None),
+ (360, 768, "_Filtered to viewports 360–768px wide._"),
+ (360, None, "_Filtered to viewports ≥360px wide._"),
+ (None, 768, "_Filtered to viewports ≤768px wide._"),
+ ]
+ )
+ def test_viewport_band(self, vmin, vmax, expected):
+ assert _viewport_band(vmin, vmax) == expected