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.

28.9 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    afterMount,
    beforeUnmount,
    kea,
    key,
    listeners,
    path,
    props,
    propsChanged,
    reducers,
    selectors,
} from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'

import { lemonToast } from '@posthog/lemon-ui'

import api from 'lib/api'
import { Dayjs, dayjs } from 'lib/dayjs'
import { HogQLQueryString, hogql } from 'lib/utils/hogql'
import { teamLogic } from 'scenes/teamLogic'

import { LogEntryLevel } from '~/types'

export const ALL_LOG_LEVELS: LogEntryLevel[] = ['DEBUG', 'LOG', 'INFO', 'WARN', 'ERROR']
export const POLLING_INTERVAL = 5000
export const LOG_VIEWER_LIMIT = 100
export const LOG_GROUP_LIMIT = 10
export const LOG_GROUP_TOTAL_LOGS_LIMIT = 5000
// Bounds cost only: a short sliced page falls back to the full GROUP BY in loadGroupedLogs.
export const LOG_GROUP_ROWS_PER_GROUP = 10000
export const LOG_GROUP_MAX_SLICE_ROWS = 1_000_000

export type LogsViewerLogicProps = {
    logicKey?: string
    sourceType: 'hog_function' | 'hog_flow' | 'batch_exports' | 'external_data_jobs' | 'data_modeling_run' | 'endpoints'
    sourceId: string
    groupByInstanceId?: boolean
    searchGroups?: string[]
    defaultFilters?: Partial<LogEntryParams>
    /**
     * Opt out of the shared `levels`, `search`, `date_from` and `date_to` URL params. Several viewers
     * can mount on one scene and the params carry no prefix, so one viewer's filter would override
     * another's `defaultFilters`.
     */
    disableUrlSync?: boolean
}

export type LogsViewerFilters = {
    levels: LogEntryLevel[]
    search: string
    date_from?: string
    date_to?: string
}

export type LogEntry = {
    message: string
    instanceId: string
    level: LogEntryLevel
    timestamp: Dayjs
    rawTimestamp: string
}

export type GroupedLogEntry = {
    instanceId: string
    maxTimestamp: Dayjs
    maxRawTimestamp: string
    minTimestamp: Dayjs
    minRawTimestamp: string
    logLevel: LogEntryLevel
    entries: LogEntry[]
}

export type LogEntryParams = {
    sourceType: LogsViewerLogicProps['sourceType']
    sourceId: string
    levels: LogEntryLevel[]
    searchGroups: string[]
    dateFrom?: string
    dateTo?: string
    order: 'ASC' | 'DESC'
    instanceId?: string
    limit?: number
}

const toKey = (log: LogEntry): string => {
    return `${log.instanceId}-${log.level}-${log.rawTimestamp}`
}

export const toAbsoluteClickhouseTimestamp = (timestamp: Dayjs): string => {
    // TRICKY: HogQL interprets bare timestamps as being in the team's timezone,
    // so we must format in the team timezone (not UTC).
    // See https://github.com/PostHog/posthog/pull/45651
    const teamTimezone = teamLogic.findMounted()?.values.currentTeam?.timezone ?? 'UTC'
    return timestamp.tz(teamTimezone).format('YYYY-MM-DD HH:mm:ss.SSS')
}

// An empty `levels` selection means "all levels" in the picker (it renders as
// "All levels"), so omit the predicate entirely. Emitting `lower(level) IN ()`
// is invalid HogQL ("empty parentheses are not a valid expression") and fails
// the whole query — which surfaced as a toast when deselecting the last level
// or paging older entries. Values come from a fixed enum, so raw is safe here.
const levelInClause = (levels: LogEntryLevel[]): string =>
    levels.length > 0 ? `AND lower(level) IN (${levels.map((level) => `'${level.toLowerCase()}'`).join(',')})` : ''

