: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 internal notes with @-mentions to observations (#122359)
Kim Svatos Dugand851ba9add45
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex bda983ba7b0f..bac16d6ad09d 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -14799,9 +14799,9 @@ snapshots:scenes-app-replay-vision--observation-detail-classifier--light:hash: v1.k794b7964.812c52630f07aad627bbef36145b4499599d5df16411d81dfe884abac4e5b48c.YNeITkL81fdUmXdlHQSOaVOxIi1otp_nLJPYEjWSWkcscenes-app-replay-vision--observation-detail-failed--dark:- hash: v1.k794b7964.07b7872338385fd4798f0d5ba9bc83103e7eded996ad25bacbfac44e78141850.ELDT3n6Usls8RGZ-22vo6KPDOrh05j5HP6-RnDy4wHI+ hash: v1.k794b7964.178910865db4028b36eac2c728a188654bd41ec72ce8e3f1f7c9fd7f04546b88.x5-JMI3AJDOufpCjRtOOcqWRrQmcWDUFqpx2YE2VC-0scenes-app-replay-vision--observation-detail-failed--light:- hash: v1.k794b7964.865a18ec9e2c1d9616742ac66c69072d90ded6efb4bc8e973d43a7e9cdc205ee.8UP6XrRPnVlsT97P9jstn4CnaeBZZJD9oMPPfx4DwcQ+ hash: v1.k794b7964.d785723c2d89ed620d75d0ef2055f898a01b7325101229d4e54cf37e2dc17af7.fv0LS2k7i2Mak73ZKguMZkf_kkciOPKble3HlvFiBPQscenes-app-replay-vision--observation-detail-inline-scan--dark:hash: v1.k794b7964.ae52ae6b7550bd29bb072461a76f6adb7225017bef54712ae0983da16d73d38c.TMsKlJUqYj_m_dfJE700BerOPX_sIpZYfuZHqrEhGIEscenes-app-replay-vision--observation-detail-inline-scan--light:@@ -14815,21 +14815,21 @@ snapshots:scenes-app-replay-vision--observation-detail-monitor-inconclusive--light:hash: v1.k794b7964.51caae084374f8732810fc955d637cc0cba2049e991f6e8265cd01fc5ed53487.rT7EJy5Z5T4fOiZeaJTpzZkQQA29DIaN-hcZ2GtegCsscenes-app-replay-vision--observation-detail-not-scanned--dark:- hash: v1.k794b7964.5aaf0fce8c31111ab54cc6b9f977c306d10a7490720f1f519b8071658531dc6f.anx8zQcKtVWrkZII_qKhA5Za18rbKNC6ZJ7UNu0lYHc+ hash: v1.k794b7964.d92f751579ed56cd5e6dec23891b430b3a43d82065e160e62396fcca3fa973db.kGlivzbryjSCgzG6mAtZ3lI9fyGBLPrCUj65uibKE2kscenes-app-replay-vision--observation-detail-not-scanned--light:- hash: v1.k794b7964.6ee2b084470e459f2fd89d32589b547dab570db7f939a20d7a19def3094ec69b.qyNB5ElOhbpF099xZGOqXkf2ZZvAHzmHEsJ1rw468Gs+ hash: v1.k794b7964.8293b9fb2a7338d4f83eff3d0d5f557de7641017aec799f733efacd45bc7baee.gxeOxuDbSSIpryNYiDFrdUwVEUQ3gpuNjb3c5J_sdFEscenes-app-replay-vision--observation-detail-recording-expired--dark:- hash: v1.k794b7964.7c51a1c2d8e2e76dac0d6ee37ca3e3765755cc2ec7eafe33fcbab9818c3205b2.qFfCtRUTcXPgLJ1GMkNYRMr7HXjtS2mREQYEs1n0dZk+ hash: v1.k794b7964.fcbe89006a1bb557b6bc43713c4701692f2732250b5e7c6a414cfce39b5a718b.b-xw0njT9ETXR7a-1_gXHSmjIVdw8JUH2pSlRKGJCYYscenes-app-replay-vision--observation-detail-recording-expired--light:- hash: v1.k794b7964.7d41766ac840c8497df9533ceb88f0086afdef57975b1f951c69183f8d060140.LFlTkcd2zNKfvqkEVgBcZBWPyVDizpCV1JoCmj8JdsE+ hash: v1.k794b7964.8cff206a81bfe127a9f25dd0cdb7105d79251147aefeb7b5f8acf802d2c7c832.BpijYHiG7JszmH6HCyTLl0HIrdk5HQLZvZ_4HzfHud4scenes-app-replay-vision--observation-detail-scorer--dark:hash: v1.k794b7964.35969efd42660b47ef1ebb786fc9472428cd09dcb09c415f72674dd029c0c1f8.V0_UrhVG3UA6I3S9buZ63q0J2_NbT9k1gnOg3GiwnEUscenes-app-replay-vision--observation-detail-scorer--light:hash: v1.k794b7964.22324e39500a751d81afa2f8182d9c5bfa3210cab96e87275823a68bd742675a.UgutZacJ0sLcHH7UdObmCzZPgJhEVpkio7zxH_r90b4scenes-app-replay-vision--observation-detail-summarize-button--dark:- hash: v1.k794b7964.b6352f9e6927ea338746776eef45109f3b7a13879aae0ad7fe5171fca1939d65.pSQTGMRBL8PO4VxW_Y3J3ZZREZDuconTOwUJnXnUyn4+ hash: v1.k794b7964.e50ba21fe7a4a5d690ab033b46af9e0a38ccb003e3fdf84e5e2fd1c23d071f7e.DPWsjNBZn4T8iV76Lsg6X4txN827VTHFpCsB_qgslBQscenes-app-replay-vision--observation-detail-summarize-button--light:- hash: v1.k794b7964.6b8d659d537b98e11ff5a73e1d80f801d50980450845a7ab8bc574e1bb999d89.eASeUu7GVtBYfK9fq4HRPArLXsJJ_tYVZ1lItGfqbl8+ hash: v1.k794b7964.491a0e0883bcbf0cc6206b910db87e1aa01c8cc9adbd51a7f11a6cd5662010a8.jBI2OFokY37mhDn-XB3OIj7htiD2eLmUjzSHlaeulskscenes-app-replay-vision--observation-detail-summary-with-timeline--dark:hash: v1.k794b7964.5f217eb61e6b3a843dc8fb6d9b255f55aff8f95e29581c4ee303db78fc4eb2ad.u9RtPaF134pNlgU-fbrbUnPrw3hkRV0lvxlBXeALgUcscenes-app-replay-vision--observation-detail-summary-with-timeline--light:diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsxindex 28e8b29e6296..d9817e53688b 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx@@ -81,6 +81,7 @@ const SOURCE_TYPE_TO_PATH: Record<NotificationEventSourceTypeEnumApi, ((id: strierror_tracking: (id) => urls.errorTrackingIssue(id),customer_analytics: null,ticket: (id) => urls.supportTicketDetail(id),+ replay_observation: (id) => urls.replayVisionObservation(id),}export interface NotificationGroup {diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/discussion/SidePanelDiscussion.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/discussion/SidePanelDiscussion.tsxindex 404fb1f29819..1ab211eafd91 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/discussion/SidePanelDiscussion.tsx+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/discussion/SidePanelDiscussion.tsx@@ -17,7 +17,8 @@ import { sidePanelDiscussionLogic } from './sidePanelDiscussionLogic'const HedgehogStop = pngHoggie(stopPng)export const SidePanelDiscussion = (): JSX.Element => {- const { commentsLogicProps } = useValues(sidePanelDiscussionLogic)+ const { commentsLogicProps, sceneSidePanelContext } = useValues(sidePanelDiscussionLogic)+ const disabledReason = sceneSidePanelContext.discussions_disabled_reasonconst { scope, item_id } = commentsLogicProps ?? {}const discussionTitle = (@@ -43,6 +44,8 @@ export const SidePanelDiscussion = (): JSX.Element => {<DiscussionContent logicProps={commentsLogicProps}><SidePanelPaneHeader title={discussionTitle} /></DiscussionContent>+ ) : disabledReason ? (+ <p className="m-0 p-4 text-secondary">{disabledReason}</p>) : (<div className="mx-auto p-8 max-w-160 mt-8 "><div className="max-w-24 mx-auto">diff --git a/frontend/src/layout/navigation-3000/sidepanel/types.ts b/frontend/src/layout/navigation-3000/sidepanel/types.tsindex 48017e11fcea..adfe3f4f329f 100644--- a/frontend/src/layout/navigation-3000/sidepanel/types.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/types.ts@@ -11,6 +11,8 @@ export type SidePanelSceneContext = {// only currently used for comments which are very similar to activity itemsactivity_item_context?: CommentType['item_context']discussions_disabled?: boolean+ /** Why this scene has turned discussions off, shown in place of the generic "not supported" message. */+ discussions_disabled_reason?: string/** The canvas on screen. Its panel tabs replace the general ones. */canvas_id?: string/** Whether the canvas on screen is being edited by hand, which adds its Blocks tab. */diff --git a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsxindex d9be5010424b..012f693a116e 100644--- a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx+++ b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx@@ -231,6 +231,7 @@ const SCOPE_DISPLAY_NAMES: Partial<Record<ActivityScope, { singular: string; plusingular: 'Project secret API key',plural: 'Project secret API keys',},+ [ActivityScope.REPLAY_OBSERVATION]: { singular: 'Observation', plural: 'Observations' },[ActivityScope.TICKET]: { singular: 'Support ticket', plural: 'Support tickets' },}diff --git a/frontend/src/lib/components/Comments/Comment.tsx b/frontend/src/lib/components/Comments/Comment.tsxindex 9ceb987d8138..d916196843c9 100644--- a/frontend/src/lib/components/Comments/Comment.tsx+++ b/frontend/src/lib/components/Comments/Comment.tsx@@ -24,7 +24,7 @@ import { CommentType } from '~/types'import { CommentComposer } from './CommentComposer'import { CommentsLogicProps, CommentWithRepliesType, commentsLogic } from './commentsLogic'-import { getCommentText, getRecordingLinkInfo, isViewingRecording } from './commentUtils'+import { getCommentText, getRecordingLinkInfo, isViewingRecording, scopeSyncsToSlack } from './commentUtils'import { sendCommentToSlackLogic } from './sendCommentToSlackLogic'// Comments that came in from a synced Slack thread have no PostHog author; their Slack identity@@ -197,7 +197,11 @@ const CommentTopRow = ({ comment }: { comment: CommentType }): JSX.Element => {const slackThread = comment.slack_thread// Only an untracked top-level comment (a thread root) can be sent to Slack; replies follow their parent.const canSendToSlack =- featureFlags[FEATURE_FLAGS.DISCUSSIONS_SLACK_SYNC] && !comment.source_comment && !fromSlack && !slackThread+ featureFlags[FEATURE_FLAGS.DISCUSSIONS_SLACK_SYNC] &&+ scopeSyncsToSlack(comment.scope) &&+ !comment.source_comment &&+ !fromSlack &&+ !slackThreadreturn (<div className="flex items-center justify-between gap-2">diff --git a/frontend/src/lib/components/Comments/CommentComposer.tsx b/frontend/src/lib/components/Comments/CommentComposer.tsxindex 98834eac9a80..75227b9dbd96 100644--- a/frontend/src/lib/components/Comments/CommentComposer.tsx+++ b/frontend/src/lib/components/Comments/CommentComposer.tsx@@ -11,6 +11,7 @@ import { LemonRichContentEditor } from 'lib/lemon-ui/LemonRichContent/LemonRichCimport { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { CommentsLogicProps, commentsLogic } from './commentsLogic'+import { scopeSyncsToSlack } from './commentUtils'import { SlackDestinationPicker } from './SlackDestinationPicker'export type CommentComposerProps = CommentsLogicProps & {@@ -43,7 +44,8 @@ export const CommentComposer = ({ variant = 'footer', ...props }: CommentComposeconst { featureFlags } = useValues(featureFlagLogic)// Toggling a brand-new top-level comment straight to Slack; replies sync automatically.- const showSlackToggle = !replyingCommentId && !!featureFlags[FEATURE_FLAGS.DISCUSSIONS_SLACK_SYNC]+ const showSlackToggle =+ !replyingCommentId && !!featureFlags[FEATURE_FLAGS.DISCUSSIONS_SLACK_SYNC] && scopeSyncsToSlack(props.scope)const placeholder = replyingCommentId? 'Reply...'diff --git a/frontend/src/lib/components/Comments/commentUtils.ts b/frontend/src/lib/components/Comments/commentUtils.tsindex 97c562195e10..3babfde01672 100644--- a/frontend/src/lib/components/Comments/commentUtils.ts+++ b/frontend/src/lib/components/Comments/commentUtils.ts@@ -34,6 +34,13 @@ export function getRecordingLinkInfo(comment: RecordingCommentTarget): Recording}}+/** Scopes whose discussions never mirror to Slack, because a Slack channel cannot apply their access checks. */+const SCOPES_WITHOUT_SLACK_SYNC: ReadonlySet<string> = new Set([ActivityScope.REPLAY_OBSERVATION])++export function scopeSyncsToSlack(scope: string): boolean {+ return !SCOPES_WITHOUT_SLACK_SYNC.has(scope)+}+export function getCommentText(comment: { content?: string | null; rich_content?: JSONContent | null }): string {// This is only temporary until all comments are backfilled to rich contentconst content = comment.rich_contentdiff --git a/frontend/src/types.ts b/frontend/src/types.tsindex c8ed19bffd37..b300bd61c67b 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -6196,6 +6196,7 @@ export enum ActivityScope {CROSS_PROJECT_DASHBOARD = 'CrossProjectDashboard',REPLAY = 'Replay',REPLAY_SCANNER = 'ReplayScanner',+ REPLAY_OBSERVATION = 'ReplayObservation',VISION_ALERT_CONFIGURATION = 'VisionAlertConfiguration',// TODO: doh! we don't need replay and recordingRECORDING = 'recording',diff --git a/posthog/api/comments.py b/posthog/api/comments.pyindex 7564e7942c7d..93d2f7bfbd1d 100644--- a/posthog/api/comments.py+++ b/posthog/api/comments.py@@ -1,3 +1,4 @@+import uuidfrom contextlib import nullcontextfrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Any, cast@@ -32,6 +33,7 @@ from posthog.models.comment import Comment, CommentSlackThreadfrom posthog.models.comment.comment import (CANVAS_COMMENT_SCOPES,COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API,+ OBSERVATION_COMMENT_SCOPES,TICKET_COMMENT_SCOPES,activity_log_scope_for,canonical_comment_scope,@@ -51,6 +53,11 @@ from posthog.tasks.comment_slack_sync import backfill_comment_slack_threadfrom posthog.tasks.email import send_discussions_mentionedfrom products.conversations.backend import reply_dedupe+from products.replay_vision.backend.facade.api import (+ can_view_observation,+ observation_note_write_rejection,+ observation_viewer_user_ids,+)if TYPE_CHECKING:from products.access_control.backend.facade.user_access_control import UserAccessControl@@ -90,6 +97,18 @@ def _require_ticket_editor_access(raise exceptions.PermissionDenied("You do not have access to this ticket")+def _can_view_observation(*, team_id: int, item_id: str | None, user_access_control: "UserAccessControl") -> bool:+ return bool(item_id) and can_view_observation(user_access_control, team_id, cast(str, item_id))+++def _canonical_observation_id(item_id: Any) -> Any:+ """Store observation ids in one spelling, so lookups and cleanup that compare strings find every note."""+ try:+ return str(uuid.UUID(str(item_id)))+ except ValueError:+ return item_id++# A reservation with no posted root older than this is a crashed send — safe to retry.STALE_SLACK_RESERVATION_GRACE = timedelta(minutes=2)@@ -248,6 +267,11 @@ def _stored_comment_task_id(comment: Comment) -> str | None:def _mentions_allowed_for_comment_target(*, team_id: int, scope: str, item_id: str | None, item_context: dict | None, mentioned_user_ids: list[int]) -> list[int]:+ if scope in OBSERVATION_COMMENT_SCOPES:+ if not item_id:+ return []+ viewer_ids = observation_viewer_user_ids(team_id=team_id, observation_id=item_id, user_ids=mentioned_user_ids)+ return [user_id for user_id in mentioned_user_ids if user_id in viewer_ids]if scope not in DESKTOP_COMMENT_SCOPES:return mentioned_user_idsif scope in CANVAS_COMMENT_SCOPES:@@ -441,6 +465,19 @@ class CommentSerializer(serializers.ModelSerializer):scope = root.scopeitem_id = root.item_id+ if scope in OBSERVATION_COMMENT_SCOPES and "item_id" in data:+ data["item_id"] = item_id = _canonical_observation_id(item_id)++ # A note's replies are read through its thread, which checks only the root. Fixing where an observation+ # note sits, and which thread it is in, keeps a whole thread under one access check.+ if instance and ({instance.scope, scope, getattr(source_comment, "scope", None)} & OBSERVATION_COMMENT_SCOPES):+ if (scope, item_id) != (instance.scope, instance.item_id):+ raise exceptions.ValidationError({"item_id": "An observation note cannot move to another item."})+ if getattr(source_comment, "id", None) != instance.source_comment_id:+ raise exceptions.ValidationError(+ {"source_comment": "An observation note cannot move to another thread."}+ )+scopes_and_items = {(scope, item_id)}if instance:scopes_and_items.add((instance.scope, instance.item_id))@@ -453,6 +490,18 @@ class CommentSerializer(serializers.ModelSerializer):item_id=target_item_id,user_access_control=self.context["get_user_access_control"](),)+ elif target_scope in OBSERVATION_COMMENT_SCOPES:+ rejection = (+ observation_note_write_rejection(+ self.context["get_user_access_control"](), self.context["get_team"]().id, target_item_id+ )+ if target_item_id+ else "forbidden"+ )+ if rejection == "forbidden":+ raise exceptions.PermissionDenied("You do not have access to this observation")+ if rejection == "not_finished":+ raise exceptions.ValidationError({"item_id": "You can add notes after the scan succeeds."})target_scope = data.get("scope", instance.scope if instance else None)target_item_id = data.get("item_id", instance.item_id if instance else None)@@ -734,12 +783,17 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVexcept (ValueError, django_exceptions.ValidationError):return Nonecandidate_scopes.discard(None)- if not candidate_scopes & TICKET_COMMENT_SCOPES:+ is_ticket = bool(candidate_scopes & TICKET_COMMENT_SCOPES)+ is_observation = bool(candidate_scopes & OBSERVATION_COMMENT_SCOPES)+ if not is_ticket and not is_observation:return Noneaccess = "read" if self.action in self.scope_object_read_actions else "write"- required: list[str] = [f"ticket:{access}"]+ required: list[str] = [f"ticket:{access}"] if is_ticket else []if candidate_scopes - TICKET_COMMENT_SCOPES:required.append(f"comment:{access}")+ if is_observation:+ # Observation notes are recording-derived content, so they need the observation API's read scopes too.+ required.extend(["replay_scanner:read", "session_recording:read"])return required@extend_schema(parameters=[CommentListQueryParamsSerializer])@@ -878,13 +932,7 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVTicket,)- pk = self.kwargs.get("pk")- if not pk:- return- try:- target = Comment.objects.filter(team_id=self.team_id, pk=pk).values_list("scope", "item_id").first()- except (ValueError, django_exceptions.ValidationError):- return+ target = self._pk_target()if not target:returnscope, item_id = target@@ -904,6 +952,28 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV# Match the list path, where a denied ticket's comments are simply absent.raise exceptions.NotFound()+ def _pk_target(self) -> tuple[str, str | None] | None:+ """The (scope, item_id) of the detail action's comment, read once for every scope gate."""+ if not hasattr(self, "_pk_target_cache"):+ target = None+ if pk := self.kwargs.get("pk"):+ try:+ target = Comment.objects.filter(team_id=self.team_id, pk=pk).values_list("scope", "item_id").first()+ except (ValueError, django_exceptions.ValidationError):+ target = None+ self._pk_target_cache = target+ return self._pk_target_cache++ def _require_observation_viewer_access_for_pk(self) -> None:+ """Gate a detail action on the observation its target comment belongs to, as the list path does."""+ target = self._pk_target()+ if not target or target[0] not in OBSERVATION_COMMENT_SCOPES:+ return+ if not _can_view_observation(+ team_id=self.team_id, item_id=target[1], user_access_control=self.user_access_control+ ):+ raise exceptions.NotFound()+def _require_task_comment_viewer_access_for_pk(self) -> None:pk = self.kwargs.get("pk")if not pk:@@ -991,6 +1061,11 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV)if scope in TICKET_COMMENT_SCOPES:queryset = self._filter_ticket_scoped_queryset(queryset, params.get("item_id"))+ elif scope in OBSERVATION_COMMENT_SCOPES:+ if not _can_view_observation(+ team_id=self.team_id, item_id=params.get("item_id"), user_access_control=self.user_access_control+ ):+ return queryset.none()elif scope in DESKTOP_COMMENT_SCOPES:task_id = params.get("task_id")item_id = params.get("item_id")@@ -1011,9 +1086,12 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVelif self.action in ("list", "count"):# Product-owned scopes require their own object-level access checks and must# never leak through an unscoped generic comments query.- queryset = queryset.exclude(scope__in=[*TICKET_COMMENT_SCOPES, *DESKTOP_COMMENT_SCOPES])+ queryset = queryset.exclude(+ scope__in=[*TICKET_COMMENT_SCOPES, *DESKTOP_COMMENT_SCOPES, *OBSERVATION_COMMENT_SCOPES]+ )else:self._require_ticket_viewer_access_for_pk()+ self._require_observation_viewer_access_for_pk()self._require_task_comment_viewer_access_for_pk()if params.get("item_id"):@@ -1160,6 +1238,9 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVraise exceptions.ValidationError("Only a top-level comment (a thread root) can be sent to Slack")if comment.scope == "conversations_ticket":raise exceptions.ValidationError("Conversations tickets sync to Slack through the support product")+ if comment.scope in OBSERVATION_COMMENT_SCOPES:+ # A Slack channel has no observation access check, in either direction.+ raise exceptions.ValidationError("Replay Vision observation notes cannot be sent to Slack")params = SendCommentToSlackSerializer(data=request.data)params.is_valid(raise_exception=True)diff --git a/posthog/api/test/test_comments.py b/posthog/api/test/test_comments.pyindex 707143c2eaf7..3c3631e10d40 100644--- a/posthog/api/test/test_comments.py+++ b/posthog/api/test/test_comments.py@@ -2563,6 +2563,13 @@ class TestCommentHelperFunctions(SimpleTestCase):("without_slug_dashboard", "Dashboard", "789", "", "/dashboard/789#panel=discussion"),("without_slug_replay", "Replay", "rec_123", "", "/replay/rec_123#panel=discussion"),("without_slug_feature_flag", "FeatureFlag", "10", "", "/feature-flags/10#panel=discussion"),+ (+ "without_slug_replay_observation",+ "ReplayObservation",+ "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b",+ "",+ "/replay-vision/observations/0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b#panel=discussion",+ ),("unknown_scope_fallback", "UnknownScope", "123", "", "#panel=discussion"),# item_id is client-supplied free text — mrkdwn/URL control chars must be encoded.(diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex bfe63e3595e2..6939f7074915 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -75,6 +75,7 @@ ActivityScope = Literal["EarlyAccessFeature","SessionRecordingPlaylist","ReplayScanner",+ "ReplayObservation","VisionAlertConfiguration","Comment","Team",@@ -458,6 +459,8 @@ field_with_masked_contents: dict[AuditableScope, list[str]] = {# directly, keyed by the comment's own scope."Ticket": ["content"],cast(AuditableScope, "conversations_ticket"): ["content"],+ # Observation notes are gated on observation access, which activity_log:read does not imply.+ "ReplayObservation": ["content"],# The rubric API is limited to staff, so saved criteria and generated suggestions must not be# readable through activity_log:read. Record that the rubrics changed, never their contents."SignalScoutConfig": ["rubrics"],diff --git a/posthog/models/comment/comment.py b/posthog/models/comment/comment.pyindex 5eaef91b9091..3839bd2d53fd 100644--- a/posthog/models/comment/comment.py+++ b/posthog/models/comment/comment.py@@ -76,6 +76,10 @@ TICKET_COMMENT_SCOPES = frozenset({"Ticket", "conversations_ticket"})# Product-owned content in these scopes is available only through the owning product's API.COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API = frozenset({"EmailThread"})+# Notes on a Replay Vision observation discuss recording-derived output, so reading, writing and+# being mentioned in them all require access to the observation itself.+OBSERVATION_COMMENT_SCOPES = frozenset({"ReplayObservation"})+CANVAS_COMMENT_SCOPES = frozenset({"canvas", "desktop_canvas"})STORED_CANVAS_COMMENT_SCOPE = "canvas"diff --git a/posthog/models/comment/slack_thread.py b/posthog/models/comment/slack_thread.pyindex b1d8cd33161d..375c053c822e 100644--- a/posthog/models/comment/slack_thread.py+++ b/posthog/models/comment/slack_thread.py@@ -1,6 +1,6 @@from django.db import models, transaction-from posthog.models.comment.comment import COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API, Comment+from posthog.models.comment.comment import COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API, OBSERVATION_COMMENT_SCOPES, Commentfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.signals import mutable_receiverfrom posthog.models.utils import UUIDModel@@ -74,7 +74,11 @@ def mirror_comment_reply_to_slack_on_create(sender, instance: Comment, created:"""if not created or not instance.source_comment_id:return- if instance.scope == "conversations_ticket" or instance.scope in COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API:+ if (+ instance.scope == "conversations_ticket"+ or instance.scope in COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API+ or instance.scope in OBSERVATION_COMMENT_SCOPES+ ):returnitem_context = instance.item_contextif isinstance(item_context, dict) and (item_context.get("from_slack") or item_context.get("is_emoji")):diff --git a/posthog/models/comment/utils.py b/posthog/models/comment/utils.pyindex 8a0e19dd9fdb..86f6da80cd44 100644--- a/posthog/models/comment/utils.py+++ b/posthog/models/comment/utils.py@@ -7,7 +7,7 @@ import structlogfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import User-from posthog.models.comment.comment import CANVAS_COMMENT_SCOPES+from posthog.models.comment.comment import CANVAS_COMMENT_SCOPES, OBSERVATION_COMMENT_SCOPESfrom products.cdp.backend.internal_events import InternalEventEvent, InternalEventPerson, produce_internal_event@@ -27,6 +27,7 @@ SCOPE_TO_SOURCE_TYPE: dict[str, str] = {"Survey": "survey","Experiment": "experiment","ErrorTracking": "error_tracking",+ "ReplayObservation": "replay_observation",# Unlike the PascalCase model-name scopes above, customer-facing ticket messages are written# with the literal "conversations_ticket" scope (see products/conversations), while internal# ticket discussions use the "Ticket" scope. Both are ticket-sourced.@@ -42,6 +43,7 @@ SCOPE_TO_PATH_MAPPING: dict[str, str] = {"Dashboard": "/dashboard/{item_id}","Survey": "/surveys/{item_id}","Experiment": "/experiments/{item_id}",+ "ReplayObservation": "/replay-vision/observations/{item_id}",# See note above: customer-facing ticket messages use the "conversations_ticket" scope literal,# while internal ticket discussions use the "Ticket" scope. Both land on the ticket page."conversations_ticket": "/support/tickets/{item_id}",@@ -59,6 +61,7 @@ SCOPE_DISPLAY_NAMES: dict[str, str] = {"Survey": "a survey","Experiment": "an experiment","ErrorTracking": "an error tracking issue",+ "ReplayObservation": "a Replay Vision observation","Ticket": "a support ticket",}@@ -115,6 +118,17 @@ def extract_plain_text_from_rich_content(rich_content: Optional[dict]) -> str:return "".join(text_parts)+# Mention notifications and events outlive the access check made when they are sent, and the notifications+# API and CDP destinations do not recheck the observation. So they carry this text instead of the note.+OBSERVATION_NOTE_PLACEHOLDER = "A note on a Replay Vision observation. Open it in PostHog to read it."+++def _mention_fanout_content(comment: "Comment") -> str | None:+ if comment.scope in OBSERVATION_COMMENT_SCOPES:+ return OBSERVATION_NOTE_PLACEHOLDER+ return extract_plain_text_from_rich_content(comment.rich_content) or comment.content++def produce_discussion_mention_events(comment: "Comment",mentioned_user_ids: list[int],@@ -130,7 +144,7 @@ def produce_discussion_mention_events(returnitem_url = build_comment_item_url(comment.scope, comment.item_id, slug)- comment_content = extract_plain_text_from_rich_content(comment.rich_content) or comment.content+ comment_content = _mention_fanout_content(comment)commenter_data = {"id": str(commenter.id),@@ -190,7 +204,7 @@ def send_mention_notifications(if not commenter:return- comment_content = extract_plain_text_from_rich_content(comment.rich_content) or comment.content+ comment_content = _mention_fanout_content(comment)body = comment_content[:200] if comment_content else ""for user_id in mentioned_user_ids:diff --git a/posthog/tasks/comment_slack_sync.py b/posthog/tasks/comment_slack_sync.pyindex 859ea20b5d2d..812fd330013a 100644--- a/posthog/tasks/comment_slack_sync.py+++ b/posthog/tasks/comment_slack_sync.py@@ -10,7 +10,7 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.comment.formatting import slack_files_to_placeholder_lines, slack_to_content_and_rich_contentfrom posthog.helpers.slack_thread_mirror import post_comment_to_slack_thread, slack_author_from_userfrom posthog.models.comment import Comment, CommentSlackThread-from posthog.models.comment.comment import COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API+from posthog.models.comment.comment import COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API, OBSERVATION_COMMENT_SCOPESfrom posthog.models.comment.slack_thread import DISCUSSIONS_SLACK_SYNC_FLAGfrom posthog.models.integration import SlackIntegrationfrom posthog.models.team import Team@@ -122,7 +122,7 @@ def _mark_reply_synced(reply: Comment, ts: object) -> None:def _reply_skip_reason(reply: Comment) -> str | None:- if reply.scope in COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API:+ if reply.scope in COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API or reply.scope in OBSERVATION_COMMENT_SCOPES:return "protected_scope"item_context = reply.item_context if isinstance(reply.item_context, dict) else {}if item_context.get("from_slack"):@@ -208,7 +208,7 @@ def ingest_slack_discussion_reply(.select_related("integration__team").first())- if mirror is None:+ if mirror is None or mirror.scope in OBSERVATION_COMMENT_SCOPES:return# message_ts is the idempotency key; without it a redelivered event would duplicate the# comment (the enqueuing side already refuses these — this is the fail-closed backstop).diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 7e74281542cb..f1a0decaabe9 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -43,7 +43,8 @@ from posthog.models import ()from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.comment import Comment-from posthog.models.comment.utils import DESKTOP_COMMENT_SCOPES, build_comment_item_url+from posthog.models.comment.comment import OBSERVATION_COMMENT_SCOPES+from posthog.models.comment.utils import DESKTOP_COMMENT_SCOPES, OBSERVATION_NOTE_PLACEHOLDER, build_comment_item_urlfrom posthog.models.messaging import MessagingRecord, get_email_hashesfrom posthog.models.organization_notification_lock import (GovernedSetting,@@ -2139,7 +2140,10 @@ def send_discussions_mentioned(comment_id: str, mentioned_user_ids: list[int], stemplate_name="discussions_mentioned",template_context={"commenter": commenter,- "content": comment.content,+ # The email is sent later than the access check on the mention, so it never carries an observation note.+ "content": OBSERVATION_NOTE_PLACEHOLDER+ if comment.scope in OBSERVATION_COMMENT_SCOPES+ else comment.content,"team": team,"href": href,},diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex bf65addbdff3..3d82026dafcc 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -291,6 +291,7 @@ pre_delete:products.customer_analytics.backend.signals.delete_private_account_vipre_delete:products.experiments.backend.activity_logging.handle_experiment_holdout_deletepre_delete:products.experiments.backend.activity_logging.handle_experiment_saved_metric_deletepre_delete:products.managed_migrations.backend.activity_logging.handle_batch_import_delete+pre_delete:products.replay_vision.backend.observation_notes.delete_scanner_observation_notespre_delete:products.tasks.backend.models.clear_channel_repositories_on_github_integration_deletepre_delete:products.tasks.backend.team_deletion.cancel_task_workflows_on_team_deletepre_save:posthog.models.event_ingestion_restriction_config.capture_old_restriction_typediff --git a/products/notifications/backend/facade/enums.py b/products/notifications/backend/facade/enums.pyindex e6ce88df2f13..958081fc495d 100644--- a/products/notifications/backend/facade/enums.py+++ b/products/notifications/backend/facade/enums.py@@ -57,6 +57,7 @@ class SourceType(str, Enum):ERROR_TRACKING = "error_tracking"CUSTOMER_ANALYTICS = "customer_analytics"TICKET = "ticket"+ REPLAY_OBSERVATION = "replay_observation"class NotificationOnlyResourceType(str, Enum):diff --git a/products/notifications/frontend/generated/api.schemas.ts b/products/notifications/frontend/generated/api.schemas.tsindex 21b8d261a290..f54d2b5710ec 100644--- a/products/notifications/frontend/generated/api.schemas.ts+++ b/products/notifications/frontend/generated/api.schemas.ts@@ -18,6 +18,7 @@* * `error_tracking` - ERROR_TRACKING* * `customer_analytics` - CUSTOMER_ANALYTICS* * `ticket` - TICKET+ * * `replay_observation` - REPLAY_OBSERVATION*/export type NotificationEventSourceTypeEnumApi =(typeof NotificationEventSourceTypeEnumApi)[keyof typeof NotificationEventSourceTypeEnumApi]@@ -33,6 +34,7 @@ export const NotificationEventSourceTypeEnumApi = {ErrorTracking: 'error_tracking',CustomerAnalytics: 'customer_analytics',Ticket: 'ticket',+ ReplayObservation: 'replay_observation',} as const/**diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex 584b6c35d89e..4663b09a6084 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -1420,6 +1420,7 @@ export type ActivityLogListParams = {* * `EarlyAccessFeature` - EarlyAccessFeature* * `SessionRecordingPlaylist` - SessionRecordingPlaylist* * `ReplayScanner` - ReplayScanner+ * * `ReplayObservation` - ReplayObservation* * `VisionAlertConfiguration` - VisionAlertConfiguration* * `Comment` - Comment* * `Team` - Team@@ -1536,6 +1537,7 @@ export const ActivityLogListScope = {EarlyAccessFeature: 'EarlyAccessFeature',SessionRecordingPlaylist: 'SessionRecordingPlaylist',ReplayScanner: 'ReplayScanner',+ ReplayObservation: 'ReplayObservation',VisionAlertConfiguration: 'VisionAlertConfiguration',Comment: 'Comment',Team: 'Team',@@ -1639,6 +1641,7 @@ export const ActivityLogListScope = {* * `EarlyAccessFeature` - EarlyAccessFeature* * `SessionRecordingPlaylist` - SessionRecordingPlaylist* * `ReplayScanner` - ReplayScanner+ * * `ReplayObservation` - ReplayObservation* * `VisionAlertConfiguration` - VisionAlertConfiguration* * `Comment` - Comment* * `Team` - Team@@ -1743,6 +1746,7 @@ export const ActivityLogListScopesItem = {EarlyAccessFeature: 'EarlyAccessFeature',SessionRecordingPlaylist: 'SessionRecordingPlaylist',ReplayScanner: 'ReplayScanner',+ ReplayObservation: 'ReplayObservation',VisionAlertConfiguration: 'VisionAlertConfiguration',Comment: 'Comment',Team: 'Team',diff --git a/products/replay_vision/backend/apps.py b/products/replay_vision/backend/apps.pyindex 16d918458cb7..47e937765b9b 100644--- a/products/replay_vision/backend/apps.py+++ b/products/replay_vision/backend/apps.py@@ -13,5 +13,6 @@ class ReplayVisionConfig(AppConfig):activity_logging,experiment_launch,media_expiry,+ observation_notes,search_suggestion_cleanup,)diff --git a/products/replay_vision/backend/facade/api.py b/products/replay_vision/backend/facade/api.pyindex 3a2bdd06e637..24bfd3c8fecc 100644--- a/products/replay_vision/backend/facade/api.py+++ b/products/replay_vision/backend/facade/api.py@@ -1,3 +1,4 @@+from collections.abc import Iterablefrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Literalfrom uuid import UUID@@ -19,7 +20,9 @@ from products.replay_vision.backend.models.replay_scanner import ReplayScanner,from products.replay_vision.backend.observation_formatting import format_line, read_outputfrom products.replay_vision.backend.scanner_access import (accessible_observations,+ can_read_observation,can_read_targeted_experiment,+ is_uuid,readable_observation_scanner_ids,)from products.replay_vision.backend.session_limits import MAX_SESSION_ID_LENGTH@@ -298,6 +301,73 @@ def start_workflow_observation_request()+def can_view_observation(access: UserAccessControl, team_id: int, observation_id: str) -> bool:+ """Whether the caller may read one observation, with the gates the observations API applies.++ Those are session recording access, the scanner's RBAC, the scanner's current experiment and the+ experiment in the observation's own snapshot. A malformed or unknown id reads as not viewable.+ """+ observation = _observation_for_access_check(team_id, observation_id)+ return observation is not None and _can_view_loaded_observation(access, team_id, observation)+++NoteWriteRejection = Literal["forbidden", "not_finished"]+++def observation_note_write_rejection(+ access: UserAccessControl, team_id: int, observation_id: str+) -> NoteWriteRejection | None:+ """Why the caller may not write a note on the observation, or None.++ Notes need read access, and a succeeded scan: a retry deletes a failed or ineligible row and the new+ scan gets a new id, which would strand the notes on the old one.+ """+ observation = _observation_for_access_check(team_id, observation_id)+ if observation is None or not _can_view_loaded_observation(access, team_id, observation):+ return "forbidden"+ if observation.status != ObservationStatus.SUCCEEDED:+ return "not_finished"+ return None+++def observation_viewer_user_ids(*, team_id: int, observation_id: str, user_ids: Iterable[int]) -> set[int]:+ """The users among `user_ids` who may read the observation, so a note's mentions reach only them.++ The observation and the memberships load once for all users. Each user still needs their own access+ resolution, because access control is per member.+ """+ observation = _observation_for_access_check(team_id, observation_id)+ if observation is None:+ return set()+ team = TeamModel.objects.get(id=team_id)+ member_ids = OrganizationMembership.objects.filter(+ organization_id=team.organization_id, user_id__in=list(user_ids), user__is_active=True+ ).values_list("user_id", flat=True)+ viewer_ids: set[int] = set()+ for user in User.objects.filter(id__in=list(member_ids)):+ access = UserAccessControl(user=user, team=team, organization_id=str(team.organization_id))+ if access.has_project_access and _can_view_loaded_observation(access, team_id, observation):+ viewer_ids.add(user.id)+ return viewer_ids+++def _observation_for_access_check(team_id: int, observation_id: str) -> ReplayObservation | None:+ if not is_uuid(observation_id):+ return None+ return ReplayObservation.objects.filter(team_id=team_id, id=observation_id).select_related("scanner").first()+++def _can_view_loaded_observation(access: UserAccessControl, team_id: int, observation: ReplayObservation) -> bool:+ if not access.check_access_level_for_resource("session_recording", required_level="viewer"):+ return False+ scanner = observation.scanner+ return (+ bool(access.check_access_level_for_object(scanner, "viewer"))+ and can_read_targeted_experiment(access, team_id, scanner)+ and can_read_observation(access, team_id, observation)+ )++def _can_scan_with(access: UserAccessControl, team_id: int, scanner: ReplayScanner) -> bool:return bool(access.check_access_level_for_object(scanner, "editor")) and can_read_targeted_experiment(access, team_id, scannerdiff --git a/products/replay_vision/backend/observation_notes.py b/products/replay_vision/backend/observation_notes.pynew file mode 100644index 000000000000..f92c8a511779--- /dev/null+++ b/products/replay_vision/backend/observation_notes.py@@ -0,0 +1,31 @@+"""Deleting the notes on observations that go away with their scanner.++Notes are generic comments keyed by observation id, so no foreign key cascades them. The receiver sits on+the scanner, not the observation, because a per-observation receiver would add one query for each+observation in a scanner delete. A retry deletes only failed or ineligible rows, which cannot have notes,+and a team delete cascades comments through the team.+"""++from django.db.models import CharField+from django.db.models.functions import Cast+from django.db.models.signals import pre_delete+from django.dispatch import receiver++from posthog.models.comment import Comment+from posthog.models.comment.comment import OBSERVATION_COMMENT_SCOPES++from products.replay_vision.backend.models.replay_observation import ReplayObservation+from products.replay_vision.backend.models.replay_scanner import ReplayScanner+++@receiver(pre_delete, sender=ReplayScanner)+def delete_scanner_observation_notes(sender: type[ReplayScanner], instance: ReplayScanner, **kwargs: object) -> None:+ # Note item_ids are stored as canonical UUID text, so the scanner's observation ids match them in SQL.+ observation_ids = (+ ReplayObservation.objects.filter(team_id=instance.team_id, scanner_id=instance.id)+ .annotate(id_text=Cast("id", output_field=CharField()))+ .values("id_text")+ )+ Comment.objects.filter(+ team_id=instance.team_id, scope__in=OBSERVATION_COMMENT_SCOPES, item_id__in=observation_ids+ ).delete()diff --git a/products/replay_vision/backend/tests/test_observation_notes.py b/products/replay_vision/backend/tests/test_observation_notes.pynew file mode 100644index 000000000000..a185af1230a2--- /dev/null+++ b/products/replay_vision/backend/tests/test_observation_notes.py@@ -0,0 +1,319 @@+from posthog.test.base import APIBaseTest+from unittest import mock++from django.utils import timezone++from parameterized import parameterized+from rest_framework import status++from posthog.constants import AvailableFeature+from posthog.models import User+from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.comment import Comment, CommentSlackThread+from posthog.models.comment.utils import OBSERVATION_NOTE_PLACEHOLDER+from posthog.tasks.email import send_discussions_mentioned++from products.access_control.backend.models.access_control import AccessControl+from products.replay_vision.backend.models.replay_observation import (+ ObservationStatus,+ ObservationTrigger,+ ReplayObservation,+)+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType+from products.replay_vision.backend.tests.helpers import snapshot_for++SCOPE = "ReplayObservation"+++class TestObservationNotesAccess(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ self.scanner = ReplayScanner.objects.create(+ team=self.team,+ name="Checkout monitor",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "did the user check out?"},+ model=ScannerModel.GEMINI_3_8_FLASH,+ )+ self.observation = ReplayObservation.objects.create(+ scanner=self.scanner,+ team=self.team,+ session_id="s-notes",+ status=ObservationStatus.SUCCEEDED,+ scanner_snapshot=snapshot_for(self.scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ completed_at=timezone.now(),+ )+ self.note = Comment.objects.create(+ team=self.team, scope=SCOPE, item_id=str(self.observation.id), content="private note", created_by=self.user+ )+ self.member = User.objects.create_and_join(self.organization, "[email protected]", "password")++ def _set_member_scanner_access(self, access_level: str) -> None:+ self._set_member_access("replay_scanner", access_level, str(self.scanner.id))++ def _set_member_access(self, resource: str, access_level: str, resource_id: str | None = None) -> None:+ AccessControl.objects.create(+ team=self.team,+ resource=resource,+ resource_id=resource_id,+ organization_member=self.member.organization_memberships.get(organization=self.organization),+ access_level=access_level,+ )++ @parameterized.expand(+ [+ ("scanner_denied", "replay_scanner", "none", False),+ ("recordings_denied", "session_recording", "none", False),+ ("scanner_viewer", "replay_scanner", "viewer", True),+ ]+ )+ def test_notes_follow_observation_access(self, _name: str, resource: str, access_level: str, allowed: bool) -> None:+ self._set_member_access(resource, access_level, str(self.scanner.id) if resource == "replay_scanner" else None)+ self.client.force_login(self.member)+ base = f"/api/projects/{self.team.id}/comments"+ target = f"scope={SCOPE}&item_id={self.observation.id}"++ listed = self.client.get(f"{base}?{target}").json()["results"]+ unscoped = self.client.get(base).json()["results"]+ detail = self.client.get(f"{base}/{self.note.id}")+ thread = self.client.get(f"{base}/{self.note.id}/thread")+ count = self.client.get(f"{base}/count?{target}").json()["count"]+ created = self.client.post(base, {"content": "my note", "scope": SCOPE, "item_id": str(self.observation.id)})+ reply = self.client.post(base, {"content": "my reply", "scope": SCOPE, "source_comment": str(self.note.id)})++ assert [c["id"] for c in listed] == ([str(self.note.id)] if allowed else [])+ # Product-owned scopes never ride along on an unscoped list, whatever the caller's access.+ assert unscoped == []+ assert detail.status_code == (status.HTTP_200_OK if allowed else status.HTTP_404_NOT_FOUND)+ assert thread.status_code == (status.HTTP_200_OK if allowed else status.HTTP_404_NOT_FOUND)+ assert count == (1 if allowed else 0)+ assert created.status_code == (status.HTTP_201_CREATED if allowed else status.HTTP_403_FORBIDDEN)+ assert reply.status_code == (status.HTTP_201_CREATED if allowed else status.HTTP_403_FORBIDDEN)++ @parameterized.expand([("denied", "none", False), ("viewer", "viewer", True)])+ @mock.patch("posthog.api.comments.send_mention_notifications")+ @mock.patch("posthog.api.comments.produce_discussion_mention_events")+ @mock.patch("posthog.tasks.email.send_discussions_mentioned.delay")+ def test_mentions_reach_only_members_who_can_view_the_observation(+ self,+ _name: str,+ access_level: str,+ notified: bool,+ send_email: mock.Mock,+ produce_events: mock.Mock,+ send_notifications: mock.Mock,+ ) -> None:+ self._set_member_scanner_access(access_level)++ response = self.client.post(+ f"/api/projects/{self.team.id}/comments",+ {+ "content": "PM, please look",+ "scope": SCOPE,+ "item_id": str(self.observation.id),+ "mentions": [self.member.id],+ },+ )++ assert response.status_code == status.HTTP_201_CREATED+ if notified:+ assert send_email.call_args.args[1] == [self.member.id]+ else:+ send_email.assert_not_called()+ send_notifications.assert_not_called()++ def test_note_content_is_masked_in_activity_log(self) -> None:+ Comment.objects.create(+ team=self.team,+ scope=SCOPE,+ item_id=str(self.observation.id),+ content="secret reply",+ created_by=self.user,+ source_comment=self.note,+ )++ entries = ActivityLog.objects.filter(team_id=self.team.id, activity="commented", scope__in=[SCOPE, "Comment"])++ assert sorted(entry.scope for entry in entries) == ["Comment", SCOPE]+ for entry in entries:+ assert entry.detail is not None+ assert entry.detail["changes"][0]["after"] == "masked"++ @mock.patch("posthog.tasks.email.send_discussions_mentioned.delay")+ @mock.patch("posthog.models.comment.utils.produce_internal_event")+ @mock.patch("products.notifications.backend.facade.api.create_notification")+ def test_mention_fanout_carries_no_note_text(+ self, create_notification: mock.Mock, produce_event: mock.Mock, send_email: mock.Mock+ ) -> None:+ # Notifications and CDP mention events are read later without an observation access check.+ self._set_member_scanner_access("viewer")++ response = self.client.post(+ f"/api/projects/{self.team.id}/comments",+ {+ "content": "checkout secret",+ "scope": SCOPE,+ "item_id": str(self.observation.id),+ "mentions": [self.member.id],+ },+ )++ assert response.status_code == status.HTTP_201_CREATED+ notification = create_notification.call_args.args[0]+ event = produce_event.call_args.kwargs["event"]+ assert notification.body == OBSERVATION_NOTE_PLACEHOLDER[:200]+ assert event.properties["comment_content"] == OBSERVATION_NOTE_PLACEHOLDER+ assert "checkout secret" not in f"{notification} {event.properties}"++ def _observation(self, scanner: ReplayScanner, session_id: str, **fields: object) -> ReplayObservation:+ values: dict[str, object] = {+ "status": ObservationStatus.SUCCEEDED,+ "completed_at": timezone.now(),+ **fields,+ }+ return ReplayObservation.objects.create(+ scanner=scanner,+ team=self.team,+ session_id=session_id,+ scanner_snapshot=snapshot_for(scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ **values,+ )++ @parameterized.expand(+ [+ ("note_to_other_observation", "note", {"item_id": "other"}, "item_id"),+ ("other_comment_into_observation", "notebook_comment", {"scope": SCOPE, "item_id": "target"}, "item_id"),+ ("reply_to_other_thread", "reply", {"source_comment": "other_root"}, "source_comment"),+ ]+ )+ def test_comment_cannot_move_across_an_observation_boundary(+ self, _name: str, moved: str, change: dict[str, str], error_attr: str+ ) -> None:+ # /thread authorizes only the root, so a moved comment would carry note text across the access check.+ other = self._observation(self.scanner, "s-other")+ other_root = Comment.objects.create(+ team=self.team, scope=SCOPE, item_id=str(other.id), content="other thread", created_by=self.user+ )+ comment = {+ "note": self.note,+ "notebook_comment": Comment.objects.create(+ team=self.team, scope="Notebook", item_id="n1", content="root", created_by=self.user+ ),+ "reply": Comment.objects.create(+ team=self.team,+ scope=SCOPE,+ item_id=str(self.observation.id),+ content="reply",+ created_by=self.user,+ source_comment=self.note,+ ),+ }[moved]+ before = (comment.scope, comment.item_id, comment.source_comment_id)+ values = {"other": str(other.id), "target": str(self.observation.id), "other_root": str(other_root.id)}++ response = self.client.patch(+ f"/api/projects/{self.team.id}/comments/{comment.id}",+ {"content": "moved", **{key: values.get(value, value) for key, value in change.items()}},+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == error_attr+ comment.refresh_from_db()+ assert (comment.scope, comment.item_id, comment.source_comment_id) == before++ @parameterized.expand(+ [+ ("failed", {"status": ObservationStatus.FAILED, "error_reason": "provider_transient:Timed out."}),+ ("running", {"status": ObservationStatus.RUNNING, "completed_at": None}),+ ]+ )+ def test_notes_need_a_finished_scan(self, _name: str, fields: dict[str, object]) -> None:+ # A retry deletes an unfinished row and gives the new scan a new id, which would strand its notes.+ unfinished = self._observation(self.scanner, "s-unfinished", **fields)++ response = self.client.post(+ f"/api/projects/{self.team.id}/comments",+ {"content": "too early", "scope": SCOPE, "item_id": str(unfinished.id)},+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "item_id"+ assert not Comment.objects.filter(item_id=str(unfinished.id)).exists()++ @mock.patch("posthog.api.comments.CommentViewSet._slack_mirror_flag_enabled", return_value=True)+ def test_note_cannot_be_sent_to_slack(self, _flag: mock.Mock) -> None:+ # A Slack channel has no observation access check, in either direction.+ response = self.client.post(+ f"/api/projects/{self.team.id}/comments/{self.note.id}/send_to_slack/",+ {"integration_id": 1, "channel_id": "C1"},+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["detail"] == "Replay Vision observation notes cannot be sent to Slack"+ assert not CommentSlackThread.objects.for_team(self.team.id).filter(source_comment_id=self.note.id).exists()++ def test_scanner_delete_removes_the_notes_on_its_observations(self) -> None:+ reply = Comment.objects.create(+ team=self.team,+ scope=SCOPE,+ item_id=str(self.observation.id),+ content="reply",+ created_by=self.user,+ source_comment=self.note,+ )+ other_scanner = ReplayScanner.objects.create(+ team=self.team,+ name="Signup monitor",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "did the user sign up?"},+ model=ScannerModel.GEMINI_3_8_FLASH,+ )+ kept = Comment.objects.create(+ team=self.team,+ scope=SCOPE,+ item_id=str(self._observation(other_scanner, "s-kept").id),+ content="kept",+ created_by=self.user,+ )++ # Any spelling of the UUID resolves the observation, so the write stores one spelling for the cleanup to match.+ uppercase = self.client.post(+ f"/api/projects/{self.team.id}/comments",+ {"content": "uppercase id", "scope": SCOPE, "item_id": str(self.observation.id).upper()},+ )++ self.scanner.delete()++ assert uppercase.status_code == status.HTTP_201_CREATED+ assert not Comment.objects.filter(id__in=[self.note.id, reply.id, uppercase.json()["id"]]).exists()+ assert Comment.objects.filter(id=kept.id).exists()++ @mock.patch("posthog.tasks.email.is_email_available", return_value=True)+ @mock.patch("posthog.tasks.email.EmailMessage")+ def test_mention_email_sent_after_access_is_revoked_carries_no_note_text(+ self, email_message: mock.Mock, _email_available: mock.Mock+ ) -> None:+ self._set_member_scanner_access("viewer")+ note = Comment.objects.create(+ team=self.team,+ scope=SCOPE,+ item_id=str(self.observation.id),+ content="checkout secret",+ created_by=self.user,+ )+ # The email task runs after the mention was authorized, so access can be gone by then.+ AccessControl.objects.filter(resource="replay_scanner", resource_id=str(self.scanner.id)).update(+ access_level="none"+ )++ send_discussions_mentioned(str(note.id), [self.member.id], "")++ context = email_message.call_args.kwargs["template_context"]+ assert context["content"] == OBSERVATION_NOTE_PLACEHOLDER+ assert "checkout secret" not in str(email_message.call_args)diff --git a/products/replay_vision/frontend/observations/ObservationNotesButton.tsx b/products/replay_vision/frontend/observations/ObservationNotesButton.tsxnew file mode 100644index 000000000000..3f1cea0f083e--- /dev/null+++ b/products/replay_vision/frontend/observations/ObservationNotesButton.tsx@@ -0,0 +1,32 @@+import { useActions, useValues } from 'kea'++import { IconChat } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { sidePanelDiscussionLogic } from '~/layout/navigation-3000/sidepanel/panels/discussion/sidePanelDiscussionLogic'++import { notesButtonLabel, replayObservationSceneLogic } from './replayObservationSceneLogic'++export const NOTES_BUTTON_TOOLTIP =+ 'Internal notes for your team. @-mention a teammate to notify them, or add a note as a task.'++/** Opens the observation's notes in the discussion side panel, so the page itself stays free of them. */+export function ObservationNotesButton(): JSX.Element {+ const { notesPanelOpen, notesDisabledReason } = useValues(replayObservationSceneLogic)+ const { commentCount } = useValues(sidePanelDiscussionLogic)+ const { toggleNotesPanel } = useActions(replayObservationSceneLogic)+ return (+ <LemonButton+ icon={<IconChat />}+ type="secondary"+ size="small"+ active={notesPanelOpen}+ onClick={toggleNotesPanel}+ disabledReason={notesDisabledReason}+ tooltip={NOTES_BUTTON_TOOLTIP}+ data-attr="vision-observation-notes"+ >+ {notesButtonLabel(notesDisabledReason, commentCount)}+ </LemonButton>+ )+}diff --git a/products/replay_vision/frontend/observations/QuillObservationNotesButton.tsx b/products/replay_vision/frontend/observations/QuillObservationNotesButton.tsxnew file mode 100644index 000000000000..0eaba7730303--- /dev/null+++ b/products/replay_vision/frontend/observations/QuillObservationNotesButton.tsx@@ -0,0 +1,28 @@+import { useActions, useValues } from 'kea'++import { IconChat } from '@posthog/icons'+import { Button } from '@posthog/quill'++import { sidePanelDiscussionLogic } from '~/layout/navigation-3000/sidepanel/panels/discussion/sidePanelDiscussionLogic'++import { NOTES_BUTTON_TOOLTIP } from './ObservationNotesButton'+import { notesButtonLabel, replayObservationSceneLogic } from './replayObservationSceneLogic'++export function QuillObservationNotesButton(): JSX.Element {+ const { notesPanelOpen, notesDisabledReason } = useValues(replayObservationSceneLogic)+ const { commentCount } = useValues(sidePanelDiscussionLogic)+ const { toggleNotesPanel } = useActions(replayObservationSceneLogic)+ return (+ <Button+ variant="outline"+ aria-pressed={notesPanelOpen}+ onClick={toggleNotesPanel}+ disabledReason={notesDisabledReason ?? undefined}+ tooltip={NOTES_BUTTON_TOOLTIP}+ data-attr="vision-observation-notes"+ >+ <IconChat />+ {notesButtonLabel(notesDisabledReason, commentCount)}+ </Button>+ )+}diff --git a/products/replay_vision/frontend/observations/QuillReplayObservationActions.tsx b/products/replay_vision/frontend/observations/QuillReplayObservationActions.tsxindex 6f80aff7fb1b..9530eaef38fe 100644--- a/products/replay_vision/frontend/observations/QuillReplayObservationActions.tsx+++ b/products/replay_vision/frontend/observations/QuillReplayObservationActions.tsx@@ -5,6 +5,7 @@ import { KeyboardShortcut } from 'lib/components/KeyboardShortcut/KeyboardShortcimport { LinkPrimitive } from 'lib/lemon-ui/Link'import { ReplayVisionFeedbackButton } from '../components/ReplayVisionFeedbackButton'+import { QuillObservationNotesButton } from './QuillObservationNotesButton'import { QuillObservationShareButton } from './QuillObservationShareButton'export function QuillReplayObservationActions({@@ -74,6 +75,7 @@ export function QuillReplayObservationActions({Next<IconArrowRight /></Button>+ <QuillObservationNotesButton /><QuillObservationShareButtonobservationId={observationId}sessionRecordingId={sessionRecordingId}diff --git a/products/replay_vision/frontend/observations/ReplayObservation.test.tsx b/products/replay_vision/frontend/observations/ReplayObservation.test.tsxindex 8724ddb0ff1d..1bcb85593ebd 100644--- a/products/replay_vision/frontend/observations/ReplayObservation.test.tsx+++ b/products/replay_vision/frontend/observations/ReplayObservation.test.tsx@@ -3,8 +3,10 @@ import '@testing-library/jest-dom'import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { router } from 'kea-router'+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { SidePanelTab } from '~/types'import { ReplayObservationSceneComponent } from './ReplayObservation'import { replayObservationSceneLogic } from './replayObservationSceneLogic'@@ -42,6 +44,8 @@ jest.mock('../components/CitedMarkdown', () => {}})+const notesButton = (): HTMLElement => document.querySelector('[data-attr="vision-observation-notes"]') as HTMLElement+describe('ReplayObservation', () => {beforeEach(() => {useMocks({@@ -77,6 +81,7 @@ describe('ReplayObservation', () => {completed_at: '2026-07-01T00:01:00Z',...observationOverrides,}),+ '/api/projects/:team/comments/': { results: [] },},post: {'/api/projects/:team/vision/observations/:id/viewed/': () => [204],@@ -143,27 +148,44 @@ describe('ReplayObservation', () => {})it.each([- ['an unrated succeeded scan', {}, true, true],- ['an already rated scan', { label: { is_correct: true, feedback: '' } }, false, true],+ ['an unrated succeeded scan', {}, true, true, true],+ ['an already rated scan', { label: { is_correct: true, feedback: '' } }, false, true, true],['a failed scan',{ status: 'failed', error_reason: 'provider_transient:Timed out.', scanner_result: null },false,false,+ // A retry replaces a failed scan with a new id, which would strand its notes.+ false,],])(- 'for %s, shows the rating question and the event link only when they apply',- async (_name, overrides, asksForRating, linksEvent) => {+ 'for %s, shows the rating question, the event link and the notes button only when they apply',+ async (_name, overrides, asksForRating, linksEvent, notesEnabled) => {observationOverrides = overridesrender(<ReplayObservationSceneComponent />)await screen.findByTestId('observation-recording')expect(screen.queryByText('Did the scanner get this right?') !== null).toBe(asksForRating)+ expect(notesButton()).toHaveAttribute('aria-disabled', String(!notesEnabled))+ expect(replayObservationSceneLogic.values.sidePanelContext.discussions_disabled).toBe(!notesEnabled)fireEvent.click(screen.getByText('Details'))expect(screen.queryByText('$recording_observed') !== null).toBe(linksEvent)})+ it('keeps notes off the page and toggles them in the discussion panel', async () => {+ render(<ReplayObservationSceneComponent />)+ await screen.findByTestId('observation-recording')+ expect(screen.queryByText('Comment on this Observation')).toBeNull()++ fireEvent.click(notesButton())+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(true)+ expect(sidePanelStateLogic.values.selectedTab).toBe(SidePanelTab.Discussion)++ fireEvent.click(notesButton())+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(false)+ })+it.each([['an unrated scan saves the rating', {}, [{ is_correct: true, feedback: '' }]],['an already rated scan ignores the key', { label: { is_correct: false, feedback: '' } }, []],diff --git a/products/replay_vision/frontend/observations/ReplayObservation.tsx b/products/replay_vision/frontend/observations/ReplayObservation.tsxindex 03e0dde497b1..dc6d0c8b0317 100644--- a/products/replay_vision/frontend/observations/ReplayObservation.tsx+++ b/products/replay_vision/frontend/observations/ReplayObservation.tsx@@ -31,6 +31,7 @@ import { ObservationDetails } from './ObservationDetails'import { ObservationFacts } from './ObservationFacts'import { ObservationHeadline } from './ObservationHeadline'import { ObservationLabelControl } from './ObservationLabelControl'+import { ObservationNotesButton } from './ObservationNotesButton'import { ObservationPinnedProperties } from './ObservationPinnedProperties'import { ObservationReasoning } from './ObservationReasoning'import { ObservationRecordingUnavailable } from './ObservationRecordingUnavailable'@@ -220,6 +221,7 @@ export function ReplayObservationSceneComponent(): JSX.Element {>Next</LemonButton>+ <ObservationNotesButton /><ObservationShareButtonobservationId={observation.id}sessionRecordingId={observation.session_id}diff --git a/products/replay_vision/frontend/observations/replayObservationLogic.test.ts b/products/replay_vision/frontend/observations/replayObservationLogic.test.tsindex fefa20674235..063d0e953ae0 100644--- a/products/replay_vision/frontend/observations/replayObservationLogic.test.ts+++ b/products/replay_vision/frontend/observations/replayObservationLogic.test.ts@@ -382,6 +382,18 @@ describe('replayObservationLogic', () => {}})+ it('leaves the scene alone when a response arrives for an observation the user has left', async () => {+ router.actions.push(urls.replayVisionObservation('obs-2'))+ const logic = replayObservationLogic({ id: 'obs-1' })+ logic.mount()+ try {+ await expectLogic(logic).toDispatchActions(['loadObservationSuccess'])+ expect(sceneLogic.values.observationStatus).toBeNull()+ } finally {+ logic.unmount()+ }+ })+it('does not seed from a page once the scene has been left', async () => {lastObservationsPage.current = page(['a', 'obs-1', 'c'])sceneLogic.unmount()diff --git a/products/replay_vision/frontend/observations/replayObservationLogic.ts b/products/replay_vision/frontend/observations/replayObservationLogic.tsindex 4e349eefd2e2..7347c80be1c2 100644--- a/products/replay_vision/frontend/observations/replayObservationLogic.ts+++ b/products/replay_vision/frontend/observations/replayObservationLogic.ts@@ -349,10 +349,15 @@ export const replayObservationLogic = kea<replayObservationLogicType>([const inFlight = values.observation?.status === 'pending' || values.observation?.status === 'running'scheduleObservationPoll(cache.disposables, inFlight, actions.loadObservation)}- const setParentBreadcrumb = (observation: ReplayObservationApi): void => {- replayObservationSceneLogic().actions.setParentBreadcrumb(- parentBreadcrumbFor(observation, router.values.searchParams)- )+ const syncScene = (observation: ReplayObservationApi): void => {+ const sceneLogic = replayObservationSceneLogic()+ // A late response for an observation the user has left must not change the one on screen.+ if (sceneLogic.values.observationId && sceneLogic.values.observationId !== props.id) {+ return+ }+ const sceneActions = sceneLogic.actions+ sceneActions.setParentBreadcrumb(parentBreadcrumbFor(observation, router.values.searchParams))+ sceneActions.setObservationStatus(observation.status)}return {loadObservation: async () => {@@ -369,7 +374,7 @@ export const replayObservationLogic = kea<replayObservationLogicType>([values.pageNeighbors ? undefined : values.neighborParams)actions.loadObservationSuccess(response)- setParentBreadcrumb(response)+ syncScene(response)} catch (error: any) {// Only toast the initial load — background poll retries would otherwise spam one toast per tick.if (!values.loadedObservation) {@@ -388,7 +393,7 @@ export const replayObservationLogic = kea<replayObservationLogicType>([},loadObservationFailure: reschedulePoll,- seedObservation: ({ observation }) => setParentBreadcrumb(observation),+ seedObservation: ({ observation }) => syncScene(observation),markViewed: async () => {const teamId = teamLogic.values.currentTeamIddiff --git a/products/replay_vision/frontend/observations/replayObservationSceneLogic.ts b/products/replay_vision/frontend/observations/replayObservationSceneLogic.tsindex 0de31f5e9607..13992d5f94b5 100644--- a/products/replay_vision/frontend/observations/replayObservationSceneLogic.ts+++ b/products/replay_vision/frontend/observations/replayObservationSceneLogic.ts@@ -1,11 +1,17 @@-import { MakeLogicType, actions, beforeUnmount, kea, path, reducers, selectors } from 'kea'+import { MakeLogicType, actions, beforeUnmount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { urlToAction } from 'kea-router'import { urls } from 'scenes/urls'-import { Breadcrumb } from '~/types'+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'+import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'+import { ActivityScope, Breadcrumb, SidePanelTab } from '~/types'-import type { ReplayObservationApi, VisionObservationsRetrieveParams } from '../generated/api.schemas'+import type {+ ReplayObservationApi,+ ObservationStatusEnumApi,+ VisionObservationsRetrieveParams,+} from '../generated/api.schemas'import { VISION_ROOT_BREADCRUMB } from '../utils/breadcrumbs'export type ObservationResultTab = 'summary' | 'timeline'@@ -18,34 +24,79 @@ export interface ObservationsPage {filterParams: VisionObservationsRetrieveParams}+/** Why notes are off for an observation, or null when they are on. */+export function observationNotesDisabledReason(status: ObservationStatusEnumApi | null): string | null {+ if (status === 'succeeded') {+ return null+ }+ if (status === null) {+ return 'Loading the observation...'+ }+ // A retry deletes an unfinished scan and gives the new scan a new id, which would strand its notes.+ return status === 'pending' || status === 'running'+ ? 'You can add notes when the scan finishes.'+ : 'You can add notes after the scan succeeds. A retry replaces this scan, so notes on it would be lost.'+}++/** The notes button label. The count comes from the side panel's discussion logic, which reads the global+ * scene, so the buttons read it rather than this scene logic connecting to it. */+export function notesButtonLabel(disabledReason: string | null, noteCount: number): string {+ return !disabledReason && noteCount > 0 ? `Notes (${noteCount})` : 'Notes'+}+/** The page the scanner table last loaded, so a row opened from it paints before its own read lands. */export const lastObservationsPage: { current: ObservationsPage | null } = { current: null }// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface replayObservationSceneLogicValues {+ selectedTab: SidePanelTab | null // sidePanelStateLogic+ sidePanelOpen: boolean // sidePanelStateLogicbreadcrumbs: Breadcrumb[]+ notesDisabledReason: string | null+ notesPanelOpen: booleanobservationId: string+ observationStatus: ObservationStatusEnumApi | nullparentBreadcrumb: Breadcrumb | nullresultTab: ObservationResultTab+ sidePanelContext: SidePanelSceneContext}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface replayObservationSceneLogicActions {+ closeSidePanel: (tab?: SidePanelTab | undefined) => {+ tab: SidePanelTab | undefined+ } // sidePanelStateLogic+ openSidePanel: (+ tab: SidePanelTab,+ options?: string | undefined+ ) => {+ options: string | undefined+ tab: SidePanelTab+ } // sidePanelStateLogicsetObservationId: (observationId: string) => {observationId: string}+ setObservationStatus: (observationStatus: ObservationStatusEnumApi) => {+ observationStatus: ObservationStatusEnumApi+ }setParentBreadcrumb: (parentBreadcrumb: Breadcrumb | null) => {parentBreadcrumb: Breadcrumb | null}setResultTab: (resultTab: ObservationResultTab) => {resultTab: ObservationResultTab}+ toggleNotesPanel: () => {+ value: true+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface replayObservationSceneLogicMeta {__keaTypeGenInternalSelectorTypes: {breadcrumbs: (observationId: string, parentBreadcrumb: Breadcrumb | null) => Breadcrumb[]+ notesDisabledReason: (observationStatus: ObservationStatusEnumApi | null) => string | null+ notesPanelOpen: (sidePanelOpen: boolean, selectedTab: SidePanelTab | null) => boolean+ sidePanelContext: (observationId: string, notesDisabledReason: string | null) => SidePanelSceneContext}}@@ -59,12 +110,20 @@ export type replayObservationSceneLogicType = MakeLogicType<export const replayObservationSceneLogic = kea<replayObservationSceneLogicType>([path(['products', 'replay_vision', 'frontend', 'observations', 'replayObservationSceneLogic']),+ connect(() => ({+ values: [sidePanelStateLogic, ['sidePanelOpen', 'selectedTab']],+ actions: [sidePanelStateLogic, ['openSidePanel', 'closeSidePanel']],+ })),+actions({setObservationId: (observationId: string) => ({ observationId }),// Pushed by replayObservationLogic once the observation loads. The scene's back button returns// to this crumb, so where it points decides where "back" lands.setParentBreadcrumb: (parentBreadcrumb: Breadcrumb | null) => ({ parentBreadcrumb }),setResultTab: (resultTab: ObservationResultTab) => ({ resultTab }),+ // Pushed by replayObservationLogic too, so the discussion panel knows whether notes are allowed.+ setObservationStatus: (observationStatus: ObservationStatusEnumApi) => ({ observationStatus }),+ toggleNotesPanel: true,}),reducers({@@ -82,6 +141,13 @@ export const replayObservationSceneLogic = kea<replayObservationSceneLogicType>(setObservationId: () => null,},],+ observationStatus: [+ null as ObservationStatusEnumApi | null,+ {+ setObservationStatus: (_, { observationStatus }) => observationStatus ?? null,+ setObservationId: () => null,+ },+ ],// Kept across previous and next, so a reviewer can page through timelines.resultTab: ['summary' as ObservationResultTab,@@ -104,8 +170,37 @@ export const replayObservationSceneLogic = kea<replayObservationSceneLogicType>(},],],+ notesDisabledReason: [+ (s) => [s.observationStatus],+ (observationStatus: ObservationStatusEnumApi | null): string | null =>+ observationNotesDisabledReason(observationStatus),+ ],+ notesPanelOpen: [+ (s) => [s.sidePanelOpen, s.selectedTab],+ (sidePanelOpen: boolean, selectedTab: SidePanelTab | null): boolean =>+ sidePanelOpen && selectedTab === SidePanelTab.Discussion,+ ],+ [SIDE_PANEL_CONTEXT_KEY]: [+ (s) => [s.observationId, s.notesDisabledReason],+ (observationId: string, disabledReason: string | null): SidePanelSceneContext => ({+ activity_scope: ActivityScope.REPLAY_OBSERVATION,+ activity_item_id: observationId,+ discussions_disabled: disabledReason !== null,+ discussions_disabled_reason: disabledReason ?? undefined,+ }),+ ],}),+ listeners(({ actions, values }) => ({+ toggleNotesPanel: () => {+ if (values.notesPanelOpen) {+ actions.closeSidePanel()+ } else {+ actions.openSidePanel(SidePanelTab.Discussion)+ }+ },+ })),+urlToAction(({ actions, values }) => ({[urls.replayVisionObservation(':observationId')]: ({ observationId }) => {const next = observationId || ''diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 08b914a1bccd..11f04fbd54a7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -73611,6 +73611,7 @@ export namespace Schemas {* * `error_tracking` - ERROR_TRACKING* * `customer_analytics` - CUSTOMER_ANALYTICS* * `ticket` - TICKET+ * * `replay_observation` - REPLAY_OBSERVATION*/export type NotificationEventSourceTypeEnum = typeof NotificationEventSourceTypeEnum[keyof typeof NotificationEventSourceTypeEnum];@@ -73626,6 +73627,7 @@ export namespace Schemas {ErrorTracking: 'error_tracking',CustomerAnalytics: 'customer_analytics',Ticket: 'ticket',+ ReplayObservation: 'replay_observation',} as const;export interface NotificationEvent {@@ -128126,6 +128128,7 @@ export namespace Schemas {* * `EarlyAccessFeature` - EarlyAccessFeature* * `SessionRecordingPlaylist` - SessionRecordingPlaylist* * `ReplayScanner` - ReplayScanner+ * * `ReplayObservation` - ReplayObservation* * `VisionAlertConfiguration` - VisionAlertConfiguration* * `Comment` - Comment* * `Team` - Team@@ -128243,6 +128246,7 @@ export namespace Schemas {EarlyAccessFeature: 'EarlyAccessFeature',SessionRecordingPlaylist: 'SessionRecordingPlaylist',ReplayScanner: 'ReplayScanner',+ ReplayObservation: 'ReplayObservation',VisionAlertConfiguration: 'VisionAlertConfiguration',Comment: 'Comment',Team: 'Team',@@ -128346,6 +128350,7 @@ export namespace Schemas {* * `EarlyAccessFeature` - EarlyAccessFeature* * `SessionRecordingPlaylist` - SessionRecordingPlaylist* * `ReplayScanner` - ReplayScanner+ * * `ReplayObservation` - ReplayObservation* * `VisionAlertConfiguration` - VisionAlertConfiguration* * `Comment` - Comment* * `Team` - Team@@ -128451,6 +128456,7 @@ export namespace Schemas {EarlyAccessFeature: 'EarlyAccessFeature',SessionRecordingPlaylist: 'SessionRecordingPlaylist',ReplayScanner: 'ReplayScanner',+ ReplayObservation: 'ReplayObservation',VisionAlertConfiguration: 'VisionAlertConfiguration',Comment: 'Comment',Team: 'Team',