:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(conversations): share the tickets poll across browser tabs (#125574)
Paul D'Ambrab9bdee65f40f
diff --git a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.ts b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.tsindex 5e20651c12a9..2cdd85dcfcf6 100644--- a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.ts+++ b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.ts@@ -15,6 +15,12 @@ import { BillingType, SidePanelTab } from '~/types'import type { ConversationTicket } from '../../types'import { sidepanelTicketsLogic } from './sidepanelTicketsLogic'+import { loadTicketsAcrossTabs } from './ticketsAcrossTabs'++jest.mock('./ticketsAcrossTabs', () => ({+ loadTicketsAcrossTabs: jest.fn((fetchTickets) => fetchTickets()),+ clearSharedTickets: jest.fn(),+}))describe('sidepanelTicketsLogic', () => {let logic: ReturnType<typeof sidepanelTicketsLogic.build>@@ -90,6 +96,11 @@ describe('sidepanelTicketsLogic', () => {{},true)+ // The new ticket must show up now, so it skips the shared freshness window+ expect(loadTicketsAcrossTabs).toHaveBeenLastCalledWith(+ expect.any(Function),+ expect.objectContaining({ force: true })+ )// Leaving the composer clears the prefill so a later blank "New ticket" starts emptylogic.actions.setView('list')diff --git a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.tsindex 6b7b6c1765f3..dde7d04eae9c 100644--- a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts+++ b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts@@ -31,6 +31,7 @@ import { billingLogic } from 'scenes/billing/billingLogic'import { organizationLogic } from 'scenes/organizationLogic'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { type BillingType, SidePanelTab } from '~/types'@@ -44,6 +45,7 @@ import type {SidePanelTicketFilter,SidePanelViewState,} from '../../types'+import { clearSharedTickets, loadTicketsAcrossTabs } from './ticketsAcrossTabs'function ticketMatchesFilter(ticket: ConversationTicket, filter: SidePanelTicketFilter): boolean {switch (filter) {@@ -161,6 +163,15 @@ export interface sidepanelTicketsLogicActions {resetSendSupportRequest: (values?: SupportFormFields | undefined) => {values?: SupportFormFields} // supportLogic+ logout: (+ preserveLocation?: any,+ nextUrl?: string | undefined,+ reason?: string | undefined+ ) => {+ nextUrl: string | undefined+ preserveLocation: any+ reason: string | undefined+ } // userLogicgrantSupportExemption: () => {value: true}@@ -170,8 +181,8 @@ export interface sidepanelTicketsLogicActions {loadMessages: (ticketId: string) => {ticketId: string}- loadTickets: () => {- value: true+ loadTickets: (force?: boolean) => {+ force: boolean}markAsRead: (ticketId: string) => {ticketId: string@@ -301,12 +312,14 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([['closeEmailForm', 'closeSupportForm', 'clearPendingViewTicket', 'resetSendSupportRequest'],sidePanelStateLogic,['closeSidePanel', 'setSidePanelOptions'],+ userLogic,+ ['logout'],],})),actions({grantSupportExemption: true,initTickets: true,- loadTickets: true,+ loadTickets: (force: boolean = false) => ({ force }),startPolling: true,stopPolling: true,setTickets: (tickets: ConversationTicket[]) => ({ tickets }),@@ -542,6 +555,9 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([],}),listeners(({ actions, values, cache }) => ({+ logout: () => {+ clearSharedTickets()+ },initTickets: () => {if (cache.initialized) {return@@ -566,7 +582,7 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([document.addEventListener('visibilitychange', cache.onVisibilityChange)}},- loadTickets: async () => {+ 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@@ -590,7 +606,7 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([// Conversations extension loads lazily — retry until it's readyif ((cache.conversationsRetries ?? 0) < 20) {cache.conversationsRetries = (cache.conversationsRetries ?? 0) + 1- cache.conversationsRetryTimer = window.setTimeout(() => actions.loadTickets(), 500)+ cache.conversationsRetryTimer = window.setTimeout(() => actions.loadTickets(force), 500)return}// Out of retries. Kept separate from the send-failure event because nothing was@@ -630,13 +646,19 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([actions.setTicketsLoading(true)}try {- const response = await posthog.conversations.getTickets({ limit: 50 })- if (response) {+ 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) {cache.ticketsFetched = true- actions.setTickets(response.results as ConversationTicket[])+ 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 (response.results.length > 0) {+ if (tickets.length > 0) {actions.startPolling()} else {actions.stopPolling()@@ -803,7 +825,7 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([})actions.setView('ticket')}- actions.loadTickets()+ actions.loadTickets(true)actions.loadMessages(response.ticket_id)lemonToast.success('Message sent!')onSuccess()@@ -956,7 +978,7 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([unread_count: 0,last_message_at: pending.created_at,})- actions.loadTickets()+ actions.loadTickets(true)},requestRestoreLink: async ({ email }) => {const conversations = posthog.conversations as any@@ -997,7 +1019,7 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([cache.restoreRetryTimer = window.setTimeout(() => actions.restoreFromUrlToken(token), 500)} else {removeRestoreTokenFromUrl()- actions.loadTickets()+ actions.loadTickets(true)}return}@@ -1020,7 +1042,7 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([console.error('Failed to restore from URL token:', e)} finally {removeRestoreTokenFromUrl()- actions.loadTickets()+ actions.loadTickets(true)}},})),diff --git a/products/conversations/frontend/components/SidePanel/ticketsAcrossTabs.test.ts b/products/conversations/frontend/components/SidePanel/ticketsAcrossTabs.test.tsnew file mode 100644index 000000000000..30d72357347c--- /dev/null+++ b/products/conversations/frontend/components/SidePanel/ticketsAcrossTabs.test.ts@@ -0,0 +1,119 @@+import type { PostHog } from 'posthog-js'++import type { ConversationTicket } from '../../types'++const START = 1_000_000+const MAX_AGE_MS = 10_000+const OPTIONS = { maxAgeMs: MAX_AGE_MS }++const ticket = (id: string): ConversationTicket => ({ id }) as ConversationTicket++describe('loadTicketsAcrossTabs', () => {+ let now: number+ let posthog: PostHog+ let loadTicketsAcrossTabs: typeof import('./ticketsAcrossTabs').loadTicketsAcrossTabs+ let clearSharedTickets: typeof import('./ticketsAcrossTabs').clearSharedTickets++ const fetchingTickets = (...ids: string[]): jest.Mock => jest.fn().mockResolvedValue(ids.map(ticket))++ beforeEach(async () => {+ now = START+ jest.spyOn(Date, 'now').mockImplementation(() => now)+ localStorage.clear()+ // A logout stops the module for the life of the page, so each test needs a fresh copy+ jest.resetModules()+ posthog = (await import('posthog-js')).default+ ;({ loadTicketsAcrossTabs, clearSharedTickets } = await import('./ticketsAcrossTabs'))+ })++ afterEach(() => {+ jest.restoreAllMocks()+ ;(posthog as any).config = undefined+ })++ test.each([+ { name: 'under the max age', ageMs: MAX_AGE_MS - 1, force: false, fetches: 1 },+ { name: 'at the max age', ageMs: MAX_AGE_MS, force: false, fetches: 2 },+ { name: 'under the max age but forced', ageMs: 1, force: true, fetches: 2 },+ ])('fetches $fetches time(s) for a second load $name', async ({ ageMs, force, fetches }) => {+ const fetchTickets = fetchingTickets('fetched')++ await loadTicketsAcrossTabs(fetchTickets, OPTIONS)+ now += ageMs+ const tickets = await loadTicketsAcrossTabs(fetchTickets, { ...OPTIONS, force })++ expect(fetchTickets).toHaveBeenCalledTimes(fetches)+ expect(tickets).toEqual([ticket('fetched')])+ })++ it('keeps the stored tickets when a fetch returns nothing', async () => {+ await loadTicketsAcrossTabs(fetchingTickets('stored'), OPTIONS)+ now += 1++ expect(await loadTicketsAcrossTabs(jest.fn().mockResolvedValue(null), { ...OPTIONS, force: true })).toBeNull()++ const fetchTickets = fetchingTickets('fetched')+ expect(await loadTicketsAcrossTabs(fetchTickets, OPTIONS)).toEqual([ticket('stored')])+ expect(fetchTickets).not.toHaveBeenCalled()+ })++ it('never reuses tickets fetched for another identity', async () => {+ const fetchTickets = fetchingTickets('a-ticket')+ ;(posthog as any).config = { identity_distinct_id: 'person-a' }+ await loadTicketsAcrossTabs(fetchTickets, OPTIONS)+ ;(posthog as any).config = { identity_distinct_id: 'person-b' }++ await loadTicketsAcrossTabs(fetchTickets, OPTIONS)++ expect(fetchTickets).toHaveBeenCalledTimes(2)+ })++ it('fetches again after the stored tickets are cleared', async () => {+ const fetchTickets = fetchingTickets('fetched')+ await loadTicketsAcrossTabs(fetchTickets, OPTIONS)++ clearSharedTickets()+ await loadTicketsAcrossTabs(fetchTickets, OPTIONS)++ expect(fetchTickets).toHaveBeenCalledTimes(2)+ })++ test.each([+ { name: 'in this tab', logOut: (): void => clearSharedTickets() },+ {+ name: 'in another tab',+ logOut: (): void => {+ localStorage.clear()+ window.dispatchEvent(new StorageEvent('storage', { key: 'posthog-conversations-tickets' }))+ },+ },+ ])('stops storing tickets after a logout $name', async ({ logOut }) => {+ const fetchTickets = fetchingTickets('fetched')+ let finishFetch = (): void => {}+ const inFlight = loadTicketsAcrossTabs(+ () => new Promise((resolve) => (finishFetch = () => resolve([ticket('in-flight')]))),+ OPTIONS+ )++ logOut()+ finishFetch()+ await inFlight+ await loadTicketsAcrossTabs(fetchTickets, OPTIONS)+ await loadTicketsAcrossTabs(fetchTickets, OPTIONS)++ expect(localStorage.length).toBe(0)+ expect(fetchTickets).toHaveBeenCalledTimes(2)+ })++ it('still fetches from the network when storage throws', async () => {+ const denied = (): never => {+ throw new DOMException('denied', 'SecurityError')+ }+ jest.spyOn(Storage.prototype, 'getItem').mockImplementation(denied)+ jest.spyOn(Storage.prototype, 'setItem').mockImplementation(denied)+ jest.spyOn(Storage.prototype, 'removeItem').mockImplementation(denied)++ expect(await loadTicketsAcrossTabs(fetchingTickets('fetched'), OPTIONS)).toEqual([ticket('fetched')])+ expect(() => clearSharedTickets()).not.toThrow()+ })+})diff --git a/products/conversations/frontend/components/SidePanel/ticketsAcrossTabs.ts b/products/conversations/frontend/components/SidePanel/ticketsAcrossTabs.tsnew file mode 100644index 000000000000..f5153186eadb--- /dev/null+++ b/products/conversations/frontend/components/SidePanel/ticketsAcrossTabs.ts@@ -0,0 +1,55 @@+import posthog from 'posthog-js'+import { z } from 'zod'++import { localStorageSlot } from 'lib/utils/localStorageSlot'++import type { ConversationTicket } from '../../types'++const STORAGE_KEY = 'posthog-conversations-tickets'++// One slot for every identity, so a person who used this browser earlier leaves nothing behind.+const sharedTickets = localStorageSlot(+ STORAGE_KEY,+ z.object({+ identity: z.string(),+ fetchedAt: z.number(),+ tickets: z.array(z.custom<ConversationTicket>()),+ })+)++// This page still fetches as the old identity after a logout, so it must not store that person's tickets again.+let loggedOut = false+window.addEventListener('storage', (event) => {+ if (event.key === STORAGE_KEY && event.newValue === null) {+ loggedOut = true+ }+})++export async function loadTicketsAcrossTabs(+ fetchTickets: () => Promise<ConversationTicket[] | null>,+ options: { force?: boolean; maxAgeMs: number }+): Promise<ConversationTicket[] | null> {+ // The widget fetches tickets as its signed identity, which can differ from the current distinct id+ // when another tab logs in as someone else, so that identity scopes the stored tickets.+ const identity = posthog.config?.identity_distinct_id ?? posthog.get_distinct_id?.() ?? ''++ const stored = options.force ? null : sharedTickets.get()+ if (stored?.identity === identity && Date.now() - stored.fetchedAt < options.maxAgeMs) {+ return stored.tickets+ }++ const tickets = await fetchTickets()+ if (tickets && !loggedOut) {+ sharedTickets.set({ identity, fetchedAt: Date.now(), tickets })+ }+ return tickets+}++export function clearSharedTickets(): void {+ loggedOut = true+ try {+ localStorage.removeItem(STORAGE_KEY)+ } catch {+ // Disabled storage must not prevent logout.+ }+}diff --git a/products/conversations/frontend/scenes/myTickets/myTicketsSceneLogic.test.ts b/products/conversations/frontend/scenes/myTickets/myTicketsSceneLogic.test.tsindex fe27f807da23..aa6881370339 100644--- a/products/conversations/frontend/scenes/myTickets/myTicketsSceneLogic.test.ts+++ b/products/conversations/frontend/scenes/myTickets/myTicketsSceneLogic.test.ts@@ -8,6 +8,7 @@ import { myTicketsSceneLogic } from './myTicketsSceneLogic'describe('myTicketsSceneLogic', () => {beforeEach(() => {+ localStorage.clear()initKeaTests();(posthog as any).conversations = {isAvailable: () => true,@@ -16,6 +17,7 @@ describe('myTicketsSceneLogic', () => {})afterEach(() => {+ jest.restoreAllMocks()delete (posthog as any).conversations})@@ -31,6 +33,8 @@ describe('myTicketsSceneLogic', () => {const callsAtBoot = getTickets.mock.calls.lengthexpect(callsAtBoot).toBeGreaterThan(0)+ const bootTime = Date.now()+ jest.spyOn(Date, 'now').mockReturnValue(bootTime + 60_000)const sceneLogic = myTicketsSceneLogic.build()sceneLogic.mount()await expectLogic(ticketsLogic).toFinishAllListeners()diff --git a/products/conversations/frontend/scenes/myTickets/myTicketsSceneLogic.ts b/products/conversations/frontend/scenes/myTickets/myTicketsSceneLogic.tsindex 7b9c14a48ef0..6af5a25af8db 100644--- a/products/conversations/frontend/scenes/myTickets/myTicketsSceneLogic.ts+++ b/products/conversations/frontend/scenes/myTickets/myTicketsSceneLogic.ts@@ -4,8 +4,8 @@ import { sidepanelTicketsLogic } from '../../components/SidePanel/sidepanelTicke// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface myTicketsSceneLogicActions {- loadTickets: () => {- value: true+ loadTickets: (force?: boolean | undefined) => {+ force: boolean} // sidepanelTicketsLogic}