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.

4.4 KB
Raw Blame
import { TIMESTAMP_REF_PREFIX } from 'lib/lemon-ui/LemonMarkdown'
import { colonDelimitedDuration } from 'lib/utils/durations'

export type Segment = { kind: 'text'; value: string } | { kind: 'chip'; timestamp_ms: number }

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
}

// Wider than the backend's TIMESTAMP_CITATION_RE (scanners/base.py), which only parses comma-joined lists.
const TIMESTAMP_CITATION_RE = /\s*\(\s*t\s*(\d+(?:\s*(?:[,\u2013-]|to|and)\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 })
        }
        // Each comma-separated item is one cited moment. A range has a duration, so only its start seeks.
        for (const item of match[1].split(/,|\band\b/)) {
            const seconds = item.match(/\d+/)
            if (seconds) {
                segments.push({ kind: 'chip', timestamp_ms: parseInt(seconds[0], 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]))
}

/**
 * Markdown source for a cited field, each chip written back as a `t:<ms>` target. One string rather than
 * a segment list, or a bullet spanning a citation parses as two documents. The renderer sanitizes.
 */
export function citedMarkdown(text: string, segments: unknown): string {
    const list = parseCitedSegments(text, segments)
    if (list.length === 0) {
        return text
    }
    let out = ''
    for (const segment of list) {
        if (segment.kind === 'text') {
            out += segment.value
            continue
        }
        // Glued to the preceding word, except after a `!`, where that would make the pair an image.
        // Whole non-negative digits only: LemonMarkdown reads nothing else, and would leave a dead label.
        const timestampMs = Math.max(0, Math.round(segment.timestamp_ms))
        const label = colonDelimitedDuration(Math.floor(timestampMs / 1000), null)
        out += `${out.endsWith('!') ? ' ' : ''}[${label}](${TIMESTAMP_REF_PREFIX}${timestampMs})`
    }
    return out
}

/** Plain-text rendering of a cited field for the clipboard: citation chips become readable `(mm:ss)` timestamps. */
export function citedTextToPlainText(text: string, segments: unknown): string {
    const list = parseCitedSegments(text, segments)
    if (list.length === 0) {
        return text
    }
    let out = ''
    for (const segment of list) {
        if (segment.kind === 'text') {
            out += segment.value
            continue
        }
        const label = colonDelimitedDuration(Math.max(0, Math.floor(segment.timestamp_ms / 1000)), null)
        out += `${out && !/\s$/.test(out) ? ' ' : ''}(${label})`
    }
    return out
}

export function stripCitations(text: string, segments?: unknown): string {
    return parseCitedSegments(text, segments)
        .map((segment) => (segment.kind === 'text' ? segment.value : ' '))
        .join('')
        .replace(/\s+/g, ' ')
        .trim()
}