: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): goal flow with one-click starting points (#109781)
Tue Haulunda8f8070a6dd6
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex b12c78555e44..dbab9d572963 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -12111,21 +12111,21 @@ 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.4f713baaac755abc276c4b8c73ef52a9e7d782d5daa7a3ecfe85da78c42c0b24.cCsTK5Amd519GiU8JGw5K4KufEBosM1gSXzOssc65mU+ hash: v1.k794b7964.0e217111dad1655b8f29f92a117fe21859397c6e17608bc983c5b3150ab51aa1.YgSqbOV1H2Sz19D2DInvsCtf3254tssxpOMLeZ6FfoIscenes-app-replay-vision--scanner-editor-goal-flow--light:- hash: v1.k794b7964.4e016e86a155fea0300d1c6fec4e4d2d11c4502f9865ece9839056862b8e79fc.imLVOUpY09Gjo2rHMmKHmmu1D0OR_PzdSsQWaPgmOks+ hash: v1.k794b7964.65daabfa43c8af10372bed7d82dbb917a2e06f5b38b515d1588941459211ebae.W6hkdSVsuAiuxpkdBDCxgtYgTxMNrlFR4uPuaDql7xsscenes-app-replay-vision--scanner-editor-goal-overview--dark:- hash: v1.k794b7964.4ef60f727ace235099b7180e0b8e6e96a81e3626ce2ccae46f74c29508f85c15.Mp6FnYUKmqMQBB2sni9IukHvqlxQSXt5l1F91H6F8Zg+ hash: v1.k794b7964.e6714595ba0ce82b0d2120120327e228824680238b822730da5737b64ca1377b.l4FiR3KFlfqccQNVs7_oxpENN8I0TGebcifFQU64ND4scenes-app-replay-vision--scanner-editor-goal-overview--light:- hash: v1.k794b7964.2820672a63528051df5cbb805e984c645eaf35a5f3437b59eaa70e90f1a5f118.S63d60T6vwVkop1Z_-KvK0rTZiRymODAiDvjaaJD7Do+ hash: v1.k794b7964.1df9b72547fe7a33557154c0cdecca42849523ee3930aa02eaf674a99ff688b0.nCG6Ar0h6d71Y-exUY6xM4PYlI1RxHshkWu-f1IVTrIscenes-app-replay-vision--scanner-editor-goal-overview-experiment--dark:hash: v1.k794b7964.bb23ed20fa34a412db9228dba2790feb2f2f4ea9a39353c5cf86db21e853746b.0kjhA7cqYlnGm1XT6TDODIphKatHsAykS0i3PVy7s4Iscenes-app-replay-vision--scanner-editor-goal-overview-experiment--light:hash: v1.k794b7964.6eaedf34e715312cbca9d79b2d6e634630338edd3c75e54410f41f4ea633b1bd.vVF1dO7E1KQN60xV05xwLEBhM2_mwDB6rfPNDFLzPA4scenes-app-replay-vision--scanner-editor-goal-overview-loading--dark:- hash: v1.k794b7964.7230ea3eab0869f5a8f86849383f3e04194551a3afcc074a50b1397b46a2b375.zj1EqjarBjVHCpotlMJ9paSjR9AuCTzOUFbMGckAQBY+ hash: v1.k794b7964.99201d1fcc588f17814fd36d77580993ae1af5aa4d0a61936b13be79fafbe826.2zmd7lGjTNlYy2ES__K7YR9BjisPNV3JWXMZICO6Rfcscenes-app-replay-vision--scanner-editor-goal-overview-loading--light:- hash: v1.k794b7964.0d734d87e1105b4e24c9bb56cda230512228305903f7011d87565a9e8eccd3a7.A5dFxW7Ss-kphe3r11EfHJQgb5X8nxEjOLGxPya1BD8+ hash: v1.k794b7964.5582e18627bc245ef9e9e85502d1d40afe8ec06e02d5f1f4410b795c97a69616.YkMhLUMo3Cn-ms_UNLkc94JjUFg3myjXCZnyZGzY9Qoscenes-app-replay-vision--scanner-editor-triggers--dark:hash: v1.k794b7964.5bc5dc77d7346163d92585657a949d38938bdbabf11a2a0341bc3a6b9c980c80.AL7y75QUTSwtUvG6XKJvD4CPhbEXC4TmNPkxG_57CQ4scenes-app-replay-vision--scanner-editor-triggers--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 14b7b1eb1305..d526299bcf92 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -570,7 +570,7 @@ export const FEATURE_FLAGS = {VISION_ENTRYPOINT_ERROR_TRACKING: 'vision-entrypoint-error-tracking', // owner: #team-replay, cross-sell entry point from the error tracking issue recording tabVISION_ENTRYPOINT_EXPERIMENTS: 'vision-entrypoint-experiments', // owner: #team-replay, cross-sell entry points from experimentsVISION_ENTRYPOINT_REPLAY_FILTERS: 'vision-entrypoint-replay-filters', // owner: #team-replay, cross-sell entry point from the replay filters panel- VISION_GOAL_BASED_CREATION_FLOW: 'vision-goal-based-creation-flow', // owner: #team-replay multivariate=control,test — gate on === 'test'; a truthy check turns on for control too+ VISION_GOAL_FLOW_V2: 'vision-goal-flow-v2', // owner: #team-replay multivariate=control,test — gate on === 'test'; a truthy check turns on for control tooVISUAL_REVIEW: 'visual-review', // owner: #team-devexWAREHOUSE_MULTI_DESTINATION: 'warehouse-multi-destination', // owner: #team-warehouse-sourcesWAREHOUSE_PERSON_PROPERTIES: 'warehouse-person-properties', // owner: @tomowers #team-warehouse-sources, gates warehouse -> person properties (person-target custom property sources)diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 7a362ba6c44f..8f64733f7aa6 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -118,7 +118,11 @@ from products.replay_vision.backend.models.replay_scanner import (ScannerType,apply_experiment_targeting,)-from products.replay_vision.backend.prompt_questions import question_fields_for_save, scanner_question+from products.replay_vision.backend.prompt_questions import (+ question_fields_for_save,+ scanner_question,+ template_question,+)from products.replay_vision.backend.queries import (ESTIMATE_STALE_AFTER,MIN_SAMPLING_RATE,@@ -175,7 +179,7 @@ _QUERY_FIELDS_TO_STRIP = ("date_from", "date_to")# The goal-based creation flow's flag. Multivariate so it can graduate to an experiment without a# rename; server-side so a client/rollout skew cannot half-apply the new flow.-GOAL_FLOW_FLAG = "vision-goal-based-creation-flow"+GOAL_FLOW_FLAG = "vision-goal-flow-v2"class ScannerCreationMethod(models.TextChoices):@@ -325,6 +329,9 @@ def scanner_lifecycle_properties(scanner: ReplayScanner) -> dict[str, Any]:# separate flag keeps experiment-scoped scanners countable apart from hand-filtered ones."has_filters": any(query.get(key) for key in _QUERY_FILTER_KEYS) or bool(scanner.experiment_targeting),"has_experiment_targeting": bool(scanner.experiment_targeting),+ # True when the prompt is a stock template's word for word, so a creation-flow experiment can+ # tell a scanner tailored to the team from a template saved with its defaults.+ "uses_template_prompt": template_question(scanner.scanner_config) is not None,"estimated_monthly_observations": estimate,"estimated_monthly_credits": (estimate * observation_credits_for_model(scanner.model) if estimate is not None else None@@ -478,6 +485,16 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerialchoices=ScannerType.choices,help_text="What the scanner does: monitor, classifier, scorer, or summarizer.",)+ goal = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ max_length=2000,+ help_text=(+ "The goal an AI draft was built from, in the creator's own words, so the scanner keeps "+ "what it was meant to find. Set on create only and ignored on update."+ ),+ )creation_method = serializers.ChoiceField(choices=ScannerCreationMethod.choices,required=False,@@ -649,6 +666,7 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial"description","tags","scanner_type",+ "goal","creation_method","scanner_config","prompt_question",@@ -955,6 +973,8 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial# A scanner is built once, so this says nothing about an edit. Dropped here because the UI# PATCHes the whole form back and would otherwise send it into the getattr diff below.validated_data.pop("creation_method", None)+ # The goal records what the scanner was first built for, so an edit never rewrites it.+ validated_data.pop("goal", None)# Compared as tagify()d names, since that is what set_tags_on_object stores.tags_changed = tags is not None and {tagify(t) for t in tags} != set(instance.tagged_items.values_list("tag__name", flat=True)@@ -1024,7 +1044,7 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial@staticmethoddef _reraise_unique_name_violation(error: IntegrityError) -> NoReturn:# Narrow to the unique-name constraint so other future constraints aren't mis-reported as duplicates.- if "replay_scanner_unique_team_name" in str(error):+ if "replay_scanner_unique_configured_team_name" in str(error):raise serializers.ValidationError({"name": "A scanner with this name already exists in this team."})raise errordiff --git a/products/replay_vision/backend/migrations/0102_replayscanner_goal.py b/products/replay_vision/backend/migrations/0102_replayscanner_goal.pynew file mode 100644index 000000000000..5ce753a8a4c4--- /dev/null+++ b/products/replay_vision/backend/migrations/0102_replayscanner_goal.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.17 on 2026-10-01 09:20++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("replay_vision", "0101_replayscanner_prompt_question"),+ ]++ operations = [+ migrations.AddField(+ model_name="replayscanner",+ name="goal",+ field=models.TextField(+ blank=True,+ help_text="The goal the creator typed or picked when an AI draft built this scanner, kept as written. Null for scanners built any other way.",+ null=True,+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txtindex 0f745e2b9c69..c53178338ca3 100644--- a/products/replay_vision/backend/migrations/max_migration.txt+++ b/products/replay_vision/backend/migrations/max_migration.txt@@ -1 +1 @@-0101_replayscanner_prompt_question+0102_replayscanner_goaldiff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.pyindex 292428c85eab..64aee0d3e359 100644--- a/products/replay_vision/backend/models/replay_scanner.py+++ b/products/replay_vision/backend/models/replay_scanner.py@@ -132,6 +132,11 @@ class ReplayScanner(Taggable, ModelActivityMixin, UUIDModel):default="",help_text="Free-form description for the scanner management UI. Not used by the model.",)+ goal = models.TextField(+ null=True,+ blank=True,+ help_text="The goal the creator typed or picked when an AI draft built this scanner, kept as written. Null for scanners built any other way.",+ )scanner_type = models.CharField(max_length=32, choices=ScannerType.choices)scanner_config = models.JSONField(default=dict, help_text="Type-specific configuration; always includes `prompt`.")diff --git a/products/replay_vision/backend/scanner_draft.py b/products/replay_vision/backend/scanner_draft.pyindex 872cc7cbee92..ec0b9269cd24 100644--- a/products/replay_vision/backend/scanner_draft.py+++ b/products/replay_vision/backend/scanner_draft.py@@ -11,6 +11,7 @@ re-validates everything on save.import reimport uuid+import itertoolsfrom collections.abc import Collection, Sequencefrom dataclasses import dataclass, replacefrom typing import Any, Literal, cast@@ -82,10 +83,11 @@ _SCALE_SPAN_ALLOWED = 100# CoreMemory.text is model-capped at 10k chars; cap lower to keep the one-shot draft prompt lean._MAX_BUSINESS_CONTEXT_CHARS = 5_000# Thinking tokens are drawn from this same budget, and a vague goal makes the model deliberate far-# longer than it writes: at 4096 the JSON was being cut off mid-object after only ~150 tokens of-# answer. Doubling it clears that while staying well inside `_MODEL_CALL_TIMEOUT_MS` — a budget the-# model cannot exhaust before the request times out just trades a quick failure for a slow one.-_MAX_OUTPUT_TOKENS = 8192+# longer than it writes: the answer itself stays under ~1k tokens, so a cut-off draft is the+# reasoning running out of room.+# A budget the model cannot exhaust before `_MODEL_CALL_TIMEOUT_MS` just trades a quick failure for+# a slow one, so raise the timeout with it if drafts start timing out instead.+_MAX_OUTPUT_TOKENS = 16_384# Bounds on assembled context so a scanner-heavy team can't blow up the prompt._MAX_EXISTING_SCANNERS = 15_SCANNER_GIST_CHARS = 200@@ -410,6 +412,26 @@ def _existing_scanners(team: Team, user_access_control: UserAccessControl) -> lireturn out+def _free_scanner_name(team_id: int, name: str) -> str:+ """The drafted name, or the first free "<name> (n)" when the team already has a scanner by that name.++ Names are unique per team, so a taken name would fail only at save, after the person reviewed the+ draft. Checked against every configured scanner, not only the ones the caller can read, because the+ constraint covers them all.+ """+ # The stem leaves room for a " (n)" suffix, so a candidate cut to fit the column is still checked.+ stem = name[: _MAX_NAME_LENGTH - 10]+ taken = set(ReplayScanner.objects.filter(team_id=team_id, name__startswith=stem).values_list("name", flat=True))+ if name not in taken:+ return name+ for n in itertools.count(2):+ suffix = f" ({n})"+ candidate = name[: _MAX_NAME_LENGTH - len(suffix)] + suffix+ if candidate not in taken:+ return candidate+ raise AssertionError("unreachable")++def _head_and_tail(text: str, cap: int) -> str:"""Memory facts are appended chronologically, so a head-only slice would drop the newest ones.Keep both ends, like CoreMemory.formatted_text does."""@@ -574,7 +596,8 @@ 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, allowed_screens=taxonomy.screens, allowed_events=events, team_id=team.id)+ draft = _finalize(parsed, allowed_screens=taxonomy.screens, allowed_events=events, team_id=team.id)+ return replace(draft, name=_free_scanner_name(team.id, draft.name))def _hit_output_cap(response: GenerateContentResponse) -> bool:@@ -1921,7 +1944,7 @@ def draft_scanner_from_goal_v2()# 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.- draft = replace(draft, credit_limit=monthly_credit_budget)+ draft = replace(draft, name=_free_scanner_name(team.id, draft.name), credit_limit=monthly_credit_budget)try:solution = _solve_budget(diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 6789939e46c9..928d4f5a8cd0 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -6,7 +6,7 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import MagicMock, patchfrom django.core.cache import cache-from django.db import connection+from django.db import IntegrityError, connection, transactionfrom django.test import SimpleTestCase, override_settingsfrom django.test.utils import CaptureQueriesContextfrom django.utils import timezone@@ -242,6 +242,35 @@ class TestReplayScannerViewSet(_VisionAPITestCase):)self.assertEqual(resp.status_code, 400)+ def test_unique_name_clash_at_the_database_is_a_name_error(self) -> None:+ self._create_scanner(name="dup")+ with self.assertRaises(IntegrityError) as clash, transaction.atomic():+ self._create_scanner(name="dup")++ with self.assertRaises(DRFValidationError) as raised:+ ReplayScannerSerializer._reraise_unique_name_violation(clash.exception)+ self.assertIn("name", cast(dict, raised.exception.detail))++ def test_goal_is_kept_on_create_and_ignored_on_update(self) -> None:+ resp = self.client.post(+ self.scanners_url,+ data={+ "name": "with-goal",+ "goal": "find where people give up in billing",+ "scanner_type": ScannerType.MONITOR,+ "scanner_config": {"prompt": "p"},+ "model": ScannerModel.GEMINI_3_8_FLASH,+ },+ format="json",+ )+ self.assertEqual(resp.status_code, 201, resp.json())+ scanner_id = resp.json()["id"]++ patch_resp = self.client.patch(f"{self.scanners_url}{scanner_id}/", data={"goal": "rewritten"}, format="json")++ self.assertEqual(patch_resp.status_code, 200, patch_resp.json())+ self.assertEqual(ReplayScanner.objects.get(id=scanner_id).goal, "find where people give up in billing")+def test_list_returns_only_team_scanners(self) -> None:self._create_scanner(name="ours")other_org = Organization.objects.create(name="other")@@ -1238,6 +1267,7 @@ class TestScannerLifecycleTelemetry(_VisionAPITestCase):self.assertEqual(properties["sampling_rate"], 0.25)self.assertTrue(properties["has_filters"])self.assertFalse(properties["has_experiment_targeting"])+ self.assertFalse(properties["uses_template_prompt"])self.assertTrue(properties["enabled"])self.assertEqual(properties["organization_id"], str(self.team.organization_id))# Session auth resolves to "web" (the app UI), MCP callers to "mcp".diff --git a/products/replay_vision/backend/tests/test_scanner_draft.py b/products/replay_vision/backend/tests/test_scanner_draft.pyindex 9c2923594e8d..d73f1050b2ee 100644--- a/products/replay_vision/backend/tests/test_scanner_draft.py+++ b/products/replay_vision/backend/tests/test_scanner_draft.py@@ -4,6 +4,7 @@ from unittest.mock import MagicMock, patchfrom django.utils import timezonefrom google.genai.types import FinishReason+from parameterized import parameterizedfrom rest_framework import statusfrom posthog.schema import RecordingsQuery@@ -24,6 +25,7 @@ from products.replay_vision.backend.queries.scanner_volume_estimate import Scannfrom products.replay_vision.backend.queries.visited_paths import VisitedPathfrom products.replay_vision.backend.scanner_draft import (_MAX_BASELINE_EVENTS,+ _MAX_OUTPUT_TOKENS,DraftError,ScannerDraft,_build_user_content,@@ -494,7 +496,7 @@ class TestGenerate:_generate(user_content="goal", team_id=1, distinct_id="u")- assert generate.call_args.kwargs["config"].max_output_tokens == 8192+ assert generate.call_args.kwargs["config"].max_output_tokens == _MAX_OUTPUT_TOKENS@patch("products.replay_vision.backend.scanner_draft.genai.Client")def test_output_cut_off_by_the_token_budget_is_its_own_failure(self, mock_client_cls):@@ -581,6 +583,24 @@ class TestDraftScannerEndpoint(_VisionAPITestCase):"events": [{"id": "checkout_started", "name": "checkout_started", "type": "events", "order": 0}],}+ @parameterized.expand(+ [+ ("free name kept", [], "User intent"),+ ("taken name suffixed", ["User intent"], "User intent (2)"),+ ("next free suffix", ["User intent", "User intent (2)"], "User intent (3)"),+ ]+ )+ @patch(_GENERATE_PATH)+ def test_drafted_name_avoids_existing_scanner_names(self, _name, existing, expected, mock_generate):+ mock_generate.return_value = _draft(name="User intent")+ for name in existing:+ self._create_scanner(name=name, scanner_type=ScannerType.MONITOR, scanner_config={"prompt": "Anything?"})++ resp = self.client.post(self.draft_url, data={"goal": "understand what users come here to do"}, format="json")++ assert resp.status_code == status.HTTP_200_OK, resp.json()+ assert resp.json()["name"] == expected+@patch(_CORE_MEMORY_FLAG_PATH, return_value=False)@patch(_GENERATE_PATH)def test_grounds_the_model_call_in_scanners_and_business_context(self, mock_generate, _flag):diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex e702458459e2..cd3e6b05a74e 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -1085,6 +1085,12 @@ export interface ReplayScannerApi {* * `scorer` - Scorer* * `summarizer` - Summarizer */scanner_type: ScannerTypeEnumApi+ /**+ * The goal an AI draft was built from, in the creator's own words, so the scanner keeps what it was meant to find. Set on create only and ignored on update.+ * @maxLength 2000+ * @nullable+ */+ goal?: string | null/** How the creator built this scanner: from an AI draft, from a template, or from scratch. Reported to product analytics at creation and not stored on the scanner. Independent of any experiment the creator is in, since a person offered the AI flow can still fill the form by hand. Only the app can answer this, so a request from anywhere else reports the calling surface instead of whatever it sends here. Ignored on update.** * `ai` - AI draft@@ -1213,6 +1219,12 @@ export interface PatchedReplayScannerApi {* * `scorer` - Scorer* * `summarizer` - Summarizer */scanner_type?: ScannerTypeEnumApi+ /**+ * The goal an AI draft was built from, in the creator's own words, so the scanner keeps what it was meant to find. Set on create only and ignored on update.+ * @maxLength 2000+ * @nullable+ */+ goal?: string | null/** How the creator built this scanner: from an AI draft, from a template, or from scratch. Reported to product analytics at creation and not stored on the scanner. Independent of any experiment the creator is in, since a person offered the AI flow can still fill the form by hand. Only the app can answer this, so a request from anywhere else reports the calling surface instead of whatever it sends here. Ignored on update.** * `ai` - AI draftdiff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.tsindex c1bba6a3421d..a28064cf00c5 100644--- a/products/replay_vision/frontend/generated/api.zod.ts+++ b/products/replay_vision/frontend/generated/api.zod.ts@@ -486,6 +486,8 @@ export const visionScannersCreateBodyTagsItemMax = 255export const visionScannersCreateBodyTagsMax = 32+export const visionScannersCreateBodyGoalMax = 2000+export const visionScannersCreateBodySamplingRateMin = 0export const visionScannersCreateBodySamplingRateMax = 1@@ -519,6 +521,13 @@ export const VisionScannersCreateBody = /* @__PURE__ */ zod.describe('What the scanner does: monitor, classifier, scorer, or summarizer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'),+ goal: zod+ .string()+ .max(visionScannersCreateBodyGoalMax)+ .nullish()+ .describe(+ "The goal an AI draft was built from, in the creator's own words, so the scanner keeps what it was meant to find. Set on create only and ignored on update."+ ),creation_method: zod.union([zod@@ -626,6 +635,8 @@ export const visionScannersPartialUpdateBodyTagsItemMax = 255export const visionScannersPartialUpdateBodyTagsMax = 32+export const visionScannersPartialUpdateBodyGoalMax = 2000+export const visionScannersPartialUpdateBodySamplingRateMin = 0export const visionScannersPartialUpdateBodySamplingRateMax = 1@@ -661,6 +672,13 @@ export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod.describe('What the scanner does: monitor, classifier, scorer, or summarizer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'),+ goal: zod+ .string()+ .max(visionScannersPartialUpdateBodyGoalMax)+ .nullish()+ .describe(+ "The goal an AI draft was built from, in the creator's own words, so the scanner keeps what it was meant to find. Set on create only and ignored on update."+ ),creation_method: zod.union([zoddiff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsxindex 21756ba3fe67..323adecaa745 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx@@ -1706,12 +1706,12 @@ export const StartupProgramCap: StoryObj = {],}-// The goal-based creation flow when the flag's test variant is on: the two questions (goal, budget)-// lead, with the template gallery kept below them as a start-from-a-template alternative.+// The goal-based creation flow when the flag's test variant is on: a typed goal and budget on the+// left, one-click starting points on the right.export const ScannerEditorGoalFlow: StoryObj = {parameters: {pageUrl: urls.replayVisionScannerTemplate('new'),- featureFlags: { [FEATURE_FLAGS.VISION_GOAL_BASED_CREATION_FLOW]: 'test' },+ featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V2]: 'test' },},}@@ -1749,7 +1749,7 @@ const goalDraft: DraftScannerResponseApi = {export const ScannerEditorGoalOverview: StoryObj = {parameters: {pageUrl: urls.replayVisionScannerOverview('new'),- featureFlags: { [FEATURE_FLAGS.VISION_GOAL_BASED_CREATION_FLOW]: 'test' },+ featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V2]: 'test' },},decorators: [(StoryFn) => {@@ -1777,7 +1777,7 @@ export const ScannerEditorGoalOverview: StoryObj = {export const ScannerEditorGoalOverviewExperiment: StoryObj = {parameters: {pageUrl: urls.replayVisionScannerOverview('new'),- featureFlags: { [FEATURE_FLAGS.VISION_GOAL_BASED_CREATION_FLOW]: 'test' },+ featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V2]: 'test' },},decorators: [mswDecorator({@@ -1861,9 +1861,16 @@ export const ScannerEditorGoalOverviewExperiment: StoryObj = {export const ScannerEditorGoalOverviewLoading: StoryObj = {parameters: {pageUrl: urls.replayVisionScannerOverview('new'),- featureFlags: { [FEATURE_FLAGS.VISION_GOAL_BASED_CREATION_FLOW]: 'test' },+ featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V2]: 'test' },+ testOptions: { waitForLoadersToDisappear: false, waitForSelector: '.LemonSkeleton' },},decorators: [+ // A draft request that never answers, because a failed one sends the page back to the goal step.+ mswDecorator({+ post: {+ '/api/projects/:team_id/vision/scanners/draft/': (): Promise<never> => new Promise(() => {}),+ },+ }),(StoryFn) => {const logic = replayScannerLogic({ id: 'new' })logic.mount()diff --git a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsxindex 3fb0d0fbd70b..eb082d9abe18 100644--- a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx@@ -111,7 +111,7 @@ export function ScannerEditorSceneComponent(): JSX.Element {const { searchParams } = useValues(router)const { featureFlags } = useValues(featureFlagLogic)// Multivariate flag; a truthy check would turn the goal flow on for control too.- const goalFlow = featureFlags[FEATURE_FLAGS.VISION_GOAL_BASED_CREATION_FLOW] === 'test'+ const goalFlow = featureFlags[FEATURE_FLAGS.VISION_GOAL_FLOW_V2] === 'test'// Read once on mount, because the wizard strips the deep-link params as soon as it consumes them.const [experimentDeepLink] = useState(() => parseExperimentScannerParams(router.values.searchParams) !== null)// Reached a form step by clicking Edit on the goal overview: the overview is home, not a wizarddiff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsxindex 2e72f9a703d1..401519e03bfa 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { useState } from 'react'-import { IconSparkles } from '@posthog/icons'+import { IconChevronRight, IconPlus, IconSparkles } from '@posthog/icons'import { LemonButton, LemonInput, LemonTextArea } from '@posthog/lemon-ui'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'@@ -10,139 +10,171 @@ import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPimport { getReplayVisionEditDisabledReason } from '../../utils/accessControl'import { creditsToUsd } from '../../utils/credits'import { replayScannerLogic } from '../replayScannerLogic'-import { ScannerTemplatePicker } from './ScannerTemplatePicker'+import { ScannerTemplate, defaultScannerTemplates } from '../scannerTemplates'+import { ScannerResumeDraftBanner } from './ScannerResumeDraftBanner'+import { SCANNER_TEMPLATE_ICONS } from './scannerTemplateIcons'+import { startScannerFromTemplate } from './startScannerFromTemplate'// Credits, not recordings: the agent picks the model, so a fixed recording count no longer maps to// a fixed cost. The budget is what the user actually controls, and matches how we bill.const MIN_SCAN_BUDGET = 1const MAX_SCAN_BUDGET = 100000000-/** The goal-based creation flow's two questions (goal, monthly budget): drafts a full scanner- * and lands the user on the overview step to review it. The templates sit below, so someone who- * would rather start from a pre-built scanner than describe a goal can see that option up front. */+/** The goal-based creation flow: a typed goal and a monthly budget on the left, one-click starting+ * points on the right. Both draft a full scanner through the agent and land the user on the overview+ * step to review it, so a one-click start still gets a scanner fitted to the project. */export function ScannerGoalFlow(): JSX.Element {const logic = replayScannerLogic({ id: 'new' })const { goalDraftInput, goalBudgetInput, goalDraftLoading, experimentContext } = useValues(logic)const { draftScannerFromGoal, setGoalDraftInput, setGoalBudgetInput } = useActions(logic)+ const { dataProcessingAccepted } = useValues(aiConsentLogic)+ const [pendingDraft, setPendingDraft] = useState<{ goal: string; templateKey?: string } | null>(null)// Drafting creates a scanner, so it needs the same editor access as the rest of the wizard.const editDisabledReason = getReplayVisionEditDisabledReason()- const { dataProcessingAccepted } = useValues(aiConsentLogic)- const [consentRequested, setConsentRequested] = useState(false)-const budgetValid =goalBudgetInput != null && goalBudgetInput >= MIN_SCAN_BUDGET && goalBudgetInput <= MAX_SCAN_BUDGET+ const startDisabledReason =+ editDisabledReason ??+ (!budgetValid ? 'Enter a monthly credit budget' : goalDraftLoading ? 'Drafting your scanner' : null)- const submit = (): void => {- draftScannerFromGoal(goalDraftInput.trim(), goalBudgetInput ?? undefined)- }- const handleSubmit = (): void => {- if (editDisabledReason || !goalDraftInput.trim() || !budgetValid || goalDraftLoading) {- return- }+ const typedGoalDisabledReason =+ startDisabledReason ?? (!goalDraftInput.trim() ? 'Describe what you want to find out' : null)++ const start = (goal: string, templateKey?: string): void => {// Drafting calls an AI endpoint the backend rejects without org consent; interpose the// popover instead of letting the request 400.if (!dataProcessingAccepted) {- setConsentRequested(true)+ setPendingDraft({ goal, templateKey })return}- submit()+ draftScannerFromGoal(goal, goalBudgetInput ?? undefined, templateKey)+ }+ const startFromTypedGoal = (): void => {+ if (!typedGoalDisabledReason) {+ start(goalDraftInput.trim())+ }+ }+ const startFromStarter = (starter: ScannerTemplate): void => {+ if (!startDisabledReason) {+ start(starter.goal, starter.key)+ }}return (- <div className="space-y-4">- <div className="rounded-xl border-2 border-[var(--color-ai)] p-4 flex flex-col gap-4">- <div className="flex flex-col gap-1">- <label htmlFor="vision-goal-flow-goal" className="text-sm font-medium">- What do you want to find out?- </label>- <LemonTextArea- id="vision-goal-flow-goal"- value={goalDraftInput}- onChange={setGoalDraftInput}- placeholder="e.g. Find out where people give up in billing"- minRows={2}- maxRows={5}- data-attr="vision-goal-flow-goal"- />- <div className="text-xs text-muted">- Say what to learn and which part of the product to watch. The agent maps it onto your real- pages.- </div>- {/* A draft restored from an earlier experiment-scoped session keeps its targeting- through this flow, so say whose sessions the scanner ends up watching. */}- {experimentContext ? (- <div className="text-xs text-muted">- This scanner keeps watching people exposed to {experimentContext.experiment.name}. You don't- have to mention the experiment.+ <div className="@container flex flex-col gap-4">+ <ScannerResumeDraftBanner />+ <AIConsentPopoverWrapper+ placement="bottom"+ showArrow+ ignoreDismissal+ hideTrainingDisclaimer+ hidden={pendingDraft === null}+ onApprove={() => {+ if (pendingDraft) {+ draftScannerFromGoal(pendingDraft.goal, goalBudgetInput ?? undefined, pendingDraft.templateKey)+ }+ setPendingDraft(null)+ }}+ onDismiss={() => setPendingDraft(null)}+ >+ <div className="grid grid-cols-1 @3xl:grid-cols-2 gap-4">+ <div className="rounded-lg border-2 border-[var(--color-ai)] p-4 flex flex-col gap-4">+ <div className="flex flex-col gap-1">+ <label htmlFor="vision-goal-flow-goal" className="text-sm font-semibold">+ What do you want to find out?+ </label>+ <LemonTextArea+ id="vision-goal-flow-goal"+ value={goalDraftInput}+ onChange={setGoalDraftInput}+ placeholder="e.g. Find out where people give up in billing"+ minRows={3}+ maxRows={6}+ data-attr="vision-goal-flow-goal"+ />+ <div className="text-xs text-muted">+ Say what to learn and which part of the product to watch. The agent maps it onto your+ real pages.+ </div>+ {/* A draft restored from an earlier experiment-scoped session keeps its targeting+ through this flow, so say whose sessions the scanner ends up watching. */}+ {experimentContext ? (+ <div className="text-xs text-muted">+ This scanner keeps watching people exposed to {experimentContext.experiment.name}.+ You don't have to mention the experiment.+ </div>+ ) : null}</div>- ) : null}- </div>- <div className="flex flex-col gap-1">- <label htmlFor="vision-goal-flow-budget" className="text-sm font-medium">- About how much do you want to spend a month?- </label>- <div className="flex items-center gap-3">- <LemonInput- id="vision-goal-flow-budget"- type="number"- min={MIN_SCAN_BUDGET}- max={MAX_SCAN_BUDGET}- value={goalBudgetInput ?? undefined}- onChange={(value) => setGoalBudgetInput(value ?? null)}- suffix={<span className="text-muted">credits</span>}- className="w-40"- data-attr="vision-goal-flow-budget"- />- {budgetValid && goalBudgetInput != null ? (- <span className="text-xs text-muted">≈ {creditsToUsd(goalBudgetInput)} a month</span>- ) : null}- </div>- <div className="text-xs text-muted">- 1,000 credits ≈ $10. The agent picks the model and fits the scanner to this.+ <div className="flex flex-col gap-1">+ <label htmlFor="vision-goal-flow-budget" className="text-sm font-semibold">+ About how much do you want to spend a month?+ </label>+ <div className="flex flex-wrap items-center gap-3">+ <LemonInput+ id="vision-goal-flow-budget"+ type="number"+ min={MIN_SCAN_BUDGET}+ max={MAX_SCAN_BUDGET}+ value={goalBudgetInput ?? undefined}+ onChange={(value) => setGoalBudgetInput(value ?? null)}+ suffix={<span className="text-muted">credits</span>}+ className="w-40"+ data-attr="vision-goal-flow-budget"+ />+ {budgetValid && goalBudgetInput != null ? (+ <span className="text-xs text-muted">+ ≈ {creditsToUsd(goalBudgetInput)} a month+ </span>+ ) : null}+ </div>+ <div className="text-xs text-muted">+ 1,000 credits ≈ $10. The agent picks the model and fits the scanner to this.+ </div>+ </div>++ <div className="flex items-center justify-between mt-auto">+ <div className="flex items-center gap-1.5 text-xs text-tertiary">+ <IconSparkles className="text-ai size-3.5" />+ <span>PostHog AI</span>+ </div>+ <LemonButton+ type="primary"+ loading={goalDraftLoading}+ // Inside the consent popover's reference, so Lemon would add a dropdown chevron.+ sideIcon={null}+ disabledReason={typedGoalDisabledReason}+ onClick={startFromTypedGoal}+ data-attr="vision-goal-flow-submit"+ >+ Draft my scanner+ </LemonButton>+ </div></div>- </div>- <div className="flex items-center justify-between">- <div className="flex items-center gap-1.5 text-xs text-tertiary">- <IconSparkles className="text-ai size-3.5" />- <span>PostHog AI</span>+ <div className="rounded-lg border border-border bg-bg-light p-4 flex flex-col gap-2">+ <span className="text-sm font-semibold">Common starting points</span>+ <span className="text-xs text-muted">One click drafts a scanner fitted to your project.</span>+ <div className="flex flex-col gap-1">+ {defaultScannerTemplates.map((template) => (+ <LemonButton+ key={template.key}+ fullWidth+ icon={SCANNER_TEMPLATE_ICONS[template.icon]}+ sideIcon={<IconChevronRight />}+ tooltip={template.goal}+ disabledReason={startDisabledReason}+ onClick={() => startFromStarter(template)}+ data-attr={`vision-goal-starter-${template.key}`}+ >+ {template.goal_question}+ </LemonButton>+ ))}+ </div></div>- <AIConsentPopoverWrapper- placement="bottom-end"- showArrow- ignoreDismissal- hideTrainingDisclaimer- hidden={!consentRequested}- onApprove={() => {- setConsentRequested(false)- submit()- }}- onDismiss={() => setConsentRequested(false)}- >- <LemonButton- type="primary"- loading={goalDraftLoading}- onClick={handleSubmit}- // The button is the popover's reference, so Lemon would add a dropdown- // chevron; it submits rather than opening a menu, so suppress it.- sideIcon={null}- disabledReason={- editDisabledReason ??- (!goalDraftInput.trim()- ? 'Describe what you want to find out'- : !budgetValid- ? 'Enter a monthly credit budget'- : undefined)- }- data-attr="vision-goal-flow-submit"- >- Draft my scanner- </LemonButton>- </AIConsentPopoverWrapper></div>- </div>+ </AIConsentPopoverWrapper><div className="flex items-center gap-4"><div className="flex-1 border-t border-border" />@@ -150,9 +182,15 @@ export function ScannerGoalFlow(): JSX.Element {<div className="flex-1 border-t border-border" /></div>- <div className="flex flex-col gap-3">- <p className="text-center text-sm text-muted m-0">Start from a template</p>- <ScannerTemplatePicker />+ <div className="flex justify-center">+ <LemonButton+ type="secondary"+ icon={<IconPlus />}+ onClick={() => startScannerFromTemplate(null)}+ data-attr="vision-template-blank"+ >+ Create from scratch+ </LemonButton></div></div>)diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsxindex b5f7bdbf34de..a11bc64f26dd 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx@@ -9,6 +9,7 @@ import { LemonBanner, LemonButton, LemonSkeleton, LemonSnack, LemonTag, Spinner,import { formatPropertyLabel } from 'lib/components/PropertyFilters/utils'import { LoadingBar } from 'lib/lemon-ui/LoadingBar'import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'+import { percentage } from 'lib/utils/numbers'import { pluralize } from 'lib/utils/strings'import { urls } from 'scenes/urls'@@ -295,7 +296,6 @@ export function ScannerGoalOverview({ scannerId }: { scannerId: string }): JSX.E// fields do not. It also matches the eligible count above, since both come from one estimate.const monthlyObservations = scannerEstimate?.estimated_observations_per_month ?? nullconst monthlyCredits = scannerEstimate?.estimated_credits_per_month ?? null- const samplingPct = Math.round(scanner.sampling_rate * 100)const creditsPerObservation =scannerEstimate?.credits_per_observation ?? OBSERVATION_CREDITS_BY_MODEL[scanner.model] ?? null// The budget is credits, so compare the projected credit cost against the cap (which the draft@@ -382,7 +382,7 @@ export function ScannerGoalOverview({ scannerId }: { scannerId: string }): JSX.EscannerId={scannerId}><div className="grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-2 text-sm">- <StatRow label="Goal">+ <StatRow label="Recordings">{monthlyObservations != null ? (<span className="font-medium">about {monthlyObservations.toLocaleString()} recordings a month@@ -394,7 +394,8 @@ export function ScannerGoalOverview({ scannerId }: { scannerId: string }): JSX.E)}</StatRow><StatRow label="Sampling">- <LemonTag type="muted">{samplingPct}%</LemonTag>+ {/* Two decimals, because a high-traffic project on a small budget lands near the 0.0001 floor. */}+ <LemonTag type="muted">{percentage(scanner.sampling_rate, 2)}</LemonTag></StatRow><StatRow label="Activity filter"><LemonTag type="muted">{activityFilterLabel(scanner.sampling_mode)}</LemonTag>diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerResumeDraftBanner.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerResumeDraftBanner.tsxnew file mode 100644index 000000000000..08e3e1df2ce5--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerResumeDraftBanner.tsx@@ -0,0 +1,69 @@+import { useActions, useValues } from 'kea'+import { combineUrl, router } from 'kea-router'++import { IconPencil, IconTrash } from '@posthog/icons'+import { LemonBanner, LemonButton } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { urls } from 'scenes/urls'++import { ScannerTypeBadge } from '../../components/ScannerTypeBadge'+import { replayScannerLogic } from '../replayScannerLogic'++export function ScannerResumeDraftBanner(): JSX.Element | null {+ const logic = replayScannerLogic({ id: 'new' })+ const { scannerDraftSavedAt, scanner } = useValues(logic)+ const { discardScannerDraft } = useActions(logic)++ if (scannerDraftSavedAt === null) {+ return null+ }++ const handleResume = (): void => {+ const { template: _template, ...params } = router.values.searchParams+ router.actions.push(combineUrl(urls.replayVisionScannerDetails('new'), params).url)+ }++ return (+ <LemonBanner+ type="info"+ icon={<IconPencil />}+ action={{+ children: 'Resume draft',+ onClick: handleResume,+ 'data-attr': 'vision-template-resume-draft',+ }}+ >+ <div className="flex flex-wrap items-center gap-2">+ <span className="font-semibold">Resume your draft</span>+ <span className="text-secondary font-normal">+ {scanner?.name ? `"${scanner.name}"` : 'Untitled scanner'}+ </span>+ {scanner?.scanner_type && <ScannerTypeBadge scannerType={scanner.scanner_type} />}+ <span className="text-secondary font-normal">saved {dayjs(scannerDraftSavedAt).fromNow()}.</span>+ <LemonButton+ size="xsmall"+ type="tertiary"+ status="danger"+ icon={<IconTrash />}+ tooltip="Discard this draft"+ className="ml-auto"+ data-attr="vision-template-discard-draft"+ onClick={(): void =>+ LemonDialog.open({+ title: 'Discard this draft?',+ description: 'This cannot be undone.',+ primaryButton: {+ children: 'Discard',+ status: 'danger',+ onClick: (): void => discardScannerDraft(),+ },+ secondaryButton: { children: 'Keep my draft' },+ })+ }+ />+ </div>+ </LemonBanner>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTemplatePicker.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTemplatePicker.tsxindex 675c853a6591..fd57781cfae6 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTemplatePicker.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTemplatePicker.tsx@@ -1,61 +1,15 @@-import { useActions, useValues } from 'kea'-import { combineUrl, router } from 'kea-router'--import {- IconCheckCircle,- IconNotebook,- IconPencil,- IconPlus,- IconTarget,- IconThumbsDown,- IconTrash,- IconWarning,-} from '@posthog/icons'-import { LemonBanner, LemonButton } from '@posthog/lemon-ui'--import { dayjs } from 'lib/dayjs'-import { LemonDialog } from 'lib/lemon-ui/LemonDialog'-import { urls } from 'scenes/urls'+import { IconPlus } from '@posthog/icons'import { ScannerTypeBadge } from '../../components/ScannerTypeBadge'-import { replayScannerLogic } from '../replayScannerLogic'-import { ScannerTemplate, ScannerTemplateIcon, defaultScannerTemplates } from '../scannerTemplates'+import { ScannerTemplate, defaultScannerTemplates } from '../scannerTemplates'import { scannerTypeOutputHint } from '../types'-import { scannerStartSearchParams } from './scannerStartParams'--const TEMPLATE_ICONS: Record<ScannerTemplateIcon, JSX.Element> = {- warning: <IconWarning />,- notebook: <IconNotebook />,- target: <IconTarget />,- 'thumbs-down': <IconThumbsDown />,- check: <IconCheckCircle />,-}+import { ScannerResumeDraftBanner } from './ScannerResumeDraftBanner'+import { SCANNER_TEMPLATE_ICONS } from './scannerTemplateIcons'+import { startScannerFromTemplate } from './startScannerFromTemplate'-export function TemplateCard({ template }: { template: ScannerTemplate | 'blank' }): JSX.Element {+function TemplateCard({ template }: { template: ScannerTemplate | 'blank' }): JSX.Element {const isBlank = template === 'blank'- const { searchParams } = useValues(router)- const { scannerDraftSavedAt } = useValues(replayScannerLogic({ id: 'new' }))-- const start = (): void => {- const templateKey = isBlank ? null : template.key- replayScannerLogic({ id: 'new' }).actions.startFromTemplate(templateKey)- router.actions.push(- combineUrl(urls.replayVisionScannerDetails('new'), scannerStartSearchParams(searchParams, templateKey)).url- )- }-- const handleClick = (): void => {- if (scannerDraftSavedAt === null) {- start()- return- }- LemonDialog.open({- title: 'Start over and lose your draft?',- description: 'The scanner you have in progress will be replaced by this template.',- primaryButton: { children: 'Start over', status: 'danger', onClick: start },- secondaryButton: { children: 'Keep my draft' },- })- }+ const handleClick = (): void => startScannerFromTemplate(isBlank ? null : template.key)return (<button@@ -67,7 +21,7 @@ export function TemplateCard({ template }: { template: ScannerTemplate | 'blank'<div className="flex flex-col items-center text-center gap-4 h-full"><div className="bg-primary-3000/10 rounded-lg flex-shrink-0 size-12 flex items-center justify-center"><span className="w-6 h-6 text-primary-3000 [&_svg]:w-6 [&_svg]:h-6">- {isBlank ? <IconPlus /> : TEMPLATE_ICONS[template.icon]}+ {isBlank ? <IconPlus /> : SCANNER_TEMPLATE_ICONS[template.icon]}</span></div><div className="flex-1 flex flex-col justify-start w-full">@@ -98,68 +52,10 @@ export function TemplateCard({ template }: { template: ScannerTemplate | 'blank')}-function ResumeDraftBanner(): JSX.Element | null {- const logic = replayScannerLogic({ id: 'new' })- const { scannerDraftSavedAt, scanner } = useValues(logic)- const { discardScannerDraft } = useActions(logic)- const { searchParams } = useValues(router)-- if (scannerDraftSavedAt === null) {- return null- }-- const handleResume = (): void => {- const { template: _template, ...params } = searchParams- router.actions.push(combineUrl(urls.replayVisionScannerDetails('new'), params).url)- }-- return (- <LemonBanner- type="info"- icon={<IconPencil />}- action={{- children: 'Resume draft',- onClick: handleResume,- 'data-attr': 'vision-template-resume-draft',- }}- >- <div className="flex flex-wrap items-center gap-2">- <span className="font-semibold">Resume your draft</span>- <span className="text-secondary font-normal">- {scanner?.name ? `"${scanner.name}"` : 'Untitled scanner'}- </span>- {scanner?.scanner_type && <ScannerTypeBadge scannerType={scanner.scanner_type} />}- <span className="text-secondary font-normal">saved {dayjs(scannerDraftSavedAt).fromNow()}.</span>- <LemonButton- size="xsmall"- type="tertiary"- status="danger"- icon={<IconTrash />}- tooltip="Discard this draft"- className="ml-auto"- data-attr="vision-template-discard-draft"- onClick={(): void =>- LemonDialog.open({- title: 'Discard this draft?',- description: 'This cannot be undone.',- primaryButton: {- children: 'Discard',- status: 'danger',- onClick: (): void => discardScannerDraft(),- },- secondaryButton: { children: 'Keep my draft' },- })- }- />- </div>- </LemonBanner>- )-}-export function ScannerTemplatePicker(): JSX.Element {return (<div className="flex flex-col gap-6">- <ResumeDraftBanner />+ <ScannerResumeDraftBanner /><div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">{defaultScannerTemplates.map((template) => (<TemplateCard key={template.key} template={template} />diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsxindex 4001b8f18288..2b3f799db31f 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx@@ -36,7 +36,7 @@ import { ClassifierScannerConfig, SummarizerScannerConfig, scannerTypeLabel } frfunction useManualWithoutAi(scannerId: string): boolean {const { isNew, goalDraft } = useValues(replayScannerLogic({ id: scannerId }))const { featureFlags } = useValues(featureFlagLogic)- return isNew && !goalDraft && featureFlags[FEATURE_FLAGS.VISION_GOAL_BASED_CREATION_FLOW] === 'test'+ return isNew && !goalDraft && featureFlags[FEATURE_FLAGS.VISION_GOAL_FLOW_V2] === 'test'}export const SUMMARIZER_LENGTH_OPTIONS: { value: SummarizerScannerConfig['length']; label: string }[] = [diff --git a/products/replay_vision/frontend/replay_scanners/components/scannerTemplateIcons.tsx b/products/replay_vision/frontend/replay_scanners/components/scannerTemplateIcons.tsxnew file mode 100644index 000000000000..31c12ce198fb--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/scannerTemplateIcons.tsx@@ -0,0 +1,11 @@+import { IconCheckCircle, IconNotebook, IconTarget, IconThumbsDown, IconWarning } from '@posthog/icons'++import { ScannerTemplateIcon } from '../scannerTemplates'++export const SCANNER_TEMPLATE_ICONS: Record<ScannerTemplateIcon, JSX.Element> = {+ warning: <IconWarning />,+ notebook: <IconNotebook />,+ target: <IconTarget />,+ 'thumbs-down': <IconThumbsDown />,+ check: <IconCheckCircle />,+}diff --git a/products/replay_vision/frontend/replay_scanners/components/startScannerFromTemplate.ts b/products/replay_vision/frontend/replay_scanners/components/startScannerFromTemplate.tsnew file mode 100644index 000000000000..63cd6183856f--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/startScannerFromTemplate.ts@@ -0,0 +1,34 @@+import { combineUrl, router } from 'kea-router'++import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { urls } from 'scenes/urls'++import { replayScannerLogic } from '../replayScannerLogic'+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. */+export function startScannerFromTemplate(templateKey: string | null): void {+ const logic = replayScannerLogic({ id: 'new' })+ const start = (): void => {+ logic.actions.startFromTemplate(templateKey)+ router.actions.push(+ combineUrl(+ urls.replayVisionScannerDetails('new'),+ scannerStartSearchParams(router.values.searchParams, templateKey)+ ).url+ )+ }+ if (logic.values.scannerDraftSavedAt === null) {+ start()+ return+ }+ LemonDialog.open({+ title: 'Start over and lose your draft?',+ description: templateKey+ ? 'The scanner you have in progress will be replaced by this template.'+ : 'The scanner you have in progress will be replaced by a blank one.',+ primaryButton: { children: 'Start over', status: 'danger', onClick: start },+ secondaryButton: { children: 'Keep my draft' },+ })+}diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex 210473407553..41181bb45b74 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -199,8 +199,9 @@ describe('replayScannerLogic', () => {).toFinishAllListeners()expect(draftSpy).toHaveBeenCalled()- expect(logic.values.goalDraftInput).toEqual('')+ expect(logic.values.goalDraftInput).toEqual('understand what users come here to do')expect(logic.values.scanner).toMatchObject({+ goal: 'understand what users come here to do',name: draft.name,description: draft.description,scanner_type: draft.scanner_type,@@ -1688,14 +1689,17 @@ describe('replayScannerLogic', () => {})})- it('drafting from a goal reports the AI path without the goal text', async () => {+ it.each([+ ['a typed goal', undefined, null],+ ['a goal starter', 'dead_end', 'dead_end'],+ ])('drafting from %s reports the AI path without the goal text', async (_, templateKey, reportedKey) => {const captureSpy = jest.spyOn(posthog, 'capture')await expectLogic(logic, () => {- logic.actions.draftScannerFromGoal(' find users who get stuck ')+ logic.actions.draftScannerFromGoal(' find users who get stuck ', undefined, templateKey)}).toFinishAllListeners()expect(captureSpy).toHaveBeenCalledWith('replay_vision_scanner_creation_started', {creation_method: 'ai',- template_key: null,+ template_key: reportedKey,goal_length: 'find users who get stuck'.length,})})diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex 9a464f69c33b..1f39eb04ab81 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -467,10 +467,12 @@ export interface replayScannerLogicActions {}draftScannerFromGoal: (goal: string,- monthlyCreditBudget?: number+ monthlyCreditBudget?: number,+ templateKey?: string) => {goal: stringmonthlyCreditBudget: number | undefined+ templateKey: string | undefined}draftScannerFromGoalFailure: (error: string,@@ -484,12 +486,14 @@ export interface replayScannerLogicActions {payload?: {goal: stringmonthlyCreditBudget: number | undefined+ templateKey: string | undefined}) => {goalDraft: DraftScannerResponseApi | nullpayload?: {goal: stringmonthlyCreditBudget: number | undefined+ templateKey: string | undefined}}loadObservationStats: () => {@@ -856,7 +860,11 @@ export const replayScannerLogic = kea<replayScannerLogicType>([acceptTagSuggestion: (tag: string) => ({ tag }),acceptAllTagSuggestions: true,dismissTagSuggestions: true,- draftScannerFromGoal: (goal: string, monthlyCreditBudget?: number) => ({ goal, monthlyCreditBudget }),+ draftScannerFromGoal: (goal: string, monthlyCreditBudget?: number, templateKey?: string) => ({+ goal,+ monthlyCreditBudget,+ templateKey,+ }),setGoalDraftInput: (goal: string) => ({ goal }),setGoalBudgetInput: (budget: number | null) => ({ budget }),loadObservations: (background = false) => ({ background }),@@ -1022,7 +1030,16 @@ export const replayScannerLogic = kea<replayScannerLogicType>([// A duplicate name is the one field error the details step can fix, so route back to it.if (error.attr === 'name' && error.detail) {actions.setScannerManualErrors({ name: error.detail })- router.actions.push(urls.replayVisionScannerDetails(props.id))+ // From the goal overview, mark the trip so the details step returns there after the fix.+ router.actions.push(+ scannerStepUrlWithParams(+ 'details',+ props.id,+ currentStep === 'overview'+ ? { ...router.values.searchParams, from: 'overview' }+ : router.values.searchParams+ )+ )lemonToast.error(error.detail)throw error}@@ -1125,15 +1142,18 @@ export const replayScannerLogic = kea<replayScannerLogicType>(['',{setGoalDraftInput: (_, { goal }) => goal,- // Cleared once a draft or a template pick consumed it, so a stale goal doesn't linger.- draftScannerFromGoalSuccess: () => '',+ // Kept through a successful draft so "Start over" on the review step returns with the goal+ // still there to edit. A template pick, a discard, or a save ends that goal.startFromTemplate: () => '',+ discardScannerDraft: () => '',+ scannerSaved: () => '',},],- // The monthly credit budget input on the goal-based creation flow. Default 5,000 credits- // (~$50): the round anchor the budget question shows, and enough for a real first scanner.+ // The monthly credit budget input on the goal-based creation flow. The default equals the free+ // monthly credits (FREE_TIER_MONTHLY_CREDITS in backend/billing.py), so a first scanner fits the+ // free tier and costs nothing unless the person raises it. Change both values together.goalBudgetInput: [- 5000 as number | null,+ 2500 as number | null,{setGoalBudgetInput: (_, { budget }) => budget,},@@ -1959,10 +1979,11 @@ export const replayScannerLogic = kea<replayScannerLogicType>([},// Fires on request rather than result, so failed drafts still count as entering the AI path.- draftScannerFromGoal: ({ goal, monthlyCreditBudget }) => {+ draftScannerFromGoal: ({ goal, monthlyCreditBudget, templateKey }) => {posthog.capture('replay_vision_scanner_creation_started', {creation_method: 'ai',- template_key: null,+ // Set when a goal starter card wrote the goal, so the funnel can split typed goals from one-click ones.+ template_key: templateKey ?? null,// The goal is customer text, so only its length is captured.goal_length: goal.trim().length,})@@ -1975,7 +1996,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([},// A successful AI draft seeds the wizard form, then the configure step opens for review.- draftScannerFromGoalSuccess: ({ goalDraft }) => {+ draftScannerFromGoalSuccess: ({ goalDraft, payload }) => {if (!goalDraft) {return}@@ -2008,6 +2029,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([// Applied as form values (not baked into the reset) so the draft persists like hand-edited// input and survives a reload of the configure step.actions.setScannerValues({+ // Saved with the scanner, so it keeps the intent it was drafted from.+ goal: payload?.goal.trim() || null,name: context ? experimentScannerName(goalDraft.name, context.experiment.name) : goalDraft.name,description: goalDraft.description,scanner_type: goalDraft.scanner_type as ScannerType,@@ -2057,7 +2080,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([},draftScannerFromGoalFailure: ({ errorObject }) => {- lemonToast.error(`Couldn't draft a scanner${errorObject?.detail ? `: ${errorObject.detail}` : ''}`)+ lemonToast.error(errorObject?.detail ?? "Couldn't draft a scanner. Try again in a moment.")// The goal flow moved to the overview skeleton on request; with no draft to show,// send the user back to the questions to try again.if (router.values.location.pathname.endsWith(urls.replayVisionScannerOverview('new'))) {diff --git a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts b/products/replay_vision/frontend/replay_scanners/scannerTemplates.tsindex aa90202e7ca1..a421fb56f76f 100644--- a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts@@ -18,6 +18,9 @@ interface BaseTemplate {name: stringdescription: stringicon: ScannerTemplateIcon+ // What the goal-based flow drafts from when someone clicks this template's starter, in place of a typed goal.+ goal: string+ goal_question: stringscanner_name: stringscanner_description: string}@@ -48,6 +51,8 @@ export type ScannerTemplate = MonitorTemplate | SummarizerTemplate | ClassifierTexport const defaultScannerTemplates: readonly ScannerTemplate[] = [{key: 'dead_end',+ goal: 'Find sessions where people get stuck on a page with no clear next step',+ goal_question: 'Where do people get stuck?',name: 'Dead ends',description: 'Detect sessions where the user gets stuck on a page with no clear path forward.',icon: 'warning',@@ -60,6 +65,8 @@ export const defaultScannerTemplates: readonly ScannerTemplate[] = [},{key: 'session_summary',+ goal: 'Summarize what people do in each session and where they run into trouble',+ goal_question: 'What happens in each session?',name: 'Session summary',description: 'Generate a short narrative of what the user actually did in the session.',icon: 'notebook',@@ -73,6 +80,8 @@ export const defaultScannerTemplates: readonly ScannerTemplate[] = [},{key: 'user_intent',+ goal: 'Find out what people are trying to do when they visit',+ goal_question: 'What are people trying to do?',name: 'User intent',description: 'Classify the session by what the user appeared to be trying to do.',icon: 'target',@@ -87,6 +96,8 @@ export const defaultScannerTemplates: readonly ScannerTemplate[] = [},{key: 'frustration_score',+ goal: 'Find out where people get frustrated and how badly',+ goal_question: 'Where do people get frustrated?',name: 'Frustration score',description: 'Score how much friction or frustration the user appeared to experience.',icon: 'thumbs-down',@@ -100,6 +111,8 @@ export const defaultScannerTemplates: readonly ScannerTemplate[] = [},{key: 'session_outcome',+ goal: 'Find out whether people finish what they came to do, give up, or hit an error',+ goal_question: 'Do people finish what they came to do?',name: 'Session outcome',description: 'Categorize each session by what actually happened: task completed, abandoned, errored, etc.',icon: 'check',diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c5d2de15bd14..241616e23369 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -68275,6 +68275,12 @@ export namespace Schemas {* * `scorer` - Scorer* * `summarizer` - Summarizer */scanner_type: ScannerTypeEnum;+ /**+ * The goal an AI draft was built from, in the creator's own words, so the scanner keeps what it was meant to find. Set on create only and ignored on update.+ * @maxLength 2000+ * @nullable+ */+ goal?: string | null;/** How the creator built this scanner: from an AI draft, from a template, or from scratch. Reported to product analytics at creation and not stored on the scanner. Independent of any experiment the creator is in, since a person offered the AI flow can still fill the form by hand. Only the app can answer this, so a request from anywhere else reports the calling surface instead of whatever it sends here. Ignored on update.** * `ai` - AI draft@@ -79768,6 +79774,12 @@ export namespace Schemas {* * `scorer` - Scorer* * `summarizer` - Summarizer */scanner_type?: ScannerTypeEnum;+ /**+ * The goal an AI draft was built from, in the creator's own words, so the scanner keeps what it was meant to find. Set on create only and ignored on update.+ * @maxLength 2000+ * @nullable+ */+ goal?: string | null;/** How the creator built this scanner: from an AI draft, from a template, or from scratch. Reported to product analytics at creation and not stored on the scanner. Independent of any experiment the creator is in, since a person offered the AI flow can still fill the form by hand. Only the app can answer this, so a request from anywhere else reports the calling surface instead of whatever it sends here. Ignored on update.** * `ai` - AI draftdiff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.tsindex 390dd2d07e55..654f63f305c4 100644--- a/services/mcp/src/generated/replay_vision/api.ts+++ b/services/mcp/src/generated/replay_vision/api.ts@@ -726,6 +726,8 @@ export const visionScannersCreateBodyTagsItemMax = 255export const visionScannersCreateBodyTagsMax = 32+export const visionScannersCreateBodyGoalMax = 2000+export const visionScannersCreateBodySamplingRateMin = 0export const visionScannersCreateBodySamplingRateMax = 1@@ -759,6 +761,13 @@ export const VisionScannersCreateBody = () => zod.describe('What the scanner does: monitor, classifier, scorer, or summarizer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'),+ goal: zod+ .string()+ .max(visionScannersCreateBodyGoalMax)+ .nullish()+ .describe(+ "The goal an AI draft was built from, in the creator's own words, so the scanner keeps what it was meant to find. Set on create only and ignored on update."+ ),creation_method: zod.union([zod@@ -887,6 +896,8 @@ export const visionScannersPartialUpdateBodyTagsItemMax = 255export const visionScannersPartialUpdateBodyTagsMax = 32+export const visionScannersPartialUpdateBodyGoalMax = 2000+export const visionScannersPartialUpdateBodySamplingRateMin = 0export const visionScannersPartialUpdateBodySamplingRateMax = 1@@ -922,6 +933,13 @@ export const VisionScannersPartialUpdateBody = () => zod.describe('What the scanner does: monitor, classifier, scorer, or summarizer.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'),+ goal: zod+ .string()+ .max(visionScannersPartialUpdateBodyGoalMax)+ .nullish()+ .describe(+ "The goal an AI draft was built from, in the creator's own words, so the scanner keeps what it was meant to find. Set on create only and ignored on update."+ ),creation_method: zod.union([zoddiff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.tsindex c3113857668b..4f6e425f1cb9 100644--- a/services/mcp/src/tools/generated/replay_vision.ts+++ b/services/mcp/src/tools/generated/replay_vision.ts@@ -928,6 +928,9 @@ const visionScannersCreate = (): ToolBase<if (params.scanner_type !== undefined) {body['scanner_type'] = params.scanner_type}+ if (params.goal !== undefined) {+ body['goal'] = params.goal+ }if (params.creation_method !== undefined) {body['creation_method'] = params.creation_method}@@ -1787,6 +1790,9 @@ const visionScannersUpdate = (): ToolBase<ReturnType<typeof VisionScannersUpdateif (params.scanner_type !== undefined) {body['scanner_type'] = params.scanner_type}+ if (params.goal !== undefined) {+ body['goal'] = params.goal+ }if (params.creation_method !== undefined) {body['creation_method'] = params.creation_method}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.jsonindex 8b4d40ee7679..4f45b38a5216 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json@@ -76,6 +76,18 @@],"description": "The experiment this scanner's targeting watches, if any. Set null when the experiment targeting is removed."},+ "goal": {+ "anyOf": [+ {+ "maxLength": 2000,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "The goal an AI draft was built from, in the creator's own words, so the scanner keeps what it was meant to find. Set on create only and ignored on update."+ },"model": {"description": "Concrete model to use for this scanner.\n\n* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n* `gemini-3-flash-preview` - Gemini 3 Flash\n* `gemini-3.8-flash` - Gemini 3.8 Flash","enum": ["gemini-3.5-flash-lite", "gemini-3-flash-preview", "gemini-3.8-flash"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.jsonindex 2b2a668f60d8..3ef8373b129d 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json@@ -75,6 +75,18 @@],"description": "The experiment this scanner's targeting watches, if any. Set null when the experiment targeting is removed."},+ "goal": {+ "anyOf": [+ {+ "maxLength": 2000,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "The goal an AI draft was built from, in the creator's own words, so the scanner keeps what it was meant to find. Set on create only and ignored on update."+ },"id": {"description": "A UUID string identifying this replay scanner.","type": "string"