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.

fix(phai): let sandbox-mode and impersonated users create tasks (#87798)

Georgiy Tarasov796685e74615
diff --git a/products/posthog_ai/frontend/logics/aiOnboardingLogic.test.ts b/products/posthog_ai/frontend/logics/aiOnboardingLogic.test.ts
index 62fe407d55fe..1e2acd2b8807 100644
--- a/products/posthog_ai/frontend/logics/aiOnboardingLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/aiOnboardingLogic.test.ts
@@ -98,6 +98,21 @@ describe('aiOnboardingLogic', () => {
})
})
+ // `/api/users/` rejects writes from an impersonated session, so persisting the flag can only
+ // fail. The takeover still has to close, or every dismissal re-opens it over the composer.
+ it('closes without writing the seen flag while impersonating', async () => {
+ mountLogic()
+ userLogic.findMounted()?.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, is_impersonated: true })
+
+ await expectLogic(logic, () => {
+ logic.actions.closeOnboarding()
+ }).toFinishAllListeners()
+
+ expect(userUpdates).toHaveLength(0)
+ expect(logic.values.hasSeenOnboarding).toBe(true)
+ expect(logic.values.isOpen).toBe(false)
+ })
+
// Which step a user bails on is the segment signal the onboarding exists to collect. Stepping back and
// forth must not inflate it, or the per-step funnel stops meaning anything.
it('reports each step view only once per opening', async () => {
diff --git a/products/posthog_ai/frontend/logics/aiOnboardingLogic.ts b/products/posthog_ai/frontend/logics/aiOnboardingLogic.ts
index 85eceaa9403c..740d984d4885 100644
--- a/products/posthog_ai/frontend/logics/aiOnboardingLogic.ts
+++ b/products/posthog_ai/frontend/logics/aiOnboardingLogic.ts
@@ -44,11 +44,13 @@ export interface aiOnboardingLogicValues {
currentStep: OnboardingStep | null
githubConnected: boolean
hasSeenOnboarding: boolean
+ hasSeenOnboardingPersisted: boolean
isOpen: boolean
isReplay: boolean
projectHasData: boolean
reportProperties: OnboardingReportProperties
repositoryCount: number
+ seenThisSession: boolean
starterPrompts: readonly string[]
stepIndex: number
viewedStepKeys: Record<string, true>
@@ -100,7 +102,8 @@ export interface aiOnboardingLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
currentStep: (stepIndex: number) => OnboardingStep | null
- hasSeenOnboarding: (user: UserType | null) => boolean
+ hasSeenOnboardingPersisted: (user: UserType | null) => boolean
+ hasSeenOnboarding: (hasSeenOnboardingPersisted: boolean, seenThisSession: boolean) => boolean
projectHasData: (currentTeam: TeamPublicType | TeamType | null) => boolean
starterPrompts: (projectHasData: boolean) => readonly string[]
githubConnected: (githubIntegrations: IntegrationType[]) => boolean
@@ -183,6 +186,14 @@ export const aiOnboardingLogic = kea<aiOnboardingLogicType>([
setStepIndex: (_, { stepIndex }) => stepIndex,
},
],
+ // The seen flag normally round-trips the server, but an impersonated session can never persist
+ // it, so hold it here as well to keep the takeover closed for the rest of the session.
+ seenThisSession: [
+ false,
+ {
+ markOnboardingSeen: () => true,
+ },
+ ],
// Fire-once guard so re-entering a step (via Back, or the dot row) doesn't re-report it.
viewedStepKeys: [
{} as Record<string, true>,
@@ -198,10 +209,15 @@ export const aiOnboardingLogic = kea<aiOnboardingLogicType>([
(s) => [s.stepIndex],
(stepIndex: number): OnboardingStep | null => DEFAULT_ONBOARDING_STEPS[stepIndex] ?? null,
],
- hasSeenOnboarding: [
+ hasSeenOnboardingPersisted: [
(s) => [s.user],
(user: UserType | null): boolean => !!user?.has_seen_product_intro_for?.[POSTHOG_AI_ONBOARDING_SEEN_KEY],
],
+ hasSeenOnboarding: [
+ (s) => [s.hasSeenOnboardingPersisted, s.seenThisSession],
+ (hasSeenOnboardingPersisted: boolean, seenThisSession: boolean): boolean =>
+ hasSeenOnboardingPersisted || seenThisSession,
+ ],
// `TeamPublicType` has no `ingested_event`, so read it defensively rather than casting.
projectHasData: [
(s) => [s.currentTeam],
@@ -279,7 +295,14 @@ export const aiOnboardingLogic = kea<aiOnboardingLogicType>([
posthog.capture('posthog ai onboarding media replayed', values.reportProperties)
},
markOnboardingSeen: () => {
- if (values.hasSeenOnboarding) {
+ // Reads the persisted value, not `hasSeenOnboarding`: the session reducer above already
+ // flipped on this action, so the combined selector would skip every write.
+ if (values.hasSeenOnboardingPersisted) {
+ return
+ }
+ // `/api/users/` rejects writes from an impersonated session (ImpersonationBlockedPathsMiddleware),
+ // and the only outcome of trying is a failure toast on top of the takeover.
+ if (values.user?.is_impersonated) {
return
}
actions.updateUser({
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index b144123f590e..3f2592303f4b 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -598,9 +598,9 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
actions.loadRepositories()
} catch (error) {
actions.releaseApplyBackTargets(streamKey)
- // Show the existing failure and return to the composer with the typed text intact.
+ // Return to the composer with the typed text intact, and no toast: the composer is
+ // still on screen, so a failure banner over it reads as a dead end.
actions.clearActiveCreation()
- lemonToast.error('Failed to create task')
actions.submitNewTaskFailure(error instanceof Error ? error.message : 'Unknown error')
}
},
diff --git a/products/tasks/backend/access.py b/products/tasks/backend/access.py
index 75e529b1fb5e..0606d7a69780 100644
--- a/products/tasks/backend/access.py
+++ b/products/tasks/backend/access.py
@@ -47,19 +47,32 @@ class DesktopAccessDecision(StrEnum):
return None
+# Either flag grants the same access. `tasks` is the Desktop waitlist. `phai-sandbox-mode` is the
+# PostHog AI composer, which reaches the same cloud runs through a different entry point, and rolls
+# out to organizations that are not on the Desktop waitlist.
+TASKS_ACCESS_FEATURE_FLAGS = ("tasks", "phai-sandbox-mode")
+
+
def has_tasks_access(user: User) -> bool:
+ """
+ User has access to PostHog Desktop if one of the `TASKS_ACCESS_FEATURE_FLAGS` is enabled for
+ them OR they have redeemed an invite code.
+ """
if not user or not user.is_authenticated or not user.distinct_id:
return False
organization = getattr(user, "organization", None)
organization_id = str(organization.id) if organization is not None else None
- if feature_enabled_or_false(
- "tasks",
- str(user.distinct_id),
- groups={"organization": organization_id} if organization_id is not None else None,
- group_properties={"organization": {"id": organization_id}} if organization_id is not None else None,
- only_evaluate_locally=False,
- send_feature_flag_events=False,
+ if any(
+ feature_enabled_or_false(
+ flag_key,
+ str(user.distinct_id),
+ groups={"organization": organization_id} if organization_id is not None else None,
+ group_properties={"organization": {"id": organization_id}} if organization_id is not None else None,
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ for flag_key in TASKS_ACCESS_FEATURE_FLAGS
):
return True
return CodeInviteRedemption.objects.filter(user=user).exists()
diff --git a/products/tasks/backend/tests/test_desktop_access.py b/products/tasks/backend/tests/test_desktop_access.py
index 4ef5fb6a4eeb..744e42124108 100644
--- a/products/tasks/backend/tests/test_desktop_access.py
+++ b/products/tasks/backend/tests/test_desktop_access.py
@@ -1,4 +1,4 @@
-from posthog.test.base import APIBaseTest
+from posthog.test.base import APIBaseTest, BaseTest
from unittest.mock import MagicMock, patch
from django.core.cache import cache
@@ -13,6 +13,7 @@ from products.tasks.backend.access import (
DesktopAccessReason,
DesktopAccessResolutionError,
get_desktop_access_decision,
+ has_tasks_access,
)
from products.tasks.backend.logic.services.code_usage_gate import code_access_required_response
from products.tasks.backend.models import CodeInvite, CodeInviteRedemption
@@ -242,3 +243,19 @@ class TestDesktopAccessPolicy(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)
self.assertEqual(response.json()["code"], "desktop_access_unavailable")
+
+
+class TestTasksAccessFlags(BaseTest):
+ @parameterized.expand(
+ [
+ ("desktop_waitlist", {"tasks"}, True),
+ ("posthog_ai_composer", {"phai-sandbox-mode"}, True),
+ ("neither", set(), False),
+ ]
+ )
+ def test_either_access_flag_grants_access(self, _name: str, enabled_flags: set[str], expected: bool) -> None:
+ with patch(
+ "products.tasks.backend.access.feature_enabled_or_false",
+ side_effect=lambda flag_key, *_args, **_kwargs: flag_key in enabled_flags,
+ ):
+ assert has_tasks_access(self.user) is expected