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.

6.8 KB
Raw Blame
import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { teamLogic } from 'scenes/teamLogic'

import { visionScannersObservationsList } from '../generated/api'
import type { ReplayObservationApi } from '../generated/api.schemas'
import { OBSERVE_POLL_GRACE_MS, scheduleObservationPoll, shouldPollObservations } from '../logics/observationPolling'

/**
 * A scan takes at most MAX_SESSIONS_PER_SCAN (200) recordings and a session can hold more than one row,
 * so the default page would truncate a large scan and leave sessions looking unfinished forever.
 */
const OBSERVATIONS_PAGE_LIMIT = 500
/** Give up after this long. A recording that has not settled by now needs the scanner page, not a spinner. */
const POLL_DEADLINE_MS = 10 * 60 * 1000
/** Consecutive failed reads before the widget stops retrying. */
const MAX_CONSECUTIVE_FAILURES = 5

export interface ReplayVisionScanWidgetLogicProps {
    /** The inline scanner the scan minted. Its observations are the scan's results. */
    scanId: string
    /** Only these sessions belong to this scan; the scanner is shared and holds older rows too. */
    sessionIds: string[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface replayVisionScanWidgetLogicValues {
    gaveUp: boolean
    latestPerSession: ReplayObservationApi[]
    observations: ReplayObservationApi[]
    observationsLoading: boolean
    pendingCount: number
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface replayVisionScanWidgetLogicActions {
    giveUp: () => {
        value: true
    }
    loadObservations: () => any
    loadObservationsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadObservationsSuccess: (
        observations: ReplayObservationApi[],
        payload?: any
    ) => {
        observations: ReplayObservationApi[]
        payload?: any
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface replayVisionScanWidgetLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        latestPerSession: (observations: ReplayObservationApi[]) => ReplayObservationApi[]
        pendingCount: (latestPerSession: ReplayObservationApi[], arg: string[]) => number
    }
}

export type replayVisionScanWidgetLogicType = MakeLogicType<
    replayVisionScanWidgetLogicValues,
    replayVisionScanWidgetLogicActions,
    ReplayVisionScanWidgetLogicProps,
    replayVisionScanWidgetLogicMeta
>

export const replayVisionScanWidgetLogic = kea<replayVisionScanWidgetLogicType>([
    path(['products', 'replay_vision', 'frontend', 'posthogAi', 'replayVisionScanWidgetLogic']),
    props({} as ReplayVisionScanWidgetLogicProps),
    key((props: ReplayVisionScanWidgetLogicProps) => `${props.scanId}:${props.sessionIds.join(',')}`),

    actions({ giveUp: true }),

    reducers({
        gaveUp: [false, { giveUp: () => true }],
    }),

    loaders(({ props }) => ({
        observations: [
            [] as ReplayObservationApi[],
            {
                loadObservations: async () => {
                    const teamId = teamLogic.values.currentTeamId
                    // An empty `session_id` reads as "no filter", which would return the shared scanner's
                    // whole history. Nothing started, so there is nothing to read back.
                    if (!teamId || !props.sessionIds.length) {
                        return []
                    }
                    // Filter server-side. The scanner is shared, so asking for the newest N rows can come
                    // back holding only other people's sessions, leaving this scan looking unfinished.
                    const response = await visionScannersObservationsList(String(teamId), props.scanId, {
                        session_id: props.sessionIds.join(','),
                        limit: OBSERVATIONS_PAGE_LIMIT,
                    })
                    return response.results ?? []
                },
            },
        ],
    })),

    selectors({
        latestPerSession: [
            (s) => [s.observations],
            (observations: ReplayObservationApi[]): ReplayObservationApi[] => {
                // A session can hold more than one row, an earlier scan plus a retry. Newest wins, so a
                // stale row is never shown as this scan's finding and never counts a session twice.
                const newest = new Map<string, ReplayObservationApi>()
                for (const observation of observations) {
                    if (!newest.has(observation.session_id)) {
                        newest.set(observation.session_id, observation)
                    }
                }
                return [...newest.values()]
            },
        ],
        pendingCount: [
            (s) => [s.latestPerSession, (_, p: ReplayVisionScanWidgetLogicProps) => p.sessionIds],
            (latestPerSession: ReplayObservationApi[], sessionIds: string[]): number =>
                Math.max(
                    0,
                    sessionIds.length -
                        latestPerSession.filter((o) => o.status !== 'pending' && o.status !== 'running').length
                ),
        ],
    }),

    listeners(({ actions, values, cache }) => {
        // A row appears a moment after its scan starts, so an empty early response means "not yet".
        // The deadline stops a recording that never settles from polling for the life of the thread.
        const withinWindow = (): boolean =>
            shouldPollObservations(values.pendingCount > 0, cache.startedAt + OBSERVE_POLL_GRACE_MS) &&
            Date.now() < cache.startedAt + POLL_DEADLINE_MS
        const reschedule = (shouldPoll: boolean): void =>
            scheduleObservationPoll(cache.disposables, shouldPoll, actions.loadObservations)

        // Stopping while work is outstanding has to be visible, or the spinner sits there for good.
        const settle = (shouldPoll: boolean): void => {
            reschedule(shouldPoll)
            if (!shouldPoll && values.pendingCount > 0) {
                actions.giveUp()
            }
        }

        return {
            loadObservationsSuccess: () => {
                cache.failures = 0
                settle(withinWindow())
            },
            loadObservationsFailure: () => {
                // Without this the poll dies on the first blip and the spinner never resolves.
                cache.failures = (cache.failures ?? 0) + 1
                settle(cache.failures < MAX_CONSECUTIVE_FAILURES && withinWindow())
            },
        }
    }),

    afterMount(({ actions, cache }) => {
        cache.startedAt = Date.now()
        cache.failures = 0
        actions.loadObservations()
    }),
])