: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 UI for single session observation in replay (#58913)
Hayne Ryud6577af783f7
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 60334afc4821..5af048b9f6e6 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -3763,17 +3763,17 @@ snapshots:replay-scenes-group--group-recording-tab-empty--light:hash: v1.k794b7964.9277ae174a62b01665c4e77d032d04ae93b73b8fd15447e47e7ca1915397d11f.kJffVl3sofs8zSMyHH78rt5FFhCOBeAKh1Z7MfnTvwcreplay-scenes-group--group-recording-tab-multiple-and-not-found--dark:- hash: v1.k794b7964.ab0e9d8ac6aae5eeb4b207f3e841ed1dcd47815b2979df82c65c53739a52cb9e.4246eDrw9iIWHL3eiJd-UUmGmKT4sphI4gWvLjc9mcg+ hash: v1.k794b7964.2a78cbbe5769ee76bff2695f22fda47e249bd070c94a40cff1b3020496022911.d5Wj-TfFawHiOLkliwUw40GOsUOGdg-CJAH5fknbLKIreplay-scenes-group--group-recording-tab-multiple-and-not-found--light:- hash: v1.k794b7964.c2460615efd872435b8e9624866bd63291dc251667a20d032ade7da68fed47a0.exWQC0Tc6OogR6BpdevUQ6VRUZXRPyyPeUh3vb_3q6k+ hash: v1.k794b7964.d8056449450e1b9fca8334a799cc94c07c1f822da9f89286d0e87c5ffb7347f7.2Mj0yI-YAk501nE-4iQlOTqLRw6h8NBK8D_3gJRjQVAreplay-scenes-person--person-recording-tab-empty--dark:hash: v1.k794b7964.ace0d8cafaecebabcd55ea6909690ee6428ebc52384c463c1e176b06d2e03a1f.6I5gEHazGQ60ArmwFnEFfWNyJS-T2xlSVMbEYk8LTCMreplay-scenes-person--person-recording-tab-empty--light:hash: v1.k794b7964.52c19d8b739c74cc16baa252f96beea6879cb39402bfe76d24e251680658e804.X9m7B_OvJcHVdvlhILEseh7OAsqkTm2zMhLVb27NONkreplay-scenes-person--person-recording-tab-multiple-and-not-found--dark:- hash: v1.k794b7964.e8a516383ba4d93d6ae14e3f6fb006324d089f9fe187db2a629fcc4ac6ae750e.x-KdSFTpfhklonFiqUeKnppWScAhmYOBUsqCTkrrUBY+ hash: v1.k794b7964.ad20974bc8359c768b36b300158ca7f17d6ee5e658baddea54c08e5edb163b4c.C4FKX_HCHZgDgubTlTRcEw449hqOcoD_ptCpbWpURiEreplay-scenes-person--person-recording-tab-multiple-and-not-found--light:- hash: v1.k794b7964.f9cefe0b87caa59de07dd308c51acf6cc3243c681edaa290337aaeb3c75bd433.OBrCC49hrfhnDH_TlW02Qc5xojxb9-EmYo_oRJMnRBw+ hash: v1.k794b7964.7971eb327021ba8ada4b3e6efa457074c35b2eceeee29eb65ec3202a511a7aff.rF2OKRjWsIWulZwhaHonm44vd9mZD3mCa0drOiBitkoreplay-sharing--private-link--dark:hash: v1.k794b7964.1f6922ffd3028c6009f63d7c73edb3138f41dd971be364e3e0c78e608577f611.XsnlRF6f_3C5MFQlVuUeGgQ1lQuKYwgWYvl0507yIdsreplay-sharing--private-link--light:@@ -3787,33 +3787,33 @@ snapshots:replay-tabs-collections--recordings-play-lists--light:hash: v1.k794b7964.5fe311c94fa56875877c77ccc256e35d5fd32ed656bcd440000b01e5ea261d5f.IyqpwLPnMFH9bnUd_aToFTPfZB4_LAwzSr5N1lF2nykreplay-tabs-home-failure--not-found--dark:- hash: v1.k794b7964.146867da4a170c23d698115dc337c6f0dde967237ee26026f910bd5a9f9a0184.PGgim_Si0VXwlcMS1CpKKmQmgx9KZMPsZwdzj17yPkM+ hash: v1.k794b7964.e07b4d642f54f1c0e2d7440814236d38dbad05203ce1d3d8ea481cce7aea2f81._3CxxxFFkEBMCQpSRofzNLR7EjEYTtnAIX1ZOwfKWWAreplay-tabs-home-failure--not-found--light:- hash: v1.k794b7964.c92cd9ff5d7273f0bd102e69c7c6487a353177de956ac6290feafd00852b4fdc.3fDVHUO_Cpcmq7Et5bfc_UL_dQiJn7_iGfDypToL99o+ hash: v1.k794b7964.d67b825af56b6847b32eba945f45b36a7bb659dccd29bf5196cea714fd1e94d9.JGRRES--YXJQJTCC3M416l84oIgV9q_Wy-GSBUH7TzAreplay-tabs-home-filters-banner--product-analytics-over-limit--dark:- hash: v1.k794b7964.770e6aa902bc5eaf2e68b4be71689b42f8bbfc3fc4091baafa7e5a501ab6d03b.dpH67n7nCK3vSp4r9KTjjsXQ5N2og1UNklFH0ps8SQM+ hash: v1.k794b7964.9ee25b6594b07076cff0c2d285096a7e2d2031e3d30e58d4d043c8e3e0d44447.0wsqTslGRLqaidPoW0-teojry4FMwKSiOqo9E6i6AG8replay-tabs-home-filters-banner--product-analytics-over-limit--light:- hash: v1.k794b7964.8c94316dcd436de5d86df5d7cf2d2dc496c992a29febf7bf41a284755e308edb.NFwl-K4ZTeXBtcHYyOyJSjuajg6eM6ehlG3VIZwIcro+ hash: v1.k794b7964.9e6e0a6b500bea8a289281eaadb397a36a19381074a6d72291d186c7dbc89837.O2Q9Dv4VQBJqT5IlxRTwoYrGw7cXNkhGd2ikmDmIrZcreplay-tabs-home-filters-banner--product-analytics-under-limit--dark:- hash: v1.k794b7964.abf3a2cd2c24d9c60e2b6c49822bae99a02f48b5e01fa31498045893571c6d93.JLzGwEcLjcazRyeCy1yhBQeCobn1ARy1EbpWLzXDewQ+ hash: v1.k794b7964.ad52b017918667aa5e878fbd894a67cadcb4e9a91e5e9501c9df690a5fd62fc3.O6syOaXnY-TOC55HLThwf0Ydm0kFnu27gikMf_HS0L8replay-tabs-home-filters-banner--product-analytics-under-limit--light:- hash: v1.k794b7964.d2af98d29cdc68c189c26d5ab7bc9f741fbc9b9f6727067be5307dabe9113294.7lAyallFisBdaaGRAMxX6Wu_uWUqfSDZ9jz-6Mx_IK0+ hash: v1.k794b7964.dd4ff7babf16db27491f4164bf8478e9c6b3fba1a163c921e836c7ff7596964c.HnXAAqLQVTnrkIHCowYuko98xLnYAdgTo8-RPR_Nd5wreplay-tabs-home-success--filters-expanded--dark:- hash: v1.k794b7964.473972b3079eaf0b2f38d1292fe5f13a577addb322d784f9a86f4c058ed4b155.o0bwGTarT7D-zr7OlnS-kbUuRt_Ja4LmhK2kURLaiJo+ hash: v1.k794b7964.d7820baaf551e18f35447516a501b089bd5748e027fcc38aa9d5b2f2f759cb81.Z2PgnbfVxo3CKDFwM2-oYcfeObDkZMCY6LYI2w-cjicreplay-tabs-home-success--filters-expanded--light:- hash: v1.k794b7964.77a0b52a7baae4a5702b77260eeb861cf2d815d38507bf96ffebc2320727a6b2.Tst6fudOidCpfRdE7F-A6w6EpEGerrCQxIjIvam76TY+ hash: v1.k794b7964.c057819eb761f78a1e62f0d9527df812b3bf0324207139cdd5e439c9d19a0a76.Fct6rndoF34rPJl8LtFWz209WIYYALPmqbYK57vMO-creplay-tabs-home-success--filters-expanded-lots-of-results--dark:- hash: v1.k794b7964.2ad9f66402f39d0775bfc9d0807cc6168b63715466a001afaf62c8ab2045265f.KiV8GmxOIRFPnmwf-HqfsiKir-ODdU084V0WWRCtziY+ hash: v1.k794b7964.f9921ecf3175589fe7bf17960907980a986f88902f7de95c1ed5ba9585ab8091.qL72B0cRelizEnHIgO9aTRoVALtioUTjTWXvfU-7cEwreplay-tabs-home-success--filters-expanded-lots-of-results--light:- hash: v1.k794b7964.33a7b966488d6e5cf5fb3c49574a089d82d5ed575458fba816ebe265e7a9a668.4EW7h9yph8PXNB00sN-oC_frtj2Ynom1kSpqkYheei0+ hash: v1.k794b7964.422a985bbf5a18682e9d1a387b8f05e001f78f3c342a70ae026fb12e52d5ac6c._0MaiAKH162XwpZEZmYFklXvl8sqqISumiMKw4L2Vh8replay-tabs-home-success--filters-expanded-lots-of-results-narrow--dark:- hash: v1.k794b7964.cb4f3112e5036f6cda528ad24ffa2d52b156bd6774a65ad24b35d5a32291e297.OaRd0jazkuhplOybw4xjUAGpEOetPIB0HvD5UlqEyXQ+ hash: v1.k794b7964.9eb9674e94a41c10effeeeb7c631b30daf5bd5c3033a9ea40ba84de452f9d0eb.SXJjJW2IxZlKOMBoR-5vL1IgNPUtJoeYm7mpcvan-K4replay-tabs-home-success--filters-expanded-lots-of-results-narrow--light:- hash: v1.k794b7964.ce63b941242bd17bd52f72334970d932043233e16af07d71322aa58e4a455049.i5WByIlOQmoxd2hEJfwl1Wkswem6UBmHnA54lyXeLSg+ hash: v1.k794b7964.4e78e7a5c4521d972a81abe81ba2c2888c83a1fa8a3837a5f7a90ed4a06aec05.VVHbckchv1eFFqUNXC0C3AeYTex8t44TsCRrh9Rg7XEreplay-tabs-home-success--recent-recordings--dark:- hash: v1.k794b7964.6e2134c32682bac3aff97f4b3e2cf018ca4d17a2beead3806f0a4852a0124b5d.rY46FoLSQ4jrouHs1rsIvU7M9hKyMqWzcEq9ZCgyGsk+ hash: v1.k794b7964.6d9c8e6ab8755da013cef7483f8f4b609a5612ff4073773ebd4f08a1c339050b.EY88syRfX38f-CPicNxx8FB9B-3spbSor5UHR_4mOlAreplay-tabs-home-success--recent-recordings--light:- hash: v1.k794b7964.3da17eaca3c6291079b0ab6c78fd9af0826aef7d1dae4ea852add49f54ad32a1.qpBGboYzQjc2puP-cybpOzvKK7IxVlaTglAR7k1aE6k+ hash: v1.k794b7964.67a26ef6539a46cb0988bbc276589315f480bf26674cd009c4515de9cd63d89e.Y3LPKS6TYxU_anJeppiX0sIoi1aDCruztiKl3d9iy3Areplay-tabs-home-success--recent-recordings-empty--dark:hash: v1.k794b7964.40af47275bebca0f7f99434208bd8617d0851b315d7890375df108a13a0751c1.vWjtSWUeoaqZIL6oHCmlFwbMmUCNRikdbhZVSvjrX_kreplay-tabs-home-success--recent-recordings-empty--light:@@ -3823,9 +3823,9 @@ snapshots:replay-tabs-home-success--recordings-play-list-no-pinned-recordings--light:hash: v1.k794b7964.8fb525353e31e98c6806f8693f261fd28a66b223e8dc5e93e718a4179b4cbd3c.qnY_7DCnAnAhQz-aTDO5Gr1FZtdy2zCCKIZ_XsSPZMcreplay-tabs-home-success--second-recording-in-list--dark:- hash: v1.k794b7964.86c81ea7040f6caaf84212a9f43c9d862c752dbf0ad4e4235a064788dc5170a2.fXxHiZkxvTHg4HQ5qth3_uNA2O0j9RrRHfZKN7uWAqo+ hash: v1.k794b7964.e55e3f17536c13f7561cd6275dc2c63e9950e7f83394de972364ba0b51211c58.S9fUa5v1eSxXT-D7D7lmS3os0kSj8a1gIhb7EPsivNcreplay-tabs-home-success--second-recording-in-list--light:- hash: v1.k794b7964.5e17562ab9087a2998b0a37d55aa23923540088cf164d8e58e83c50dfbdb76d9.HNvXtacWHHQZH0iWO5MrKJVcGpfq0CcZTff9r6oNVZQ+ hash: v1.k794b7964.36ceb39895861de3d53bf2bb36ab9803c836b8cdef6a7ac4fb1d7dfee1bf3e26.OVDv2SGgEZpivhEYSsajGdVchscMaXMBMLAY-YDW3dwscenes-app-ai-observability-conversation-display--anthropic--dark:hash: v1.k794b7964.9c97c85c94605b8ce34469ddb269688ff84d0c3aa87818e6f9c94745c114a434.o6eqWM3HKURlW-MBuPGhIw6sslncdZGR6-pBuz1FVBMscenes-app-ai-observability-conversation-display--anthropic--light:@@ -5143,9 +5143,9 @@ snapshots:scenes-app-notebooks--numbered-list--light:hash: v1.k794b7964.70eadeb962d410add11648f7ba0939a5e5134c297e6467439aeb72f9e22b1504.MtRYdPpUsMVbKGiSvE2DCK6AQ9FVFhg44Y4_1g-Y81cscenes-app-notebooks--recordings-playlist--dark:- hash: v1.k794b7964.35bb673c4f22527d3a03e58207db7d9d1faa9463891b329dbfb52f3ef7cc48a7.Iit5uWevN-D0BU4oX0H8KlQMEtPY2oYfXOMaYqSa2eo+ hash: v1.k794b7964.98c49d6b24ca6df18b009a337dde8950bc26be2d85c46ee74aa907763d7f7b8f.amgp-YwT_1y1Rn_-Cgf5GV0HWdLUI9WAPiAEQrg3FB0scenes-app-notebooks--recordings-playlist--light:- hash: v1.k794b7964.012f6fb539820b075ae8d5accacfb4cec5841439db12fe4ca60042dbff825f49.4JWn67v9fQALoJEr6y9Y5qudTOWwFWj43M4M9DLv7oo+ hash: v1.k794b7964.43d83304243555e8289803c97eee4032ce2f1ec9de3a6dfbc7c2866e8b112138.rLVv-YWxkRjlmhH7nOpT0-8VHFdz_dKQdc1H27ESyacscenes-app-notebooks--text-formats--dark:hash: v1.k794b7964.18a89e84a3d1023246de21577eb15c78d44eaa252d6856a347ca8fec65154261.1f-7Wr58KvWTAUOob23JEU24MSDBz33i0xyzElngIS0scenes-app-notebooks--text-formats--light:diff --git a/frontend/src/scenes/session-recordings/player/SessionRecordingPlayer.tsx b/frontend/src/scenes/session-recordings/player/SessionRecordingPlayer.tsxindex e19c0178cb3f..c313263e3ec9 100644--- a/frontend/src/scenes/session-recordings/player/SessionRecordingPlayer.tsx+++ b/frontend/src/scenes/session-recordings/player/SessionRecordingPlayer.tsx@@ -4,8 +4,12 @@ import clsx from 'clsx'import { BindLogic, useValues } from 'kea'import { useRef } from 'react'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { MatchingEventsMatchType } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'+import { ObservationsDock } from 'products/replay_vision/frontend/components/ObservationsDock'+import { playerSettingsLogic } from './playerSettingsLogic'import { PlayerSidebar } from './PlayerSidebar'import { PlayerSummaryDock } from './PlayerSummaryDock'@@ -87,8 +91,10 @@ function SessionRecordingPlayerInternal({}): JSX.Element {const { isVerticallyStacked, sidebarOpen } = useValues(playerSettingsLogic)const { logicProps } = useValues(sessionRecordingPlayerLogic)+ const { featureFlags } = useValues(featureFlagLogic)const showSummaryDock =!noMeta && (logicProps.mode ?? SessionRecordingPlayerMode.Standard) === SessionRecordingPlayerMode.Standard+ const showVisionDock = showSummaryDock && !!featureFlags[FEATURE_FLAGS.REPLAY_VISION]return (<div@@ -99,7 +105,7 @@ function SessionRecordingPlayerInternal({><div className="flex flex-col flex-1 min-w-0 min-h-0"><PurePlayer noMeta={noMeta} noBorder={noBorder} />- {showSummaryDock && <PlayerSummaryDock />}+ {showVisionDock ? <ObservationsDock /> : showSummaryDock && <PlayerSummaryDock />}</div>{withSidebar && <PlayerSidebar />}</div>diff --git a/frontend/src/scenes/session-recordings/playlist/SessionRecordingPreview.tsx b/frontend/src/scenes/session-recordings/playlist/SessionRecordingPreview.tsxindex 9c5702a9ee49..fecedd0b05da 100644--- a/frontend/src/scenes/session-recordings/playlist/SessionRecordingPreview.tsx+++ b/frontend/src/scenes/session-recordings/playlist/SessionRecordingPreview.tsx@@ -328,7 +328,10 @@ export const SessionRecordingPreview = memo(const { filters } = useValues(sessionRecordingsPlaylistLogic)const { recordingPropertiesById, recordingPropertiesLoading } = useValues(sessionRecordingsListPropertiesLogic)const { featureFlags } = useValues(featureFlagLogic)- const summaryEnabled = !!featureFlags[FEATURE_FLAGS.REPLAY_VIDEO_BASED_SUMMARIZATION]++ // Vision teams trigger analysis from the replay-page dock, not the list. Hide the legacy+ // summarize icon when replay-vision is on so it doesn't surface alongside Vision.+ const replayVisionEnabled = !!featureFlags[FEATURE_FLAGS.REPLAY_VISION]const recordingProperties = recordingPropertiesById[recording.id]const loading = !recordingProperties && recordingPropertiesLoading@@ -418,7 +421,7 @@ export const SessionRecordingPreview = memo(<div className="flex items-center justify-between"><FirstURL startUrl={recording.start_url} />- {summaryEnabled && <RecordingSummaryIcon recording={recording} />}+ {!replayVisionEnabled && <RecordingSummaryIcon recording={recording} />}</div></div>diff --git a/posthog/api/__init__.py b/posthog/api/__init__.pyindex 4b24d2dce6cb..f8274e6c9e08 100644--- a/posthog/api/__init__.py+++ b/posthog/api/__init__.py@@ -114,7 +114,11 @@ from products.notebooks.backend.api.notebook import NotebookViewSetfrom products.notifications.backend.presentation.views import NotificationsViewSetfrom products.posthog_ai.backend.api import MCPToolsViewSetfrom products.product_tours.backend.api import ProductTourViewSet-from products.replay_vision.backend.api import ReplayObservationViewSet, ReplayScannerViewSet+from products.replay_vision.backend.api import (+ ReplayObservationViewSet,+ ReplayScannerViewSet,+ SessionReplayObservationViewSet,+)from products.signals.backend.views import SignalViewSetfrom products.tracing.backend.presentation.views import SpansViewSet as TracingSpansViewSetfrom products.user_interviews.backend.presentation.views import (@@ -1630,6 +1634,12 @@ environment_vision_scanners_router.register("environment_vision_scanner_observations",["team_id", "scanner_id"],)+environments_router.register(+ r"vision/observations",+ SessionReplayObservationViewSet,+ "environment_vision_observations",+ ["team_id"],+)environments_router.register(r"change_requests",diff --git a/products/replay_vision/backend/api/__init__.py b/products/replay_vision/backend/api/__init__.pyindex fbdc1ceea2ec..74ec2da1fe1f 100644--- a/products/replay_vision/backend/api/__init__.py+++ b/products/replay_vision/backend/api/__init__.py@@ -1,4 +1,4 @@-from products.replay_vision.backend.api.observations import ReplayObservationViewSet+from products.replay_vision.backend.api.observations import ReplayObservationViewSet, SessionReplayObservationViewSetfrom products.replay_vision.backend.api.scanners import ReplayScannerViewSet-__all__ = ["ReplayScannerViewSet", "ReplayObservationViewSet"]+__all__ = ["ReplayScannerViewSet", "ReplayObservationViewSet", "SessionReplayObservationViewSet"]diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.pyindex b1cd2f454d80..4ac5a6dd1ee6 100644--- a/products/replay_vision/backend/api/observations.py+++ b/products/replay_vision/backend/api/observations.py@@ -5,10 +5,10 @@ from django.db.models import QuerySetimport structlogimport django_filtersfrom django_filters.rest_framework import DjangoFilterBackend-from drf_spectacular.utils import extend_schema, extend_schema_field+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_viewfrom pydantic import ValidationError as PydanticValidationErrorfrom rest_framework import mixins, serializers, viewsets-from rest_framework.exceptions import NotFound, PermissionDenied+from rest_framework.exceptions import NotFound, PermissionDenied, ValidationErrorfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer@@ -218,3 +218,49 @@ class ReplayObservationViewSet(.select_related("triggered_by_user").order_by("-created_at", "id"))+++@extend_schema(tags=[VISION_TAG])+@extend_schema_view(+ list=extend_schema(+ parameters=[+ OpenApiParameter(+ "session_id",+ str,+ OpenApiParameter.QUERY,+ required=True,+ description="Session recording id to return observations for.",+ )+ ]+ )+)+class SessionReplayObservationViewSet(ReplayObservationViewSet):+ """Read-only access to a session's observations across every scanner the caller can read, for the replay-page dock."""++ # The dock fetches one session's observations; `session_id` is required and enforced in+ # safely_get_queryset, so this viewset needs none of the base's optional list filters.+ filter_backends: list = []++ def safely_get_queryset(self, queryset: QuerySet[ReplayObservation]) -> QuerySet[ReplayObservation]:+ # Observations expose recording-derived output, so reading them requires session_recording read.+ if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):+ raise PermissionDenied("Reading replay observations requires session_recording read access.")+ # Observations inherit their scanner's RBAC. The generic access filter keys on the ReplayObservation+ # row rather than its scanner, so scope explicitly to the scanners this caller can read.+ readable_scanner_ids = list(+ self.user_access_control.filter_queryset_by_access_level(+ ReplayScanner.objects.filter(team_id=self.team_id)+ ).values_list("id", flat=True)+ )+ queryset = (+ queryset.filter(team_id=self.team_id, scanner_id__in=readable_scanner_ids)+ .select_related("triggered_by_user")+ .order_by("-created_at", "id")+ )+ # A bare list would scan the whole team's observation history; the replay page always has a session.+ if self.action == "list":+ session_id = self.request.query_params.get("session_id")+ if not session_id:+ raise ValidationError("The `session_id` query parameter is required.")+ queryset = queryset.filter(session_id=session_id)+ return querysetdiff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex e2b6b54aa045..b29e07efd434 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -640,3 +640,65 @@ class TestObserveActionFeatureFlag(APIBaseTest):format="json",)self.assertEqual(resp.status_code, 404)+++class TestSessionReplayObservationViewSet(_VisionAPITestCase):+ def setUp(self) -> None:+ super().setUp()+ self.scanner_a = self._create_scanner(name="scanner-a")+ self.scanner_b = self._create_scanner(name="scanner-b")++ @property+ def session_observations_url(self) -> str:+ return f"/api/environments/{self.team.id}/vision/observations/"++ def _create_observation(self, scanner: ReplayScanner, session_id: str) -> ReplayObservation:+ return ReplayObservation.objects.create(+ scanner=scanner,+ session_id=session_id,+ scanner_snapshot=_snapshot_for(scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ )++ def test_list_returns_observations_from_every_scanner_for_the_session(self) -> None:+ self._create_observation(self.scanner_a, "sess-target")+ self._create_observation(self.scanner_b, "sess-target")+ self._create_observation(self.scanner_a, "sess-other")++ resp = self.client.get(f"{self.session_observations_url}?session_id=sess-target")+ self.assertEqual(resp.status_code, 200)+ results = resp.json()["results"]+ self.assertEqual({r["scanner_id"] for r in results}, {str(self.scanner_a.id), str(self.scanner_b.id)})++ def test_list_requires_session_id(self) -> None:+ resp = self.client.get(self.session_observations_url)+ self.assertEqual(resp.status_code, 400)++ def test_list_excludes_other_teams(self) -> None:+ other_org = Organization.objects.create(name="other")+ other_team = Team.objects.create(organization=other_org, name="other-team")+ other_scanner = ReplayScanner.objects.create(+ team=other_team,+ name="theirs",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_FLASH,+ )+ ReplayObservation.objects.create(+ scanner=other_scanner,+ session_id="sess-target",+ scanner_snapshot=_snapshot_for(other_scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ )+ self._create_observation(self.scanner_a, "sess-target")++ resp = self.client.get(f"{self.session_observations_url}?session_id=sess-target")+ self.assertEqual(resp.status_code, 200)+ results = resp.json()["results"]+ self.assertEqual([r["scanner_id"] for r in results], [str(self.scanner_a.id)])++ def test_retrieve(self) -> None:+ observation = self._create_observation(self.scanner_a, "sess-target")+ resp = self.client.get(f"{self.session_observations_url}{observation.id}/")+ self.assertEqual(resp.status_code, 200)+ self.assertEqual(resp.json()["id"], str(observation.id))diff --git a/products/replay_vision/frontend/components/ObservationCard.tsx b/products/replay_vision/frontend/components/ObservationCard.tsxnew file mode 100644index 000000000000..e3f1a084ff77--- /dev/null+++ b/products/replay_vision/frontend/components/ObservationCard.tsx@@ -0,0 +1,207 @@+import { IconWarning } from '@posthog/icons'+import { LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'++import type { ScannerTypeEnumApi, ReplayObservationApi } from '../generated/api.schemas'++const SCANNER_TYPE_LABEL: Record<ScannerTypeEnumApi, string> = {+ monitor: 'Monitor',+ classifier: 'Classifier',+ scorer: 'Scorer',+ summarizer: 'Summarizer',+ indexer: 'Indexer',+}++export function ObservationStatusTag({ status }: { status: ReplayObservationApi['status'] }): JSX.Element {+ if (status === 'succeeded') {+ return <LemonTag type="success">Succeeded</LemonTag>+ }+ if (status === 'failed') {+ return <LemonTag type="danger">Failed</LemonTag>+ }+ if (status === 'running') {+ return (+ <LemonTag type="warning">+ <Spinner className="mr-1" /> Running+ </LemonTag>+ )+ }+ return <LemonTag type="default">Pending</LemonTag>+}++function readResult(observation: ReplayObservationApi): Record<string, unknown> | null {+ const output = observation.scanner_result?.model_output+ return output && typeof output === 'object' ? (output as Record<string, unknown>) : null+}++/** Compact, single-cell preview of an observation result for the Vision scene's observations table. */+export function ObservationResultSummary({ observation }: { observation: ReplayObservationApi }): JSX.Element {+ if (observation.status === 'failed') {+ return (+ <Tooltip title={observation.error_reason || 'Unknown error'}>+ <span className="inline-flex items-center gap-1 text-danger text-sm">+ <IconWarning /> {observation.error_reason || 'Failed'}+ </span>+ </Tooltip>+ )+ }+ const scannerType = observation.scanner_snapshot?.scanner_type+ const result = readResult(observation)+ if (!scannerType || !result) {+ return <span className="text-muted text-sm">—</span>+ }+ return <ObservationResult scannerType={scannerType} result={result} compact />+}++function ObservationResult({+ scannerType,+ result,+ compact = false,+}: {+ scannerType: ScannerTypeEnumApi+ result: Record<string, unknown>+ compact?: boolean+}): JSX.Element {+ const reasoning = typeof result.reasoning === 'string' ? result.reasoning : null+ const reasoningClass = compact ? 'text-muted text-xs truncate' : 'text-muted text-sm'+ const bodyClass = compact ? 'text-sm truncate' : 'text-sm'++ if (scannerType === 'monitor') {+ const verdict = Boolean(result.verdict)+ return (+ <div className="flex flex-col gap-1">+ <LemonTag type={verdict ? 'success' : 'default'}>{verdict ? 'Yes' : 'No'}</LemonTag>+ {reasoning && <span className={reasoningClass}>{reasoning}</span>}+ </div>+ )+ }++ if (scannerType === 'summarizer') {+ const title = typeof result.title === 'string' ? result.title : null+ const summary = typeof result.summary === 'string' ? result.summary : null+ return (+ <div className="flex flex-col gap-1">+ {title && <span className="font-semibold text-sm">{title}</span>}+ {summary && <span className={bodyClass}>{summary}</span>}+ </div>+ )+ }++ if (scannerType === 'classifier') {+ const tags = Array.isArray(result.tags) ? (result.tags as string[]) : []+ return (+ <div className="flex flex-col gap-1">+ <div className="flex flex-wrap gap-1">+ {tags.length === 0 ? (+ <span className="text-muted text-sm">No tags</span>+ ) : (+ tags.map((tag) => (+ <LemonTag key={tag} type="option">+ {tag}+ </LemonTag>+ ))+ )}+ </div>+ {reasoning && <span className={reasoningClass}>{reasoning}</span>}+ </div>+ )+ }++ if (scannerType === 'scorer') {+ const score = typeof result.score === 'number' ? result.score : null+ const label = typeof result.label === 'string' ? result.label : null+ return (+ <div className="flex flex-col gap-1">+ <span className="text-sm">+ <span className="font-semibold">{score ?? '—'}</span>+ {label && <span className="text-muted"> {label}</span>}+ </span>+ {reasoning && <span className={reasoningClass}>{reasoning}</span>}+ </div>+ )+ }++ const summary = typeof result.summary === 'string' ? result.summary : null+ const userType = typeof result.user_type === 'string' ? result.user_type : null+ const outcome = typeof result.outcome === 'string' ? result.outcome : null+ const keywords = Array.isArray(result.keywords) ? (result.keywords as string[]) : []+ return (+ <div className="flex flex-col gap-1">+ {summary && <span className={bodyClass}>{summary}</span>}+ {userType && (+ <span className={reasoningClass}>+ <span className="font-medium">User: </span>+ {userType}+ </span>+ )}+ {outcome && (+ <span className={reasoningClass}>+ <span className="font-medium">Outcome: </span>+ {outcome}+ </span>+ )}+ {keywords.length > 0 && (+ <div className="flex flex-wrap gap-1">+ {keywords.map((keyword) => (+ <LemonTag key={keyword} type="option" size="small">+ {keyword}+ </LemonTag>+ ))}+ </div>+ )}+ </div>+ )+}++/** In-progress state for a pending/running observation. */+function ObservationProgress({ observation }: { observation: ReplayObservationApi }): JSX.Element {+ return (+ <div className="flex items-center gap-2 text-muted text-sm">+ <Spinner textColored />+ <span>{observation.status === 'pending' ? 'Queued…' : 'Analyzing recording…'}</span>+ </div>+ )+}++/** Full observation presentation for the replay-page dock and the Vision scene's expanded rows. */+export function ObservationCard({ observation }: { observation: ReplayObservationApi }): JSX.Element {+ const snapshot = observation.scanner_snapshot+ const scannerType = snapshot?.scanner_type+ const result = readResult(observation)+ const signalsCount = observation.scanner_result?.signals_count ?? 0++ return (+ <div className="border rounded p-3 bg-surface-primary space-y-2">+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center gap-2 min-w-0">+ <ObservationStatusTag status={observation.status} />+ <span className="font-semibold text-sm truncate">{snapshot?.name || 'Scanner'}</span>+ {scannerType && <span className="text-muted text-xs">{SCANNER_TYPE_LABEL[scannerType]}</span>}+ </div>+ <TZLabel time={observation.created_at} className="text-muted text-xs whitespace-nowrap" />+ </div>++ {observation.status === 'failed' && observation.error_reason && (+ <div className="text-danger text-sm">{observation.error_reason}</div>+ )}++ {observation.status === 'succeeded' && scannerType && result && (+ <ObservationResult scannerType={scannerType} result={result} />+ )}++ {(observation.status === 'pending' || observation.status === 'running') && (+ <ObservationProgress observation={observation} />+ )}++ <div className="flex items-center gap-3 text-muted text-xs">+ {snapshot?.model && <span className="font-mono">{snapshot.model}</span>}+ {signalsCount > 0 && (+ <span>+ {signalsCount} signal{signalsCount === 1 ? '' : 's'}+ </span>+ )}+ </div>+ </div>+ )+}diff --git a/products/replay_vision/frontend/components/ObservationsDock.tsx b/products/replay_vision/frontend/components/ObservationsDock.tsxnew file mode 100644index 000000000000..ba9e1abb7ad8--- /dev/null+++ b/products/replay_vision/frontend/components/ObservationsDock.tsx@@ -0,0 +1,161 @@+import { useActions, useValues } from 'kea'+import { useRef } from 'react'++import { IconChevronDown, IconEye } from '@posthog/icons'+import { LemonButton, LemonInput, Link, Spinner } from '@posthog/lemon-ui'++import { Resizer } from 'lib/components/Resizer/Resizer'+import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'+import { LemonDropdown } from 'lib/lemon-ui/LemonDropdown/LemonDropdown'+import { sessionRecordingPlayerLogic } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'+import { urls } from 'scenes/urls'++import type { ReplayScannerApi } from '../generated/api.schemas'+import { observationsDockLogic } from '../logics/observationsDockLogic'+import { ObservationCard } from './ObservationCard'++const COLLAPSED_HEIGHT = 44+const DEFAULT_EXPANDED_HEIGHT = 480+const MIN_EXPANDED_HEIGHT = 120+const MAX_EXPANDED_HEIGHT = 800++export function ObservationsDock(): JSX.Element | null {+ const { sessionRecordingId } = useValues(sessionRecordingPlayerLogic)++ if (!sessionRecordingId) {+ return null+ }+ return <ObservationsDockContent sessionId={sessionRecordingId} />+}++/** Searchable scanner picker for "Observe this recording"; a flat menu doesn't scale to teams with many scanners. */+function ScannerPicker({ sessionId }: { sessionId: string }): JSX.Element {+ const logic = observationsDockLogic({ sessionId })+ const { scanners, filteredScanners, scannerSearch, scannerPickerOpen, observing } = useValues(logic)+ const { observe, setScannerSearch, setScannerPickerOpen } = useActions(logic)++ return (+ <LemonDropdown+ visible={scannerPickerOpen}+ onVisibilityChange={setScannerPickerOpen}+ closeOnClickInside={false}+ placement="top-start"+ overlay={+ <div className="w-80">+ <div className="p-1 border-b">+ <LemonInput+ type="search"+ size="small"+ placeholder="Search scanners…"+ value={scannerSearch}+ onChange={setScannerSearch}+ autoFocus+ />+ </div>+ <div className="max-h-80 overflow-y-auto p-1">+ {scanners.length === 0 ? (+ <Link to={urls.replayVision()} className="block px-2 py-3 text-sm">+ No scanners yet — create one+ </Link>+ ) : filteredScanners.length === 0 ? (+ <div className="px-2 py-3 text-sm text-muted">No scanners match your search.</div>+ ) : (+ filteredScanners.map((scanner: ReplayScannerApi) => (+ <LemonButton+ key={scanner.id}+ fullWidth+ size="small"+ onClick={() => observe(scanner.id)}+ >+ <span className="flex items-center justify-between gap-2 w-full">+ <span className="truncate">{scanner.name}</span>+ <span className="text-muted text-xs shrink-0">{scanner.scanner_type}</span>+ </span>+ </LemonButton>+ ))+ )}+ </div>+ </div>+ }+ >+ <LemonButton+ size="small"+ type="primary"+ icon={<IconEye />}+ sideIcon={<IconChevronDown />}+ loading={observing}+ data-attr="vision-observe-recording"+ >+ Observe this recording+ </LemonButton>+ </LemonDropdown>+ )+}++function ObservationsDockContent({ sessionId }: { sessionId: string }): JSX.Element {+ const logic = observationsDockLogic({ sessionId })+ const { observations, observationsLoading, dockOpen } = useValues(logic)+ const { setDockOpen } = useActions(logic)++ const dockRef = useRef<HTMLDivElement>(null)+ const resizerProps: ResizerLogicProps = {+ logicKey: 'vision-observations-dock',+ placement: 'top',+ containerRef: dockRef,+ }+ const { desiredSize, isResizeInProgress } = useValues(resizerLogic(resizerProps))++ const hasContent = observations.length > 0 || observationsLoading+ const expandedHeight = Math.max(+ MIN_EXPANDED_HEIGHT,+ Math.min(MAX_EXPANDED_HEIGHT, desiredSize ?? DEFAULT_EXPANDED_HEIGHT)+ )++ return (+ <div+ ref={dockRef}+ className={`relative border-t bg-surface-primary overflow-hidden flex flex-col ${+ isResizeInProgress ? '' : 'transition-[max-height] duration-300 ease-out'+ }`}+ style={{ maxHeight: dockOpen ? expandedHeight : COLLAPSED_HEIGHT }}+ data-attr="vision-observations-dock"+ >+ {dockOpen && <Resizer {...resizerProps} />}+ <div className="flex items-center gap-3 h-11 px-3 shrink-0">+ <ScannerPicker sessionId={sessionId} />+ {observations.length > 0 && (+ <span className="text-muted text-sm">+ {observations.length} observation{observations.length === 1 ? '' : 's'}+ </span>+ )}+ {hasContent && (+ <LemonButton+ className="ml-auto"+ size="small"+ icon={<IconChevronDown className={dockOpen ? 'rotate-180' : ''} />}+ onClick={() => setDockOpen(!dockOpen)}+ tooltip={dockOpen ? 'Collapse' : 'Expand'}+ aria-label={dockOpen ? 'Collapse observations' : 'Expand observations'}+ />+ )}+ </div>+ {dockOpen && (+ <div className="flex-1 overflow-y-auto px-3 pb-3 space-y-2">+ {observationsLoading && observations.length === 0 ? (+ <div className="flex items-center gap-2 text-muted py-4">+ <Spinner /> Loading observations…+ </div>+ ) : observations.length === 0 ? (+ <div className="text-muted text-sm py-4">+ No observations yet. Pick a scanner to observe this recording.+ </div>+ ) : (+ observations.map((observation) => (+ <ObservationCard key={observation.id} observation={observation} />+ ))+ )}+ </div>+ )}+ </div>+ )+}diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 51dd07dc6672..d8cb4192905b 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -7,6 +7,21 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+/**+ * * `pending` - Pending+ * `running` - Running+ * `succeeded` - Succeeded+ * `failed` - Failed+ */+export type ObservationStatusEnumApi = (typeof ObservationStatusEnumApi)[keyof typeof ObservationStatusEnumApi]++export const ObservationStatusEnumApi = {+ Pending: 'pending',+ Running: 'running',+ Succeeded: 'succeeded',+ Failed: 'failed',+} as const+/*** * `monitor` - Monitor* `classifier` - Classifier@@ -24,6 +39,17 @@ export const ScannerTypeEnumApi = {Indexer: 'indexer',} as const+/**+ * * `gemini-3-flash-preview` - Gemini 3 Flash+ * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite+ */+export type ScannerModelEnumApi = (typeof ScannerModelEnumApi)[keyof typeof ScannerModelEnumApi]++export const ScannerModelEnumApi = {+ Gemini3FlashPreview: 'gemini-3-flash-preview',+ Gemini31FlashLitePreview: 'gemini-3.1-flash-lite-preview',+} as const+/*** * `google` - Google*/@@ -34,14 +60,65 @@ export const ScannerProviderEnumApi = {} as const/**- * * `gemini-3-flash-preview` - Gemini 3 Flash- * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite+ * Mirrors `temporal.types.ScannerSnapshot` for OpenAPI generation.*/-export type ScannerModelEnumApi = (typeof ScannerModelEnumApi)[keyof typeof ScannerModelEnumApi]+export interface ScannerSnapshotApi {+ /** Scanner name at run time. */+ name: string+ /** Scanner type (monitor, classifier, scorer, summarizer, indexer) at run time.-export const ScannerModelEnumApi = {- Gemini3FlashPreview: 'gemini-3-flash-preview',- Gemini31FlashLitePreview: 'gemini-3.1-flash-lite-preview',+ * `monitor` - Monitor+ * `classifier` - Classifier+ * `scorer` - Scorer+ * `summarizer` - Summarizer+ * `indexer` - Indexer */+ scanner_type: ScannerTypeEnumApi+ /** The `ReplayScanner.scanner_version` value at the moment the workflow ran. */+ scanner_version: number+ /** Concrete model that ran the observation.++ * `gemini-3-flash-preview` - Gemini 3 Flash+ * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite */+ model: ScannerModelEnumApi+ /** Concrete provider that ran the observation.++ * `google` - Google */+ provider: ScannerProviderEnumApi+ /** Whether the observation was run with Signal emission enabled. */+ emits_signals: boolean+ /** Scanner-type-specific configuration at run time (prompt, tags, scale, etc.). */+ scanner_config: unknown+}++/**+ * Maps the short `event_id` the LLM cites in `model_output.reasoning` to citation metadata: `{uuid, timestamp_ms}`. Only includes hashes the LLM actually cited.+ */+export type ScannerResultApiEventIdMapping = { [key: string]: unknown }++/**+ * Mirrors `temporal.types.ScannerResult` for OpenAPI generation.+ */+export interface ScannerResultApi {+ /** Validated scanner output. Shape depends on `scanner_snapshot.scanner_type`; always carries `confidence` and `scanner_type`. */+ model_output: unknown+ /**+ * Number of PostHog Signals emitted from this observation.+ * @minimum 0+ */+ signals_count: number+ /** Maps the short `event_id` the LLM cites in `model_output.reasoning` to citation metadata: `{uuid, timestamp_ms}`. Only includes hashes the LLM actually cited. */+ event_id_mapping: ScannerResultApiEventIdMapping+}++/**+ * * `schedule` - Schedule+ * `on_demand` - On demand+ */+export type ObservationTriggerEnumApi = (typeof ObservationTriggerEnumApi)[keyof typeof ObservationTriggerEnumApi]++export const ObservationTriggerEnumApi = {+ Schedule: 'schedule',+ OnDemand: 'on_demand',} as const/**@@ -99,6 +176,50 @@ export interface UserBasicApi {role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null}+export interface ReplayObservationApi {+ readonly id: string+ /** The scanner that produced this observation. */+ readonly scanner_id: string+ /** Session recording id this scanner was applied to. */+ readonly session_id: string+ /** Observation status (pending, running, succeeded, failed).++ * `pending` - Pending+ * `running` - Running+ * `succeeded` - Succeeded+ * `failed` - Failed */+ readonly status: ObservationStatusEnumApi+ /** Populated on failure; includes the malformed model response when validation fails. */+ readonly error_reason: string+ /** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */+ readonly workflow_id: string+ /** Frozen view of the scanner at run time; scanner edits do not retroactively mutate this observation. */+ readonly scanner_snapshot: ScannerSnapshotApi | null+ /** Result data persisted on success; null until the observation succeeds. */+ readonly scanner_result: ScannerResultApi | null+ /** Whether this observation came from the schedule or an on-demand request.++ * `schedule` - Schedule+ * `on_demand` - On demand */+ readonly triggered_by: ObservationTriggerEnumApi+ /** User who triggered an on-demand observation; null for scheduled observations. */+ readonly triggered_by_user: UserBasicApi | null+ /** @nullable */+ started_at?: string | null+ /** @nullable */+ completed_at?: string | null+ readonly created_at: string+}++export interface PaginatedReplayObservationListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: ReplayObservationApi[]+}+export interface ReplayScannerApi {readonly id: string/**@@ -227,125 +348,19 @@ export interface ObserveResponseApi {workflow_id: string}-/**- * * `pending` - Pending- * `running` - Running- * `succeeded` - Succeeded- * `failed` - Failed- */-export type ObservationStatusEnumApi = (typeof ObservationStatusEnumApi)[keyof typeof ObservationStatusEnumApi]--export const ObservationStatusEnumApi = {- Pending: 'pending',- Running: 'running',- Succeeded: 'succeeded',- Failed: 'failed',-} as const--/**- * Mirrors `temporal.types.ScannerSnapshot` for OpenAPI generation.- */-export interface ScannerSnapshotApi {- /** Scanner name at run time. */- name: string- /** Scanner type (monitor, classifier, scorer, summarizer, indexer) at run time.-- * `monitor` - Monitor- * `classifier` - Classifier- * `scorer` - Scorer- * `summarizer` - Summarizer- * `indexer` - Indexer */- scanner_type: ScannerTypeEnumApi- /** The `ReplayScanner.scanner_version` value at the moment the workflow ran. */- scanner_version: number- /** Concrete model that ran the observation.-- * `gemini-3-flash-preview` - Gemini 3 Flash- * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite */- model: ScannerModelEnumApi- /** Concrete provider that ran the observation.-- * `google` - Google */- provider: ScannerProviderEnumApi- /** Whether the observation was run with Signal emission enabled. */- emits_signals: boolean- /** Scanner-type-specific configuration at run time (prompt, tags, scale, etc.). */- scanner_config: unknown-}--/**- * Maps the short `event_id` the LLM cites in `model_output.reasoning` to citation metadata: `{uuid, timestamp_ms}`. Only includes hashes the LLM actually cited.- */-export type ScannerResultApiEventIdMapping = { [key: string]: unknown }--/**- * Mirrors `temporal.types.ScannerResult` for OpenAPI generation.- */-export interface ScannerResultApi {- /** Validated scanner output. Shape depends on `scanner_snapshot.scanner_type`; always carries `confidence` and `scanner_type`. */- model_output: unknown+export type VisionObservationsListParams = {/**- * Number of PostHog Signals emitted from this observation.- * @minimum 0+ * Number of results to return per page.*/- signals_count: number- /** Maps the short `event_id` the LLM cites in `model_output.reasoning` to citation metadata: `{uuid, timestamp_ms}`. Only includes hashes the LLM actually cited. */- event_id_mapping: ScannerResultApiEventIdMapping-}--/**- * * `schedule` - Schedule- * `on_demand` - On demand- */-export type ObservationTriggerEnumApi = (typeof ObservationTriggerEnumApi)[keyof typeof ObservationTriggerEnumApi]--export const ObservationTriggerEnumApi = {- Schedule: 'schedule',- OnDemand: 'on_demand',-} as const--export interface ReplayObservationApi {- readonly id: string- /** The scanner that produced this observation. */- readonly scanner_id: string- /** Session recording id this scanner was applied to. */- readonly session_id: string- /** Observation status (pending, running, succeeded, failed).-- * `pending` - Pending- * `running` - Running- * `succeeded` - Succeeded- * `failed` - Failed */- readonly status: ObservationStatusEnumApi- /** Populated on failure; includes the malformed model response when validation fails. */- readonly error_reason: string- /** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */- readonly workflow_id: string- /** Frozen view of the scanner at run time; scanner edits do not retroactively mutate this observation. */- readonly scanner_snapshot: ScannerSnapshotApi | null- /** Result data persisted on success; null until the observation succeeds. */- readonly scanner_result: ScannerResultApi | null- /** Whether this observation came from the schedule or an on-demand request.-- * `schedule` - Schedule- * `on_demand` - On demand */- readonly triggered_by: ObservationTriggerEnumApi- /** User who triggered an on-demand observation; null for scheduled observations. */- readonly triggered_by_user: UserBasicApi | null- /** @nullable */- started_at?: string | null- /** @nullable */- completed_at?: string | null- readonly created_at: string-}--export interface PaginatedReplayObservationListApi {- count: number- /** @nullable */- next?: string | null- /** @nullable */- previous?: string | null- results: ReplayObservationApi[]+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+ /**+ * Session recording id to return observations for.+ */+ session_id: string}export type VisionScannersListParams = {diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.tsindex ffd171b8d4a0..6435f9625ab6 100644--- a/products/replay_vision/frontend/generated/api.ts+++ b/products/replay_vision/frontend/generated/api.ts@@ -16,6 +16,7 @@ import type {PatchedReplayScannerApi,ReplayObservationApi,ReplayScannerApi,+ VisionObservationsListParams,VisionScannersListParams,VisionScannersObservationsListParams,} from './api.schemas'@@ -37,6 +38,54 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]}: DistributeReadOnlyOverUnions<T>+export const getVisionObservationsListUrl = (projectId: string, params: VisionObservationsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/environments/${projectId}/vision/observations/?${stringifiedParams}`+ : `/api/environments/${projectId}/vision/observations/`+}++/**+ * Read-only access to a session's observations across every scanner the caller can read, for the replay-page dock.+ */+export const visionObservationsList = async (+ projectId: string,+ params: VisionObservationsListParams,+ options?: RequestInit+): Promise<PaginatedReplayObservationListApi> => {+ return apiMutator<PaginatedReplayObservationListApi>(getVisionObservationsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getVisionObservationsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/environments/${projectId}/vision/observations/${id}/`+}++/**+ * Read-only access to a session's observations across every scanner the caller can read, for the replay-page dock.+ */+export const visionObservationsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ReplayObservationApi> => {+ return apiMutator<ReplayObservationApi>(getVisionObservationsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}+export const getVisionScannersListUrl = (projectId: string, params?: VisionScannersListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/replay_vision/frontend/logics/observationPolling.ts b/products/replay_vision/frontend/logics/observationPolling.tsnew file mode 100644index 000000000000..3883916402fe--- /dev/null+++ b/products/replay_vision/frontend/logics/observationPolling.ts@@ -0,0 +1,26 @@+const POLL_INTERVAL_MS = 3000+const POLL_KEY = 'pollObservations'++interface ObservationPollDisposables {+ add: (setup: () => () => void, key?: string) => void+ dispose: (key: string) => void+}++/**+ * Start or stop the recurring observation refresh. Keyed so a repeat call replaces the prior timer;+ * the kea-disposables plugin clears it on unmount and pauses it while the tab is hidden.+ */+export function scheduleObservationPoll(+ disposables: ObservationPollDisposables,+ shouldPoll: boolean,+ poll: () => void+): void {+ if (shouldPoll) {+ disposables.add(() => {+ const id = setTimeout(poll, POLL_INTERVAL_MS)+ return () => clearTimeout(id)+ }, POLL_KEY)+ } else {+ disposables.dispose(POLL_KEY)+ }+}diff --git a/products/replay_vision/frontend/logics/observationsDockLogic.ts b/products/replay_vision/frontend/logics/observationsDockLogic.tsnew file mode 100644index 000000000000..29470f96e6cc--- /dev/null+++ b/products/replay_vision/frontend/logics/observationsDockLogic.ts@@ -0,0 +1,171 @@+import { actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'++import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { teamLogic } from 'scenes/teamLogic'++import { visionScannersList, visionScannersObserveCreate, visionObservationsList } from '../generated/api'+import type { ReplayScannerApi, ReplayObservationApi } from '../generated/api.schemas'+import { scheduleObservationPoll } from './observationPolling'+import type { observationsDockLogicType } from './observationsDockLogicType'++// The observe endpoint only starts the workflow; its row is created a moment later. Keep polling+// for this window after an observe so the new card appears even before anything reports in flight.+const OBSERVE_POLL_GRACE_MS = 30000++export interface ObservationsDockLogicProps {+ sessionId: string+}++export const observationsDockLogic = kea<observationsDockLogicType>([+ path(['products', 'replay_vision', 'frontend', 'logics', 'observationsDockLogic']),+ props({} as ObservationsDockLogicProps),+ key((props) => props.sessionId),++ actions({+ loadObservations: true,+ loadObservationsSuccess: (observations: ReplayObservationApi[]) => ({ observations }),+ loadObservationsFailure: true,+ loadScanners: true,+ loadScannersSuccess: (scanners: ReplayScannerApi[]) => ({ scanners }),+ loadScannersFailure: true,+ observe: (scannerId: string) => ({ scannerId }),+ observeSuccess: true,+ observeFailure: true,+ setDockOpen: (open: boolean) => ({ open }),+ setScannerPickerOpen: (open: boolean) => ({ open }),+ setScannerSearch: (search: string) => ({ search }),+ }),++ reducers({+ observations: [+ [] as ReplayObservationApi[],+ {+ loadObservationsSuccess: (_, { observations }) => observations,+ },+ ],+ observationsLoading: [+ false,+ {+ loadObservations: () => true,+ loadObservationsSuccess: () => false,+ loadObservationsFailure: () => false,+ },+ ],+ scanners: [+ [] as ReplayScannerApi[],+ {+ loadScannersSuccess: (_, { scanners }) => scanners,+ },+ ],+ observing: [+ false,+ {+ observe: () => true,+ observeSuccess: () => false,+ observeFailure: () => false,+ },+ ],+ dockOpen: [+ false,+ {+ setDockOpen: (_, { open }) => open,+ },+ ],+ scannerPickerOpen: [+ false,+ {+ setScannerPickerOpen: (_, { open }) => open,+ },+ ],+ scannerSearch: [+ '',+ {+ setScannerSearch: (_, { search }) => search,+ // Reset the query each time the picker is opened or closed.+ setScannerPickerOpen: () => '',+ },+ ],+ pollUntil: [+ 0,+ {+ observeSuccess: () => Date.now() + OBSERVE_POLL_GRACE_MS,+ },+ ],+ }),++ selectors({+ hasObservationsInFlight: [+ (s) => [s.observations],+ (observations: ReplayObservationApi[]): boolean =>+ observations.some((o) => o.status === 'pending' || o.status === 'running'),+ ],+ filteredScanners: [+ (s) => [s.scanners, s.scannerSearch],+ (scanners: ReplayScannerApi[], scannerSearch: string): ReplayScannerApi[] => {+ const query = scannerSearch.trim().toLowerCase()+ return query ? scanners.filter((scanner) => scanner.name.toLowerCase().includes(query)) : scanners+ },+ ],+ }),++ listeners(({ actions, props, values, cache }) => ({+ loadObservations: async () => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ return+ }+ try {+ const response = await visionObservationsList(String(teamId), { session_id: props.sessionId })+ actions.loadObservationsSuccess(response.results ?? [])+ } catch {+ actions.loadObservationsFailure()+ }+ },++ loadObservationsSuccess: () => {+ // Poll while work is in flight, and through the grace window after an observe.+ scheduleObservationPoll(+ cache.disposables,+ values.hasObservationsInFlight || Date.now() < values.pollUntil,+ actions.loadObservations+ )+ },++ loadScanners: async () => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ return+ }+ try {+ const response = await visionScannersList(String(teamId))+ actions.loadScannersSuccess(response.results ?? [])+ } catch {+ actions.loadScannersFailure()+ }+ },++ observe: async ({ scannerId }) => {+ actions.setScannerPickerOpen(false)+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ actions.observeFailure()+ return+ }+ try {+ await visionScannersObserveCreate(String(teamId), scannerId, { session_id: props.sessionId })+ lemonToast.success('Observation started')+ actions.observeSuccess()+ actions.setDockOpen(true)+ actions.loadObservations()+ } catch (error) {+ lemonToast.error(`Failed to start observation: ${String(error)}`)+ actions.observeFailure()+ }+ },+ })),++ afterMount(({ actions }) => {+ actions.loadObservations()+ actions.loadScanners()+ }),+])diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsxindex 795f4a5e78f8..f817030e3938 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx@@ -133,8 +133,9 @@ export function ReplayScannersScene(): JSX.Element {{title: 'Config',key: 'config',+ width: '40%',render: (_, scanner) => (- <div className="max-w-md text-sm font-mono bg-bg-light border rounded px-2 py-1 truncate">+ <div className="text-sm font-mono bg-bg-light border rounded px-2 py-1 truncate">{scanner.scanner_config.prompt || '(empty)'}</div>),diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsxindex c6e266c2e06f..d6efc694a719 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx@@ -1,125 +1,21 @@import { useActions, useValues } from 'kea'-import { IconRefresh, IconWarning } from '@posthog/icons'-import { LemonButton, LemonTable, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'+import { IconRefresh } from '@posthog/icons'+import { LemonButton, LemonTable, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { urls } from 'scenes/urls'+import { ObservationCard, ObservationResultSummary, ObservationStatusTag } from '../../components/ObservationCard'+import type { ReplayObservationApi } from '../../generated/api.schemas'import { replayScannerLogic } from '../replayScannerLogic'-import { ScannerType, ObservationStatus, ReplayObservation } from '../types'--function StatusTag({ status }: { status: ObservationStatus }): JSX.Element {- if (status === 'succeeded') {- return <LemonTag type="success">Succeeded</LemonTag>- }- if (status === 'failed') {- return <LemonTag type="danger">Failed</LemonTag>- }- if (status === 'running') {- return (- <LemonTag type="warning">- <Spinner className="mr-1" /> Running- </LemonTag>- )- }- return <LemonTag type="default">Pending</LemonTag>-}--function ResultPreview({- scannerType,- observation,-}: {- scannerType: ScannerType- observation: ReplayObservation-}): JSX.Element {- if (observation.status === 'failed') {- return (- <Tooltip title={observation.error_reason || 'Unknown error'}>- <span className="inline-flex items-center gap-1 text-danger text-sm">- <IconWarning /> {observation.error_reason || 'Failed'}- </span>- </Tooltip>- )- }- if (observation.status !== 'succeeded' || !observation.result) {- return <span className="text-muted text-sm">—</span>- }- const r = observation.result- if (scannerType === 'monitor') {- const verdict = Boolean(r.verdict)- return (- <div className="flex flex-col gap-1 max-w-md">- <LemonTag type={verdict ? 'success' : 'default'}>{verdict ? 'Yes' : 'No'}</LemonTag>- {typeof r.reasoning === 'string' && <span className="text-muted text-xs truncate">{r.reasoning}</span>}- </div>- )- }- if (scannerType === 'summarizer') {- return (- <div className="flex flex-col max-w-md">- {typeof r.title === 'string' && <span className="font-semibold text-sm truncate">{r.title}</span>}- {typeof r.summary === 'string' && <span className="text-muted text-xs line-clamp-2">{r.summary}</span>}- </div>- )- }- if (scannerType === 'classifier') {- const tags = Array.isArray(r.tags) ? (r.tags as string[]) : []- return (- <div className="flex flex-wrap gap-1 max-w-md">- {tags.length === 0 ? (- <span className="text-muted text-sm">No tags</span>- ) : (- tags.map((t) => (- <LemonTag key={t} type="option">- {t}- </LemonTag>- ))- )}- </div>- )- }- if (scannerType === 'scorer') {- const score = typeof r.score === 'number' ? r.score : null- const label = typeof r.label === 'string' ? r.label : null- return (- <div className="flex items-baseline gap-2">- <span className="font-semibold text-lg tabular-nums">{score ?? '—'}</span>- {label && <span className="text-muted text-xs">{label}</span>}- </div>- )- }- if (scannerType === 'indexer') {- const keywords = Array.isArray(r.keywords) ? (r.keywords as string[]) : []- return (- <div className="flex flex-col max-w-md">- {typeof r.summary === 'string' && <span className="text-sm truncate">{r.summary}</span>}- {keywords.length > 0 && (- <div className="flex flex-wrap gap-1 mt-1">- {keywords.slice(0, 5).map((k) => (- <LemonTag key={k} type="option" size="small">- {k}- </LemonTag>- ))}- {keywords.length > 5 && <span className="text-muted text-xs">+{keywords.length - 5}</span>}- </div>- )}- </div>- )- }- return <span className="text-muted text-sm">—</span>-}export function ScannerObservationsTable({ scannerId, tabId }: { scannerId: string; tabId: string }): JSX.Element {const logic = replayScannerLogic({ id: scannerId, tabId })- const { scanner, observations, observationsLoading } = useValues(logic)+ const { observations, observationsLoading, hasObservationsInFlight } = useValues(logic)const { loadObservations } = useActions(logic)- if (!scanner) {- return <div className="text-muted">Loading…</div>- }-const stats = observations.reduce((acc, o) => {acc.total += 1@@ -128,33 +24,35 @@ export function ScannerObservationsTable({ scannerId, tabId }: { scannerId: stri} else if (o.status === 'failed') {acc.failed += 1} else {- acc.running += 1+ acc.inFlight += 1}return acc},- { total: 0, succeeded: 0, failed: 0, running: 0 }+ { total: 0, succeeded: 0, failed: 0, inFlight: 0 })- const successRate = stats.total > 0 ? Math.round((stats.succeeded / stats.total) * 100) : null+ const completed = stats.succeeded + stats.failed+ const successRate = completed > 0 ? Math.round((stats.succeeded / completed) * 100) : null- const columns: LemonTableColumns<ReplayObservation> = [+ const columns: LemonTableColumns<ReplayObservationApi> = [{title: 'Session',key: 'session',+ width: 300,render: (_, obs) => (- <Link to={urls.replaySingle(obs.session_id)} className="font-mono text-xs text-primary">- {obs.session_id.slice(0, 12)}…+ <Link to={urls.replaySingle(obs.session_id)} className="font-mono text-xs text-primary truncate block">+ {obs.session_id}</Link>),},{title: 'Status',key: 'status',- render: (_, obs) => <StatusTag status={obs.status} />,+ render: (_, obs) => <ObservationStatusTag status={obs.status} />,},{title: 'Result',key: 'result',- render: (_, obs) => <ResultPreview scannerType={scanner.scanner_type} observation={obs} />,+ render: (_, obs) => <ObservationResultSummary observation={obs} />,},{title: 'Triggered by',@@ -168,7 +66,9 @@ export function ScannerObservationsTable({ scannerId, tabId }: { scannerId: stri{title: 'Model',key: 'model',- render: (_, obs) => <span className="font-mono text-xs text-muted">{obs.model_used || '—'}</span>,+ render: (_, obs) => (+ <span className="font-mono text-xs text-muted">{obs.scanner_snapshot?.model || '—'}</span>+ ),},{title: 'Created',@@ -203,23 +103,31 @@ export function ScannerObservationsTable({ scannerId, tabId }: { scannerId: stri<div className="text-muted">Failed</div></div>)}- {stats.running > 0 && (+ {stats.inFlight > 0 && (<div className="text-center">- <div className="font-semibold text-lg">{stats.running}</div>+ <div className="font-semibold text-lg">{stats.inFlight}</div><div className="text-muted">In flight</div></div>)}</div>)}- <LemonButton- size="small"- type="secondary"- icon={<IconRefresh />}- onClick={() => loadObservations()}- loading={observationsLoading}+ <Tooltip+ title={+ hasObservationsInFlight+ ? 'Auto-refreshing while observations are in flight'+ : 'Refresh observations'+ }>- Refresh- </LemonButton>+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconRefresh />}+ onClick={() => loadObservations()}+ loading={observationsLoading}+ >+ Refresh+ </LemonButton>+ </Tooltip></div></div><LemonTable@@ -229,11 +137,19 @@ export function ScannerObservationsTable({ scannerId, tabId }: { scannerId: strirowKey="id"pagination={{ pageSize: 50 }}nouns={['observation', 'observations']}+ expandable={{+ rowExpandable: (obs) => obs.status === 'succeeded' || obs.status === 'failed',+ expandedRowRender: (obs) => (+ <div className="p-2">+ <ObservationCard observation={obs} />+ </div>+ ),+ }}emptyState={- <span className="text-muted">- No observations yet. Once this scanner runs against matching recordings, results will appear- here.- </span>+ <div className="p-6 text-center text-muted">+ No observations yet. Observations appear here once the scanner runs on a schedule, or when you+ observe a recording from the session replay page.+ </div>}/></div>diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex a8c1538fecba..8ae2938466af 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -17,6 +17,8 @@ import {visionScannersPartialUpdate,visionScannersRetrieve,} from '../generated/api'+import type { ReplayObservationApi } from '../generated/api.schemas'+import { scheduleObservationPoll } from '../logics/observationPolling'import type { replayScannerLogicType } from './replayScannerLogicType'import {DEFAULT_MODEL,@@ -24,11 +26,9 @@ import {ScannerConfig,ScannerType,ReplayScanner,- ReplayObservation,scannerFromApi,scannerToApiBody,scannerToPatchedApiBody,- observationsFromApi,} from './types'export interface ReplayScannerLogicProps {@@ -86,7 +86,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([loadScannerFailure: true,setScannerType: (scannerType: ScannerType) => ({ scannerType }),loadObservations: true,- loadObservationsSuccess: (observations: ReplayObservation[]) => ({ observations }),+ loadObservationsSuccess: (observations: ReplayObservationApi[]) => ({ observations }),loadObservationsFailure: true,deleteScanner: true,}),@@ -154,7 +154,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([},],observations: [- [] as ReplayObservation[],+ [] as ReplayObservationApi[],{loadObservationsSuccess: (_, { observations }) => observations,},@@ -180,9 +180,14 @@ export const replayScannerLogic = kea<replayScannerLogicType>([return !objectsEqual(scanner, original)},],+ hasObservationsInFlight: [+ (s) => [s.observations],+ (observations: ReplayObservationApi[]): boolean =>+ observations.some((o) => o.status === 'pending' || o.status === 'running'),+ ],}),- listeners(({ actions, props }) => ({+ listeners(({ actions, props, values, cache }) => ({loadScanner: async () => {if (props.id === 'new') {actions.loadScannerSuccess(newScanner())@@ -238,11 +243,15 @@ export const replayScannerLogic = kea<replayScannerLogicType>([}try {const response = await visionScannersObservationsList(String(teamId), props.id)- actions.loadObservationsSuccess(observationsFromApi(response.results ?? []))+ actions.loadObservationsSuccess(response.results ?? [])} catch {actions.loadObservationsFailure()}},++ loadObservationsSuccess: () => {+ scheduleObservationPoll(cache.disposables, values.hasObservationsInFlight, actions.loadObservations)+ },})),afterMount(({ actions, props }) => {diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.tsindex 54d432bd9e61..bc35c89b2f16 100644--- a/products/replay_vision/frontend/replay_scanners/types.ts+++ b/products/replay_vision/frontend/replay_scanners/types.ts@@ -1,13 +1,11 @@import { RecordingsQuery } from '~/queries/schema/schema-general'-import type { PatchedReplayScannerApi, ReplayScannerApi, ReplayObservationApi } from '../generated/api.schemas'+import type { PatchedReplayScannerApi, ReplayScannerApi } from '../generated/api.schemas'export type ScannerType = 'monitor' | 'classifier' | 'scorer' | 'summarizer' | 'indexer'export type EnabledFilter = 'enabled' | 'disabled'-export type ObservationStatus = 'pending' | 'running' | 'succeeded' | 'failed'-export const DEFAULT_PROVIDER = 'google'export const DEFAULT_MODEL = 'gemini-3-flash'@@ -163,26 +161,3 @@ export function scannerToPatchedApiBody(): PatchedReplayScannerApi {return scanner as unknown as PatchedReplayScannerApi}--export function observationsFromApi(apis: readonly ReplayObservationApi[]): ReplayObservation[] {- return apis.map((api) => api as unknown as ReplayObservation)-}--export interface ReplayObservation {- id: string- scanner_id: string- session_id: string- status: ObservationStatus- error_reason: string- workflow_id: string- scanner_version: number- scanner_config_snapshot: Record<string, unknown>- model_used: string- provider_used: string- triggered_by: 'schedule' | 'on_demand'- triggered_by_user: { id: number; first_name: string } | null- result: Record<string, unknown> | null- created_at: string- started_at: string | null- completed_at: string | null-}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 118cf50b1ad4..6873563205fe 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -41609,6 +41609,21 @@ export namespace Schemas {topic?: string;};+ export type VisionObservationsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ /**+ * Session recording id to return observations for.+ */+ session_id: string;+ };+export type VisionScannersListParams = {/*** Filter to scanners that emit Signals.