const buildBoundaryFilters = (request: LogEntryParams): string => {
    return hogql`
        AND log_source = ${request.sourceType}
        AND log_source_id = ${request.sourceId}
        AND timestamp > {filters.dateRange.from}
        AND timestamp < {filters.dateRange.to}
        ${hogql.raw(levelInClause(request.levels))}
    `
}

const buildSearchFilters = ({ searchGroups, levels, instanceId }: LogEntryParams): string => {
    let query = hogql`\n${hogql.raw(levelInClause(levels))}`

    searchGroups.forEach((search) => {
        query = (query +
            hogql`\nAND (message ILIKE concat('%', ${search}, '%') OR instance_id ILIKE concat('%', ${search}, '%'))`) as HogQLQueryString
    })

    if (instanceId) {
        query = (query + hogql`\nAND instance_id = ${instanceId}`) as HogQLQueryString
    }

    return query
}

const queryLogEntries = async (query: HogQLQueryString, request: LogEntryParams): Promise<LogEntry[]> => {
    const response = await api.queryHogQL(
        query,
        { scene: 'HogFunction', productKey: 'pipeline_destinations' },
        {
            refresh: 'force_blocking',
            filtersOverride: {
                date_from: request.dateFrom ?? '-7d',
                date_to: request.dateTo,
            },
        }
    )

    return response.results.map(
        (result): LogEntry => ({
            instanceId: result[0],
            timestamp: dayjs(result[1]),
            rawTimestamp: result[1],
            level: result[2].toUpperCase(),
            message: result[3],
        })
    )
}

const loadLogs = async (request: LogEntryParams): Promise<LogEntry[]> => {
    const query = hogql`
        SELECT instance_id, timestamp, level, message
        FROM log_entries
        WHERE 1=1
        ${hogql.raw(buildBoundaryFilters(request))}
        ${hogql.raw(buildSearchFilters(request))}
        ORDER BY timestamp ${hogql.raw(request.order)}
        LIMIT ${request.limit ?? LOG_VIEWER_LIMIT}`

    return await queryLogEntries(query, request)
}

// An instance in the newest-rows slice has its latest row there too, so the order matches the full GROUP BY
// without its per-instance state. A slice of the oldest rows can understate max(timestamp), so ASC can't.
export const groupedLogsSliceRows = (
    request: LogEntryParams,
    groupLimit: number,
    groupOffset: number
): number | null => {
    if (request.order !== 'DESC') {
        return null
    }
    const rows = (groupOffset + groupLimit) * LOG_GROUP_ROWS_PER_GROUP
    return rows <= LOG_GROUP_MAX_SLICE_ROWS ? rows : null
}

// A page cut by the line cap loses the same groups under the full GROUP BY, so only short pages retry.
export const shouldRetryGroupedLogsWithoutSlice = (entries: LogEntry[], groupLimit: number): boolean => {
    if (entries.length >= LOG_GROUP_TOTAL_LOGS_LIMIT) {
        return false
    }
    return new Set(entries.map((entry) => entry.instanceId)).size < groupLimit
}

// Grouped pagination keyset-pages over instance groups by offsetting the group subquery, ordered by
// most recent activity. We deliberately do NOT paginate with a `timestamp < cursor` boundary: batch
// workflows emit hundreds of instances within the same millisecond, so a timestamp cursor (truncated
// to ms) excludes every remaining group at once and the viewer falsely reports "No older entries".
// The instance_id tiebreaker keeps the ordering stable across pages.
export const buildGroupedLogsQuery = (
    request: LogEntryParams,
    groupLimit: number,
    groupOffset: number = 0,
    sliceRows: number | null = groupedLogsSliceRows(request, groupLimit, groupOffset)
): HogQLQueryString => {
    const groupSource =
        sliceRows !== null
            ? hogql`(
                SELECT instance_id, timestamp
                FROM log_entries
                WHERE 1=1
                ${hogql.raw(buildBoundaryFilters(request))}
                ${hogql.raw(buildSearchFilters(request))}
                ORDER BY timestamp DESC
                LIMIT ${sliceRows}
            )`
            : hogql`log_entries
            WHERE 1=1
            ${hogql.raw(buildBoundaryFilters(request))}
            ${hogql.raw(buildSearchFilters(request))}`

    return hogql`
        SELECT instance_id, timestamp, level, message
        FROM log_entries
        WHERE 1=1
        ${hogql.raw(buildBoundaryFilters(request))}
        AND instance_id in (
            SELECT instance_id
            FROM ${hogql.raw(groupSource)}
            GROUP BY instance_id
            ORDER BY max(timestamp) ${hogql.raw(request.order)}, instance_id DESC
            LIMIT ${groupLimit}
            OFFSET ${groupOffset}
        )
        ORDER BY timestamp DESC
        LIMIT ${LOG_GROUP_TOTAL_LOGS_LIMIT}`
}

