: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): report which path a scanner was created from (#83520)
coryslatera59c3c1b7757
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 369ee4648df5..f20a5f9dc13f 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3972,6 +3972,9 @@ importers:lodash.uniqby:specifier: ^4.7.0version: 4.7.0+ posthog-js:+ specifier: 'catalog:'+ version: 1.417.1react:specifier: 18.3.1version: 18.3.1diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex a1a56b37a39a..5773ceb61414 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -1969,22 +1969,48 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vibody = DraftScannerRequestSerializer(data=request.data)body.is_valid(raise_exception=True)+ goal = body.validated_data["goal"]+ # The goal is customer text, so only its length goes into telemetry.+ draft_properties: dict[str, Any] = {"goal_length": len(goal), "team_id": self.team_id}+try:drafted = draft_scanner_from_goal(team=self.team,user=cast(User, request.user),- goal=body.validated_data["goal"],+ goal=goal,user_access_control=self.user_access_control,# Core memory's own API is INTERNAL (session-only), so scoped tokens must not# receive its content through the draft either.include_business_context=get_authenticator_scopes(request.successful_authenticator) is None,)except DraftError:+ # Report failures too, so model errors don't read as user abandonment.+ report_user_action(+ cast(User, request.user),+ "replay_vision_scanner_drafted",+ {**draft_properties, "success": False},+ team=self.team,+ request=request,+ )return Response({"detail": "Couldn't draft a scanner right now. Try again in a moment."},status=status.HTTP_503_SERVICE_UNAVAILABLE,)+ report_user_action(+ cast(User, request.user),+ "replay_vision_scanner_drafted",+ {+ **draft_properties,+ "success": True,+ "scanner_type": drafted.scanner_type,+ # Whether the goal mapped to a real event filter or fell back to no targeting.+ "has_query": bool(drafted.query),+ },+ team=self.team,+ request=request,+ )+return Response(DraftScannerResponseSerializer({diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 2e2a7801405f..276adb4c9c01 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -43,6 +43,7 @@ from products.replay_vision.backend.models.vision_action import VisionActionfrom products.replay_vision.backend.queries import SAVE_ESTIMATE_BUDGETfrom products.replay_vision.backend.queries.scanner_candidate_query import SETTLE_INTERVALfrom products.replay_vision.backend.quota import BillingPeriod, _current_period_bounds+from products.replay_vision.backend.scanner_draft import DraftError, ScannerDraftfrom products.replay_vision.backend.temporal.constants import (APPLY_SCANNER_EXECUTION_TIMEOUT,APPLY_SCANNER_WORKFLOW_NAME,@@ -1046,6 +1047,46 @@ class TestScannerLifecycleTelemetry(_VisionAPITestCase):if expected_events:self.assertEqual(report.call_args.args[2]["edited_fields"], sorted(mutation.keys()))+ @parameterized.expand(+ [+ ("drafted", None, 200, True),+ ("model_failed", DraftError(), 503, False),+ ]+ )+ def test_draft_reports_outcome(+ self, _name: str, error: Exception | None, expected_status: int, expected_success: bool+ ) -> None:+ # A draft that reports nothing would read as user abandonment instead of a model failure.+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ drafted = ScannerDraft(+ name="stuck-in-onboarding",+ description="Sessions where onboarding stalls",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "did the user get stuck?"},+ rationale="Onboarding drop-off is the stated goal",+ query={"kind": "RecordingsQuery", "events": [{"id": "$pageview"}]},+ )+ goal = "find users who get stuck in onboarding"+ with (+ patch(+ "products.replay_vision.backend.api.scanners.draft_scanner_from_goal",+ side_effect=error,+ return_value=drafted,+ ),+ patch("products.replay_vision.backend.api.scanners.report_user_action") as report,+ ):+ resp = self.client.post(f"{self.scanners_url}draft/", data={"goal": goal}, format="json")++ self.assertEqual(resp.status_code, expected_status, resp.json())+ drafted_events = [call for call in report.call_args_list if call.args[1] == "replay_vision_scanner_drafted"]+ self.assertEqual(len(drafted_events), 1)+ properties = drafted_events[0].args[2]+ self.assertEqual(properties["success"], expected_success)+ self.assertEqual(properties["goal_length"], len(goal))+ # The goal is customer text; only its length may ride along.+ self.assertNotIn("goal", properties)+class TestScannerDigestProvisioning(_VisionAPITestCase):_CREATE_BODY = {diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex 1bb30d540bc5..fb593ed0bef8 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -1,5 +1,6 @@import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { teamLogic } from 'scenes/teamLogic'@@ -1258,4 +1259,31 @@ describe('replayScannerLogic', () => {}})})++ describe('creation path telemetry', () => {+ // Both paths end on the same created event, so these captures are the only path marker.+ it.each([+ ['dead_end', 'template'],+ [null, 'scratch'],+ ])('startFromTemplate(%s) reports the %s path', (templateKey, creationMethod) => {+ const captureSpy = jest.spyOn(posthog, 'capture')+ logic.actions.startFromTemplate(templateKey)+ expect(captureSpy).toHaveBeenCalledWith('replay_vision_scanner_creation_started', {+ creation_method: creationMethod,+ template_key: templateKey,+ })+ })++ it('drafting from a goal reports the AI path without the goal text', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture')+ await expectLogic(logic, () => {+ logic.actions.draftScannerFromGoal(' find users who get stuck ')+ }).toFinishAllListeners()+ expect(captureSpy).toHaveBeenCalledWith('replay_vision_scanner_creation_started', {+ creation_method: 'ai',+ template_key: null,+ goal_length: 'find users who get stuck'.length,+ })+ })+ })})diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex 68cbc391e173..c73b447184da 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -17,6 +17,7 @@ import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } fromimport { loaders } from 'kea-loaders'import { actionToUrl, beforeUnload, router, urlToAction } from 'kea-router'import { CombinedLocation } from 'kea-router/lib/utils'+import posthog from 'posthog-js'import api from 'lib/api'import { scrollToFormError } from 'lib/forms/scrollToFormError'@@ -1606,6 +1607,16 @@ export const replayScannerLogic = kea<replayScannerLogicType>([persistDraft()},+ // Fires on request rather than result, so failed drafts still count as entering the AI path.+ draftScannerFromGoal: ({ goal }) => {+ posthog.capture('replay_vision_scanner_creation_started', {+ creation_method: 'ai',+ template_key: null,+ // The goal is customer text, so only its length is captured.+ goal_length: goal.trim().length,+ })+ },+// A successful AI draft seeds the wizard form, then the configure step opens for review.draftScannerFromGoalSuccess: ({ goalDraft }) => {if (!goalDraft) {@@ -1679,6 +1690,11 @@ export const replayScannerLogic = kea<replayScannerLogicType>([persistDraft()},startFromTemplate: ({ templateKey }) => {+ // Counterpart of the AI capture, so the creation funnel can split by path.+ posthog.capture('replay_vision_scanner_creation_started', {+ creation_method: templateKey ? 'template' : 'scratch',+ template_key: templateKey,+ })clearScannerDraft()actions.setScannerDraftSavedAt(null)// An experiment prefill (targeted query, scoped name) has to survive the templatediff --git a/products/replay_vision/package.json b/products/replay_vision/package.jsonindex b8fd736ed4ba..08752f841086 100644--- a/products/replay_vision/package.json+++ b/products/replay_vision/package.json@@ -9,7 +9,8 @@"kea-forms": "catalog:","kea-loaders": "catalog:","kea-router": "catalog:",- "lodash.uniqby": "^4.7.0"+ "lodash.uniqby": "^4.7.0",+ "posthog-js": "catalog:"},"devDependencies": {"@testing-library/react": "^14.3.1",