: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 overview per scanner (#60264)
Hayne Ryud86ec508bbd2
diff --git a/products/replay_vision/frontend/components/FilterPill.tsx b/products/replay_vision/frontend/components/FilterPill.tsxnew file mode 100644index 000000000000..e1c9b74b951f--- /dev/null+++ b/products/replay_vision/frontend/components/FilterPill.tsx@@ -0,0 +1,34 @@+import { LemonButton, LemonButtonWithDropdown, LemonCheckbox } from '@posthog/lemon-ui'++export function FilterPill<T extends string>({+ label,+ options,+ value,+ onChange,+}: {+ label: string+ options: { value: T; label: string }[]+ value: T[]+ onChange: (next: T[]) => void+}): JSX.Element {+ const toggle = (v: T): void => {+ onChange(value.includes(v) ? value.filter((x) => x !== v) : [...value, v])+ }+ return (+ <LemonButtonWithDropdown+ type="secondary"+ size="small"+ dropdown={{+ closeOnClickInside: false,+ overlay: options.map((opt) => (+ <LemonButton key={opt.value} fullWidth onClick={() => toggle(opt.value)}>+ <LemonCheckbox checked={value.includes(opt.value)} className="pointer-events-none mr-2" />+ {opt.label}+ </LemonButton>+ )),+ }}+ >+ {value.length > 0 ? `${label} (${value.length})` : label}+ </LemonButtonWithDropdown>+ )+}diff --git a/products/replay_vision/frontend/components/ObservationCard.tsx b/products/replay_vision/frontend/components/ObservationCard.tsxindex 342bc77f54bf..de4a224da4ef 100644--- a/products/replay_vision/frontend/components/ObservationCard.tsx+++ b/products/replay_vision/frontend/components/ObservationCard.tsx@@ -10,6 +10,7 @@ import {parseIneligibleReason,scannerTypeLabel,} from '../replay_scanners/types'+import { CitationPart, formatSessionOffset, parseCitedText } from '../utils/citations'export function ObservationStatusTag({ status }: { status: ReplayObservationApi['status'] }): JSX.Element {if (status === 'succeeded') {@@ -37,57 +38,37 @@ export function readResult(observation: ReplayObservationApi): Record<string, unreturn output && typeof output === 'object' ? (output as Record<string, unknown>) : null}-// Mirrors backend's `_EVENT_ID_CITATION_RE`; keep in sync.-const EVENT_ID_PATTERN = /\(event_id ([0-9a-f]{16})\)/gi--function formatSessionOffset(ms: number): string {- const totalSeconds = Math.max(0, Math.floor(ms / 1000))- const h = Math.floor(totalSeconds / 3600)- const m = Math.floor((totalSeconds % 3600) / 60)- const s = totalSeconds % 60- if (h > 0) {- return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`- }- return `${m}:${s.toString().padStart(2, '0')}`-}--export function CitedText({ observation, text }: { observation: ReplayObservationApi; text: string }): JSX.Element {- const mapping = (observation.scanner_result?.event_id_mapping ?? {}) as Record<string, unknown>- if (!text || Object.keys(mapping).length === 0) {- return <>{text}</>- }- const sessionId = observation.session_id- const parts: React.ReactNode[] = []- let lastIndex = 0- let chipIndex = 0- EVENT_ID_PATTERN.lastIndex = 0- let match: RegExpExecArray | null- while ((match = EVENT_ID_PATTERN.exec(text)) !== null) {- const [full, hash] = match- const citation = mapping[hash.toLowerCase()] as { uuid?: string; timestamp_ms?: number } | undefined- if (!citation || typeof citation.timestamp_ms !== 'number') {- continue- }- if (match.index > lastIndex) {- parts.push(text.slice(lastIndex, match.index))- }- parts.push(- <Link- key={`evt-${chipIndex++}`}- to={urls.replaySingle(sessionId, {- secondsOffsetFromStart: Math.max(0, Math.floor(citation.timestamp_ms / 1000)),- })}- >- <IconRewindPlay className="inline-block align-text-bottom mr-0.5" />- <span className="font-mono">{formatSessionOffset(citation.timestamp_ms)}</span>- </Link>- )- lastIndex = match.index + full.length- }- if (lastIndex < text.length) {- parts.push(text.slice(lastIndex))- }- return <>{parts}</>+/** Dumb renderer for parsed citation parts. Pass `onSeek` to make citations interactive; omit for plain-text timestamps. */+export function CitedText({+ parts,+ onSeek,+}: {+ parts: CitationPart[]+ onSeek?: (timestampMs: number) => void+}): JSX.Element {+ return (+ <>+ {parts.map((part, i) => {+ if (part.type === 'text') {+ return <span key={i}>{part.value}</span>+ }+ const label = formatSessionOffset(part.timestampMs)+ if (onSeek) {+ return (+ <Link key={i} onClick={() => onSeek(part.timestampMs)}>+ <IconRewindPlay className="inline-block align-text-bottom mr-0.5" />+ <span className="font-mono">{label}</span>+ </Link>+ )+ }+ return (+ <span key={i} className="text-muted font-mono">+ {label}+ </span>+ )+ })}+ </>+ )}export function readConfig(snapshot: ScannerSnapshotApi | null): Record<string, unknown> {@@ -99,10 +80,16 @@ export function ObservationPrimaryOutput({observation,compact = false,showPrompt = true,+ onSeek,+ expandSummary = false,}: {observation: ReplayObservationApicompact?: booleanshowPrompt?: boolean+ /** Called with timestamp_ms when a citation chip is clicked. If omitted, citations render as plain text. */+ onSeek?: (timestampMs: number) => void+ /** When true (dock/detail), summarizer body wraps in full; when false (table), single-line truncate. */+ expandSummary?: boolean}): JSX.Element | null {const snapshot = observation.scanner_snapshotconst result = readResult(observation)@@ -112,6 +99,7 @@ export function ObservationPrimaryOutput({const scannerType = snapshot.scanner_typeconst config = readConfig(snapshot)const prompt = showPrompt && typeof config.prompt === 'string' ? config.prompt : null+ const summaryClass = expandSummary ? 'text-sm whitespace-pre-wrap' : compact ? 'text-sm truncate' : 'text-sm'const bodyClass = compact ? 'text-sm truncate' : 'text-sm'const promptClass = 'text-xs text-muted'@@ -134,8 +122,11 @@ export function ObservationPrimaryOutput({<div className="flex flex-col gap-1">{title && <span className="font-semibold text-sm">{title}</span>}{summary && (- <span className={bodyClass}>- {compact ? summary : <CitedText observation={observation} text={summary} />}+ <span className={summaryClass}>+ <CitedText+ parts={parseCitedText(summary, observation.scanner_result?.event_id_mapping)}+ onSeek={onSeek}+ /></span>)}</div>@@ -146,37 +137,68 @@ export function ObservationPrimaryOutput({const fixedTags = Array.isArray(result.tags) ? (result.tags as string[]) : []const freeformTags = Array.isArray(result.tags_freeform) ? (result.tags_freeform as string[]) : []const empty = fixedTags.length === 0 && freeformTags.length === 0- return (- <div className="flex flex-col gap-1">- <div className="flex flex-wrap gap-1">- {empty ? (- <span className="text-muted text-sm">No tags</span>- ) : (- <>- {fixedTags.map((tag) => (- <LemonTag- key={`fixed-${tag}`}- size="medium"- type="option"- title="From the configured tag list"- >- {tag}- </LemonTag>- ))}- {freeformTags.map((tag) => (- <LemonTag- key={`freeform-${tag}`}- size="medium"- type="default"- icon={<IconSparkles />}- title="Free-form tag from the model"- >- {tag}- </LemonTag>- ))}- </>- )}+ const renderFixed = (): JSX.Element[] =>+ fixedTags.map((tag) => (+ <LemonTag key={`fixed-${tag}`} size="medium" type="option" title="From the configured tag list">+ {tag}+ </LemonTag>+ ))+ const renderFreeform = (): JSX.Element[] =>+ freeformTags.map((tag) => (+ <LemonTag+ key={`freeform-${tag}`}+ size="medium"+ type="default"+ icon={<IconSparkles />}+ title="Free-form tag from the model"+ >+ {tag}+ </LemonTag>+ ))+ if (compact) {+ return (+ <div className="flex flex-col gap-1">+ <div className="flex flex-wrap gap-1">+ {empty ? (+ <span className="text-muted text-sm">No tags</span>+ ) : (+ <>+ {renderFixed()}+ {renderFreeform()}+ </>+ )}+ </div>+ {prompt && <span className={promptClass}>{prompt}</span>}+ </div>+ )+ }+ if (empty) {+ return (+ <div className="flex flex-col gap-1">+ <span className="text-muted text-sm">No tags</span>+ {prompt && <span className={promptClass}>{prompt}</span>}</div>+ )+ }+ return (+ <div className="flex flex-col gap-3">+ {fixedTags.length > 0 && (+ <div className="flex flex-col gap-1.5">+ <div className="text-xs font-medium uppercase tracking-wide text-muted">Fixed</div>+ <p className="text-xs text-muted m-0">Tags from the scanner's configured list.</p>+ <div className="flex flex-wrap gap-1">{renderFixed()}</div>+ </div>+ )}+ {freeformTags.length > 0 && (+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center gap-1 text-xs font-medium uppercase tracking-wide text-muted">+ <IconSparkles className="text-sm" />+ <span>Freeform</span>+ </div>+ <p className="text-xs text-muted m-0">Emitted by the model outside the configured tags.</p>+ <div className="flex flex-wrap gap-1">{renderFreeform()}</div>+ </div>+ )}{prompt && <span className={promptClass}>{prompt}</span>}</div>)@@ -184,18 +206,19 @@ export function ObservationPrimaryOutput({if (scannerType === 'scorer') {const score = typeof result.score === 'number' ? result.score : null- const label = typeof result.label === 'string' ? result.label : null+ const resultLabel = typeof result.label === 'string' ? result.label : nullconst scale =config.scale && typeof config.scale === 'object' ? (config.scale as Record<string, unknown>) : nullconst scaleMax = scale && typeof scale.max === 'number' ? scale.max : nullconst scaleLabel = scale && typeof scale.label === 'string' ? scale.label : null+ // Prefer the per-observation label (specific); fall back to the configured scale label (axis name).+ const displayLabel = resultLabel ?? scaleLabelreturn (<div className="flex flex-col gap-1"><span className="text-sm"><span className="font-semibold text-base">{score ?? '—'}</span>{scaleMax !== null && <span className="text-muted"> / {scaleMax}</span>}- {scaleLabel && <span className="text-muted text-xs"> {scaleLabel}</span>}- {label && <span className="text-muted"> — {label}</span>}+ {displayLabel && <span className="text-muted"> — {displayLabel}</span>}</span>{prompt && <span className={promptClass}>{prompt}</span>}</div>@@ -324,7 +347,13 @@ function ObservationProgress({ observation }: { observation: ReplayObservationAp)}-export function ObservationDockCard({ observation }: { observation: ReplayObservationApi }): JSX.Element {+export function ObservationDockCard({+ observation,+ onSeek,+}: {+ observation: ReplayObservationApi+ onSeek?: (timestampMs: number) => void+}): JSX.Element {const snapshot = observation.scanner_snapshotconst scannerType = snapshot?.scanner_typeconst result = readResult(observation)@@ -351,7 +380,7 @@ export function ObservationDockCard({ observation }: { observation: ReplayObserv)}{observation.status === 'succeeded' && snapshot && result && (- <ObservationPrimaryOutput observation={observation} compact />+ <ObservationPrimaryOutput observation={observation} compact onSeek={onSeek} expandSummary />)}{(observation.status === 'pending' || observation.status === 'running') && (diff --git a/products/replay_vision/frontend/components/ObservationsDock.tsx b/products/replay_vision/frontend/components/ObservationsDock.tsxindex 732b1f9456b2..75e6f74239ba 100644--- a/products/replay_vision/frontend/components/ObservationsDock.tsx+++ b/products/replay_vision/frontend/components/ObservationsDock.tsx@@ -96,6 +96,12 @@ function ObservationsDockContent({ sessionId }: { sessionId: string }): JSX.Elemconst logic = observationsDockLogic({ sessionId })const { observations, observationsLoading, dockOpen } = useValues(logic)const { setDockOpen } = useActions(logic)+ // sessionRecordingPlayerLogic is keyed by playerKey+sessionRecordingId; seek the exact mounted+ // player by its bound props rather than a propless default instance.+ const { logicProps } = useValues(sessionRecordingPlayerLogic)+ const seekToTime = (ms: number): void => {+ sessionRecordingPlayerLogic.findMounted(logicProps)?.actions.seekToTime(ms)+ }const dockRef = useRef<HTMLDivElement>(null)const resizerProps: ResizerLogicProps = {@@ -151,7 +157,7 @@ function ObservationsDockContent({ sessionId }: { sessionId: string }): JSX.Elem</div>) : (observations.map((observation) => (- <ObservationDockCard key={observation.id} observation={observation} />+ <ObservationDockCard key={observation.id} observation={observation} onSeek={seekToTime} />)))}</div>diff --git a/products/replay_vision/frontend/logics/observationsDockLogic.ts b/products/replay_vision/frontend/logics/observationsDockLogic.tsindex 29470f96e6cc..7ad82177358a 100644--- a/products/replay_vision/frontend/logics/observationsDockLogic.ts+++ b/products/replay_vision/frontend/logics/observationsDockLogic.ts@@ -151,6 +151,13 @@ export const observationsDockLogic = kea<observationsDockLogicType>([actions.observeFailure()return}+ // Backend keys the workflow id on (scanner, session); re-triggering the same pair silently no-ops.+ if (values.observations.some((o) => o.scanner_id === scannerId)) {+ lemonToast.info('This scanner has already been run on this recording.')+ actions.observeFailure()+ actions.setDockOpen(true)+ return+ }try {await visionScannersObserveCreate(String(teamId), scannerId, { session_id: props.sessionId })lemonToast.success('Observation started')diff --git a/products/replay_vision/frontend/observations/ReplayObservation.tsx b/products/replay_vision/frontend/observations/ReplayObservation.tsxindex 99f58b0d66b2..6e652f0ebb97 100644--- a/products/replay_vision/frontend/observations/ReplayObservation.tsx+++ b/products/replay_vision/frontend/observations/ReplayObservation.tsx@@ -8,7 +8,10 @@ import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { SceneExport } from 'scenes/sceneTypes'import { SessionRecordingPlayer } from 'scenes/session-recordings/player/SessionRecordingPlayer'-import { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'+import {+ SessionRecordingPlayerMode,+ sessionRecordingPlayerLogic,+} from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'@@ -26,6 +29,7 @@ import {readResult,} from '../components/ObservationCard'import { modelLabel, scannerTypeLabel } from '../replay_scanners/types'+import { parseCitedText } from '../utils/citations'import { replayObservationLogic } from './replayObservationLogic'import { ReplayObservationSceneLogicProps, replayObservationSceneLogic } from './replayObservationSceneLogic'@@ -71,11 +75,6 @@ export function ReplayObservationSceneComponent({ tabId }: { tabId: string }): Jconst triggerLabel = observation.triggered_by === 'on_demand' ? 'On demand' : 'Schedule'const snapshotConfig = readConfig(snapshot ?? null)const prompt = typeof snapshotConfig.prompt === 'string' ? snapshotConfig.prompt : null- const configuredTags =- scannerType === 'classifier' && Array.isArray(snapshotConfig.tags)- ? (snapshotConfig.tags as unknown[]).filter((t): t is string => typeof t === 'string')- : []- const multiLabel = scannerType === 'classifier' ? snapshotConfig.multi_label === true : falseconst summarizerLength =scannerType === 'summarizer' && typeof snapshotConfig.length === 'string' ? snapshotConfig.length : nullconst durationMs =@@ -91,6 +90,15 @@ export function ReplayObservationSceneComponent({ tabId }: { tabId: string }): J: `${Math.floor(durationMs / 60_000)}m ${Math.floor((durationMs % 60_000) / 1000)}s`: null+ const seekEmbeddedPlayer = (ms: number): void => {+ sessionRecordingPlayerLogic+ .findMounted({+ playerKey: `vision-observation-${observation.id}`,+ sessionRecordingId: observation.session_id,+ })+ ?.actions.seekToTime(ms)+ }+return (<SceneContent><SceneTitleSection@@ -99,7 +107,7 @@ export function ReplayObservationSceneComponent({ tabId }: { tabId: string }): JresourceType={{ type: 'replay_vision' }}/>- <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">+ <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"><div className="flex items-center justify-between gap-2"><div className="flex items-center gap-2">@@ -122,17 +130,11 @@ export function ReplayObservationSceneComponent({ tabId }: { tabId: string }): J{prompt && scannerType !== 'summarizer' && (<p className="text-sm text-default m-0 leading-snug">{prompt}</p>)}- <ObservationPrimaryOutput observation={observation} showPrompt={false} />- {configuredTags.length > 0 && (- <div className="flex flex-wrap items-center gap-1 text-xs text-muted">- <span>Allowed tags{multiLabel ? ' (multi-label)' : ''}:</span>- {configuredTags.map((tag) => (- <LemonTag key={tag} type="option" size="small">- {tag}- </LemonTag>- ))}- </div>- )}+ <ObservationPrimaryOutput+ observation={observation}+ showPrompt={false}+ onSeek={seekEmbeddedPlayer}+ /></div>)}@@ -143,16 +145,21 @@ export function ReplayObservationSceneComponent({ tabId }: { tabId: string }): J)}</section>- <section className="border rounded p-4 bg-surface-primary space-y-2">- <div className="text-sm font-medium">Reasoning</div>- {reasoning ? (- <p className="text-sm whitespace-pre-wrap m-0">- <CitedText observation={observation} text={reasoning} />- </p>- ) : (- <p className="text-muted text-sm m-0">No reasoning provided.</p>- )}- </section>+ {scannerType !== 'summarizer' && (+ <section className="border rounded p-4 bg-surface-primary space-y-2">+ <div className="text-sm font-medium">Reasoning</div>+ {reasoning ? (+ <p className="text-sm whitespace-pre-wrap m-0">+ <CitedText+ parts={parseCitedText(reasoning, observation.scanner_result?.event_id_mapping)}+ onSeek={seekEmbeddedPlayer}+ />+ </p>+ ) : (+ <p className="text-muted text-sm m-0">No reasoning provided.</p>+ )}+ </section>+ )}</div><section className="border rounded p-4 bg-surface-primary">diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsxindex 53c51746413b..76a67298568e 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx@@ -2,16 +2,7 @@ import { useActions, useValues } from 'kea'import { router } from 'kea-router'import { IconCopy, IconEye, IconPencil, IconPlus, IconSearch, IconTrash } from '@posthog/icons'-import {- LemonButton,- LemonButtonWithDropdown,- LemonCheckbox,- LemonInput,- LemonSwitch,- LemonTable,- LemonTag,- Link,-} from '@posthog/lemon-ui'+import { LemonButton, LemonInput, LemonSwitch, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'import { XRayHog } from 'lib/components/hedgehogs'@@ -27,6 +18,7 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'import { AccessControlLevel, AccessControlResourceType } from '~/types'+import { FilterPill } from '../components/FilterPill'import { VisionQuotaMeter } from './components/VisionQuotaMeter'import { replayScannersLogic } from './replayScannersLogic'import { ENABLED_OPTIONS, EnabledFilter, SCANNER_TYPE_OPTIONS, ScannerType, ReplayScanner } from './types'@@ -42,39 +34,6 @@ export const scene: SceneExport = {productKey: ProductKey.REPLAY_VISION,}-function FilterPill<T extends string>({- label,- options,- value,- onChange,-}: {- label: string- options: { value: T; label: string }[]- value: T[]- onChange: (next: T[]) => void-}): JSX.Element {- const toggle = (v: T): void => {- onChange(value.includes(v) ? value.filter((x) => x !== v) : [...value, v])- }- return (- <LemonButtonWithDropdown- type="secondary"- size="small"- dropdown={{- closeOnClickInside: false,- overlay: options.map((opt) => (- <LemonButton key={opt.value} fullWidth onClick={() => toggle(opt.value)}>- <LemonCheckbox checked={value.includes(opt.value)} className="pointer-events-none mr-2" />- {opt.label}- </LemonButton>- )),- }}- >- {value.length > 0 ? `${label} (${value.length})` : label}- </LemonButtonWithDropdown>- )-}-export function ReplayScannersScene(): JSX.Element {const { filteredScanners, scanners, scannersLoading, search, enabledFilter, scannerTypeFilter, hasActiveFilters } =useValues(replayScannersLogic)diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerInsightsChart.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerInsightsChart.tsxnew file mode 100644index 000000000000..a0dbc4946c4e--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerInsightsChart.tsx@@ -0,0 +1,187 @@+import { useActions, useValues } from 'kea'++import { DateFilter } from 'lib/components/DateFilter/DateFilter'++import { Query } from '~/queries/Query/Query'+import { InsightVizNode, NodeKind, ProductKey, TrendsQuery } from '~/queries/schema/schema-general'+import {+ AnyPropertyFilter,+ BaseMathType,+ ChartDisplayType,+ PropertyFilterType,+ PropertyMathType,+ PropertyOperator,+} from '~/types'++import { replayScannerLogic } from '../replayScannerLogic'+import { ScannerType } from '../types'++const RECORDING_OBSERVED_EVENT = '$recording_observed'+const COLLECTION_ID = 'replay-vision-scanner-insights'++function scannerIdFilter(scannerId: string): AnyPropertyFilter {+ return {+ type: PropertyFilterType.Event,+ key: 'scanner_id',+ operator: PropertyOperator.Exact,+ value: scannerId,+ }+}++function buildQuery(+ scannerId: string,+ scannerType: ScannerType,+ dateFrom: string | null,+ dateTo: string | null+): TrendsQuery {+ const base = scannerIdFilter(scannerId)+ const dateRange = { date_from: dateFrom, date_to: dateTo }+ if (scannerType === 'monitor') {+ return {+ kind: NodeKind.TrendsQuery,+ series: [+ {+ kind: NodeKind.EventsNode,+ event: RECORDING_OBSERVED_EVENT,+ math: BaseMathType.TotalCount,+ name: 'Yes verdicts',+ properties: [+ base,+ {+ type: PropertyFilterType.Event,+ key: 'scanner_output_verdict',+ operator: PropertyOperator.Exact,+ value: 'true',+ },+ ],+ },+ {+ kind: NodeKind.EventsNode,+ event: RECORDING_OBSERVED_EVENT,+ math: BaseMathType.TotalCount,+ name: 'Total observations',+ properties: [base],+ },+ ],+ trendsFilter: { display: ChartDisplayType.ActionsLineGraph, formula: 'A / B * 100' },+ dateRange,+ interval: 'day',+ }+ }+ if (scannerType === 'classifier') {+ return {+ kind: NodeKind.TrendsQuery,+ series: [+ {+ kind: NodeKind.EventsNode,+ event: RECORDING_OBSERVED_EVENT,+ math: BaseMathType.TotalCount,+ name: 'Observations',+ properties: [base],+ },+ ],+ breakdownFilter: {+ // Union fixed + freeform tags; arrayJoin gives each tag its own series.+ breakdown:+ "arrayJoin(arrayConcat(JSONExtract(ifNull(properties.scanner_output_tags, '[]'), 'Array(String)'), JSONExtract(ifNull(properties.scanner_output_tags_freeform, '[]'), 'Array(String)')))",+ breakdown_type: 'hogql',+ },+ trendsFilter: { display: ChartDisplayType.ActionsAreaGraph },+ dateRange,+ interval: 'day',+ }+ }+ if (scannerType === 'scorer') {+ const scoreSeries = (math: PropertyMathType, name: string): TrendsQuery['series'][number] => ({+ kind: NodeKind.EventsNode,+ event: RECORDING_OBSERVED_EVENT,+ math,+ math_property: 'scanner_output_score',+ name,+ properties: [base],+ })+ return {+ kind: NodeKind.TrendsQuery,+ series: [+ scoreSeries(PropertyMathType.Median, 'p50'),+ scoreSeries(PropertyMathType.P90, 'p90'),+ scoreSeries(PropertyMathType.Average, 'avg'),+ ],+ trendsFilter: { display: ChartDisplayType.ActionsLineGraph },+ dateRange,+ interval: 'day',+ }+ }+ return {+ kind: NodeKind.TrendsQuery,+ series: [+ {+ kind: NodeKind.EventsNode,+ event: RECORDING_OBSERVED_EVENT,+ math: BaseMathType.TotalCount,+ name: 'Observations',+ properties: [base],+ },+ ],+ trendsFilter: { display: ChartDisplayType.ActionsLineGraph },+ dateRange,+ interval: 'day',+ }+}++function chartTitle(scannerType: ScannerType): string {+ if (scannerType === 'monitor') {+ return 'Yes rate (%) over time'+ }+ if (scannerType === 'classifier') {+ return 'Tag mix over time'+ }+ if (scannerType === 'scorer') {+ return 'Score percentiles over time'+ }+ return 'Observations over time'+}++export function ScannerInsightsChart({+ scannerId,+ scannerType,+ tabId,+}: {+ scannerId: string+ scannerType: ScannerType+ tabId: string+}): JSX.Element {+ const { chartDateFrom, chartDateTo } = useValues(replayScannerLogic({ id: scannerId, tabId }))+ const { setChartDateRange } = useActions(replayScannerLogic({ id: scannerId, tabId }))+ // `tags.productKey` is required for ClickHouse query tagging; without it the runner aborts.+ const source: TrendsQuery = {+ ...buildQuery(scannerId, scannerType, chartDateFrom, chartDateTo),+ tags: { productKey: ProductKey.REPLAY_VISION },+ }+ return (+ <div className="border rounded p-4 bg-surface-primary space-y-3">+ <div className="flex items-baseline justify-between gap-2">+ <span className="text-sm font-medium">{chartTitle(scannerType)}</span>+ <DateFilter+ dateFrom={chartDateFrom}+ dateTo={chartDateTo}+ onChange={(from, to) => setChartDateRange(from ?? null, to ?? null)}+ />+ </div>+ <div className="InsightCard h-80">+ <Query+ query={{ kind: NodeKind.InsightVizNode, source } as InsightVizNode}+ readOnly+ embedded+ inSharedMode+ context={{+ insightProps: {+ dashboardItemId: `new-replay-vision-scanner-${scannerId}-chart`,+ dataNodeCollectionId: COLLECTION_ID,+ },+ }}+ />+ </div>+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsxindex 28a664563b1f..348a3d11612d 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx@@ -7,34 +7,83 @@ import { TZLabel } from 'lib/components/TZLabel'import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { urls } from 'scenes/urls'+import { FilterPill } from '../../components/FilterPill'import { ObservationResultSummary, ObservationStatusTag } from '../../components/ObservationCard'import type { ReplayObservationApi } from '../../generated/api.schemas'-import { replayScannerLogic } from '../replayScannerLogic'+import { readScore, readVerdict } from '../../utils/observation'+import {+ ObservationStatusValue,+ ObservationTriggeredByValue,+ ObservationVerdictValue,+ replayScannerLogic,+} from '../replayScannerLogic'+import { ScannerOverview } from './ScannerOverview'++const STATUS_OPTIONS: { value: ObservationStatusValue; label: string }[] = [+ { value: 'succeeded', label: 'Succeeded' },+ { value: 'failed', label: 'Failed' },+ { value: 'ineligible', label: 'Ineligible' },+ { value: 'running', label: 'Running' },+ { value: 'pending', label: 'Pending' },+]++const TRIGGERED_BY_OPTIONS: { value: ObservationTriggeredByValue; label: string }[] = [+ { value: 'on_demand', label: 'On demand' },+ { value: 'schedule', label: 'Schedule' },+]++const VERDICT_OPTIONS: { value: ObservationVerdictValue; label: string }[] = [+ { value: 'yes', label: 'Yes' },+ { value: 'no', label: 'No' },+]++// Nulls (no model output) sort last regardless of direction.+function compareByScore(a: ReplayObservationApi, b: ReplayObservationApi): number {+ const sa = readScore(a)+ const sb = readScore(b)+ if (sa === null || sb === null) {+ return sa === sb ? 0 : sa === null ? 1 : -1+ }+ return sa - sb+}++function compareByVerdict(a: ReplayObservationApi, b: ReplayObservationApi): number {+ const va = readVerdict(a)+ const vb = readVerdict(b)+ if (va === vb) {+ return 0+ }+ if (va === null || vb === null) {+ return va === null ? 1 : -1+ }+ return va ? -1 : 1+}export function ScannerObservationsTable({ scannerId, tabId }: { scannerId: string; tabId: string }): JSX.Element {const logic = replayScannerLogic({ id: scannerId, tabId })- const { observations, observationsLoading, hasObservationsInFlight } = useValues(logic)- const { loadObservations } = useActions(logic)-- const stats = observations.reduce(- (acc, o) => {- acc.total += 1- if (o.status === 'succeeded') {- acc.succeeded += 1- } else if (o.status === 'failed') {- acc.failed += 1- } else if (o.status === 'ineligible') {- acc.ineligible += 1- } else {- acc.inFlight += 1- }- return acc- },- { total: 0, succeeded: 0, failed: 0, ineligible: 0, inFlight: 0 }- )- // Success rate excludes ineligible — those weren't scanner failures, they were skipped at the gate.- const scored = stats.succeeded + stats.failed- const successRate = scored > 0 ? Math.round((stats.succeeded / scored) * 100) : null+ const {+ observationsLoading,+ hasObservationsInFlight,+ filteredObservations,+ observationStatusFilter,+ observationTriggeredByFilter,+ observationVerdictFilter,+ observationTagFilter,+ hasActiveObservationFilters,+ availableTags,+ observationStats,+ scanner,+ } = useValues(logic)+ const {+ loadObservations,+ setObservationStatusFilter,+ setObservationTriggeredByFilter,+ setObservationVerdictFilter,+ setObservationTagFilter,+ clearObservationFilters,+ } = useActions(logic)+ const scannerType = scanner?.scanner_type+ const tagFilterOptions = availableTags.map((tag) => ({ value: tag, label: tag }))const columns: LemonTableColumns<ReplayObservationApi> = [{@@ -63,6 +112,8 @@ export function ScannerObservationsTable({ scannerId, tabId }: { scannerId: stri<ObservationResultSummary observation={obs} /></div>),+ sorter:+ scannerType === 'scorer' ? compareByScore : scannerType === 'monitor' ? compareByVerdict : undefined,},{title: 'Triggered by',@@ -99,38 +150,41 @@ export function ScannerObservationsTable({ scannerId, tabId }: { scannerId: strireturn (<div className="space-y-4">+ <ScannerOverview scannerId={scannerId} tabId={tabId} /><div className="flex items-start justify-between gap-4"><p className="text-muted text-sm m-0">Past applications of this scanner to session recordings. Each row is one observation.</p><div className="flex items-center gap-4">- {stats.total > 0 && (+ {observationStats.total > 0 && (<div className="flex gap-4 text-sm"><div className="text-center">- <div className="font-semibold text-lg">{stats.total}</div>+ <div className="font-semibold text-lg">{observationStats.total}</div><div className="text-muted">Total</div></div>- {successRate !== null && (+ {observationStats.successRate !== null && (<div className="text-center">- <div className="font-semibold text-lg text-success">{successRate}%</div>+ <div className="font-semibold text-lg text-success">+ {observationStats.successRate}%+ </div><div className="text-muted">Success rate</div></div>)}- {stats.failed > 0 && (+ {observationStats.failed > 0 && (<div className="text-center">- <div className="font-semibold text-lg text-danger">{stats.failed}</div>+ <div className="font-semibold text-lg text-danger">{observationStats.failed}</div><div className="text-muted">Failed</div></div>)}- {stats.ineligible > 0 && (+ {observationStats.ineligible > 0 && (<div className="text-center">- <div className="font-semibold text-lg">{stats.ineligible}</div>+ <div className="font-semibold text-lg">{observationStats.ineligible}</div><div className="text-muted">Ineligible</div></div>)}- {stats.inFlight > 0 && (+ {observationStats.inFlight > 0 && (<div className="text-center">- <div className="font-semibold text-lg">{stats.inFlight}</div>+ <div className="font-semibold text-lg">{observationStats.inFlight}</div><div className="text-muted">In flight</div></div>)}@@ -155,17 +209,55 @@ export function ScannerObservationsTable({ scannerId, tabId }: { scannerId: stri</Tooltip></div></div>+ {observationStats.total > 0 && (+ <div className="flex flex-wrap items-center gap-2">+ <FilterPill<ObservationStatusValue>+ label="Status"+ options={STATUS_OPTIONS}+ value={observationStatusFilter}+ onChange={setObservationStatusFilter}+ />+ <FilterPill<ObservationTriggeredByValue>+ label="Triggered by"+ options={TRIGGERED_BY_OPTIONS}+ value={observationTriggeredByFilter}+ onChange={setObservationTriggeredByFilter}+ />+ {scannerType === 'monitor' && (+ <FilterPill<ObservationVerdictValue>+ label="Verdict"+ options={VERDICT_OPTIONS}+ value={observationVerdictFilter}+ onChange={setObservationVerdictFilter}+ />+ )}+ {scannerType === 'classifier' && tagFilterOptions.length > 0 && (+ <FilterPill<string>+ label="Tag"+ options={tagFilterOptions}+ value={observationTagFilter}+ onChange={setObservationTagFilter}+ />+ )}+ {hasActiveObservationFilters && (+ <LemonButton type="tertiary" size="small" onClick={() => clearObservationFilters()}>+ Clear filters+ </LemonButton>+ )}+ </div>+ )}<LemonTablecolumns={columns}- dataSource={observations}+ dataSource={filteredObservations}loading={observationsLoading}rowKey="id"pagination={{ pageSize: 50 }}nouns={['observation', 'observations']}emptyState={<div className="p-6 text-center text-muted">- No observations yet. Observations appear here once the scanner runs on a schedule, or when you- observe a recording from the session replay page.+ {hasActiveObservationFilters+ ? 'No observations match your filters.'+ : 'No observations yet. Observations appear here once the scanner runs on a schedule, or when you observe a recording from the session replay page.'}</div>}/>diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsxnew file mode 100644index 000000000000..f3f5d3554497--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx@@ -0,0 +1,166 @@+import { useValues } from 'kea'+import { useMemo } from 'react'++import { LemonTag } from '@posthog/lemon-ui'++import { buildTheme } from 'lib/charts/utils/theme'+import { BoxPlot } from 'lib/hog-charts'+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'++import { replayScannerLogic } from '../replayScannerLogic'+import { ScannerType } from '../types'+import { ScannerInsightsChart } from './ScannerInsightsChart'++function OverviewPanel({+ title,+ subtitle,+ children,+}: {+ title: string+ subtitle?: React.ReactNode+ children: React.ReactNode+}): JSX.Element {+ return (+ <div className="border rounded p-4 bg-surface-primary space-y-3">+ <div className="flex items-baseline justify-between gap-2">+ <span className="text-sm font-medium">{title}</span>+ {subtitle && <span className="text-xs text-muted tabular-nums">{subtitle}</span>}+ </div>+ {children}+ </div>+ )+}++function MonitorOverview({ scannerId, tabId }: { scannerId: string; tabId: string }): JSX.Element | null {+ const { monitorStats } = useValues(replayScannerLogic({ id: scannerId, tabId }))+ const { yesTotal, noTotal } = monitorStats+ const total = yesTotal + noTotal+ if (total === 0) {+ return null+ }+ const yesPct = Math.round((yesTotal / total) * 100)++ return (+ <OverviewPanel title="Verdict mix" subtitle={`${total} verdict${total === 1 ? '' : 's'}`}>+ <LemonProgress percent={yesPct} />+ <div className="flex items-center gap-4 text-sm">+ <span className="flex items-center gap-2">+ <LemonTag type="success">Yes</LemonTag>+ <span className="tabular-nums">+ {yesTotal} ({yesPct}%)+ </span>+ </span>+ <span className="flex items-center gap-2">+ <LemonTag type="default">No</LemonTag>+ <span className="tabular-nums">+ {noTotal} ({100 - yesPct}%)+ </span>+ </span>+ </div>+ </OverviewPanel>+ )+}++function ClassifierOverview({ scannerId, tabId }: { scannerId: string; tabId: string }): JSX.Element | null {+ const { classifierTagStats } = useValues(replayScannerLogic({ id: scannerId, tabId }))+ const { fixedRanked, freeformRanked, totalWithTags } = classifierTagStats+ if (totalWithTags === 0) {+ return null+ }++ const renderRanked = (ranked: [string, number][], emptyMessage: string): JSX.Element => {+ if (ranked.length === 0) {+ return <div className="text-muted text-sm">{emptyMessage}</div>+ }+ const maxCount = ranked[0][1]+ return (+ <div className="space-y-1.5">+ {ranked.map(([tag, count]) => (+ <div key={tag} className="flex items-center gap-2">+ <LemonTag type="option" className="shrink-0">+ {tag}+ </LemonTag>+ <LemonProgress percent={Math.round((count / maxCount) * 100)} />+ <span className="text-xs text-muted tabular-nums w-8 text-right">{count}</span>+ </div>+ ))}+ </div>+ )+ }++ return (+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">+ <OverviewPanel title="Top fixed tags" subtitle="from configured vocabulary">+ {renderRanked(fixedRanked, 'No fixed-vocabulary tags emitted yet.')}+ </OverviewPanel>++ <OverviewPanel title="Top freeform tags" subtitle="outside configured vocabulary">+ {renderRanked(freeformRanked, 'No freeform tags emitted.')}+ </OverviewPanel>+ </div>+ )+}++function ScorerOverview({ scannerId, tabId }: { scannerId: string; tabId: string }): JSX.Element | null {+ const { scorerScores, scorerSummary } = useValues(replayScannerLogic({ id: scannerId, tabId }))+ const theme = useMemo(() => buildTheme(), [])+ if (!scorerSummary) {+ return null+ }+ return (+ <OverviewPanel title="Score distribution" subtitle={`${scorerScores.length} scored`}>+ <div className="h-40 flex flex-col">+ <BoxPlot+ labels={['Scores']}+ series={[{ key: 'scores', label: 'Scores', color: theme.colors[0], data: [scorerSummary] }]}+ config={{ showGrid: false }}+ theme={theme}+ />+ </div>+ <div className="flex justify-between gap-4 text-xs text-muted tabular-nums pt-1 border-t">+ <span>min {scorerSummary.min.toFixed(1)}</span>+ <span>median {scorerSummary.median.toFixed(1)}</span>+ <span>avg {scorerSummary.mean.toFixed(1)}</span>+ <span>max {scorerSummary.max.toFixed(1)}</span>+ </div>+ </OverviewPanel>+ )+}++export function ScannerOverview({ scannerId, tabId }: { scannerId: string; tabId: string }): JSX.Element | null {+ const { scanner, coverageStats } = useValues(replayScannerLogic({ id: scannerId, tabId }))+ if (!scanner) {+ return null+ }+ const scannerType: ScannerType = scanner.scanner_type+ // Summarizer panel deferred to the Max chat follow-up.+ const typeOverview =+ scannerType === 'monitor' ? (+ <MonitorOverview scannerId={scannerId} tabId={tabId} />+ ) : scannerType === 'classifier' ? (+ <ClassifierOverview scannerId={scannerId} tabId={tabId} />+ ) : scannerType === 'scorer' ? (+ <ScorerOverview scannerId={scannerId} tabId={tabId} />+ ) : null+ if (!typeOverview && scannerType !== 'summarizer') {+ return null+ }+ const showChart = scannerType !== 'summarizer'+ const showCoverage = coverageStats.totalSessions > 0+ if (!showCoverage && !showChart && !typeOverview) {+ return null+ }+ return (+ <div className="space-y-4">+ {showCoverage && (+ <div className="text-xs text-muted tabular-nums">+ Scanned <span className="font-semibold text-default">{coverageStats.recentSessions}</span> session+ {coverageStats.recentSessions === 1 ? '' : 's'} in the last {coverageStats.recentDays} days ·{' '}+ <span className="font-semibold text-default">{coverageStats.totalSessions}</span> total+ </div>+ )}+ {showChart && <ScannerInsightsChart scannerId={scannerId} scannerType={scannerType} tabId={tabId} />}+ {typeOverview}+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex 8ae2938466af..2cdec797491a 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -19,6 +19,7 @@ import {} from '../generated/api'import type { ReplayObservationApi } from '../generated/api.schemas'import { scheduleObservationPoll } from '../logics/observationPolling'+import { readFixedTags, readFreeformTags, readModelOutput, readTags, readVerdict } from '../utils/observation'import type { replayScannerLogicType } from './replayScannerLogicType'import {DEFAULT_MODEL,@@ -36,6 +37,20 @@ export interface ReplayScannerLogicProps {tabId: string}+export type ObservationStatusValue = ReplayObservationApi['status']+export type ObservationTriggeredByValue = ReplayObservationApi['triggered_by']+export type ObservationVerdictValue = 'yes' | 'no'++function quantile(sorted: number[], q: number): number {+ if (sorted.length === 1) {+ return sorted[0]+ }+ const pos = (sorted.length - 1) * q+ const lo = Math.floor(pos)+ const hi = Math.ceil(pos)+ return lo === hi ? sorted[lo] : sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo)+}+function defaultConfigForType(scannerType: ScannerType): ScannerConfig {if (scannerType === 'summarizer') {return { prompt: '', length: 'medium' }@@ -89,6 +104,12 @@ export const replayScannerLogic = kea<replayScannerLogicType>([loadObservationsSuccess: (observations: ReplayObservationApi[]) => ({ observations }),loadObservationsFailure: true,deleteScanner: true,+ setObservationStatusFilter: (values: ObservationStatusValue[]) => ({ values }),+ setObservationTriggeredByFilter: (values: ObservationTriggeredByValue[]) => ({ values }),+ setObservationVerdictFilter: (values: ObservationVerdictValue[]) => ({ values }),+ setObservationTagFilter: (values: string[]) => ({ values }),+ clearObservationFilters: true,+ setChartDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),}),forms(({ props }) => ({@@ -167,6 +188,36 @@ export const replayScannerLogic = kea<replayScannerLogicType>([loadObservationsFailure: () => false,},],+ observationStatusFilter: [+ [] as ObservationStatusValue[],+ {+ setObservationStatusFilter: (_, { values }) => values,+ clearObservationFilters: () => [],+ },+ ],+ observationTriggeredByFilter: [+ [] as ObservationTriggeredByValue[],+ {+ setObservationTriggeredByFilter: (_, { values }) => values,+ clearObservationFilters: () => [],+ },+ ],+ observationVerdictFilter: [+ [] as ObservationVerdictValue[],+ {+ setObservationVerdictFilter: (_, { values }) => values,+ clearObservationFilters: () => [],+ },+ ],+ observationTagFilter: [+ [] as string[],+ {+ setObservationTagFilter: (_, { values }) => values,+ clearObservationFilters: () => [],+ },+ ],+ chartDateFrom: ['-14d' as string | null, { setChartDateRange: (_, { dateFrom }) => dateFrom }],+ chartDateTo: [null as string | null, { setChartDateRange: (_, { dateTo }) => dateTo }],}),selectors({@@ -185,6 +236,220 @@ export const replayScannerLogic = kea<replayScannerLogicType>([(observations: ReplayObservationApi[]): boolean =>observations.some((o) => o.status === 'pending' || o.status === 'running'),],+ filteredObservations: [+ (s) => [+ s.observations,+ s.observationStatusFilter,+ s.observationTriggeredByFilter,+ s.observationVerdictFilter,+ s.observationTagFilter,+ ],+ (+ observations: ReplayObservationApi[],+ statusFilter: ObservationStatusValue[],+ triggeredByFilter: ObservationTriggeredByValue[],+ verdictFilter: ObservationVerdictValue[],+ tagFilter: string[]+ ): ReplayObservationApi[] => {+ return observations.filter((o) => {+ if (statusFilter.length > 0 && !statusFilter.includes(o.status)) {+ return false+ }+ if (triggeredByFilter.length > 0 && !triggeredByFilter.includes(o.triggered_by)) {+ return false+ }+ if (verdictFilter.length > 0) {+ const verdict = readVerdict(o)+ if (verdict === null || !verdictFilter.includes(verdict ? 'yes' : 'no')) {+ return false+ }+ }+ if (tagFilter.length > 0) {+ const present = readTags(o)+ if (!tagFilter.some((t) => present.includes(t))) {+ return false+ }+ }+ return true+ })+ },+ ],+ hasActiveObservationFilters: [+ (s) => [+ s.observationStatusFilter,+ s.observationTriggeredByFilter,+ s.observationVerdictFilter,+ s.observationTagFilter,+ ],+ (+ statusFilter: ObservationStatusValue[],+ triggeredByFilter: ObservationTriggeredByValue[],+ verdictFilter: ObservationVerdictValue[],+ tagFilter: string[]+ ): boolean =>+ statusFilter.length > 0 ||+ triggeredByFilter.length > 0 ||+ verdictFilter.length > 0 ||+ tagFilter.length > 0,+ ],+ availableTags: [+ (s) => [s.observations],+ (observations: ReplayObservationApi[]): string[] => {+ const set = new Set<string>()+ for (const obs of observations) {+ for (const tag of readTags(obs)) {+ set.add(tag)+ }+ }+ return Array.from(set).sort()+ },+ ],+ observationStats: [+ (s) => [s.observations],+ (+ observations: ReplayObservationApi[]+ ): {+ total: number+ succeeded: number+ failed: number+ ineligible: number+ inFlight: number+ successRate: number | null+ } => {+ let succeeded = 0+ let failed = 0+ let ineligible = 0+ let inFlight = 0+ for (const o of observations) {+ if (o.status === 'succeeded') {+ succeeded += 1+ } else if (o.status === 'failed') {+ failed += 1+ } else if (o.status === 'ineligible') {+ ineligible += 1+ } else {+ inFlight += 1+ }+ }+ // Success rate excludes ineligible: those were skipped at the gate, not scanner failures.+ const scored = succeeded + failed+ return {+ total: observations.length,+ succeeded,+ failed,+ ineligible,+ inFlight,+ successRate: scored > 0 ? Math.round((succeeded / scored) * 100) : null,+ }+ },+ ],+ succeededObservations: [+ (s) => [s.observations],+ (observations: ReplayObservationApi[]): ReplayObservationApi[] =>+ observations.filter((o) => o.status === 'succeeded'),+ ],+ monitorStats: [+ (s) => [s.succeededObservations],+ (observations: ReplayObservationApi[]): { yesTotal: number; noTotal: number } => {+ let yesTotal = 0+ let noTotal = 0+ for (const obs of observations) {+ const v = readVerdict(obs)+ if (v === true) {+ yesTotal += 1+ } else if (v === false) {+ noTotal += 1+ }+ }+ return { yesTotal, noTotal }+ },+ ],+ classifierTagStats: [+ (s) => [s.succeededObservations],+ (+ observations: ReplayObservationApi[]+ ): {+ fixedRanked: [string, number][]+ freeformRanked: [string, number][]+ totalWithTags: number+ } => {+ const fixedCounts = new Map<string, number>()+ const freeformCounts = new Map<string, number>()+ let totalWithTags = 0+ for (const obs of observations) {+ const fixed = readFixedTags(obs)+ const freeform = readFreeformTags(obs)+ if (fixed.length === 0 && freeform.length === 0) {+ continue+ }+ totalWithTags += 1+ for (const tag of fixed) {+ fixedCounts.set(tag, (fixedCounts.get(tag) ?? 0) + 1)+ }+ for (const tag of freeform) {+ freeformCounts.set(tag, (freeformCounts.get(tag) ?? 0) + 1)+ }+ }+ const rank = (counts: Map<string, number>): [string, number][] =>+ Array.from(counts.entries())+ .sort((a, b) => b[1] - a[1])+ .slice(0, 10)+ return { fixedRanked: rank(fixedCounts), freeformRanked: rank(freeformCounts), totalWithTags }+ },+ ],+ scorerScores: [+ (s) => [s.succeededObservations],+ (observations: ReplayObservationApi[]): number[] => {+ const items: number[] = []+ for (const obs of observations) {+ const out = readModelOutput(obs)+ if (out && typeof out.score === 'number') {+ items.push(out.score)+ }+ }+ items.sort((a, b) => a - b)+ return items+ },+ ],+ scorerSummary: [+ (s) => [s.scorerScores],+ (+ scores: number[]+ ): { min: number; p25: number; median: number; mean: number; p75: number; max: number } | null => {+ if (scores.length === 0) {+ return null+ }+ return {+ min: scores[0],+ p25: quantile(scores, 0.25),+ median: quantile(scores, 0.5),+ mean: scores.reduce((a, b) => a + b, 0) / scores.length,+ p75: quantile(scores, 0.75),+ max: scores[scores.length - 1],+ }+ },+ ],+ // Distinct sessions scanned: last 14 days and total. Surfaces sweep-job coverage.+ coverageStats: [+ (s) => [s.observations],+ (+ observations: ReplayObservationApi[]+ ): { recentSessions: number; totalSessions: number; recentDays: number } => {+ const cutoff = dayjs().subtract(14, 'day')+ const recent = new Set<string>()+ const all = new Set<string>()+ for (const obs of observations) {+ if (!obs.session_id) {+ continue+ }+ all.add(obs.session_id)+ if (dayjs(obs.created_at).isAfter(cutoff)) {+ recent.add(obs.session_id)+ }+ }+ return { recentSessions: recent.size, totalSessions: all.size, recentDays: 14 }+ },+ ],}),listeners(({ actions, props, values, cache }) => ({diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.tsindex c46275d3138f..f800f80db2ca 100644--- a/products/replay_vision/frontend/replay_scanners/types.ts+++ b/products/replay_vision/frontend/replay_scanners/types.ts@@ -131,11 +131,6 @@ export const SCANNER_TYPE_OPTIONS: { value: ScannerType; label: string; descriptlabel: 'Scorer',description: 'Scores the session on a configurable numeric scale.',},- {- value: 'indexer',- label: 'Indexer',- description: 'Generates semantic embeddings of the session for free-text search.',- },]export type EditorTab = 'observations' | 'configuration'diff --git a/products/replay_vision/frontend/utils/citations.ts b/products/replay_vision/frontend/utils/citations.tsnew file mode 100644index 000000000000..07c49fd97a34--- /dev/null+++ b/products/replay_vision/frontend/utils/citations.ts@@ -0,0 +1,50 @@+/** Inline `(event_id <hash>)` marker the model emits in free-text fields. Mirrors backend's `_EVENT_ID_CITATION_RE`; keep in sync. */+const EVENT_ID_PATTERN = /\(event_id ([0-9a-f]{16})\)/gi++export type CitationPart = { type: 'text'; value: string } | { type: 'citation'; timestampMs: number; uuid?: string }++/**+ * Parse free-text from a scanner's model output into a sequence of plain-text segments and citation chips,+ * resolving inline `(event_id <hash>)` markers against the observation's `event_id_mapping`. Unresolved markers+ * are stripped so they never reach the UI as raw text.+ */+export function parseCitedText(+ text: string | null | undefined,+ mapping: Record<string, unknown> | null | undefined+): CitationPart[] {+ if (!text) {+ return []+ }+ const map = mapping ?? {}+ const parts: CitationPart[] = []+ let lastIndex = 0+ EVENT_ID_PATTERN.lastIndex = 0+ let match: RegExpExecArray | null+ while ((match = EVENT_ID_PATTERN.exec(text)) !== null) {+ const [full, hash] = match+ const citation = map[hash.toLowerCase()] as { uuid?: string; timestamp_ms?: number } | undefined+ if (match.index > lastIndex) {+ parts.push({ type: 'text', value: text.slice(lastIndex, match.index) })+ }+ if (citation && typeof citation.timestamp_ms === 'number') {+ parts.push({ type: 'citation', timestampMs: citation.timestamp_ms, uuid: citation.uuid })+ }+ // Unresolved citations are silently dropped — raw markers must never reach the UI.+ lastIndex = match.index + full.length+ }+ if (lastIndex < text.length) {+ parts.push({ type: 'text', value: text.slice(lastIndex) })+ }+ return parts+}++export function formatSessionOffset(ms: number): string {+ const totalSeconds = Math.max(0, Math.floor(ms / 1000))+ const h = Math.floor(totalSeconds / 3600)+ const m = Math.floor((totalSeconds % 3600) / 60)+ const s = totalSeconds % 60+ if (h > 0) {+ return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`+ }+ return `${m}:${s.toString().padStart(2, '0')}`+}diff --git a/products/replay_vision/frontend/utils/observation.ts b/products/replay_vision/frontend/utils/observation.tsnew file mode 100644index 000000000000..c2431f10f003--- /dev/null+++ b/products/replay_vision/frontend/utils/observation.ts@@ -0,0 +1,37 @@+import type { ReplayObservationApi } from '../generated/api.schemas'++export function readModelOutput(obs: ReplayObservationApi): Record<string, unknown> | null {+ const out = obs.scanner_result?.model_output+ return out && typeof out === 'object' ? (out as Record<string, unknown>) : null+}++export function readScore(obs: ReplayObservationApi): number | null {+ const raw = readModelOutput(obs)?.score+ return typeof raw === 'number' ? raw : null+}++export function readVerdict(obs: ReplayObservationApi): boolean | null {+ const raw = readModelOutput(obs)?.verdict+ return typeof raw === 'boolean' ? raw : null+}++function readStringArray(value: unknown): string[] {+ if (!Array.isArray(value)) {+ return []+ }+ return value.filter((t): t is string => typeof t === 'string')+}++/** Tags from the scanner's configured vocabulary. */+export function readFixedTags(obs: ReplayObservationApi): string[] {+ return readStringArray(readModelOutput(obs)?.tags)+}++/** Tags the model emits outside the vocabulary when `allow_freeform_tags` is on. */+export function readFreeformTags(obs: ReplayObservationApi): string[] {+ return readStringArray(readModelOutput(obs)?.tags_freeform)+}++export function readTags(obs: ReplayObservationApi): string[] {+ return [...readFixedTags(obs), ...readFreeformTags(obs)]+}