Skip to content

: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.

feat(replay): observations tab UI overhaul (#103747)

Hayne Ryu34a8d85f17cb
diff --git a/frontend/src/scenes/session-recordings/player/controller/Seekbar.scss b/frontend/src/scenes/session-recordings/player/controller/Seekbar.scss
index 6b8ab6f573ed..b38f04e4269d 100644
--- a/frontend/src/scenes/session-recordings/player/controller/Seekbar.scss
+++ b/frontend/src/scenes/session-recordings/player/controller/Seekbar.scss
@@ -76,10 +76,20 @@
cursor: pointer;
background-color: var(--color-accent);
border-radius: 2px;
- opacity: 0.75;
- transition: opacity 150ms ease;
+ opacity: 0.45;
+ transition:
+ opacity 150ms ease,
+ width 150ms ease,
+ margin-left 150ms ease;
+
+ &--flagged {
+ opacity: 0.85;
+ }
- &:hover {
+ &:hover,
+ &--hovered {
+ width: 5px;
+ margin-left: -2.5px;
opacity: 1;
}
}
diff --git a/products/replay_vision/frontend/components/ObservationProgressBar.tsx b/products/replay_vision/frontend/components/ObservationProgressBar.tsx
index 1070c47314fb..e78c45081e88 100644
--- a/products/replay_vision/frontend/components/ObservationProgressBar.tsx
+++ b/products/replay_vision/frontend/components/ObservationProgressBar.tsx
@@ -1,10 +1,9 @@
import { useActions, useValues } from 'kea'
-import { useRef } from 'react'
+import { useEffect, useRef } from 'react'
import { IconCheckCircle, IconCircleDashed, IconWarning } from '@posthog/icons'
import { Spinner } from '@posthog/lemon-ui'
-import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { usePeriodicRerender } from 'lib/hooks/usePeriodicRerender'
import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
@@ -74,14 +73,15 @@ export function ObservationProgressBar({
const { startStream } = useActions(observationProgressLogic({ observationId, sessionId }))
usePeriodicRerender(1000)
- // The bar only renders for in-flight observations, so its mount is the signal to open the stream.
- useOnMountEffect(() => startStream())
+ // Record when the active phase was first observed so its asymptotic fill animates from then.
+ const startTimesRef = useRef<Record<number, number>>({})
+ useEffect(() => {
+ startTimesRef.current = {}
+ startStream()
+ }, [observationId, startStream])
const currentStep = Math.min(progress?.step ?? 0, PHASE_ORDER.length - 1)
const activePhase = PHASE_ORDER[currentStep]
-
- // Record when the active phase was first observed so its asymptotic fill animates from then.
- const startTimesRef = useRef<Record<number, number>>({})
if (!(currentStep in startTimesRef.current)) {
startTimesRef.current[currentStep] = Date.now()
}
diff --git a/products/replay_vision/frontend/components/ObservationSeekbarMarks.tsx b/products/replay_vision/frontend/components/ObservationSeekbarMarks.tsx
index 4c79802e3aa8..0f016f349420 100644
--- a/products/replay_vision/frontend/components/ObservationSeekbarMarks.tsx
+++ b/products/replay_vision/frontend/components/ObservationSeekbarMarks.tsx
@@ -1,11 +1,13 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import React from 'react'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { cn } from 'lib/utils/css-classes'
import { colonDelimitedDuration } from 'lib/utils/durations'
import { sessionRecordingPlayerLogic } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
import { observationsDockLogic } from '../logics/observationsDockLogic'
+import type { ObservationSeekbarMark, ObservationSeekbarMarkEntry } from '../utils/observation'
import { visionSurfaceShown } from '../utils/visionSurface'
interface ObservationSeekbarMarksProps {
@@ -13,6 +15,41 @@ interface ObservationSeekbarMarksProps {
onSeek: (timestampMs: number) => void
}
+/** Shared by the seekbar and the sidebar timeline. */
+export function ObservationMarkTooltip({ mark }: { mark: ObservationSeekbarMark }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-1">
+ <span className="font-medium">{colonDelimitedDuration(Math.floor(mark.timestampMs / 1000), null)}</span>
+ {mark.entries.map((entry, i) => (
+ <div key={i} className="flex flex-col">
+ <span>{[entry.scannerName, entry.headline].filter(Boolean).join(' · ')}</span>
+ {entry.sentence && (
+ <span className="text-xs opacity-75">
+ <CitedSentence entry={entry} />
+ </span>
+ )}
+ </div>
+ ))}
+ </div>
+ )
+}
+
+function CitedSentence({ entry }: { entry: ObservationSeekbarMarkEntry }): JSX.Element {
+ const sentence = entry.sentence ?? ''
+ const clause = entry.snippet?.replace(/^…|…$/g, '') ?? ''
+ const at = clause ? sentence.toLowerCase().indexOf(clause.toLowerCase()) : -1
+ if (at < 0) {
+ return <>{sentence}</>
+ }
+ return (
+ <>
+ {sentence.slice(0, at)}
+ <strong>{sentence.slice(at, at + clause.length)}</strong>
+ {sentence.slice(at + clause.length)}
+ </>
+ )
+}
+
export const ObservationSeekbarMarks = React.memo(function ObservationSeekbarMarks(
props: ObservationSeekbarMarksProps
): JSX.Element | null {
@@ -28,7 +65,9 @@ function ObservationSeekbarMarksContent({
endTimeMs,
onSeek,
}: ObservationSeekbarMarksProps & { sessionId: string }): JSX.Element | null {
- const { seekbarMarks } = useValues(observationsDockLogic({ sessionId }))
+ const logic = observationsDockLogic({ sessionId })
+ const { seekbarMarks, hoveredMarkMs } = useValues(logic)
+ const { setHoveredMark } = useActions(logic)
if (seekbarMarks.length === 0 || endTimeMs <= 0) {
return null
@@ -41,28 +80,19 @@ function ObservationSeekbarMarksContent({
if (position < 0 || position > 100) {
return null
}
- const timeLabel = colonDelimitedDuration(Math.floor(mark.timestampMs / 1000), null)
return (
- <Tooltip
- key={mark.timestampMs}
- title={
- <div className="flex flex-col gap-1">
- <span className="font-medium">{timeLabel}</span>
- {mark.entries.map((entry, i) => (
- <div key={i} className="flex flex-col">
- <span>{[entry.scannerName, entry.headline].filter(Boolean).join(' · ')}</span>
- {entry.snippet && <span className="text-xs opacity-75">{entry.snippet}</span>}
- </div>
- ))}
- </div>
- }
- placement="top"
- >
+ <Tooltip key={mark.timestampMs} title={<ObservationMarkTooltip mark={mark} />} placement="top">
<div
- className="PlayerSeekbar__observation"
+ className={cn(
+ 'PlayerSeekbar__observation',
+ mark.flagged && 'PlayerSeekbar__observation--flagged',
+ hoveredMarkMs === mark.timestampMs && 'PlayerSeekbar__observation--hovered'
+ )}
data-attr="vision-seekbar-observation-mark"
// eslint-disable-next-line react/forbid-dom-props
style={{ left: `${position}%` }}
+ onMouseEnter={() => setHoveredMark(mark.timestampMs)}
+ onMouseLeave={() => setHoveredMark(null)}
// The slider scrubs on mousedown. Without this the pointer-position seek overrides the exact one.
onMouseDown={(e) => e.stopPropagation()}
onTouchStart={(e) => e.stopPropagation()}
diff --git a/products/replay_vision/frontend/components/ObservationTimeline.tsx b/products/replay_vision/frontend/components/ObservationTimeline.tsx
new file mode 100644
index 000000000000..eb215cf9bebf
--- /dev/null
+++ b/products/replay_vision/frontend/components/ObservationTimeline.tsx
@@ -0,0 +1,111 @@
+import { useActions, useValues } from 'kea'
+import { Fragment, useEffect } from 'react'
+
+import { LemonButton, Tooltip } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+import { colonDelimitedDuration } from 'lib/utils/durations'
+import { sessionRecordingPlayerLogic } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
+
+import { observationsDockLogic } from '../logics/observationsDockLogic'
+import type { ObservationSeekbarMark } from '../utils/observation'
+import { currentMarkIndex, timelineGapPx } from '../utils/observationTimeline'
+import { ObservationMarkTooltip } from './ObservationSeekbarMarks'
+
+const ROW_GRID = 'grid grid-cols-[2.5rem_1rem_minmax(0,1fr)] gap-x-1.5'
+
+export function ObservationTimeline({
+ sessionId,
+ marks,
+ onSeek,
+}: {
+ sessionId: string
+ marks: ObservationSeekbarMark[]
+ onSeek: (timestampMs: number) => void
+}): JSX.Element {
+ const { currentPlayerTime } = useValues(sessionRecordingPlayerLogic)
+ const logic = observationsDockLogic({ sessionId })
+ const { hoveredMarkMs } = useValues(logic)
+ const { setHoveredMark } = useActions(logic)
+ const currentIndex = currentMarkIndex(marks, currentPlayerTime)
+ useEffect(() => () => setHoveredMark(null), [setHoveredMark])
+
+ return (
+ <div className="flex flex-col py-0.5" data-attr="vision-observation-timeline">
+ {marks.map((mark, index) => {
+ const passed = mark.timestampMs <= currentPlayerTime
+ const isCurrent = index === currentIndex
+ const gapPx = index === 0 ? 0 : timelineGapPx(mark.timestampMs - marks[index - 1].timestampMs)
+ const lead = mark.entries[0]
+ const railColor = passed ? 'bg-accent' : 'bg-border'
+ return (
+ <Fragment key={mark.timestampMs}>
+ {gapPx > 0 && (
+ <div
+ className={cn(ROW_GRID, 'px-2')}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ height: gapPx }}
+ >
+ <span />
+ <span className={cn('w-0.5 h-full justify-self-center', railColor)} />
+ </div>
+ )}
+ <div
+ data-current-moment={isCurrent ? true : undefined}
+ className={cn(
+ ROW_GRID,
+ 'px-2 py-0.5 transition-colors',
+ isCurrent && 'bg-fill-highlight-50',
+ hoveredMarkMs === mark.timestampMs && 'bg-surface-secondary'
+ )}
+ onMouseEnter={() => setHoveredMark(mark.timestampMs)}
+ onMouseLeave={() => setHoveredMark(null)}
+ >
+ <span
+ className={cn(
+ 'self-center text-xs font-mono text-right',
+ isCurrent ? 'text-accent font-semibold' : 'text-secondary'
+ )}
+ >
+ {colonDelimitedDuration(Math.floor(mark.timestampMs / 1000), null)}
+ </span>
+ <div className="flex flex-col items-center -my-0.5">
+ <span className={cn('w-0.5 flex-1', railColor)} />
+ <span
+ className={cn(
+ 'w-2.5 h-2.5 rounded-full shrink-0',
+ mark.flagged ? 'bg-accent' : passed ? 'bg-accent opacity-60' : 'bg-border',
+ isCurrent && 'ring-2 ring-accent ring-offset-1'
+ )}
+ />
+ <span
+ className={cn(
+ 'w-0.5 flex-1',
+ passed && index < currentIndex ? 'bg-accent' : 'bg-border'
+ )}
+ />
+ </div>
+ <Tooltip title={<ObservationMarkTooltip mark={mark} />} placement="left">
+ <LemonButton
+ size="xsmall"
+ fullWidth
+ onClick={() => onSeek(mark.timestampMs)}
+ data-attr="vision-timeline-moment"
+ >
+ <span
+ className={cn(
+ 'text-sm truncate min-w-0 text-left',
+ mark.flagged ? 'font-semibold' : 'font-normal'
+ )}
+ >
+ {lead?.snippet ?? lead?.headline ?? lead?.scannerName}
+ </span>
+ </LemonButton>
+ </Tooltip>
+ </div>
+ </Fragment>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.tsx b/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.tsx
index a0ee2c745aee..0226244bab11 100644
--- a/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.tsx
+++ b/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.tsx
@@ -1,20 +1,44 @@
import { useActions, useValues } from 'kea'
+import { type ReactNode, forwardRef, useEffect, useMemo, useRef, useState } from 'react'
-import { IconChevronDown, IconEye } from '@posthog/icons'
-import { LemonButton, LemonInput, Link, Spinner } from '@posthog/lemon-ui'
+import { IconChevronDown, IconChevronRight, IconCollapse, IconExpand, IconEye } from '@posthog/icons'
+import { LemonBadge, LemonButton, LemonInput, LemonSwitch, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
+import { useResizeObserver } from 'lib/hooks/useResizeObserver'
import { LemonDropdown } from 'lib/lemon-ui/LemonDropdown/LemonDropdown'
+import { cn } from 'lib/utils/css-classes'
import { sessionRecordingPlayerLogic } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
import { urls } from 'scenes/urls'
-import type { ReplayScannerApi } from '../generated/api.schemas'
+import type { ReplayObservationApi, ReplayScannerApi } from '../generated/api.schemas'
import { observationsDockLogic } from '../logics/observationsDockLogic'
import { visionQuotaLogic } from '../logics/visionQuotaLogic'
+import { SCANNER_TYPE_TAG_TYPE, configFromSnapshot, scannerTypeLabel } from '../replay_scanners/types'
+import {
+ ObservationSeekbarMark,
+ isFlaggedObservation,
+ isSummaryObservation,
+ observationSeekbarMarks,
+ readModelOutput,
+ readReasoning,
+ scannerLabel,
+} from '../utils/observation'
+import { currentMarkIndex, nextMarkAfter } from '../utils/observationTimeline'
import { quotaUx } from '../utils/quotaProjection'
import { ScanBlock, recordingScanBlock } from '../utils/scanEligibility'
import { visionSurfaceShown } from '../utils/visionSurface'
-import { ObservationDockCard } from './ObservationCard'
-import { ScannerTypeBadge } from './ScannerTypeBadge'
+import { CitedMarkdown } from './CitedMarkdown'
+import {
+ FailureDetail,
+ IneligibleDetail,
+ ObservationPrimaryOutput,
+ ObservationResultSummary,
+ ObservationStatusTag,
+} from './ObservationCard'
+import { ObservationProgressBar } from './ObservationProgressBar'
+import { ObservationRetryButton } from './ObservationRetryButton'
+import { ObservationTimeline } from './ObservationTimeline'
+import { ScannerTypeBadge, scannerTypeIcon } from './ScannerTypeBadge'
export function PlayerSidebarObservationsTab(): JSX.Element | null {
const { sessionRecordingId, logicProps } = useValues(sessionRecordingPlayerLogic)
@@ -23,7 +47,7 @@ export function PlayerSidebarObservationsTab(): JSX.Element | null {
if (!visionSurfaceShown(logicProps) || !sessionRecordingId) {
return null
}
- return <ObservationsTabContent sessionId={sessionRecordingId} />
+ return <ObservationsTabContent key={sessionRecordingId} sessionId={sessionRecordingId} />
}
function ScannerPicker({
@@ -113,16 +137,326 @@ function ScannerPicker({
)
}
+const CURRENT_MOMENT_SELECTOR = '[data-current-moment]'
+
+const isInFlight = (o: ReplayObservationApi): boolean => o.status === 'pending' || o.status === 'running'
+
+function defaultFocus(observations: ReplayObservationApi[]): ReplayObservationApi | null {
+ return (
+ observations.find(isInFlight) ?? observations.find((o) => o.status === 'succeeded') ?? observations[0] ?? null
+ )
+}
+
+function ObservationRuns({
+ sessionId,
+ observations,
+ seekbarMarks,
+ onSeek,
+}: {
+ sessionId: string
+ observations: ReplayObservationApi[]
+ seekbarMarks: ObservationSeekbarMark[]
+ onSeek: (timestampMs: number) => void
+}): JSX.Element | null {
+ const logic = observationsDockLogic({ sessionId })
+ const { focusedObservationId, followMoments, retryingObservationIds } = useValues(logic)
+ const { focusObservation, setFollowMoments, retryObservation } = useActions(logic)
+ const { currentPlayerTime } = useValues(sessionRecordingPlayerLogic)
+ const paneRef = useRef<HTMLDivElement>(null)
+ const followedMs = useRef<number | null>(null)
+ const marksByRun = useMemo(
+ () => new Map(observations.map((o) => [o.id, observationSeekbarMarks([o])])),
+ [observations]
+ )
+ const focused = observations.find((o) => o.id === focusedObservationId) ?? defaultFocus(observations)
+ const currentIndex = currentMarkIndex(seekbarMarks, currentPlayerTime)
+ const currentMs = currentIndex >= 0 ? seekbarMarks[currentIndex].timestampMs : null
+
+ useEffect(() => {
+ if (!followMoments) {
+ followedMs.current = null
+ return
+ }
+ if (currentMs === null || followedMs.current === currentMs) {
+ return
+ }
+ const owns = (o: ReplayObservationApi): boolean =>
+ marksByRun.get(o.id)?.some((m) => m.timestampMs === currentMs) ?? false
+ if (focused && !owns(focused)) {
+ const owner = observations.find(owns)
+ if (owner) {
+ focusObservation(owner.id)
+ return
+ }
+ }
+ followedMs.current = currentMs
+ paneRef.current?.querySelector<HTMLElement>(CURRENT_MOMENT_SELECTOR)?.scrollIntoView({ block: 'nearest' })
+ }, [currentMs, followMoments, focused, observations, marksByRun, focusObservation])
+
+ if (observations.length === 0) {
+ return null
+ }
+ const flaggedCount = observations.filter(isFlaggedObservation).length
+ return (
+ <div className="flex-1 min-h-0 overflow-y-auto" data-attr="vision-observation-runs">
+ {focused && (
+ <FocusPane
+ ref={paneRef}
+ sessionId={sessionId}
+ observation={focused}
+ marks={marksByRun.get(focused.id) ?? []}
+ onSeek={onSeek}
+ onRetry={() => retryObservation(focused.id)}
+ retrying={retryingObservationIds.includes(focused.id)}
+ />
+ )}
+ <SectionHeader label="Runs" count={observations.length} className="sticky top-0 z-10">
+ {flaggedCount > 0 && (
+ <Tooltip title={`${flaggedCount} flagged`}>
+ <LemonBadge.Number count={flaggedCount} size="small" status="primary" />
+ </Tooltip>
+ )}
+ </SectionHeader>
+ <div>
+ {observations.map((observation) => {
+ const count = marksByRun.get(observation.id)?.length ?? 0
+ const scannerType = observation.scanner_snapshot?.scanner_type
+ return (
+ <div key={observation.id} className="border-b border-primary">
+ <LemonButton
+ fullWidth
+ size="small"
+ className="rounded-none"
+ active={observation.id === focused?.id}
+ icon={
+ scannerType ? (
+ <Tooltip title={scannerTypeLabel(scannerType)}>
+ <LemonTag type={SCANNER_TYPE_TAG_TYPE[scannerType]} size="small">
+ {scannerTypeIcon(scannerType)}
+ </LemonTag>
+ </Tooltip>
+ ) : undefined
+ }
+ onClick={() => {
+ focusObservation(observation.id)
+ setFollowMoments(false)
+ }}
+ data-attr="vision-run-row"
+ >
+ <span className="flex items-center gap-2 min-w-0 w-full font-normal">
+ <span className="text-sm truncate flex-1">{scannerLabel(observation)}</span>
+ <span className="flex items-center gap-2 min-w-0 max-w-[60%]">
+ <RunResult observation={observation} />
+ {count > 0 && (
+ <Tooltip title={`${count} cited moment${count === 1 ? '' : 's'}`}>
+ <LemonBadge.Number
+ count={count}
+ maxDigits={2}
+ size="small"
+ status={isFlaggedObservation(observation) ? 'primary' : 'muted'}
+ />
+ </Tooltip>
+ )}
+ </span>
+ </span>
+ </LemonButton>
+ </div>
+ )
+ })}
+ </div>
+ </div>
+ )
+}
+
+function SectionHeader({
+ label,
+ count,
+ className,
+ children,
+}: {
+ label: string
+ count: number
+ className?: string
+ children?: ReactNode
+}): JSX.Element {
+ return (
+ <div
+ className={cn(
+ 'flex items-center gap-2 px-3 py-1.5 border-y border-primary bg-surface-tertiary dark:bg-surface-secondary text-xs font-semibold uppercase tracking-wide text-secondary',
+ className
+ )}
+ >
+ {label}
+ <LemonBadge.Number count={count} maxDigits={2} size="small" status="muted" showZero />
+ {children}
+ </div>
+ )
+}
+
+function RunResult({ observation }: { observation: ReplayObservationApi }): JSX.Element | null {
+ if (observation.status !== 'succeeded') {
+ return <ObservationStatusTag status={observation.status} errorReason={observation.error_reason} />
+ }
+ if (isSummaryObservation(observation)) {
+ return null
+ }
+ return <ObservationResultSummary observation={observation} />
+}
+
+const FocusPane = forwardRef<
+ HTMLDivElement,
+ {
+ sessionId: string
+ observation: ReplayObservationApi
+ marks: ObservationSeekbarMark[]
+ onSeek: (timestampMs: number) => void
+ onRetry: () => void
+ retrying: boolean
+ }
+>(function FocusPane({ sessionId, observation, marks, onSeek, onRetry, retrying }, ref) {
+ const [textOpenFor, setTextOpenFor] = useState<string | null>(null)
+ const showText = textOpenFor === observation.id
+ const { height: contentHeight, ref: contentRef } = useResizeObserver<HTMLDivElement>({ box: 'border-box' })
+ const isSummary = isSummaryObservation(observation)
+ const reasoning = observation.status === 'succeeded' && !isSummary ? readReasoning(observation) : null
+ const hasText = observation.status === 'succeeded' && (isSummary || reasoning !== null)
+ const textLabel = isSummary ? 'summary' : 'reasoning'
+ const prompt = configFromSnapshot(observation.scanner_snapshot)?.prompt ?? null
+ const scannerType = observation.scanner_snapshot?.scanner_type
+ return (
+ <div
+ ref={ref}
+ className="overflow-hidden transition-[height] duration-200 ease-in-out border-b"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ height: contentHeight }}
+ data-attr="vision-focus-run"
+ >
+ <div ref={contentRef}>
+ <div className="flex items-center gap-2 px-3 py-2">
+ {scannerType && (
+ <Tooltip title={scannerTypeLabel(scannerType)}>
+ <LemonTag type={SCANNER_TYPE_TAG_TYPE[scannerType]} size="small">
+ {scannerTypeIcon(scannerType)}
+ </LemonTag>
+ </Tooltip>
+ )}
+ <Tooltip title={prompt}>
+ <span className="text-sm font-semibold truncate">{scannerLabel(observation)}</span>
+ </Tooltip>
+ <span className="ml-auto shrink-0 min-w-0 max-w-[50%]">
+ <RunResult observation={observation} />
+ </span>
+ </div>
+ {(observation.error_reason || isInFlight(observation)) && (
+ <div className="flex flex-col gap-2 px-2 pb-2">
+ {observation.status === 'failed' && observation.error_reason && (
+ <FailureDetail errorReason={observation.error_reason} />
+ )}
+ {observation.status === 'ineligible' && observation.error_reason && (
+ <IneligibleDetail errorReason={observation.error_reason} />
+ )}
+ {observation.error_reason && (
+ <div>
+ <ObservationRetryButton
+ status={observation.status}
+ errorReason={observation.error_reason}
+ onRetry={onRetry}
+ loading={retrying}
+ size="xsmall"
+ dataAttr="vision-tab-retry-observation"
+ />
+ </div>
+ )}
+ {isInFlight(observation) && (
+ <ObservationProgressBar
+ observationId={observation.id}
+ sessionId={observation.session_id}
+ compact
+ />
+ )}
+ </div>
+ )}
+ {marks.length > 0 && (
+ <>
+ <SectionHeader label="Moments" count={marks.length} />
+ <ObservationTimeline sessionId={sessionId} marks={marks} onSeek={onSeek} />
+ </>
+ )}
+ <div className="flex flex-col gap-2 px-2 py-2">
+ {observation.status === 'succeeded' && marks.length === 0 && (
+ <span className="text-xs text-muted">No cited moments.</span>
+ )}
+ <div className="flex items-center gap-2">
+ {hasText && (
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ sideIcon={showText ? <IconCollapse /> : <IconExpand />}
+ onClick={() => setTextOpenFor(showText ? null : observation.id)}
+ data-attr="vision-run-text-toggle"
+ >
+ {showText ? `Hide ${textLabel}` : `Show ${textLabel}`}
+ </LemonButton>
+ )}
+ <Link to={urls.replayVisionObservation(observation.id)} className="text-xs ml-auto">
+ View details
+ </Link>
+ </div>
+ {hasText && showText && (
+ <div className="text-sm">
+ {isSummary ? (
+ <ObservationPrimaryOutput
+ observation={observation}
+ showPrompt={false}
+ expandSummary
+ copyable
+ onSeek={onSeek}
+ />
+ ) : (
+ <CitedMarkdown
+ text={reasoning ?? ''}
+ segments={readModelOutput(observation)?.reasoning_segments}
+ onSeek={onSeek}
+ />
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ )
+})
+
function ObservationsTabContent({ sessionId }: { sessionId: string }): JSX.Element {
const logic = observationsDockLogic({ sessionId })
- const { observations, observationsLoading, retryingObservationIds } = useValues(logic)
- const { retryObservation } = useActions(logic)
+ const { observations, observationsLoading, seekbarMarks, followMoments } = useValues(logic)
+ const { setFollowMoments, focusObservation } = useActions(logic)
+ const lastJumpMs = useRef<number | null>(null)
// The player logic is keyed; seek the exact mounted instance, not a propless default
- const { logicProps, sessionPlayerMetaData } = useValues(sessionRecordingPlayerLogic)
+ const { logicProps, sessionPlayerMetaData, currentPlayerTime } = useValues(sessionRecordingPlayerLogic)
const seekToTime = (ms: number): void => {
sessionRecordingPlayerLogic.findMounted(logicProps)?.actions.seekToTime(ms)
}
const scanBlock = recordingScanBlock(sessionPlayerMetaData)
+ // A seek can land short of its target; step from the last jump while still on it.
+ const nextFrom =
+ lastJumpMs.current !== null && Math.abs(currentPlayerTime - lastJumpMs.current) < 1000
+ ? lastJumpMs.current
+ : currentPlayerTime
+ const nextMoment = nextMarkAfter(seekbarMarks, nextFrom)
+ const jumpToNextMoment = (): void => {
+ if (!nextMoment) {
+ return
+ }
+ lastJumpMs.current = nextMoment.timestampMs
+ seekToTime(nextMoment.timestampMs)
+ const owner = observations.find((o) =>
+ observationSeekbarMarks([o]).some((m) => m.timestampMs === nextMoment.timestampMs)
+ )
+ if (owner) {
+ focusObservation(owner.id)
+ }
+ }
return (
<div className="flex flex-col flex-1 min-h-0" data-attr="vision-observations-tab">
@@ -151,25 +485,40 @@ function ObservationsTabContent({ sessionId }: { sessionId: string }): JSX.Eleme
)}
</div>
) : (
- <div className="flex-1 overflow-y-auto p-2 space-y-2">
- {observations.map((observation) => (
- <ObservationDockCard
- key={observation.id}
- observation={observation}
- onSeek={seekToTime}
- onRetry={() => retryObservation(observation.id)}
- retrying={retryingObservationIds.includes(observation.id)}
- />
- ))}
- <div className="flex justify-center">
- <ScannerPicker
- sessionId={sessionId}
- scanBlock={scanBlock}
- type="secondary"
- placement="top-start"
- />
+ <>
+ <div className="@container flex items-center gap-2 p-2 border-b bg-surface-secondary">
+ <ScannerPicker sessionId={sessionId} scanBlock={scanBlock} type="secondary" />
+ {seekbarMarks.length > 0 && (
+ <div className="ml-auto flex items-center gap-2">
+ <LemonSwitch
+ size="xsmall"
+ checked={followMoments}
+ onChange={setFollowMoments}
+ label="Follow"
+ data-attr="vision-follow-moments"
+ />
+ <span className="hidden @[400px]:block">
+ <LemonButton
+ size="small"
+ type="secondary"
+ sideIcon={<IconChevronRight />}
+ disabledReason={nextMoment ? undefined : 'No later moments'}
+ onClick={jumpToNextMoment}
+ data-attr="vision-next-moment"
+ >
+ Next moment
+ </LemonButton>
+ </span>
+ </div>
+ )}
</div>
- </div>
+ <ObservationRuns
+ sessionId={sessionId}
+ observations={observations}
+ seekbarMarks={seekbarMarks}
+ onSeek={seekToTime}
+ />
+ </>
)}
</div>
)
diff --git a/products/replay_vision/frontend/logics/observationsDockLogic.ts b/products/replay_vision/frontend/logics/observationsDockLogic.ts
index 3f5096d7cbc1..931a9808336c 100644
--- a/products/replay_vision/frontend/logics/observationsDockLogic.ts
+++ b/products/replay_vision/frontend/logics/observationsDockLogic.ts
@@ -35,7 +35,10 @@ export interface observationsDockLogicValues {
defaultSummarizer: ReplayScannerApi | null
dockOpen: boolean
filteredScanners: ReplayScannerApi[]
+ focusedObservationId: string | null
+ followMoments: boolean
hasObservationsInFlight: boolean
+ hoveredMarkMs: number | null
observations: ReplayObservationApi[]
observationsLoading: boolean
observing: boolean
@@ -58,6 +61,9 @@ export interface observationsDockLogicActions {
setSummaryDockAutoExpand: (autoExpand: boolean) => {
autoExpand: boolean
} // visionDockPreferenceLogic
+ focusObservation: (observationId: string) => {
+ observationId: string
+ }
loadObservations: () => {
value: true
}
@@ -92,6 +98,12 @@ export interface observationsDockLogicActions {
setDockOpen: (open: boolean) => {
open: boolean
}
+ setFollowMoments: (follow: boolean) => {
+ follow: boolean
+ }
+ setHoveredMark: (timestampMs: number | null) => {
+ timestampMs: number | null
+ }
setScannerPickerOpen: (open: boolean) => {
open: boolean
}
@@ -166,6 +178,9 @@ export const observationsDockLogic = kea<observationsDockLogicType>([
retryObservationSuccess: (observationId: string) => ({ observationId }),
retryObservationFailure: (observationId: string) => ({ observationId }),
setDockOpen: (open: boolean) => ({ open }),
+ focusObservation: (observationId: string) => ({ observationId }),
+ setFollowMoments: (follow: boolean) => ({ follow }),
+ setHoveredMark: (timestampMs: number | null) => ({ timestampMs }),
setScannerPickerOpen: (open: boolean) => ({ open }),
setScannerSearch: (search: string) => ({ search }),
summarize: true,
@@ -226,6 +241,26 @@ export const observationsDockLogic = kea<observationsDockLogicType>([
setScannerPickerOpen: (_, { open }) => open,
},
],
+ // Shared so hovering a mark on one surface highlights it on the other.
+ hoveredMarkMs: [
+ null as number | null,
+ {
+ setHoveredMark: (_, { timestampMs }) => timestampMs,
+ },
+ ],
+ focusedObservationId: [
+ null as string | null,
+ {
+ focusObservation: (_, { observationId }) => observationId,
+ retryObservation: (_, { observationId }) => observationId,
+ },
+ ],
+ followMoments: [
+ true,
+ {
+ setFollowMoments: (_, { follow }) => follow,
+ },
+ ],
scannerSearch: [
'',
{
@@ -459,7 +494,12 @@ export const observationsDockLogic = kea<observationsDockLogicType>([
},
// Poll while in flight and through the observe grace window; rescheduled on failure so one hiccup can't kill it.
- loadObservationsSuccess: () => {
+ loadObservationsSuccess: ({ observations }) => {
+ const started = observations.find((o) => o.scanner_id === cache.focusScannerId)
+ if (started) {
+ cache.focusScannerId = null
+ actions.focusObservation(started.id)
+ }
openDockForExistingSummary()
settleSummarizeIfDone()
reschedulePoll()
@@ -517,6 +557,7 @@ export const observationsDockLogic = kea<observationsDockLogicType>([
if (forSummary) {
cache.summarizeScannerId = scannerId
}
+ cache.focusScannerId = scannerId
actions.observeSuccess()
afterScanStarted()
} catch (error) {
diff --git a/products/replay_vision/frontend/utils/observation.test.ts b/products/replay_vision/frontend/utils/observation.test.ts
index eaf3bd0d0697..b3732c8f309b 100644
--- a/products/replay_vision/frontend/utils/observation.test.ts
+++ b/products/replay_vision/frontend/utils/observation.test.ts
@@ -7,8 +7,13 @@ import {
scannerLabel,
} from './observation'
-const summarizerEntry = { scannerName: 'Session summarizer', headline: null, snippet: 'Rage clicked pay' }
-const longSentence = 'x'.repeat(200)
+const summarizerEntry = {
+ scannerName: 'Session summarizer',
+ headline: null,
+ snippet: 'Rage clicked pay',
+ sentence: 'Rage clicked pay (02:41) (00:30) (02:41)',
+}
+const longSentence = 'X'.repeat(200)
function makeObservation(
scannerType: string,
@@ -75,8 +80,8 @@ describe('observation utils', () => {
),
],
expected: [
- { timestampMs: 30_000, entries: [summarizerEntry] },
- { timestampMs: 161_000, entries: [summarizerEntry] },
+ { timestampMs: 30_000, flagged: false, entries: [summarizerEntry] },
+ { timestampMs: 161_000, flagged: false, entries: [summarizerEntry] },
],
},
{
@@ -92,11 +97,13 @@ describe('observation utils', () => {
expected: [
{
timestampMs: 42_000,
+ flagged: true,
entries: [
{
scannerName: 'Error monitor',
headline: 'Verdict: yes',
snippet: 'Error toast shown',
+ sentence: 'Error toast shown (00:42)',
},
],
},
@@ -111,9 +118,15 @@ describe('observation utils', () => {
expected: [
{
timestampMs: 42_000,
+ flagged: false,
entries: [
- { scannerName: 'Monitor A', headline: null, snippet: 'Saw it' },
- { scannerName: 'Scorer B', headline: 'Score: 3', snippet: 'Also saw it' },
+ { scannerName: 'Monitor A', headline: null, snippet: 'Saw it', sentence: 'Saw it (00:42)' },
+ {
+ scannerName: 'Scorer B',
+ headline: 'Score: 3',
+ snippet: 'Also saw it',
+ sentence: 'Also saw it (00:42)',
+ },
],
},
],
@@ -129,8 +142,14 @@ describe('observation utils', () => {
expected: [
{
timestampMs: 42_000,
+ flagged: false,
entries: [
- { scannerName: 'Scanner', headline: null, snippet: `${longSentence.slice(0, 159)}…` },
+ {
+ scannerName: 'Scanner',
+ headline: null,
+ snippet: `${longSentence.slice(0, 159)}…`,
+ sentence: `${longSentence} (00:42)`,
+ },
],
},
],
@@ -156,7 +175,15 @@ describe('observation utils', () => {
expected: [
{
timestampMs: 42_000,
- entries: [{ scannerName: 'Quick summary', headline: null, snippet: 'Rage clicked pay' }],
+ flagged: false,
+ entries: [
+ {
+ scannerName: 'Quick summary',
+ headline: null,
+ snippet: 'Rage clicked pay',
+ sentence: 'Rage clicked pay (00:42)',
+ },
+ ],
},
],
},
@@ -174,12 +201,108 @@ describe('observation utils', () => {
}),
],
expected: [
- { timestampMs: 42_000, entries: [{ scannerName: 'Scanner', headline: null, snippet: null }] },
+ {
+ timestampMs: 42_000,
+ flagged: false,
+ entries: [{ scannerName: 'Scanner', headline: null, snippet: null, sentence: null }],
+ },
+ ],
+ },
+ {
+ name: 'sub-second citations merge into the whole second, flagged when any monitor there answered yes',
+ observations: [
+ makeObservation(
+ 'summarizer',
+ {
+ summary: 'Paid',
+ summary_segments: [
+ { kind: 'text', value: 'Paid' },
+ { kind: 'chip', timestamp_ms: 42_400 },
+ ],
+ },
+ 'succeeded',
+ 'Session summarizer'
+ ),
+ makeObservation(
+ 'monitor',
+ { verdict: 'yes', reasoning: 'Paid (t 42).' },
+ 'succeeded',
+ 'Pay monitor'
+ ),
+ ],
+ expected: [
+ {
+ timestampMs: 42_000,
+ flagged: true,
+ entries: [
+ {
+ scannerName: 'Session summarizer',
+ headline: null,
+ snippet: 'Paid',
+ sentence: 'Paid (00:42)',
+ },
+ {
+ scannerName: 'Pay monitor',
+ headline: 'Verdict: yes',
+ snippet: 'Paid',
+ sentence: 'Paid (00:42)',
+ },
+ ],
+ },
],
},
])('$name', ({ observations, expected }) => {
expect(observationSeekbarMarks(observations)).toEqual(expected)
})
+
+ it.each<{ name: string; reasoning: string; snippets: (string | null)[]; sentences: string[] }>([
+ {
+ name: 'clauses between chips drop dangling punctuation, brackets and conjunctions',
+ reasoning:
+ 'Opened the page (t 10), they searched (t 20), and hit an error (see (t 30)) so a banner appeared: (t 40).',
+ snippets: ['Opened the page', '…they searched', '…hit an error', '…a banner appeared'],
+ sentences: Array(4).fill(
+ 'Opened the page (00:10), they searched (00:20), and hit an error (see (00:30)) so a banner appeared: (00:40)'
+ ),
+ },
+ {
+ name: 'a clause ending on a function word drops it',
+ reasoning: 'For instance, after selecting a recording at (t 49), buffering appeared (t 51).',
+ snippets: ['For instance, after selecting a recording', '…buffering appeared'],
+ sentences: Array(2).fill(
+ 'For instance, after selecting a recording at (00:49), buffering appeared (00:51)'
+ ),
+ },
+ {
+ name: 'a clause too short to read extends to the next chip, then to the whole sentence',
+ reasoning: 'First (t 5) the user paid (t 8). At (t 12) the page went blank. Then (t 20).',
+ snippets: ['First the user paid', '…the user paid', 'At the page went blank', null],
+ sentences: [
+ 'First (00:05) the user paid (00:08)',
+ 'First (00:05) the user paid (00:08)',
+ 'At (00:12) the page went blank',
+ 'Then (00:20)',
+ ],
+ },
+ {
+ name: 'a citation opening a sentence belongs to the sentence before it',
+ reasoning: 'The user paid. (t 8) The page went blank (t 12).',
+ snippets: ['The user paid', 'The page went blank'],
+ sentences: ['The user paid', '(00:08) The page went blank (00:12)'],
+ },
+ {
+ name: 'a citation opening the text does not make the clause after it mid-sentence',
+ reasoning: '(t 5) The user paid (t 8).',
+ snippets: ['The user paid', 'The user paid'],
+ sentences: Array(2).fill('(00:05) The user paid (00:08)'),
+ },
+ ])('$name', ({ reasoning, snippets, sentences }) => {
+ const entries = observationSeekbarMarks([makeObservation('monitor', { reasoning })]).map(
+ (mark) => mark.entries[0]
+ )
+ expect(entries.map((e) => e.snippet)).toEqual(snippets)
+ expect(entries.map((e) => e.sentence)).toEqual(sentences)
+ })
})
describe('dockObservations', () => {
diff --git a/products/replay_vision/frontend/utils/observation.ts b/products/replay_vision/frontend/utils/observation.ts
index b687d8cbf98b..bc3e6680eb55 100644
--- a/products/replay_vision/frontend/utils/observation.ts
+++ b/products/replay_vision/frontend/utils/observation.ts
@@ -1,4 +1,5 @@
import { dayjs } from 'lib/dayjs'
+import { colonDelimitedDuration } from 'lib/utils/durations'
import { type ReplayObservationApi, ScannerOriginEnumApi, ScannerTypeEnumApi } from '../generated/api.schemas'
import { citedTextToPlainText, parseCitedSegments } from './citations'
@@ -122,38 +123,71 @@ export interface ObservationSeekbarMarkEntry {
scannerName: string
headline: string | null
snippet: string | null
+ sentence: string | null
}
export interface ObservationSeekbarMark {
timestampMs: number
entries: ObservationSeekbarMarkEntry[]
+ /** A monitor answered yes here, so the moment is drawn stronger. */
+ flagged: boolean
+}
+
+export function isFlaggedObservation(obs: ReplayObservationApi): boolean {
+ return obs.scanner_snapshot?.scanner_type === 'monitor' && readVerdict(obs) === 'yes'
+}
+
+/** Models cite whole seconds, so a sub-second offset is the same moment. */
+export function markBucketMs(timestampMs: number): number {
+ return Math.floor(Math.max(0, timestampMs) / 1000) * 1000
}
const SNIPPET_MAX_LENGTH = 160
+const SNIPPET_MIN_WORDS = 2
+const CHIP_PLACEHOLDER = '\uE000'
+const CHIP_PLACEHOLDER_RE = /\uE000/g
+const DANGLING_TAIL_RE =
+ /\s+(a|an|the|and|or|but|as|at|in|on|to|of|for|by|with|from|into|onto|about|around|near|after|before|during|until|when|while|where|which|that|then|so)$/i
-function lastSentence(text: string): string | null {
- // Flattened first: a mark has room for one line, where a bullet marker reads as the sentence start.
- const flat = flattenMarkdownToLine(text)
- if (!flat) {
- return null
- }
- // No lookbehind regex, it breaks chunk parsing on older browsers.
- let start = 0
- for (const match of flat.matchAll(/[.!?]+\s+/g)) {
- start = match.index + match[0].length
+/** Fragments left between chips, e.g. `) and the banner appeared` or `, then it failed (see`. */
+function tidyClause(fragment: string): string {
+ let clause = fragment
+ .replace(/[.!?]+\s*$/, '')
+ .replace(/^[^\p{L}\p{N}"'“‘([]+/u, '')
+ .replace(/^(and|but|then|so)\b\s*/i, '')
+ .replace(/\s*\([^)]*$/, '')
+ for (;;) {
+ const trimmed = clause.replace(/[\s,;:\-–—]+$/, '').replace(DANGLING_TAIL_RE, '')
+ if (trimmed === clause) {
+ return clause
+ }
+ clause = trimmed
}
- const last = flat
- .slice(start)
- .replace(/[.!?]+$/, '')
+}
+
+function wordCount(text: string): number {
+ return text.split(/\s+/).filter(Boolean).length
+}
+
+function tidySentence(text: string): string {
+ return text
+ .replace(/\s+([,.;:!?)])/g, '$1')
+ .replace(/\s{2,}/g, ' ')
.trim()
- if (!last) {
- return null
- }
- return last.length > SNIPPET_MAX_LENGTH ? `${last.slice(0, SNIPPET_MAX_LENGTH - 1)}…` : last
}
-/** Cited timestamps in a succeeded observation's output, each with the sentence that cites it. */
-function readCitations(obs: ReplayObservationApi): { timestampMs: number; snippet: string | null }[] {
+function truncate(text: string): string {
+ return text.length > SNIPPET_MAX_LENGTH ? `${text.slice(0, SNIPPET_MAX_LENGTH - 1)}…` : text
+}
+
+interface Citation {
+ timestampMs: number
+ snippet: string | null
+ sentence: string | null
+}
+
+/** Cited timestamps in a succeeded observation's output, each with the clause that cites it. */
+function readCitations(obs: ReplayObservationApi): Citation[] {
const output = readModelOutput(obs)
if (!output || obs.status !== 'succeeded') {
return []
@@ -165,23 +199,79 @@ function readCitations(obs: ReplayObservationApi): { timestampMs: number; snippe
if (typeof text !== 'string' || !text) {
return []
}
- const parsed = parseCitedSegments(text, segments)
- const snippetByTimestamp = new Map<number, string | null>()
- parsed.forEach((segment, index) => {
- if (segment.kind !== 'chip' || snippetByTimestamp.has(segment.timestamp_ms)) {
- return
+ let flat = ''
+ const chips: { timestampMs: number; offset: number }[] = []
+ for (const segment of parseCitedSegments(text, segments)) {
+ if (segment.kind === 'chip') {
+ flat += flat ? ` ${CHIP_PLACEHOLDER}` : CHIP_PLACEHOLDER
+ chips.push({ timestampMs: segment.timestamp_ms, offset: flat.length - 1 })
+ continue
}
- let snippet: string | null = null
- for (let i = index - 1; i >= 0; i--) {
- const previous = parsed[i]
- if (previous.kind === 'text') {
- snippet = lastSentence(previous.value)
+ const piece = flattenMarkdownToLine(segment.value)
+ if (piece) {
+ flat += flat ? ` ${piece}` : piece
+ }
+ }
+ // No lookbehind regex, it breaks chunk parsing on older browsers.
+ const sentenceStarts = [0, ...[...flat.matchAll(/[.!?]+\s+/g)].map((m) => m.index + m[0].length)]
+ const sentenceStart = (offset: number): number => {
+ let start = 0
+ for (const s of sentenceStarts) {
+ if (s > offset) {
break
}
+ start = s
}
- snippetByTimestamp.set(segment.timestamp_ms, snippet)
- })
- return [...snippetByTimestamp.entries()].map(([timestampMs, snippet]) => ({ timestampMs, snippet }))
+ return start
+ }
+ const hasText = (slice: string): boolean => slice.replace(CHIP_PLACEHOLDER_RE, '').trim() !== ''
+
+ const seen = new Set<number>()
+ const citations: Citation[] = []
+ for (const chip of chips) {
+ if (seen.has(chip.timestampMs)) {
+ continue
+ }
+ seen.add(chip.timestampMs)
+ let sStart = sentenceStart(chip.offset)
+ let sEnd = sentenceStarts.find((s) => s > chip.offset) ?? flat.length
+ if (sStart > 0 && !hasText(flat.slice(sStart, chip.offset))) {
+ sEnd = sStart
+ sStart = sentenceStart(sStart - 1)
+ }
+ const inSentence = chips.filter((c) => c.offset >= sStart && c.offset < sEnd)
+ const previous = inSentence.filter((c) => c.offset < chip.offset).pop()
+ const next = inSentence.find((c) => c.offset > chip.offset)
+ const from = previous ? previous.offset + 1 : sStart
+ const to = next ? next.offset : sEnd
+ let clause = tidyClause(flat.slice(from, Math.min(chip.offset, sEnd)))
+ if (wordCount(clause) < SNIPPET_MIN_WORDS) {
+ clause = tidyClause(tidySentence(flat.slice(from, to).replace(CHIP_PLACEHOLDER_RE, '')))
+ }
+ let midSentence = hasText(flat.slice(sStart, from))
+ if (wordCount(clause) < SNIPPET_MIN_WORDS) {
+ clause = tidyClause(tidySentence(flat.slice(sStart, sEnd).replace(CHIP_PLACEHOLDER_RE, '')))
+ midSentence = false
+ }
+ const times = inSentence.map((c) => c.timestampMs)
+ const raw = flat.slice(sStart, sEnd)
+ const sentence = hasText(raw)
+ ? tidySentence(
+ raw.replace(
+ CHIP_PLACEHOLDER_RE,
+ () => `(${colonDelimitedDuration(Math.floor(times.shift()! / 1000), null)})`
+ )
+ ).replace(/[\s.!?,;:]+$/, '')
+ : null
+ citations.push({
+ timestampMs: chip.timestampMs,
+ snippet: clause
+ ? truncate(midSentence ? `…${clause}` : clause.charAt(0).toUpperCase() + clause.slice(1))
+ : null,
+ sentence,
+ })
+ }
+ return citations
}
function observationHeadline(obs: ReplayObservationApi): string | null {
@@ -197,21 +287,31 @@ function observationHeadline(obs: ReplayObservationApi): string | null {
return null
}
-/** One mark per cited timestamp; entries merged when scanners cite the same moment. */
+/** One mark per cited second; entries merged when scanners cite the same moment. */
export function observationSeekbarMarks(observations: ReplayObservationApi[]): ObservationSeekbarMark[] {
const entriesByTimestamp = new Map<number, Map<string, ObservationSeekbarMarkEntry>>()
+ const flaggedTimestamps = new Set<number>()
for (const obs of observations) {
const scannerName = scannerLabel(obs)
const headline = observationHeadline(obs)
- for (const { timestampMs, snippet } of readCitations(obs)) {
- const entries = entriesByTimestamp.get(timestampMs) ?? new Map<string, ObservationSeekbarMarkEntry>()
- entries.set(JSON.stringify([scannerName, headline, snippet]), { scannerName, headline, snippet })
- entriesByTimestamp.set(timestampMs, entries)
+ const flagged = isFlaggedObservation(obs)
+ for (const { timestampMs, snippet, sentence } of readCitations(obs)) {
+ const bucket = markBucketMs(timestampMs)
+ const entries = entriesByTimestamp.get(bucket) ?? new Map<string, ObservationSeekbarMarkEntry>()
+ entries.set(JSON.stringify([scannerName, headline, snippet]), { scannerName, headline, snippet, sentence })
+ entriesByTimestamp.set(bucket, entries)
+ if (flagged) {
+ flaggedTimestamps.add(bucket)
+ }
}
}
return [...entriesByTimestamp.entries()]
.sort(([a], [b]) => a - b)
- .map(([timestampMs, entries]) => ({ timestampMs, entries: [...entries.values()] }))
+ .map(([timestampMs, entries]) => ({
+ timestampMs,
+ entries: [...entries.values()],
+ flagged: flaggedTimestamps.has(timestampMs),
+ }))
}
/** One succeeded observation as clipboard text: a metadata line, then the result body. */
diff --git a/products/replay_vision/frontend/utils/observationTimeline.test.ts b/products/replay_vision/frontend/utils/observationTimeline.test.ts
new file mode 100644
index 000000000000..d35d1963e1cd
--- /dev/null
+++ b/products/replay_vision/frontend/utils/observationTimeline.test.ts
@@ -0,0 +1,26 @@
+import type { ObservationSeekbarMark } from './observation'
+import { TIMELINE_GAP_MAX_PX, currentMarkIndex, nextMarkAfter, timelineGapPx } from './observationTimeline'
+
+const mark = (timestampMs: number): ObservationSeekbarMark => ({ timestampMs, entries: [], flagged: false })
+const marks = [mark(10_000), mark(42_000), mark(42_000), mark(90_000)]
+
+describe('observationTimeline', () => {
+ it.each<[string, number, number]>([
+ ['no gap', 0, 0],
+ ['scales with elapsed seconds', 10_000, 3],
+ ['caps at the ceiling', 600_000, TIMELINE_GAP_MAX_PX],
+ ['never negative', -5_000, 0],
+ ])('timelineGapPx: %s', (_, deltaMs, expected) => {
+ expect(timelineGapPx(deltaMs)).toBe(expected)
+ })
+
+ it.each<[string, number, number, number | null]>([
+ ['before the first mark', 0, -1, 10_000],
+ ['exactly on a mark', 42_000, 2, 90_000],
+ ['between marks', 50_000, 2, 90_000],
+ ['past the last mark', 100_000, 3, null],
+ ])('playhead %s', (_, playerTimeMs, expectedIndex, expectedNextMs) => {
+ expect(currentMarkIndex(marks, playerTimeMs)).toBe(expectedIndex)
+ expect(nextMarkAfter(marks, playerTimeMs)?.timestampMs ?? null).toBe(expectedNextMs)
+ })
+})
diff --git a/products/replay_vision/frontend/utils/observationTimeline.ts b/products/replay_vision/frontend/utils/observationTimeline.ts
new file mode 100644
index 000000000000..fdfdd75f8f78
--- /dev/null
+++ b/products/replay_vision/frontend/utils/observationTimeline.ts
@@ -0,0 +1,26 @@
+import type { ObservationSeekbarMark } from './observation'
+
+// Rows are spaced by elapsed time, capped so one quiet stretch can't push the rest off screen.
+export const TIMELINE_GAP_PX_PER_SECOND = 0.3
+export const TIMELINE_GAP_MAX_PX = 20
+
+export function timelineGapPx(deltaMs: number): number {
+ return Math.min(TIMELINE_GAP_MAX_PX, Math.max(0, (deltaMs / 1000) * TIMELINE_GAP_PX_PER_SECOND))
+}
+
+/** -1 when playback has not reached the first mark. */
+export function currentMarkIndex(marks: ObservationSeekbarMark[], playerTimeMs: number): number {
+ let index = -1
+ for (let i = 0; i < marks.length; i++) {
+ if (marks[i].timestampMs <= playerTimeMs) {
+ index = i
+ } else {
+ break
+ }
+ }
+ return index
+}
+
+export function nextMarkAfter(marks: ObservationSeekbarMark[], playerTimeMs: number): ObservationSeekbarMark | null {
+ return marks.find((mark) => mark.timestampMs > playerTimeMs) ?? null
+}