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.

fix(today): load support tickets only on support surfaces (#127870)

Adam Leithef6748b32142
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/support/SidePanelSupport.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/support/SidePanelSupport.tsx
index 50acdeda4a88..e9d9b6bcbefa 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/support/SidePanelSupport.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/support/SidePanelSupport.tsx
@@ -1,4 +1,4 @@
-import { useActions, useValues } from 'kea'
+import { useActions, useMountedLogic, useValues } from 'kea'
import React from 'react'
import { IconExpand45, IconFeatures, IconHelmet, IconMap, IconWarning } from '@posthog/icons'
@@ -18,7 +18,10 @@ import { ProductKey } from '~/queries/schema/schema-general'
import { BillingPlan, BillingType, SidePanelTab } from '~/types'
import { SidePanelTickets } from 'products/conversations/frontend/components/SidePanel/SidePanelTickets'
-import { sidepanelTicketsLogic } from 'products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic'
+import {
+ liveTicketsLogic,
+ sidepanelTicketsLogic,
+} from 'products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic'
import { SidePanelPaneHeader } from '../../components/SidePanelPaneHeader'
import { SidePanelContentContainer } from '../../SidePanelContentContainer'
@@ -191,14 +194,13 @@ export function SidePanelSupport(): JSX.Element {
useValues(userLogic)
const { openSidePanel, closeSidePanel } = useActions(sidePanelStateLogic)
const { billing, billingLoading, billingPlan } = useValues(billingLogic)
- const { tickets, canCreateTicket, view, currentTicket } = useValues(sidepanelTicketsLogic)
+ useMountedLogic(liveTicketsLogic)
+ const { canAccessTickets, canCreateTicket, myTicketsUrl } = useValues(sidepanelTicketsLogic)
const isCloudOrDev = preflight?.cloud || process.env.NODE_ENV === 'development'
const showMaxAI = isCloudOrDev
const isBillingLoaded = !billingLoading && billing !== undefined
- // Free plans can't open new tickets, but tickets they already have (billing questions, PostHog AI
- // bug reports) stay readable and repliable here
- const showTickets = isCloudOrDev && (canCreateTicket || tickets.length > 0)
+ const showTickets = isCloudOrDev && canAccessTickets
return (
<div className="SidePanelSupport contents">
@@ -208,7 +210,7 @@ export function SidePanelSupport(): JSX.Element {
<LemonButton
size="xsmall"
icon={<IconExpand45 />}
- to={urls.myTickets(view === 'ticket' ? currentTicket?.id : undefined)}
+ to={myTicketsUrl}
onClick={() => closeSidePanel()}
tooltip="View your tickets full screen"
// LemonButton's tooltip→aria-label fallback only applies to plain buttons,
diff --git a/frontend/src/layout/today/TodaySupportPanel.tsx b/frontend/src/layout/today/TodaySupportPanel.tsx
index f14299ac3231..bb94196b7ee0 100644
--- a/frontend/src/layout/today/TodaySupportPanel.tsx
+++ b/frontend/src/layout/today/TodaySupportPanel.tsx
@@ -1,4 +1,4 @@
-import { useActions, useValues } from 'kea'
+import { useActions, useMountedLogic, useValues } from 'kea'
import { IconExternal, IconFeatures, IconHelmet, IconMap } from '@posthog/icons'
import { Button, Heading, Skeleton, Text, cn } from '@posthog/quill'
@@ -14,7 +14,10 @@ import { ProductKey } from '~/queries/schema/schema-general'
import { BillingPlan, SidePanelTab } from '~/types'
import { QuillSupportTickets } from 'products/conversations/frontend/components/QuillSidePanel/QuillSupportTickets'
-import { sidepanelTicketsLogic } from 'products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic'
+import {
+ liveTicketsLogic,
+ sidepanelTicketsLogic,
+} from 'products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic'
import { todayContextPanelLogic } from './todayContextPanelLogic'
import { TodaySupportResponseTimes } from './TodaySupportResponseTimes'
@@ -43,14 +46,14 @@ function ExternalLinkButton({ href, children }: { href: string; children: React.
export function TodaySupportPanel(): JSX.Element {
const { preflight } = useValues(preflightLogic)
const { billing, billingLoading, billingPlan } = useValues(billingLogic)
- const { tickets, canCreateTicket, view } = useValues(sidepanelTicketsLogic)
+ useMountedLogic(liveTicketsLogic)
+ const { canAccessTickets, canCreateTicket, view } = useValues(sidepanelTicketsLogic)
const { featureFlags } = useValues(featureFlagLogic)
const { togglePanelTab } = useActions(todayContextPanelLogic)
const isCloudOrDev = preflight?.cloud || process.env.NODE_ENV === 'development'
const billingLoaded = !billingLoading && billing !== undefined
- // Free plans can't open new tickets, but tickets they already have stay readable and repliable.
- const showTickets = isCloudOrDev && (canCreateTicket || tickets.length > 0)
+ const showTickets = isCloudOrDev && canAccessTickets
// An open ticket, a new ticket or recovery fills the panel on its own, so the thread and composer get the room.
// An open ticket scrolls its own thread. The forms scroll as a whole, so Submit stays reachable in a short panel.
diff --git a/frontend/src/layout/today/TodaySupportTicketFetching.test.tsx b/frontend/src/layout/today/TodaySupportTicketFetching.test.tsx
new file mode 100644
index 000000000000..32a94352c2ce
--- /dev/null
+++ b/frontend/src/layout/today/TodaySupportTicketFetching.test.tsx
@@ -0,0 +1,53 @@
+import { render } from '@testing-library/react'
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import { preflightLogic } from 'lib/logic/preflightLogic'
+
+import { SidePanelSupport } from '~/layout/navigation-3000/sidepanel/panels/support/SidePanelSupport'
+import { initKeaTests } from '~/test/init'
+
+import { sidepanelTicketsLogic } from 'products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic'
+
+import { TodaySupportPanel } from './TodaySupportPanel'
+import { TodayTopBarPanelTabs } from './TodayTopBarPanelTabs'
+
+describe('support ticket fetching', () => {
+ let getTickets: jest.Mock
+
+ beforeEach(() => {
+ window.localStorage.clear()
+ initKeaTests()
+ getTickets = jest.fn().mockResolvedValue({ results: [] })
+ ;(posthog as any).conversations = { isAvailable: () => true, getTickets }
+ preflightLogic.mount()
+ preflightLogic.actions.loadPreflightSuccess({ cloud: true, is_debug: false } as any)
+ })
+
+ afterEach(() => {
+ delete (posthog as any).conversations
+ })
+
+ it('does not fetch from the top bar, which renders on every page', async () => {
+ const { getByLabelText, unmount } = render(<TodayTopBarPanelTabs />)
+ expect(getByLabelText('Support')).toBeTruthy()
+
+ await expectLogic(sidepanelTicketsLogic).toFinishAllListeners()
+
+ expect(getTickets).not.toHaveBeenCalled()
+ unmount()
+ })
+
+ it.each([
+ ['the Today panel', TodaySupportPanel],
+ ['the side panel', SidePanelSupport],
+ ])('fetches from %s and keeps existing tickets reachable on a free plan', async (_case, Surface) => {
+ getTickets.mockResolvedValue({
+ results: [{ id: 't1', status: 'open', message_count: 1, created_at: '2026-07-13T00:00:00Z' }],
+ })
+ const { findByText, unmount } = render(<Surface />)
+
+ expect(await findByText('Your tickets')).toBeTruthy()
+ unmount()
+ })
+})
diff --git a/frontend/src/layout/today/TodayTopBarPanelTab.tsx b/frontend/src/layout/today/TodayTopBarPanelTab.tsx
index 33d919223c0b..832cf272fb56 100644
--- a/frontend/src/layout/today/TodayTopBarPanelTab.tsx
+++ b/frontend/src/layout/today/TodayTopBarPanelTab.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { ComponentType, useState } from 'react'
-import { IconPulse, IconSparkles } from '@posthog/icons'
+import { IconPulse, IconSparkles, IconSupport } from '@posthog/icons'
import { Button, Kbd, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'
import { sidePanelNotificationsLogic } from '~/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic'
@@ -10,9 +10,11 @@ import { SidePanelTab } from '~/types'
import { todayContextPanelLogic } from './todayContextPanelLogic'
-// The top bar's own icons where the side panel's would read wrong at this size.
+// The top bar's own icons where the side panel's would read wrong at this size. Support also stays static because the
+// side panel's icon reads the ticket logic for its unread count, and this bar renders on every page without live tickets.
const TODAY_TAB_ICONS: Partial<Record<SidePanelTab, ComponentType>> = {
[SidePanelTab.Max]: IconSparkles,
+ [SidePanelTab.Support]: IconSupport,
[SidePanelTab.Activity]: IconPulse,
}
diff --git a/frontend/src/layout/today/todayContextPanelLogic.test.ts b/frontend/src/layout/today/todayContextPanelLogic.test.ts
index 1d8986332a41..58aa8ae79b5e 100644
--- a/frontend/src/layout/today/todayContextPanelLogic.test.ts
+++ b/frontend/src/layout/today/todayContextPanelLogic.test.ts
@@ -1,6 +1,11 @@
+import { urls } from 'scenes/urls'
+
import { initKeaTests } from '~/test/init'
import { SidePanelTab } from '~/types'
+import { sidepanelTicketsLogic } from 'products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic'
+import { ConversationTicket } from 'products/conversations/frontend/types'
+
import { todayContextPanelLogic } from './todayContextPanelLogic'
describe('todayContextPanelLogic', () => {
@@ -16,6 +21,21 @@ describe('todayContextPanelLogic', () => {
logic.unmount()
})
+ it.each([
+ ['the tickets page', 'list', urls.myTickets()],
+ ['the open ticket', 'ticket', urls.myTickets('t1')],
+ ] as const)('links the Support tab full screen item to %s', (_case, view, expectedUrl) => {
+ const ticket = { id: 't1', status: 'open', message_count: 1, created_at: '2026-07-13T00:00:00Z' }
+ logic.actions.openSidePanel(SidePanelTab.Support)
+ expect(logic.values.fullScreenUrl).toBeNull()
+
+ sidepanelTicketsLogic.actions.setTickets([ticket as ConversationTicket])
+ if (view === 'ticket') {
+ sidepanelTicketsLogic.actions.setCurrentTicket(ticket as ConversationTicket)
+ }
+ expect(logic.values.fullScreenUrl).toBe(expectedUrl)
+ })
+
it('keeps the floating button away until the user undocks the panel', () => {
expect(logic.values.launcherHidden).toBe(true)
diff --git a/frontend/src/layout/today/todayContextPanelLogic.ts b/frontend/src/layout/today/todayContextPanelLogic.ts
index ef04ef786655..7799b73c4d14 100644
--- a/frontend/src/layout/today/todayContextPanelLogic.ts
+++ b/frontend/src/layout/today/todayContextPanelLogic.ts
@@ -10,7 +10,6 @@ import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePane
import { SidePanelTab } from '~/types'
import { sidepanelTicketsLogic } from 'products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic'
-import { ConversationTicket, SidePanelViewState } from 'products/conversations/frontend/types'
import { projectSessionKey, readSessionValue, writeSessionValue } from './todaySessionStorage'
import { todayShellLogic } from './todayShellLogic'
@@ -57,10 +56,8 @@ export interface todayContextPanelLogicValues {
enabledTabs: SidePanelTab[] // sidePanelLogic
selectedTab: SidePanelTab | null // sidePanelStateLogic
sidePanelOpen: boolean // sidePanelStateLogic
- canCreateTicket: boolean // sidepanelTicketsLogic
- currentTicket: ConversationTicket | null // sidepanelTicketsLogic
- supportView: SidePanelViewState // sidepanelTicketsLogic
- tickets: ConversationTicket[] // sidepanelTicketsLogic
+ canAccessTickets: boolean // sidepanelTicketsLogic
+ myTicketsUrl: string // sidepanelTicketsLogic
onAiPage: boolean // todayShellLogic
activeTab: SidePanelTab
canUndock: boolean
@@ -154,10 +151,8 @@ export interface todayContextPanelLogicMeta {
fullScreenUrl: (
activeTab: SidePanelTab,
selectedNotebook: string,
- tickets: ConversationTicket[],
- canCreateTicket: boolean,
- supportView: SidePanelViewState,
- currentTicket: ConversationTicket | null
+ canAccessTickets: boolean,
+ myTicketsUrl: string
) => string | null
}
}
@@ -184,7 +179,7 @@ export const todayContextPanelLogic = kea<todayContextPanelLogicType>([
notebookPanelLogic,
['selectedNotebook'],
sidepanelTicketsLogic,
- ['tickets', 'canCreateTicket', 'view as supportView', 'currentTicket'],
+ ['canAccessTickets', 'myTicketsUrl'],
todayShellLogic,
['onAiPage'],
],
@@ -322,25 +317,20 @@ export const todayContextPanelLogic = kea<todayContextPanelLogicType>([
],
fullScreenUrl: [
// PostHog AI's URL comes from the chat logic, which the header reads only while the panel is open.
- (s) => [s.activeTab, s.selectedNotebook, s.tickets, s.canCreateTicket, s.supportView, s.currentTicket],
+ (s) => [s.activeTab, s.selectedNotebook, s.canAccessTickets, s.myTicketsUrl],
(
activeTab: SidePanelTab,
selectedNotebook: string,
- tickets: ConversationTicket[],
- canCreateTicket: boolean,
- supportView: SidePanelViewState,
- currentTicket: ConversationTicket | null
+ canAccessTickets: boolean,
+ myTicketsUrl: string
): string | null => {
switch (activeTab) {
case SidePanelTab.Activity:
return urls.advancedActivityLogs()
case SidePanelTab.Notebooks:
return urls.notebook(selectedNotebook)
- // Matches the support panel's own expand button: the tickets page, on the open ticket if any.
case SidePanelTab.Support:
- return canCreateTicket || tickets.length > 0
- ? urls.myTickets(supportView === 'ticket' ? currentTicket?.id : undefined)
- : null
+ return canAccessTickets ? myTicketsUrl : null
default:
return null
}
diff --git a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.ts b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.ts
index d958b9aac6e0..cf4c910a1a81 100644
--- a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.ts
+++ b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.ts
@@ -14,7 +14,7 @@ import { initKeaTests } from '~/test/init'
import { BillingType, SidePanelTab } from '~/types'
import type { ConversationTicket } from '../../types'
-import { sidepanelTicketsLogic } from './sidepanelTicketsLogic'
+import { liveTicketsLogic, sidepanelTicketsLogic } from './sidepanelTicketsLogic'
import { loadTicketsAcrossTabs } from './ticketsAcrossTabs'
jest.mock('./ticketsAcrossTabs', () => ({
@@ -24,6 +24,22 @@ jest.mock('./ticketsAcrossTabs', () => ({
describe('sidepanelTicketsLogic', () => {
let logic: ReturnType<typeof sidepanelTicketsLogic.build>
+ let unmountLive: (() => void) | undefined
+
+ const mountLive = (): void => {
+ logic = sidepanelTicketsLogic.build()
+ logic.mount()
+ unmountLive = liveTicketsLogic.mount()
+ }
+
+ const mountSurface = (onSupportSurface: boolean): void => {
+ if (onSupportSurface) {
+ mountLive()
+ } else {
+ logic = sidepanelTicketsLogic.build()
+ logic.mount()
+ }
+ }
const setSubscriptionLevel = (subscriptionLevel: BillingType['subscription_level']): void => {
billingLogic.actions.loadBillingSuccess({ subscription_level: subscriptionLevel } as BillingType)
@@ -48,6 +64,8 @@ describe('sidepanelTicketsLogic', () => {
})
afterEach(() => {
+ unmountLive?.()
+ unmountLive = undefined
logic?.unmount()
delete (posthog as any).conversations
})
@@ -341,8 +359,7 @@ describe('sidepanelTicketsLogic', () => {
})
router.actions.push(urls.myTickets(linkedId))
- logic = sidepanelTicketsLogic.build()
- logic.mount()
+ mountLive()
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.view).toBe(expectedView)
@@ -361,8 +378,7 @@ describe('sidepanelTicketsLogic', () => {
sidePanelStateLogic.mount()
sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Support, 'ticket:t2')
- logic = sidepanelTicketsLogic.build()
- logic.mount()
+ mountLive()
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.view).toBe('ticket')
@@ -414,22 +430,16 @@ describe('sidepanelTicketsLogic', () => {
})
// The panel already shows free plans the community and upgrade options, and they have no email
- // channel, so warning them the chat failed would offer support they don't actually get. The
- // unread badge also mounts this logic on every page, so outside a support surface the toast
- // would interrupt unrelated work (and block clicks under the toast container) for anyone whose
+ // channel, so warning them the chat failed would offer support they don't actually get. A
+ // forced load can also run with no support surface open, and there the toast would interrupt unrelated work (and block clicks under the toast container) for anyone whose
// ad blocker keeps the widget from loading.
it.each([
['warns an entitled plan on the support panel', 'paid', true, true],
['stays quiet on a free plan', 'free', true, false],
['stays quiet outside support surfaces', 'paid', false, false],
- ])('when the widget never loads, %s', async (_case, subscriptionLevel, onSupportPanel, expectWarning) => {
+ ])('when the widget never loads, %s', async (_case, subscriptionLevel, onSupportSurface, expectWarning) => {
const errorToast = jest.spyOn(lemonToast, 'error').mockReturnValue('' as never)
- if (onSupportPanel) {
- sidePanelStateLogic.mount()
- sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Support)
- }
- logic = sidepanelTicketsLogic.build()
- logic.mount()
+ mountSurface(onSupportSurface as boolean)
await expectLogic(logic).toFinishAllListeners()
// After the mount, so the fixture loads don't put the paid plan back. canCreateTicket also
@@ -447,7 +457,7 @@ describe('sidepanelTicketsLogic', () => {
;(posthog.capture as jest.Mock).mockClear()
await expectLogic(logic, () => {
- logic.actions.loadTickets()
+ logic.actions.loadTickets(true)
}).toFinishAllListeners()
// Recorded either way, so the failure rate stays visible even where we don't interrupt
@@ -460,27 +470,22 @@ describe('sidepanelTicketsLogic', () => {
errorToast.mockRestore()
})
- // The unread badge keeps this logic polling on every page, so a failed background fetch must
- // not toast over unrelated work. It is still captured so the failure rate stays visible.
+ // A forced load can run with no support surface open, so a failure must not toast over unrelated
+ // work. It is still captured so the failure rate stays visible.
it.each([
['toasts on the support panel', true, 1],
['stays quiet outside support surfaces', false, 0],
- ])('when fetching tickets fails, %s', async (_case, onSupportPanel, expectedToasts) => {
+ ])('when fetching tickets fails, %s', async (_case, onSupportSurface, expectedToasts) => {
const errorToast = jest.spyOn(lemonToast, 'error').mockReturnValue('' as never)
jest.spyOn(console, 'error').mockImplementation(() => {})
- if (onSupportPanel) {
- sidePanelStateLogic.mount()
- sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Support)
- }
- logic = sidepanelTicketsLogic.build()
- logic.mount()
+ mountSurface(onSupportSurface as boolean)
await expectLogic(logic).toFinishAllListeners()
;(posthog as any).conversations.getTickets = jest.fn().mockRejectedValue(new Error('429'))
;(posthog.capture as jest.Mock).mockClear()
await expectLogic(logic, () => {
- logic.actions.loadTickets()
+ logic.actions.loadTickets(true)
}).toFinishAllListeners()
const loadFailures = (posthog.capture as jest.Mock).mock.calls.filter(
@@ -562,6 +567,140 @@ describe('sidepanelTicketsLogic', () => {
})
})
+ describe('live tickets', () => {
+ const oneTicket = {
+ results: [{ id: 't1', status: 'open', message_count: 1, created_at: '2026-07-13T00:00:00Z' }],
+ }
+ const setPageVisibility = (state: DocumentVisibilityState): void => {
+ jest.spyOn(document, 'visibilityState', 'get').mockReturnValue(state)
+ jest.spyOn(document, 'hidden', 'get').mockReturnValue(state === 'hidden')
+ document.dispatchEvent(new Event('visibilitychange'))
+ }
+
+ afterEach(() => {
+ jest.useRealTimers()
+ jest.restoreAllMocks()
+ })
+
+ it('does not fetch for a reader, including when a side panel tab opens', async () => {
+ sidePanelStateLogic.mount()
+ logic = sidepanelTicketsLogic.build()
+ logic.mount()
+ await expectLogic(logic, () => {
+ sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Activity)
+ sidePanelStateLogic.actions.closeSidePanel()
+ }).toFinishAllListeners()
+
+ expect((posthog as any).conversations.getTickets).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ['the ticket list', false, 20 * 1000],
+ ['an open thread', true, 10 * 1000],
+ ])('polls %s at its own cadence', async (_case, insideThread, interval) => {
+ jest.useFakeTimers()
+ const getTickets = jest.fn().mockResolvedValue(oneTicket)
+ ;(posthog as any).conversations.getTickets = getTickets
+ mountLive()
+ await jest.advanceTimersByTimeAsync(0)
+ if (insideThread) {
+ logic.actions.setCurrentTicket(oneTicket.results[0] as ConversationTicket)
+ }
+ getTickets.mockClear()
+
+ await jest.advanceTimersByTimeAsync(interval - 1)
+ expect(getTickets).not.toHaveBeenCalled()
+ await jest.advanceTimersByTimeAsync(1)
+ expect(getTickets).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not resume polling when a load finishes after the surface unmounts', async () => {
+ jest.useFakeTimers()
+ let resolveTickets!: (value: typeof oneTicket) => void
+ const getTickets = jest.fn().mockReturnValue(
+ new Promise((resolve) => {
+ resolveTickets = resolve
+ })
+ )
+ ;(posthog as any).conversations.getTickets = getTickets
+ mountLive()
+ unmountLive?.()
+ unmountLive = undefined
+
+ resolveTickets(oneTicket)
+ await jest.advanceTimersByTimeAsync(0)
+ expect(logic.values.tickets).toHaveLength(1)
+
+ await jest.advanceTimersByTimeAsync(5 * 60 * 1000)
+ expect(getTickets).toHaveBeenCalledTimes(1)
+ })
+
+ it('refreshes when the tab returns and stops polling while it is hidden', async () => {
+ jest.useFakeTimers()
+ const getTickets = jest.fn().mockResolvedValue(oneTicket)
+ ;(posthog as any).conversations.getTickets = getTickets
+ mountLive()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(getTickets).toHaveBeenCalledTimes(1)
+
+ setPageVisibility('hidden')
+ await jest.advanceTimersByTimeAsync(5 * 60 * 1000)
+ expect(getTickets).toHaveBeenCalledTimes(1)
+
+ setPageVisibility('visible')
+ await jest.advanceTimersByTimeAsync(0)
+ expect(getTickets).toHaveBeenCalledTimes(2)
+ })
+
+ it.each([true, false])(
+ 'waits for token restoration before fetching with widget available=%s',
+ async (available) => {
+ jest.useFakeTimers()
+ let finishRestore!: () => void
+ const restoreFromToken = jest.fn().mockReturnValue(
+ new Promise<void>((resolve) => {
+ finishRestore = resolve
+ })
+ )
+ const getTickets = jest.fn().mockResolvedValue(oneTicket)
+ const isAvailable = jest.fn().mockReturnValue(available)
+ ;(posthog as any).conversations = { isAvailable, restoreFromToken, getTickets }
+ router.actions.push('/', { ph_conv_restore: 'token' })
+
+ mountLive()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(getTickets).not.toHaveBeenCalled()
+ isAvailable.mockReturnValue(true)
+ await jest.advanceTimersByTimeAsync(500)
+ expect(restoreFromToken).toHaveBeenCalledTimes(1)
+ logic.actions.loadTickets()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(getTickets).not.toHaveBeenCalled()
+
+ finishRestore()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(getTickets).toHaveBeenCalledTimes(1)
+ expect(logic.values.tickets).toHaveLength(1)
+ await jest.advanceTimersByTimeAsync(20_000)
+ expect(getTickets).toHaveBeenCalledTimes(2)
+ }
+ )
+
+ it('consumes a restore link with no support surface open, then loads the restored tickets', async () => {
+ const restoreFromToken = jest.fn().mockResolvedValue({ status: 'success', migrated_ticket_ids: ['t1'] })
+ ;(posthog as any).conversations.restoreFromToken = restoreFromToken
+ ;(posthog as any).conversations.getTickets = jest.fn().mockResolvedValue(oneTicket)
+ router.actions.push('/', { ph_conv_restore: 'token' })
+
+ logic = sidepanelTicketsLogic.build()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(restoreFromToken).toHaveBeenCalledWith('token')
+ expect(logic.values.tickets).toHaveLength(1)
+ })
+ })
+
// ticketsLoading drives a full-list spinner. Polls reuse loadTickets, so only the first
// successful fetch may raise it, including a 0-ticket result that would otherwise flash
// the spinner over the empty state on every refresh.
@@ -573,8 +712,7 @@ describe('sidepanelTicketsLogic', () => {
})
)
- logic = sidepanelTicketsLogic.build()
- logic.mount()
+ mountLive()
expect(logic.values.ticketsLoading).toBe(true)
resolveTickets({ results: [] })
@@ -595,8 +733,7 @@ describe('sidepanelTicketsLogic', () => {
})
it('does not raise ticketsLoading when tickets are already loaded', async () => {
- logic = sidepanelTicketsLogic.build()
- logic.mount()
+ mountLive()
await expectLogic(logic).toFinishAllListeners()
const ticket = {
diff --git a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts
index 66dd15f6f9c1..126473cf41b7 100644
--- a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts
+++ b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts
@@ -65,24 +65,13 @@ 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 without every idle tab hammering the widget once a minute.
-const POLL_INTERVAL_BACKGROUND = 60 * 1000 // support surface not visible: only keep the unread badge fresh
+// 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:'
-// True when the person can actually see support: the side panel open on the Support tab, or the
-// full-screen tickets scene. Reads the live router so callers don't have to thread the pathname in.
-function isOnSupportSurface(sidePanelOpen: boolean, selectedTab: SidePanelTab | null): boolean {
- return (
- (sidePanelOpen && selectedTab === SidePanelTab.Support) ||
- removeProjectIdIfPresent(router.values.location.pathname) === urls.myTickets()
- )
-}
-
function removeRestoreTokenFromUrl(): void {
if ('ph_conv_restore' in router.values.searchParams) {
const { ph_conv_restore: _, ...rest } = router.values.searchParams
@@ -119,6 +108,7 @@ export interface sidepanelTicketsLogicValues {
status: string
} | null // supportLogic
sendSupportRequest: SupportFormFields // supportLogic
+ canAccessTickets: boolean
canCreateTicket: boolean
currentTicket: ConversationTicket | null
effectiveStatusFilter: SidePanelTicketFilter
@@ -129,6 +119,7 @@ export interface sidepanelTicketsLogicValues {
messageSending: boolean
messages: ChatMessage[]
messagesLoading: boolean
+ myTicketsUrl: string
newTicketContext: string | null
newTicketDraft: JSONContent | null
newTicketDraftRevision: number
@@ -139,6 +130,7 @@ export interface sidepanelTicketsLogicValues {
ticketFilterCounts: Record<SidePanelTicketFilter, number>
tickets: ConversationTicket[]
ticketsLoading: boolean
+ ticketsRequestsInFlight: number
totalUnreadCount: number
view: SidePanelViewState
}
@@ -172,10 +164,10 @@ export interface sidepanelTicketsLogicActions {
preserveLocation: any
reason: string | undefined
} // userLogic
- grantSupportExemption: () => {
+ finishTicketsFetch: () => {
value: true
}
- initTickets: () => {
+ grantSupportExemption: () => {
value: true
}
loadMessages: (ticketId: string) => {
@@ -248,13 +240,10 @@ export interface sidepanelTicketsLogicActions {
setView: (view: SidePanelViewState) => {
view: SidePanelViewState
}
- startPolling: () => {
- value: true
- }
startTicketFromSupportForm: () => {
value: true
}
- stopPolling: () => {
+ startTicketsFetch: () => {
value: true
}
}
@@ -282,6 +271,8 @@ export interface sidepanelTicketsLogicMeta {
isErrorReport: boolean
) => boolean
isBillingResolved: (billing: BillingType | null, billingLoading: boolean) => boolean
+ canAccessTickets: (canCreateTicket: boolean, tickets: ConversationTicket[]) => boolean
+ myTicketsUrl: (view: SidePanelViewState, currentTicket: ConversationTicket | null) => string
}
}
@@ -318,15 +309,14 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
})),
actions({
grantSupportExemption: true,
- initTickets: true,
loadTickets: (force: boolean = false) => ({ force }),
- startPolling: true,
- stopPolling: true,
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 }),
@@ -370,6 +360,13 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
setHasMoreMessages: (_, { hasMore }) => hasMore,
},
],
+ ticketsRequestsInFlight: [
+ 0,
+ {
+ startTicketsFetch: (state) => state + 1,
+ finishTicketsFetch: (state) => state - 1,
+ },
+ ],
ticketsLoading: [
false,
{
@@ -553,36 +550,26 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
(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()
},
- initTickets: () => {
- if (cache.initialized) {
+ loadTickets: async ({ force }) => {
+ if (cache.restoringFromUrlToken) {
return
}
- cache.initialized = true
-
- const restoreToken = router.values.searchParams['ph_conv_restore']
- if (restoreToken) {
- actions.restoreFromUrlToken(restoreToken)
- } else {
- actions.loadTickets()
- }
-
- if (!cache.onVisibilityChange) {
- cache.onVisibilityChange = (): void => {
- if (document.visibilityState === 'visible') {
- actions.loadTickets()
- } else {
- actions.stopPolling()
- }
- }
- document.addEventListener('visibilitychange', cache.onVisibilityChange)
- }
- },
- loadTickets: async ({ force }) => {
// 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
@@ -619,19 +606,17 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
can_create_ticket: values.canCreateTicket,
})
}
- // This logic also mounts from the panel bar's unread badge, which renders on every
- // 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.
- const onSupportSurface = isOnSupportSurface(values.sidePanelOpen, values.selectedTab)
+ // 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 &&
- onSupportSurface &&
+ liveTicketsLogic.isMounted() &&
(values.canCreateTicket || !values.isBillingResolved)
) {
cache.conversationsUnavailableWarned = true
@@ -645,6 +630,8 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
if (!cache.ticketsFetched) {
actions.setTicketsLoading(true)
}
+ actions.startTicketsFetch()
+ const requestDisposables = cache.disposables
try {
const tickets = await loadTicketsAcrossTabs(
async () => {
@@ -653,16 +640,9 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
},
{ force, maxAgeMs: POLL_INTERVAL_THREAD }
)
- if (tickets) {
+ if (tickets && !requestDisposables.isDisposed) {
cache.ticketsFetched = true
actions.setTickets(tickets)
- // With no tickets there's nothing to poll for; creating one re-runs loadTickets
- // and restarts polling. Otherwise (re)schedule at the cadence startPolling picks.
- if (tickets.length > 0) {
- actions.startPolling()
- } else {
- actions.stopPolling()
- }
}
} catch (e) {
console.error('Failed to load tickets:', e)
@@ -674,59 +654,16 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
error: e,
can_create_ticket: values.canCreateTicket,
})
- // The background poll for the unread badge runs on every page, so a transient
- // failure there would toast on surfaces that have nothing to do with support
- if (isOnSupportSurface(values.sidePanelOpen, values.selectedTab)) {
+ // 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 {
- actions.setTicketsLoading(false)
- }
- },
- startPolling: () => {
- // Only poll while the page is visible
- if (document.visibilityState !== 'visible') {
- return
- }
- // Nothing to poll for until the user has at least one ticket. Creating one re-runs
- // loadTickets, which restarts polling from there.
- if (values.tickets.length === 0) {
- actions.stopPolling()
- return
- }
- // Clear any existing poll timer
- if (cache.pollTimer) {
- clearTimeout(cache.pollTimer)
- }
- const onSupportSurface = isOnSupportSurface(values.sidePanelOpen, values.selectedTab)
- // Only treat a thread as open when the surface showing it is actually visible — the logic
- // stays mounted for the panel-bar unread badge, so `view` can still be 'ticket' for a
- // panel the user has since closed.
- const insideTicket = onSupportSurface && values.view === 'ticket' && !!values.currentTicket
- const interval = insideTicket
- ? POLL_INTERVAL_THREAD
- : onSupportSurface
- ? POLL_INTERVAL_ACTIVE
- : POLL_INTERVAL_BACKGROUND
- cache.pollTimer = window.setTimeout(() => {
- actions.loadTickets()
- // loadTickets only refreshes the list, so a support reply wouldn't appear while the
- // reader sits inside the thread. Re-check on fire in case they've since navigated away,
- // and skip when a load is already running so a slow fetch can't overlap this one.
- if (
- values.currentTicket &&
- values.view === 'ticket' &&
- !values.messagesLoading &&
- isOnSupportSurface(values.sidePanelOpen, values.selectedTab)
- ) {
- actions.loadMessages(values.currentTicket.id)
+ if (!requestDisposables.isDisposed) {
+ actions.finishTicketsFetch()
+ actions.setTicketsLoading(false)
}
- }, interval)
- },
- stopPolling: () => {
- if (cache.pollTimer) {
- clearTimeout(cache.pollTimer)
- cache.pollTimer = null
}
},
loadMessages: async ({ ticketId }) => {
@@ -877,8 +814,6 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
if (values.sidePanelOpen && values.selectedTab === SidePanelTab.Support) {
actions.setSidePanelOptions(`${TICKET_OPTIONS_PREFIX}${ticket.id}`)
}
- // Cadence is bumped to the thread rate by the setView('ticket') dispatched above, so no
- // startPolling here — it would just reschedule the same timer a second time.
},
setView: ({ view }) => {
// Only clear our own format; other option strings belong to the support form
@@ -890,8 +825,6 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
) {
actions.setSidePanelOptions(null)
}
- // Leaving a thread (back to the list or composer) drops polling back to the slower cadence.
- actions.startPolling()
},
openTicketById: ({ ticketId }) => {
if (values.view === 'ticket' && values.currentTicket?.id === ticketId) {
@@ -1009,6 +942,7 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
}
},
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
@@ -1019,6 +953,7 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
cache.restoreRetryTimer = window.setTimeout(() => actions.restoreFromUrlToken(token), 500)
} else {
removeRestoreTokenFromUrl()
+ cache.restoringFromUrlToken = false
actions.loadTickets(true)
}
return
@@ -1042,6 +977,7 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
console.error('Failed to restore from URL token:', e)
} finally {
removeRestoreTokenFromUrl()
+ cache.restoringFromUrlToken = false
actions.loadTickets(true)
}
},
@@ -1089,22 +1025,6 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
actions.openTicketById(options.slice(TICKET_OPTIONS_PREFIX.length))
}
},
- sidePanelOpen: (open: boolean) => {
- if (open) {
- // A fresh fetch on open; loadTickets reschedules polling at the active cadence.
- actions.loadTickets()
- } else {
- // Closing doesn't fetch (nothing renders the result), but polling drops to the slow
- // background cadence — or stops if there are no tickets.
- actions.startPolling()
- }
- },
- selectedTab: () => {
- // Switching tabs inside an already-open panel changes the support surface without
- // touching sidePanelOpen, so re-evaluate the cadence — otherwise the timer keeps its
- // previous interval until it next fires (e.g. entering Support still polls at 60s).
- actions.startPolling()
- },
isEmailFormOpen: (open: boolean) => {
if (open) {
actions.startTicketFromSupportForm()
@@ -1116,20 +1036,20 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
}
},
})),
- beforeUnmount(({ actions, cache }) => {
- actions.stopPolling()
+ beforeUnmount(({ cache }) => {
if (cache.conversationsRetryTimer) {
clearTimeout(cache.conversationsRetryTimer)
}
if (cache.restoreRetryTimer) {
clearTimeout(cache.restoreRetryTimer)
}
- if (cache.onVisibilityChange) {
- document.removeEventListener('visibilitychange', cache.onVisibilityChange)
- }
}),
afterMount(({ values, actions }) => {
- actions.initTickets()
+ // 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.
@@ -1147,3 +1067,84 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
}
}),
])
+
+// 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')
+ }),
+])
diff --git a/products/conversations/frontend/scenes/myTickets/MyTicketsScene.tsx b/products/conversations/frontend/scenes/myTickets/MyTicketsScene.tsx
index c17593c15dbb..cb9dfb671ca3 100644
--- a/products/conversations/frontend/scenes/myTickets/MyTicketsScene.tsx
+++ b/products/conversations/frontend/scenes/myTickets/MyTicketsScene.tsx
@@ -15,9 +15,6 @@ import { Ticket } from '../../components/SidePanel/Ticket'
import { TicketsList } from '../../components/SidePanel/TicketsList'
import { myTicketsSceneLogic } from './myTicketsSceneLogic'
-// myTicketsSceneLogic rather than sidepanelTicketsLogic directly: the tickets logic never unmounts
-// (the side panel tab icon keeps it alive), so only a scene-scoped logic gets a fresh mount, and
-// with it a ticket refetch, on each navigation here
export const scene: SceneExport = {
component: MyTicketsScene,
logic: myTicketsSceneLogic,
diff --git a/products/conversations/frontend/scenes/myTickets/myTicketsSceneLogic.test.ts b/products/conversations/frontend/scenes/myTickets/myTicketsSceneLogic.test.ts
index aa6881370339..0af60ca0b195 100644
--- a/products/conversations/frontend/scenes/myTickets/myTicketsSceneLogic.test.ts
+++ b/products/conversations/frontend/scenes/myTickets/myTicketsSceneLogic.test.ts
@@ -1,14 +1,20 @@
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+
import { initKeaTests } from '~/test/init'
-import { sidepanelTicketsLogic } from '../../components/SidePanel/sidepanelTicketsLogic'
+import { liveTicketsLogic, sidepanelTicketsLogic } from '../../components/SidePanel/sidepanelTicketsLogic'
import { myTicketsSceneLogic } from './myTicketsSceneLogic'
+jest.mock('../../components/SidePanel/ticketsAcrossTabs', () => ({
+ loadTicketsAcrossTabs: jest.fn((fetchTickets) => fetchTickets()),
+ clearSharedTickets: jest.fn(),
+}))
+
describe('myTicketsSceneLogic', () => {
beforeEach(() => {
- localStorage.clear()
initKeaTests()
;(posthog as any).conversations = {
isAvailable: () => true,
@@ -17,31 +23,147 @@ describe('myTicketsSceneLogic', () => {
})
afterEach(() => {
+ jest.useRealTimers()
jest.restoreAllMocks()
delete (posthog as any).conversations
})
- // The tickets logic stays mounted for the whole session via the side panel tab icon, so its own
- // boot-time load never re-runs. Without the scene-mount refetch, navigating to /my-tickets shows
- // whatever the boot-time load returned (often nothing) until a full page reload.
- it('refetches tickets when the scene mounts while the tickets logic is already mounted', async () => {
+ it.each([
+ [false, 'old first'],
+ [true, 'old first'],
+ [false, 'new first'],
+ [true, 'new first'],
+ [false, 'old rejection'],
+ [true, 'old rejection'],
+ ])('keeps requests scoped to their mount with reused logic=%s and %s', async (reuseLogic, completion) => {
+ jest.useFakeTimers()
+ jest.spyOn(console, 'error').mockImplementation(() => {})
+ const toastError = jest.spyOn(lemonToast, 'error')
+ const getTickets = (posthog as any).conversations.getTickets as jest.Mock
+ const oldResponse = {
+ results: [{ id: 'old-ticket', status: 'open', message_count: 1, created_at: '2026-07-21T00:00:00Z' }],
+ }
+ const newResponse = { results: [{ ...oldResponse.results[0], id: 'new-ticket' }] }
+ let finishOld!: (response: typeof oldResponse) => void
+ let rejectOld!: (error: Error) => void
+ let finishNew!: (response: typeof newResponse) => void
+ getTickets
+ .mockReturnValueOnce(
+ new Promise<typeof oldResponse>((resolve, reject) => {
+ finishOld = resolve
+ rejectOld = reject
+ })
+ )
+ .mockReturnValueOnce(
+ new Promise<typeof newResponse>((resolve) => {
+ finishNew = resolve
+ })
+ )
+ const oldTicketsLogic = sidepanelTicketsLogic.build()
+ oldTicketsLogic.mount()
+ const unmountOldSupport = liveTicketsLogic.mount()
+ unmountOldSupport()
+ oldTicketsLogic.unmount()
+
+ const newTicketsLogic = reuseLogic ? oldTicketsLogic : sidepanelTicketsLogic.build()
+ newTicketsLogic.mount()
+ const unmountNewSupport = liveTicketsLogic.mount()
+ if (completion === 'new first') {
+ finishNew(newResponse)
+ await jest.advanceTimersByTimeAsync(0)
+ }
+ if (completion === 'old rejection') {
+ rejectOld(new Error('old request failed'))
+ } else {
+ finishOld(oldResponse)
+ }
+ await jest.advanceTimersByTimeAsync(0)
+ expect(newTicketsLogic.values.tickets).toEqual(completion === 'new first' ? newResponse.results : [])
+ expect(newTicketsLogic.values.ticketsRequestsInFlight).toBe(completion === 'new first' ? 0 : 1)
+ expect(newTicketsLogic.values.ticketsLoading).toBe(completion !== 'new first')
+ expect(toastError).not.toHaveBeenCalled()
+ getTickets.mockClear()
+ const sceneLogic = myTicketsSceneLogic.build()
+ sceneLogic.mount()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(getTickets).toHaveBeenCalledTimes(completion === 'new first' ? 1 : 0)
+
+ finishNew(newResponse)
+ await jest.advanceTimersByTimeAsync(0)
+ sceneLogic.unmount()
+ unmountNewSupport()
+ newTicketsLogic.unmount()
+ })
+
+ it('does not add a scene request while a second forced request is still pending', async () => {
+ jest.useFakeTimers()
const ticketsLogic = sidepanelTicketsLogic.build()
ticketsLogic.mount()
- await expectLogic(ticketsLogic).toFinishAllListeners()
+ const unmountSupport = liveTicketsLogic.mount()
+ await jest.advanceTimersByTimeAsync(0)
+ const getTickets = (posthog as any).conversations.getTickets as jest.Mock
+ let finishFirst!: () => void
+ let finishSecond!: () => void
+ getTickets
+ .mockReturnValueOnce(
+ new Promise<void>((resolve) => {
+ finishFirst = resolve
+ })
+ )
+ .mockReturnValueOnce(
+ new Promise<void>((resolve) => {
+ finishSecond = resolve
+ })
+ )
+ ticketsLogic.actions.loadTickets(true)
+ ticketsLogic.actions.loadTickets(true)
+
+ finishFirst()
+ await jest.advanceTimersByTimeAsync(0)
+ getTickets.mockClear()
+ const sceneLogic = myTicketsSceneLogic.build()
+ sceneLogic.mount()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(getTickets).not.toHaveBeenCalled()
+ finishSecond()
+ await jest.advanceTimersByTimeAsync(0)
+ sceneLogic.unmount()
+ unmountSupport()
+ ticketsLogic.unmount()
+ })
+
+ it.each([
+ ['cold mount', false, false],
+ ['retry after a panel failure', true, false],
+ ['return after an earlier successful load', false, true],
+ ])('loads tickets once on %s', async (_case, supportOpen, primed) => {
+ const ticketsLogic = sidepanelTicketsLogic.build()
+ ticketsLogic.mount()
const getTickets = (posthog as any).conversations.getTickets as jest.Mock
- const callsAtBoot = getTickets.mock.calls.length
- expect(callsAtBoot).toBeGreaterThan(0)
+ let unmountSupport: (() => void) | undefined
+ if (primed) {
+ const unmountPrevious = liveTicketsLogic.mount()
+ await expectLogic(ticketsLogic).toFinishAllListeners()
+ unmountPrevious()
+ getTickets.mockClear()
+ }
+ if (supportOpen) {
+ jest.spyOn(console, 'error').mockImplementation(() => {})
+ getTickets.mockRejectedValueOnce(new Error('unavailable'))
+ unmountSupport = liveTicketsLogic.mount()
+ await expectLogic(ticketsLogic).toFinishAllListeners()
+ getTickets.mockClear()
+ }
- const bootTime = Date.now()
- jest.spyOn(Date, 'now').mockReturnValue(bootTime + 60_000)
const sceneLogic = myTicketsSceneLogic.build()
sceneLogic.mount()
await expectLogic(ticketsLogic).toFinishAllListeners()
- expect(getTickets.mock.calls.length).toBe(callsAtBoot + 1)
-
+ expect(getTickets).toHaveBeenCalledTimes(1)
+ expect(liveTicketsLogic.isMounted()).toBe(true)
sceneLogic.unmount()
+ unmountSupport?.()
ticketsLogic.unmount()
})
})
diff --git a/products/conversations/frontend/scenes/myTickets/myTicketsSceneLogic.ts b/products/conversations/frontend/scenes/myTickets/myTicketsSceneLogic.ts
index 6af5a25af8db..617d5aae54ce 100644
--- a/products/conversations/frontend/scenes/myTickets/myTicketsSceneLogic.ts
+++ b/products/conversations/frontend/scenes/myTickets/myTicketsSceneLogic.ts
@@ -1,26 +1,30 @@
import { MakeLogicType, afterMount, connect, kea, path } from 'kea'
-import { sidepanelTicketsLogic } from '../../components/SidePanel/sidepanelTicketsLogic'
+import { liveTicketsLogic, sidepanelTicketsLogic } from '../../components/SidePanel/sidepanelTicketsLogic'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface myTicketsSceneLogicValues {
+ ticketsRequestsInFlight: number // sidepanelTicketsLogic
+}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface myTicketsSceneLogicActions {
loadTickets: (force?: boolean | undefined) => {
force: boolean
- } // sidepanelTicketsLogic
+ } // liveTicketsLogic
}
-export type myTicketsSceneLogicType = MakeLogicType<{}, myTicketsSceneLogicActions>
+export type myTicketsSceneLogicType = MakeLogicType<myTicketsSceneLogicValues, myTicketsSceneLogicActions>
-// sidepanelTicketsLogic stays mounted for the whole session (the side panel tab icon reads its
-// unread count), so its own initial load runs once at app boot and never again. This scene-scoped
-// logic exists to refetch on every navigation to the tickets scene, the same way the side panel
-// refetches each time it opens.
export const myTicketsSceneLogic = kea<myTicketsSceneLogicType>([
path(['products', 'conversations', 'frontend', 'scenes', 'myTickets', 'myTicketsSceneLogic']),
connect(() => ({
- actions: [sidepanelTicketsLogic, ['loadTickets']],
+ values: [sidepanelTicketsLogic, ['ticketsRequestsInFlight']],
+ actions: [liveTicketsLogic, ['loadTickets']],
})),
- afterMount(({ actions }) => {
- actions.loadTickets()
+ afterMount(({ actions, values }) => {
+ if (values.ticketsRequestsInFlight === 0) {
+ actions.loadTickets()
+ }
}),
])