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.

feat(max): add onboarding AI consent and non-admin access request (#62105)

Joe Martindb0fad4aeff1
diff --git a/frontend/src/scenes/max/components/QuestionInput.tsx b/frontend/src/scenes/max/components/QuestionInput.tsx
index a747e81affd0..c393ceeec60b 100644
--- a/frontend/src/scenes/max/components/QuestionInput.tsx
+++ b/frontend/src/scenes/max/components/QuestionInput.tsx
@@ -144,7 +144,7 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
},
ref
) {
- const { dataProcessingAccepted, dataProcessingApprovalDisabledReason } = useValues(maxGlobalLogic)
+ const { dataProcessingAccepted } = useValues(maxGlobalLogic)
const { question, panelId: maxPanelId } = useValues(maxLogic)
const { setQuestion } = useActions(maxLogic)
const { user } = useValues(userLogic)
@@ -258,11 +258,6 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
if (cancelLoading) {
disabledReason = 'Cancelling...'
}
- // For non-admins, disable button when consent not given (admins see popup instead)
- const isAdmin = !dataProcessingApprovalDisabledReason
- if (!dataProcessingAccepted && !isAdmin && !disabledReason) {
- disabledReason = dataProcessingApprovalDisabledReason
- }
useEffect(() => {
if (!streamingActive && textAreaRef?.current) {
@@ -476,7 +471,7 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
mainAxis: state.placement.includes('top') ? 30 : 1,
})),
]}
- hidden={!isAdmin || (!threadLoading && !pendingPrompt)}
+ hidden={!threadLoading && !pendingPrompt}
>
<LemonButton
data-attr={showStopButton ? 'max-stop-generation' : 'max-send-message'}
@@ -501,9 +496,9 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
submit(inputValue)
}}
tooltip={
- disabledReason ? (
- disabledReason
- ) : showStopButton ? (
+ // If there's a disabled reason tooltip shown below, don't show a tooltip here
+ // Else, show the tooltip based on the button state
+ disabledReason ? undefined : showStopButton ? (
<>
Let's bail <KeyboardShortcut enter />
</>
diff --git a/frontend/src/scenes/max/maxGlobalLogic.tsx b/frontend/src/scenes/max/maxGlobalLogic.tsx
index 83aa58d10598..c0166574d1b4 100644
--- a/frontend/src/scenes/max/maxGlobalLogic.tsx
+++ b/frontend/src/scenes/max/maxGlobalLogic.tsx
@@ -18,6 +18,7 @@ import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePane
import { Conversation, ConversationDetail, SidePanelTab } from '~/types'
import { conversationsDestroy } from 'products/conversations/frontend/generated/api'
+import { requestAiAccessCreate } from 'products/platform_features/frontend/generated/api'
import { TOOL_DEFINITIONS, ToolRegistration } from './max-constants'
import type { maxGlobalLogicType } from './maxGlobalLogicType'
@@ -25,7 +26,13 @@ import { SIDE_PANEL_PANEL_ID, maxLogic, mergeConversationHistory, mergeConversat
// Keep this stored across all projects, only display this once per device
const AI_LIABILITY_NOTICE_STORAGE_KEY = 'posthog_ai_liability_notice_dismissed'
-const AI_DATA_PROCESSING_DISMISSED_STORAGE_KEY = 'posthog_ai_data_processing_dismissed'
+
+// 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'
/** Tools available everywhere. These CAN be shadowed by contextual tools for scene-specific handling (e.g. to intercept insight creation). */
export const STATIC_TOOLS: ToolRegistration[] = [
@@ -105,6 +112,9 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([
deleteConversation: (id: string) => ({ id }),
dismissLiabilityNotice: true,
dismissDataProcessing: true,
+ requestAiAccess: true,
+ markAiAccessRequested: (organizationId: string) => ({ organizationId }),
+ requestAiAccessError: true,
}),
loaders(({ values }) => ({
@@ -178,6 +188,21 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([
dismissDataProcessing: () => true,
},
],
+ 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 }) => {
@@ -185,6 +210,23 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([
is_ai_data_processing_approved: testOnlyOverride ?? true,
})
},
+ requestAiAccess: async () => {
+ const organization = values.currentOrganization
+ if (!organization) {
+ actions.requestAiAccessError()
+ return
+ }
+ 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)
+ lemonToast.success('Request sent to your organization admins')
+ } catch {
+ actions.requestAiAccessError()
+ lemonToast.error('Could not send your request. Please try again.')
+ }
+ },
askSidePanelMax: ({ prompt }) => {
newInternalTab(urls.ai(undefined, prompt))
},
@@ -250,6 +292,11 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([
? `Ask an admin or owner of ${currentOrganization?.name} to approve this`
: null,
],
+ aiAccessRequested: [
+ (s) => [s.aiAccessRequestedByOrg, s.currentOrganization],
+ (aiAccessRequestedByOrg, currentOrganization): boolean =>
+ !!(currentOrganization && aiAccessRequestedByOrg[currentOrganization.id]),
+ ],
isOrganizationCreatedRecently: [
(s) => [s.currentOrganization],
(currentOrganization): boolean => {
diff --git a/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsx b/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsx
index d004233f6e34..b3f6f5cde990 100644
--- a/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsx
+++ b/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsx
@@ -1,10 +1,11 @@
import { useActions, useAsyncActions, useValues } from 'kea'
import { useCallback } from 'react'
-import { IconArrowRight, IconLock } from '@posthog/icons'
+import { IconArrowRight, IconCheck, IconLock } from '@posthog/icons'
import { LemonButton, Popover, PopoverProps, Tooltip } from '@posthog/lemon-ui'
import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
import { getExternalAIProvidersTooltipTitle, openAIConsentLegalDialog } from './aiConsentCopy'
@@ -52,6 +53,33 @@ export function AIConsentPopoverContent({
)
}
+function AIAccessRequestPopoverContent(): JSX.Element {
+ const { requestingAiAccess, aiAccessRequested } = useValues(maxGlobalLogic)
+ const { requestAiAccess } = useActions(maxGlobalLogic)
+
+ 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">
+ <LemonButton
+ data-attr="ai-access-request"
+ type="primary"
+ size="xsmall"
+ onClick={() => requestAiAccess()}
+ loading={requestingAiAccess}
+ disabledReason={aiAccessRequested ? 'Your request has been sent' : undefined}
+ sideIcon={aiAccessRequested ? <IconCheck /> : <IconArrowRight />}
+ >
+ {aiAccessRequested ? 'Request sent' : 'Request access'}
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
+
export function AIConsentPopoverWrapper({
hidden,
children,
@@ -71,6 +99,7 @@ export function AIConsentPopoverWrapper({
const { dataProcessingApprovalDisabledReason, dataProcessingAccepted, dataProcessingDismissed } =
useValues(maxGlobalLogic)
const { dismissDataProcessing } = useActions(maxGlobalLogic)
+ const { isAdminOrOwner } = useValues(organizationLogic)
const handleDismiss = (): void => {
if (!ignoreDismissal) {
@@ -82,15 +111,19 @@ export function AIConsentPopoverWrapper({
return (
<Popover
overlay={
- <AIConsentPopoverContent
- approvalDisabledReason={dataProcessingApprovalDisabledReason}
- onApprove={() =>
- void acceptDataProcessing()
- .then(() => onApprove?.())
- .catch(console.error)
- }
- onDismiss={handleDismiss}
- />
+ isAdminOrOwner ? (
+ <AIConsentPopoverContent
+ approvalDisabledReason={dataProcessingApprovalDisabledReason}
+ onApprove={() =>
+ void acceptDataProcessing()
+ .then(() => onApprove?.())
+ .catch(console.error)
+ }
+ onDismiss={handleDismiss}
+ />
+ ) : (
+ <AIAccessRequestPopoverContent />
+ )
}
style={{ zIndex: 'var(--z-modal)' }} // Don't show above the re-authentication modal
visible={!hidden && !dataProcessingAccepted && (ignoreDismissal || !dataProcessingDismissed)}
diff --git a/posthog/api/organization.py b/posthog/api/organization.py
index 936f51bdfa11..cb58f22bc3d8 100644
--- a/posthog/api/organization.py
+++ b/posthog/api/organization.py
@@ -40,12 +40,15 @@ from posthog.permissions import (
CREATE_ACTIONS,
APIScopePermission,
OrganizationAdminWritePermissions,
+ OrganizationMemberPermissions,
TimeSensitiveActionPermission,
extract_organization,
)
+from posthog.rate_limit import PostHogAIAccessRequestIPThrottle, PostHogAIAccessRequestUserThrottle
from posthog.rbac.migrations.rbac_feature_flag_migration import rbac_feature_flag_role_access_migration
from posthog.rbac.migrations.rbac_team_migration import rbac_team_access_control_migration
from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
+from posthog.tasks.email import send_posthog_ai_access_request
from posthog.tasks.tasks import delete_organization_data_and_notify_task
from posthog.user_permissions import UserPermissions, UserPermissionsSerializerMixin
from posthog.utils import get_safe_cache, safe_cache_set
@@ -351,6 +354,12 @@ class OrganizationSerializer(
return super().to_representation(instance)
+class OrganizationAIAccessRequestResponseSerializer(serializers.Serializer):
+ success = serializers.BooleanField(
+ help_text="Whether the access request was accepted and the organization admins were notified."
+ )
+
+
@extend_schema(extensions={"x-product": "platform_features"})
class OrganizationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
scope_object = "organization"
@@ -392,6 +401,13 @@ class OrganizationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
return update_permissions
+ # Any org member may ask an admin to enable PostHog AI — enabling still requires admin.
+ if self.action == "request_ai_access":
+ return [
+ permission()
+ for permission in [permissions.IsAuthenticated, APIScopePermission, OrganizationMemberPermissions]
+ ]
+
# We don't override for other actions
raise NotImplementedError()
@@ -566,3 +582,30 @@ class OrganizationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
return Response({"status": False, "error": "An internal error has occurred."}, status=500)
return Response({"status": True})
+
+ @extend_schema(request=None, responses={200: OrganizationAIAccessRequestResponseSerializer})
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="request_ai_access",
+ throttle_classes=[PostHogAIAccessRequestUserThrottle, PostHogAIAccessRequestIPThrottle],
+ )
+ def request_ai_access(self, request: Request, **kwargs) -> Response:
+ """Notify organization admins that a member is requesting PostHog AI be enabled."""
+ organization = self.organization
+ user = cast(User, request.user)
+
+ # Nothing to request if PostHog AI is already enabled for the org.
+ if organization.is_ai_data_processing_approved:
+ raise exceptions.ValidationError("PostHog AI is already enabled for this organization.")
+
+ # Members only — admins can enable PostHog AI themselves, so there's nobody to ask.
+ membership = OrganizationMembership.objects.filter(user=user, organization=organization).first()
+ if membership is None or membership.level >= OrganizationMembership.Level.ADMIN:
+ raise exceptions.PermissionDenied("Only members can request access; admins can enable PostHog AI directly.")
+
+ send_posthog_ai_access_request.delay(
+ organization_id=str(organization.id),
+ requesting_user_id=user.id,
+ )
+ return Response({"success": True})
diff --git a/posthog/api/test/test_organization.py b/posthog/api/test/test_organization.py
index 317d95e4a596..80f93ba33958 100644
--- a/posthog/api/test/test_organization.py
+++ b/posthog/api/test/test_organization.py
@@ -1230,3 +1230,66 @@ class TestOrganizationRbacMigrations(APIBaseTest):
"rbac_team_migration_failed",
{"user": self.admin_user.distinct_id, "error": "Test error"},
)
+
+
+class TestOrganizationRequestAIAccessAPI(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ # The endpoint is members-only, so default the requester to a plain member.
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ # AI is requestable only while it's disabled.
+ self.organization.is_ai_data_processing_approved = False
+ self.organization.save()
+ # Throttles key off the django cache, which persists across tests.
+ cache.clear()
+
+ def _url(self) -> str:
+ return f"/api/organizations/{self.organization.id}/request_ai_access/"
+
+ @patch("posthog.api.organization.send_posthog_ai_access_request")
+ def test_member_can_request_ai_access(self, mock_task):
+ response = self.client.post(self._url())
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json() == {"success": True}
+ mock_task.delay.assert_called_once_with(
+ organization_id=str(self.organization.id),
+ requesting_user_id=self.user.id,
+ )
+
+ @parameterized.expand(
+ [
+ ("admin", OrganizationMembership.Level.ADMIN),
+ ("owner", OrganizationMembership.Level.OWNER),
+ ]
+ )
+ @patch("posthog.api.organization.send_posthog_ai_access_request")
+ def test_admins_cannot_request_ai_access(self, _name, level, mock_task):
+ self.organization_membership.level = level
+ self.organization_membership.save()
+
+ response = self.client.post(self._url())
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+ mock_task.delay.assert_not_called()
+
+ @patch("posthog.api.organization.send_posthog_ai_access_request")
+ def test_cannot_request_ai_access_when_already_enabled(self, mock_task):
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+
+ response = self.client.post(self._url())
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ mock_task.delay.assert_not_called()
+
+ @patch("posthog.api.organization.send_posthog_ai_access_request")
+ def test_request_ai_access_is_rate_limited(self, mock_task):
+ first = self.client.post(self._url())
+ assert first.status_code == status.HTTP_200_OK, first.content
+
+ second = self.client.post(self._url())
+ assert second.status_code == status.HTTP_429_TOO_MANY_REQUESTS, second.content
+ # Only the first request reached the task.
+ mock_task.delay.assert_called_once()
diff --git a/posthog/email.py b/posthog/email.py
index a161e21a9ee9..490ab8cf0a54 100644
--- a/posthog/email.py
+++ b/posthog/email.py
@@ -123,6 +123,7 @@ CUSTOMER_IO_TEMPLATE_ID_MAP = {
"provisioning_welcome": "67",
"baa_signed_ai_disabled": "68",
"integration_access_requested": "70",
+ "posthog_ai_access_requested": "72",
}
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index 0e12e32644cf..41b3b2a8dce3 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -359,6 +359,18 @@ class SignupResendInviteThrottle(UserOrEmailRateThrottle):
rate = "5/hour"
+# Requesting PostHog AI access emails the org admins, so cap it per user and per IP
+# to keep a single member (or a shared-IP burst) from spamming admins' inboxes.
+class PostHogAIAccessRequestUserThrottle(UserRateThrottle):
+ scope = "posthog_ai_access_request_user"
+ rate = "1/day"
+
+
+class PostHogAIAccessRequestIPThrottle(IPThrottle):
+ scope = "posthog_ai_access_request_ip"
+ rate = "1/day"
+
+
class BurstRateThrottle(PersonalApiKeyRateThrottle):
# Throttle class that's applied on all endpoints (except for capture + decide)
# Intended to block quick bursts of requests, per project
diff --git a/posthog/tasks/email.py b/posthog/tasks/email.py
index 9f1c7485b557..e63d93904674 100644
--- a/posthog/tasks/email.py
+++ b/posthog/tasks/email.py
@@ -2049,3 +2049,69 @@ def send_integration_access_request(team_id: int, requesting_user_id: int, kind:
for user in recipients:
message.add_user_recipient(user)
message.send()
+
+
+@shared_task(**EMAIL_TASK_KWARGS)
+@skip_team_scope_audit
+def send_posthog_ai_access_request(organization_id: str, requesting_user_id: int) -> None:
+ """Notify org admins that a member is requesting PostHog AI be enabled."""
+ organization = Organization.objects.filter(id=organization_id).first()
+ requester = User.objects.filter(id=requesting_user_id).first()
+ if organization is None or requester is None:
+ return
+
+ log_context = {"organization_id": organization_id, "requesting_user_id": requesting_user_id}
+ requester_name = sanitize_display_name(
+ requester.first_name,
+ fallback="A teammate",
+ context={"task": "send_posthog_ai_access_request", "field": "requester_first_name", **log_context},
+ )
+ org_name = sanitize_display_name(
+ organization.name,
+ fallback="your organization",
+ context={"task": "send_posthog_ai_access_request", "field": "organization_name", **log_context},
+ )
+
+ # AI consent is an org-level setting reachable from any project; prefer the requester's
+ # current project so the link feels familiar, falling back to any project in the org.
+ current_team = requester.current_team
+ team = (
+ current_team
+ if current_team is not None and current_team.organization_id == organization.id
+ else organization.teams.first()
+ )
+ if team is None:
+ return
+ posthog_ai_url = (
+ f"{settings.SITE_URL}/project/{team.id}/settings/organization-details#setting=organization-ai-consent"
+ )
+
+ # Deterministic per requester so re-clicking doesn't spam admins (MessagingRecord dedups).
+ campaign_key = f"posthog_ai_access_request_{organization_id}_{requesting_user_id}"
+
+ # Org admins/owners can enable PostHog AI, so they're the recipients of the request.
+ memberships = (
+ OrganizationMembership.objects.select_related("user")
+ .filter(organization_id=organization.id, level__gte=OrganizationMembership.Level.ADMIN)
+ .exclude(user_id=requesting_user_id)
+ )
+ recipients = [membership.user for membership in memberships if membership.user.email]
+ if not recipients:
+ return
+
+ message = EmailMessage(
+ use_http=True,
+ campaign_key=campaign_key,
+ subject=f"{requester_name} requested access to PostHog AI",
+ template_name="posthog_ai_access_requested",
+ template_context={
+ "requester_name": requester_name,
+ "requester_email": requester.email or "",
+ "organization_name": org_name,
+ "posthog_ai_url": posthog_ai_url,
+ },
+ reply_to=requester.email or "",
+ )
+ for user in recipients:
+ message.add_user_recipient(user)
+ message.send()
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index dcd43e26d509..9277cf98bf7a 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -49,6 +49,7 @@
'posthog.tasks.email.send_password_changed_email',
'posthog.tasks.email.send_password_reset',
'posthog.tasks.email.send_personal_api_key_exposed',
+ 'posthog.tasks.email.send_posthog_ai_access_request',
'posthog.tasks.email.send_project_deleted_email',
'posthog.tasks.email.send_project_secret_api_key_exposed',
'posthog.tasks.email.send_provisioning_welcome',
diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.py
index 35b389e8ec7d..921016aeff66 100644
--- a/posthog/tasks/test/test_email.py
+++ b/posthog/tasks/test/test_email.py
@@ -38,6 +38,7 @@ from posthog.tasks.email import (
send_member_join,
send_new_ticket_notification,
send_password_reset,
+ send_posthog_ai_access_request,
send_provisioning_welcome,
should_send_pipeline_error_notification,
)
@@ -1635,6 +1636,48 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):
assert "Test Customer" in mocked_email_messages[0].html_body
assert "Hello, I need help with something" in mocked_email_messages[0].html_body
+ def test_send_posthog_ai_access_request(self, MockEmailMessage: MagicMock) -> None:
+ mocked_email_messages = mock_email_messages(MockEmailMessage)
+
+ org, _owner = create_org_team_and_user("2022-01-02 00:00:00", "[email protected]")
+ team = org.teams.first()
+ assert team is not None
+ member = User.objects.create_and_join(
+ organization=org,
+ password=None,
+ level=OrganizationMembership.Level.MEMBER,
+ )
+
+ send_posthog_ai_access_request(organization_id=str(org.id), requesting_user_id=member.id)
+
+ assert len(mocked_email_messages) == 1
+ message = mocked_email_messages[0]
+ assert message.send.call_count == 1
+ assert message.template_name == "posthog_ai_access_requested"
+ # The owner who can enable PostHog AI is notified, not the requesting member.
+ recipient_emails = {dest["raw_email"] for dest in message.to}
+ assert recipient_emails == {"[email protected]"}
+ assert message.properties["organization_name"] == org.name
+ assert (
+ message.properties["posthog_ai_url"]
+ == f"{settings.SITE_URL}/project/{team.id}/settings/organization-details#setting=organization-ai-consent"
+ )
+ assert message.html_body
+
+ def test_send_posthog_ai_access_request_no_admins_is_noop(self, MockEmailMessage: MagicMock) -> None:
+ mocked_email_messages = mock_email_messages(MockEmailMessage)
+
+ org, owner = create_org_team_and_user("2022-01-02 00:00:00", "[email protected]")
+ # Drop the only admin to a member so there's nobody who could enable PostHog AI.
+ membership = OrganizationMembership.objects.get(organization=org, user=owner)
+ membership.level = OrganizationMembership.Level.MEMBER
+ membership.save()
+
+ send_posthog_ai_access_request(organization_id=str(org.id), requesting_user_id=owner.id)
+
+ assert len(mocked_email_messages) == 0
+
def test_send_new_ticket_notification_no_recipients(self, MockEmailMessage: MagicMock) -> None:
from products.conversations.backend.models import Ticket
diff --git a/posthog/templates/email/posthog_ai_access_requested.html b/posthog/templates/email/posthog_ai_access_requested.html
new file mode 100644
index 000000000000..1976b63f2f43
--- /dev/null
+++ b/posthog/templates/email/posthog_ai_access_requested.html
@@ -0,0 +1,19 @@
+{% extends "email/base.html" %} {% load posthog_assets %} {% load posthog_filters %}
+{% block heading %}{{ requester_name }} requested access to PostHog AI{% endblock %}
+{% block section %}
+<!-- prettier-ignore -->
+<p>
+ <strong>{{ requester_name }}</strong> (<a href="mailto:{{ requester_email }}">{{ requester_email }}</a>) wants to
+ use PostHog AI in <strong>{{ organization_name }}</strong>. Enabling PostHog AI requires admin access, so they're
+ asking you to turn it on.
+</p>
+<div class="mb mt text-center">
+ <a class="button primary" href="{{ posthog_ai_url }}">Enable PostHog AI</a>
+</div>
+<div class="mt">
+ <p>
+ If the button above doesn't work, paste this link into your browser:<br />
+ <a href="{{ posthog_ai_url }}">{{ posthog_ai_url }}</a>
+ </p>
+</div>
+{% endblock %}
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 90d4dac63b76..a12546208353 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -232,6 +232,11 @@ export interface PatchedOrganizationApi {
readonly is_pending_deletion?: boolean | null
}
+export interface OrganizationAIAccessRequestResponseApi {
+ /** Whether the access request was accepted and the organization admins were notified. */
+ success: boolean
+}
+
/**
* * `engineering` - Engineering
* * `data` - Data
diff --git a/products/platform_features/frontend/generated/api.ts b/products/platform_features/frontend/generated/api.ts
index 45f492dfa053..1afa48a78cb3 100644
--- a/products/platform_features/frontend/generated/api.ts
+++ b/products/platform_features/frontend/generated/api.ts
@@ -21,6 +21,7 @@ import type {
CommentsListParams,
ListParams,
MembersListParams,
+ OrganizationAIAccessRequestResponseApi,
OrganizationApi,
OrganizationMemberApi,
PaginatedActivityLogListApi,
@@ -158,6 +159,23 @@ export const destroy = async (id: string, options?: RequestInit): Promise<void>
})
}
+export const getRequestAiAccessCreateUrl = (id: string) => {
+ return `/api/organizations/${id}/request_ai_access/`
+}
+
+/**
+ * Notify organization admins that a member is requesting PostHog AI be enabled.
+ */
+export const requestAiAccessCreate = async (
+ id: string,
+ options?: RequestInit
+): Promise<OrganizationAIAccessRequestResponseApi> => {
+ return apiMutator<OrganizationAIAccessRequestResponseApi>(getRequestAiAccessCreateUrl(id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getMembersListUrl = (organizationId: string, params?: MembersListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/platform_features/mcp/tools.yaml b/products/platform_features/mcp/tools.yaml
index 7810b1dbf560..e794f357619d 100644
--- a/products/platform_features/mcp/tools.yaml
+++ b/products/platform_features/mcp/tools.yaml
@@ -349,6 +349,9 @@ tools:
referring to a session recording rather than a survey response.
feature_flag: promoted-product
feature_flag_variant: intent_plus
+ request-ai-access-create:
+ operation: request_ai_access_create
+ enabled: false
role-get:
operation: roles_retrieve
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 534e321677e0..e889958ee878 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -28870,6 +28870,11 @@ export namespace Schemas {
readonly is_pending_deletion: boolean | null;
}
+ export interface OrganizationAIAccessRequestResponse {
+ /** Whether the access request was accepted and the organization admins were notified. */
+ success: boolean;
+ }
+
/**
* Serializer for `Organization` model with minimal attributes to speeed up loading and transfer times.
* Also used for nested serializers.