: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
feat(toolbar): gate heatmaps behind a plan entitlement (#97742)
Jordan Mryyan24c6acc4ff04
diff --git a/docs/internal/toolbar-entitlements.md b/docs/internal/toolbar-entitlements.mdnew file mode 100644index 000000000000..19423eae836b--- /dev/null+++ b/docs/internal/toolbar-entitlements.md@@ -0,0 +1,17 @@+# Toolbar plan entitlements++`GET /api/user/toolbar_entitlements/` requires a logged-in session and access to the toolbar for the current project. It returns an `entitlements` map of feature names to booleans, based on the current organization’s available features. `ToolbarEntitlementsSerializer` defines its OpenAPI response schema.++Gated toolbar tools are a Cloud plan entitlement.+On a self-hosted deployment the endpoint reports every gated feature as entitled, so a rollout can never take a toolbar tool away from a self-hosted user, licensed or not.+Legacy self-hosted license tiers therefore do not list these features.++When the `toolbar-paid-heatmaps` rollout flag is enabled, toolbar heatmaps require `toolbar_heatmaps: true`. Loading, failed requests, and missing entitlements do not grant access. The menu shows a loading state while checking access and offers a retry when access cannot be determined. A failed request is logged under the `entitlements` context and reported in the `toolbar api request` telemetry, so the rollout can be watched without waiting for a user report. The request gives up after five seconds, so a stalled one reaches that retry rather than spinning for the rest of the page session. Only an explicit `false` shows the plan upgrade prompt.+The toolbar button follows the same rule: it carries the lock badge only for an explicit `false`, and while the check is pending or failed its tooltip says that instead of asking for a subscription.+That prompt also offers a recheck, so a user who upgrades in the billing tab unlocks the tool without reloading the page they are working on.++Opening the heatmap menu while access is loading does not enable heatmaps. A confirmed entitlement enables the open menu; refreshing or losing that entitlement disables heatmaps. A rollout flag that arrives after the menu opened reconciles the open heatmap the same way, so the page overlays cannot stay painted under the plan panel. When the rollout flag is disabled, the toolbar retains its existing behavior.++This is a toolbar UI gate. The rollout flag does not add entitlement enforcement to the heatmap data endpoints.++The `HeatmapEntitlementsLoading` Storybook story keeps the entitlement request pending to cover the loading state. Its screenshot test waits for “Checking plan access…” to appear and sets `waitForLoadersToDisappear: false` so the visible spinner does not time out the test.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 8c587ed7afd2..de446b3455c4 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -11476,6 +11476,14 @@ snapshots:hash: v1.k794b7964.b5c5685fbf4362ffdeb86b71403d992895bc7f465a89e3950e73d805659120cd.LflCqOqs_3HllO3yAenQoTU4XkVLmdFgiMZdver44EIscenes-other-toolbar--heatmap-dark--light:hash: v1.k794b7964.54ea6dd30881be4b788facdce098a207fb5171f6ed969451c4f378ed9bb17f67.kmPM0TK8dLKElYiLRmgDMvswiByHAMWOmC2nhEaeCTM+ scenes-other-toolbar--heatmap-entitlements-error--dark:+ hash: v1.k794b7964.11b12d94798a78afe633b555550a3b6be8c84ed4bb03adfa0c80c923fe739115.THJ-PW5rpBcnp8Cgfab7g-J3Jfumq6ULrZl053qREuI+ scenes-other-toolbar--heatmap-entitlements-error--light:+ hash: v1.k794b7964.d628aec0cc4ba7f5359f87ede92c2a29e3c81238e723a91ddea25f0c36e1cbdf.VrzMCvXUBehL0dFKel21d1ee0rDmzThv2ZKdhkvRS_Y+ scenes-other-toolbar--heatmap-entitlements-loading--dark:+ hash: v1.k794b7964.18953cf5eb039c2db6229fc2ccf6a409686f509ee37a1098f9ef7bcb61401ed0.wUGMJJJGGLGPONfCvzgzodVgweh7dgQDprBar-JWt_I+ scenes-other-toolbar--heatmap-entitlements-loading--light:+ hash: v1.k794b7964.0b56bde4bd671759d3974635bb2840e151386e07a75e93d69e909730a1a5a60b.zNIvrMFECMskqVuP1e2YkDNUgLKei44C6_34QMizEr4scenes-other-toolbar--inspect--dark:hash: v1.k794b7964.37fa05b873d6876ff8a932209f515de7c81b3cf80af3810489d1e101acb61aa5.00b1XmAvLslDcl3T7oSAyL01QePjoUOaDM3CoV_roaYscenes-other-toolbar--inspect--light:diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex ee7d82ec2792..0d376c52a315 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -4284,6 +4284,21 @@ export interface LeakedKeyReportResponseApi {type: LeakedKeyReportResponseTypeEnumApi | null}+/**+ * Whether the current organization has each toolbar plan entitlement, keyed by feature name.+ */+export type ToolbarEntitlementsApiEntitlements = { [key: string]: boolean }++export interface ToolbarEntitlementsApi {+ /** Whether the current organization has each toolbar plan entitlement, keyed by feature name. */+ entitlements: ToolbarEntitlementsApiEntitlements+}++export interface ToolbarEntitlementsErrorApi {+ /** Why toolbar entitlements could not be retrieved. */+ error: string+}+/*** * `disabled` - disabled* * `toolbar` - toolbardiff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex a1d7879bb2dc..aa0454457181 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -81,6 +81,7 @@ import type {RevokeOtherSessionsResponseApi,SCIMTokenResponseApi,SharingConfigurationApi,+ ToolbarEntitlementsApi,UploadedMediaApi,UploadedMediaCreate201,UploadedMediaCreateBody,@@ -2538,6 +2539,17 @@ export const revokeLeakedKeyCreate = async (})}+export const getUserToolbarEntitlementsRetrieveUrl = () => {+ return `/api/user/toolbar_entitlements/`+}++export const userToolbarEntitlementsRetrieve = async (options?: RequestInit): Promise<ToolbarEntitlementsApi> => {+ return apiMutator<ToolbarEntitlementsApi>(getUserToolbarEntitlementsRetrieveUrl(), {+ ...options,+ method: 'GET',+ })+}+export const getUsersListUrl = (params?: UsersListParams) => {const normalizedParams = new URLSearchParams()diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex f0ffa5ee65c4..69b01447f95c 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -520,6 +520,7 @@ export const FEATURE_FLAGS = {TASKS_STREAM_VIA_PROXY: 'tasks-stream-via-proxy', // owner: #team-ai-observabilityTAXONOMIC_FILTER_MENU_REBUILD: 'taxonomic-filter-menu-rebuild', // owner: @adamleith, opt-in to the rebuilt TaxonomicFilter — headless filter panel + new popover menu (column / preview-pane)TEXT_CARD_WORD_ART: 'text-card-word-art', // owner: @jonmcwest, gates the word art insert button in dashboard text cards+ TOOLBAR_PAID_HEATMAPS: 'toolbar-paid-heatmaps', // owner: #team-web-analyticsTRACING: 'tracing', // owner: #team-apm (@jonmcwest, @frankh)TRACING_FACET_RAIL: 'tracing-facet-rail', // owner: #team-apm — gates the facet rail (faceted filter sidebar) in tracingTRACING_LATENCY_HEATMAP: 'tracing-latency-heatmap', // owner: #team-apm — gates the latency-over-time heatmap chart in tracingdiff --git a/frontend/src/toolbar/TELEMETRY.md b/frontend/src/toolbar/TELEMETRY.mdindex dd1b05646dd1..92fc9991220e 100644--- a/frontend/src/toolbar/TELEMETRY.md+++ b/frontend/src/toolbar/TELEMETRY.md@@ -101,17 +101,18 @@ Fired when the UI host configuration modal is shown (auth error state).### `toolbar api request`-Fired after every `toolbarFetch` call. Covers all toolbar API endpoints.+Fired after every `toolbarFetch` call, and after the entitlements request, which carries the session cookie instead of a bearer token.+Covers all toolbar API endpoints.| Property | Type | Description || ----------------- | --------- | -------------------------------------------------- || `method` | `string` | HTTP method (`GET`, `POST`, `PATCH`, `DELETE`) || `pathname` | `string` | API path (e.g., `/api/projects/@current/actions/`) |-| `status` | `number` | HTTP response status code |+| `status` | `number` | HTTP status, or 0 if the request never landed || `duration_ms` | `number` | Total time including any token retry || `did_token_retry` | `boolean` | Whether a 401 triggered a token refresh + retry |-**File:** `toolbarConfigLogic.ts`+**File:** `toolbarFetch.ts`## Menu and modediff --git a/frontend/src/toolbar/Toolbar.stories.tsx b/frontend/src/toolbar/Toolbar.stories.tsxindex 88c01eb7ad50..9c99d0f371c9 100644--- a/frontend/src/toolbar/Toolbar.stories.tsx+++ b/frontend/src/toolbar/Toolbar.stories.tsx@@ -18,6 +18,7 @@ import { listExperimentsAPIResponse } from './__mocks__/list-web-experiments-resimport { listWebVitalsAPIResponse } from './__mocks__/list-web-vitals-response'import { MenuState, toolbarLogic } from './bar/toolbarLogic'import { toolbarConfigLogic } from './toolbarConfigLogic'+import { toolbarPosthogJS } from './toolbarPosthogJS'import { TOOLBAR_ID } from './utils'function useToolbarStyles(): void {@@ -58,6 +59,8 @@ type StoryArgs = {minimized?: booleanunauthenticated?: booleantheme?: 'light' | 'dark'+ heatmapLocked?: boolean+ entitlementsState?: 'loading' | 'error'}const meta: Meta<StoryArgs> = {@@ -67,7 +70,7 @@ const meta: Meta<StoryArgs> = {layout: 'fullscreen',viewMode: 'story',},- render: (props) => {+ render: (props, { parameters }) => {const toolbarParams: ToolbarParams = {accessToken: props.unauthenticated ? undefined : 'UExb1dCsoqBtrhrZYxzmxXQ7XdjVH5Ea_zbQjTFuJqk',actionId: undefined,@@ -92,6 +95,7 @@ const meta: Meta<StoryArgs> = {featureFlags: {'web-vitals': true,'web-vitals-toolbar': true,+ 'toolbar-paid-heatmaps': props.heatmapLocked ?? false,},sessionRecording: {endpoint: '/s/',@@ -99,6 +103,15 @@ const meta: Meta<StoryArgs> = {},'/api/element/stats/': listHeatmapStatsAPIResponse,'/api/heatmap/': { results: [] },+ '/api/user/toolbar_entitlements': () => {+ if (props.entitlementsState === 'loading') {+ return new Promise(() => {})+ }+ if (props.entitlementsState === 'error') {+ return [500, {}]+ }+ return { entitlements: { toolbar_heatmaps: !props.heatmapLocked } }+ },'/api/projects/@current/feature_flags/my_flags': listMyFlagsAPIResponse,'/api/projects/@current/actions/': listActionsAPIResponse,'/api/projects/@current/web_experiments/': listExperimentsAPIResponse,@@ -113,10 +126,13 @@ const meta: Meta<StoryArgs> = {const { setVisibleMenu, setDragPosition, toggleMinimized, toggleTheme } = useActions(theToolbarLogic)useEffect(() => {+ // The toolbar uses its own SDK instance, so the app's Storybook flag overrides do not reach it.+ toolbarPosthogJS.featureFlags.overrideFeatureFlags({ flags: parameters.featureFlags ?? {} })setDragPosition(50, 50)setVisibleMenu(props.menu || 'none')toggleMinimized(props.minimized ?? false)toggleTheme(props.theme || 'light')+ return () => toolbarPosthogJS.featureFlags.overrideFeatureFlags(false)}, [Object.values(props)]) // oxlint-disable-line react-hooks/exhaustive-depsreturn (@@ -146,6 +162,27 @@ export const Heatmap: Story = {args: { menu: 'heatmap' },}+export const HeatmapLocked: Story = {+ parameters: { featureFlags: { 'toolbar-paid-heatmaps': true } },+ args: { menu: 'heatmap', heatmapLocked: true },+}++export const HeatmapEntitlementsLoading: Story = {+ parameters: {+ featureFlags: { 'toolbar-paid-heatmaps': true },+ testOptions: {+ waitForLoadersToDisappear: false,+ waitForSelector: 'text=Checking plan access…',+ },+ },+ args: { menu: 'heatmap', heatmapLocked: true, entitlementsState: 'loading' },+}++export const HeatmapEntitlementsError: Story = {+ parameters: { featureFlags: { 'toolbar-paid-heatmaps': true } },+ args: { menu: 'heatmap', heatmapLocked: true, entitlementsState: 'error' },+}+export const Inspect: Story = {args: { menu: 'inspect' },}diff --git a/frontend/src/toolbar/bar/Toolbar.tsx b/frontend/src/toolbar/bar/Toolbar.tsxindex fe22edc48e6e..864ea9401a72 100644--- a/frontend/src/toolbar/bar/Toolbar.tsx+++ b/frontend/src/toolbar/bar/Toolbar.tsx@@ -17,6 +17,7 @@ import {IconHide,IconLeave,IconLive,+ IconLock,IconMessage,IconNight,IconPieChart,@@ -28,7 +29,7 @@ import {IconWarning,IconX,} from '@posthog/icons'-import { LemonBadge, Spinner } from '@posthog/lemon-ui'+import { LemonBadge, LemonButton, Spinner } from '@posthog/lemon-ui'import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'import { IconFlare, IconMenu } from 'lib/lemon-ui/icons'@@ -40,6 +41,7 @@ import { retryImport } from 'lib/utils/retryImport'import { AnimatedLogomark } from '~/toolbar/bar/AnimatedLogomark'import { AuthConfirmModal } from '~/toolbar/bar/AuthConfirmModal'import { PII_MASKING_PRESET_COLORS } from '~/toolbar/bar/piiMaskingStyles'+import { ToolbarLockedFeature } from '~/toolbar/bar/ToolbarLockedFeature'import { toolbarLogic } from '~/toolbar/bar/toolbarLogic'import { UiHostConfigModal } from '~/toolbar/bar/UiHostConfigModal'import { fieldNotesLogic } from '~/toolbar/field-notes/fieldNotesLogic'@@ -48,9 +50,16 @@ import { screenshotUploadLogic } from '~/toolbar/screenshot-upload/screenshotUplimport { ScreenshotUploadModal } from '~/toolbar/screenshot-upload/ScreenshotUploadModal'import { surveysToolbarLogic } from '~/toolbar/surveys/surveysToolbarLogic'import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'+import {+ ToolbarFeatureGateStatus,+ toolbarEntitlementsLogic,+ useToolbarFeatureGateStatus,+} from '~/toolbar/toolbarEntitlementsLogic'import { useToolbarFeatureFlag } from '~/toolbar/toolbarPosthogJS'+import { AvailableFeature } from '~/types'import { ToolbarButton } from './ToolbarButton'+import { ToolbarMenu } from './ToolbarMenu'// Each feature menu is a lazy split point: its component graph (and per-tab logics only it// mounts, like the event debugger's 200KB+ taxonomy) is fetched when the tab first opens, not@@ -111,6 +120,29 @@ const WebVitalsToolbarMenu = lazy(() =>const HELP_URL = 'https://posthog.com/docs/toolbar?utm_medium=in-product&utm_campaign=toolbar-help-button'+const HEATMAP_GATE_TITLES: Record<ToolbarFeatureGateStatus, string | undefined> = {+ available: undefined,+ checking: 'Heatmaps (checking plan access…)',+ unknown: "Heatmaps (couldn't check plan access, click to try again)",+ locked: 'Heatmaps (Pay-as-you-go subscription required)',+}++function LockableMenuIcon({ icon, locked }: { icon: JSX.Element; locked: boolean }): JSX.Element {+ if (!locked) {+ return icon+ }+ return (+ <span+ className="relative flex"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ fontSize: '1.5rem' }}+ >+ {icon}+ <IconLock className="absolute -top-1 -right-1 text-xs text-secondary" />+ </span>+ )+}+function EnabledStatusItem({ label, value }: { label: string; value: boolean }): JSX.Element {return (<div className="flex justify-between items-center w-full">@@ -362,6 +394,7 @@ export function ToolbarInfoMenu(): JSX.Element | null {const ref = useRef<HTMLDivElement | null>(null)const { visibleMenu, isDragging, menuProperties, minimized, isBlurred } = useValues(toolbarLogic)const { setMenu } = useActions(toolbarLogic)+ const { loadEntitlements } = useActions(toolbarEntitlementsLogic)const { isAuthenticated } = useValues(toolbarConfigLogic)@@ -374,10 +407,42 @@ export function ToolbarInfoMenu(): JSX.Element | null {const fieldNotesFlag = useToolbarFeatureFlag('field-notes')const showFieldNotes = inStorybook() || inStorybookTestRunner() || fieldNotesFlag+ const heatmapGate = useToolbarFeatureGateStatus(AvailableFeature.TOOLBAR_HEATMAPS, 'toolbar-paid-heatmaps')+const content = minimized ? null : visibleMenu === 'flags' ? (<FlagsToolbarMenu />) : visibleMenu === 'heatmap' ? (- <HeatmapToolbarMenu />+ heatmapGate === 'checking' ? (+ <ToolbarMenu>+ <ToolbarMenu.Body>+ <div className="flex items-center justify-center gap-2 py-4">+ <Spinner />+ <span>Checking plan access…</span>+ </div>+ </ToolbarMenu.Body>+ </ToolbarMenu>+ ) : heatmapGate === 'unknown' ? (+ <ToolbarMenu>+ <ToolbarMenu.Body>+ <p className="m-0">Couldn't check your plan access. Try again to use heatmaps.</p>+ </ToolbarMenu.Body>+ <ToolbarMenu.Footer>+ <LemonButton+ type="primary"+ fullWidth+ center+ onClick={loadEntitlements}+ data-attr="toolbar-entitlements-retry"+ >+ Try again+ </LemonButton>+ </ToolbarMenu.Footer>+ </ToolbarMenu>+ ) : heatmapGate === 'locked' ? (+ <ToolbarLockedFeature featureName="Heatmaps" />+ ) : (+ <HeatmapToolbarMenu />+ )) : visibleMenu === 'actions' ? (<ActionsToolbarMenu />) : visibleMenu === 'debugger' ? (@@ -462,6 +527,8 @@ export function Toolbar(): JSX.Element | null {const showFieldNotes = inStorybook() || inStorybookTestRunner() || fieldNotesFlagconst { hasOpenedFieldNotes } = useValues(fieldNotesLogic)+ const heatmapGate = useToolbarFeatureGateStatus(AvailableFeature.TOOLBAR_HEATMAPS, 'toolbar-paid-heatmaps')+useEffect(() => {setElement(ref.current)return () => setElement(null)@@ -565,8 +632,8 @@ export function Toolbar(): JSX.Element | null {</span></ToolbarButton>) : (- <ToolbarButton menuId="heatmap">- <IconCursorClick />+ <ToolbarButton menuId="heatmap" title={HEATMAP_GATE_TITLES[heatmapGate]}>+ <LockableMenuIcon icon={<IconCursorClick />} locked={heatmapGate === 'locked'} /></ToolbarButton>)}<ToolbarButton menuId="actions">@@ -591,8 +658,8 @@ export function Toolbar(): JSX.Element | null {)}{/* Heatmaps moves here and takes the app icon when field notes is enabled */}{showFieldNotes && (- <ToolbarButton menuId="heatmap" title="Heatmaps">- <IconApp />+ <ToolbarButton menuId="heatmap" title={HEATMAP_GATE_TITLES[heatmapGate] ?? 'Heatmaps'}>+ <LockableMenuIcon icon={<IconApp />} locked={heatmapGate === 'locked'} /></ToolbarButton>)}{showSurveys && (diff --git a/frontend/src/toolbar/bar/ToolbarLockedFeature.test.tsx b/frontend/src/toolbar/bar/ToolbarLockedFeature.test.tsxnew file mode 100644index 000000000000..6e670e318ac2--- /dev/null+++ b/frontend/src/toolbar/bar/ToolbarLockedFeature.test.tsx@@ -0,0 +1,30 @@+import '@testing-library/jest-dom'++import { fireEvent, render, screen } from '@testing-library/react'+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { ToolbarLockedFeature } from '~/toolbar/bar/ToolbarLockedFeature'+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'+import { toolbarEntitlementsLogic } from '~/toolbar/toolbarEntitlementsLogic'++describe('ToolbarLockedFeature', () => {+ beforeEach(() => {+ initKeaTests()+ toolbarConfigLogic.build({ apiURL: 'http://localhost' }).mount()+ useMocks({ get: { '/api/user/toolbar_entitlements': () => ({ entitlements: { toolbar_heatmaps: true } }) } })+ })++ it('rechecks the plan so an upgrade in another tab unlocks the feature', async () => {+ const logic = toolbarEntitlementsLogic()+ logic.mount()+ render(<ToolbarLockedFeature featureName="Heatmaps" />)++ await expectLogic(logic, () => {+ fireEvent.click(screen.getByText('Check again'))+ })+ .toDispatchActions(['loadEntitlements', 'loadEntitlementsSuccess'])+ .toMatchValues({ entitlements: { toolbar_heatmaps: true } })+ })+})diff --git a/frontend/src/toolbar/bar/ToolbarLockedFeature.tsx b/frontend/src/toolbar/bar/ToolbarLockedFeature.tsxnew file mode 100644index 000000000000..e7bf6ceba0c2--- /dev/null+++ b/frontend/src/toolbar/bar/ToolbarLockedFeature.tsx@@ -0,0 +1,57 @@+import { useActions, useValues } from 'kea'++import { IconLock } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { toolbarLockedFeatureLogic } from '~/toolbar/bar/toolbarLockedFeatureLogic'+import { ToolbarMenu } from '~/toolbar/bar/ToolbarMenu'+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'+import { toolbarEntitlementsLogic } from '~/toolbar/toolbarEntitlementsLogic'+import { urls } from '~/toolbar/urls'+import { joinWithUiHost } from '~/toolbar/utils'++export interface ToolbarLockedFeatureProps {+ featureName: string+}++export function ToolbarLockedFeature({ featureName }: ToolbarLockedFeatureProps): JSX.Element {+ const { uiHost } = useValues(toolbarConfigLogic)+ const { reportViewPlansClicked } = useActions(toolbarLockedFeatureLogic({ featureName }))+ const { loadEntitlements } = useActions(toolbarEntitlementsLogic)++ return (+ <ToolbarMenu>+ <ToolbarMenu.Body>+ <div className="flex flex-col items-center text-center gap-2 py-4">+ <IconLock className="text-2xl text-secondary" />+ <h3 className="text-sm font-semibold m-0">This feature isn't in your plan</h3>+ <p className="text-secondary m-0">+ To use {featureName.toLowerCase()} in the toolbar, upgrade your account to pay-as-you-go.+ </p>+ </div>+ </ToolbarMenu.Body>+ <ToolbarMenu.Footer>+ <LemonButton+ type="secondary"+ fullWidth+ center+ onClick={loadEntitlements}+ data-attr="toolbar-locked-feature-check-again"+ >+ Check again+ </LemonButton>+ <LemonButton+ type="primary"+ fullWidth+ center+ to={joinWithUiHost(uiHost, urls.organizationBilling())}+ targetBlank+ data-attr="toolbar-locked-feature-view-plans"+ onClick={reportViewPlansClicked}+ >+ View plans+ </LemonButton>+ </ToolbarMenu.Footer>+ </ToolbarMenu>+ )+}diff --git a/frontend/src/toolbar/bar/toolbarLockedFeatureLogic.ts b/frontend/src/toolbar/bar/toolbarLockedFeatureLogic.tsnew file mode 100644index 000000000000..40ef559cfcd5--- /dev/null+++ b/frontend/src/toolbar/bar/toolbarLockedFeatureLogic.ts@@ -0,0 +1,36 @@+import { MakeLogicType, actions, afterMount, kea, listeners, path, props } from 'kea'++import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'++export interface ToolbarLockedFeatureLogicProps {+ featureName: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface toolbarLockedFeatureLogicActions {+ reportViewPlansClicked: () => {+ value: true+ }+}++export type toolbarLockedFeatureLogicType = MakeLogicType<+ {},+ toolbarLockedFeatureLogicActions,+ ToolbarLockedFeatureLogicProps+>++export const toolbarLockedFeatureLogic = kea<toolbarLockedFeatureLogicType>([+ props({} as ToolbarLockedFeatureLogicProps),+ path(['toolbar', 'bar', 'toolbarLockedFeatureLogic']),+ actions({+ reportViewPlansClicked: true,+ }),+ listeners(({ props }) => ({+ reportViewPlansClicked: () => {+ toolbarPosthogJS.capture('toolbar locked feature view plans clicked', { feature: props.featureName })+ },+ })),+ afterMount(({ props }) => {+ toolbarPosthogJS.capture('toolbar locked feature viewed', { feature: props.featureName })+ }),+])diff --git a/frontend/src/toolbar/bar/toolbarLogic.ts b/frontend/src/toolbar/bar/toolbarLogic.tsindex 87d001d9dcdc..5ea8f60af6c3 100644--- a/frontend/src/toolbar/bar/toolbarLogic.ts+++ b/frontend/src/toolbar/bar/toolbarLogic.ts@@ -17,10 +17,12 @@ import { flagsToolbarLogic } from '~/toolbar/flags/flagsToolbarLogic'import { productToursLogic } from '~/toolbar/product-tours/productToursLogic'import { surveysToolbarLogic } from '~/toolbar/surveys/surveysToolbarLogic'import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'+import { isToolbarFeatureGated, toolbarEntitlementsLogic } from '~/toolbar/toolbarEntitlementsLogic'import { toolbarLogger } from '~/toolbar/toolbarLogger'import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'import { TOOLBAR_CONTAINER_CLASS, TOOLBAR_ID, inBounds, makeNavigateWrapper } from '~/toolbar/utils'import { webVitalsToolbarLogic } from '~/toolbar/web-vitals/webVitalsToolbarLogic'+import { AvailableFeature } from '~/types'import type { CommonFilters, HeatmapFilters, HeatmapFixedPositionMode } from '../../lib/components/heatmaps/types'import type { HedgehogModeInterface } from '../../lib/components/HedgehogMode/types'@@ -258,6 +260,9 @@ export interface toolbarLogicActions {startGracefulExit: () => {value: true}+ syncHeatmapGate: () => {+ value: true+ }syncWithHedgehog: () => {value: true}@@ -411,6 +416,7 @@ export const toolbarLogic = kea<toolbarLogicType>([setHedgehogModeEnabled: (hedgehogModeEnabled: boolean) => ({ hedgehogModeEnabled }),setDragPosition: (x: number, y: number) => ({ x, y }),syncWithHedgehog: true,+ syncHeatmapGate: true,openHedgehogOptions: true,setVisibleMenu: (visibleMenu: MenuState) => ({visibleMenu,@@ -775,6 +781,28 @@ export const toolbarLogic = kea<toolbarLogicType>([],}),listeners(({ actions, values }) => ({+ [toolbarEntitlementsLogic.actionTypes.loadEntitlements]: () => {+ if (isToolbarFeatureGated(AvailableFeature.TOOLBAR_HEATMAPS, 'toolbar-paid-heatmaps')) {+ actions.disableHeatmap()+ }+ },+ [toolbarEntitlementsLogic.actionTypes.loadEntitlementsSuccess]: () => {+ actions.syncHeatmapGate()+ },+ // Both halves of the gate move on their own: the entitlement arrives as an action, the+ // rollout flag as a posthog-js callback. An open heatmap has to follow either one.+ syncHeatmapGate: () => {+ if (values.visibleMenu !== 'heatmap') {+ return+ }+ const gated = isToolbarFeatureGated(AvailableFeature.TOOLBAR_HEATMAPS, 'toolbar-paid-heatmaps')+ if (gated) {+ actions.disableHeatmap()+ } else {+ actions.enableHeatmap()+ }+ values.getHedgehogActor()?.setOnFire(gated ? 0 : 1)+ },setOAuthTokens: () => {if (values.minimized) {actions.toggleMinimized(false)@@ -796,8 +824,10 @@ export const toolbarLogic = kea<toolbarLogicType>([actions.hideButtonSurveys()if (visibleMenu === 'heatmap') {- actions.enableHeatmap()- values.getHedgehogActor()?.setOnFire(1)+ if (!isToolbarFeatureGated(AvailableFeature.TOOLBAR_HEATMAPS, 'toolbar-paid-heatmaps')) {+ actions.enableHeatmap()+ values.getHedgehogActor()?.setOnFire(1)+ }} else if (visibleMenu === 'actions') {actions.showButtonActions()} else if (visibleMenu === 'experiments') {@@ -982,6 +1012,11 @@ export const toolbarLogic = kea<toolbarLogicType>([actions.setCspBlocksNewFunction(true)}+ cache.disposables.add(+ () => toolbarPosthogJS.onFeatureFlags(() => actions.syncHeatmapGate()),+ 'heatmapGateFlags'+ )+// Add window event listeners using disposablescache.disposables.add(() => {const clickListener = (e: MouseEvent): void => {diff --git a/frontend/src/toolbar/toolbarEntitlementsLogic.test.ts b/frontend/src/toolbar/toolbarEntitlementsLogic.test.tsnew file mode 100644index 000000000000..0d87535ea324--- /dev/null+++ b/frontend/src/toolbar/toolbarEntitlementsLogic.test.ts@@ -0,0 +1,184 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { toolbarLogic } from '~/toolbar/bar/toolbarLogic'+import { heatmapToolbarMenuLogic } from '~/toolbar/elements/heatmapToolbarMenuLogic'+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'+import {+ ToolbarEntitlements,+ ToolbarFeatureGateStatus,+ isToolbarFeatureGated,+ toolbarEntitlementsLogic,+ toolbarFeatureGateStatus,+} from '~/toolbar/toolbarEntitlementsLogic'+import { toolbarLogger } from '~/toolbar/toolbarLogger'+import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'+import { AvailableFeature } from '~/types'++describe('toolbarEntitlementsLogic', () => {+ let logic: ReturnType<typeof toolbarEntitlementsLogic.build>++ beforeEach(() => {+ initKeaTests()+ toolbarPosthogJS.stopSessionRecording = jest.fn()+ toolbarConfigLogic.build({ apiURL: 'http://localhost' }).mount()+ logic = toolbarEntitlementsLogic()+ logic.mount()+ })++ it.each([+ ['unknown', null, false],+ ['missing', {}, false],+ ['explicitly false', { toolbar_heatmaps: false }, false],+ ['explicitly true', { toolbar_heatmaps: true }, true],+ ])('isEntitled requires confirmation when a feature is %s', (_desc, payload, expected) => {+ logic.actions.loadEntitlementsSuccess(payload as Record<string, boolean> | null)+ expect(logic.values.isEntitled(AvailableFeature.TOOLBAR_HEATMAPS)).toBe(expected)+ })++ it.each<[ToolbarFeatureGateStatus, string, boolean, ToolbarEntitlements | null, boolean]>([+ ['available', 'the rollout is off', false, null, false],+ ['checking', 'the request is pending', true, null, true],+ ['unknown', 'the request failed', true, null, false],+ ['unknown', 'the feature is missing', true, {}, false],+ ['locked', 'the feature is false', true, { toolbar_heatmaps: false }, false],+ ['available', 'the feature is true', true, { toolbar_heatmaps: true }, false],+ ])('reports the gate as %s when %s', (expected, _desc, rolloutEnabled, entitlements, entitlementsLoading) => {+ expect(+ toolbarFeatureGateStatus(+ AvailableFeature.TOOLBAR_HEATMAPS,+ rolloutEnabled,+ entitlements,+ entitlementsLoading+ )+ ).toBe(expected)+ })++ it('loads the entitlement map from the endpoint', async () => {+ useMocks({+ get: {+ '/api/user/toolbar_entitlements': () => ({ entitlements: { toolbar_heatmaps: false } }),+ },+ })++ await expectLogic(logic, () => {+ logic.actions.loadEntitlements()+ })+ .toDispatchActions(['loadEntitlementsSuccess'])+ .toMatchValues({ entitlements: { toolbar_heatmaps: false } })++ expect(logic.values.isEntitled(AvailableFeature.TOOLBAR_HEATMAPS)).toBe(false)+ })++ it.each([403, 500])('denies access and reports the failure when the endpoint returns %s', async (status) => {+ const capture = jest.spyOn(toolbarPosthogJS, 'capture')+ const warn = jest.spyOn(toolbarLogger, 'warn')+ useMocks({+ get: {+ '/api/user/toolbar_entitlements': () => [status, {}],+ },+ })++ await expectLogic(logic, () => {+ logic.actions.loadEntitlements()+ })+ .toDispatchActions(['loadEntitlementsSuccess'])+ .toMatchValues({ entitlements: null })++ expect(logic.values.isEntitled(AvailableFeature.TOOLBAR_HEATMAPS)).toBe(false)+ expect(capture).toHaveBeenCalledWith(+ 'toolbar api request',+ expect.objectContaining({ pathname: '/api/user/toolbar_entitlements', status })+ )+ expect(warn).toHaveBeenCalledWith('entitlements', expect.any(String), expect.objectContaining({ status }))+ jest.restoreAllMocks()+ })++ it('gives up on a stalled request so the retry becomes reachable', async () => {+ jest.useFakeTimers()+ useMocks({ get: { '/api/user/toolbar_entitlements': () => new Promise(() => {}) } })++ logic.actions.loadEntitlements()+ expect(logic.values.entitlementsLoading).toBe(true)++ // Well past the request's own bound. Without one, the loader would stay pending and the+ // menu would keep showing the spinner, which has no retry.+ jest.advanceTimersByTime(10_000)+ jest.useRealTimers()+ await expectLogic(logic).toDispatchActions(['loadEntitlementsSuccess'])++ expect(logic.values.entitlementsLoading).toBe(false)+ expect(logic.values.entitlements).toBe(null)+ })++ it('keeps an open heatmap disabled until access is confirmed and disables it after access is lost', async () => {+ jest.spyOn(toolbarPosthogJS, 'getFeatureFlag').mockReturnValue(true)+ const toolbar = toolbarLogic()+ toolbar.mount()+ const heatmap = heatmapToolbarMenuLogic()+ let finishRequest!: (value: unknown) => void+ const response = new Promise((resolve) => {+ finishRequest = resolve+ })+ useMocks({ get: { '/api/user/toolbar_entitlements': () => response } })++ logic.actions.loadEntitlements()+ toolbar.actions.setVisibleMenu('heatmap')+ expect(logic.values.entitlementsLoading).toBe(true)+ expect(isToolbarFeatureGated(AvailableFeature.TOOLBAR_HEATMAPS, 'toolbar-paid-heatmaps')).toBe(true)+ expect(heatmap.values.heatmapEnabled).toBe(false)++ await expectLogic(logic, () => {+ finishRequest({ entitlements: { toolbar_heatmaps: true } })+ }).toFinishAllListeners()+ expect(logic.values.entitlementsLoading).toBe(false)+ expect(heatmap.values.heatmapEnabled).toBe(true)++ await expectLogic(logic, () => {+ logic.actions.loadEntitlements()+ expect(logic.values.isEntitled(AvailableFeature.TOOLBAR_HEATMAPS)).toBe(false)+ expect(heatmap.values.heatmapEnabled).toBe(false)+ }).toFinishAllListeners()+ expect(heatmap.values.heatmapEnabled).toBe(true)++ logic.actions.loadEntitlementsSuccess({ toolbar_heatmaps: false })+ expect(heatmap.values.heatmapEnabled).toBe(false)+ toolbar.unmount()+ jest.restoreAllMocks()+ })++ it('disables an open heatmap when the rollout flag arrives after the menu opened', async () => {+ let onFeatureFlags: (() => void) | undefined+ jest.spyOn(toolbarPosthogJS, 'onFeatureFlags').mockImplementation((callback: any) => {+ onFeatureFlags = callback+ return () => {}+ })+ // The internal posthog instance bootstraps with no flags, so the gate reads as off+ // until its own /flags response lands.+ const getFeatureFlag = jest.spyOn(toolbarPosthogJS, 'getFeatureFlag').mockReturnValue(undefined)+ logic.actions.loadEntitlementsSuccess({ toolbar_heatmaps: false })+ const toolbar = toolbarLogic()+ toolbar.mount()+ const heatmap = heatmapToolbarMenuLogic()++ toolbar.actions.setVisibleMenu('heatmap')+ expect(heatmap.values.heatmapEnabled).toBe(true)++ getFeatureFlag.mockReturnValue(true)+ await expectLogic(toolbar, () => {+ onFeatureFlags?.()+ }).toFinishAllListeners()++ expect(heatmap.values.heatmapEnabled).toBe(false)+ toolbar.unmount()+ jest.restoreAllMocks()+ })++ it.each([true, false])('gates unmounted entitlement logic only when rollout is %s', (rolloutEnabled) => {+ initKeaTests()+ jest.spyOn(toolbarPosthogJS, 'getFeatureFlag').mockReturnValue(rolloutEnabled)+ expect(isToolbarFeatureGated(AvailableFeature.TOOLBAR_HEATMAPS, 'toolbar-paid-heatmaps')).toBe(rolloutEnabled)+ jest.restoreAllMocks()+ })+})diff --git a/frontend/src/toolbar/toolbarEntitlementsLogic.ts b/frontend/src/toolbar/toolbarEntitlementsLogic.tsnew file mode 100644index 000000000000..178f60957bdd--- /dev/null+++ b/frontend/src/toolbar/toolbarEntitlementsLogic.ts@@ -0,0 +1,184 @@+import { MakeLogicType, afterMount, connect, kea, listeners, path, selectors, useValues } from 'kea'+import { loaders } from 'kea-loaders'++import { FeatureFlagKey } from 'lib/constants'+import { permanentlyMount } from 'lib/utils/kea-logic-builders'++import type { ToolbarEntitlementsApiEntitlements } from '~/generated/core/api.schemas'+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'+import { captureToolbarApiRequest } from '~/toolbar/toolbarFetch'+import { toolbarLogger } from '~/toolbar/toolbarLogger'+import { toolbarPosthogJS, useToolbarFeatureFlag } from '~/toolbar/toolbarPosthogJS'+import { safeFetch } from '~/toolbar/utils'+import { AvailableFeature } from '~/types'++export type ToolbarEntitlements = ToolbarEntitlementsApiEntitlements++const ENTITLEMENTS_PATH = '/api/user/toolbar_entitlements'+// Matches the toolbar's other blocking check, the uiHost reachability HEAD request.+const ENTITLEMENTS_TIMEOUT_MS = 5000++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface toolbarEntitlementsLogicValues {+ isAuthenticated: boolean // toolbarConfigLogic+ uiHost: string // toolbarConfigLogic+ entitlements: ToolbarEntitlements | null+ entitlementsLoading: boolean+ isEntitled: (feature: AvailableFeature) => boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface toolbarEntitlementsLogicActions {+ setOAuthTokens: (+ accessToken: string,+ refreshToken: string | null,+ clientId: string+ ) => {+ accessToken: string+ clientId: string+ refreshToken: string | null+ } // toolbarConfigLogic+ loadEntitlements: () => any+ loadEntitlementsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadEntitlementsSuccess: (+ entitlements: ToolbarEntitlementsApiEntitlements | null,+ payload?: any+ ) => {+ entitlements: ToolbarEntitlementsApiEntitlements | null+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface toolbarEntitlementsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ isEntitled: (+ entitlements: ToolbarEntitlementsApiEntitlements | null,+ entitlementsLoading: boolean+ ) => (feature: AvailableFeature) => boolean+ }+}++export type toolbarEntitlementsLogicType = MakeLogicType<+ toolbarEntitlementsLogicValues,+ toolbarEntitlementsLogicActions,+ Record<string, any>,+ toolbarEntitlementsLogicMeta+>++export const toolbarEntitlementsLogic = kea<toolbarEntitlementsLogicType>([+ path(['toolbar', 'toolbarEntitlementsLogic']),+ connect(() => ({+ values: [toolbarConfigLogic, ['uiHost', 'isAuthenticated']],+ actions: [toolbarConfigLogic, ['setOAuthTokens']],+ })),+ loaders(({ values }) => ({+ entitlements: [+ null as ToolbarEntitlements | null,+ {+ loadEntitlements: async () => {+ const startTime = performance.now()+ // 0 keeps a network failure distinguishable from an HTTP status in telemetry.+ let status = 0+ try {+ const response = await safeFetch(`${values.uiHost}${ENTITLEMENTS_PATH}`, {+ credentials: 'include',+ // A stall would hold the gate closed for the whole page session,+ // because the retry lives in the failed branch, not the pending one.+ signal: AbortSignal.timeout(ENTITLEMENTS_TIMEOUT_MS),+ })+ status = response.status+ if (!response.ok) {+ toolbarLogger.warn('entitlements', 'Entitlements request failed', { status })+ return null+ }+ const data = await response.json()+ return (data.entitlements as ToolbarEntitlements) ?? null+ } catch (error) {+ toolbarLogger.warn('entitlements', 'Entitlements request failed', {+ status,+ error: error instanceof Error ? error.message : String(error),+ })+ return null+ } finally {+ captureToolbarApiRequest({+ url: ENTITLEMENTS_PATH,+ method: 'GET',+ status,+ durationMs: Math.round(performance.now() - startTime),+ })+ }+ },+ },+ ],+ })),+ selectors({+ isEntitled: [+ (s) => [s.entitlements, s.entitlementsLoading],+ (entitlements: ToolbarEntitlements | null, entitlementsLoading: boolean) =>+ (feature: AvailableFeature): boolean =>+ !entitlementsLoading && entitlements?.[feature] === true,+ ],+ }),+ listeners(({ actions }) => ({+ setOAuthTokens: () => {+ actions.loadEntitlements()+ },+ })),+ afterMount(({ actions, values }) => {+ if (values.isAuthenticated) {+ actions.loadEntitlements()+ }+ }),+ permanentlyMount(),+])++/** `checking` and `unknown` block the feature like `locked` does, but the plan is not the reason. */+export type ToolbarFeatureGateStatus = 'available' | 'checking' | 'unknown' | 'locked'++export function toolbarFeatureGateStatus(+ feature: AvailableFeature,+ rolloutEnabled: boolean,+ entitlements: ToolbarEntitlements | null,+ entitlementsLoading: boolean+): ToolbarFeatureGateStatus {+ if (!rolloutEnabled) {+ return 'available'+ }+ if (entitlementsLoading) {+ return 'checking'+ }+ const entitled = entitlements?.[feature]+ if (entitled === true) {+ return 'available'+ }+ return entitled === false ? 'locked' : 'unknown'+}++export function useToolbarFeatureGateStatus(+ feature: AvailableFeature,+ rolloutFlag: FeatureFlagKey+): ToolbarFeatureGateStatus {+ const rolloutEnabled = useToolbarFeatureFlag(rolloutFlag)+ const { entitlements, entitlementsLoading } = useValues(toolbarEntitlementsLogic)+ return toolbarFeatureGateStatus(feature, rolloutEnabled, entitlements, entitlementsLoading)+}++export function isToolbarFeatureGated(feature: AvailableFeature, rolloutFlag: FeatureFlagKey): boolean {+ const rolloutEnabled = !!toolbarPosthogJS.getFeatureFlag(rolloutFlag)+ const values = toolbarEntitlementsLogic.findMounted()?.values+ return (+ toolbarFeatureGateStatus(+ feature,+ rolloutEnabled,+ values?.entitlements ?? null,+ values?.entitlementsLoading ?? false+ ) !== 'available'+ )+}diff --git a/frontend/src/toolbar/toolbarFetch.ts b/frontend/src/toolbar/toolbarFetch.tsindex 8e16fafba999..c4dc5127b49c 100644--- a/frontend/src/toolbar/toolbarFetch.ts+++ b/frontend/src/toolbar/toolbarFetch.ts@@ -115,15 +115,12 @@ export async function toolbarFetch(})})- const durationMs = Math.round(performance.now() - startTime)- const { pathname } = combineUrl(url)-- toolbarPosthogJS.capture('toolbar api request', {+ captureToolbarApiRequest({+ url,method,- pathname,status: response.status,- duration_ms: durationMs,- did_token_retry: didRetry,+ durationMs: Math.round(performance.now() - startTime),+ didTokenRetry: didRetry,})if (response.status === 403) {@@ -136,6 +133,35 @@ export async function toolbarFetch(return response}+/**+ * The one place that emits `toolbar api request`, so every toolbar request reports the same+ * shape. Exported for the requests that cannot go through `toolbarFetch` — the entitlements+ * load carries the session cookie rather than a bearer token, and still belongs in this+ * telemetry.+ */+export function captureToolbarApiRequest({+ url,+ method,+ status,+ durationMs,+ didTokenRetry = false,+}: {+ url: string+ method: string+ /** HTTP status, or 0 when the request never reached the server. */+ status: number+ durationMs: number+ didTokenRetry?: boolean+}): void {+ toolbarPosthogJS.capture('toolbar api request', {+ method,+ pathname: combineUrl(url).pathname,+ status,+ duration_ms: durationMs,+ did_token_retry: didTokenRetry,+ })+}+export interface ToolbarMediaUploadResponse {id: stringimage_location: stringdiff --git a/frontend/src/toolbar/urls.test.ts b/frontend/src/toolbar/urls.test.tsindex b5fee6a787f3..0e5558388adf 100644--- a/frontend/src/toolbar/urls.test.ts+++ b/frontend/src/toolbar/urls.test.ts@@ -15,6 +15,7 @@ describe('toolbar urls duplicate', () => {featureFlag: [[123], ['my-flag']],featureFlags: [[], ['history']],heatmap: [['hm-abc123'], [123]],+ organizationBilling: [[], [['product_analytics']], [['product_analytics', 'session_replay']]],productTour: [['tour-id'], ['tour-id', 'step=2'], ['tour-id', '?step=2']],sessionProfile: [['session-uuid']],settings: [[], ['project'], ['environment-customization', 'date-and-time'], ['user']],diff --git a/frontend/src/toolbar/urls.ts b/frontend/src/toolbar/urls.tsindex ede0167f05b0..1a22c748544a 100644--- a/frontend/src/toolbar/urls.ts+++ b/frontend/src/toolbar/urls.ts@@ -24,6 +24,8 @@ export const urls = {featureFlag: (id: string | number): string => `/feature_flags/${id}`,featureFlags: (tab?: string): string => `/feature_flags${tab ? `?tab=${tab}` : ''}`,heatmap: (id: string | number): string => `/heatmaps/${id}`,+ organizationBilling: (products?: string[]): string =>+ `/organization/billing${products && products.length ? `?products=${products.join(',')}` : ''}`,productTour: (id: string, params?: string): string =>`/product_tours/${id}${params ? `?${params.startsWith('?') ? params.slice(1) : params}` : ''}`,sessionProfile: (id: string): string => `/sessions/${id}`,diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex b94785beaed7..e3cf191f82df 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -235,6 +235,7 @@ export enum AvailableFeature {DATA_COLOR_THEMES = 'data_color_themes',ORGANIZATION_INVITE_SETTINGS = 'organization_invite_settings',ORGANIZATION_SECURITY_SETTINGS = 'organization_security_settings',+ TOOLBAR_HEATMAPS = 'toolbar_heatmaps',}type AvailableFeatureUnion = `${AvailableFeature}`diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex 3df9aaa477cb..2e1d2ee8044d 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -2667,6 +2667,42 @@ class TestToolbarAccessControl(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ @parameterized.expand(+ [+ ("cloud_feature_absent", True, [], False),+ (+ "cloud_feature_available",+ True,+ [{"key": AvailableFeature.TOOLBAR_HEATMAPS, "name": AvailableFeature.TOOLBAR_HEATMAPS}],+ True,+ ),+ ("self_hosted_feature_absent", False, [], True),+ ]+ )+ def test_get_toolbar_entitlements_reflects_org_features(self, _name, cloud, extra_features, expected):+ self.organization.available_product_features = [+ *(self.organization.available_product_features or []),+ *extra_features,+ ]+ self.organization.save()++ with self.is_cloud(cloud):+ response = self.client.get("/api/user/toolbar_entitlements/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["entitlements"]["toolbar_heatmaps"], expected)++ @parameterized.expand([("toolbar_access", status.HTTP_403_FORBIDDEN), ("session", status.HTTP_401_UNAUTHORIZED)])+ def test_get_toolbar_entitlements_denied_without_required_access(self, missing_access: str, expected: int) -> None:+ if missing_access == "session":+ self.client.logout()+ else:+ self._deny_toolbar_access()++ response = self.client.get("/api/user/toolbar_entitlements/")++ self.assertEqual(response.status_code, expected)+def test_redirect_to_site_allowed_with_default_access(self):response = self.client.get("/api/user/redirect_to_site/?appUrl=http%3A%2F%2F127.0.0.1%3A8010")diff --git a/posthog/api/user.py b/posthog/api/user.pyindex 1ba880bfc2c6..901c79aee7a7 100644--- a/posthog/api/user.py+++ b/posthog/api/user.py@@ -38,6 +38,7 @@ from prometheus_client import Counterfrom rest_framework import exceptions, mixins, serializers, status, viewsetsfrom rest_framework.exceptions import NotFoundfrom rest_framework.permissions import AllowAny, IsAuthenticated+from rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.views import APIViewfrom social_django.models import UserSocialAuth@@ -76,7 +77,8 @@ from posthog.auth import (SessionAuthentication,session_auth_required,)-from posthog.constants import INVITE_DAYS_VALIDITY, PERMITTED_FORUM_DOMAINS+from posthog.cloud_utils import is_cloud+from posthog.constants import INVITE_DAYS_VALIDITY, PERMITTED_FORUM_DOMAINS, AvailableFeaturefrom posthog.email import is_email_availablefrom posthog.event_usage import (report_user_deleted_account,@@ -1867,6 +1869,57 @@ def get_toolbar_preloaded_flags(request):return JsonResponse({"featureFlags": feature_flags})+TOOLBAR_ENTITLEMENT_FEATURES: list[AvailableFeature] = [+ AvailableFeature.TOOLBAR_HEATMAPS,+]+++def _toolbar_entitlements(organization: Organization) -> dict[str, bool]:+ """Gated toolbar tools are a Cloud plan entitlement, so every self-hosted deployment keeps them."""+ if not is_cloud():+ return {feature.value: True for feature in TOOLBAR_ENTITLEMENT_FEATURES}+ return {feature.value: organization.is_feature_available(feature) for feature in TOOLBAR_ENTITLEMENT_FEATURES}+++class ToolbarEntitlementsSerializer(serializers.Serializer):+ entitlements = serializers.DictField(+ child=serializers.BooleanField(),+ help_text="Whether the current organization has each toolbar plan entitlement, keyed by feature name.",+ )+++class ToolbarEntitlementsErrorSerializer(serializers.Serializer):+ error = serializers.CharField(help_text="Why toolbar entitlements could not be retrieved.")+++class ToolbarEntitlementsView(APIView):+ authentication_classes = [SessionAuthentication]+ permission_classes = [IsAuthenticated]+ include_in_api_docs = True++ @extend_schema(+ extensions={"x-product": "core"},+ responses={+ 200: ToolbarEntitlementsSerializer,+ 400: ToolbarEntitlementsErrorSerializer,+ 403: ToolbarEntitlementsErrorSerializer,+ },+ )+ def get(self, request: Request) -> JsonResponse:+ user = cast(User, request.user)+ team = user.team+ if not team:+ return JsonResponse({"error": "No team found"}, status=400)++ if not _user_can_access_toolbar(user, team):+ return JsonResponse({"error": "Unauthorized"}, status=403)++ return JsonResponse({"entitlements": _toolbar_entitlements(team.organization)})+++get_toolbar_entitlements = session_auth_required(ToolbarEntitlementsView.as_view())++@session_auth_required@require_http_methods(["POST"])def prepare_toolbar_preloaded_flags(request):diff --git a/posthog/constants.py b/posthog/constants.pyindex 3705a592c6ae..268bc8f17e95 100644--- a/posthog/constants.py+++ b/posthog/constants.py@@ -56,6 +56,7 @@ class AvailableFeature(StrEnum):APPROVALS = "approvals"XAA_AUTHENTICATION = "xaa_authentication"POSTHOG_CODE_USAGE = "posthog_code_usage"+ TOOLBAR_HEATMAPS = "toolbar_heatmaps"TREND_FILTER_TYPE_ACTIONS = "actions"diff --git a/posthog/urls.py b/posthog/urls.pyindex 5db14ce9becc..6da70e9a6bbc 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -174,6 +174,7 @@ urlpatterns = [path("", include(tf_urls)),opt_slash_path("api/user/prepare_toolbar_preloaded_flags", user.prepare_toolbar_preloaded_flags),opt_slash_path("api/user/get_toolbar_preloaded_flags", user.get_toolbar_preloaded_flags),+ opt_slash_path("api/user/toolbar_entitlements", user.get_toolbar_entitlements),opt_slash_path("api/user/toolbar_oauth_refresh", user.toolbar_oauth_refresh),path("toolbar_oauth/authorize/", login_required(user.toolbar_oauth_authorize)),path("toolbar_oauth/callback", user.toolbar_oauth_callback),diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yamlindex 807ed5a1293a..c371118c8a19 100644--- a/services/mcp/definitions/core.yaml+++ b/services/mcp/definitions/core.yaml@@ -579,6 +579,9 @@ tools:param_overrides:uuid:description: User UUID, or `@me` to target the authenticated user.+ user-toolbar-entitlements-retrieve:+ operation: user_toolbar_entitlements_retrieve+ enabled: falseusers-cancel-email-change-request-partial-update:operation: users_cancel_email_change_request_partial_updateenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6913c8949f2b..d6ba72dc9885 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -93848,6 +93848,21 @@ export namespace Schemas {tags?: string[];}+ /**+ * Whether the current organization has each toolbar plan entitlement, keyed by feature name.+ */+ export type ToolbarEntitlementsEntitlements = {[key: string]: boolean};++ export interface ToolbarEntitlements {+ /** Whether the current organization has each toolbar plan entitlement, keyed by feature name. */+ entitlements: ToolbarEntitlementsEntitlements;+ }++ export interface ToolbarEntitlementsError {+ /** Why toolbar entitlements could not be retrieved. */+ error: string;+ }+export interface TopPage {/** Host for the page, if recorded. */host: string;