: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): offer a one-click dashboard for each scanner (#115063)
Tue Haulund2fae7991a2b5
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 89f6ef5a4274..5bb028002596 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -13358,6 +13358,10 @@ snapshots:hash: v1.k794b7964.79627bbcaf1345596a4230711f90d9eba24f1573be64c223b3c05fb85642b05f.0imokLmvnCGRhNwGiL6uxRaz3DayL3voUkn-lGl3TMgscenes-app-replay-vision--monitor-overview--light:hash: v1.k794b7964.78c674851e796673dbc50f43f862493f25b646aa72f0e45170dd66b737e4d8d7.3KYDsrwG2gMYKec4kttVDHpZr5J7WnNCbtj-sXFDrLc+ scenes-app-replay-vision--monitor-overview-dashboard-offer--dark:+ hash: v1.k794b7964.938b0069da1eb943fdd15aadb01c142603111292859bc34fea0f93bce95f7ac8.qVQYF7Gy-ISCeG-RjVYnDXF_HcEzaHxpM8A1atMZBdE+ scenes-app-replay-vision--monitor-overview-dashboard-offer--light:+ hash: v1.k794b7964.cc0d32580736768a2944ed90c09ef78ffac5e8c3ffc15d51307d7529f8a9a606.vEM-tv6APY-YhgbYYYe4LREOHBxr1SvVvsXVouNLnxEscenes-app-replay-vision--monitor-overview-with-root-cause--dark:hash: v1.k794b7964.95eb50d69e46376f28de8821b0d1dfa356c08db91249e14f900cb54e7d58c278.oCAAFUd8iCTVgaeYB6ogtIxzaALytcTJ7tuCFgqEED8scenes-app-replay-vision--monitor-overview-with-root-cause--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 0d3aa8f166ae..16407bab8aaf 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -534,6 +534,7 @@ export const FEATURE_FLAGS = {REPLAY_RECOMMENDED_RECORDINGS_FILTER_EXPERIMENT: 'replay-recommended-recordings-filter-experiment', // owner: @arnohillen #team-replay multivariate=control,testREPLAY_TRIGGERS_V2: 'replay-triggers-v2', // owner: #team-replayREPLAY_UI_REDESIGN_2026: 'replay-ui-redesign-2026', // owner: #team-replay, New UI layout for replay+ REPLAY_VISION_SCANNER_DASHBOARD: 'replay-vision-scanner-dashboard', // owner: #team-replay, one-click dashboard offer on the scanner overview and its MCP toolREPLAY_VISION_WATCH_IN_LIST_EXPERIMENT: 'replay-vision-watch-in-list-experiment', // owner: #team-replay multivariate=control,in-list,watch-tab,both. Compare the variant string, a truthy check turns on for control tooREVAMPED_PY_NOTEBOOKS: 'revamped-py-notebooks', // owner: #team-data-toolsREVENUE_FIELDS_IN_POWER_USERS_TABLE: 'revenue-fields-in-power-users-table', // owner: @arthurdedeus #team-customer-analyticsdiff --git a/products/dashboards/backend/facade/api.py b/products/dashboards/backend/facade/api.pyindex 1971376b9294..0b272b406461 100644--- a/products/dashboards/backend/facade/api.py+++ b/products/dashboards/backend/facade/api.py@@ -21,15 +21,19 @@ from pydantic.dataclasses import dataclassfrom rest_framework import serializersfrom posthog.api.sharing_publish_gate import check_can_add_insight_to_shared_dashboard+from posthog.helpers.dashboard_templates import create_from_templatefrom posthog.models.user import Userfrom posthog.user_permissions import UserPermissionsfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.dashboards.backend.facade.enums import PrivilegeLevelfrom products.dashboards.backend.models.dashboard import Dashboard+from products.dashboards.backend.models.dashboard_templates import DashboardTemplatefrom products.dashboards.backend.models.dashboard_tile import DashboardTileif TYPE_CHECKING:+ from posthog.models.team import Team+from products.product_analytics.backend.facade.models import Insight@@ -89,6 +93,43 @@ def _refs_in_given_order(dashboard_ids: Sequence[int]) -> tuple[DashboardRef, ..)+def viewable_dashboard_ref(dashboard_id: int, *, team: "Team", user: User) -> DashboardRef | None:+ """The dashboard as a ref when it is live in this team and the user may view it, else None.++ Object-level access rules can hide one dashboard from a user who has team-wide dashboard access.+ """+ dashboard = Dashboard.objects.filter(team_id=team.id, pk=dashboard_id).first()+ if dashboard is None:+ return None+ if UserAccessControl(user=user, team=team).check_access_level_for_object(dashboard, "viewer") is False:+ return None+ return DashboardRef(id=dashboard.id, name=dashboard.name)+++def create_dashboard_from_tiles(+ *,+ team: "Team",+ user: User,+ name: str,+ description: str,+ filters: dict[str, Any],+ tiles: list[dict[str, Any]],+ tags: list[str],+) -> DashboardRef:+ """Create a dashboard from template-shaped tile definitions, for products that build dashboards in code.++ Runs inside the caller's transaction, so a failure part way leaves no dashboard behind when the caller rolls back.+ """+ template = DashboardTemplate(+ template_name=name, dashboard_description=description, dashboard_filters=filters, tiles=tiles, tags=tags+ )+ dashboard = Dashboard.objects.create(+ team_id=team.id, name=name, created_by=user, creation_mode=Dashboard.CreationMode.TEMPLATE+ )+ create_from_template(dashboard, template, user, user_access_control=UserAccessControl(user=user, team=team))+ return DashboardRef(id=dashboard.id, name=dashboard.name)++def dashboard_refs(dashboard_ids: Sequence[int]) -> tuple[DashboardRef, ...]:"""Dashboard IDs and names for callers that already validated the dashboard IDs."""return _refs_in_given_order(dashboard_ids)diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 0521aa07fc1f..090cb75f1dff 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -157,6 +157,13 @@ from products.replay_vision.backend.scanner_config import (analytics_source_kwargs,scanner_config_error,)+from products.replay_vision.backend.scanner_dashboard import (+ DASHBOARD_SUGGESTION_MIN_OBSERVATIONS,+ DashboardNotViewable,+ create_scanner_dashboard,+ live_dashboard_ids,+ scanners_ready_for_dashboard,+)from products.replay_vision.backend.scanner_draft import DraftError, draft_scanner_from_goal, draft_scanner_from_goal_v2from products.replay_vision.backend.scanning import (MAX_SESSIONS_PER_SCAN,@@ -607,6 +614,19 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial"every N schedule intervals. Expensive filters raise it."),)+ dashboard_id = serializers.SerializerMethodField(+ help_text=(+ "Dashboard created for this scanner with the create_dashboard action. Null when none was created "+ "or the user deleted it."+ ),+ )+ dashboard_suggested = serializers.SerializerMethodField(+ help_text=(+ f"Whether to offer the user a dashboard for this scanner: true when the scanner has no dashboard and at "+ f"least {DASHBOARD_SUGGESTION_MIN_OBSERVATIONS} succeeded observations to chart. Offer it once and do not "+ "repeat the offer if the user declines."+ ),+ )last_swept_at = serializers.DateTimeField(read_only=True,help_text="Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery.",@@ -648,6 +668,8 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial"credits_used_against_limit","limit_reached","sweep_throttle_factor",+ "dashboard_id",+ "dashboard_suggested","last_swept_at","created_at","created_by",@@ -667,6 +689,8 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial"credits_used_against_limit","limit_reached","sweep_throttle_factor",+ "dashboard_id",+ "dashboard_suggested","last_swept_at","created_at","created_by",@@ -742,6 +766,28 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerialdatetime.now(UTC),)+ def _page_dashboard_state(self, scanner: ReplayScanner) -> tuple[dict[UUID, int], set[UUID]]:+ # Shared across the list's children, so a page costs two queries rather than two per scanner.+ state = self.context.get("_scanner_dashboard_state")+ if state is None:+ root = self.root+ page = root.instance if isinstance(root, serializers.ListSerializer) else None+ scanners = list(page) if page is not None else [scanner]+ live = live_dashboard_ids(scanner.team_id, scanners)+ ready = scanners_ready_for_dashboard(scanner.team_id, [s.id for s in scanners if s.id not in live])+ state = (live, ready)+ self.context["_scanner_dashboard_state"] = state+ return state++ @extend_schema_field(serializers.IntegerField(allow_null=True))+ def get_dashboard_id(self, scanner: ReplayScanner) -> int | None:+ return self._page_dashboard_state(scanner)[0].get(scanner.id)++ @extend_schema_field(serializers.BooleanField())+ def get_dashboard_suggested(self, scanner: ReplayScanner) -> bool:+ # Readiness is only computed for scanners without a live dashboard.+ return scanner.id in self._page_dashboard_state(scanner)[1]+@extend_schema_field(serializers.BooleanField())def get_limit_reached(self, scanner: ReplayScanner) -> bool:# `blocked`, not `exhausted`: the enforcement gates admit an observation only when its full cost@@ -2136,6 +2182,14 @@ class SelfDrivingPullRequestSerializer(serializers.Serializer):merged = serializers.BooleanField(help_text="Whether the pull request has merged.")+class ScannerDashboardResponseSerializer(serializers.Serializer):+ dashboard_id = serializers.IntegerField(help_text="Id of the scanner's dashboard.")+ name = serializers.CharField(help_text="Name of the dashboard.")+ created = serializers.BooleanField(+ help_text="True when this call created the dashboard. False when the scanner already had one, which is returned instead."+ )++class ScannerSelfDrivingStatsSerializer(serializers.Serializer):"""Response of GET /vision/scanners/:id/self_driving_stats/."""@@ -2971,6 +3025,59 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vistatus=status.HTTP_201_CREATED,)+ @extend_schema(+ request=None,+ responses={+ 201: ScannerDashboardResponseSerializer,+ 200: OpenApiResponse(+ response=ScannerDashboardResponseSerializer, description="The scanner already had a dashboard."+ ),+ },+ )+ @action(+ detail=True,+ methods=["post"],+ url_path="create_dashboard",+ required_scopes=["replay_scanner:read", "session_recording:read", "dashboard:write", "insight:write"],+ )+ def create_dashboard(self, request: Request, **kwargs: Any) -> Response:+ """Create a dashboard that charts this scanner's observations, and link it to the scanner.++ The tiles depend on the scanner type: who the scanner matched, which accounts they belong to,+ type-specific breakdowns, and the latest matching recordings. Calling it again returns the+ existing dashboard rather than a second one."""+ # The tiles show scanner reasoning and link recordings, which is the same exposure as the observations endpoint.+ if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):+ raise PermissionDenied("Creating a scanner dashboard requires session_recording read access.")+ # `dashboard:write` in required_scopes only constrains API keys; session RBAC evaluates against this+ # viewset's replay_scanner scope object, so the caller's dashboard access must be checked explicitly.+ if not self.user_access_control.check_access_level_for_resource("dashboard", required_level="editor"):+ raise PermissionDenied("Creating a scanner dashboard requires dashboard edit access.")+ scanner = self.get_object()+ user = cast(User, request.user)+ try:+ dashboard, created = create_scanner_dashboard(scanner, user)+ except DashboardNotViewable:+ raise PermissionDenied("This scanner already has a dashboard that you don't have access to.")+ if created:+ report_user_action(+ user,+ "replay_vision_scanner_dashboard_created",+ {+ "scanner_id": str(scanner.id),+ "scanner_type": scanner.scanner_type,+ "dashboard_id": dashboard.id,+ },+ team=self.team,+ request=request,+ )+ return Response(+ ScannerDashboardResponseSerializer(+ {"dashboard_id": dashboard.id, "name": dashboard.name, "created": created}+ ).data,+ status=status.HTTP_201_CREATED if created else status.HTTP_200_OK,+ )+@extend_schema(request=EstimateRequestSerializer,responses={200: EstimateResponseSerializer},diff --git a/products/replay_vision/backend/migrations/0121_replayscanner_dashboard_id.py b/products/replay_vision/backend/migrations/0121_replayscanner_dashboard_id.pynew file mode 100644index 000000000000..2f5d9920bb7b--- /dev/null+++ b/products/replay_vision/backend/migrations/0121_replayscanner_dashboard_id.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.18 on 2026-10-11 09:16++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("replay_vision", "0120_replayobservationrequest_wait_for_session_end"),+ ]++ operations = [+ migrations.AddField(+ model_name="replayscanner",+ name="dashboard_id",+ field=models.BigIntegerField(+ blank=True,+ help_text="Dashboard created for this scanner from Replay Vision. Can point at a dashboard the user later deleted.",+ null=True,+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txtindex 94e31c88a1d3..1789cc26f8bc 100644--- a/products/replay_vision/backend/migrations/max_migration.txt+++ b/products/replay_vision/backend/migrations/max_migration.txt@@ -1 +1 @@-0120_replayobservationrequest_wait_for_session_end+0121_replayscanner_dashboard_iddiff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.pyindex fc81923e75a1..45fef74dd0c9 100644--- a/products/replay_vision/backend/models/replay_scanner.py+++ b/products/replay_vision/backend/models/replay_scanner.py@@ -363,6 +363,13 @@ class ReplayScanner(Taggable, ModelActivityMixin, UUIDModel):help_text="Credits admitted since the last admission-budget refresh. Every refresh resets this to the admitting cost, or to zero on a refusal.",)+ # A plain id rather than a foreign key, so that this product holds no constraint on the dashboards table.+ dashboard_id = models.BigIntegerField(+ null=True,+ blank=True,+ help_text="Dashboard created for this scanner from Replay Vision. Can point at a dashboard the user later deleted.",+ )+created_at = models.DateTimeField(auto_now_add=True)created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")updated_at = models.DateTimeField(auto_now=True)diff --git a/products/replay_vision/backend/scanner_dashboard.py b/products/replay_vision/backend/scanner_dashboard.pynew file mode 100644index 000000000000..65764f3e2e78--- /dev/null+++ b/products/replay_vision/backend/scanner_dashboard.py@@ -0,0 +1,527 @@+import re+import textwrap+from collections.abc import Collection, Sequence+from datetime import timedelta+from functools import cached_property+from typing import Any, cast+from uuid import UUID++from django.db import transaction+from django.db.models import Exists, OuterRef+from django.utils import timezone++import structlog++from posthog.hogql.escape_sql import escape_hogql_identifier++from posthog.models.group_type_mapping import get_group_types_for_project+from posthog.models.user import User++from products.dashboards.backend.facade.api import (+ DashboardRef,+ create_dashboard_from_tiles,+ unknown_dashboard_ids,+ viewable_dashboard_ref,+)+from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType+from products.replay_vision.backend.queries.scanner_candidate_query import OBSERVATION_EVENT_NAME++logger = structlog.get_logger(__name__)++# Enough rows that every tile renders a real chart on the day the dashboard is created.+DASHBOARD_SUGGESTION_MIN_OBSERVATIONS = 20++DASHBOARD_NAME_PREFIX = "Replay Vision: "+DASHBOARD_DAYS = 30+DASHBOARD_DATE_FROM = f"-{DASHBOARD_DAYS}d"++_TILE_HEIGHT = 5+# How far back "first seen" looks for a freeform category, so the tile does not scan the scanner's whole history.+_FREEFORM_FIRST_SEEN_LOOKBACK = "1 YEAR"++# `{scanner_id}` is substituted by `_sql_node` rather than bound through HogQL `values`, because `values` turns+# `{filters}` into a HogVM global and the dashboard date filter stops applying. The id is a server UUID, so it is safe+# to inline.+_SCANNER_MATCH = f"event = '{OBSERVATION_EVENT_NAME}' AND properties.scanner_id = '{{scanner_id}}'"+_SCANNER_WHERE = f"{_SCANNER_MATCH} AND {{filters}}"+_YES_SQL = "properties.scanner_output_verdict = 'yes'"+_FREEFORM_EXPR = "JSONExtract(ifNull(properties.scanner_output_tags_freeform, '[]'), 'Array(String)')"+_TAGS_EXPR = (+ f"arrayConcat(JSONExtract(ifNull(properties.scanner_output_tags, '[]'), 'Array(String)'), {_FREEFORM_EXPR})"+)+++class DashboardNotViewable(Exception):+ """The scanner already has a dashboard that the requester may not view."""+++def live_dashboard_ids(team_id: int, scanners: Sequence[ReplayScanner]) -> dict[UUID, int]:+ """Linked dashboards that still exist, by scanner. A scanner whose dashboard the user deleted is left out."""+ linked = {scanner.id: cast(int, scanner.dashboard_id) for scanner in scanners if scanner.dashboard_id is not None}+ if not linked:+ return {}+ gone = set(unknown_dashboard_ids(list(linked.values()), team_id=team_id))+ return {scanner_id: dashboard_id for scanner_id, dashboard_id in linked.items() if dashboard_id not in gone}+++def scanners_ready_for_dashboard(team_id: int, scanner_ids: Collection[UUID]) -> set[UUID]:+ """The scanners with at least `DASHBOARD_SUGGESTION_MIN_OBSERVATIONS` succeeded observations inside the+ dashboard's default date range, so the dashboard the offer creates opens with data in it."""+ if not scanner_ids:+ return set()+ window_start = timezone.now() - timedelta(days=DASHBOARD_DAYS)+ # An offset probe stops at the threshold row, so a scanner with millions of observations costs the same as one with 20.+ threshold_row = (+ ReplayObservation.objects.filter(+ scanner_id=OuterRef("pk"), status=ObservationStatus.SUCCEEDED, completed_at__gte=window_start+ )+ .order_by()+ .values("pk")[DASHBOARD_SUGGESTION_MIN_OBSERVATIONS - 1 : DASHBOARD_SUGGESTION_MIN_OBSERVATIONS]+ )+ return set(+ ReplayScanner.objects.filter(team_id=team_id, id__in=scanner_ids)+ .filter(Exists(threshold_row))+ .values_list("id", flat=True)+ )+++def create_scanner_dashboard(scanner: ReplayScanner, user: User) -> tuple[DashboardRef, bool]:+ """Create the scanner's dashboard and link it, or return the live one already linked.++ Returns (dashboard, created). The scanner row lock serializes two clicks on the same scanner,+ so that one scanner never gets two dashboards.+ """+ # Built before the lock because it reads group types, which can call personhog.+ tiles = build_scanner_dashboard_tiles(scanner)+ with transaction.atomic():+ locked = ReplayScanner.objects.select_for_update().get(pk=scanner.pk, team_id=scanner.team_id)+ existing_id = live_dashboard_ids(locked.team_id, [locked]).get(locked.id)+ if existing_id is not None:+ existing = viewable_dashboard_ref(existing_id, team=scanner.team, user=user)+ if existing is None:+ raise DashboardNotViewable(existing_id)+ return existing, False+ dashboard = create_dashboard_from_tiles(+ team=scanner.team,+ user=user,+ name=f"{DASHBOARD_NAME_PREFIX}{locked.name}"[:400],+ description=(+ f"What the '{locked.name}' scanner finds in your session recordings, and who it affects. "+ "Charts count observations on the day the scanner ran, not the day of the recording."+ ),+ filters={"date_from": DASHBOARD_DATE_FROM},+ tiles=tiles,+ tags=["replay-vision"],+ )+ # A queryset update so that linking a dashboard is not logged or treated as a scanner config edit.+ ReplayScanner.objects.filter(pk=locked.pk).update(dashboard_id=dashboard.id)+ scanner.dashboard_id = dashboard.id+ return dashboard, True+++def build_scanner_dashboard_tiles(scanner: ReplayScanner) -> list[dict[str, Any]]:+ builder = _TileBuilder(scanner)+ builder.add_shared_tiles()+ builder.add_type_tiles()+ builder.add_latest_sessions_tile()+ return builder.tiles+++class _TileBuilder:+ def __init__(self, scanner: ReplayScanner) -> None:+ self.scanner = scanner+ self.scanner_id = str(scanner.id)+ self.is_monitor = scanner.scanner_type == ScannerType.MONITOR+ self.tiles: list[dict[str, Any]] = []+ self._x = 0+ self._y = 0++ # Shared across every scanner type.++ def add_shared_tiles(self) -> None:+ hit_filter = self._hit_filter()+ people_name = "People with a yes verdict" if self.is_monitor else "People observed"+ self._trend(+ people_name,+ "Distinct people in recordings this scanner matched, per week.",+ series=[+ self._series(+ people_name,+ math="hogql",+ math_hogql="count(DISTINCT properties.recording_distinct_id)",+ extra=hit_filter,+ )+ ],+ display="ActionsBar",+ )+ if self._primary_group_type is None:+ return+ index, plural = self._primary_group_type+ self._trend(+ f"{plural.capitalize()} affected",+ f"Distinct {plural} with at least one matching recording, per week.",+ series=[+ self._series(+ f"{plural.capitalize()} affected",+ math="unique_group",+ math_group_type_index=index,+ extra=hit_filter,+ )+ ],+ display="ActionsBar",+ )+ self._account_table(+ f"Top {plural}",+ f"The {plural} with the most matching recordings.",+ columns={"recordings": "count()", "people": "count(DISTINCT properties.recording_distinct_id)"},+ sort="recordings DESC",+ where=f" AND {_YES_SQL}" if self.is_monitor else "",+ )++ def add_latest_sessions_tile(self) -> None:+ scanner_type = ScannerType(self.scanner.scanner_type)+ name, description, order = "Latest matching sessions", "The newest observations", "timestamp DESC"+ detail = "properties.scanner_output_reasoning"+ if scanner_type == ScannerType.CLASSIFIER:+ detail = f"arrayStringConcat({_TAGS_EXPR}, ', ')"+ elif scanner_type in (ScannerType.SUMMARIZER, ScannerType.EXPERIMENT):+ name, description = "Most notable sessions", "The most notable observations"+ order = "toFloat(properties.scanner_output_notability) DESC NULLS LAST"+ detail = "properties.scanner_output_title"+ score_column = (+ "toFloat(properties.scanner_output_score) AS score, " if scanner_type == ScannerType.SCORER else ""+ )+ where = f" AND {_YES_SQL}" if self.is_monitor else ""+ self._sql_table(+ name,+ f"{description}, with a link to each recording.",+ f"""+ SELECT timestamp AS observed_at, {score_column}{detail} AS finding,+ properties.recording_distinct_id AS person, recordingButton(properties.session_id) AS recording+ FROM events+ WHERE {_SCANNER_WHERE}{where}+ ORDER BY {order}+ LIMIT 50+ """,+ width=12,+ )++ # Per scanner type.++ def add_type_tiles(self) -> None:+ {+ ScannerType.MONITOR: self._monitor_tiles,+ ScannerType.CLASSIFIER: self._classifier_tiles,+ ScannerType.SCORER: self._scorer_tiles,+ ScannerType.SUMMARIZER: self._summarizer_tiles,+ ScannerType.EXPERIMENT: self._experiment_tiles,+ }[ScannerType(self.scanner.scanner_type)]()++ def _monitor_tiles(self) -> None:+ self._trend(+ "Yes rate",+ "Share of observed recordings with a yes verdict.",+ series=[+ self._series("Yes verdicts", extra=self._hit_filter()),+ self._series("All observations"),+ ],+ trends_filter={"formulaNodes": [{"formula": "A / B * 100", "custom_name": "Yes rate (%)"}]},+ )+ self._sql_chart(+ "Confidence of yes verdicts",+ "How sure the scanner was when it said yes. Many low-confidence verdicts can mean the prompt is vague.",+ f"""+ SELECT round(toFloat(properties.scanner_output_confidence), 1) AS confidence, count() AS verdicts+ FROM events+ WHERE {_SCANNER_WHERE} AND {_YES_SQL}+ AND properties.scanner_output_confidence IS NOT NULL+ GROUP BY confidence+ ORDER BY confidence+ """,+ x="confidence",+ y="verdicts",+ )++ def _classifier_tiles(self) -> None:+ self._trend(+ "Category share",+ "Each category's share of observations over time.",+ series=[self._series("Observations")],+ breakdown={"breakdown": f"arrayJoin({_TAGS_EXPR})", "breakdown_type": "hogql"},+ display="ActionsAreaGraph",+ trends_filter={"showPercentStackView": True},+ )+ self._sql_table(+ "Categories that appear together",+ "Pairs of categories assigned to the same recording.",+ f"""+ SELECT pair.1 AS first_category, pair.2 AS second_category, count() AS recordings+ FROM (SELECT {_TAGS_EXPR} AS tags FROM events WHERE {_SCANNER_WHERE})+ ARRAY JOIN arrayFilter(p -> p.1 < p.2, arrayFlatten(arrayMap(a -> arrayMap(b -> (a, b), tags), tags))) AS pair+ GROUP BY first_category, second_category+ ORDER BY recordings DESC+ LIMIT 20+ """,+ )+ # First seen looks back past the range, so a category the scanner has used for months sorts below one+ # it started using this week.+ self._sql_table(+ "Freeform categories",+ "Categories the scanner suggested outside your list, newest first. "+ "Frequent ones are candidates to add to the scanner.",+ f"""+ SELECT in_range.category AS category, in_range.recordings AS recordings, all_time.first_seen AS first_seen+ FROM (+ SELECT tag AS category, count() AS recordings+ FROM (SELECT {_FREEFORM_EXPR} AS tags FROM events WHERE {_SCANNER_WHERE})+ ARRAY JOIN tags AS tag+ GROUP BY category+ ) AS in_range+ LEFT JOIN (+ SELECT tag AS category, min(timestamp) AS first_seen+ FROM (+ SELECT {_FREEFORM_EXPR} AS tags, timestamp+ FROM events+ WHERE {_SCANNER_MATCH} AND timestamp > now() - INTERVAL {_FREEFORM_FIRST_SEEN_LOOKBACK}+ )+ ARRAY JOIN tags AS tag+ GROUP BY category+ ) AS all_time ON in_range.category = all_time.category+ ORDER BY first_seen DESC+ LIMIT 20+ """,+ )++ def _scorer_tiles(self) -> None:+ self._sql_chart(+ "Score distribution",+ "How many recordings received each score.",+ f"""+ SELECT round(toFloat(properties.scanner_output_score), 1) AS score, count() AS recordings+ FROM events+ WHERE {_SCANNER_WHERE} AND properties.scanner_output_score IS NOT NULL+ GROUP BY score+ ORDER BY score+ """,+ x="score",+ y="recordings",+ )+ self._trend(+ "Score percentiles",+ "The 10th, 50th and 90th percentile score per week. The average hides the tail, these do not.",+ series=[+ self._series(+ "10th percentile",+ math="hogql",+ math_hogql="quantile(0.1)(toFloat(properties.scanner_output_score))",+ ),+ self._series("Median", math="median", math_property="scanner_output_score"),+ self._series("90th percentile", math="p90", math_property="scanner_output_score"),+ ],+ )+ if self._primary_group_type is None:+ return+ plural = self._primary_group_type[1]+ self._account_table(+ f"Lowest scoring {plural}",+ f"The {plural} with the lowest average score, among those with at least 3 scored recordings.",+ columns={+ "average_score": "round(avg(toFloat(properties.scanner_output_score)), 2)",+ "recordings": "count()",+ },+ sort="average_score ASC",+ having="HAVING recordings >= 3",+ )++ def _summarizer_tiles(self) -> None:+ self._notability_distribution()+ self._trend(+ "Average chapters per recording",+ "A rough measure of how much happens in each session.",+ series=[self._series("Chapters", math="avg", math_property="scanner_output_chapter_count")],+ )++ def _experiment_tiles(self) -> None:+ self._trend(+ "Observations by variant",+ "Observed recordings per experiment variant, per week.",+ series=[self._series("Observations")],+ breakdown={"breakdown": "experiment_variant", "breakdown_type": "event"},+ display="ActionsBar",+ )+ self._trend(+ "Average notability by variant",+ "How notable the scanner found each variant's sessions over the date range. Higher means more unusual "+ "behavior.",+ series=[self._series("Notability", math="avg", math_property="scanner_output_notability")],+ breakdown={"breakdown": "experiment_variant", "breakdown_type": "event"},+ # One bar per variant: stacked weekly bars would add the variants' averages together.+ display="ActionsBarValue",+ )+ self._notability_distribution()++ def _notability_distribution(self) -> None:+ self._sql_chart(+ "Notability distribution",+ "How notable the scanner found each session, from 0 (routine) to 1 (unusual).",+ f"""+ SELECT round(toFloat(properties.scanner_output_notability), 1) AS notability, count() AS recordings+ FROM events+ WHERE {_SCANNER_WHERE} AND properties.scanner_output_notability IS NOT NULL+ GROUP BY notability+ ORDER BY notability+ """,+ x="notability",+ y="recordings",+ )++ # Helpers.++ def _hit_filter(self) -> list[dict[str, Any]]:+ if not self.is_monitor:+ return []+ return [{"type": "event", "key": "scanner_output_verdict", "operator": "exact", "value": "yes"}]++ @cached_property+ def _primary_group_type(self) -> tuple[int, str] | None:+ try:+ group_types = get_group_types_for_project(+ self.scanner.team.project_id, caller_tag="replay_vision/scanner_dashboard"+ )+ except Exception:+ # The account tiles are optional, so a failed lookup builds the dashboard without them.+ logger.warning("replay_vision.scanner_dashboard.group_types_lookup_failed", scanner_id=self.scanner_id)+ return None+ if not group_types:+ return None+ first = min(group_types, key=lambda mapping: mapping["group_type_index"])+ plural = str(first.get("name_plural") or _pluralize(first["group_type"])).lower()+ # The plural is user-edited and becomes a column alias, so keep only characters an identifier allows.+ return first["group_type_index"], re.sub(r"[^\w ]", "", plural).strip() or "accounts"++ def _series(self, name: str, *, extra: list[dict[str, Any]] | None = None, **math: Any) -> dict[str, Any]:+ return {+ "kind": "EventsNode",+ "event": OBSERVATION_EVENT_NAME,+ "name": name,+ "custom_name": name,+ "math": math.pop("math", "total"),+ **math,+ "properties": [+ {"type": "event", "key": "scanner_id", "operator": "exact", "value": self.scanner_id},+ *(extra or []),+ ],+ }++ def _trend(+ self,+ name: str,+ description: str,+ *,+ series: list[dict[str, Any]],+ display: str = "ActionsLineGraph",+ breakdown: dict[str, Any] | None = None,+ trends_filter: dict[str, Any] | None = None,+ ) -> None:+ source: dict[str, Any] = {+ "kind": "TrendsQuery",+ "series": series,+ # Weekly, because a scanner samples a few recordings a day and daily buckets are mostly noise.+ "interval": "week",+ "dateRange": {"date_from": DASHBOARD_DATE_FROM},+ "trendsFilter": {"display": display, **(trends_filter or {})},+ }+ if breakdown:+ source["breakdownFilter"] = breakdown+ self._add(name, description, {"kind": "InsightVizNode", "source": source})++ def _sql_chart(self, name: str, description: str, query: str, *, x: str, y: str) -> None:+ self._add(+ name,+ description,+ self._sql_node(+ query,+ display="ActionsBar",+ chartSettings={"xAxis": {"column": x}, "yAxis": [{"column": y}]},+ ),+ )++ def _sql_table(self, name: str, description: str, query: str, *, width: int = 6) -> None:+ self._add(name, description, self._sql_node(query), width=width)++ def _account_table(+ self,+ name: str,+ description: str,+ *,+ columns: dict[str, str],+ sort: str,+ where: str = "",+ having: str = "",+ ) -> None:+ """A table of the primary group type's accounts, labeled with each group's name when it has one.++ `columns` maps output column names to aggregate expressions, and `sort` is one of those names plus a direction.+ """+ assert self._primary_group_type is not None+ index, plural = self._primary_group_type+ aggregates = ", ".join(f"{expression} AS {column}" for column, expression in columns.items())+ # Rank on the events alone, then look up names for the 20 rows shown rather than joining every group.+ self._sql_table(+ name,+ description,+ f"""+ WITH ranked AS (+ SELECT $group_{index} AS group_key, {aggregates}+ FROM events+ WHERE {_SCANNER_WHERE}{where} AND notEmpty($group_{index})+ GROUP BY group_key+ {having}+ ORDER BY {sort}+ LIMIT 20+ )+ SELECT ifNull(nullIf(toString(named.name), ''), ranked.group_key) AS {escape_hogql_identifier(plural)},+ {", ".join(f"ranked.{column} AS {column}" for column in columns)}+ FROM ranked+ LEFT JOIN (+ SELECT key, properties.name AS name+ FROM groups+ WHERE index = {index} AND key IN (SELECT group_key FROM ranked)+ ) AS named ON named.key = ranked.group_key+ ORDER BY {sort}+ """,+ )++ def _sql_node(self, query: str, **settings: Any) -> dict[str, Any]:+ return {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": textwrap.dedent(query).strip().replace("{scanner_id}", self.scanner_id),+ "filters": {"dateRange": {"date_from": DASHBOARD_DATE_FROM}},+ },+ **settings,+ }++ def _add(self, name: str, description: str, query: dict[str, Any], *, width: int = 6) -> None:+ # Explicit layouts keep the builder's order: tiles fill two columns, and a full-width tile starts a new row.+ if self._x + width > 12:+ self._x, self._y = 0, self._y + _TILE_HEIGHT+ self.tiles.append(+ {+ "type": "INSIGHT",+ "name": name,+ "description": description,+ "query": query,+ "layouts": {"sm": {"x": self._x, "y": self._y, "w": width, "h": _TILE_HEIGHT}},+ "color": None,+ }+ )+ self._x += width+++def _pluralize(noun: str) -> str:+ if noun.endswith("y") and not noun.endswith(("ay", "ey", "oy", "uy")):+ return f"{noun[:-1]}ies"+ return f"{noun}es" if noun.endswith(("s", "x", "ch", "sh")) else f"{noun}s"diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex f17be8dc1fdd..8a720f4acc52 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -998,6 +998,7 @@ class TestReplayScannerViewSet(_VisionAPITestCase):[("impact", "get"),("affected_cohort", "post"),+ ("create_dashboard", "post"),])def test_recording_derived_action_rejected_without_session_recording_read(self, url_path: str, method: str) -> None:@@ -1007,12 +1008,18 @@ class TestReplayScannerViewSet(_VisionAPITestCase):self.assertEqual(resp.status_code, 403, resp.json())self.assertIn("session_recording", resp.json()["detail"])- def test_affected_cohort_rejected_without_cohort_edit_access(self) -> None:+ @parameterized.expand(+ [+ ("affected_cohort", "cohort"),+ ("create_dashboard", "dashboard"),+ ]+ )+ def test_action_rejected_without_edit_access_to_what_it_creates(self, url_path: str, resource: str) -> None:scanner = self._create_scanner()- with self._patch_deny_resource("cohort"):- resp = self.client.post(f"{self.scanners_url}{scanner.id}/affected_cohort/", format="json")+ with self._patch_deny_resource(resource):+ resp = self.client.post(f"{self.scanners_url}{scanner.id}/{url_path}/", format="json")self.assertEqual(resp.status_code, 403, resp.json())- self.assertIn("cohort", resp.json()["detail"])+ self.assertIn(resource, resp.json()["detail"])class TestScannerScoutCallerRules(_VisionAPITestCase):diff --git a/products/replay_vision/backend/tests/test_scanner_dashboard.py b/products/replay_vision/backend/tests/test_scanner_dashboard.pynew file mode 100644index 000000000000..e080f2607e0c--- /dev/null+++ b/products/replay_vision/backend/tests/test_scanner_dashboard.py@@ -0,0 +1,171 @@+from datetime import timedelta+from typing import Any++from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events+from unittest.mock import patch++from django.utils import timezone++from parameterized import parameterized++from posthog.api.services.query import ExecutionMode, process_query_dict+from posthog.models.group.util import create_group+from posthog.test.persons import create_group_type_mapping++from products.dashboards.backend.models.dashboard import Dashboard+from products.replay_vision.backend.models.replay_observation import (+ ObservationStatus,+ ObservationTrigger,+ ReplayObservation,+)+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType+from products.replay_vision.backend.scanner_dashboard import (+ DASHBOARD_SUGGESTION_MIN_OBSERVATIONS,+ create_scanner_dashboard,+)+from products.replay_vision.backend.tests.helpers import snapshot_for++_OUTPUT_BY_TYPE: dict[ScannerType, dict[str, Any]] = {+ ScannerType.MONITOR: {+ "scanner_output_verdict": "yes",+ "scanner_output_confidence": 0.8,+ "scanner_output_reasoning": "The user retried checkout three times.",+ },+ ScannerType.CLASSIFIER: {+ "scanner_output_tags": ["billing", "onboarding"],+ "scanner_output_tags_freeform": ["exports"],+ "scanner_output_reasoning": "Both flows appear.",+ },+ ScannerType.SCORER: {"scanner_output_score": 2.0, "scanner_output_reasoning": "Slow progress."},+ ScannerType.SUMMARIZER: {+ "scanner_output_title": "Set up a dashboard",+ "scanner_output_notability": 0.4,+ "scanner_output_chapter_count": 3,+ },+ ScannerType.EXPERIMENT: {+ "scanner_output_title": "Tried the new pricing page",+ "scanner_output_notability": 0.6,+ "scanner_output_chapter_count": 2,+ "experiment_variant": "test",+ },+}+++class _ScannerDashboardTestCase(APIBaseTest):+ def _make_scanner(self, scanner_type: ScannerType = ScannerType.MONITOR) -> ReplayScanner:+ return ReplayScanner.objects.create(+ team=self.team,+ name=f"dashboard-{scanner_type}",+ scanner_type=scanner_type,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_8_FLASH,+ )+++class TestScannerDashboardTiles(ClickhouseTestMixin, _ScannerDashboardTestCase):+ @parameterized.expand([(scanner_type.value, scanner_type) for scanner_type in ScannerType])+ def test_every_tile_returns_rows_for_observed_recordings(self, _name: str, scanner_type: ScannerType) -> None:+ create_group_type_mapping(+ team=self.team, project_id=self.team.project_id, group_type_index=0, group_type="company"+ )+ create_group(team_id=self.team.pk, group_type_index=0, group_key="acme", properties={"name": "Acme Inc"})+ scanner = self._make_scanner(scanner_type)+ # Trends ignore `$group_0` on events older than the group type mapping, so stamp the events after it.+ observed_at = timezone.now()+ # Three recordings for one company, so that the "at least 3 recordings" account tiles have a row.+ for index in range(3):+ _create_event(+ team=self.team,+ event="$recording_observed",+ distinct_id="replay-vision-system",+ timestamp=observed_at + timedelta(seconds=index),+ properties={+ "scanner_id": str(scanner.id),+ "scanner_type": scanner_type.value,+ "session_id": f"session-{index}",+ "recording_distinct_id": f"user-{index}",+ "$group_0": "acme",+ **_OUTPUT_BY_TYPE[scanner_type],+ },+ )+ flush_persons_and_events()++ dashboard_ref, _ = create_scanner_dashboard(scanner, self.user)++ tiles = list(Dashboard.objects.get(pk=dashboard_ref.id, team=self.team).tiles.select_related("insight"))+ self.assertGreater(len(tiles), 3)+ for tile in tiles:+ insight = tile.insight+ assert insight is not None and insight.query is not None+ query = insight.query+ with self.subTest(insight.name):+ response = process_query_dict(+ self.team, query["source"], execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS+ )+ payload = response if isinstance(response, dict) else response.model_dump()+ self.assertFalse(payload.get("error"), payload.get("error"))+ results = payload["results"]+ if query["kind"] == "InsightVizNode":+ self.assertGreater(+ sum(series.get("aggregated_value") or sum(series["data"]) for series in results),+ 0,+ insight.name,+ )+ else:+ self.assertGreater(len(results), 0)+ if insight.name in ("Top companies", "Lowest scoring companies"):+ self.assertEqual(results[0][0], "Acme Inc")+++class TestScannerDashboardEndpoint(_ScannerDashboardTestCase):+ def _observe(self, scanner: ReplayScanner, count: int, *, days_ago: int = 0) -> None:+ start = ReplayObservation.objects.filter(scanner=scanner).count()+ ReplayObservation.objects.bulk_create(+ ReplayObservation(+ scanner=scanner,+ team=self.team,+ session_id=f"session-{index}",+ status=ObservationStatus.SUCCEEDED,+ scanner_snapshot=snapshot_for(scanner),+ scanner_result={},+ triggered_by=ObservationTrigger.SCHEDULE,+ completed_at=timezone.now() - timedelta(days=days_ago),+ )+ for index in range(start, start + count)+ )++ def _scanner_state(self, scanner: ReplayScanner) -> tuple[int | None, bool]:+ body = self.client.get(f"/api/projects/{self.team.id}/vision/scanners/{scanner.id}/").json()+ return body["dashboard_id"], body["dashboard_suggested"]++ def _create_dashboard(self, scanner: ReplayScanner, expected_status: int) -> int:+ response = self.client.post(f"/api/projects/{self.team.id}/vision/scanners/{scanner.id}/create_dashboard/")+ self.assertEqual(response.status_code, expected_status, response.json())+ return response.json()["dashboard_id"]++ def test_suggests_once_populated_and_links_one_live_dashboard(self) -> None:+ scanner = self._make_scanner()+ # Observations older than the dashboard's date range would chart nothing, so they do not count.+ self._observe(scanner, DASHBOARD_SUGGESTION_MIN_OBSERVATIONS, days_ago=40)+ self.assertEqual(self._scanner_state(scanner), (None, False))++ self._observe(scanner, DASHBOARD_SUGGESTION_MIN_OBSERVATIONS - 1)+ self.assertEqual(self._scanner_state(scanner), (None, False))++ self._observe(scanner, 1)+ self.assertEqual(self._scanner_state(scanner), (None, True))++ dashboard_id = self._create_dashboard(scanner, 201)+ self.assertEqual(self._scanner_state(scanner), (dashboard_id, False))+ self.assertEqual(self._create_dashboard(scanner, 200), dashboard_id)+ # A caller who may not view the linked dashboard must not learn its name through the scanner.+ with patch(+ "products.access_control.backend.facade.user_access_control.UserAccessControl.check_access_level_for_object",+ return_value=False,+ ):+ response = self.client.post(f"/api/projects/{self.team.id}/vision/scanners/{scanner.id}/create_dashboard/")+ self.assertEqual(response.status_code, 403, response.json())++ Dashboard.objects.filter(pk=dashboard_id).update(deleted=True)+ self.assertEqual(self._scanner_state(scanner), (None, True))+ self.assertNotEqual(self._create_dashboard(scanner, 201), dashboard_id)diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 95cea47935b1..3f438f4827b3 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -1312,6 +1312,13 @@ export interface ReplayScannerApi {readonly limit_reached: boolean/** How much the scheduled sweep is slowed to keep this scanner inside its daily ClickHouse read budget. 1 means it checks for new recordings on the normal schedule; N means it checks once every N schedule intervals. Expensive filters raise it. */readonly sweep_throttle_factor: number+ /**+ * Dashboard created for this scanner with the create_dashboard action. Null when none was created or the user deleted it.+ * @nullable+ */+ readonly dashboard_id: number | null+ /** Whether to offer the user a dashboard for this scanner: true when the scanner has no dashboard and at least 20 succeeded observations to chart. Offer it once and do not repeat the offer if the user declines. */+ readonly dashboard_suggested: boolean/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */readonly last_swept_at: stringreadonly created_at: string@@ -1445,6 +1452,13 @@ export interface PatchedReplayScannerApi {readonly limit_reached?: boolean/** How much the scheduled sweep is slowed to keep this scanner inside its daily ClickHouse read budget. 1 means it checks for new recordings on the normal schedule; N means it checks once every N schedule intervals. Expensive filters raise it. */readonly sweep_throttle_factor?: number+ /**+ * Dashboard created for this scanner with the create_dashboard action. Null when none was created or the user deleted it.+ * @nullable+ */+ readonly dashboard_id?: number | null+ /** Whether to offer the user a dashboard for this scanner: true when the scanner has no dashboard and at least 20 succeeded observations to chart. Offer it once and do not repeat the offer if the user declines. */+ readonly dashboard_suggested?: boolean/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */readonly last_swept_at?: stringreadonly created_at?: string@@ -1559,6 +1573,15 @@ export interface BulkObserveResponseApi {results: BulkObserveResultApi[]}+export interface ScannerDashboardResponseApi {+ /** Id of the scanner's dashboard. */+ dashboard_id: number+ /** Name of the dashboard. */+ name: string+ /** True when this call created the dashboard. False when the scanner already had one, which is returned instead. */+ created: boolean+}+/*** Who this scanner's findings affected in the window; counted from observations, not estimated.*/diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.tsindex 52b286896134..657f8988828a 100644--- a/products/replay_vision/frontend/generated/api.ts+++ b/products/replay_vision/frontend/generated/api.ts@@ -45,6 +45,7 @@ import type {ReplayScannerBackfillApi,RetryResponseApi,ScannerCreatorsResponseApi,+ ScannerDashboardResponseApi,ScannerImpactApi,ScannerScoutCreateApi,ScannerScoutCreateResponseApi,@@ -811,6 +812,28 @@ export const visionScannersBulkObserveCreate = async (})}+export const getVisionScannersCreateDashboardCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/vision/scanners/${id}/create_dashboard/`+}++/**+ * Create a dashboard that charts this scanner's observations, and link it to the scanner.+ *+ * The tiles depend on the scanner type: who the scanner matched, which accounts they belong to,+ * type-specific breakdowns, and the latest matching recordings. Calling it again returns the+ * existing dashboard rather than a second one.+ */+export const visionScannersCreateDashboardCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ScannerDashboardResponseApi> => {+ return apiMutator<ScannerDashboardResponseApi>(getVisionScannersCreateDashboardCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getVisionScannersDuplicateCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/vision/scanners/${id}/duplicate/`}diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsxindex 320cfaad26a8..ed6658924764 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx@@ -83,6 +83,8 @@ const scanner = (overrides: Partial<ReplayScannerApi> = {}): ReplayScannerApi =>estimated_at: null,user_access_level: 'editor',sweep_throttle_factor: 1,+ dashboard_id: null,+ dashboard_suggested: false,...overrides,}) as ReplayScannerApi@@ -1239,6 +1241,15 @@ export const ScannerStatusThrottled: StoryObj = {decorators: [overviewDecorator({ ...summarizerScanner, sweep_throttle_factor: 12 }, summarizerStats)],}+// Once a scanner has enough observations, the overview offers a dashboard for it.+export const MonitorOverviewDashboardOffer: StoryObj = {+ parameters: {+ pageUrl: urls.replayVision(monitorOverviewScanner.id),+ featureFlags: { [FEATURE_FLAGS.REPLAY_VISION_SCANNER_DASHBOARD]: true },+ },+ decorators: [overviewDecorator({ ...monitorOverviewScanner, dashboard_suggested: true }, monitorOverviewStats)],+}+export const ClassifierOverview: StoryObj = {parameters: { pageUrl: urls.replayVision(classifierOverviewScanner.id) },decorators: [overviewDecorator(classifierOverviewScanner, classifierOverviewStats)],diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerDashboardOffer.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerDashboardOffer.tsxnew file mode 100644index 000000000000..ee78380e7329--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerDashboardOffer.tsx@@ -0,0 +1,40 @@+import { useActions, useValues } from 'kea'++import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { lemonBannerLogic } from 'lib/lemon-ui/LemonBanner/lemonBannerLogic'++import { scannerDashboardLogic, scannerDashboardOfferDismissKey } from '../scannerDashboardLogic'++export function ScannerDashboardOffer({ scannerId }: { scannerId: string }): JSX.Element | null {+ const { showDashboardOffer } = useValues(scannerDashboardLogic({ scannerId }))+ const { isDismissed } = useValues(lemonBannerLogic({ dismissKey: scannerDashboardOfferDismissKey(scannerId) }))+ if (!showDashboardOffer || isDismissed) {+ return null+ }+ return <VisibleScannerDashboardOffer scannerId={scannerId} />+}++function VisibleScannerDashboardOffer({ scannerId }: { scannerId: string }): JSX.Element {+ const { creatingDashboard } = useValues(scannerDashboardLogic({ scannerId }))+ const { createDashboard, dashboardOfferShown, dismissDashboardOffer } = useActions(+ scannerDashboardLogic({ scannerId })+ )+ useOnMountEffect(dashboardOfferShown)++ return (+ <LemonBanner+ type="info"+ dismissKey={scannerDashboardOfferDismissKey(scannerId)}+ onClose={dismissDashboardOffer}+ action={{+ children: 'Create dashboard',+ onClick: createDashboard,+ loading: creatingDashboard,+ 'data-attr': 'vision-scanner-dashboard-offer-create',+ }}+ >+ Track this scanner's findings on a dashboard.+ </LemonBanner>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsxindex 2db739bb36bb..197b7b880e9f 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx@@ -13,6 +13,7 @@ import { ReplayScannerTab, replayScannerSceneLogic } from '../replayScannerSceneimport { scannerOverviewLogic } from '../scannerOverviewLogic'import { ScannerType } from '../types'import { RootCausePrompt } from './RootCausePrompt'+import { ScannerDashboardOffer } from './ScannerDashboardOffer'import { ScannerInsightsChart } from './ScannerInsightsChart'import { ScannerOverviewFilters } from './ScannerOverviewFilters'import { ScannerScoutCard } from './ScannerScoutCard'@@ -421,6 +422,7 @@ export function ScannerOverview({ scannerId }: { scannerId: string }): JSX.Eleme</div></div><div className="@container min-w-0 flex flex-col gap-4 order-3 @5xl:col-start-2 @5xl:row-start-2">+ <ScannerDashboardOffer scannerId={scannerId} />{firstScanPending ? (<FirstScanPendingPanel scannerId={scannerId} />) : (diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsxindex 97a869842cf0..b3721d95b859 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsx@@ -13,6 +13,7 @@ import { formatCreditCount } from '../../utils/credits'import { scannerExperimentScope, scopeVariantsLabel } from '../experimentTargeting'import { replayScannerLogic } from '../replayScannerLogic'import { ReplayScannerTab } from '../replayScannerSceneLogic'+import { scannerDashboardLogic } from '../scannerDashboardLogic'import { scannerEditUrl } from '../scannerEditorSceneLogic'import { SCANNER_TYPE_OPTIONS, modelName, scannerTypeLabel } from '../types'import { PromptPreview } from './PromptPreview'@@ -24,6 +25,7 @@ function EnabledText({ enabled }: { enabled: boolean }): JSX.Element {export function ScannerSetupCard({ scannerId }: { scannerId: string }): JSX.Element | null {const { scanner, experimentContext } = useValues(replayScannerLogic({ id: scannerId }))+ const { dashboardId } = useValues(scannerDashboardLogic({ scannerId }))if (!scanner) {return null}@@ -145,6 +147,13 @@ export function ScannerSetupCard({ scannerId }: { scannerId: string }): JSX.Elem</span></LabeledRow>)}+ {dashboardId !== null && (+ <LabeledRow label="Dashboard">+ <Link to={urls.dashboard(dashboardId)} data-attr="vision-setup-open-dashboard">+ Open dashboard+ </Link>+ </LabeledRow>+ )}<LabeledRow label="Filters"><div className="[&_.PropertyFilterButton]:h-6 [&_.PropertyFilterButton]:text-xs [&_.UniversalFilterButton]:h-6 [&_.UniversalFilterButton]:text-xs"><ScannerRecordingFilters query={scanner.query} />diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex 584e40e99c29..520d44c64e5a 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -698,6 +698,9 @@ export interface replayScannerLogicActions {windowDays: number}}+ scannerDashboardLinked: (dashboardId: number) => {+ dashboardId: number+ }scannerSaved: (scanner: ScannerFormValues) => {scanner: ScannerFormValues}@@ -957,6 +960,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([toggleEnabledFailure: true,turnOnSelfDriving: true,turnOnSelfDrivingSuccess: (scannerVersion: number, updatedAt: string) => ({ scannerVersion, updatedAt }),+ scannerDashboardLinked: (dashboardId: number) => ({ dashboardId }),turnOnSelfDrivingFailure: true,setObservationStatusFilter: (values: ObservationStatusValue[]) => ({ values }),setObservationTriggeredByFilter: (values: ObservationTriggeredByValue[]) => ({ values }),@@ -1270,6 +1274,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([// Only the sweep watermark lands, so a background refresh can't clobber unsaved form edits.scannerWatermarkRefreshed: (state: ReplayScanner, { scanner }: { scanner: ReplayScanner }) =>state ? { ...state, last_swept_at: scanner.last_swept_at } : scanner,+ scannerDashboardLinked: (state: ReplayScanner, { dashboardId }: { dashboardId: number }) =>+ state ? { ...state, dashboard_id: dashboardId, dashboard_suggested: false } : state,},experimentContext: [null as ExperimentScannerContext | null,@@ -1291,6 +1297,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([state? { ...state, emits_signals: true, scanner_version: scannerVersion, updated_at: updatedAt }: state,+ // Mirrors the `scanner` patch so linking a dashboard never leaves the form looking edited.+ scannerDashboardLinked: (state, { dashboardId }) =>+ state ? { ...state, dashboard_id: dashboardId, dashboard_suggested: false } : state,},],togglingEnabled: [diff --git a/products/replay_vision/frontend/replay_scanners/scannerDashboardLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerDashboardLogic.tsnew file mode 100644index 000000000000..e690d9165409--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/scannerDashboardLogic.ts@@ -0,0 +1,143 @@+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { router } from 'kea-router'+import posthog from 'posthog-js'++import { FEATURE_FLAGS } from 'lib/constants'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { AccessControlLevel, AccessControlResourceType } from '~/types'++import { visionScannersCreateDashboardCreate } from '../generated/api'+import { getReplayVisionEditDisabledReason } from '../utils/accessControl'+import { replayScannerLogic } from './replayScannerLogic'+import type { ScannerFormValues } from './types'++export interface ScannerDashboardLogicProps {+ scannerId: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface scannerDashboardLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogic+ scanner: ScannerFormValues // replayScannerLogic+ creatingDashboard: boolean+ dashboardId: number | null+ showDashboardOffer: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface scannerDashboardLogicActions {+ scannerDashboardLinked: (dashboardId: number) => {+ dashboardId: number+ } // replayScannerLogic+ createDashboard: () => {+ value: true+ }+ createDashboardFinished: () => {+ value: true+ }+ dashboardOfferShown: () => {+ value: true+ }+ dismissDashboardOffer: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface scannerDashboardLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ dashboardId: (scanner: ScannerFormValues) => number | null+ showDashboardOffer: (featureFlags: FeatureFlagsSet, scanner: ScannerFormValues) => boolean+ }+}++export type scannerDashboardLogicType = MakeLogicType<+ scannerDashboardLogicValues,+ scannerDashboardLogicActions,+ ScannerDashboardLogicProps,+ scannerDashboardLogicMeta+>++// The dismissal is per viewer and per scanner, so it lives in the banner's localStorage key rather than on the scanner.+// pinned: localStorage key prefix, renaming it shows the offer again to everyone who dismissed it+export const scannerDashboardOfferDismissKey = (scannerId: string): string =>+ `replay-vision-scanner-dashboard-offer-${scannerId}`++export const scannerDashboardLogic = kea<scannerDashboardLogicType>([+ props({} as ScannerDashboardLogicProps),+ key((props) => props.scannerId),+ path((key) => ['products', 'replay_vision', 'frontend', 'replay_scanners', 'scannerDashboardLogic', key]),+ connect((props: ScannerDashboardLogicProps) => ({+ values: [replayScannerLogic({ id: props.scannerId }), ['scanner'], featureFlagLogic, ['featureFlags']],+ actions: [replayScannerLogic({ id: props.scannerId }), ['scannerDashboardLinked']],+ })),+ actions({+ createDashboard: true,+ createDashboardFinished: true,+ dashboardOfferShown: true,+ dismissDashboardOffer: true,+ }),+ reducers({+ creatingDashboard: [+ false,+ {+ createDashboard: () => true,+ createDashboardFinished: () => false,+ },+ ],+ }),+ selectors({+ dashboardId: [(s) => [s.scanner], (scanner: ScannerFormValues): number | null => scanner?.dashboard_id ?? null],+ showDashboardOffer: [+ (s) => [s.featureFlags, s.scanner],+ (featureFlags: FeatureFlagsSet, scanner: ScannerFormValues): boolean =>+ !!featureFlags[FEATURE_FLAGS.REPLAY_VISION_SCANNER_DASHBOARD] &&+ !!scanner?.dashboard_suggested &&+ // Only offer to people the endpoint accepts, rather than showing a button that answers with a 403.+ !getReplayVisionEditDisabledReason(scanner.user_access_level) &&+ !getAccessControlDisabledReason(AccessControlResourceType.Dashboard, AccessControlLevel.Editor),+ ],+ }),+ listeners(({ actions, props, values }) => ({+ createDashboard: async () => {+ const teamId = teamLogic.values.currentTeamId+ try {+ if (!teamId) {+ return+ }+ const response = await visionScannersCreateDashboardCreate(String(teamId), props.scannerId)+ actions.scannerDashboardLinked(response.dashboard_id)+ lemonToast.success(`Dashboard "${response.name}" created`, {+ button: {+ label: 'Open dashboard',+ action: () => router.actions.push(urls.dashboard(response.dashboard_id)),+ },+ })+ } catch (error: any) {+ lemonToast.error(`Couldn't create the dashboard${error?.detail ? `: ${error.detail}` : ''}`)+ } finally {+ actions.createDashboardFinished()+ }+ },+ dashboardOfferShown: () => {+ // pinned: analytics event name, renaming breaks the offer funnel+ posthog.capture('replay_vision_scanner_dashboard_offer_shown', {+ scanner_id: props.scannerId,+ scanner_type: values.scanner?.scanner_type,+ })+ },+ dismissDashboardOffer: () => {+ // pinned: analytics event name, renaming breaks the offer funnel+ posthog.capture('replay_vision_scanner_dashboard_offer_dismissed', {+ scanner_id: props.scannerId,+ scanner_type: values.scanner?.scanner_type,+ })+ },+ })),+])diff --git a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts b/products/replay_vision/frontend/replay_scanners/scannerTemplates.tsindex 0e26886c020c..baa2cd42dd7e 100644--- a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts@@ -170,6 +170,8 @@ export function newScanner(templateKey?: string | null, teamName?: string | nullcredits_used_against_limit: 0,limit_reached: false,sweep_throttle_factor: 1,+ dashboard_id: null,+ dashboard_suggested: false,} as constconst template = findScannerTemplate(templateKey ?? undefined)diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yamlindex 5183b0ee8ba2..c5fcc70e5813 100644--- a/products/replay_vision/mcp/tools.yaml+++ b/products/replay_vision/mcp/tools.yaml@@ -571,6 +571,22 @@ tools:- created_by- updated_atrequires_ai_consent: true+ vision-scanners-dashboard-create:+ operation: vision_scanners_create_dashboard_create+ enabled: true+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Create a dashboard for a scanner+ description: >+ Create a dashboard that charts a scanner's observations and link it to the scanner. Tiles depend on the+ scanner type: people (and accounts, when group analytics is set up) the scanner matched per week,+ type-specific breakdowns such as yes rate, category share or score percentiles, and the latest matching+ recordings. Offer it when `vision-scanners-get` returns `dashboard_suggested: true`, at most once per+ conversation, and only call it when the user agrees. Calling it again returns the existing dashboard+ (`created: false`) rather than a second one. Link the user to the dashboard at /dashboard/{dashboard_id}.+ feature_flag: replay-vision-scanner-dashboardvision-scanners-delete:operation: vision_scanners_destroyenabled: true@@ -662,6 +678,8 @@ tools:`vision-scanners-list`. Returns the full configuration including `scanner_config` (the type-specific promptand response schema parameters), the `RecordingsQuery` used to select sessions, and operational fields like`enabled`, `sampling_rate`, `provider`, `model`, `emits_signals`, `scanner_version`, and `last_swept_at`.+ `dashboard_id` links the scanner's dashboard when one exists, and `dashboard_suggested` says whether to+ offer the user one with `vision-scanners-dashboard-create`.vision-scanners-impact-get:operation: vision_scanners_impact_retrieveenabled: truediff --git a/products/replay_vision/skills/creating-replay-vision-scanners/SKILL.md b/products/replay_vision/skills/creating-replay-vision-scanners/SKILL.mdindex a135bb27ce35..35abd80e9a8d 100644--- a/products/replay_vision/skills/creating-replay-vision-scanners/SKILL.md+++ b/products/replay_vision/skills/creating-replay-vision-scanners/SKILL.md@@ -172,6 +172,9 @@ observations they have to go read.and call `vision-scanners-backfills-create` only once they agree, passing that `total_credits` as`max_total_credits`. If the create is rejected because the window now costs more, estimate again and askagain. Watch it with `vision-scanners-backfills-get`.+- **Dashboard, once there is data.** When `vision-scanners-get` returns `dashboard_suggested: true` (the scanner+ has enough observations and no dashboard yet), offer once to create one with `vision-scanners-dashboard-create`.+ Do not repeat the offer if the user declines. A brand-new scanner is never suggested, because it has nothing to chart.- **Notifications and digests.** `vision-alerts-create` (plus a destination) notifies on findings;`vision-scanners-scouts-create` adds a scheduled scout that writes a report about the scanner's findings.- **Say how the scanner gets better.** A first prompt is a guess, and the first sweep is what corrects it.diff --git a/products/replay_vision/skills/exploring-replay-vision-observations/SKILL.md b/products/replay_vision/skills/exploring-replay-vision-observations/SKILL.mdindex d906d7aa6458..163dc7d23a60 100644--- a/products/replay_vision/skills/exploring-replay-vision-observations/SKILL.md+++ b/products/replay_vision/skills/exploring-replay-vision-observations/SKILL.md@@ -137,6 +137,9 @@ Match the action to the user's intent, and **corroborate before you create work*tracked work, `vision-observations-create-task` opens a PostHog task from one observation (idempotent perobservation; it does not start a coding agent). Group by distinct issue, not per observation: pick theclearest observation for each issue.+- **Track the scanner on a dashboard.** If the scanner from Step 1 has `dashboard_suggested: true`, offer once to+ create its dashboard with `vision-scanners-dashboard-create`, and drop it if the user declines. When it has+ `dashboard_id`, link that dashboard instead of building new insights for what it already charts.- **Get told when it recurs.** `vision-alerts-create` puts an alert on the scanner: a `match` alert fires onevery matching observation, a `metric` alert when a count or average score crosses a threshold over awindow. Add a Slack or webhook destination with `vision-alerts-destinations-create`.diff --git a/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.stories.tsx b/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.stories.tsxindex 5bd74673dd29..11de391221b2 100644--- a/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.stories.tsx+++ b/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.stories.tsx@@ -80,6 +80,8 @@ const meta: Meta<typeof ContentAutopilot> = {parameters: {layout: 'fullscreen',featureFlags: [FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE, FEATURE_FLAGS.WEB_ANALYTICS_CONTENT_AUTOPILOT],+ // The fixtures carry fixed dates and the UI shows them relative to now, so the clock is pinned near them.+ mockDate: '2026-09-30',},}diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 2c4b775a5bf4..3d322b1d4884 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -14012,6 +14012,21 @@},"requires_ai_consent": true},+ "vision-scanners-dashboard-create": {+ "description": "Create a dashboard that charts a scanner's observations and link it to the scanner. Tiles depend on the scanner type: people (and accounts, when group analytics is set up) the scanner matched per week, type-specific breakdowns such as yes rate, category share or score percentiles, and the latest matching recordings. Offer it when `vision-scanners-get` returns `dashboard_suggested: true`, at most once per conversation, and only call it when the user agrees. Calling it again returns the existing dashboard (`created: false`) rather than a second one. Link the user to the dashboard at /dashboard/{dashboard_id}.",+ "category": "Replay vision",+ "feature": "replay_vision",+ "summary": "Create a dashboard for a scanner",+ "title": "Create a dashboard for a scanner",+ "required_scopes": ["replay_scanner:read", "session_recording:read", "dashboard:write", "insight:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "replay-vision-scanner-dashboard"+ },"vision-scanners-delete": {"description": "Permanently delete a replay vision scanner by ID. The scanner stops scanning immediately and its scheduled Temporal jobs are removed by the reconciler. Past observations recorded by this scanner are deleted along with it. Use sparingly — to stop a scanner without losing its history, set `enabled: false` via `vision-scanners-update` instead.","category": "Replay vision",@@ -14071,7 +14086,7 @@}},"vision-scanners-get": {- "description": "Get a single replay vision scanner. The scanner id goes in `id` — the `vision-scanners-observations-*` tools take the same value as `scanner_id`, but this one does not accept that name. Get an id from `vision-scanners-list`. Returns the full configuration including `scanner_config` (the type-specific prompt and response schema parameters), the `RecordingsQuery` used to select sessions, and operational fields like `enabled`, `sampling_rate`, `provider`, `model`, `emits_signals`, `scanner_version`, and `last_swept_at`.",+ "description": "Get a single replay vision scanner. The scanner id goes in `id` — the `vision-scanners-observations-*` tools take the same value as `scanner_id`, but this one does not accept that name. Get an id from `vision-scanners-list`. Returns the full configuration including `scanner_config` (the type-specific prompt and response schema parameters), the `RecordingsQuery` used to select sessions, and operational fields like `enabled`, `sampling_rate`, `provider`, `model`, `emits_signals`, `scanner_version`, and `last_swept_at`. `dashboard_id` links the scanner's dashboard when one exists, and `dashboard_suggested` says whether to offer the user one with `vision-scanners-dashboard-create`.","category": "Replay vision","feature": "replay_vision","summary": "Get replay vision scanner",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 7c8c0528ff62..4bea21ee745e 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -14690,6 +14690,21 @@},"requires_ai_consent": true},+ "vision-scanners-dashboard-create": {+ "description": "Create a dashboard that charts a scanner's observations and link it to the scanner. Tiles depend on the scanner type: people (and accounts, when group analytics is set up) the scanner matched per week, type-specific breakdowns such as yes rate, category share or score percentiles, and the latest matching recordings. Offer it when `vision-scanners-get` returns `dashboard_suggested: true`, at most once per conversation, and only call it when the user agrees. Calling it again returns the existing dashboard (`created: false`) rather than a second one. Link the user to the dashboard at /dashboard/{dashboard_id}.",+ "category": "Replay vision",+ "feature": "replay_vision",+ "summary": "Create a dashboard for a scanner",+ "title": "Create a dashboard for a scanner",+ "required_scopes": ["replay_scanner:read", "session_recording:read", "dashboard:write", "insight:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "replay-vision-scanner-dashboard"+ },"vision-scanners-delete": {"description": "Permanently delete a replay vision scanner by ID. The scanner stops scanning immediately and its scheduled Temporal jobs are removed by the reconciler. Past observations recorded by this scanner are deleted along with it. Use sparingly — to stop a scanner without losing its history, set `enabled: false` via `vision-scanners-update` instead.","category": "Replay vision",@@ -14749,7 +14764,7 @@}},"vision-scanners-get": {- "description": "Get a single replay vision scanner. The scanner id goes in `id` — the `vision-scanners-observations-*` tools take the same value as `scanner_id`, but this one does not accept that name. Get an id from `vision-scanners-list`. Returns the full configuration including `scanner_config` (the type-specific prompt and response schema parameters), the `RecordingsQuery` used to select sessions, and operational fields like `enabled`, `sampling_rate`, `provider`, `model`, `emits_signals`, `scanner_version`, and `last_swept_at`.",+ "description": "Get a single replay vision scanner. The scanner id goes in `id` — the `vision-scanners-observations-*` tools take the same value as `scanner_id`, but this one does not accept that name. Get an id from `vision-scanners-list`. Returns the full configuration including `scanner_config` (the type-specific prompt and response schema parameters), the `RecordingsQuery` used to select sessions, and operational fields like `enabled`, `sampling_rate`, `provider`, `model`, `emits_signals`, `scanner_version`, and `last_swept_at`. `dashboard_id` links the scanner's dashboard when one exists, and `dashboard_suggested` says whether to offer the user one with `vision-scanners-dashboard-create`.","category": "Replay vision","feature": "replay_vision","summary": "Get replay vision scanner",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex bf3498119afb..4c276d007e5d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -71801,6 +71801,13 @@ export namespace Schemas {readonly limit_reached: boolean;/** How much the scheduled sweep is slowed to keep this scanner inside its daily ClickHouse read budget. 1 means it checks for new recordings on the normal schedule; N means it checks once every N schedule intervals. Expensive filters raise it. */readonly sweep_throttle_factor: number;+ /**+ * Dashboard created for this scanner with the create_dashboard action. Null when none was created or the user deleted it.+ * @nullable+ */+ readonly dashboard_id: number | null;+ /** Whether to offer the user a dashboard for this scanner: true when the scanner has no dashboard and at least 20 succeeded observations to chart. Offer it once and do not repeat the offer if the user declines. */+ readonly dashboard_suggested: boolean;/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */readonly last_swept_at: string;readonly created_at: string;@@ -83812,6 +83819,13 @@ export namespace Schemas {readonly limit_reached?: boolean;/** How much the scheduled sweep is slowed to keep this scanner inside its daily ClickHouse read budget. 1 means it checks for new recordings on the normal schedule; N means it checks once every N schedule intervals. Expensive filters raise it. */readonly sweep_throttle_factor?: number;+ /**+ * Dashboard created for this scanner with the create_dashboard action. Null when none was created or the user deleted it.+ * @nullable+ */+ readonly dashboard_id?: number | null;+ /** Whether to offer the user a dashboard for this scanner: true when the scanner has no dashboard and at least 20 succeeded observations to chart. Offer it once and do not repeat the offer if the user declines. */+ readonly dashboard_suggested?: boolean;/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */readonly last_swept_at?: string;readonly created_at?: string;@@ -97976,6 +97990,15 @@ export namespace Schemas {creators: UserBasic[];}+ export interface ScannerDashboardResponse {+ /** Id of the scanner's dashboard. */+ dashboard_id: number;+ /** Name of the dashboard. */+ name: string;+ /** True when this call created the dashboard. False when the scanner already had one, which is returned instead. */+ created: boolean;+ }+/*** Who this scanner's findings affected in the window; counted from observations, not estimated.*/diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.tsindex d8e79bf2a873..d6ed38b71765 100644--- a/services/mcp/src/generated/replay_vision/api.ts+++ b/services/mcp/src/generated/replay_vision/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 51 enabled ops+ * PostHog API - MCP 52 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -1249,6 +1249,22 @@ export const VisionScannersBulkObserveCreateBody = () => zod}).describe('Body of POST \/vision\/scanners\/{id}\/bulk_observe\/.')+/**+ * Create a dashboard that charts this scanner's observations, and link it to the scanner.+ *+ * The tiles depend on the scanner type: who the scanner matched, which accounts they belong to,+ * type-specific breakdowns, and the latest matching recordings. Calling it again returns the+ * existing dashboard rather than a second one.+ */+export const VisionScannersCreateDashboardCreateParams = () => zod.object({+ id: zod.string().describe('A UUID string identifying this replay scanner.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})+/*** Copy a scanner into a new disabled scanner named "<name> (copy)".*diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.tsindex ae4e124a6eda..eeec5b354871 100644--- a/services/mcp/src/tools/generated/replay_vision.ts+++ b/services/mcp/src/tools/generated/replay_vision.ts@@ -961,6 +961,27 @@ const visionScannersCreate = (): ToolBase<},})+const VisionScannersDashboardCreateSchema = () => {+ const VisionScannersCreateDashboardCreateParams = orvalSchemas.VisionScannersCreateDashboardCreateParams()+ return VisionScannersCreateDashboardCreateParams.omit({ project_id: true })+}++const visionScannersDashboardCreate = (): ToolBase<+ ReturnType<typeof VisionScannersDashboardCreateSchema>,+ Schemas.ScannerDashboardResponse+> => ({+ name: 'vision-scanners-dashboard-create',+ schema: VisionScannersDashboardCreateSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof VisionScannersDashboardCreateSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.ScannerDashboardResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/${encodeURIComponent(String(params.id))}/create_dashboard/`,+ })+ return result+ },+})+const VisionScannersDeleteSchema = () => {const VisionScannersDestroyParams = orvalSchemas.VisionScannersDestroyParams()return VisionScannersDestroyParams.omit({ project_id: true })@@ -1708,6 +1729,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'vision-scanners-backfills-resume': visionScannersBackfillsResume,'vision-scanners-counts': visionScannersCounts,'vision-scanners-create': visionScannersCreate,+ 'vision-scanners-dashboard-create': visionScannersDashboardCreate,'vision-scanners-delete': visionScannersDelete,'vision-scanners-draft': visionScannersDraft,'vision-scanners-duplicate': visionScannersDuplicate,diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 9f5965668d26..7abf35e7fd22 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -1067,6 +1067,7 @@ describe('Tool Filtering - Feature Flags', () => {'cross-project-dashboards','warehouse-suggestions','scouts-tool-access',+ 'replay-vision-scanner-dashboard','metrics-dashboard-import',]expect(allFlags).toEqual(expect.arrayContaining(branchFlags))diff --git a/tach.toml b/tach.tomlindex 119c339b9342..6d94d776f013 100644--- a/tach.toml+++ b/tach.toml@@ -813,6 +813,8 @@ depends_on = ["products.alerts","products.cdp","products.cohorts",+ # Facade-only: scanner dashboards are created and looked up through the dashboards facade.+ "products.dashboards","products.event_definitions","products.experiments","products.exports",