: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(signals): stop in-session inbox opens reading as cold deep links (#96451)
posthog[bot]f9f48ea7f81f
diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.tsindex 0122a4617c65..6203767b6e1b 100644--- a/products/signals/frontend/inbox/inboxAnalytics.ts+++ b/products/signals/frontend/inbox/inboxAnalytics.ts@@ -396,24 +396,32 @@ export function captureInboxReportsImpressed(params: {* "opened from Needs decision" are one breakdown. Null when the report isn't in a loaded list* (a cold deep-link), in which case `rank` and `list_size` are null too.*/-export function captureInboxReportOpened(params: {- report: SignalReport- openMethod: InboxReportOpenMethod- previousReportId: string | null- rank: number | null- listSize: number | null- section: InboxReportSectionKey | null-}): void {- captureInboxEvent(INBOX_EVENTS.REPORT_OPENED, {- ...baseReportProperties(params.report),- status: params.report.status ?? null,- source_products: params.report.source_products ?? [],- open_method: params.openMethod,- previous_report_id: params.previousReportId,- rank: params.rank,- list_size: params.listSize,- section: params.section,- })+export function captureInboxReportOpened(+ params: {+ report: SignalReport+ openMethod: InboxReportOpenMethod+ previousReportId: string | null+ rank: number | null+ listSize: number | null+ section: InboxReportSectionKey | null+ },+ /** The unload flush passes `{ send_instantly: true }` so the open leaves before the page does. */+ options?: CaptureOptions+): void {+ captureInboxEvent(+ INBOX_EVENTS.REPORT_OPENED,+ {+ ...baseReportProperties(params.report),+ status: params.report.status ?? null,+ source_products: params.report.source_products ?? [],+ open_method: params.openMethod,+ previous_report_id: params.previousReportId,+ rank: params.rank,+ list_size: params.listSize,+ section: params.section,+ },+ options+ )}export function captureInboxReportClosed(diff --git a/products/signals/frontend/inbox/inboxSceneLogic.test.ts b/products/signals/frontend/inbox/inboxSceneLogic.test.tsindex 630884f42ab7..512ad72d1328 100644--- a/products/signals/frontend/inbox/inboxSceneLogic.test.ts+++ b/products/signals/frontend/inbox/inboxSceneLogic.test.ts@@ -1,6 +1,10 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'+import { combineUrl, router } from 'kea-router'/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'+import type { CaptureOptions } from 'posthog-js'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'@@ -14,7 +18,20 @@ import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemaimport { inboxSceneLogic, mergeSignalRuns } from './inboxSceneLogic'import { inboxBulkActionsLogic } from './logics/inboxBulkActionsLogic'-import { SignalReportStatus, SignalScoutRunSummary } from './types'+import { reportListLogic, sectionListLogicProps } from './logics/reportListLogic'+import { SignalReport, SignalReportStatus, SignalScoutRunSummary } from './types'++function openedCalls(spy: jest.SpyInstance): any[][] {+ return spy.mock.calls.filter((call) => call[0] === 'Inbox report opened')+}++function openedEvents(spy: jest.SpyInstance): Record<string, any>[] {+ return openedCalls(spy).map((call) => call[1] as Record<string, any>)+}++function waitForOpenRankRetry(): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, 400))+}function scoutRun(overrides: Partial<SignalScoutRunSummary> = {}): SignalScoutRunSummary {return {@@ -120,6 +137,8 @@ describe('inboxSceneLogic routing', () => {'/api/projects/:team_id/signals/scout/configs/': [],},})+ // The list-visited flag lives in session storage, so it outlives a test.+ window.sessionStorage.clear()initKeaTests()featureFlagLogic.mount()})@@ -331,6 +350,145 @@ describe('inboxSceneLogic routing', () => {expect(openMethod).toBe(expectedMethod)})+ // A reload, a new tab, and a bundle update each start a fresh logic. Switching project is a+ // same-tab page load as well, and it keeps session storage, so the marker is per project.+ it.each([+ { where: 'the same project', team: MOCK_DEFAULT_TEAM, expected: 'click' },+ {+ where: 'another project',+ team: { ...MOCK_DEFAULT_TEAM, id: MOCK_DEFAULT_TEAM.id + 1 },+ expected: 'deeplink',+ },+ ])('a report URL loaded fresh in $where after the list was visited reads $expected', async ({ team, expected }) => {+ mountWithRedesign(true)+ router.actions.push(urls.inbox('reports'))+ logic.unmount()++ initKeaTests(true, team)+ featureFlagLogic.mount()+ mountWithRedesign(true)++ let openMethod: string | undefined+ await expectLogic(logic, () => router.actions.push(urls.inboxReport('reports', 'r1'))).toDispatchActions([+ (action: any) => {+ if (action.type !== logic.actionTypes.setSelectedReportId) {+ return false+ }+ openMethod = action.payload.openMethod+ return true+ },+ ])+ expect(openMethod).toBe(expected)+ })++ // A rank read at open time is null on a cold load, and joins to no impression row. The event is+ // then captured after the wait, so it also has to carry the moment the report opened: a scroll+ // or an action taken during the wait would otherwise read earlier than the open.+ it('holds `Inbox report opened` until the list answers, then reports the rank and the open time', async () => {+ const report = { id: 'r1', title: 'Crash on login' } as SignalReport+ useMocks({+ get: {+ '/api/projects/:team_id/signals/reports/': {+ results: [report],+ count: 1,+ next: null,+ previous: null,+ },+ },+ })+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ mountWithRedesign(false)+ const listLogic = reportListLogic(sectionListLogicProps('needs-decision'))+ listLogic.mount()+ listLogic.actions.loadReports()++ logic.actions.setSelectedReportId('r1')+ const beforeOpen = Date.now()+ logic.actions.loadSelectedReportSuccess(report)+ const afterOpen = Date.now()+ expect(openedEvents(captureSpy)).toHaveLength(0)++ await waitForOpenRankRetry()++ expect(openedEvents(captureSpy)[0]).toMatchObject({ rank: 1, list_size: 1 })+ const stampedAt = (openedCalls(captureSpy)[0][2] as CaptureOptions | undefined)?.timestamp?.getTime()+ expect(stampedAt).toBeGreaterThanOrEqual(beforeOpen)+ expect(stampedAt).toBeLessThanOrEqual(afterOpen)+ captureSpy.mockRestore()+ listLogic.unmount()+ })++ // The flat list merges every selected state, so a state that answers late can add rows that sort+ // above the report. Ranking on the first state to answer records a rank that is too small, and+ // the impression side (which waits for all of them) then records a different one.+ it('under the flat list the rank waits for the slower state, not the first one to answer', async () => {+ const opened = { id: 'r1', title: 'Crash on login', priority: 'P2' } as SignalReport+ const higher = { id: 'r2', title: 'Checkout times out', priority: 'P0' } as SignalReport+ let releaseMonitoring = (): void => {}+ const monitoringAnswered = new Promise<void>((resolve) => {+ releaseMonitoring = resolve+ })+ useMocks({+ get: {+ '/api/projects/:team_id/signals/reports/': async ({ request }) => {+ // Only the monitoring state filters on an open implementation PR.+ if (new URL(request.url).searchParams.get('has_implementation_pr') === 'true') {+ await monitoringAnswered+ return [200, { results: [higher], count: 1, next: null, previous: null }]+ }+ return [200, { results: [opened], count: 1, next: null, previous: null }]+ },+ },+ })+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ mountWithRedesign(true)+ const needsDecision = reportListLogic(sectionListLogicProps('needs-decision'))+ const monitoring = reportListLogic(sectionListLogicProps('monitoring'))+ needsDecision.mount()+ monitoring.mount()+ needsDecision.actions.loadReports()+ monitoring.actions.loadReports()++ logic.actions.setSelectedReportId('r1')+ logic.actions.loadSelectedReportSuccess(opened)++ await waitForOpenRankRetry()+ expect(needsDecision.values.reports).toHaveLength(1)+ expect(openedEvents(captureSpy)).toHaveLength(0)++ releaseMonitoring()+ await waitForOpenRankRetry()++ expect(openedEvents(captureSpy)[0]).toMatchObject({ rank: 2, list_size: 2 })+ captureSpy.mockRestore()+ needsDecision.unmount()+ monitoring.unmount()+ })++ // posthog-js drains its batch queue from its own `pagehide` handler, which is registered before+ // this scene's. An open left to normal batching is enqueued after that drain and never leaves.+ it('a page unload while an open is still waiting sends the open instantly, ahead of the close', () => {+ const report = { id: 'r1', title: 'Crash on login' } as SignalReport+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ mountWithRedesign(true)++ // No list is mounted, so the rank never resolves and the open stays pending.+ logic.actions.setSelectedReportId('r1')+ logic.actions.loadSelectedReportSuccess(report)+ expect(openedEvents(captureSpy)).toHaveLength(0)++ window.dispatchEvent(new Event('pagehide'))++ const inboxCalls = captureSpy.mock.calls.filter(([name]) =>+ ['Inbox report opened', 'Inbox report closed'].includes(name as string)+ )+ expect(inboxCalls.map(([name]) => name)).toEqual(['Inbox report opened', 'Inbox report closed'])+ // The open also carries its own `timestamp`, so match the option that bypasses the queue.+ expect(inboxCalls[0][2]).toMatchObject({ send_instantly: true })+ expect(inboxCalls[1][2]).toEqual({ send_instantly: true })+ captureSpy.mockRestore()+ })+it('stops the runs poll when opening another surface closes the panel', () => {// Opening a report flips `isRunsOpen` false through a mutual-exclusion reducer, not// `setRunsOpen(false)`, so the poll teardown cannot hang off the `setRunsOpen` listener alonediff --git a/products/signals/frontend/inbox/inboxSceneLogic.ts b/products/signals/frontend/inbox/inboxSceneLogic.tsindex 7aaea1d211c6..09137a08019f 100644--- a/products/signals/frontend/inbox/inboxSceneLogic.ts+++ b/products/signals/frontend/inbox/inboxSceneLogic.ts@@ -10,6 +10,7 @@ import api from 'lib/api'import { ApiError } from 'lib/api-error'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'+import { getCurrentTeamIdOrNone } from 'lib/utils/getAppContext'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { reconcileById } from 'lib/utils/objects'import { sceneConfigurations } from 'scenes/scenes'@@ -201,6 +202,36 @@ function clearScratchpadSearch(): void {}}+// `open_method` reads `deeplink` only when this visit never saw an inbox list URL. Session storage+// is the right scope: it survives a reload and is copied into a tab opened from a link.+const INBOX_LIST_VISITED_STORAGE_KEY_PREFIX = 'posthog.inbox.listVisited'++/**+ * Per project, because switching project is a same-tab page load that keeps session storage, and a+ * list seen in one project says nothing about a report link in another. The project comes from the+ * server-rendered app context rather than `teamLogic`, because the marker is read from a route+ * handler on a cold load, before the team request answers.+ */+function inboxListVisitedStorageKey(): string {+ return `${INBOX_LIST_VISITED_STORAGE_KEY_PREFIX}.${getCurrentTeamIdOrNone() ?? 'none'}`+}++function markInboxListVisited(): void {+ try {+ window.sessionStorage.setItem(inboxListVisitedStorageKey(), '1')+ } catch {+ return+ }+}++function hasVisitedInboxList(): boolean {+ try {+ return window.sessionStorage.getItem(inboxListVisitedStorageKey()) === '1'+ } catch {+ return false+ }+}+function mountedReportLists(): ReturnType<typeof reportListLogic.build>[] {return (Object.keys(INBOX_REPORT_SECTION_LIST_PARAMS) as InboxReportSectionKey[]).flatMap((sectionKey) => {const mounted = reportListLogic.findMounted({@@ -281,6 +312,86 @@ function findReportRank(return { rank: null, listSize: null, section: null }}+// One list answered, with rows or with a failure, and none is still fetching. Until then, a missing+// rank means "not loaded yet". This mirrors the rule the impression side settles on, so an open and+// the impression it joins to describe the same list.+function reportListsSettled(): boolean {+ const mounted = INBOX_REPORT_SECTION_KEYS.map((sectionKey) =>+ reportListLogic.findMounted({ sectionKey, listParams: INBOX_REPORT_SECTION_LIST_PARAMS[sectionKey] })+ ).filter((logic) => !!logic)+ return (+ mounted.some((logic) => logic.values.isLoaded || logic.values.reportsLoadFailed) &&+ mounted.every((logic) => !logic.values.reportsResponseLoading)+ )+}++const OPEN_RANK_WAIT_MS = 5000+const OPEN_RANK_POLL_MS = 250++// A cold load answers the report fetch long before the lists, so a rank read at open time is null+// and the row joins to no impression. Wait for the lists, then send whatever the lookup gives.+function captureOpenWhenRanked(+ cache: Record<string, any>,+ tracking: InboxOpenTracking,+ openMethod: InboxReportOpenMethod,+ flatList: boolean+): void {+ const previousReportId = cache.previousReportId ?? null+ const deadline = Date.now() + OPEN_RANK_WAIT_MS++ const fire = (resolved: ReturnType<typeof findReportRank>, options?: CaptureOptions): void => {+ cache.pendingOpenCapture = undefined+ cache.disposables.dispose('openRank')+ captureInboxReportOpened(+ {+ report: tracking.report,+ openMethod,+ previousReportId,+ rank: resolved.rank,+ listSize: resolved.listSize,+ section: resolved.section,+ },+ // The wait puts the capture up to `OPEN_RANK_WAIT_MS` after the report opened, and+ // posthog-js stamps an event at the capture moment. Without the override, a scroll or an+ // action taken in the detail pane during the wait reads earlier than the open that+ // started it. The caller's options win, so the unload flush keeps `send_instantly`.+ { timestamp: new Date(tracking.openedAt), ...options }+ )+ }+ // The first read sees the list as the person left it, so a rank found there is the rank they+ // acted on, even while a filter refetch is in flight. Every later read waits for the lists to+ // settle: the flat list merges the selected states, and a state that answers late adds rows that+ // can sort above the report, which makes a rank read from the states that answered first too+ // small.+ const fireWhenReady = (firstRead: boolean): void => {+ const resolved = findReportRank(tracking.report.id, flatList)+ if ((firstRead && resolved.rank !== null) || reportListsSettled() || Date.now() >= deadline) {+ fire(resolved)+ }+ }++ cache.pendingOpenCapture = (options?: CaptureOptions) => fire(findReportRank(tracking.report.id, flatList), options)+ fireWhenReady(true)+ if (!cache.pendingOpenCapture) {+ return+ }+ cache.disposables.add(() => {+ const interval = setInterval(() => fireWhenReady(false), OPEN_RANK_POLL_MS)+ return () => clearInterval(interval)+ }, 'openRank')+}++/**+ * Send a still-waiting open now, so no close can precede it. The unload flush must pass its+ * `options` on: posthog-js batches a capture that carries none, and it drains that queue from its+ * own `pagehide` handler, which is registered at `init()` and therefore runs before this one. An+ * open enqueued after the drain never leaves the page.+ */+function flushPendingOpen(cache: Record<string, any>, options?: CaptureOptions): void {+ const capture = cache.pendingOpenCapture as ((options?: CaptureOptions) => void) | undefined+ capture?.(options)+}+/*** The URL for whichever full-width inbox surface is open, or the list otherwise. The surfaces* (report, scout detail, scratchpad, findings, runs, triage) are mutually exclusive, so a fixed@@ -342,6 +453,7 @@ function flushOpenReport(if (!open) {return}+ flushPendingOpen(cache, options)captureInboxReportClosed({ report: open.report, timeSpentMs: Date.now() - open.openedAt, closeMethod }, options)cache.openTracking = undefined}@@ -877,6 +989,7 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([// switching straight to another report, `deselected` when returning to the list.const open: InboxOpenTracking | undefined = cache.openTrackingif (open) {+ flushPendingOpen(cache)const closeMethod: InboxReportCloseMethod = id ? 'next_report' : 'deselected'captureInboxReportClosed({report: open.report,@@ -926,16 +1039,14 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([if (!report || values.selectedReportId !== report.id || cache.openTracking?.report.id === report.id) {return}- const { rank, listSize, section } = findReportRank(report.id, values.isRedesign)- captureInboxReportOpened({- report,- openMethod: (cache.pendingOpenMethod as InboxReportOpenMethod | undefined) ?? 'unknown',- previousReportId: cache.previousReportId ?? null,- rank,- listSize,- section,- })- cache.openTracking = { report, openedAt: Date.now(), scrolled: false }+ const tracking: InboxOpenTracking = { report, openedAt: Date.now(), scrolled: false }+ cache.openTracking = tracking+ captureOpenWhenRanked(+ cache,+ tracking,+ (cache.pendingOpenMethod as InboxReportOpenMethod | undefined) ?? 'unknown',+ values.isRedesign+ )cache.pendingOpenMethod = undefined// Best-effort server-side view record: consumption evidence that keeps the authoring// scout from being auto-paused as ignored. The analytics event above stays the rich@@ -1152,7 +1263,7 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([],})),- urlToAction(({ actions, values, cache }) => {+ urlToAction(({ actions, values }) => {const closeAllSurfaces = (): void => {if (values.selectedReportId !== null) {actions.setSelectedReportId(null)@@ -1215,13 +1326,13 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([redirectForLayout(urls.inbox('reports'), searchParams, hashParams)return}- cache.inboxListVisited = true+ markInboxListVisited()if (!values.isTriageOpen) {actions.setTriageOpen(true)}},[urls.inbox()]: (_, __, hashParams) => {- cache.inboxListVisited = true+ markInboxListVisited()consumeScoutTemplateHash(actions, hashParams)closeAllSurfaces()},@@ -1240,7 +1351,7 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([router.actions.replace(urls.inboxReport('reports', tab), searchParams, hashParams)return}- cache.inboxListVisited = true+ markInboxListVisited()consumeScoutTemplateHash(actions, hashParams)// Staff-only tabs (Not actionable): bounce non-staff to the default tab. Under the// redesign that list is a section the Reports tab hides from non-staff instead.@@ -1337,7 +1448,7 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([typeof searchParams.back === 'string' && searchParams.back.startsWith(urls.inboxTriage())actions.setSelectedReportId(reportId,- fromTriage ? 'triage' : cache.inboxListVisited ? 'click' : 'deeplink'+ fromTriage ? 'triage' : hasVisitedInboxList() ? 'click' : 'deeplink')}},