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.

9.3 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'

import { incidentStatusLogic } from 'lib/components/HelpMenu/incidentStatusLogic'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic, getFeatureFlagPayload } from 'lib/logic/featureFlagLogic'

import type { ComponentIncidentAlert } from '../../lib/components/HelpMenu/incidentStatusLogic'
import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'

export interface ChangelogEntry {
    title: string
    description: string
    tag?: 'new' | 'improved' | 'beta'
}

export interface AlertEntry {
    title: string
    description: string
    severity: 'warning' | 'error'
}

interface ChangelogPayload {
    entries: ChangelogEntry[]
}

const CHANGELOG_STORAGE_KEY = 'posthog_ai_changelog_last_seen'
const CHANGELOG_DISMISSED_KEY = 'posthog_ai_changelog_dismissed'

function generateEntriesHash(entries: ChangelogEntry[]): string {
    const content = entries.map((e) => `${e.title}|${e.description}|${e.tag || ''}`).join('::')
    let hash = 0
    for (let i = 0; i < content.length; i++) {
        const char = content.charCodeAt(i)
        hash = (hash << 5) - hash + char
        hash = hash & hash
    }
    return Math.abs(hash).toString(36)
}

function parseChangelogPayload(payload: unknown): ChangelogEntry[] {
    if (!payload || typeof payload !== 'object') {
        return []
    }
    const typedPayload = payload as ChangelogPayload
    if (!Array.isArray(typedPayload.entries)) {
        return []
    }
    return typedPayload.entries.filter(
        (entry): entry is ChangelogEntry =>
            typeof entry === 'object' &&
            entry !== null &&
            typeof entry.title === 'string' &&
            typeof entry.description === 'string'
    )
}

function getLastSeenHashFromStorage(): string | null {
    try {
        return localStorage.getItem(CHANGELOG_STORAGE_KEY)
    } catch {
        return null
    }
}

function setLastSeenHashToStorage(hash: string): void {
    try {
        localStorage.setItem(CHANGELOG_STORAGE_KEY, hash)
    } catch {
        // Ignore storage errors
    }
}

function isDismissedInStorage(hash: string): boolean {
    try {
        const dismissedHash = localStorage.getItem(CHANGELOG_DISMISSED_KEY)
        return dismissedHash === hash
    } catch {
        return false
    }
}

function setDismissedInStorage(hash: string): void {
    try {
        localStorage.setItem(CHANGELOG_DISMISSED_KEY, hash)
    } catch {
        // Ignore storage errors
    }
}

