: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
import api from 'lib/api'
import { sceneRenderedLogic } from 'lib/logic/sceneRenderedLogic'
import { teamLogic } from 'scenes/teamLogic'
import type { TeamPublicType, TeamType } from '../../../frontend/src/types'
import { browserNotificationLogic } from './browserNotificationLogic'
const POLL_INTERVAL = 5 * 1000 // 5 seconds - backend is cached so frequent polling is cheap
export interface UnreadCountResponse {
count: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface supportTicketCounterLogicValues {
canShowNotifications: boolean // browserNotificationLogic
sceneHasRendered: boolean // sceneRenderedLogic
currentTeam: TeamPublicType | TeamType | null // teamLogic
errorCounter: number
isSupportEnabled: boolean
unreadCount: number
unreadCountLoading: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface supportTicketCounterLogicActions {
showNotification: (count: number) => {
count: number
} // browserNotificationLogic
sceneRendered: () => {
value: true
} // sceneRenderedLogic
clearErrorCount: () => {
value: true
}
incrementErrorCount: () => {
value: true
}
loadUnreadCount: () => {
value: true
}
loadUnreadCountFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadUnreadCountSuccess: (
unreadCount: number,
payload?: {
value: true
}
) => {
unreadCount: number
payload?: {
value: true
}
}
refreshCount: () => {
value: true
}
resetCount: () => {
value: true
}
resetCountFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
resetCountSuccess: (
unreadCount: number,
payload?: {
value: true
}
) => {
unreadCount: number
payload?: {
value: true
}
}
schedulePoll: () => {
value: true
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface supportTicketCounterLogicMeta {
__keaTypeGenInternalSelectorTypes: {
isSupportEnabled: (currentTeam: TeamPublicType | TeamType | null) => boolean
}
}
export type supportTicketCounterLogicType = MakeLogicType<
supportTicketCounterLogicValues,
supportTicketCounterLogicActions,
Record<string, any>,
supportTicketCounterLogicMeta
>
export const supportTicketCounterLogic = kea<supportTicketCounterLogicType>([
path(['products', 'conversations', 'frontend', 'supportTicketCounterLogic']),
connect(() => ({
values: [
teamLogic,
['currentTeam'],
browserNotificationLogic,
['canShowNotifications'],
sceneRenderedLogic,
['sceneHasRendered'],
],
actions: [browserNotificationLogic, ['showNotification'], sceneRenderedLogic, ['sceneRendered']],
})),
actions({
incrementErrorCount: true,
clearErrorCount: true,
resetCount: true, // Reset count when team changes or user logs out
refreshCount: true, // Public action for other logics to trigger immediate refresh
loadUnreadCount: true, // Explicit parameterless action (loader will use this)
schedulePoll: true, // Re-schedule the next poll via disposables
}),
reducers({
errorCounter: [
0,
{
incrementErrorCount: (state) => (state >= 5 ? 5 : state + 1),
clearErrorCount: () => 0,
resetCount: () => 0,
},
],
}),
loaders(({ actions, values }) => ({
unreadCount: [
0,
{
loadUnreadCount: async (_, breakpoint) => {
if (!values.isSupportEnabled) {
return 0
}
await breakpoint(1)
try {
const response = await api.conversationsTickets.unreadCount()
actions.clearErrorCount()
return response.count
} catch {
// Swallow errors - increment counter for backoff
actions.incrementErrorCount()
return values.unreadCount // Keep previous value on error
}
},
resetCount: () => 0, // Immediately set count to 0 on team change/logout
},
],
})),
selectors({
isSupportEnabled: [
(s) => [s.currentTeam],
(currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType): boolean =>
!!currentTeam?.conversations_enabled,
],
}),
listeners(({ actions, values, cache }) => ({
// The count shows only as a badge, so its first request waits for the scene's own requests.
sceneRendered: () => {
if (values.isSupportEnabled) {
actions.loadUnreadCount()
}
},
// Re-schedule after each load completes. The loader catches API errors
// and returns a value, so the failure action never actually dispatches —
// a single success listener covers both the happy path and the swallowed
// error path. The disposables plugin auto-pauses the scheduled timer
// when the tab is hidden and resumes it when visible.
loadUnreadCountSuccess: () => actions.schedulePoll(),
schedulePoll: () => {
if (!values.isSupportEnabled) {
return
}
const interval = values.errorCounter
? POLL_INTERVAL * (values.errorCounter + 1) // Backoff on errors
: POLL_INTERVAL
cache.disposables.add(() => {
const id = window.setTimeout(actions.loadUnreadCount, interval)
return () => clearTimeout(id)
}, 'pollTimeout')
},
refreshCount: () => {
// Intentionally visibility-agnostic: callers (e.g. ticket-viewed events)
// want an immediate count refresh regardless of tab focus. The follow-up
// polling resumes through schedulePoll, which IS gated by visibility
// via the disposables plugin's pause/resume.
cache.disposables.dispose('pollTimeout')
actions.loadUnreadCount()
},
})),
subscriptions(({ actions, values, cache }) => ({
// React to team changes - reset and re-fetch for new team
currentTeam: (currentTeam, oldTeam) => {
// Skip initial mount (oldTeam is undefined)
if (
oldTeam === undefined ||
(currentTeam?.id === oldTeam?.id &&
currentTeam?.conversations_enabled === oldTeam?.conversations_enabled)
) {
return
}
cache.disposables.dispose('pollTimeout')
actions.resetCount()
if (currentTeam?.conversations_enabled) {
actions.loadUnreadCount()
}
},
unreadCount: (unreadCount, oldUnreadCount) => {
if (oldUnreadCount === undefined) {
return
}
if (unreadCount > oldUnreadCount && values.canShowNotifications) {
actions.showNotification(unreadCount)
}
},
})),
afterMount(({ actions, values }) => {
if (values.sceneHasRendered && values.isSupportEnabled) {
actions.loadUnreadCount()
}
}),
])