: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): retry failed observations and first-scan handoff (#68123)
Tue Haulunda0fd276ec777
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.pyindex 41cd63436939..b19b1e948393 100644--- a/products/replay_vision/backend/api/observations.py+++ b/products/replay_vision/backend/api/observations.py@@ -1,5 +1,5 @@import uuid-from typing import Any, get_args+from typing import Any, cast, get_argsfrom django.conf import settingsfrom django.db.models import Case, CharField, FloatField, Func, IntegerField, Q, QuerySet, Value, When@@ -12,7 +12,7 @@ import django_filtersfrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_viewfrom pydantic import ValidationError as PydanticValidationError-from rest_framework import mixins, serializers, viewsets+from rest_framework import mixins, serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import NotFound, PermissionDenied, ValidationErrorfrom rest_framework.request import Request@@ -21,11 +21,17 @@ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.streaming import sse_streaming_response+from posthog.models.user import Userfrom posthog.renderers import ServerSentEventRendererfrom products.replay_vision.backend.api.filters import MultiChoiceFilter, OrderByFilter, ordering_enumfrom products.replay_vision.backend.api.observation_progress import stream_observation_progressfrom products.replay_vision.backend.api.observation_stats import compute_observation_stats+from products.replay_vision.backend.api.trigger import (+ WorkflowStartOutcome,+ check_observation_quota,+ start_apply_scanner_workflow,+)from products.replay_vision.backend.error_kinds import ERROR_REASON_HELP_TEXTfrom products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermissionfrom products.replay_vision.backend.models.replay_observation import (@@ -278,6 +284,17 @@ class ObservationStatsSerializer(serializers.Serializer):)+class RetryResponseSerializer(serializers.Serializer):+ """Async-accepted response for POST /vision/scanners/{id}/observations/{id}/retry/."""++ workflow_id = serializers.CharField(+ help_text=(+ "Temporal workflow id for the re-run. The retried observation row is deleted; look up its "+ "replacement via GET /vision/scanners/{id}/observations/?session_id=<session_id>."+ ),+ )++# Single source of truth for orderable fields; the list endpoint's OpenAPI override mirrors these as a string enum.OBSERVATION_ORDER_FIELDS = ("created_at", "started_at", "completed_at", "status")@@ -505,6 +522,40 @@ class ReplayObservationViewSet(payload = compute_observation_stats(scanner, queryset, recent_days=recent_days)return Response(payload)+ @extend_schema(request=None, responses={202: RetryResponseSerializer})+ @action(detail=True, methods=["post"], required_scopes=["replay_scanner:write", "session_recording:read"])+ def retry(self, request: Request, **kwargs: Any) -> Response:+ """Delete a failed observation and re-run its scanner on the same recording. Returns 202 with the workflow handle."""+ observation = self.get_object()+ # The nested route already resolved the scanner for RBAC; the session route pays one FK fetch.+ scanner = getattr(self, "_scanner_for_url_cache", None) or observation.scanner+ # Retry writes to the scanner; the session route's get_object only object-checks the observation row.+ self.check_object_permissions(self.request, scanner)+ if observation.status != ObservationStatus.FAILED:+ raise ValidationError("Only failed observations can be retried.")+ check_observation_quota(self.team.organization_id)+ session_id = observation.session_id+ # Free the UNIQUE(scanner, session_id) slot; the usage ledger is immutable, so the failed attempt stays counted.+ observation.delete()+ workflow_id, outcome = start_apply_scanner_workflow(+ scanner, session_id, triggered_by_user_id=cast(User, request.user).id+ )+ if outcome is WorkflowStartOutcome.ALREADY_RUNNING:+ # The prior run is still closing, so its deterministic id blocks the restart and no new row will appear.+ return Response(+ {"detail": "The previous run is still finishing. Scan the recording again in a moment."},+ status=status.HTTP_409_CONFLICT,+ )+ if outcome is WorkflowStartOutcome.FAILED:+ # `detail` (not `error`) so ApiError carries the message into the frontend toast.+ return Response(+ {+ "detail": "Failed to start the retry. The recording now shows as not scanned and can be scanned again."+ },+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )+ return Response(RetryResponseSerializer({"workflow_id": workflow_id}).data, status=status.HTTP_202_ACCEPTED)+@extend_schema_view(list=extend_schema(diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 1a38bc96dcf2..1d103e372ede 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -1,6 +1,5 @@from typing import Any, NoReturn, cast-from django.conf import settingsfrom django.db import IntegrityErrorfrom django.db.models import CharField, Count, F, Q, QuerySet, Valuefrom django.db.models.functions import Coalesce, NullIf@@ -8,7 +7,6 @@ from django.utils import timezoneimport structlogimport django_filters-from asgiref.sync import async_to_syncfrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_viewfrom pydantic import ValidationError as PydanticValidationError@@ -17,21 +15,12 @@ from rest_framework.decorators import actionfrom rest_framework.exceptions import NotFound, PermissionDenied, ValidationErrorfrom rest_framework.request import Requestfrom rest_framework.response import Response-from temporalio.common import SearchAttributePair, TypedSearchAttributes-from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.schema import RecordingsQueryfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer-from posthog.exceptions import QuotaLimitExceededfrom posthog.models.user import User-from posthog.temporal.common.client import sync_connect-from posthog.temporal.common.search_attributes import (- POSTHOG_SCANNER_ID_KEY,- POSTHOG_SESSION_RECORDING_ID_KEY,- POSTHOG_TEAM_ID_KEY,-)from products.replay_vision.backend.api.filters import (MultiChoiceFilter,@@ -40,8 +29,12 @@ from products.replay_vision.backend.api.filters import (split_csv,validate_csv_choices,)+from products.replay_vision.backend.api.trigger import (+ WorkflowStartOutcome,+ check_observation_quota,+ start_apply_scanner_workflow,+)from products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermission-from products.replay_vision.backend.models.replay_observation import ObservationTriggerfrom products.replay_vision.backend.models.replay_scanner import (ReplayScanner,ScannerModel,@@ -56,17 +49,11 @@ from products.replay_vision.backend.queries import (project_monthly_observations,refresh_scanner_estimate,)-from products.replay_vision.backend.quota import compute_quota_snapshot, sum_enabled_scanner_estimates+from products.replay_vision.backend.quota import sum_enabled_scanner_estimatesfrom 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 (- APPLY_SCANNER_EXECUTION_TIMEOUT,- APPLY_SCANNER_WORKFLOW_NAME,- MAX_SESSION_ID_LENGTH,- build_apply_scanner_workflow_id,-)+from products.replay_vision.backend.temporal.constants import MAX_SESSION_ID_LENGTHfrom products.replay_vision.backend.temporal.scanners import validate_scanner_config-from products.replay_vision.backend.temporal.types import ApplyScannerInputs# Date is set by the schedule at trigger time, not by the user — strip on save._QUERY_FIELDS_TO_STRIP = ("date_from", "date_to")@@ -720,55 +707,15 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):raise PermissionDenied("Triggering an on-demand observation requires session_recording read access.")- snapshot = compute_quota_snapshot(organization_id=self.team.organization_id)- if snapshot.exhausted:- raise QuotaLimitExceeded(- detail=(- f"Monthly Replay Vision quota of {snapshot.monthly_quota:,} observations reached. "- f"Resets {snapshot.period_end.strftime('%b')} {snapshot.period_end.day}."- )- )+ check_observation_quota(self.team.organization_id)body = ObserveRequestSerializer(data=request.data)body.is_valid(raise_exception=True)session_id: str = body.validated_data["session_id"]user = cast(User, request.user)- workflow_id = build_apply_scanner_workflow_id(scanner.id, session_id)- try:- client = sync_connect()- async_to_sync(client.start_workflow)( # type: ignore[misc]- APPLY_SCANNER_WORKFLOW_NAME, # type: ignore[arg-type]- ApplyScannerInputs( # type: ignore[arg-type]- scanner_id=scanner.id,- session_id=session_id,- team_id=scanner.team_id,- triggered_by=ObservationTrigger.ON_DEMAND,- triggered_by_user_id=user.id,- ),- id=workflow_id,- task_queue=settings.REPLAY_VISION_TASK_QUEUE,- execution_timeout=APPLY_SCANNER_EXECUTION_TIMEOUT,- # Stamp the scanner id so on-demand applies count toward the sweep's in-flight cap.- search_attributes=TypedSearchAttributes(- search_attributes=[- SearchAttributePair(key=POSTHOG_TEAM_ID_KEY, value=scanner.team_id),- SearchAttributePair(key=POSTHOG_SESSION_RECORDING_ID_KEY, value=session_id),- SearchAttributePair(key=POSTHOG_SCANNER_ID_KEY, value=str(scanner.id)),- ]- ),- )- except WorkflowAlreadyStartedError as exc:- # Pin to our own workflow_id so a future id_reuse_policy change can't silently 202 an unrelated run.- if exc.workflow_id != workflow_id:- logger.exception("replay_vision.observe.workflow_id_mismatch", workflow_id=workflow_id)- return Response(- {"error": "Failed to start observation workflow"},- status=status.HTTP_503_SERVICE_UNAVAILABLE,- )- logger.info("replay_vision.observe.workflow_already_started", workflow_id=workflow_id)- except Exception:- logger.exception("replay_vision.observe.workflow_start_failed", workflow_id=workflow_id)+ workflow_id, outcome = start_apply_scanner_workflow(scanner, session_id, triggered_by_user_id=user.id)+ if outcome is WorkflowStartOutcome.FAILED:return Response({"error": "Failed to start observation workflow"},status=status.HTTP_503_SERVICE_UNAVAILABLE,diff --git a/products/replay_vision/backend/api/trigger.py b/products/replay_vision/backend/api/trigger.pynew file mode 100644index 000000000000..ba38a76b8ba0--- /dev/null+++ b/products/replay_vision/backend/api/trigger.py@@ -0,0 +1,91 @@+"""Shared Temporal trigger for on-demand scanner applications (observe and retry)."""++import enum+from uuid import UUID++from django.conf import settings++import structlog+from asgiref.sync import async_to_sync+from temporalio.common import SearchAttributePair, TypedSearchAttributes+from temporalio.exceptions import WorkflowAlreadyStartedError++from posthog.exceptions import QuotaLimitExceeded+from posthog.temporal.common.client import sync_connect+from posthog.temporal.common.search_attributes import (+ POSTHOG_SCANNER_ID_KEY,+ POSTHOG_SESSION_RECORDING_ID_KEY,+ POSTHOG_TEAM_ID_KEY,+)++from products.replay_vision.backend.models.replay_observation import ObservationTrigger+from products.replay_vision.backend.models.replay_scanner import ReplayScanner+from products.replay_vision.backend.quota import compute_quota_snapshot+from products.replay_vision.backend.temporal.constants import (+ APPLY_SCANNER_EXECUTION_TIMEOUT,+ APPLY_SCANNER_WORKFLOW_NAME,+ build_apply_scanner_workflow_id,+)+from products.replay_vision.backend.temporal.types import ApplyScannerInputs++logger = structlog.get_logger(__name__)+++class WorkflowStartOutcome(enum.Enum):+ STARTED = "started"+ # A workflow with our deterministic id is already running — the scan is effectively in progress.+ ALREADY_RUNNING = "already_running"+ FAILED = "failed"+++def check_observation_quota(organization_id: UUID) -> None:+ """Raise 402 when the org's monthly observation quota is exhausted."""+ snapshot = compute_quota_snapshot(organization_id=organization_id)+ if snapshot.exhausted:+ raise QuotaLimitExceeded(+ detail=(+ f"Monthly Replay Vision quota of {snapshot.monthly_quota:,} observations reached. "+ f"Resets {snapshot.period_end.strftime('%b')} {snapshot.period_end.day}."+ )+ )+++def start_apply_scanner_workflow(+ scanner: ReplayScanner, session_id: str, *, triggered_by_user_id: int+) -> tuple[str, WorkflowStartOutcome]:+ """Start the deterministic apply-scanner workflow for one (scanner, session); never raises."""+ workflow_id = build_apply_scanner_workflow_id(scanner.id, session_id)+ try:+ client = sync_connect()+ async_to_sync(client.start_workflow)( # type: ignore[misc]+ APPLY_SCANNER_WORKFLOW_NAME, # type: ignore[arg-type]+ ApplyScannerInputs( # type: ignore[arg-type]+ scanner_id=scanner.id,+ session_id=session_id,+ team_id=scanner.team_id,+ triggered_by=ObservationTrigger.ON_DEMAND,+ triggered_by_user_id=triggered_by_user_id,+ ),+ id=workflow_id,+ task_queue=settings.REPLAY_VISION_TASK_QUEUE,+ execution_timeout=APPLY_SCANNER_EXECUTION_TIMEOUT,+ # Stamp the scanner id so on-demand applies count toward the sweep's in-flight cap.+ search_attributes=TypedSearchAttributes(+ search_attributes=[+ SearchAttributePair(key=POSTHOG_TEAM_ID_KEY, value=scanner.team_id),+ SearchAttributePair(key=POSTHOG_SESSION_RECORDING_ID_KEY, value=session_id),+ SearchAttributePair(key=POSTHOG_SCANNER_ID_KEY, value=str(scanner.id)),+ ]+ ),+ )+ except WorkflowAlreadyStartedError as exc:+ # Pin to our own workflow_id so a future id_reuse_policy change can't silently accept an unrelated run.+ if exc.workflow_id != workflow_id:+ logger.exception("replay_vision.observe.workflow_id_mismatch", workflow_id=workflow_id)+ return workflow_id, WorkflowStartOutcome.FAILED+ logger.info("replay_vision.observe.workflow_already_started", workflow_id=workflow_id)+ return workflow_id, WorkflowStartOutcome.ALREADY_RUNNING+ except Exception:+ logger.exception("replay_vision.observe.workflow_start_failed", workflow_id=workflow_id)+ return workflow_id, WorkflowStartOutcome.FAILED+ return workflow_id, WorkflowStartOutcome.STARTEDdiff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 58e8af4e2f0e..d29f9c0fad67 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -10,8 +10,8 @@ from django.utils import timezonefrom parameterized import parameterizedfrom temporalio.exceptions import WorkflowAlreadyStartedError-from posthog.models import Organization, Team, User-from posthog.models.utils import uuid7+from posthog.models import Organization, PersonalAPIKey, Team, User+from posthog.models.utils import generate_random_token_personal, hash_key_value, uuid7from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom products.replay_vision.backend.models.replay_observation import (@@ -1321,8 +1321,8 @@ class TestReplayObservationViewSet(_VisionAPITestCase):self.assertEqual(body["status_counts"]["succeeded"], 0)-@patch("products.replay_vision.backend.api.scanners.async_to_sync")-@patch("products.replay_vision.backend.api.scanners.sync_connect")+@patch("products.replay_vision.backend.api.trigger.async_to_sync")+@patch("products.replay_vision.backend.api.trigger.sync_connect")class TestObserveAction(_VisionAPITestCase):def setUp(self) -> None:super().setUp()@@ -1463,8 +1463,8 @@ class TestObserveAction(_VisionAPITestCase):self.assertEqual(resp.status_code, 503, resp.json())-@patch("products.replay_vision.backend.api.scanners.async_to_sync")-@patch("products.replay_vision.backend.api.scanners.sync_connect")+@patch("products.replay_vision.backend.api.trigger.async_to_sync")+@patch("products.replay_vision.backend.api.trigger.sync_connect")class TestObserveActionFeatureFlag(APIBaseTest):def test_flag_off_returns_404(self, _mock_sync_connect: MagicMock, _mock_async_to_sync: MagicMock) -> None:with patch(@@ -1486,6 +1486,177 @@ class TestObserveActionFeatureFlag(APIBaseTest):self.assertEqual(resp.status_code, 404)+@patch("products.replay_vision.backend.api.trigger.async_to_sync")+@patch("products.replay_vision.backend.api.trigger.sync_connect")+class TestRetryActions(_VisionAPITestCase):+ def setUp(self) -> None:+ super().setUp()+ self.scanner = self._create_scanner()++ def _create_failed(self, session_id: str) -> ReplayObservation:+ return ReplayObservation.objects.create(+ scanner=self.scanner,+ session_id=session_id,+ scanner_snapshot=_snapshot_for(self.scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ status=ObservationStatus.FAILED,+ error_reason="internal_error:boom",+ completed_at=timezone.now(),+ )++ def retry_url(self, observation_id: str) -> str:+ return f"{self.observations_url(str(self.scanner.id))}{observation_id}/retry/"++ def test_retry_deletes_row_and_starts_workflow(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ mock_client = MagicMock()+ mock_sync_connect.return_value = mock_client+ start_workflow = MagicMock()+ mock_async_to_sync.return_value = start_workflow+ observation = self._create_failed("sess-retry")++ resp = self.client.post(self.retry_url(str(observation.id)))+ self.assertEqual(resp.status_code, 202, resp.json())++ expected_workflow_id = build_apply_scanner_workflow_id(self.scanner.id, "sess-retry")+ self.assertEqual(resp.json(), {"workflow_id": expected_workflow_id})+ self.assertFalse(ReplayObservation.objects.filter(id=observation.id).exists())++ args, kwargs = start_workflow.call_args+ self.assertEqual(kwargs["id"], expected_workflow_id)+ inputs = args[1]+ self.assertEqual(inputs.triggered_by, ObservationTrigger.ON_DEMAND)+ self.assertEqual(inputs.triggered_by_user_id, self.user.id)++ def test_retry_rejects_non_failed_statuses(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # Plain loop, not @parameterized: class-level @patch mis-orders expanded args.+ start_workflow = MagicMock()+ mock_async_to_sync.return_value = start_workflow+ cases = [+ (ObservationStatus.SUCCEEDED, timezone.now()),+ (ObservationStatus.INELIGIBLE, timezone.now()),+ (ObservationStatus.PENDING, None),+ ]+ for status_value, completed_at in cases:+ with self.subTest(status=status_value):+ observation = ReplayObservation.objects.create(+ scanner=self.scanner,+ session_id=f"sess-keep-{status_value}",+ scanner_snapshot=_snapshot_for(self.scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ status=status_value,+ error_reason="kind:msg" if status_value == ObservationStatus.INELIGIBLE else "",+ completed_at=completed_at,+ )++ resp = self.client.post(self.retry_url(str(observation.id)))+ self.assertEqual(resp.status_code, 400, resp.json())+ self.assertTrue(ReplayObservation.objects.filter(id=observation.id).exists())+ start_workflow.assert_not_called()++ def test_retry_keeps_row_when_quota_exhausted(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ start_workflow = MagicMock()+ mock_async_to_sync.return_value = start_workflow+ observation = self._create_failed("sess-quota")++ exhausted = MagicMock(exhausted=True, monthly_quota=500, period_end=timezone.now())+ with patch("products.replay_vision.backend.api.trigger.compute_quota_snapshot", return_value=exhausted):+ resp = self.client.post(self.retry_url(str(observation.id)))+ self.assertEqual(resp.status_code, 402, resp.json())+ self.assertTrue(ReplayObservation.objects.filter(id=observation.id).exists())+ start_workflow.assert_not_called()++ def test_retry_dispatch_failure_returns_503_with_row_deleted(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # Documented contract: the slot is freed even when the start fails, so the session can be re-scanned.+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock(side_effect=RuntimeError("temporal unavailable"))+ observation = self._create_failed("sess-broken")++ resp = self.client.post(self.retry_url(str(observation.id)))+ self.assertEqual(resp.status_code, 503)+ # `detail` is what the frontend toast surfaces; `error` would be silently dropped.+ self.assertIn("can be scanned again", resp.json()["detail"])+ self.assertFalse(ReplayObservation.objects.filter(id=observation.id).exists())++ def _personal_api_key(self, scopes: list[str]) -> str:+ value = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="retry-test",+ user=self.user,+ secure_value=hash_key_value(value),+ scopes=scopes,+ )+ return value++ def test_retry_scope_enforcement_for_personal_api_keys(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # The write scope comes from the @action decorator; losing it would let read-scoped keys retry.+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()+ observation = self._create_failed("sess-scopes")+ read_key = self._personal_api_key(["replay_scanner:read", "session_recording:read"])+ write_key = self._personal_api_key(["replay_scanner:write", "session_recording:read"])++ denied = self.client.post(self.retry_url(str(observation.id)), HTTP_AUTHORIZATION=f"Bearer {read_key}")+ self.assertEqual(denied.status_code, 403, denied.json())+ self.assertTrue(ReplayObservation.objects.filter(id=observation.id).exists())++ allowed = self.client.post(self.retry_url(str(observation.id)), HTTP_AUTHORIZATION=f"Bearer {write_key}")+ self.assertEqual(allowed.status_code, 202, allowed.json())++ def test_retry_denied_without_scanner_editor_access(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # The session route's get_object only checks the observation row; retry must object-check the scanner.+ start_workflow = MagicMock()+ mock_async_to_sync.return_value = start_workflow+ observation = self._create_failed("sess-rbac")++ with patch(+ "posthog.rbac.user_access_control.UserAccessControl.check_access_level_for_object",+ side_effect=lambda obj, required_level=None, **_: not isinstance(obj, ReplayScanner),+ ):+ resp = self.client.post(f"/api/environments/{self.team.id}/vision/observations/{observation.id}/retry/")+ self.assertEqual(resp.status_code, 403, resp.json())+ self.assertTrue(ReplayObservation.objects.filter(id=observation.id).exists())+ start_workflow.assert_not_called()++ def test_retry_conflict_when_previous_run_still_active(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ observation = self._create_failed("sess-still-running")+ workflow_id = build_apply_scanner_workflow_id(self.scanner.id, "sess-still-running")+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock(+ side_effect=WorkflowAlreadyStartedError(workflow_id=workflow_id, workflow_type=APPLY_SCANNER_WORKFLOW_NAME)+ )++ resp = self.client.post(self.retry_url(str(observation.id)))+ self.assertEqual(resp.status_code, 409, resp.json())+ # Documented contract: the slot is already freed; the recording can be scanned again shortly.+ self.assertFalse(ReplayObservation.objects.filter(id=observation.id).exists())++ def test_retry_works_on_session_scoped_route(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # The replay-page dock retries through /vision/observations/, not the scanner-nested route.+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()+ observation = self._create_failed("sess-dock")++ resp = self.client.post(f"/api/environments/{self.team.id}/vision/observations/{observation.id}/retry/")+ self.assertEqual(resp.status_code, 202, resp.json())+ self.assertFalse(ReplayObservation.objects.filter(id=observation.id).exists())++class TestSessionReplayObservationViewSet(_VisionAPITestCase):def setUp(self) -> None:super().setUp()diff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.pyindex 2d9a6b60cff1..c3fb882e3627 100644--- a/products/replay_vision/backend/tests/test_quota.py+++ b/products/replay_vision/backend/tests/test_quota.py@@ -372,8 +372,8 @@ class TestVisionQuotaEndpoint(_VisionQuotaTestCase):assert resp.status_code == 404-@patch("products.replay_vision.backend.api.scanners.async_to_sync")-@patch("products.replay_vision.backend.api.scanners.sync_connect")+@patch("products.replay_vision.backend.api.trigger.async_to_sync")+@patch("products.replay_vision.backend.api.trigger.sync_connect")class TestObserveQuotaEnforcement(_VisionQuotaTestCase):@propertydef observe_url(self) -> str:diff --git a/products/replay_vision/frontend/components/ObservationCard.tsx b/products/replay_vision/frontend/components/ObservationCard.tsxindex bd65105a4761..345a928ad421 100644--- a/products/replay_vision/frontend/components/ObservationCard.tsx+++ b/products/replay_vision/frontend/components/ObservationCard.tsx@@ -1,9 +1,12 @@-import { IconRewindPlay, IconSparkles } from '@posthog/icons'-import { LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'+import { IconRefresh, IconRewindPlay, IconSparkles } from '@posthog/icons'+import { LemonButton, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'+import { AccessControlAction } from 'lib/components/AccessControlAction'import { colonDelimitedDuration } from 'lib/utils/durations'import { urls } from 'scenes/urls'+import { AccessControlLevel, AccessControlResourceType } from '~/types'+import type { ReplayObservationApi } from '../generated/api.schemas'import {type ClassifierScannerConfig,@@ -374,9 +377,13 @@ export function IneligibleDetail({ errorReason }: { errorReason: string }): JSX.export function ObservationDockCard({observation,onSeek,+ onRetry,+ retrying = false,}: {observation: ReplayObservationApionSeek?: (timestampMs: number) => void+ onRetry?: () => void+ retrying?: boolean}): JSX.Element {const snapshot = observation.scanner_snapshotconst scannerType = snapshot?.scanner_type@@ -396,7 +403,26 @@ export function ObservationDockCard({</div>{observation.status === 'failed' && observation.error_reason && (- <FailureDetail errorReason={observation.error_reason} />+ <div className="space-y-2">+ <FailureDetail errorReason={observation.error_reason} />+ {onRetry && (+ <AccessControlAction+ resourceType={AccessControlResourceType.SessionRecording}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ size="xsmall"+ type="secondary"+ icon={<IconRefresh />}+ onClick={onRetry}+ loading={retrying}+ data-attr="vision-dock-retry-observation"+ >+ Retry scan+ </LemonButton>+ </AccessControlAction>+ )}+ </div>)}{observation.status === 'ineligible' && observation.error_reason && (diff --git a/products/replay_vision/frontend/components/ObservationsDock.tsx b/products/replay_vision/frontend/components/ObservationsDock.tsxindex 2c822e0b164f..5ade67a18d93 100644--- a/products/replay_vision/frontend/components/ObservationsDock.tsx+++ b/products/replay_vision/frontend/components/ObservationsDock.tsx@@ -102,8 +102,8 @@ function ScannerPicker({ sessionId }: { sessionId: string }): JSX.Element {function ObservationsDockContent({ sessionId }: { sessionId: string }): JSX.Element {const logic = observationsDockLogic({ sessionId })- const { observations, observationsLoading, dockOpen } = useValues(logic)- const { setDockOpen } = useActions(logic)+ const { observations, observationsLoading, dockOpen, retryingObservationIds } = useValues(logic)+ const { setDockOpen, retryObservation } = useActions(logic)// sessionRecordingPlayerLogic is keyed by playerKey+sessionRecordingId; seek the exact mounted// player by its bound props rather than a propless default instance.const { logicProps } = useValues(sessionRecordingPlayerLogic)@@ -166,7 +166,13 @@ function ObservationsDockContent({ sessionId }: { sessionId: string }): JSX.Elem</div>) : (observations.map((observation) => (- <ObservationDockCard key={observation.id} observation={observation} onSeek={seekToTime} />+ <ObservationDockCard+ key={observation.id}+ observation={observation}+ onSeek={seekToTime}+ onRetry={() => retryObservation(observation.id)}+ retrying={retryingObservationIds.includes(observation.id)}+ />)))}</div>diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex f27c9625a77b..eb042f08cc39 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -513,6 +513,14 @@ export interface PaginatedReplayObservationListApi {results: ReplayObservationApi[]}+/**+ * Async-accepted response for POST /vision/scanners/{id}/observations/{id}/retry/.+ */+export interface RetryResponseApi {+ /** Temporal workflow id for the re-run. The retried observation row is deleted; look up its replacement via GET /vision/scanners/{id}/observations/?session_id=<session_id>. */+ workflow_id: string+}+export interface VisionQuotaApi {/** Total observations the org may complete per calendar month. */readonly monthly_quota: numberdiff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.tsindex 2dc30517e25b..493e6702ee2a 100644--- a/products/replay_vision/frontend/generated/api.ts+++ b/products/replay_vision/frontend/generated/api.ts@@ -22,6 +22,7 @@ import type {PatchedVisionActionApi,ReplayObservationApi,ReplayScannerApi,+ RetryResponseApi,ScannerCreatorsResponseApi,ScannerStatsResponseApi,SuggestTagsRequestApi,@@ -262,6 +263,24 @@ export const visionObservationsRetrieve = async (})}+export const getVisionObservationsRetryCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/vision/observations/${id}/retry/`+}++/**+ * Delete a failed observation and re-run its scanner on the same recording. Returns 202 with the workflow handle.+ */+export const visionObservationsRetryCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<RetryResponseApi> => {+ return apiMutator<RetryResponseApi>(getVisionObservationsRetryCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getEnvironmentVisionQuotaRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/vision/quota/`}@@ -457,6 +476,25 @@ export const visionScannersObservationsRetrieve = async (})}+export const getVisionScannersObservationsRetryCreateUrl = (projectId: string, scannerId: string, id: string) => {+ return `/api/projects/${projectId}/vision/scanners/${scannerId}/observations/${id}/retry/`+}++/**+ * Delete a failed observation and re-run its scanner on the same recording. Returns 202 with the workflow handle.+ */+export const visionScannersObservationsRetryCreate = async (+ projectId: string,+ scannerId: string,+ id: string,+ options?: RequestInit+): Promise<RetryResponseApi> => {+ return apiMutator<RetryResponseApi>(getVisionScannersObservationsRetryCreateUrl(projectId, scannerId, id), {+ ...options,+ method: 'POST',+ })+}+export const getVisionScannersObservationsStatsRetrieveUrl = (projectId: string,scannerId: string,diff --git a/products/replay_vision/frontend/logics/observationRetry.ts b/products/replay_vision/frontend/logics/observationRetry.tsnew file mode 100644index 000000000000..4592b0579a72--- /dev/null+++ b/products/replay_vision/frontend/logics/observationRetry.ts@@ -0,0 +1,27 @@+import { ApiError } from 'lib/api-error'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { teamLogic } from 'scenes/teamLogic'++import { visionObservationsRetryCreate } from '../generated/api'+import { refreshVisionQuota } from './visionQuotaLogic'++/** Shared core of the retry surfaces — request, toasts, quota refresh; each caller owns its own follow-up. */+export async function requestObservationRetry(+ observationId: string,+ successMessage = 'Retrying scan — the new observation will appear shortly.'+): Promise<boolean> {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ return false+ }+ try {+ await visionObservationsRetryCreate(String(teamId), observationId)+ lemonToast.success(successMessage)+ refreshVisionQuota()+ return true+ } catch (error) {+ const detail = error instanceof ApiError && error.detail ? `: ${error.detail}` : ''+ lemonToast.error(`Failed to retry observation${detail}`)+ return false+ }+}diff --git a/products/replay_vision/frontend/logics/observationsDockLogic.ts b/products/replay_vision/frontend/logics/observationsDockLogic.tsindex 3862abd710b4..1c7acf90986a 100644--- a/products/replay_vision/frontend/logics/observationsDockLogic.ts+++ b/products/replay_vision/frontend/logics/observationsDockLogic.ts@@ -3,9 +3,10 @@ import { actions, afterMount, connect, kea, key, listeners, path, props, reducerimport { lemonToast } from 'lib/lemon-ui/LemonToast'import { teamLogic } from 'scenes/teamLogic'-import { visionScannersObserveCreate, visionObservationsList } from '../generated/api'+import { visionObservationsList, visionScannersObserveCreate } from '../generated/api'import type { ReplayScannerApi, ReplayObservationApi } from '../generated/api.schemas'import { OBSERVE_POLL_GRACE_MS, scheduleObservationPoll, shouldPollObservations } from './observationPolling'+import { requestObservationRetry } from './observationRetry'import type { observationsDockLogicType } from './observationsDockLogicType'import { refreshVisionQuota } from './visionQuotaLogic'import { visionScannersListLogic } from './visionScannersListLogic'@@ -31,6 +32,9 @@ export const observationsDockLogic = kea<observationsDockLogicType>([observe: (scannerId: string) => ({ scannerId }),observeSuccess: true,observeFailure: true,+ retryObservation: (observationId: string) => ({ observationId }),+ retryObservationSuccess: (observationId: string) => ({ observationId }),+ retryObservationFailure: (observationId: string) => ({ observationId }),setDockOpen: (open: boolean) => ({ open }),setScannerPickerOpen: (open: boolean) => ({ open }),setScannerSearch: (search: string) => ({ search }),@@ -79,10 +83,25 @@ export const observationsDockLogic = kea<observationsDockLogicType>([setScannerPickerOpen: () => '',},],+ retryingObservationIds: [+ [] as string[],+ {+ retryObservation: (state: string[], { observationId }: { observationId: string }) => [+ ...state,+ observationId,+ ],+ retryObservationSuccess: (state: string[], { observationId }: { observationId: string }) =>+ state.filter((id) => id !== observationId),+ retryObservationFailure: (state: string[], { observationId }: { observationId: string }) =>+ state.filter((id) => id !== observationId),+ },+ ],pollUntil: [0,{observeSuccess: () => Date.now() + OBSERVE_POLL_GRACE_MS,+ // The replacement row is inserted by the workflow moments after the retry 202 lands.+ retryObservationSuccess: () => Date.now() + OBSERVE_POLL_GRACE_MS,},],}),@@ -155,6 +174,15 @@ export const observationsDockLogic = kea<observationsDockLogicType>([actions.observeFailure()}},++ retryObservation: async ({ observationId }) => {+ if (!(await requestObservationRetry(observationId))) {+ actions.retryObservationFailure(observationId)+ return+ }+ actions.retryObservationSuccess(observationId)+ actions.loadObservations()+ },}}),diff --git a/products/replay_vision/frontend/observations/ReplayObservation.tsx b/products/replay_vision/frontend/observations/ReplayObservation.tsxindex ba3d8fa50c5e..419d0c5f3351 100644--- a/products/replay_vision/frontend/observations/ReplayObservation.tsx+++ b/products/replay_vision/frontend/observations/ReplayObservation.tsx@@ -1,4 +1,4 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'import { useEffect, useRef, useState } from 'react'import {@@ -9,12 +9,14 @@ import {IconExpand,IconGear,IconInfo,+ IconRefresh,IconSparkles,IconThoughtBubble,IconVideoCamera,} from '@posthog/icons'import { LemonButton, LemonCard, LemonTag, Link } from '@posthog/lemon-ui'+import { AccessControlAction } from 'lib/components/AccessControlAction'import { TZLabel } from 'lib/components/TZLabel'import { dayjs } from 'lib/dayjs'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'@@ -31,6 +33,7 @@ import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'+import { AccessControlLevel, AccessControlResourceType } from '~/types'import { BooleanTag } from '../components/BooleanTag'import { CardHeader } from '../components/CardHeader'@@ -114,7 +117,8 @@ export function ReplayObservationSceneComponent(): JSX.Element {const observationLogic = replayObservationLogic({ id: observationId })useAttachedLogic(observationLogic, replayObservationSceneLogic)- const { observation, observationLoading } = useValues(observationLogic)+ const { observation, observationLoading, retrying } = useValues(observationLogic)+ const { retryObservation } = useActions(observationLogic)if (observationLoading && !observation) {return (@@ -395,6 +399,23 @@ export function ReplayObservationSceneComponent(): JSX.Element {<p className="text-sm text-default m-0 leading-snug font-mono">{failedMessage}</p></LabeledRow>)}+ <div>+ <AccessControlAction+ resourceType={AccessControlResourceType.SessionRecording}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ type="primary"+ size="small"+ icon={<IconRefresh />}+ onClick={() => retryObservation()}+ loading={retrying}+ data-attr="vision-observation-detail-retry"+ >+ Retry scan+ </LemonButton>+ </AccessControlAction>+ </div></div>)}diff --git a/products/replay_vision/frontend/observations/replayObservationLogic.test.ts b/products/replay_vision/frontend/observations/replayObservationLogic.test.tsnew file mode 100644index 000000000000..c2e682656dff--- /dev/null+++ b/products/replay_vision/frontend/observations/replayObservationLogic.test.ts@@ -0,0 +1,67 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { replayObservationLogic } from './replayObservationLogic'+import { replayObservationSceneLogic } from './replayObservationSceneLogic'++describe('replayObservationLogic', () => {+ let retrySpy: jest.Mock+ let sceneLogic: ReturnType<typeof replayObservationSceneLogic.build>++ beforeEach(() => {+ retrySpy = jest.fn(() => [202, { workflow_id: 'wf-retry' }])+ useMocks({+ get: {+ '/api/projects/:team/vision/observations/:id/': {+ id: 'obs-1',+ scanner_id: 'scanner-9',+ session_id: 'sess-1',+ status: 'failed',+ error_reason: 'internal_error:boom',+ scanner_snapshot: {+ name: 'My scanner',+ scanner_type: 'monitor',+ scanner_version: 1,+ model: 'm',+ provider: 'p',+ emits_signals: false,+ scanner_config: { prompt: 'q' },+ },+ scanner_result: null,+ triggered_by: 'schedule',+ created_at: '2026-07-01T00:00:00Z',+ },+ },+ post: {+ '/api/projects/:team/vision/observations/:id/retry/': retrySpy,+ },+ })+ initKeaTests()+ sceneLogic = replayObservationSceneLogic()+ sceneLogic.mount()+ })++ afterEach(() => {+ sceneLogic?.unmount()+ })++ it('retry hands off to the scanner page because the retried row is deleted', async () => {+ const logic = replayObservationLogic({ id: 'obs-1' })+ logic.mount()+ try {+ await expectLogic(logic).toDispatchActions(['loadObservationSuccess'])+ await expectLogic(logic, () => logic.actions.retryObservation()).toDispatchActions([+ 'retryObservationSuccess',+ ])+ expect(retrySpy).toHaveBeenCalledTimes(1)+ expect(logic.values.retrying).toBe(false)+ // Staying put would poll a deleted id and toast an error per tick.+ expect(router.values.location.pathname).toContain('/replay-vision/scanner-9')+ } finally {+ logic.unmount()+ }+ })+})diff --git a/products/replay_vision/frontend/observations/replayObservationLogic.ts b/products/replay_vision/frontend/observations/replayObservationLogic.tsindex 2254ad8753d1..2842da0c2330 100644--- a/products/replay_vision/frontend/observations/replayObservationLogic.ts+++ b/products/replay_vision/frontend/observations/replayObservationLogic.ts@@ -1,11 +1,14 @@import { actions, afterMount, connect, kea, key, listeners, path, props, reducers } from 'kea'+import { router } from 'kea-router'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'import { visionObservationsRetrieve } from '../generated/api'import type { ReplayObservationApi } from '../generated/api.schemas'import { scheduleObservationPoll } from '../logics/observationPolling'+import { requestObservationRetry } from '../logics/observationRetry'import { observationProgressLogic } from './observationProgressLogic'import type { replayObservationLogicType } from './replayObservationLogicType'import { replayObservationSceneLogic } from './replayObservationSceneLogic'@@ -28,6 +31,9 @@ export const replayObservationLogic = kea<replayObservationLogicType>([loadObservation: true,loadObservationSuccess: (observation: ReplayObservationApi) => ({ observation }),loadObservationFailure: true,+ retryObservation: true,+ retryObservationSuccess: true,+ retryObservationFailure: true,}),reducers({@@ -45,6 +51,14 @@ export const replayObservationLogic = kea<replayObservationLogicType>([loadObservationFailure: () => false,},],+ retrying: [+ false,+ {+ retryObservation: () => true,+ retryObservationSuccess: () => false,+ retryObservationFailure: () => false,+ },+ ],}),listeners(({ actions, props, values, cache }) => {@@ -79,6 +93,23 @@ export const replayObservationLogic = kea<replayObservationLogicType>([loadObservationSuccess: reschedulePoll,loadObservationFailure: reschedulePoll,+ retryObservation: async () => {+ const retried = await requestObservationRetry(+ props.id,+ 'Retrying scan — the new observation will appear on the scanner page shortly.'+ )+ if (!retried) {+ actions.retryObservationFailure()+ return+ }+ actions.retryObservationSuccess()+ // The retried row is deleted, so this page's id now dangles — hand off to the scanner.+ const scannerId = values.observation?.scanner_id+ if (scannerId) {+ router.actions.push(urls.replayVision(scannerId))+ }+ },+// When the stream reports the observation has settled, reload once to render the final result.streamCompleted: () => {actions.loadObservation()diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsxindex 108acb203cbf..e734cf906694 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx@@ -1,12 +1,15 @@import { useActions, useValues } from 'kea'-import { IconRefresh, IconRewindPlay } from '@posthog/icons'+import { IconPlay, IconRefresh, IconRewindPlay } from '@posthog/icons'import { LemonButton, LemonInput, LemonTable, LemonTag, LemonTagType, Link, Tooltip } from '@posthog/lemon-ui'+import { AccessControlAction } from 'lib/components/AccessControlAction'import { TZLabel } from 'lib/components/TZLabel'import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { urls } from 'scenes/urls'+import { AccessControlLevel, AccessControlResourceType } from '~/types'+import { FilterPill } from '../../components/FilterPill'import { ObservationResultSummary, ObservationStatusTag } from '../../components/ObservationCard'import type { ReplayObservationApi } from '../../generated/api.schemas'@@ -94,9 +97,11 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):observationStats,scanner,triggeringOnDemandObservation,+ retryingObservationIds,} = useValues(logic)const {refreshObservations,+ retryObservation,setObservationsPage,setObservationsSort,setObservationStatusFilter,@@ -193,16 +198,36 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):key: 'actions',width: 1,render: (_, obs) => (- <LemonButton- size="small"- type="secondary"- icon={<IconRewindPlay />}- to={urls.replaySingle(obs.session_id)}- className="whitespace-nowrap"- data-attr="vision-observation-view-recording"- >- View recording- </LemonButton>+ <div className="flex gap-1">+ {obs.status === 'failed' && (+ <AccessControlAction+ resourceType={AccessControlResourceType.SessionRecording}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconRefresh />}+ onClick={() => retryObservation(obs.id)}+ loading={retryingObservationIds.includes(obs.id)}+ className="whitespace-nowrap"+ data-attr="vision-observation-retry"+ >+ Retry+ </LemonButton>+ </AccessControlAction>+ )}+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconRewindPlay />}+ to={urls.replaySingle(obs.session_id)}+ className="whitespace-nowrap"+ data-attr="vision-observation-view-recording"+ >+ View recording+ </LemonButton>+ </div>),},]@@ -318,11 +343,24 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):noSortingCancellationnouns={['observation', 'observations']}emptyState={- <div className="p-6 text-center text-muted">- {hasActiveObservationFilters- ? 'No observations match your filters.'- : "No observations yet. They'll appear here once the scanner fires on its schedule, or when you manually trigger one from a session recording."}- </div>+ hasActiveObservationFilters ? (+ <div className="p-6 text-center text-muted">No observations match your filters.</div>+ ) : (+ <div className="p-6 flex flex-col items-center gap-3 text-center">+ <div className="text-muted">+ No observations yet. They'll appear here once the scanner fires on its schedule — or+ scan a recording right now.+ </div>+ <LemonButton+ type="primary"+ icon={<IconPlay />}+ to={`${urls.replayVision(scannerId)}?tab=on-demand`}+ data-attr="vision-observations-empty-scan-now"+ >+ Scan a recording now+ </LemonButton>+ </div>+ )}/></div>diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex 8f0eab5ddd42..5b730b453e55 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -21,11 +21,13 @@ import { ClassifierScanner, ReplayScanner, ScorerScanner } from './types'describe('replayScannerLogic', () => {let logic: ReturnType<typeof replayScannerLogic.build>let observeSpy: jest.Mock+ let retrySpy: jest.Mocklet suggestSpy: jest.Mocklet createSpy: jest.MockbeforeEach(() => {observeSpy = jest.fn(() => [202, { workflow_id: 'wf-test' }])+ retrySpy = jest.fn(() => [202, { workflow_id: 'wf-retry' }])suggestSpy = jest.fn(() => [200, { suggestions: [] }])createSpy = jest.fn(() => [201, { id: 'created-scanner' }])useMocks({@@ -36,6 +38,7 @@ describe('replayScannerLogic', () => {post: {'/api/projects/:team/vision/scanners/': createSpy,'/api/projects/:team/vision/scanners/:id/observe/': observeSpy,+ '/api/projects/:team/vision/observations/:id/retry/': retrySpy,'/api/projects/:team/vision/scanners/suggest_tags/': suggestSpy,},})@@ -643,6 +646,24 @@ describe('replayScannerLogic', () => {})})+ describe('retrying failed observations', () => {+ it('retryObservation hits the endpoint and re-arms the poll window for the replacement row', async () => {+ const persisted = replayScannerLogic({ id: 'abc-123' })+ persisted.mount()+ try {+ await expectLogic(persisted, () => persisted.actions.retryObservation('obs-1')).toDispatchActions([+ 'retryObservationSuccess',+ ])+ expect(retrySpy).toHaveBeenCalledTimes(1)+ expect(persisted.values.retryingObservationIds).toEqual([])+ // Without the grace window the replacement row, inserted moments later, is never polled in.+ expect(persisted.values.pollUntil).toBeGreaterThan(Date.now())+ } finally {+ persisted.unmount()+ }+ })+ })+describe('background polling', () => {it('background reloads stay silent so the table stays interactable, foreground loads do not', () => {const persisted = replayScannerLogic({ id: 'abc-123' })diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex b7ed2b1fecea..ee2a18f442f0 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -29,6 +29,7 @@ import type {TagSuggestionApi,} from '../generated/api.schemas'import { OBSERVE_POLL_GRACE_MS, scheduleObservationPoll, shouldPollObservations } from '../logics/observationPolling'+import { requestObservationRetry } from '../logics/observationRetry'import { refreshVisionQuota } from '../logics/visionQuotaLogic'import { type UrlSorting, parseCsvParam, parseSortParam, serializeSortParam } from '../utils/urlParams'import type { replayScannerLogicType } from './replayScannerLogicType'@@ -232,6 +233,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([triggerOnDemandObservation: (sessionId: string, silent = false) => ({ sessionId, silent }),triggerOnDemandObservationSuccess: true,triggerOnDemandObservationFailure: true,+ retryObservation: (observationId: string) => ({ observationId }),+ retryObservationSuccess: (observationId: string) => ({ observationId }),+ retryObservationFailure: (observationId: string) => ({ observationId }),refreshObservations: true,}),@@ -295,7 +299,14 @@ export const replayScannerLogic = kea<replayScannerLogicType>([const response = await visionScannersCreate(String(teamId), scannerToApiBody(body))actions.scannerSaved(scanner)router.actions.replace(urls.replayVision(response.id))- lemonToast.success('Scanner created')+ // First results are minutes away on the schedule — hand off to the instant on-demand tab.+ lemonToast.success('Scanner created', {+ button: {+ label: 'Scan a recording now',+ action: () => router.actions.push(`${urls.replayVision(response.id)}?tab=on-demand`),+ dataAttr: 'vision-scanner-created-scan-now',+ },+ })} else {await visionScannersPartialUpdate(String(teamId), props.id, scannerToPatchedApiBody(body))actions.scannerSaved(scanner)@@ -375,6 +386,21 @@ export const replayScannerLogic = kea<replayScannerLogicType>([0,{triggerOnDemandObservationSuccess: () => Date.now() + OBSERVE_POLL_GRACE_MS,+ // The replacement row is inserted by the workflow moments after the retry 202 lands.+ retryObservationSuccess: () => Date.now() + OBSERVE_POLL_GRACE_MS,+ },+ ],+ retryingObservationIds: [+ [] as string[],+ {+ retryObservation: (state: string[], { observationId }: { observationId: string }) => [+ ...state,+ observationId,+ ],+ retryObservationSuccess: (state: string[], { observationId }: { observationId: string }) =>+ state.filter((id) => id !== observationId),+ retryObservationFailure: (state: string[], { observationId }: { observationId: string }) =>+ state.filter((id) => id !== observationId),},],scannerLoading: [@@ -849,6 +875,15 @@ export const replayScannerLogic = kea<replayScannerLogicType>([triggerOnDemandObservationSuccess: () => refreshVisionQuota(),+ retryObservation: async ({ observationId }) => {+ if (props.id === 'new' || !(await requestObservationRetry(observationId))) {+ actions.retryObservationFailure(observationId)+ return+ }+ actions.retryObservationSuccess(observationId)+ reloadObservationsAndStats()+ },+refreshObservations: () => reloadObservationsAndStats(),loadObservations: async (_, breakpoint) => {diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yamlindex 5223d60af536..6a63a5992c98 100644--- a/products/replay_vision/mcp/tools.yaml+++ b/products/replay_vision/mcp/tools.yaml@@ -67,6 +67,9 @@ tools:`scanner_snapshot` (the scanner's configuration at run time) and `scanner_result` (the LLM output, with anyevent citations). Use `vision-observations-list` to find observation IDs for a session first.feature_flag: replay-vision+ vision-observations-retry-create:+ operation: vision_observations_retry_create+ enabled: falsevision-quota-retrieve:operation: environment_vision_quota_retrieveenabled: true@@ -229,6 +232,9 @@ tools:scanner_type), and the `session_id` of the recording it analysed. Use this to inspect what a scanner hasfound over time; to see every scanner's observations for one session, use `vision-observations-list`.feature_flag: replay-vision+ vision-scanners-observations-retry-create:+ operation: vision_scanners_observations_retry_create+ enabled: falsevision-scanners-observations-stats-retrieve:operation: vision_scanners_observations_stats_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 032f1baeb8f5..793876ad76df 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -47627,6 +47627,14 @@ export namespace Schemas {export type RetrieveFileDownloadResponse = RetrieveBasicOutput | RetrieveCompletedOutput | RetrieveFailedOutput;+ /**+ * Async-accepted response for POST /vision/scanners/{id}/observations/{id}/retry/.+ */+ export interface RetryResponse {+ /** Temporal workflow id for the re-run. The retried observation row is deleted; look up its replacement via GET /vision/scanners/{id}/observations/?session_id=<session_id>. */+ workflow_id: string;+ }+export interface ReviewQueueCreate {/*** Human-readable queue name.