: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(replay-vision): add product intent (#75191)
coryslatereac266f41ac7
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 731669806e0f..b3719d6ef412 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -39916,6 +39916,9 @@"session_replay_set_filters","session_replay_experiment_link_clicked","session_replay_save_filters_as_scanner",+ "replay_vision_viewed",+ "replay_vision_scanner_created",+ "replay_vision_scan_triggered","error_tracking_exception_autocapture_enabled","error_tracking_issue_sorting","error_tracking_docs_viewed",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex be94e26ed683..df5d3218219c 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -10181,6 +10181,14 @@ export enum ProductIntentContext {SESSION_REPLAY_EXPERIMENT_LINK_CLICKED = 'session_replay_experiment_link_clicked',SESSION_REPLAY_SAVE_FILTERS_AS_SCANNER = 'session_replay_save_filters_as_scanner',+ // Replay Vision+ // Shallow: dwelled on the scanner list long enough to have read it. Deliberately not a bare+ // pageview — a mount-and-bounce must not start the activation clock for the team.+ REPLAY_VISION_VIEWED = 'replay_vision_viewed',+ // Deep, both registered server-side so agent/API callers count too, not just the app.+ REPLAY_VISION_SCANNER_CREATED = 'replay_vision_scanner_created',+ REPLAY_VISION_SCAN_TRIGGERED = 'replay_vision_scan_triggered',+// Error TrackingERROR_TRACKING_EXCEPTION_AUTOCAPTURE_ENABLED = 'error_tracking_exception_autocapture_enabled',ERROR_TRACKING_ISSUE_SORTING = 'error_tracking_issue_sorting',diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex a45192707cce..073ee7fdb71a 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -3593,6 +3593,9 @@ class ProductIntentContext(StrEnum):SESSION_REPLAY_SET_FILTERS = "session_replay_set_filters"SESSION_REPLAY_EXPERIMENT_LINK_CLICKED = "session_replay_experiment_link_clicked"SESSION_REPLAY_SAVE_FILTERS_AS_SCANNER = "session_replay_save_filters_as_scanner"+ REPLAY_VISION_VIEWED = "replay_vision_viewed"+ REPLAY_VISION_SCANNER_CREATED = "replay_vision_scanner_created"+ REPLAY_VISION_SCAN_TRIGGERED = "replay_vision_scan_triggered"ERROR_TRACKING_EXCEPTION_AUTOCAPTURE_ENABLED = "error_tracking_exception_autocapture_enabled"ERROR_TRACKING_ISSUE_SORTING = "error_tracking_issue_sorting"ERROR_TRACKING_DOCS_VIEWED = "error_tracking_docs_viewed"diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 63423a856909..a56074a5b76d 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -17,6 +17,7 @@ from drf_spectacular.utils import (extend_schema_field,extend_schema_view,)+from loginas.utils import is_impersonated_sessionfrom pydantic import ValidationError as PydanticValidationErrorfrom rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import action@@ -24,13 +25,15 @@ from rest_framework.exceptions import NotFound, PermissionDenied, Throttled, Valfrom rest_framework.request import Requestfrom rest_framework.response import Response-from posthog.schema import RecordingsQuery+from posthog.schema import ProductIntentContext, ProductKey, RecordingsQueryfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.tagged_item import TaggedItemSerializerMixin, set_tags_on_object-from posthog.event_usage import EventSource, get_event_source, report_user_action+from posthog.event_usage import EventSource, get_event_source, get_request_analytics_properties, report_user_actionfrom posthog.exceptions import QuotaLimitExceeded+from posthog.exceptions_capture import capture_exception+from posthog.models.product_intent.product_intent import ProductIntentfrom posthog.models.tag import tagifyfrom posthog.models.tagged_item import TaggedItemfrom posthog.models.team import Team@@ -233,6 +236,30 @@ _QUERY_FILTER_KEYS = ()+def _register_replay_vision_intent(+ request: Request,+ team: Team,+ context: ProductIntentContext,+ metadata: dict[str, Any],+) -> None:+ # Call at most once per request: register() writes a row every time, and a bulk scan can carry+ # hundreds of session ids.+ # Staff impersonating a customer is not the team's intent, so skip rather than fail the request.+ if is_impersonated_session(request):+ return+ # Best-effort: the scan or create already happened, so a failure must not 500 and invite a retry.+ try:+ ProductIntent.register(+ team=team,+ product_type=ProductKey.REPLAY_VISION,+ context=context,+ user=cast(User, request.user),+ metadata={**get_request_analytics_properties(request), **metadata},+ )+ except Exception as e:+ capture_exception(e)++def _scanner_lifecycle_properties(scanner: ReplayScanner) -> dict[str, Any]:"""Config choices at save time, so launch dashboards can see whether the defaults get changed.Filter *values* stay out: they can carry customer data (URLs, emails)."""@@ -1704,6 +1731,20 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi)return response+ def perform_create(self, serializer: Any) -> None:+ super().perform_create(serializer)+ # Saving a scanner means writing a prompt and picking a type, which is the least ambiguous+ # "wants to use this" signal the product has.+ _register_replay_vision_intent(+ self.request,+ self.team,+ ProductIntentContext.REPLAY_VISION_SCANNER_CREATED,+ {+ "scanner_id": str(serializer.instance.id),+ "scanner_type": serializer.instance.scanner_type,+ },+ )+def perform_destroy(self, instance: ReplayScanner) -> None:# Snapshot lifecycle props before the row is deleted.properties = _scanner_lifecycle_properties(instance)@@ -1896,6 +1937,16 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viteam=self.team,request=request,)+ _register_replay_vision_intent(+ request,+ self.team,+ ProductIntentContext.REPLAY_VISION_SCAN_TRIGGERED,+ {+ "scanner_id": str(scanner.id),+ "scanner_type": scanner.scanner_type,+ "scan_shape": "single",+ },+ )return Response(ObserveResponseSerializer({"workflow_id": workflow_id}).data,status=status.HTTP_202_ACCEPTED,@@ -1949,6 +2000,21 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viteam=self.team,request=request,)+ # Once for the batch, not once per session: `register()` writes the row on every call and+ # `session_ids` can be in the hundreds. Registered even when everything was skipped, because+ # asking for a scan you didn't get the quota for is still intent.+ _register_replay_vision_intent(+ request,+ self.team,+ ProductIntentContext.REPLAY_VISION_SCAN_TRIGGERED,+ {+ "scanner_id": str(scanner.id),+ "scanner_type": scanner.scanner_type,+ "scan_shape": "bulk",+ "requested": len(session_ids),+ "started": started,+ },+ )# Key off the outcomes, not skip_reason: skip_reason only names the limit that would bind# first, and a batch that never reached the cap must not report exhaustion.if any(result["scan_outcome"] == "skipped_quota" for result in results):diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex af147310483b..5347de5dc2ef 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -16,9 +16,12 @@ from prometheus_client import REGISTRYfrom rest_framework.exceptions import ValidationError as DRFValidationErrorfrom temporalio.exceptions import WorkflowAlreadyStartedError+from posthog.schema import ProductIntentContext, ProductKey+from posthog.api.tagged_item import set_tags_on_objectfrom posthog.event_usage import EventSourcefrom posthog.models import Organization, PersonalAPIKey, Team, User+from posthog.models.product_intent.product_intent import ProductIntentfrom posthog.models.tagged_item import TaggedItemfrom posthog.models.utils import generate_random_token_personal, hash_key_value, uuid7from posthog.redis import get_client@@ -4073,3 +4076,175 @@ class TestScannerSelfDrivingStatsAPI(_VisionAPITestCase):assert kwargs["source_product"] == "replay_vision"assert kwargs["source_type"] == "scanner_finding"assert kwargs["extra_equals"] == {"scanner_id": str(scanner.id)}+++@patch("products.replay_vision.backend.api.trigger.async_to_sync")+@patch("products.replay_vision.backend.api.trigger.sync_connect")+class TestReplayVisionProductIntent(_VisionAPITestCase):+ def setUp(self) -> None:+ super().setUp()+ self.scanner = self._create_scanner()+ get_client().delete(_team_key(self.team.id), _scanner_key(self.scanner.id))++ def observe_url(self, scanner_id: str) -> str:+ return f"{self.scanners_url}{scanner_id}/observe/"++ def bulk_url(self, scanner_id: str) -> str:+ return f"{self.scanners_url}{scanner_id}/bulk_observe/"++ def _intent(self) -> ProductIntent | None:+ return ProductIntent.objects.filter(team=self.team, product_type=ProductKey.REPLAY_VISION).first()++ def test_no_intent_before_anyone_touches_the_product(+ self, _mock_sync_connect: MagicMock, _mock_async_to_sync: MagicMock+ ) -> None:+ # Guards the baseline the other tests rest on: `_create_scanner` writes the row directly, so+ # only requests through the API register intent.+ self.assertIsNone(self._intent())++ def test_creating_a_scanner_registers_intent(+ self, _mock_sync_connect: MagicMock, _mock_async_to_sync: MagicMock+ ) -> None:+ resp = self.client.post(+ self.scanners_url,+ data={+ "name": "intent-create",+ "scanner_type": ScannerType.MONITOR,+ "scanner_config": {"prompt": "did checkout complete?"},+ "model": ScannerModel.GEMINI_3_8_FLASH,+ },+ format="json",+ )+ self.assertEqual(resp.status_code, 201, resp.json())++ intent = self._intent()+ assert intent is not None+ self.assertEqual(intent.contexts, {ProductIntentContext.REPLAY_VISION_SCANNER_CREATED: 1})++ def test_on_demand_scan_registers_intent(self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock) -> None:+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()++ resp = self.client.post(+ self.observe_url(str(self.scanner.id)), data={"session_id": "sess-intent"}, format="json"+ )+ self.assertEqual(resp.status_code, 202, resp.json())++ intent = self._intent()+ assert intent is not None+ self.assertEqual(intent.contexts, {ProductIntentContext.REPLAY_VISION_SCAN_TRIGGERED: 1})++ def test_bulk_scan_registers_intent_once_for_the_batch(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # The load-bearing assertion in this file: `register()` writes the intent row on every call,+ # and a bulk scan can carry hundreds of session ids. Registering per session would turn one+ # click into hundreds of writes on a request path that already fans out to Temporal.+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()++ resp = self.client.post(+ self.bulk_url(str(self.scanner.id)),+ data={"session_ids": ["sess-a", "sess-b", "sess-c", "sess-d"]},+ format="json",+ )+ self.assertEqual(resp.status_code, 202, resp.json())++ intent = self._intent()+ assert intent is not None+ self.assertEqual(intent.contexts, {ProductIntentContext.REPLAY_VISION_SCAN_TRIGGERED: 1})++ def test_intent_records_the_calling_surface(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # `source` is what makes "do agent-triggered scans count toward activation" a filter rather+ # than a re-instrumentation, so it has to reach the emitted event.+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()++ with patch("posthoganalytics.capture") as capture:+ resp = self.client.post(+ self.observe_url(str(self.scanner.id)),+ data={"session_id": "sess-source"},+ format="json",+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ self.assertEqual(resp.status_code, 202, resp.json())++ intent_events = [+ call for call in capture.call_args_list if call.kwargs.get("event") == "user showed product intent"+ ]+ self.assertEqual(len(intent_events), 1)+ properties = intent_events[0].kwargs["properties"]+ self.assertEqual(properties["product_key"], ProductKey.REPLAY_VISION)+ self.assertEqual(properties["intent_context"], ProductIntentContext.REPLAY_VISION_SCAN_TRIGGERED)+ self.assertEqual(properties["source"], "mcp")+ self.assertTrue(properties["is_first_intent_for_product"])++ def test_repeat_actions_accumulate_contexts_without_moving_the_clock(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # One row per (team, product), so `created_at` must stay put across later actions — it's the+ # funnel start date. The per-context counters are what activation criteria read.+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()++ self.client.post(self.observe_url(str(self.scanner.id)), data={"session_id": "sess-1"}, format="json")+ first = self._intent()+ assert first is not None+ created_at = first.created_at++ self.client.post(self.observe_url(str(self.scanner.id)), data={"session_id": "sess-2"}, format="json")+ self.client.post(+ self.scanners_url,+ data={+ "name": "intent-second-action",+ "scanner_type": ScannerType.MONITOR,+ "scanner_config": {"prompt": "did checkout complete?"},+ "model": ScannerModel.GEMINI_3_8_FLASH,+ },+ format="json",+ )++ self.assertEqual(ProductIntent.objects.filter(team=self.team, product_type=ProductKey.REPLAY_VISION).count(), 1)+ intent = self._intent()+ assert intent is not None+ self.assertEqual(intent.created_at, created_at)+ self.assertEqual(+ intent.contexts,+ {+ ProductIntentContext.REPLAY_VISION_SCAN_TRIGGERED: 2,+ ProductIntentContext.REPLAY_VISION_SCANNER_CREATED: 1,+ },+ )++ def test_impersonated_session_does_not_register_intent(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # Staff impersonating a customer would otherwise start that team's activation clock.+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()++ with patch("products.replay_vision.backend.api.scanners.is_impersonated_session", return_value=True):+ resp = self.client.post(+ self.observe_url(str(self.scanner.id)), data={"session_id": "sess-impersonated"}, format="json"+ )++ self.assertEqual(resp.status_code, 202, resp.json())+ self.assertIsNone(self._intent())++ def test_intent_failure_does_not_fail_the_request(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # Intent is registered after the workflow has started; a 500 here would make the caller+ # retry a scan that already ran.+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()++ with patch.object(ProductIntent, "register", side_effect=Exception("intent backend down")):+ resp = self.client.post(+ self.observe_url(str(self.scanner.id)), data={"session_id": "sess-intent-down"}, format="json"+ )++ self.assertEqual(resp.status_code, 202, resp.json())+ self.assertIsNone(self._intent())diff --git a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.tsindex a50e69b3ee65..5e1c95b4a842 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts@@ -2,14 +2,18 @@ import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { addProductIntent } from 'lib/utils/product-intents'+import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'import { tagsModel } from '~/models/tagsModel'+import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { visionQuotaLogic } from '../logics/visionQuotaLogic'import { makeQuota as makeQuotaFixture } from '../utils/quotaTestUtils'import {+ REPLAY_VISION_INTENT_DWELL_MS,buildScannerListParams,replayScannersLogic,resolveScannerOrderByKey,@@ -17,6 +21,10 @@ import {} from './replayScannersLogic'import { ScannerConfig, ScannerType, ReplayScanner } from './types'+jest.mock('lib/utils/product-intents', () => ({+ addProductIntent: jest.fn().mockResolvedValue(null),+}))+const quotaFixture = makeQuotaFixture({credit_limit: 1000,credits_used: 100,@@ -535,4 +543,55 @@ describe('replayScannersLogic', () => {expect(logic.values.filters.page).toBe(1)expect(logic.values.scanners).toHaveLength(1)})++ describe('shallow product intent', () => {+ // The dwell gate is the whole point of this signal: there is one ProductIntent row per team+ // and its created_at starts the 30-day activation clock, so a mount-and-bounce must not+ // register. This is the bug that read Surveys' activation down from 10.5% to 2.8%.+ beforeEach(() => {+ jest.useFakeTimers()+ ;(addProductIntent as jest.Mock).mockClear()+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ it('does not register on mount alone', () => {+ router.actions.push(urls.replayVision())+ jest.advanceTimersByTime(REPLAY_VISION_INTENT_DWELL_MS - 1)++ expect(addProductIntent).not.toHaveBeenCalled()+ })++ it('registers once the dwell threshold passes', () => {+ router.actions.push(urls.replayVision())+ jest.advanceTimersByTime(REPLAY_VISION_INTENT_DWELL_MS)++ expect(addProductIntent).toHaveBeenCalledTimes(1)+ expect(addProductIntent).toHaveBeenCalledWith({+ product_type: ProductKey.REPLAY_VISION,+ intent_context: ProductIntentContext.REPLAY_VISION_VIEWED,+ })+ })++ it('registers once, not once per filter change', () => {+ // urlToAction re-fires on every filter change, and each re-arm would be another write.+ router.actions.push(urls.replayVision())+ router.actions.push(`${urls.replayVision()}?search=checkout`)+ router.actions.push(`${urls.replayVision()}?search=refund`)+ jest.advanceTimersByTime(REPLAY_VISION_INTENT_DWELL_MS * 3)++ expect(addProductIntent).toHaveBeenCalledTimes(1)+ })++ it('does not register after unmount', () => {+ router.actions.push(urls.replayVision())+ logic.unmount()+ jest.advanceTimersByTime(REPLAY_VISION_INTENT_DWELL_MS * 2)++ expect(addProductIntent).not.toHaveBeenCalled()+ logic.mount()+ })+ })})diff --git a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.tsindex b4c24de75dd4..7fa606367194 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts@@ -16,10 +16,12 @@ import { router, urlToAction } from 'kea-router'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'import { objectsEqual } from 'lib/utils/objects'+import { addProductIntent } from 'lib/utils/product-intents'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { tagsModel } from '~/models/tagsModel'+import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import {visionScannersCreatorsRetrieve,@@ -72,6 +74,8 @@ export interface ScannersSorting {}export const SCANNERS_PAGE_SIZE = 50+// Matches LLM Analytics' dashboard dwell gate, so the shallow-intent bar is the same across products.+export const REPLAY_VISION_INTENT_DWELL_MS = 15000const ALL_ENABLED: EnabledFilter[] = ENABLED_OPTIONS.map((o) => o.value)const ALL_SCANNER_TYPES: ScannerType[] = SCANNER_TYPE_OPTIONS.map((o) => o.value)const DEFAULT_SORT: ScannersSorting = { columnKey: 'created_at', order: -1 }@@ -696,6 +700,26 @@ export const replayScannersLogic = kea<replayScannersLogicType>([urlToAction(({ actions, values, cache }) => ({[urls.replayVision()]: (_, searchParams) => {+ // Shallow product intent: reading the scanner list for a while is interest, and it's the+ // only signal the people who never create a scanner ever produce. Gated on dwell rather+ // than on the route firing, because urlToAction runs on mount and a bounce would then+ // start the team's 30-day activation clock. Registered as a disposable so the clock+ // pauses while the tab is hidden: a background tab is not dwell.+ if (!cache.dwellIntentArmed) {+ cache.dwellIntentArmed = true+ cache.disposables.add(() => {+ const timer = setTimeout(() => {+ // Drop the disposable once fired, so a later hide/show cycle does not+ // re-arm the timer and register again.+ cache.disposables.dispose('replayVisionDwell')+ void addProductIntent({+ product_type: ProductKey.REPLAY_VISION,+ intent_context: ProductIntentContext.REPLAY_VISION_VIEWED,+ })+ }, REPLAY_VISION_INTENT_DWELL_MS)+ return () => clearTimeout(timer)+ }, 'replayVisionDwell')+ }const pageRaw = Number(searchParams.page ?? 1)const parsed: ScannersFilters = {search: typeof searchParams.search === 'string' ? searchParams.search : '',