: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
fix(replay-vision): persist create-scanner intent through SSO reauth redirect (#82295)
Hayne Ryub0f8b8897420
diff --git a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.tsindex bd9787a41a87..1fe65445bc0c 100644--- a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts+++ b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts@@ -33,7 +33,7 @@ export interface TwoFAMethodsResponse {has_passkeys: boolean}-const LOOKAHEAD_EXPIRY_SECONDS = 60 * 5+export const LOOKAHEAD_EXPIRY_SECONDS = 60 * 5// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface timeSensitiveAuthenticationLogicValues {diff --git a/frontend/src/scenes/max/maxGlobalLogic.tsx b/frontend/src/scenes/max/maxGlobalLogic.tsxindex ad7717aca7e3..d8cdbf2c2ea7 100644--- a/frontend/src/scenes/max/maxGlobalLogic.tsx+++ b/frontend/src/scenes/max/maxGlobalLogic.tsx@@ -125,7 +125,11 @@ export interface maxGlobalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface maxGlobalLogicActions {- acceptDataProcessing: (testOnlyOverride?: boolean | undefined) => {+ acceptDataProcessing: (+ testOnlyOverride?: boolean | undefined,+ resumeUrl?: string | undefined+ ) => {+ resumeUrl: string | undefinedtestOnlyOverride: boolean | undefined} // aiConsentLogicdismissDataProcessing: () => {diff --git a/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsx b/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsxindex a88720f4403e..7f67bde41f3d 100644--- a/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsx+++ b/frontend/src/scenes/settings/organization/AIConsentPopoverWrapper.tsx@@ -90,6 +90,7 @@ export function AIConsentPopoverWrapper({onApprove,onDismiss,hideTrainingDisclaimer,+ pendingRedirectUrl,...popoverProps}: Pick<PopoverProps, 'placement' | 'fallbackPlacements' | 'middleware' | 'showArrow'> & {children: JSX.Element@@ -100,12 +101,18 @@ export function AIConsentPopoverWrapper({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 } = useActions(aiConsentLogic)- const { isAdminOrOwner } = useValues(organizationLogic)+ const { dismissDataProcessing, setPendingApprovalRedirect } = useActions(aiConsentLogic)+ const { isAdminOrOwner, currentOrganization } = useValues(organizationLogic)const handleDismiss = (): void => {if (!ignoreDismissal) {@@ -121,11 +128,19 @@ export function AIConsentPopoverWrapper({<AIConsentPopoverContentapprovalDisabledReason={dataProcessingApprovalDisabledReason}hideTrainingDisclaimer={hideTrainingDisclaimer}- onApprove={() =>+ onApprove={() => {+ if (pendingRedirectUrl && currentOrganization) {+ // Cleared by the acceptDataProcessing listener on success or failure.+ setPendingApprovalRedirect({+ url: pendingRedirectUrl,+ organizationId: currentOrganization.id,+ setAt: Date.now(),+ })+ }void acceptDataProcessing().then(() => onApprove?.()).catch(console.error)- }+ }}onDismiss={handleDismiss}/>) : (diff --git a/frontend/src/scenes/settings/organization/aiConsentLogic.test.ts b/frontend/src/scenes/settings/organization/aiConsentLogic.test.tsindex 7fe191a64305..ddfad8f35fc5 100644--- a/frontend/src/scenes/settings/organization/aiConsentLogic.test.ts+++ b/frontend/src/scenes/settings/organization/aiConsentLogic.test.ts@@ -1,16 +1,19 @@-import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER } from 'lib/api.mock'+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import { OrganizationMembershipLevel } from 'lib/constants'+import { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { AppContext } from '~/types'import { requestAiAccessCreate } from 'products/platform_features/frontend/generated/api'-import { aiConsentLogic } from './aiConsentLogic'+import { PendingApprovalRedirect, aiConsentLogic } from './aiConsentLogic'jest.mock('products/platform_features/frontend/generated/api', () => ({requestAiAccessCreate: jest.fn(),@@ -94,7 +97,7 @@ describe('aiConsentLogic', () => {expect(logic.values.dataProcessingDismissed).toBe(true)})- it('acceptDataProcessing approves AI data processing for the current organization', async () => {+ it('acceptDataProcessing approves AI data processing for the current organization and toasts success', async () => {initKeaTests(true, undefined, undefined, {...MOCK_DEFAULT_ORGANIZATION,is_ai_data_processing_approved: false,@@ -107,6 +110,110 @@ describe('aiConsentLogic', () => {}).toFinishAllListeners()expect(logic.values.dataProcessingAccepted).toBe(true)+ expect(lemonToast.success).toHaveBeenCalledWith('AI data processing approved')+ })++ // Regression guards for the SSO reauthentication redirect: it unloads the page before the+ // approval request is sent, so the confirmed intent is persisted and replayed on return.+ describe('pendingApprovalRedirect', () => {+ const pendingRedirect = (overrides: Partial<PendingApprovalRedirect> = {}): PendingApprovalRedirect => ({+ url: '/replay-vision/new/template',+ organizationId: MOCK_DEFAULT_ORGANIZATION.id,+ setAt: Date.now(),+ ...overrides,+ })++ const remountWithPending = (redirect: PendingApprovalRedirect): void => {+ logic = aiConsentLogic()+ logic.mount()+ logic.actions.setPendingApprovalRedirect(redirect)+ logic.unmount()+ logic = aiConsentLogic()+ logic.mount()+ }++ it('replays the lost approval and resumes navigation on remount', async () => {+ initKeaTests(true, undefined, undefined, {+ ...MOCK_DEFAULT_ORGANIZATION,+ is_ai_data_processing_approved: false,+ })+ remountWithPending(pendingRedirect())++ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.dataProcessingAccepted).toBe(true)+ expect(logic.values.pendingApprovalRedirect).toBe(null)+ expect(router.values.location.pathname).toContain('/replay-vision/new/template')+ expect(lemonToast.success).toHaveBeenCalledWith('AI data processing approved')+ })++ it('only redirects when consent was already granted before the round trip', () => {+ initKeaTests(true, undefined, undefined, {+ ...MOCK_DEFAULT_ORGANIZATION,+ is_ai_data_processing_approved: false,+ })+ logic = aiConsentLogic()+ logic.mount()+ logic.actions.setPendingApprovalRedirect(pendingRedirect())+ logic.unmount()++ initKeaTests(true, undefined, undefined, {+ ...MOCK_DEFAULT_ORGANIZATION,+ is_ai_data_processing_approved: true,+ })+ logic = aiConsentLogic()+ logic.mount()++ expect(logic.values.pendingApprovalRedirect).toBe(null)+ expect(router.values.location.pathname).toContain('/replay-vision/new/template')+ })++ it.each([+ { name: 'the intent is older than the TTL', overrides: { setAt: Date.now() - 16 * 60 * 1000 } },+ { name: 'the intent belongs to another organization', overrides: { organizationId: 'some-other-org' } },+ ])('drops the intent without approving when $name', async ({ overrides }) => {+ initKeaTests(true, undefined, undefined, {+ ...MOCK_DEFAULT_ORGANIZATION,+ is_ai_data_processing_approved: false,+ })+ remountWithPending(pendingRedirect(overrides))++ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.dataProcessingAccepted).toBe(false)+ expect(logic.values.pendingApprovalRedirect).toBe(null)+ expect(lemonToast.success).not.toHaveBeenCalled()+ })++ it('drops the intent when the sensitive session is still stale, instead of reopening the reauth modal', async () => {+ window.POSTHOG_APP_CONTEXT = {+ current_user: {+ ...MOCK_DEFAULT_USER,+ sensitive_session_expires_at: dayjs().subtract(1, 'minute').toISOString(),+ organization: { ...MOCK_DEFAULT_ORGANIZATION, is_ai_data_processing_approved: false },+ },+ } as unknown as AppContext+ initKeaTests(true)+ remountWithPending(pendingRedirect())++ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.dataProcessingAccepted).toBe(false)+ expect(logic.values.pendingApprovalRedirect).toBe(null)+ expect(lemonToast.success).not.toHaveBeenCalled()+ })++ it('leaves navigation alone when there is nothing pending', () => {+ initKeaTests(true, undefined, undefined, {+ ...MOCK_DEFAULT_ORGANIZATION,+ is_ai_data_processing_approved: true,+ })+ const pathnameBeforeMount = router.values.location.pathname+ logic = aiConsentLogic()+ logic.mount()++ expect(router.values.location.pathname).toBe(pathnameBeforeMount)+ })})describe('requestAiAccess', () => {diff --git a/frontend/src/scenes/settings/organization/aiConsentLogic.ts b/frontend/src/scenes/settings/organization/aiConsentLogic.tsindex 44cfa4e795c9..66247d880022 100644--- a/frontend/src/scenes/settings/organization/aiConsentLogic.ts+++ b/frontend/src/scenes/settings/organization/aiConsentLogic.ts@@ -1,13 +1,16 @@-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'+import { router } from 'kea-router'+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 { requestAiAccessCreate } from 'products/platform_features/frontend/generated/api'-import type { OrganizationType } from '../../../types'+import type { OrganizationType, UserType } from '../../../types'// Keep this stored across all projects, only display this once per monthconst AI_DATA_PROCESSING_DISMISSED_STORAGE_KEY = `posthog_ai_data_processing_dismissed_${dayjs().format('YYYY-MM')}`@@ -16,20 +19,38 @@ const AI_DATA_PROCESSING_DISMISSED_STORAGE_KEY = `posthog_ai_data_processing_dis// 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'++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 // userLogicaiAccessRequested: booleanaiAccessRequestedByOrg: Record<string, boolean>dataProcessingAccepted: booleandataProcessingApprovalDisabledReason: string | nulldataProcessingDismissed: boolean+ pendingApprovalRedirect: PendingApprovalRedirect | nullrequestingAiAccess: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface aiConsentLogicActions {- acceptDataProcessing: (testOnlyOverride?: boolean) => {+ acceptDataProcessing: (+ testOnlyOverride?: boolean,+ resumeUrl?: string+ ) => {+ resumeUrl: string | undefinedtestOnlyOverride: boolean | undefined}dismissDataProcessing: () => {@@ -44,6 +65,9 @@ export interface aiConsentLogicActions {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.@@ -68,14 +92,15 @@ export type aiConsentLogicType = MakeLogicType<export const aiConsentLogic = kea<aiConsentLogicType>([path(['scenes', 'settings', 'organization', 'aiConsentLogic']),connect(() => ({- values: [organizationLogic, ['currentOrganization']],+ values: [organizationLogic, ['currentOrganization'], userLogic, ['user']],})),actions({- acceptDataProcessing: (testOnlyOverride?: boolean) => ({ testOnlyOverride }),+ acceptDataProcessing: (testOnlyOverride?: boolean, resumeUrl?: string) => ({ testOnlyOverride, resumeUrl }),dismissDataProcessing: true,requestAiAccess: true,markAiAccessRequested: (organizationId: string) => ({ organizationId }),requestAiAccessError: true,+ setPendingApprovalRedirect: (redirect: PendingApprovalRedirect | null) => ({ redirect }),}),reducers({dataProcessingDismissed: [@@ -85,6 +110,13 @@ export const aiConsentLogic = kea<aiConsentLogicType>([dismissDataProcessing: () => true,},],+ pendingApprovalRedirect: [+ null as PendingApprovalRedirect | null,+ { persist: true, storageKey: AI_CONSENT_PENDING_REDIRECT_STORAGE_KEY },+ {+ setPendingApprovalRedirect: (_, { redirect }) => redirect,+ },+ ],requestingAiAccess: [false,{@@ -102,10 +134,21 @@ export const aiConsentLogic = kea<aiConsentLogicType>([],}),listeners(({ actions, values }) => ({- acceptDataProcessing: async ({ testOnlyOverride }) => {- await organizationLogic.asyncActions.updateOrganization({- is_ai_data_processing_approved: testOnlyOverride ?? true,- })+ acceptDataProcessing: async ({ testOnlyOverride, 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)+ throw error+ }+ actions.setPendingApprovalRedirect(null)+ lemonToast.success('AI data processing approved')+ if (resumeUrl) {+ router.actions.push(resumeUrl)+ }},requestAiAccess: async () => {const organization = values.currentOrganization@@ -145,4 +188,33 @@ export const aiConsentLogic = kea<aiConsentLogicType>([!!(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)+ }+ },+ })),])diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsxindex 0fad97fb8f5a..93d076640546 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx@@ -91,6 +91,7 @@ function CreateScannerButton({ignoreDismissalhideTrainingDisclaimerhidden={!consentRequested}+ pendingRedirectUrl={urls.replayVisionTemplates()}onApprove={() => {setConsentRequested(false)goToCreate()