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.4 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers } from 'kea'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'

import api from 'lib/api'
import { keyForInsightLogicProps } from 'lib/insights/sharedUtils'
import { sanitizeInsight, sanitizeQuery } from 'lib/utils/eventUsageLogic'
import { objectClean, objectsEqual } from 'lib/utils/objects'
import { projectLogic } from 'scenes/projectLogic'
import { userLogic } from 'scenes/userLogic'

import { isSharedView } from '~/exporter/exporterViewLogic'
import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/insightVizKeys'
import { isNodeWithSource } from '~/queries/schema/node-guards'
import { Node } from '~/queries/schema/schema-general'
import { InsightLogicProps } from '~/types'

import type { DataNode } from '../../queries/schema/schema-general'
import type { InsightModel } from '../../types'
import { insightLogic } from './insightLogic'
import { insightSceneLogic } from './insightSceneLogic'

function reportInsightViewed(
    insightModel: Partial<InsightModel>,
    query: Node | null,
    isFirstLoad: boolean,
    delay?: number
): void {
    const payload: Record<string, any> = {
        report_delay: delay,
        is_first_component_load: isFirstLoad,
        viewer_is_creator:
            insightModel.created_by?.uuid && userLogic.values.user?.uuid
                ? insightModel.created_by?.uuid === userLogic.values.user?.uuid
                : undefined,
        is_saved: insightModel.saved,
        description_length: insightModel.description?.length ?? 0,
        tags_count: insightModel.tags?.length ?? 0,
        insight: sanitizeInsight(insightModel),
        insight_id: insightModel.id,
        insight_short_id: insightModel.short_id,
        ...sanitizeQuery(query),
    }

    // The view path passes a bare source node, so sanitizeQuery's `query_kind`/`query_source_kind`
    // describe the source rather than the wrapper. Override them from the full stored query so
    // `query_kind` consistently means the top-level node, matching every other insight event.
    const modelQuery = insightModel.query as Node | null | undefined
    if (modelQuery) {
        payload.query_kind = modelQuery.kind
        payload.query_source_kind = isNodeWithSource(modelQuery) ? modelQuery.source.kind : undefined
    }

    const eventName = delay ? 'insight analyzed' : 'insight viewed'
    posthog.capture(eventName, objectClean({ ...payload, source: 'web' }))
}

const IS_TEST_MODE = process.env.NODE_ENV === 'test'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface insightUsageLogicValues {
    query: DataNode<Record<string, any>> // dataNodeLogic
    insight: Partial<InsightModel<Node<Record<string, any>>>> // insightLogic
    currentProjectId: number | null // projectLogic
    isFirstLoad: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface insightUsageLogicActions {
    onQueryChange: (
        query: Node | null,
        previousQuery?: Node | null
    ) => {
        previousQuery: Node<Record<string, any>> | null | undefined
        query: Node<Record<string, any>> | null
    }
    setNotFirstLoad: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface insightUsageLogicMeta {
    key: string
}

export type insightUsageLogicType = MakeLogicType<
    insightUsageLogicValues,
    insightUsageLogicActions,
    InsightLogicProps,
    insightUsageLogicMeta
>

export const insightUsageLogic = kea<insightUsageLogicType>([
    props({} as InsightLogicProps),
    key(keyForInsightLogicProps('new')),
    path((key) => ['scenes', 'insights', 'insightUsageLogic', key]),
    connect((props: InsightLogicProps) => ({
        values: [
            projectLogic,
            ['currentProjectId'],
            insightLogic(props),
            ['insight'],
            dataNodeLogic({ key: insightVizDataNodeKey(props) } as DataNodeLogicProps),
            ['query'],
        ],
    })),
    actions({
        onQueryChange: (query: Node | null, previousQuery?: Node | null) => ({
            query,
            previousQuery,
        }),
        setNotFirstLoad: true,
    }),
    reducers({
        isFirstLoad: [
            true,
            {
                setNotFirstLoad: () => false,
            },
        ],
    }),
    listeners(({ actions, props, values }) => ({
        onQueryChange: async ({ query }, breakpoint) => {
            // We only want to report direct views on the insights page.
            const logic = insightSceneLogic.findMounted()
            // Unsaved insights share an empty short_id, so it can't tell the scene's insight from a preview.
            const sceneDashboardItemId = logic?.values.insightLogicRef?.logic.props.dashboardItemId

            if (!logic || sceneDashboardItemId !== props.dashboardItemId) {
                return
            }

            // Report the insight being viewed to our '/viewed' endpoint.
            // Used for "recently viewed insights", and in insights dashboard.
            if (values.insight.id && !isSharedView()) {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. insightsViewedCreate() from 'products/product_analytics/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                void api.create(`api/projects/${values.currentProjectId}/insights/viewed`, {
                    insight_ids: [values.insight.id],
                })
            }

            // Debounce to avoid noisy events from the query changing multiple times.
            await breakpoint(IS_TEST_MODE ? 1 : 500)

            reportInsightViewed(values.insight, query, values.isFirstLoad, 0)
            actions.setNotFirstLoad()

            // Record a second view after 10 seconds.
            await breakpoint(IS_TEST_MODE ? 1 : 10000)

            reportInsightViewed(values.insight, query, values.isFirstLoad, 10)
        },
    })),
    subscriptions(({ actions }) => ({
        query: (query, oldQuery) => {
            if (objectsEqual(query, oldQuery)) {
                return
            }
            actions.onQueryChange(query, oldQuery)
        },
    })),
])