:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): UUID citations as render-ready segments (#60605)
Tue Haulund2259254ac26a
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.pyindex c604990fd0ab..4c1b7587637e 100644--- a/products/replay_vision/backend/api/observations.py+++ b/products/replay_vision/backend/api/observations.py@@ -70,13 +70,6 @@ class ScannerResultSerializer(serializers.Serializer):min_value=0,help_text="Number of PostHog Signals emitted from this observation.",)- event_id_mapping = serializers.DictField(- child=serializers.JSONField(),- help_text=(- "Maps the short `event_id` the LLM cites in `model_output.reasoning` to citation metadata: "- "`{uuid, timestamp_ms}`. Only includes hashes the LLM actually cited."- ),- )class ReplayObservationSerializer(serializers.ModelSerializer):diff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.pyindex 6e03cc6e7709..0a3b0a17619f 100644--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py@@ -22,7 +22,7 @@ from products.replay_vision.backend.temporal.decorators import track_activityfrom products.replay_vision.backend.temporal.errors import FailureKind, ScannerFailureErrorfrom products.replay_vision.backend.temporal.metrics import REPLAY_VISION_PROVIDER_CALLfrom products.replay_vision.backend.temporal.scanners import scanner_from_snapshot-from products.replay_vision.backend.temporal.scanners.base import BaseScanner+from products.replay_vision.backend.temporal.scanners.base import BaseScanner, ChipSegment, Segment, TextSegmentfrom products.replay_vision.backend.temporal.state import (StateActivitiesEnum,get_data_class_from_redis,@@ -30,7 +30,6 @@ from products.replay_vision.backend.temporal.state import ()from products.replay_vision.backend.temporal.types import (CallScannerProviderInputs,- EventCitation,ScannerCallOutput,ScannerLlmInputs,ScannerSnapshot,@@ -39,8 +38,11 @@ from products.replay_vision.backend.temporal.types import (logger = structlog.get_logger(__name__)_MAX_LLM_ATTEMPTS = 2 # one initial call + one re-prompt with the validation error appended-# Captures the hex hash inside `(event_id <hash>)`; case-insensitive since model output isn't deterministic.-_EVENT_ID_CITATION_RE = re.compile(r"\(event_id ([0-9a-f]{16})\)", re.IGNORECASE)+# `(event_uuid <uuid>)` with optional leading whitespace, so we eat the space when stripping the paren.+_EVENT_UUID_CITATION_RE = re.compile(+ r"\s*\(event_uuid ([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\)",+ re.IGNORECASE,+)@activity.defn@@ -72,39 +74,50 @@ async def call_scanner_provider_activity(inputs: CallScannerProviderInputs) -> Sprompt_parts=prompt_parts,team_id=inputs.team_id,)- finalized, filtered_mapping = _resolve_citations(finalized, scanner, llm_inputs.event_id_mapping)- return ScannerCallOutput(model_output=finalized, event_id_mapping=filtered_mapping)+ finalized = _resolve_citations(finalized, scanner, llm_inputs.event_timestamps)+ return ScannerCallOutput(model_output=finalized)def _resolve_citations(finalized: BaseModel,scanner: BaseScanner,- mapping: dict[str, EventCitation],-) -> tuple[BaseModel, dict[str, EventCitation]]:- """Slim event_id_mapping to citations actually used; strip hallucinated `(event_id <hash>)` parens whose hash isn't in `mapping`."""- cited_hashes: set[str] = set()- field_updates: dict[str, str] = {}+ event_timestamps: dict[str, int],+) -> BaseModel:+ """Walk each `(event_uuid <uuid>)` marker in the citation fields: drop hallucinated ones, build the plain text, and persist a parallel render-ready segment list."""+ field_updates: dict[str, str | list[Segment]] = {}for field in scanner.citation_fields:text = getattr(finalized, field, None)if not isinstance(text, str):continue-- def _filter(match: re.Match[str]) -> str:- hex_hash = match.group(1).lower()- if hex_hash not in mapping:- return "" # drop dead citation rather than leaving a parenthetical the FE can't resolve- cited_hashes.add(hex_hash)- # Rewrite with canonical lowercase hex so persisted text matches the mapping keys.- return f"(event_id {hex_hash})"-- new_text = _EVENT_ID_CITATION_RE.sub(_filter, text)- if new_text != text:- field_updates[field] = new_text+ plain, segments = _extract_segments(text, event_timestamps)+ field_updates[field] = plain+ field_updates[f"{field}_segments"] = segmentsif field_updates:finalized = finalized.model_copy(update=field_updates)- filtered_mapping = {h: c for h, c in mapping.items() if h in cited_hashes}- return finalized, filtered_mapping+ return finalized+++def _extract_segments(text: str, event_timestamps: dict[str, int]) -> tuple[str, list[Segment]]:+ """Walk `(event_uuid <uuid>)` markers in `text`; drop hallucinated uuids; return (plain text, render-ready text/chip segments)."""+ plain_parts: list[str] = []+ segments: list[Segment] = []+ last_end = 0+ for match in _EVENT_UUID_CITATION_RE.finditer(text):+ chunk = text[last_end : match.start()]+ plain_parts.append(chunk)+ if chunk:+ segments.append(TextSegment(value=chunk))+ uuid = match.group(1).lower()+ timestamp_ms = event_timestamps.get(uuid)+ if timestamp_ms is not None:+ segments.append(ChipSegment(uuid=uuid, timestamp_ms=timestamp_ms))+ last_end = match.end()+ trailing = text[last_end:]+ plain_parts.append(trailing)+ if trailing:+ segments.append(TextSegment(value=trailing))+ return "".join(plain_parts), segmentsdef _load_snapshot(observation_id: UUID, team_id: int) -> ScannerSnapshot:diff --git a/products/replay_vision/backend/temporal/activities/fetch_session_events.py b/products/replay_vision/backend/temporal/activities/fetch_session_events.pyindex 736af818dec8..7cd740a64129 100644--- a/products/replay_vision/backend/temporal/activities/fetch_session_events.py+++ b/products/replay_vision/backend/temporal/activities/fetch_session_events.py@@ -21,7 +21,6 @@ from products.replay_vision.backend.temporal.state import (store_data_in_redis,)from products.replay_vision.backend.temporal.types import (- EventCitation,EventTable,FetchSessionEventsInputs,ScannerLlmInputs,@@ -29,14 +28,13 @@ from products.replay_vision.backend.temporal.types import ()# Pagination shape mirrors session_summary's fetcher; without it HogQL applies LimitContext.QUERY's default of 100.-_EVENTS_PER_PAGE = 3000-_MAX_EVENT_PAGES = 5 # Hard cap on prompt size for very chatty sessions; sets `events_truncated` when reached.+_EVENTS_PER_PAGE = 2000+_MAX_EVENT_PAGES = 1 # Hard cap on prompt size for very chatty sessions; sets `events_truncated` when reached.# Noisy SDK-internal events that add no signal for the LLM._EVENTS_TO_IGNORE = ["$feature_flag_called"]-# `properties.*` is the HogQL prefix for JSON properties; bare names are top-level columns.-# `uuid` lets us map short event_ids back to real events; never sent to the LLM.+# `properties.*` is the HogQL prefix for JSON properties; `uuid` is surfaced to the LLM as the `event_uuid` citation handle._EXTRA_FIELDS = ["uuid","elements_chain_ids",@@ -49,8 +47,8 @@ _URL_PREFIX = "url"_WINDOW_PREFIX = "window"# Per-value cap to keep one oversized field from blowing the prompt token budget._MAX_FIELD_LEN = 2000-# 64-bit hex hash for event dedup — 32-bit (8 hex) hits 50% birthday-collision around 77k events.-_EVENT_ID_BYTES = 8+# Fixed-size dedup key — keeps `seen_hashes` bounded on chatty sessions where each row can carry ~KB-sized truncated exception text.+_DEDUP_HASH_BYTES = 8@activity.defn@@ -129,7 +127,7 @@ def _fetch_payload(team_id: int, session_id: str) -> ScannerLlmInputs | None:if columns is None or not all_rows:return None- processed_columns, processed_rows, url_mapping, window_mapping, event_id_mapping = _process_events(+ processed_columns, processed_rows, url_mapping, window_mapping, event_timestamps = _process_events(columns, all_rows, session_start=metadata["start_time"])# Derive from duration; clamp because CH can yield active > duration (tab visibility, clock skew).@@ -141,7 +139,7 @@ def _fetch_payload(team_id: int, session_id: str) -> ScannerLlmInputs | None:events=EventTable(columns=processed_columns, rows=processed_rows),url_mapping=url_mapping,window_mapping=window_mapping,- event_id_mapping=event_id_mapping,+ event_timestamps=event_timestamps,metadata=SessionMetadata(start_time=metadata["start_time"],end_time=metadata["end_time"],@@ -160,8 +158,8 @@ def _fetch_payload(team_id: int, session_id: str) -> ScannerLlmInputs | None:def _process_events(raw_columns: list[str], raw_rows: list[list[Any]], *, session_start: dt.datetime-) -> tuple[list[str], list[list[Any]], dict[str, str], dict[str, str], dict[str, EventCitation]]:- """Dedup, truncate, intern URLs/windows, project uuid into the event_id mapping."""+) -> tuple[list[str], list[list[Any]], dict[str, str], dict[str, str], dict[str, int]]:+ """Dedup, truncate, intern URLs/windows, surface uuid as `event_uuid` for the LLM, and build the uuid → relative-ms lookup."""uuid_index = raw_columns.index("uuid") if "uuid" in raw_columns else Nonetimestamp_index = raw_columns.index("timestamp") if "timestamp" in raw_columns else None# All other indexes are over the LLM-visible column set (uuid stripped); compute once.@@ -171,26 +169,24 @@ def _process_events(url_tokens: dict[str, str] = {} # actual -> token; flipped at the end for the promptwindow_tokens: dict[str, str] = {}- event_id_mapping: dict[str, EventCitation] = {}+ event_timestamps: dict[str, int] = {}seen_hashes: set[str] = set()processed: list[list[Any]] = []for row in raw_rows:- # Hash the LLM-visible projection (uuid is unique per event and would defeat dedup).visible = list(row)uuid_value: Any = Noneif uuid_index is not None:uuid_value = visible.pop(uuid_index)- raw_hash = _row_hash(visible)- if raw_hash in seen_hashes:+ dedup_key = _row_hash(visible)+ if dedup_key in seen_hashes:continue- seen_hashes.add(raw_hash)+ seen_hashes.add(dedup_key)- if uuid_value is not None:- # ClickHouse returns `uuid` as `uuid.UUID`, not str.- event_id_mapping[raw_hash] = EventCitation(- uuid=str(uuid_value),- timestamp_ms=_relative_ms(row[timestamp_index] if timestamp_index is not None else None, session_start),+ uuid_str = str(uuid_value) if uuid_value is not None else ""+ if uuid_str:+ event_timestamps[uuid_str] = _relative_ms(+ row[timestamp_index] if timestamp_index is not None else None, session_start)# Intern before truncate so the token map keys on the full value, not a clipped prefix.@@ -198,12 +194,12 @@ def _process_events(visible[url_index] = _intern(visible[url_index], url_tokens, _URL_PREFIX)if window_index is not None:visible[window_index] = _intern(visible[window_index], window_tokens, _WINDOW_PREFIX)- processed.append([raw_hash, *(_truncate(v) for v in visible)])+ processed.append([uuid_str, *(_truncate(v) for v in visible)])- output_columns = ["event_id", *visible_columns]+ output_columns = ["event_uuid", *visible_columns]url_mapping = {token: actual for actual, token in url_tokens.items()}window_mapping = {token: actual for actual, token in window_tokens.items()}- return output_columns, processed, url_mapping, window_mapping, event_id_mapping+ return output_columns, processed, url_mapping, window_mapping, event_timestampsdef _relative_ms(event_timestamp: Any, session_start: dt.datetime) -> int:@@ -238,7 +234,7 @@ def _truncate(value: Any) -> Any:def _row_hash(row: list[Any]) -> str:- """Deterministic 16-char (64-bit) hex of the row contents; identical events collapse to the same id."""- # `repr` quotes strings and renders `None` as `None`, so a literal "" and a None column don't collide.+ """Fixed-size in-process dedup key; bounds `seen_hashes` memory on chatty sessions where each visible row can be KBs."""+ # `repr` keeps `None` distinct from the literal `"None"` string.joined = "\0".join(repr(v) for v in row)- return hashlib.sha256(joined.encode()).hexdigest()[: _EVENT_ID_BYTES * 2]+ return hashlib.sha256(joined.encode()).hexdigest()[: _DEDUP_HASH_BYTES * 2]diff --git a/products/replay_vision/backend/temporal/scanners/base.py b/products/replay_vision/backend/temporal/scanners/base.pyindex a354826a139c..0e460b3c3e30 100644--- a/products/replay_vision/backend/temporal/scanners/base.py+++ b/products/replay_vision/backend/temporal/scanners/base.py@@ -1,6 +1,6 @@"""Base class for all Replay Vision scanner types."""-from typing import TYPE_CHECKING, Any, ClassVar+from typing import TYPE_CHECKING, Annotated, Any, ClassVar, Literalfrom pydantic import BaseModel, Field@@ -10,6 +10,21 @@ if TYPE_CHECKING:from products.replay_vision.backend.temporal.types import EventTable+# Sited here rather than `temporal/types.py`: `types.py` imports from this module, so siting Segment in types.py would close the cycle.+class TextSegment(BaseModel, frozen=True):+ kind: Literal["text"] = "text"+ value: str+++class ChipSegment(BaseModel, frozen=True):+ kind: Literal["chip"] = "chip"+ uuid: str+ timestamp_ms: int = Field(ge=0)+++Segment = Annotated[TextSegment | ChipSegment, Field(discriminator="kind")]++class BaseScannerOutput(BaseModel, frozen=True):"""Final output shape emitted as `$recording_observed` event properties (flattened with `scanner_output_*` keys)."""@@ -32,7 +47,7 @@ class BaseScanner(BaseModel, frozen=True):# Per-scanner-type Jinja2 template under `prompts/`. Subclasses set this.prompt_template: ClassVar[str] = ""- # Names of free-text fields on the LLM response that may contain `(event_id <hash>)` citations.+ # Names of free-text fields on the LLM response that may contain `(event_uuid <uuid>)` citations.citation_fields: ClassVar[tuple[str, ...]] = ()# Persisted output class — subclasses override to stamp their `scanner_type` discriminator.output_cls: ClassVar[type["BaseScannerOutput"] | None] = Nonediff --git a/products/replay_vision/backend/temporal/scanners/classifier.py b/products/replay_vision/backend/temporal/scanners/classifier.pyindex 403975dcd2be..ba4dd975460e 100644--- a/products/replay_vision/backend/temporal/scanners/classifier.py+++ b/products/replay_vision/backend/temporal/scanners/classifier.py@@ -8,7 +8,7 @@ from typing import Any, ClassVar, Literalfrom pydantic import BaseModel, Field, create_model, field_validatorfrom products.replay_vision.backend.models.replay_scanner import ScannerType-from products.replay_vision.backend.temporal.scanners.base import BaseScanner, BaseScannerOutput+from products.replay_vision.backend.temporal.scanners.base import BaseScanner, BaseScannerOutput, Segment_MAX_FREEFORM_TAGS = 5# Anything that isn't a-z, 0-9, underscore, or dash collapses to a single underscore.@@ -30,6 +30,7 @@ class ClassifierOutput(BaseScannerOutput, frozen=True):),)reasoning: str = Field(description="One paragraph grounding the tag choice in concrete moments.")+ reasoning_segments: list[Segment] = Field(default_factory=list)@field_validator("tags_freeform", mode="after")@classmethoddiff --git a/products/replay_vision/backend/temporal/scanners/monitor.py b/products/replay_vision/backend/temporal/scanners/monitor.pyindex dc1847e66305..0c46c999a274 100644--- a/products/replay_vision/backend/temporal/scanners/monitor.py+++ b/products/replay_vision/backend/temporal/scanners/monitor.py@@ -5,7 +5,7 @@ from typing import ClassVar, Literalfrom pydantic import BaseModel, Fieldfrom products.replay_vision.backend.models.replay_scanner import ScannerType-from products.replay_vision.backend.temporal.scanners.base import BaseScanner, BaseScannerOutput+from products.replay_vision.backend.temporal.scanners.base import BaseScanner, BaseScannerOutput, Segmentclass MonitorLlmResponse(BaseScannerOutput, frozen=True):@@ -18,9 +18,10 @@ class MonitorLlmResponse(BaseScannerOutput, frozen=True):class MonitorOutput(MonitorLlmResponse, frozen=True):- """Persisted output: adds the discriminator for the `AnyScannerOutput` union."""+ """Persisted output: `reasoning` is plain prose; `reasoning_segments` is the same prose pre-split into render-ready text + chip segments."""scanner_type: Literal[ScannerType.MONITOR] = ScannerType.MONITOR+ reasoning_segments: list[Segment] = Field(default_factory=list)class MonitorScanner(BaseScanner, frozen=True):diff --git a/products/replay_vision/backend/temporal/scanners/prompts/_macros.jinja b/products/replay_vision/backend/temporal/scanners/prompts/_macros.jinjaindex 049dfa511fa8..4afa81f1b318 100644--- a/products/replay_vision/backend/temporal/scanners/prompts/_macros.jinja+++ b/products/replay_vision/backend/temporal/scanners/prompts/_macros.jinja@@ -1,4 +1,4 @@{# Citation policy that scanners can opt into. Call as `{{ cite_in('reasoning') }}` or `{{ cite_in('summary') }}`. #}{%- macro cite_in(field_name) -%}-Inside `{{ field_name }}`, cite key events as `(event_id <hex-hash>)`, e.g. `(event_id 030df0f4f45a4d7a)`. One event per parens; max 1–2 citations per paragraph. Cite only turning points, blockers, and climaxes — skip routine navigation. Never cite by ordinal, position, or any identifier other than the hex hash.+Inside `{{ field_name }}`, cite key events as `(event_uuid <uuid>)`, e.g. `(event_uuid 0193abcd-1234-7e89-9abc-deadbeefcafe)`. One event per parens; max 1–2 citations per paragraph. Cite only turning points, blockers, and climaxes — skip routine navigation. Never cite by ordinal, position, or any identifier other than the UUID exactly as it appears in the events table.{%- endmacro -%}diff --git a/products/replay_vision/backend/temporal/scanners/prompts/base.jinja b/products/replay_vision/backend/temporal/scanners/prompts/base.jinjaindex c372b92377a2..73a98a013340 100644--- a/products/replay_vision/backend/temporal/scanners/prompts/base.jinja+++ b/products/replay_vision/backend/temporal/scanners/prompts/base.jinja@@ -17,7 +17,7 @@ Confidence calibration:<events_format>Each event is an object with these fields:-- event_id: 16-char hex hash; the only identifier you may use to refer to a specific event+- event_uuid: PostHog event UUID; the only identifier you may use to refer to a specific event- event: type of event (e.g. `$pageview`, `$autocapture`, `$exception`)- timestamp: when it occurred (ISO 8601)- elements_chain_href / elements_chain_texts / elements_chain_elements / elements_chain_ids: what was interacted withdiff --git a/products/replay_vision/backend/temporal/scanners/prompts/summarizer.jinja b/products/replay_vision/backend/temporal/scanners/prompts/summarizer.jinjaindex 80bc65cdd08d..85b8b79a3399 100644--- a/products/replay_vision/backend/temporal/scanners/prompts/summarizer.jinja+++ b/products/replay_vision/backend/temporal/scanners/prompts/summarizer.jinja@@ -14,5 +14,5 @@ Also produce facets that characterize this session for free-text search by futur- `friction_points`: list of named blockers, errors, or frustrations the user hit (empty if none). Only include things the user would notice — visible error states, dead clicks, rage clicks, abandoned actions, page reloads. Background JS console errors that don't affect the UI (ResizeObserver loops, feature-flag fetch failures, third-party script noise) are not friction.- `keywords`: 5-15 distinctive lowercase terms — favor action verbs and specific feature names; skip generic terms ('user', 'session', 'navigation') and the product/team name.-Do not include any event citations or `event_id` hashes inside `intent`, `outcome`, `friction_points`, or `keywords` — those are consumed by a vector-embedding pipeline and hex tokens would be noise.+Do not include any event citations or `event_uuid` values inside `intent`, `outcome`, `friction_points`, or `keywords` — those are consumed by a vector-embedding pipeline and UUID tokens would be noise.{% endif %}{% endblock %}diff --git a/products/replay_vision/backend/temporal/scanners/scorer.py b/products/replay_vision/backend/temporal/scanners/scorer.pyindex 5f7e0aaaea1e..ad388758ead4 100644--- a/products/replay_vision/backend/temporal/scanners/scorer.py+++ b/products/replay_vision/backend/temporal/scanners/scorer.py@@ -5,7 +5,7 @@ from typing import Any, ClassVar, Literalfrom pydantic import BaseModel, Field, create_model, model_validatorfrom products.replay_vision.backend.models.replay_scanner import ScannerType-from products.replay_vision.backend.temporal.scanners.base import BaseScanner, BaseScannerOutput+from products.replay_vision.backend.temporal.scanners.base import BaseScanner, BaseScannerOutput, Segmentclass ScoreScale(BaseModel, frozen=True):@@ -24,6 +24,7 @@ class ScorerOutput(BaseScannerOutput, frozen=True):scanner_type: Literal[ScannerType.SCORER] = ScannerType.SCORERscore: float = Field(description="Numeric score on the configured scale.")reasoning: str = Field(description="One paragraph grounding the score in concrete moments.")+ reasoning_segments: list[Segment] = Field(default_factory=list)label: str | None = Field(default=None, description="Echoes `scanner_config.scale.label`; workflow-stamped, not model-generated.")diff --git a/products/replay_vision/backend/temporal/scanners/summarizer.py b/products/replay_vision/backend/temporal/scanners/summarizer.pyindex b3b52a311a74..435a7029d438 100644--- a/products/replay_vision/backend/temporal/scanners/summarizer.py+++ b/products/replay_vision/backend/temporal/scanners/summarizer.py@@ -5,7 +5,7 @@ from typing import Any, ClassVar, Literalfrom pydantic import BaseModel, Field, field_validatorfrom products.replay_vision.backend.models.replay_scanner import ScannerType-from products.replay_vision.backend.temporal.scanners.base import BaseScanner, BaseScannerOutput+from products.replay_vision.backend.temporal.scanners.base import BaseScanner, BaseScannerOutput, SegmentSummaryLength = Literal["short", "medium", "long"]@@ -64,6 +64,7 @@ class SummarizerOutput(SummarizerLlmResponse, frozen=True):"""Persisted output: facet fields default to empty so flag-off summarizers round-trip cleanly."""scanner_type: Literal[ScannerType.SUMMARIZER] = ScannerType.SUMMARIZER+ summary_segments: list[Segment] = Field(default_factory=list)intent: str = ""outcome: str = ""friction_points: list[str] = Field(default_factory=list)diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.pyindex 25f6aae0fb2a..f3eab36b057f 100644--- a/products/replay_vision/backend/temporal/types.py+++ b/products/replay_vision/backend/temporal/types.py@@ -41,21 +41,11 @@ class ScannerSnapshot(BaseModel, frozen=True):) from exc-class EventCitation(BaseModel, frozen=True):- """One entry in `event_id_mapping`: enough metadata for a UI to render a deep-link to the cited event."""-- uuid: str = Field(description="Real PostHog event UUID; use with `/api/.../events/{uuid}` to fetch the event.")- timestamp_ms: int = Field(- ge=0, description="Milliseconds since session start; use to seek the session replay player to the moment."- )--class ScannerResult(BaseModel, frozen=True):"""Result data of a completed observation, persisted into `ReplayObservation.scanner_result`."""model_output: AnyScannerOutputsignals_count: int = Field(default=0, ge=0)- event_id_mapping: dict[str, EventCitation] = Field(default_factory=dict)class ApplyScannerInputs(BaseModel, frozen=True):@@ -166,7 +156,7 @@ class ScannerLlmInputs(BaseModel, frozen=True):# Reverse mappings: `url_1` -> actual URL, `window_1` -> actual window UUID.url_mapping: dict[str, str] = Field(default_factory=dict)window_mapping: dict[str, str] = Field(default_factory=dict)- event_id_mapping: dict[str, EventCitation] = Field(default_factory=dict)+ event_timestamps: dict[str, int] = Field(default_factory=dict)metadata: SessionMetadata@@ -200,8 +190,6 @@ class ScannerCallOutput(BaseModel, frozen=True):"""Result of one `call_scanner_provider` invocation."""model_output: AnyScannerOutput- # Short event_id (LLM-facing) -> citation metadata, propagated from `ScannerLlmInputs` for downstream resolution.- event_id_mapping: dict[str, EventCitation] = Field(default_factory=dict)class CleanupGeminiFileInputs(BaseModel, frozen=True):diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.pyindex df67f8dde205..78fcf8f19f08 100644--- a/products/replay_vision/backend/temporal/workflow.py+++ b/products/replay_vision/backend/temporal/workflow.py@@ -200,10 +200,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):MarkObservationSucceededInputs(observation_id=observation_id,scanner_type=scanner_type,- scanner_result=ScannerResult(- model_output=call_output.model_output,- event_id_mapping=call_output.event_id_mapping,- ),+ scanner_result=ScannerResult(model_output=call_output.model_output),),start_to_close_timeout=dt.timedelta(seconds=30),retry_policy=_STATE_ACTIVITY_RETRY,diff --git a/products/replay_vision/backend/tests/test_scanners.py b/products/replay_vision/backend/tests/test_scanners.pyindex b97b06f55f1c..fafb9540b27d 100644--- a/products/replay_vision/backend/tests/test_scanners.py+++ b/products/replay_vision/backend/tests/test_scanners.py@@ -583,6 +583,7 @@ class TestToEventProperties:assert props == {"scanner_output_verdict": True,"scanner_output_reasoning": "found it",+ "scanner_output_reasoning_segments": [],"scanner_output_confidence": 0.9,}diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex 2845973584e5..9164411a4474 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -29,7 +29,11 @@ from products.replay_vision.backend.models.replay_observation import (from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerTypefrom products.replay_vision.backend.quota import QuotaSnapshotfrom products.replay_vision.backend.temporal import ApplyScannerWorkflow-from products.replay_vision.backend.temporal.activities.call_scanner_provider import call_scanner_provider_activity+from products.replay_vision.backend.temporal.activities.call_scanner_provider import (+ _extract_segments,+ _resolve_citations,+ call_scanner_provider_activity,+)from products.replay_vision.backend.temporal.activities.cleanup_gemini_file import cleanup_gemini_file_activityfrom products.replay_vision.backend.temporal.activities.create_observation import create_observation_activityfrom products.replay_vision.backend.temporal.activities.embed_summarizer_observation import (@@ -54,9 +58,10 @@ from products.replay_vision.backend.temporal.errors import (IneligibleSessionKind,ScannerFailureError,)+from products.replay_vision.backend.temporal.scanners.base import ChipSegment, Segment, TextSegmentfrom products.replay_vision.backend.temporal.scanners.classifier import ClassifierOutput-from products.replay_vision.backend.temporal.scanners.monitor import MonitorOutput-from products.replay_vision.backend.temporal.scanners.summarizer import SummarizerOutput+from products.replay_vision.backend.temporal.scanners.monitor import MonitorOutput, MonitorScanner+from products.replay_vision.backend.temporal.scanners.summarizer import SummarizerOutput, SummarizerScannerfrom products.replay_vision.backend.temporal.state import (StateActivitiesEnum,generate_state_key,@@ -686,7 +691,7 @@ class TestFetchSessionEventsActivity:assert stored is not Noneassert stored.session_id == "sess-1"assert stored.team_id == scanner.team_id- assert stored.events.columns == ["event_id", "event", "timestamp", "$session_id"]+ assert stored.events.columns == ["event_uuid", "event", "timestamp", "$session_id"]assert stored.metadata.start_time == startassert stored.metadata.end_time == endassert stored.metadata.duration_seconds == 300.0@@ -694,22 +699,14 @@ class TestFetchSessionEventsActivity:assert stored.events.rows[0][1:] == ["$pageview", "2026-05-12T10:00:00Z", "sess-1"]@pytest.mark.asyncio- async def test_paginates_through_get_events_until_short_page(self) -> None:+ async def test_fetches_a_single_page_with_the_configured_limit(self) -> None:scanner = await sync_to_async(_make_scanner)()observation_id = uuid.uuid4()start = dt.datetime(2026, 5, 12, 10, 0, 0, tzinfo=dt.UTC)metadata = {"start_time": start, "end_time": start, "duration": 60, "active_seconds": 30}- page_size = 3000-- full_page_rows = [("$pageview", start, f"sess-{i}") for i in range(page_size)]- last_page_rows = [("$pageview", start, "sess-last")]+ page_rows = [("$pageview", start, f"sess-{i}") for i in range(50)]mock_obj = self._make_session_replay_events_mock(- metadata,- [- # First page reports more available; second page (short) reports no more, ending the loop.- (["event", "timestamp", "$session_id"], full_page_rows, True),- (["event", "timestamp", "$session_id"], last_page_rows, False),- ],+ metadata, [(["event", "timestamp", "$session_id"], page_rows, False)])with patch(@@ -717,23 +714,18 @@ class TestFetchSessionEventsActivity:return_value=mock_obj,):await fetch_session_events_activity(- FetchSessionEventsInputs(- observation_id=observation_id,- team_id=scanner.team_id,- session_id="sess-1",- )+ FetchSessionEventsInputs(observation_id=observation_id, team_id=scanner.team_id, session_id="sess-1"))- assert mock_obj.get_events.call_count == 2+ assert mock_obj.get_events.call_count == 1assert mock_obj.get_events.call_args_list[0].kwargs["page"] == 0- assert mock_obj.get_events.call_args_list[1].kwargs["page"] == 1- assert mock_obj.get_events.call_args_list[0].kwargs["limit"] == page_size+ assert mock_obj.get_events.call_args_list[0].kwargs["limit"] == 2000redis_client = get_async_client(settings.REPLAY_VISION_REDIS_URL)key = generate_state_key(label=StateActivitiesEnum.SESSION_EVENTS, state_id=str(observation_id))stored = await get_data_class_from_redis(redis_client, key, target_class=ScannerLlmInputs)assert stored is not None- assert len(stored.events.rows) == page_size + 1+ assert len(stored.events.rows) == 50@pytest.mark.asyncioasync def test_is_idempotent_when_redis_already_has_payload(self) -> None:@@ -995,12 +987,12 @@ class TestFetchSessionEventsActivity:stored = await get_data_class_from_redis(redis_client, key, target_class=ScannerLlmInputs)assert stored is not Noneassert len(stored.events.rows) == 2 # rageclick collapsed, $pageview kept- assert "uuid" not in stored.events.columns # not surfaced to the LLM- # The mapping records the FIRST uuid seen for each unique event_id.- assert len(stored.event_id_mapping) == 2- uuids = {c.uuid for c in stored.event_id_mapping.values()}- assert "00000000-0000-0000-0000-000000000001" in uuids- assert "00000000-0000-0000-0000-000000000004" in uuids+ assert "event_uuid" in stored.events.columns+ assert "uuid" not in stored.events.columns+ assert set(stored.event_timestamps.keys()) == {+ "00000000-0000-0000-0000-000000000001",+ "00000000-0000-0000-0000-000000000004",+ }@pytest.mark.asyncioasync def test_session_metadata_round_trips_to_payload(self) -> None:@@ -1042,15 +1034,15 @@ class TestFetchSessionEventsActivity:assert m.events_truncated is False@pytest.mark.asyncio- async def test_marks_events_truncated_when_last_page_has_more(self) -> None:+ async def test_marks_events_truncated_when_first_page_has_more(self) -> None:scanner = await sync_to_async(_make_scanner)()observation_id = uuid.uuid4()start = dt.datetime(2026, 5, 12, 10, 0, 0, tzinfo=dt.UTC)metadata = {"start_time": start, "end_time": start, "duration": 60, "active_seconds": 30}- # All 5 pages report has_more=True — we've used the page budget but more events exist.- full_page = [("$pageview", start, f"sess-{i}") for i in range(3000)]- pages = [(["event", "timestamp", "$session_id"], full_page, True)] * 5- mock_obj = self._make_session_replay_events_mock(metadata, pages)+ full_page = [("$pageview", start, f"sess-{i}") for i in range(2000)]+ mock_obj = self._make_session_replay_events_mock(+ metadata, [(["event", "timestamp", "$session_id"], full_page, True)]+ )with patch("products.replay_vision.backend.temporal.activities.fetch_session_events.SessionReplayEvents",@@ -1067,16 +1059,15 @@ class TestFetchSessionEventsActivity:assert stored.metadata.events_truncated is True@pytest.mark.asyncio- async def test_does_not_mark_truncated_when_last_page_exactly_fills_budget(self) -> None:+ async def test_does_not_mark_truncated_when_first_page_exactly_fills_budget(self) -> None:scanner = await sync_to_async(_make_scanner)()observation_id = uuid.uuid4()start = dt.datetime(2026, 5, 12, 10, 0, 0, tzinfo=dt.UTC)metadata = {"start_time": start, "end_time": start, "duration": 60, "active_seconds": 30}- # Four full pages with more available, then the fifth full page reports no more.- full_page = [("$pageview", start, f"sess-{i}") for i in range(3000)]- pages: list[tuple] = [(["event", "timestamp", "$session_id"], full_page, True)] * 4- pages.append((["event", "timestamp", "$session_id"], full_page, False))- mock_obj = self._make_session_replay_events_mock(metadata, pages)+ full_page = [("$pageview", start, f"sess-{i}") for i in range(2000)]+ mock_obj = self._make_session_replay_events_mock(+ metadata, [(["event", "timestamp", "$session_id"], full_page, False)]+ )with patch("products.replay_vision.backend.temporal.activities.fetch_session_events.SessionReplayEvents",@@ -1802,3 +1793,135 @@ class TestWorkflowErrorHelpers:def test_root_cause_message_falls_back_to_str_for_bare_exceptions(self) -> None:assert _root_cause_message(ValueError("bad arg")) == "bad arg"+++_UUID_A = "0193abcd-1234-7e89-9abc-deadbeefcafe"+_UUID_B = "0193abcd-1234-7e89-9abc-feedface0000"+_UUID_HALLUCINATED = "0193abcd-1234-7e89-9abc-aaaaaaaaaaaa"+++def _monitor_scanner() -> MonitorScanner:+ return MonitorScanner(prompt="p")+++def _summarizer_scanner() -> SummarizerScanner:+ return SummarizerScanner(prompt="p")+++class TestExtractSegments:+ @pytest.mark.parametrize(+ "text,event_timestamps,expected_plain,expected_segments",+ [+ pytest.param(+ f"Foo (event_uuid {_UUID_A}) bar",+ {_UUID_A: 1234},+ "Foo bar",+ [+ TextSegment(value="Foo"),+ ChipSegment(uuid=_UUID_A, timestamp_ms=1234),+ TextSegment(value=" bar"),+ ],+ id="inline",+ ),+ pytest.param(+ f"A (event_uuid {_UUID_A}) then B (event_uuid {_UUID_B}) then C.",+ {_UUID_A: 100, _UUID_B: 200},+ "A then B then C.",+ [+ TextSegment(value="A"),+ ChipSegment(uuid=_UUID_A, timestamp_ms=100),+ TextSegment(value=" then B"),+ ChipSegment(uuid=_UUID_B, timestamp_ms=200),+ TextSegment(value=" then C."),+ ],+ id="multiple",+ ),+ pytest.param(+ f"X (event_uuid {_UUID_A}) Y (event_uuid {_UUID_HALLUCINATED}) Z.",+ {_UUID_A: 50},+ "X Y Z.",+ [+ TextSegment(value="X"),+ ChipSegment(uuid=_UUID_A, timestamp_ms=50),+ TextSegment(value=" Y"),+ TextSegment(value=" Z."),+ ],+ id="hallucinated_uuid_dropped",+ ),+ pytest.param(+ f"(event_uuid {_UUID_A}) was the cause.",+ {_UUID_A: 0},+ " was the cause.",+ [+ ChipSegment(uuid=_UUID_A, timestamp_ms=0),+ TextSegment(value=" was the cause."),+ ],+ id="citation_at_start",+ ),+ pytest.param(+ f"It ended (event_uuid {_UUID_A})",+ {_UUID_A: 999},+ "It ended",+ [+ TextSegment(value="It ended"),+ ChipSegment(uuid=_UUID_A, timestamp_ms=999),+ ],+ id="citation_at_end",+ ),+ pytest.param(+ "Nothing to strip.",+ {_UUID_A: 0},+ "Nothing to strip.",+ [TextSegment(value="Nothing to strip.")],+ id="no_citations",+ ),+ pytest.param(+ f"Saw (event_uuid {_UUID_A.upper()}).",+ {_UUID_A: 42},+ "Saw.",+ [+ TextSegment(value="Saw"),+ ChipSegment(uuid=_UUID_A, timestamp_ms=42),+ TextSegment(value="."),+ ],+ id="uppercase_uuid_normalized",+ ),+ ],+ )+ def test_extract_segments(+ self,+ text: str,+ event_timestamps: dict[str, int],+ expected_plain: str,+ expected_segments: list[Segment],+ ) -> None:+ plain, segments = _extract_segments(text, event_timestamps)+ assert plain == expected_plain+ assert segments == expected_segments+++class TestResolveCitations:+ def test_populates_field_and_segments(self) -> None:+ finalized = MonitorOutput(verdict=True, reasoning=f"User retried (event_uuid {_UUID_A}) twice.", confidence=0.9)+ resolved = _resolve_citations(finalized, _monitor_scanner(), {_UUID_A: 1234})+ assert isinstance(resolved, MonitorOutput)+ assert resolved.reasoning == "User retried twice."+ assert resolved.reasoning_segments == [+ TextSegment(value="User retried"),+ ChipSegment(uuid=_UUID_A, timestamp_ms=1234),+ TextSegment(value=" twice."),+ ]++ def test_summarizer_uses_summary_field(self) -> None:+ finalized = SummarizerOutput(title="t", summary=f"They tried X (event_uuid {_UUID_A}).", confidence=0.9)+ resolved = _resolve_citations(finalized, _summarizer_scanner(), {_UUID_A: 7})+ assert isinstance(resolved, SummarizerOutput)+ assert resolved.summary == "They tried X."+ assert any(isinstance(s, ChipSegment) and s.uuid == _UUID_A for s in resolved.summary_segments)++ def test_no_citations_in_text_yields_single_text_segment(self) -> None:+ finalized = MonitorOutput(verdict=True, reasoning="No citations here.", confidence=0.9)+ resolved = _resolve_citations(finalized, _monitor_scanner(), {_UUID_A: 0})+ assert isinstance(resolved, MonitorOutput)+ assert resolved.reasoning == "No citations here."+ assert resolved.reasoning_segments == [TextSegment(value="No citations here.")]diff --git a/products/replay_vision/frontend/components/ObservationCard.tsx b/products/replay_vision/frontend/components/ObservationCard.tsxindex a6fa6d6ed05a..eb52a3cfa6d9 100644--- a/products/replay_vision/frontend/components/ObservationCard.tsx+++ b/products/replay_vision/frontend/components/ObservationCard.tsx@@ -1,6 +1,7 @@import { IconRewindPlay, IconSparkles, IconWarning } from '@posthog/icons'import { LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'+import { colonDelimitedDuration } from 'lib/utils'import { urls } from 'scenes/urls'import type { ReplayObservationApi, ScannerSnapshotApi } from '../generated/api.schemas'@@ -10,7 +11,6 @@ import {parseIneligibleReason,scannerTypeLabel,} from '../replay_scanners/types'-import { CitationPart, formatSessionOffset, parseCitedText } from '../utils/citations'export function ObservationStatusTag({ status }: { status: ReplayObservationApi['status'] }): JSX.Element {if (status === 'succeeded') {@@ -38,24 +38,48 @@ export function readResult(observation: ReplayObservationApi): Record<string, unreturn output && typeof output === 'object' ? (output as Record<string, unknown>) : null}-/** Dumb renderer for parsed citation parts. Pass `onSeek` to make citations interactive; omit for plain-text timestamps. */+type Segment = { kind: 'text'; value: string } | { kind: 'chip'; uuid: string; timestamp_ms: number }++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.uuid === 'string' && 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({- parts,+ text,+ segments,onSeek,}: {- parts: CitationPart[]+ text: string+ segments: unknownonSeek?: (timestampMs: number) => void}): JSX.Element {+ const list = Array.isArray(segments) ? (segments.filter(isSegment) as Segment[]) : []+ if (list.length === 0) {+ return <>{text}</>+ }return (<>- {parts.map((part, i) => {- if (part.type === 'text') {- return <span key={i}>{part.value}</span>+ {list.map((segment, i) => {+ if (segment.kind === 'text') {+ return <span key={i}>{segment.value}</span>}- const label = formatSessionOffset(part.timestampMs)+ const seconds = Math.max(0, Math.floor(segment.timestamp_ms / 1000))+ const label = colonDelimitedDuration(seconds, null)if (onSeek) {return (- <Link key={i} onClick={() => onSeek(part.timestampMs)}>+ <Link key={i} onClick={() => onSeek(segment.timestamp_ms)}><IconRewindPlay className="inline-block align-text-bottom mr-0.5" /><span className="font-mono">{label}</span></Link>@@ -123,10 +147,7 @@ export function ObservationPrimaryOutput({{title && <span className="font-semibold text-sm">{title}</span>}{summary && (<span className={summaryClass}>- <CitedText- parts={parseCitedText(summary, observation.scanner_result?.event_id_mapping)}- onSeek={onSeek}- />+ <CitedText text={summary} segments={result.summary_segments} onSeek={onSeek} /></span>)}</div>diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 585ee58d7242..702bfe8ab16d 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -89,11 +89,6 @@ export interface ScannerSnapshotApi {scanner_config: unknown}-/**- * Maps the short `event_id` the LLM cites in `model_output.reasoning` to citation metadata: `{uuid, timestamp_ms}`. Only includes hashes the LLM actually cited.- */-export type ScannerResultApiEventIdMapping = { [key: string]: unknown }-/*** Mirrors `temporal.types.ScannerResult` for OpenAPI generation.*/@@ -105,8 +100,6 @@ export interface ScannerResultApi {* @minimum 0*/signals_count: number- /** Maps the short `event_id` the LLM cites in `model_output.reasoning` to citation metadata: `{uuid, timestamp_ms}`. Only includes hashes the LLM actually cited. */- event_id_mapping: ScannerResultApiEventIdMapping}/**diff --git a/products/replay_vision/frontend/observations/ReplayObservation.tsx b/products/replay_vision/frontend/observations/ReplayObservation.tsxindex 6e652f0ebb97..730e5de6fa4d 100644--- a/products/replay_vision/frontend/observations/ReplayObservation.tsx+++ b/products/replay_vision/frontend/observations/ReplayObservation.tsx@@ -29,7 +29,6 @@ import {readResult,} from '../components/ObservationCard'import { modelLabel, scannerTypeLabel } from '../replay_scanners/types'-import { parseCitedText } from '../utils/citations'import { replayObservationLogic } from './replayObservationLogic'import { ReplayObservationSceneLogicProps, replayObservationSceneLogic } from './replayObservationSceneLogic'@@ -70,6 +69,7 @@ export function ReplayObservationSceneComponent({ tabId }: { tabId: string }): Jconst snapshot = observation.scanner_snapshotconst result = readResult(observation)const reasoning = result && typeof result.reasoning === 'string' ? result.reasoning : null+ const reasoningSegments = result?.reasoning_segmentsconst scannerType = snapshot?.scanner_typeconst scannerName = snapshot?.name || 'Scanner'const triggerLabel = observation.triggered_by === 'on_demand' ? 'On demand' : 'Schedule'@@ -150,10 +150,7 @@ export function ReplayObservationSceneComponent({ tabId }: { tabId: string }): J<div className="text-sm font-medium">Reasoning</div>{reasoning ? (<p className="text-sm whitespace-pre-wrap m-0">- <CitedText- parts={parseCitedText(reasoning, observation.scanner_result?.event_id_mapping)}- onSeek={seekEmbeddedPlayer}- />+ <CitedText text={reasoning} segments={reasoningSegments} onSeek={seekEmbeddedPlayer} /></p>) : (<p className="text-muted text-sm m-0">No reasoning provided.</p>diff --git a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts b/products/replay_vision/frontend/replay_scanners/scannerTemplates.tsindex a319538c25d7..78d9fda578d9 100644--- a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts@@ -1,6 +1,5 @@import type {ClassifierScannerConfig,- IndexerScannerConfig,MonitorScannerConfig,ScorerScannerConfig,SummarizerScannerConfig,@@ -47,17 +46,7 @@ export interface ScorerTemplate extends BaseTemplate {scanner_config: ScorerScannerConfig}-export interface IndexerTemplate extends BaseTemplate {- scanner_type: 'indexer'- scanner_config: IndexerScannerConfig-}--export type ScannerTemplate =- | MonitorTemplate- | SummarizerTemplate- | ClassifierTemplate- | ScorerTemplate- | IndexerTemplate+export type ScannerTemplate = MonitorTemplate | SummarizerTemplate | ClassifierTemplate | ScorerTemplateexport const defaultScannerTemplates: readonly ScannerTemplate[] = [{diff --git a/products/replay_vision/frontend/utils/citations.ts b/products/replay_vision/frontend/utils/citations.tsdeleted file mode 100644index 07c49fd97a34..000000000000--- a/products/replay_vision/frontend/utils/citations.ts+++ /dev/null@@ -1,50 +0,0 @@-/** Inline `(event_id <hash>)` marker the model emits in free-text fields. Mirrors backend's `_EVENT_ID_CITATION_RE`; keep in sync. */-const EVENT_ID_PATTERN = /\(event_id ([0-9a-f]{16})\)/gi--export type CitationPart = { type: 'text'; value: string } | { type: 'citation'; timestampMs: number; uuid?: string }--/**- * Parse free-text from a scanner's model output into a sequence of plain-text segments and citation chips,- * resolving inline `(event_id <hash>)` markers against the observation's `event_id_mapping`. Unresolved markers- * are stripped so they never reach the UI as raw text.- */-export function parseCitedText(- text: string | null | undefined,- mapping: Record<string, unknown> | null | undefined-): CitationPart[] {- if (!text) {- return []- }- const map = mapping ?? {}- const parts: CitationPart[] = []- let lastIndex = 0- EVENT_ID_PATTERN.lastIndex = 0- let match: RegExpExecArray | null- while ((match = EVENT_ID_PATTERN.exec(text)) !== null) {- const [full, hash] = match- const citation = map[hash.toLowerCase()] as { uuid?: string; timestamp_ms?: number } | undefined- if (match.index > lastIndex) {- parts.push({ type: 'text', value: text.slice(lastIndex, match.index) })- }- if (citation && typeof citation.timestamp_ms === 'number') {- parts.push({ type: 'citation', timestampMs: citation.timestamp_ms, uuid: citation.uuid })- }- // Unresolved citations are silently dropped — raw markers must never reach the UI.- lastIndex = match.index + full.length- }- if (lastIndex < text.length) {- parts.push({ type: 'text', value: text.slice(lastIndex) })- }- return parts-}--export function formatSessionOffset(ms: number): string {- const totalSeconds = Math.max(0, Math.floor(ms / 1000))- const h = Math.floor(totalSeconds / 3600)- const m = Math.floor((totalSeconds % 3600) / 60)- const s = totalSeconds % 60- if (h > 0) {- return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`- }- return `${m}:${s.toString().padStart(2, '0')}`-}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 507e2275b34e..ddc03bbc8a4e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -24067,11 +24067,6 @@ export namespace Schemas {scanner_config: unknown;}- /**- * Maps the short `event_id` the LLM cites in `model_output.reasoning` to citation metadata: `{uuid, timestamp_ms}`. Only includes hashes the LLM actually cited.- */- export type ScannerResultEventIdMapping = { [key: string]: unknown };-/*** Mirrors `temporal.types.ScannerResult` for OpenAPI generation.*/@@ -24083,8 +24078,6 @@ export namespace Schemas {* @minimum 0*/signals_count: number;- /** Maps the short `event_id` the LLM cites in `model_output.reasoning` to citation metadata: `{uuid, timestamp_ms}`. Only includes hashes the LLM actually cited. */- event_id_mapping: ScannerResultEventIdMapping;}export interface ReplayObservation {