: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
import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
import { router } from 'kea-router'
import posthog from 'posthog-js'
import { LOOKAHEAD_EXPIRY_SECONDS } from 'lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic'
import { OrganizationMembershipLevel } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { organizationLogic } from 'scenes/organizationLogic'
import { userLogic } from 'scenes/userLogic'
import type { OrganizationType, UserType } from '~/types'
import { requestAiAccessCreate } from 'products/platform_features/frontend/generated/api'
// Keep this stored across all projects, only display this once per month
const AI_DATA_PROCESSING_DISMISSED_STORAGE_KEY = `posthog_ai_data_processing_dismissed_${dayjs().format('YYYY-MM')}`
// Records, per organization, that this member has already asked an admin to enable
// PostHog AI — so the request button doesn't invite repeated submissions.
const AI_ACCESS_REQUESTED_STORAGE_KEY = 'posthog_ai_access_requested_by_org'
// Survives the full-page SSO reauthentication redirect, which unloads the page before the approval
// request is sent, so the confirmed intent can be replayed on return.
const AI_CONSENT_PENDING_REDIRECT_STORAGE_KEY = 'posthog_ai_consent_pending_redirect'
export const AI_CONSENT_PENDING_REDIRECT_TTL_MS = 15 * 60 * 1000
export interface PendingApprovalRedirect {
url: string
organizationId: string
setAt: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiConsentLogicValues {
currentOrganization: OrganizationType | null // organizationLogic
user: UserType | null // userLogic
aiAccessRequested: boolean
aiAccessRequestedByOrg: Record<string, boolean>
dataProcessingAccepted: boolean
dataProcessingApprovalDisabledReason: string | null
dataProcessingDismissed: boolean
pendingApprovalRedirect: PendingApprovalRedirect | null
requestingAiAccess: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiConsentLogicActions {
acceptDataProcessing: (
testOnlyOverride?: boolean,
resumeUrl?: string
) => {
resumeUrl: string | undefined
testOnlyOverride: boolean | undefined
}
dismissDataProcessing: () => {
value: true
}
markAiAccessRequested: (organizationId: string) => {
organizationId: string
}
requestAiAccess: () => {
value: true
}
requestAiAccessError: () => {
value: true
}
setPendingApprovalRedirect: (redirect: PendingApprovalRedirect | null) => {
redirect: PendingApprovalRedirect | null
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiConsentLogicMeta {
__keaTypeGenInternalSelectorTypes: {
dataProcessingAccepted: (currentOrganization: OrganizationType | null) => boolean
dataProcessingApprovalDisabledReason: (currentOrganization: OrganizationType | null) => string | null
aiAccessRequested: (
aiAccessRequestedByOrg: Record<string, boolean>,
currentOrganization: OrganizationType | null
) => boolean
}
}
export type aiConsentLogicType = MakeLogicType<
aiConsentLogicValues,
aiConsentLogicActions,
Record<string, any>,
aiConsentLogicMeta
>
export const aiConsentLogic = kea<aiConsentLogicType>([
path(['layout', 'ai', 'aiConsentLogic']),
connect(() => ({
values: [organizationLogic, ['currentOrganization'], userLogic, ['user']],
})),
actions({
acceptDataProcessing: (testOnlyOverride?: boolean, resumeUrl?: string) => ({ testOnlyOverride, resumeUrl }),
dismissDataProcessing: true,
requestAiAccess: true,
markAiAccessRequested: (organizationId: string) => ({ organizationId }),
requestAiAccessError: true,
setPendingApprovalRedirect: (redirect: PendingApprovalRedirect | null) => ({ redirect }),
}),
reducers({
dataProcessingDismissed: [
false,
{ persist: true, storageKey: AI_DATA_PROCESSING_DISMISSED_STORAGE_KEY },
{
dismissDataProcessing: () => true,
},
],
pendingApprovalRedirect: [
null as PendingApprovalRedirect | null,
{ persist: true, storageKey: AI_CONSENT_PENDING_REDIRECT_STORAGE_KEY },
{
setPendingApprovalRedirect: (_, { redirect }) => redirect,
},
],
requestingAiAccess: [
false,
{
requestAiAccess: () => true,
markAiAccessRequested: () => false,
requestAiAccessError: () => false,
},
],
aiAccessRequestedByOrg: [
{} as Record<string, boolean>,
{ persist: true, storageKey: AI_ACCESS_REQUESTED_STORAGE_KEY },
{
markAiAccessRequested: (state, { organizationId }) => ({ ...state, [organizationId]: true }),
},
],
}),
listeners(({ actions, values }) => ({
acceptDataProcessing: async ({ testOnlyOverride, resumeUrl }) => {
// Attempt and outcome are captured separately so a gate that accepts clicks but never
// approves shows up as a gap between the two, rather than only in a session recording.
posthog.capture('ai_consent_approval_submitted', { is_resumed: !!resumeUrl })
try {
await organizationLogic.asyncActions.updateOrganization({
is_ai_data_processing_approved: testOnlyOverride ?? true,
})
} catch (error) {
// A real failure (a lost SSO redirect unloads the page instead of rejecting).
actions.setPendingApprovalRedirect(null)
posthog.capture('ai_consent_approval_failed')
throw error
}
actions.setPendingApprovalRedirect(null)
posthog.capture('ai_consent_approved')
lemonToast.success('AI data processing approved')
if (resumeUrl) {
router.actions.push(resumeUrl)
}
},
requestAiAccess: async () => {
const organization = values.currentOrganization
if (!organization) {
actions.requestAiAccessError()
return
}
posthog.capture('ai_access_request_submitted')
try {
// Backend notifies the org admins/owners via a customer.io email — keeps the
// recipient resolution server-side so it can't be tampered with from the client.
await requestAiAccessCreate(organization.id)
actions.markAiAccessRequested(organization.id)
posthog.capture('ai_access_requested')
lemonToast.success('Request sent to your organization admins')
} catch {
actions.requestAiAccessError()
posthog.capture('ai_access_request_failed')
lemonToast.error('Could not send your request. Please try again.')
}
},
})),
selectors({
dataProcessingAccepted: [
(s) => [s.currentOrganization],
(currentOrganization: OrganizationType | null): boolean =>
!!currentOrganization?.is_ai_data_processing_approved,
],
dataProcessingApprovalDisabledReason: [
(s) => [s.currentOrganization],
(currentOrganization: OrganizationType | null): string | null =>
!currentOrganization?.membership_level ||
currentOrganization.membership_level < OrganizationMembershipLevel.Admin
? `Ask an admin or owner of ${currentOrganization?.name} to approve this`
: null,
],
aiAccessRequested: [
(s) => [s.aiAccessRequestedByOrg, s.currentOrganization],
(aiAccessRequestedByOrg: Record<string, boolean>, currentOrganization: OrganizationType | null): boolean =>
!!(currentOrganization && aiAccessRequestedByOrg[currentOrganization.id]),
],
}),
events(({ actions, asyncActions, values }) => ({
afterMount: () => {
const pending = values.pendingApprovalRedirect
if (!pending) {
return
}
const sameOrg = pending.organizationId === values.currentOrganization?.id
if (values.dataProcessingAccepted) {
actions.setPendingApprovalRedirect(null)
if (sameOrg) {
router.actions.push(pending.url)
}
return
}
// Consent missing: the approval request was lost to the SSO redirect. Replay the
// already-confirmed approval, guarded so it cannot misfire later, elsewhere, or
// straight back into the reauth modal.
const fresh = Date.now() - pending.setAt <= AI_CONSENT_PENDING_REDIRECT_TTL_MS
const canApprove = !values.dataProcessingApprovalDisabledReason
const sessionHasRunway =
dayjs(values.user?.sensitive_session_expires_at).diff(dayjs(), 'seconds') >= LOOKAHEAD_EXPIRY_SECONDS
if (fresh && sameOrg && canApprove && sessionHasRunway) {
// Failure surfaces via organizationLogic's updateOrganizationFailure toast.
void asyncActions.acceptDataProcessing(undefined, pending.url).catch(() => {})
} else {
actions.setPendingApprovalRedirect(null)
}
},
})),
])