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.

11.0 KB
Raw Blame
import { MakeLogicType, actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'

import { teamLogic } from 'scenes/teamLogic'

import { observationsDockLogic } from '../logics/observationsDockLogic'
import {
    DISPLAY_PHASES,
    type DisplayPhase,
    type ObservationFrameProgress,
    type ObservationProgress,
    displayStepFor,
    framesOf,
    isRenderingStep,
    overallPercent,
} from './observationProgress'

interface DisplayState {
    step: number
    /** Client-clock ms when the current display step started. */
    startedAt: number
}

interface RememberedProgress {
    progress: ObservationProgress | null
    display: DisplayState | null
    percent: number
}

// Survives unmount so a reopened tab or dock resumes the bar instead of restarting it.
const progressMemory = new Map<string, RememberedProgress>()

function rememberedProgress(observationId: string): RememberedProgress {
    return progressMemory.get(observationId) ?? { progress: null, display: null, percent: 0 }
}

const PROGRESS_TICK_MS = 1000
const RECONNECT_INITIAL_DELAY_MS = 2000
const RECONNECT_MAX_DELAY_MS = 30000

export interface ObservationProgressLogicProps {
    observationId: string
    /** Lets the dock list refresh on completion; optional since the details page has no dock. */
    sessionId?: string
}

interface StreamHandlers {
    setProgress: (progress: ObservationProgress) => void
    streamCompleted: () => void
    setStreamError: (error: string) => void
}

/** Parse one SSE block (`event: <label>\ndata: <json>`) from our progress endpoint and dispatch it. */
function dispatchSseBlock(block: string, handlers: StreamHandlers): void {
    let event = ''
    const dataLines: string[] = []
    for (const line of block.split('\n')) {
        if (line.startsWith('event:')) {
            event = line.slice('event:'.length).trim()
        } else if (line.startsWith('data:')) {
            dataLines.push(line.slice('data:'.length).replace(/^ /, ''))
        }
    }
    const data = dataLines.join('\n')
    if (event === 'observation-progress') {
        try {
            handlers.setProgress(JSON.parse(data))
        } catch {
            // Drop an unparseable tick; the next one refreshes the bar.
        }
    } else if (event === 'observation-complete') {
        handlers.streamCompleted()
    } else if (event === 'observation-error') {
        handlers.setStreamError(data)
    }
}

async function consumeProgressStream(
    teamId: number,
    observationId: string,
    signal: AbortSignal,
    handlers: StreamHandlers
): Promise<boolean> {
    // Plain GET so read-only users can stream too (api.createResponse POSTs, which is blocked for them).
    const response = await fetch(`/api/projects/${teamId}/vision/observations/${observationId}/progress/`, {
        method: 'GET',
        headers: { Accept: 'text/event-stream' },
        credentials: 'same-origin',
        signal,
    })
    if (!response.ok || !response.body) {
        return false
    }
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let buffer = ''
    let received = false
    while (true) {
        const { done, value } = await reader.read()
        if (done) {
            return received
        }
        buffer += decoder.decode(value, { stream: true })
        let boundary = buffer.indexOf('\n\n')
        while (boundary !== -1) {
            received = true
            dispatchSseBlock(buffer.slice(0, boundary), handlers)
            buffer = buffer.slice(boundary + 2)
            boundary = buffer.indexOf('\n\n')
        }
    }
}

function waitFor(ms: number, signal: AbortSignal): Promise<void> {
    return new Promise((resolve) => {
        const onAbort = (): void => {
            clearTimeout(timer)
            resolve()
        }
        const timer = setTimeout(() => {
            signal.removeEventListener('abort', onAbort)
            resolve()
        }, ms)
        signal.addEventListener('abort', onAbort, { once: true })
    })
}

/** The server caps stream length and proxies drop idle streams, so any close short of a terminal event reconnects. */
async function followProgressStream(
    teamId: number,
    observationId: string,
    signal: AbortSignal,
    handlers: StreamHandlers
): Promise<void> {
    let delayMs = RECONNECT_INITIAL_DELAY_MS
    while (!signal.aborted) {
        let received = false
        try {
            received = await consumeProgressStream(teamId, observationId, signal, handlers)
        } catch {
            // An abort ends the loop; other errors reconnect.
        }
        delayMs = received ? RECONNECT_INITIAL_DELAY_MS : Math.min(delayMs * 2, RECONNECT_MAX_DELAY_MS)
        await waitFor(delayMs, signal)
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationProgressLogicValues {
    display: DisplayState | null
    displayPhase: DisplayPhase
    frames: ObservationFrameProgress | null
    percent: number
    progress: ObservationProgress | null
    stepNumber: number
    streamError: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationProgressLogicActions {
    setPercent: (percent: number) => {
        percent: number
    }
    setProgress: (
        progress: ObservationProgress,
        receivedAt?: number
    ) => {
        progress: ObservationProgress
        receivedAt: number
    }
    setStreamError: (error: string) => {
        error: string
    }
    startStream: () => {
        value: true
    }
    streamCompleted: () => {
        value: true
    }
    tick: (now?: number) => {
        now: number
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationProgressLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        frames: (progress: ObservationProgress | null) => ObservationFrameProgress | null
        displayPhase: (display: DisplayState | null) => DisplayPhase
        stepNumber: (display: DisplayState | null) => number
    }
}

export type observationProgressLogicType = MakeLogicType<
    observationProgressLogicValues,
    observationProgressLogicActions,
    ObservationProgressLogicProps,
    observationProgressLogicMeta
>

/**
 * Streams live progress for one in-flight observation over SSE. Keyed by observation id, so the dock card and the
 * details page share a single stream. The stream self-terminates once the observation settles.
 */
export const observationProgressLogic = kea<observationProgressLogicType>([
    path(['products', 'replay_vision', 'frontend', 'observations', 'observationProgressLogic']),
    props({} as ObservationProgressLogicProps),
    key((props) => props.observationId),

    actions({
        // Idempotent — callers that know the observation is in flight open the stream; settled rows never do.
        startStream: true,
        setProgress: (progress: ObservationProgress, receivedAt: number = Date.now()) => ({ progress, receivedAt }),
        tick: (now: number = Date.now()) => ({ now }),
        setPercent: (percent: number) => ({ percent }),
        streamCompleted: true,
        setStreamError: (error: string) => ({ error }),
    }),

    reducers(({ props }) => ({
        progress: [
            rememberedProgress(props.observationId).progress,
            {
                setProgress: (_, { progress }) => progress,
            },
        ],
        display: [
            rememberedProgress(props.observationId).display,
            {
                setProgress: (state, { progress, receivedAt }) => {
                    const step = displayStepFor(progress)
                    // A stale tick (failed query, render retry) must not pull the bar back.
                    if (state && step <= state.step) {
                        return state
                    }
                    // Rendering is measured in frames, so only time-filled steps need the server's elapsed time.
                    const elapsedMs = isRenderingStep(step) ? 0 : (progress.phase_elapsed_s ?? 0) * 1000
                    return { step, startedAt: receivedAt - elapsedMs }
                },
            },
        ],
        percent: [
            rememberedProgress(props.observationId).percent,
            {
                setPercent: (state, { percent }) => Math.max(state, percent),
            },
        ],
        streamError: [
            null as string | null,
            {
                setStreamError: (_, { error }) => error,
            },
        ],
    })),

    selectors({
        frames: [
            (s) => [s.progress],
            (progress: ObservationProgress | null): ObservationFrameProgress | null => framesOf(progress),
        ],
        displayPhase: [
            (s) => [s.display],
            (display: DisplayState | null): DisplayPhase => DISPLAY_PHASES[display?.step ?? 0],
        ],
        stepNumber: [(s) => [s.display], (display: DisplayState | null): number => (display?.step ?? 0) + 1],
    }),

    listeners(({ props, actions, cache, values }) => ({
        setProgress: ({ receivedAt }) => {
            actions.tick(receivedAt)
        },
        tick: ({ now }) => {
            const { display, frames } = values
            if (display) {
                const elapsedS = (now - display.startedAt) / 1000
                actions.setPercent(overallPercent(display.step, elapsedS, frames))
            }
            progressMemory.set(props.observationId, {
                progress: values.progress,
                display: values.display,
                percent: values.percent,
            })
        },
        startStream: () => {
            const teamId = teamLogic.values.currentTeamId
            if (cache.streamStarted || !teamId) {
                return
            }
            cache.streamStarted = true
            // Disposable so the fetch is aborted on unmount and paused while the tab is hidden.
            cache.disposables.add(() => {
                const controller = new AbortController()
                void followProgressStream(teamId, props.observationId, controller.signal, actions)
                return () => controller.abort()
            }, 'progressStream')
            cache.disposables.add(() => {
                const interval = setInterval(() => actions.tick(), PROGRESS_TICK_MS)
                return () => clearInterval(interval)
            }, 'progressTicker')
        },
        streamCompleted: () => {
            // The observation settled — dispose the stream so tab hide/show cycles don't resurrect it.
            cache.disposables.dispose('progressStream')
            cache.disposables.dispose('progressTicker')
            progressMemory.delete(props.observationId)
            // Refresh the dock list so the finished card swaps to the result immediately; no-op if the dock isn't mounted.
            if (props.sessionId) {
                observationsDockLogic.findMounted({ sessionId: props.sessionId })?.actions.loadObservations()
            }
        },
        setStreamError: () => {
            cache.disposables.dispose('progressStream')
            cache.disposables.dispose('progressTicker')
        },
    })),
])