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.

24.6 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    afterMount,
    isBreakpoint,
    kea,
    key,
    listeners,
    path,
    props,
    reducers,
    selectors,
} from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'

import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { NodeKind } from '~/queries/schema/schema-general'

import {
    visionObservationsSearchRetrieve,
    visionObservationsSearchSuggestionsRetrieve,
    visionObservationsSearchViewedCreate,
} from '../generated/api'
import type { ObservationSearchResultApi } from '../generated/api.schemas'
import { ReplayScannerTab } from '../replay_scanners/replayScannerSceneLogic'
import { readSimilarSearchIntent } from './observationQueries'

// The server's MAX_SEARCH_LIMIT. A larger value would 400.
const SEARCH_RESULT_LIMIT = 50

// Client-side paging over the single ranked response. Not in the URL, where the observations table owns `page`.
export const SEARCH_PAGE_SIZE = 9

export type SearchResultTarget = 'watch' | 'detail'

const TOP_MATCH_COUNT = 3
// The server's error code when the organization has not allowed AI data processing.
const AI_CONSENT_REQUIRED_CODE = 'ai_data_processing_not_approved'
const RECENT_QUERIES_LIMIT = 3
// One URL change can dispatch the same action twice. A short breakpoint collapses them into one request.
export const SEARCH_COALESCE_MS = 10

export type ResultsView = 'grid' | 'list'

