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.

5.9 KB
Raw Blame
import { MakeLogicType, actions, afterMount, beforeUnmount, connect, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'

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

import { projectLogic } from 'scenes/projectLogic'
import { urls } from 'scenes/urls'

import { streamlitAppsCreate, streamlitAppsDestroy, streamlitAppsList } from './generated/api'
import type { AppContractApi, AppSummaryContractApi } from './generated/api.schemas'

const LIST_POLL_INTERVAL_MS = 10_000

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface streamlitAppsLogicValues {
    currentProjectId: number | null // projectLogic
    streamlitApps: AppSummaryContractApi[]
    streamlitAppsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface streamlitAppsLogicActions {
    createStreamlitApp: ({ name, description }: { description?: string; name: string }) => {
        name: string
        description?: string
    }
    createStreamlitAppFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    createStreamlitAppSuccess: (
        streamlitApps: AppSummaryContractApi[],
        payload?: {
            name: string
            description?: string
        }
    ) => {
        streamlitApps: AppSummaryContractApi[]
        payload?: {
            name: string
            description?: string
        }
    }
    deleteStreamlitApp: ({ shortId }: { shortId: string }) => {
        shortId: string
    }
    deleteStreamlitAppFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteStreamlitAppSuccess: (
        streamlitApps: AppSummaryContractApi[],
        payload?: {
            shortId: string
        }
    ) => {
        streamlitApps: AppSummaryContractApi[]
        payload?: {
            shortId: string
        }
    }
    loadStreamlitApps: () => any
    loadStreamlitAppsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadStreamlitAppsSuccess: (
        streamlitApps: AppSummaryContractApi[],
        payload?: any
    ) => {
        streamlitApps: AppSummaryContractApi[]
        payload?: any
    }
    startListPolling: () => {
        value: true
    }
    stopListPolling: () => {
        value: true
    }
    updateStreamlitApp: (app: AppContractApi | AppSummaryContractApi) => {
        app: AppContractApi | AppSummaryContractApi
    }
}

export type streamlitAppsLogicType = MakeLogicType<streamlitAppsLogicValues, streamlitAppsLogicActions>

export const streamlitAppsLogic = kea<streamlitAppsLogicType>([
    path(['products', 'streamlit_apps', 'frontend', 'streamlitAppsLogic']),

    connect(() => ({
        values: [projectLogic, ['currentProjectId']],
    })),

    actions({
        updateStreamlitApp: (app: AppContractApi | AppSummaryContractApi) => ({ app }),
        startListPolling: true,
        stopListPolling: true,
    }),

    loaders(({ values }) => ({
        streamlitApps: [
            [] as AppSummaryContractApi[],
            {
                loadStreamlitApps: async () => {
                    const response = await streamlitAppsList(String(values.currentProjectId))
                    return response.results
                },
                createStreamlitApp: async ({ name, description }: { name: string; description?: string }) => {
                    const newApp = await streamlitAppsCreate(String(values.currentProjectId), { name, description })
                    lemonToast.success('App created')
                    router.actions.push(urls.streamlitAppEdit(newApp.short_id))
                    return [...values.streamlitApps, newApp]
                },
                deleteStreamlitApp: async ({ shortId }: { shortId: string }) => {
                    await streamlitAppsDestroy(String(values.currentProjectId), shortId)
                    lemonToast.success('App deleted')
                    return values.streamlitApps.filter((a) => a.short_id !== shortId)
                },
            },
        ],
    })),

    reducers({
        streamlitApps: {
            updateStreamlitApp: (state, { app }) =>
                state.map((a) => (a.short_id === app.short_id ? { ...a, ...app } : a)),
        },
    }),

    listeners(({ actions, cache }) => ({
        startListPolling: () => {
            // Idempotent — timers stack otherwise on re-fire.
            if (cache.listPollTimer) {
                clearInterval(cache.listPollTimer)
            }
            cache.listPollTimer = setInterval(() => {
                if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
                    return
                }
                actions.loadStreamlitApps()
            }, LIST_POLL_INTERVAL_MS)
        },
        stopListPolling: () => {
            if (cache.listPollTimer) {
                clearInterval(cache.listPollTimer)
                cache.listPollTimer = null
            }
        },
    })),

    afterMount(({ actions, cache }) => {
        actions.loadStreamlitApps()
        actions.startListPolling()
        // Refetch on tab focus so returning users don't sit on stale state for a poll interval.
        if (typeof document !== 'undefined') {
            cache.visibilityHandler = (): void => {
                if (document.visibilityState === 'visible') {
                    actions.loadStreamlitApps()
                }
            }
            document.addEventListener('visibilitychange', cache.visibilityHandler)
        }
    }),

    beforeUnmount(({ actions, cache }) => {
        actions.stopListPolling()
        if (typeof document !== 'undefined' && cache.visibilityHandler) {
            document.removeEventListener('visibilitychange', cache.visibilityHandler)
            cache.visibilityHandler = null
        }
    }),
])