: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(posthog-ai): gate tasks surface sends behind AI consent popover (#68220)
Georgiy Tarasov8f4554664fad
diff --git a/frontend/src/scenes/max/maxGlobalLogic.test.ts b/frontend/src/scenes/max/maxGlobalLogic.test.tsindex 103ac895104f..0dbe0bfafebb 100644--- a/frontend/src/scenes/max/maxGlobalLogic.test.ts+++ b/frontend/src/scenes/max/maxGlobalLogic.test.ts@@ -5,6 +5,7 @@ import api from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'+import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -115,6 +116,29 @@ describe('maxGlobalLogic', () => {})})+ // Consent state (accept/dismiss/request-access) now lives in aiConsentLogic (see aiConsentLogic.test.ts)+ // and is only forwarded here via `connect` so the ~15 existing consumers keep reading it off+ // maxGlobalLogic unchanged. This guards the forwarding wiring itself — a mistake here (e.g. connecting+ // to the wrong source, or a stale value) wouldn't be caught by typechecking, since the shape stays the+ // same either way.+ describe('consent forwarding from aiConsentLogic', () => {+ it('dismissing via maxGlobalLogic updates aiConsentLogic and is reflected back', () => {+ const consent = aiConsentLogic()+ consent.mount()++ // Same underlying state, not two independent copies.+ expect(logic.values.dataProcessingAccepted).toBe(consent.values.dataProcessingAccepted)+ expect(logic.values.dataProcessingDismissed).toBe(false)++ logic.actions.dismissDataProcessing()++ expect(consent.values.dataProcessingDismissed).toBe(true)+ expect(logic.values.dataProcessingDismissed).toBe(true)++ consent.unmount()+ })+ })+describe('editInsightToolRegistered selector', () => {it('returns true when contextual create_insight tool is registered', async () => {// Initially should be false (only static tool available)diff --git a/frontend/src/scenes/max/maxGlobalLogic.tsx b/frontend/src/scenes/max/maxGlobalLogic.tsxindex a16d164ff75f..0d9849d7f0e2 100644--- a/frontend/src/scenes/max/maxGlobalLogic.tsx+++ b/frontend/src/scenes/max/maxGlobalLogic.tsx@@ -3,7 +3,7 @@ import { loaders } from 'kea-loaders'import { router } from 'kea-router'import api from 'lib/api'-import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'+import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'@@ -11,6 +11,7 @@ import { newInternalTab } from 'lib/utils/newInternalTab'import { organizationLogic } from 'scenes/organizationLogic'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { sceneLogic } from 'scenes/sceneLogic'+import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -18,7 +19,6 @@ import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePaneimport { 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 { PHAI_VIEW_MODE_KEY } from './max-storage-keys'@@ -35,13 +35,6 @@ export type PhaiViewMode = 'new' | 'legacy'// Keep this stored across all projects, only display this once per deviceconst AI_LIABILITY_NOTICE_STORAGE_KEY = 'posthog_ai_liability_notice_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[] = [{@@ -107,24 +100,34 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([['sidePanelOpen', 'selectedTab'],preflightLogic,['preflight', 'isCloudOrDev'],+ aiConsentLogic,+ [+ 'dataProcessingAccepted',+ 'dataProcessingDismissed',+ 'dataProcessingApprovalDisabledReason',+ 'aiAccessRequested',+ 'requestingAiAccess',+ ],+ ],+ actions: [+ router,+ ['locationChanged'],+ sidePanelStateLogic,+ ['openSidePanel'],+ aiConsentLogic,+ ['acceptDataProcessing', 'dismissDataProcessing', 'requestAiAccess'],],- actions: [router, ['locationChanged'], sidePanelStateLogic, ['openSidePanel']],})),actions({openSidePanelMax: (conversationId?: string) => ({ conversationId }),openSidePanelMaxWithTaskBind: (taskId: string) => ({ taskId }),askSidePanelMax: (prompt: string) => ({ prompt }),- acceptDataProcessing: (testOnlyOverride?: boolean) => ({ testOnlyOverride }),registerTool: (tool: ToolRegistration) => ({ tool }),deregisterTool: (key: string) => ({ key }),prependOrReplaceConversation: (conversation: ConversationDetail | Conversation) => ({ conversation }),deleteConversation: (id: string) => ({ id }),dismissLiabilityNotice: true,- dismissDataProcessing: true,setPhaiViewMode: (mode: PhaiViewMode) => ({ mode }),- requestAiAccess: true,- markAiAccessRequested: (organizationId: string) => ({ organizationId }),- requestAiAccessError: true,}),loaders(({ values }) => ({@@ -195,28 +198,6 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([dismissLiabilityNotice: () => true,},],- dataProcessingDismissed: [- false,- { persist: true, storageKey: AI_DATA_PROCESSING_DISMISSED_STORAGE_KEY },- {- 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 }),- },- ],// The user's chosen implementation, persisted per device. Defaults to the new surface so a// flagged user lands there; `effectivePhaiView` collapses this to legacy when the flag is off.phaiViewMode: [@@ -228,28 +209,6 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([],}),listeners(({ actions, values }) => ({- acceptDataProcessing: async ({ testOnlyOverride }) => {- await organizationLogic.asyncActions.updateOrganization({- 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))},@@ -311,10 +270,6 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([() => [router.selectors.searchParams],(searchParams): string | null => searchParams?.chat ?? null,],- dataProcessingAccepted: [- (s) => [s.currentOrganization],- (currentOrganization): boolean => !!currentOrganization?.is_ai_data_processing_approved,- ],// On Cloud/dev a provider key is always present. On a self-hosted (hobby) instance Max only// works once ANTHROPIC_API_KEY is configured, so we surface a "set the key" state instead.// Treat a not-yet-loaded preflight (null) as available so the empty-state doesn't flash@@ -323,19 +278,6 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([(s) => [s.isCloudOrDev, s.preflight],(isCloudOrDev, preflight): boolean => !preflight || !!isCloudOrDev || !!preflight.anthropic_available,],- dataProcessingApprovalDisabledReason: [- (s) => [s.currentOrganization],- (currentOrganization): 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, 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.tsxindex b3f6f5cde990..1626a4a94dc4 100644--- a/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsx+++ b/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsx@@ -4,10 +4,10 @@ import { useCallback } from 'react'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'+import { aiConsentLogic } from './aiConsentLogic'export function AIConsentPopoverContent({onApprove,@@ -54,8 +54,8 @@ export function AIConsentPopoverContent({}function AIAccessRequestPopoverContent(): JSX.Element {- const { requestingAiAccess, aiAccessRequested } = useValues(maxGlobalLogic)- const { requestAiAccess } = useActions(maxGlobalLogic)+ const { requestingAiAccess, aiAccessRequested } = useValues(aiConsentLogic)+ const { requestAiAccess } = useActions(aiConsentLogic)return (<div className="flex flex-col gap-2 m-1.5 max-w-prose">@@ -95,10 +95,10 @@ export function AIConsentPopoverWrapper({onApprove?: () => voidonDismiss?: () => void}): JSX.Element {- const { acceptDataProcessing } = useAsyncActions(maxGlobalLogic)+ const { acceptDataProcessing } = useAsyncActions(aiConsentLogic)const { dataProcessingApprovalDisabledReason, dataProcessingAccepted, dataProcessingDismissed } =- useValues(maxGlobalLogic)- const { dismissDataProcessing } = useActions(maxGlobalLogic)+ useValues(aiConsentLogic)+ const { dismissDataProcessing } = useActions(aiConsentLogic)const { isAdminOrOwner } = useValues(organizationLogic)const handleDismiss = (): void => {diff --git a/frontend/src/scenes/settings/organization/aiConsentLogic.test.ts b/frontend/src/scenes/settings/organization/aiConsentLogic.test.tsnew file mode 100644index 000000000000..7fe191a64305--- /dev/null+++ b/frontend/src/scenes/settings/organization/aiConsentLogic.test.ts@@ -0,0 +1,146 @@+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { OrganizationMembershipLevel } from 'lib/constants'+import { lemonToast } from 'lib/lemon-ui/LemonToast'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { requestAiAccessCreate } from 'products/platform_features/frontend/generated/api'++import { aiConsentLogic } from './aiConsentLogic'++jest.mock('products/platform_features/frontend/generated/api', () => ({+ requestAiAccessCreate: jest.fn(),+}))++jest.mock('lib/lemon-ui/LemonToast', () => ({+ lemonToast: { success: jest.fn(), error: jest.fn() },+}))++describe('aiConsentLogic', () => {+ let logic: ReturnType<typeof aiConsentLogic.build>++ beforeEach(() => {+ // dataProcessingDismissed / aiAccessRequestedByOrg are persisted to localStorage, which jsdom+ // keeps alive across tests in this file — start each test from a clean slate.+ localStorage.clear()+ useMocks({+ patch: {+ '/api/organizations/:id': async ({ request }) => [+ 200,+ {+ ...MOCK_DEFAULT_ORGANIZATION,+ ...((await request.json()) as Partial<typeof MOCK_DEFAULT_ORGANIZATION>),+ },+ ],+ },+ })+ })++ afterEach(() => {+ logic?.unmount()+ jest.restoreAllMocks()+ })++ describe('dataProcessingAccepted selector', () => {+ it.each([+ { approved: true, expected: true },+ { approved: false, expected: false },+ ])(+ 'is $expected when the organization is_ai_data_processing_approved is $approved',+ ({ approved, expected }) => {+ initKeaTests(true, undefined, undefined, {+ ...MOCK_DEFAULT_ORGANIZATION,+ is_ai_data_processing_approved: approved,+ })+ logic = aiConsentLogic()+ logic.mount()++ expect(logic.values.dataProcessingAccepted).toBe(expected)+ }+ )+ })++ describe('dataProcessingApprovalDisabledReason selector', () => {+ it.each([+ { level: OrganizationMembershipLevel.Admin, expected: null },+ { level: OrganizationMembershipLevel.Owner, expected: null },+ {+ level: OrganizationMembershipLevel.Member,+ expected: `Ask an admin or owner of ${MOCK_DEFAULT_ORGANIZATION.name} to approve this`,+ },+ ])('is $expected for membership level $level', ({ level, expected }) => {+ initKeaTests(true, undefined, undefined, { ...MOCK_DEFAULT_ORGANIZATION, membership_level: level })+ logic = aiConsentLogic()+ logic.mount()++ expect(logic.values.dataProcessingApprovalDisabledReason).toBe(expected)+ })+ })++ // Regression guard for the extraction: dismissal must persist under the exact+ // `posthog_ai_data_processing_dismissed_<YYYY-MM>` key the popover already relies on, or a user's+ // dismissal silently stops sticking across reloads.+ it('dismissDataProcessing marks the popover dismissed', async () => {+ initKeaTests()+ logic = aiConsentLogic()+ logic.mount()++ expect(logic.values.dataProcessingDismissed).toBe(false)+ logic.actions.dismissDataProcessing()+ expect(logic.values.dataProcessingDismissed).toBe(true)+ })++ it('acceptDataProcessing approves AI data processing for the current organization', async () => {+ initKeaTests(true, undefined, undefined, {+ ...MOCK_DEFAULT_ORGANIZATION,+ is_ai_data_processing_approved: false,+ })+ logic = aiConsentLogic()+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.acceptDataProcessing()+ }).toFinishAllListeners()++ expect(logic.values.dataProcessingAccepted).toBe(true)+ })++ describe('requestAiAccess', () => {+ it('marks the request sent and toasts on success', async () => {+ ;(requestAiAccessCreate as jest.Mock).mockResolvedValue({})+ initKeaTests()+ logic = aiConsentLogic()+ logic.mount()++ expect(logic.values.aiAccessRequested).toBe(false)++ await expectLogic(logic, () => {+ logic.actions.requestAiAccess()+ }).toFinishAllListeners()++ expect(requestAiAccessCreate).toHaveBeenCalledWith(MOCK_DEFAULT_ORGANIZATION.id)+ expect(logic.values.aiAccessRequested).toBe(true)+ expect(logic.values.requestingAiAccess).toBe(false)+ expect(lemonToast.success).toHaveBeenCalled()+ })++ it('surfaces an error and leaves the request unmarked when the API call fails', async () => {+ ;(requestAiAccessCreate as jest.Mock).mockRejectedValue(new Error('boom'))+ initKeaTests()+ logic = aiConsentLogic()+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.requestAiAccess()+ }).toFinishAllListeners()++ expect(logic.values.aiAccessRequested).toBe(false)+ expect(logic.values.requestingAiAccess).toBe(false)+ expect(lemonToast.error).toHaveBeenCalled()+ })+ })+})diff --git a/frontend/src/scenes/settings/organization/aiConsentLogic.ts b/frontend/src/scenes/settings/organization/aiConsentLogic.tsnew file mode 100644index 000000000000..543141048ab0--- /dev/null+++ b/frontend/src/scenes/settings/organization/aiConsentLogic.ts@@ -0,0 +1,98 @@+import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'++import { OrganizationMembershipLevel } from 'lib/constants'+import { dayjs } from 'lib/dayjs'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { organizationLogic } from 'scenes/organizationLogic'++import { requestAiAccessCreate } from 'products/platform_features/frontend/generated/api'++import type { aiConsentLogicType } from './aiConsentLogicType'++// 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'++export const aiConsentLogic = kea<aiConsentLogicType>([+ path(['scenes', 'settings', 'organization', 'aiConsentLogic']),+ connect(() => ({+ values: [organizationLogic, ['currentOrganization']],+ })),+ actions({+ acceptDataProcessing: (testOnlyOverride?: boolean) => ({ testOnlyOverride }),+ dismissDataProcessing: true,+ requestAiAccess: true,+ markAiAccessRequested: (organizationId: string) => ({ organizationId }),+ requestAiAccessError: true,+ }),+ reducers({+ dataProcessingDismissed: [+ false,+ { persist: true, storageKey: AI_DATA_PROCESSING_DISMISSED_STORAGE_KEY },+ {+ 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 }) => {+ await organizationLogic.asyncActions.updateOrganization({+ 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.')+ }+ },+ })),+ selectors({+ dataProcessingAccepted: [+ (s) => [s.currentOrganization],+ (currentOrganization): boolean => !!currentOrganization?.is_ai_data_processing_approved,+ ],+ dataProcessingApprovalDisabledReason: [+ (s) => [s.currentOrganization],+ (currentOrganization): 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, currentOrganization): boolean =>+ !!(currentOrganization && aiAccessRequestedByOrg[currentOrganization.id]),+ ],+ }),+])diff --git a/products/posthog_ai/frontend/components/composer/Composer.tsx b/products/posthog_ai/frontend/components/composer/Composer.tsxindex dc7380fb0145..ab3d99d69606 100644--- a/products/posthog_ai/frontend/components/composer/Composer.tsx+++ b/products/posthog_ai/frontend/components/composer/Composer.tsx@@ -340,12 +340,19 @@ export interface ComposerSubmitProps {'data-attr'?: string}-/** The absolutely-positioned send cluster, sibling of Frame inside Root's relative wrapper. */-function ComposerSubmit({ icon, tooltip, className, ...rest }: ComposerSubmitProps): JSX.Element {+/**+ * The absolutely-positioned send cluster, sibling of Frame inside Root's relative wrapper. `forwardRef`+ * so callers can anchor a `Popover` to it (Popover clones its child with a ref).+ */+const ComposerSubmit = forwardRef<HTMLDivElement, ComposerSubmitProps>(function ComposerSubmit(+ { icon, tooltip, className, ...rest },+ ref+): JSX.Element {const { sendDisabledReason, loading, showStop, onStop, isThreadVisible } = useComposerContext()return (<divdata-slot="composer-submit"+ ref={ref}className={cn('absolute flex items-center',isThreadVisible ? 'bottom-[9px] right-[9px]' : 'bottom-[7px] right-[7px]',@@ -378,7 +385,7 @@ function ComposerSubmit({ icon, tooltip, className, ...rest }: ComposerSubmitPro)}</div>)-}+})export const Composer = Object.assign(ComposerRoot, {Root: ComposerRoot,diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.tsindex 6f1a55c2530f..1e6c850144f1 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts@@ -2,6 +2,7 @@ import { expectLogic } from 'kea-test-utils'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { projectLogic } from 'scenes/projectLogic'+import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { initKeaTests } from '~/test/init'@@ -498,6 +499,36 @@ describe('runInteractionLogic', () => {expect(logic.values.queuedMessages).toEqual([{ id: expect.any(String), content: 'first\n\nsecond' }])})+ // The tasks run backend has no server-side consent check, so a follow-up (or a fresh-run send on a+ // terminal run) must be blocked client-side before it reaches `tasksRunsCommandCreate` /+ // `tasksRunCreate`. Uses a distinct `runId` key so the logic is built (and connects to+ // `aiConsentLogic`) after the selector is stubbed.+ it('blocks composerForm.submit and sends nothing when consent is not accepted', async () => {+ const consent = aiConsentLogic()+ consent.mount()+ jest.spyOn(consent.selectors, 'dataProcessingAccepted').mockReturnValue(false)++ const blockedRunId = 'run-blocked'+ const blockedStream = runStreamLogic({ streamKey: blockedRunId })+ blockedStream.mount()+ const blockedLogic = runInteractionLogic({ taskId: TASK_ID, runId: blockedRunId, onRunStarted })+ blockedLogic.mount()++ blockedLogic.actions.setComposerFormValues({ draft: 'ship it' })+ await expectLogic(blockedLogic, () => {+ blockedLogic.actions.submitComposerForm()+ }).toFinishAllListeners()++ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()+ expect(tasksRunCreate).not.toHaveBeenCalled()+ expect(blockedLogic.values.consentBlocked).toBe(true)++ blockedLogic.unmount()+ blockedStream.unmount()+ consent.unmount()+ jest.restoreAllMocks()+ })+it('no-ops on submit with an empty draft', async () => {await expectLogic(logic, () => {logic.actions.submitComposerForm()diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.tsindex 99d288f9f9b6..fbf2c75cfe87 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts@@ -3,6 +3,7 @@ import { forms } from 'kea-forms'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { projectLogic } from 'scenes/projectLogic'+import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import {DEFAULT_COMPOSER_EFFORT,@@ -81,6 +82,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([['currentRunStatus', 'pendingPermissionRequest', 'respondingToPermission', 'isThinking'],attachedContextLogic,['contextItems', 'sentContextKeysByTask'],+ aiConsentLogic,+ ['dataProcessingAccepted'],],actions: [runStreamLogic({ streamKey: props.streamKey ?? props.runId }),@@ -92,6 +95,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([actions({setSending: (sending: boolean) => ({ sending }),+ blockOnConsent: true,+ clearConsentBlock: true,// Start a fresh run on the task, seeded with this message and chained from the finished run.startNewRun: (content: string) => ({ content }),setStartingRun: (starting: boolean) => ({ starting }),@@ -126,6 +131,14 @@ export const runInteractionLogic = kea<runInteractionLogicType>([setSending: (_, { sending }) => sending,},],+ consentBlocked: [+ false,+ {+ blockOnConsent: () => true,+ clearConsentBlock: () => false,+ submitComposerForm: () => false,+ },+ ],startingRun: [false,{@@ -198,6 +211,10 @@ export const runInteractionLogic = kea<runInteractionLogicType>([if (!content) {return}+ if (!values.dataProcessingAccepted) {+ actions.blockOnConsent()+ return+ }// A finished run can't take a follow-up signal — send starts a fresh run instead, seeded with// this message and chained from the run just viewed.if (values.isTerminal) {diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsxindex 8cf51f25af18..c5fbe8e6c6ba 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx@@ -2,6 +2,8 @@ import { useActions, useValues } from 'kea'import { router } from 'kea-router'import { useRef } from 'react'+import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'+import {Composer,DEFAULT_SUGGESTIONS_DATA,@@ -18,9 +20,10 @@ import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'import { RepositorySelector } from './RepositorySelector'export function TaskComposer(): JSX.Element {- const { submitNewTask, setNewTaskData, setActiveSuggestionGroup, applySuggestion } =+ const { submitNewTask, setNewTaskData, setActiveSuggestionGroup, applySuggestion, clearConsentBlock } =useActions(taskTrackerSceneLogic)- const { newTaskData, isSubmittingTask, activeSuggestionGroup, headline } = useValues(taskTrackerSceneLogic)+ const { newTaskData, isSubmittingTask, activeSuggestionGroup, headline, consentBlocked } =+ useValues(taskTrackerSceneLogic)// Buffer the description locally and debounce the write to kea so each keystroke is a cheap, isolated// re-render instead of a store dispatch. `Composer.Root` already blocks send on an empty `draft.value`@@ -86,7 +89,16 @@ export function TaskComposer(): JSX.Element {</Composer.Footer></Composer.Frame><Suggestions.Dropdown />- <Composer.Submit data-attr="task-composer-send" />+ <AIConsentPopoverWrapper+ placement="bottom-end"+ showArrow+ ignoreDismissal+ hidden={!consentBlocked}+ onApprove={() => submitNewTask()}+ onDismiss={() => clearConsentBlock()}+ >+ <Composer.Submit data-attr="task-composer-send" />+ </AIConsentPopoverWrapper></Composer.Root></div>diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsxindex b81f7de111a0..14391477f42a 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx@@ -1,5 +1,6 @@import { BindLogic, useActions, useValues } from 'kea'+import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'import { userLogic } from 'scenes/userLogic'import { runInteractionLogic, type RunInteractionLogicProps } from 'products/posthog_ai/frontend/api/logics'@@ -98,9 +99,16 @@ function TaskRunChatContent({}function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }): JSX.Element {- const { composerForm, isSubmitting, isBusy, queuedMessages, isTerminal, selectedModel, selectedEffort } = useValues(- runInteractionLogic(logicProps)- )+ const {+ composerForm,+ isSubmitting,+ isBusy,+ queuedMessages,+ isTerminal,+ selectedModel,+ selectedEffort,+ consentBlocked,+ } = useValues(runInteractionLogic(logicProps))const {setComposerFormValues,submitComposerForm,@@ -109,6 +117,7 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):removeQueuedMessage,setModel,setEffort,+ clearConsentBlock,} = useActions(runInteractionLogic(logicProps))const draft = useDebouncedDraft(composerForm.draft, (value) => setComposerFormValues({ draft: value }))@@ -153,7 +162,16 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):/></Composer.Footer></Composer.Frame>- <Composer.Submit data-attr="sandbox-composer-send" />+ <AIConsentPopoverWrapper+ placement="top-end"+ showArrow+ ignoreDismissal+ hidden={!consentBlocked}+ onApprove={() => submitComposerForm()}+ onDismiss={() => clearConsentBlock()}+ >+ <Composer.Submit data-attr="sandbox-composer-send" />+ </AIConsentPopoverWrapper></Composer.Root>)}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.tsindex f25c12b22b05..9f7084df6c57 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts@@ -1,6 +1,8 @@import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -107,6 +109,31 @@ describe('taskTrackerSceneLogic', () => {expect(attachedContextLogic().values.sentContextKeysByTask).toEqual({ 'new-task': ['insight:sig'] })})+ // The tasks backend has no server-side consent check (unlike the conversations coordinator), so a+ // send must be blocked client-side before it ever reaches `api.tasks.create` — otherwise a sandbox+ // run starts with zero consent enforcement. Uses a distinct `panelId` key so the logic is built+ // (and connects to `aiConsentLogic`) after the selector is stubbed.+ it('blocks submitNewTask without creating a task when AI data processing consent is not accepted', async () => {+ const consent = aiConsentLogic()+ consent.mount()+ jest.spyOn(consent.selectors, 'dataProcessingAccepted').mockReturnValue(false)++ const blockedLogic = taskTrackerSceneLogic({ panelId: 'consent-test' })+ blockedLogic.mount()+ blockedLogic.actions.setNewTaskData({ description: 'do the thing' })+ blockedLogic.actions.submitNewTask()++ await expectLogic(blockedLogic).toFinishAllListeners()++ expect(createBody).toBeNull()+ expect(blockedLogic.values.consentBlocked).toBe(true)+ expect(blockedLogic.values.isSubmittingTask).toBe(false)++ blockedLogic.unmount()+ consent.unmount()+ jest.restoreAllMocks()+ })+// The repo picker only renders once `repositoryConfig.integrationId` is set (auto-selected from the// connected GitHub org). Submitting resets the form, wiping that id; without re-deriving it the picker// stays blank for every subsequent new task. Guards that the auto-select is restored after a submit.diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex d93a95bb20a6..f6b0b6c777b0 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -6,6 +6,7 @@ import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { uuid } from 'lib/utils/dom'+import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import {ClaudeRuntimeAdapterEnumApi,@@ -75,6 +76,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([['integrations'],attachedContextLogic,['contextItems'],+ aiConsentLogic,+ ['dataProcessingAccepted'],],actions: [runnerPanelLogic(props),@@ -103,6 +106,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([// Re-points the panel at a fresh run started from the composer on a reopened terminal task// (the run surface's own re-pointing targets the detail scene, which the panel doesn't render).updateActiveCreationRun: (runId: string) => ({ runId }),+ blockOnConsent: true,+ clearConsentBlock: true,}),reducers({@@ -119,6 +124,15 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([submitNewTask: () => true,submitNewTaskSuccess: () => false,submitNewTaskFailure: () => false,+ blockOnConsent: () => false,+ },+ ],+ consentBlocked: [+ false,+ {+ blockOnConsent: () => true,+ clearConsentBlock: () => false,+ submitNewTask: () => false,},],// Last repo/integration the user picked, persisted to localStorage so the composer comes back pre-filled.@@ -204,6 +218,11 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([}},submitNewTask: async () => {+ if (!values.dataProcessingAccepted) {+ actions.blockOnConsent()+ return+ }+const { description, repositoryConfig, model, reasoningEffort } = values.newTaskDataif (!description.trim()) {