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): show the summary's chapters as a breakdown in the observations tab (#110752)

Tue Haulunda4e8b81ffbe6
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 40809615f054..a763196a1b2a 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -12482,6 +12482,42 @@ snapshots:
hash: v1.k794b7964.27a90f028f594c371370fdc56b6ba14a427b34c27292e63f3c0a94e939e6a941.051i8LHCU3DaiN6kC_4gXIOwokLOxcjBVJ9zjcH-0HA
scenes-app-replay-vision-recordingexpiredtag--default--light:
hash: v1.k794b7964.dd4a7fd2ad97f5474ad762293c6fe59be57e93be64067e04a655e9443b8670d2.yotBh0ZOpK-CikDFoXSsLVMJdKw1WZJPq_2H6nO5hfg
+ scenes-app-replay-vision-recordingtimeline--chapters-without-frames--dark:
+ hash: v1.k794b7964.e29d5d97d464489fd6c3143b6557cef245c81cc6072fda66045c4ce9cf65bae0.VYeyIQtD-t4Nj0p9fjfOt6SNRJUhwPrQQX1m4BmieSw
+ scenes-app-replay-vision-recordingtimeline--chapters-without-frames--light:
+ hash: v1.k794b7964.6ef6fa13d824c61e61bc0d6c9c9043dc02deb51c3cf18ca08b9de96671bc2ba3.dmuxNKi5hFUhWseFgkoA1ZLSH56WYHf5kC8Vx8zja0M
+ scenes-app-replay-vision-recordingtimeline--long-recording-with-idle-gaps--dark:
+ hash: v1.k794b7964.30c333f3e18fb5b950b245b0336fffc7fe69360815c6f12876d05df64f1d9a2e.EFMh5EzIwkQS584dbshtTZZremEPj0Ioc0O2hr2F0EQ
+ scenes-app-replay-vision-recordingtimeline--long-recording-with-idle-gaps--light:
+ hash: v1.k794b7964.54ecc970414740c49a50737af25ad1dc91a5a4d701e65d94dcb0add43c44be6f.8RHvCr0sImcO2TYtAGLKRW-syItq2yTsN7IrpCIwEPo
+ scenes-app-replay-vision-recordingtimeline--medium-recording-with-scans--dark:
+ hash: v1.k794b7964.6c1a910283df8f1ef6c32197cbecd588443a287e50d4c6e4b1b7e0f76cd232df.nxKlXYNhd7Pae4D6OMK4pHXQ7tNhmgj8dhj_rHeadxQ
+ scenes-app-replay-vision-recordingtimeline--medium-recording-with-scans--light:
+ hash: v1.k794b7964.51e6e67b5266789e678498a466586787af05739bec32c7658dde45905d8a1cf0.BlnYjegsM_hjqQLRMB-eiz6fc3yAMIrS1AlmM029jS4
+ scenes-app-replay-vision-recordingtimeline--one-scan-no-summary--dark:
+ hash: v1.k794b7964.7a797b048f18259d51bbb61409d961bebe67e989e14450b012785796aef3f0ff.YmD9NFpiI-fkinozTKl6wrGH74H1CY6_4m9JsfQBMsk
+ scenes-app-replay-vision-recordingtimeline--one-scan-no-summary--light:
+ hash: v1.k794b7964.ee642d929551e335580ca212353fb62ba7f27640558dc0ec93a16243c11733e8.dXgtpRprHyAv0Ed1v5eL4bOu9_Hne-kw23mdSqGFbLY
+ scenes-app-replay-vision-recordingtimeline--short-recording-summary-only--dark:
+ hash: v1.k794b7964.fda12edf03edbc5e2e20f8c2a6ab80b7d1b1d807d668c6f80d3fc900915edf26.Z2T5FhsfpDpSCuOs0REv-IsBhf2rSmcM74xKb9dP0dM
+ scenes-app-replay-vision-recordingtimeline--short-recording-summary-only--light:
+ hash: v1.k794b7964.43c1e3bc81d9ed38bc7c556710bf9a017d137f5571206cc318b3a239cdedfd7a.MJQvCUblaQfiZBUv_lWmoDWBuYhHwxbbHI0_549uA40
+ scenes-app-replay-vision-recordingtimeline--summary-from-before-breakdowns--dark:
+ hash: v1.k794b7964.24a1ff1392ac386c427c67fd17001666fd4b45fe2a98714c762c1ede8d6a5bee.0G6QHJ7iN6BNHH5R-aAqiDtU9azuQtAgQIZ-0r0MXug
+ scenes-app-replay-vision-recordingtimeline--summary-from-before-breakdowns--light:
+ hash: v1.k794b7964.dd57548ef167a241b4640475c1b678d4e48016e5c468e96263ed6985d4b0e9d1.jVbfu2YWiSVVlvYUefcaZ5X4swQzd4gol6Jnm1rw5zA
+ scenes-app-replay-vision-recordingtimeline--summary-in-progress--dark:
+ hash: v1.k794b7964.02b563e162ad594ce42807ab9f6527dd0b0a94d076f5e376af4aa1c9e0262747.bEOm8Ud6DvSsOnHKkdJqJRO0GoAVFotQDphesBy1s3g
+ scenes-app-replay-vision-recordingtimeline--summary-in-progress--light:
+ hash: v1.k794b7964.2025c9acd9d06dbb0568ff23882c29b23e7ace5ac63a2fa09102ca039b37c0b6.JRxISHQLRnBhFg_FMN_BFXtJgymUQtTiVJyIRGX32-8
+ scenes-app-replay-vision-recordingtimeline--summary-with-idle-chapters-from-before-inactive-periods--dark:
+ hash: v1.k794b7964.cd013789e544963b8d95bf1d4eacee9b8b4336960e9f4735583d7d9ff353d10d.yD-t6X-ZsnRGTCeHoDB8kgvMnf1dU1G-_waP6cZOmGA
+ scenes-app-replay-vision-recordingtimeline--summary-with-idle-chapters-from-before-inactive-periods--light:
+ hash: v1.k794b7964.2bd8d7cef9ba9bbc6ca109d0305946479a40e49b5ce1b94e5441ae90e3452daf.2kmw3D-4NBPGsouPDa4Do8KnBfMO6PPGlFWsyKC_MZs
+ scenes-app-replay-vision-recordingtimeline--very-long-recording--dark:
+ hash: v1.k794b7964.628aadee0591ed32bec6030dad4acc732423c095d82a0f75930710736851fa28.3mh2R55GMgaCMNSdXOcUqECUPP4MmFCDYu_0jqs331E
+ scenes-app-replay-vision-recordingtimeline--very-long-recording--light:
+ hash: v1.k794b7964.a04715d7aa78cff8fcfb049420139f30f87ac31872679219f3ee7f4be8475cf2.RW9X9AswVQmbJBWPH6SLAV52RPjoUy5MIcCOXDIGeBM
scenes-app-replay-vision-spendtrajectorychart--hits-the-limit--dark:
hash: v1.k794b7964.cf96414912c6d8f0d73808db3f1d833c661d12b3b0449cdd49b95d4dc8059e80.3sA2mn18MksUWQQ4mq6wEPbkJhGP3O258Y6Q2fTWhgM
scenes-app-replay-vision-spendtrajectorychart--hits-the-limit--light:
diff --git a/frontend/src/scenes/session-recordings/player/PlayerSidebar.tsx b/frontend/src/scenes/session-recordings/player/PlayerSidebar.tsx
index ec3db6760aa6..939c5d85ba4b 100644
--- a/frontend/src/scenes/session-recordings/player/PlayerSidebar.tsx
+++ b/frontend/src/scenes/session-recordings/player/PlayerSidebar.tsx
@@ -108,9 +108,9 @@ export function PlayerSidebar(): JSX.Element {
// The root scrolls, not the bar, so the scrollbar cannot collide with the bar's bottom-anchored underline
barClassName="!mb-0 w-max min-w-full !overflow-x-visible"
size="small"
- className="overflow-x-auto overflow-y-clip !self-start"
+ // Fills the row rather than hugging the tabs, so subpixel tab widths cannot leave a scrollbar with nothing to scroll
+ className="flex-1 min-w-0 overflow-x-auto overflow-y-clip !self-start"
/>
- <div className="flex flex-1 border-b shrink-0" />
<div className="flex gap-1 border-b end">
<LemonButton
data-attr="player-sidebar-dock-toggle"
diff --git a/products/replay_vision/frontend/__mocks__/recordingTimelineObservations.ts b/products/replay_vision/frontend/__mocks__/recordingTimelineObservations.ts
new file mode 100644
index 000000000000..2f1b5660cb69
--- /dev/null
+++ b/products/replay_vision/frontend/__mocks__/recordingTimelineObservations.ts
@@ -0,0 +1,133 @@
+import type { ReplayObservationApi } from '../generated/api.schemas'
+
+// Fixtures for the recording timeline's stories: a summary with chapters and idle, and scans with key moments.
+export const MIN = 60_000
+let nextId = 1
+const id = (): string => `0198f2a1-0000-7000-8000-${String(nextId++).padStart(12, '0')}`
+
+export interface ChapterSpec {
+ start: number
+ end: number
+ title: string
+ frame?: boolean
+}
+
+export function summary({
+ chapters = [],
+ inactive = [],
+ status = 'succeeded',
+ legacyIdle = false,
+}: {
+ chapters?: ChapterSpec[]
+ inactive?: [number, number][]
+ status?: ReplayObservationApi['status']
+ legacyIdle?: boolean
+}): ReplayObservationApi {
+ const output: Record<string, unknown> = {
+ scanner_type: 'summarizer',
+ title: 'Session summary',
+ summary: '',
+ confidence: 0.8,
+ chapters: chapters.map((c) => ({
+ kind: 'activity',
+ start_ms: c.start,
+ end_ms: c.end,
+ title: c.title,
+ thumbnail_ms: Math.round((c.start + c.end) / 2),
+ })),
+ }
+ if (legacyIdle) {
+ output.chapters = (output.chapters as Record<string, unknown>[]).flatMap((c, i) =>
+ i === 0 ? [c] : [{ kind: 'idle', start_ms: c.start_ms, end_ms: c.start_ms, title: 'Idle' }, c]
+ )
+ } else {
+ output.inactive_periods = inactive.map(([start, end]) => ({ start_ms: start, end_ms: end }))
+ }
+ return {
+ id: id(),
+ session_id: 'session-1',
+ status,
+ created_at: '2026-10-02T09:00:00Z',
+ scanner_origin: 'inline',
+ scanner_snapshot: { name: 'Quick summary', scanner_type: 'summarizer', scanner_config: {} },
+ scanner_result: status === 'succeeded' ? { model_output: output } : null,
+ media: chapters.flatMap((c, position) =>
+ c.frame === false ? [] : [{ id: id(), kind: 'chapter', position, asset_id: 1 }]
+ ),
+ } as unknown as ReplayObservationApi
+}
+
+function scan(
+ scannerType: 'monitor' | 'scorer' | 'classifier',
+ name: string,
+ keyMomentMs: number | null,
+ answer: Record<string, unknown>
+): ReplayObservationApi {
+ return {
+ id: id(),
+ session_id: 'session-1',
+ status: 'succeeded',
+ created_at: '2026-10-02T09:05:00Z',
+ scanner_origin: 'configured',
+ scanner_snapshot: { name, scanner_type: scannerType, scanner_config: {} },
+ scanner_result: {
+ model_output: { scanner_type: scannerType, confidence: 0.8, key_moment_ms: keyMomentMs, ...answer },
+ },
+ media: [],
+ } as unknown as ReplayObservationApi
+}
+
+export const checkoutMonitor = (at: number | null): ReplayObservationApi =>
+ scan('monitor', 'Struggled at checkout', at, { verdict: 'yes', reasoning: '' })
+export const frustrationScorer = (at: number | null): ReplayObservationApi =>
+ scan('scorer', 'Frustration', at, { score: 4, reasoning: '' })
+export const intentClassifier = (at: number | null): ReplayObservationApi =>
+ scan('classifier', 'Visit intent', at, { tags: ['Pricing research'], reasoning: '' })
+
+export const SHORT = [
+ { start: 0, end: 18_000, title: 'Browses surveys product page' },
+ { start: 18_000, end: 39_000, title: 'Reviews survey use cases table' },
+ { start: 39_000, end: 61_000, title: 'Opens install with AI prompt' },
+]
+
+export const MEDIUM = [
+ { start: 0, end: 52_000, title: 'Searches for winter jackets' },
+ { start: 52_000, end: 118_000, title: 'Compares three parka product pages' },
+ { start: 131_000, end: 176_000, title: 'Adds insulated parka to cart' },
+ { start: 176_000, end: 214_000, title: 'Applies discount code at checkout' },
+ { start: 214_000, end: 236_000, title: 'Payment form rejects card' },
+ { start: 236_000, end: 291_000, title: 'Retries payment with a second card' },
+]
+export const MEDIUM_INACTIVE: [number, number][] = [
+ [118_000, 131_000],
+ [140_000, 146_000],
+]
+
+export const LONG: ChapterSpec[] = [
+ { start: 0, end: 3 * MIN, title: 'Signs in and opens the dashboard' },
+ { start: 3 * MIN, end: 7 * MIN, title: 'Filters revenue report by region' },
+ { start: 17 * MIN, end: 21 * MIN, title: 'Exports quarterly revenue to CSV' },
+ { start: 21 * MIN, end: 34 * MIN, title: 'Edits invoice line items' },
+ { start: 44 * MIN, end: 47 * MIN, title: 'Opens billing settings' },
+ { start: 47 * MIN, end: 52 * MIN, title: 'Updates payment method details' },
+ { start: 52 * MIN, end: 58 * MIN, title: 'Invites a teammate to the workspace' },
+]
+export const LONG_INACTIVE: [number, number][] = [
+ [7 * MIN, 17 * MIN],
+ [25 * MIN, 31 * MIN],
+ [34 * MIN, 44 * MIN],
+ [58 * MIN, 61 * MIN],
+]
+
+export const VERY_LONG: ChapterSpec[] = Array.from({ length: 20 }, (_, i) => ({
+ start: i * 9 * MIN,
+ end: i * 9 * MIN + 6 * MIN,
+ title: [
+ 'Triages alerts on the sensor dashboard',
+ 'Acknowledges the cooling unit alert',
+ 'Reviews sensor history for unit 4',
+ 'Opens the maintenance ticket form',
+ 'Assigns the ticket to the on-call engineer',
+ ][i % 5],
+}))
+export const VERY_LONG_INACTIVE: [number, number][] = VERY_LONG.map((c) => [c.end, c.end + 3 * MIN])
diff --git a/products/replay_vision/frontend/components/ObservationSeekbarMarks.tsx b/products/replay_vision/frontend/components/ObservationSeekbarMarks.tsx
index 0f016f349420..1f922cf935b3 100644
--- a/products/replay_vision/frontend/components/ObservationSeekbarMarks.tsx
+++ b/products/replay_vision/frontend/components/ObservationSeekbarMarks.tsx
@@ -7,7 +7,7 @@ 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 type { TimelineMarker } from '../utils/recordingTimeline'
import { visionSurfaceShown } from '../utils/visionSurface'
interface ObservationSeekbarMarksProps {
@@ -15,41 +15,6 @@ 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 {
@@ -66,39 +31,62 @@ function ObservationSeekbarMarksContent({
onSeek,
}: ObservationSeekbarMarksProps & { sessionId: string }): JSX.Element | null {
const logic = observationsDockLogic({ sessionId })
- const { seekbarMarks, hoveredMarkMs } = useValues(logic)
- const { setHoveredMark } = useActions(logic)
+ const { timeline, hoveredMarkMs } = useValues(logic)
+ const { setHoveredMark, focusObservation } = useActions(logic)
- if (seekbarMarks.length === 0 || endTimeMs <= 0) {
+ if (timeline.markers.length === 0 || endTimeMs <= 0) {
return null
}
+ // Scans can share a key moment, and stacked marks would hide all but the top one.
+ const groups = new Map<number, TimelineMarker[]>()
+ for (const marker of timeline.markers) {
+ groups.set(marker.timestampMs, [...(groups.get(marker.timestampMs) ?? []), marker])
+ }
+
return (
<>
- {seekbarMarks.map((mark) => {
- const position = (mark.timestampMs / endTimeMs) * 100
+ {[...groups.entries()].map(([timestampMs, markers]) => {
+ const position = (timestampMs / endTimeMs) * 100
if (position < 0 || position > 100) {
return null
}
+ const marker = markers[0]
return (
- <Tooltip key={mark.timestampMs} title={<ObservationMarkTooltip mark={mark} />} placement="top">
+ <Tooltip
+ key={timestampMs}
+ title={
+ <div className="flex flex-col gap-0.5">
+ <span className="font-medium">
+ {colonDelimitedDuration(Math.floor(timestampMs / 1000), null)}
+ </span>
+ {markers.map((m) => (
+ <span key={m.observationId}>
+ {[m.scannerName, m.result].filter(Boolean).join(' · ')}
+ </span>
+ ))}
+ </div>
+ }
+ placement="top"
+ >
<div
className={cn(
'PlayerSeekbar__observation',
- mark.flagged && 'PlayerSeekbar__observation--flagged',
- hoveredMarkMs === mark.timestampMs && 'PlayerSeekbar__observation--hovered'
+ markers.some((m) => m.flagged) && 'PlayerSeekbar__observation--flagged',
+ hoveredMarkMs === marker.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)}
+ onMouseEnter={() => setHoveredMark(marker.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()}
onClick={(e) => {
e.stopPropagation()
- onSeek(mark.timestampMs)
+ onSeek(marker.timestampMs)
+ focusObservation(marker.observationId)
}}
/>
</Tooltip>
diff --git a/products/replay_vision/frontend/components/ObservationThumbnail.tsx b/products/replay_vision/frontend/components/ObservationThumbnail.tsx
index a8b59d5139f5..b352f80fe5a0 100644
--- a/products/replay_vision/frontend/components/ObservationThumbnail.tsx
+++ b/products/replay_vision/frontend/components/ObservationThumbnail.tsx
@@ -10,6 +10,8 @@ import { ReplayObservationApi } from '../generated/api.schemas'
interface ObservationThumbnailProps {
observation: ReplayObservationApi
+ /** A summary chapter's index, to show that chapter's frame instead of the observation's thumbnail. */
+ chapter?: number
/** Sizing and shape come from the caller, since a table cell and a detail page want very different frames. */
className?: string
children?: React.ReactNode
@@ -18,7 +20,12 @@ interface ObservationThumbnailProps {
const RETRY_DELAY_MS = 2000
/** The frame the scan picked out of the session, as a 16:9 poster. */
-export function ObservationThumbnail({ observation, className, children }: ObservationThumbnailProps): JSX.Element {
+export function ObservationThumbnail({
+ observation,
+ chapter,
+ className,
+ children,
+}: ObservationThumbnailProps): JSX.Element {
const { currentTeamId } = useValues(teamLogic)
const [attempt, setAttempt] = useState(0)
const [failedId, setFailedId] = useState<string | null>(null)
@@ -28,7 +35,7 @@ export function ObservationThumbnail({ observation, className, children }: Obser
useEffect(() => {
setAttempt(0)
setFailedId(null)
- }, [observation.id])
+ }, [observation.id, chapter])
useEffect(() => {
return () => {
@@ -44,12 +51,21 @@ export function ObservationThumbnail({ observation, className, children }: Obser
// no requests. The URL is the endpoint rather than the asset, so a re-render after a retry still resolves.
// Optional at runtime, whatever the generated type says: fixtures and a response cached from before
// the field existed both reach here, and a poster must not take the scene down with it.
- const hasThumbnail = (observation.media ?? []).some((entry) => entry.kind === 'thumbnail')
+ const hasThumbnail = (observation.media ?? []).some((entry) =>
+ chapter === undefined ? entry.kind === 'thumbnail' : entry.kind === 'chapter' && entry.position === chapter
+ )
const baseSrc =
hasThumbnail && currentTeamId !== null && !failed
- ? getVisionObservationsThumbnailRetrieveUrl(String(currentTeamId), observation.id)
+ ? getVisionObservationsThumbnailRetrieveUrl(
+ String(currentTeamId),
+ observation.id,
+ chapter === undefined ? undefined : { chapter }
+ )
: undefined
- const src = baseSrc !== undefined && attempt > 0 ? `${baseSrc}?retry=${attempt}` : baseSrc
+ const src =
+ baseSrc !== undefined && attempt > 0
+ ? `${baseSrc}${baseSrc.includes('?') ? '&' : '?'}retry=${attempt}`
+ : baseSrc
const onError = (): void => {
// One retry: the redirect target can blink, and the poster would stay blank for the whole mount.
diff --git a/products/replay_vision/frontend/components/ObservationTimeline.tsx b/products/replay_vision/frontend/components/ObservationTimeline.tsx
deleted file mode 100644
index fa697087cd47..000000000000
--- a/products/replay_vision/frontend/components/ObservationTimeline.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-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'
-const ROW_GRID_HOURS = 'grid grid-cols-[4rem_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)
- const hasHours = marks.some((mark) => mark.timestampMs >= 3_600_000)
- const rowGrid = hasHours ? ROW_GRID_HOURS : ROW_GRID
- 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(rowGrid, '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(
- rowGrid,
- '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), hasHours ? 3 : 2)}
- </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 9ab8232443e0..0a1b4fda400b 100644
--- a/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.tsx
+++ b/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.tsx
@@ -1,8 +1,8 @@
import { useActions, useValues } from 'kea'
-import { type ReactNode, forwardRef, useEffect, useMemo, useRef, useState } from 'react'
+import { useEffect, useMemo, useRef } from 'react'
-import { IconChevronDown, IconChevronRight, IconCollapse, IconExpand, IconEye } from '@posthog/icons'
-import { LemonBadge, LemonButton, LemonInput, LemonSwitch, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
+import { IconChevronDown, IconChevronRight, IconEye } from '@posthog/icons'
+import { 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'
@@ -13,18 +13,10 @@ import { urls } from 'scenes/urls'
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 { SCANNER_TYPE_TAG_TYPE, scannerTypeLabel } from '../replay_scanners/types'
+import { isSummaryObservation, readModelOutput, readReasoning, scannerLabel } from '../utils/observation'
import { quotaUx } from '../utils/quotaProjection'
+import { currentRowIndex, nextTimelineStopMs, timelineRows as buildTimelineRows } from '../utils/recordingTimeline'
import { ScanBlock, recordingScanBlock } from '../utils/scanEligibility'
import { visionSurfaceShown } from '../utils/visionSurface'
import { CitedMarkdown } from './CitedMarkdown'
@@ -37,7 +29,7 @@ import {
} from './ObservationCard'
import { ObservationProgressBar } from './ObservationProgressBar'
import { ObservationRetryButton } from './ObservationRetryButton'
-import { ObservationTimeline } from './ObservationTimeline'
+import { RecordingTimeline } from './RecordingTimeline'
import { ScannerTypeBadge, scannerTypeIcon } from './ScannerTypeBadge'
export function PlayerSidebarObservationsTab(): JSX.Element | null {
@@ -163,59 +155,17 @@ function ObservationRuns({
onSeek: (timestampMs: number) => void
}): JSX.Element | null {
const logic = observationsDockLogic({ sessionId })
- const { focusedObservationId, followMoments, retryingObservationIds } = useValues(logic)
+ const { focusedObservationId, retryingObservationIds } = useValues(logic)
const { focusObservation, 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 focusedMarks = focused ? (marksByRun.get(focused.id) ?? []) : []
- const currentIndex = currentMarkIndex(focusedMarks, currentPlayerTime)
- const currentMs = currentIndex >= 0 ? focusedMarks[currentIndex].timestampMs : null
-
- useEffect(() => {
- if (!followMoments) {
- followedMs.current = null
- return
- }
- if (currentMs === null || followedMs.current === currentMs) {
- return
- }
- followedMs.current = currentMs
- paneRef.current?.querySelector<HTMLElement>(CURRENT_MOMENT_SELECTOR)?.scrollIntoView({ block: 'nearest' })
- }, [currentMs, followMoments])
-
if (observations.length === 0) {
return null
}
- const flaggedCount = observations.filter(isFlaggedObservation).length
+ const focused = observations.find((o) => o.id === focusedObservationId) ?? defaultFocus(observations)
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>
+ <>
+ <SectionHeader label="Observations" />
<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">
@@ -240,38 +190,26 @@ function ObservationRuns({
<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>
+ {observation.id === focused?.id && (
+ <FocusPane
+ observation={observation}
+ onSeek={onSeek}
+ onRetry={() => retryObservation(observation.id)}
+ retrying={retryingObservationIds.includes(observation.id)}
+ />
+ )}
</div>
)
})}
</div>
- </div>
+ </>
)
}
-function SectionHeader({
- label,
- count,
- className,
- children,
-}: {
- label: string
- count: number
- className?: string
- children?: ReactNode
-}): JSX.Element {
+function SectionHeader({ label, className }: { label: string; className?: string }): JSX.Element {
return (
<div
className={cn(
@@ -280,8 +218,6 @@ function SectionHeader({
)}
>
{label}
- <LemonBadge.Number count={count} maxDigits={2} size="small" status="muted" showZero />
- {children}
</div>
)
}
@@ -296,50 +232,29 @@ function RunResult({ observation }: { observation: ReplayObservationApi }): JSX.
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
+function FocusPane({
+ observation,
+ onSeek,
+ onRetry,
+ retrying,
+}: {
+ observation: ReplayObservationApi
+ onSeek: (timestampMs: number) => void
+ onRetry: () => void
+ retrying: boolean
+}): JSX.Element {
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"
+ className="overflow-hidden transition-[height] duration-200 ease-in-out border-t bg-surface-primary"
// 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 && (
@@ -369,37 +284,8 @@ const FocusPane = forwardRef<
)}
</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
- data-attr="vision-observation-open-from-sidebar"
- to={urls.replayVisionObservation(observation.id)}
- className="text-xs ml-auto"
- >
- View details
- </Link>
- </div>
- {hasText && showText && (
+ {hasText && (
<div className="text-sm">
{isSummary ? (
<ObservationPrimaryOutput
@@ -418,19 +304,33 @@ const FocusPane = forwardRef<
)}
</div>
)}
+ <Link
+ data-attr="vision-observation-open-from-sidebar"
+ to={urls.replayVisionObservation(observation.id)}
+ className="text-xs self-end"
+ >
+ View details
+ </Link>
</div>
</div>
</div>
)
-})
+}
function ObservationsTabContent({ sessionId }: { sessionId: string }): JSX.Element {
const logic = observationsDockLogic({ sessionId })
- const { observations, observationsLoading, seekbarMarks, followMoments } = useValues(logic)
- const { setFollowMoments, focusObservation } = useActions(logic)
+ const { observations, observationsLoading, timeline, followMoments, summarizePending } = useValues(logic)
+ const { setFollowMoments, summarize } = useActions(logic)
+ const { quota } = useValues(visionQuotaLogic)
+ const { disabledReason: quotaDisabledReason } = quotaUx(quota)
const lastJumpMs = useRef<number | null>(null)
+ const timelineRef = useRef<HTMLDivElement>(null)
+ const followedIndex = useRef<number | null>(null)
// The player logic is keyed; seek the exact mounted instance, not a propless default
- const { logicProps, sessionPlayerMetaData, currentPlayerTime } = useValues(sessionRecordingPlayerLogic)
+ const { logicProps, sessionPlayerMetaData, currentPlayerTime, sessionPlayerData } =
+ useValues(sessionRecordingPlayerLogic)
+ const durationMs = sessionPlayerData.durationMs > 0 ? sessionPlayerData.durationMs : null
+ const timelineRows = useMemo(() => buildTimelineRows(timeline, durationMs), [timeline, durationMs])
const seekToTime = (ms: number): void => {
sessionRecordingPlayerLogic.findMounted(logicProps)?.actions.seekToTime(ms)
}
@@ -440,20 +340,27 @@ function ObservationsTabContent({ sessionId }: { sessionId: string }): JSX.Eleme
lastJumpMs.current !== null && Math.abs(currentPlayerTime - lastJumpMs.current) < 1000
? lastJumpMs.current
: currentPlayerTime
- const nextMoment = nextMarkAfter(seekbarMarks, nextFrom)
- const jumpToNextMoment = (): void => {
- if (!nextMoment) {
+ const nextStopMs = nextTimelineStopMs(timeline, nextFrom)
+ const jumpToNext = (): void => {
+ if (nextStopMs === null) {
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)
- }
+ lastJumpMs.current = nextStopMs
+ seekToTime(nextStopMs)
}
+ const currentIndex = currentRowIndex(timelineRows, currentPlayerTime)
+
+ useEffect(() => {
+ if (!followMoments) {
+ followedIndex.current = null
+ return
+ }
+ if (currentIndex < 0 || followedIndex.current === currentIndex) {
+ return
+ }
+ followedIndex.current = currentIndex
+ timelineRef.current?.querySelector<HTMLElement>(CURRENT_MOMENT_SELECTOR)?.scrollIntoView({ block: 'nearest' })
+ }, [currentIndex, followMoments])
return (
<div className="flex flex-col flex-1 min-h-0" data-attr="vision-observations-tab">
@@ -485,7 +392,7 @@ function ObservationsTabContent({ sessionId }: { sessionId: string }): JSX.Eleme
<>
<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 && (
+ {timelineRows.length > 0 && (
<div className="ml-auto flex items-center gap-2">
<LemonSwitch
size="xsmall"
@@ -499,17 +406,31 @@ function ObservationsTabContent({ sessionId }: { sessionId: string }): JSX.Eleme
size="small"
type="secondary"
sideIcon={<IconChevronRight />}
- disabledReason={nextMoment ? undefined : 'No later moments'}
- onClick={jumpToNextMoment}
+ disabledReason={
+ nextStopMs !== null ? undefined : 'Nothing later in the recording'
+ }
+ onClick={jumpToNext}
data-attr="vision-next-moment"
>
- Next moment
+ Next
</LemonButton>
</span>
</div>
)}
</div>
- <ObservationRuns sessionId={sessionId} observations={observations} onSeek={seekToTime} />
+ <div className="flex-1 min-h-0 overflow-y-auto" ref={timelineRef}>
+ <SectionHeader label="Breakdown" />
+ <RecordingTimeline
+ timeline={timeline}
+ rows={timelineRows}
+ currentTimeMs={currentPlayerTime}
+ onSeek={seekToTime}
+ onSummarize={summarize}
+ summarizing={summarizePending}
+ summarizeDisabledReason={scanBlock?.reason ?? quotaDisabledReason}
+ />
+ <ObservationRuns sessionId={sessionId} observations={observations} onSeek={seekToTime} />
+ </div>
</>
)}
</div>
diff --git a/products/replay_vision/frontend/components/RecordingTimeline.stories.tsx b/products/replay_vision/frontend/components/RecordingTimeline.stories.tsx
new file mode 100644
index 000000000000..d0acb37756a5
--- /dev/null
+++ b/products/replay_vision/frontend/components/RecordingTimeline.stories.tsx
@@ -0,0 +1,117 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { mswDecorator } from '~/mocks/browser'
+import { sessionFrameResponse } from '~/mocks/fixtures/sessionFrame'
+
+import {
+ LONG,
+ LONG_INACTIVE,
+ MEDIUM,
+ MEDIUM_INACTIVE,
+ MIN,
+ SHORT,
+ VERY_LONG,
+ VERY_LONG_INACTIVE,
+ checkoutMonitor,
+ frustrationScorer,
+ intentClassifier,
+ summary,
+} from '../__mocks__/recordingTimelineObservations'
+import type { ReplayObservationApi } from '../generated/api.schemas'
+import { recordingTimeline, timelineRows } from '../utils/recordingTimeline'
+import { RecordingTimeline } from './RecordingTimeline'
+
+const meta: Meta<typeof RecordingTimeline> = {
+ title: 'Scenes-App/Replay Vision/RecordingTimeline',
+ component: RecordingTimeline,
+ decorators: [
+ mswDecorator({
+ get: { '/api/projects/:team_id/vision/observations/:id/thumbnail/': () => sessionFrameResponse() },
+ }),
+ (Story) => (
+ <div className="w-[420px] border rounded bg-surface-primary">
+ <Story />
+ </div>
+ ),
+ ],
+ parameters: { testOptions: { waitForLoadersToDisappear: false } },
+}
+export default meta
+
+type Story = StoryObj<{ observations: ReplayObservationApi[]; currentTimeMs?: number; durationMs?: number }>
+
+const render: Story['render'] = ({ observations, currentTimeMs = 0, durationMs }) => {
+ const timeline = recordingTimeline(observations)
+ durationMs ??= Math.max(5 * MIN, ...timeline.chapters.map((c) => c.endMs))
+ return (
+ <RecordingTimeline
+ timeline={timeline}
+ rows={timelineRows(timeline, durationMs)}
+ currentTimeMs={currentTimeMs}
+ onSeek={() => {}}
+ onSummarize={() => {}}
+ summarizing={false}
+ />
+ )
+}
+
+export const OneScanNoSummary: Story = {
+ render,
+ args: { observations: [checkoutMonitor(214_000)] },
+}
+
+export const SummaryInProgress: Story = {
+ render,
+ args: { observations: [summary({ status: 'running' }), checkoutMonitor(214_000)] },
+}
+
+export const SummaryFromBeforeBreakdowns: Story = {
+ render,
+ args: { observations: [summary({}), checkoutMonitor(214_000)] },
+}
+
+export const ShortRecordingSummaryOnly: Story = {
+ render,
+ args: { observations: [summary({ chapters: SHORT })], currentTimeMs: 25_000 },
+}
+
+export const MediumRecordingWithScans: Story = {
+ render,
+ args: {
+ observations: [
+ summary({ chapters: MEDIUM, inactive: MEDIUM_INACTIVE }),
+ checkoutMonitor(221_000),
+ frustrationScorer(240_000),
+ intentClassifier(60_000),
+ ],
+ currentTimeMs: 225_000,
+ },
+}
+
+export const LongRecordingWithIdleGaps: Story = {
+ render,
+ args: {
+ observations: [summary({ chapters: LONG, inactive: LONG_INACTIVE }), checkoutMonitor(50 * MIN)],
+ currentTimeMs: 12 * MIN,
+ },
+}
+
+export const VeryLongRecording: Story = {
+ render,
+ args: {
+ observations: [summary({ chapters: VERY_LONG, inactive: VERY_LONG_INACTIVE }), frustrationScorer(95 * MIN)],
+ currentTimeMs: 100 * MIN,
+ },
+}
+
+export const ChaptersWithoutFrames: Story = {
+ render,
+ args: {
+ observations: [summary({ chapters: MEDIUM.map((c) => ({ ...c, frame: false })), inactive: MEDIUM_INACTIVE })],
+ },
+}
+
+export const SummaryWithIdleChaptersFromBeforeInactivePeriods: Story = {
+ render,
+ args: { observations: [summary({ chapters: MEDIUM, legacyIdle: true })] },
+}
diff --git a/products/replay_vision/frontend/components/RecordingTimeline.tsx b/products/replay_vision/frontend/components/RecordingTimeline.tsx
new file mode 100644
index 000000000000..602923ccac6e
--- /dev/null
+++ b/products/replay_vision/frontend/components/RecordingTimeline.tsx
@@ -0,0 +1,228 @@
+import { Fragment } from 'react'
+
+import { IconSparkles } from '@posthog/icons'
+import { LemonButton, Spinner, Tooltip } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+import { colonDelimitedDuration, humanFriendlyDuration } from 'lib/utils/durations'
+
+import type { ReplayObservationApi } from '../generated/api.schemas'
+import type { RecordingTimeline as RecordingTimelineData, TimelineRow } from '../utils/recordingTimeline'
+import { MIN_INACTIVE_ROW_MS, currentRowIndex, rowStartMs, timelineGapPx } from '../utils/recordingTimeline'
+import { ObservationThumbnail } from './ObservationThumbnail'
+import { TimelineRail } from './TimelineRail'
+
+export interface RecordingTimelineProps {
+ timeline: RecordingTimelineData
+ rows: TimelineRow[]
+ currentTimeMs: number
+ onSeek: (timestampMs: number) => void
+ onSummarize: () => void
+ summarizing: boolean
+ summarizeDisabledReason?: string | null
+}
+
+const ROW_GRID = 'grid grid-cols-[2.5rem_1rem_minmax(0,1fr)] gap-x-1.5 px-2'
+const ROW_GRID_HOURS = 'grid grid-cols-[4rem_1rem_minmax(0,1fr)] gap-x-1.5 px-2'
+const HOUR_MS = 3_600_000
+
+const formatSpan = (ms: number): string => humanFriendlyDuration(ms / 1000, { maxUnits: 1 })
+
+function SummaryNotice({
+ timeline,
+ onSummarize,
+ summarizing,
+ summarizeDisabledReason,
+}: RecordingTimelineProps): JSX.Element | null {
+ if (timeline.summaryState === 'ready') {
+ return null
+ }
+ if (timeline.summaryState === 'pending') {
+ return (
+ <div
+ className="flex items-center gap-2 px-3 py-2 text-xs text-secondary"
+ data-attr="vision-timeline-pending"
+ >
+ <Spinner className="text-sm" /> Building the breakdown of this recording…
+ </div>
+ )
+ }
+ const outdated = timeline.summaryState === 'outdated'
+ return (
+ <div className="flex flex-col items-start gap-2 px-3 py-3" data-attr="vision-timeline-cta">
+ <span className="text-xs text-secondary">
+ {outdated
+ ? 'This recording was summarized before breakdowns existed.'
+ : 'Summarize this recording to get a breakdown of what happened, part by part.'}
+ </span>
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconSparkles />}
+ onClick={onSummarize}
+ loading={summarizing}
+ disabledReason={summarizeDisabledReason}
+ data-attr={outdated ? 'vision-timeline-rebuild' : 'vision-timeline-summarize'}
+ >
+ {outdated ? 'Rebuild the breakdown' : 'Summarize this recording'}
+ </LemonButton>
+ </div>
+ )
+}
+
+/** The recording's breakdown on a time rail: the summary's chapters and the idle gaps between them. */
+export function RecordingTimeline(props: RecordingTimelineProps): JSX.Element {
+ const { timeline, rows, currentTimeMs, onSeek } = props
+ const currentIndex = currentRowIndex(rows, currentTimeMs)
+ const hasHours = rows.some((row) => rowStartMs(row) >= HOUR_MS)
+ const rowGrid = hasHours ? ROW_GRID_HOURS : ROW_GRID
+ const formatTime = (ms: number): string => colonDelimitedDuration(Math.floor(ms / 1000), hasHours ? 3 : 2)
+
+ return (
+ <div className="flex flex-col py-1" data-attr="vision-recording-timeline">
+ {rows.map((row, index) => {
+ const startMs = rowStartMs(row)
+ const isCurrent = index === currentIndex
+ const passedAbove = startMs <= currentTimeMs
+ const passedBelow = index < currentIndex
+ const gapPx = index === 0 ? 0 : timelineGapPx(startMs - rowStartMs(rows[index - 1]))
+ const inactive = row.kind === 'inactive'
+ const timeCell = (
+ <span
+ className={cn(
+ 'text-xs font-mono text-right',
+ row.kind === 'chapter' ? 'pt-2' : 'self-center py-1',
+ isCurrent ? 'text-accent font-semibold' : inactive ? 'text-tertiary' : 'text-secondary'
+ )}
+ >
+ {formatTime(startMs)}
+ </span>
+ )
+ return (
+ <Fragment key={`${row.kind}-${startMs}-${index}`}>
+ {gapPx > 0 && (
+ <div
+ className={rowGrid}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ height: gapPx }}
+ >
+ <span />
+ <TimelineRail
+ dot="none"
+ passedAbove={passedAbove}
+ passedBelow={passedAbove}
+ isCurrent={false}
+ dashed={rows[index - 1].kind === 'inactive'}
+ />
+ </div>
+ )}
+ {row.kind === 'chapter' ? (
+ <div
+ data-current-moment={isCurrent ? true : undefined}
+ className={cn(rowGrid, 'transition-colors', isCurrent && 'bg-fill-highlight-50')}
+ >
+ {timeCell}
+ <TimelineRail
+ dot="chapter"
+ first={index === 0}
+ last={index === rows.length - 1}
+ passedAbove={passedAbove}
+ passedBelow={passedBelow}
+ isCurrent={isCurrent}
+ alignTop
+ />
+ <button
+ type="button"
+ onClick={() => onSeek(row.chapter.startMs)}
+ className="flex gap-2 min-w-0 text-left cursor-pointer rounded hover:bg-surface-secondary p-1 -mx-1 my-0.5"
+ data-attr="vision-timeline-chapter"
+ >
+ <Tooltip
+ title={
+ row.chapter.hasFrame ? (
+ <ObservationThumbnail
+ observation={timeline.summary as ReplayObservationApi}
+ chapter={row.chapter.position}
+ className="w-128 border-0"
+ />
+ ) : undefined
+ }
+ placement="left"
+ delayMs={300}
+ containerClassName="max-w-none p-1"
+ >
+ <span className="flex shrink-0">
+ <ObservationThumbnail
+ observation={timeline.summary as ReplayObservationApi}
+ chapter={row.chapter.position}
+ className="w-20 shrink-0"
+ />
+ </span>
+ </Tooltip>
+ <span className="flex flex-col min-w-0 gap-0.5">
+ <span className="text-sm font-medium line-clamp-2">{row.chapter.title}</span>
+ <span className="text-xs text-secondary">
+ {formatSpan(
+ row.chapter.endMs - row.chapter.startMs - row.chapter.inactiveMs
+ )}
+ {row.chapter.inactiveMs >= MIN_INACTIVE_ROW_MS && (
+ <span className="text-tertiary">
+ {' '}
+ · {formatSpan(row.chapter.inactiveMs)} inactive
+ </span>
+ )}
+ </span>
+ </span>
+ </button>
+ </div>
+ ) : row.kind === 'boundary' ? (
+ <div
+ data-current-moment={isCurrent ? true : undefined}
+ className={cn(rowGrid, isCurrent && 'bg-fill-highlight-50')}
+ data-attr="vision-timeline-boundary"
+ >
+ {timeCell}
+ <TimelineRail
+ dot="boundary"
+ first={index === 0}
+ last={index === rows.length - 1}
+ passedAbove={passedAbove}
+ passedBelow={passedBelow}
+ isCurrent={false}
+ />
+ <button
+ type="button"
+ onClick={() => onSeek(row.atMs)}
+ className="text-xs text-secondary text-left py-1 cursor-pointer hover:text-primary"
+ >
+ {row.edge === 'start' ? 'Session start' : 'Session end'}
+ </button>
+ </div>
+ ) : (
+ <div
+ data-current-moment={isCurrent ? true : undefined}
+ className={rowGrid}
+ data-attr="vision-timeline-inactive"
+ >
+ {timeCell}
+ <TimelineRail
+ dot="none"
+ first={index === 0}
+ last={index === rows.length - 1}
+ passedAbove={passedAbove}
+ passedBelow={passedBelow}
+ isCurrent={false}
+ dashed
+ />
+ <span className="text-xs text-tertiary italic py-1">
+ Inactive for {formatSpan(row.endMs - row.startMs)}
+ </span>
+ </div>
+ )}
+ </Fragment>
+ )
+ })}
+ <SummaryNotice {...props} />
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/components/TimelineRail.tsx b/products/replay_vision/frontend/components/TimelineRail.tsx
new file mode 100644
index 000000000000..0b12503e9816
--- /dev/null
+++ b/products/replay_vision/frontend/components/TimelineRail.tsx
@@ -0,0 +1,57 @@
+import { cn } from 'lib/utils/css-classes'
+
+export type TimelineRailDot = 'chapter' | 'boundary' | 'none'
+
+/** The rail cell of one timeline row: the line through it, and the dot that marks where the row sits. */
+export function TimelineRail({
+ dot,
+ passedAbove,
+ passedBelow,
+ isCurrent,
+ dashed = false,
+ alignTop = false,
+ first = false,
+ last = false,
+}: {
+ dot: TimelineRailDot
+ passedAbove: boolean
+ passedBelow: boolean
+ isCurrent: boolean
+ /** Idle time, where the user was not there to be followed. */
+ dashed?: boolean
+ /** Puts the dot level with the first line of the row rather than its middle, for tall rows. */
+ alignTop?: boolean
+ /** The rail starts and stops at the rows at its ends, rather than running out of the list. */
+ first?: boolean
+ last?: boolean
+}): JSX.Element {
+ const segment = (passed: boolean, grow: boolean, hidden: boolean): string =>
+ cn(
+ grow ? 'flex-1' : 'h-3.5 shrink-0',
+ hidden
+ ? 'w-0.5'
+ : dashed
+ ? cn('w-0 border-l-2 border-dotted', passed ? 'border-accent' : 'border-secondary')
+ : cn('w-0.5', passed ? 'bg-accent' : 'bg-border')
+ )
+ return (
+ <div className="flex flex-col items-center self-stretch">
+ <span className={segment(passedAbove, !alignTop, first)} />
+ {dot !== 'none' && (
+ <span
+ className={cn(
+ 'rounded-full shrink-0',
+ dot === 'chapter' ? 'w-3 h-3' : 'w-2 h-2',
+ dot === 'boundary'
+ ? cn('rounded-sm', passedAbove ? 'bg-accent' : 'bg-border-bold')
+ : passedAbove
+ ? 'bg-accent'
+ : 'bg-surface-primary border-2 border-primary',
+ isCurrent && 'ring-2 ring-accent ring-offset-1'
+ )}
+ />
+ )}
+ <span className={segment(passedBelow, true, last)} />
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/logics/observationsDockLogic.ts b/products/replay_vision/frontend/logics/observationsDockLogic.ts
index 931a9808336c..1c994be5faf0 100644
--- a/products/replay_vision/frontend/logics/observationsDockLogic.ts
+++ b/products/replay_vision/frontend/logics/observationsDockLogic.ts
@@ -9,7 +9,8 @@ import { teamLogic } from 'scenes/teamLogic'
import { visionObservationsList, visionScannersInlineScanCreate, visionScannersObserveCreate } from '../generated/api'
import type { ReplayScannerApi, ReplayObservationApi } from '../generated/api.schemas'
import { isSummarizerScanner } from '../replay_scanners/types'
-import { ObservationSeekbarMark, isSummaryObservation, observationSeekbarMarks } from '../utils/observation'
+import { isSummaryObservation } from '../utils/observation'
+import { RecordingTimeline, recordingTimeline } from '../utils/recordingTimeline'
import { OBSERVE_POLL_GRACE_MS, scheduleObservationPoll, shouldPollObservations } from './observationPolling'
import { requestObservationRetry } from './observationRetry'
import {
@@ -46,11 +47,11 @@ export interface observationsDockLogicValues {
retryingObservationIds: string[]
scannerPickerOpen: boolean
scannerSearch: string
- seekbarMarks: ObservationSeekbarMark[]
summarizePending: boolean
summarizerScanners: ReplayScannerApi[]
summarizing: boolean
summaryInFlight: boolean
+ timeline: RecordingTimeline
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -134,7 +135,7 @@ export interface observationsDockLogicMeta {
hasObservationsInFlight: (observations: ReplayObservationApi[]) => boolean
summaryInFlight: (observations: ReplayObservationApi[]) => boolean
summarizePending: (summarizing: boolean, summaryInFlight: boolean) => boolean
- seekbarMarks: (observations: ReplayObservationApi[]) => ObservationSeekbarMark[]
+ timeline: (observations: ReplayObservationApi[]) => RecordingTimeline
summarizerScanners: (scanners: ReplayScannerApi[]) => ReplayScannerApi[]
defaultSummarizer: (
scanners: ReplayScannerApi[],
@@ -312,9 +313,9 @@ export const observationsDockLogic = kea<observationsDockLogicType>([
(s) => [s.summarizing, s.summaryInFlight],
(summarizing: boolean, summaryInFlight: boolean): boolean => summarizing || summaryInFlight,
],
- seekbarMarks: [
+ timeline: [
(s) => [s.observations],
- (observations: ReplayObservationApi[]): ObservationSeekbarMark[] => observationSeekbarMarks(observations),
+ (observations: ReplayObservationApi[]): RecordingTimeline => recordingTimeline(observations),
],
summarizerScanners: [
(s) => [s.scanners],
diff --git a/products/replay_vision/frontend/utils/observation.test.ts b/products/replay_vision/frontend/utils/observation.test.ts
index b3732c8f309b..c6f08cbd1a8a 100644
--- a/products/replay_vision/frontend/utils/observation.test.ts
+++ b/products/replay_vision/frontend/utils/observation.test.ts
@@ -1,19 +1,5 @@
import type { ReplayObservationApi } from '../generated/api.schemas'
-import {
- ObservationSeekbarMark,
- dockObservations,
- observationClipboardText,
- observationSeekbarMarks,
- scannerLabel,
-} from './observation'
-
-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)
+import { dockObservations, observationClipboardText, scannerLabel } from './observation'
function makeObservation(
scannerType: string,
@@ -59,252 +45,6 @@ describe('observation utils', () => {
})
})
- describe('observationSeekbarMarks', () => {
- it.each<{ name: string; observations: ReplayObservationApi[]; expected: ObservationSeekbarMark[] }>([
- {
- name: 'summarizer: persisted citation segments become marks, deduped and ascending',
- observations: [
- makeObservation(
- 'summarizer',
- {
- summary: 'Rage clicked pay',
- summary_segments: [
- { kind: 'text', value: 'Rage clicked pay' },
- { kind: 'chip', timestamp_ms: 161_000 },
- { kind: 'chip', timestamp_ms: 30_000 },
- { kind: 'chip', timestamp_ms: 161_000 },
- ],
- },
- 'succeeded',
- 'Session summarizer'
- ),
- ],
- expected: [
- { timestampMs: 30_000, flagged: false, entries: [summarizerEntry] },
- { timestampMs: 161_000, flagged: false, entries: [summarizerEntry] },
- ],
- },
- {
- name: 'monitor: leaked (t N) markers parsed client-side, verdict headline, citing sentence as snippet',
- observations: [
- makeObservation(
- 'monitor',
- { verdict: 'yes', reasoning: 'User opened checkout. Error toast shown (t 42).' },
- 'succeeded',
- 'Error monitor'
- ),
- ],
- expected: [
- {
- timestampMs: 42_000,
- flagged: true,
- entries: [
- {
- scannerName: 'Error monitor',
- headline: 'Verdict: yes',
- snippet: 'Error toast shown',
- sentence: 'Error toast shown (00:42)',
- },
- ],
- },
- ],
- },
- {
- name: 'two scanners citing the same moment merge into one mark',
- observations: [
- makeObservation('monitor', { reasoning: 'Saw it (t 42).' }, 'succeeded', 'Monitor A'),
- makeObservation('scorer', { score: 3, reasoning: 'Also saw it (t 42).' }, 'succeeded', 'Scorer B'),
- ],
- expected: [
- {
- timestampMs: 42_000,
- flagged: false,
- entries: [
- { 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)',
- },
- ],
- },
- ],
- },
- {
- name: 'non-succeeded observations contribute no marks',
- observations: [makeObservation('monitor', { reasoning: 'Saw it (t 42).' }, 'failed')],
- expected: [],
- },
- {
- name: 'snippets longer than 160 characters are truncated with an ellipsis',
- observations: [makeObservation('monitor', { reasoning: `${longSentence} (t 42).` })],
- expected: [
- {
- timestampMs: 42_000,
- flagged: false,
- entries: [
- {
- scannerName: 'Scanner',
- headline: null,
- snippet: `${longSentence.slice(0, 159)}…`,
- sentence: `${longSentence} (00:42)`,
- },
- ],
- },
- ],
- },
- {
- // A one-off summarize is the scan most likely to cite a timestamp, and its scanner has
- // no name. Passing the raw name through leaves the tooltip line blank, because a
- // summarizer has no headline to fall back on either.
- name: 'a quick summary labels its mark rather than leaving it blank',
- observations: [
- {
- ...makeObservation('summarizer', {
- summary: 'Rage clicked pay',
- summary_segments: [
- { kind: 'text', value: 'Rage clicked pay' },
- { kind: 'chip', timestamp_ms: 42_000 },
- ],
- }),
- scanner_origin: 'inline',
- scanner_snapshot: { scanner_type: 'summarizer', name: '' },
- } as unknown as ReplayObservationApi,
- ],
- expected: [
- {
- timestampMs: 42_000,
- flagged: false,
- entries: [
- {
- scannerName: 'Quick summary',
- headline: null,
- snippet: 'Rage clicked pay',
- sentence: 'Rage clicked pay (00:42)',
- },
- ],
- },
- ],
- },
- {
- name: 'output without citations yields no marks',
- observations: [makeObservation('monitor', { verdict: 'yes', reasoning: 'Error toast shown.' })],
- expected: [],
- },
- {
- name: 'citation with no preceding text yields a null snippet',
- observations: [
- makeObservation('summarizer', {
- summary: 'Rage clicked pay',
- summary_segments: [{ kind: 'chip', timestamp_ms: 42_000 }],
- }),
- ],
- expected: [
- {
- 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', () => {
const obs = (
id: string,
diff --git a/products/replay_vision/frontend/utils/observation.ts b/products/replay_vision/frontend/utils/observation.ts
index a88b67ac5e4b..fb8ad8916f3e 100644
--- a/products/replay_vision/frontend/utils/observation.ts
+++ b/products/replay_vision/frontend/utils/observation.ts
@@ -1,9 +1,7 @@
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'
-import { flattenMarkdownToLine } from './markdown'
+import { citedTextToPlainText } from './citations'
/** The dock's built-in prompt and the observations it produces have to answer to one name. */
export const BUILT_IN_SUMMARY_LABEL = 'Quick summary'
@@ -131,201 +129,10 @@ export function readTags(obs: ReplayObservationApi): string[] {
return [...readFixedTags(obs), ...readFreeformTags(obs)]
}
-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
-
-/** 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
- }
-}
-
-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()
-}
-
-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 []
- }
- const [text, segments] =
- obs.scanner_snapshot?.scanner_type === 'summarizer'
- ? [output.summary, output.summary_segments]
- : [output.reasoning, output.reasoning_segments]
- if (typeof text !== 'string' || !text) {
- 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
- }
- 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
- }
- 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 {
- const scannerType = obs.scanner_snapshot?.scanner_type
- if (scannerType === 'monitor') {
- const verdict = readVerdict(obs)
- return verdict ? `Verdict: ${verdict}` : null
- }
- if (scannerType === 'scorer') {
- const score = readScore(obs)
- return score !== null ? `Score: ${score}` : null
- }
- return null
-}
-
-/** 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)
- 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()],
- flagged: flaggedTimestamps.has(timestampMs),
- }))
-}
-
/** One succeeded observation as clipboard text: a metadata line, then the result body. */
export function observationClipboardText(obs: ReplayObservationApi): string | null {
const output = readModelOutput(obs)
diff --git a/products/replay_vision/frontend/utils/observationTimeline.test.ts b/products/replay_vision/frontend/utils/observationTimeline.test.ts
deleted file mode 100644
index d35d1963e1cd..000000000000
--- a/products/replay_vision/frontend/utils/observationTimeline.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-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
deleted file mode 100644
index fdfdd75f8f78..000000000000
--- a/products/replay_vision/frontend/utils/observationTimeline.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-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
-}
diff --git a/products/replay_vision/frontend/utils/recordingTimeline.test.ts b/products/replay_vision/frontend/utils/recordingTimeline.test.ts
new file mode 100644
index 000000000000..f82f619df9d1
--- /dev/null
+++ b/products/replay_vision/frontend/utils/recordingTimeline.test.ts
@@ -0,0 +1,178 @@
+import type { ReplayObservationApi } from '../generated/api.schemas'
+import { recordingTimeline, timelineRows } from './recordingTimeline'
+
+function summary(
+ output: Record<string, unknown> | null,
+ status: ReplayObservationApi['status'] = 'succeeded',
+ createdAt = '2026-10-02T09:00:00Z',
+ id = 'summary-1'
+): ReplayObservationApi {
+ return {
+ id,
+ status,
+ created_at: createdAt,
+ scanner_snapshot: { scanner_type: 'summarizer', name: 'Summary' },
+ scanner_result: output ? { model_output: { scanner_type: 'summarizer', ...output } } : null,
+ media: [],
+ } as unknown as ReplayObservationApi
+}
+
+function monitor(id: string, keyMomentMs: number | null, verdict = 'yes'): ReplayObservationApi {
+ return {
+ id,
+ status: 'succeeded',
+ created_at: '2026-10-02T09:05:00Z',
+ scanner_snapshot: { scanner_type: 'monitor', name: id },
+ scanner_result: { model_output: { scanner_type: 'monitor', verdict, key_moment_ms: keyMomentMs } },
+ media: [],
+ } as unknown as ReplayObservationApi
+}
+
+const chapter = (start: number, end: number, title: string, kind = 'activity'): Record<string, unknown> => ({
+ kind,
+ start_ms: start,
+ end_ms: end,
+ title,
+})
+
+describe('recordingTimeline', () => {
+ it.each<{
+ name: string
+ observations: ReplayObservationApi[]
+ state: string
+ chapters: number
+ markers: number
+ inactive?: number
+ }>([
+ { name: 'only scans', observations: [monitor('m1', 5_000)], state: 'none', chapters: 0, markers: 1 },
+ {
+ name: 'a summary still running',
+ observations: [summary(null, 'running'), monitor('m1', 5_000)],
+ state: 'pending',
+ chapters: 0,
+ markers: 1,
+ },
+ {
+ name: 'a summary from before chapters existed',
+ observations: [summary({ title: 't' })],
+ state: 'outdated',
+ chapters: 0,
+ markers: 0,
+ },
+ {
+ name: 'a summary from before inactive periods, whose idle chapters become gaps',
+ observations: [
+ summary({
+ chapters: [
+ chapter(0, 10_000, 'A'),
+ chapter(10_000, 70_000, 'Idle', 'idle'),
+ chapter(70_000, 80_000, 'B'),
+ ],
+ }),
+ ],
+ state: 'ready',
+ chapters: 2,
+ markers: 0,
+ inactive: 1,
+ },
+ {
+ name: 'a summary with chapters, and a scan without a key moment',
+ observations: [summary({ chapters: [chapter(0, 10_000, 'A')] }), monitor('m1', null)],
+ state: 'ready',
+ chapters: 1,
+ markers: 0,
+ },
+ ])('reads the state of $name', ({ observations, state, chapters, markers, inactive = 0 }) => {
+ const timeline = recordingTimeline(observations)
+ expect([
+ timeline.summaryState,
+ timeline.chapters.length,
+ timeline.markers.length,
+ timeline.inactive.length,
+ ]).toEqual([state, chapters, markers, inactive])
+ })
+
+ it.each<{ name: string; observations: ReplayObservationApi[]; durationMs: number | null; expected: string[] }>([
+ {
+ name: 'scans without a breakdown leave the rail empty',
+ observations: [monitor('m1', 5_000)],
+ durationMs: 60_000,
+ expected: [],
+ },
+ {
+ name: 'a breakdown sits between the session start and end',
+ observations: [summary({ chapters: [chapter(0, 10_000, 'A')] }), monitor('m1', 5_000)],
+ durationMs: 60_000,
+ expected: ['boundary start', 'chapter', 'boundary end'],
+ },
+ {
+ name: 'a recording that loads shorter than its chapters still ends after them',
+ observations: [summary({ chapters: [chapter(0, 90_000, 'A')] })],
+ durationMs: 60_000,
+ expected: ['boundary start', 'chapter', 'boundary end 90000'],
+ },
+ {
+ name: 'an idle stretch that starts inside a chapter begins where the chapter ends',
+ observations: [
+ summary({
+ chapters: [chapter(0, 20_000, 'A'), chapter(90_000, 100_000, 'B')],
+ inactive_periods: [{ start_ms: 10_000, end_ms: 90_000 }],
+ }),
+ ],
+ durationMs: 100_000,
+ expected: ['boundary start', 'chapter', 'inactive 20000', 'chapter', 'boundary end'],
+ },
+ {
+ name: 'an unknown length leaves out the end',
+ observations: [summary({ chapters: [chapter(0, 10_000, 'A')] })],
+ durationMs: null,
+ expected: ['boundary start', 'chapter'],
+ },
+ ])('$name', ({ observations, durationMs, expected }) => {
+ const rows = timelineRows(recordingTimeline(observations), durationMs)
+ expect(
+ rows.map((row) =>
+ row.kind === 'inactive'
+ ? `inactive ${row.startMs}`
+ : row.kind !== 'boundary'
+ ? row.kind
+ : row.edge === 'end' && row.atMs !== durationMs
+ ? `boundary end ${row.atMs}`
+ : `boundary ${row.edge}`
+ )
+ ).toEqual(expected)
+ })
+
+ it('uses the newest succeeded summary', () => {
+ const older = summary({ chapters: [chapter(0, 10_000, 'Old')] }, 'succeeded', '2026-10-01T09:00:00Z', 'old')
+ const newer = summary({ chapters: [chapter(0, 10_000, 'New')] }, 'succeeded', '2026-10-02T09:00:00Z', 'new')
+ expect(recordingTimeline([older, newer]).chapters.map((c) => c.title)).toEqual(['New'])
+ })
+
+ it('lays chapters and long idle out in time order, skipping idle chapters and short pauses', () => {
+ const observations = [
+ summary({
+ chapters: [
+ chapter(0, 20_000, 'Browses'),
+ chapter(20_000, 30_000, 'Idle', 'idle'),
+ chapter(90_000, 120_000, 'Buys'),
+ ],
+ inactive_periods: [
+ { start_ms: 20_000, end_ms: 90_000 },
+ { start_ms: 100_000, end_ms: 105_000 },
+ ],
+ }),
+ monitor('in-gap', 50_000),
+ ]
+ const timeline = recordingTimeline(observations)
+ const rows = timelineRows(timeline).map((row) =>
+ row.kind === 'chapter'
+ ? `chapter ${row.chapter.title}`
+ : row.kind === 'inactive'
+ ? `inactive ${row.startMs}-${row.endMs}`
+ : `boundary ${row.edge}`
+ )
+ expect(rows).toEqual(['boundary start', 'chapter Browses', 'inactive 20000-90000', 'chapter Buys'])
+ expect(timeline.chapters.find((c) => c.title === 'Buys')?.inactiveMs).toBe(5_000)
+ })
+})
diff --git a/products/replay_vision/frontend/utils/recordingTimeline.ts b/products/replay_vision/frontend/utils/recordingTimeline.ts
new file mode 100644
index 000000000000..6aa1708068f9
--- /dev/null
+++ b/products/replay_vision/frontend/utils/recordingTimeline.ts
@@ -0,0 +1,247 @@
+import type { ReplayObservationApi } from '../generated/api.schemas'
+import {
+ VERDICT_LABEL,
+ isFlaggedObservation,
+ isSummaryObservation,
+ readModelOutput,
+ readScore,
+ readTags,
+ readVerdict,
+ scannerLabel,
+} from './observation'
+
+/** Shorter idle is a pause in the flow of a chapter, not something worth a row of its own. */
+export const MIN_INACTIVE_ROW_MS = 30_000
+
+export interface TimelineChapter {
+ /** Index into the summary's `model_output.chapters`, which is how the chapter's frame is fetched. */
+ position: number
+ startMs: number
+ endMs: number
+ title: string
+ hasFrame: boolean
+ /** Inactive time inside the chapter, from pauses the chapter spans. */
+ inactiveMs: number
+}
+
+export interface TimelineInactive {
+ startMs: number
+ endMs: number
+}
+
+export interface TimelineMarker {
+ observationId: string
+ timestampMs: number
+ scannerName: string
+ scannerType: string | null
+ /** The answer the run gave, for example "Yes", "Score 4" or a tag; null when it has none to show. */
+ result: string | null
+ flagged: boolean
+}
+
+/**
+ * What the timeline can show for this recording:
+ * `ready` has chapters, `pending` has a summary still running, `outdated` has a summary that predates chapters,
+ * and `none` has no summary at all.
+ */
+export type SummaryState = 'ready' | 'pending' | 'outdated' | 'none'
+
+export interface RecordingTimeline {
+ summary: ReplayObservationApi | null
+ summaryState: SummaryState
+ chapters: TimelineChapter[]
+ inactive: TimelineInactive[]
+ markers: TimelineMarker[]
+}
+
+/** One row on the rail. */
+export type TimelineRow =
+ | { kind: 'chapter'; chapter: TimelineChapter }
+ | { kind: 'inactive'; startMs: number; endMs: number }
+ | { kind: 'boundary'; edge: 'start' | 'end'; atMs: number }
+
+// Rows are spaced by elapsed time, capped so one quiet stretch can't push the rest off screen.
+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))
+}
+
+function readNumber(value: unknown): number | null {
+ return typeof value === 'number' && Number.isFinite(value) ? value : null
+}
+
+function readChapters(summary: ReplayObservationApi): TimelineChapter[] {
+ const raw = readModelOutput(summary)?.chapters
+ if (!Array.isArray(raw)) {
+ return []
+ }
+ const framePositions = new Set(
+ (summary.media ?? []).filter((entry) => entry.kind === 'chapter').map((entry) => entry.position)
+ )
+ const chapters: TimelineChapter[] = []
+ raw.forEach((entry: unknown, position) => {
+ if (!entry || typeof entry !== 'object') {
+ return
+ }
+ const chapter = entry as Record<string, unknown>
+ const startMs = readNumber(chapter.start_ms)
+ const endMs = readNumber(chapter.end_ms)
+ // Summaries written before inactive periods existed list idle as chapters; the gaps carry it now.
+ if (chapter.kind === 'idle' || startMs === null || endMs === null || endMs <= startMs) {
+ return
+ }
+ chapters.push({
+ position,
+ startMs,
+ endMs,
+ title: typeof chapter.title === 'string' ? chapter.title : '',
+ hasFrame: framePositions.has(position),
+ inactiveMs: 0,
+ })
+ })
+ return chapters.sort((a, b) => a.startMs - b.startMs)
+}
+
+function readInactive(summary: ReplayObservationApi): TimelineInactive[] {
+ const output = readModelOutput(summary)
+ const periods = output?.inactive_periods
+ const chapters = output?.chapters
+ // Summaries written before inactive periods existed list idle as chapters instead.
+ const raw: unknown[] = Array.isArray(periods)
+ ? periods
+ : Array.isArray(chapters)
+ ? chapters.filter((c: unknown) => (c as Record<string, unknown> | null)?.kind === 'idle')
+ : []
+ return raw
+ .map((entry: unknown) => {
+ const period = (entry ?? {}) as Record<string, unknown>
+ return { startMs: readNumber(period.start_ms), endMs: readNumber(period.end_ms) }
+ })
+ .filter((p): p is TimelineInactive => p.startMs !== null && p.endMs !== null && p.endMs > p.startMs)
+ .sort((a, b) => a.startMs - b.startMs)
+}
+
+function markerResult(observation: ReplayObservationApi): string | null {
+ const verdict = readVerdict(observation)
+ if (verdict) {
+ return VERDICT_LABEL[verdict]
+ }
+ const score = readScore(observation)
+ if (score !== null) {
+ return `Score ${score}`
+ }
+ const tags = readTags(observation)
+ return tags.length > 0 ? tags.join(', ') : null
+}
+
+function readMarker(observation: ReplayObservationApi): TimelineMarker | null {
+ const timestampMs = readNumber(readModelOutput(observation)?.key_moment_ms)
+ if (observation.status !== 'succeeded' || timestampMs === null) {
+ return null
+ }
+ return {
+ observationId: observation.id,
+ timestampMs,
+ scannerName: scannerLabel(observation),
+ scannerType: observation.scanner_snapshot?.scanner_type ?? null,
+ result: markerResult(observation),
+ flagged: isFlaggedObservation(observation),
+ }
+}
+
+function overlapMs(a: TimelineInactive, startMs: number, endMs: number): number {
+ return Math.max(0, Math.min(a.endMs, endMs) - Math.max(a.startMs, startMs))
+}
+
+function uncoveredParts(period: TimelineInactive, chapters: TimelineChapter[]): TimelineInactive[] {
+ let parts = [period]
+ for (const c of chapters) {
+ parts = parts.flatMap((p) =>
+ [
+ { startMs: p.startMs, endMs: Math.min(p.endMs, c.startMs) },
+ { startMs: Math.max(p.startMs, c.endMs), endMs: p.endMs },
+ ].filter((part) => part.endMs > part.startMs)
+ )
+ }
+ return parts
+}
+
+/** The recording's timeline: the newest summary's chapters, with every other run's key moment as a marker. */
+export function recordingTimeline(observations: ReplayObservationApi[]): RecordingTimeline {
+ const summaries = observations
+ .filter(isSummaryObservation)
+ .sort((a, b) => (b.created_at ?? '').localeCompare(a.created_at ?? ''))
+ const summary = summaries.find((o) => o.status === 'succeeded') ?? null
+ const pending = summaries.some((o) => o.status === 'pending' || o.status === 'running')
+ const markers = observations
+ .filter((o) => !isSummaryObservation(o))
+ .map(readMarker)
+ .filter((m): m is TimelineMarker => m !== null)
+ .sort((a, b) => a.timestampMs - b.timestampMs)
+
+ const chapters = summary ? readChapters(summary) : []
+ const allInactive = summary ? readInactive(summary) : []
+ for (const chapter of chapters) {
+ chapter.inactiveMs = allInactive.reduce((sum, p) => sum + overlapMs(p, chapter.startMs, chapter.endMs), 0)
+ }
+ // A gap row is the inactive time no chapter covers, so a pause a chapter spans never shows twice.
+ const inactive = allInactive
+ .flatMap((p) => uncoveredParts(p, chapters))
+ .filter((p) => p.endMs - p.startMs >= MIN_INACTIVE_ROW_MS)
+
+ const summaryState: SummaryState =
+ chapters.length > 0 ? 'ready' : pending ? 'pending' : summary ? 'outdated' : 'none'
+ return { summary, summaryState, chapters, inactive, markers }
+}
+
+/** The rows the sidebar lists, in time order: the session's ends, chapters and idle gaps. Empty without chapters. */
+export function timelineRows(timeline: RecordingTimeline, durationMs: number | null = null): TimelineRow[] {
+ if (timeline.chapters.length === 0) {
+ return []
+ }
+ const rows: { atMs: number; order: number; row: TimelineRow }[] = []
+ rows.push({ atMs: 0, order: -1, row: { kind: 'boundary', edge: 'start', atMs: 0 } })
+ for (const chapter of timeline.chapters) {
+ rows.push({ atMs: chapter.startMs, order: 0, row: { kind: 'chapter', chapter } })
+ }
+ for (const gap of timeline.inactive) {
+ rows.push({ atMs: gap.startMs, order: 1, row: { kind: 'inactive', startMs: gap.startMs, endMs: gap.endMs } })
+ }
+ if (durationMs !== null && durationMs > 0) {
+ // The player's length can come up short of what the scan saw, and the end must still close the rail.
+ const endMs = Math.max(durationMs, ...timeline.chapters.map((c) => c.endMs))
+ rows.push({ atMs: endMs, order: 3, row: { kind: 'boundary', edge: 'end', atMs: endMs } })
+ }
+ return rows.sort((a, b) => a.atMs - b.atMs || a.order - b.order).map(({ row }) => row)
+}
+
+/** Where a row sits on the recording's clock, which the rail spaces and the player highlights by. */
+export function rowStartMs(row: TimelineRow): number {
+ switch (row.kind) {
+ case 'chapter':
+ return row.chapter.startMs
+ case 'inactive':
+ return row.startMs
+ case 'boundary':
+ return row.atMs
+ }
+}
+
+/** The row the player is in: the last one that started at or before the player's position, or -1 before the first. */
+export function currentRowIndex(rows: TimelineRow[], playerTimeMs: number): number {
+ let current = -1
+ rows.forEach((row, index) => {
+ if (rowStartMs(row) <= playerTimeMs) {
+ current = index
+ }
+ })
+ return current
+}
+
+/** The next chapter start after the player's position. */
+export function nextTimelineStopMs(timeline: RecordingTimeline, playerTimeMs: number): number | null {
+ const later = timeline.chapters.map((c) => c.startMs).filter((ms) => ms > playerTimeMs)
+ return later.length > 0 ? Math.min(...later) : null
+}