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, events, kea, key, path, props, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import api from 'lib/api'
import {
    ActivityChange,
    ActivityLogItem,
    actorEmailForLogItem,
    userNameForLogItem,
} from 'lib/components/ActivityLog/humanizeActivity'

import { ActivityScope } from '~/types'

export interface InsightHistoryLogicProps {
    insightId: number
}

/** One saved state of the insight's query: the result of a single edit. */
export interface InsightQueryVersion {
    id?: string
    createdAt: string
    authorName: string
    email?: string | null
    isSystem: boolean
    /** SQL before this edit — the previous version, used as the diff base */
    beforeSql: string
    /** SQL as of this edit — what "Restore" brings back */
    afterSql: string
}

/** Pull the HogQL text out of an insight `query` field activity change (a DataVisualizationNode). */
export function getChangeSql(changeSide: ActivityChange['before'] | ActivityChange['after']): string | null {
    if (!changeSide || typeof changeSide !== 'object' || Array.isArray(changeSide)) {
        return null
    }
    const source = (changeSide as { source?: unknown }).source
    if (!source || typeof source !== 'object') {
        return null
    }
    const query = (source as { query?: unknown }).query
    return typeof query === 'string' && query.trim() !== '' ? query : null
}

export function getQueryChange(logItem: ActivityLogItem): ActivityChange | null {
    return (
        logItem.detail?.changes?.find(
            (change) =>
                change.field === 'query' &&
                getChangeSql(change.after) !== null &&
                // Settings-only edits (chart type, axis config) also touch the query JSON —
                // only SQL text changes count as versions, otherwise the diff has nothing to show
                getChangeSql(change.after) !== getChangeSql(change.before)
        ) ?? null
    )
}

const ACTIVITY_PAGE_SIZE = 100
// Safety cap: 10 pages = 1000 activity entries. Beyond that we stop and admit the history is partial.
const ACTIVITY_MAX_PAGES = 10

export interface InsightActivityPage {
    items: ActivityLogItem[]
    /** False when the log was too long to fetch fully — the oldest loaded entry is NOT the creation state */
    complete: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface insightHistoryLogicValues {
    activity: ActivityLogItem[]
    activityPage: InsightActivityPage
    activityPageLoading: boolean
    historyComplete: boolean
    versions: InsightQueryVersion[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface insightHistoryLogicActions {
    loadActivity: () => any
    loadActivityFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadActivitySuccess: (
        activityPage:
            | {
                  complete: false
                  items: ActivityLogItem[]
              }
            | {
                  complete: true
                  items: ActivityLogItem[]
              },
        payload?: any
    ) => {
        activityPage:
            | {
                  complete: false
                  items: ActivityLogItem[]
              }
            | {
                  complete: true
                  items: ActivityLogItem[]
              }
        payload?: any
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface insightHistoryLogicMeta {
    key: number
    __keaTypeGenInternalSelectorTypes: {
        activity: (activityPage: InsightActivityPage) => ActivityLogItem[]
        historyComplete: (activityPage: InsightActivityPage) => boolean
        versions: (activity: ActivityLogItem[]) => InsightQueryVersion[]
    }
}

export type insightHistoryLogicType = MakeLogicType<
    insightHistoryLogicValues,
    insightHistoryLogicActions,
    InsightHistoryLogicProps,
    insightHistoryLogicMeta
>

export const insightHistoryLogic = kea<insightHistoryLogicType>([
    path(['data-warehouse', 'editor', 'insightHistoryLogic']),
    props({} as InsightHistoryLogicProps),
    key((props) => props.insightId),
    loaders(({ props }) => ({
        activityPage: [
            { items: [], complete: true } as InsightActivityPage,
            {
                loadActivity: async () => {
                    const items: ActivityLogItem[] = []
                    for (let page = 1; page <= ACTIVITY_MAX_PAGES; page++) {
                        const response = await api.activity
                            .listRequest({
                                scope: ActivityScope.INSIGHT,
                                item_id: props.insightId,
                                page,
                                page_size: ACTIVITY_PAGE_SIZE,
                            })
                            .get()
                        items.push(...(response.results ?? []))
                        // `next` is null on the last page — unlike a results-length check, this stays
                        // correct when the total is an exact multiple of the page size
                        if (!response.next) {
                            return { items, complete: true }
                        }
                    }
                    return { items, complete: false }
                },
            },
        ],
    })),
    selectors({
        activity: [(s) => [s.activityPage], (activityPage: InsightActivityPage) => activityPage.items],
        historyComplete: [(s) => [s.activityPage], (activityPage: InsightActivityPage) => activityPage.complete],
        // Newest first, only edits that changed the SQL — each one is a "version"
        versions: [
            (s) => [s.activity],
            (activity: ActivityLogItem[]): InsightQueryVersion[] =>
                activity
                    .map((logItem): InsightQueryVersion | null => {
                        const queryChange = getQueryChange(logItem)
                        if (!queryChange) {
                            return null
                        }
                        return {
                            id: logItem.id,
                            createdAt: logItem.created_at,
                            authorName: userNameForLogItem(logItem),
                            email: actorEmailForLogItem(logItem) ?? undefined,
                            isSystem: !!logItem.is_system,
                            beforeSql: getChangeSql(queryChange.before) ?? '',
                            afterSql: getChangeSql(queryChange.after) ?? '',
                        }
                    })
                    .filter((version): version is InsightQueryVersion => version !== null),
        ],
    }),
    events(({ actions }) => ({
        afterMount: () => {
            actions.loadActivity()
        },
    })),
])