export interface ObservationSearchLogicProps {
    /** Keys the persisted recent searches, so one project's queries never show in another. */
    teamId: number | null
    /** Also keys the persisted recent searches, so another account on this browser starts empty. */
    userId: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationSearchLogicValues {
    dateFrom: string | null
    dateTo: string | null
    expiredSessionIds: Set<string>
    page: number
    pageCount: number
    pageEndIndex: number
    pageResults: ObservationSearchResultApi[]
    pageStartIndex: number
    pendingSourceObservationId: string | null
    query: string
    recentQueries: string[]
    reranked: boolean
    results: ObservationSearchResultApi[] | null
    scannerId: string | null
    searchedQuery: string | null
    searching: boolean
    sourceObservationId: string | null
    suggestedQueries: string[]
    suggestedQueriesLoading: boolean
    topMatchIds: Set<string> | null
    truncated: boolean
    unavailableSessionIds: string[]
    unavailableSessionIdsLoading: boolean
    view: ResultsView
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationSearchLogicActions {
    checkRecordingAvailability: (sessionIds: string[]) => string[]
    checkRecordingAvailabilityFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    checkRecordingAvailabilitySuccess: (
        unavailableSessionIds: string[],
        payload?: string[]
    ) => {
        unavailableSessionIds: string[]
        payload?: string[]
    }
    clearSearch: () => {
        value: true
    }
    loadSuggestedQueries: (_: void) => void
    loadSuggestedQueriesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSuggestedQueriesSuccess: (
        suggestedQueries: string[],
        payload?: void
    ) => {
        suggestedQueries: string[]
        payload?: void
    }
    resultOpened: (
        observationId: string,
        target: SearchResultTarget
    ) => {
        observationId: string
        target: SearchResultTarget
    }
    search: () => {
        value: true
    }
    searchFailure: () => {
        value: true
    }
    searchSimilar: (
        query: string,
        sourceObservationId: string
    ) => {
        query: string
        sourceObservationId: string
    }
    searchSuccess: (
        results: ObservationSearchResultApi[],
        query: string,
        truncated: boolean,
        sourceObservationId?: string | null,
        reranked?: boolean
    ) => {
        query: string
        reranked: boolean
        results: ObservationSearchResultApi[]
        sourceObservationId: string | null
        truncated: boolean
    }
    setDateRange: (
        dateFrom: string | null,
        dateTo: string | null
    ) => {
        dateFrom: string | null
        dateTo: string | null
    }
    setPage: (page: number) => {
        page: number
    }
    setQuery: (query: string) => {
        query: string
    }
    setScannerId: (scannerId: string | null) => {
        scannerId: string | null
    }
    setView: (view: ResultsView) => {
        view: ResultsView
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationSearchLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        expiredSessionIds: (unavailableSessionIds: string[]) => Set<string>
        pageCount: (results: ObservationSearchResultApi[] | null) => number
        pageResults: (results: ObservationSearchResultApi[] | null, page: number) => ObservationSearchResultApi[]
        pageStartIndex: (page: number) => number
        pageEndIndex: (pageStartIndex: number, pageResults: ObservationSearchResultApi[]) => number
        topMatchIds: (results: ObservationSearchResultApi[] | null) => Set<string> | null
    }
}

export type observationSearchLogicType = MakeLogicType<
    observationSearchLogicValues,
    observationSearchLogicActions,
    ObservationSearchLogicProps,
    observationSearchLogicMeta
>

// This event carries no query property. The text is free and can hold customer names or emails.
// The `q` URL parameter still reaches analytics through `$current_url`, as it does for every event on this page.
function captureSearchOutcome(
    scannerId: string | null,
    outcome: {
        succeeded: boolean
        result_count?: number
        reranked?: boolean
        error_status?: number
        error_code?: string
    }
): void {
    posthog.capture('replay vision observation search completed', {
        ...outcome,
        scope: searchScope(scannerId),
    })
}

function searchScope(scannerId: string | null): 'scanner' | 'cross-scanner' {
    return scannerId ? 'scanner' : 'cross-scanner'
}

export const observationSearchLogic = kea<observationSearchLogicType>([
    path(['products', 'replay_vision', 'frontend', 'search', 'observationSearchLogic']),
    props({} as ObservationSearchLogicProps),
    key((props) => `${props.userId ?? 'user'}:${props.teamId ?? 'team'}`),

    actions({
        setQuery: (query: string) => ({ query }),
        setScannerId: (scannerId: string | null) => ({ scannerId }),
        // The DateFilter's "All time" preset emits the `all` sentinel, which the search API rejects;
        // it expresses an unbounded range by omitting the bound.
        setDateRange: (dateFrom: string | null, dateTo: string | null) => ({
            dateFrom: dateFrom === 'all' ? null : dateFrom,
            dateTo: dateTo === 'all' ? null : dateTo,
        }),
        setPage: (page: number) => ({ page }),
        setView: (view: ResultsView) => ({ view }),
        search: true,
        searchSimilar: (query: string, sourceObservationId: string) => ({ query, sourceObservationId }),
        searchSuccess: (
            results: ObservationSearchResultApi[],
            query: string,
            truncated: boolean,
            sourceObservationId: string | null = null,
            reranked: boolean = false
        ) => ({
            results,
            query,
            truncated,
            sourceObservationId,
            reranked,
        }),
        resultOpened: (observationId: string, target: SearchResultTarget) => ({ observationId, target }),
        searchFailure: true,
        clearSearch: true,
    }),

    reducers({
        query: [
            '' as string,
            {
                setQuery: (_, { query }) => query,
                searchSimilar: (_, { query }) => query,
                clearSearch: () => '',
            },
        ],
        scannerId: [
            null as string | null,
            {
                setScannerId: (_, { scannerId }) => scannerId,
            },
        ],
        // Relative (`-30d`) or absolute bounds on when the observation was analyzed; null means unbounded.
        dateFrom: [
            null as string | null,
            {
                setDateRange: (_, { dateFrom }) => dateFrom,
            },
        ],
        dateTo: [
            null as string | null,
            {
                setDateRange: (_, { dateTo }) => dateTo,
            },
        ],
        // Provenance of the next search. Editing the prose makes it a regular search.
        pendingSourceObservationId: [
            null as string | null,
            {
                searchSimilar: (_, { sourceObservationId }) => sourceObservationId,
                setQuery: () => null,
                clearSearch: () => null,
            },
        ],
        // Provenance of the displayed results, so their links keep the prose out of the URL until a new search lands.
        sourceObservationId: [
            null as string | null,
            {
                searchSuccess: (_, { sourceObservationId }) => sourceObservationId,
                clearSearch: () => null,
            },
        ],
        // null until the first search, so the empty state can tell "not searched yet" from "no matches".
        results: [
            null as ObservationSearchResultApi[] | null,
            {
                searchSuccess: (_, { results }) => results,
                clearSearch: () => null,
            },
        ],
        searching: [
            false,
            {
                search: () => true,
                searchSuccess: () => false,
                searchFailure: () => false,
                clearSearch: () => false,
            },
        ],
        searchedQuery: [
            null as string | null,
            {
                searchSuccess: (_, { query }) => query,
                clearSearch: () => null,
            },
        ],
        recentQueries: [
            [] as string[],
            { persist: true },
            {
                searchSuccess: (state, { query, results, sourceObservationId }) =>
                    sourceObservationId === null && results.length > 0
                        ? [query, ...state.filter((recent) => recent !== query)].slice(0, RECENT_QUERIES_LIMIT)
                        : state,
            },
        ],
        page: [
            1 as number,
            {
                setPage: (_, { page }) => page,
                searchSuccess: () => 1,
            },
        ],
        view: [
            'grid' as ResultsView,
            { persist: true },
            {
                setView: (_, { view }) => view,
            },
        ],
        // The server cut the response to `limit`, so the results are a top slice, not everything that matched.
        truncated: [
            false,
            {
                searchSuccess: (_, { truncated }) => truncated,
                clearSearch: () => false,
            },
        ],
        reranked: [
            false,
            {
                searchSuccess: (_, { reranked }) => reranked,
                clearSearch: () => false,
            },
        ],
        // Stale confirmations must not tag the next search's results while its own check is in flight.
        unavailableSessionIds: [
            [] as string[],
            {
                search: () => [],
                clearSearch: () => [],
            },
        ],
    }),

    loaders(({ values }) => ({
        // Searched sessions whose recording no longer exists. A recording keeps the retention period it
        // was captured under and the team setting can change afterwards, so expiry is confirmed against
        // the recordings API instead of being derived from the observation's age.
        unavailableSessionIds: [
            [] as string[],
            {
                checkRecordingAvailability: async (sessionIds: string[], breakpoint) => {
                    if (sessionIds.length === 0) {
                        return []
                    }
                    try {
                        const response = await api.recordings.list({
                            kind: NodeKind.RecordingsQuery,
                            session_ids: sessionIds,
                        })
                        breakpoint()
                        const playable = new Set(response.results.map((recording) => recording.id))
                        return sessionIds.filter((sessionId) => !playable.has(sessionId))
                    } catch (error) {
                        if (error instanceof Error && isBreakpoint(error)) {
                            throw error
                        }
                        // No session-recording access (403) or a transient failure: show no expired tags
                        // rather than an error toast, since this action is not on initKea's allow list.
                        return []
                    }
                },
            },
        ],
        suggestedQueries: [
            [] as string[],
            {
                loadSuggestedQueries: async (_: void, breakpoint) => {
                    await breakpoint(SEARCH_COALESCE_MS)
                    const teamId = teamLogic.values.currentTeamId
                    // A deep-linked query renders results, never the empty state, so its suggestions would go unseen.
                    if (!teamId || router.values.searchParams.q) {
                        return []
                    }
                    const scope = values.scannerId ? { scanner_id: values.scannerId } : undefined
                    // The view is what keeps a scanner's suggestions refreshing; it is a separate POST so the read
                    // stays side-effect free, and nothing here waits on it.
                    void visionObservationsSearchViewedCreate(String(teamId), scope).catch(() => undefined)
                    try {
                        const response = await visionObservationsSearchSuggestionsRetrieve(String(teamId), scope)
                        return response.queries ?? []
                    } catch {
                        // The empty state falls back to fixed examples, so a failed suggestion fetch stays silent.
                        return []
                    }
                },
            },
        ],
    })),

    selectors({
        expiredSessionIds: [
            (s) => [s.unavailableSessionIds],
            (unavailableSessionIds: string[]): Set<string> => new Set(unavailableSessionIds),
        ],
        pageCount: [
            (s) => [s.results],
            (results: ObservationSearchResultApi[] | null): number =>
                results ? Math.ceil(results.length / SEARCH_PAGE_SIZE) : 0,
        ],
        pageResults: [
            (s) => [s.results, s.page],
            (results: ObservationSearchResultApi[] | null, page: number): ObservationSearchResultApi[] =>
                results ? results.slice((page - 1) * SEARCH_PAGE_SIZE, page * SEARCH_PAGE_SIZE) : [],
        ],
        pageStartIndex: [(s) => [s.page], (page: number): number => (page - 1) * SEARCH_PAGE_SIZE],
        pageEndIndex: [
            (s) => [s.pageStartIndex, s.pageResults],
            (pageStartIndex: number, pageResults: ObservationSearchResultApi[]): number =>
                pageStartIndex + pageResults.length,
        ],
        // Null when the tiers would not separate anything, so a lone tier is never labeled.
        topMatchIds: [
            (s) => [s.results],
            (results: ObservationSearchResultApi[] | null): Set<string> | null =>
                results && results.length > TOP_MATCH_COUNT
                    ? new Set(results.slice(0, TOP_MATCH_COUNT).map((result) => result.observation.id))
                    : null,
        ],
    }),

    listeners(({ actions, values }) => ({
        // Emptying the input (the field's clear button included) is how a person gets back to the empty state.
        setQuery: ({ query }) => {
            if (!query.trim() && values.searchedQuery !== null) {
                actions.clearSearch()
            }
        },
        setScannerId: () => {
            actions.loadSuggestedQueries()
            if (values.searchedQuery !== null || values.searching) {
                actions.search()
            }
        },
        setDateRange: () => {
            if (values.searchedQuery !== null || values.searching) {
                actions.search()
            }
        },
        searchSuccess: ({ results }) => {
            // An observation is created when its scan runs, not when the session happened, so its age
            // cannot rule expiry out for a backfilled scan of an old session. The recordings API is the
            // source of truth, so check every result's session in one batched request (at most 50).
            const sessionIds = Array.from(new Set(results.map((result) => result.observation.session_id)))
            actions.checkRecordingAvailability(sessionIds)
        },
        searchSimilar: () => actions.search(),
        // Rank against `reranked` tells whether the reranked order puts the results people open higher.
        resultOpened: ({ observationId, target }) => {
            const index = values.results?.findIndex((result) => result.observation.id === observationId) ?? -1
            if (index < 0) {
                return
            }
            posthog.capture('replay vision observation search result opened', {
                rank: index + 1,
                target,
                reranked: values.reranked,
                result_count: values.results?.length ?? 0,
                scope: searchScope(values.scannerId),
                similar_search: values.sourceObservationId !== null,
            })
        },
        search: async (_, breakpoint) => {
            await breakpoint(SEARCH_COALESCE_MS)
            const query = values.query.trim()
            if (!query) {
                actions.searchFailure()
                return
            }
            const teamId = teamLogic.values.currentTeamId
            if (!teamId) {
                actions.searchFailure()
                return
            }
            const sourceObservationId = values.pendingSourceObservationId
            try {
                const response = await visionObservationsSearchRetrieve(String(teamId), {
                    q: query,
                    limit: SEARCH_RESULT_LIMIT,
                    ...(values.scannerId ? { scanner_id: values.scannerId } : {}),
                    ...(values.dateFrom ? { date_from: values.dateFrom } : {}),
                    ...(values.dateTo ? { date_to: values.dateTo } : {}),
                })
                // Drop out-of-order responses. The newest search owns the results.
                breakpoint()
                // The source of a "find similar" search is its own nearest neighbour.
                const results = (response.results ?? []).filter((r) => r.observation.id !== sourceObservationId)
                const reranked = response.reranked ?? false
                captureSearchOutcome(values.scannerId, { succeeded: true, result_count: results.length, reranked })
                // Cleared while in flight: the late response must not refill the card.
                if (!values.searching) {
                    return
                }
                actions.searchSuccess(results, query, response.truncated ?? false, sourceObservationId, reranked)
            } catch (error: any) {
                if (error instanceof Error && isBreakpoint(error)) {
                    throw error
                }
                // Drop out-of-order failures, like the success path above. A newer search owns the outcome,
                // so an older failure must not skew the capture, raise a toast, or stop the spinner.
                breakpoint()
                captureSearchOutcome(values.scannerId, {
                    succeeded: false,
                    error_status: error?.status,
                    error_code: error?.code,
                })
                if (error?.code === AI_CONSENT_REQUIRED_CODE) {
                    lemonToast.error('AI data processing is turned off for your organization.', {
                        button: {
                            label: 'Open settings',
                            action: () =>
                                router.actions.push(urls.settings('organization-details', 'organization-ai-consent')),
                        },
                    })
                } else {
                    lemonToast.error(`Search failed${error?.detail ? `: ${error.detail}` : ''}`)
                }
                actions.searchFailure()
            }
        },
    })),

    afterMount(({ actions }) => {
        actions.loadSuggestedQueries()
    }),

    actionToUrl(({ values }) => {
        const withScope = (
            q: string | undefined,
            replace: boolean = true
        ): [string, Record<string, unknown>, Record<string, unknown>, { replace: boolean }] => [
            router.values.location.pathname,
            {
                ...router.values.searchParams,
                q,
                scanner: values.scannerId ?? undefined,
                date_from: values.dateFrom ?? undefined,
                date_to: values.dateTo ?? undefined,
                similar: values.pendingSourceObservationId ?? undefined,
            },
            router.values.hashParams,
            { replace },
        ]
        return {
            // Observation prose stays out of the URL (see markSimilarSearchIntent).
            // A submitted query pushes, so browser back returns to the previous search.
            search: () =>
                withScope(values.pendingSourceObservationId ? undefined : values.query.trim() || undefined, false),
            clearSearch: () => withScope(undefined),
            setScannerId: () => withScope(router.values.searchParams.q),
            setDateRange: () => withScope(router.values.searchParams.q),
        }
    }),

    urlToAction(({ actions, values }) => {
        return {
            [urls.replayVision()]: (_: unknown, searchParams: Record<string, unknown>) => {
                if (searchParams.tab !== ReplayScannerTab.Search) {
                    return
                }
                const scanner = typeof searchParams.scanner === 'string' ? searchParams.scanner : null
                if (scanner !== values.scannerId) {
                    actions.setScannerId(scanner)
                }
                const dateFrom = typeof searchParams.date_from === 'string' ? searchParams.date_from : null
                const dateTo = typeof searchParams.date_to === 'string' ? searchParams.date_to : null
                if (dateFrom !== values.dateFrom || dateTo !== values.dateTo) {
                    actions.setDateRange(dateFrom, dateTo)
                }
                const similar = typeof searchParams.similar === 'string' ? searchParams.similar : ''
                if (similar) {
                    // Result links keep `similar` after typing cleared the pending source, so match the shown source too.
                    if (similar === values.pendingSourceObservationId || similar === values.sourceObservationId) {
                        return
                    }
                    const similarQuery = readSimilarSearchIntent(similar)
                    if (similarQuery) {
                        actions.searchSimilar(similarQuery, similar)
                    } else {
                        // No stored query: clearing drops the param and the previous results.
                        actions.clearSearch()
                    }
                    return
                }
                // kea-router decodes ?q=true to a boolean, so stringify instead of dropping it.
                const raw = searchParams.q
                const q = typeof raw === 'string' ? raw : raw != null ? String(raw) : ''
                // Run a deep-linked query once. The trimmed-input check blocks the actionToUrl echo and keeps
                // a failed query from re-firing on unrelated URL changes.
                if (q && q !== values.searchedQuery && q !== values.query.trim()) {
                    actions.setQuery(q)
                    actions.search()
                } else if (!q && values.searchedQuery !== null && values.sourceObservationId === null) {
                    // The URL lost its query (back navigation, or a tab switch dropped it), so show the empty state.
                    actions.clearSearch()
                }
            },
        }
    }),
])