: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): add duplicate action to the scanner list menu (#81441)
Arno Hillena0976c259048
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 5144e8d432da..0e9c3777dc25 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -28,7 +28,7 @@ from posthog.schema import RecordingsQueryfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer-from posthog.api.tagged_item import TaggedItemSerializerMixin+from posthog.api.tagged_item import TaggedItemSerializerMixin, set_tags_on_objectfrom posthog.event_usage import report_user_actionfrom posthog.exceptions import QuotaLimitExceededfrom posthog.models.tag import tagify@@ -203,6 +203,22 @@ def _refresh_estimate_fail_soft(scanner: ReplayScanner) -> None:logger.exception("replay_vision.estimate_refresh_failed", scanner_id=str(scanner.id))+def _scanner_copy_name(team_id: int, source_name: str) -> str:+ """First free "<name> (copy)" / "<name> (copy N)" variant, truncated to the name column limit.+ One query for the team's names, since suffix-dependent truncation defeats a startswith filter;+ scanner counts per team are small. The unique constraint stays the backstop for a concurrent+ create racing this check."""+ taken = set(ReplayScanner.objects.filter(team_id=team_id).values_list("name", flat=True))+ for n in range(1, len(taken) + 2):+ suffix = " (copy)" if n == 1 else f" (copy {n})"+ candidate = f"{source_name[: 255 - len(suffix)]}{suffix}"+ if candidate not in taken:+ return candidate+ # Unreachable given the range spans more than the collisions, but stay well-defined; the DB+ # uniqueness constraint is the final backstop.+ return source_name++class FeedbackThemeSessionSerializer(serializers.Serializer):observation_id = serializers.CharField(help_text="Observation whose feedback comment backs this theme.")session_id = serializers.CharField(help_text="Session recording the feedback comment was about.")@@ -1495,6 +1511,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi"update","partial_update","destroy",+ "duplicate","observe","bulk_observe","inline_scan",@@ -1506,7 +1523,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vihttp_method_names = ["get", "post", "patch", "delete", "head", "options"]# Same authorization as /observe/: configuring a scanner indirectly exposes recording contents.- _CONFIG_ACTIONS = {"create", "update", "partial_update"}+ _CONFIG_ACTIONS = {"create", "update", "partial_update", "duplicate"}def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:if self.action in self._CONFIG_ACTIONS:@@ -1564,6 +1581,72 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, virequest=self.request,)+ @extend_schema(request=None, responses={201: ReplayScannerSerializer})+ @action(detail=True, methods=["post"])+ def duplicate(self, request: Request, **kwargs: Any) -> Response:+ """Copy a scanner into a new disabled scanner named "<name> (copy)".++ Copies the stored model row rather than the serializer's read representation, so a query+ that no longer validates survives the copy; duplicating through the create endpoint would+ silently drop it. Experiment targeting is the exception and follows the read path instead.+ Unlike create, no digest is provisioned: the copy starts disabled and unreviewed."""+ # An object-level editor grant on one scanner is enough to get past the permission+ # class, but this action creates a new scanner, so it must clear the same+ # resource-level bar the create action enforces.+ if not self.user_access_control.check_access_level_for_resource("replay_scanner", required_level="editor"):+ raise PermissionDenied("Duplicating a scanner requires editor access to Replay Vision scanners.")+ source = self.get_object()+ if not self.team.organization.is_ai_data_processing_approved:+ raise serializers.ValidationError(+ "Your organization needs to allow AI analysis before you can create a Replay Vision scanner."+ )+ user = cast(User, request.user)+ # A scanner is viewable at a coarser grain than its targeted experiment, so the read path+ # nulls an experiment the caller cannot view. Drop it from the copy for the same reason:+ # create rejects targeting such an experiment, and duplicate must not be the way around it.+ experiment_targeting = source.experiment_targeting+ if experiment_targeting:+ experiment_id = experiment_targeting.get("experiment_id")+ if experiment_id is None or not is_experiment_accessible(+ self.user_access_control, self.team_id, experiment_id+ ):+ experiment_targeting = None+ # One transaction so a failed tag write can't leave an untagged copy behind. Side effects stay outside.+ with transaction.atomic():+ try:+ scanner = ReplayScanner.objects.create(+ team=self.team,+ created_by=user,+ name=_scanner_copy_name(self.team_id, source.name),+ description=source.description,+ scanner_type=source.scanner_type,+ scanner_config=source.scanner_config,+ query=source.query,+ sampling_rate=source.sampling_rate,+ sampling_mode=source.sampling_mode,+ credit_limit=source.credit_limit,+ provider=source.provider,+ model=source.model,+ emits_signals=source.emits_signals,+ experiment_targeting=experiment_targeting,+ enabled=False,+ )+ except IntegrityError as e:+ ReplayScannerSerializer._reraise_unique_name_violation(e)+ tags = list(source.tagged_items.values_list("tag__name", flat=True))+ if tags:+ set_tags_on_object(tags, scanner)+ _refresh_estimate_fail_soft(scanner)+ # Distinct from replay_vision_scanner_created so duplicates don't inflate wizard-completion counts.+ report_user_action(+ user,+ "replay_vision_scanner_duplicated",+ {**_scanner_lifecycle_properties(scanner), "source_scanner_id": str(source.id)},+ team=self.team,+ request=request,+ )+ return Response(self.get_serializer(scanner).data, status=status.HTTP_201_CREATED)+@extend_schema(responses={200: ScannerCreatorsResponseSerializer})@action(detail=False, methods=["get"], pagination_class=None)def creators(self, request: Request, **kwargs: Any) -> Response:diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex b771f2f7d99c..6efdea3de584 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -1112,6 +1112,108 @@ class TestScannerDigestProvisioning(_VisionAPITestCase):self.assertFalse(VisionAction.objects.for_team(self.team.id).filter(scanner_id=resp.json()["id"]).exists())+class TestScannerDuplicateAction(_VisionAPITestCase):+ def _duplicate(self, scanner_id: Any) -> Any:+ return self.client.post(f"{self.scanners_url}{scanner_id}/duplicate/")++ def test_duplicate_copies_stored_fields_the_read_path_redacts(self) -> None:+ experiment = create_experiment(self.team, "checkout-redesign")+ targeting = {"experiment_id": experiment.id, "variant_keys": ["test"], "use_exposure_fallback": False}+ # A stored filter that no longer passes RecordingsQuery validation: the serializer's read+ # path nulls it, so a copy built from the list response would silently lose it.+ stale_query = {"kind": "RecordingsQuery", "duration": "not-a-list"}+ source = self._create_scanner(+ name="redacted-source",+ query=stale_query,+ experiment_targeting=targeting,+ credit_limit=500,+ sampling_rate=0.25,+ enabled=True,+ )+ set_tags_on_object(["checkout", "billing"], source)++ resp = self._duplicate(source.id)++ self.assertEqual(resp.status_code, 201, resp.json())+ body = resp.json()+ self.assertEqual(body["name"], "redacted-source (copy)")+ self.assertFalse(body["enabled"])+ # The response still goes through the read path, which redacts the invalid stored filter.+ self.assertIsNone(body["query"])+ copy = ReplayScanner.objects.get(id=body["id"])+ self.assertEqual(copy.query, stale_query)+ self.assertEqual(copy.experiment_targeting, targeting)+ self.assertEqual(copy.credit_limit, 500)+ self.assertEqual(copy.sampling_rate, 0.25)+ self.assertEqual(copy.scanner_config, source.scanner_config)+ self.assertFalse(copy.enabled)+ self.assertEqual(copy.created_by_id, self.user.id)+ self.assertEqual(sorted(copy.tagged_items.values_list("tag__name", flat=True)), ["billing", "checkout"])++ def test_duplicate_drops_targeting_for_an_experiment_the_caller_cannot_view(self) -> None:+ experiment = create_experiment(self.team, "pricing-test")+ targeting = {"experiment_id": experiment.id, "variant_keys": ["test"], "use_exposure_fallback": False}+ source = self._create_scanner(name="targeted-source", experiment_targeting=targeting)++ # A scanner is viewable at a coarser grain than its experiment, so this caller reads the+ # scanner with the targeting already nulled. Copying the stored row instead would hand them+ # a scanner that scans against an experiment the create path refuses to target.+ with patch(+ "products.replay_vision.backend.api.scanners.is_experiment_accessible",+ return_value=False,+ ):+ resp = self._duplicate(source.id)++ self.assertEqual(resp.status_code, 201, resp.json())+ copy = ReplayScanner.objects.get(id=resp.json()["id"])+ self.assertIsNone(copy.experiment_targeting)+ source.refresh_from_db()+ self.assertEqual(source.experiment_targeting, targeting)++ def test_duplicate_numbers_the_copy_name_when_taken(self) -> None:+ source = self._create_scanner(name="my-scanner")+ first = self._duplicate(source.id)+ second = self._duplicate(source.id)+ self.assertEqual(first.status_code, 201, first.json())+ self.assertEqual(second.status_code, 201, second.json())+ self.assertEqual(first.json()["name"], "my-scanner (copy)")+ self.assertEqual(second.json()["name"], "my-scanner (copy 2)")++ def test_duplicate_rejected_without_resource_level_editor_access(self) -> None:+ source = self._create_scanner(name="my-scanner")+ # A caller holding an object-level editor grant while the resource level is "none":+ # the permission class admits the request, so the action must enforce the+ # resource-level bar itself, exactly as the create action does.+ with (+ patch(+ "products.access_control.backend.facade.user_access_control.UserAccessControl.check_access_level_for_resource",+ side_effect=lambda resource, **_: resource != "replay_scanner",+ ),+ patch(+ "products.access_control.backend.facade.user_access_control.UserAccessControl.has_any_specific_access_for_resource",+ return_value=True,+ ),+ ):+ resp = self._duplicate(source.id)+ self.assertEqual(resp.status_code, 403, resp.json())+ self.assertIn("editor access", resp.json()["detail"])+ self.assertEqual(ReplayScanner.objects.filter(team=self.team).count(), 1)++ def test_duplicate_provisions_no_digest_and_reports_a_distinct_event(self) -> None:+ source = self._create_scanner(name="my-scanner")+ with patch("products.replay_vision.backend.api.scanners.report_user_action") as report:+ resp = self._duplicate(source.id)+ self.assertEqual(resp.status_code, 201, resp.json())+ copy_id = resp.json()["id"]+ self.assertFalse(VisionAction.objects.for_team(self.team.id).filter(scanner_id=copy_id).exists())+ report.assert_called_once()+ self.assertEqual(report.call_args.args[1], "replay_vision_scanner_duplicated")+ properties = report.call_args.args[2]+ self.assertEqual(properties["scanner_id"], copy_id)+ self.assertEqual(properties["source_scanner_id"], str(source.id))+ self.assertEqual(properties["scanner_type"], ScannerType.MONITOR)++class TestScannerEstimatePersistence(_VisionAPITestCase):def _create_payload(self, **overrides: Any) -> dict[str, Any]:payload: dict[str, Any] = {diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.tsindex 0d6de8b1e625..3539855b7fc8 100644--- a/products/replay_vision/frontend/generated/api.ts+++ b/products/replay_vision/frontend/generated/api.ts@@ -809,6 +809,29 @@ export const visionScannersBulkObserveCreate = async (})}+export const getVisionScannersDuplicateCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/vision/scanners/${id}/duplicate/`+}++/**+ * Copy a scanner into a new disabled scanner named "<name> (copy)".+ *+ * Copies the stored model row rather than the serializer's read representation, so a query+ * that no longer validates survives the copy; duplicating through the create endpoint would+ * silently drop it. Experiment targeting is the exception and follows the read path instead.+ * Unlike create, no digest is provisioned: the copy starts disabled and unreviewed.+ */+export const visionScannersDuplicateCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ReplayScannerApi> => {+ return apiMutator<ReplayScannerApi>(getVisionScannersDuplicateCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getVisionScannersImpactRetrieveUrl = (projectId: string,id: string,diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsxindex 7e5ddf8d191c..f4ed2f4fe194 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx@@ -53,7 +53,7 @@ const TYPE_OPTIONS: { value: ScannerType; label: string }[] = SCANNER_TYPE_OPTIOfunction ScannerRowActions({ scanner }: { scanner: ReplayScanner }): JSX.Element {const { deletingIds } = useValues(replayScannersLogic)- const { deleteScanner } = useActions(replayScannersLogic)+ const { deleteScanner, duplicateScanner } = useActions(replayScannersLogic)return (<More@@ -69,6 +69,17 @@ function ScannerRowActions({ scanner }: { scanner: ReplayScanner }): JSX.Element>Edit</LemonButton>+ <LemonButton+ fullWidth+ onClick={() => duplicateScanner(scanner.id)}+ // Duplicating creates a new scanner, so gate on resource-level edit access+ // rather than this row's per-object level.+ disabledReason={getReplayVisionEditDisabledReason()}+ data-attr="vision-scanner-duplicate"+ data-ph-capture-attribute-scanner-type={scanner.scanner_type}+ >+ Duplicate+ </LemonButton><LemonDivider /><LemonButtonfullWidthdiff --git a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.tsindex f3c89195699d..7a6cfad752c1 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts@@ -460,6 +460,56 @@ describe('replayScannersLogic', () => {})})+ describe('duplicateScanner', () => {+ it('calls the duplicate endpoint and routes to the configure page of the copy', async () => {+ const duplicated: string[] = []+ useMocks({+ post: {+ '/api/projects/:team/vision/scanners/:id/duplicate/': ({ params }: { params: any }) => {+ duplicated.push(String(params.id))+ return [201, makeScanner({ id: 'new-id', name: 'Confused checkout (copy)', enabled: false })]+ },+ },+ })+ logic.actions.loadScannersSuccess(scanners, scanners.length)++ await expectLogic(logic, () => logic.actions.duplicateScanner('a')).toFinishAllListeners()++ expect(duplicated).toEqual(['a'])+ expect(router.values.location.pathname).toContain('/replay-vision/new-id/configure')+ expect(logic.values.duplicatingIds).toEqual([])+ })++ it.each([+ {+ case: 'a validation failure with a detail',+ response: [400, { type: 'validation_error', code: 'invalid', detail: 'Bad config' }],+ expectedMessage: 'Failed to duplicate scanner: Bad config',+ },+ {+ case: 'a failure with no error body',+ response: [500, null],+ expectedMessage: 'Failed to duplicate scanner',+ },+ ])(+ 'shows an error, stays put, and releases the in-flight guard on $case',+ async ({ response, expectedMessage }) => {+ useMocks({+ post: { '/api/projects/:team/vision/scanners/:id/duplicate/': () => response },+ })+ const errorToast = jest.spyOn(lemonToast, 'error')+ logic.actions.loadScannersSuccess(scanners, scanners.length)+ const pathBefore = router.values.location.pathname++ await expectLogic(logic, () => logic.actions.duplicateScanner('a')).toFinishAllListeners()++ expect(errorToast).toHaveBeenCalledWith(expectedMessage)+ expect(router.values.location.pathname).toBe(pathBefore)+ expect(logic.values.duplicatingIds).toEqual([])+ }+ )+ })+it('setChartDateRange updates the chart date range', async () => {await expectLogic(logic, () => logic.actions.setChartDateRange('-90d', null)).toMatchValues({chartDateFrom: '-90d',diff --git a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.tsindex 2fc84580532c..75de3d68c18e 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts@@ -24,6 +24,7 @@ import { tagsModel } from '~/models/tagsModel'import {visionScannersCreatorsRetrieve,visionScannersDestroy,+ visionScannersDuplicateCreate,visionScannersList,visionScannersPartialUpdate,visionScannersStatsRetrieve,@@ -156,6 +157,7 @@ export interface replayScannersLogicValues {creators: UserBasicApi[]creatorsLoading: booleandeletingIds: string[]+ duplicatingIds: string[]enabledFilter: EnabledFilter[]filters: ScannersFiltershasActiveFilters: boolean@@ -188,6 +190,9 @@ export interface replayScannersLogicActions {deleteScannerSuccess: (id: string) => {id: string}+ duplicateScanner: (id: string) => {+ id: string+ }loadCreators: () => {value: true}@@ -260,6 +265,13 @@ export interface replayScannersLogicActions {deleting: booleanid: string}+ setScannerDuplicating: (+ id: string,+ duplicating: boolean+ ) => {+ duplicating: boolean+ id: string+ }setScannersFilters: (filters: Partial<ScannersFilters>,replace?: boolean@@ -337,6 +349,8 @@ export const replayScannersLogic = kea<replayScannersLogicType>([deleteScanner: (id: string) => ({ id }),deleteScannerSuccess: (id: string) => ({ id }),setScannerDeleting: (id: string, deleting: boolean) => ({ id, deleting }),+ duplicateScanner: (id: string) => ({ id }),+ setScannerDuplicating: (id: string, duplicating: boolean) => ({ id, duplicating }),toggleScannerEnabled: (id: string) => ({ id }),toggleScannerEnabledStarted: (id: string) => ({ id }),toggleScannerEnabledDone: (id: string) => ({ id }),@@ -438,6 +452,13 @@ export const replayScannersLogic = kea<replayScannersLogicType>([deleting ? [...state, id] : state.filter((i) => i !== id),},],+ duplicatingIds: [+ [] as string[],+ {+ setScannerDuplicating: (state, { id, duplicating }) =>+ duplicating ? [...state, id] : state.filter((i) => i !== id),+ },+ ],scannersLoading: [false,{@@ -534,6 +555,26 @@ export const replayScannersLogic = kea<replayScannersLogicType>([}},+ duplicateScanner: async ({ id }) => {+ const teamId = teamLogic.values.currentTeamId+ // The in-flight guard keeps a double-click from creating two copies.+ if (!teamId || values.duplicatingIds.includes(id)) {+ return+ }+ actions.setScannerDuplicating(id, true)+ try {+ // The server copies the stored config (including fields the list response redacts),+ // picks a free copy name, and leaves the copy disabled for review in the editor.+ const response = await visionScannersDuplicateCreate(String(teamId), id)+ lemonToast.success('Scanner duplicated')+ router.actions.push(urls.replayVisionScannerConfigure(response.id))+ } catch (error: any) {+ lemonToast.error(`Failed to duplicate scanner${error?.detail ? `: ${error.detail}` : ''}`)+ } finally {+ actions.setScannerDuplicating(id, false)+ }+ },+// Refetch after any mutation so the page + creator dropdown + team-wide stats + quota meter stay accurate.deleteScannerSuccess: () => {actions.loadScanners()diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yamlindex 9a4d6110b988..c2cb1d402c48 100644--- a/products/replay_vision/mcp/tools.yaml+++ b/products/replay_vision/mcp/tools.yaml@@ -428,6 +428,9 @@ tools:vision-scanners-draft-create:operation: vision_scanners_draft_createenabled: false+ vision-scanners-duplicate-create:+ operation: vision_scanners_duplicate_create+ enabled: falsevision-scanners-estimate-create:operation: vision_scanners_estimate_createenabled: true