Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

6.0 KB
Raw Blame
import { useActions, useAsyncActions, useValues } from 'kea'
import { useCallback } from 'react'

import { IconArrowRight, IconLock } from '@posthog/icons'
import { LemonButton, Popover, PopoverProps, Tooltip } from '@posthog/lemon-ui'

import { organizationLogic } from 'scenes/organizationLogic'

import { aiConsentLogic } from '~/layout/ai/aiConsentLogic'

import { AIAccessRequest } from './AIAccessRequest'
import { getExternalAIProvidersTooltipTitle, openAIConsentLegalDialog } from './aiConsentCopy'

export function AIConsentPopoverContent({
    onApprove,
    onDismiss,
    approvalDisabledReason,
    hideTrainingDisclaimer,
}: {
    onApprove: () => void | Promise<void>
    onDismiss: () => void
    approvalDisabledReason: string | null
    /** Omit the "won't be used for training third-party models" line where it doesn't apply. */
    hideTrainingDisclaimer?: boolean
}): JSX.Element {
    const focusOnMount = useCallback((el: HTMLButtonElement | null) => {
        el?.focus()
    }, [])

    return (
        <div className="flex flex-col gap-2 m-1.5 max-w-prose">
            <p className="font-medium text-pretty">
                PostHog AI needs your approval to potentially process identifying user data with{' '}
                <Tooltip title={getExternalAIProvidersTooltipTitle()}>
                    <dfn>external AI providers</dfn>
                </Tooltip>
                .{!hideTrainingDisclaimer && <i> Your data won't be used for training third-party models.</i>}
            </p>
            <div className="flex gap-1.5 self-end">
                <LemonButton data-attr="ai-consent-cancel" type="secondary" size="xsmall" onClick={onDismiss}>
                    Cancel
                </LemonButton>
                <LemonButton
                    data-attr="ai-consent-approve"
                    type="primary"
                    size="xsmall"
                    onClick={() => openAIConsentLegalDialog({ onConfirm: onApprove })}
                    sideIcon={approvalDisabledReason ? <IconLock /> : <IconArrowRight />}
                    disabledReason={approvalDisabledReason}
                    tooltip={approvalDisabledReason ? undefined : 'You are approving this as an organization admin'}
                    tooltipPlacement="bottom"
                    ref={focusOnMount}
                >
                    I allow AI analysis in this organization
                </LemonButton>
            </div>
        </div>
    )
}

function AIAccessRequestPopoverContent(): JSX.Element {
    return (
        <div className="flex flex-col gap-2 m-1.5 max-w-prose">
            <p className="font-medium text-pretty">
                PostHog AI access has not been enabled for this organization. You can request access from an
                organization owner or admin.
            </p>
            <div className="flex self-end">
                <AIAccessRequest />
            </div>
        </div>
    )
}

export function AIConsentPopoverWrapper({
    hidden,
    children,
    ignoreDismissal,
    onApprove,
    onBeforeApprove,
    onDismiss,
    hideTrainingDisclaimer,
    pendingRedirectUrl,
    ...popoverProps
}: Pick<PopoverProps, 'placement' | 'fallbackPlacements' | 'middleware' | 'showArrow'> & {
    children: JSX.Element
    hidden?: boolean
    /** Always show popover regardless of prior dismissal. */
    ignoreDismissal?: boolean
    onApprove?: () => void
    /**
     * Runs once the person confirms, before the approval request. That request can trigger a
     * full-page SSO reauthentication, so persist here anything `onApprove` would need after it.
     */
    onBeforeApprove?: () => void
    onDismiss?: () => void
    /** Passed through to AIConsentPopoverContent. */
    hideTrainingDisclaimer?: boolean
    /**
     * URL to continue to once consent is approved. Approving can trigger a full-page SSO
     * reauthentication redirect that unloads the page before the approval request is sent, so the
     * intent is persisted and `aiConsentLogic` finishes the approval and navigation on return.
     */
    pendingRedirectUrl?: string
}): JSX.Element {
    const { acceptDataProcessing } = useAsyncActions(aiConsentLogic)
    const { dataProcessingApprovalDisabledReason, dataProcessingAccepted, dataProcessingDismissed } =
        useValues(aiConsentLogic)
    const { dismissDataProcessing, setPendingApprovalRedirect } = useActions(aiConsentLogic)
    const { isAdminOrOwner, currentOrganization } = useValues(organizationLogic)

    const handleDismiss = (): void => {
        if (!ignoreDismissal) {
            dismissDataProcessing()
        }
        onDismiss?.()
    }

    return (
        <Popover
            overlay={
                isAdminOrOwner ? (
                    <AIConsentPopoverContent
                        approvalDisabledReason={dataProcessingApprovalDisabledReason}
                        hideTrainingDisclaimer={hideTrainingDisclaimer}
                        onApprove={async () => {
                            if (pendingRedirectUrl && currentOrganization) {
                                // Cleared by the acceptDataProcessing listener on success or failure.
                                setPendingApprovalRedirect({
                                    url: pendingRedirectUrl,
                                    organizationId: currentOrganization.id,
                                    setAt: Date.now(),
                                })
                            }
                            onBeforeApprove?.()
                            await acceptDataProcessing()
                            onApprove?.()
                        }}
                        onDismiss={handleDismiss}
                    />
                ) : (
                    <AIAccessRequestPopoverContent />
                )
            }
            style={{ zIndex: 'var(--z-modal)' }} // Don't show above the re-authentication modal
            visible={!hidden && !dataProcessingAccepted && (ignoreDismissal || !dataProcessingDismissed)}
            onClickOutside={handleDismiss}
            {...popoverProps}
        >
            {children}
        </Popover>
    )
}