: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(heatmaps): scope the overlay to an exact window and width (#114214)
Jordan Mryyan374ab67d1d68
diff --git a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts b/frontend/src/lib/components/heatmaps/heatmapDataLogic.tsindex ed920ef221d0..ce904a6e0cb8 100644--- a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts+++ b/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts@@ -32,6 +32,20 @@ import { ToolbarRequestError } from '~/toolbar/toolbarRequestError'import { HeatmapElement, HeatmapResponseType } from '~/toolbar/types'import { FilterType } from '~/types'+export interface HeatmapDateRangeOverride {+ date_from: string+ date_to: string+ timestamp_from: string+ timestamp_to: string+}++export interface HeatmapHistoryView {+ owner: string+ dateRange: HeatmapDateRangeOverride+ width: number+ imageUrl: string+}+// The endpoint defaults to a bounded page for API callers; the overlay renders every point.const UNBOUNDED_HEATMAP_LIMIT = 0@@ -171,6 +185,8 @@ export interface heatmapDataLogicValues {areaEventsLoadingMore: booleancommonFilters: CommonFiltersdateRange: string | null+ dateRangeOverride: HeatmapDateRangeOverride | null+ effectiveCommonFilters: CommonFiltersfilteredHeatmapElements: HeatmapElement[]heatmapBoundsFilter: HeatmapBoundsFilter | nullheatmapColorPalette: string | null@@ -182,6 +198,7 @@ export interface heatmapDataLogicValues {heatmapTooltipNoun: stringheatmapTooltipSuppressed: booleanheightOverride: number+ historyView: HeatmapHistoryView | nullhref: string | nullhrefMatchType: HrefMatchTypeisHeightCapped: boolean@@ -288,6 +305,9 @@ export interface heatmapDataLogicActions {setHeatmapTooltipSuppressed: (suppressed: boolean) => {suppressed: boolean}+ setHistoryView: (view: HeatmapHistoryView | null) => {+ view: HeatmapHistoryView | null+ }setHref: (href: string) => {href: string}@@ -312,9 +332,18 @@ export interface heatmapDataLogicActions {export interface heatmapDataLogicMeta {key: 'in-app' | 'toolbar'__keaTypeGenInternalSelectorTypes: {+ dateRangeOverride: (historyView: HeatmapHistoryView | null) => HeatmapDateRangeOverride | null+ effectiveCommonFilters: (+ commonFilters: CommonFilters,+ dateRangeOverride: HeatmapDateRangeOverride | null+ ) => CommonFiltersdateRange: (commonFilters: CommonFilters) => string | nullheatmapElements: (rawHeatmap: HeatmapResponseType | null) => HeatmapElement[]- analysisWidth: (windowWidthOverride: number | null, windowWidth: number) => number+ analysisWidth: (+ windowWidthOverride: number | null,+ windowWidth: number,+ historyView: HeatmapHistoryView | null+ ) => numberviewportRange: (heatmapFilters: HeatmapFilters,analysisWidth: number@@ -355,6 +384,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([actions({loadHeatmap: true,setCommonFilters: (filters: CommonFilters) => ({ filters }),+ setHistoryView: (view: HeatmapHistoryView | null) => ({ view }),setHeatmapFilters: (filters: HeatmapFilters) => ({ filters }),patchHeatmapFilters: (filters: Partial<HeatmapFilters>) => ({ filters }),setHeatmapFixedPositionMode: (mode: HeatmapFixedPositionMode) => ({ mode }),@@ -390,6 +420,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([setCommonFilters: (_, { filters }) => filters,},],+ historyView: [null as HeatmapHistoryView | null, { setHistoryView: (_, { view }) => view }],heatmapFilters: [DEFAULT_HEATMAP_FILTERS,{ persist: true },@@ -497,7 +528,8 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([actions.setIsReady(false)- const { date_from, date_to, filter_test_accounts, cohort_ids, events } = values.commonFilters+ const { date_from, date_to, filter_test_accounts, cohort_ids, events } =+ values.effectiveCommonFiltersconst { type, aggregation } = values.heatmapFilters// toolbar fetch collapses queryparams but this URL has multiple with the same name@@ -506,6 +538,8 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([type,date_from,date_to,+ timestamp_from: values.dateRangeOverride?.timestamp_from,+ timestamp_to: values.dateRangeOverride?.timestamp_to,url_exact: values.hrefMatchType === 'exact' ? values.href : undefined,url_pattern: values.hrefMatchType === 'pattern' ? values.href : undefined,viewport_width_min: values.viewportRange.min,@@ -539,7 +573,8 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([await breakpoint(100)- const { date_from, date_to, filter_test_accounts, cohort_ids, events } = values.commonFilters+ const { date_from, date_to, filter_test_accounts, cohort_ids, events } =+ values.effectiveCommonFiltersconst { type } = values.heatmapFiltersconst apiURL = `${heatmapApiPath(props.context, 'events/')}${encodeParams(@@ -547,6 +582,8 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([type,date_from,date_to,+ timestamp_from: values.dateRangeOverride?.timestamp_from,+ timestamp_to: values.dateRangeOverride?.timestamp_to,url_exact: values.hrefMatchType === 'exact' ? values.href : undefined,url_pattern: values.hrefMatchType === 'pattern' ? values.href : undefined,viewport_width_min: values.viewportRange.min,@@ -568,6 +605,17 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([],})),selectors(({ props }) => ({+ dateRangeOverride: [+ (s) => [s.historyView],+ (view: HeatmapHistoryView | null): HeatmapDateRangeOverride | null => view?.dateRange ?? null,+ ],+ effectiveCommonFilters: [+ (s) => [s.commonFilters, s.dateRangeOverride],+ (commonFilters: CommonFilters, dateRangeOverride: HeatmapDateRangeOverride | null): CommonFilters =>+ dateRangeOverride+ ? { ...commonFilters, date_from: dateRangeOverride.date_from, date_to: dateRangeOverride.date_to }+ : commonFilters,+ ],dateRange: [(s) => [s.commonFilters],(commonFilters: Partial<FilterType>) => {@@ -613,9 +661,11 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([// match that width and not the width of the analyst's own browser. In the toolbar the// overlay sits on the real page, so the live window width is the right anchor.analysisWidth: [- (s) => [s.windowWidthOverride, s.windowWidth],- (windowWidthOverride: number | null, windowWidth: number): number =>- windowWidthOverride ?? (props.context === 'in-app' ? DEFAULT_HEATMAP_WIDTH : windowWidth),+ (s) => [s.windowWidthOverride, s.windowWidth, s.historyView],+ (windowWidthOverride: number | null, windowWidth: number, historyView: HeatmapHistoryView | null): number =>+ historyView?.width ??+ windowWidthOverride ??+ (props.context === 'in-app' ? DEFAULT_HEATMAP_WIDTH : windowWidth),],viewportRange: [@@ -741,6 +791,12 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([actions.clearSelectedArea()actions.loadHeatmap()},+ setHistoryView: () => {+ actions.clearSelectedArea()+ actions.setIsReady(false)+ actions.resetHeatmapData()+ actions.loadHeatmap()+ },setHeatmapFilters: () => {actions.loadHeatmap()},@@ -767,7 +823,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([return}- const { date_from, date_to, filter_test_accounts, cohort_ids, events } = values.commonFilters+ const { date_from, date_to, filter_test_accounts, cohort_ids, events } = values.effectiveCommonFiltersconst { type } = values.heatmapFiltersconst nextOffset = currentEvents.results.length@@ -776,6 +832,8 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([type,date_from,date_to,+ timestamp_from: values.dateRangeOverride?.timestamp_from,+ timestamp_to: values.dateRangeOverride?.timestamp_to,url_exact: values.hrefMatchType === 'exact' ? values.href : undefined,url_pattern: values.hrefMatchType === 'pattern' ? values.href : undefined,viewport_width_min: values.viewportRange.min,diff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.pyindex 8ce68946d551..b6a8369591f6 100644--- a/products/web_analytics/backend/api/heatmaps_api.py+++ b/products/web_analytics/backend/api/heatmaps_api.py@@ -324,6 +324,17 @@ class HeatmapsRequestSerializer(serializers.Serializer):required=False,help_text="End of the window, inclusive. Relative or absolute 'YYYY-MM-DD'. Defaults to today.",)+ timestamp_from = serializers.DateTimeField(+ required=False,+ default_timezone=UTC,+ help_text="Inclusive UTC instant. Supply with timestamp_to to override date bounds.",+ )+ timestamp_to = serializers.DateTimeField(+ required=False,+ default_timezone=UTC,+ help_text="Exclusive UTC instant. Supply with timestamp_from to override date bounds.",+ )+url_exact = serializers.CharField(required=False,help_text="Match a single page by exact URL (trailing slash is ignored). Mutually exclusive with url_pattern.",@@ -471,6 +482,10 @@ class HeatmapsRequestSerializer(serializers.Serializer):return anchor_url_pattern(value)def validate(self, values) -> dict:+ if ("timestamp_from" in values) != ("timestamp_to" in values):+ raise serializers.ValidationError("Supply timestamp_from and timestamp_to together.")+ if "timestamp_from" in values and values["timestamp_from"] >= values["timestamp_to"]:+ raise serializers.ValidationError("timestamp_from must precede timestamp_to.")url_exact = values.get("url_exact", None)url_pattern = values.get("url_pattern", None)resolved = resolve_url_filter(url_exact, url_pattern)@@ -803,8 +818,12 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):if hide_zero_coordinates and not is_scrolldepth_query:exprs.append(parse_expr("NOT (x = 0 AND y = 0)"))- date_from: date = request_serializer.validated_data["date_from"]- date_to: date | None = request_serializer.validated_data.get("date_to", None)+ date_from: date | datetime = request_serializer.validated_data.get(+ "timestamp_from", request_serializer.validated_data["date_from"]+ )+ date_to: date | datetime | None = request_serializer.validated_data.get(+ "timestamp_to", request_serializer.validated_data.get("date_to")+ )exprs.extend(self._capture_allowlist_predicates(date_from, date_to))if request_serializer.validated_data.get("filter_test_accounts") is True:exprs.append(self._build_test_accounts_filter(date_from, date_to))@@ -839,7 +858,9 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):fold = self._compute_fold_summary(exprs)return self._return_heatmap_coordinates_response(results, fold, has_more)- def _capture_allowlist_predicates(self, date_from: date, date_to: date | None) -> List[ast.Expr]: # noqa: UP006+ def _capture_allowlist_predicates(+ self, date_from: date | datetime, date_to: date | datetime | None+ ) -> List[ast.Expr]: # noqa: UP006if not settings.HEATMAP_URL_ALLOWLIST_ENFORCEMENT_ENABLED:return []config = TeamHeatmapConfig.objects.filter(team_id=self.team.pk).first()@@ -891,8 +912,8 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):def _sessions_seen_in_events(self,- date_from: date,- date_to: date,+ date_from: date | datetime,+ date_to: date | datetime,*,filter_test_accounts: bool = False,predicate: ast.Expr | None = None,@@ -908,8 +929,12 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):HogQLFilters(filterTestAccounts=filter_test_accounts,dateRange=DateRange(- date_from=date_from.strftime("%Y-%m-%d"),- date_to=date_to.strftime("%Y-%m-%dT00:00:00"),+ date_from=date_from.isoformat()+ if isinstance(date_from, datetime)+ else date_from.strftime("%Y-%m-%d"),+ date_to=date_to.isoformat()+ if isinstance(date_to, datetime)+ else date_to.strftime("%Y-%m-%dT00:00:00"),),),self.team,@@ -929,18 +954,20 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):right=events_select,)- def _build_test_accounts_filter(self, date_from: date, date_to: date | None) -> ast.CompareOperation:+ def _build_test_accounts_filter(+ self, date_from: date | datetime, date_to: date | datetime | None+ ) -> ast.CompareOperation:# The heatmap predicate treats date_to as an inclusive day via `timestamp <= {date_to} + interval 1 day`.# Pass the same bound as an explicit next-day-midnight datetime, which HogQLFilters uses verbatim with a# strict `<`, so the events subquery covers the same inclusive days as the main heatmap query. A date-only# value would instead snap to the end of that next day and widen the window by a day.- events_date_to = (date_to or date.today()) + timedelta(days=1)+ events_date_to = date_to if isinstance(date_to, datetime) else (date_to or date.today()) + timedelta(days=1)return self._session_id_in(self._sessions_seen_in_events(date_from, events_date_to, filter_test_accounts=True))def _build_event_filters(self,- date_from: date,- date_to: date | None,+ date_from: date | datetime,+ date_to: date | datetime | None,events: List[dict[str, Any]], # noqa: UP006) -> List[ast.Expr]: # noqa: UP006"""One session subquery per selected event, so a heatmap row survives only when its session@@ -950,8 +977,12 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):per filter, because the combined form kept producing bugs. The cost here is an extra subqueryper filter, and a heatmap carries a handful of filters at most."""- events_date_from = date_from - EVENT_FILTER_SESSION_BUFFER- events_date_to = (date_to or date.today()) + timedelta(days=1) + EVENT_FILTER_SESSION_BUFFER+ events_date_from = date_from if isinstance(date_from, datetime) else date_from - EVENT_FILTER_SESSION_BUFFER+ events_date_to = (+ date_to+ if isinstance(date_to, datetime)+ else (date_to or date.today()) + timedelta(days=1) + EVENT_FILTER_SESSION_BUFFER+ )filters: list[ast.Expr] = []for entity in events:@@ -984,7 +1015,11 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# Compiled into session subqueries by _build_event_filters, not a heatmaps-table predicate.continueplaceholders[key] = Constant(value=value)- placeholders.setdefault("date_to", Constant(value=date.today().strftime("%Y-%m-%d")))+ if "timestamp_from" in validated_data:+ placeholders.pop("date_from", None)+ placeholders.pop("date_to", None)+ else:+ placeholders.setdefault("date_to", Constant(value=date.today().strftime("%Y-%m-%d")))return placeholders@staticmethod@@ -993,6 +1028,8 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):predicate_mapping: dict[str, str] = {# should always have values+ "timestamp_from": "timestamp >= {timestamp_from}",+ "timestamp_to": "timestamp < {timestamp_to}","date_from": "timestamp >= {date_from}","type": "`type` = {type}",# optional@@ -1118,8 +1155,8 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):else:exprs.append(ast.Or(exprs=point_conditions))- date_from: date = validated_data["date_from"]- date_to: date | None = validated_data.get("date_to", None)+ date_from: date | datetime = validated_data.get("timestamp_from", validated_data["date_from"])+ date_to: date | datetime | None = validated_data.get("timestamp_to", validated_data.get("date_to"))exprs.extend(self._capture_allowlist_predicates(date_from, date_to))if validated_data.get("filter_test_accounts") is True:exprs.append(self._build_test_accounts_filter(date_from, date_to))diff --git a/products/web_analytics/backend/test/test_heatmaps_api.py b/products/web_analytics/backend/test/test_heatmaps_api.pyindex 32722ea96348..0d582f55402c 100644--- a/products/web_analytics/backend/test/test_heatmaps_api.py+++ b/products/web_analytics/backend/test/test_heatmaps_api.py@@ -14,7 +14,7 @@ from posthog.test.base import ()from unittest.mock import patch-from django.test import override_settings+from django.test import SimpleTestCase, override_settingsfrom django.utils import timezonefrom parameterized import parameterized@@ -27,6 +27,7 @@ from posthog.models import Organization, Teamfrom posthog.models.event.util import format_clickhouse_timestampfrom posthog.models.team.team_heatmap_config import TeamHeatmapConfig+from products.web_analytics.backend.api.heatmaps_api import HeatmapsRequestSerializerfrom products.web_analytics.backend.models.heatmap_capture_config_version import HeatmapCaptureConfigVersionINSERT_SINGLE_HEATMAP_EVENT = """@@ -63,6 +64,39 @@ SELECTclass TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest):CLASS_DATA_LEVEL_SETUP = False+ def test_exact_timestamp_interval_is_half_open_for_overlay_and_area_events(self) -> None:+ for timestamp in ("2024-03-10T05:00:00", "2024-03-11T03:59:59", "2024-03-11T04:00:00"):+ self._create_heatmap_event("interval-session", "click", date_from=timestamp, x=20, y=20)+ params: dict[str, str | int | None] = {+ "timestamp_from": "2024-03-10T05:00:00Z",+ "timestamp_to": "2024-03-11T04:00:00Z",+ "date_from": "2024-03-12",+ "type": "click",+ }+ self._assert_heatmap_single_result_count(params, 2)+ result = self._get_heatmap(params).data["results"][0]+ points = quote(dumps([{"x": result["pointer_relative_x"], "y": result["pointer_y"], "target_fixed": True}]))+ drill = self.client.get(+ f"/api/heatmap/events/?timestamp_from=2024-03-10T05:00:00Z×tamp_to=2024-03-11T04:00:00Z&type=click&points={points}"+ )+ assert drill.status_code == 200+ assert drill.data["total_count"] == 2++ def test_exact_interval_also_bounds_event_session_filters(self) -> None:+ self._create_heatmap_event("inside", "click", date_from="2024-05-01T12:00:00", x=20, y=20)+ self._create_heatmap_event("outside", "click", date_from="2024-05-01T12:00:00", x=20, y=20)+ self.create_event(session_id="inside", timestamp="2024-05-01T04:00:00", event_name="purchase", properties={})+ self.create_event(session_id="outside", timestamp="2024-05-02T04:00:00", event_name="purchase", properties={})+ with self._event_filter_flag(True):+ self._assert_heatmap_single_result_count(+ {+ "timestamp_from": "2024-05-01T04:00:00Z",+ "timestamp_to": "2024-05-02T04:00:00Z",+ "events": self._events_param([{"id": "purchase"}]),+ },+ 1,+ )+def _assert_heatmap_no_result_count(self, params: dict[str, str | int | None] | None, expected_status_code: int = status.HTTP_200_OK) -> None:@@ -952,3 +986,16 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest){"date_from": "2023-03-08", "events": quote(events, safe="")},expected_status_code=status.HTTP_400_BAD_REQUEST,)+++class TestHeatmapsRequestIntervals(SimpleTestCase):+ @parameterized.expand(+ [+ ({"timestamp_from": "2024-05-01T00:00:00Z"},),+ ({"timestamp_to": "2024-05-02T00:00:00Z"},),+ ({"timestamp_from": "2024-05-02T00:00:00Z", "timestamp_to": "2024-05-01T00:00:00Z"},),+ ]+ )+ def test_invalid_intervals_are_rejected(self, params: dict[str, str]) -> None:+ serializer = HeatmapsRequestSerializer(data=params, context={"team": Team(timezone="UTC")})+ assert not serializer.is_valid()diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.tsindex f44106a4da5d..7d5c486eb066 100644--- a/products/web_analytics/frontend/generated/api.schemas.ts+++ b/products/web_analytics/frontend/generated/api.schemas.ts@@ -1556,6 +1556,14 @@ export type HeatmapsListParams = {* @maximum 1000000*/offset?: number+ /**+ * Inclusive UTC instant. Supply with timestamp_to to override date bounds.+ */+ timestamp_from?: string+ /**+ * Exclusive UTC instant. Supply with timestamp_from to override date bounds.+ */+ timestamp_to?: 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@@ -1642,6 +1650,14 @@ export type HeatmapsEventsRetrieveParams = {* @minLength 1*/points: string+ /**+ * Inclusive UTC instant. Supply with timestamp_to to override date bounds.+ */+ timestamp_from?: string+ /**+ * Exclusive UTC instant. Supply with timestamp_from to override date bounds.+ */+ timestamp_to?: string/*** The interaction type to return. One of: 'click' (default), 'rageclick', 'mousemove', or 'scrolldepth'. Scrolldepth returns scroll buckets instead of x/y coordinates.* @minLength 1diff --git a/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.tsx b/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.tsxindex 01afbc635747..f292a5725063 100644--- a/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.tsx+++ b/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.tsx@@ -65,12 +65,14 @@ export function HeatmapScene({ id }: { id: string }): JSX.Element {regenerateDisabledReason,switchToScreenshotDisabledReason,displayUrlIsPattern,+ historyView,} = useValues(logic)const {setName,onIframeLoad,setScreenshotLoaded,setScreenshotError,+ setHistoryScreenshotStatus,exportHeatmap,setContainerWidth,discardChanges,@@ -283,13 +285,21 @@ export function HeatmapScene({ id }: { id: string }): JSX.Element {display: 'block',}}onLoad={() => {- setScreenshotLoaded(true)- setScreenshotError(null)+ if (historyView) {+ setHistoryScreenshotStatus(historyView.imageUrl, true)+ } else {+ setScreenshotLoaded(true)+ setScreenshotError(null)+ }}}className="rounded-b-lg border-l border-r border-b"onError={() => {- setScreenshotLoaded(false)- setScreenshotError('The screenshot failed to load.')+ if (historyView) {+ setHistoryScreenshotStatus(historyView.imageUrl, false)+ } else {+ setScreenshotLoaded(false)+ setScreenshotError('The screenshot failed to load.')+ }}}/></>diff --git a/products/web_analytics/frontend/heatmaps/scenes/heatmap/heatmapLogic.ts b/products/web_analytics/frontend/heatmaps/scenes/heatmap/heatmapLogic.tsindex 0aa525c21d92..72981363d0e6 100644--- a/products/web_analytics/frontend/heatmaps/scenes/heatmap/heatmapLogic.ts+++ b/products/web_analytics/frontend/heatmaps/scenes/heatmap/heatmapLogic.ts@@ -5,7 +5,7 @@ import posthog from 'posthog-js'import type { JSX } from 'react'import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'-import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'+import { HeatmapHistoryView, heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'import { hasWildcard } from 'lib/components/heatmaps/heatmapUrlMatch'import type { CommonFilters, HeatmapFilters, HeatmapFixedPositionMode } from 'lib/components/heatmaps/types'import { DEFAULT_HEATMAP_WIDTH } from 'lib/components/IframedToolbarBrowser/utils'@@ -136,6 +136,7 @@ export interface heatmapLogicValues {heatmapFilters: HeatmapFilters // heatmapDataLogicheatmapFixedPositionMode: HeatmapFixedPositionMode // heatmapDataLogicheightOverride: number // heatmapDataLogic+ historyView: HeatmapHistoryView | null // heatmapDataLogicisHeightCapped: boolean // heatmapDataLogicwidthOverride: number // heatmapDataLogiccurrentPagePreflight: PagePreflight | null // heatmapsBrowserLogic@@ -148,6 +149,10 @@ export interface heatmapLogicValues {currentTeamIdStrict: number | string // teamLogicblockConsentModals: booleancontainerWidth: number | null+ currentLockedWidth: number | null+ currentScreenshotError: string | null+ currentScreenshotLoaded: boolean+ currentScreenshotUrl: string | nulldataUrlEditDisabledReason: string | nulldesiredNumericWidth: numberdisplayUrlIsPattern: boolean@@ -157,6 +162,10 @@ export interface heatmapLogicValues {generatingScreenshot: booleanhasUnsavedChanges: booleanheatmapId: string | null+ historyScreenshotStatus: {+ loaded: boolean+ url: string+ } | nullisDisplayUrlValid: booleanisPageUrlDraftValid: booleanloading: boolean@@ -200,6 +209,9 @@ export interface heatmapLogicActions {loadHeatmap: () => {value: true} // heatmapDataLogic+ setHistoryView: (view: HeatmapHistoryView | null) => {+ view: HeatmapHistoryView | null+ } // heatmapDataLogicsetWindowWidthOverride: (widthOverride: number | null) => {widthOverride: number | null} // heatmapDataLogic@@ -269,6 +281,13 @@ export interface heatmapLogicActions {setHeatmapId: (id: string | null) => {id: string | null}+ setHistoryScreenshotStatus: (+ url: string,+ loaded: boolean+ ) => {+ loaded: boolean+ url: string+ }setLoading: (loading: boolean) => {loading: boolean}@@ -325,6 +344,8 @@ export interface heatmapLogicProps {export interface heatmapLogicMeta {key: number | string__keaTypeGenInternalSelectorTypes: {+ screenshotUrl: (currentScreenshotUrl: string | null, historyView: HeatmapHistoryView | null) => string | null+ lockedWidth: (currentLockedWidth: number | null, historyView: HeatmapHistoryView | null) => number | nulldraftSettings: (name: string,pageUrlDraft: string,@@ -364,7 +385,27 @@ export interface heatmapLogicMeta {iframeBanner: IFrameBanner | null,currentPagePreflight: PagePreflight | null) => string | JSX.Element | null- previewUnavailable: (previewError: string | JSX.Element | null, generatingScreenshot: boolean) => boolean+ screenshotLoaded: (+ currentScreenshotLoaded: boolean,+ historyScreenshotStatus: {+ loaded: boolean+ url: string+ } | null,+ historyView: HeatmapHistoryView | null+ ) => boolean+ screenshotError: (+ currentScreenshotError: string | null,+ historyScreenshotStatus: {+ loaded: boolean+ url: string+ } | null,+ historyView: HeatmapHistoryView | null+ ) => string | null+ previewUnavailable: (+ previewError: string | JSX.Element | null,+ generatingScreenshot: boolean,+ historyView: HeatmapHistoryView | null+ ) => booleanisDisplayUrlValid: (displayUrl: string | null) => booleandisplayUrlIsPattern: (displayUrl: string | null) => booleanisPageUrlDraftValid: (pageUrlDraft: string) => boolean@@ -413,6 +454,7 @@ export const heatmapLogic = kea<heatmapLogicType>(['widthOverride','heightOverride','isHeightCapped',+ 'historyView',],],actions: [@@ -421,7 +463,7 @@ export const heatmapLogic = kea<heatmapLogicType>([heatmapsSceneLogic,['loadSavedHeatmaps', 'setSavedHeatmaps'],heatmapDataLogic({ context: 'in-app' }),- ['loadHeatmap', 'setWindowWidthOverride'],+ ['loadHeatmap', 'setWindowWidthOverride', 'setHistoryView'],exportsLogic,['startHeatmapExport'],],@@ -449,6 +491,7 @@ export const heatmapLogic = kea<heatmapLogicType>([pollScreenshotStatus: (width?: number) => ({ width }),setHeatmapId: (id: string | null) => ({ id }),setScreenshotLoaded: (screenshotLoaded: boolean) => ({ screenshotLoaded }),+ setHistoryScreenshotStatus: (url: string, loaded: boolean) => ({ url, loaded }),setLockedWidth: (lockedWidth: number | null) => ({ lockedWidth }),regenerateScreenshot: true,generateScreenshot: true,@@ -469,13 +512,20 @@ export const heatmapLogic = kea<heatmapLogicType>([name: ['New heatmap', { setName: (_, { name }) => name }],loading: [false, { setLoading: (_, { loading }) => loading }],status: ['processing' as HeatmapStatus, { setStatus: (_, { status }) => status }],- screenshotUrl: [null as string | null, { setScreenshotUrl: (_, { url }) => url }],- screenshotError: [null as string | null, { setScreenshotError: (_, { error }) => error }],+ currentScreenshotUrl: [null as string | null, { setScreenshotUrl: (_, { url }) => url }],+ currentScreenshotError: [null as string | null, { setScreenshotError: (_, { error }) => error }],generatingScreenshot: [false, { setGeneratingScreenshot: (_, { generating }) => generating }],// expose a screenshotLoading alias for UI compatibilityscreenshotLoading: [false as boolean, { setScreenshotUrl: () => false }],heatmapId: [null as string | null, { setHeatmapId: (_, { id }) => id }],- screenshotLoaded: [false, { setScreenshotLoaded: (_, { screenshotLoaded }) => screenshotLoaded }],+ currentScreenshotLoaded: [false, { setScreenshotLoaded: (_, { screenshotLoaded }) => screenshotLoaded }],+ historyScreenshotStatus: [+ null as { url: string; loaded: boolean } | null,+ {+ setHistoryScreenshotStatus: (_, { url, loaded }) => ({ url, loaded }),+ setHistoryView: (state, { view }) => (view ? state : null),+ },+ ],containerWidth: [null as number | null, { setContainerWidth: (_, { containerWidth }) => containerWidth }],blockConsentModals: [false as boolean, { setBlockConsentModals: (_, { value }) => value }],pageUrlDraft: [@@ -486,7 +536,7 @@ export const heatmapLogic = kea<heatmapLogicType>([},],userAccessLevel: [null as AccessControlLevel | null, { setUserAccessLevel: (_, { level }) => level }],- lockedWidth: [null as number | null, { setLockedWidth: (_, { lockedWidth }) => lockedWidth }],+ currentLockedWidth: [null as number | null, { setLockedWidth: (_, { lockedWidth }) => lockedWidth }],}),listeners(({ actions, values, props, cache }) => ({load: async () => {@@ -770,6 +820,9 @@ export const heatmapLogic = kea<heatmapLogicType>([}},exportHeatmap: () => {+ if (values.historyView) {+ return+ }if ((values.previewType === 'screenshot' && !values.screenshotUrl) ||(!values.displayUrl && !values.dataUrl)@@ -791,6 +844,14 @@ export const heatmapLogic = kea<heatmapLogicType>([},})),selectors({+ screenshotUrl: [+ (s) => [s.currentScreenshotUrl, s.historyView],+ (url: string | null, view: HeatmapHistoryView | null): string | null => view?.imageUrl ?? url,+ ],+ lockedWidth: [+ (s) => [s.currentLockedWidth, s.historyView],+ (width: number | null, view: HeatmapHistoryView | null): number | null => view?.width ?? width,+ ],draftSettings: [(s) => [s.name, s.pageUrlDraft, s.dataUrl, s.type, s.blockConsentModals],(@@ -909,9 +970,31 @@ export const heatmapLogic = kea<heatmapLogicType>([: message},],+ screenshotLoaded: [+ (s) => [s.currentScreenshotLoaded, s.historyScreenshotStatus, s.historyView],+ (+ current: boolean,+ status: { url: string; loaded: boolean } | null,+ view: HeatmapHistoryView | null+ ): boolean => (view ? status?.url === view.imageUrl && status.loaded : current),+ ],+ screenshotError: [+ (s) => [s.currentScreenshotError, s.historyScreenshotStatus, s.historyView],+ (+ current: string | null,+ status: { url: string; loaded: boolean } | null,+ view: HeatmapHistoryView | null+ ): string | null =>+ view+ ? status?.url === view.imageUrl && !status.loaded+ ? 'The historical screenshot failed to load.'+ : null+ : current,+ ],previewUnavailable: [- (s) => [s.previewError, s.generatingScreenshot],- (error: string | JSX.Element | null, generating: boolean): boolean => !!error || generating,+ (s) => [s.previewError, s.generatingScreenshot, s.historyView],+ (error: string | JSX.Element | null, generating: boolean, view: HeatmapHistoryView | null): boolean =>+ !!error || (generating && !view),],isDisplayUrlValid: [(s) => [s.displayUrl], (displayUrl: string | null) => isValidPageUrl(displayUrl)],displayUrlIsPattern: [(s) => [s.displayUrl], (displayUrl: string | null) => hasWildcard(displayUrl ?? '')],diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f82df5d238b6..e692f1562dc9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -122302,6 +122302,14 @@ export namespace Schemas {* @maximum 1000000*/offset?: number;+ /**+ * Inclusive UTC instant. Supply with timestamp_to to override date bounds.+ */+ timestamp_from?: string;+ /**+ * Exclusive UTC instant. Supply with timestamp_from to override date bounds.+ */+ timestamp_to?: 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@@ -122389,6 +122397,14 @@ export namespace Schemas {* @minLength 1*/points: string;+ /**+ * Inclusive UTC instant. Supply with timestamp_to to override date bounds.+ */+ timestamp_from?: string;+ /**+ * Exclusive UTC instant. Supply with timestamp_from to override date bounds.+ */+ timestamp_to?: string;/*** The interaction type to return. One of: 'click' (default), 'rageclick', 'mousemove', or 'scrolldepth'. Scrolldepth returns scroll buckets instead of x/y coordinates.* @minLength 1diff --git a/services/mcp/src/generated/web_analytics/api.ts b/services/mcp/src/generated/web_analytics/api.tsindex 6b09a609f33e..125df22b27c1 100644--- a/services/mcp/src/generated/web_analytics/api.ts+++ b/services/mcp/src/generated/web_analytics/api.ts@@ -88,6 +88,14 @@ export const HeatmapsListQueryParams = () => zod.object({.describe("Number of hottest-first points to skip, for paging through cooler coordinates. Ignored for the 'scrolldepth' type."),+ timestamp_from: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe('Inclusive UTC instant. Supply with timestamp_to to override date bounds.'),+ timestamp_to: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe('Exclusive UTC instant. Supply with timestamp_from to override date bounds.'),type: zod.string().min(1)@@ -198,6 +206,14 @@ export const HeatmapsEventsRetrieveQueryParams = () => zod.object({.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."),+ timestamp_from: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe('Inclusive UTC instant. Supply with timestamp_to to override date bounds.'),+ timestamp_to: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe('Exclusive UTC instant. Supply with timestamp_from to override date bounds.'),type: zod.string().min(1)diff --git a/services/mcp/src/tools/generated/web_analytics.ts b/services/mcp/src/tools/generated/web_analytics.tsindex e97d9c772921..dfb8123e585f 100644--- a/services/mcp/src/tools/generated/web_analytics.ts+++ b/services/mcp/src/tools/generated/web_analytics.ts@@ -31,6 +31,8 @@ const heatmapsEvents = (): ToolBase<ReturnType<typeof HeatmapsEventsSchema>, Schlimit: params.limit,offset: params.offset,points: params.points,+ timestamp_from: params.timestamp_from,+ timestamp_to: params.timestamp_to,type: params.type,url_exact: params.url_exact,url_pattern: params.url_pattern,@@ -68,6 +70,8 @@ const heatmapsList = (): ToolBase<hide_zero_coordinates: params.hide_zero_coordinates,limit: params.limit,offset: params.offset,+ timestamp_from: params.timestamp_from,+ timestamp_to: params.timestamp_to,type: params.type,url_exact: params.url_exact,url_pattern: params.url_pattern,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/heatmaps-events.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/heatmaps-events.jsonindex ae43342bb47a..349ddf75fc31 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/heatmaps-events.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/heatmaps-events.json@@ -74,6 +74,18 @@"minLength": 1,"type": "string"},+ "timestamp_from": {+ "description": "Inclusive UTC instant. Supply with timestamp_to to override date bounds.",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },+ "timestamp_to": {+ "description": "Exclusive UTC instant. Supply with timestamp_from to override date bounds.",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },"type": {"default": "click","description": "The interaction type to return. One of: 'click' (default), 'rageclick', 'mousemove', or 'scrolldepth'. Scrolldepth returns scroll buckets instead of x/y coordinates.",diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/heatmaps-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/heatmaps-list.jsonindex 1a26c4b10c9f..21880cbdc29a 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/heatmaps-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/heatmaps-list.json@@ -70,6 +70,18 @@"minimum": 0,"type": "number"},+ "timestamp_from": {+ "description": "Inclusive UTC instant. Supply with timestamp_to to override date bounds.",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },+ "timestamp_to": {+ "description": "Exclusive UTC instant. Supply with timestamp_from to override date bounds.",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },"type": {"default": "click","description": "The interaction type to return. One of: 'click' (default), 'rageclick', 'mousemove', or 'scrolldepth'. Scrolldepth returns scroll buckets instead of x/y coordinates.",