: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): bulk scan recordings on demand (#72678)
Kim Svatos Dugan375f7836e2d9
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 3f0692fc672b..14eec701ca1d 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -65,13 +65,18 @@ from products.replay_vision.backend.queries import (refresh_scanner_estimate,)from products.replay_vision.backend.quota import (+ compute_quota_snapshot,credits_used_by_scanner,current_period_bounds,sum_enabled_scanner_estimated_credits,)from products.replay_vision.backend.tag_suggestions import SuggestionError, suggest_classifier_tagsfrom products.replay_vision.backend.tags import slugify_tag-from products.replay_vision.backend.temporal.constants import MAX_SESSION_ID_LENGTH+from products.replay_vision.backend.temporal.constants import (+ MAX_IN_FLIGHT_APPLIES_PER_SCANNER,+ MAX_IN_FLIGHT_APPLIES_PER_TEAM,+ MAX_SESSION_ID_LENGTH,+)from products.replay_vision.backend.temporal.scanners import validate_scanner_config# Date is set by the schedule at trigger time, not by the user — strip on save.@@ -581,6 +586,60 @@ class ObserveResponseSerializer(serializers.Serializer):)+# One request can start at most this many scans. Bounds the fan-out of a single bulk trigger well+# under the in-flight caps; the frontend selects from one loaded page, so this is rarely the binding+# limit — the concurrency headroom usually is.+BULK_OBSERVE_MAX_SESSIONS = 200+++class BulkObserveRequestSerializer(serializers.Serializer):+ """Body of POST /vision/scanners/{id}/bulk_observe/."""++ session_ids = serializers.ListField(+ child=serializers.CharField(max_length=MAX_SESSION_ID_LENGTH),+ allow_empty=False,+ max_length=BULK_OBSERVE_MAX_SESSIONS,+ help_text=(+ f"Session recording IDs to scan on demand, at most {BULK_OBSERVE_MAX_SESSIONS} per request. "+ "Scans start until the in-flight limit or monthly credit quota is reached; the rest are "+ "reported as skipped rather than failing the whole batch. Already-running sessions are a no-op."+ ),+ )+++class BulkObserveResultSerializer(serializers.Serializer):+ """Per-session outcome of a bulk scan trigger."""++ session_id = serializers.CharField(help_text="The session recording this outcome is for.")+ # Named scan_outcome (not outcome) so its generated enum doesn't collide with other products'+ # `outcome` enums — a bare `outcome` ChoiceField forces the shared OutcomeEnum to be renamed.+ scan_outcome = serializers.ChoiceField(+ choices=[+ ("started", "Started"),+ ("already_running", "Already running"),+ ("skipped_limit", "Skipped — in-flight limit reached"),+ ("skipped_quota", "Skipped — monthly credit quota reached"),+ ("failed", "Failed to start"),+ ],+ help_text=(+ "'started' — a scan workflow was kicked off; 'already_running' — a scan for this session is "+ "already in flight (no-op, not recharged); 'skipped_limit' — the in-flight cap was reached "+ "before this session; 'skipped_quota' — the monthly credit quota would be exceeded; "+ "'failed' — the workflow failed to start."+ ),+ )+++class BulkObserveResponseSerializer(serializers.Serializer):+ """Result of POST /vision/scanners/{id}/bulk_observe/ — partial success by design."""++ started = serializers.IntegerField(help_text="How many new scans were started.")+ results = BulkObserveResultSerializer(+ many=True,+ help_text="Per-session outcomes, in request order (deduplicated).",+ )++class EstimateRequestSerializer(serializers.Serializer):"""Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config."""@@ -985,6 +1044,78 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):status=status.HTTP_202_ACCEPTED,)+ @extend_schema(+ request=BulkObserveRequestSerializer,+ responses={202: BulkObserveResponseSerializer},+ )+ @action(+ detail=True,+ methods=["post"],+ url_path="bulk_observe",+ required_scopes=["replay_scanner:write", "session_recording:read"],+ )+ def bulk_observe(self, request: Request, **kwargs: Any) -> Response:+ """Apply this scanner to many sessions on demand. Starts as many as fit under the in-flight+ caps and monthly credit quota, reporting the rest as skipped rather than failing the batch."""+ scanner = self.get_object()+ # Observation output exposes recording contents, so this requires session_recording read.+ if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):+ raise PermissionDenied("Triggering on-demand observations requires session_recording read access.")++ body = BulkObserveRequestSerializer(data=request.data)+ body.is_valid(raise_exception=True)+ # Dedup preserving order — the same session twice in one batch would just be a wasted no-op.+ session_ids = list(dict.fromkeys(body.validated_data["session_ids"]))+ user = cast(User, request.user)++ # "Scan what fits": compute how many NEW scans can start once, up front. The tighter of the+ # in-flight caps and the remaining monthly quota bounds it; the loser names the skip reason so+ # the user knows which limit they hit. Decrementing a local counter as we start models each new+ # in-flight row without re-querying (a started scan consumes exactly one slot).+ max_starts, skip_reason = self._bulk_observe_headroom(scanner)+ results: list[dict[str, str]] = []+ started = 0+ for session_id in session_ids:+ if started >= max_starts:+ results.append({"session_id": session_id, "scan_outcome": skip_reason})+ continue+ workflow_id, outcome = start_apply_scanner_workflow(+ scanner, session_id, triggered_by_user_id=user.id, trigger=ObservationTrigger.ON_DEMAND+ )+ if outcome is WorkflowStartOutcome.STARTED:+ started += 1+ results.append({"session_id": session_id, "scan_outcome": "started"})+ elif outcome is WorkflowStartOutcome.ALREADY_RUNNING:+ # Already in flight — counted in the caps already, so it consumes no new headroom.+ results.append({"session_id": session_id, "scan_outcome": "already_running"})+ else:+ results.append({"session_id": session_id, "scan_outcome": "failed"})++ return Response(+ BulkObserveResponseSerializer({"started": started, "results": results}).data,+ status=status.HTTP_202_ACCEPTED,+ )++ def _bulk_observe_headroom(self, scanner: ReplayScanner) -> tuple[int, str]:+ """(max_starts, skip_reason): how many new scans can start, and the reason once that's used up."""+ team_in_flight = ReplayObservation.in_flight_for_team(self.team_id).count()+ scanner_in_flight = ReplayObservation.in_flight_for_team(self.team_id).filter(scanner_id=scanner.id).count()+ in_flight_limit = max(+ 0,+ min(+ MAX_IN_FLIGHT_APPLIES_PER_SCANNER - scanner_in_flight,+ MAX_IN_FLIGHT_APPLIES_PER_TEAM - team_in_flight,+ ),+ )+ snapshot = compute_quota_snapshot(self.team.organization_id)+ cost = observation_credits_for_model(scanner.model)+ # Uncapped org (remaining None) → quota never binds; otherwise how many of THIS model's cost fit.+ quota_limit = in_flight_limit if snapshot.remaining is None else (snapshot.remaining // cost if cost else 0)+ # Report quota as the reason only when it's the strictly tighter limit.+ if quota_limit < in_flight_limit:+ return quota_limit, "skipped_quota"+ return in_flight_limit, "skipped_limit"+@extend_schema(parameters=[ScannerImpactQuerySerializer], responses={200: ScannerImpactSerializer})@action(detail=True,diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex ffeb0a29fc9f..41f239ec9657 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -1558,6 +1558,122 @@ class TestObserveAction(_VisionAPITestCase):self.assertEqual(resp.status_code, 503, resp.json())+@patch("products.replay_vision.backend.api.trigger.async_to_sync")+@patch("products.replay_vision.backend.api.trigger.sync_connect")+class TestBulkObserveAction(_VisionAPITestCase):+ def setUp(self) -> None:+ super().setUp()+ self.scanner = self._create_scanner()++ def bulk_url(self, scanner_id: str) -> str:+ return f"{self.scanners_url}{scanner_id}/bulk_observe/"++ def _in_flight(self, session_id: str) -> None:+ ReplayObservation.objects.create(+ scanner=self.scanner,+ session_id=session_id,+ scanner_snapshot=_snapshot_for(self.scanner),+ triggered_by=ObservationTrigger.ON_DEMAND,+ status=ObservationStatus.PENDING,+ )++ def test_starts_a_scan_per_session_and_reports_started(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ mock_sync_connect.return_value = MagicMock()+ start_workflow = MagicMock()+ mock_async_to_sync.return_value = start_workflow++ resp = self.client.post(+ self.bulk_url(str(self.scanner.id)), data={"session_ids": ["a", "b", "c"]}, format="json"+ )+ self.assertEqual(resp.status_code, 202, resp.json())+ body = resp.json()+ self.assertEqual(body["started"], 3)+ self.assertEqual([r["scan_outcome"] for r in body["results"]], ["started", "started", "started"])+ self.assertEqual(start_workflow.call_count, 3)++ def test_deduplicates_session_ids(self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock) -> None:+ mock_sync_connect.return_value = MagicMock()+ start_workflow = MagicMock()+ mock_async_to_sync.return_value = start_workflow++ resp = self.client.post(+ self.bulk_url(str(self.scanner.id)), data={"session_ids": ["dup", "dup", "other"]}, format="json"+ )+ self.assertEqual(resp.status_code, 202, resp.json())+ # The repeated id collapses to one — a second start would be a wasted no-op.+ self.assertEqual([r["session_id"] for r in resp.json()["results"]], ["dup", "other"])+ self.assertEqual(start_workflow.call_count, 2)++ def test_scans_what_fits_under_the_in_flight_cap_and_skips_the_rest(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()+ # Two slots already used against a cap of 3 → only one new scan fits; the other two are skipped.+ self._in_flight("running-1")+ self._in_flight("running-2")++ with patch("products.replay_vision.backend.api.scanners.MAX_IN_FLIGHT_APPLIES_PER_SCANNER", 3):+ resp = self.client.post(+ self.bulk_url(str(self.scanner.id)), data={"session_ids": ["x", "y", "z"]}, format="json"+ )+ self.assertEqual(resp.status_code, 202, resp.json())+ body = resp.json()+ self.assertEqual(body["started"], 1)+ self.assertEqual([r["scan_outcome"] for r in body["results"]], ["started", "skipped_limit", "skipped_limit"])++ def test_skips_for_quota_when_the_credit_budget_is_the_tighter_limit(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()+ # Enough in-flight headroom, but only one observation's worth of credits left → quota is the+ # binding limit, so the skip reason must say quota, not in-flight.+ cost = observation_credits_for_model(self.scanner.model)+ with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", cost):+ resp = self.client.post(+ self.bulk_url(str(self.scanner.id)), data={"session_ids": ["p", "q"]}, format="json"+ )+ self.assertEqual(resp.status_code, 202, resp.json())+ body = resp.json()+ self.assertEqual(body["started"], 1)+ self.assertEqual([r["scan_outcome"] for r in body["results"]], ["started", "skipped_quota"])++ def test_already_running_session_is_a_no_op_and_consumes_no_headroom(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ mock_sync_connect.return_value = MagicMock()++ def _start(*args: Any, **kwargs: Any) -> None:+ # The first session is already running elsewhere; the rest start normally.+ if kwargs["id"] == build_apply_scanner_workflow_id(self.scanner.id, "already"):+ raise WorkflowAlreadyStartedError(workflow_id=kwargs["id"], workflow_type=APPLY_SCANNER_WORKFLOW_NAME)++ mock_async_to_sync.return_value = MagicMock(side_effect=_start)++ resp = self.client.post(+ self.bulk_url(str(self.scanner.id)), data={"session_ids": ["already", "fresh"]}, format="json"+ )+ self.assertEqual(resp.status_code, 202, resp.json())+ body = resp.json()+ self.assertEqual(body["started"], 1)+ self.assertEqual([r["scan_outcome"] for r in body["results"]], ["already_running", "started"])++ def test_rejects_empty_and_oversized_batches(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ empty = self.client.post(self.bulk_url(str(self.scanner.id)), data={"session_ids": []}, format="json")+ self.assertEqual(empty.status_code, 400)+ too_many = self.client.post(+ self.bulk_url(str(self.scanner.id)),+ data={"session_ids": [f"s{i}" for i in range(201)]},+ format="json",+ )+ self.assertEqual(too_many.status_code, 400)++@patch("products.replay_vision.backend.api.trigger.async_to_sync")@patch("products.replay_vision.backend.api.trigger.sync_connect")class TestObserveActionFeatureFlag(APIBaseTest):diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 3634f1d734f3..db21f2b3adbd 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -937,6 +937,61 @@ export interface AffectedCohortResponseApi {readonly window_days: number}+/**+ * Body of POST /vision/scanners/{id}/bulk_observe/.+ */+export interface BulkObserveRequestApi {+ /**+ * Session recording IDs to scan on demand, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch. Already-running sessions are a no-op.+ * @maxItems 200+ * @items.maxLength 128+ */+ session_ids: string[]+}++/**+ * * `started` - Started+ * * `already_running` - Already running+ * * `skipped_limit` - Skipped — in-flight limit reached+ * * `skipped_quota` - Skipped — monthly credit quota reached+ * * `failed` - Failed to start+ */+export type ScanOutcomeEnumApi = (typeof ScanOutcomeEnumApi)[keyof typeof ScanOutcomeEnumApi]++export const ScanOutcomeEnumApi = {+ Started: 'started',+ AlreadyRunning: 'already_running',+ SkippedLimit: 'skipped_limit',+ SkippedQuota: 'skipped_quota',+ Failed: 'failed',+} as const++/**+ * Per-session outcome of a bulk scan trigger.+ */+export interface BulkObserveResultApi {+ /** The session recording this outcome is for. */+ session_id: string+ /** 'started' — a scan workflow was kicked off; 'already_running' — a scan for this session is already in flight (no-op, not recharged); 'skipped_limit' — the in-flight cap was reached before this session; 'skipped_quota' — the monthly credit quota would be exceeded; 'failed' — the workflow failed to start.+ *+ * * `started` - Started+ * * `already_running` - Already running+ * * `skipped_limit` - Skipped — in-flight limit reached+ * * `skipped_quota` - Skipped — monthly credit quota reached+ * * `failed` - Failed to start */+ scan_outcome: ScanOutcomeEnumApi+}++/**+ * Result of POST /vision/scanners/{id}/bulk_observe/ — partial success by design.+ */+export interface BulkObserveResponseApi {+ /** How many new scans were started. */+ started: number+ /** Per-session outcomes, in request order (deduplicated). */+ results: BulkObserveResultApi[]+}+/*** Who this scanner's findings affected in the window; counted from observations, not estimated.*/diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.tsindex 907d96680780..4bcc23517b28 100644--- a/products/replay_vision/frontend/generated/api.ts+++ b/products/replay_vision/frontend/generated/api.ts@@ -12,6 +12,8 @@ import type {AffectedCohortRequestApi,AffectedCohortResponseApi,ApplyPromptSuggestionRequestApi,+ BulkObserveRequestApi,+ BulkObserveResponseApi,CreateTaskFromObservationResponseApi,CurrentPromptSuggestionApi,EstimateRequestApi,@@ -507,6 +509,28 @@ export const visionScannersAffectedCohortCreate = async (})}+export const getVisionScannersBulkObserveCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/vision/scanners/${id}/bulk_observe/`+}++/**+ * Apply this scanner to many sessions on demand. Starts as many as fit under the in-flight+ * caps and monthly credit quota, reporting the rest as skipped rather than failing the batch.+ */+export const visionScannersBulkObserveCreate = async (+ projectId: string,+ id: string,+ bulkObserveRequestApi: BulkObserveRequestApi,+ options?: RequestInit+): Promise<BulkObserveResponseApi> => {+ return apiMutator<BulkObserveResponseApi>(getVisionScannersBulkObserveCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(bulkObserveRequestApi),+ })+}+export const getVisionScannersImpactRetrieveUrl = (projectId: string,id: string,diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.tsindex 968ce9672b03..3fa577a05a07 100644--- a/products/replay_vision/frontend/generated/api.zod.ts+++ b/products/replay_vision/frontend/generated/api.zod.ts@@ -544,6 +544,25 @@ export const VisionScannersAffectedCohortCreateBody = /* @__PURE__ */ zod}).describe('Body of POST \/vision\/scanners\/:id\/affected_cohort\/. Same qualifiers as the impact GET.')+/**+ * Apply this scanner to many sessions on demand. Starts as many as fit under the in-flight+ * caps and monthly credit quota, reporting the rest as skipped rather than failing the batch.+ */+export const visionScannersBulkObserveCreateBodySessionIdsItemMax = 128++export const visionScannersBulkObserveCreateBodySessionIdsMax = 200++export const VisionScannersBulkObserveCreateBody = /* @__PURE__ */ zod+ .object({+ session_ids: zod+ .array(zod.string().max(visionScannersBulkObserveCreateBodySessionIdsItemMax))+ .max(visionScannersBulkObserveCreateBodySessionIdsMax)+ .describe(+ 'Session recording IDs to scan on demand, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch. Already-running sessions are a no-op.'+ ),+ })+ .describe('Body of POST \/vision\/scanners\/{id}\/bulk_observe\/.')+/*** Apply this scanner to one specific session, on demand. Returns 202 with the workflow handle.*/diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsxindex 04b495663485..0be903024ccf 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsx@@ -87,8 +87,10 @@ function RecordingsList({ scannerId }: { scannerId: string }): JSX.Element {const { filters, totalFiltersCount, sessionRecordings, sessionRecordingsResponseLoading, hasNext } =useValues(sessionRecordingsPlaylistLogic)const { setFilters, resetFilters, maybeLoadSessionRecordings } = useActions(sessionRecordingsPlaylistLogic)- const { observationBySession, pendingId, refreshingObservations } = useValues(scannerRunTabLogic({ scannerId }))- const { setVisibleSessionIds, startScan } = useActions(scannerRunTabLogic({ scannerId }))+ const { observationBySession, pendingId, refreshingObservations, bulkScanning } = useValues(+ scannerRunTabLogic({ scannerId })+ )+ const { setVisibleSessionIds, startScan, startBulkScan } = useActions(scannerRunTabLogic({ scannerId }))// Sync the playlist's visible rows into the logic, which owns the observation lookup and polling.const visibleIdsKey = sessionRecordings.map((recording) => recording.id).join(',')@@ -211,6 +213,35 @@ function RecordingsList({ scannerId }: { scannerId: string }): JSX.Element {rowKey="id"emptyState="No recordings match these filters."data-attr="vision-run-recordings-table"+ bulkSelection={{+ noun: ['recording', 'recordings'],+ // Only not-yet-scanned rows are selectable — a scanned or in-flight session has nothing+ // to (re)scan, matching the per-row button that swaps to "View observation".+ isRowSelectable: (recording) =>+ observationBySession[recording.id] || pendingId === recording.id+ ? { disabledReason: 'Already scanned' }+ : true,+ renderActions: ({ selectedKeys, selectedCount, clearSelection }) => (+ <AccessControlAction+ resourceType={AccessControlResourceType.SessionRecording}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPlay />}+ loading={bulkScanning}+ onClick={() => {+ startBulkScan(selectedKeys as string[])+ clearSelection()+ }}+ data-attr="vision-run-bulk-scan"+ >+ Scan {selectedCount} selected+ </LemonButton>+ </AccessControlAction>+ ),+ }}/>{hasNext && (<div className="flex justify-center">@@ -239,8 +270,8 @@ function ScanFromRecordings({ scannerId }: { scannerId: string }): JSX.Element {<div><h3 className="text-sm font-medium mb-1">Pick from your recordings</h3><p className="text-muted text-sm m-0">- Filter your session recordings and run this scanner against any of them. Each scan produces one- observation.+ Filter your session recordings and run this scanner against any of them. Scan one at a time, or+ select several and scan them together. Each scan produces one observation.</p></div><BindLogic logic={sessionRecordingsPlaylistLogic} props={logicProps}>diff --git a/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.test.tsindex 5b2004846631..775fa0cc2474 100644--- a/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.test.ts@@ -14,6 +14,12 @@ describe('scannerRunTabLogic', () => {useMocks({get: {'/api/projects/:team/vision/scanners/:id/': () => [404, {}],+ // The connected replayScannerLogic loads stats on mount; give it a valid shape so its+ // status-counts selector doesn't throw when this test awaits the full listener cascade.+ '/api/projects/:team/vision/scanners/:id/observations/stats/': () => [+ 200,+ { status_counts: { in_flight: 0, succeeded: 0, failed: 0, ineligible: 0 }, total: 0 },+ ],'/api/projects/:team/vision/scanners/:id/observations/': ({ request }: { request: Request }) => {requestedUrls.push(request.url)return [@@ -63,4 +69,30 @@ describe('scannerRunTabLogic', () => {}).toDispatchActions(['loadObservationsSuccess'])expect(logic.values.pendingId).toBeNull()})++ it('bulk scan posts the selected sessions and clears its loading state', async () => {+ let postedBody: any+ useMocks({+ post: {+ '/api/projects/:team/vision/scanners/:id/bulk_observe/': async ({ request }: { request: Request }) => {+ postedBody = await request.json()+ return [+ 202,+ {+ started: 2,+ results: [+ { session_id: 'a', scan_outcome: 'started' },+ { session_id: 'b', scan_outcome: 'started' },+ { session_id: 'c', scan_outcome: 'skipped_limit' },+ ],+ },+ ]+ },+ },+ })+ await expectLogic(logic, () => logic.actions.startBulkScan(['a', 'b', 'c'])).toFinishAllListeners()+ // The selected session ids reach the bulk endpoint, and the button's loading state is released.+ expect(postedBody).toEqual({ session_ids: ['a', 'b', 'c'] })+ expect(logic.values.bulkScanning).toBe(false)+ })})diff --git a/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.tsindex 2cbea44ad987..0bc31fce9860 100644--- a/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.ts@@ -12,9 +12,10 @@ import {selectors,} from 'kea'+import { lemonToast } from 'lib/lemon-ui/LemonToast'import { teamLogic } from 'scenes/teamLogic'-import { visionScannersObservationsList } from '../generated/api'+import { visionScannersBulkObserveCreate, visionScannersObservationsList } from '../generated/api'import type { ReplayObservationApi } from '../generated/api.schemas'import { scheduleObservationPoll } from '../logics/observationPolling'import { replayScannerLogic } from './replayScannerLogic'@@ -33,6 +34,7 @@ export interface ScannerRunTabLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scannerRunTabLogicValues {triggeringOnDemandObservation: boolean // replayScannerLogic+ bulkScanning: booleanobservationBySession: Record<string, RowObservation>pendingId: string | nullrefreshingObservations: boolean@@ -55,6 +57,9 @@ export interface scannerRunTabLogicActions {triggerOnDemandObservationSuccess: () => {value: true} // replayScannerLogic+ bulkScanDone: () => {+ value: true+ }loadObservations: (background?: any) => {background: any}@@ -70,6 +75,9 @@ export interface scannerRunTabLogicActions {setVisibleSessionIds: (sessionIds: string[]) => {sessionIds: string[]}+ startBulkScan: (sessionIds: string[]) => {+ sessionIds: string[]+ }startScan: (sessionId: string) => {sessionId: string}@@ -111,6 +119,8 @@ export const scannerRunTabLogic = kea<scannerRunTabLogicType>([actions({setVisibleSessionIds: (sessionIds: string[]) => ({ sessionIds }),startScan: (sessionId: string) => ({ sessionId }),+ startBulkScan: (sessionIds: string[]) => ({ sessionIds }),+ bulkScanDone: true,setPendingId: (sessionId: string) => ({ sessionId }),loadObservations: (background = false) => ({ background }),loadObservationsSuccess: (bySession: Record<string, RowObservation>) => ({ bySession }),@@ -149,6 +159,14 @@ export const scannerRunTabLogic = kea<scannerRunTabLogicType>([loadObservationsFailure: () => false,},],+ // Loading state for the "Scan N selected" bulk button.+ bulkScanning: [+ false,+ {+ startBulkScan: () => true,+ bulkScanDone: () => false,+ },+ ],}),selectors({@@ -186,6 +204,48 @@ export const scannerRunTabLogic = kea<scannerRunTabLogicType>([actions.triggerOnDemandObservation(sessionId, true)},+ startBulkScan: async ({ sessionIds }) => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId || sessionIds.length === 0) {+ actions.bulkScanDone()+ return+ }+ try {+ const response = await visionScannersBulkObserveCreate(String(teamId), props.scannerId, {+ session_ids: sessionIds,+ })+ const results = response.results ?? []+ const started = response.started+ // The backend scans what fits and reports the rest — surface the split so the user+ // knows a partial run happened rather than assuming everything started.+ const limited = results.filter(+ (r) => r.scan_outcome === 'skipped_limit' || r.scan_outcome === 'skipped_quota'+ ).length+ const failed = results.filter((r) => r.scan_outcome === 'failed').length+ const extras = [+ limited ? `${limited} skipped (limit reached)` : null,+ failed ? `${failed} failed to start` : null,+ ]+ .filter(Boolean)+ .join(', ')+ if (started > 0) {+ lemonToast.success(+ `Started ${started} scan${started === 1 ? '' : 's'}${extras ? ` — ${extras}` : ''}`+ )+ } else if (limited > 0) {+ lemonToast.warning("No scans started — you've hit the in-flight or monthly credit limit.")+ } else {+ lemonToast.error('No scans started. Please try again.')+ }+ // Started scans create pending observations server-side — refetch to reflect them.+ actions.loadObservations()+ } catch (error: any) {+ lemonToast.error(`Bulk scan failed${error?.detail ? `: ${error.detail}` : ''}`)+ } finally {+ actions.bulkScanDone()+ }+ },+// A successful trigger creates a pending observation server-side — refetch to pick it up.triggerOnDemandObservationSuccess: () => actions.loadObservations(),diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yamlindex 49cbeafcc21e..57b1c2366621 100644--- a/products/replay_vision/mcp/tools.yaml+++ b/products/replay_vision/mcp/tools.yaml@@ -145,6 +145,9 @@ tools:creates a new cohort. Use it anywhere cohorts work: funnel breakdowns, retention, survey targeting,experiment exclusion. Fails when the window has no users or none resolve to a person profile.feature_flag: replay-vision+ vision-scanners-bulk-observe-create:+ operation: vision_scanners_bulk_observe_create+ enabled: falsevision-scanners-create:operation: vision_scanners_createenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 09b11da6c6ee..084c2f2fd844 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -13331,6 +13331,62 @@ export namespace Schemas {notification_ids: string[];}+ /**+ * Body of POST /vision/scanners/{id}/bulk_observe/.+ */+ export interface BulkObserveRequest {+ /**+ * Session recording IDs to scan on demand, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch. Already-running sessions are a no-op.+ * @maxItems 200+ * @items.maxLength 128+ */+ session_ids: string[];+ }++ /**+ * * `started` - Started+ * * `already_running` - Already running+ * * `skipped_limit` - Skipped — in-flight limit reached+ * * `skipped_quota` - Skipped — monthly credit quota reached+ * * `failed` - Failed to start+ */+ export type ScanOutcomeEnum = typeof ScanOutcomeEnum[keyof typeof ScanOutcomeEnum];+++ export const ScanOutcomeEnum = {+ Started: 'started',+ AlreadyRunning: 'already_running',+ SkippedLimit: 'skipped_limit',+ SkippedQuota: 'skipped_quota',+ Failed: 'failed',+ } as const;++ /**+ * Per-session outcome of a bulk scan trigger.+ */+ export interface BulkObserveResult {+ /** The session recording this outcome is for. */+ session_id: string;+ /** 'started' — a scan workflow was kicked off; 'already_running' — a scan for this session is already in flight (no-op, not recharged); 'skipped_limit' — the in-flight cap was reached before this session; 'skipped_quota' — the monthly credit quota would be exceeded; 'failed' — the workflow failed to start.+ *+ * * `started` - Started+ * * `already_running` - Already running+ * * `skipped_limit` - Skipped — in-flight limit reached+ * * `skipped_quota` - Skipped — monthly credit quota reached+ * * `failed` - Failed to start */+ scan_outcome: ScanOutcomeEnum;+ }++ /**+ * Result of POST /vision/scanners/{id}/bulk_observe/ — partial success by design.+ */+ export interface BulkObserveResponse {+ /** How many new scans were started. */+ started: number;+ /** Per-session outcomes, in request order (deduplicated). */+ results: BulkObserveResult[];+ }+/*** * `new` - New* * `open` - Open