function clearDismissedFromStorage(): void {
    try {
        localStorage.removeItem(CHANGELOG_DISMISSED_KEY)
    } catch {
        // Ignore storage errors
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface maxChangelogLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    aiIncidentAlerts: ComponentIncidentAlert[] // incidentStatusLogic
    alerts: AlertEntry[]
    entries: ChangelogEntry[]
    entriesHash: string | null
    entriesOverride: ChangelogEntry[] | null
    hasAlerts: boolean
    hasEntries: boolean
    hasUnread: boolean
    isDismissed: boolean
    isDismissedOverride: boolean | null
    isOpen: boolean
    isVisible: boolean
    lastSeenHash: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface maxChangelogLogicActions {
    closeChangelog: () => {
        value: true
    }
    dismissChangelog: () => {
        value: true
    }
    enableChangelog: () => {
        value: true
    }
    openChangelog: () => {
        value: true
    }
    setEntries: (entries: ChangelogEntry[]) => {
        entries: ChangelogEntry[]
    }
    setIsDismissed: (isDismissed: boolean) => {
        isDismissed: boolean
    }
    setLastSeenHash: (hash: string | null) => {
        hash: string | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface maxChangelogLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        entries: (entriesOverride: ChangelogEntry[] | null, featureFlags: FeatureFlagsSet) => ChangelogEntry[]
        alerts: (aiIncidentAlerts: ComponentIncidentAlert[]) => AlertEntry[]
        entriesHash: (entries: ChangelogEntry[]) => string | null
        hasEntries: (entries: ChangelogEntry[]) => boolean
        hasAlerts: (alerts: AlertEntry[]) => boolean
        hasUnread: (entriesHash: string | null, lastSeenHash: string | null) => boolean
        isDismissed: (isDismissedOverride: boolean | null, entriesHash: string | null) => boolean
        isVisible: (hasEntries: boolean, hasAlerts: boolean, isDismissed: boolean, isOpen: boolean) => boolean
    }
}

export type maxChangelogLogicType = MakeLogicType<
    maxChangelogLogicValues,
    maxChangelogLogicActions,
    Record<string, any>,
    maxChangelogLogicMeta
>

export const maxChangelogLogic = kea<maxChangelogLogicType>([
    path(['scenes', 'max', 'maxChangelogLogic']),

    connect(() => ({
        values: [featureFlagLogic, ['featureFlags'], incidentStatusLogic, ['aiIncidentAlerts']],
    })),

    actions({
        openChangelog: true,
        closeChangelog: true,
        dismissChangelog: true,
        enableChangelog: true,
        setLastSeenHash: (hash: string | null) => ({ hash }),
        setIsDismissed: (isDismissed: boolean) => ({ isDismissed }),
        // For testing/storybook only
        setEntries: (entries: ChangelogEntry[]) => ({ entries }),
    }),

    reducers({
        // Override entries for testing - null means use feature flag payload
        entriesOverride: [
            null as ChangelogEntry[] | null,
            {
                setEntries: (_, { entries }) => entries,
            },
        ],
        isOpen: [
            false,
            {
                openChangelog: () => true,
                closeChangelog: () => false,
                dismissChangelog: () => false,
            },
        ],
        lastSeenHash: [
            getLastSeenHashFromStorage(),
            {
                setLastSeenHash: (_, { hash }) => hash,
            },
        ],
        isDismissedOverride: [
            null as boolean | null,
            {
                setIsDismissed: (_, { isDismissed }) => isDismissed,
                // When entries are set for testing, reset dismissed state
                setEntries: () => false,
            },
        ],
    }),

    selectors({
        // Derive entries from feature flag payload, with override for testing
        entries: [
            (s) => [s.entriesOverride, s.featureFlags],
            (
                entriesOverride: ChangelogEntry[] | null,
                featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet
            ): ChangelogEntry[] => {
                if (entriesOverride !== null) {
                    return entriesOverride
                }
                // featureFlags dependency ensures this re-runs when flags load
                if (!featureFlags) {
                    return []
                }
                const payload = getFeatureFlagPayload(FEATURE_FLAGS.POSTHOG_AI_CHANGELOG)
                return parseChangelogPayload(payload)
            },
        ],
        // Derive alerts from ongoing incident.io incidents tagged to PostHog AI
        alerts: [
            (s) => [s.aiIncidentAlerts],
            (
                aiIncidentAlerts: import('lib/components/HelpMenu/incidentStatusLogic').ComponentIncidentAlert[]
            ): AlertEntry[] => aiIncidentAlerts,
        ],
        entriesHash: [
            (s) => [s.entries],
            (entries: ChangelogEntry[]): string | null => (entries.length > 0 ? generateEntriesHash(entries) : null),
        ],
        hasEntries: [(s) => [s.entries], (entries: ChangelogEntry[]): boolean => entries.length > 0],
        hasAlerts: [(s) => [s.alerts], (alerts: AlertEntry[]): boolean => alerts.length > 0],
        hasUnread: [
            (s) => [s.entriesHash, s.lastSeenHash],
            (entriesHash: string | null, lastSeenHash: string | null): boolean =>
                !!entriesHash && entriesHash !== lastSeenHash,
        ],
        isDismissed: [
            (s) => [s.isDismissedOverride, s.entriesHash],
            (isDismissedOverride: boolean | null, entriesHash: string | null): boolean => {
                if (isDismissedOverride !== null) {
                    return isDismissedOverride
                }
                return entriesHash ? isDismissedInStorage(entriesHash) : true
            },
        ],
        isVisible: [
            (s) => [s.hasEntries, s.hasAlerts, s.isDismissed, s.isOpen],
            (hasEntries: boolean, hasAlerts: boolean, isDismissed: boolean, isOpen: boolean): boolean =>
                hasAlerts || (hasEntries && (!isDismissed || isOpen)),
        ],
    }),

    listeners(({ actions, values }) => ({
        openChangelog: () => {
            if (values.entriesHash) {
                setLastSeenHashToStorage(values.entriesHash)
                actions.setLastSeenHash(values.entriesHash)
            }
        },
        dismissChangelog: () => {
            if (values.entriesHash) {
                setDismissedInStorage(values.entriesHash)
            }
            actions.setIsDismissed(true)
        },
        enableChangelog: () => {
            clearDismissedFromStorage()
            actions.setIsDismissed(false)
        },
    })),
])