: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(posthog-ai): decide 2.0 from one flag and keep it working for grandfathered users (#129441)
Peter Kirkham6c122e71ed36
diff --git a/frontend/src/layout/ai/pendingAiPrompt.ts b/frontend/src/layout/ai/pendingAiPrompt.tsnew file mode 100644index 000000000000..2971b7040371--- /dev/null+++ b/frontend/src/layout/ai/pendingAiPrompt.ts@@ -0,0 +1,11 @@+/** Key for persisting pending AI prompts across page reloads (e.g., OAuth redirects) */+export const PENDING_AI_PROMPT_KEY = 'posthog_ai_pending_prompt'++/** Classic PostHog AI prefills its composer with this prompt the next time it mounts. */+export function stashPendingAiPrompt(prompt: string): void {+ try {+ sessionStorage.setItem(PENDING_AI_PROMPT_KEY, JSON.stringify({ prompt, timestamp: Date.now() }))+ } catch {+ // sessionStorage might be unavailable+ }+}diff --git a/frontend/src/layout/ai/runnerPanelLogic.ts b/frontend/src/layout/ai/runnerPanelLogic.tsindex be2fc66f1902..b0ed3cbb9ee6 100644--- a/frontend/src/layout/ai/runnerPanelLogic.ts+++ b/frontend/src/layout/ai/runnerPanelLogic.ts@@ -35,6 +35,9 @@ export interface runnerPanelLogicActions {goBack: () => {value: true}+ handOffToClassic: (prompt: string) => {+ prompt: string+ }setActiveCreation: (creation: ActiveCreation) => {creation: ActiveCreation}@@ -82,6 +85,9 @@ export const runnerPanelLogic = kea<runnerPanelLogicType>([setHistoryExpanded: (expanded: boolean) => ({ expanded }),goBack: true,setCameFromHistory: (cameFromHistory: boolean) => ({ cameFromHistory }),+ // The server refused a 2.0 send, and the host is about to swap this panel to classic PostHog AI.+ // The host gives the prompt to classic as its draft.+ handOffToClassic: (prompt: string) => ({ prompt }),}),reducers({diff --git a/frontend/src/lib/logic/featureFlagLogic.ts b/frontend/src/lib/logic/featureFlagLogic.tsindex c77d9d0a60a0..330eaa6b0d42 100644--- a/frontend/src/lib/logic/featureFlagLogic.ts+++ b/frontend/src/lib/logic/featureFlagLogic.ts@@ -48,6 +48,13 @@ export function getPersistedFeatureFlags(appContext: AppContext | undefined = ge}let cachedFlagsSerialized: string | null = null+// Set when the server refuses PostHog AI 2.0 to a page that still shows it. It overrides the server-rendered+// decision, and it also works in an OAuth session, which never reads that decision.+let posthogAiAccessRevoked = false++export function revokePostHogAIAccess(): void {+ posthogAiAccessRevoked = true+}let cachedFlagsProxy: FeatureFlagsSet | null = nullfunction spyOnFeatureFlags(featureFlags: FeatureFlagsSet): FeatureFlagsSet {@@ -58,7 +65,7 @@ function spyOnFeatureFlags(featureFlags: FeatureFlagsSet): FeatureFlagsSet {? { ...persistedFlags, ...featureFlags }: persistedFlags// PostHog AI 2.0 follows the server's access gate, which also admits beta orgs, so a denied user never sees 2.0 UI.- const posthogAiAccess = appContext?.posthog_ai_access+ const posthogAiAccess = posthogAiAccessRevoked ? false : appContext?.posthog_ai_accessif (posthogAiAccess !== undefined) {availableFlags[FEATURE_FLAGS.PHAI_SANDBOX_MODE] = posthogAiAccess}@@ -156,6 +163,9 @@ export const featureFlagLogic = kea<featureFlagLogicType>([],}),afterMount(({ actions }) => {+ // The app shell keeps this logic mounted for the page lifetime, so a new mount is a new page that+ // starts from the server decision again.+ posthogAiAccessRevoked = falseposthog.onFeatureFlags(actions.setFeatureFlags)if (posthog.config?.advanced_disable_flags) {// posthog-js never calls back when flags are off, and the app holds its first renderdiff --git a/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx b/frontend/src/scenes/max/components/AiFirstMaxInstance.tsxindex db0695c84489..ff39be9ac552 100644--- a/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx+++ b/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx@@ -178,7 +178,7 @@ export function AiFirstMaxInstance({ tabId, taskId, chatId }: AiFirstMaxInstance</div>)}<div className="flex flex-col flex-1 min-h-0">- <BindLogic logic={phaiAiComposerSeedLogic} props={{}}>+ <BindLogic logic={phaiAiComposerSeedLogic} props={{ tabId }}>{/* The quill task header carries the debug logs switch in its own overflow menu. */}<EmbeddedRunnertaskId={taskId}diff --git a/frontend/src/scenes/max/max-storage-keys.ts b/frontend/src/scenes/max/max-storage-keys.tsindex 4c59680b0050..aa58e238f068 100644--- a/frontend/src/scenes/max/max-storage-keys.ts+++ b/frontend/src/scenes/max/max-storage-keys.ts@@ -3,8 +3,8 @@// the heavy Max thread runtime (and the sandbox stream logic) into the authenticated-shell// eager import graph — see frontend/bin/check-eager-graph.mjs.-/** Key for persisting pending AI prompts across page reloads (e.g., OAuth redirects) */-export const PENDING_AI_PROMPT_KEY = 'posthog_ai_pending_prompt'+// The 2.0 runner stashes a refused prompt under this key too, and it cannot import from scenes/max.+export { PENDING_AI_PROMPT_KEY } from '~/layout/ai/pendingAiPrompt'/** Scene keys whose PostHog AI panel auto-open the user has dismissed (see sceneAgentPanelLogic). */export const PHAI_SCENE_AUTO_OPEN_DISMISSED_KEY = 'posthog_ai_scene_auto_open_dismissed'diff --git a/frontend/src/scenes/max/phaiAiComposerSeedLogic.ts b/frontend/src/scenes/max/phaiAiComposerSeedLogic.tsindex 1a94807f3138..5eac219f9bfc 100644--- a/frontend/src/scenes/max/phaiAiComposerSeedLogic.ts+++ b/frontend/src/scenes/max/phaiAiComposerSeedLogic.ts@@ -1,12 +1,20 @@-import { MakeLogicType, connect, kea, path } from 'kea'+import { MakeLogicType, connect, kea, listeners, path, props } from 'kea'import { router, urlToAction } from 'kea-router'import { urls } from 'scenes/urls'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'+import { composerSeedLogic } from 'products/posthog_ai/frontend/api/logics'import type { ComposerSeed } from '../../../../products/posthog_ai/frontend/logics/composerSeedLogic'import { maxGlobalLogic } from './maxGlobalLogic'+import { maxLogic } from './maxLogic'++export interface PhaiAiComposerSeedLogicProps {+ /** The scene tab of the hosting AI scene, which also keys its classic `maxLogic`. */+ tabId?: string+}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface phaiAiComposerSeedLogicValues {@@ -18,9 +26,16 @@ export interface phaiAiComposerSeedLogicActions {setSeed: (seed: ComposerSeed) => {seed: ComposerSeed} // composerSeedLogic+ handOffToClassic: (prompt: string) => {+ prompt: string+ } // runnerPanelLogic}-export type phaiAiComposerSeedLogicType = MakeLogicType<phaiAiComposerSeedLogicValues, phaiAiComposerSeedLogicActions>+export type phaiAiComposerSeedLogicType = MakeLogicType<+ phaiAiComposerSeedLogicValues,+ phaiAiComposerSeedLogicActions,+ PhaiAiComposerSeedLogicProps+>/*** Forwards the existing `/ai?ask=...` deep link into the new task composer. This logic is mounted only while@@ -28,12 +43,20 @@ export type phaiAiComposerSeedLogicType = MakeLogicType<phaiAiComposerSeedLogicV*/export const phaiAiComposerSeedLogic = kea<phaiAiComposerSeedLogicType>([path(['scenes', 'max', 'phaiAiComposerSeedLogic']),+ props({} as PhaiAiComposerSeedLogicProps),connect({values: [maxGlobalLogic, ['dataProcessingAccepted']],- actions: [composerSeedLogic, ['setSeed']],+ actions: [composerSeedLogic, ['setSeed'], runnerPanelLogic({}), ['handOffToClassic']],}),+ listeners(({ props }) => ({+ // The scene swaps to the legacy chat next, and that chat reads its draft from this tab's `maxLogic`.+ handOffToClassic: ({ prompt }) => {+ maxLogic.findMounted({ panelId: props.tabId })?.actions.setQuestion(prompt)+ },+ })),+urlToAction(({ actions, values }) => ({[urls.ai()]: (_, search, hash) => {if (search.ask && !search.chat && !search.task) {diff --git a/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.test.ts b/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.test.tsindex d73a74797a12..10bb580de37c 100644--- a/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.test.ts+++ b/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.test.ts@@ -2,6 +2,7 @@ import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'import { expectLogic } from 'kea-test-utils'+import { SIDE_PANEL_PANEL_ID } from '~/layout/ai/aiPanelIds'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -9,6 +10,7 @@ import { SidePanelTab } from '~/types'import { taskTrackerSceneLogic } from 'products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic'+import { maxLogic } from './maxLogic'import { phaiSidePanelComposerSeedLogic } from './phaiSidePanelComposerSeedLogic'describe('phaiSidePanelComposerSeedLogic', () => {@@ -53,6 +55,31 @@ describe('phaiSidePanelComposerSeedLogic', () => {trackerLogic?.unmount()})+ // The panel swaps to the legacy chat when the server refuses a 2.0 send, which unmounts the runner and its+ // restored draft. The refused message must become the legacy chat's draft, or the user loses it.+ it('gives a send the server refuses to the legacy chat as its draft', async () => {+ useMocks({+ post: {+ '/api/projects/:team/tasks/': () => [+ 403,+ { type: 'permission_denied', code: 'task_unavailable', error: "This task isn't available to you." },+ ],+ },+ })+ initKeaTests()+ const legacyChat = maxLogic({ panelId: SIDE_PANEL_PANEL_ID })+ legacyChat.mount()+ try {+ mountPanelLogics()+ trackerLogic.actions.setNewTaskData({ description: 'Explain the example chart' })+ await expectLogic(trackerLogic, () => trackerLogic.actions.submitNewTask()).toFinishAllListeners()++ expect(legacyChat.values.question).toBe('Explain the example chart')+ } finally {+ legacyChat.unmount()+ }+ })+// The org-level AI data-processing consent gate: an auto-run CTA (`!`-prefixed prompt) must never start// an agent run before the org approved AI data processing — the legacy path blocks this in `askMax`, and// dropping the `dataProcessingAccepted` check in the seed bridge would silently ship unconsented sandboxdiff --git a/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.ts b/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.tsindex 229821bd8434..63fc14d9ee17 100644--- a/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.ts+++ b/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.ts@@ -1,13 +1,14 @@import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props } from 'kea'-import { REPORT_AI_PANEL, SCOUT_AI_PANEL } from '~/layout/ai/aiPanelIds'+import { REPORT_AI_PANEL, SCOUT_AI_PANEL, SIDE_PANEL_PANEL_ID } from '~/layout/ai/aiPanelIds'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { SidePanelTab } from '~/types'import { ComposerSeed, composerSeedLogic } from 'products/posthog_ai/frontend/api/logics'import { maxGlobalLogic } from './maxGlobalLogic'-import { parseCommandString } from './maxLogic'+import { maxLogic, parseCommandString } from './maxLogic'export interface PhaiSidePanelComposerSeedLogicProps {/** The embedded composer's panel key — the same one passed to its `taskTrackerSceneLogic`/`composerSeedLogic`. */@@ -47,6 +48,9 @@ export interface phaiSidePanelComposerSeedLogicActions {setSeed: (seed: ComposerSeed) => {seed: ComposerSeed} // composerSeedLogic+ handOffToClassic: (prompt: string) => {+ prompt: string+ } // runnerPanelLogic}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -82,10 +86,19 @@ export const phaiSidePanelComposerSeedLogic = kea<phaiSidePanelComposerSeedLogicmaxGlobalLogic,['dataProcessingAccepted'],],- actions: [composerSeedLogic({ panelId: props.panelId }), ['setSeed']],+ actions: [+ composerSeedLogic({ panelId: props.panelId }),+ ['setSeed'],+ runnerPanelLogic({ panelId: props.panelId }),+ ['handOffToClassic'],+ ],})),listeners(({ actions, values }) => ({+ // The panel swaps to the legacy chat next, and that chat reads its draft from the side panel `maxLogic`.+ handOffToClassic: ({ prompt }) => {+ maxLogic.findMounted({ panelId: SIDE_PANEL_PANEL_ID })?.actions.setQuestion(prompt)+ },[sidePanelStateLogic.actionTypes.openSidePanel]: ({ tab, options }) => {if (tab !== SidePanelTab.Max) {returndiff --git a/products/posthog_ai/frontend/logics/tasksLogic.ts b/products/posthog_ai/frontend/logics/tasksLogic.tsindex fb055ed6167c..bb44334e1499 100644--- a/products/posthog_ai/frontend/logics/tasksLogic.ts+++ b/products/posthog_ai/frontend/logics/tasksLogic.ts@@ -23,7 +23,7 @@ import { OriginProduct, Task, TaskAssigneeFilter, TaskListParams, TaskUpsertPropimport { taskEventsLogic } from './taskEventsLogic'import { taskHistoryLogic } from './taskHistoryLogic'-export function hasTasksFlag(featureFlags: FeatureFlagsSet): boolean {+function hasTasksFlag(featureFlags: FeatureFlagsSet): boolean {return !!(featureFlags[FEATURE_FLAGS.TASKS] || featureFlags[FEATURE_FLAGS.PHAI_SANDBOX_MODE])}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsxindex 046a6bf6028a..501f645ba69c 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx@@ -280,6 +280,9 @@ function UnifiedNavigationStory({ viewMode = 'new' }: { viewMode?: 'new' | 'legareturn <App />}+// The list and composer need PostHog AI 2.0 access, or the scene sends the user to classic PostHog AI.+const WITH_POSTHOG_AI_ACCESS = [FEATURE_FLAGS.TASKS, FEATURE_FLAGS.PHAI_SANDBOX_MODE]+const meta: Meta = {component: App,title: 'Scenes-App/Tasks',@@ -310,7 +313,11 @@ export default metatype Story = StoryObj<typeof meta>-export const Composer: Story = {}+export const Composer: Story = {+ parameters: {+ featureFlags: WITH_POSTHOG_AI_ACCESS,+ },+}export const UnifiedNavigation: Story = {render: () => <UnifiedNavigationStory />,@@ -391,13 +398,14 @@ export const PiTaskSelected: Story = {export const NewTask: Story = {parameters: {pageUrl: taskNewUrl(),+ featureFlags: WITH_POSTHOG_AI_ACCESS,},}export const NewTaskQuill: Story = {parameters: {pageUrl: taskNewUrl(),- featureFlags: [FEATURE_FLAGS.TASKS, FEATURE_FLAGS.PHAI_QUILL],+ featureFlags: [...WITH_POSTHOG_AI_ACCESS, FEATURE_FLAGS.PHAI_QUILL],},}@@ -406,6 +414,7 @@ export const NewTaskQuill: Story = {export const NewTaskWithRepository: Story = {parameters: {pageUrl: taskNewUrl(),+ featureFlags: WITH_POSTHOG_AI_ACCESS,},decorators: [mswDecorator({@@ -578,7 +587,10 @@ const MOBILE_PARAMETERS = {}export const MobileComposer: Story = {- parameters: MOBILE_PARAMETERS,+ parameters: {+ ...MOBILE_PARAMETERS,+ featureFlags: WITH_POSTHOG_AI_ACCESS,+ },}// Mobile: the new-task composer is the single full-screen column.@@ -586,6 +598,7 @@ export const MobileNewTask: Story = {parameters: {...MOBILE_PARAMETERS,pageUrl: taskNewUrl(),+ featureFlags: WITH_POSTHOG_AI_ACCESS,},}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.tsindex e7bca4a5a682..09f8d1030e64 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts@@ -5,14 +5,17 @@ import { expectLogic } from 'kea-test-utils'import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { phaiAiComposerSeedLogic } from 'scenes/max/phaiAiComposerSeedLogic'import { urls } from 'scenes/urls'import { aiConsentLogic } from '~/layout/ai/aiConsentLogic'import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'+import { PENDING_AI_PROMPT_KEY } from '~/layout/ai/pendingAiPrompt'import { todaySpacesLogic } from '~/layout/today/todaySpacesLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { AppContext } from '~/types'import {ModelAccessEnumApi,@@ -108,8 +111,11 @@ describe('taskTrackerSceneLogic', () => {},})initKeaTests()- // Without Tasks access the scene sends `/tasks` URLs to classic PostHog AI.- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TASKS], { [FEATURE_FLAGS.TASKS]: true })+ // Without PostHog AI 2.0 the scene sends `/tasks` URLs to classic PostHog AI.+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TASKS, FEATURE_FLAGS.PHAI_SANDBOX_MODE], {+ [FEATURE_FLAGS.TASKS]: true,+ [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true,+ })toolEvents = toolStreamEventsLogic()toolEvents.mount()toolEvents.actions.registerToolListener('editor', {@@ -195,13 +201,15 @@ describe('taskTrackerSceneLogic', () => {expect(runBody).not.toHaveProperty('pending_user_artifact_ids')})- // An Inbox task link must still open its transcript without Tasks access.+ // An Inbox task link must still open its transcript without 2.0. The Tasks flag alone does not grant the composer,+ // because the server decides 2.0 from one flag.it.each([- ['/tasks', '/ai'],- ['/tasks/new', '/ai'],- ['/tasks/a1b2c3d4-0000-4000-8000-000000000001', '/tasks/a1b2c3d4-0000-4000-8000-000000000001'],- ])('without Tasks access, %s lands on %s', async (start, expected) => {- featureFlagLogic.actions.setFeatureFlags([], {})+ ['/tasks', '/ai', {}],+ ['/tasks/new', '/ai', {}],+ ['/tasks/new', '/ai', { [FEATURE_FLAGS.TASKS]: true }],+ ['/tasks/a1b2c3d4-0000-4000-8000-000000000001', '/tasks/a1b2c3d4-0000-4000-8000-000000000001', {}],+ ])('without PostHog AI 2.0, %s lands on %s (flags %j)', async (start, expected, flags) => {+ featureFlagLogic.actions.setFeatureFlags(Object.keys(flags), flags)logic.mount()router.actions.push(start)await expectLogic(logic).toFinishAllListeners()@@ -406,6 +414,43 @@ describe('taskTrackerSceneLogic', () => {})+ // A page can still show 2.0 after the server stopped allowing it. The refused message must reach classic+ // PostHog AI without passing through the URL, and the switch must also hold in an OAuth session, which+ // has no server-rendered app context.+ it.each([+ ['with the server-rendered decision', true],+ ['without an app context', false],+ ])('hands a send the server refuses to classic PostHog AI %s', async (_, hasAppContext) => {+ const originalAppContext = window.POSTHOG_APP_CONTEXT+ window.POSTHOG_APP_CONTEXT = hasAppContext+ ? ({ ...originalAppContext, posthog_ai_access: true } as AppContext)+ : undefined+ useMocks({+ post: {+ '/api/projects/:team/tasks/': () => [+ 403,+ { type: 'permission_denied', code: 'task_unavailable', error: "This task isn't available to you." },+ ],+ },+ })+ try {+ logic.mount()+ router.actions.push('/tasks/new')+ logic.actions.setNewTaskData({ description: 'Explain the example chart' })+ await expectLogic(logic, () => logic.actions.submitNewTask()).toFinishAllListeners()++ expect(featureFlagLogic.values.featureFlags[FEATURE_FLAGS.PHAI_SANDBOX_MODE]).toBe(false)+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toBe('/ai')+ expect(router.values.searchParams).toEqual({})+ expect(JSON.parse(sessionStorage.getItem(PENDING_AI_PROMPT_KEY) ?? '{}')).toMatchObject({+ prompt: 'Explain the example chart',+ })+ } finally {+ window.POSTHOG_APP_CONTEXT = originalAppContext+ sessionStorage.clear()+ }+ })+// PostHog AI can run without a repo: a description-only submit must still create and run the task with a// null repository, not bail. Guards against re-adding a "Repository is required" gate on the send path.it('creates and runs a task with no repository selected', async () => {diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex e6e1d746facc..1a6c7c50c4c8 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -8,7 +8,7 @@ import { lemonToast } from '@posthog/lemon-ui'import { ApiError } from 'lib/api-error'import { FEATURE_FLAGS } from 'lib/constants'import { integrationsLogic } from 'lib/integrations/integrationsLogic'-import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { type FeatureFlagsSet, featureFlagLogic, revokePostHogAIAccess } from 'lib/logic/featureFlagLogic'import { uuid } from 'lib/utils/dom'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { projectLogic } from 'scenes/projectLogic'@@ -17,6 +17,7 @@ import { urls } from 'scenes/urls'import { aiConsentLogic } from '~/layout/ai/aiConsentLogic'import type { AttachedContextItem } from '~/layout/ai/attachedContext'import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'+import { stashPendingAiPrompt } from '~/layout/ai/pendingAiPrompt'import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import type { ActiveCreation } from '~/layout/ai/runnerPanelLogic'import { todaySpacesLogic } from '~/layout/today/todaySpacesLogic'@@ -61,7 +62,7 @@ import { runCancellationLogic } from '../../logics/runCancellationLogic'import { runInteractionLogic, type RunContinuationHandoff } from '../../logics/runInteractionLogic'import { taskDefaultsLogic } from '../../logics/taskDefaultsLogic'import { taskRunDefaultsLogic } from '../../logics/taskRunDefaultsLogic'-import { hasTasksFlag, tasksLogic } from '../../logics/tasksLogic'+import { tasksLogic } from '../../logics/tasksLogic'import { taskWarmLogic } from '../../logics/taskWarmLogic'import type { WarmLease, WarmSubmission } from '../../logics/taskWarmLogic'import { toolStreamEventsLogic } from '../../logics/toolStreamEventsLogic'@@ -513,6 +514,30 @@ export type taskTrackerSceneLogicType = MakeLogicType<taskTrackerSceneLogicMeta>+/**+ * The server refused 2.0 to a page that still shows it, such as one rendered before a flag outage.+ * Classic PostHog AI takes over for the rest of the session, with the user's message as its draft.+ */+function moveToClassicPostHogAI(featureFlags: FeatureFlagsSet, message: string, panelId: string | undefined): void {+ revokePostHogAIAccess()+ // A side panel or the AI scene swaps to classic in place, so its host takes the message. The message never+ // goes in the URL, because pageview events record the full URL.+ const swapsInPlace = !!panelId || removeProjectIdIfPresent(router.values.location.pathname) === urls.ai()+ if (message.trim()) {+ if (swapsInPlace) {+ runnerPanelLogic({ panelId }).actions.handOffToClassic(message)+ } else {+ stashPendingAiPrompt(message)+ }+ }+ // featureFlagLogic applies the revocation when it computes the flags, so resending the current flags applies it.+ const currentFlags: Record<string, string | boolean> = JSON.parse(JSON.stringify(featureFlags))+ featureFlagLogic.findMounted()?.actions.setFeatureFlags(Object.keys(currentFlags), currentFlags)+ if (!swapsInPlace) {+ router.actions.push(urls.ai())+ }+}+export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([path(['products', 'posthog_ai', 'frontend', 'scenes', 'TaskTracker', 'taskTrackerSceneLogic']),props({} as TaskTrackerSceneLogicProps),@@ -1300,6 +1325,9 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([}actions.clearActiveCreation()}+ if (error instanceof ApiError && error.code === 'task_unavailable') {+ moveToClassicPostHogAI(values.featureFlags, values.newTaskData.description, props.panelId)+ }if (error instanceof ApiError && error.code === 'warm_run_activation_unavailable') {lemonToast.error("Couldn't start this run yet. Please try again.")}@@ -1423,9 +1451,9 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([actions.clearActiveCreation()}}- // Only the list and composer fall back to classic PostHog AI. Inbox task links need neither flag.+ // Only the list and composer fall back to classic PostHog AI. Inbox task links need no 2.0 access.const redirectedWithoutAccess = (taskId?: string): boolean => {- if (props.panelId || hasTasksFlag(values.featureFlags) || (taskId && taskId !== 'new')) {+ if (props.panelId || values.featureFlags[FEATURE_FLAGS.PHAI_SANDBOX_MODE] || (taskId && taskId !== 'new')) {return false}router.actions.replace(urls.ai())diff --git a/products/tasks/backend/access.py b/products/tasks/backend/access.pyindex 1242ddb834b0..dcb17c4d8e02 100644--- a/products/tasks/backend/access.py+++ b/products/tasks/backend/access.py@@ -99,15 +99,12 @@ def _signed_up_after_cutoff(user: User) -> bool:return cutoff is not None and user.date_joined >= cutoff-def _resolve_flag(- flag_key: str, user: User, organization: "Organization", person_properties: dict[str, str] | None = None-) -> bool | None:+def _resolve_flag(flag_key: str, user: User, organization: "Organization") -> bool | None:organization_id = str(organization.id)enabled = get_feature_flag_or_none(flag_key,str(user.distinct_id),groups={"organization": organization_id},- person_properties=person_properties,group_properties={"organization": {"id": organization_id}},only_evaluate_locally=False,send_feature_flag_events=False,@@ -212,9 +209,10 @@ class PostHogAIAccessDecision(StrEnum):_POSTHOG_AI_DECISION_VALUES = frozenset(decision.value for decision in PostHogAIAccessDecision)-# Everyone who has PostHog AI 2.0 before the gate keeps it, whatever the beta rules say.-POSTHOG_AI_GRANDFATHERED_FLAGS = ("phai-sandbox-mode", "tasks")-POSTHOG_AI_BETA_FLAG = "phai-2-beta"+# The one flag that decides PostHog AI 2.0. Its `grandfathered` variant keeps 2.0 for everyone who had it before+# the gate, whatever the beta rules say. Its `beta` variant is the rollout, and the rules in its payload apply.+POSTHOG_AI_ACCESS_FLAG = "phai-2-beta"+POSTHOG_AI_GRANDFATHERED_VARIANT = "grandfathered"_POSTHOG_AI_FUNDING_CACHE_SECONDS = 300_POSTHOG_AI_DECISION_CACHE_KEY = "posthog_ai_access_decision:{organization_id}:{user_id}:{flags_fingerprint}"# Most page loads come more than a minute after the user's previous one, so a short cache misses on nearly every@@ -256,11 +254,11 @@ def _posthog_ai_person_properties(user: User) -> dict[str, str]:return {"email": user.email} if user.email else {}-def _resolve_beta(user: User, organization: "Organization") -> FeatureFlagResult | None:+def _resolve_access_flag(user: User, organization: "Organization") -> FeatureFlagResult | None:organization_id = str(organization.id)try:return posthoganalytics.get_feature_flag_result(- POSTHOG_AI_BETA_FLAG,+ POSTHOG_AI_ACCESS_FLAG,str(user.distinct_id),groups={"organization": organization_id},person_properties=_posthog_ai_person_properties(user),@@ -268,7 +266,7 @@ def _resolve_beta(user: User, organization: "Organization") -> FeatureFlagResultsend_feature_flag_events=False,)except Exception:- logger.warning("posthog_ai_beta_flag_failed", exc_info=True)+ logger.warning("posthog_ai_access_flag_failed", exc_info=True)return None@@ -277,25 +275,24 @@ def get_posthog_ai_access_decision(user: User, organization: "Organization") ->if not user or not user.is_authenticated or not user.distinct_id:return PostHogAIAccessDecision.UNRESOLVED- person_properties = _posthog_ai_person_properties(user)- # A failed lookup reads as None. Caching it as a denial would hide a flag outage.- flag_unresolved = False- for flag in POSTHOG_AI_GRANDFATHERED_FLAGS:- enabled = _resolve_flag(flag, user, organization, person_properties)- if enabled:- return PostHogAIAccessDecision.GRANDFATHERED- flag_unresolved = flag_unresolved or enabled is None- if flag_unresolved:- return PostHogAIAccessDecision.UNRESOLVED+ decision = _decide_posthog_ai_access(user, organization)+ # A fresh decision replaces the page-render copy, so a denied caller's next page shows classic PostHog AI.+ _remember_page_render_decision(user, organization, decision)+ return decision+- beta = _resolve_beta(user, organization)- if beta is None:+def _decide_posthog_ai_access(user: User, organization: "Organization") -> PostHogAIAccessDecision:+ access = _resolve_access_flag(user, organization)+ # A failed lookup reads as None. Caching it as a denial would hide a flag outage.+ if access is None:return PostHogAIAccessDecision.UNRESOLVED- if not beta.enabled:+ if not access.enabled:return PostHogAIAccessDecision.BETA_OFF- rules = _posthog_ai_beta_rules(beta.payload)+ if access.variant == POSTHOG_AI_GRANDFATHERED_VARIANT:+ return PostHogAIAccessDecision.GRANDFATHERED+ rules = _posthog_ai_beta_rules(access.payload)if rules is None:- logger.warning("posthog_ai_beta_rules_invalid", flag_key=POSTHOG_AI_BETA_FLAG)+ logger.warning("posthog_ai_beta_rules_invalid", flag_key=POSTHOG_AI_ACCESS_FLAG)return PostHogAIAccessDecision.UNRESOLVEDtry:@@ -317,23 +314,36 @@ def _deciding_flags_fingerprint() -> str | None:all_definitions = posthoganalytics.feature_flag_definitions()if all_definitions is None:return None- deciding_keys = {*POSTHOG_AI_GRANDFATHERED_FLAGS, POSTHOG_AI_BETA_FLAG}- definitions = [definition for definition in all_definitions if definition.get("key") in deciding_keys]- serialized = json.dumps(sorted(definitions, key=lambda definition: definition["key"]), sort_keys=True, default=str)+ definitions = [definition for definition in all_definitions if definition.get("key") == POSTHOG_AI_ACCESS_FLAG]+ serialized = json.dumps(definitions, sort_keys=True, default=str)return hashlib.sha256(serialized.encode()).hexdigest()[:16]-def get_cached_posthog_ai_access_decision(- user: User, organization: "Organization", *, cache_seconds: int = _POSTHOG_AI_PAGE_RENDER_CACHE_SECONDS-) -> PostHogAIAccessDecision:- """For page renders, so a load does not wait on remote flag lookups. Enforcement points call the uncached- decision. An unresolved decision is never cached."""+def _page_render_cache_key_and_timeout(user: User, organization: "Organization") -> tuple[str, int]:flags_fingerprint = _deciding_flags_fingerprint()+ timeout = _POSTHOG_AI_PAGE_RENDER_CACHE_SECONDSif flags_fingerprint is None:- cache_seconds = min(cache_seconds, _POSTHOG_AI_UNLOADED_DEFINITIONS_CACHE_SECONDS)+ timeout = _POSTHOG_AI_UNLOADED_DEFINITIONS_CACHE_SECONDScache_key = _POSTHOG_AI_DECISION_CACHE_KEY.format(organization_id=organization.id, user_id=user.pk, flags_fingerprint=flags_fingerprint)+ return cache_key, timeout+++def _remember_page_render_decision(user: User, organization: "Organization", decision: PostHogAIAccessDecision) -> None:+ if decision == PostHogAIAccessDecision.UNRESOLVED or not user.pk:+ return+ cache_key, timeout = _page_render_cache_key_and_timeout(user, organization)+ try:+ cache.set(cache_key, decision.value, timeout=timeout)+ except Exception:+ logger.warning("posthog_ai_access_decision_cache_write_failed", exc_info=True)+++def get_cached_posthog_ai_access_decision(user: User, organization: "Organization") -> PostHogAIAccessDecision:+ """For page renders, so a load does not wait on remote flag lookups. Enforcement points call the uncached+ decision, which also refreshes this copy. An unresolved decision is never cached."""+ cache_key, _timeout = _page_render_cache_key_and_timeout(user, organization)try:cached = cache.get(cache_key)except Exception:@@ -341,13 +351,7 @@ def get_cached_posthog_ai_access_decision(cached = Noneif isinstance(cached, str) and cached in _POSTHOG_AI_DECISION_VALUES:return PostHogAIAccessDecision(cached)- decision = get_posthog_ai_access_decision(user, organization)- if decision != PostHogAIAccessDecision.UNRESOLVED:- try:- cache.set(cache_key, decision.value, timeout=cache_seconds)- except Exception:- logger.warning("posthog_ai_access_decision_cache_write_failed", exc_info=True)- return decision+ return get_posthog_ai_access_decision(user, organization)def has_loops_access(user: User, team: "Team | None" = None) -> bool:diff --git a/products/tasks/backend/logic/services/code_usage_gate.py b/products/tasks/backend/logic/services/code_usage_gate.pyindex df7930595f9c..08b64cebf2ef 100644--- a/products/tasks/backend/logic/services/code_usage_gate.py+++ b/products/tasks/backend/logic/services/code_usage_gate.py@@ -134,19 +134,28 @@ def code_access_required_response(posthog_ai_task_id: str | UUID | None = None,fail_open_on_resolution_error: bool = False,) -> Response | None:- """Also applies the PostHog AI 2.0 gate to PostHog AI tasks, so every sandbox entry point that- checks Desktop access checks that too. Pass `origin_product` when no task exists yet.+ """PostHog AI tasks take the PostHog AI 2.0 decision in place of the Desktop check. Every other task takes+ the Desktop check. Pass `origin_product` when no task exists yet.- `posthog_ai_task_id` names the task for the PostHog AI gate only. Use it where a sandbox token bound to- the task must still pass the Desktop gate, which a `task_id` would let it skip."""+ `posthog_ai_task_id` names the task without the sandbox-token exemption that a `task_id` gives, for a+ caller whose sandbox token must not skip the check."""if _task_bound_internal_run(request, task_id):return None- # A Desktop fail-open must not skip the AI gate, which resolves on its own.- if desktop_response := _desktop_access_required_response(request, organization, fail_open_on_resolution_error):- return desktop_response- return posthog_ai_access_required_response(- request, organization, task_id=task_id or posthog_ai_task_id, origin_product=origin_product- )+ if _is_posthog_ai_task(organization, task_id or posthog_ai_task_id, origin_product):+ # The 2.0 decision already applies the funding rules to beta orgs, and it never refuses a grandfathered+ # user, so the Desktop rules would only break a 2.0 the UI shows as available.+ return _posthog_ai_access_required_response(request, organization)+ return _desktop_access_required_response(request, organization, fail_open_on_resolution_error)+++def _is_posthog_ai_task(organization: "Organization", task_id: str | UUID | None, origin_product: str | None) -> bool:+ if origin_product is None and task_id is not None:+ origin_product = (+ Task.objects.filter(id=task_id, team__organization_id=organization.id)+ .values_list("origin_product", flat=True)+ .first()+ )+ return origin_product == Task.OriginProduct.POSTHOG_AIdef _desktop_access_required_response(@@ -202,21 +211,7 @@ def _desktop_access_required_response()-def posthog_ai_access_required_response(- request: Request,- organization: "Organization",- *,- task_id: str | UUID | None = None,- origin_product: str | None = None,-) -> Response | None:- if origin_product is None and task_id is not None:- origin_product = (- Task.objects.filter(id=task_id, team__organization_id=organization.id)- .values_list("origin_product", flat=True)- .first()- )- if origin_product != Task.OriginProduct.POSTHOG_AI:- return None+def _posthog_ai_access_required_response(request: Request, organization: "Organization") -> Response | None:if get_posthog_ai_access_decision(cast("User", request.user), organization).allowed:return Nonereturn Response(diff --git a/products/tasks/backend/tests/test_desktop_access.py b/products/tasks/backend/tests/test_desktop_access.pyindex 703122611109..8ca6ba27b06b 100644--- a/products/tasks/backend/tests/test_desktop_access.py+++ b/products/tasks/backend/tests/test_desktop_access.py@@ -11,7 +11,13 @@ from rest_framework import statusfrom posthog.models import Organization, OrganizationMembership, Team-from products.tasks.backend.access import DesktopAccessReason, DesktopAccessResolutionError, get_desktop_access_decision+from products.tasks.backend.access import (+ DesktopAccessDecision,+ DesktopAccessReason,+ DesktopAccessResolutionError,+ PostHogAIAccessDecision,+ get_desktop_access_decision,+)from products.tasks.backend.logic.services.code_usage_gate import code_access_required_responsefrom ee.billing.billing_manager import OrganizationFundingStatus, PrepaidCreditState, StartupProgramLabel@@ -221,6 +227,31 @@ class TestDesktopAccessPolicy(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)self.assertEqual(response.data["code"], "desktop_access_unavailable")+ @parameterized.expand(+ [+ ("posthog_ai_task_skips_desktop_rules", "posthog_ai", "startup_plan", "grandfathered", None),+ ("posthog_ai_task_takes_the_2_0_decision", "posthog_ai", "allowed", "beta_off", "task_unavailable"),+ ("code_task_keeps_desktop_rules", "user_created", "startup_plan", "grandfathered", "code_access_required"),+ ]+ )+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_authenticator_scopes", return_value=[])+ def test_task_gate_follows_the_task_origin(+ self, _name: str, origin_product: str, desktop: str, posthog_ai: str, expected_code: str | None, _mock_scopes+ ) -> None:+ with (+ patch(+ "products.tasks.backend.logic.services.code_usage_gate.get_desktop_access_decision",+ return_value=DesktopAccessDecision(desktop),+ ),+ patch(+ "products.tasks.backend.logic.services.code_usage_gate.get_posthog_ai_access_decision",+ return_value=PostHogAIAccessDecision(posthog_ai),+ ),+ ):+ response = code_access_required_response(MagicMock(), self.organization, origin_product=origin_product)++ self.assertEqual(response.data["code"] if response is not None else None, expected_code)+@parameterized.expand([("override_none", None, False, None, False),diff --git a/products/tasks/backend/tests/test_posthog_ai_access.py b/products/tasks/backend/tests/test_posthog_ai_access.pyindex bab8a650ceb2..ec94b9d62433 100644--- a/products/tasks/backend/tests/test_posthog_ai_access.py+++ b/products/tasks/backend/tests/test_posthog_ai_access.py@@ -29,64 +29,21 @@ class TestPostHogAIAccessDecision(SimpleTestCase):@parameterized.expand([(- "sandbox_flag_beats_every_deny",- {"phai-sandbox-mode"},- False,- RULES,- "Startup",- True,- 0,- "2026-09-01",- PostHogAIAccessDecision.GRANDFATHERED,- ),- (- "tasks_flag_beats_every_deny",- {"tasks"},- True,- RULES,+ "grandfathered_variant_beats_every_deny",+ "grandfathered",None,+ "Startup",True,0,"2026-09-01",PostHogAIAccessDecision.GRANDFATHERED,),- (- "beta_off_denies_outside_override",- set(),- False,- RULES,- None,- False,- 9,- "2025-01-01",- PostHogAIAccessDecision.BETA_OFF,- ),- (- "startup_program",- set(),- True,- RULES,- "YC",- False,- 9,- "2025-01-01",- PostHogAIAccessDecision.STARTUP_PROGRAM,- ),- (- "prepaid_credits",- set(),- True,- RULES,- None,- True,- 9,- "2025-01-01",- PostHogAIAccessDecision.PREPAID_CREDITS,- ),+ ("flag_off_denies", None, RULES, None, False, 9, "2025-01-01", PostHogAIAccessDecision.BETA_OFF),+ ("startup_program", "beta", RULES, "YC", False, 9, "2025-01-01", PostHogAIAccessDecision.STARTUP_PROGRAM),+ ("prepaid_credits", "beta", RULES, None, True, 9, "2025-01-01", PostHogAIAccessDecision.PREPAID_CREDITS),("created_after_cutoff",- set(),- True,+ "beta",RULES,None,False,@@ -94,12 +51,11 @@ class TestPostHogAIAccessDecision(SimpleTestCase):"2026-06-01",PostHogAIAccessDecision.CREATED_AFTER_CUTOFF,),- ("low_trust", set(), True, RULES, None, False, 4, "2025-01-01", PostHogAIAccessDecision.LOW_TRUST),- ("passes_every_rule", set(), True, RULES, None, False, 5, "2025-01-01", PostHogAIAccessDecision.ALLOWED),+ ("low_trust", "beta", RULES, None, False, 4, "2025-01-01", PostHogAIAccessDecision.LOW_TRUST),+ ("passes_every_rule", "beta", RULES, None, False, 5, "2025-01-01", PostHogAIAccessDecision.ALLOWED),("beta_without_rules_fails_closed",- set(),- True,+ "beta",None,None,False,@@ -109,8 +65,7 @@ class TestPostHogAIAccessDecision(SimpleTestCase):),("rules_as_json_string",- set(),- True,+ "beta",json.dumps(RULES),None,False,@@ -120,8 +75,7 @@ class TestPostHogAIAccessDecision(SimpleTestCase):),("billing_unavailable_fails_closed",- set(),- True,+ "beta",RULES,None,False,@@ -135,8 +89,7 @@ class TestPostHogAIAccessDecision(SimpleTestCase):def test_decision(self,_name: str,- grandfathered_flags: set[str],- beta_enabled: bool,+ variant: str | None,rules: dict[str, Any] | str | None,startup_program_label: StartupProgramLabel | None,has_prepaid_credits: bool,@@ -145,6 +98,7 @@ class TestPostHogAIAccessDecision(SimpleTestCase):expected: PostHogAIAccessDecision,billing_unavailable: bool = False,) -> None:+ cache.clear()organization = Organization(name="Fixture org",created_at=datetime.fromisoformat(org_created).replace(tzinfo=UTC),@@ -152,14 +106,12 @@ class TestPostHogAIAccessDecision(SimpleTestCase):)user = User(email="[email protected]", distinct_id="fixture-distinct-id")prepaid = PrepaidCreditState.ACTIVE if has_prepaid_credits else PrepaidCreditState.NONE- beta = FeatureFlagResult(key="phai-2-beta", enabled=beta_enabled, variant=None, payload=rules, reason=None)+ access = FeatureFlagResult(+ key="phai-2-beta", enabled=variant is not None, variant=variant, payload=rules, reason=None+ )with (- patch(- "products.tasks.backend.access.get_feature_flag_or_none",- side_effect=lambda key, *_args, **_kwargs: key in grandfathered_flags,- ),- patch("products.tasks.backend.access.posthoganalytics.get_feature_flag_result", return_value=beta),+ patch("products.tasks.backend.access.posthoganalytics.get_feature_flag_result", return_value=access),patch("products.tasks.backend.access._get_funding_status",return_value=OrganizationFundingStatus(@@ -174,10 +126,9 @@ class TestPostHogAIAccessDecision(SimpleTestCase):@parameterized.expand([- ("resolved_decision_is_reused", False, RULES, True, 30, None, True, PostHogAIAccessDecision.ALLOWED, 1),+ ("resolved_decision_is_reused", RULES, True, 30, None, True, PostHogAIAccessDecision.ALLOWED, 1),("resolved_decision_expires",- False,RULES,True,24 * 60 + 1,@@ -188,7 +139,6 @@ class TestPostHogAIAccessDecision(SimpleTestCase):),("deciding_flag_edit_busts_it",- False,RULES,True,30,@@ -199,7 +149,6 @@ class TestPostHogAIAccessDecision(SimpleTestCase):),("other_flag_edit_keeps_it",- False,RULES,True,30,@@ -210,7 +159,6 @@ class TestPostHogAIAccessDecision(SimpleTestCase):),("unloaded_definitions_reused_briefly",- False,RULES,True,0,@@ -221,7 +169,6 @@ class TestPostHogAIAccessDecision(SimpleTestCase):),("unloaded_definitions_expire_fast",- False,RULES,True,2,@@ -232,7 +179,6 @@ class TestPostHogAIAccessDecision(SimpleTestCase):),("beta_without_rules_is_not_cached",- False,None,True,30,@@ -241,20 +187,8 @@ class TestPostHogAIAccessDecision(SimpleTestCase):PostHogAIAccessDecision.UNRESOLVED,2,),- (- "failed_override_lookup_not_cached",- None,- RULES,- True,- 30,- None,- True,- PostHogAIAccessDecision.UNRESOLVED,- 2,- ),("failed_beta_lookup_not_cached",- False,RULES,False,30,@@ -268,7 +202,6 @@ class TestPostHogAIAccessDecision(SimpleTestCase):def test_cached_decision(self,_name: str,- override_value: bool | None,rules: dict[str, Any] | None,beta_resolves: bool,minutes_between_loads: int,@@ -283,7 +216,7 @@ class TestPostHogAIAccessDecision(SimpleTestCase):)user = User(pk=1, email="[email protected]", distinct_id="fixture-distinct-id")beta = (- FeatureFlagResult(key="phai-2-beta", enabled=True, variant=None, payload=rules, reason=None)+ FeatureFlagResult(key="phai-2-beta", enabled=True, variant="beta", payload=rules, reason=None)if beta_resolveselse None)@@ -293,7 +226,6 @@ class TestPostHogAIAccessDecision(SimpleTestCase):]with (- patch("products.tasks.backend.access.get_feature_flag_or_none", return_value=override_value),patch("products.tasks.backend.access.posthoganalytics.get_feature_flag_result", return_value=beta),patch("products.tasks.backend.access.posthoganalytics.feature_flag_definitions",@@ -319,3 +251,31 @@ class TestPostHogAIAccessDecision(SimpleTestCase):self.assertEqual((first, second), (expected, expected))self.assertEqual(mock_decision.call_count, expected_evaluations)++ def test_server_refusal_refreshes_the_page_render_decision(self) -> None:+ cache.clear()+ organization = Organization(+ name="Fixture org", created_at=datetime(2025, 1, 1, tzinfo=UTC), customer_trust_scores={"events": 9}+ )+ user = User(pk=1, email="[email protected]", distinct_id="fixture-distinct-id")+ access = FeatureFlagResult(key="phai-2-beta", enabled=True, variant="beta", payload=RULES, reason=None)++ with (+ patch("products.tasks.backend.access.posthoganalytics.get_feature_flag_result", return_value=access),+ patch("products.tasks.backend.access.posthoganalytics.feature_flag_definitions", return_value=[]),+ patch(+ "products.tasks.backend.access._get_funding_status",+ return_value=OrganizationFundingStatus(+ startup_program_label=None, prepaid_credit_state=PrepaidCreditState.NONE+ ),+ ),+ ):+ page_before = get_cached_posthog_ai_access_decision(user, organization)+ organization.customer_trust_scores = {"events": 1}+ refused = get_posthog_ai_access_decision(user, organization)+ page_after = get_cached_posthog_ai_access_decision(user, organization)++ self.assertEqual(+ (page_before, refused, page_after),+ (PostHogAIAccessDecision.ALLOWED, PostHogAIAccessDecision.LOW_TRUST, PostHogAIAccessDecision.LOW_TRUST),+ )