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.

49.4 KB
Raw Blame
import { JSONContent } from '@tiptap/core'
import {
    MakeLogicType,
    actions,
    beforeUnmount,
    afterMount,
    connect,
    kea,
    listeners,
    path,
    reducers,
    selectors,
} from 'kea'
import { actionToUrl, router, urlToAction } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'

import {
    appendExceptionToMessage,
    appendTicketContext,
    captureSupportTicketBlocked,
    captureSupportWidgetLoadFailed,
    SUPPORT_WIDGET_UNAVAILABLE_MESSAGE,
    supportLogic,
    warnIfMessageTooLong,
    warnSupportWidgetUnavailable,
} from 'lib/components/Support/supportLogic'
import { EMAIL_SUPPORT_BUTTON, lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { billingLogic } from 'lib/logic/billing/billingLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { organizationLogic } from 'scenes/organizationLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { type BillingType, SidePanelTab } from '~/types'

import type { SupportFormFields } from '../../../../../frontend/src/lib/components/Support/supportLogic'
import type {
    ChatMessage,
    ConversationMessage,
    ConversationTicket,
    RestoreFlowState,
    SidePanelTicketFilter,
    SidePanelViewState,
} from '../../types'
import { clearSharedTickets, loadTicketsAcrossTabs } from './ticketsAcrossTabs'

function ticketMatchesFilter(ticket: ConversationTicket, filter: SidePanelTicketFilter): boolean {
    switch (filter) {
        case 'all':
            return true
        case 'unread':
            return (ticket.unread_count ?? 0) > 0
        case 'active':
            return ticket.status !== 'resolved'
        default:
            return ticket.status === filter
    }
}

/** Most recent activity on a ticket, for ordering. Falls back to creation when nothing was said yet. */
function ticketActivityTime(ticket: ConversationTicket): number {
    return new Date(ticket.last_message_at ?? ticket.created_at).getTime() || 0
}

// Poll cadence scales with how actively the user is looking at support, so an open thread stays fresh.
const POLL_INTERVAL_ACTIVE = 20 * 1000 // support surface open on the ticket list
const POLL_INTERVAL_THREAD = 10 * 1000 // a ticket thread is open, so replies must land quickly

// Panel options for a ticket deep link (#panel=support:ticket:<id>); supportRouterLogic skips this prefix
const TICKET_OPTIONS_PREFIX = 'ticket:'

function removeRestoreTokenFromUrl(): void {
    if ('ph_conv_restore' in router.values.searchParams) {
        const { ph_conv_restore: _, ...rest } = router.values.searchParams
        router.actions.replace(router.values.location.pathname, rest, router.values.hashParams)
    }
}

function messageToRichContent(message: string): JSONContent {
    return {
        type: 'doc',
        content: message.split('\n').map((line) => ({
            type: 'paragraph',
            ...(line ? { content: [{ type: 'text', text: line }] } : {}),
        })),
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sidepanelTicketsLogicValues {
    billing: BillingType | null // billingLogic
    billingLoading: boolean // billingLogic
    supportResponseTime: string | null // billingLogic
    isCurrentOrganizationNew: boolean // organizationLogic
    isCloudOrDev: boolean | undefined // preflightLogic
    selectedTab: SidePanelTab | null // sidePanelStateLogic
    selectedTabOptions: string | null // sidePanelStateLogic
    sidePanelOpen: boolean // sidePanelStateLogic
    isBillingIssue: boolean // supportLogic
    isEmailFormOpen: boolean // supportLogic
    isErrorReport: boolean // supportLogic
    pendingViewTicket: {
        created_at: string
        id: string
        status: string
    } | null // supportLogic
    sendSupportRequest: SupportFormFields // supportLogic
    canAccessTickets: boolean
    canCreateTicket: boolean
    currentTicket: ConversationTicket | null
    effectiveStatusFilter: SidePanelTicketFilter
    filteredTickets: ConversationTicket[]
    hasMoreMessages: boolean
    hasSupportExemption: boolean
    isBillingResolved: boolean
    messageSending: boolean
    messages: ChatMessage[]
    messagesLoading: boolean
    myTicketsUrl: string
    newTicketContext: string | null
    newTicketDraft: JSONContent | null
    newTicketDraftRevision: number
    pendingTicketId: string | null
    restoreError: string | null
    restoreState: RestoreFlowState
    statusFilter: SidePanelTicketFilter | null
    ticketFilterCounts: Record<SidePanelTicketFilter, number>
    tickets: ConversationTicket[]
    ticketsLoading: boolean
    ticketsRequestsInFlight: number
    totalUnreadCount: number
    view: SidePanelViewState
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sidepanelTicketsLogicActions {
    closeSidePanel: (tab?: SidePanelTab | undefined) => {
        tab: SidePanelTab | undefined
    } // sidePanelStateLogic
    setSidePanelOptions: (options: string | null) => {
        options: string | null
    } // sidePanelStateLogic
    clearPendingViewTicket: () => {
        value: true
    } // supportLogic
    closeEmailForm: () => {
        value: true
    } // supportLogic
    closeSupportForm: () => {
        value: true
    } // supportLogic
    resetSendSupportRequest: (values?: SupportFormFields | undefined) => {
        values?: SupportFormFields
    } // supportLogic
    logout: (
        preserveLocation?: any,
        nextUrl?: string | undefined,
        reason?: string | undefined
    ) => {
        nextUrl: string | undefined
        preserveLocation: any
        reason: string | undefined
    } // userLogic
    finishTicketsFetch: () => {
        value: true
    }
    grantSupportExemption: () => {
        value: true
    }
    loadMessages: (ticketId: string) => {
        ticketId: string
    }
    loadTickets: (force?: boolean) => {
        force: boolean
    }
    markAsRead: (ticketId: string) => {
        ticketId: string
    }
    openPendingTicket: () => {
        value: true
    }
    openTicketById: (ticketId: string) => {
        ticketId: string
    }
    requestRestoreLink: (email: string) => {
        email: string
    }
    restoreFromUrlToken: (token: string) => {
        token: string
    }
    sendMessage: (
        content: string,
        onSuccess: () => void
    ) => {
        content: string
        onSuccess: () => void
    }
    setCurrentTicket: (ticket: ConversationTicket) => {
        ticket: ConversationTicket
    }
    setHasMoreMessages: (hasMore: boolean) => {
        hasMore: boolean
    }
    setMessageSending: (sending: boolean) => {
        sending: boolean
    }
    setMessages: (messages: ChatMessage[]) => {
        messages: ChatMessage[]
    }
    setMessagesLoading: (loading: boolean) => {
        loading: boolean
    }
    setNewTicketContext: (context: string | null) => {
        context: string | null
    }
    setNewTicketDraft: (content: JSONContent | null) => {
        content: JSONContent | null
    }
    setPendingTicketId: (ticketId: string | null) => {
        ticketId: string | null
    }
    setRestoreError: (error: string | null) => {
        error: string | null
    }
    setRestoreState: (state: RestoreFlowState) => {
        state: RestoreFlowState
    }
    setStatusFilter: (status: SidePanelTicketFilter) => {
        status: SidePanelTicketFilter
    }
    setTickets: (tickets: ConversationTicket[]) => {
        tickets: ConversationTicket[]
    }
    setTicketsLoading: (loading: boolean) => {
        loading: boolean
    }
    setView: (view: SidePanelViewState) => {
        view: SidePanelViewState
    }
    startTicketFromSupportForm: () => {
        value: true
    }
    startTicketsFetch: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sidepanelTicketsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        totalUnreadCount: (tickets: ConversationTicket[]) => number
        effectiveStatusFilter: (
            statusFilter: SidePanelTicketFilter | null,
            totalUnreadCount: number
        ) => SidePanelTicketFilter
        ticketFilterCounts: (tickets: ConversationTicket[]) => Record<SidePanelTicketFilter, number>
        filteredTickets: (
            tickets: ConversationTicket[],
            effectiveStatusFilter: SidePanelTicketFilter,
            currentTicket: ConversationTicket | null,
            view: SidePanelViewState
        ) => ConversationTicket[]
        canCreateTicket: (
            billing: BillingType | null,
            isCurrentOrganizationNew: boolean,
            hasSupportExemption: boolean,
            isBillingIssue: boolean,
            isErrorReport: boolean
        ) => boolean
        isBillingResolved: (billing: BillingType | null, billingLoading: boolean) => boolean
        canAccessTickets: (canCreateTicket: boolean, tickets: ConversationTicket[]) => boolean
        myTicketsUrl: (view: SidePanelViewState, currentTicket: ConversationTicket | null) => string
    }
}

export type sidepanelTicketsLogicType = MakeLogicType<
    sidepanelTicketsLogicValues,
    sidepanelTicketsLogicActions,
    Record<string, any>,
    sidepanelTicketsLogicMeta
>

export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
    path(['products', 'conversations', 'frontend', 'components', 'SidePanel', 'sidepanelTicketsLogic']),
    connect(() => ({
        values: [
            sidePanelStateLogic,
            ['sidePanelOpen', 'selectedTab', 'selectedTabOptions'],
            supportLogic,
            ['isEmailFormOpen', 'sendSupportRequest', 'pendingViewTicket', 'isBillingIssue', 'isErrorReport'],
            billingLogic,
            ['billing', 'billingLoading', 'supportResponseTime'],
            organizationLogic,
            ['isCurrentOrganizationNew'],
            preflightLogic,
            ['isCloudOrDev'],
        ],
        actions: [
            supportLogic,
            ['closeEmailForm', 'closeSupportForm', 'clearPendingViewTicket', 'resetSendSupportRequest'],
            sidePanelStateLogic,
            ['closeSidePanel', 'setSidePanelOptions'],
            userLogic,
            ['logout'],
        ],
    })),
    actions({
        grantSupportExemption: true,
        loadTickets: (force: boolean = false) => ({ force }),
        setTickets: (tickets: ConversationTicket[]) => ({ tickets }),
        loadMessages: (ticketId: string) => ({ ticketId }),
        setMessages: (messages: ChatMessage[]) => ({ messages }),
        setHasMoreMessages: (hasMore: boolean) => ({ hasMore }),
        setTicketsLoading: (loading: boolean) => ({ loading }),
        startTicketsFetch: true,
        finishTicketsFetch: true,
        setMessagesLoading: (loading: boolean) => ({ loading }),
        markAsRead: (ticketId: string) => ({ ticketId }),
        setMessageSending: (sending: boolean) => ({ sending }),
        setView: (view: SidePanelViewState) => ({ view }),
        setCurrentTicket: (ticket: ConversationTicket) => ({ ticket }),
        setNewTicketDraft: (content: JSONContent | null) => ({ content }),
        setNewTicketContext: (context: string | null) => ({ context }),
        startTicketFromSupportForm: true,
        openPendingTicket: true,
        sendMessage: (content: string, onSuccess: () => void) => ({ content, onSuccess }),
        openTicketById: (ticketId: string) => ({ ticketId }),
        setPendingTicketId: (ticketId: string | null) => ({ ticketId }),
        requestRestoreLink: (email: string) => ({ email }),
        restoreFromUrlToken: (token: string) => ({ token }),
        setRestoreState: (state: RestoreFlowState) => ({ state }),
        setRestoreError: (error: string | null) => ({ error }),
        setStatusFilter: (status: SidePanelTicketFilter) => ({ status }),
    }),
    reducers({
        view: [
            'list' as SidePanelViewState,
            {
                setView: (_, { view }) => view,
            },
        ],
        tickets: [
            [] as ConversationTicket[],
            {
                setTickets: (_, { tickets }) => tickets,
            },
        ],
        messages: [
            [] as ChatMessage[],
            {
                setMessages: (_, { messages }) => messages,
            },
        ],
        hasMoreMessages: [
            false,
            {
                setHasMoreMessages: (_, { hasMore }) => hasMore,
            },
        ],
        ticketsRequestsInFlight: [
            0,
            {
                startTicketsFetch: (state) => state + 1,
                finishTicketsFetch: (state) => state - 1,
            },
        ],
        ticketsLoading: [
            false,
            {
                setTicketsLoading: (_, { loading }) => loading,
            },
        ],
        currentTicket: [
            null as ConversationTicket | null,
            {
                setCurrentTicket: (_, { ticket }) => ticket,
            },
        ],
        // Ticket id from a URL that arrived before the list loaded; consumed by setTickets
        pendingTicketId: [
            null as string | null,
            {
                setPendingTicketId: (_, { ticketId }) => ticketId,
                setCurrentTicket: () => null,
            },
        ],
        newTicketDraft: [
            null as JSONContent | null,
            {
                setNewTicketDraft: (_, { content }) => content,
                // Clear once we leave the composer so a later blank "New ticket" doesn't show a stale prefill
                setView: (state, { view }) => (view === 'new' ? state : null),
            },
        ],
        // Cleared with the draft, so a later blank "New ticket" doesn't carry it
        newTicketContext: [
            null as string | null,
            {
                setNewTicketContext: (_, { context }) => context,
                setView: (state, { view }) => (view === 'new' ? state : null),
            },
        ],
        // Bumped only when a draft is injected via setNewTicketDraft (a prefilled CTA), so NewTicket
        // remounts to pick up the seeded content. Plain typing never calls this, so it doesn't remount.
        newTicketDraftRevision: [
            0,
            {
                setNewTicketDraft: (state) => state + 1,
            },
        ],
        messagesLoading: [
            false,
            {
                setMessagesLoading: (_, { loading }) => loading,
            },
        ],
        messageSending: [
            false,
            {
                setMessageSending: (_, { sending }) => sending,
            },
        ],
        restoreState: [
            'idle' as RestoreFlowState,
            {
                setRestoreState: (_, { state }) => state,
                setView: () => 'idle' as RestoreFlowState,
            },
        ],
        restoreError: [
            null as string | null,
            {
                setRestoreError: (_, { error }) => error,
                setRestoreState: () => null,
            },
        ],
        // `null` means "not chosen yet": the list then defaults to unread tickets when there are
        // any, otherwise to active ones, so a long history never buries what needs attention.
        statusFilter: [
            null as SidePanelTicketFilter | null,
            {
                setStatusFilter: (_, { status }) => status,
            },
        ],
        // Held for the life of the open panel rather than read off the support request, which resets
        // the moment the intent is consumed — a plan that can't open tickets would otherwise lose the
        // exemption mid-compose, and with it the composer it was just granted
        hasSupportExemption: [
            false as boolean,
            {
                grantSupportExemption: () => true,
                closeSidePanel: () => false,
            },
        ],
    }),
    selectors({
        totalUnreadCount: [
            (s) => [s.tickets],
            (tickets: ConversationTicket[]) => tickets.reduce((sum, t) => sum + (t.unread_count ?? 0), 0),
        ],
        effectiveStatusFilter: [
            (s) => [s.statusFilter, s.totalUnreadCount],
            (statusFilter: SidePanelTicketFilter | null, totalUnreadCount: number): SidePanelTicketFilter =>
                statusFilter ?? (totalUnreadCount > 0 ? 'unread' : 'active'),
        ],
        ticketFilterCounts: [
            (s) => [s.tickets],
            (tickets: ConversationTicket[]): Record<SidePanelTicketFilter, number> => {
                const counts: Record<SidePanelTicketFilter, number> = {
                    unread: 0,
                    active: 0,
                    all: tickets.length,
                    new: 0,
                    open: 0,
                    pending: 0,
                    on_hold: 0,
                    resolved: 0,
                }
                for (const ticket of tickets) {
                    counts[ticket.status] += 1
                    if (ticket.status !== 'resolved') {
                        counts.active += 1
                    }
                    if ((ticket.unread_count ?? 0) > 0) {
                        counts.unread += 1
                    }
                }
                return counts
            },
        ],
        // Unread threads float to the top, then most recent activity. The open thread counts as
        // unread while it is being read: opening it marks it read, and the full-screen scene keeps
        // the list beside the thread, so without the pin the row would drop or vanish on click.
        filteredTickets: [
            (s) => [s.tickets, s.effectiveStatusFilter, s.currentTicket, s.view],
            (
                tickets: ConversationTicket[],
                effectiveStatusFilter: SidePanelTicketFilter,
                currentTicket: ConversationTicket | null,
                view: SidePanelViewState
            ): ConversationTicket[] => {
                const pinnedId = view === 'ticket' ? (currentTicket?.id ?? null) : null
                const surfaces = (ticket: ConversationTicket): boolean =>
                    ticket.id === pinnedId || (ticket.unread_count ?? 0) > 0
                return tickets
                    .filter((ticket) => ticket.id === pinnedId || ticketMatchesFilter(ticket, effectiveStatusFilter))
                    .sort((a, b) => {
                        const surfaceDelta = Number(surfaces(b)) - Number(surfaces(a))
                        return surfaceDelta !== 0 ? surfaceDelta : ticketActivityTime(b) - ticketActivityTime(a)
                    })
            },
        ],
        // Opening a ticket is the paid part of support. Reading and replying to tickets already in
        // the account isn't — free plans can end up with tickets via billing questions or PostHog AI
        // bug reports, and abandoning those threads helps nobody.
        canCreateTicket: [
            (s) => [s.billing, s.isCurrentOrganizationNew, s.hasSupportExemption, s.isBillingIssue, s.isErrorReport],
            (
                billing: BillingType | null,
                isCurrentOrganizationNew: boolean,
                hasSupportExemption: boolean,
                isBillingIssue: boolean,
                isErrorReport: boolean
            ): boolean => {
                const hasSupportTrial =
                    billing?.trial?.status === 'active' &&
                    ['boost', 'scale', 'enterprise'].includes(billing.trial?.target ?? '')
                return (
                    billing?.subscription_level === 'paid' ||
                    billing?.subscription_level === 'custom' ||
                    hasSupportTrial ||
                    isCurrentOrganizationNew ||
                    // Billing questions are answered on every plan, and a crash we surfaced ourselves
                    // is always worth hearing about — the error boundary offers to email an engineer,
                    // so blocking that would break a promise we just made. Read live from the request
                    // as well as the sticky reducer: CTAs that don't open the composer never reach
                    // `startTicketFromSupportForm`, so the reducer alone would miss them.
                    isBillingIssue ||
                    isErrorReport ||
                    hasSupportExemption
                )
            },
        ],
        // `billing` is lazily loaded, so a null value means "not fetched yet" just as often as it
        // means "no billing". Entitlement is only knowable once it settles.
        isBillingResolved: [
            (s) => [s.billing, s.billingLoading],
            (billing: BillingType | null, billingLoading: boolean): boolean => !billingLoading && billing !== null,
        ],
        // Free plans can't open new tickets, but tickets they already have (billing questions, PostHog AI
        // bug reports) stay readable and repliable.
        canAccessTickets: [
            (s) => [s.canCreateTicket, s.tickets],
            (canCreateTicket: boolean, tickets: ConversationTicket[]): boolean => canCreateTicket || tickets.length > 0,
        ],
        myTicketsUrl: [
            (s) => [s.view, s.currentTicket],
            (view: SidePanelViewState, currentTicket: ConversationTicket | null): string =>
                urls.myTickets(view === 'ticket' ? currentTicket?.id : undefined),
        ],
    }),
    listeners(({ actions, values, cache }) => ({
        logout: () => {
            clearSharedTickets()
        },
        loadTickets: async ({ force }) => {
            if (cache.restoringFromUrlToken) {
                return
            }
            // We don't support self-hosted, and the conversations extension is cloud-only — both the
            // panel and the tickets scene already render a community-forum message instead. This logic
            // still mounts there (the scene declares it in its SceneExport), so without this it would
            // retry a widget that will never arrive and then tell a self-hosted user to email us.
            //
            // Explicitly `=== false` rather than falsy: `isCloudOrDev` is undefined until preflight
            // resolves, and treating that as self-hosted would block the first load on cloud. Retries
            // re-read it, so a self-hosted instance stops as soon as preflight lands — well inside the
            // 20 attempts it takes to warn.
            if (values.isCloudOrDev === false) {
                return
            }
            if (cache.conversationsRetryTimer) {
                clearTimeout(cache.conversationsRetryTimer)
                cache.conversationsRetryTimer = null
            }
            // Not just a truthiness check: posthog-js creates the `conversations` facade at init,
            // but its methods resolve null until the lazily loaded manager is ready — a cold page
            // load would otherwise render an empty list once and never retry
            if (!posthog.conversations?.isAvailable()) {
                // Conversations extension loads lazily — retry until it's ready
                if ((cache.conversationsRetries ?? 0) < 20) {
                    cache.conversationsRetries = (cache.conversationsRetries ?? 0) + 1
                    cache.conversationsRetryTimer = window.setTimeout(() => actions.loadTickets(force), 500)
                    return
                }
                // Out of retries. Kept separate from the send-failure event because nothing was
                // submitted here, and recorded even when we stay quiet so the rate is measurable.
                if (!cache.conversationsUnavailableCaptured) {
                    cache.conversationsUnavailableCaptured = true
                    captureSupportWidgetLoadFailed({
                        surface: 'side_panel_tickets',
                        reason: 'extension_missing',
                        can_create_ticket: values.canCreateTicket,
                    })
                }
                // A forced load can run on any page, so an unavailable widget (an ad blocker is enough)
                // would otherwise raise a persistent error toast on surfaces that have nothing to do with
                // support and block clicks on whatever sits under the toast container. Only warn while the
                // person is actually on a support surface; opening one later re-runs loadTickets and warns then.
                // Only warn people who could act on it. A free plan has no email fallback, and the
                // panel already shows them the community and upgrade options, so a toast offering
                // to email us would promise a channel they don't get. Warn while entitlement is
                // still unresolved, matching how the composer opens rather than drop a message.
                if (
                    !cache.conversationsUnavailableWarned &&
                    liveTicketsLogic.isMounted() &&
                    (values.canCreateTicket || !values.isBillingResolved)
                ) {
                    cache.conversationsUnavailableWarned = true
                    warnSupportWidgetUnavailable()
                }
                return
            }
            cache.conversationsRetries = 0
            // Polls, tab-focus, and scene remounts reuse loadTickets. The flag drives a full-list
            // spinner, so it is only raised until the first successful fetch.
            if (!cache.ticketsFetched) {
                actions.setTicketsLoading(true)
            }
            actions.startTicketsFetch()
            const requestDisposables = cache.disposables
            try {
                const tickets = await loadTicketsAcrossTabs(
                    async () => {
                        const response = await posthog.conversations.getTickets({ limit: 50 })
                        return response ? (response.results as ConversationTicket[]) : null
                    },
                    { force, maxAgeMs: POLL_INTERVAL_THREAD }
                )
                if (tickets && !requestDisposables.isDisposed) {
                    cache.ticketsFetched = true
                    actions.setTickets(tickets)
                }
            } catch (e) {
                console.error('Failed to load tickets:', e)
                // Reported because a customer who can't see their tickets can't reply to support on
                // them either, and the toast alone left us blind to how often that happens
                captureSupportWidgetLoadFailed({
                    surface: 'side_panel_tickets',
                    reason: 'tickets_load_failed',
                    error: e,
                    can_create_ticket: values.canCreateTicket,
                })
                // A forced load can run on any page, so a transient failure there would toast on
                // surfaces that have nothing to do with support
                if (!requestDisposables.isDisposed && liveTicketsLogic.isMounted()) {
                    lemonToast.error('Failed to load tickets.')
                }
            } finally {
                if (!requestDisposables.isDisposed) {
                    actions.finishTicketsFetch()
                    actions.setTicketsLoading(false)
                }
            }
        },
        loadMessages: async ({ ticketId }) => {
            if (!ticketId || !posthog.conversations) {
                return
            }
            actions.setMessagesLoading(true)
            try {
                const allMessages: ConversationMessage[] = []
                let after: string | undefined
                let hasMore = true

                // Fetch all pages of messages using `after` timestamp pagination
                while (hasMore) {
                    const response = await (posthog.conversations.getMessages as any)(ticketId, after)
                    // Check if we're still viewing the same ticket (avoid race condition when switching quickly)
                    if (!response || values.currentTicket?.id !== ticketId) {
                        return
                    }
                    const messages = response.messages as ConversationMessage[]
                    allMessages.push(...messages)
                    hasMore = response.has_more && messages.length > 0
                    // Use the last message's created_at as the `after` cursor for next page
                    if (hasMore && messages.length > 0) {
                        after = messages[messages.length - 1].created_at
                    }
                }

                // Transform and set all messages
                const transformedMessages: ChatMessage[] = allMessages.map((msg) => ({
                    id: msg.id,
                    content: msg.content,
                    authorType: msg.author_type,
                    authorName: msg.author_name || '',
                    createdAt: msg.created_at,
                }))
                actions.setMessages(transformedMessages)
                actions.setHasMoreMessages(false)
            } catch (e) {
                console.error('Failed to load messages:', e)
                // A thread that won't open is a customer who can't continue a conversation they
                // already started, so it belongs in the same rate signal as a dead panel
                captureSupportWidgetLoadFailed({
                    surface: 'side_panel_tickets',
                    reason: 'thread_load_failed',
                    error: e,
                })
                lemonToast.error('Failed to load messages. Please try again.')
            } finally {
                actions.setMessagesLoading(false)
            }
        },
        sendMessage: async ({ content: typed, onSuccess }) => {
            if (!typed.trim() || values.messageSending) {
                return
            }
            const content = values.view === 'new' ? appendTicketContext(typed, values.newTicketContext) : typed
            // Bailing quietly here left the button un-loaded and the typed message sitting in the box
            // with no explanation, which is the worst version of this now conversations is the only channel
            if (!posthog.conversations) {
                captureSupportTicketBlocked({
                    surface: 'side_panel_composer',
                    reason: 'widget_unavailable',
                    message: content,
                    is_new_ticket: values.view === 'new',
                })
                warnSupportWidgetUnavailable()
                return
            }
            if (warnIfMessageTooLong(content)) {
                captureSupportTicketBlocked({
                    surface: 'side_panel_composer',
                    reason: 'message_too_long',
                    message: content,
                    is_new_ticket: values.view === 'new',
                })
                return
            }
            actions.setMessageSending(true)
            try {
                // If we're in "new" view, force creation of a new ticket
                const forceNewTicket = values.view === 'new'

                const response = await posthog.conversations.sendMessage(content, {}, forceNewTicket)
                if (response) {
                    // If we just created a new ticket, set it as current and switch to chat view
                    if (values.view === 'new') {
                        actions.setCurrentTicket({
                            id: response.ticket_id,
                            status: response.ticket_status,
                            message_count: 1,
                            created_at: response.created_at,
                            unread_count: 0,
                            last_message: content,
                            last_message_at: response.created_at,
                        })
                        actions.setView('ticket')
                    }
                    actions.loadTickets(true)
                    actions.loadMessages(response.ticket_id)
                    lemonToast.success('Message sent!')
                    onSuccess()
                } else {
                    // A null response means nothing was sent, so surface it instead of silently
                    // resetting. The widget endpoint reports the rejections it sees itself, but it
                    // can't see a send the extension declined to make — and only the client still
                    // holds the draft, which is the part a responder needs.
                    captureSupportTicketBlocked({
                        surface: 'side_panel_composer',
                        reason: 'widget_declined',
                        message: content,
                        is_new_ticket: values.view === 'new',
                    })
                    lemonToast.error('Failed to send message. Please try again.', {
                        button: EMAIL_SUPPORT_BUTTON,
                    })
                }
            } catch (e) {
                console.error('Failed to send message:', e)
                captureSupportTicketBlocked({
                    surface: 'side_panel_composer',
                    reason: 'send_failed',
                    message: content,
                    error: e,
                    is_new_ticket: values.view === 'new',
                })
                lemonToast.error('Failed to send message. Please try again.', { button: EMAIL_SUPPORT_BUTTON })
            } finally {
                actions.setMessageSending(false)
            }
        },
        markAsRead: async ({ ticketId }) => {
            if (!ticketId || !posthog.conversations) {
                return
            }
            try {
                await posthog.conversations.markAsRead(ticketId)
            } catch (e) {
                console.error('Failed to mark as read:', e)
            }
        },
        setCurrentTicket: ({ ticket }: { ticket: ConversationTicket }) => {
            actions.setView('ticket')
            actions.setMessages([]) // Clear messages immediately to avoid showing stale data
            actions.loadMessages(ticket.id)
            actions.markAsRead(ticket.id)
            // Mirror the open ticket into the panel hash so the address bar stays linkable
            if (values.sidePanelOpen && values.selectedTab === SidePanelTab.Support) {
                actions.setSidePanelOptions(`${TICKET_OPTIONS_PREFIX}${ticket.id}`)
            }
        },
        setView: ({ view }) => {
            // Only clear our own format; other option strings belong to the support form
            if (
                view !== 'ticket' &&
                values.sidePanelOpen &&
                values.selectedTab === SidePanelTab.Support &&
                values.selectedTabOptions?.startsWith(TICKET_OPTIONS_PREFIX)
            ) {
                actions.setSidePanelOptions(null)
            }
        },
        openTicketById: ({ ticketId }) => {
            if (values.view === 'ticket' && values.currentTicket?.id === ticketId) {
                return
            }
            const ticket = values.tickets.find((t) => t.id === ticketId)
            if (ticket) {
                actions.setCurrentTicket(ticket)
            } else {
                actions.setPendingTicketId(ticketId)
            }
        },
        setTickets: ({ tickets }) => {
            const pending = values.pendingTicketId
            if (!pending) {
                return
            }
            const ticket = tickets.find((t) => t.id === pending)
            if (ticket) {
                actions.setCurrentTicket(ticket)
            } else {
                // Loaded and absent means a stale link; clear so polls don't re-run the lookup
                actions.setPendingTicketId(null)
            }
        },
        // "Contact support" CTAs (error boundaries, empty states, etc.) open the support form via
        // supportLogic, which should land in this composer instead, carrying any prefilled message
        // with them
        startTicketFromSupportForm: () => {
            // Billing problems are answered on every plan, and a crash the error boundary surfaced is
            // always worth hearing about, so both earn an exemption even when the plan excludes support
            if (values.isBillingIssue || values.isErrorReport) {
                actions.grantSupportExemption()
            } else if (values.isBillingResolved && !values.canCreateTicket) {
                // Still consume the intent (see below), just without opening the composer — the panel
                // explains why and points at the community and upgrade options instead. Only ever on a
                // known-ineligible plan: consuming is irreversible, so while entitlement is still
                // unknown we open the composer rather than turn someone away on a maybe.
                //
                // No draft is passed, and that's not an omission: this runs the moment a CTA fires,
                // before any composer is on screen, so nothing has been typed yet. Every CTA that
                // reaches here passes no message either. What's lost is the customer's intent to
                // reach us, which is what the event records.
                captureSupportTicketBlocked({
                    surface: 'support_form',
                    reason: 'not_entitled',
                    kind: values.sendSupportRequest?.kind,
                    can_create_ticket: false,
                })
                actions.closeEmailForm()
                actions.closeSupportForm()
                actions.resetSendSupportRequest()
                return
            }
            const request = values.sendSupportRequest
            // Guarding on the message alone dropped the exception, because an error boundary CTA
            // carries an exception and no message — and its crash card promises we attach it
            const draft = appendExceptionToMessage(request?.message ?? '', request?.exception_event)
            if (draft) {
                actions.setNewTicketDraft(messageToRichContent(draft))
            }
            actions.setNewTicketContext(request?.ticket_context || null)
            actions.setView('new')
            // Consume the support-form intent fully (or supportRouterLogic keeps treating the form as
            // open and ignores future URL-driven opens), and reset so a stale message can't resurface
            // prefilled on a later CTA that carries none
            actions.closeEmailForm()
            actions.closeSupportForm()
            actions.resetSendSupportRequest()
        },
        // "View" on a submission toast (Max AI, feature-preview feedback, etc.) should land in the
        // created ticket's thread, matching where the composer flow leaves you
        openPendingTicket: () => {
            const pending = values.pendingViewTicket
            if (!pending) {
                return
            }
            actions.clearPendingViewTicket()
            actions.setCurrentTicket({
                id: pending.id,
                status: pending.status as ConversationTicket['status'],
                message_count: 1,
                created_at: pending.created_at,
                unread_count: 0,
                last_message_at: pending.created_at,
            })
            actions.loadTickets(true)
        },
        requestRestoreLink: async ({ email }) => {
            const conversations = posthog.conversations as any
            if (!conversations?.requestRestoreLink) {
                // Returning quietly left the button idle with no explanation. This form already renders
                // restoreError inline, which beats a toast for something the user has to act on.
                captureSupportWidgetLoadFailed({ surface: 'restore_form', reason: 'extension_missing' })
                actions.setRestoreError(
                    `${SUPPORT_WIDGET_UNAVAILABLE_MESSAGE} Try turning it off for this site and reloading.`
                )
                actions.setRestoreState('error')
                return
            }
            actions.setRestoreState('sending')
            try {
                await conversations.requestRestoreLink(email)
                actions.setRestoreState('sent')
            } catch (e: any) {
                // Someone who lost their tickets and can't get the restore link has no way back to a
                // conversation they already started, so it's worth the same visibility as a dead panel
                captureSupportWidgetLoadFailed({ surface: 'restore_form', reason: 'restore_link_failed', error: e })
                const message =
                    e?.status === 429
                        ? 'Too many requests. Please try again later.'
                        : 'Something went wrong. Please try again.'
                actions.setRestoreError(message)
                actions.setRestoreState('error')
            }
        },
        restoreFromUrlToken: async ({ token }) => {
            cache.restoringFromUrlToken = true
            const conversations = posthog.conversations as any
            // isAvailable rather than method presence: the facade and its methods exist from
            // posthog-js init, but resolve null until the manager loads — which would consume
            // the one-shot restore token without restoring anything
            if (!posthog.conversations?.isAvailable()) {
                if ((cache.restoreRetries ?? 0) < 20) {
                    cache.restoreRetries = (cache.restoreRetries ?? 0) + 1
                    cache.restoreRetryTimer = window.setTimeout(() => actions.restoreFromUrlToken(token), 500)
                } else {
                    removeRestoreTokenFromUrl()
                    cache.restoringFromUrlToken = false
                    actions.loadTickets(true)
                }
                return
            }
            try {
                // Use restoreFromToken(token) directly instead of restoreFromUrlToken()
                // because posthog-js clears the token from the URL during its own
                // initialization, causing restoreFromUrlToken() to return null.
                const result = await conversations.restoreFromToken(token)
                if (result?.status === 'success') {
                    const count = result.migrated_ticket_ids?.length ?? 0
                    if (count > 0) {
                        lemonToast.success(
                            `Restored ${count} ticket${count === 1 ? '' : 's'} from your previous session.`
                        )
                    }
                }
            } catch (e) {
                // Token may have been consumed by posthog-js already — that's OK,
                // the migration still happened so loadTickets will see them.
                console.error('Failed to restore from URL token:', e)
            } finally {
                removeRestoreTokenFromUrl()
                cache.restoringFromUrlToken = false
                actions.loadTickets(true)
            }
        },
    })),
    // Both blocks guard on the pathname because this logic also backs the side panel, which can
    // be open on any page where the URL must stay untouched
    urlToAction(({ actions, values }) => ({
        [urls.myTickets()]: (_, searchParams) => {
            const ticketId = searchParams['ticket']
            if (typeof ticketId === 'string' && ticketId) {
                actions.openTicketById(ticketId)
            } else if (values.view === 'ticket') {
                // Also catches browser-back from ?ticket=
                actions.setView('list')
            }
        },
    })),
    actionToUrl(() => ({
        setCurrentTicket: ({ ticket }) => {
            // The scene is project-based, so the window pathname carries a /project/<id> prefix
            if (removeProjectIdIfPresent(router.values.location.pathname) !== urls.myTickets()) {
                return undefined
            }
            return [
                router.values.location.pathname,
                { ...router.values.searchParams, ticket: ticket.id },
                router.values.hashParams,
            ]
        },
        setView: ({ view }) => {
            if (
                view === 'ticket' ||
                removeProjectIdIfPresent(router.values.location.pathname) !== urls.myTickets() ||
                !('ticket' in router.values.searchParams)
            ) {
                return undefined
            }
            const { ticket: _discarded, ...searchParams } = router.values.searchParams
            return [router.values.location.pathname, searchParams, router.values.hashParams]
        },
    })),
    subscriptions(({ actions, values }) => ({
        selectedTabOptions: (options: string | null) => {
            if (values.selectedTab === SidePanelTab.Support && options?.startsWith(TICKET_OPTIONS_PREFIX)) {
                actions.openTicketById(options.slice(TICKET_OPTIONS_PREFIX.length))
            }
        },
        isEmailFormOpen: (open: boolean) => {
            if (open) {
                actions.startTicketFromSupportForm()
            }
        },
        pendingViewTicket: (pending: { id: string } | null) => {
            if (pending) {
                actions.openPendingTicket()
            }
        },
    })),
    beforeUnmount(({ cache }) => {
        if (cache.conversationsRetryTimer) {
            clearTimeout(cache.conversationsRetryTimer)
        }
        if (cache.restoreRetryTimer) {
            clearTimeout(cache.restoreRetryTimer)
        }
    }),
    afterMount(({ values, actions }) => {
        // A restore link can land on any page and its token is one-shot, so this does not wait for a support surface.
        const restoreToken = router.values.searchParams['ph_conv_restore']
        if (restoreToken) {
            actions.restoreFromUrlToken(restoreToken)
        }
        // A cold load of a `#panel=support:...:true` URL can set these before this logic mounts, so
        // the isEmailFormOpen/pendingViewTicket subscriptions above only fire on change and would
        // otherwise miss them — re-consume here too.
        if (values.isEmailFormOpen) {
            actions.startTicketFromSupportForm()
        }
        if (values.pendingViewTicket) {
            actions.openPendingTicket()
        }
        if (
            values.selectedTab === SidePanelTab.Support &&
            values.selectedTabOptions?.startsWith(TICKET_OPTIONS_PREFIX)
        ) {
            actions.openTicketById(values.selectedTabOptions.slice(TICKET_OPTIONS_PREFIX.length))
        }
    }),
])

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface liveTicketsLogicValues {
    currentTicket: ConversationTicket | null // sidepanelTicketsLogic
    messagesLoading: boolean // sidepanelTicketsLogic
    tickets: ConversationTicket[] // sidepanelTicketsLogic
    view: SidePanelViewState // sidepanelTicketsLogic
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface liveTicketsLogicActions {
    loadMessages: (ticketId: string) => {
        ticketId: string
    } // sidepanelTicketsLogic
    loadTickets: (force?: boolean | undefined) => {
        force: boolean
    } // sidepanelTicketsLogic
    setTickets: (tickets: ConversationTicket[]) => {
        tickets: ConversationTicket[]
    } // sidepanelTicketsLogic
    setView: (view: SidePanelViewState) => {
        view: SidePanelViewState
    } // sidepanelTicketsLogic
    schedulePoll: () => {
        value: true
    }
}

export type liveTicketsLogicType = MakeLogicType<liveTicketsLogicValues, liveTicketsLogicActions>

/**
 * Keeps tickets fresh while a support surface is on screen, so a mounted copy of this logic means that surface exists.
 * Every person's widget requests share one rate limit, so mount this from a surface, never from something that only
 * reads sidepanelTicketsLogic.
 */
export const liveTicketsLogic = kea<liveTicketsLogicType>([
    path(['products', 'conversations', 'frontend', 'components', 'SidePanel', 'liveTicketsLogic']),
    connect(() => ({
        values: [sidepanelTicketsLogic, ['tickets', 'view', 'currentTicket', 'messagesLoading']],
        actions: [sidepanelTicketsLogic, ['loadTickets', 'loadMessages', 'setTickets', 'setView']],
    })),
    actions({
        schedulePoll: true,
    }),
    listeners(({ actions, values, cache }) => ({
        setTickets: () => actions.schedulePoll(),
        // Entering or leaving a thread changes the cadence.
        setView: () => actions.schedulePoll(),
        schedulePoll: () => {
            // Nothing to poll for until the user has at least one ticket. Creating one re-runs
            // loadTickets, which schedules polling from there.
            if (values.tickets.length === 0) {
                cache.disposables.dispose('poll')
                return
            }
            const insideTicket = values.view === 'ticket' && !!values.currentTicket
            cache.disposables.add(() => {
                const timer = window.setTimeout(
                    () => {
                        actions.loadTickets()
                        // loadTickets only refreshes the list, so a support reply wouldn't appear while the
                        // reader sits inside the thread. Skip when a load is already running so a slow fetch
                        // can't overlap this one.
                        if (values.currentTicket && values.view === 'ticket' && !values.messagesLoading) {
                            actions.loadMessages(values.currentTicket.id)
                        }
                    },
                    insideTicket ? POLL_INTERVAL_THREAD : POLL_INTERVAL_ACTIVE
                )
                return () => clearTimeout(timer)
            }, 'poll')
        },
    })),
    afterMount(({ actions, cache }) => {
        // Disposables pause while the tab is hidden, so this also refreshes the tickets each time the tab returns.
        cache.disposables.add(() => {
            actions.loadTickets()
            return () => {}
        }, 'refresh')
    }),
])