const loadGroupedLogs = async (
    request: LogEntryParams,
    groupLimit: number = LOG_GROUP_LIMIT,
    groupOffset: number = 0
): Promise<LogEntry[]> => {
    const run = (sliceRows: number | null): Promise<LogEntry[]> =>
        queryLogEntries(buildGroupedLogsQuery(request, groupLimit, groupOffset, sliceRows), request)

    const sliceRows = groupedLogsSliceRows(request, groupLimit, groupOffset)
    const entries = await run(sliceRows)
    if (sliceRows !== null && shouldRetryGroupedLogsWithoutSlice(entries, groupLimit)) {
        return await run(null)
    }
    return entries
}

export const groupLogs = (logs: LogEntry[]): GroupedLogEntry[] => {
    const sorted = [...logs].sort((a, b) =>
        a.rawTimestamp < b.rawTimestamp ? -1 : a.rawTimestamp > b.rawTimestamp ? 1 : 0
    )

    const byId: Record<string, GroupedLogEntry> = {}
    const dedupeCache = new Set<string>()

    for (const log of sorted) {
        const key = toKey(log)
        if (dedupeCache.has(key)) {
            continue
        }
        dedupeCache.add(key)
        const group = (byId[log.instanceId] ??= {
            instanceId: log.instanceId,
            maxTimestamp: log.timestamp,
            maxRawTimestamp: log.rawTimestamp,
            minTimestamp: log.timestamp,
            minRawTimestamp: log.rawTimestamp,
            logLevel: log.level,
            entries: [],
        })
        group.entries.push(log)
        // Since logs are sorted ascending, the last entry always has the max timestamp
        group.maxTimestamp = log.timestamp
        group.maxRawTimestamp = log.rawTimestamp
        group.logLevel = log.level
    }

    return Object.values(byId).reverse()
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsViewerLogicValues {
    allLogEntries: LogEntry[]
    allLogEntryKeys: Set<string>
    expandedRows: Record<string, boolean>
    filters: LogsViewerFilters
    groupedLogs: GroupedLogEntry[]
    groupedLogsLoading: boolean
    hiddenLogs: LogEntry[]
    hiddenLogsLoading: boolean
    isGrouped: boolean
    isThereMoreToLoad: boolean
    logEntryParams: LogEntryParams
    logsLoading: boolean
    newestLogTimestamp: Dayjs | null
    oldestLogTimestamp: Dayjs | null
    unGroupedLogs: LogEntry[]
    unGroupedLogsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsViewerLogicActions {
    addLogGroups: (logGroups: GroupedLogEntry[]) => {
        logGroups: GroupedLogEntry[]
    }
    addLogGroupsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    addLogGroupsSuccess: (
        groupedLogs: GroupedLogEntry[],
        payload?: {
            logGroups: GroupedLogEntry[]
        }
    ) => {
        groupedLogs: GroupedLogEntry[]
        payload?: {
            logGroups: GroupedLogEntry[]
        }
    }
    clearHiddenLogs: () => {
        value: true
    }
    clearHiddenLogsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    clearHiddenLogsSuccess: (
        hiddenLogs: never[],
        payload?: {
            value: true
        }
    ) => {
        hiddenLogs: never[]
        payload?: {
            value: true
        }
    }
    clearLogs: () => {
        value: true
    }
    loadGroupedLogs: () => {
        value: true
    }
    loadGroupedLogsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadGroupedLogsSuccess: (
        groupedLogs: GroupedLogEntry[],
        payload?: {
            value: true
        }
    ) => {
        groupedLogs: GroupedLogEntry[]
        payload?: {
            value: true
        }
    }
    loadLogs: () => {
        value: true
    }
    loadMoreGroupedLogs: () => any
    loadMoreGroupedLogsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadMoreGroupedLogsSuccess: (
        groupedLogs: GroupedLogEntry[],
        payload?: any
    ) => {
        groupedLogs: GroupedLogEntry[]
        payload?: any
    }
    loadMoreUngroupedLogs: () => any
    loadMoreUngroupedLogsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadMoreUngroupedLogsSuccess: (
        unGroupedLogs: LogEntry[],
        payload?: any
    ) => {
        unGroupedLogs: LogEntry[]
        payload?: any
    }
    loadNewerLogs: () => {
        value: true
    }
    loadNewerLogsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadNewerLogsSuccess: (
        hiddenLogs: LogEntry[],
        payload?: {
            value: true
        }
    ) => {
        hiddenLogs: LogEntry[]
        payload?: {
            value: true
        }
    }
    loadOlderLogs: () => {
        value: true
    }
    loadUngroupedLogs: () => {
        value: true
    }
    loadUngroupedLogsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadUngroupedLogsSuccess: (
        unGroupedLogs: LogEntry[],
        payload?: {
            value: true
        }
    ) => {
        unGroupedLogs: LogEntry[]
        payload?: {
            value: true
        }
    }
    markLogsEnd: () => {
        value: true
    }
    revealHiddenLogs: () => {
        value: true
    }
    scheduleLoadNewerLogs: () => {
        value: true
    }
    setFilters: (filters: Partial<LogsViewerFilters>) => {
        filters: Partial<LogsViewerFilters>
    }
    setIsGrouped: (isGrouped: boolean) => {
        isGrouped: boolean
    }
    setRowExpanded: (
        instanceId: string,
        expanded: boolean
    ) => {
        expanded: boolean
        instanceId: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsViewerLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        logsLoading: (groupedLogsLoading: boolean, unGroupedLogsLoading: boolean) => boolean
        logEntryParams: (arg: any, filters: LogsViewerFilters) => LogEntryParams
        allLogEntries: (groupedLogs: GroupedLogEntry[], unGroupedLogs: LogEntry[], hiddenLogs: LogEntry[]) => LogEntry[]
        allLogEntryKeys: (allLogEntries: LogEntry[]) => Set<string>
        newestLogTimestamp: (allLogEntries: LogEntry[]) => Dayjs | null
        oldestLogTimestamp: (allLogEntries: LogEntry[]) => Dayjs | null
    }
}

export type logsViewerLogicType = MakeLogicType<
    logsViewerLogicValues,
    logsViewerLogicActions,
    LogsViewerLogicProps,
    logsViewerLogicMeta
>

export const logsViewerLogic = kea<logsViewerLogicType>([
    path((key) => ['scenes', 'pipeline', 'hogfunctions', 'logs', 'logsViewerLogic', key]),
    props({} as LogsViewerLogicProps), // TODO: Remove `stage` from props, it isn't needed here for anything
    key(({ sourceType, sourceId, logicKey }) => logicKey || `${sourceType}:${sourceId}`),
    actions({
        setFilters: (filters: Partial<LogsViewerFilters>) => ({ filters }),
        addLogGroups: (logGroups: GroupedLogEntry[]) => ({ logGroups }),
        clearHiddenLogs: true,
        markLogsEnd: true,
        revealHiddenLogs: true,
        setRowExpanded: (instanceId: string, expanded: boolean) => ({ instanceId, expanded }),
        scheduleLoadNewerLogs: true,
        loadLogs: true,
        loadNewerLogs: true,
        loadOlderLogs: true,
        clearLogs: true,
        loadGroupedLogs: true,
        loadUngroupedLogs: true,
        setIsGrouped: (isGrouped: boolean) => ({ isGrouped }),
    }),
    reducers(({ props }) => ({
        isGrouped: [
            props.groupByInstanceId ?? true,
            {
                setIsGrouped: (_, { isGrouped }) => isGrouped,
            },
        ],
        filters: [
            {
                search: '',
                levels: props.defaultFilters?.levels ?? ALL_LOG_LEVELS,
                date_from: props.defaultFilters?.dateFrom ?? '-7d',
                date_to: props.defaultFilters?.dateTo,
            } as LogsViewerFilters,
            {
                setFilters: (state, { filters }) => ({
                    ...state,
                    ...filters,
                }),
            },
        ],
        isThereMoreToLoad: [
            true,
            {
                markLogsEnd: () => false,
                loadLogs: () => true,
            },
        ],
        expandedRows: [
            {} as Record<string, boolean>,
            {
                setRowExpanded: (state, { instanceId, expanded }) => ({
                    ...state,
                    [instanceId]: expanded,
                }),
            },
        ],

        unGroupedLogs: [
            [] as LogEntry[],
            {
                clearLogs: () => [],
            },
        ],
        groupedLogs: [
            [] as GroupedLogEntry[],
            {
                clearLogs: () => [],
            },
        ],
    })),
    loaders(({ values, actions }) => ({
        unGroupedLogs: [
            [] as LogEntry[],
            {
                loadUngroupedLogs: async (_, breakpoint) => {
                    await breakpoint(10)
                    actions.clearHiddenLogs()
                    const results = await loadLogs(values.logEntryParams)
                    await breakpoint(10)
                    return results
                },
                loadMoreUngroupedLogs: async () => {
                    if (!values.oldestLogTimestamp) {
                        return values.unGroupedLogs
                    }
                    const logParams: LogEntryParams = {
                        ...values.logEntryParams,
                        dateTo: toAbsoluteClickhouseTimestamp(values.oldestLogTimestamp),
                        limit: values.unGroupedLogs.length + LOG_VIEWER_LIMIT,
                    }

                    const results = await loadLogs(logParams)

                    if (!results.length) {
                        actions.markLogsEnd()
                    }

                    const newLogs = results.filter((log) => !values.allLogEntryKeys.has(toKey(log)))
                    return [...newLogs, ...values.unGroupedLogs].sort((a, b) => b.timestamp.diff(a.timestamp))
                },
            },
        ],
        groupedLogs: [
            [] as GroupedLogEntry[],
            {
                loadGroupedLogs: async (_, breakpoint) => {
                    await breakpoint(10)

                    actions.clearHiddenLogs()
                    const results = await loadGroupedLogs(values.logEntryParams).catch((e) => {
                        lemonToast.error('Error loading logs ' + e.message)
                        throw e
                    })
                    await breakpoint(10)

                    return groupLogs(results)
                },
                loadMoreGroupedLogs: async () => {
                    const results = await loadGroupedLogs(
                        values.logEntryParams,
                        LOG_GROUP_LIMIT,
                        values.groupedLogs.length
                    )

                    if (!results.length) {
                        actions.markLogsEnd()
                    }
                    return groupLogs([...values.groupedLogs.flatMap((group) => group.entries), ...results])
                },

                addLogGroups: ({ logGroups }) => {
                    return groupLogs([
                        ...logGroups.flatMap((group) => group.entries),
                        ...values.groupedLogs.flatMap((group) => group.entries),
                    ])
                },
            },
        ],

        hiddenLogs: [
            [] as LogEntry[],
            {
                loadNewerLogs: async (_, breakpoint) => {
                    await breakpoint(10)

                    // We load all logs groups that have a timestamp after the newest log timestamp
                    // For ones we already have we just replace them, otherwise we add them to the "hidden" logs list
                    if (!values.newestLogTimestamp) {
                        return values.hiddenLogs
                    }

                    const logParams: LogEntryParams = {
                        ...values.logEntryParams,
                        dateFrom: toAbsoluteClickhouseTimestamp(values.newestLogTimestamp),
                        order: 'ASC',
                    }

                    let newLogs: LogEntry[] = []

                    if (values.isGrouped) {
                        const results = await loadGroupedLogs(logParams)

                        await breakpoint(10)

                        const newLogs: LogEntry[] = []
                        const newLogsToImmediateAdd: LogEntry[] = []
                        const existingLogIds = values.groupedLogs.map((log) => log.instanceId)

                        if (values.logsLoading) {
                            // TRICKY: Something changed whilst we were doing this query - we don't want to mess with things
                            // so we just exit
                            return values.hiddenLogs
                        }

                        for (const log of results) {
                            if (existingLogIds.includes(log.instanceId)) {
                                // If we already have this log group showing then we can just update it
                                newLogsToImmediateAdd.push(log)
                            } else {
                                // Otherwise we add it to the list of hidden logs
                                newLogs.push(log)
                            }
                        }

                        if (newLogsToImmediateAdd.length) {
                            // Update the existing logs with the new data
                            actions.loadGroupedLogsSuccess(
                                groupLogs([
                                    ...newLogsToImmediateAdd,
                                    ...values.groupedLogs.flatMap((group) => group.entries),
                                ])
                            )
                        }
                    } else {
                        const results = await loadLogs(logParams)
                        await breakpoint(10)
                        newLogs = results
                    }

                    actions.scheduleLoadNewerLogs()

                    // Filter out any duplicates as the time ranges are never perfectly accurate
                    newLogs = newLogs.filter((log) => !values.allLogEntryKeys.has(toKey(log)))

                    return [...newLogs, ...values.hiddenLogs]
                },
                clearHiddenLogs: () => [],
            },
        ],
    })),
    selectors(() => ({
        logsLoading: [
            (s) => [s.groupedLogsLoading, s.unGroupedLogsLoading],
            (groupedLogsLoading: boolean, unGroupedLogsLoading: boolean): boolean => {
                return groupedLogsLoading || unGroupedLogsLoading
            },
        ],
        logEntryParams: [
            (s) => [(_, p) => p, s.filters],
            (props, filters: LogsViewerFilters): LogEntryParams => {
                const searchGroups = [filters.search, ...(props.searchGroups || [])].filter((x) => !!x) as string[]
                return {
                    ...props.defaultFilters,
                    levels: filters.levels,
                    searchGroups: searchGroups,
                    sourceType: props.sourceType,
                    sourceId: props.sourceId,
                    dateFrom: filters.date_from,
                    dateTo: filters.date_to,
                    order: 'DESC',
                }
            },
        ],

        allLogEntries: [
            (s) => [s.groupedLogs, s.unGroupedLogs, s.hiddenLogs],
            (groupedLogs: GroupedLogEntry[], unGroupedLogs: LogEntry[], hiddenLogs: LogEntry[]): LogEntry[] => {
                return [...groupedLogs.flatMap((log) => log.entries), ...unGroupedLogs, ...hiddenLogs]
            },
        ],

        allLogEntryKeys: [
            (s) => [s.allLogEntries],
            (allLogEntries: LogEntry[]): Set<string> => {
                return new Set(allLogEntries.map(toKey))
            },
        ],

        newestLogTimestamp: [
            (s) => [s.allLogEntries],
            (allLogEntries: LogEntry[]): Dayjs | null => {
                const item = allLogEntries.reduce(
                    (max, log) => {
                        if (!max) {
                            return log.timestamp
                        }
                        return log.timestamp.isAfter(max) ? log.timestamp : max
                    },
                    null as Dayjs | null
                )

                return item ? item.tz(teamLogic.findMounted()?.values.currentTeam?.timezone) : null
            },
        ],

        oldestLogTimestamp: [
            (s) => [s.allLogEntries],
            (allLogEntries: LogEntry[]): Dayjs | null => {
                return allLogEntries.reduce(
                    (min, log) => {
                        if (!min) {
                            return log.timestamp
                        }
                        return log.timestamp.isBefore(min) ? log.timestamp : min
                    },
                    null as Dayjs | null
                )
            },
        ],
    })),
    propsChanged(({ props, actions }, oldProps) => {
        if (props.groupByInstanceId !== oldProps.groupByInstanceId) {
            actions.setIsGrouped(props.groupByInstanceId ?? true)
        }
    }),
    listeners(({ actions, cache, values }) => ({
        loadLogs: () => {
            if (values.isGrouped) {
                actions.loadGroupedLogs()
            } else {
                actions.loadUngroupedLogs()
            }
        },
        loadOlderLogs: () => {
            if (values.isGrouped) {
                actions.loadMoreGroupedLogs()
            } else {
                actions.loadMoreUngroupedLogs()
            }
        },
        setFilters: async ({ filters }, breakpoint) => {
            await breakpoint(filters.search ? 500 : 10) // Longer debounce when typing in the search field
            actions.loadLogs()
        },
        setIsGrouped: async () => {
            actions.clearLogs()
            actions.loadLogs()
        },
        loadGroupedLogsSuccess: () => actions.scheduleLoadNewerLogs(),
        loadUngroupedLogsSuccess: () => actions.scheduleLoadNewerLogs(),
        scheduleLoadNewerLogs: () => {
            cache.disposables.add(() => {
                const timeoutId = setTimeout(() => actions.loadNewerLogs(), POLLING_INTERVAL)
                return () => clearTimeout(timeoutId)
            }, 'pollingTimeout')
        },

        revealHiddenLogs: () => {
            if (!values.hiddenLogs.length) {
                return
            }

            if (values.isGrouped) {
                actions.loadMoreGroupedLogsSuccess(
                    groupLogs([...values.hiddenLogs, ...values.groupedLogs.flatMap((group) => group.entries)])
                )
            } else {
                actions.loadMoreUngroupedLogsSuccess(
                    [...values.unGroupedLogs, ...values.hiddenLogs].sort((a, b) => b.timestamp.diff(a.timestamp))
                )
            }

            actions.clearHiddenLogs()
        },
    })),
    afterMount(({ actions }) => {
        actions.loadLogs()
    }),
    beforeUnmount(() => {
        // Disposables handle cleanup automatically
    }),
    actionToUrl(({ values, props }) => {
        if (props.disableUrlSync) {
            return {}
        }
        const syncProperties = (
            properties: Record<string, any>
        ): [string, Record<string, any>, Record<string, any>] => {
            const newSearch = { ...router.values.searchParams, ...properties }
            Object.keys(properties).forEach((key) => {
                if (properties[key] === null || properties[key] === undefined) {
                    delete newSearch[key]
                }
            })
            return [router.values.location.pathname, newSearch, router.values.hashParams]
        }

        return {
            setFilters: ({ filters }) => syncProperties(filters),
            setIsGrouped: () => syncProperties({ grouped: values.isGrouped }),
        }
    }),
    urlToAction(({ actions, values, props }) => {
        const reactToTabChange = (_: any, search: Record<string, any>): void => {
            if (props.disableUrlSync) {
                return
            }
            Object.keys(search).forEach((key) => {
                if (key in values.filters && search[key] !== values.filters[key as keyof LogsViewerFilters]) {
                    actions.setFilters({ [key]: search[key] })
                }
            })

            if (typeof search.grouped === 'boolean' && search.grouped !== values.isGrouped) {
                actions.setIsGrouped(search.grouped)
            }
        }

        return {
            '*': reactToTabChange,
        }
    }),
])