: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 experiment scanners from the goal flow (#118552)
Tue Haulunde1a16a7858a9
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex c4137a13f335..2699394b3df7 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -13891,25 +13891,29 @@ snapshots:scenes-app-replay-vision--scanner-editor-details--light:hash: v1.k794b7964.6a0bec1cca5a2d30c5ae7ad47d071406b55c337c4b6574d0c601d97ef5f56749.ebPyjAyNgVrgCHUvj3sL2nLQm23sw5Pe28YYdK94Gtwscenes-app-replay-vision--scanner-editor-goal-flow--dark:- hash: v1.k794b7964.4e4f1adef25e8ecdab67f67e509caebdfbb8098500f3a070d89a695ac8f91852.mkbyvXbnVWikExo74IoI1pwSOKN6uuAYkQ9Gu9TJ0pk+ hash: v1.k794b7964.54704e12a4eb28c568f1d7341371eb85b8626b88258f316cf635286ebb4e0eb8.JtMuT9-1OV64NzYC-PcNEqIErarlvklO9kSY4o3N37gscenes-app-replay-vision--scanner-editor-goal-flow--light:- hash: v1.k794b7964.29d093aecbf976edb75dc11d72308bd72779a2c87bc669f3d98596748d72bb77.d4netmI6e388wifkra4IA4HOOuF8Et-oNrIYegrxM5Q+ hash: v1.k794b7964.25084193b6d9cab0c0a3dc32fd6c37e7016558e4c3fba4c86b1131fcc289957f.A9CGMyFwJTyhWBfMhdee4G0z9xIA6TKpRSzXPzQy4c0scenes-app-replay-vision--scanner-editor-goal-flow-budget--dark:- hash: v1.k794b7964.7057b5e8825ff9fb5bf4397dd4b40f423038367cb81aebc519ef62c68bd78fd6.lDf8ThWKFgRsClSogBWyLfDEtkB3tRA1diKxBHqAfTo+ hash: v1.k794b7964.ed055bebedf289193506b4672a715d170cd3e810ca097ff1a5e65335ca4516b2.4SP2GfwEyX728qJhrzeuRl7LSSRFU_2jKK_IPWdimeEscenes-app-replay-vision--scanner-editor-goal-flow-budget--light:- hash: v1.k794b7964.644e1350b0953c9df13cf881fde9f63e6b6c7831241f0792e0a17c75be410221.VD8tZXOJbq8zsFeLTpTHDVCeTGIKSlgmUoVh71RDwZc+ hash: v1.k794b7964.0f56f5b7de26046ba909c3eb42adeaefe0e317cc59c5f51e2c8158c8a07b71e0.2yS8pSdT8665oU61jJ6s4aR-7fgYIqXjruZegY45PjQ+ scenes-app-replay-vision--scanner-editor-goal-flow-experiment-picker--dark:+ hash: v1.k794b7964.5eac4fee3e088daf0f204dcb2896bee08c82769ceebb309b83b5eb8a1e1665d4.dfXnGv5RS9Zij8XqzUN_Zg5gtl9pPXu0AKbOcij9MqI+ scenes-app-replay-vision--scanner-editor-goal-flow-experiment-picker--light:+ hash: v1.k794b7964.1d9c603ab0b9b663aad7ba9a9f7f7f411c9701e7ef6dab18a48ba86da72e6e92.i8xJt0k7zeGGUcL7HiMpuLz7HjzV0RZiTgDY-O9aLWQscenes-app-replay-vision--scanner-editor-goal-flow-free-credits-used--dark:- hash: v1.k794b7964.4e020db337e427c01e8d7870cd07c7c12b27ea8715b0b2e945d45b7444f05852.nHfzx6tV51Cj5FLdfFWGGO_UVt2-5CHAFKh5Tzsq7x8+ hash: v1.k794b7964.26d07fac294f96d1105726af596f2d43c688400a29bff7ccc346b9a06f2a00e3.yWrxPU0zdX_M24CSIxtQJPhjQ9HOfVF0-YXr7j8CuYEscenes-app-replay-vision--scanner-editor-goal-flow-free-credits-used--light:- hash: v1.k794b7964.ecb94f70f6b13b80d47a3a7f59b45c1f9a9012ecef1ff0a56fbd8eba088cad39.pnydN1giJjbyCc7o0n98joUjg46NcA7L4NKWGkqbvuA+ hash: v1.k794b7964.b707385d0abb1de4de312429fbf86f73995f23d46c9dc5b234d507e2a0912deb.GC9QylMvwVKSGOgRv01k3tVf1e8LZSUvdGRS1DVq_-Uscenes-app-replay-vision--scanner-editor-goal-overview--dark:hash: v1.k794b7964.f01ae73fc01d6f402ea1587d8fa62cd0195288283e5f02640a7d533b4ad09bfd.udZKrn75onISEkfnNqDPgFTA1zHMAm5n383-eNRdoPwscenes-app-replay-vision--scanner-editor-goal-overview--light:hash: v1.k794b7964.9522d0cf5a021637d694e64b47499b3ea59b1f4190b418a3c956edd230bb6674.jMbMAjH6vT_UynFlvsCkdNSpKOI3kiY2sEvjaYd6458scenes-app-replay-vision--scanner-editor-goal-overview-experiment--dark:- hash: v1.k794b7964.eb9e640621c319777e9d0f35160e175e5740430705ed29e2b00190a416916561.LnXPwb9D0h9JoDXETFIZmQ9mX_kexX838Nm7XfM33TA+ hash: v1.k794b7964.ff99ba79fbfec7a00ba628dd14684009f265db243e1229b5c310b0ddff910761.LiBVYYeSabHpDOdizYDUvhClIU-BHbV9bHqX7eH722Yscenes-app-replay-vision--scanner-editor-goal-overview-experiment--light:- hash: v1.k794b7964.d2d2658ddbf2aace36438d92fa5aa1689badeb9445c1c55322234d0e3a0d66ce.AMSsv3Q7mbqIiVnfFXikAe3a0i4NMkDGtc9JJc-ZE_U+ hash: v1.k794b7964.c7f92ae93655de4db16599b2c0dab86aba90f532e1f1fcd8a84f356cbe93a913.BqywSiFVge-leDfmo8pelcW3VgQZFZRCHiEmCxS2jqIscenes-app-replay-vision--scanner-editor-goal-overview-free-only--dark:hash: v1.k794b7964.c3c29df373cd8e663770b097f02a4772ffc2ba0c51e10a245fb5cf8ef7bdff68.rPAbWs7-3bfCc9X1HQcY30nfQscWET-stKmszLHV-foscenes-app-replay-vision--scanner-editor-goal-overview-free-only--light:diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 01d29a570b8f..b175e92974e9 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -164,7 +164,13 @@ from products.replay_vision.backend.scanner_dashboard import (live_dashboard_ids,scanners_ready_for_dashboard,)-from products.replay_vision.backend.scanner_draft import DraftError, draft_scanner_from_goal, draft_scanner_from_goal_v2+from products.replay_vision.backend.scanner_draft import (+ DraftError,+ UnwatchableExperimentError,+ draft_scanner_from_goal,+ draft_scanner_from_goal_v2,+ scopes_allow_read,+)from products.replay_vision.backend.scanning import (MAX_SESSIONS_PER_SCAN,run_inline_scan,@@ -2027,6 +2033,15 @@ class DraftScannerRequestSerializer(serializers.Serializer):"ignored while the goal-based flow's flag is off for the caller."),)+ experiment_id = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=9223372036854775807,+ help_text=(+ "Goal-based flow only: a launched experiment the person picked for the scanner to watch. "+ "The draft is then an `experiment` scanner on it. Ignored without `monthly_credit_budget`."+ ),+ )class DraftScannerResponseSerializer(serializers.Serializer):@@ -2083,14 +2098,6 @@ class DraftScannerResponseSerializer(serializers.Serializer):"mis-estimate stops the scanner at the credits the user agreed to. Null on the legacy flow."),)- experiment_targeting = ScannerExperimentTargetingField(- allow_null=True,- help_text=(- "Goal-based flow only: the experiment whose participants the draft watches, when the goal "- "named one of the project's launched experiments. Null when it named none. Carried "- "separately from `query`, which never holds an exposure filter."- ),- )estimated_monthly_observations = serializers.IntegerField(allow_null=True,help_text=(@@ -3317,6 +3324,13 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi# actions, experiments) is gated per resource against these scopes inside the drafter.allowed_scopes = get_authenticator_scopes(request.successful_authenticator)include_business_context = allowed_scopes is None+ experiment_id = body.validated_data.get("experiment_id") if goal_flow else None+ # Denied, out-of-scope and nonexistent ids read the same, so the error never confirms an experiment exists.+ if experiment_id is not None and not (+ scopes_allow_read(allowed_scopes, "experiment")+ and is_experiment_accessible(self.user_access_control, self.team_id, experiment_id)+ ):+ raise ValidationError({"experiment_id": "Experiment not found in this project."})try:if goal_flow:@@ -3328,6 +3342,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viuser_access_control=self.user_access_control,include_business_context=include_business_context,allowed_scopes=allowed_scopes,+ experiment_id=experiment_id,)else:drafted = draft_scanner_from_goal(@@ -3337,6 +3352,10 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viuser_access_control=self.user_access_control,include_business_context=include_business_context,)+ except UnwatchableExperimentError:+ raise ValidationError(+ {"experiment_id": "Pick a running experiment that splits people, not groups, into variants."}+ )except DraftError as e:# The 503 below is deliberately uniform, so the reason only survives here.logger.warning(@@ -3367,9 +3386,8 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi"scanner_type": drafted.scanner_type,# Whether the goal mapped to a real filter or fell back to no targeting."has_query": bool(drafted.query),- # Whether the goal named an experiment, so the scan watches its participants rather- # than everyone who reached the same pages.- "has_experiment_targeting": drafted.experiment_targeting is not None,+ "has_experiment_targeting": drafted.scanner_type == ScannerType.EXPERIMENT,+ "experiment_picked": experiment_id is not None,"sampling_mode": drafted.sampling_mode,"sampling_rate": drafted.sampling_rate,"model": drafted.model,@@ -3393,7 +3411,6 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi"sampling_rate": drafted.sampling_rate,"model": drafted.model,"credit_limit": drafted.credit_limit,- "experiment_targeting": drafted.experiment_targeting,"estimated_monthly_observations": drafted.estimated_monthly_observations,}).datadiff --git a/products/replay_vision/backend/scanner_draft.py b/products/replay_vision/backend/scanner_draft.pyindex 2f54142cbd15..153aa3e27be3 100644--- a/products/replay_vision/backend/scanner_draft.py+++ b/products/replay_vision/backend/scanner_draft.py@@ -55,6 +55,7 @@ from products.replay_vision.backend.models.replay_scanner import (ScannerModel,ScannerType,apply_experiment_targeting,+ config_experiment_scope,)from products.replay_vision.backend.queries.action_volume import recent_action_sessionsfrom products.replay_vision.backend.queries.event_volume import recent_event_sessions@@ -261,6 +262,11 @@ class DraftError(Exception):self.detail = detail+class UnwatchableExperimentError(Exception):+ """The experiment a draft was asked to watch is one a scan cannot watch: never launched, deleted,+ group-aggregated, or without variants."""++class _LlmDraft(BaseModel):"""The model's structured output: one drafted scanner."""@@ -325,11 +331,6 @@ class ScannerDraft:# budget so a mis-estimate cannot overspend it. None on the legacy path.model: str | None = Nonecredit_limit: int | None = None- # Shape: ScannerExperimentTargetingSerializer. Set by the goal-based path when the goal named one- # of the team's experiments, so the scan watches that experiment's participants. It stays out of- # `query`, which is where the API refuses an exposure filter, and rides to the wizard as its own- # field the way a saved scanner carries it.- experiment_targeting: dict[str, Any] | None = None@dataclass(frozen=True, kw_only=True)@@ -896,7 +897,7 @@ class _LlmEventPropertyFilter(BaseModel):class _LlmDraftV2(BaseModel):"""The model's structured output for the goal-based flow: one drafted scanner plus targeting."""- scanner_type: Literal["monitor", "classifier", "scorer", "summarizer"] = Field(+ scanner_type: Literal["monitor", "classifier", "scorer", "summarizer", "experiment"] = Field(description="The scanner type that best fits the goal.")name: str = Field(description="Short scanner name (under 8 words), e.g. 'Checkout abandonment'.")@@ -918,7 +919,7 @@ class _LlmDraftV2(BaseModel):default=None, description="Scorer only: one-word label for the dimension being scored, e.g. 'frustration'.")length: Literal["short", "medium", "long"] = Field(- default="medium", description="Summarizer only: how long each summary should be."+ default="medium", description="Summarizer and experiment only: how long each summary should be.")allow_inconclusive: bool = Field(default=False,@@ -991,7 +992,7 @@ class _LlmDraftV2(BaseModel):_SYSTEM_PROMPT_V2 = """You turn a PostHog user's goal into a draft Replay Vision scanner. A scanner watches individual session-recordings of the user's product and produces one observation per recording. There are four scanner types:+recordings of the user's product and produces one observation per recording. There are five scanner types:- monitor: answers a yes/no question about the session (e.g. "Did the user fail to complete checkout?").Best when the goal is detecting whether something specific happened.@@ -1001,6 +1002,9 @@ recordings of the user's product and produces one observation per recording. TheBest when the goal is ranking sessions by intensity of something.- summarizer: writes a free-text summary of the session. Best when the goal is broad ("what are usersdoing?", "give me an overview") and doesn't fit one question, dimension, or vocabulary.+- experiment: summarizes how each person exposed to one A/B experiment experiences the change under+ test. Pick it whenever you set filter_experiment, and only then: it is the type built to watch an+ experiment's participants, so a goal about an experiment always gets it.A short or vague goal ("test", "help", "what's going on") is not a puzzle to work out. Draft a summarizer overthe whole product with no filters and move on. The user reviews the draft in the wizard and narrows it@@ -1037,6 +1041,10 @@ Pick the single type that best fits the goal, then draft the scanner:configured separately via `scale_min`/`scale_max`.- summarizer: say what every summary must cover and in what order (what the person was trying to do,what the product did, where they got stuck, how it ended), and what to leave out.+ - experiment: the scanner already knows the experiment's name, hypothesis and variants, and must never+ be told which variant a session got. Say which surface the change lives on, what to watch for on it+ (the moments that show whether the change helps or hurts the goal), and what to leave out. Do not+ restate the experiment or ask the scanner to name a variant.- Fill only the fields relevant to the chosen type; leave the rest at their defaults.- For monitors: set allow_inconclusive to true when many sessions won't even reach the flow the questionis about (e.g. a checkout question when most sessions never open checkout), so those sessions aren't@@ -1094,7 +1102,8 @@ Pick the single type that best fits the goal, then draft the scanner:limits the scan to the people that experiment exposed, which no page or event filter canexpress: a page filter scans everyone who visited the page, so the control group's sessions landin the results too and the observations describe the old experience and the new one at once.- Copy the name exactly; anything not in the list is discarded.+ Copy the name exactly; anything not in the list is discarded. Setting it means scanner_type is+ experiment.- filter_experiment_variant: the variant whose experience the goal is about, copied exactly fromthat experiment's variants. A goal about the new thing means the variant that has it, notcontrol. Leave empty only when the goal compares the variants or names none.@@ -1152,6 +1161,7 @@ def _build_user_content_v2(actions: Sequence[_MatchedAction] = (),cohorts: Sequence[_MatchedCohort] = (),experiments: Sequence[_MatchedExperiment] = (),+ pinned_experiment: _MatchedExperiment | None = None,business_context: str = "",company: str = "",) -> str:@@ -1226,6 +1236,18 @@ def _build_user_content_v2(),))+ if pinned_experiment is not None:+ lines.append(+ "\n"+ + as_untrusted_data(+ "chosen-experiment",+ [f'"{pinned_experiment.name}" -> variants: {", ".join(pinned_experiment.variants)}'],+ source=(+ "the experiment the user picked for this scanner to watch. Copy its name into "+ "filter_experiment and draft an experiment scanner about it"+ ),+ )+ )if experiments:lines.append("\n"@@ -1314,7 +1336,7 @@ def _events_for_goal(team: Team, goal: str) -> list[str]:return list(dict.fromkeys([*quoted, *matched, *baseline]))-def _scopes_allow_read(allowed_scopes: list[str] | None, resource: APIScopeObject) -> bool:+def scopes_allow_read(allowed_scopes: list[str] | None, resource: APIScopeObject) -> bool:"""Whether a credential's API scopes permit reading `resource`.`None` means session or other non-token auth, which is not scope-gated (RBAC applies instead).@@ -1367,10 +1389,10 @@ def _goal_entity_matches() or user_access_control.has_any_specific_access_for_resource(resource, required_level="viewer")acl_kinds: tuple[APIScopeObject, ...] = ("survey", "action", "experiment")- kinds: set[str] = {kind for kind in acl_kinds if _readable(kind) and _scopes_allow_read(allowed_scopes, kind)}+ kinds: set[str] = {kind for kind in acl_kinds if _readable(kind) and scopes_allow_read(allowed_scopes, kind)}# Cohorts are team-scoped only, not in ACCESS_CONTROL_RESOURCES, so they get no resource gate,# but a scoped token still must hold cohort:read to receive them.- if _scopes_allow_read(allowed_scopes, "cohort"):+ if scopes_allow_read(allowed_scopes, "cohort"):kinds.add("cohort")# `search_entities` builds its result by unioning one queryset per kind, then orders by the rank# those querysets annotate. With no kind it orders an empty base queryset by a column that was@@ -1735,12 +1757,12 @@ def _finalize_v2(allowed_actions: Sequence[_MatchedAction] = (),allowed_cohorts: Sequence[_MatchedCohort] = (),allowed_experiments: Sequence[_MatchedExperiment] = (),+ pinned_experiment: _MatchedExperiment | None = None,) -> ScannerDraft:"""Normalize the v2 model output; costing is applied by the caller."""name = parsed.name.strip()[:_MAX_NAME_LENGTH]if not name or not parsed.prompt.strip():raise DraftError("missing_name_or_prompt")- scanner_config = _normalized_config(parsed) # type: ignore[arg-type]proposed_pages = _proposed_filter_values(parsed.filter_pages, allowed_pages)# Dead events count as offered here: they left the briefing, but revival below can still put one@@ -1770,9 +1792,14 @@ def _finalize_v2(for name in dict.fromkeys(n.strip() for n in parsed.filter_cohorts)if name in cohorts_by_name][:_MAX_FILTER_COHORTS]- targeting = _grounded_targeting(- parsed.filter_experiment, parsed.filter_experiment_variant, allowed=allowed_experiments+ # The user picked this experiment, so a draft that named another one, or none, still watches it.+ experiment_name, experiments = (+ (pinned_experiment.name, [pinned_experiment])+ if pinned_experiment is not None+ else (parsed.filter_experiment, allowed_experiments))+ targeting = _grounded_targeting(experiment_name, parsed.filter_experiment_variant, allowed=experiments)+ scanner_type, scanner_config = _typed_config(parsed, targeting)# Dropping a dead event narrows only while another filter still holds the scan down. Alone it# inverts, leaving a query that matches every session rather than none, so the event goes back.revived_dead_events = (@@ -1857,16 +1884,40 @@ def _finalize_v2(return ScannerDraft(name=name,description=parsed.description.strip()[:_MAX_DESCRIPTION_LENGTH],- scanner_type=parsed.scanner_type,+ scanner_type=scanner_type,scanner_config=scanner_config,rationale=parsed.rationale.strip()[:_MAX_RATIONALE_LENGTH],query=query,sampling_mode=parsed.sampling_mode,model=parsed.model,- experiment_targeting=targeting,)+def _typed_config(parsed: _LlmDraftV2, targeting: dict[str, Any] | None) -> tuple[str, dict[str, Any]]:+ """The scanner type and config for the v2 draft.++ A draft that watches an experiment becomes the experiment type whatever type the model picked,+ because only that type scopes the scan to the experiment's participants and tells the scanner+ what the experiment changes. The drafted prompt becomes its focus. An experiment type with no+ experiment that survived grounding falls back to the summarizer it is built on.+ """+ if targeting is None:+ if parsed.scanner_type == "experiment":+ parsed = parsed.model_copy(update={"scanner_type": "summarizer"})+ return parsed.scanner_type, _normalized_config(parsed) # type: ignore[arg-type]+ summary = _normalized_config(parsed.model_copy(update={"scanner_type": "summarizer"})) # type: ignore[arg-type]+ variant = targeting.get("variant")+ scanner_config = {+ **summary,+ "experiment_id": targeting["experiment_id"],+ "variants": [variant] if variant else None,+ "balance_variants": True,+ }+ if error := scanner_config_error(ScannerType.EXPERIMENT, scanner_config):+ raise DraftError("config_invalid", error)+ return ScannerType.EXPERIMENT.value, scanner_config++def _closing(item: Callable[[], _T]) -> Callable[[], _T]:def run() -> _T:try:@@ -1920,13 +1971,36 @@ def draft_scanner_from_goal_v2(user_access_control: UserAccessControl,include_business_context: bool = True,allowed_scopes: list[str] | None = None,+ experiment_id: int | None = None,) -> ScannerDraft:"""The goal-based flow: ground the goal in the team's real pages, draft the whole scanner in onemodel call, then solve the sampling dials from the stated monthly credit budget.+ `experiment_id` is an experiment the user picked for the scanner to watch. The draft is then an+ experiment scanner on it, whatever the goal names. The caller checks the user and the token may+ read it; this raises UnwatchableExperimentError when a scan cannot watch it.+Raises DraftError on model failure. A costing failure does not fail the draft: the samplingfields come back None and the wizard keeps its defaults."""+ pinned_experiment: _MatchedExperiment | None = None+ if experiment_id is not None:+ try:+ targetable = targetable_experiments(team, experiment_ids=[experiment_id])+ except Exception as e:+ # Unlike a goal-matched experiment, the picked one is the whole draft, so a failed read is+ # an outage to retry rather than a refused pick.+ raise DraftError("experiment_read_failed") from e+ pinned_experiment = next(+ (+ _MatchedExperiment(name=t.name, experiment_id=t.id, variants=t.variants)+ for t in targetable+ if t.name.strip()+ ),+ None,+ )+ if pinned_experiment is None:+ raise UnwatchableExperimentError()company = (" / ".join(part for part in [team.organization.name, team.project.name if team.project else ""] if part)if include_business_context@@ -1938,7 +2012,7 @@ def draft_scanner_from_goal_v2(# analytics read behind query:read, so a scoped token without it gets the names unmeasured —# counts the briefing would show could otherwise reach the model's prompt and rationale.def measure(names: Sequence[str]) -> list[_CandidateEvent]:- if _scopes_allow_read(allowed_scopes, "query"):+ if scopes_allow_read(allowed_scopes, "query"):return _measured_events(team, names)return [_CandidateEvent(name=name) for name in names]@@ -2002,7 +2076,8 @@ def draft_scanner_from_goal_v2(surveys=matches.surveys,actions=matches.actions,cohorts=matches.cohorts,- experiments=matches.experiments,+ experiments=[e for e in matches.experiments if e != pinned_experiment],+ pinned_experiment=pinned_experiment,business_context=_business_context(team, user) if include_business_context else "",company=company,)@@ -2025,6 +2100,7 @@ def draft_scanner_from_goal_v2(allowed_actions=matches.actions,allowed_cohorts=matches.cohorts,allowed_experiments=matches.experiments,+ pinned_experiment=pinned_experiment,)# The cap is the stated budget, so a mis-estimate stops the scanner at the credits the user# agreed to rather than overspending. Kept even when costing fails, so the guardrail survives.@@ -2038,7 +2114,7 @@ def draft_scanner_from_goal_v2(# Targeting survives the page fallback: the goal named the experiment, so a population# that ignores it answers a different question, and unlike an event filter it cannot be# the dead part — the exposure read is resolved from the experiment itself.- experiment_targeting=draft.experiment_targeting,+ experiment_targeting=config_experiment_scope(draft.scanner_config),monthly_credit_budget=monthly_credit_budget,credits_per_observation=observation_credits_for_model(draft.model or ScannerModel.GEMINI_3_FLASH_PREVIEW),model_mode=draft.sampling_mode or SamplingMode.COMPREHENSIVE,diff --git a/products/replay_vision/backend/tests/test_scanner_draft.py b/products/replay_vision/backend/tests/test_scanner_draft.pyindex 28f8e8258f97..9130d6815606 100644--- a/products/replay_vision/backend/tests/test_scanner_draft.py+++ b/products/replay_vision/backend/tests/test_scanner_draft.py@@ -1,4 +1,5 @@import threading+from typing import Anyimport pytestfrom unittest.mock import MagicMock, patch@@ -31,6 +32,7 @@ from products.replay_vision.backend.scanner_draft import (_MAX_OUTPUT_TOKENS,DraftError,ScannerDraft,+ UnwatchableExperimentError,_build_user_content,_build_user_content_v2,_business_context,@@ -616,7 +618,6 @@ class TestDraftScannerEndpoint(_VisionAPITestCase):"sampling_rate": None,"model": None,"credit_limit": None,- "experiment_targeting": None,"estimated_monthly_observations": None,}@@ -1291,41 +1292,72 @@ class TestFinalizeV2Actions:class TestFinalizeV2Experiments:_EXPERIMENT = _MatchedExperiment(name="AI creation flow", experiment_id=11, variants=("control", "test"))+ _OTHER = _MatchedExperiment(name="Pricing page test", experiment_id=12, variants=("control", "cheaper"))- def _finalize(self, **overrides):+ def _finalize(self, pinned=None, **overrides):return _finalize_v2(_draft_v2(**overrides),allowed_pages=[],allowed_events=[],team_id=1,- allowed_experiments=[self._EXPERIMENT],+ allowed_experiments=[self._EXPERIMENT, self._OTHER],+ pinned_experiment=pinned,)- def test_a_grounded_experiment_becomes_targeting_on_the_named_variant(self):- # A page filter would scan everyone who reached the same screen, control group included, so- # the variant the goal is about has to come through as targeting.- draft = self._finalize(filter_experiment="AI creation flow", filter_experiment_variant="test")-- assert draft.experiment_targeting == {"experiment_id": 11, "variant": "test"}+ @parameterized.expand(+ [+ ("named_variant", {"filter_experiment_variant": "test"}, ["test"]),+ ("no_variant_watches_every_variant", {}, None),+ # The exposure filter refuses a variant the experiment does not define, which would take the+ # whole scan down; every variant still answers a wider version of the goal.+ ("invented_variant_watches_every_variant", {"filter_experiment_variant": "treatment"}, None),+ ]+ )+ def test_a_grounded_experiment_becomes_an_experiment_scanner(self, _name, overrides, variants):+ # A page filter would scan everyone who reached the same screen, control group included, and+ # only the experiment type tells the scanner what the experiment changes.+ draft = self._finalize(filter_experiment="AI creation flow", **overrides)++ assert draft.scanner_type == "experiment"+ assert draft.scanner_config == {+ "prompt": "Did the user give up in billing? Answer yes or no with a one-sentence reason.",+ "length": "medium",+ "experiment_id": 11,+ "variants": variants,+ "balance_variants": True,+ }# Exposure never rides in the query blob; the API refuses it there.assert draft.query is not None and "experiment_exposure" not in draft.query- def test_no_named_variant_watches_every_variant(self):- draft = self._finalize(filter_experiment="AI creation flow")-- assert draft.experiment_targeting == {"experiment_id": 11, "variant": None}-- def test_an_invented_experiment_name_is_dropped(self):- draft = self._finalize(filter_experiment="Some other test", filter_experiment_variant="test")+ @parameterized.expand(+ [+ ("invented_experiment", "monitor", "Some other test", "monitor"),+ ("experiment_type_without_an_experiment", "experiment", "", "summarizer"),+ ]+ )+ def test_no_grounded_experiment_keeps_a_type_that_needs_none(self, _name, scanner_type, experiment, expected):+ draft = self._finalize(scanner_type=scanner_type, filter_experiment=experiment)- assert draft.experiment_targeting is None+ assert draft.scanner_type == expected+ assert "experiment_id" not in draft.scanner_config- def test_an_invented_variant_falls_back_to_every_variant(self):- # The exposure filter refuses a variant the experiment does not define, which would take the- # whole scan down; every variant still answers a wider version of the goal.- draft = self._finalize(filter_experiment="AI creation flow", filter_experiment_variant="treatment")+ @parameterized.expand(+ [+ ("named_none", {}, None),+ ("named_another", {"filter_experiment": "Pricing page test"}, None),+ (+ "kept_its_variant",+ {"filter_experiment": "AI creation flow", "filter_experiment_variant": "test"},+ ["test"],+ ),+ ]+ )+ def test_a_picked_experiment_wins_over_what_the_model_named(self, _name, overrides, variants):+ draft = self._finalize(pinned=self._EXPERIMENT, **overrides)- assert draft.experiment_targeting == {"experiment_id": 11, "variant": None}+ assert draft.scanner_type == "experiment"+ assert draft.scanner_config["experiment_id"] == 11+ assert draft.scanner_config["variants"] == variantsclass TestFinalizeV2:@@ -1685,7 +1717,7 @@ class TestDraftV2(_VisionAPITestCase):return estimate- def _drafted_with(self, generate, estimate):+ def _drafted_with(self, generate, estimate, experiment_id=None):with (patch(f"{_MODULE}.fetch_visited_paths", return_value=(VisitedPath(pathname="/billing", sessions=10),)),# Measure every candidate live, so these tests exercise the estimate-based fallback rather@@ -1703,6 +1735,7 @@ class TestDraftV2(_VisionAPITestCase):goal="find out where people give up in billing",monthly_credit_budget=10_000,user_access_control=_access_control(allow=True),+ experiment_id=experiment_id,)def test_an_event_filter_that_matches_nothing_falls_back_to_the_pages(self):@@ -1907,10 +1940,15 @@ class TestDraftV2(_VisionAPITestCase):{"key": "$survey_id", "value": [str(survey.id)], "operator": "exact", "type": "event"}]- def test_the_experiment_the_goal_named_is_carried_as_targeting_and_counted(self):- # The whole point of the targeting: the projection has to count that experiment's- # participants, not every session the pages match, while the query the wizard saves stays- # the exposure-free blob the API accepts.+ @parameterized.expand(+ [+ ("named_in_the_goal", {"filter_experiment": "Billing upgrade prompt"}, False),+ ("picked_by_the_user", {}, True),+ ]+ )+ def test_the_watched_experiment_becomes_an_experiment_scanner_and_is_counted(self, _name, overrides, picked):+ # The projection has to count that experiment's participants, not every session the pages+ # match, while the query the wizard saves stays the exposure-free blob the API accepts.experiment = _launched_experiment(self.team, self.user, "Billing upgrade prompt")counted: list[RecordingsQuery] = []@@ -1919,19 +1957,32 @@ class TestDraftV2(_VisionAPITestCase):return ScannerVolumeEstimate(matched_sessions=300, effective_window_days=30)draft = self._drafted_with(- _draft_v2(- filter_pages=["/billing"],- filter_experiment="Billing upgrade prompt",- filter_experiment_variant="test",- ),+ _draft_v2(filter_pages=["/billing"], filter_experiment_variant="test", **overrides),estimate,+ experiment_id=experiment.id if picked else None,)- assert draft.experiment_targeting == {"experiment_id": experiment.id, "variant": "test"}+ assert draft.scanner_type == "experiment"+ assert draft.scanner_config["experiment_id"] == experiment.id+ assert draft.scanner_config["variants"] == ["test"]assert draft.query is not None and "experiment_exposure" not in draft.queryassert counted[0].experiment_exposure is not Noneassert counted[0].experiment_exposure.experiment_id == experiment.id- assert counted[0].experiment_exposure.variant == "test"+ assert counted[0].experiment_exposure.variants == ["test"]++ def test_a_picked_experiment_that_never_launched_is_refused_before_the_model_runs(self):+ experiment = _launched_experiment(self.team, self.user, "Billing upgrade prompt", launched=False)++ with patch(_GENERATE_PATH) as generate, pytest.raises(UnwatchableExperimentError):+ draft_scanner_from_goal_v2(+ team=self.team,+ user=self.user,+ goal="track my experiment",+ monthly_credit_budget=10_000,+ user_access_control=_access_control(allow=True),+ experiment_id=experiment.id,+ )+ generate.assert_not_called()def test_solved_dials_reach_the_draft(self):draft = self._run(pages=("/billing",), generate=_draft_v2(filter_pages=["/billing"]))@@ -2032,6 +2083,39 @@ class TestDraftEndpointGoalFlow(_VisionAPITestCase):assert body["credit_limit"] == 5000assert body["estimated_monthly_observations"] == 1000+ @parameterized.expand([("not_in_the_project",), ("never_launched",), ("token_without_experiment_read",)])+ def test_a_picked_experiment_a_scan_cannot_watch_is_a_400(self, case):+ headers: dict[str, Any] = {}+ if case == "not_in_the_project":+ experiment_id = 999_999+ else:+ experiment_id = _launched_experiment(+ self.team, self.user, "Checkout test", launched=case == "token_without_experiment_read"+ ).id+ if case == "token_without_experiment_read":+ value = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="draft-scope-test",+ user=self.user,+ secure_value=hash_key_value(value),+ scopes=["replay_scanner:write", "session_recording:read"],+ )+ headers["HTTP_AUTHORIZATION"] = f"Bearer {value}"+ with (+ patch(f"{_API_MODULE}._goal_flow_enabled", return_value=True),+ patch(_GENERATE_PATH) as generate,+ ):+ resp = self.client.post(+ self.draft_url,+ data={"goal": "track my experiment", "monthly_credit_budget": 5000, "experiment_id": experiment_id},+ format="json",+ **headers,+ )++ assert resp.status_code == status.HTTP_400_BAD_REQUEST, resp.json()+ assert resp.json()["attr"] == "experiment_id"+ generate.assert_not_called()+def test_budget_with_the_flag_off_degrades_to_the_legacy_draft(self):# A client/rollout skew (page loaded before the flag flipped off) must not half-apply the# new flow: the request still answers, as a legacy draft with null dials.diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 765a9ef856db..a49c2079b53d 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -2646,6 +2646,12 @@ export interface DraftScannerRequestApi {* @maximum 100000000*/monthly_credit_budget?: number+ /**+ * Goal-based flow only: a launched experiment the person picked for the scanner to watch. The draft is then an `experiment` scanner on it. Ignored without `monthly_credit_budget`.+ * @minimum 1+ * @maximum 2147483647+ */+ experiment_id?: number}/**@@ -2692,8 +2698,6 @@ export interface DraftScannerResponseApi {* @nullable*/credit_limit: number | null- /** Goal-based flow only: the experiment whose participants the draft watches, when the goal named one of the project's launched experiments. Null when it named none. Carried separately from `query`, which never holds an exposure filter. */- experiment_targeting: ScannerExperimentTargetingApi | null/*** Goal-based flow only: recordings a month the drafted scanner is projected to watch under the solved dials. Its credit cost lands at or under `monthly_credit_budget`, except when the budget is below what the minimum sampling rate can reach, where this is the floor and exceeds the budget. Null whenever `sampling_mode` is.* @nullablediff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.tsindex 418aa903aaff..f1cab844762a 100644--- a/products/replay_vision/frontend/generated/api.zod.ts+++ b/products/replay_vision/frontend/generated/api.zod.ts@@ -1293,6 +1293,8 @@ export const visionScannersDraftCreateBodyGoalMax = 2000export const visionScannersDraftCreateBodyMonthlyCreditBudgetMax = 100000000+export const visionScannersDraftCreateBodyExperimentIdMax = 2147483647+export const VisionScannersDraftCreateBody = /* @__PURE__ */ zod.object({goal: zod@@ -1307,6 +1309,14 @@ export const VisionScannersDraftCreateBody = /* @__PURE__ */ zod.describe("Goal-based flow only: credits a month to spend (1 credit = $0.01). The draft picks the `model`, then solves `sampling_mode` and `sampling_rate` so the projected spend lands on this number, and sets `credit_limit` to it as a hard cap. Omitted on the legacy flow, and ignored while the goal-based flow's flag is off for the caller."),+ experiment_id: zod+ .number()+ .min(1)+ .max(visionScannersDraftCreateBodyExperimentIdMax)+ .optional()+ .describe(+ 'Goal-based flow only: a launched experiment the person picked for the scanner to watch. The draft is then an `experiment` scanner on it. Ignored without `monthly_credit_budget`.'+ ),}).describe("Body of POST \/vision\/scanners\/draft\/ — the user's goal, stated in their own words.")diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsxindex 388c14b1edb2..0c8308bbae53 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx@@ -886,6 +886,16 @@ const variantsDecorator = (readout: ExperimentVariantsReadoutApi): ReturnType<ty},})+const runningExperiments = {+ count: 2,+ next: null,+ previous: null,+ results: [+ { id: 11, name: 'AI creation flow', feature_flag: { filters: {} } },+ { id: 12, name: 'Pricing page layout', feature_flag: { filters: {} } },+ ],+}+const meta: Meta = {component: App,title: 'Scenes-App/Replay Vision',@@ -899,6 +909,7 @@ const meta: Meta = {mswDecorator({get: {'/api/projects/:team_id/tags/': ['checkout', 'core flows'],+ '/api/projects/:team_id/experiments/': runningExperiments,'/api/projects/:team_id/vision/scanners/': scanners,'/api/projects/:team_id/vision/scanners/stats/': scannerStats,'/api/projects/:team_id/vision/scanners/creators/': { creators: [alice, bob] },@@ -1950,7 +1961,6 @@ const goalDraft: DraftScannerResponseApi = {sampling_rate: 0.25,model: 'gemini-3-flash-preview',credit_limit: 5000,- experiment_targeting: null,estimated_monthly_observations: 1000,}@@ -1987,7 +1997,7 @@ export const ScannerEditorGoalOverview: StoryObj = {export const ScannerEditorGoalOverviewExperiment: StoryObj = {parameters: {pageUrl: urls.replayVisionScannerOverview('new'),- featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V3]: 'test' },+ featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V3]: 'test', [FEATURE_FLAGS.VISION_EXPERIMENT_SCANNER]: true },},decorators: [mswDecorator({@@ -2022,10 +2032,14 @@ export const ScannerEditorGoalOverviewExperiment: StoryObj = {const draft: DraftScannerResponseApi = {...goalDraft,name: 'New creation flow friction',- description: 'Flags sessions where a participant struggles in the new AI creation flow.',+ description: 'Describes how participants get through the new AI creation flow.',+ scanner_type: 'experiment',scanner_config: {- prompt: 'Did the participant hesitate, backtrack, or give up while describing their goal in the scanner creation flow? Answer yes or no with a one-sentence reason.',- allow_inconclusive: true,+ prompt: 'Watch the scanner creation flow. Note where the participant hesitates, backtracks, or gives up while describing their goal, and how the session ends.',+ length: 'medium',+ experiment_id: 11,+ variants: ['test'],+ balance_variants: true,},rationale:'Your goal is about the new AI creation flow, so this watches only the sessions of people the experiment put in its test variant, on the pages where that flow lives. Struggling looks unremarkable, so it watches all matching replays rather than only the eventful ones.',@@ -2048,7 +2062,6 @@ export const ScannerEditorGoalOverviewExperiment: StoryObj = {},],} as RecordingsQuery,- experiment_targeting: { experiment_id: 11, variant: 'test' },}logic.actions.draftScannerFromGoalSuccess(draft)logic.actions.setScannerValues({@@ -2059,7 +2072,6 @@ export const ScannerEditorGoalOverviewExperiment: StoryObj = {query: draft.query as RecordingsQuery,sampling_mode: draft.sampling_mode as SamplingMode,sampling_rate: draft.sampling_rate ?? 1,- experiment_targeting: draft.experiment_targeting,})return <StoryFn />},@@ -2189,6 +2201,26 @@ export const ScannerEditorGoalFlowBudget: StoryObj = {],}+// "Track an experiment" opened and an experiment picked: the starter lists running experiments and drafts an+// experiment scanner on the one picked.+export const ScannerEditorGoalFlowExperimentPicker: StoryObj = {+ parameters: {+ pageUrl: urls.replayVisionScannerTemplate('new'),+ featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V3]: 'test' },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await userEvent.click(await canvas.findByText('Track an experiment'))+ const picker = await waitFor(() => {+ const button = canvasElement.querySelector('[data-attr="vision-goal-starter-experiment-picker"]')+ expect(button).not.toHaveClass('LemonButton--loading')+ return button as HTMLElement+ })+ await userEvent.click(picker)+ await userEvent.click(await within(document.body).findByText('AI creation flow'))+ },+}+// No free credits left this period, so "Free" is disabled and the budget input shows.export const ScannerEditorGoalFlowFreeCreditsUsed: StoryObj = {parameters: {diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalExperimentStarter.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalExperimentStarter.tsxnew file mode 100644index 000000000000..a4125407dd7d--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalExperimentStarter.tsx@@ -0,0 +1,132 @@+import { useActions, useValues } from 'kea'+import { useEffect, useState } from 'react'++import { IconChevronRight, IconFlask } from '@posthog/icons'+import { LemonButton, LemonInput, LemonSelect } from '@posthog/lemon-ui'++import { cn } from 'lib/utils/css-classes'++import type { ExperimentBasicApi } from 'products/experiments/frontend/generated/api.schemas'++import { experimentScannerPickerLogic } from '../experimentScannerPickerLogic'++export interface ScannerGoalExperimentStarterProps {+ disabledReason: string | null+ onDraft: (goal: string, experimentId: number) => void+}++export function ScannerGoalExperimentStarter({+ disabledReason,+ onDraft,+}: ScannerGoalExperimentStarterProps): JSX.Element | null {+ const { experimentOptions, experimentOptionsLoading, hasLoadedOptions, loadFailed, search } =+ useValues(experimentScannerPickerLogic)+ const { ensureOptionsLoaded, setSearch } = useActions(experimentScannerPickerLogic)+ const [open, setOpen] = useState(false)+ // Kept as the object because a later search can drop the picked experiment from the options.+ const [experiment, setExperiment] = useState<ExperimentBasicApi | null>(null)+ const options =+ experiment && !experimentOptions.some((option) => option.id === experiment.id)+ ? [experiment, ...experimentOptions]+ : experimentOptions++ useEffect(() => {+ ensureOptionsLoaded()+ }, [ensureOptionsLoaded])++ // Hidden until the first load answers, and when the project runs no experiment to pick. A failed load+ // still shows the starter so that opening the menu can retry.+ if (!loadFailed && (!hasLoadedOptions || (!search && options.length === 0))) {+ return null+ }++ return (+ <div className="flex flex-col gap-2">+ <LemonButton+ fullWidth+ icon={<IconFlask />}+ sideIcon={<IconChevronRight className={cn('transition-transform', open && 'rotate-90')} />}+ tooltip="Pick a running experiment and see how people experience each variant"+ disabledReason={disabledReason}+ onClick={() => setOpen(!open)}+ data-attr="vision-goal-starter-experiment"+ >+ Track an experiment+ </LemonButton>+ {open ? (+ <div className="flex flex-col gap-2 pl-8">+ <div className="flex flex-col gap-0.5">+ <span className="text-sm font-semibold">Pick an experiment</span>+ <span className="text-xs text-muted">+ The agent drafts a scanner that watches the people in this experiment and describes how each+ variant plays out for them.+ </span>+ </div>+ <LemonSelect<number>+ fullWidth+ placeholder="Select a running experiment"+ loading={experimentOptionsLoading}+ value={experiment?.id}+ menu={{ onVisibilityChange: (visible) => visible && ensureOptionsLoaded() }}+ options={[+ {+ title: (+ // The menu closes on any click inside it, which would dismiss it when the search box is clicked.+ <div onClick={(e) => e.stopPropagation()}>+ <LemonInput+ type="search"+ size="small"+ fullWidth+ autoFocus+ placeholder="Search experiments"+ value={search}+ onChange={setSearch}+ data-attr="vision-goal-starter-experiment-search"+ />+ </div>+ ),+ // LemonSelect drops a section with no options, and the search box with it.+ options:+ options.length > 0+ ? options.map((option) => ({ value: option.id, label: option.name }))+ : [+ {+ value: 0,+ label: experimentOptionsLoading+ ? 'Searching...'+ : loadFailed+ ? "Couldn't load running experiments"+ : 'No running experiments match your search',+ disabledReason: loadFailed+ ? 'Close and reopen this menu to try again'+ : 'Try a different search',+ },+ ],+ },+ ]}+ onChange={(id) => setExperiment(options.find((option) => option.id === id) ?? null)}+ data-attr="vision-goal-starter-experiment-picker"+ />+ <div className="flex justify-end">+ <LemonButton+ type="primary"+ size="small"+ disabledReason={disabledReason ?? (experiment ? null : 'Select an experiment first')}+ onClick={() => {+ if (experiment) {+ onDraft(+ `Track how people experience the "${experiment.name}" experiment`,+ experiment.id+ )+ }+ }}+ data-attr="vision-goal-starter-experiment-draft"+ >+ Draft my scanner+ </LemonButton>+ </div>+ </div>+ ) : null}+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsxindex 429b36da698a..f8394b49d735 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx@@ -1,10 +1,9 @@import { useActions, useValues } from 'kea'import { useState } from 'react'-import { IconChevronRight, IconFlask, IconPlus, IconSparkles } from '@posthog/icons'+import { IconChevronRight, IconPlus, IconSparkles } from '@posthog/icons'import { LemonButton, LemonInput, LemonSegmentedButton, LemonTextArea } from '@posthog/lemon-ui'-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { PopoverReferenceContext } from 'lib/lemon-ui/Popover/Popover'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'@@ -14,6 +13,7 @@ import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'import { creditsToUsd, formatCreditCount } from '../../utils/credits'import { GoalSpendMode, goalSpendChoice, replayScannerLogic } from '../replayScannerLogic'import { ScannerTemplate, defaultScannerTemplates } from '../scannerTemplates'+import { ScannerGoalExperimentStarter } from './ScannerGoalExperimentStarter'import { ScannerResumeDraftBanner } from './ScannerResumeDraftBanner'import { SCANNER_TEMPLATE_ICONS } from './scannerTemplateIcons'import { startScannerFromTemplate } from './startScannerFromTemplate'@@ -28,6 +28,7 @@ interface PendingDraft {templateKey?: stringbudget: number | undefinedfreeOnly: boolean+ experimentId?: number}/** The goal-based creation flow: a typed goal and a monthly budget on the left, one-click starting@@ -40,7 +41,6 @@ export function ScannerGoalFlow(): JSX.Element {const { draftScannerFromGoal, setGoalDraftInput, setGoalBudgetInput, setGoalSpendMode } = useActions(logic)const { dataProcessingAccepted } = useValues(aiConsentLogic)const { freeCreditsLeft } = useValues(visionQuotaLogic)- const experimentScanners = useFeatureFlag('VISION_EXPERIMENT_SCANNER')// The spend choice is captured with the goal, so a quota that loads while consent is open cannot change it.const [pendingDraft, setPendingDraft] = useState<PendingDraft | null>(null)@@ -58,8 +58,8 @@ export function ScannerGoalFlow(): JSX.Element {const typedGoalDisabledReason =startDisabledReason ?? (!goalDraftInput.trim() ? 'Describe what you want to find out' : null)- const start = (goal: string, templateKey?: string): void => {- const request = { goal, templateKey, budget: spend.budget, freeOnly: spendMode === 'free' }+ const start = (goal: string, templateKey?: string, experimentId?: number): void => {+ const request = { goal, templateKey, budget: spend.budget, freeOnly: spendMode === 'free', experimentId }// Drafting calls an AI endpoint the backend rejects without org consent; interpose the// popover instead of letting the request 400.if (!dataProcessingAccepted) {@@ -68,8 +68,8 @@ export function ScannerGoalFlow(): JSX.Element {}draft(request)}- const draft = ({ goal, templateKey, budget, freeOnly }: PendingDraft): void => {- draftScannerFromGoal(goal, budget, templateKey, freeOnly)+ const draft = ({ goal, templateKey, budget, freeOnly, experimentId }: PendingDraft): void => {+ draftScannerFromGoal(goal, budget, templateKey, freeOnly, experimentId)}const startFromTypedGoal = (): void => {if (!typedGoalDisabledReason) {@@ -225,19 +225,13 @@ export function ScannerGoalFlow(): JSX.Element {{template.goal_question}</LemonButton>))}- {experimentScanners && (- <LemonButton- fullWidth- icon={<IconFlask />}- sideIcon={<IconChevronRight />}- tooltip="Pick a running experiment and compare what people do in each variant"- disabledReason={editDisabledReason}- onClick={() => startScannerFromTemplate(null, 'experiment')}- data-attr="vision-goal-starter-experiment"- >- Watch my experiment- </LemonButton>- )}+ {/* Inside the consent popover's reference, which would give its buttons dropdown arrows. */}+ <PopoverReferenceContext.Provider value={null}>+ <ScannerGoalExperimentStarter+ disabledReason={startDisabledReason}+ onDraft={(goal, experimentId) => start(goal, 'track_experiment', experimentId)}+ />+ </PopoverReferenceContext.Provider></div></div></div>diff --git a/products/replay_vision/frontend/replay_scanners/components/startScannerFromTemplate.ts b/products/replay_vision/frontend/replay_scanners/components/startScannerFromTemplate.tsindex 3611cb1c5760..63cd6183856f 100644--- a/products/replay_vision/frontend/replay_scanners/components/startScannerFromTemplate.ts+++ b/products/replay_vision/frontend/replay_scanners/components/startScannerFromTemplate.ts@@ -4,19 +4,14 @@ import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { urls } from 'scenes/urls'import { replayScannerLogic } from '../replayScannerLogic'-import type { ScannerType } from '../types'import { scannerStartSearchParams } from './scannerStartParams'/** Starts a new scanner from a template, or from scratch when `templateKey` is null, and opens the- * details step. A saved draft would be replaced, so the person confirms that first. A scratch start- * can also preset the type. */-export function startScannerFromTemplate(templateKey: string | null, scannerType?: ScannerType): void {+ * details step. A saved draft would be replaced, so the person confirms that first. */+export function startScannerFromTemplate(templateKey: string | null): void {const logic = replayScannerLogic({ id: 'new' })const start = (): void => {logic.actions.startFromTemplate(templateKey)- if (scannerType) {- logic.actions.setScannerType(scannerType)- }router.actions.push(combineUrl(urls.replayVisionScannerDetails('new'),diff --git a/products/replay_vision/frontend/replay_scanners/experimentScannerPickerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/experimentScannerPickerLogic.test.tsindex 1c2b6e92d34f..1511ebce5c29 100644--- a/products/replay_vision/frontend/replay_scanners/experimentScannerPickerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/experimentScannerPickerLogic.test.ts@@ -39,4 +39,25 @@ describe('experimentScannerPickerLogic', () => {expect(logic.values.experimentOptions.map((experiment) => experiment.id)).toEqual([1])})++ it('loads again on the next ensure after a failed load', async () => {+ let calls = 0+ useMocks({+ get: {+ '/api/projects/:team/experiments/': () => {+ calls += 1+ return calls === 1 ? [500, {}] : [200, { results: [{ id: 1, name: 'Checkout redesign' }] }]+ },+ },+ })+ const logic = experimentScannerPickerLogic()+ logic.mount()++ await expectLogic(logic, () => logic.actions.ensureOptionsLoaded()).toFinishAllListeners()+ expect(logic.values.loadFailed).toBe(true)++ await expectLogic(logic, () => logic.actions.ensureOptionsLoaded()).toFinishAllListeners()+ expect(logic.values.loadFailed).toBe(false)+ expect(logic.values.experimentOptions.map((experiment) => experiment.id)).toEqual([1])+ })})diff --git a/products/replay_vision/frontend/replay_scanners/experimentScannerPickerLogic.ts b/products/replay_vision/frontend/replay_scanners/experimentScannerPickerLogic.tsindex ac356aadea0b..9e6c8600a580 100644--- a/products/replay_vision/frontend/replay_scanners/experimentScannerPickerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/experimentScannerPickerLogic.ts@@ -16,6 +16,7 @@ export interface experimentScannerPickerLogicValues {experimentOptions: ExperimentBasicApi[]experimentOptionsLoading: booleanhasLoadedOptions: boolean+ loadFailed: booleansearch: string}@@ -72,6 +73,10 @@ export const experimentScannerPickerLogic = kea<experimentScannerPickerLogicTypereducers({search: ['', { setSearch: (_: string, { search }: { search: string }) => search }],hasLoadedOptions: [false, { loadOptionsSuccess: () => true }],+ loadFailed: [+ false,+ { loadOptions: () => false, loadOptionsSuccess: () => false, loadOptionsFailure: () => true },+ ],}),loaders(({ values }) => ({@@ -106,7 +111,7 @@ export const experimentScannerPickerLogic = kea<experimentScannerPickerLogicTypeactions.loadOptions({ debounce: true })},ensureOptionsLoaded: () => {- if (!values.hasLoadedOptions && !values.experimentOptionsLoading) {+ if ((!values.hasLoadedOptions || values.loadFailed) && !values.experimentOptionsLoading) {actions.loadOptions({ debounce: false })}},diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex cd5c2596470c..e932c132a6c0 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -357,46 +357,66 @@ describe('replayScannerLogic', () => {})// The experiment is not part of the query, so the form is its only carrier: dropped here, the- // saved scanner watches every visitor of the drafted pages instead of the participants. The- // API refuses new legacy targeting, so either draft shape must become the experiment type.+ // saved scanner watches every visitor of the drafted pages instead of the participants.it.each([{- shape: 'legacy targeting on another type',- scanner_type: 'classifier',- scanner_config: { prompt: 'Describe the friction.', tags: ['smooth'], multi_label: false },- experiment_targeting: { experiment_id: 11, variant: 'test' },+ experimentScanners: true,+ expected: {+ scanner_type: 'experiment',+ scanner_config: { prompt: 'Describe the friction.', experiment_id: 11, variants: ['test'] },+ experiment_targeting: null,+ },},{- shape: 'the experiment type',- scanner_type: 'experiment',- scanner_config: { prompt: 'Describe the friction.', experiment_id: 11, variants: ['test'] },- experiment_targeting: null,- },- ])('carries the drafted experiment onto the form from $shape', async (draft) => {- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.VISION_EXPERIMENT_SCANNER]: true })- draftSpy.mockReturnValue([- 200,- {- name: 'New entrypoint friction',- description: 'Describes friction in the new entrypoint.',- rationale: '',- query: null,- scanner_type: draft.scanner_type,- scanner_config: draft.scanner_config,- experiment_targeting: draft.experiment_targeting,+ experimentScanners: false,+ expected: {+ scanner_type: 'summarizer',+ scanner_config: { prompt: 'Describe the friction.', length: 'medium' },+ experiment_targeting: { experiment_id: 11, variant: 'test' },},- ])+ },+ ])(+ 'carries a drafted experiment scanner onto the form, experiment scanners $experimentScanners',+ async ({ experimentScanners, expected }) => {+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.VISION_EXPERIMENT_SCANNER]: experimentScanners,+ })+ draftSpy.mockReturnValue([+ 200,+ {+ name: 'New entrypoint friction',+ description: 'Describes friction in the new entrypoint.',+ rationale: '',+ query: null,+ scanner_type: 'experiment',+ scanner_config: {+ prompt: 'Describe the friction.',+ length: 'medium',+ experiment_id: 11,+ variants: ['test'],+ balance_variants: true,+ },+ },+ ])+ router.actions.push(urls.replayVisionScannerTemplate('new'))++ await expectLogic(logic, () =>+ logic.actions.draftScannerFromGoal('friction in the new AI entrypoint')+ ).toFinishAllListeners()++ expect(logic.values.scanner).toMatchObject(expected)+ }+ )++ it('sends the experiment the person picked with a goal-flow draft', async () => {router.actions.push(urls.replayVisionScannerTemplate('new'))await expectLogic(logic, () =>- logic.actions.draftScannerFromGoal('friction in the new AI entrypoint')+ logic.actions.draftScannerFromGoal('Track the checkout test', 500, 'track_experiment', false, 11)).toFinishAllListeners()- expect(logic.values.scanner).toMatchObject({- scanner_type: 'experiment',- scanner_config: { prompt: 'Describe the friction.', experiment_id: 11, variants: ['test'] },- experiment_targeting: null,- })+ const { request } = (draftSpy.mock.calls as unknown as [{ request: Request }][])[0][0]+ expect(await request.json()).toMatchObject({ monthly_credit_budget: 500, experiment_id: 11 })})// Until the flag is on for a team, the prefill stays legacy targeting on the drafted type.diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex b41984215ea3..dc708b59d7bc 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -210,16 +210,12 @@ function goalFlowEnabled(): boolean {return featureFlagLogic.values.featureFlags[FEATURE_FLAGS.VISION_GOAL_FLOW_V3] === 'test'}-/** The experiment a goal draft named, in the experiment type's config or in the legacy targeting. */function draftExperimentScope(goalDraft: DraftScannerResponseApi): ScannerExperimentScope | null {- if (goalDraft.scanner_type === 'experiment') {- const config = goalDraft.scanner_config as ExperimentScannerConfig- return config.experiment_id ? { experimentId: config.experiment_id, variants: config.variants ?? null } : null- }- const targeting = goalDraft.experiment_targeting- return targeting?.experiment_id- ? { experimentId: targeting.experiment_id, variants: targeting.variant ? [targeting.variant] : null }- : null+ if (goalDraft.scanner_type !== 'experiment') {+ return null+ }+ const config = goalDraft.scanner_config as ExperimentScannerConfig+ return config.experiment_id ? { experimentId: config.experiment_id, variants: config.variants ?? null } : null}/** A draft that watches an experiment becomes the experiment type, keeping the drafted prompt as its focus. */@@ -255,6 +251,21 @@ function draftScannerTypeAndConfig(}}+/** Without the experiment type, a drafted experiment scanner becomes the summarizer it is built on, and its+ * experiment moves to legacy targeting. */+function legacyDraftTypeAndConfig(+ goalDraft: DraftScannerResponseApi+): Pick<ScannerFormValues, 'scanner_type' | 'scanner_config'> {+ if (goalDraft.scanner_type !== 'experiment') {+ return {+ scanner_type: goalDraft.scanner_type as ScannerType,+ scanner_config: goalDraft.scanner_config as ScannerConfig,+ } as Pick<ScannerFormValues, 'scanner_type' | 'scanner_config'>+ }+ const config = goalDraft.scanner_config as ExperimentScannerConfig+ return { scanner_type: 'summarizer', scanner_config: { prompt: config.prompt, length: config.length ?? 'medium' } }+}+function omitQuery(scanner: ReplayScanner): Omit<ReplayScanner, 'query'> {const { query: _query, ...rest } = scannerreturn rest@@ -605,8 +616,10 @@ export interface replayScannerLogicActions {goal: string,monthlyCreditBudget?: number,templateKey?: string,- freeOnly?: boolean+ freeOnly?: boolean,+ experimentId?: number) => {+ experimentId: number | undefinedfreeOnly: booleangoal: stringgoalFlow: boolean@@ -623,6 +636,7 @@ export interface replayScannerLogicActions {draftScannerFromGoalSuccess: (goalDraft: DraftScannerResponseApi | null,payload?: {+ experimentId: number | undefinedfreeOnly: booleangoal: stringgoalFlow: boolean@@ -632,6 +646,7 @@ export interface replayScannerLogicActions {) => {goalDraft: DraftScannerResponseApi | nullpayload?: {+ experimentId: number | undefinedfreeOnly: booleangoal: stringgoalFlow: boolean@@ -1056,12 +1071,14 @@ export const replayScannerLogic = kea<replayScannerLogicType>([goal: string,monthlyCreditBudget?: number,templateKey?: string,- freeOnly?: boolean+ freeOnly?: boolean,+ experimentId?: number) => ({goal,monthlyCreditBudget,templateKey,freeOnly: freeOnly ?? false,+ experimentId,// Read when the request starts, so a flag refresh while it runs cannot change what the result saves.goalFlow: monthlyCreditBudget != null && goalFlowEnabled(),}),@@ -1297,7 +1314,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([null as DraftScannerResponseApi | null,{// Errors surface through draftScannerFromGoalFailure; kea-loaders dispatches it for us.- draftScannerFromGoal: async ({ goal, monthlyCreditBudget }) => {+ draftScannerFromGoal: async ({ goal, monthlyCreditBudget, experimentId }) => {const teamId = teamLogic.values.currentTeamIdif (!teamId || !goal.trim()) {return values.goalDraft@@ -1305,7 +1322,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([return await visionScannersDraftCreate(String(teamId), {goal: goal.trim(),...(typeof monthlyCreditBudget === 'number' && monthlyCreditBudget > 0- ? { monthly_credit_budget: monthlyCreditBudget }+ ? { monthly_credit_budget: monthlyCreditBudget, experiment_id: experimentId }: {}),})},@@ -2372,10 +2389,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([description: goalDraft.description,...(asExperimentScanner? draftScannerTypeAndConfig(goalDraft, draftedExperiment, context)- : {- scanner_type: goalDraft.scanner_type as ScannerType,- scanner_config: goalDraft.scanner_config as ScannerConfig,- }),+ : legacyDraftTypeAndConfig(goalDraft)),// The drafted session filter (when the goal mapped to real screens or events); the// triggers step shows it for review like any hand-picked filter. Under an// experiment prefill it keeps that experiment's test-account setting.@@ -2405,7 +2419,14 @@ export const replayScannerLogic = kea<replayScannerLogicType>([// named (or the one the wizard was entered from) stays legacy targeting.experiment_targeting: asExperimentScanner? null- : (goalDraft.experiment_targeting ?? (context ? buildExperimentTargeting(context) : null)),+ : draftedExperiment+ ? {+ experiment_id: draftedExperiment.experimentId,+ variant: draftedExperiment.variants?.[0] ?? null,+ }+ : context+ ? buildExperimentTargeting(context)+ : null,})// Loads the experiment so the editor shows its name and variants, the same way it// does for a scanner started from the experiment itself.diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yamlindex 87ea92631833..155e2926c5cc 100644--- a/products/replay_vision/mcp/tools.yaml+++ b/products/replay_vision/mcp/tools.yaml@@ -622,8 +622,9 @@ tools:onboarding"). Nothing is saved. Returns `name`, `description`, `scanner_type`, `scanner_config`, `query` anda `rationale` addressed to the person. When `monthly_credit_budget` is honored the draft also picks`sampling_mode`, `sampling_rate`, `model` and `credit_limit` to fit the budget; otherwise those come back- null. Review the draft with the person, then pass it to `vision-scanners-create`. The call is an inline LLM- request and can take a while.+ null. A draft that watches an experiment comes back as an `experiment` scanner; with a budget, pass+ `experiment_id` to draft one on a launched experiment the person picked. Review the draft with the person,+ then pass it to `vision-scanners-create`. The call is an inline LLM request and can take a while.requires_ai_consent: truevision-scanners-duplicate:operation: vision_scanners_duplicate_creatediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 6ec0ad6cf0e6..9168c1c2285c 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -13980,7 +13980,7 @@}},"vision-scanners-draft": {- "description": "Draft a full scanner configuration from a natural-language `goal` (e.g. \"find where users get stuck during onboarding\"). Nothing is saved. Returns `name`, `description`, `scanner_type`, `scanner_config`, `query` and a `rationale` addressed to the person. When `monthly_credit_budget` is honored the draft also picks `sampling_mode`, `sampling_rate`, `model` and `credit_limit` to fit the budget; otherwise those come back null. Review the draft with the person, then pass it to `vision-scanners-create`. The call is an inline LLM request and can take a while.",+ "description": "Draft a full scanner configuration from a natural-language `goal` (e.g. \"find where users get stuck during onboarding\"). Nothing is saved. Returns `name`, `description`, `scanner_type`, `scanner_config`, `query` and a `rationale` addressed to the person. When `monthly_credit_budget` is honored the draft also picks `sampling_mode`, `sampling_rate`, `model` and `credit_limit` to fit the budget; otherwise those come back null. A draft that watches an experiment comes back as an `experiment` scanner; with a budget, pass `experiment_id` to draft one on a launched experiment the person picked. Review the draft with the person, then pass it to `vision-scanners-create`. The call is an inline LLM request and can take a while.","category": "Replay vision","feature": "replay_vision","summary": "Draft scanner from goal",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 5c411bb85c13..ccde7b646b62 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -14655,7 +14655,7 @@}},"vision-scanners-draft": {- "description": "Draft a full scanner configuration from a natural-language `goal` (e.g. \"find where users get stuck during onboarding\"). Nothing is saved. Returns `name`, `description`, `scanner_type`, `scanner_config`, `query` and a `rationale` addressed to the person. When `monthly_credit_budget` is honored the draft also picks `sampling_mode`, `sampling_rate`, `model` and `credit_limit` to fit the budget; otherwise those come back null. Review the draft with the person, then pass it to `vision-scanners-create`. The call is an inline LLM request and can take a while.",+ "description": "Draft a full scanner configuration from a natural-language `goal` (e.g. \"find where users get stuck during onboarding\"). Nothing is saved. Returns `name`, `description`, `scanner_type`, `scanner_config`, `query` and a `rationale` addressed to the person. When `monthly_credit_budget` is honored the draft also picks `sampling_mode`, `sampling_rate`, `model` and `credit_limit` to fit the budget; otherwise those come back null. A draft that watches an experiment comes back as an `experiment` scanner; with a budget, pass `experiment_id` to draft one on a launched experiment the person picked. Review the draft with the person, then pass it to `vision-scanners-create`. The call is an inline LLM request and can take a while.","category": "Replay vision","feature": "replay_vision","summary": "Draft scanner from goal",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 43de75d9c065..02c3b1ad0cd3 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -38118,6 +38118,12 @@ export namespace Schemas {* @maximum 100000000*/monthly_credit_budget?: number;+ /**+ * Goal-based flow only: a launched experiment the person picked for the scanner to watch. The draft is then an `experiment` scanner on it. Ignored without `monthly_credit_budget`.+ * @minimum 1+ * @maximum 2147483647+ */+ experiment_id?: number;}/**@@ -38134,25 +38140,6 @@ export namespace Schemas {Comprehensive: 'comprehensive',} as const;- /**- * The experiment a scanner watches. Scans derive their person-scoped exposure filter from- * this blob at query time, so it is the only place an experiment can enter a scanner's- * targeting — which is what lets the write-side access check and read-side redaction cover it.- */- export interface ScannerExperimentTargeting {- /**- * The experiment the scanner watches.- * @minimum 1- */- experiment_id: number;- /**- * Narrow to sessions of people exposed to this variant. Null means every variant.- * @maxLength 400- * @nullable- */- variant?: string | null;- }-/*** An AI-drafted scanner configuration, ready to seed the creation wizard. Nothing is persisted.*/@@ -38197,8 +38184,6 @@ export namespace Schemas {* @nullable*/credit_limit: number | null;- /** Goal-based flow only: the experiment whose participants the draft watches, when the goal named one of the project's launched experiments. Null when it named none. Carried separately from `query`, which never holds an exposure filter. */- experiment_targeting: ScannerExperimentTargeting | null;/*** Goal-based flow only: recordings a month the drafted scanner is projected to watch under the solved dials. Its credit cost lands at or under `monthly_credit_budget`, except when the budget is below what the minimum sampling rate can reach, where this is the floor and exceeds the budget. Null whenever `sampling_mode` is.* @nullable@@ -42137,6 +42122,25 @@ export namespace Schemas {variants?: string[] | null;}+ /**+ * The experiment a scanner watches. Scans derive their person-scoped exposure filter from+ * this blob at query time, so it is the only place an experiment can enter a scanner's+ * targeting — which is what lets the write-side access check and read-side redaction cover it.+ */+ export interface ScannerExperimentTargeting {+ /**+ * The experiment the scanner watches.+ * @minimum 1+ */+ experiment_id: number;+ /**+ * Narrow to sessions of people exposed to this variant. Null means every variant.+ * @maxLength 400+ * @nullable+ */+ variant?: string | null;+ }+/*** Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config.*/diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.tsindex eca933b3d100..a9a7fecb170a 100644--- a/services/mcp/src/generated/replay_vision/api.ts+++ b/services/mcp/src/generated/replay_vision/api.ts@@ -2065,6 +2065,8 @@ export const visionScannersDraftCreateBodyGoalMax = 2000export const visionScannersDraftCreateBodyMonthlyCreditBudgetMax = 100000000+export const visionScannersDraftCreateBodyExperimentIdMax = 2147483647+export const VisionScannersDraftCreateBody = () => zod.object({goal: zod@@ -2079,6 +2081,14 @@ export const VisionScannersDraftCreateBody = () => zod.describe("Goal-based flow only: credits a month to spend (1 credit = $0.01). The draft picks the `model`, then solves `sampling_mode` and `sampling_rate` so the projected spend lands on this number, and sets `credit_limit` to it as a hard cap. Omitted on the legacy flow, and ignored while the goal-based flow's flag is off for the caller."),+ experiment_id: zod+ .number()+ .min(1)+ .max(visionScannersDraftCreateBodyExperimentIdMax)+ .optional()+ .describe(+ 'Goal-based flow only: a launched experiment the person picked for the scanner to watch. The draft is then an `experiment` scanner on it. Ignored without `monthly_credit_budget`.'+ ),}).describe("Body of POST \/vision\/scanners\/draft\/ — the user's goal, stated in their own words.")diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.tsindex 120e6746a80b..98f071d994d0 100644--- a/services/mcp/src/tools/generated/replay_vision.ts+++ b/services/mcp/src/tools/generated/replay_vision.ts@@ -1023,6 +1023,9 @@ const visionScannersDraft = (): ToolBase<if (params.monthly_credit_budget !== undefined) {body['monthly_credit_budget'] = params.monthly_credit_budget}+ if (params.experiment_id !== undefined) {+ body['experiment_id'] = params.experiment_id+ }const result = await context.api.request<Schemas.DraftScannerResponse>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/draft/`,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-draft.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-draft.jsonindex 815e1b10c6fc..227918c6d91b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-draft.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-draft.json@@ -2,6 +2,12 @@"$schema": "https://json-schema.org/draft/2020-12/schema","description": "Body of POST /vision/scanners/draft/ — the user's goal, stated in their own words.","properties": {+ "experiment_id": {+ "description": "Goal-based flow only: a launched experiment the person picked for the scanner to watch. The draft is then an `experiment` scanner on it. Ignored without `monthly_credit_budget`.",+ "maximum": 2147483647,+ "minimum": 1,+ "type": "number"+ },"goal": {"description": "What the user wants to accomplish, e.g. 'find out where users get stuck during onboarding'.","maxLength": 2000,