Skip to content

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

feat(replay-vision): show impacted users and cohort per scanner (#70059)

Hayne Ryu835ac50f88d8
diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.py
index 953bb7f95968..5f4994a1b632 100644
--- a/products/cohorts/backend/models/cohort.py
+++ b/products/cohorts/backend/models/cohort.py
@@ -634,6 +634,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
*,
team_id: Optional[int] = None,
batch_size: int = DEFAULT_COHORT_INSERT_BATCH_SIZE,
+ raise_on_error: bool = False,
) -> int:
"""
Insert a list of users identified by their distinct ID into the cohort, for the given team.
@@ -642,6 +643,10 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
items: List of distinct IDs of users to be inserted into the cohort.
team_id: ID of the team for which to insert the users. Defaults to `self.team`, because of a lot of existing usage in tests.
batch_size: Number of records to process in each batch. Defaults to 1000.
+ raise_on_error: When True, a batch insert failure is re-raised and terminal cohort
+ state is left for the caller to finalize, instead of being swallowed and
+ recorded on the cohort here. Use when the caller must not treat a partial
+ insert as success.
"""
if team_id is None:
team_id = self.team_id
@@ -661,7 +666,9 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
return get_person_uuids_by_distinct_ids(team_id, items[start_idx:end_idx])
batch_iterator = FunctionBatchIterator(create_uuid_batch, batch_size=batch_size, max_items=len(items))
- return self._insert_users_list_with_batching(batch_iterator, insert_in_clickhouse=True, team_id=team_id)
+ return self._insert_users_list_with_batching(
+ batch_iterator, insert_in_clickhouse=True, team_id=team_id, raise_on_error=raise_on_error
+ )
def insert_users_list_by_uuid(
self,
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index c0d3613fb844..04ff5ceeac8f 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -39,6 +39,11 @@ from products.replay_vision.backend.billing import observation_credits_for_model
from products.replay_vision.backend.digest import provision_scanner_digest
from products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermission, is_replay_vision_actions_enabled
from products.replay_vision.backend.feedback_themes import cached_feedback_themes
+from products.replay_vision.backend.impact import (
+ DEFAULT_IMPACT_WINDOW_DAYS,
+ compute_scanner_impact,
+ create_affected_cohort,
+)
from products.replay_vision.backend.models.replay_observation import ObservationTrigger
from products.replay_vision.backend.models.replay_scanner import (
ReplayScanner,
@@ -714,6 +719,102 @@ class SuggestTagsResponseSerializer(serializers.Serializer):
)
+class ScannerImpactSerializer(serializers.Serializer):
+ """Who this scanner's findings affected in the window; counted from observations, not estimated."""
+
+ affected_sessions = serializers.IntegerField(
+ read_only=True,
+ help_text=(
+ "Distinct sessions with an affected observation in the window. For monitors only verdict-yes "
+ "observations count; for other scanner types every succeeded observation counts."
+ ),
+ )
+ affected_users = serializers.IntegerField(
+ read_only=True,
+ help_text=(
+ "Distinct users behind the affected sessions, by distinct ID. May include anonymous "
+ "device IDs when the recorded sessions were not identified."
+ ),
+ )
+ sessions_without_user = serializers.IntegerField(
+ read_only=True,
+ help_text="Affected sessions whose recording carried no distinct ID at all.",
+ )
+ window_days = serializers.IntegerField(
+ read_only=True,
+ help_text="Trailing window the counts cover, in days.",
+ )
+
+
+class _ImpactQualifiersSerializer(serializers.Serializer):
+ """Shared impact parameters. Monitors take none; classifiers require `tag`; scorers require a score bound."""
+
+ window_days = serializers.IntegerField(
+ required=False,
+ default=DEFAULT_IMPACT_WINDOW_DAYS,
+ min_value=1,
+ max_value=90,
+ help_text="Trailing window of observations to count. Defaults to 30 days.",
+ )
+ tag = serializers.CharField(
+ required=False,
+ allow_null=True,
+ default=None,
+ max_length=_MAX_TAG_LENGTH,
+ help_text=(
+ "Classifier scanners only, required for them: count sessions carrying this tag "
+ "(fixed or freeform). Not applicable to other scanner types."
+ ),
+ )
+ min_score = serializers.FloatField(
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text=(
+ "Scorer scanners only: count sessions scoring at or above this value. Scorers require "
+ "`min_score` and/or `max_score`. Not applicable to other scanner types."
+ ),
+ )
+ max_score = serializers.FloatField(
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text="Scorer scanners only: count sessions scoring at or below this value.",
+ )
+
+
+class ScannerImpactQuerySerializer(_ImpactQualifiersSerializer):
+ """Query parameters of GET /vision/scanners/:id/impact/."""
+
+
+class AffectedCohortRequestSerializer(_ImpactQualifiersSerializer):
+ """Body of POST /vision/scanners/:id/affected_cohort/. Same qualifiers as the impact GET."""
+
+
+class AffectedCohortResponseSerializer(serializers.Serializer):
+ """The static cohort created from the scanner's affected users."""
+
+ cohort_id = serializers.IntegerField(
+ read_only=True,
+ help_text="ID of the created static cohort; usable anywhere cohorts are (funnels, surveys, experiments).",
+ )
+ name = serializers.CharField(
+ read_only=True,
+ help_text="Generated cohort name, stamped with the creation date since the snapshot doesn't live-update.",
+ )
+ users_in_cohort = serializers.IntegerField(
+ read_only=True,
+ help_text=(
+ "Persons actually in the created cohort. Can be lower than `affected_users`: matched "
+ "distinct IDs without a person profile are dropped, and merged persons deduplicate."
+ ),
+ )
+ window_days = serializers.IntegerField(
+ read_only=True,
+ help_text="Trailing window the cohort was drawn from, in days.",
+ )
+
+
@extend_schema_view(
list=extend_schema(
parameters=[
@@ -839,6 +940,81 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
status=status.HTTP_202_ACCEPTED,
)
+ @extend_schema(parameters=[ScannerImpactQuerySerializer], responses={200: ScannerImpactSerializer})
+ @action(
+ detail=True,
+ methods=["get"],
+ url_path="impact",
+ required_scopes=["replay_scanner:read", "session_recording:read"],
+ )
+ def impact(self, request: Request, **kwargs: Any) -> Response:
+ """Affected sessions and users for this scanner over the trailing window."""
+ # Impact counts are derived from recording observations; without this gate a member denied
+ # session_recording access could read verdict/tag/score aggregates the observations endpoint blocks.
+ if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):
+ raise PermissionDenied("Reading scanner impact requires session_recording read access.")
+ scanner = self.get_object()
+ params = ScannerImpactQuerySerializer(data=request.query_params)
+ params.is_valid(raise_exception=True)
+ try:
+ impact = compute_scanner_impact(
+ scanner,
+ params.validated_data["window_days"],
+ tag=params.validated_data["tag"],
+ min_score=params.validated_data["min_score"],
+ max_score=params.validated_data["max_score"],
+ )
+ except ValueError as exc:
+ raise ValidationError(str(exc)) from exc
+ return Response(ScannerImpactSerializer(instance=impact).data)
+
+ @extend_schema(
+ request=AffectedCohortRequestSerializer,
+ responses={201: AffectedCohortResponseSerializer},
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="affected_cohort",
+ required_scopes=["replay_scanner:read", "session_recording:read", "cohort:write"],
+ )
+ def affected_cohort(self, request: Request, **kwargs: Any) -> Response:
+ """Save the users this scanner matched as a static cohort, for surveys, funnels, and retention analysis."""
+ # The cohort materializes recording-derived identities; require the same recording access
+ # the observations endpoint enforces before exposing per-session results.
+ if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):
+ raise PermissionDenied("Saving an affected cohort requires session_recording read access.")
+ # `cohort:write` in required_scopes only constrains API keys; session RBAC evaluates against this
+ # viewset's replay_scanner scope object, so the caller's cohort access must be checked explicitly.
+ if not self.user_access_control.check_access_level_for_resource("cohort", required_level="editor"):
+ raise PermissionDenied("Saving an affected cohort requires cohort edit access.")
+ scanner = self.get_object()
+ body = AffectedCohortRequestSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ window_days: int = body.validated_data["window_days"]
+ try:
+ cohort, inserted = create_affected_cohort(
+ scanner,
+ cast(User, request.user),
+ window_days=window_days,
+ tag=body.validated_data["tag"],
+ min_score=body.validated_data["min_score"],
+ max_score=body.validated_data["max_score"],
+ )
+ except ValueError as exc:
+ raise ValidationError(str(exc)) from exc
+ return Response(
+ AffectedCohortResponseSerializer(
+ {
+ "cohort_id": cohort.id,
+ "name": cohort.name,
+ "users_in_cohort": inserted,
+ "window_days": window_days,
+ }
+ ).data,
+ status=status.HTTP_201_CREATED,
+ )
+
@extend_schema(
request=EstimateRequestSerializer,
responses={200: EstimateResponseSerializer},
diff --git a/products/replay_vision/backend/impact.py b/products/replay_vision/backend/impact.py
new file mode 100644
index 000000000000..474823f87c7c
--- /dev/null
+++ b/products/replay_vision/backend/impact.py
@@ -0,0 +1,171 @@
+"""Who a scanner's findings affected: counted from observations, exportable as a static cohort."""
+
+from dataclasses import dataclass
+from datetime import timedelta
+
+from django.db.models import Case, CharField, Count, FloatField, Func, Q, QuerySet, Value, When
+from django.db.models.fields.json import KeyTextTransform, KeyTransform
+from django.db.models.functions import Cast, Coalesce
+from django.utils import timezone
+
+from posthog.models.user import User
+
+from products.cohorts.backend.models.cohort import Cohort
+from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
+
+DEFAULT_IMPACT_WINDOW_DAYS = 30
+# Bounds the synchronous in-request insert.
+MAX_COHORT_DISTINCT_IDS = 10_000
+# Stable prefix so Vision can re-identify its own cohorts.
+COHORT_NAME_PREFIX = "Matched by "
+
+# A distinct_id may still be an anonymous device id, not an identified person.
+_HAS_USER = ~Q(distinct_id__isnull=True) & ~Q(distinct_id="")
+
+
+@dataclass(frozen=True)
+class ScannerImpact:
+ affected_sessions: int
+ affected_users: int
+ sessions_without_user: int
+ window_days: int
+
+
+def affected_observations(
+ scanner: ReplayScanner,
+ window_days: int,
+ *,
+ tag: str | None = None,
+ min_score: float | None = None,
+ max_score: float | None = None,
+) -> QuerySet[ReplayObservation]:
+ """Succeeded observations matching the type's impact predicate; raises ValueError on invalid qualifiers."""
+ since = timezone.now() - timedelta(days=window_days)
+ base = ReplayObservation.objects.annotate(
+ # Session time, not scan time: backfills must not count as current impact.
+ _affected_at=Coalesce("session_started_at", "created_at"),
+ ).filter(
+ scanner=scanner,
+ team_id=scanner.team_id,
+ status=ObservationStatus.SUCCEEDED,
+ _affected_at__gte=since,
+ )
+ scanner_type = scanner.scanner_type
+ has_scores = min_score is not None or max_score is not None
+
+ if scanner_type == ScannerType.MONITOR:
+ if tag or has_scores:
+ raise ValueError("Monitor impact is verdict-based; tag and score filters don't apply.")
+ return base.filter(scanner_result__model_output__verdict="yes")
+
+ if scanner_type == ScannerType.CLASSIFIER:
+ if has_scores:
+ raise ValueError("Classifiers don't produce scores; use `tag` instead.")
+ if not tag:
+ raise ValueError("Classifier impact requires `tag`: the tag whose affected users you want.")
+ # Same predicate as the observations list filter.
+ return base.filter(
+ Q(scanner_result__model_output__tags__contains=[tag])
+ | Q(scanner_result__model_output__tags_freeform__contains=[tag])
+ )
+
+ if scanner_type == ScannerType.SCORER:
+ if tag:
+ raise ValueError("Scorers don't produce tags; use `min_score`/`max_score` instead.")
+ if not has_scores:
+ raise ValueError("Scorer impact requires `min_score` and/or `max_score`.")
+ score_jsonb = KeyTransform("score", KeyTransform("model_output", "scanner_result"))
+ score_text = KeyTextTransform("score", KeyTextTransform("model_output", "scanner_result"))
+ # CASE-guard the cast so a non-numeric score (schema drift) doesn't 500 the query.
+ qs = base.annotate(
+ _score_type=Func(score_jsonb, function="jsonb_typeof", output_field=CharField()),
+ _score=Case(
+ When(_score_type="number", then=Cast(score_text, FloatField())),
+ default=Value(None),
+ output_field=FloatField(),
+ ),
+ )
+ if min_score is not None:
+ qs = qs.filter(_score__gte=min_score)
+ if max_score is not None:
+ qs = qs.filter(_score__lte=max_score)
+ return qs
+
+ raise ValueError(f"Impact is not available for {scanner_type} scanners.")
+
+
+def compute_scanner_impact(
+ scanner: ReplayScanner,
+ window_days: int = DEFAULT_IMPACT_WINDOW_DAYS,
+ *,
+ tag: str | None = None,
+ min_score: float | None = None,
+ max_score: float | None = None,
+) -> ScannerImpact:
+ aggregates = affected_observations(
+ scanner, window_days, tag=tag, min_score=min_score, max_score=max_score
+ ).aggregate(
+ affected_sessions=Count("session_id", distinct=True),
+ affected_users=Count("distinct_id", filter=_HAS_USER, distinct=True),
+ sessions_without_user=Count("session_id", filter=~_HAS_USER, distinct=True),
+ )
+ return ScannerImpact(window_days=window_days, **aggregates)
+
+
+def _qualifier_label(tag: str | None, min_score: float | None, max_score: float | None) -> str:
+ if tag:
+ return f", tag {tag}"
+ if min_score is not None and max_score is not None:
+ return f", score {min_score:g} to {max_score:g}"
+ if min_score is not None:
+ return f", score {min_score:g}+"
+ if max_score is not None:
+ return f", score up to {max_score:g}"
+ return ""
+
+
+def create_affected_cohort(
+ scanner: ReplayScanner,
+ user: User | None,
+ window_days: int = DEFAULT_IMPACT_WINDOW_DAYS,
+ *,
+ tag: str | None = None,
+ min_score: float | None = None,
+ max_score: float | None = None,
+) -> tuple[Cohort, int]:
+ """Static cohort of matched users; returns (cohort, real member count). Raises ValueError when not creatable."""
+ distinct_ids = list(
+ affected_observations(scanner, window_days, tag=tag, min_score=min_score, max_score=max_score)
+ .filter(_HAS_USER)
+ .values_list("distinct_id", flat=True)
+ .distinct()[: MAX_COHORT_DISTINCT_IDS + 1]
+ )
+ if not distinct_ids:
+ raise ValueError("No users in the window to save as a cohort.")
+ if len(distinct_ids) > MAX_COHORT_DISTINCT_IDS:
+ raise ValueError(f"Too many users to save as one cohort (over {MAX_COHORT_DISTINCT_IDS:,}). Narrow the window.")
+
+ qualifier = _qualifier_label(tag, min_score, max_score)
+ cohort = Cohort.objects.create(
+ team_id=scanner.team_id,
+ name=f"{COHORT_NAME_PREFIX}{scanner.name}{qualifier} ({timezone.now().date().isoformat()})"[:400],
+ description=(
+ f"Users matched by the '{scanner.name}' scanner{qualifier} in the last {window_days} days. Static snapshot."
+ ),
+ is_static=True,
+ created_by=user,
+ )
+ try:
+ cohort.insert_users_by_list(distinct_ids, team_id=scanner.team_id, raise_on_error=True)
+ except Exception:
+ # Don't leave a partial cohort behind.
+ cohort.delete()
+ raise
+ cohort.refresh_from_db()
+ # Person-less ids are dropped and merged persons dedupe during insert.
+ inserted = cohort.count or 0
+ if inserted == 0:
+ cohort.delete()
+ raise ValueError("None of the matched users have a person profile to add to a cohort.")
+ return cohort, inserted
diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.py
index 0f056bf09afd..8a4e2151bbd9 100644
--- a/products/replay_vision/backend/quota.py
+++ b/products/replay_vision/backend/quota.py
@@ -18,7 +18,6 @@ from products.replay_vision.backend.models.replay_observation import IN_FLIGHT_S
from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsage
from products.replay_vision.backend.models.replay_quota_grant import ReplayQuotaGrant
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
-from products.replay_vision.backend.prompt_evaluation import in_flight_evaluation_credits
logger = structlog.get_logger(__name__)
@@ -100,6 +99,10 @@ def _billing_synced_limit(organization: Organization | None) -> tuple[bool, int
def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:
+ # noqa comment below: prompt_evaluation pulls in the temporal package, whose activities import
+ # this module — deferring breaks the quota -> prompt_evaluation -> temporal -> quota cycle.
+ from products.replay_vision.backend.prompt_evaluation import in_flight_evaluation_credits # noqa: PLC0415
+
# Single `now` so the usage window, bonus expiry, and any caller comparisons are computed from one instant.
now = datetime.now(UTC)
organization = Organization.objects.filter(pk=organization_id).only("usage").first()
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 99096ae9fd6d..d5578dfc7b54 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -627,12 +627,15 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
resp = self.client.get(f"{self.scanners_url}?order_by=-enabled")
self.assertEqual([r["name"] for r in resp.json()["results"]], ["on", "off"])
- def _patch_deny_session_recording(self):
+ def _patch_deny_resource(self, denied: str):
return patch(
"posthog.rbac.user_access_control.UserAccessControl.check_access_level_for_resource",
- side_effect=lambda resource, **_: resource != "session_recording",
+ side_effect=lambda resource, **_: resource != denied,
)
+ def _patch_deny_session_recording(self):
+ return self._patch_deny_resource("session_recording")
+
def test_create_rejected_without_session_recording_read(self) -> None:
with self._patch_deny_session_recording():
resp = self.client.post(
@@ -654,6 +657,26 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
resp = self.client.patch(f"{self.scanners_url}{scanner.id}/", data={"name": "renamed"}, format="json")
self.assertEqual(resp.status_code, 403, resp.json())
+ @parameterized.expand(
+ [
+ ("impact", "get"),
+ ("affected_cohort", "post"),
+ ]
+ )
+ def test_recording_derived_action_rejected_without_session_recording_read(self, url_path: str, method: str) -> None:
+ scanner = self._create_scanner()
+ with self._patch_deny_session_recording():
+ resp = getattr(self.client, method)(f"{self.scanners_url}{scanner.id}/{url_path}/", format="json")
+ 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:
+ scanner = self._create_scanner()
+ with self._patch_deny_resource("cohort"):
+ resp = self.client.post(f"{self.scanners_url}{scanner.id}/affected_cohort/", format="json")
+ self.assertEqual(resp.status_code, 403, resp.json())
+ self.assertIn("cohort", resp.json()["detail"])
+
class TestScannerDigestProvisioning(_VisionAPITestCase):
_CREATE_BODY = {
diff --git a/products/replay_vision/backend/tests/test_impact.py b/products/replay_vision/backend/tests/test_impact.py
new file mode 100644
index 000000000000..9ccd830bfe8a
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_impact.py
@@ -0,0 +1,285 @@
+from datetime import datetime, timedelta
+from typing import Any
+
+import pytest
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from products.cohorts.backend.models.cohort import Cohort
+from products.replay_vision.backend.impact import compute_scanner_impact, create_affected_cohort
+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.tests.helpers import snapshot_for as _snapshot_for
+
+
+class _ImpactTestCase(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.flag_patcher = patch(
+ "products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled",
+ return_value=True,
+ )
+ self.flag_patcher.start()
+
+ def tearDown(self) -> None:
+ self.flag_patcher.stop()
+ super().tearDown()
+
+ def _make_scanner(self, scanner_type: ScannerType = ScannerType.MONITOR) -> ReplayScanner:
+ return ReplayScanner.objects.create(
+ team=self.team,
+ name=f"impact-{scanner_type}-{ReplayScanner.objects.count()}",
+ scanner_type=scanner_type,
+ scanner_config={"prompt": "p"},
+ model=ScannerModel.GEMINI_3_FLASH,
+ )
+
+ def _make_observation(
+ self,
+ scanner: ReplayScanner,
+ *,
+ session_id: str,
+ distinct_id: str | None,
+ verdict: str | None = "yes",
+ result: dict | None = None,
+ status: ObservationStatus = ObservationStatus.SUCCEEDED,
+ created_at: datetime | None = None,
+ session_started_at: datetime | None = None,
+ ) -> ReplayObservation:
+ if result is None:
+ result = {"model_output": {"verdict": verdict}} if verdict is not None else {}
+ observation = ReplayObservation.objects.create(
+ scanner=scanner,
+ team=self.team,
+ session_id=session_id,
+ distinct_id=distinct_id,
+ status=status,
+ scanner_snapshot=_snapshot_for(scanner),
+ scanner_result=result,
+ triggered_by=ObservationTrigger.SCHEDULE,
+ session_started_at=session_started_at,
+ # DB constraint: terminal statuses carry completed_at.
+ completed_at=timezone.now() if status != ObservationStatus.PENDING else None,
+ )
+ if created_at is not None:
+ ReplayObservation.objects.filter(pk=observation.pk).update(created_at=created_at)
+ return observation
+
+
+class TestComputeScannerImpact(_ImpactTestCase):
+ def test_monitor_counts_only_verdict_yes(self) -> None:
+ scanner = self._make_scanner(ScannerType.MONITOR)
+ self._make_observation(scanner, session_id="s-yes", distinct_id="u1", verdict="yes")
+ self._make_observation(scanner, session_id="s-no", distinct_id="u2", verdict="no")
+ self._make_observation(scanner, session_id="s-inc", distinct_id="u3", verdict="inconclusive")
+
+ impact = compute_scanner_impact(scanner)
+
+ assert impact.affected_sessions == 1
+ assert impact.affected_users == 1
+
+ def test_classifier_counts_only_sessions_with_the_tag(self) -> None:
+ scanner = self._make_scanner(ScannerType.CLASSIFIER)
+ self._make_observation(scanner, session_id="s1", distinct_id="u1", result={"model_output": {"tags": ["bug"]}})
+ self._make_observation(
+ scanner, session_id="s2", distinct_id="u2", result={"model_output": {"tags_freeform": ["bug"]}}
+ )
+ self._make_observation(scanner, session_id="s3", distinct_id="u3", result={"model_output": {"tags": ["ux"]}})
+
+ assert compute_scanner_impact(scanner, tag="bug").affected_sessions == 2
+
+ def test_scorer_counts_only_sessions_within_score_bounds(self) -> None:
+ scanner = self._make_scanner(ScannerType.SCORER)
+ self._make_observation(scanner, session_id="s1", distinct_id="u1", result={"model_output": {"score": 8}})
+ self._make_observation(scanner, session_id="s2", distinct_id="u2", result={"model_output": {"score": 3}})
+ self._make_observation(
+ scanner, session_id="s3", distinct_id="u3", result={"model_output": {"score": "corrupt"}}
+ )
+
+ assert compute_scanner_impact(scanner, min_score=7).affected_sessions == 1
+ assert compute_scanner_impact(scanner, max_score=5).affected_sessions == 1
+
+ @parameterized.expand(
+ [
+ ("monitor_rejects_tag", ScannerType.MONITOR, {"tag": "bug"}),
+ ("classifier_requires_tag", ScannerType.CLASSIFIER, {}),
+ ("scorer_requires_bound", ScannerType.SCORER, {}),
+ ("summarizer_unsupported", ScannerType.SUMMARIZER, {}),
+ ]
+ )
+ def test_rejects_invalid_qualifiers_per_type(self, _name: str, scanner_type: ScannerType, kwargs: dict) -> None:
+ scanner = self._make_scanner(scanner_type)
+ with pytest.raises(ValueError):
+ compute_scanner_impact(scanner, **kwargs)
+
+ def test_deduplicates_users_across_sessions(self) -> None:
+ scanner = self._make_scanner(ScannerType.MONITOR)
+ self._make_observation(scanner, session_id="s1", distinct_id="u1")
+ self._make_observation(scanner, session_id="s2", distinct_id="u1")
+
+ impact = compute_scanner_impact(scanner)
+
+ assert impact.affected_sessions == 2
+ assert impact.affected_users == 1
+
+ @parameterized.expand([("null", None), ("empty", "")])
+ def test_splits_sessions_without_user(self, _name: str, anonymous_value: str | None) -> None:
+ scanner = self._make_scanner(ScannerType.MONITOR)
+ self._make_observation(scanner, session_id="s-anon", distinct_id=anonymous_value)
+ self._make_observation(scanner, session_id="s-known", distinct_id="u1")
+
+ impact = compute_scanner_impact(scanner)
+
+ assert impact.affected_sessions == 2
+ assert impact.affected_users == 1
+ assert impact.sessions_without_user == 1
+
+ def test_excludes_out_of_window_backfills_and_non_succeeded(self) -> None:
+ scanner = self._make_scanner(ScannerType.MONITOR)
+ self._make_observation(
+ scanner, session_id="s-old", distinct_id="u1", created_at=timezone.now() - timedelta(days=31)
+ )
+ # Backfill: old session scanned today must not count as current impact.
+ self._make_observation(
+ scanner, session_id="s-backfill", distinct_id="u2", session_started_at=timezone.now() - timedelta(days=45)
+ )
+ self._make_observation(scanner, session_id="s-failed", distinct_id="u3", status=ObservationStatus.FAILED)
+ self._make_observation(scanner, session_id="s-inel", distinct_id="u4", status=ObservationStatus.INELIGIBLE)
+
+ assert compute_scanner_impact(scanner, window_days=30).affected_sessions == 0
+
+
+def _fake_insert(members: int):
+ def insert(self: Cohort, items: list[str], **kwargs: Any) -> int:
+ Cohort.objects.filter(pk=self.pk).update(count=members)
+ return 1
+
+ return insert
+
+
+class TestCreateAffectedCohort(_ImpactTestCase):
+ def test_creates_static_cohort_and_reports_real_member_count(self) -> None:
+ scanner = self._make_scanner(ScannerType.MONITOR)
+ self._make_observation(scanner, session_id="s1", distinct_id="u1")
+ self._make_observation(scanner, session_id="s2", distinct_id="u1")
+ self._make_observation(scanner, session_id="s3", distinct_id="u2")
+ self._make_observation(scanner, session_id="s4", distinct_id=None)
+
+ # One of the two distinct ids resolves to no person; the reported count must be the cohort's, not the input's.
+ with patch.object(Cohort, "insert_users_by_list", autospec=True, side_effect=_fake_insert(1)) as mock_insert:
+ cohort, inserted = create_affected_cohort(scanner, self.user)
+
+ assert inserted == 1
+ assert sorted(mock_insert.call_args.args[1]) == ["u1", "u2"]
+ assert mock_insert.call_args.kwargs["raise_on_error"] is True
+ cohort.refresh_from_db()
+ assert cohort.is_static is True
+ assert cohort.created_by == self.user
+ assert scanner.name in (cohort.name or "")
+
+ def test_raises_when_no_users_in_window(self) -> None:
+ scanner = self._make_scanner(ScannerType.MONITOR)
+ self._make_observation(scanner, session_id="s1", distinct_id=None)
+
+ with pytest.raises(ValueError):
+ create_affected_cohort(scanner, self.user)
+ assert Cohort.objects.filter(team=self.team).count() == 0
+
+ def test_raises_when_over_size_cap(self) -> None:
+ scanner = self._make_scanner(ScannerType.MONITOR)
+ self._make_observation(scanner, session_id="s1", distinct_id="u1")
+ self._make_observation(scanner, session_id="s2", distinct_id="u2")
+
+ with patch("products.replay_vision.backend.impact.MAX_COHORT_DISTINCT_IDS", 1):
+ with pytest.raises(ValueError):
+ create_affected_cohort(scanner, self.user)
+ assert Cohort.objects.filter(team=self.team).count() == 0
+
+ @parameterized.expand(
+ [
+ ("insert_raises", "raise", RuntimeError),
+ ("no_persons_resolved", "empty", ValueError),
+ ]
+ )
+ def test_failed_or_empty_population_leaves_no_cohort(
+ self, _name: str, mode: str, expected: type[Exception]
+ ) -> None:
+ scanner = self._make_scanner(ScannerType.MONITOR)
+ self._make_observation(scanner, session_id="s1", distinct_id="u1")
+
+ side_effect = RuntimeError("boom") if mode == "raise" else _fake_insert(0)
+ with patch.object(Cohort, "insert_users_by_list", autospec=True, side_effect=side_effect):
+ with pytest.raises(expected):
+ create_affected_cohort(scanner, self.user)
+ assert Cohort.objects.filter(team=self.team).count() == 0
+
+
+class TestImpactEndpoints(_ImpactTestCase):
+ def test_impact_returns_counts(self) -> None:
+ scanner = self._make_scanner(ScannerType.MONITOR)
+ self._make_observation(scanner, session_id="s1", distinct_id="u1")
+
+ resp = self.client.get(f"/api/environments/{self.team.id}/vision/scanners/{scanner.id}/impact/")
+
+ assert resp.status_code == 200, resp.json()
+ assert resp.json() == {
+ "affected_sessions": 1,
+ "affected_users": 1,
+ "sessions_without_user": 0,
+ "window_days": 30,
+ }
+
+ def test_affected_cohort_creates_and_returns_cohort(self) -> None:
+ scanner = self._make_scanner(ScannerType.MONITOR)
+ self._make_observation(scanner, session_id="s1", distinct_id="u1")
+
+ with patch.object(Cohort, "insert_users_by_list", autospec=True, side_effect=_fake_insert(1)):
+ resp = self.client.post(
+ f"/api/environments/{self.team.id}/vision/scanners/{scanner.id}/affected_cohort/",
+ {"window_days": 7},
+ )
+
+ assert resp.status_code == 201, resp.json()
+ body = resp.json()
+ assert body["users_in_cohort"] == 1
+ assert body["window_days"] == 7
+ assert Cohort.objects.filter(pk=body["cohort_id"], is_static=True).exists()
+
+ def test_affected_cohort_400_when_no_users(self) -> None:
+ scanner = self._make_scanner(ScannerType.MONITOR)
+
+ resp = self.client.post(
+ f"/api/environments/{self.team.id}/vision/scanners/{scanner.id}/affected_cohort/",
+ {},
+ )
+
+ assert resp.status_code == 400
+
+ def test_impact_400_when_qualifier_invalid_for_type(self) -> None:
+ scanner = self._make_scanner(ScannerType.SUMMARIZER)
+
+ resp = self.client.get(f"/api/environments/{self.team.id}/vision/scanners/{scanner.id}/impact/")
+
+ assert resp.status_code == 400
+
+ def test_impact_passes_qualifiers_through(self) -> None:
+ scanner = self._make_scanner(ScannerType.CLASSIFIER)
+ self._make_observation(scanner, session_id="s1", distinct_id="u1", result={"model_output": {"tags": ["bug"]}})
+ self._make_observation(scanner, session_id="s2", distinct_id="u2", result={"model_output": {"tags": ["ux"]}})
+
+ resp = self.client.get(
+ f"/api/environments/{self.team.id}/vision/scanners/{scanner.id}/impact/",
+ {"tag": "bug", "window_days": "7"},
+ )
+
+ assert resp.status_code == 200, resp.json()
+ assert resp.json()["affected_sessions"] == 1
+ assert resp.json()["window_days"] == 7
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index e38bfcaaa022..1f85048f8bac 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -887,6 +887,62 @@ export interface PatchedReplayScannerApi {
readonly feedback_themes?: FeedbackThemesApi | null
}
+/**
+ * Body of POST /vision/scanners/:id/affected_cohort/. Same qualifiers as the impact GET.
+ */
+export interface AffectedCohortRequestApi {
+ /**
+ * Trailing window of observations to count. Defaults to 30 days.
+ * @minimum 1
+ * @maximum 90
+ */
+ window_days?: number
+ /**
+ * Classifier scanners only, required for them: count sessions carrying this tag (fixed or freeform). Not applicable to other scanner types.
+ * @maxLength 100
+ * @nullable
+ */
+ tag?: string | null
+ /**
+ * Scorer scanners only: count sessions scoring at or above this value. Scorers require `min_score` and/or `max_score`. Not applicable to other scanner types.
+ * @nullable
+ */
+ min_score?: number | null
+ /**
+ * Scorer scanners only: count sessions scoring at or below this value.
+ * @nullable
+ */
+ max_score?: number | null
+}
+
+/**
+ * The static cohort created from the scanner's affected users.
+ */
+export interface AffectedCohortResponseApi {
+ /** ID of the created static cohort; usable anywhere cohorts are (funnels, surveys, experiments). */
+ readonly cohort_id: number
+ /** Generated cohort name, stamped with the creation date since the snapshot doesn't live-update. */
+ readonly name: string
+ /** Persons actually in the created cohort. Can be lower than `affected_users`: matched distinct IDs without a person profile are dropped, and merged persons deduplicate. */
+ readonly users_in_cohort: number
+ /** Trailing window the cohort was drawn from, in days. */
+ readonly window_days: number
+}
+
+/**
+ * Who this scanner's findings affected in the window; counted from observations, not estimated.
+ */
+export interface ScannerImpactApi {
+ /** Distinct sessions with an affected observation in the window. For monitors only verdict-yes observations count; for other scanner types every succeeded observation counts. */
+ readonly affected_sessions: number
+ /** Distinct users behind the affected sessions, by distinct ID. May include anonymous device IDs when the recorded sessions were not identified. */
+ readonly affected_users: number
+ /** Affected sessions whose recording carried no distinct ID at all. */
+ readonly sessions_without_user: number
+ /** Trailing window the counts cover, in days. */
+ readonly window_days: number
+}
+
/**
* Body of POST /vision/scanners/{id}/observe/.
*/
@@ -1451,6 +1507,31 @@ export type VisionScannersListParams = {
search?: string
}
+export type VisionScannersImpactRetrieveParams = {
+ /**
+ * Scorer scanners only: count sessions scoring at or below this value.
+ * @nullable
+ */
+ max_score?: number | null
+ /**
+ * Scorer scanners only: count sessions scoring at or above this value. Scorers require `min_score` and/or `max_score`. Not applicable to other scanner types.
+ * @nullable
+ */
+ min_score?: number | null
+ /**
+ * Classifier scanners only, required for them: count sessions carrying this tag (fixed or freeform). Not applicable to other scanner types.
+ * @maxLength 100
+ * @nullable
+ */
+ tag?: string | null
+ /**
+ * Trailing window of observations to count. Defaults to 30 days.
+ * @minimum 1
+ * @maximum 90
+ */
+ window_days?: number
+}
+
export type VisionScannersObservationsListParams = {
/**
* When true, return only observations that have a shared label (thumbs up or down); when false, only unlabeled observations.
diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.ts
index 03601f2464a8..44e826fa99f3 100644
--- a/products/replay_vision/frontend/generated/api.ts
+++ b/products/replay_vision/frontend/generated/api.ts
@@ -9,6 +9,8 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ AffectedCohortRequestApi,
+ AffectedCohortResponseApi,
CurrentPromptSuggestionApi,
EstimateRequestApi,
EstimateResponseApi,
@@ -29,6 +31,7 @@ import type {
ReplayScannerPromptSuggestionApi,
RetryResponseApi,
ScannerCreatorsResponseApi,
+ ScannerImpactApi,
ScannerStatsResponseApi,
SuggestTagsRequestApi,
SuggestTagsResponseApi,
@@ -39,6 +42,7 @@ import type {
VisionObservationsListParams,
VisionObservationsRetrieveParams,
VisionQuotaApi,
+ VisionScannersImpactRetrieveParams,
VisionScannersListParams,
VisionScannersObservationsListParams,
VisionScannersObservationsRetrieveParams,
@@ -462,6 +466,62 @@ export const visionScannersDestroy = async (projectId: string, id: string, optio
})
}
+export const getVisionScannersAffectedCohortCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/vision/scanners/${id}/affected_cohort/`
+}
+
+/**
+ * Save the users this scanner matched as a static cohort, for surveys, funnels, and retention analysis.
+ */
+export const visionScannersAffectedCohortCreate = async (
+ projectId: string,
+ id: string,
+ affectedCohortRequestApi?: AffectedCohortRequestApi,
+ options?: RequestInit
+): Promise<AffectedCohortResponseApi> => {
+ return apiMutator<AffectedCohortResponseApi>(getVisionScannersAffectedCohortCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(affectedCohortRequestApi),
+ })
+}
+
+export const getVisionScannersImpactRetrieveUrl = (
+ projectId: string,
+ id: string,
+ params?: VisionScannersImpactRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/vision/scanners/${id}/impact/?${stringifiedParams}`
+ : `/api/projects/${projectId}/vision/scanners/${id}/impact/`
+}
+
+/**
+ * Affected sessions and users for this scanner over the trailing window.
+ */
+export const visionScannersImpactRetrieve = async (
+ projectId: string,
+ id: string,
+ params?: VisionScannersImpactRetrieveParams,
+ options?: RequestInit
+): Promise<ScannerImpactApi> => {
+ return apiMutator<ScannerImpactApi>(getVisionScannersImpactRetrieveUrl(projectId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getVisionScannersObserveCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/vision/scanners/${id}/observe/`
}
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index 710beb0b48b6..3b2482d4906b 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -512,6 +512,42 @@ export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Save the users this scanner matched as a static cohort, for surveys, funnels, and retention analysis.
+ */
+export const visionScannersAffectedCohortCreateBodyWindowDaysDefault = 30
+export const visionScannersAffectedCohortCreateBodyWindowDaysMax = 90
+
+export const visionScannersAffectedCohortCreateBodyTagMax = 100
+
+export const VisionScannersAffectedCohortCreateBody = /* @__PURE__ */ zod
+ .object({
+ window_days: zod
+ .number()
+ .min(1)
+ .max(visionScannersAffectedCohortCreateBodyWindowDaysMax)
+ .default(visionScannersAffectedCohortCreateBodyWindowDaysDefault)
+ .describe('Trailing window of observations to count. Defaults to 30 days.'),
+ tag: zod
+ .string()
+ .max(visionScannersAffectedCohortCreateBodyTagMax)
+ .nullish()
+ .describe(
+ 'Classifier scanners only, required for them: count sessions carrying this tag (fixed or freeform). Not applicable to other scanner types.'
+ ),
+ min_score: zod
+ .number()
+ .nullish()
+ .describe(
+ 'Scorer scanners only: count sessions scoring at or above this value. Scorers require `min_score` and\/or `max_score`. Not applicable to other scanner types.'
+ ),
+ max_score: zod
+ .number()
+ .nullish()
+ .describe('Scorer scanners only: count sessions scoring at or below this value.'),
+ })
+ .describe('Body of POST \/vision\/scanners\/:id\/affected_cohort\/. Same qualifiers as the impact GET.')
+
/**
* Apply this scanner to one specific session, on demand. Returns 202 with the workflow handle.
*/
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx
index 021757c7b6c0..5ee96a45eb81 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx
@@ -1,6 +1,7 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
-import { LemonTag, Spinner } from '@posthog/lemon-ui'
+import { IconPeople } from '@posthog/icons'
+import { LemonButton, LemonTag, Spinner } from '@posthog/lemon-ui'
import { BarChart } from '@posthog/quill-charts'
import { useChartConfig, useChartTheme } from 'lib/charts/hooks'
@@ -50,6 +51,57 @@ function PanelEmpty({ loading, message }: { loading: boolean; message: string })
return <div className="text-muted text-sm">{message}</div>
}
+function ImpactOverview({ scannerId }: { scannerId: string }): JSX.Element | null {
+ const { scanner, scannerImpact, scannerImpactLoading, affectedCohortLoading } = useValues(
+ replayScannerLogic({ id: scannerId })
+ )
+ const { saveAffectedCohort } = useActions(replayScannerLogic({ id: scannerId }))
+
+ // Impact needs a per-type predicate; only the monitor one (verdict-yes) exists without a qualifier.
+ if (scanner?.scanner_type !== 'monitor') {
+ return null
+ }
+ if (!scannerImpact || scannerImpact.affected_sessions === 0) {
+ return (
+ <OverviewPanel title="Impact" fill>
+ <PanelEmpty
+ loading={scannerImpactLoading}
+ message={
+ scannerImpact
+ ? `No affected sessions in the last ${scannerImpact.window_days} days.`
+ : "Couldn't load impact counts."
+ }
+ />
+ </OverviewPanel>
+ )
+ }
+ return (
+ <OverviewPanel title="Impact" subtitle={`last ${scannerImpact.window_days} days`} fill>
+ <div className="text-sm">
+ Matched <strong className="tabular-nums">{scannerImpact.affected_sessions.toLocaleString()}</strong>{' '}
+ session{scannerImpact.affected_sessions === 1 ? '' : 's'} from{' '}
+ <strong className="tabular-nums">{scannerImpact.affected_users.toLocaleString()}</strong> user
+ {scannerImpact.affected_users === 1 ? '' : 's'}
+ {scannerImpact.sessions_without_user > 0 && (
+ <span className="text-muted"> ({scannerImpact.sessions_without_user} without a user)</span>
+ )}
+ </div>
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconPeople />}
+ onClick={() => saveAffectedCohort()}
+ loading={affectedCohortLoading}
+ disabledReason={scannerImpact.affected_users === 0 ? 'No users to save' : undefined}
+ data-attr="vision-save-affected-cohort"
+ className="self-start"
+ >
+ Save as cohort
+ </LemonButton>
+ </OverviewPanel>
+ )
+}
+
function MonitorOverview({ scannerId }: { scannerId: string }): JSX.Element {
const { monitorStats, hasActiveObservationFilters, observationStatsApiLoading } = useValues(
replayScannerLogic({ id: scannerId })
@@ -58,7 +110,7 @@ function MonitorOverview({ scannerId }: { scannerId: string }): JSX.Element {
const total = yesTotal + noTotal + inconclusiveTotal
if (total === 0) {
return (
- <OverviewPanel title="Verdict mix">
+ <OverviewPanel title="Verdict mix" fill>
<PanelEmpty
loading={observationStatsApiLoading}
message={hasActiveObservationFilters ? 'No verdicts match the current filter.' : 'No verdicts yet.'}
@@ -71,7 +123,7 @@ function MonitorOverview({ scannerId }: { scannerId: string }): JSX.Element {
const inconclusivePct = Math.max(0, 100 - yesPct - noPct)
return (
- <OverviewPanel title="Verdict mix" subtitle={`${total} verdict${total === 1 ? '' : 's'}`}>
+ <OverviewPanel title="Verdict mix" subtitle={`${total} verdict${total === 1 ? '' : 's'}`} fill>
<LemonProgress percent={yesPct} />
<div className="flex flex-wrap items-center gap-4 text-sm">
<span className="flex items-center gap-2">
@@ -100,9 +152,15 @@ function MonitorOverview({ scannerId }: { scannerId: string }): JSX.Element {
}
function ClassifierOverview({ scannerId }: { scannerId: string }): JSX.Element | null {
- const { scanner, classifierTagStats, hasActiveObservationFilters, observationStatsApiLoading } = useValues(
- replayScannerLogic({ id: scannerId })
- )
+ const {
+ scanner,
+ classifierTagStats,
+ hasActiveObservationFilters,
+ observationStatsApiLoading,
+ affectedCohortLoading,
+ savingCohortTag,
+ } = useValues(replayScannerLogic({ id: scannerId }))
+ const { saveAffectedCohort } = useActions(replayScannerLogic({ id: scannerId }))
const { fixedRanked, freeformRanked } = classifierTagStats
// Wait for the scanner config — without it `freeformAllowed` defaults to `false` and the panel flashes the
// "disabled" copy while the config is still loading.
@@ -135,6 +193,19 @@ function ClassifierOverview({ scannerId }: { scannerId: string }): JSX.Element |
<span className="text-xs text-muted tabular-nums text-right whitespace-nowrap shrink-0 w-12">
{count.toLocaleString()}
</span>
+ <LemonButton
+ size="xsmall"
+ icon={<IconPeople />}
+ tooltip={`Save users tagged "${tag}" in the last 30 days as a cohort`}
+ onClick={() => saveAffectedCohort(tag)}
+ loading={affectedCohortLoading && savingCohortTag === tag}
+ disabledReason={
+ affectedCohortLoading && savingCohortTag !== tag
+ ? 'Another cohort is being created'
+ : undefined
+ }
+ data-attr="vision-save-tag-cohort"
+ />
</div>
))}
</div>
@@ -143,7 +214,7 @@ function ClassifierOverview({ scannerId }: { scannerId: string }): JSX.Element |
return (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
- <OverviewPanel title="Top fixed tags" subtitle="from configured vocabulary">
+ <OverviewPanel title="Top fixed tags" subtitle="from configured vocabulary" fill>
{renderRanked(fixedRanked, fixedEmpty)}
</OverviewPanel>
@@ -151,6 +222,7 @@ function ClassifierOverview({ scannerId }: { scannerId: string }): JSX.Element |
title="Top freeform tags"
subtitle={freeformAllowed ? 'outside configured vocabulary' : 'disabled'}
disabled={!freeformAllowed}
+ fill
>
{freeformAllowed ? (
renderRanked(freeformRanked, freeformEmpty)
@@ -237,10 +309,24 @@ export function ScannerOverview({ scannerId }: { scannerId: string }): JSX.Eleme
</div>
)
}
+ // Impact only exists for monitors; other types keep their overview at full width.
+ if (scannerType !== 'monitor') {
+ return (
+ <div className="space-y-4">
+ {showChart && <ScannerInsightsChart scannerId={scannerId} scannerType={scannerType} />}
+ {typeOverview}
+ </div>
+ )
+ }
return (
<div className="space-y-4">
{showChart && <ScannerInsightsChart scannerId={scannerId} scannerType={scannerType} />}
- {typeOverview}
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
+ {typeOverview && <div className="min-w-0">{typeOverview}</div>}
+ <div className="min-w-0">
+ <ImpactOverview scannerId={scannerId} />
+ </div>
+ </div>
</div>
)
}
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index 23f19906331b..bb0a0afa678d 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -26,8 +26,10 @@ import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import {
+ visionScannersAffectedCohortCreate,
visionScannersCreate,
visionScannersEstimateCreate,
+ visionScannersImpactRetrieve,
visionScannersObservationsList,
visionScannersObservationsStatsRetrieve,
visionScannersObserveCreate,
@@ -40,6 +42,7 @@ import type {
EstimateResponseApi,
ObservationStatsApi,
ReplayObservationApi,
+ ScannerImpactApi,
TagSuggestionApi,
} from '../generated/api.schemas'
import type { ScannerTypeEnumApi } from '../generated/api.schemas'
@@ -565,6 +568,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
loadScanner: true,
loadScannerSuccess: (scanner: ReplayScanner) => ({ scanner }),
loadScannerFailure: true,
+ saveAffectedCohort: (tag?: string) => ({ tag }),
setScannerType: (scannerType: ScannerType) => ({ scannerType }),
setSubmitIntent: (intent: 'save' | 'advance') => ({ intent }),
// Fired only after an actual API write, unlike submitScannerSuccess (which the advance path emits too).
@@ -702,6 +706,51 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
})),
loaders(({ props, values }) => ({
+ scannerImpact: [
+ null as ScannerImpactApi | null,
+ {
+ loadScannerImpact: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId || props.id === 'new') {
+ return null
+ }
+ return await visionScannersImpactRetrieve(String(teamId), props.id)
+ },
+ },
+ ],
+ affectedCohort: [
+ null as { cohort_id: number } | null,
+ {
+ saveAffectedCohort: async ({ tag }) => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId || props.id === 'new') {
+ return values.affectedCohort
+ }
+ try {
+ const response = await visionScannersAffectedCohortCreate(
+ String(teamId),
+ props.id,
+ tag ? { tag } : {}
+ )
+ lemonToast.success(
+ `Cohort "${response.name}" created with ${response.users_in_cohort.toLocaleString()} ${
+ response.users_in_cohort === 1 ? 'person' : 'people'
+ }`,
+ {
+ button: {
+ label: 'View cohort',
+ action: () => router.actions.push(urls.cohort(response.cohort_id)),
+ },
+ }
+ )
+ return { cohort_id: response.cohort_id }
+ } catch (error: any) {
+ lemonToast.error(`Failed to create cohort${error?.detail ? `: ${error.detail}` : ''}`)
+ return values.affectedCohort
+ }
+ },
+ },
+ ],
tagSuggestions: [
[] as TagSuggestionApi[],
{
@@ -731,6 +780,15 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
})),
reducers({
+ // Which tag's cohort is being created, so tag rows can show a per-row spinner.
+ savingCohortTag: [
+ null as string | null,
+ {
+ saveAffectedCohort: (_, { tag }) => tag ?? null,
+ saveAffectedCohortSuccess: () => null,
+ saveAffectedCohortFailure: () => null,
+ },
+ ],
originalScanner: [
null as ReplayScanner | null,
{
@@ -1146,6 +1204,10 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
actions.loadObservations()
actions.loadObservationStats()
}
+ // Impact needs the scanner type known; only monitors have a qualifier-free predicate.
+ if (props.id !== 'new' && scanner.scanner_type === 'monitor') {
+ actions.loadScannerImpact()
+ }
},
setScannerType: ({ scannerType }) => {
diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yaml
index 9a3404ce89a8..9a841ccc5092 100644
--- a/products/replay_vision/mcp/tools.yaml
+++ b/products/replay_vision/mcp/tools.yaml
@@ -124,6 +124,24 @@ tools:
silently skipped until the next period. Pair with `vision-scanners-estimate-create` to size a new scanner
against the remaining budget.
feature_flag: replay-vision
+ vision-scanners-affected-cohort-create:
+ operation: vision_scanners_affected_cohort_create
+ enabled: true
+ scopes:
+ - replay_scanner:read
+ - cohort:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Save a scanner's affected users as a cohort
+ description: >
+ Create a static cohort of the users a scanner matched within the trailing window (default 30 days). Monitors
+ count verdict-yes observations and take no qualifiers; classifiers require `tag`; scorers require
+ `min_score` and/or `max_score`. The cohort is a dated snapshot and does not live-update; calling again
+ creates a new cohort. Use it anywhere cohorts work: funnel breakdowns, retention, survey targeting,
+ experiment exclusion. Fails when the window has no users or none resolve to a person profile.
+ feature_flag: replay-vision
vision-scanners-create:
operation: vision_scanners_create
enabled: true
@@ -211,6 +229,22 @@ tools:
operational fields like `enabled`, `sampling_rate`, `provider`, `model`, `emits_signals`, `scanner_version`,
and `last_swept_at`.
feature_flag: replay-vision
+ vision-scanners-impact-retrieve:
+ operation: vision_scanners_impact_retrieve
+ enabled: true
+ scopes:
+ - replay_scanner:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get a scanner's impact counts
+ description: >
+ Affected sessions and users for a scanner over a trailing window, counted from its observations. Monitors
+ count verdict-yes observations and take no qualifiers; classifiers require `tag`; scorers require
+ `min_score` and/or `max_score`. `sessions_without_user` reports affected sessions that carried no distinct
+ ID, so the user count reads honestly against the session count.
+ feature_flag: replay-vision
vision-scanners-list:
operation: vision_scanners_list
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index e11329388e60..e28104dcdf42 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -9072,6 +9072,21 @@
},
"feature_flag": "replay-vision"
},
+ "vision-scanners-affected-cohort-create": {
+ "description": "Create a static cohort of the users a scanner matched within the trailing window (default 30 days). Monitors count verdict-yes observations and take no qualifiers; classifiers require `tag`; scorers require `min_score` and/or `max_score`. The cohort is a dated snapshot and does not live-update; calling again creates a new cohort. Use it anywhere cohorts work: funnel breakdowns, retention, survey targeting, experiment exclusion. Fails when the window has no users or none resolve to a person profile.",
+ "category": "Replay vision",
+ "feature": "replay_vision",
+ "summary": "Save a scanner's affected users as a cohort",
+ "title": "Save a scanner's affected users as a cohort",
+ "required_scopes": ["replay_scanner:read", "cohort:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "replay-vision"
+ },
"vision-scanners-create": {
"description": "Create a replay vision scanner. Pick a `scanner_type` — `monitor` (open-ended observations), `classifier` (assign a tag from a fixed label set), `scorer` (numeric rubric), or `summarizer` (free-text summary with optional facet embeddings via `emits_embeddings`) — and fill `scanner_config` to match: all types need a `prompt`; classifiers also need `tags`; scorers also need `scale`; summarizers optionally set `length` and `emits_embeddings`. `query` is a `RecordingsQuery` shape that defines which sessions the scanner watches — `date_from` and `date_to` are ignored (the schedule controls time). `sampling_rate` is a 0..1 random downsample applied after the query matches (default 1.0). `model` chooses the LLM. Names must be unique within the team. Before creating a broad scanner (a permissive `query` and/or high `sampling_rate`), first call `vision-scanners-estimate-create` to project its monthly observation volume and `vision-quota-retrieve` to check the org's remaining budget — an enabled scanner sweeps matching recordings every 5 minutes, and creation itself does not check quota, so a too-broad scanner can exhaust the monthly budget on its first sweeps.",
"category": "Replay vision",
@@ -9133,6 +9148,21 @@
},
"feature_flag": "replay-vision"
},
+ "vision-scanners-impact-retrieve": {
+ "description": "Affected sessions and users for a scanner over a trailing window, counted from its observations. Monitors count verdict-yes observations and take no qualifiers; classifiers require `tag`; scorers require `min_score` and/or `max_score`. `sessions_without_user` reports affected sessions that carried no distinct ID, so the user count reads honestly against the session count.",
+ "category": "Replay vision",
+ "feature": "replay_vision",
+ "summary": "Get a scanner's impact counts",
+ "title": "Get a scanner's impact counts",
+ "required_scopes": ["replay_scanner:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "replay-vision"
+ },
"vision-scanners-list": {
"description": "List all replay vision scanners in the current project. A scanner watches a slice of session recordings (defined by its `query` and `sampling_rate`) and runs one of four LLM analyses against each matching session: `monitor` (open-ended observations), `classifier` (tag from a fixed label set), `scorer` (numeric rubric), or `summarizer` (free-text summary, optionally with facet embeddings for downstream search). Each scanner returns its current configuration, enabled state, sampling rate, and `last_swept_at` timestamp.",
"category": "Replay vision",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index c77cc4c1e878..0e8def454110 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -9608,6 +9608,21 @@
},
"feature_flag": "replay-vision"
},
+ "vision-scanners-affected-cohort-create": {
+ "description": "Create a static cohort of the users a scanner matched within the trailing window (default 30 days). Monitors count verdict-yes observations and take no qualifiers; classifiers require `tag`; scorers require `min_score` and/or `max_score`. The cohort is a dated snapshot and does not live-update; calling again creates a new cohort. Use it anywhere cohorts work: funnel breakdowns, retention, survey targeting, experiment exclusion. Fails when the window has no users or none resolve to a person profile.",
+ "category": "Replay vision",
+ "feature": "replay_vision",
+ "summary": "Save a scanner's affected users as a cohort",
+ "title": "Save a scanner's affected users as a cohort",
+ "required_scopes": ["replay_scanner:read", "cohort:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "replay-vision"
+ },
"vision-scanners-create": {
"description": "Create a replay vision scanner. Pick a `scanner_type` — `monitor` (open-ended observations), `classifier` (assign a tag from a fixed label set), `scorer` (numeric rubric), or `summarizer` (free-text summary with optional facet embeddings via `emits_embeddings`) — and fill `scanner_config` to match: all types need a `prompt`; classifiers also need `tags`; scorers also need `scale`; summarizers optionally set `length` and `emits_embeddings`. `query` is a `RecordingsQuery` shape that defines which sessions the scanner watches — `date_from` and `date_to` are ignored (the schedule controls time). `sampling_rate` is a 0..1 random downsample applied after the query matches (default 1.0). `model` chooses the LLM. Names must be unique within the team. Before creating a broad scanner (a permissive `query` and/or high `sampling_rate`), first call `vision-scanners-estimate-create` to project its monthly observation volume and `vision-quota-retrieve` to check the org's remaining budget — an enabled scanner sweeps matching recordings every 5 minutes, and creation itself does not check quota, so a too-broad scanner can exhaust the monthly budget on its first sweeps.",
"category": "Replay vision",
@@ -9669,6 +9684,21 @@
},
"feature_flag": "replay-vision"
},
+ "vision-scanners-impact-retrieve": {
+ "description": "Affected sessions and users for a scanner over a trailing window, counted from its observations. Monitors count verdict-yes observations and take no qualifiers; classifiers require `tag`; scorers require `min_score` and/or `max_score`. `sessions_without_user` reports affected sessions that carried no distinct ID, so the user count reads honestly against the session count.",
+ "category": "Replay vision",
+ "feature": "replay_vision",
+ "summary": "Get a scanner's impact counts",
+ "title": "Get a scanner's impact counts",
+ "required_scopes": ["replay_scanner:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "replay-vision"
+ },
"vision-scanners-list": {
"description": "List all replay vision scanners in the current project. A scanner watches a slice of session recordings (defined by its `query` and `sampling_rate`) and runs one of four LLM analyses against each matching session: `monitor` (open-ended observations), `classifier` (tag from a fixed label set), `scorer` (numeric rubric), or `summarizer` (free-text summary, optionally with facet embeddings for downstream search). Each scanner returns its current configuration, enabled state, sampling rate, and `last_swept_at` timestamp.",
"category": "Replay vision",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bdab5d8b4577..c640d437fbbb 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -8036,6 +8036,48 @@ export namespace Schemas {
uploads: UploadTarget[];
}
+ /**
+ * Body of POST /vision/scanners/:id/affected_cohort/. Same qualifiers as the impact GET.
+ */
+ export interface AffectedCohortRequest {
+ /**
+ * Trailing window of observations to count. Defaults to 30 days.
+ * @minimum 1
+ * @maximum 90
+ */
+ window_days?: number;
+ /**
+ * Classifier scanners only, required for them: count sessions carrying this tag (fixed or freeform). Not applicable to other scanner types.
+ * @maxLength 100
+ * @nullable
+ */
+ tag?: string | null;
+ /**
+ * Scorer scanners only: count sessions scoring at or above this value. Scorers require `min_score` and/or `max_score`. Not applicable to other scanner types.
+ * @nullable
+ */
+ min_score?: number | null;
+ /**
+ * Scorer scanners only: count sessions scoring at or below this value.
+ * @nullable
+ */
+ max_score?: number | null;
+ }
+
+ /**
+ * The static cohort created from the scanner's affected users.
+ */
+ export interface AffectedCohortResponse {
+ /** ID of the created static cohort; usable anywhere cohorts are (funnels, surveys, experiments). */
+ readonly cohort_id: number;
+ /** Generated cohort name, stamped with the creation date since the snapshot doesn't live-update. */
+ readonly name: string;
+ /** Persons actually in the created cohort. Can be lower than `affected_users`: matched distinct IDs without a person profile are dropped, and merged persons deduplicate. */
+ readonly users_in_cohort: number;
+ /** Trailing window the cohort was drawn from, in days. */
+ readonly window_days: number;
+ }
+
export interface AgentAggregateStats {
/** Sessions currently in a live state (queued / running). */
liveCount: number;
@@ -55576,6 +55618,20 @@ export namespace Schemas {
creators: UserBasic[];
}
+ /**
+ * Who this scanner's findings affected in the window; counted from observations, not estimated.
+ */
+ export interface ScannerImpact {
+ /** Distinct sessions with an affected observation in the window. For monitors only verdict-yes observations count; for other scanner types every succeeded observation counts. */
+ readonly affected_sessions: number;
+ /** Distinct users behind the affected sessions, by distinct ID. May include anonymous device IDs when the recorded sessions were not identified. */
+ readonly affected_users: number;
+ /** Affected sessions whose recording carried no distinct ID at all. */
+ readonly sessions_without_user: number;
+ /** Trailing window the counts cover, in days. */
+ readonly window_days: number;
+ }
+
/**
* Per-scanner-type count of enabled vs total scanners.
*/
@@ -69610,6 +69666,31 @@ export namespace Schemas {
search?: string;
};
+ export type EnvironmentsVisionScannersImpactRetrieveParams = {
+ /**
+ * Scorer scanners only: count sessions scoring at or below this value.
+ * @nullable
+ */
+ max_score?: number | null;
+ /**
+ * Scorer scanners only: count sessions scoring at or above this value. Scorers require `min_score` and/or `max_score`. Not applicable to other scanner types.
+ * @nullable
+ */
+ min_score?: number | null;
+ /**
+ * Classifier scanners only, required for them: count sessions carrying this tag (fixed or freeform). Not applicable to other scanner types.
+ * @maxLength 100
+ * @nullable
+ */
+ tag?: string | null;
+ /**
+ * Trailing window of observations to count. Defaults to 30 days.
+ * @minimum 1
+ * @maximum 90
+ */
+ window_days?: number;
+ };
+
export type EnvironmentsVisionScannersObservationsListParams = {
/**
* When true, return only observations that have a shared label (thumbs up or down); when false, only unlabeled observations.
@@ -78402,6 +78483,31 @@ export namespace Schemas {
search?: string;
};
+ export type VisionScannersImpactRetrieveParams = {
+ /**
+ * Scorer scanners only: count sessions scoring at or below this value.
+ * @nullable
+ */
+ max_score?: number | null;
+ /**
+ * Scorer scanners only: count sessions scoring at or above this value. Scorers require `min_score` and/or `max_score`. Not applicable to other scanner types.
+ * @nullable
+ */
+ min_score?: number | null;
+ /**
+ * Classifier scanners only, required for them: count sessions carrying this tag (fixed or freeform). Not applicable to other scanner types.
+ * @maxLength 100
+ * @nullable
+ */
+ tag?: string | null;
+ /**
+ * Trailing window of observations to count. Defaults to 30 days.
+ * @minimum 1
+ * @maximum 90
+ */
+ window_days?: number;
+ };
+
export type VisionScannersObservationsListParams = {
/**
* When true, return only observations that have a shared label (thumbs up or down); when false, only unlabeled observations.
diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.ts
index b31cd78eea94..6c53e8df237d 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 19 enabled ops
+ * PostHog API - MCP 21 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -368,6 +368,91 @@ export const VisionScannersDestroyParams = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Save the users this scanner matched as a static cohort, for surveys, funnels, and retention analysis.
+ */
+export const VisionScannersAffectedCohortCreateParams = /* @__PURE__ */ 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/."
+ ),
+})
+
+export const visionScannersAffectedCohortCreateBodyWindowDaysDefault = 30
+export const visionScannersAffectedCohortCreateBodyWindowDaysMax = 90
+
+export const visionScannersAffectedCohortCreateBodyTagMax = 100
+
+export const VisionScannersAffectedCohortCreateBody = /* @__PURE__ */ zod
+ .object({
+ window_days: zod
+ .number()
+ .min(1)
+ .max(visionScannersAffectedCohortCreateBodyWindowDaysMax)
+ .default(visionScannersAffectedCohortCreateBodyWindowDaysDefault)
+ .describe('Trailing window of observations to count. Defaults to 30 days.'),
+ tag: zod
+ .string()
+ .max(visionScannersAffectedCohortCreateBodyTagMax)
+ .nullish()
+ .describe(
+ 'Classifier scanners only, required for them: count sessions carrying this tag (fixed or freeform). Not applicable to other scanner types.'
+ ),
+ min_score: zod
+ .number()
+ .nullish()
+ .describe(
+ 'Scorer scanners only: count sessions scoring at or above this value. Scorers require `min_score` and/or `max_score`. Not applicable to other scanner types.'
+ ),
+ max_score: zod
+ .number()
+ .nullish()
+ .describe('Scorer scanners only: count sessions scoring at or below this value.'),
+ })
+ .describe('Body of POST /vision/scanners/:id/affected_cohort/. Same qualifiers as the impact GET.')
+
+/**
+ * Affected sessions and users for this scanner over the trailing window.
+ */
+export const VisionScannersImpactRetrieveParams = /* @__PURE__ */ 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/."
+ ),
+})
+
+export const visionScannersImpactRetrieveQueryTagMax = 100
+
+export const visionScannersImpactRetrieveQueryWindowDaysDefault = 30
+export const visionScannersImpactRetrieveQueryWindowDaysMax = 90
+
+export const VisionScannersImpactRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ max_score: zod.number().nullish().describe('Scorer scanners only: count sessions scoring at or below this value.'),
+ min_score: zod
+ .number()
+ .nullish()
+ .describe(
+ 'Scorer scanners only: count sessions scoring at or above this value. Scorers require `min_score` and/or `max_score`. Not applicable to other scanner types.'
+ ),
+ tag: zod
+ .string()
+ .max(visionScannersImpactRetrieveQueryTagMax)
+ .nullish()
+ .describe(
+ 'Classifier scanners only, required for them: count sessions carrying this tag (fixed or freeform). Not applicable to other scanner types.'
+ ),
+ window_days: zod
+ .number()
+ .min(1)
+ .max(visionScannersImpactRetrieveQueryWindowDaysMax)
+ .default(visionScannersImpactRetrieveQueryWindowDaysDefault)
+ .describe('Trailing window of observations to count. Defaults to 30 days.'),
+})
+
/**
* Apply this scanner to one specific session, on demand. Returns 202 with the workflow handle.
*/
diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.ts
index 36a3a85cb9d6..bf30a1c65266 100644
--- a/services/mcp/src/tools/generated/replay_vision.ts
+++ b/services/mcp/src/tools/generated/replay_vision.ts
@@ -9,9 +9,13 @@ import {
VisionObservationsListQueryParams,
VisionObservationsRetrieveParams,
VisionObservationsRetrieveQueryParams,
+ VisionScannersAffectedCohortCreateBody,
+ VisionScannersAffectedCohortCreateParams,
VisionScannersCreateBody,
VisionScannersDestroyParams,
VisionScannersEstimateCreateBody,
+ VisionScannersImpactRetrieveParams,
+ VisionScannersImpactRetrieveQueryParams,
VisionScannersListQueryParams,
VisionScannersObservationsListParams,
VisionScannersObservationsListQueryParams,
@@ -145,6 +149,40 @@ const visionQuotaRetrieve = (): ToolBase<typeof VisionQuotaRetrieveSchema, Schem
},
})
+const VisionScannersAffectedCohortCreateSchema = VisionScannersAffectedCohortCreateParams.omit({
+ project_id: true,
+}).extend(VisionScannersAffectedCohortCreateBody.shape)
+
+const visionScannersAffectedCohortCreate = (): ToolBase<
+ typeof VisionScannersAffectedCohortCreateSchema,
+ Schemas.AffectedCohortResponse
+> => ({
+ name: 'vision-scanners-affected-cohort-create',
+ schema: VisionScannersAffectedCohortCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof VisionScannersAffectedCohortCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.window_days !== undefined) {
+ body['window_days'] = params.window_days
+ }
+ if (params.tag !== undefined) {
+ body['tag'] = params.tag
+ }
+ if (params.min_score !== undefined) {
+ body['min_score'] = params.min_score
+ }
+ if (params.max_score !== undefined) {
+ body['max_score'] = params.max_score
+ }
+ const result = await context.api.request<Schemas.AffectedCohortResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/${encodeURIComponent(String(params.id))}/affected_cohort/`,
+ body,
+ })
+ return result
+ },
+})
+
const VisionScannersCreateSchema = VisionScannersCreateBody
const visionScannersCreate = (): ToolBase<typeof VisionScannersCreateSchema, Schemas.ReplayScanner> => ({
@@ -260,6 +298,32 @@ const visionScannersGet = (): ToolBase<typeof VisionScannersGetSchema, Schemas.R
},
})
+const VisionScannersImpactRetrieveSchema = VisionScannersImpactRetrieveParams.omit({ project_id: true }).extend(
+ VisionScannersImpactRetrieveQueryParams.shape
+)
+
+const visionScannersImpactRetrieve = (): ToolBase<
+ typeof VisionScannersImpactRetrieveSchema,
+ Schemas.ScannerImpact
+> => ({
+ name: 'vision-scanners-impact-retrieve',
+ schema: VisionScannersImpactRetrieveSchema,
+ handler: async (context: Context, params: z.infer<typeof VisionScannersImpactRetrieveSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.ScannerImpact>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/${encodeURIComponent(String(params.id))}/impact/`,
+ query: {
+ max_score: params.max_score,
+ min_score: params.min_score,
+ tag: params.tag,
+ window_days: params.window_days,
+ },
+ })
+ return result
+ },
+})
+
const VisionScannersListSchema = VisionScannersListQueryParams
const visionScannersList = (): ToolBase<
@@ -540,10 +604,12 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'vision-observations-list': visionObservationsList,
'vision-observations-retrieve': visionObservationsRetrieve,
'vision-quota-retrieve': visionQuotaRetrieve,
+ 'vision-scanners-affected-cohort-create': visionScannersAffectedCohortCreate,
'vision-scanners-create': visionScannersCreate,
'vision-scanners-delete': visionScannersDelete,
'vision-scanners-estimate-create': visionScannersEstimateCreate,
'vision-scanners-get': visionScannersGet,
+ 'vision-scanners-impact-retrieve': visionScannersImpactRetrieve,
'vision-scanners-list': visionScannersList,
'vision-scanners-observations-get': visionScannersObservationsGet,
'vision-scanners-observations-list': visionScannersObservationsList,
diff --git a/tach.toml b/tach.toml
index f426849075bc..c493bb6fcc23 100644
--- a/tach.toml
+++ b/tach.toml
@@ -598,6 +598,7 @@ depends_on = [
"ee",
"posthog",
"products.cdp",
+ "products.cohorts",
"products.exports",
"products.signals",
]