:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(replay-vision): render comma-joined timestamp citations as seek chips (#70878)
Arno Hillenb2a26188cf98
diff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.pyindex 5029b6d4a9e1..d253fb55a1a8 100644--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py@@ -36,6 +36,7 @@ from products.replay_vision.backend.temporal.gemini import gemini_api_keyfrom products.replay_vision.backend.temporal.metrics import record_provider_callfrom products.replay_vision.backend.temporal.scanners import scanner_from_snapshotfrom products.replay_vision.backend.temporal.scanners.base import (+ TIMESTAMP_CITATION_RE,BaseScanner,BaseScannerOutput,ChipSegment,@@ -57,8 +58,6 @@ logger = structlog.get_logger(__name__)_MAX_LLM_ATTEMPTS = 2 # one initial call + one re-prompt with the validation error appended per step# Cache TTL: a scan is a handful of turns and finishes in minutes; well under this._VIDEO_CACHE_TTL = "900s"-# `(t <seconds>)` with optional leading whitespace, so we eat the space when stripping the paren.-_TIMESTAMP_CITATION_RE = re.compile(r"\s*\(t (\d+)\)")_OutputT = TypeVar("_OutputT", bound=BaseModel)@@ -128,16 +127,18 @@ def _extract_segments(text: str, duration_ms: int) -> tuple[str, list[Segment]]:plain_parts: list[str] = []segments: list[Segment] = []last_end = 0- for match in _TIMESTAMP_CITATION_RE.finditer(text):+ for match in TIMESTAMP_CITATION_RE.finditer(text):chunk = text[last_end : match.start()]plain_parts.append(chunk)if chunk:segments.append(TextSegment(value=chunk))- timestamp_ms = int(match.group(1)) * 1000- # Drop citations past the recording end (a misread footer value); 1s slack spares a genuine final-second- # citation from a sub-second start-time skew. The marker is stripped either way.- if timestamp_ms <= duration_ms + 1000:- segments.append(ChipSegment(timestamp_ms=timestamp_ms))+ # A leaked comma-joined marker like `(t 12, 34)` carries several moments, one chip each.+ for raw_seconds in re.findall(r"\d+", match.group(1)):+ timestamp_ms = int(raw_seconds) * 1000+ # Drop citations past the recording end (a misread footer value). 1s slack spares a genuine+ # final-second citation from a sub-second start-time skew. The marker is stripped either way.+ if timestamp_ms <= duration_ms + 1000:+ segments.append(ChipSegment(timestamp_ms=timestamp_ms))last_end = match.end()trailing = text[last_end:]plain_parts.append(trailing)diff --git a/products/replay_vision/backend/temporal/scanners/base.py b/products/replay_vision/backend/temporal/scanners/base.pyindex 2f127eeacf96..9f0e744a4357 100644--- a/products/replay_vision/backend/temporal/scanners/base.py+++ b/products/replay_vision/backend/temporal/scanners/base.py@@ -9,9 +9,11 @@ from pydantic import BaseModel, Field, field_validatorfrom products.replay_vision.backend.temporal.scanners.prompt_env import render_prompt-# `(t 123)` / `(t 123, t 456)` citation markers the model leaks into the plain-text signal description despite the-# prompt forbidding them. Matched leniently (whitespace, comma-joined times) so the strip catches every variant.-_SIGNAL_TIMESTAMP_MARKER_RE = re.compile(r"\s*\(\s*t\s*\d+(?:\s*,\s*t?\s*\d+)*\s*\)")+# `(t 123)` / `(t 123, 456)` / `(t 12, t 34)` citation markers. The prompt asks for one moment per parens, but the+# model leaks comma-joined variants too, so match leniently (whitespace, comma-joined times, optional repeated `t`).+# Shared by the signal-description stripper below and the chip extractor in `call_scanner_provider` so the two+# parsers can't drift apart. The group captures the comma-joined seconds list.+TIMESTAMP_CITATION_RE = re.compile(r"\s*\(\s*t\s*(\d+(?:\s*,\s*t?\s*\d+)*)\s*\)")# Sited here rather than `temporal/types.py`: `types.py` imports from this module, so siting Segment in types.py would close the cycle.@@ -78,7 +80,7 @@ class SignalFinding(BaseModel, frozen=True):# The model leaks `(t 123)` markers into this embedded, free-text-searchable field despite the prompt — strip# them so the timing stays only in start_time/end_time and the prose reads cleanly. Collapse any double space# the removal (or the model) leaves so the prose stays clean.- return re.sub(r"\s{2,}", " ", _SIGNAL_TIMESTAMP_MARKER_RE.sub("", value)).strip()+ return re.sub(r"\s{2,}", " ", TIMESTAMP_CITATION_RE.sub("", value)).strip()class SignalsResponse(BaseModel, frozen=True):diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex a3c8ea69062d..23efbbbedf66 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -2161,6 +2161,39 @@ class TestExtractSegments:[TextSegment(value="Nothing to strip.")],id="no_citations",),+ pytest.param(+ "Filtered repeatedly (t 12, 34, 56), then sorted.",+ "Filtered repeatedly, then sorted.",+ [+ TextSegment(value="Filtered repeatedly"),+ ChipSegment(timestamp_ms=12_000),+ ChipSegment(timestamp_ms=34_000),+ ChipSegment(timestamp_ms=56_000),+ TextSegment(value=", then sorted."),+ ],+ id="comma_joined",+ ),+ pytest.param(+ "Clicked (t 39, t 57) twice.",+ "Clicked twice.",+ [+ TextSegment(value="Clicked"),+ ChipSegment(timestamp_ms=39_000),+ ChipSegment(timestamp_ms=57_000),+ TextSegment(value=" twice."),+ ],+ id="comma_joined_repeated_t",+ ),+ pytest.param(+ "Opened (t 50, 99999) later.",+ "Opened later.",+ [+ TextSegment(value="Opened"),+ ChipSegment(timestamp_ms=50_000),+ TextSegment(value=" later."),+ ],+ id="comma_joined_out_of_range_dropped",+ ),],)def test_extract_segments(self, text: str, expected_plain: str, expected_segments: list[Segment]) -> None:diff --git a/products/replay_vision/frontend/components/ObservationCard.tsx b/products/replay_vision/frontend/components/ObservationCard.tsxindex 345a928ad421..ea4aeabf6197 100644--- a/products/replay_vision/frontend/components/ObservationCard.tsx+++ b/products/replay_vision/frontend/components/ObservationCard.tsx@@ -18,6 +18,7 @@ import {parseIneligibleReason,scannerTypeLabel,} from '../replay_scanners/types'+import { parseCitedSegments } from '../utils/citations'import { ObservationProgressBar } from './ObservationProgressBar'export function ObservationStatusTag({@@ -72,24 +73,6 @@ export function readResult(observation: ReplayObservationApi): Record<string, unreturn output && typeof output === 'object' ? (output as Record<string, unknown>) : null}-// `uuid` is legacy — only old event-uuid citations carry it; timestamp citations use `timestamp_ms` alone.-type Segment = { kind: 'text'; value: string } | { kind: 'chip'; timestamp_ms: number; uuid?: string }--function isSegment(value: unknown): value is Segment {- if (!value || typeof value !== 'object') {- return false- }- const candidate = value as Partial<Segment>- if (candidate.kind === 'text') {- return typeof (candidate as { value?: unknown }).value === 'string'- }- if (candidate.kind === 'chip') {- const chip = candidate as Partial<Extract<Segment, { kind: 'chip' }>>- return typeof chip.timestamp_ms === 'number'- }- return false-}-/** Dumb renderer for parsed citation segments. Pass `onSeek` to make citation chips interactive; omit for plain-text timestamps. */export function CitedText({text,@@ -100,7 +83,7 @@ export function CitedText({segments: unknownonSeek?: (timestampMs: number) => void}): JSX.Element {- const list = Array.isArray(segments) ? (segments.filter(isSegment) as Segment[]) : []+ const list = parseCitedSegments(text, segments)if (list.length === 0) {return <>{text}</>}diff --git a/products/replay_vision/frontend/utils/citations.test.ts b/products/replay_vision/frontend/utils/citations.test.tsnew file mode 100644index 000000000000..0a48f0134aaf--- /dev/null+++ b/products/replay_vision/frontend/utils/citations.test.ts@@ -0,0 +1,41 @@+import { type Segment, parseCitedSegments } from './citations'++describe('parseCitedSegments', () => {+ const text = (value: string): Segment => ({ kind: 'text', value })+ const chip = (seconds: number): Segment => ({ kind: 'chip', timestamp_ms: seconds * 1000 })++ it.each<{ name: string; text: string; segments: unknown; expected: Segment[] }>([+ {+ name: 'splits a leaked comma-joined marker inside a persisted text segment into one chip per second',+ text: 'ignored when segments exist',+ segments: [text('changed the filter (t 1437, 1441), scrolling'), chip(1479)],+ expected: [text('changed the filter'), chip(1437), chip(1441), text(', scrolling'), chip(1479)],+ },+ {+ name: 'handles the comma-joined variant that repeats the t prefix',+ text: '',+ segments: [text('Clicked twice (t 39, t 57) before it responded')],+ expected: [text('Clicked twice'), chip(39), chip(57), text(' before it responded')],+ },+ {+ name: 'parses markers straight from the text when no segments were persisted',+ text: 'The user retried (t 12) twice.',+ segments: undefined,+ expected: [text('The user retried'), chip(12), text(' twice.')],+ },+ {+ name: 'returns the plain text untouched when there is nothing to split',+ text: 'No citations here.',+ segments: [],+ expected: [text('No citations here.')],+ },+ {+ name: 'drops malformed entries and passes valid persisted segments through untouched',+ text: 'fallback text',+ segments: [text('Foo'), chip(12), { kind: 'chip' }, 'junk', null],+ expected: [text('Foo'), chip(12)],+ },+ ])('$name', ({ text: inputText, segments, expected }) => {+ expect(parseCitedSegments(inputText, segments)).toEqual(expected)+ })+})diff --git a/products/replay_vision/frontend/utils/citations.ts b/products/replay_vision/frontend/utils/citations.tsnew file mode 100644index 000000000000..a6ea5802b9c5--- /dev/null+++ b/products/replay_vision/frontend/utils/citations.ts@@ -0,0 +1,55 @@+// `uuid` is legacy (only old event-uuid citations carry it). Timestamp citations use `timestamp_ms` alone.+export type Segment = { kind: 'text'; value: string } | { kind: 'chip'; timestamp_ms: number; uuid?: string }++export function isSegment(value: unknown): value is Segment {+ if (!value || typeof value !== 'object') {+ return false+ }+ const candidate = value as Partial<Segment>+ if (candidate.kind === 'text') {+ return typeof (candidate as { value?: unknown }).value === 'string'+ }+ if (candidate.kind === 'chip') {+ const chip = candidate as Partial<Extract<Segment, { kind: 'chip' }>>+ return typeof chip.timestamp_ms === 'number'+ }+ return false+}++// Matches `(t 123)` and leaked comma-joined variants like `(t 123, 456)` / `(t 12, t 34)`.+// Mirrors the backend's TIMESTAMP_CITATION_RE (backend/temporal/scanners/base.py).+const TIMESTAMP_CITATION_RE = /\s*\(\s*t\s*(\d+(?:\s*,\s*t?\s*\d+)*)\s*\)/g++/** Split leaked `(t <sec>)` markers in plain text into chip segments, one chip per cited second. */+function splitLeakedCitations(text: string): Segment[] {+ const segments: Segment[] = []+ let lastEnd = 0+ for (const match of text.matchAll(TIMESTAMP_CITATION_RE)) {+ const chunk = text.slice(lastEnd, match.index)+ if (chunk) {+ segments.push({ kind: 'text', value: chunk })+ }+ for (const seconds of match[1].match(/\d+/g) ?? []) {+ segments.push({ kind: 'chip', timestamp_ms: parseInt(seconds, 10) * 1000 })+ }+ lastEnd = match.index + match[0].length+ }+ const trailing = text.slice(lastEnd)+ if (trailing) {+ segments.push({ kind: 'text', value: trailing })+ }+ return segments+}++/**+ * Render-ready segments for a cited field: the persisted segments when present (falling back to the plain text+ * otherwise), with any `(t <sec>)` markers the backend missed at scan time split into chips client-side, so+ * observations persisted before a marker variant was parseable still render seekable chips.+ */+export function parseCitedSegments(text: string, segments: unknown): Segment[] {+ const persisted = Array.isArray(segments) ? segments.filter(isSegment) : []+ if (persisted.length === 0) {+ return splitLeakedCitations(text)+ }+ return persisted.flatMap((segment) => (segment.kind === 'text' ? splitLeakedCitations(segment.value) : [segment]))+}