: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): draft an event filter alongside the goal-based scanner (#83206)
Arno Hillene27e205434d3
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 6e2a229681cd..e8120a1ee2d2 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -1255,6 +1255,11 @@ class DraftScannerResponseSerializer(serializers.Serializer):allow_blank=True,help_text="Why the draft picked this scanner type and configuration, addressed to the user.",)+ query = serializers.JSONField(+ allow_null=True,+ help_text="Drafted `RecordingsQuery` narrowing which sessions get scanned, holding one event filter "+ "picked from the team's real events; null when no event clearly matched the goal.",+ )class ScannerImpactSerializer(serializers.Serializer):@@ -1988,6 +1993,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi"scanner_type": drafted.scanner_type,"scanner_config": drafted.scanner_config,"rationale": drafted.rationale,+ "query": drafted.query,}).data)diff --git a/products/replay_vision/backend/scanner_draft.py b/products/replay_vision/backend/scanner_draft.pyindex 2158539dac1b..b004471cc789 100644--- a/products/replay_vision/backend/scanner_draft.py+++ b/products/replay_vision/backend/scanner_draft.py@@ -90,6 +90,11 @@ class _LlmDraft(BaseModel):length: Literal["short", "medium", "long"] = Field(default="medium", description="Summarizer only: how long each summary should be.")+ filter_event: str | None = Field(+ default=None,+ description="The one event name, copied EXACTLY from the briefing's most-active-events list, that a "+ "session must contain to be relevant to the goal; null when no listed event clearly maps to it.",+ )@dataclass(frozen=True, kw_only=True)@@ -101,6 +106,7 @@ class ScannerDraft:scanner_type: strscanner_config: dict[str, Any]rationale: str+ query: dict[str, Any] | None@dataclass(frozen=True, kw_only=True)@@ -193,6 +199,10 @@ Pick the single type that best fits the goal, then draft the scanner:- rationale: one or two sentences, addressed to the user, explaining why the chosen type and settings fittheir goal (e.g. why a classifier rather than a scorer, or what the scale's endpoints capture). It isshown next to the draft in the creation wizard; plain language, and don't restate the config itself.+- filter_event: when the goal targets a specific flow AND one event in the briefing's "most active custom+ events" list clearly marks that flow (e.g. a checkout goal and a checkout_started event), set it to that+ event name copied EXACTLY as listed, so only sessions containing it get scanned. When the goal is broad,+ or no listed event clearly maps to it, leave it null. Never invent or reword an event name.The briefing may include the company's name, its business context, and the team's existing scanners:- Use the business context to make the name, description, and prompt specific to THIS company's product,@@ -288,7 +298,7 @@ def draft_scanner_from_goal(company=company,)parsed = _generate(user_content=user_content, team_id=team.id, distinct_id=str(user.uuid))- return _finalize(parsed)+ return _finalize(parsed, offered_events=taxonomy.events)def _generate(*, user_content: str, team_id: int, distinct_id: str) -> _LlmDraft:@@ -342,7 +352,7 @@ def _generate(*, user_content: str, team_id: int, distinct_id: str) -> _LlmDraftraise DraftError("invalid response") from e-def _finalize(parsed: _LlmDraft) -> ScannerDraft:+def _finalize(parsed: _LlmDraft, offered_events: list[str] | None = None) -> ScannerDraft:"""Normalize the model output into a draft the wizard form (and later the create endpoint) will accept."""name = parsed.name.strip()[:_MAX_NAME_LENGTH]prompt = parsed.prompt.strip()[:_MAX_PROMPT_LENGTH]@@ -378,10 +388,20 @@ def _finalize(parsed: _LlmDraft) -> ScannerDraft:if error:raise DraftError(f"draft config invalid: {error}")+ # Only an event that exists in the offered taxonomy may become a filter: anything else is a+ # hallucinated name that would silently match no recordings.+ query: dict[str, Any] | None = None+ if parsed.filter_event and parsed.filter_event in (offered_events or []):+ query = {+ "kind": "RecordingsQuery",+ "events": [{"type": "events", "id": parsed.filter_event, "name": parsed.filter_event, "order": 0}],+ }+return ScannerDraft(name=name,description=parsed.description.strip()[:_MAX_DESCRIPTION_LENGTH],scanner_type=parsed.scanner_type,scanner_config=scanner_config,rationale=parsed.rationale.strip()[:_MAX_RATIONALE_LENGTH],+ query=query,)diff --git a/products/replay_vision/backend/tests/test_scanner_draft.py b/products/replay_vision/backend/tests/test_scanner_draft.pyindex 3260520f8b3b..db1d281a5732 100644--- a/products/replay_vision/backend/tests/test_scanner_draft.py+++ b/products/replay_vision/backend/tests/test_scanner_draft.py@@ -143,6 +143,28 @@ class TestFinalize:assert result.scanner_config == {"prompt": _draft().prompt, "length": "short"}+ def test_offered_filter_event_becomes_a_recordings_query(self):+ result = _finalize(_draft(filter_event="checkout_started"), offered_events=["checkout_started", "signup"])++ assert result.query == {+ "kind": "RecordingsQuery",+ "events": [{"type": "events", "id": "checkout_started", "name": "checkout_started", "order": 0}],+ }++ @pytest.mark.parametrize(+ "filter_event,offered_events",+ [+ ("checkout started", ["checkout_started"]), # reworded, would match nothing+ ("made_up_event", ["checkout_started"]), # hallucinated+ ("checkout_started", []), # nothing offered to ground it+ (None, ["checkout_started"]), # model declined+ ],+ )+ def test_ungrounded_filter_event_yields_no_query(self, filter_event, offered_events):+ result = _finalize(_draft(filter_event=filter_event), offered_events=offered_events)++ assert result.query is None+def test_rationale_is_trimmed_and_capped(self):result = _finalize(_draft(rationale=" why " + "x" * 600))@@ -309,6 +331,7 @@ class TestDraftScannerEndpoint(_VisionAPITestCase):"multi_label": False,},"rationale": "A classifier fits because you want the mix of visit intents, not a single yes/no.",+ "query": None,}@patch(_CORE_MEMORY_FLAG_PATH, return_value=False)diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex c3cf531b655f..d08b554b5153 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -1629,6 +1629,8 @@ export interface DraftScannerResponseApi {scanner_config: unknown/** Why the draft picked this scanner type and configuration, addressed to the user. */rationale: string+ /** Drafted `RecordingsQuery` narrowing which sessions get scanned, holding one event filter picked from the team's real events; null when no event clearly matched the goal. */+ query: unknown}/**diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex df30db5b9d02..90219ab6144b 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -112,6 +112,10 @@ describe('replayScannerLogic', () => {scanner_type: 'classifier',scanner_config: { prompt: 'Classify the session by intent.', tags: ['browsing'], multi_label: false },rationale: 'A classifier fits because you want the mix of visit intents.',+ query: {+ kind: 'RecordingsQuery',+ events: [{ type: 'events', id: 'signed_up', name: 'signed_up', order: 0 }],+ },}draftSpy.mockReturnValue([200, draft])router.actions.push(path)@@ -128,6 +132,7 @@ describe('replayScannerLogic', () => {description: draft.description,scanner_type: draft.scanner_type,scanner_config: draft.scanner_config,+ query: draft.query,})// The test router prefixes paths with /project/:id, so match on the suffix.expect(router.values.location.pathname).toContain(urls.replayVisionScannerConfigure('new'))diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex d7f5dedc667e..d7b41525477c 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -29,6 +29,7 @@ import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'+import type { RecordingsQuery } from '~/queries/schema/schema-general'import {visionScannersAffectedCohortCreate,@@ -1606,6 +1607,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([description: goalDraft.description,scanner_type: goalDraft.scanner_type as ScannerType,scanner_config: goalDraft.scanner_config as ScannerConfig,+ // The drafted event filter (when the goal mapped to a real event); the triggers step+ // shows it for review like any hand-picked filter.+ ...(goalDraft.query ? { query: goalDraft.query as RecordingsQuery } : {}),})router.actions.push(urls.replayVisionScannerConfigure('new'))},diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 936586d405fc..c4b10afe46ce 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -26381,6 +26381,8 @@ export namespace Schemas {scanner_config: unknown;/** Why the draft picked this scanner type and configuration, addressed to the user. */rationale: string;+ /** Drafted `RecordingsQuery` narrowing which sessions get scanned, holding one event filter picked from the team's real events; null when no event clearly matched the goal. */+ query: unknown;}export interface DraftStatusResponse {