: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): rework the observation page (#105826)
Tue Haulundaf795fb1cc17
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 04461e144c17..e2de724fa424 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10965,21 +10965,41 @@ snapshots:scenes-app-replay-vision--monitor-overview-with-scout-report--light:hash: v1.k794b7964.30d42b704c4a00911529c2a6cb542f8ee8649c8dd25e0a98f93d45338fcba97e._KqWLoMbKiDjbPWHIePRk4RycV1OpAwZOOrqOgNjJtUscenes-app-replay-vision--observation-detail--dark:- hash: v1.k794b7964.e9fd7c14ee1899c90ba01049012a8d9947f013869b8ec7d767b7db2220d46166.XZIczm04vBGXxRP7z-rzHaqy34GQDRXXfTrEhICqxi0+ hash: v1.k794b7964.04db72e9050fb9875aa66e42c6f32f0b59c50af729ce0d7b076b415fd67ed1bb.tfxIwfaYwBA3a7qw8WJ6sbcLzcPNJJ3mmUPaNPwwn8wscenes-app-replay-vision--observation-detail--light:- hash: v1.k794b7964.7e192691951be3702d927d1d9d192f06ea3e9cd1a241cb36d3c29c5ce09fc21b.am09e5v4YWSCyyjBOBTw5cCclechXFAeWEuXy3E6m0w+ hash: v1.k794b7964.ad74feb9578d0fb6936e071f5d43bc079b1e931176b542c746028eb552be24f8.XMJxjkby0O07z3XsGoeeimRo4qntWrfxG3z8EkL-Masscenes-app-replay-vision--observation-detail-calibration-entry-point--dark:- hash: v1.k794b7964.9d8ee815926f025fd68e694c3bc316d8f1b485f2d54bb36153c4e5cdcb9d3ae3.IXdjhtQjEyeeEZsSSy_BcLQvLYIA18srQOSptAU-QX4+ hash: v1.k794b7964.4992e8bd845a33f061bd216fd5c8d8e2ea450def212d5201e711510a7ae02313.-0hh2eZ0qhZ4ryAjXvIWwLDfupHm9l4b4eoCSZPW4bsscenes-app-replay-vision--observation-detail-calibration-entry-point--light:- hash: v1.k794b7964.cc28834863341019f828f1080b3abe045d508fcf2609f482d91e346157f7b2b2.rw_A7OzvU27gTV4WIxLiJXQHcJMSAfDUeYSQughz8Zc+ hash: v1.k794b7964.15682411ba1fc615ef13b9dea0e875b07c18c0c6e047bc7d2c417cb60379f612.QwAgDKhFahjqNKWyBYEHo6b8vRhWKMlunHNo9WNzyBU+ scenes-app-replay-vision--observation-detail-classifier--dark:+ hash: v1.k794b7964.b763e4c5c864cf111b75ec676d775da060c2409f59c25073056bba3963a338e1.RQ9jjNXkGoVpyoIRhmUZXUjy4YDYxqahc99u_MhrE_0+ scenes-app-replay-vision--observation-detail-classifier--light:+ hash: v1.k794b7964.80cbcf4a82c7cc4dffe3e1d5264fb042217acd2666bf57255c355eb8e0dbc898.e_bvnXk6-aSmt8c2R3g5_Fmwd1H0rJtm0N4kdF6DccQ+ scenes-app-replay-vision--observation-detail-failed--dark:+ hash: v1.k794b7964.674a315d11ad1da81c9f88bc4760d5f9281dcd948361d0bb9ea586a344b958a7.enqKzZx_T1ds18rcc7-VrhP0s4RiPztjkSflXZ_UaX8+ scenes-app-replay-vision--observation-detail-failed--light:+ hash: v1.k794b7964.ccc7af0445d681f79605443fc8dea1acffe9bb0500502893482854661fb96653.e1KOq9MUANpXNPInK0LDYZtJZFcDwL7yl2Ikv66i0Sgscenes-app-replay-vision--observation-detail-feedback-prompt--dark:- hash: v1.k794b7964.25f4f6b0b5f27fdcf98ec072b92d97ca9c7eccf55af31d002031197082d27673.aIbt54OC817JeBomMqEOMUqk-HFM2x-UDuWAC4h4Zas+ hash: v1.k794b7964.869fe3b3ff77933ac238492cde9fea4d004804d0a524c6135740eba2b0c0afe1.tTDwGaXkL9Pwi3j6r8BSsCEchnoJJV8fPXEO6iS0ZF8scenes-app-replay-vision--observation-detail-feedback-prompt--light:- hash: v1.k794b7964.59677d24da0b5cb9cd755a5f5af898c7a9999560caa6c7a9f653c0cdb1cd9198.VziTZTShcVxzXQMyJRuUCTDfplGGmCGd7yESU8U1m4Q+ hash: v1.k794b7964.19ece417492d20a151465d3bc1badfeee6f9d098e079bef197fc70fd9c059c2c.eGcBloxLOg_g4Liue4ObXKUAkhUHhCILqmp4t_xwQ3kscenes-app-replay-vision--observation-detail-monitor--dark:- hash: v1.k794b7964.7591a846c3cdc88eabed6184b663488cc452441ff40eac493caaed3df17dfd1d.5XU5zVS7zu6YYlbsnmIf8nzWUHPsTYVSOT1MWox-MII+ hash: v1.k794b7964.dc11425f8652d5b52e491ad511feb693e04ca5438cbe68436ba14884d8de507c.I-RCkKlDMTyeV8Yl-qqIGNseA4CfECA1kAAr5fnvX-0scenes-app-replay-vision--observation-detail-monitor--light:- hash: v1.k794b7964.768885316fe8f5e6d6e766920805adb17331c67f5452cb81878273e718d46128.613JBEPeFxtEAhgh9tMgylbHMAk-bHGqX6WL2hhlLEI+ hash: v1.k794b7964.023852ef6a73d8a7fafc4f9108bbf41b8730abd65c4c4cdf09db928cb59818c7.PLqFkNgl7o5JKok-pjLH7Wfr5pvxKgRNNxspfbotXMc+ scenes-app-replay-vision--observation-detail-not-scanned--dark:+ hash: v1.k794b7964.fffda7c1219e5530699ef8b5859f5280b6dc0f9c502a7f63f44cd4082b08be3e.k932o_Jmsn098x-maHtUP5TpTRK-vg7Kv6rsRp4K1pM+ scenes-app-replay-vision--observation-detail-not-scanned--light:+ hash: v1.k794b7964.258e10680117289b4bec61f31f1d46ce79339d47882586361ed243ad124bf727.gSrBKUmyY8rMPUpDe9F0Bj9TWleSm2kXHNc6N8R5Olo+ scenes-app-replay-vision--observation-detail-recording-expired--dark:+ hash: v1.k794b7964.2ed137bc50a435f2ffbf0fce38643b9fb49d74effae9aadf43b9e69f522eaab1.jlwgLE7JNuNnPIyA7SWIObYVx4JtSO5_PtaHgmFqfw0+ scenes-app-replay-vision--observation-detail-recording-expired--light:+ hash: v1.k794b7964.0d59378195ef018724a4da49321e6d1656717a2d8d2faafd2deda204bda13f74.yVlCbpuvP61-ltAoMaTFUMQStPBOKKg1dKwlI_lZSkk+ scenes-app-replay-vision--observation-detail-scorer--dark:+ hash: v1.k794b7964.c39e019919cd5441902e5e08ee1e8867abc3fbe60df6317d5e7d0e4c05cef773.VI5L52NXIbERiBPLfkcoHWqx13sZyf9J9FWS4vQdsYo+ scenes-app-replay-vision--observation-detail-scorer--light:+ hash: v1.k794b7964.32a888fe071d00cb4cf426b4c67f5e95f2b92fc7a0a854fc8158f8498f790201.92UnZsrMZTVVBRFjKuE4gXNVWDDh5F6GfQ-suGwZas0scenes-app-replay-vision--scanner-alerts--dark:hash: v1.k794b7964.07adaa26f0b868d6c64d7d99e3d1a317307dff376b1dc5d740c9c9cc9c2ff926.c9kS5X0nGVIU2VHq4sxwidzwpjG5bpqnlvPM-r8yEf8scenes-app-replay-vision--scanner-alerts--light:diff --git a/products/replay_vision/frontend/components/ObservationCard.tsx b/products/replay_vision/frontend/components/ObservationCard.tsxindex a428fdd57741..8c17b23ab2f1 100644--- a/products/replay_vision/frontend/components/ObservationCard.tsx+++ b/products/replay_vision/frontend/components/ObservationCard.tsx@@ -20,7 +20,7 @@ import {} from '../replay_scanners/types'import { markSimilarSearchIntent, similarSearchUrl } from '../search/observationQueries'import { citedTextToPlainText, parseCitedSegments } from '../utils/citations'-import { readReasoning, scannerLabel } from '../utils/observation'+import { VERDICT_LABEL, readReasoning, scannerLabel } from '../utils/observation'import { CitedMarkdown } from './CitedMarkdown'import { LabeledRow } from './LabeledRow'import { ObservationProgressBar } from './ObservationProgressBar'@@ -123,6 +123,7 @@ export function ObservationPrimaryOutput({expandSummary = false,copyable = false,reasoningTooltip = false,+ largeTitle = false,}: {observation: ReplayObservationApicompact?: boolean@@ -135,6 +136,8 @@ export function ObservationPrimaryOutput({copyable?: boolean/** Hovering the result shows its reasoning. For list rows, which have nowhere else to print it. */reasoningTooltip?: boolean+ /** Sets a summarizer's title at headline size, for the observation page. */+ largeTitle?: boolean}): JSX.Element | null {const snapshot = observation.scanner_snapshotconst result = readResult(observation)@@ -167,7 +170,7 @@ export function ObservationPrimaryOutput({? 'muted': 'muted'const tagLabel =- verdict === 'yes' ? 'Yes' : verdict === 'no' ? 'No' : verdict === 'inconclusive' ? 'Inconclusive' : '—'+ verdict === 'yes' || verdict === 'no' || verdict === 'inconclusive' ? VERDICT_LABEL[verdict] : '—'return (<div className="flex flex-col gap-1"><Tooltip title={resultTooltip}>@@ -188,7 +191,11 @@ export function ObservationPrimaryOutput({<div className="flex flex-col gap-1">{(title || showCopy) && (<div className="flex items-start justify-between gap-2">- {title && <span className={`font-semibold ${textClass}`}>{title}</span>}+ {title && (+ <span className={largeTitle ? 'text-xl font-bold' : `font-semibold ${textClass}`}>+ {title}+ </span>+ )}{showCopy && (<LemonButtonsize="xsmall"@@ -324,7 +331,7 @@ export function ObservationPrimaryOutput({// A reader opens an observation for the result, not the prompt they configured. Collapse the prompt to one// peek line so the verdict and reasoning stay above the fold, but keep it in view so the verdict has context.-export function PromptRow({ prompt }: { prompt: string }): JSX.Element {+function PromptRow({ prompt }: { prompt: string }): JSX.Element {const [expanded, setExpanded] = useState(false)return (<div>diff --git a/products/replay_vision/frontend/observations/FactList.tsx b/products/replay_vision/frontend/observations/FactList.tsxnew file mode 100644index 000000000000..64c59724d01c--- /dev/null+++ b/products/replay_vision/frontend/observations/FactList.tsx@@ -0,0 +1,15 @@+// A fixed label column keeps stacked lists on the page aligned with each other.+export function FactList({ children }: { children: React.ReactNode }): JSX.Element {+ return <dl className="grid grid-cols-[9rem_minmax(0,1fr)] gap-x-4 gap-y-1.5 text-sm m-0">{children}</dl>+}++export function Fact({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {+ return (+ <>+ <dt className="text-muted truncate" title={label}>+ {label}+ </dt>+ <dd className="m-0 min-w-0">{children}</dd>+ </>+ )+}diff --git a/products/replay_vision/frontend/observations/ObservationDetails.tsx b/products/replay_vision/frontend/observations/ObservationDetails.tsxnew file mode 100644index 000000000000..55fe70f43a50--- /dev/null+++ b/products/replay_vision/frontend/observations/ObservationDetails.tsx@@ -0,0 +1,85 @@+import { useValues } from 'kea'+import { useState } from 'react'++import { IconChevronRight } from '@posthog/icons'+import { Link } from '@posthog/lemon-ui'++import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'+import { TZLabel } from 'lib/components/TZLabel'+import { FEATURE_FLAGS } from 'lib/constants'+import { dayjs } from 'lib/dayjs'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { cn } from 'lib/utils/css-classes'+import { formatDurationMilliseconds } from 'lib/utils/durations'+import { urls } from 'scenes/urls'++import type { ReplayObservationApi } from '../generated/api.schemas'+import { modelLabel, modelNamingVariant } from '../replay_scanners/types'+import { Fact, FactList } from './FactList'++function durationLabel(observation: ReplayObservationApi): string | null {+ if (!observation.started_at || !observation.completed_at) {+ return null+ }+ const ms = dayjs(observation.completed_at).diff(observation.started_at)+ return Number.isFinite(ms) && ms >= 0 ? formatDurationMilliseconds(ms) : null+}++export function ObservationDetails({ observation }: { observation: ReplayObservationApi }): JSX.Element {+ const [expanded, setExpanded] = useState(false)+ const snapshot = observation.scanner_snapshot+ const { featureFlags } = useValues(featureFlagLogic)+ const namingVariant = modelNamingVariant(featureFlags[FEATURE_FLAGS.REPLAY_VISION_MODEL_TIER_NAMING_EXPERIMENT])+ const duration = durationLabel(observation)++ return (+ <div className="flex flex-col gap-2">+ <button+ type="button"+ className="flex items-center gap-1 text-sm font-medium self-start hover:text-default"+ onClick={() => setExpanded(!expanded)}+ aria-expanded={expanded}+ data-attr="vision-observation-technical-details-toggle"+ >+ <IconChevronRight className={cn('transition-transform', expanded && 'rotate-90')} />+ Details+ </button>+ {expanded && (+ <FactList>+ <Fact label="Observation ID">+ <CopyToClipboardInline explicitValue={observation.id} iconSize="xsmall" className="min-w-0">+ <span className="font-mono text-xs truncate">{observation.id}</span>+ </CopyToClipboardInline>+ </Fact>+ <Fact label="Session">+ <Link+ to={urls.sessionProfile(observation.session_id)}+ className="block font-mono text-xs truncate"+ data-attr="vision-observation-session-link"+ >+ {observation.session_id}+ </Link>+ </Fact>+ {/* The backend emits the event only once a scan succeeds. */}+ {observation.status === 'succeeded' && observation.completed_at && (+ <Fact label="Observation event">+ <Link to={urls.event(observation.id, observation.completed_at)}>$recording_observed</Link>+ </Fact>+ )}+ {observation.started_at && (+ <Fact label="Started">+ <TZLabel time={observation.started_at} />+ </Fact>+ )}+ {observation.completed_at && (+ <Fact label="Completed">+ <TZLabel time={observation.completed_at} />+ </Fact>+ )}+ {duration && <Fact label="Duration">{duration}</Fact>}+ {snapshot?.model && <Fact label="Model">{modelLabel(snapshot.model, namingVariant)}</Fact>}+ </FactList>+ )}+ </div>+ )+}diff --git a/products/replay_vision/frontend/observations/ObservationFacts.tsx b/products/replay_vision/frontend/observations/ObservationFacts.tsxnew file mode 100644index 000000000000..0908f36f56b3--- /dev/null+++ b/products/replay_vision/frontend/observations/ObservationFacts.tsx@@ -0,0 +1,71 @@+import { Link } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { urls } from 'scenes/urls'++import { ObservationConfidence, ObservationStatusTag, readResult } from '../components/ObservationCard'+import type { ReplayObservationApi } from '../generated/api.schemas'+import { OBSERVATION_TRIGGER_TAG } from '../replay_scanners/types'+import { hasScannerPage, scannerLabel } from '../utils/observation'+import { Fact, FactList } from './FactList'++export function ObservationFacts({ observation }: { observation: ReplayObservationApi }): JSX.Element {+ const result = readResult(observation)+ const person = observation.recording_subject_email ?? observation.distinct_id++ return (+ <FactList>+ <Fact label="Person">+ {observation.distinct_id ? (+ <Link to={urls.personByDistinctId(observation.distinct_id)} className="block truncate">+ {person}+ </Link>+ ) : observation.recording_subject_email ? (+ <span className="block truncate">{observation.recording_subject_email}</span>+ ) : (+ <span className="text-muted">Unknown person</span>+ )}+ </Fact>+ <Fact label="Scanned">+ <TZLabel time={observation.created_at} />+ </Fact>+ <Fact label="Status">+ <ObservationStatusTag status={observation.status} errorReason={observation.error_reason} />+ </Fact>+ <Fact label="Triggered by">+ {observation.triggered_by !== 'schedule' && observation.triggered_by_user ? (+ <ProfilePicture+ user={{+ first_name: observation.triggered_by_user.first_name,+ last_name: observation.triggered_by_user.last_name,+ email: observation.triggered_by_user.email,+ }}+ size="xs"+ showName+ />+ ) : (+ OBSERVATION_TRIGGER_TAG[observation.triggered_by].label+ )}+ </Fact>+ {result && typeof result.confidence === 'number' && (+ <Fact label="Confidence">+ <ObservationConfidence result={result} />+ </Fact>+ )}+ <Fact label="Scanner">+ {hasScannerPage(observation) ? (+ <Link+ to={urls.replayVision(observation.scanner_id)}+ className="block truncate"+ data-attr="vision-observation-scanner-link"+ >+ {scannerLabel(observation)}+ </Link>+ ) : (+ scannerLabel(observation)+ )}+ </Fact>+ </FactList>+ )+}diff --git a/products/replay_vision/frontend/observations/ObservationHeadline.tsx b/products/replay_vision/frontend/observations/ObservationHeadline.tsxnew file mode 100644index 000000000000..be3b7f619022--- /dev/null+++ b/products/replay_vision/frontend/observations/ObservationHeadline.tsx@@ -0,0 +1,145 @@+import { IconSparkles } from '@posthog/icons'+import { Tooltip } from '@posthog/lemon-ui'++import { LabeledRow } from '../components/LabeledRow'+import { ObservationPrimaryOutput } from '../components/ObservationCard'+import type { ReplayObservationApi, ScannerTypeEnumApi } from '../generated/api.schemas'+import { configFromSnapshot, type ScorerScannerConfig } from '../replay_scanners/types'+import {+ type MonitorVerdict,+ VERDICT_LABEL,+ readFixedTags,+ readFreeformTags,+ readModelOutput,+ readScore,+ readVerdict,+} from '../utils/observation'++const PILL = 'inline-flex items-center gap-1 rounded-md border-2 px-3 py-0.5 font-bold'++// Only the chosen categories show here, so the classifier's label names them as assigned.+const HEADLINE_LABEL: Record<ScannerTypeEnumApi, string> = {+ monitor: 'Verdict',+ scorer: 'Score',+ classifier: 'Assigned categories',+ summarizer: 'Summary',+}++const VERDICT_CLASS: Record<MonitorVerdict, string> = {+ yes: 'text-success border-success',+ no: 'text-danger border-danger',+ inconclusive: 'text-muted border-primary',+}++/** Red at the bottom of the scale, amber in the middle, green at the top. */+function scoreColor(score: number, min: number, max: number): string {+ const position = max > min ? Math.min(1, Math.max(0, (score - min) / (max - min))) : 1+ return position < 0.5+ ? `color-mix(in oklab, var(--warning) ${Math.round(position * 200)}%, var(--danger))`+ : `color-mix(in oklab, var(--success) ${Math.round((position - 0.5) * 200)}%, var(--warning))`+}++function HeadlineValue({+ observation,+ scannerType,+ onSeek,+}: {+ observation: ReplayObservationApi+ scannerType: ScannerTypeEnumApi+ onSeek: (timestampMs: number) => void+}): JSX.Element {+ if (scannerType === 'monitor') {+ const verdict = readVerdict(observation)+ return verdict ? (+ <span+ className={`self-start text-2xl ${PILL} ${VERDICT_CLASS[verdict]}`}+ data-attr="vision-observation-verdict"+ >+ {VERDICT_LABEL[verdict]}+ </span>+ ) : (+ <span className="text-2xl font-bold text-muted">—</span>+ )+ }++ if (scannerType === 'scorer') {+ const score = readScore(observation)+ const scale = (configFromSnapshot(observation.scanner_snapshot) as ScorerScannerConfig | null)?.scale+ const min = typeof scale?.min === 'number' ? scale.min : 0+ const max = typeof scale?.max === 'number' ? scale.max : null+ const resultLabel = readModelOutput(observation)?.label+ const label = typeof resultLabel === 'string' ? resultLabel : (scale?.label ?? null)+ return (+ <div className="flex flex-col gap-1">+ <span className="text-3xl font-bold tabular-nums">+ <span+ // The color is a position on a continuous scale, which Tailwind classes can't express.+ // eslint-disable-next-line react/forbid-dom-props+ style={score !== null && max !== null ? { color: scoreColor(score, min, max) } : undefined}+ >+ {score ?? '—'}+ </span>+ {max !== null && <span className="text-lg font-normal text-muted"> / {max}</span>}+ </span>+ {label && <span className="text-sm text-secondary">{label}</span>}+ </div>+ )+ }++ if (scannerType === 'classifier') {+ const tags = readFixedTags(observation)+ const freeform = readFreeformTags(observation)+ if (tags.length === 0 && freeform.length === 0) {+ return <span className="text-lg font-semibold text-muted">No categories</span>+ }+ return (+ <div className="flex flex-wrap gap-2">+ {tags.map((tag) => (+ <span key={`tag-${tag}`} className={`text-lg ${PILL} text-accent border-accent`}>+ {tag}+ </span>+ ))}+ {freeform.map((tag) => (+ <Tooltip+ key={`freeform-${tag}`}+ title="Freeform category: the model came up with this one because nothing in your list matched this part of the session."+ >+ <span className={`text-lg ${PILL} text-default border-primary cursor-help`}>+ <IconSparkles className="text-base" />+ {tag}+ </span>+ </Tooltip>+ ))}+ </div>+ )+ }++ return (+ <ObservationPrimaryOutput+ observation={observation}+ showPrompt={false}+ onSeek={onSeek}+ expandSummary+ copyable+ largeTitle+ />+ )+}++export function ObservationHeadline({+ observation,+ onSeek,+}: {+ observation: ReplayObservationApi+ onSeek: (timestampMs: number) => void+}): JSX.Element | null {+ const scannerType = observation.scanner_snapshot?.scanner_type+ if (!scannerType || !readModelOutput(observation)) {+ return null+ }+ return (+ <LabeledRow label={HEADLINE_LABEL[scannerType] ?? 'Result'}>+ <HeadlineValue observation={observation} scannerType={scannerType} onSeek={onSeek} />+ </LabeledRow>+ )+}diff --git a/products/replay_vision/frontend/observations/ObservationLabelControl.tsx b/products/replay_vision/frontend/observations/ObservationLabelControl.tsxindex 6a1fa6d431dc..9e5e586ceb6e 100644--- a/products/replay_vision/frontend/observations/ObservationLabelControl.tsx+++ b/products/replay_vision/frontend/observations/ObservationLabelControl.tsx@@ -2,9 +2,11 @@ import { useActions, useValues } from 'kea'import { useState } from 'react'import { IconThumbsDown, IconThumbsDownFilled, IconThumbsUp, IconThumbsUpFilled } from '@posthog/icons'-import { LemonButton, LemonTextArea, Tooltip } from '@posthog/lemon-ui'+import { LemonButton, LemonTextArea, Popover, Tooltip } from '@posthog/lemon-ui'+import { KeyboardShortcut } from 'lib/components/KeyboardShortcut/KeyboardShortcut'import { FEATURE_FLAGS } from 'lib/constants'+import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { AccessControlLevel } from '~/types'@@ -126,11 +128,20 @@ export function ObservationLabelFeedback({)}+// Rendered only beside the page's rating question, so table rows add no key listeners.+function RatingHotkeys({ onThumb, disabled }: { onThumb: (isCorrect: boolean) => void; disabled: boolean }): null {+ useKeyboardHotkeys({+ y: { action: () => onThumb(true), disabled },+ n: { action: () => onThumb(false), disabled },+ })+ return null+}+/*** Thumbs up/down rating on whether the scanner got this session right. The rating is shared across the* team (one per observation) and gathered later to improve the scanner prompt. `compact` renders just the* buttons for table cells (feedback lives in its own column via `ObservationLabelFeedback`); the default- * adds the bordered card, question, and inline feedback editor for the detail page.+ * adds the question, opens the optional feedback editor in a popover after a rating, and hides once rated.*/export function ObservationLabelControl({observationId,@@ -138,17 +149,30 @@ export function ObservationLabelControl({onChange,scannerUserAccessLevel,compact = false,-}: ObservationLabelProps & { compact?: boolean }): JSX.Element {+}: ObservationLabelProps & { compact?: boolean }): JSX.Element | null {const logic = observationLabelLogic({ observationId, initialLabel, onChange })const { label, saving, feedbackDraft } = useValues(logic)const { rate, clearRating } = useActions(logic)const { featureFlags } = useValues(featureFlagLogic)+ const [feedbackOpen, setFeedbackOpen] = useState(false)const thumbsUp = label?.is_correct === trueconst thumbsDown = label?.is_correct === falseconst editDisabledReason = useEditAccess(scannerUserAccessLevel)// Clicking the active thumb again removes the rating.+ const onThumb = (isCorrect: boolean): void => {+ if (label?.is_correct === isCorrect) {+ clearRating()+ setFeedbackOpen(false)+ return+ }+ rate(isCorrect, feedbackDraft)+ setFeedbackOpen(!compact)+ }++ const closeNote = (): void => setFeedbackOpen(false)+const buttons = (<div className="flex items-center gap-1"><LemonButton@@ -157,8 +181,22 @@ export function ObservationLabelControl({icon={thumbsUp ? <IconThumbsUpFilled /> : <IconThumbsUp />}loading={saving}disabledReason={editDisabledReason ?? undefined}- tooltip={thumbsUp ? 'Remove rating' : 'Scanner got this right'}- onClick={() => (thumbsUp ? clearRating() : rate(true, feedbackDraft))}+ tooltip={+ thumbsUp ? (+ 'Remove rating'+ ) : (+ <>+ Scanner got this right+ {!compact && (+ <>+ {' '}+ <KeyboardShortcut y />+ </>+ )}+ </>+ )+ }+ onClick={() => onThumb(true)}data-attr="replay-vision-label-thumbs-up"/><LemonButton@@ -167,8 +205,22 @@ export function ObservationLabelControl({icon={thumbsDown ? <IconThumbsDownFilled /> : <IconThumbsDown />}loading={saving}disabledReason={editDisabledReason ?? undefined}- tooltip={thumbsDown ? 'Remove rating' : 'Scanner got this wrong'}- onClick={() => (thumbsDown ? clearRating() : rate(false, feedbackDraft))}+ tooltip={+ thumbsDown ? (+ 'Remove rating'+ ) : (+ <>+ Scanner got this wrong+ {!compact && (+ <>+ {' '}+ <KeyboardShortcut n />+ </>+ )}+ </>+ )+ }+ onClick={() => onThumb(false)}data-attr="replay-vision-label-thumbs-down"/></div>@@ -178,24 +230,47 @@ export function ObservationLabelControl({return <div className="py-2">{buttons}</div>}+ if (label && !feedbackOpen) {+ return null+ }+return (- <div className="border rounded p-3 bg-surface-primary space-y-2">- <div className="flex flex-wrap items-center justify-between gap-2">- <span className="text-sm font-medium">Did the scanner get this right?</span>+ <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1 rounded bg-surface-secondary px-3 py-2">+ <RatingHotkeys onThumb={onThumb} disabled={saving || !!label || !!editDisabledReason} />+ <span className="text-sm">Did the scanner get this right?</span>+ <Popover+ // Waits for the saved label, since the feedback autosave writes onto it.+ visible={feedbackOpen && !!label}+ onClickOutside={closeNote}+ placement="bottom-end"+ overlay={+ <div className="w-80 p-1 flex flex-col gap-2">+ <span className="text-sm font-medium">Add a note</span>+ <FeedbackEditor+ observationId={observationId}+ initialLabel={initialLabel}+ onChange={onChange}+ scannerUserAccessLevel={scannerUserAccessLevel}+ compact+ promptForRightAnswer={+ thumbsDown &&+ featureFlags[FEATURE_FLAGS.REPLAY_VISION_CALIBRATION_FEEDBACK_PROMPT] === 'test'+ }+ />+ <LemonButton+ size="small"+ type="secondary"+ className="self-end"+ onClick={closeNote}+ data-attr="replay-vision-label-feedback-done"+ >+ Done+ </LemonButton>+ </div>+ }+ >{buttons}- </div>- {label && (- <FeedbackEditor- observationId={observationId}- initialLabel={initialLabel}- onChange={onChange}- scannerUserAccessLevel={scannerUserAccessLevel}- compact={false}- promptForRightAnswer={- thumbsDown && featureFlags[FEATURE_FLAGS.REPLAY_VISION_CALIBRATION_FEEDBACK_PROMPT] === 'test'- }- />- )}+ </Popover></div>)}diff --git a/products/replay_vision/frontend/observations/ObservationPinnedProperties.tsx b/products/replay_vision/frontend/observations/ObservationPinnedProperties.tsxindex 0f40ddf57ddc..c1cbc5850782 100644--- a/products/replay_vision/frontend/observations/ObservationPinnedProperties.tsx+++ b/products/replay_vision/frontend/observations/ObservationPinnedProperties.tsx@@ -1,8 +1,7 @@import { useActions, useValues } from 'kea'import { useState } from 'react'-import { IconPin } from '@posthog/icons'-import { LemonButton, LemonCard, LemonSkeleton, Link, Tooltip } from '@posthog/lemon-ui'+import { LemonButton, LemonSkeleton, Link, Tooltip } from '@posthog/lemon-ui'import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'import { PropertyIcon } from 'lib/components/PropertyIcon/PropertyIcon'@@ -10,8 +9,7 @@ import { Popover } from 'lib/lemon-ui/Popover'import { getCoreFilterDefinition } from '~/taxonomy/helpers'-import { CardHeader } from '../components/CardHeader'-import { LabeledRow } from '../components/LabeledRow'+import { Fact, FactList } from './FactList'import {PINNED_PROPERTY_GROUPS,PinnedProperty,@@ -63,32 +61,28 @@ export function ObservationPinnedProperties({ sessionId }: { sessionId: string }const { sessionProperties, sessionPropertiesLoading } = useValues(observationSessionPropertiesLogic({ sessionId }))return (- <LemonCard className="p-4" hoverEffect={false}>- <CardHeader- icon={<IconPin />}- title="Pinned properties"- actions={- <Popover- visible={pickerOpen}- onClickOutside={() => setPickerOpen(false)}- overlay={<ObservationPinnedPropertiesPicker />}- placement="bottom-end"+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between gap-2">+ <span className="text-sm font-medium">Pinned properties</span>+ <Popover+ visible={pickerOpen}+ onClickOutside={() => setPickerOpen(false)}+ overlay={<ObservationPinnedPropertiesPicker />}+ placement="bottom-end"+ >+ <LemonButton+ size="xsmall"+ type="secondary"+ onClick={() => setPickerOpen(!pickerOpen)}+ data-attr="vision-observation-pin-properties">- <LemonButton- size="xsmall"- type="secondary"- onClick={() => setPickerOpen(!pickerOpen)}- data-attr="vision-observation-pin-properties"- >- Edit pinned properties- </LemonButton>- </Popover>- }- />+ Edit+ </LemonButton>+ </Popover>+ </div>{pinnedProperties.length === 0 ? (<p className="text-sm text-muted m-0">- Pin the properties you compare across results, like the referring domain, the campaign source, or- the person's plan.+ Nothing pinned. Use Edit to pick properties that show on every observation.</p>) : queryablePinnedProperties.length === 0 ? (<p className="text-sm text-muted m-0">@@ -98,21 +92,17 @@ export function ObservationPinnedProperties({ sessionId }: { sessionId: string }) : sessionPropertiesLoading ? (<LemonSkeleton.Row repeat={2} className="h-5" />) : (- <div className="@container/pinned">- <div className="grid grid-cols-1 gap-x-6 gap-y-3 @md/pinned:grid-cols-2 @3xl/pinned:grid-cols-4">- {queryablePinnedProperties.map((property) => (- <div key={pinnedPropertyId(property)} className="min-w-0">- <LabeledRow label={propertyLabel(property)}>- <PinnedPropertyValue- property={property}- value={sessionProperties?.[pinnedPropertyId(property)] ?? null}- />- </LabeledRow>- </div>- ))}- </div>- </div>+ <FactList>+ {queryablePinnedProperties.map((property) => (+ <Fact key={pinnedPropertyId(property)} label={propertyLabel(property)}>+ <PinnedPropertyValue+ property={property}+ value={sessionProperties?.[pinnedPropertyId(property)] ?? null}+ />+ </Fact>+ ))}+ </FactList>)}- </LemonCard>+ </div>)}diff --git a/products/replay_vision/frontend/observations/ObservationRecording.test.tsx b/products/replay_vision/frontend/observations/ObservationRecording.test.tsxindex 74c8f45e5ae2..9b4ccd5c0df4 100644--- a/products/replay_vision/frontend/observations/ObservationRecording.test.tsx+++ b/products/replay_vision/frontend/observations/ObservationRecording.test.tsx@@ -6,15 +6,24 @@ const mockSeekToTime = jest.fn()const mockPlayer = jest.fn<JSX.Element, [unknown]>(() => <div data-attr="recording-player" />)let mockSessionPlayerData: { start: { valueOf: () => number } | null; end: { valueOf: () => number } | null } | nulllet mockCurrentTimestamp: number | undefined+let mockIsNotFound = falsejest.mock('kea', () => ({- useValues: () => ({ sessionPlayerData: mockSessionPlayerData, currentTimestamp: mockCurrentTimestamp }),+ useValues: () => ({+ sessionPlayerData: mockSessionPlayerData,+ currentTimestamp: mockCurrentTimestamp,+ isNotFound: mockIsNotFound,+ }),}))jest.mock('scenes/session-recordings/player/SessionRecordingPlayer', () => ({SessionRecordingPlayer: (props: unknown) => mockPlayer(props),}))+jest.mock('scenes/session-recordings/player/sessionRecordingMetaLogic', () => ({+ sessionRecordingMetaLogic: jest.fn(),+}))+jest.mock('scenes/session-recordings/player/sessionRecordingPlayerLogic', () => ({SessionRecordingPlayerMode: { Standard: 'standard' },sessionRecordingPlayerLogic: Object.assign(jest.fn(), {@@ -28,13 +37,15 @@ describe('ObservationRecording', () => {mockPlayer.mockClear()mockSessionPlayerData = nullmockCurrentTimestamp = undefined+ mockIsNotFound = false})it('preserves player options and seeks once per citation after recording data arrives', () => {- const props = { playerKey: 'player-example', sessionRecordingId: 'session-example' }+ const props = { playerKey: 'player-example', sessionRecordingId: 'session-example', unavailable: null }const { rerender } = render(<ObservationRecording {...props} pendingSeek={null} />)expect(mockPlayer).toHaveBeenLastCalledWith({- ...props,+ playerKey: props.playerKey,+ sessionRecordingId: props.sessionRecordingId,mode: 'standard',autoPlay: false,noBorder: true,@@ -80,4 +91,18 @@ describe('ObservationRecording', () => {rerender(<ObservationRecording {...props} pendingSeek={null} />)expect(mockSeekToTime).toHaveBeenCalledTimes(3)})++ it('swaps the player for the unavailable message once the recording turns out to be gone', () => {+ mockIsNotFound = true+ const { getByText } = render(+ <ObservationRecording+ playerKey="player-example"+ sessionRecordingId="session-expired"+ pendingSeek={null}+ unavailable={<span>Recording gone</span>}+ />+ )+ expect(getByText('Recording gone')).toBeTruthy()+ expect(mockPlayer).not.toHaveBeenCalled()+ })})diff --git a/products/replay_vision/frontend/observations/ObservationRecording.tsx b/products/replay_vision/frontend/observations/ObservationRecording.tsxindex 6015185dc44e..77da4d115f11 100644--- a/products/replay_vision/frontend/observations/ObservationRecording.tsx+++ b/products/replay_vision/frontend/observations/ObservationRecording.tsx@@ -1,6 +1,7 @@import { useValues } from 'kea'import { useEffect, useRef } from 'react'+import { sessionRecordingMetaLogic } from 'scenes/session-recordings/player/sessionRecordingMetaLogic'import { SessionRecordingPlayer } from 'scenes/session-recordings/player/SessionRecordingPlayer'import {SessionRecordingPlayerMode,@@ -41,11 +42,18 @@ export default function ObservationRecording({playerKey,sessionRecordingId,pendingSeek,+ unavailable,}: {playerKey: stringsessionRecordingId: stringpendingSeek: { ms: number; trigger: number } | null+ /** Shown instead of the player once the recording turns out to be gone, since observations outlive recordings. */+ unavailable: React.ReactNode}): JSX.Element {+ const { isNotFound } = useValues(sessionRecordingMetaLogic({ sessionRecordingId, playerKey }))+ if (isNotFound) {+ return <>{unavailable}</>+ }return (<><SessionRecordingPlayerdiff --git a/products/replay_vision/frontend/observations/ObservationRecordingUnavailable.tsx b/products/replay_vision/frontend/observations/ObservationRecordingUnavailable.tsxnew file mode 100644index 000000000000..8bf830d4ac7c--- /dev/null+++ b/products/replay_vision/frontend/observations/ObservationRecordingUnavailable.tsx@@ -0,0 +1,43 @@+import { IconVideoCamera } from '@posthog/icons'+import { Link } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import { ObservationThumbnail } from '../components/ObservationThumbnail'+import type { ReplayObservationApi } from '../generated/api.schemas'++export function ObservationRecordingUnavailable({ observation }: { observation: ReplayObservationApi }): JSX.Element {+ const hasFrame = observation.media.some((entry) => entry.kind === 'thumbnail')+ return (+ <div+ className="h-full flex flex-col items-center justify-center gap-4 p-6 text-center"+ data-attr="vision-observation-recording-unavailable"+ >+ {hasFrame ? (+ <figure className="m-0 flex flex-col items-center gap-2 w-full max-w-xl">+ <ObservationThumbnail observation={observation} className="w-full" />+ <figcaption className="text-xs text-muted">+ The frame saved when this recording was scanned.+ </figcaption>+ </figure>+ ) : (+ <IconVideoCamera className="text-4xl text-muted" />+ )}+ <div className="flex flex-col gap-1 max-w-md">+ <span className="text-base font-semibold">This recording is no longer available</span>+ <span className="text-sm text-secondary">+ Recordings are deleted once they pass your project's retention period. The scan result stays, so you+ can still read it and rate it.+ </span>+ </div>+ <Link+ to={urls.settings('project-replay', 'replay-retention')}+ target="_blank"+ targetBlankIcon+ className="text-sm"+ >+ Manage replay data retention+ </Link>+ </div>+ )+}diff --git a/products/replay_vision/frontend/observations/ObservationSignalReports.tsx b/products/replay_vision/frontend/observations/ObservationSignalReports.tsxdeleted file mode 100644index 422e5f543e99..000000000000--- a/products/replay_vision/frontend/observations/ObservationSignalReports.tsx+++ /dev/null@@ -1,60 +0,0 @@-import { useValues } from 'kea'--import { Link } from '@posthog/lemon-ui'--import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'-import { urls } from 'scenes/urls'--import { displayConventionalCommitTitle } from 'products/signals/frontend/inbox/utils/reportPresentation'--import { LabeledRow } from '../components/LabeledRow'-import { observationSignalReportsLogic } from './observationSignalReportsLogic'--// Mounted only when the observation emitted something, so a no-signal observation never queries.-function ReportLinks({ observationId }: { observationId: string }): JSX.Element {- const { signalReports, signalReportsLoading, signalReportsUnavailable } = useValues(- observationSignalReportsLogic({ observationId })- )-- if (signalReportsLoading) {- return <LemonSkeleton className="h-4 w-40" />- }- if (signalReportsUnavailable) {- return <span className="text-muted">Could not load linked reports</span>- }- if (!signalReports?.length) {- // The lookup window is bounded, so an old observation can have a report this does not find.- return <span className="text-muted">No linked report found</span>- }- return (- <>- {signalReports.map((report) => (- <Link- key={report.id}- to={urls.inboxReport('reports', report.id)}- data-attr="vision-observation-open-signal-report"- >- {displayConventionalCommitTitle(report.title, 'Untitled report')}- </Link>- ))}- </>- )-}--/** The signals this observation emitted, and the inbox reports they were grouped into. */-export function ObservationSignalReports({- observationId,- signalsCount,-}: {- observationId: string- signalsCount: number-}): JSX.Element {- return (- <LabeledRow label="Signals">- <div className="flex flex-col items-start gap-1">- <span>Emitted ({signalsCount})</span>- {signalsCount > 0 && <ReportLinks observationId={observationId} />}- </div>- </LabeledRow>- )-}diff --git a/products/replay_vision/frontend/observations/ObservationUnsuccessfulScan.tsx b/products/replay_vision/frontend/observations/ObservationUnsuccessfulScan.tsxnew file mode 100644index 000000000000..45e20e30492d--- /dev/null+++ b/products/replay_vision/frontend/observations/ObservationUnsuccessfulScan.tsx@@ -0,0 +1,60 @@+import { LabeledRow } from '../components/LabeledRow'+import { ObservationRetryButton } from '../components/ObservationRetryButton'+import type { ReplayObservationApi } from '../generated/api.schemas'+import {+ failureKindDescription,+ ineligibleKindDescription,+ parseFailureReason,+ parseIneligibleReason,+} from '../replay_scanners/types'++export function ObservationUnsuccessfulScan({+ observation,+ retrying,+ onRetry,+}: {+ observation: ReplayObservationApi+ retrying: boolean+ onRetry: () => void+}): JSX.Element | null {+ const failed = observation.status === 'failed'+ if (!failed && observation.status !== 'ineligible') {+ return null+ }+ const errorReason = observation.error_reason+ const failure = failed && errorReason ? parseFailureReason(errorReason) : null+ const ineligible = !failed && errorReason ? parseIneligibleReason(errorReason) : null+ const description = failure+ ? failureKindDescription(failure.kind)+ : ineligible+ ? ineligibleKindDescription(ineligible.kind)+ : errorReason || 'No reason was recorded for this scan.'+ const message = (failure ?? ineligible)?.message++ return (+ <div className="flex flex-col gap-3">+ <div className="flex flex-col gap-1">+ <span className={`text-2xl font-bold ${failed ? 'text-danger' : 'text-muted'}`}>+ {failed ? 'Scan failed' : 'Not scanned'}+ </span>+ <p className="text-sm text-default m-0 leading-snug">{description}</p>+ </div>+ {message && (+ <LabeledRow label={failed ? 'Error' : 'More info'}>+ <p className={`text-sm text-default m-0 leading-snug ${failed ? 'font-mono' : ''}`}>{message}</p>+ </LabeledRow>+ )}+ <div>+ <ObservationRetryButton+ status={observation.status}+ errorReason={errorReason}+ onRetry={onRetry}+ loading={retrying}+ emphasis={failed ? 'primary' : undefined}+ size="small"+ dataAttr="vision-observation-detail-retry"+ />+ </div>+ </div>+ )+}diff --git a/products/replay_vision/frontend/observations/ReplayObservation.test.tsx b/products/replay_vision/frontend/observations/ReplayObservation.test.tsxindex 45102de7d9c0..8724ddb0ff1d 100644--- a/products/replay_vision/frontend/observations/ReplayObservation.test.tsx+++ b/products/replay_vision/frontend/observations/ReplayObservation.test.tsx@@ -1,6 +1,6 @@import '@testing-library/jest-dom'-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { router } from 'kea-router'import { useMocks } from '~/mocks/jest'@@ -9,14 +9,14 @@ import { initKeaTests } from '~/test/init'import { ReplayObservationSceneComponent } from './ReplayObservation'import { replayObservationSceneLogic } from './replayObservationSceneLogic'-const mockRecordingImported = jest.fn()const mockRecordingRendered = jest.fn()+let observationOverrides: Record<string, unknown> = {}+const mockLabelSaved = jest.fn()jest.mock('./ObservationRecording', () => {- mockRecordingImported()return {__esModule: true,- default: (props: unknown) => {+ default: ({ unavailable: _unavailable, ...props }: Record<string, unknown>) => {mockRecordingRendered(props)return <div data-attr="observation-recording" />},@@ -25,6 +25,11 @@ jest.mock('./ObservationRecording', () => {jest.mock('./ObservationPinnedProperties', () => ({ ObservationPinnedProperties: () => null }))+jest.mock('lib/utils/accessControlUtils', () => ({+ ...jest.requireActual('lib/utils/accessControlUtils'),+ getAccessControlDisabledReason: jest.fn(() => null),+}))+jest.mock('../components/CitedMarkdown', () => {const { TimestampCitation } = jest.requireActual('../components/TimestampCitation')return {@@ -69,10 +74,17 @@ describe('ReplayObservation', () => {previous_observation_id: null,next_observation_id: 'observation-next',label: null,+ completed_at: '2026-07-01T00:01:00Z',+ ...observationOverrides,}),},post: {'/api/projects/:team/vision/observations/:id/viewed/': () => [204],+ '/api/projects/:team/vision/observations/:id/label/': async ({ request }) => {+ const body = await request.json()+ mockLabelSaved(body)+ return [200, body]+ },},})initKeaTests()@@ -80,32 +92,29 @@ describe('ReplayObservation', () => {router.actions.push('/replay-vision/observations/observation-example')})- afterEach(() => replayObservationSceneLogic.unmount())+ afterEach(() => {+ cleanup()+ replayObservationSceneLogic.unmount()+ observationOverrides = {}+ })- it('shows the result before importing the player and preserves citation and collapse behavior', async () => {+ it('renders the player beside the result and seeks it from citations and shared links', async () => {render(<ReplayObservationSceneComponent />)await screen.findByText(/The next page did not open\./)- expect(mockRecordingImported).not.toHaveBeenCalled()- expect(screen.queryByTestId('observation-recording')).not.toBeInTheDocument()-- fireEvent.click(screen.getByText('00:05'))await screen.findByTestId('observation-recording')- expect(mockRecordingImported).toHaveBeenCalledTimes(1)expect(mockRecordingRendered).toHaveBeenLastCalledWith({playerKey: 'vision-observation-observation-example',sessionRecordingId: 'session-observation-example',- pendingSeek: { ms: 5000, trigger: expect.any(Number) },+ pendingSeek: null,})- expect(screen.getByText(/The next page did not open\./)).toBeInTheDocument()- fireEvent.click(screen.getByText('Recording'))- expect(screen.queryByTestId('observation-recording')).not.toBeInTheDocument()- fireEvent.click(screen.getByText('Watch the recording'))- await screen.findByTestId('observation-recording')- expect(mockRecordingImported).toHaveBeenCalledTimes(1)- expect(mockRecordingRendered).toHaveBeenLastCalledWith(expect.objectContaining({ pendingSeek: null }))+ fireEvent.click(screen.getByText('00:05'))+ expect(mockRecordingRendered).toHaveBeenLastCalledWith(+ expect.objectContaining({ pendingSeek: { ms: 5000, trigger: expect.any(Number) } })+ )- fireEvent.click(screen.getByText('Next'))+ // A seek belongs to one observation, so moving to a sibling drops it.+ fireEvent.keyDown(document.body, { key: 'j' })await waitFor(() =>expect(mockRecordingRendered).toHaveBeenLastCalledWith({playerKey: 'vision-observation-observation-next',@@ -114,7 +123,6 @@ describe('ReplayObservation', () => {}))- fireEvent.click(screen.getByText('Recording'))for (const seconds of [0, 5.25]) {act(() => router.actions.push('/replay-vision/observations/observation-shared', { t: seconds }))await waitFor(() =>@@ -124,14 +132,48 @@ describe('ReplayObservation', () => {pendingSeek: { ms: seconds * 1000, trigger: expect.any(Number) },}))- fireEvent.click(screen.getByText('Recording'))- expect(screen.queryByTestId('observation-recording')).not.toBeInTheDocument()}for (const timestamp of ['-1', 'invalid']) {act(() => router.actions.push('/replay-vision/observations/observation-shared', { t: timestamp }))- expect(screen.queryByTestId('observation-recording')).not.toBeInTheDocument()- expect(screen.getByText('Watch the recording')).toBeInTheDocument()+ await waitFor(() =>+ expect(mockRecordingRendered).toHaveBeenLastCalledWith(expect.objectContaining({ pendingSeek: null }))+ )}})++ it.each([+ ['an unrated succeeded scan', {}, true, true],+ ['an already rated scan', { label: { is_correct: true, feedback: '' } }, false, true],+ [+ 'a failed scan',+ { status: 'failed', error_reason: 'provider_transient:Timed out.', scanner_result: null },+ false,+ false,+ ],+ ])(+ 'for %s, shows the rating question and the event link only when they apply',+ async (_name, overrides, asksForRating, linksEvent) => {+ observationOverrides = overrides+ render(<ReplayObservationSceneComponent />)+ await screen.findByTestId('observation-recording')++ expect(screen.queryByText('Did the scanner get this right?') !== null).toBe(asksForRating)+ fireEvent.click(screen.getByText('Details'))+ expect(screen.queryByText('$recording_observed') !== null).toBe(linksEvent)+ }+ )++ it.each([+ ['an unrated scan saves the rating', {}, [{ is_correct: true, feedback: '' }]],+ ['an already rated scan ignores the key', { label: { is_correct: false, feedback: '' } }, []],+ ])('pressing y on %s', async (_name, overrides, expectedSaves) => {+ observationOverrides = overrides+ mockLabelSaved.mockClear()+ render(<ReplayObservationSceneComponent />)+ await screen.findByTestId('observation-recording')++ fireEvent.keyDown(document.body, { key: 'y' })+ await waitFor(() => expect(mockLabelSaved.mock.calls.map(([body]) => body)).toEqual(expectedSaves))+ })})diff --git a/products/replay_vision/frontend/observations/ReplayObservation.tsx b/products/replay_vision/frontend/observations/ReplayObservation.tsxindex 6ba2bceae01c..80db2cda891d 100644--- a/products/replay_vision/frontend/observations/ReplayObservation.tsx+++ b/products/replay_vision/frontend/observations/ReplayObservation.tsx@@ -1,29 +1,15 @@import { useActions, useValues } from 'kea'import { router } from 'kea-router'-import { Suspense, useEffect, useState } from 'react'+import { Suspense, useEffect, useRef, useState } from 'react'-import {- IconArrowLeft,- IconArrowRight,- IconClock,- IconCollapse,- IconExpand,- IconGear,- IconInfo,- IconPlayFilled,- IconSparkles,- IconThoughtBubble,- IconVideoCamera,-} from '@posthog/icons'-import { LemonButton, LemonCard, LemonTag, Link, Spinner } from '@posthog/lemon-ui'+import { IconArrowLeft, IconArrowRight } from '@posthog/icons'+import { LemonButton, LemonCard, Link, Spinner } from '@posthog/lemon-ui'-import { TZLabel } from 'lib/components/TZLabel'+import { KeyboardShortcut } from 'lib/components/KeyboardShortcut/KeyboardShortcut'import { FEATURE_FLAGS } from 'lib/constants'-import { dayjs } from 'lib/dayjs'-import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'-import { humanFriendlyDuration, humanFriendlyMilliseconds } from 'lib/utils/durations'import { lazyWithRetry } from 'lib/utils/retryImport'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'@@ -32,45 +18,25 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'-import { BooleanTag } from '../components/BooleanTag'-import { CardHeader } from '../components/CardHeader'import { CitedMarkdown } from '../components/CitedMarkdown'import { LabeledRow } from '../components/LabeledRow'-import {- ObservationConfidence,- ObservationPrimaryOutput,- ObservationStatusTag,- PromptRow,- readResult,-} from '../components/ObservationCard'+import { readResult } from '../components/ObservationCard'import { ObservationProgressBar } from '../components/ObservationProgressBar'-import { ObservationRetryButton } from '../components/ObservationRetryButton'-import { ObservationThumbnail } from '../components/ObservationThumbnail'import { ReplayVisionFeedbackButton } from '../components/ReplayVisionFeedbackButton'-import { ScannerTypeBadge } from '../components/ScannerTypeBadge'import type { ReplayObservationApi } from '../generated/api.schemas'-import {- type ClassifierScannerConfig,- type MonitorScannerConfig,- type ScorerScannerConfig,- type SummarizerScannerConfig,- configFromSnapshot,- failureKindDescription,- ineligibleKindDescription,- modelLabel,- modelNamingVariant,- parseFailureReason,- parseIneligibleReason,- OBSERVATION_TRIGGER_TAG,- SUCCEEDED_OUTPUT_LABEL,-} from '../replay_scanners/types'+import { PromptPreview } from '../replay_scanners/components/PromptPreview'+import { configFromSnapshot } from '../replay_scanners/types'import { hasScannerPage, scannerLabel } from '../utils/observation'import { parseNumericParam } from '../utils/urlParams'+import { ObservationDetails } from './ObservationDetails'+import { ObservationFacts } from './ObservationFacts'+import { ObservationHeadline } from './ObservationHeadline'import { ObservationLabelControl } from './ObservationLabelControl'import { observationLabelLogic } from './observationLabelLogic'import { ObservationPinnedProperties } from './ObservationPinnedProperties'+import { ObservationRecordingUnavailable } from './ObservationRecordingUnavailable'import { ObservationShareButton } from './ObservationShareButton'-import { ObservationSignalReports } from './ObservationSignalReports'+import { ObservationUnsuccessfulScan } from './ObservationUnsuccessfulScan'import {neighborFilterParams,observationDetailUrl,@@ -120,9 +86,7 @@ function CalibrationEntryPoint({ observation }: { observation: ReplayObservationexport function ReplayObservationSceneComponent(): JSX.Element {const { observationId } = useValues(replayObservationSceneLogic)const { searchParams } = useValues(router)- const { featureFlags } = useValues(featureFlagLogic)- const namingVariant = modelNamingVariant(featureFlags[FEATURE_FLAGS.REPLAY_VISION_MODEL_TIER_NAMING_EXPERIMENT])- const [recordingExpanded, setRecordingExpanded] = useState(false)+ const playerRef = useRef<HTMLDivElement>(null)const [pendingSeek, setPendingSeek] = useState<{ ms: number; trigger: number } | null>(null)// A shared link carries the moment the sharer was watching, in seconds, the same way a recording link does.const sharedStartSeconds = parseNumericParam(searchParams.t)@@ -131,7 +95,6 @@ export function ReplayObservationSceneComponent(): JSX.Element {// start and any citation seek are dropped once prev/next moves to a sibling.useEffect(() => {if (sharedStartSeconds !== null && sharedStartSeconds >= 0) {- setRecordingExpanded(true)setPendingSeek({ ms: sharedStartSeconds * 1000, trigger: Date.now() })} else {setPendingSeek(null)@@ -145,6 +108,33 @@ export function ReplayObservationSceneComponent(): JSX.Element {useValues(observationLogic)const { retryObservation } = useActions(observationLogic)+ // Filters carried over from the scanner's observations table; preserved on prev/next so+ // navigation (and the server-computed neighbor ids) stay within the filtered list.+ const neighborParams = neighborFilterParams(searchParams)+ const neighborsFiltered = Object.keys(neighborParams).some((key) => key !== 'order_by')+ // Prev/next keeps the return params too, so back still lands on the list view (or the watch feed)+ // the reader came from.+ const observationUrl = (id: string): string =>+ observationDetailUrl(id, {+ ...neighborParams,+ ...scannerReturnParams(searchParams),+ ...observationOriginParams(searchParams),+ })++ useKeyboardHotkeys(+ {+ j: {+ action: () => nextObservationId && router.actions.push(observationUrl(nextObservationId)),+ disabled: !nextObservationId,+ },+ k: {+ action: () => previousObservationId && router.actions.push(observationUrl(previousObservationId)),+ disabled: !previousObservationId,+ },+ },+ [nextObservationId, previousObservationId, searchParams]+ )+if (observationLoading && !observation) {return (<SceneContent>@@ -172,75 +162,19 @@ export function ReplayObservationSceneComponent(): JSX.Element {const reasoningSegments = result?.reasoning_segmentsconst scannerType = snapshot?.scanner_typeconst scannerName = scannerLabel(observation)- const triggerLabel = OBSERVATION_TRIGGER_TAG[observation.triggered_by].label- const snapshotConfig = configFromSnapshot(snapshot)- const prompt = snapshotConfig?.prompt ?? null- const summarizerConfig = scannerType === 'summarizer' ? (snapshotConfig as SummarizerScannerConfig | null) : null- const classifierConfig = scannerType === 'classifier' ? (snapshotConfig as ClassifierScannerConfig | null) : null- const monitorConfig = scannerType === 'monitor' ? (snapshotConfig as MonitorScannerConfig | null) : null- const scorerConfig = scannerType === 'scorer' ? (snapshotConfig as ScorerScannerConfig | null) : null- const summarizerLength = summarizerConfig?.length ?? null- const classifierVocab = Array.isArray(classifierConfig?.tags) ? classifierConfig.tags : null- const classifierMultiLabel = classifierConfig ? classifierConfig.multi_label === true : null- const monitorAllowInconclusive = monitorConfig ? monitorConfig.allow_inconclusive === true : null- const classifierAllowFreeform = classifierConfig ? classifierConfig.allow_freeform_tags === true : null- const scorerMin = typeof scorerConfig?.scale?.min === 'number' ? scorerConfig.scale.min : null- const scorerMax = typeof scorerConfig?.scale?.max === 'number' ? scorerConfig.scale.max : null- const scorerLabel = typeof scorerConfig?.scale?.label === 'string' ? scorerConfig.scale.label : null- const ineligibleParsed =- observation.status === 'ineligible' && observation.error_reason- ? parseIneligibleReason(observation.error_reason)- : null- const ineligibleMessage = ineligibleParsed ? ineligibleParsed.message || null : observation.error_reason || null- const failedParsed =- observation.status === 'failed' && observation.error_reason- ? parseFailureReason(observation.error_reason)- : null- const failedMessage = failedParsed ? failedParsed.message || null : observation.error_reason || null- const durationMs =- observation.started_at && observation.completed_at- ? dayjs(observation.completed_at).diff(observation.started_at)- : null- const durationLabel =- durationMs !== null && Number.isFinite(durationMs) && durationMs >= 0- ? durationMs < 60_000- ? (humanFriendlyMilliseconds(durationMs) ?? null)- : humanFriendlyDuration(durationMs / 1000)- : null-- // Filters carried over from the scanner's observations table; preserved on prev/next so- // navigation (and the server-computed neighbor ids) stay within the filtered list.- const neighborParams = neighborFilterParams(searchParams)- const neighborsFiltered = Object.keys(neighborParams).some((key) => key !== 'order_by')- // Prev/next keeps the return params too, so back still lands on the list view (or the watch feed)- // the reader came from.- const observationUrl = (id: string): string =>- observationDetailUrl(id, {- ...neighborParams,- ...scannerReturnParams(searchParams),- ...observationOriginParams(searchParams),- })+ const prompt = configFromSnapshot(snapshot)?.prompt ?? nullconst seekEmbeddedPlayer = (ms: number): void => {- if (!recordingExpanded) {- setRecordingExpanded(true)- }setPendingSeek({ ms, trigger: Date.now() })- }-- const toggleRecordingExpanded = (): void => {- // Collapsing discards the seek intent, or re-expanding would remount the seeker and replay it.- if (recordingExpanded) {- setPendingSeek(null)- }- setRecordingExpanded(!recordingExpanded)+ // On narrow screens the player sits below the result, so bring it into view with the seek.+ playerRef.current?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })}return (<SceneContent><SceneTitleSectionname={scannerName}- description={`Observation of session ${observation.session_id}`}+ description={observation.recording_subject_email ?? undefined}resourceType={{ type: 'replay_vision' }}actions={<>@@ -258,9 +192,12 @@ export function ReplayObservationSceneComponent(): JSX.Element {: 'No newer observation'}tooltip={- neighborsFiltered- ? 'Previous observation matching your filters'- : 'Previous (newer) observation for this scanner'+ <>+ {neighborsFiltered+ ? 'Previous observation matching your filters'+ : 'Previous (newer) observation for this scanner'}{' '}+ <KeyboardShortcut k />+ </>}data-attr="vision-observation-prev">@@ -280,9 +217,12 @@ export function ReplayObservationSceneComponent(): JSX.Element {: 'No older observation'}tooltip={- neighborsFiltered- ? 'Next observation matching your filters'- : 'Next (older) observation for this scanner'+ <>+ {neighborsFiltered+ ? 'Next observation matching your filters'+ : 'Next (older) observation for this scanner'}{' '}+ <KeyboardShortcut j />+ </>}data-attr="vision-observation-next">@@ -298,325 +238,80 @@ export function ReplayObservationSceneComponent(): JSX.Element {}/>- <LemonCard className="overflow-hidden p-0" hoverEffect={false}>- {recordingExpanded ? (- <div- className="flex items-center gap-2 bg-surface-primary p-3 cursor-pointer hover:bg-surface-secondary"- onClick={toggleRecordingExpanded}- >- <LemonButton- icon={<IconCollapse />}- size="small"- tooltip="Collapse recording"- onClick={(e) => {- e.stopPropagation()- toggleRecordingExpanded()- }}- data-attr="vision-observation-recording-toggle"- />- <IconVideoCamera className="text-muted-alt" />- <h3 className="text-lg font-semibold m-0">Recording</h3>- </div>- ) : (- // Collapsed, this row is the only sign the page holds a video, so it leads with a- // thumbnail of the player it opens: a dark screen carrying one play target.- <button- type="button"- className="w-full flex items-center gap-3 p-3 text-left bg-surface-primary hover:bg-surface-secondary"- onClick={toggleRecordingExpanded}- aria-expanded={false}- data-attr="vision-observation-recording-toggle"- >- <ObservationThumbnail observation={observation} className="w-20 shrink-0">- <IconPlayFilled className="text-xl text-brand-red drop-shadow" />- </ObservationThumbnail>- <span className="flex-1 min-w-0">- <h3 className="text-lg font-semibold m-0">Watch the recording</h3>- <span className="text-sm text-muted">Play the session this observation was made from</span>- </span>- <IconExpand className="text-lg text-muted-alt shrink-0" />- </button>- )}- {recordingExpanded && (- <div className="border-t border-border h-[calc(100vh-16rem)] min-h-[480px]">- <Suspense fallback={<Spinner className="m-4" />}>- <ObservationRecording- playerKey={playerKey}- sessionRecordingId={observation.session_id}- pendingSeek={pendingSeek}- />- </Suspense>- </div>- )}- </LemonCard>-- <div className={scannerType === 'summarizer' ? '' : 'grid grid-cols-1 lg:grid-cols-2 gap-4'}>- <section className="border rounded p-4 bg-surface-primary space-y-3">- <CardHeader icon={<IconSparkles />} title="Result" />-- {observation.status === 'failed' && observation.error_reason && (- <div className="flex flex-col gap-3">- {scannerType && (- <LabeledRow label="Type">- <ScannerTypeBadge scannerType={scannerType} />+ <div className="@container">+ <div className="grid grid-cols-1 gap-4 items-start @4xl:grid-cols-[minmax(20rem,1fr)_minmax(0,2fr)]">+ <div className="flex flex-col gap-4 min-w-0">+ <section className="border rounded p-4 bg-surface-primary flex flex-col gap-4">+ {/* Only a finished scan answered the prompt, so the question shows beside its answer. */}+ {prompt && observation.status === 'succeeded' && (+ <LabeledRow label="Prompt">+ <PromptPreview prompt={prompt} dataAttr="vision-observation-show-prompt" /></LabeledRow>)}- <LabeledRow label="Reason">- <p className="text-sm text-default m-0 leading-snug">- {failedParsed- ? failureKindDescription(failedParsed.kind)- : observation.error_reason}- </p>- </LabeledRow>- {failedParsed && failedMessage && (- <LabeledRow label="Details">- <p className="text-sm text-default m-0 leading-snug font-mono">{failedMessage}</p>- </LabeledRow>- )}- <div>- <ObservationRetryButton- status={observation.status}- errorReason={observation.error_reason}- onRetry={() => retryObservation()}- loading={retrying}- emphasis="primary"- size="small"- dataAttr="vision-observation-detail-retry"- />- </div>- </div>- )}- {observation.status === 'ineligible' && observation.error_reason && (- <div className="flex flex-col gap-3">- {scannerType && (- <LabeledRow label="Type">- <ScannerTypeBadge scannerType={scannerType} />- </LabeledRow>- )}- <LabeledRow label="Reason">- <p className="text-sm text-default m-0 leading-snug">- {ineligibleParsed- ? ineligibleKindDescription(ineligibleParsed.kind)- : observation.error_reason}- </p>- </LabeledRow>- {ineligibleParsed && ineligibleMessage && (- <LabeledRow label="Details">- <p className="text-sm text-default m-0 leading-snug">{ineligibleMessage}</p>- </LabeledRow>- )}- <div>- <ObservationRetryButton- status={observation.status}- errorReason={observation.error_reason}- onRetry={() => retryObservation()}- loading={retrying}- size="small"- dataAttr="vision-observation-detail-retry"- />- </div>- </div>- )}+ <ObservationUnsuccessfulScan+ observation={observation}+ retrying={retrying}+ onRetry={() => retryObservation()}+ />- {observation.status === 'succeeded' && snapshot && result && (- <div className="flex flex-col gap-3">- {scannerType && (- <LabeledRow label="Type">- <ScannerTypeBadge scannerType={scannerType} />- </LabeledRow>+ {observation.status === 'succeeded' && snapshot && result && (+ <>+ <ObservationHeadline observation={observation} onSeek={seekEmbeddedPlayer} />+ {scannerType !== 'summarizer' && reasoning && (+ <LabeledRow label="Reasoning">+ <CitedMarkdown+ text={reasoning}+ segments={reasoningSegments}+ onSeek={seekEmbeddedPlayer}+ />+ </LabeledRow>+ )}+ <ObservationLabelControl+ observationId={observation.id}+ initialLabel={observation.label}+ />+ <CalibrationEntryPoint observation={observation} />+ </>)}- <LabeledRow label={scannerType ? SUCCEEDED_OUTPUT_LABEL[scannerType] : ''}>- <ObservationPrimaryOutput- observation={observation}- showPrompt={false}- onSeek={seekEmbeddedPlayer}- copyable- />- </LabeledRow>- {prompt && scannerType !== 'summarizer' && <PromptRow prompt={prompt} />}- {observation.completed_at && (- <LabeledRow label="Event">- <Link to={urls.event(observation.id, observation.completed_at)}>- $recording_observed- </Link>- </LabeledRow>- )}- {snapshot.emits_signals && (- <ObservationSignalReports- observationId={observation.id}- signalsCount={observation.scanner_result?.signals_count ?? 0}- />- )}- <ObservationLabelControl observationId={observation.id} initialLabel={observation.label} />- <CalibrationEntryPoint observation={observation} />- </div>- )}-- {(observation.status === 'pending' || observation.status === 'running') && (- <ObservationProgressBar observationId={observation.id} sessionId={observation.session_id} />- )}- </section>-- {scannerType !== 'summarizer' && (- <section- className={`border rounded p-4 space-y-2 ${- reasoning ? 'bg-surface-primary' : 'bg-surface-secondary opacity-60'- }`}- >- <CardHeader icon={<IconThoughtBubble />} title="Model reasoning" />- {reasoning ? (- <CitedMarkdown text={reasoning} segments={reasoningSegments} onSeek={seekEmbeddedPlayer} />- ) : (- <p className="text-muted text-sm m-0 italic">- {observation.status === 'ineligible'- ? 'The model was not invoked.'- : observation.status === 'failed'- ? 'No reasoning available — the observation failed before completion.'- : observation.status === 'succeeded'- ? 'No reasoning provided.'- : 'Awaiting model output…'}- </p>- )}- </section>- )}- </div>- <ObservationPinnedProperties sessionId={observation.session_id} />-- <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">- <LemonCard className="p-4" hoverEffect={false}>- <CardHeader icon={<IconInfo />} title="Observation details" />- <div className="flex flex-col gap-3 text-sm">- <LabeledRow label="Status">- <ObservationStatusTag status={observation.status} errorReason={observation.error_reason} />- </LabeledRow>- {result && typeof result.confidence === 'number' && (- <LabeledRow label="Confidence">- <ObservationConfidence result={result} />- </LabeledRow>- )}- <LabeledRow label="Triggered by">- {observation.triggered_by !== 'schedule' && observation.triggered_by_user ? (- <ProfilePicture- user={{- first_name: observation.triggered_by_user.first_name,- last_name: observation.triggered_by_user.last_name,- email: observation.triggered_by_user.email,- }}- size="sm"- showName+ {(observation.status === 'pending' || observation.status === 'running') && (+ <ObservationProgressBar+ observationId={observation.id}+ sessionId={observation.session_id}/>- ) : (- <span>{triggerLabel}</span>- )}- </LabeledRow>- <LabeledRow label="Session">- <Link- to={urls.sessionProfile(observation.session_id)}- className="break-all lg:break-normal"- data-attr="vision-observation-session-link"- >- {observation.session_id}- </Link>- </LabeledRow>- <LabeledRow label="Person">- {observation.distinct_id ? (- <Link- to={urls.personByDistinctId(observation.distinct_id)}- className="break-all lg:break-normal"- >- {observation.recording_subject_email ?? observation.distinct_id}- </Link>- ) : observation.recording_subject_email ? (- <span className="break-all lg:break-normal">{observation.recording_subject_email}</span>- ) : (- <span className="text-muted">—</span>)}- </LabeledRow>- </div>- </LemonCard>- <LemonCard className="p-4" hoverEffect={false}>- <CardHeader icon={<IconClock />} title="Lifecycle" />- <div className="flex flex-col gap-3 text-sm">- <LabeledRow label="Created at">- <TZLabel time={observation.created_at} />- </LabeledRow>- {observation.started_at && (- <LabeledRow label="Started at">- <TZLabel time={observation.started_at} />- </LabeledRow>- )}- {observation.completed_at && (- <LabeledRow label="Completed at">- <TZLabel time={observation.completed_at} />- </LabeledRow>- )}- {durationLabel && (- <LabeledRow label="Duration">- <span>{durationLabel}</span>- </LabeledRow>- )}+ <div className="border-t pt-3">+ <ObservationFacts observation={observation} />+ </div>+ <div className="border-t pt-3">+ <ObservationPinnedProperties sessionId={observation.session_id} />+ </div>+ <div className="border-t pt-3">+ <ObservationDetails observation={observation} />+ </div>+ </section></div>- </LemonCard>- <LemonCard className="p-4" hoverEffect={false}>- <CardHeader icon={<IconGear />} title="Configuration" />- <div className="flex flex-col gap-3 text-sm">- {snapshot?.model && (- <LabeledRow label="Model">- <span>{modelLabel(snapshot.model, namingVariant)}</span>- </LabeledRow>- )}- {summarizerLength && (- <LabeledRow label="Summary length">- <span className="capitalize">{summarizerLength}</span>- </LabeledRow>- )}- {classifierVocab && classifierVocab.length > 0 && (- <LabeledRow label="Categories">- <div className="flex flex-wrap gap-1">- {classifierVocab.map((tag) => (- <LemonTag key={tag} type="default" size="small">- {tag}- </LemonTag>- ))}- </div>- </LabeledRow>- )}- {monitorAllowInconclusive !== null && (- <LabeledRow label="Allow inconclusive verdicts">- <BooleanTag value={monitorAllowInconclusive} />- </LabeledRow>- )}- {classifierMultiLabel !== null && (- <LabeledRow label="Multiple categories per session">- <BooleanTag value={classifierMultiLabel} />- </LabeledRow>- )}- {classifierAllowFreeform !== null && (- <LabeledRow label="Freeform categories">- <BooleanTag value={classifierAllowFreeform} />- </LabeledRow>- )}- {scorerMin !== null && (- <LabeledRow label="Scale minimum">- <span>{scorerMin}</span>- </LabeledRow>- )}- {scorerMax !== null && (- <LabeledRow label="Scale maximum">- <span>{scorerMax}</span>- </LabeledRow>- )}- {scorerLabel && (- <LabeledRow label="Score label">- <span>{scorerLabel}</span>- </LabeledRow>- )}+ {/* 16:10 leaves the player's top bar on top of a 16:9 frame, the shape of most recordings. */}+ <div ref={playerRef} className="@container/player min-w-0 @4xl:sticky @4xl:top-4">+ <LemonCard+ className="overflow-hidden p-0 h-[min(62.5cqw,calc(100vh-8rem))]"+ hoverEffect={false}+ >+ {/* Lazy, so the result renders before the player's code arrives. */}+ <Suspense fallback={<Spinner className="m-4" />}>+ <ObservationRecording+ playerKey={playerKey}+ sessionRecordingId={observation.session_id}+ pendingSeek={pendingSeek}+ unavailable={<ObservationRecordingUnavailable observation={observation} />}+ />+ </Suspense>+ </LemonCard></div>- </LemonCard>+ </div></div></SceneContent>)diff --git a/products/replay_vision/frontend/observations/observationLabelLogic.test.ts b/products/replay_vision/frontend/observations/observationLabelLogic.test.tsindex bc177ca8db00..ae5b86b7ebb0 100644--- a/products/replay_vision/frontend/observations/observationLabelLogic.test.ts+++ b/products/replay_vision/frontend/observations/observationLabelLogic.test.ts@@ -56,6 +56,32 @@ describe('observationLabelLogic feedback autosave', () => {expect(onChange).toHaveBeenCalledWith({ is_correct: isCorrect, feedback: 'scanner missed the refund step' })})+ it('saves a note typed just before the page unmounts, which cancels the pending autosave', async () => {+ mountLogic(false)+ logic.actions.setFeedbackDraft('wrong: the user finished checkout')+ await jest.advanceTimersByTimeAsync(300)+ logic.unmount()++ expect(visionObservationsLabelCreate).toHaveBeenCalledTimes(1)+ expect(visionObservationsLabelCreate).toHaveBeenCalledWith(TEAM_ID, 'obs-1', {+ is_correct: false,+ feedback: 'wrong: the user finished checkout',+ })+ })++ it('keeps a rating still in flight when the page unmounts with an unsaved note', async () => {+ mountLogic(true)+ ;(visionObservationsLabelCreate as jest.Mock).mockImplementationOnce(() => new Promise(() => {}))+ logic.actions.rate(false, 'old feedback')+ logic.actions.setFeedbackDraft('it missed the declined card')+ logic.unmount()++ expect(visionObservationsLabelCreate).toHaveBeenLastCalledWith(TEAM_ID, 'obs-1', {+ is_correct: false,+ feedback: 'it missed the declined card',+ })+ })+it('settles as synced when the API trims the feedback it stores', async () => {// The API trims before storing, so the echoed label never matches a draft with trailing whitespace.;(visionObservationsLabelCreate as jest.Mock).mockImplementation((_team, _id, body) =>@@ -120,4 +146,22 @@ describe('observationLabelLogic feedback autosave', () => {expect(logic.values.label).toEqual({ is_correct: true, feedback: 'teammate feedback' })expect(logic.values.feedbackDraft).toEqual('teammate feedback')})++ it("keeps a teammate's adopted rating when an edited note saves on unmount", async () => {+ mountLogic(false)+ logic.actions.rate(true, 'old feedback')+ await jest.advanceTimersByTimeAsync(0)+ observationLabelLogic({+ observationId: 'obs-1',+ initialLabel: { is_correct: false, feedback: 'teammate feedback' },+ onChange,+ })+ logic.actions.setFeedbackDraft('teammate feedback, plus mine')+ logic.unmount()++ expect(visionObservationsLabelCreate).toHaveBeenLastCalledWith(TEAM_ID, 'obs-1', {+ is_correct: false,+ feedback: 'teammate feedback, plus mine',+ })+ })})diff --git a/products/replay_vision/frontend/observations/observationLabelLogic.ts b/products/replay_vision/frontend/observations/observationLabelLogic.tsindex f16321c71d21..70876f960073 100644--- a/products/replay_vision/frontend/observations/observationLabelLogic.ts+++ b/products/replay_vision/frontend/observations/observationLabelLogic.ts@@ -1,4 +1,16 @@-import { MakeLogicType, actions, kea, key, listeners, path, props, propsChanged, reducers, selectors } from 'kea'+import {+ MakeLogicType,+ actions,+ beforeUnmount,+ kea,+ key,+ listeners,+ path,+ props,+ propsChanged,+ reducers,+ selectors,+} from 'kea'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { teamLogic } from 'scenes/teamLogic'@@ -138,6 +150,8 @@ export const observationLabelLogic = kea<observationLabelLogicType>([return}cache.labelEpoch = (cache.labelEpoch ?? 0) + 1+ // The adopted label supersedes anything this viewer sent, so a note saved on unmount keeps its rating.+ cache.lastSentLabel = undefinedactions.labelUpdated(next)actions.setFeedbackDraft(next?.feedback ?? '')}),@@ -160,6 +174,7 @@ export const observationLabelLogic = kea<observationLabelLogicType>([},rate: async ({ isCorrect, feedback }) => {+ cache.lastSentLabel = { is_correct: isCorrect, feedback }cache.labelEpoch = (cache.labelEpoch ?? 0) + 1const epoch = cache.labelEpochconst teamId = teamLogic.values.currentTeamId@@ -187,6 +202,7 @@ export const observationLabelLogic = kea<observationLabelLogicType>([},clearRating: async () => {+ cache.lastSentLabel = nullcache.labelEpoch = (cache.labelEpoch ?? 0) + 1const epoch = cache.labelEpochconst teamId = teamLogic.values.currentTeamId@@ -209,4 +225,17 @@ export const observationLabelLogic = kea<observationLabelLogicType>([}},})),+ // Unmounting cancels the pending autosave, so a note typed just before leaving the page saves here instead.+ beforeUnmount(({ values, props, cache }) => {+ // A rating still in flight has not reached `label` yet, and a save carrying the older rating could overwrite it.+ const latest: ReplayObservationLabelApi | null =+ cache.lastSentLabel === undefined ? values.label : cache.lastSentLabel+ const teamId = teamLogic.values.currentTeamId+ if (latest && teamId && normalizeFeedback(latest.feedback) !== normalizeFeedback(values.feedbackDraft)) {+ void visionObservationsLabelCreate(String(teamId), props.observationId, {+ is_correct: latest.is_correct,+ feedback: values.feedbackDraft,+ }).catch(() => lemonToast.error('Failed to save your note'))+ }+ }),])diff --git a/products/replay_vision/frontend/observations/observationSignalReportsLogic.ts b/products/replay_vision/frontend/observations/observationSignalReportsLogic.tsdeleted file mode 100644index 4ec125446761..000000000000--- a/products/replay_vision/frontend/observations/observationSignalReportsLogic.ts+++ /dev/null@@ -1,101 +0,0 @@-import { MakeLogicType, actions, afterMount, kea, key, path, props, reducers } from 'kea'-import { loaders } from 'kea-loaders'-import posthog from 'posthog-js'--import { teamLogic } from 'scenes/teamLogic'--import { visionObservationsSignalReportsList } from '../generated/api'-import { ObservationSignalReportApi } from '../generated/api.schemas'--export interface ObservationSignalReportsLogicProps {- observationId: string-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface observationSignalReportsLogicValues {- signalReports: ObservationSignalReportApi[] | null- signalReportsLoading: boolean- signalReportsUnavailable: boolean-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface observationSignalReportsLogicActions {- loadSignalReports: () => any- loadSignalReportsFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadSignalReportsSuccess: (- signalReports: ObservationSignalReportApi[] | null,- payload?: any- ) => {- signalReports: ObservationSignalReportApi[] | null- payload?: any- }- setSignalReportsUnavailable: () => {- value: true- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface observationSignalReportsLogicMeta {- key: string-}--export type observationSignalReportsLogicType = MakeLogicType<- observationSignalReportsLogicValues,- observationSignalReportsLogicActions,- ObservationSignalReportsLogicProps,- observationSignalReportsLogicMeta->--/** Grouping runs after the scan finishes, so an empty list means "not grouped yet" as much as "never grouped". */-export const observationSignalReportsLogic = kea<observationSignalReportsLogicType>([- path(['products', 'replay_vision', 'frontend', 'observations', 'observationSignalReportsLogic']),- props({} as ObservationSignalReportsLogicProps),- key((props) => props.observationId),-- actions({- setSignalReportsUnavailable: true,- }),-- reducers({- // A failed read must not read as "no reports": the caller may simply lack inbox access.- signalReportsUnavailable: [- false,- {- setSignalReportsUnavailable: () => true,- loadSignalReports: () => false,- },- ],- }),-- loaders(({ props, actions }) => ({- signalReports: [- null as ObservationSignalReportApi[] | null,- {- loadSignalReports: async () => {- const teamId = teamLogic.values.currentTeamId- if (!teamId) {- return null- }- try {- return await visionObservationsSignalReportsList(String(teamId), props.observationId)- } catch (e) {- // Supplementary context on an already-rendered page: fail quiet, don't toast over it.- posthog.captureException(e)- actions.setSignalReportsUnavailable()- return null- }- },- },- ],- })),-- afterMount(({ actions }) => {- actions.loadSignalReports()- }),-])diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsxindex 1e288dddcf2e..6b2874503ad2 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx@@ -2,6 +2,9 @@ import type { Meta, StoryObj } from '@storybook/react'import { FEATURE_FLAGS } from 'lib/constants'import { App } from 'scenes/App'+import recordingEventsJson from 'scenes/session-recordings/__mocks__/recording_events_query'+import { recordingMetaJson } from 'scenes/session-recordings/__mocks__/recording_meta'+import { snapshotsAsJSONLines } from 'scenes/session-recordings/__mocks__/recording_snapshots'import { urls } from 'scenes/urls'import { mswDecorator } from '~/mocks/browser'@@ -820,6 +823,21 @@ const meta: Meta = {'$entry_utm_source','$entry_current_url',]),+ // The observation page embeds the player, so it needs a recording to play.+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) =>+ new URL(request.url).searchParams.get('source') === 'blob_v2'+ ? new Response(snapshotsAsJSONLines())+ : {+ sources: [+ {+ source: 'blob_v2',+ start_timestamp: '2023-08-11T12:03:36.097000Z',+ end_timestamp: '2023-08-11T12:04:52.268000Z',+ blob_key: '0',+ },+ ],+ },+ '/api/environments/:team_id/session_recordings/:id': recordingMetaJson,'/api/projects/:team_id/property_definitions/': ({ request }) => {const type = new URL(request.url).searchParams.get('type')return type === 'person'@@ -829,12 +847,19 @@ const meta: Meta = {},post: {'/api/environments/:team_id/query/:query_kind/': async ({ request }) => {- const body = (await request.json()) as { query?: { query?: string } } | null+ const body = (await request.json()) as { query?: { kind?: string; query?: string } } | null+ if (body?.query?.kind === 'EventsQuery') {+ return recordingEventsJson+ }// The observation page's pinned strip is the only query aliasing its columns this way.return body?.query?.query?.includes('as pinned_0')? { results: [sessionPropertiesRow] }: observationsTrend},+ '/api/projects/:team_id/vision/observations/:id/label/': async ({ request }) => {+ const body = (await request.json()) as { is_correct: boolean; feedback?: string }+ return { is_correct: body.is_correct, feedback: body.feedback ?? '' }+ },'/api/projects/:team_id/vision/scanners/estimate/': estimate,'/api/projects/:team_id/vision/scanners/:scannerId/backfills/estimate/': backfillEstimate,},@@ -1078,6 +1103,109 @@ export const ScorerObservations: StoryObj = {]),}+const observationDetailFor = (+ scannerResponse: ReplayScannerApi,+ id: string,+ output: Record<string, unknown>+): ReplayObservationApi =>+ observation({+ id,+ scanner_id: scannerResponse.id,+ recording_subject_email: '[email protected]',+ distinct_id: 'user_2m1x9d',+ previous_observation_id: '00000000-0000-0000-0000-0000000000b1',+ next_observation_id: '00000000-0000-0000-0000-0000000000b4',+ scanner_snapshot: {+ ...observation().scanner_snapshot!,+ name: scannerResponse.name,+ scanner_type: scannerResponse.scanner_type,+ scanner_config: scannerResponse.scanner_config,+ },+ scanner_result: {+ model_output: { scanner_type: scannerResponse.scanner_type, ...output },+ signals_count: 0,+ verification: null,+ },+ })++const classifierObservationDetail = observationDetailFor(+ classifierOverviewScanner,+ '00000000-0000-0000-0000-0000000000d4',+ {+ tags: ['rage-click', 'slow-load'],+ tags_freeform: ['coupon-confusion'],+ confidence: 0.88,+ reasoning: 'Clicked the disabled submit button repeatedly while the shipping rates loaded.',+ }+)++const scorerObservationDetail = observationDetailFor(scorerOverviewScanner, '00000000-0000-0000-0000-0000000000d5', {+ score: 8.5,+ label: 'Strong buying intent',+ confidence: 0.86,+ reasoning: 'Compared plans, opened billing and invited a teammate.',+})++const observationDetailStory = (detail: ReplayObservationApi): StoryObj => ({+ parameters: { pageUrl: urls.replayVisionObservation(detail.id) },+ decorators: [mswDecorator({ get: { '/api/projects/:team_id/vision/observations/:id/': detail } })],+})++// A scan the model never finished, so the page leads with the failure and a retry instead of a result.+const failedObservationDetail = observation({+ ...monitorObservationDetail,+ id: '00000000-0000-0000-0000-0000000000d6',+ status: 'failed',+ error_reason: 'provider_transient:The model timed out before returning a result.',+ scanner_result: null,+})++export const ObservationDetailFailed: StoryObj = observationDetailStory(failedObservationDetail)++// The session had no screen data to watch, so no model ran and a later retry may still succeed.+const notScannedObservationDetail = observation({+ ...monitorObservationDetail,+ id: '00000000-0000-0000-0000-0000000000d7',+ status: 'ineligible',+ error_reason: 'no_snapshots:The recording has no snapshot data yet.',+ scanner_result: null,+})++// A scan still in progress, so the page shows progress where the result goes.+const runningObservationDetail = observation({+ ...monitorObservationDetail,+ id: '00000000-0000-0000-0000-0000000000d8',+ status: 'running',+ error_reason: '',+ scanner_result: null,+ completed_at: null,+})++export const ObservationDetailNotScanned: StoryObj = observationDetailStory(notScannedObservationDetail)++export const ObservationDetailRunning: StoryObj = {+ ...observationDetailStory(runningObservationDetail),+ // A running scan keeps its progress and status spinners going, so the page never settles for a snapshot.+ tags: ['test-skip'],+}++// The observation outlived its recording, so the player's place explains why and shows the saved frame.+export const ObservationDetailRecordingExpired: StoryObj = {+ parameters: { pageUrl: urls.replayVisionObservation(monitorObservationDetail.id) },+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/vision/observations/:id/': monitorObservationDetail,+ '/api/environments/:team_id/session_recordings/:id': () => [404, { detail: 'Not found.' }],+ },+ }),+ ],+}++export const ObservationDetailClassifier: StoryObj = observationDetailStory(classifierObservationDetail)++export const ObservationDetailScorer: StoryObj = observationDetailStory(scorerObservationDetail)+export const ScannerOnDemand: StoryObj = {parameters: { pageUrl: `${urls.replayVision(summarizerScanner.id)}?tab=run` },}diff --git a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsxindex a0554a382df3..3fb0d0fbd70b 100644--- a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx@@ -609,6 +609,8 @@ function EditorFooter({loading={isSubmitting}disabledReason={saveDisabledReason}onClick={() => (needsConsent ? setConsentRequested(true) : onSave())}+ // The consent popover anchors here, and a popover anchor gets a dropdown chevron unless told otherwise.+ sideIcon={null}data-attr="vision-editor-save"data-ph-capture-attribute-scanner-type={scanner?.scanner_type}>diff --git a/products/replay_vision/frontend/replay_scanners/components/PromptPreview.tsx b/products/replay_vision/frontend/replay_scanners/components/PromptPreview.tsxnew file mode 100644index 000000000000..40ab8f82639b--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/PromptPreview.tsx@@ -0,0 +1,26 @@+import { useState } from 'react'++import { LemonModal } from '@posthog/lemon-ui'++import { ClippedPreview } from './ClippedPreview'++export function PromptPreview({ prompt, dataAttr }: { prompt: string; dataAttr: string }): JSX.Element {+ const [open, setOpen] = useState(false)+ return (+ <div className="bg-surface-secondary border rounded p-2">+ <ClippedPreview+ clip="short"+ buttonLabel="Show full prompt"+ dataAttr={dataAttr}+ onOpenFull={() => setOpen(true)}+ >+ <div className="whitespace-pre-wrap text-sm">{prompt}</div>+ </ClippedPreview>+ <LemonModal isOpen={open} onClose={() => setOpen(false)} title="Prompt" width={720}>+ <div className="whitespace-pre-wrap font-mono text-sm bg-surface-tertiary border rounded p-3">+ {prompt}+ </div>+ </LemonModal>+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsxindex 96248542503b..94dbdc349416 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsx@@ -1,7 +1,6 @@import { useValues } from 'kea'-import { useState } from 'react'-import { LemonButton, LemonModal, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'+import { LemonButton, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { FEATURE_FLAGS } from 'lib/constants'@@ -15,7 +14,7 @@ import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'import { formatCreditCount } from '../../utils/credits'import { replayScannerLogic } from '../replayScannerLogic'import { SCANNER_TYPE_OPTIONS, modelName, modelNamingVariant, scannerTypeLabel } from '../types'-import { ClippedPreview } from './ClippedPreview'+import { PromptPreview } from './PromptPreview'import { ScannerRecordingFilters } from './ScannerRecordingFilters'function EnabledText({ enabled }: { enabled: boolean }): JSX.Element {@@ -25,7 +24,6 @@ function EnabledText({ enabled }: { enabled: boolean }): JSX.Element {export function ScannerSetupCard({ scannerId }: { scannerId: string }): JSX.Element | null {const { scanner, experimentContext } = useValues(replayScannerLogic({ id: scannerId }))const { featureFlags } = useValues(featureFlagLogic)- const [promptOpen, setPromptOpen] = useState(false)if (!scanner) {return null}@@ -73,21 +71,7 @@ export function ScannerSetupCard({ scannerId }: { scannerId: string }): JSX.Elem<LabeledRow label="Prompt">{config.prompt ? (- <div className="bg-surface-secondary border rounded p-2">- <ClippedPreview- clip="short"- buttonLabel="Show full prompt"- dataAttr="vision-setup-show-prompt"- onOpenFull={() => setPromptOpen(true)}- >- <div className="whitespace-pre-wrap text-sm">{config.prompt}</div>- </ClippedPreview>- <LemonModal isOpen={promptOpen} onClose={() => setPromptOpen(false)} title="Prompt" width={720}>- <div className="whitespace-pre-wrap font-mono text-sm bg-surface-tertiary border rounded p-3">- {config.prompt}- </div>- </LemonModal>- </div>+ <PromptPreview prompt={config.prompt} dataAttr="vision-setup-show-prompt" />) : (<span className="text-muted">—</span>)}diff --git a/products/replay_vision/frontend/utils/observation.ts b/products/replay_vision/frontend/utils/observation.tsindex bc3e6680eb55..f4d6ea33be38 100644--- a/products/replay_vision/frontend/utils/observation.ts+++ b/products/replay_vision/frontend/utils/observation.ts@@ -41,6 +41,8 @@ export function readConfidence(obs: ReplayObservationApi): number | null {export type MonitorVerdict = 'yes' | 'no' | 'inconclusive'+export const VERDICT_LABEL: Record<MonitorVerdict, string> = { yes: 'Yes', no: 'No', inconclusive: 'Inconclusive' }+export function readVerdict(obs: ReplayObservationApi): MonitorVerdict | null {const raw = readModelOutput(obs)?.verdictreturn raw === 'yes' || raw === 'no' || raw === 'inconclusive' ? raw : null