Skip to content

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

feat(posthog-ai): gate posthog ai 2.0 behind a server-side access decision (#125122)

Peter Kirkham9ebe83d34fa3
diff --git a/ee/api/conversation.py b/ee/api/conversation.py
index 2cc7fd60c2a5..3fe60b8f2228 100644
--- a/ee/api/conversation.py
+++ b/ee/api/conversation.py
@@ -56,6 +56,7 @@ from products.posthog_ai.backend.context_wrapper import ALLOWED_TYPES as ALLOWED
from products.posthog_ai.backend.message_routing import SandboxSession
from products.posthog_ai.backend.models.assistant import Conversation
from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.access import get_posthog_ai_access_decision
from products.tasks.backend.facade.contracts import TaskDetailDTO
from products.tasks.backend.facade.run_config import INITIAL_PERMISSION_MODE_CHOICES
@@ -66,7 +67,6 @@ from ee.hogai.core.executor import AgentExecutor
from ee.hogai.queue import ConversationQueueMessage, ConversationQueueStore, QueueFullError, build_queue_message
from ee.hogai.stream.redis_stream import get_conversation_stream_key
from ee.hogai.utils.aio import async_to_sync
-from ee.hogai.utils.feature_flags import has_sandbox_mode_feature_flag
from ee.hogai.utils.sse import AssistantSSESerializer
from ee.hogai.utils.types import PartialAssistantState
@@ -735,6 +735,9 @@ class ConversationViewSet(
raise QuotaLimitExceeded(
"Your organization reached its AI credit usage limit. Increase the limits in Billing settings, or ask an org admin to do so."
)
+ # Checked before the lookup, so a denied caller cannot continue an existing sandbox conversation either.
+ if not get_posthog_ai_access_decision(cast(User, request.user), self.team.organization).allowed:
+ raise exceptions.ValidationError("This conversation is not on the sandbox runtime.")
serializer = SandboxOpenSerializer(data=request.data, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
@@ -761,8 +764,8 @@ class ConversationViewSet(
`open` is create-or-resume: a brand-new conversation (first warm or first message) has no row
yet, so a plain `get_object()` would 404. A brand-new row is only born on the sandbox runtime,
- and only for a sandbox-eligible caller — otherwise we'd persist an orphaned LangGraph row that
- `open` immediately rejects. Returns whether the row was created this request so the caller can
+ and `open` checks PostHog AI 2.0 access first, so a caller outside it can't spam orphaned rows by
+ POSTing random ids. Returns whether the row was created this request so the caller can
drop it again if nothing ends up being provisioned.
`bind_task` (already validated for team + visibility by `SandboxOpenSerializer`) binds the new
@@ -775,10 +778,6 @@ class ConversationViewSet(
# nosemgrep: idor-lookup-without-team, idor-taint-user-input-to-model-get (user+team checked below)
conversation = Conversation.objects.get(id=conversation_id)
except Conversation.DoesNotExist:
- # Gate first-use creation on eligibility so a non-sandbox caller can't spam orphaned rows
- # by POSTing `open` with random ids — `open` would create then reject each one otherwise.
- if not has_sandbox_mode_feature_flag(self.team, user):
- raise exceptions.ValidationError("This conversation is not on the sandbox runtime.")
conversation = Conversation.objects.create(
user=user,
team=self.team,
diff --git a/ee/api/tests/test_conversation.py b/ee/api/tests/test_conversation.py
index 8ab1d715bcbf..8b87c6575a03 100644
--- a/ee/api/tests/test_conversation.py
+++ b/ee/api/tests/test_conversation.py
@@ -38,6 +38,7 @@ from posthog.temporal.ai.research_agent import ResearchAgentWorkflow, ResearchAg
from products.posthog_ai.backend.message_routing import SandboxRouteResult
from products.posthog_ai.backend.models.assistant import Conversation
+from products.tasks.backend.facade.access import PostHogAIAccessDecision
from products.tasks.backend.models import Channel, Task, TaskRun
from ee.api.conversation import ConversationViewSet, MessageSerializer, QueueMessageSerializer
@@ -1315,6 +1316,11 @@ class TestConversationSandboxRoute(APIBaseTest):
)
self.mock_select_repo = patcher.start()
self.addCleanup(patcher.stop)
+ access_patcher = patch(
+ "ee.api.conversation.get_posthog_ai_access_decision", return_value=PostHogAIAccessDecision.GRANDFATHERED
+ )
+ access_patcher.start()
+ self.addCleanup(access_patcher.stop)
def _sandbox_conversation(self) -> Conversation:
return Conversation.objects.create(
@@ -1371,7 +1377,9 @@ class TestConversationSandboxRoute(APIBaseTest):
task_id="t", run_id="r", trace_id=None, run_status="queued", just_created_run=True
)
with (
- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),
+ patch(
+ "ee.api.conversation.get_posthog_ai_access_decision", return_value=PostHogAIAccessDecision.GRANDFATHERED
+ ),
patch("ee.api.conversation.SandboxSession") as m_session,
patch("ee.api.conversation.report_user_action"),
):
@@ -1410,7 +1418,9 @@ class TestConversationSandboxRoute(APIBaseTest):
task_id=str(task.id), run_id="r", trace_id=None, run_status="queued", just_created_run=True
)
with (
- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),
+ patch(
+ "ee.api.conversation.get_posthog_ai_access_decision", return_value=PostHogAIAccessDecision.GRANDFATHERED
+ ),
patch("ee.api.conversation.SandboxSession") as m_session,
patch("ee.api.conversation.report_user_action"),
):
@@ -1443,7 +1453,9 @@ class TestConversationSandboxRoute(APIBaseTest):
conversation_id = str(uuid.uuid4())
with (
- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),
+ patch(
+ "ee.api.conversation.get_posthog_ai_access_decision", return_value=PostHogAIAccessDecision.GRANDFATHERED
+ ),
patch("ee.api.conversation.SandboxSession") as m_session,
):
response = self.client.post(
@@ -1496,7 +1508,9 @@ class TestConversationSandboxRoute(APIBaseTest):
)
conversation_id = str(uuid.uuid4())
with (
- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),
+ patch(
+ "ee.api.conversation.get_posthog_ai_access_decision", return_value=PostHogAIAccessDecision.GRANDFATHERED
+ ),
patch("ee.api.conversation.SandboxSession") as m_session,
):
response = self.client.post(
@@ -1521,7 +1535,9 @@ class TestConversationSandboxRoute(APIBaseTest):
)
conversation_id = str(uuid.uuid4())
with (
- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),
+ patch(
+ "ee.api.conversation.get_posthog_ai_access_decision", return_value=PostHogAIAccessDecision.GRANDFATHERED
+ ),
patch("ee.api.conversation.SandboxSession") as m_session,
):
response = self.client.post(
@@ -1576,7 +1592,9 @@ class TestConversationSandboxRoute(APIBaseTest):
agent_runtime=Conversation.AgentRuntime.SANDBOX,
)
with (
- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),
+ patch(
+ "ee.api.conversation.get_posthog_ai_access_decision", return_value=PostHogAIAccessDecision.GRANDFATHERED
+ ),
patch("ee.api.conversation.SandboxSession") as m_session,
):
response = self.client.post(
@@ -1604,7 +1622,9 @@ class TestConversationSandboxRoute(APIBaseTest):
task_id=str(signal_task.id), run_id="r", trace_id=None, run_status="queued", just_created_run=True
)
with (
- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),
+ patch(
+ "ee.api.conversation.get_posthog_ai_access_decision", return_value=PostHogAIAccessDecision.GRANDFATHERED
+ ),
patch("ee.api.conversation.SandboxSession") as m_session,
patch("ee.api.conversation.report_user_action"),
):
@@ -1767,7 +1787,7 @@ class TestConversationSandboxRoute(APIBaseTest):
# with random ids — first-use creation is gated on eligibility, so no row is persisted.
conversation_id = str(uuid.uuid4())
with (
- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=False),
+ patch("ee.api.conversation.get_posthog_ai_access_decision", return_value=PostHogAIAccessDecision.BETA_OFF),
patch("ee.api.conversation.SandboxSession") as m_session,
):
response = self.client.post(
@@ -1784,7 +1804,9 @@ class TestConversationSandboxRoute(APIBaseTest):
# action returns 204 and removes the row it created — no orphaned conversations accumulate.
conversation_id = str(uuid.uuid4())
with (
- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),
+ patch(
+ "ee.api.conversation.get_posthog_ai_access_decision", return_value=PostHogAIAccessDecision.GRANDFATHERED
+ ),
patch("ee.api.conversation.SandboxSession") as m_session,
):
m_session.return_value.open.return_value = None
@@ -1870,7 +1892,9 @@ class TestConversationSandboxRoute(APIBaseTest):
agent_runtime=Conversation.AgentRuntime.LANGGRAPH,
)
with (
- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),
+ patch(
+ "ee.api.conversation.get_posthog_ai_access_decision", return_value=PostHogAIAccessDecision.GRANDFATHERED
+ ),
patch("ee.api.conversation.SandboxSession") as m_session,
):
response = self.client.post(
@@ -2027,7 +2051,9 @@ class TestConversationCreateRuntime(APIBaseTest):
# Opening a conversation never converts — conversion only fires on a new message.
conversation = self._langgraph_conversation()
with (
- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),
+ patch(
+ "ee.api.conversation.get_posthog_ai_access_decision", return_value=PostHogAIAccessDecision.GRANDFATHERED
+ ),
patch("ee.api.conversation.SandboxSession") as m_routing,
patch("langgraph.graph.state.CompiledStateGraph.aget_state", new_callable=AsyncMock),
):
@@ -2044,7 +2070,9 @@ class TestConversationCreateRuntime(APIBaseTest):
# even for a user on the sandbox flag — and never touches the sandbox router.
conversation_id = str(uuid.uuid4())
with (
- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),
+ patch(
+ "ee.api.conversation.get_posthog_ai_access_decision", return_value=PostHogAIAccessDecision.GRANDFATHERED
+ ),
patch("ee.api.conversation.SandboxSession") as m_routing,
patch("ee.hogai.core.executor.AgentExecutor.astream", return_value=_async_generator()),
patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._mock_streaming_response),
@@ -2092,7 +2120,7 @@ class TestConversationCreateRuntime(APIBaseTest):
# takes the streaming path — never the sandbox router.
conversation = self._langgraph_conversation()
with (
- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=False),
+ patch("ee.api.conversation.get_posthog_ai_access_decision", return_value=PostHogAIAccessDecision.BETA_OFF),
patch("ee.api.conversation.SandboxSession") as m_routing,
patch("ee.hogai.core.executor.AgentExecutor.astream", return_value=_async_generator()),
patch("posthog.api.streaming.StreamingHttpResponse", side_effect=self._mock_streaming_response),
@@ -2109,7 +2137,9 @@ class TestConversationCreateRuntime(APIBaseTest):
# message hits the existing "cannot resume streaming" conflict instead.
conversation = self._langgraph_conversation(status=Conversation.Status.IN_PROGRESS)
with (
- patch("ee.api.conversation.has_sandbox_mode_feature_flag", return_value=True),
+ patch(
+ "ee.api.conversation.get_posthog_ai_access_decision", return_value=PostHogAIAccessDecision.GRANDFATHERED
+ ),
patch("ee.api.conversation.SandboxSession") as m_routing,
):
response = self._send(conversation)
diff --git a/ee/hogai/sandbox/executor.py b/ee/hogai/sandbox/executor.py
index eb4683928bad..609625fb9893 100644
--- a/ee/hogai/sandbox/executor.py
+++ b/ee/hogai/sandbox/executor.py
@@ -23,6 +23,7 @@ from posthog.temporal.common.client import sync_connect
from products.posthog_ai.backend.models.assistant import Conversation
from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.access import get_posthog_ai_access_decision
from products.tasks.backend.facade.streams import (
TASK_RUN_STREAM_WATCHED_REFRESH_INTERVAL_SECONDS,
TaskRunRedisStream,
@@ -43,7 +44,6 @@ from ee.hogai.sandbox.types import (
is_turn_complete,
)
from ee.hogai.utils.aio import async_to_sync
-from ee.hogai.utils.feature_flags import has_sandbox_mode_feature_flag
logger = structlog.get_logger(__name__)
@@ -60,7 +60,7 @@ def handle_sandbox_message(
is_new_conversation: bool,
) -> HttpResponseBase:
"""Handle a sandbox-mode message: create/resume a task run and stream events back."""
- if not settings.DEBUG and not has_sandbox_mode_feature_flag(team, user):
+ if not settings.DEBUG and not get_posthog_ai_access_decision(user, team.organization).allowed:
raise exceptions.PermissionDenied("Sandbox mode is not enabled for this user.")
if is_new_conversation:
diff --git a/frontend/src/layout/ai/aiShellLogic.test.ts b/frontend/src/layout/ai/aiShellLogic.test.ts
index f4c66d8da557..6e0fb5a37754 100644
--- a/frontend/src/layout/ai/aiShellLogic.test.ts
+++ b/frontend/src/layout/ai/aiShellLogic.test.ts
@@ -5,6 +5,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { initKeaTests } from '~/test/init'
+import { AppContext } from '~/types'
import { aiShellLogic } from './aiShellLogic'
@@ -46,23 +47,32 @@ describe('aiShellLogic', () => {
// The flag is the only thing that may expose the new posthog_ai surface — without the gate a stored
// preference (or a missing default) would leak it to every user. Lock in: flag off collapses to legacy
- // regardless of the stored mode; flag on passes the stored mode through.
+ // regardless of the stored mode; flag on passes the stored mode through. When the server sends its
+ // access decision, that decision replaces the flag: a denied user gets classic PostHog AI.
describe('effectivePhaiView selector', () => {
it.each([
- { flagOn: false, mode: 'new', expected: 'legacy' },
- { flagOn: false, mode: 'legacy', expected: 'legacy' },
- { flagOn: true, mode: 'new', expected: 'new' },
- { flagOn: true, mode: 'legacy', expected: 'legacy' },
+ { flagOn: false, gate: undefined, mode: 'new', expected: 'legacy' },
+ { flagOn: false, gate: undefined, mode: 'legacy', expected: 'legacy' },
+ { flagOn: true, gate: undefined, mode: 'new', expected: 'new' },
+ { flagOn: true, gate: undefined, mode: 'legacy', expected: 'legacy' },
+ { flagOn: true, gate: false, mode: 'new', expected: 'legacy' },
+ { flagOn: false, gate: true, mode: 'new', expected: 'new' },
] as const)(
- 'is $expected when sandbox flag is $flagOn and stored mode is $mode',
- async ({ flagOn, mode, expected }) => {
- featureFlagLogic.actions.setFeatureFlags(
- flagOn ? [FEATURE_FLAGS.PHAI_SANDBOX_MODE] : [],
- flagOn ? { [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true } : {}
- )
- logic.actions.setPhaiViewMode(mode)
+ 'is $expected when sandbox flag is $flagOn, access gate is $gate and stored mode is $mode',
+ async ({ flagOn, gate, mode, expected }) => {
+ const originalAppContext = window.POSTHOG_APP_CONTEXT
+ window.POSTHOG_APP_CONTEXT = { ...originalAppContext, posthog_ai_access: gate } as AppContext
+ try {
+ featureFlagLogic.actions.setFeatureFlags(
+ flagOn ? [FEATURE_FLAGS.PHAI_SANDBOX_MODE] : [],
+ flagOn ? { [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true } : {}
+ )
+ logic.actions.setPhaiViewMode(mode)
- await expectLogic(logic).toMatchValues({ effectivePhaiView: expected })
+ await expectLogic(logic).toMatchValues({ effectivePhaiView: expected })
+ } finally {
+ window.POSTHOG_APP_CONTEXT = originalAppContext
+ }
}
)
})
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index d66c3ebaa691..b1be175645ea 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -453,7 +453,7 @@ export const FEATURE_FLAGS = {
PAYMENT_ENTRY_CONTACT_SUPPORT: 'payment-entry-contact-support', // owner: #team-billing, see `PaymentEntryModal.tsx`
PHAI_PLAN_MODE: 'phai-plan-mode', // owner: #team-posthog-ai
PHAI_QUILL: 'phai-quill', // owner: #team-posthog-ai, renders the PostHog AI chat thread in quill like PostHog Desktop; on with today-rail-nav too
- PHAI_SANDBOX_MODE: 'phai-sandbox-mode', // owner: #team-posthog-ai, PostHog AI 2.0: the sandbox runtime and the task composer; without it the today-rail-nav chats use the legacy chat
+ PHAI_SANDBOX_MODE: 'phai-sandbox-mode', // owner: #team-posthog-ai, PostHog AI 2.0: the sandbox runtime and the task composer; without it the today-rail-nav chats use the legacy chat. The app reads the server's access gate in its place (featureFlagLogic)
PHAI_SCENE_AUTO_OPEN: 'phai-scene-auto-open', // owner: #team-posthog-ai
PHAI_TASKS: 'phai-tasks', // owner: #team-array
PI_ACP: 'pi-acp', // owner: #team-agent-infrastructure, Pi runs write ACP and show on the web run surface
diff --git a/frontend/src/lib/logic/featureFlagLogic.ts b/frontend/src/lib/logic/featureFlagLogic.ts
index bc9fdfec4335..c77d9d0a60a0 100644
--- a/frontend/src/lib/logic/featureFlagLogic.ts
+++ b/frontend/src/lib/logic/featureFlagLogic.ts
@@ -1,7 +1,7 @@
import { MakeLogicType, actions, afterMount, kea, path, reducers } from 'kea'
import posthog from 'posthog-js'
-import { FeatureFlagKey } from 'lib/constants'
+import { FEATURE_FLAGS, FeatureFlagKey } from 'lib/constants'
import { getAppContext } from 'lib/utils/getAppContext'
import { AppContext, PreflightStatus } from '~/types'
@@ -57,6 +57,11 @@ function spyOnFeatureFlags(featureFlags: FeatureFlagsSet): FeatureFlagsSet {
areClientFeatureFlagsHonored(appContext?.preflight ?? null) || process.env.NODE_ENV === 'test'
? { ...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
+ if (posthogAiAccess !== undefined) {
+ availableFlags[FEATURE_FLAGS.PHAI_SANDBOX_MODE] = posthogAiAccess
+ }
const serialized = JSON.stringify(availableFlags)
if (serialized === cachedFlagsSerialized && cachedFlagsProxy) {
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 040a8bdd7bc3..ed6318e6c9ca 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5294,6 +5294,8 @@ export interface AppContext {
* record to pin specific multivariate variants (e.g. an experiment arm) for a story.
*/
persisted_feature_flags?: string[] | Record<string, string | boolean>
+ /** Whether the server's access gate gives this user PostHog AI 2.0. Absent when no user is signed in. */
+ posthog_ai_access?: boolean
anonymous: boolean
frontend_apps?: Record<number, FrontendAppConfig>
effective_resource_access_control: Record<AccessControlResourceType, AccessControlLevel>
diff --git a/posthog/utils.py b/posthog/utils.py
index d6e48b01198e..dbf551fd070e 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -899,6 +899,7 @@ def add_user_app_context(request: HttpRequest, posthog_app_context: dict[str, An
from posthog.user_permissions import UserPermissions
from products.access_control.backend.facade.user_access_control import ACCESS_CONTROL_RESOURCES, UserAccessControl
+ from products.tasks.backend.facade.access import get_cached_posthog_ai_access_decision
user = cast("User", request.user)
@@ -964,6 +965,14 @@ def add_user_app_context(request: HttpRequest, posthog_app_context: dict[str, An
posthog_app_context["has_screen"] = event_info["has_screen"]
posthog_app_context["has_person_email"] = get_has_person_email(user.team)
+ with tracer.start_as_current_span("template.posthog_ai_access"):
+ try:
+ posthog_ai_access = get_cached_posthog_ai_access_decision(user, user.team.organization).allowed
+ except Exception as error:
+ capture_exception(error)
+ posthog_ai_access = False
+ posthog_app_context["posthog_ai_access"] = posthog_ai_access
+
with tracer.start_as_current_span("template.user_home_settings"):
home_settings = UserHomeSettings.objects.filter(team=user.team, user=user).first()
posthog_app_context["homepage"] = (home_settings.homepage or None) if home_settings else None
diff --git a/products/posthog_ai/backend/receivers.py b/products/posthog_ai/backend/receivers.py
index 0a55516d22d7..af6fbbf3f0b1 100644
--- a/products/posthog_ai/backend/receivers.py
+++ b/products/posthog_ai/backend/receivers.py
@@ -48,6 +48,13 @@ def _feature_flags() -> Any:
return feature_flags
+def _has_posthog_ai_access(team: Team, user: User) -> bool:
+ # Deferred for the same reason as the flag helpers: the gate pulls in the tasks API stack.
+ from products.tasks.backend.facade.access import get_posthog_ai_access_decision # noqa: PLC0415
+
+ return get_posthog_ai_access_decision(user, team.organization).allowed
+
+
def connect() -> None:
register_task_read_exclusion(copied_chats_hidden_without_sandbox_mode, name="posthog_ai_copied_chats")
register_task_run_start_guard(catch_up_conversation_copy_before_run, name="posthog_ai_conversation_copy")
@@ -78,7 +85,7 @@ def copied_chats_hidden_without_sandbox_mode(team_id: int, user_id: int | None)
return ()
team = Team.objects.filter(id=team_id).only("id", "organization_id").first()
user = User.objects.filter(id=user_id).only("id", "distinct_id").first()
- if team is None or user is None or flags.has_sandbox_mode_feature_flag(team, user):
+ if team is None or user is None or _has_posthog_ai_access(team, user):
return ()
return copied_task_ids
@@ -98,7 +105,7 @@ def catch_up_conversation_copy_before_run(task_id: str, team_id: int, user_id: i
)
if conversation is None:
return None
- if not flags.has_sandbox_mode_feature_flag(conversation.team, conversation.user):
+ if not _has_posthog_ai_access(conversation.team, conversation.user):
return SANDBOX_MODE_REQUIRED_MESSAGE
if not flags.has_conversation_task_mirror_feature_flag(conversation.team, conversation.user):
# The kill switch stops copying altogether; a stale copy is then expected, not a reason to refuse.
@@ -130,7 +137,7 @@ def mark_conversation_sandbox_on_first_run(sender: type, instance: Any, created:
task_id=instance.task_id, agent_runtime=Conversation.AgentRuntime.LANGGRAPH
)
for conversation in conversations:
- if not flags.has_sandbox_mode_feature_flag(conversation.team, conversation.user):
+ if not _has_posthog_ai_access(conversation.team, conversation.user):
# Without the flag the legacy screen cannot send to the sandbox path, so the chat stays put.
continue
Conversation.objects.filter(id=conversation.id, agent_runtime=Conversation.AgentRuntime.LANGGRAPH).update(
diff --git a/products/posthog_ai/backend/tests/test_message_routing.py b/products/posthog_ai/backend/tests/test_message_routing.py
index 4d54f2087113..da84cf83ce28 100644
--- a/products/posthog_ai/backend/tests/test_message_routing.py
+++ b/products/posthog_ai/backend/tests/test_message_routing.py
@@ -23,6 +23,7 @@ from products.tasks.backend.facade import (
api as tasks_facade,
warm as warm_facade,
)
+from products.tasks.backend.facade.access import PostHogAIAccessDecision
from products.tasks.backend.models import Task, TaskRun
ROUTING = "products.posthog_ai.backend.message_routing"
@@ -478,6 +479,12 @@ class TestSandboxWarmViaOpen(APIBaseTest):
team=self.team,
agent_runtime=Conversation.AgentRuntime.SANDBOX,
)
+ access_patcher = patch(
+ "products.tasks.backend.logic.services.warm.get_posthog_ai_access_decision",
+ return_value=PostHogAIAccessDecision.GRANDFATHERED,
+ )
+ access_patcher.start()
+ self.addCleanup(access_patcher.stop)
def _service(self) -> SandboxSession:
return SandboxSession(self.conversation, self.user)
diff --git a/products/posthog_ai/backend/tests/test_receivers.py b/products/posthog_ai/backend/tests/test_receivers.py
index e3c8cff4f561..cf2fcde5e774 100644
--- a/products/posthog_ai/backend/tests/test_receivers.py
+++ b/products/posthog_ai/backend/tests/test_receivers.py
@@ -14,13 +14,14 @@ from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.models import Task, TaskRun
FLAGS = "ee.hogai.utils.feature_flags"
+RECEIVERS = "products.posthog_ai.backend.receivers"
class ConversationTaskTestMixin(APIBaseTest):
def setUp(self) -> None:
super().setUp()
- for flag in ("has_sandbox_mode_feature_flag", "has_conversation_task_mirror_feature_flag"):
- p = patch(f"{FLAGS}.{flag}", return_value=True)
+ for target in (f"{RECEIVERS}._has_posthog_ai_access", f"{FLAGS}.has_conversation_task_mirror_feature_flag"):
+ p = patch(target, return_value=True)
p.start()
self.addCleanup(p.stop)
@@ -56,7 +57,7 @@ class TestConversationFollowsTaskRun(ConversationTaskTestMixin):
def test_an_owner_without_sandbox_mode_keeps_the_langgraph_runtime(self) -> None:
conversation, task = self._linked_conversation()
- with patch(f"{FLAGS}.has_sandbox_mode_feature_flag", return_value=False):
+ with patch(f"{RECEIVERS}._has_posthog_ai_access", return_value=False):
TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED, state={})
conversation.refresh_from_db()
assert conversation.agent_runtime == Conversation.AgentRuntime.LANGGRAPH
@@ -90,7 +91,7 @@ class TestCatchUpBeforeRun(ConversationTaskTestMixin):
def test_refuses_the_run_for_an_owner_without_sandbox_mode(self) -> None:
_, task = self._linked_conversation()
with (
- patch(f"{FLAGS}.has_sandbox_mode_feature_flag", return_value=False),
+ patch(f"{RECEIVERS}._has_posthog_ai_access", return_value=False),
patch(f"products.posthog_ai.backend.conversation_mirror.amirror_conversation") as copy,
):
assert self._guard(task) == SANDBOX_MODE_REQUIRED_MESSAGE
@@ -132,7 +133,7 @@ class TestCopiedChatsHiddenWithoutSandboxMode(ConversationTaskTestMixin):
def test_a_user_without_sandbox_mode_sees_no_copied_chat(self) -> None:
copied, continued, plain = self._tasks()
- with patch(f"{FLAGS}.has_sandbox_mode_feature_flag", return_value=False):
+ with patch(f"{RECEIVERS}._has_posthog_ai_access", return_value=False):
assert self._visible_ids() == {continued.id, plain.id}
def test_a_user_with_sandbox_mode_sees_the_copies(self) -> None:
diff --git a/products/posthog_ai/frontend/e2e/run-surface.spec.ts b/products/posthog_ai/frontend/e2e/run-surface.spec.ts
index 92f8259a778d..8230bb58ca7b 100644
--- a/products/posthog_ai/frontend/e2e/run-surface.spec.ts
+++ b/products/posthog_ai/frontend/e2e/run-surface.spec.ts
@@ -180,9 +180,10 @@ async function openRunDeepLink(page: Page, teamId: string): Promise<void> {
})
}
-async function prepareRunComposer(page: Page): Promise<void> {
- await page.addInitScript(() => {
+async function prepareRunComposer(page: Page, { posthogAiAccess = false } = {}): Promise<void> {
+ await page.addInitScript((serverAllowsPosthogAi: boolean) => {
let appContext: {
+ posthog_ai_access?: boolean
current_user?: {
organization?: { is_ai_data_processing_approved?: boolean }
has_seen_product_intro_for?: Record<string, boolean>
@@ -192,6 +193,10 @@ async function prepareRunComposer(page: Page): Promise<void> {
configurable: true,
get: () => appContext,
set: (value: typeof appContext) => {
+ // The app shows PostHog AI 2.0 only when the server's access gate allows it.
+ if (serverAllowsPosthogAi) {
+ value.posthog_ai_access = true
+ }
if (value.current_user?.organization) {
value.current_user.organization.is_ai_data_processing_approved = true
}
@@ -204,7 +209,7 @@ async function prepareRunComposer(page: Page): Promise<void> {
appContext = value
},
})
- })
+ }, posthogAiAccess)
}
test.describe('Task run surface', () => {
@@ -368,7 +373,7 @@ test.describe('Task run surface', () => {
const agentReady = new Promise<void>((resolve) => {
startAgent = resolve
})
- await prepareRunComposer(page)
+ await prepareRunComposer(page, { posthogAiAccess: true })
await mockFeatureFlags(page, {
[TASKS_FLAG]: true,
'phai-sandbox-mode': true,
diff --git a/products/posthog_ai/frontend/logics/tasksLogic.ts b/products/posthog_ai/frontend/logics/tasksLogic.ts
index bb44334e1499..fb055ed6167c 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, TaskUpsertProp
import { taskEventsLogic } from './taskEventsLogic'
import { taskHistoryLogic } from './taskHistoryLogic'
-function hasTasksFlag(featureFlags: FeatureFlagsSet): boolean {
+export 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/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
index c773faa33599..8fd35db271a3 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
@@ -108,6 +108,8 @@ 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 })
toolEvents = toolStreamEventsLogic()
toolEvents.mount()
toolEvents.actions.registerToolListener('editor', {
@@ -193,6 +195,20 @@ describe('taskTrackerSceneLogic', () => {
expect(runBody).not.toHaveProperty('pending_user_artifact_ids')
})
+ // An Inbox task link must still open its transcript without Tasks access.
+ 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([], {})
+ logic.mount()
+ router.actions.push(start)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(router.values.location.pathname).toBe(`/project/997${expected}`)
+ })
+
it.each([
['/ai', '/ai', { task: 'new-task' }],
['/tasks/new', '/tasks/new-task', {}],
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index 47ac4b7730ab..8b8fb2280945 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -61,7 +61,7 @@ import { runCancellationLogic } from '../../logics/runCancellationLogic'
import { runInteractionLogic, type RunContinuationHandoff } from '../../logics/runInteractionLogic'
import { taskDefaultsLogic } from '../../logics/taskDefaultsLogic'
import { taskRunDefaultsLogic } from '../../logics/taskRunDefaultsLogic'
-import { tasksLogic } from '../../logics/tasksLogic'
+import { hasTasksFlag, tasksLogic } from '../../logics/tasksLogic'
import { taskWarmLogic } from '../../logics/taskWarmLogic'
import type { WarmLease, WarmSubmission } from '../../logics/taskWarmLogic'
import { toolStreamEventsLogic } from '../../logics/toolStreamEventsLogic'
@@ -1419,10 +1419,20 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
actions.clearActiveCreation()
}
}
+ // Only the list and composer fall back to classic PostHog AI. Inbox task links need neither flag.
+ const redirectedWithoutAccess = (taskId?: string): boolean => {
+ if (props.panelId || hasTasksFlag(values.featureFlags) || (taskId && taskId !== 'new')) {
+ return false
+ }
+ router.actions.replace(urls.ai())
+ return true
+ }
return {
+ '/tasks': () => (redirectedWithoutAccess() ? undefined : clearIfLeftCreatedTask()),
// An embedded instance never navigates the main app on its own creation (see `submitNewTask`), so
// main-app URL changes are unrelated to its run — never release the side panel's active creation.
- '/tasks/:taskId': ({ taskId }) => (props.panelId ? undefined : clearIfLeftCreatedTask(taskId)),
+ '/tasks/:taskId': ({ taskId }) =>
+ props.panelId || redirectedWithoutAccess(taskId) ? undefined : clearIfLeftCreatedTask(taskId),
[urls.ai()]: (_, search) =>
props.panelId
? undefined
diff --git a/products/tasks/backend/access.py b/products/tasks/backend/access.py
index 48d184f2a424..0bbf05600f41 100644
--- a/products/tasks/backend/access.py
+++ b/products/tasks/backend/access.py
@@ -1,3 +1,4 @@
+import json
from datetime import UTC, datetime
from enum import StrEnum
from typing import TYPE_CHECKING
@@ -6,12 +7,16 @@ from django.conf import settings
from django.core.cache import cache
import structlog
+import posthoganalytics
+from posthoganalytics.types import FeatureFlagResult
from posthog.cloud_utils import get_cached_instance_license
+from posthog.dataclasses import frozen
from posthog.models.user import User
from posthog.ph_client import feature_enabled_or_false, get_feature_flag_or_none
from products.tasks.backend.facade.contracts import DesktopAccessReason
+from products.tasks.backend.logic.services.desktop_gateway_token import best_customer_trust_score
from products.tasks.backend.metrics import (
DesktopAccessOutcome,
observe_desktop_access_decision,
@@ -93,12 +98,15 @@ 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") -> bool | None:
+def _resolve_flag(
+ flag_key: str, user: User, organization: "Organization", person_properties: dict[str, str] | None = None
+) -> 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,
@@ -184,6 +192,142 @@ def get_desktop_access_decision(
return decision
+class PostHogAIAccessDecision(StrEnum):
+ """Whether a user gets PostHog AI 2.0 (the sandbox runtime). The value is an internal reason code."""
+
+ GRANDFATHERED = "grandfathered"
+ ALLOWED = "allowed"
+ BETA_OFF = "beta_off"
+ STARTUP_PROGRAM = "startup_program"
+ PREPAID_CREDITS = "prepaid_credits"
+ CREATED_AFTER_CUTOFF = "created_after_cutoff"
+ LOW_TRUST = "low_trust"
+ UNRESOLVED = "unresolved"
+
+ @property
+ def allowed(self) -> bool:
+ return self in (PostHogAIAccessDecision.GRANDFATHERED, PostHogAIAccessDecision.ALLOWED)
+
+
+_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"
+_POSTHOG_AI_FUNDING_CACHE_SECONDS = 300
+_POSTHOG_AI_DECISION_CACHE_KEY = "posthog_ai_access_decision:{organization_id}:{user_id}"
+
+
+@frozen
+class PostHogAIBetaRules:
+ created_before: datetime
+ min_trust_score: float
+
+
+def _posthog_ai_beta_rules(payload: object) -> PostHogAIBetaRules | None:
+ """Reads the beta rules from the flag payload, so they change without a deploy."""
+ if isinstance(payload, str):
+ try:
+ payload = json.loads(payload)
+ except ValueError:
+ return None
+ if not isinstance(payload, dict):
+ return None
+ try:
+ cutoff = datetime.fromisoformat(str(payload["cutoff_date"]))
+ min_trust_score = float(payload["min_trust_score"])
+ except (KeyError, TypeError, ValueError):
+ return None
+ return PostHogAIBetaRules(
+ created_before=cutoff if cutoff.tzinfo is not None else cutoff.replace(tzinfo=UTC),
+ min_trust_score=min_trust_score,
+ )
+
+
+def _posthog_ai_person_properties(user: User) -> dict[str, str]:
+ # The targeting flags match on email, so passing it lets the SDK evaluate them locally.
+ return {"email": user.email} if user.email else {}
+
+
+def _resolve_beta(user: User, organization: "Organization") -> FeatureFlagResult | None:
+ organization_id = str(organization.id)
+ try:
+ return posthoganalytics.get_feature_flag_result(
+ POSTHOG_AI_BETA_FLAG,
+ str(user.distinct_id),
+ groups={"organization": organization_id},
+ person_properties=_posthog_ai_person_properties(user),
+ group_properties={"organization": {"id": organization_id}},
+ send_feature_flag_events=False,
+ )
+ except Exception:
+ logger.warning("posthog_ai_beta_flag_failed", exc_info=True)
+ return None
+
+
+def get_posthog_ai_access_decision(user: User, organization: "Organization") -> PostHogAIAccessDecision:
+ """Fails closed: a denied or unresolved caller gets classic PostHog AI instead."""
+ 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
+
+ beta = _resolve_beta(user, organization)
+ if beta is None:
+ return PostHogAIAccessDecision.UNRESOLVED
+ if not beta.enabled:
+ return PostHogAIAccessDecision.BETA_OFF
+ rules = _posthog_ai_beta_rules(beta.payload)
+ if rules is None:
+ logger.warning("posthog_ai_beta_rules_invalid", flag_key=POSTHOG_AI_BETA_FLAG)
+ return PostHogAIAccessDecision.UNRESOLVED
+
+ try:
+ funding = _cached_funding_decision(user, organization, _POSTHOG_AI_FUNDING_CACHE_SECONDS)
+ except DesktopAccessResolutionError:
+ return PostHogAIAccessDecision.UNRESOLVED
+ if funding == DesktopAccessDecision.STARTUP_PLAN:
+ return PostHogAIAccessDecision.STARTUP_PROGRAM
+ if funding == DesktopAccessDecision.PREPAID_CREDITS:
+ return PostHogAIAccessDecision.PREPAID_CREDITS
+ if organization.created_at >= rules.created_before:
+ return PostHogAIAccessDecision.CREATED_AFTER_CUTOFF
+ if best_customer_trust_score(organization) < rules.min_trust_score:
+ return PostHogAIAccessDecision.LOW_TRUST
+ return PostHogAIAccessDecision.ALLOWED
+
+
+def get_cached_posthog_ai_access_decision(
+ user: User, organization: "Organization", *, cache_seconds: int = 60
+) -> 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."""
+ cache_key = _POSTHOG_AI_DECISION_CACHE_KEY.format(organization_id=organization.id, user_id=user.pk)
+ try:
+ cached = cache.get(cache_key)
+ except Exception:
+ logger.warning("posthog_ai_access_decision_cache_read_failed", exc_info=True)
+ cached = None
+ if 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
+
+
def has_loops_access(user: User, team: "Team | None" = None) -> bool:
if not user.distinct_id:
return False
diff --git a/products/tasks/backend/facade/access.py b/products/tasks/backend/facade/access.py
index 8ef13098ed48..af57cc4ae058 100644
--- a/products/tasks/backend/facade/access.py
+++ b/products/tasks/backend/facade/access.py
@@ -5,7 +5,10 @@ from products.signals.backend.facade.metric_access import metric_context_reader
from products.tasks.backend.access import (
DesktopAccessDecision,
DesktopAccessResolutionError,
+ PostHogAIAccessDecision,
+ get_cached_posthog_ai_access_decision,
get_desktop_access_decision,
+ get_posthog_ai_access_decision,
has_loops_access,
)
from products.tasks.backend.facade.contracts import DesktopAccessReason
@@ -61,9 +64,12 @@ __all__ = [
"DesktopAccessDecision",
"DesktopAccessReason",
"DesktopAccessResolutionError",
+ "PostHogAIAccessDecision",
"code_access_required_response",
"compute_quota_limit_response",
"get_desktop_access_decision",
+ "get_cached_posthog_ai_access_decision",
+ "get_posthog_ai_access_decision",
"has_loops_access",
"is_sandbox_run_request",
"may_read_task_run_context",
diff --git a/products/tasks/backend/logic/services/code_usage_gate.py b/products/tasks/backend/logic/services/code_usage_gate.py
index 2cc596c6591a..df7930595f9c 100644
--- a/products/tasks/backend/logic/services/code_usage_gate.py
+++ b/products/tasks/backend/logic/services/code_usage_gate.py
@@ -11,7 +11,11 @@ from posthog.auth import OAuthAccessTokenAuthentication
from posthog.permissions import get_authenticator_scopes
from posthog.temporal.oauth import SANDBOX_OAUTH_APP_CLIENT_IDS
-from products.tasks.backend.access import DesktopAccessResolutionError, get_desktop_access_decision
+from products.tasks.backend.access import (
+ DesktopAccessResolutionError,
+ get_desktop_access_decision,
+ get_posthog_ai_access_decision,
+)
from products.tasks.backend.facade.contracts import DesktopAccessReason
from products.tasks.backend.logic.services.compute_quota import (
COMPUTE_QUOTA_DENIAL_CODE,
@@ -19,6 +23,7 @@ from products.tasks.backend.logic.services.compute_quota import (
organization_deactivated,
)
from products.tasks.backend.metrics import observe_code_usage_gate_check
+from products.tasks.backend.models import Task
from products.tasks.backend.presentation.serializers import TaskRunErrorResponseSerializer
if TYPE_CHECKING:
@@ -125,11 +130,28 @@ def code_access_required_response(
organization: "Organization",
*,
task_id: str | UUID | None = None,
+ origin_product: str | None = None,
+ 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_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."""
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
+ )
+
+def _desktop_access_required_response(
+ request: Request, organization: "Organization", fail_open_on_resolution_error: bool
+) -> Response | None:
try:
decision = get_desktop_access_decision(cast("User", request.user), organization)
except DesktopAccessResolutionError:
@@ -180,6 +202,35 @@ def code_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
+ if get_posthog_ai_access_decision(cast("User", request.user), organization).allowed:
+ return None
+ return Response(
+ TaskRunErrorResponseSerializer(
+ {
+ "type": "permission_denied",
+ "code": "task_unavailable",
+ "error": "This task isn't available to you.",
+ }
+ ).data,
+ status=status.HTTP_403_FORBIDDEN,
+ )
+
+
def usage_limit_response(user, team_id: int) -> Response | None:
"""Return a 429 when the team is over its PostHog Desktop usage limit, else None.
diff --git a/products/tasks/backend/logic/services/desktop_gateway_token.py b/products/tasks/backend/logic/services/desktop_gateway_token.py
index 59909082b109..ea27165db63d 100644
--- a/products/tasks/backend/logic/services/desktop_gateway_token.py
+++ b/products/tasks/backend/logic/services/desktop_gateway_token.py
@@ -197,11 +197,15 @@ def posthog_code_billing_synced(organization: "Organization") -> bool:
_PAID_TRUST_MINIMUM = 7.0
-def posthog_code_trusted(organization: "Organization") -> bool:
- """Whether the org's best trust score shows a paid invoice; a missing or malformed score counts as zero."""
+def best_customer_trust_score(organization: "Organization") -> float:
+ """The org's best trust score across billed resources; a missing or malformed score counts as zero."""
scores = organization.customer_trust_scores or {}
- best = max((float(v) for v in scores.values() if isinstance(v, int | float)), default=0.0)
- return best >= _PAID_TRUST_MINIMUM
+ return max((float(v) for v in scores.values() if isinstance(v, int | float)), default=0.0)
+
+
+def posthog_code_trusted(organization: "Organization") -> bool:
+ """Whether the org's best trust score shows a paid invoice."""
+ return best_customer_trust_score(organization) >= _PAID_TRUST_MINIMUM
def _override_tier(raw: object) -> LimitTier | None:
diff --git a/products/tasks/backend/logic/services/tests/test_warm.py b/products/tasks/backend/logic/services/tests/test_warm.py
index 569352141916..19d57cb1c274 100644
--- a/products/tasks/backend/logic/services/tests/test_warm.py
+++ b/products/tasks/backend/logic/services/tests/test_warm.py
@@ -6,6 +6,7 @@ from rest_framework.exceptions import PermissionDenied, Throttled
from posthog.exceptions import QuotaLimitExceeded
+from products.tasks.backend.access import PostHogAIAccessDecision
from products.tasks.backend.constants import DEFAULT_SANDBOX_WORKING_DIR
from products.tasks.backend.logic.services.warm import SandboxWarmer, WarmSourceChanged
from products.tasks.backend.models import Task, TaskRun
@@ -22,6 +23,15 @@ def test_code_cloud_warm_pool_caps():
class TestSandboxWarmerWarm(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.posthog_ai_access = PostHogAIAccessDecision.GRANDFATHERED
+ access_patcher = patch(
+ f"{WARM}.get_posthog_ai_access_decision", side_effect=lambda *_args, **_kwargs: self.posthog_ai_access
+ )
+ access_patcher.start()
+ self.addCleanup(access_patcher.stop)
+
def _task(self, *, origin=Task.OriginProduct.POSTHOG_AI, created_by=None) -> Task:
return Task.objects.create(
team=self.team,
@@ -151,13 +161,26 @@ class TestSandboxWarmerWarm(APIBaseTest):
assert result.just_created is True
assert task.runs.count() == 1
- def test_over_quota_raises_and_creates_no_run(self):
+ @parameterized.expand(
+ [
+ ("over_quota", PostHogAIAccessDecision.GRANDFATHERED, True, QuotaLimitExceeded),
+ ("posthog_ai_denied", PostHogAIAccessDecision.BETA_OFF, False, PermissionDenied),
+ ]
+ )
+ def test_refused_warm_creates_no_run(
+ self,
+ _name: str,
+ access: PostHogAIAccessDecision,
+ over_quota: bool,
+ expected_error: type[Exception],
+ ):
+ self.posthog_ai_access = access
task = self._task()
with (
patch(f"{WARM}.execute_task_processing_workflow") as m_workflow,
- patch(f"{WARM}.is_team_limited", return_value=True),
+ patch(f"{WARM}.is_team_limited", return_value=over_quota),
):
- with self.assertRaises(QuotaLimitExceeded):
+ with self.assertRaises(expected_error):
SandboxWarmer(task, user=self.user).warm()
assert task.runs.count() == 0
diff --git a/products/tasks/backend/logic/services/warm.py b/products/tasks/backend/logic/services/warm.py
index 2ae3cf89d64f..ae5d152eba11 100644
--- a/products/tasks/backend/logic/services/warm.py
+++ b/products/tasks/backend/logic/services/warm.py
@@ -26,6 +26,7 @@ from posthog.exceptions import QuotaLimitExceeded
from posthog.models.team import Team
from posthog.models.user import User
+from products.tasks.backend.access import get_posthog_ai_access_decision
from products.tasks.backend.logic.services.compute_quota import organization_deactivated
from products.tasks.backend.logic.services.workflow_dispatch import WorkflowDispatchOptions, enqueue_or_start_workflow
from products.tasks.backend.models import Task, TaskRun
@@ -63,6 +64,12 @@ def _ai_credits_checker(team: Team, user: User) -> None:
)
+def _posthog_ai_checker(team: Team, user: User) -> None:
+ if not get_posthog_ai_access_decision(user, team.organization).allowed:
+ raise PermissionDenied("Warming is not enabled for this user.")
+ _ai_credits_checker(team, user)
+
+
class SandboxWarmer:
"""Idempotently warm a sandbox Run for an existing Task, enforcing the product's quota gate and a
state-derived warm-pool cap, then dispatching the processing workflow after commit.
@@ -82,7 +89,7 @@ class SandboxWarmer:
# origin: gated by the ``tasks-prewarm-sandbox`` flag at the endpoint, not an AI-credit budget).
# Fail-closed: an origin absent from this registry cannot warm at all.
ORIGIN_PRODUCT_QUOTA: dict[str, Callable[[Team, User], None] | None] = {
- Task.OriginProduct.POSTHOG_AI: _ai_credits_checker,
+ Task.OriginProduct.POSTHOG_AI: _posthog_ai_checker,
Task.OriginProduct.USER_CREATED: None,
Task.OriginProduct.SIGNAL_REPORT: _ai_credits_checker,
}
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 31f1a35d6c88..457c5d6a6771 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -325,7 +325,6 @@ WARM_SANDBOX_FLAGS_BY_ORIGIN_PRODUCT: dict[str, str] = {
# Origins that warm for every user, with no flag left to evaluate.
WARM_SANDBOX_UNGATED_ORIGIN_PRODUCTS: frozenset[str] = frozenset(
{
- tasks_facade.TaskOriginProduct.POSTHOG_AI,
tasks_facade.TaskOriginProduct.SIGNAL_REPORT,
}
)
@@ -885,7 +884,9 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
and validated_data.get("github_user_integration") is None
)
if not is_code_access_exempt and (
- access_response := code_access_required_response(request, self.organization)
+ access_response := code_access_required_response(
+ request, self.organization, origin_product=origin_product
+ )
):
return access_response
if limit_response := usage_limit_response(request.user, self.team_id):
@@ -1712,6 +1713,8 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""
if origin_product in WARM_SANDBOX_UNGATED_ORIGIN_PRODUCTS:
return True
+ if origin_product == tasks_facade.TaskOriginProduct.POSTHOG_AI:
+ return tasks_access.get_posthog_ai_access_decision(cast(User, self.request.user), self.organization).allowed
flag = WARM_SANDBOX_FLAGS_BY_ORIGIN_PRODUCT.get(origin_product)
if flag is None:
return False
@@ -1777,7 +1780,9 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
code_access_allowed = False
if origin_product == tasks_facade.TaskOriginProduct.SIGNAL_REPORT:
code_access_allowed = code_access_required_response(request, self.organization) is None
- elif access_response := code_access_required_response(request, self.organization):
+ elif access_response := code_access_required_response(
+ request, self.organization, origin_product=origin_product
+ ):
return access_response
user_id = self._user_id()
@@ -3707,7 +3712,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# A side question drives the agent and spends model tokens on the caller's behalf. Unlike
# user_message below, it has no Inbox surface to exempt, so every caller takes both gates.
if method == "side_question":
- if access_response := code_access_required_response(request, self.organization):
+ if access_response := code_access_required_response(request, self.organization, posthog_ai_task_id=task_id):
return access_response
if limit_response := usage_limit_response(request.user, self.team_id):
return limit_response
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 07fa2be0d965..4ab6baddc7ea 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -256,6 +256,14 @@ class BaseTaskAPITest(TestCase):
),
)
self.desktop_access_patcher.start()
+ self._posthog_ai_access = tasks_access.PostHogAIAccessDecision.GRANDFATHERED
+ for module in ("logic.services.code_usage_gate", "logic.services.warm", "facade.access"):
+ posthog_ai_access_patcher = patch(
+ f"products.tasks.backend.{module}.get_posthog_ai_access_decision",
+ side_effect=lambda *_args, **_kwargs: self._posthog_ai_access,
+ )
+ posthog_ai_access_patcher.start()
+ self.addCleanup(posthog_ai_access_patcher.stop)
self.set_tasks_feature_flag(True)
def tearDown(self):
@@ -14570,13 +14578,23 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
Task.Runtime.ACP,
"permission_response",
{"requestId": "perm-1", "optionId": "allow"},
+ False,
status.HTTP_200_OK,
),
+ (
+ "permission_response_posthog_ai_denied",
+ Task.Runtime.ACP,
+ "permission_response",
+ {"requestId": "perm-1", "optionId": "allow"},
+ True,
+ status.HTTP_403_FORBIDDEN,
+ ),
(
"pi_permission_response",
Task.Runtime.PI,
"pi/rpc",
{"command": {"id": "req-1", "type": "permission_response", "optionId": "allow"}},
+ False,
status.HTTP_200_OK,
),
(
@@ -14588,6 +14606,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
"server": "playwright",
"payload": {"jsonrpc": "2.0", "id": 1, "result": {"content": []}},
},
+ False,
status.HTTP_503_SERVICE_UNAVAILABLE,
),
(
@@ -14595,6 +14614,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
Task.Runtime.PI,
"pi/rpc",
{"command": {"id": "req-1", "type": "prompt", "message": "continue"}},
+ False,
status.HTTP_503_SERVICE_UNAVAILABLE,
),
]
@@ -14610,6 +14630,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
runtime: Task.Runtime,
method: str,
params: dict[str, Any],
+ posthog_ai_denied: bool,
expected_status: int,
mock_post: MagicMock,
_mock_access: MagicMock,
@@ -14617,6 +14638,9 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "id": "req-1", "result": {"accepted": True}})
task = self.create_task(runtime=runtime)
+ if posthog_ai_denied:
+ self._posthog_ai_access = tasks_access.PostHogAIAccessDecision.BETA_OFF
+ Task.objects.filter(id=task.id).update(origin_product=Task.OriginProduct.POSTHOG_AI)
run = self._create_run_with_sandbox(task)
response = self.client.post(
@@ -14629,7 +14653,8 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
if expected_status == status.HTTP_200_OK:
mock_post.assert_called_once()
else:
- self.assertEqual(response.json()["code"], "desktop_access_unavailable")
+ expected_code = "task_unavailable" if posthog_ai_denied else "desktop_access_unavailable"
+ self.assertEqual(response.json()["code"], expected_code)
mock_post.assert_not_called()
@parameterized.expand(
@@ -14948,10 +14973,20 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(forwarded["method"], "side_question")
self.assertEqual(forwarded["params"]["question"], "what does it do?")
+ @parameterized.expand(
+ [
+ ("desktop_denied", False, Task.OriginProduct.USER_CREATED, "code_access_required"),
+ ("posthog_ai_denied", True, Task.OriginProduct.POSTHOG_AI, "task_unavailable"),
+ ]
+ )
@patch("products.tasks.backend.presentation.views.api.http_requests.post")
- def test_command_side_question_requires_code_access(self, mock_post):
- self.set_tasks_feature_flag(False)
+ def test_command_side_question_requires_access(
+ self, _name: str, desktop_access: bool, origin_product: str, expected_code: str, mock_post
+ ):
+ self.set_tasks_feature_flag(desktop_access)
+ self._posthog_ai_access = tasks_access.PostHogAIAccessDecision.BETA_OFF
task = self.create_task()
+ Task.objects.filter(id=task.id).update(origin_product=origin_product)
run = self._create_run_with_sandbox(task)
response = self.client.post(
@@ -14961,7 +14996,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
- self.assertEqual(response.json()["code"], "code_access_required")
+ self.assertEqual(response.json()["code"], expected_code)
mock_post.assert_not_called()
@patch("products.tasks.backend.presentation.views.api.http_requests.post")
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index b19369f8736a..38058dacffbd 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -28,6 +28,7 @@ from products.tasks.backend.facade import (
contracts,
warm as warm_facade,
)
+from products.tasks.backend.facade.access import PostHogAIAccessDecision
from products.tasks.backend.facade.profiles import (
Repository,
SourceKind,
@@ -1154,7 +1155,11 @@ class TestFacadeReadsAndMappers(TestCase):
@patch("products.tasks.backend.logic.services.warm.execute_task_processing_workflow")
@patch("products.tasks.backend.logic.services.warm.is_team_limited", return_value=False)
- def test_warm_task_run_returns_contract(self, _mock_quota, mock_workflow):
+ @patch(
+ "products.tasks.backend.logic.services.warm.get_posthog_ai_access_decision",
+ return_value=PostHogAIAccessDecision.GRANDFATHERED,
+ )
+ def test_warm_task_run_returns_contract(self, _mock_access, _mock_quota, mock_workflow):
task = self._make_task(origin_product=Task.OriginProduct.POSTHOG_AI)
with self.captureOnCommitCallbacks(execute=True):
diff --git a/products/tasks/backend/tests/test_posthog_ai_access.py b/products/tasks/backend/tests/test_posthog_ai_access.py
new file mode 100644
index 000000000000..e065f5ea00a0
--- /dev/null
+++ b/products/tasks/backend/tests/test_posthog_ai_access.py
@@ -0,0 +1,219 @@
+import json
+from datetime import UTC, datetime
+from typing import Any
+
+from unittest.mock import patch
+
+from django.core.cache import cache
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from posthoganalytics.types import FeatureFlagResult
+
+from posthog.models import Organization, User
+
+from products.tasks.backend.access import (
+ DesktopAccessResolutionError,
+ PostHogAIAccessDecision,
+ get_cached_posthog_ai_access_decision,
+ get_posthog_ai_access_decision,
+)
+
+from ee.billing.billing_manager import OrganizationFundingStatus, PrepaidCreditState, StartupProgramLabel
+
+RULES = {"cutoff_date": "2026-06-01T00:00:00+00:00", "min_trust_score": 5}
+
+
+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,
+ None,
+ 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,
+ ),
+ (
+ "created_after_cutoff",
+ set(),
+ True,
+ RULES,
+ None,
+ False,
+ 9,
+ "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),
+ (
+ "beta_without_rules_fails_closed",
+ set(),
+ True,
+ None,
+ None,
+ False,
+ 9,
+ "2025-01-01",
+ PostHogAIAccessDecision.UNRESOLVED,
+ ),
+ (
+ "rules_as_json_string",
+ set(),
+ True,
+ json.dumps(RULES),
+ None,
+ False,
+ 5,
+ "2025-01-01",
+ PostHogAIAccessDecision.ALLOWED,
+ ),
+ (
+ "billing_unavailable_fails_closed",
+ set(),
+ True,
+ RULES,
+ None,
+ False,
+ 9,
+ "2025-01-01",
+ PostHogAIAccessDecision.UNRESOLVED,
+ True,
+ ),
+ ]
+ )
+ def test_decision(
+ self,
+ _name: str,
+ grandfathered_flags: set[str],
+ beta_enabled: bool,
+ rules: dict[str, Any] | str | None,
+ startup_program_label: StartupProgramLabel | None,
+ has_prepaid_credits: bool,
+ trust_score: int,
+ org_created: str,
+ expected: PostHogAIAccessDecision,
+ billing_unavailable: bool = False,
+ ) -> None:
+ organization = Organization(
+ name="Fixture org",
+ created_at=datetime.fromisoformat(org_created).replace(tzinfo=UTC),
+ customer_trust_scores={"events": trust_score},
+ )
+ 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)
+
+ 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._get_funding_status",
+ return_value=OrganizationFundingStatus(
+ startup_program_label=startup_program_label, prepaid_credit_state=prepaid
+ ),
+ side_effect=DesktopAccessResolutionError("billing unavailable") if billing_unavailable else None,
+ ),
+ ):
+ decision = get_posthog_ai_access_decision(user, organization)
+
+ self.assertEqual(decision, expected)
+
+ @parameterized.expand(
+ [
+ ("resolved_decision_is_reused", False, RULES, True, PostHogAIAccessDecision.ALLOWED, 1),
+ ("beta_without_rules_is_not_cached", False, None, True, PostHogAIAccessDecision.UNRESOLVED, 2),
+ ("failed_override_lookup_is_not_cached", None, RULES, True, PostHogAIAccessDecision.UNRESOLVED, 2),
+ ("failed_beta_lookup_is_not_cached", False, RULES, False, PostHogAIAccessDecision.UNRESOLVED, 2),
+ ]
+ )
+ def test_cached_decision(
+ self,
+ _name: str,
+ override_value: bool | None,
+ rules: dict[str, Any] | None,
+ beta_resolves: bool,
+ expected: PostHogAIAccessDecision,
+ expected_evaluations: int,
+ ) -> 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")
+ beta = (
+ FeatureFlagResult(key="phai-2-beta", enabled=True, variant=None, payload=rules, reason=None)
+ if beta_resolves
+ else None
+ )
+
+ 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._get_funding_status",
+ return_value=OrganizationFundingStatus(
+ startup_program_label=None, prepaid_credit_state=PrepaidCreditState.NONE
+ ),
+ ),
+ patch(
+ "products.tasks.backend.access.get_posthog_ai_access_decision", wraps=get_posthog_ai_access_decision
+ ) as mock_decision,
+ ):
+ first = get_cached_posthog_ai_access_decision(user, organization)
+ second = get_cached_posthog_ai_access_decision(user, organization)
+
+ self.assertEqual((first, second), (expected, expected))
+ self.assertEqual(mock_decision.call_count, expected_evaluations)
diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.py
index 9e5a2466be6a..333c60ec31cb 100644
--- a/products/tasks/backend/tests/test_warm_facade.py
+++ b/products/tasks/backend/tests/test_warm_facade.py
@@ -73,12 +73,23 @@ def _allow_desktop_access(test_case: APIBaseTest) -> None:
test_case.addCleanup(access_patcher.stop)
+def _allow_posthog_ai_access(test_case: APIBaseTest) -> None:
+ for module in ("logic.services.code_usage_gate", "logic.services.warm", "facade.access"):
+ access_patcher = patch(
+ f"products.tasks.backend.{module}.get_posthog_ai_access_decision",
+ return_value=tasks_access.PostHogAIAccessDecision.GRANDFATHERED,
+ )
+ access_patcher.start()
+ test_case.addCleanup(access_patcher.stop)
+
+
class TestWarmTaskSandbox(APIBaseTest):
def setUp(self) -> None:
super().setUp()
self.integration = Integration.objects.create(team=self.team, kind="github", config={})
- # The warm endpoint gates on Desktop access; these tests cover warm forwarding, not the gate.
+ # The warm endpoint gates on Desktop and PostHog AI access; these tests cover warm forwarding, not the gates.
_allow_desktop_access(self)
+ _allow_posthog_ai_access(self)
def _warm(self, **overrides):
kwargs: dict[str, Any] = {
@@ -127,7 +138,7 @@ class TestWarmTaskSandbox(APIBaseTest):
@parameterized.expand(
[
- ("posthog_ai_warms_with_every_flag_off", facade.TaskOriginProduct.POSTHOG_AI, False, True),
+ ("posthog_ai_warms_without_a_warm_flag", facade.TaskOriginProduct.POSTHOG_AI, False, True),
("code_app_stays_gated_when_off", facade.TaskOriginProduct.USER_CREATED, False, False),
("code_app_warms_when_on", facade.TaskOriginProduct.USER_CREATED, True, True),
]
@@ -1666,6 +1677,10 @@ class TestWarmRunRelease(APIBaseTest):
class TestWarmTaskResumeSandbox(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ _allow_posthog_ai_access(self)
+
def test_warm_resume_from_an_import_run_marks_the_warm_run(self):
task = Task.objects.create(
team=self.team,