: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(phai): make marking a product intro seen actually persist (#92352)
Georgiy Tarasov85ad22ed7080
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 000b3937e90e..de923f5ac82b 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -4960,6 +4960,19 @@ export interface OnboardingSkipRequestApi {step_at_skip?: string}+/**+ * Request body for PATCH /api/users/@me/product_intro_seen.+ */+export interface PatchedProductIntroSeenApi {+ /**+ * Which key in `has_seen_product_intro_for` to set. Any string is accepted: besides the product keys, the map holds keys composed per team and keys for surfaces that are not products.+ * @maxLength 128+ */+ product_key?: string+ /** Whether the intro counts as seen. Send false to show it again. */+ seen?: boolean+}+/*** * `ios` - iOS* * `android` - Android@@ -5439,3 +5452,5 @@ export type UsersLoginSessionsListParams = {email?: stringis_staff?: boolean}++export type UsersProductIntroSeenPartialUpdate200 = { [key: string]: boolean }diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex 745c73a10b88..28a0254d3101 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -67,6 +67,7 @@ import type {PatchedFileSystemShortcutApi,PatchedIdentityProviderConfigApi,PatchedOrganizationDomainApi,+ PatchedProductIntroSeenApi,PatchedProjectBackwardCompatApi,PatchedProjectSecretAPIKeyApi,PatchedUserApi,@@ -102,6 +103,7 @@ import type {UsersIntegrationsListParams,UsersListParams,UsersLoginSessionsListParams,+ UsersProductIntroSeenPartialUpdate200,VerifyEmailRequestApi,} from './api.schemas'@@ -3120,6 +3122,34 @@ export const usersOnboardingSkipCreate = async (})}+export const getUsersProductIntroSeenPartialUpdateUrl = (uuid: string) => {+ return `/api/users/${uuid}/product_intro_seen/`+}++/**+ * Record that this user has seen one product intro.+ *+ * Separate from the `has_seen_product_intro_for` field on the main user PATCH, which requires a+ * recently authenticated session. Dismissing an intro must not depend on that: a re-auth prompt+ * would cover the intro it interrupts, and the dismissal would never persist. Nothing reachable+ * here changes an account, an organization, or a profile.+ *+ * Merging server-side also keeps two intros dismissed from separate tabs from dropping each+ * other's key, which a read-modify-write of the whole map cannot avoid.+ */+export const usersProductIntroSeenPartialUpdate = async (+ uuid: string,+ patchedProductIntroSeenApi?: PatchedProductIntroSeenApi,+ options?: RequestInit+): Promise<UsersProductIntroSeenPartialUpdate200> => {+ return apiMutator<UsersProductIntroSeenPartialUpdate200>(getUsersProductIntroSeenPartialUpdateUrl(uuid), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedProductIntroSeenApi),+ })+}+export const getUsersPushTokensCreateUrl = (uuid: string) => {return `/api/users/${uuid}/push_tokens/`}diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.tsindex 0dd802a2414b..a3bc461dec07 100644--- a/frontend/src/generated/core/api.zod.ts+++ b/frontend/src/generated/core/api.zod.ts@@ -1438,6 +1438,37 @@ export const UsersOnboardingSkipCreateBody = /* @__PURE__ */ zod'Request body for POST \/api\/users\/{id}\/onboarding\/skip\/.\n\nSource of truth for OpenAPI \/ generated TS \/ zod \/ MCP — bind this serializer at\nruntime so the contract clients believe is enforced (length cap, choice validation,\nno extra fields) is actually enforced server-side.')+/**+ * Record that this user has seen one product intro.+ *+ * Separate from the `has_seen_product_intro_for` field on the main user PATCH, which requires a+ * recently authenticated session. Dismissing an intro must not depend on that: a re-auth prompt+ * would cover the intro it interrupts, and the dismissal would never persist. Nothing reachable+ * here changes an account, an organization, or a profile.+ *+ * Merging server-side also keeps two intros dismissed from separate tabs from dropping each+ * other's key, which a read-modify-write of the whole map cannot avoid.+ */+export const usersProductIntroSeenPartialUpdateBodyProductKeyMax = 128++export const usersProductIntroSeenPartialUpdateBodySeenDefault = true++export const UsersProductIntroSeenPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ product_key: zod+ .string()+ .max(usersProductIntroSeenPartialUpdateBodyProductKeyMax)+ .optional()+ .describe(+ 'Which key in `has_seen_product_intro_for` to set. Any string is accepted: besides the product keys, the map holds keys composed per team and keys for surfaces that are not products.'+ ),+ seen: zod+ .boolean()+ .default(usersProductIntroSeenPartialUpdateBodySeenDefault)+ .describe('Whether the intro counts as seen. Send false to show it again.'),+ })+ .describe('Request body for PATCH \/api\/users\/@me\/product_intro_seen.')+/*** Idempotent upsert: if the (user, token) pair already exists, `platform` and `last_seen_at` are refreshed. Otherwise a new row is created.* @summary Register a push notification tokendiff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 48d58fc617bf..2d29c06817ac 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -40186,6 +40186,7 @@"pipeline_destinations","pipeline_transformations","platform_and_support",+ "posthog_ai_onboarding","product_analytics","product_tours","pulse",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 2e7d51dc4610..a24341d7c129 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -10062,6 +10062,7 @@ export enum ProductKey {PIPELINE_DESTINATIONS = 'pipeline_destinations',PIPELINE_TRANSFORMATIONS = 'pipeline_transformations',PLATFORM_AND_SUPPORT = 'platform_and_support',+ POSTHOG_AI_ONBOARDING = 'posthog_ai_onboarding',PRODUCT_ANALYTICS = 'product_analytics',PRODUCT_TOURS = 'product_tours',PULSE = 'pulse',diff --git a/frontend/src/scenes/userLogic.ts b/frontend/src/scenes/userLogic.tsindex bfe268d95729..c35d853464c6 100644--- a/frontend/src/scenes/userLogic.ts+++ b/frontend/src/scenes/userLogic.ts@@ -760,16 +760,18 @@ export const userLogic = kea<userLogicType>([},updateHasSeenProductIntroFor: async ({ productKey, value }, breakpoint) => {await breakpoint(10)- await api- .update('api/users/@me/', {- has_seen_product_intro_for: {- ...values.user?.has_seen_product_intro_for,- [productKey]: value,- },- })- .then(() => {- actions.loadUser()- })+ try {+ // Its own endpoint rather than a field on the user PATCH: that one needs a recently+ // authenticated session, so a risk step-up would answer a dismissal with the re-auth modal.+ // It also merges the key server-side, so two tabs can't drop each other's write.+ await api.update('api/users/@me/product_intro_seen', { product_key: productKey, seen: value })+ actions.loadUser()+ } catch (error: any) {+ // Marking an intro seen runs behind whatever the user is already doing, so a failure is+ // logged rather than surfaced: a toast would land on top of the intro they just dismissed.+ // The intro comes back next visit, which is the honest outcome of a write that didn't land.+ console.error(error)+ }},switchTeam: ({ teamId, destination }) => {sidePanelStateLogic.findMounted()?.actions.closeSidePanel()diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.pyindex 83e46cfb0290..2a7e25f94fe2 100644--- a/posthog/api/test/test_authentication.py+++ b/posthog/api/test/test_authentication.py@@ -2265,6 +2265,16 @@ class TestTimeSensitivePermissions(APIBaseTest):)assert res.status_code == 200+ def test_user_can_mark_a_product_intro_seen_without_recent_authentication(self):+ now = datetime.now()+ with freeze_time(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10)):+ res = self.client.patch(+ "/api/users/@me/product_intro_seen",+ {"product_key": "posthog_ai_onboarding"},+ format="json",+ )+ assert res.status_code == 200+class TestTeamSecretTokenAuthentication(APIBaseTest):def setUp(self):diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex 7c070e73ebf0..8262184e76be 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -27,7 +27,7 @@ from social_django.models import UserSocialAuthfrom posthog.api.email_verification import email_verification_code_verifierfrom posthog.api.oauth.toolbar_service import ToolbarOAuthState, build_toolbar_oauth_state, new_state_nonce-from posthog.api.user import UserSerializer+from posthog.api.user import MAX_PRODUCT_INTROS_SEEN, UserSerializerfrom posthog.constants import AvailableFeaturefrom posthog.helpers.two_factor_session import code_based_verification_token_generatorfrom posthog.models import Team, User@@ -782,6 +782,107 @@ class TestUserAPI(APIBaseTest):],)+ def test_marking_a_product_intro_seen_keeps_the_other_keys(self):+ # The map is shared by every product intro. A write that replaced it wholesale would re-trigger+ # every other intro the user has already dismissed.+ self.user.has_seen_product_intro_for = {"session_replay": True}+ self.user.save()++ response = self.client.patch(+ "/api/users/@me/product_intro_seen",+ {"product_key": "posthog_ai_onboarding"},+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {"session_replay": True, "posthog_ai_onboarding": True}++ def test_marking_a_product_intro_unseen_shows_it_again(self):+ self.user.has_seen_product_intro_for = {"session_replay": True}+ self.user.save()++ response = self.client.patch(+ "/api/users/@me/product_intro_seen",+ {"product_key": "session_replay", "seen": False},+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {"session_replay": False}++ @parameterized.expand(+ [+ ("missing_key", {}),+ ("blank_key", {"product_key": ""}),+ ("oversized_key", {"product_key": "x" * 129}),+ ]+ )+ def test_marking_a_product_intro_seen_rejects_bad_keys(self, _name: str, payload: dict):+ # This action skips the re-auth gate, so an unbounded key would let a stolen session grow the+ # blob on the user row without ever re-authenticating.+ response = self.client.patch("/api/users/@me/product_intro_seen", payload, content_type="application/json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ self.user.refresh_from_db()+ assert not self.user.has_seen_product_intro_for++ @parameterized.expand([("user:write", 200), ("user:read", 403)])+ def test_marking_a_product_intro_seen_over_token_auth(self, scope: str, expected_status: int):+ # A custom @action resolves to no scopes unless it declares them, and `APIScopePermission` refuses+ # that outright — so without `required_scopes` every intro dismissal 403s in standalone OAuth mode,+ # which is the failure this endpoint exists to remove. Session auth skips scopes, so only a token+ # exercises this.+ key = self.create_personal_api_key_with_scopes([scope])+ self.client.logout()++ response = self.client.patch(+ "/api/users/@me/product_intro_seen",+ {"product_key": "posthog_ai_onboarding"},+ content_type="application/json",+ HTTP_AUTHORIZATION=f"Bearer {key}",+ )++ assert response.status_code == expected_status, response.content++ def test_marking_a_product_intro_seen_locks_the_row(self):+ # The whole map is rewritten on every write, so two concurrent dismissals both read the pre-merge+ # map and the later save drops the earlier key. Asserting the lock is a proxy for that race, which+ # a single-threaded test cannot reproduce.+ with CaptureQueriesContext(connection) as ctx:+ response = self.client.patch(+ "/api/users/@me/product_intro_seen",+ {"product_key": "posthog_ai_onboarding"},+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_200_OK+ locking_selects = [+ q["sql"] for q in ctx.captured_queries if "posthog_user" in q["sql"] and "FOR UPDATE" in q["sql"]+ ]+ assert locking_selects, "the merge must read the user row FOR UPDATE"++ def test_marking_a_product_intro_seen_caps_the_map(self):+ self.user.has_seen_product_intro_for = {f"product_{i}": True for i in range(MAX_PRODUCT_INTROS_SEEN)}+ self.user.save()++ response = self.client.patch(+ "/api/users/@me/product_intro_seen",+ {"product_key": "one_too_many"},+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST++ # A key already in the map still updates at the cap, or a full map would freeze every intro.+ assert (+ self.client.patch(+ "/api/users/@me/product_intro_seen",+ {"product_key": "product_0", "seen": False},+ content_type="application/json",+ ).status_code+ == status.HTTP_200_OK+ )+def _assert_set_scene_choice(self, scene: str, dashboard: Dashboard, user: User, expected_choices: list[dict]) -> None:diff --git a/posthog/api/test/test_user_auth_session.py b/posthog/api/test/test_user_auth_session.pyindex e558f5b1a155..979e3eebf26b 100644--- a/posthog/api/test/test_user_auth_session.py+++ b/posthog/api/test/test_user_auth_session.py@@ -229,6 +229,23 @@ class TestUserAuthSessionAPI(APIBaseTest):self.assertEqual(response.status_code, 403)self.assertEqual(response.json()["code"], "sensitive_action_required_reauth")+ def test_step_up_does_not_block_marking_a_product_intro_seen(self):+ # Dismissing a product intro is why this action is exempt: gated, it answers the dismissal with+ # the re-auth modal drawn over the intro, and the dismissal never persists.+ session = self.client.session+ session["step_up_required"] = True+ session.save()++ response = self.client.patch(+ "/api/users/@me/product_intro_seen",+ {"product_key": "posthog_ai_onboarding"},+ content_type="application/json",+ )++ self.assertEqual(response.status_code, 200, response.content)+ self.user.refresh_from_db()+ self.assertEqual(self.user.has_seen_product_intro_for, {"posthog_ai_onboarding": True})+def test_stale_session_still_allows_allowlisted_field_write(self):# Without a step-up, the allow-list still relaxes the time-based freshness window — guards that# the step-up reordering didn't break the normal allow_if_only_fields path.diff --git a/posthog/api/user.py b/posthog/api/user.pyindex 7c9d6daff04b..2b507f634e05 100644--- a/posthog/api/user.py+++ b/posthog/api/user.py@@ -161,6 +161,10 @@ NUM_2FA_BACKUP_CODES = 10MAX_PIPELINE_NOTIFICATIONS = 1000_PIPELINE_ID_PATTERN = re.compile(r"^(?:hog_function|batch_export|plugin_config):[0-9a-zA-Z-]{1,128}$")+# `product_intro_seen` is exempt from the re-auth gate, so it gets a ceiling of its own. Only a new key+# is refused at the ceiling, so an intro the user already dismissed still reopens and closes.+MAX_PRODUCT_INTROS_SEEN = 100+def _reject_locked_notification_settings(user: User, incoming: Notifications, current: Mapping[str, Any]) -> None:"""Stop a member changing a setting their organization enforces.@@ -986,6 +990,23 @@ class ScenePersonalisationSerializer(serializers.ModelSerializer):)+class ProductIntroSeenSerializer(serializers.Serializer):+ """Request body for PATCH /api/users/@me/product_intro_seen."""++ product_key = serializers.CharField(+ max_length=128,+ help_text=(+ "Which key in `has_seen_product_intro_for` to set. Any string is accepted: besides the "+ "product keys, the map holds keys composed per team and keys for surfaces that are not "+ "products."+ ),+ )+ seen = serializers.BooleanField(+ default=True,+ help_text="Whether the intro counts as seen. Send false to show it again.",+ )++class UserAuthSessionSerializer(serializers.ModelSerializer):"""A cookie-auth login session shown on the user's 'Web sessions' screen."""@@ -1103,6 +1124,7 @@ class UserViewSet(time_sensitive_exclude_actions = ["hedgehog_config","scene_personalisation",+ "product_intro_seen",]time_sensitive_allow_actions = ["hedgehog_config"]filter_backends = [DjangoFilterBackend]@@ -1464,6 +1486,53 @@ class UserViewSet(return Response(self.get_serializer(instance=instance).data)+ @extend_schema(+ request=ProductIntroSeenSerializer,+ responses={+ 200: OpenApiResponse(+ response={"type": "object", "additionalProperties": {"type": "boolean"}},+ description="The user's whole `has_seen_product_intro_for` map, after the merge.",+ )+ },+ )+ # `required_scopes` is explicit because the viewset resolves scopes from `scope_object` plus the+ # read/write action lists, and a custom @action is in neither — leaving it unset resolves to no+ # scopes at all, which `APIScopePermission` refuses outright, even for a wildcard token.+ @action(methods=["PATCH"], detail=True, required_scopes=["user:write"])+ def product_intro_seen(self, request, **kwargs) -> Response:+ """Record that this user has seen one product intro.++ Separate from the `has_seen_product_intro_for` field on the main user PATCH, which requires a+ recently authenticated session. Dismissing an intro must not depend on that: a re-auth prompt+ would cover the intro it interrupts, and the dismissal would never persist. Nothing reachable+ here changes an account, an organization, or a profile.++ Merging server-side also keeps two intros dismissed from separate tabs from dropping each+ other's key, which a read-modify-write of the whole map cannot avoid.+ """+ serializer = ProductIntroSeenSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ product_key = serializer.validated_data["product_key"]++ instance = self.get_object()++ with transaction.atomic():+ # Lock the user row so concurrent dismissals from separate tabs merge into the map instead of+ # overwriting it wholesale, and so the size cap counts committed keys rather than a stale read.+ locked = User.objects.select_for_update().get(pk=instance.pk)+ seen_for = locked.has_seen_product_intro_for or {}++ if product_key not in seen_for and len(seen_for) >= MAX_PRODUCT_INTROS_SEEN:+ raise serializers.ValidationError(+ f"Cannot track more than {MAX_PRODUCT_INTROS_SEEN} product intros",+ code="invalid_input",+ )++ locked.has_seen_product_intro_for = {**seen_for, product_key: serializer.validated_data["seen"]}+ locked.save(update_fields=["has_seen_product_intro_for"])++ return Response(locked.has_seen_product_intro_for)+@action(methods=["GET", "PATCH"],detail=True,diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex b9409903eeac..117a2c844156 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -3701,6 +3701,7 @@ class ProductKey(StrEnum):PIPELINE_DESTINATIONS = "pipeline_destinations"PIPELINE_TRANSFORMATIONS = "pipeline_transformations"PLATFORM_AND_SUPPORT = "platform_and_support"+ POSTHOG_AI_ONBOARDING = "posthog_ai_onboarding"PRODUCT_ANALYTICS = "product_analytics"PRODUCT_TOURS = "product_tours"PULSE = "pulse"diff --git a/products/posthog_ai/frontend/logics/aiOnboardingLogic.test.ts b/products/posthog_ai/frontend/logics/aiOnboardingLogic.test.tsindex 1e2acd2b8807..b19ef2ad6f57 100644--- a/products/posthog_ai/frontend/logics/aiOnboardingLogic.test.ts+++ b/products/posthog_ai/frontend/logics/aiOnboardingLogic.test.ts@@ -16,18 +16,37 @@ import { composerSeedLogic } from './composerSeedLogic'describe('aiOnboardingLogic', () => {let logic: ReturnType<typeof aiOnboardingLogic.build>let seedLogic: ReturnType<typeof composerSeedLogic.build>- let userUpdates: Record<string, any>[]+ let seenWrites: Record<string, any>[]+ let failNextSeenWrite: booleanbeforeEach(() => {- userUpdates = []+ seenWrites = []+ failNextSeenWrite = falseuseMocks({patch: {- '/api/users/@me/': async ({ request }) => {+ '/api/users/@me/product_intro_seen': async ({ request }) => {const body = (await request.json()) as Record<string, any>- userUpdates.push(body)- return { ...MOCK_DEFAULT_USER, ...body }+ seenWrites.push(body)+ if (failNextSeenWrite) {+ failNextSeenWrite = false+ return [500, { detail: 'the seen write failed' }]+ }+ return { [body.product_key]: body.seen }},},+ get: {+ // The reload after a write has to see it, the way the real endpoint does. Without this the+ // persisted flag never flips and every dismissal looks like a first write.+ '/api/users/@me/': () => [+ 200,+ {+ ...MOCK_DEFAULT_USER,+ has_seen_product_intro_for: Object.fromEntries(+ seenWrites.map(({ product_key, seen }) => [product_key, seen])+ ),+ },+ ],+ },})})@@ -79,23 +98,79 @@ describe('aiOnboardingLogic', () => {})})- // `has_seen_product_intro_for` is one shared map across every product intro. Writing the onboarding key- // without spreading the existing entries would silently re-trigger every other product's intro.- it('records the seen flag without dropping other product intros', async () => {+ // Persisting only on the way out greeted people again on their next visit, because closing the tab,+ // following a link, or reloading never reaches a dismissal. A replay has to stay silent: it opens the+ // takeover on surfaces that never showed it, so writing there swallows the one real showing.+ // The key matters too — one the open check doesn't read reopens the takeover forever.+ it.each([+ ['opens', false, [{ product_key: POSTHOG_AI_ONBOARDING_SEEN_KEY, seen: true }]],+ ['is replayed', true, []],+ ])('records the seen flag when the takeover %s', async (_name, isReplay, expected) => {+ mountLogic()+ userLogic.findMounted()?.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER })++ await expectLogic(logic, () => {+ logic.actions.openOnboarding(isReplay)+ }).toFinishAllListeners()++ expect(seenWrites).toEqual(expected)+ })++ // Both the open and the dismissal mark the takeover seen, so the persisted flag is what stops the+ // second one from writing again and dragging another full user reload behind it.+ it('records the seen flag once across an open and a dismissal', async () => {mountLogic()- userLogic- .findMounted()- ?.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, has_seen_product_intro_for: { session_replay: true } })+ userLogic.findMounted()?.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER })+ await expectLogic(logic, () => {+ logic.actions.openOnboarding()+ }).toFinishAllListeners()await expectLogic(logic, () => {logic.actions.closeOnboarding()}).toFinishAllListeners()- expect(userUpdates).toHaveLength(1)- expect(userUpdates[0].has_seen_product_intro_for).toEqual({- session_replay: true,- [POSTHOG_AI_ONBOARDING_SEEN_KEY]: true,- })+ expect(seenWrites).toEqual([{ product_key: POSTHOG_AI_ONBOARDING_SEEN_KEY, seen: true }])+ })++ // A replay opens the takeover on a surface that never showed it, so it has to write nothing on the way+ // out as well as on open. Otherwise dismissing, finishing, or answering a prompt after a replay persists+ // the flag and swallows the user's one real first-run showing on the new surface.+ it.each([+ ['dismissed', () => logic.actions.closeOnboarding()],+ ['finished', () => logic.actions.finishOnboarding()],+ ['answered with a starter prompt', () => logic.actions.selectStarterPrompt('Audit my event tracking.')],+ ])('writes nothing when a replay is %s', async (_name, exit) => {+ mountLogic()+ userLogic.findMounted()?.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER })++ await expectLogic(logic, () => {+ logic.actions.openOnboarding(true)+ }).toFinishAllListeners()+ await expectLogic(logic, () => {+ exit()+ }).toFinishAllListeners()++ expect(seenWrites).toHaveLength(0)+ // The session flag has to stay clear as well, or the real surface cannot open the takeover for the+ // rest of the session. Guarding inside `markOnboardingSeen` would pass the check above but fail here.+ expect(logic.values.hasSeenOnboarding).toBe(false)+ })++ // A failed write must not stop a later one from persisting the flag, or a transient error means the+ // takeover comes back for good. An earlier guard latched before the request and never cleared.+ it('retries the seen write on dismissal after the open-time write fails', async () => {+ mountLogic()+ userLogic.findMounted()?.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER })+ failNextSeenWrite = true++ await expectLogic(logic, () => {+ logic.actions.openOnboarding()+ }).toFinishAllListeners()+ await expectLogic(logic, () => {+ logic.actions.closeOnboarding()+ }).toFinishAllListeners()++ expect(seenWrites).toHaveLength(2)})// `/api/users/` rejects writes from an impersonated session, so persisting the flag can only@@ -105,10 +180,11 @@ describe('aiOnboardingLogic', () => {userLogic.findMounted()?.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, is_impersonated: true })await expectLogic(logic, () => {+ logic.actions.openOnboarding()logic.actions.closeOnboarding()}).toFinishAllListeners()- expect(userUpdates).toHaveLength(0)+ expect(seenWrites).toHaveLength(0)expect(logic.values.hasSeenOnboarding).toBe(true)expect(logic.values.isOpen).toBe(false)})diff --git a/products/posthog_ai/frontend/logics/aiOnboardingLogic.ts b/products/posthog_ai/frontend/logics/aiOnboardingLogic.tsindex 740d984d4885..00f5b443e1b4 100644--- a/products/posthog_ai/frontend/logics/aiOnboardingLogic.ts+++ b/products/posthog_ai/frontend/logics/aiOnboardingLogic.ts@@ -6,6 +6,7 @@ import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { teamLogic } from 'scenes/teamLogic'import { userLogic } from 'scenes/userLogic'+import { ProductKey } from '~/queries/schema/schema-general'import type { IntegrationType, TeamPublicType, TeamType, UserType } from '~/types'import {@@ -16,11 +17,8 @@ import {} from '../components/onboarding/onboardingSteps'import { type ComposerSeed, composerSeedLogic } from './composerSeedLogic'-/**- * Key into `user.has_seen_product_intro_for`. That map is a plain `Record<string, boolean>` end to end, so a- * non-`ProductKey` key is fine — web analytics already stores its own composed key there the same way.- */-export const POSTHOG_AI_ONBOARDING_SEEN_KEY = 'posthog_ai_onboarding'+/** Key into `user.has_seen_product_intro_for`. Named here because it reads better at the call sites. */+export const POSTHOG_AI_ONBOARDING_SEEN_KEY = ProductKey.POSTHOG_AI_ONBOARDINGexport interface AiOnboardingLogicProps {/** The embedded composer's panel key, so a chosen starter prompt reaches the right composer. */@@ -61,12 +59,12 @@ export interface aiOnboardingLogicActions {setSeed: (seed: ComposerSeed) => {seed: ComposerSeed} // composerSeedLogic- updateUser: (- user: Partial<UserType>,- successCallback?: (() => void) | undefined+ updateHasSeenProductIntroFor: (+ productKey: ProductKey,+ value?: boolean | undefined) => {- successCallback: (() => void) | undefined- user: Partial<UserType>+ productKey: ProductKey+ value: boolean} // userLogicclickGithubCta: () => {value: true@@ -148,7 +146,12 @@ export const aiOnboardingLogic = kea<aiOnboardingLogicType>([aiConsentLogic,['dataProcessingAccepted'],],- actions: [userLogic, ['updateUser'], composerSeedLogic({ panelId: props.panelId }), ['setSeed']],+ actions: [+ userLogic,+ ['updateHasSeenProductIntroFor'],+ composerSeedLogic({ panelId: props.panelId }),+ ['setSeed'],+ ],})),actions({@@ -249,11 +252,18 @@ export const aiOnboardingLogic = kea<aiOnboardingLogicType>([}),listeners(({ actions, values }) => ({- openOnboarding: () => {+ openOnboarding: ({ isReplay }) => {posthog.capture('posthog ai onboarding shown', values.reportProperties)if (values.currentStep) {actions.markStepViewed(values.currentStep.key)}+ // Persisted on open rather than only on the way out. A user who reads a step and then closes+ // the tab, follows a link, or reloads never reaches a dismissal, so the takeover greeted them+ // again on their next visit. A replay writes nothing: it re-opens the takeover on surfaces that+ // never showed it by themselves, and marking it seen there would swallow the one real showing.+ if (!isReplay) {+ actions.markOnboardingSeen()+ }},setStepIndex: () => {const step = values.currentStep@@ -268,11 +278,18 @@ export const aiOnboardingLogic = kea<aiOnboardingLogicType>([// skip event carries the step it happened on rather than only reporting that a dismissal occurred.posthog.capture('posthog ai onboarding step skipped', values.reportProperties)posthog.capture('posthog ai onboarding dismissed', values.reportProperties)- actions.markOnboardingSeen()+ // A replay writes nothing on the way out either, matching the open carve-out above, because it+ // re-opened the takeover on a surface that never showed it and persisting here would swallow the+ // one real showing.+ if (!values.isReplay) {+ actions.markOnboardingSeen()+ }},finishOnboarding: () => {posthog.capture('posthog ai onboarding completed', values.reportProperties)- actions.markOnboardingSeen()+ if (!values.isReplay) {+ actions.markOnboardingSeen()+ }},selectStarterPrompt: ({ prompt }) => {posthog.capture('posthog ai onboarding starter prompt clicked', {@@ -283,7 +300,9 @@ export const aiOnboardingLogic = kea<aiOnboardingLogicType>([// prompt only prefills, so the consent popover never fires on top of the onboarding. The user's// own send then goes through the composer's normal consent flow.actions.setSeed({ prompt, autoSubmit: values.dataProcessingAccepted })- actions.markOnboardingSeen()+ if (!values.isReplay) {+ actions.markOnboardingSeen()+ }},clickGithubCta: () => {posthog.capture('posthog ai onboarding github cta clicked', {@@ -305,12 +324,7 @@ export const aiOnboardingLogic = kea<aiOnboardingLogicType>([if (values.user?.is_impersonated) {return}- actions.updateUser({- has_seen_product_intro_for: {- ...values.user?.has_seen_product_intro_for,- [POSTHOG_AI_ONBOARDING_SEEN_KEY]: true,- },- })+ actions.updateHasSeenProductIntroFor(POSTHOG_AI_ONBOARDING_SEEN_KEY)},})),])diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yamlindex 38658e905bd5..f4944a0d8658 100644--- a/services/mcp/definitions/core.yaml+++ b/services/mcp/definitions/core.yaml@@ -647,6 +647,9 @@ tools:users-onboarding-skip-create:operation: users_onboarding_skip_createenabled: false+ users-product-intro-seen-partial-update:+ operation: users_product_intro_seen_partial_update+ enabled: falseusers-push-tokens-create:operation: users_push_tokens_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9c0511e913fb..38dbb41cc547 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -64579,6 +64579,19 @@ export namespace Schemas {homepage?: PinnedSceneTab | null;}+ /**+ * Request body for PATCH /api/users/@me/product_intro_seen.+ */+ export interface PatchedProductIntroSeen {+ /**+ * Which key in `has_seen_product_intro_for` to set. Any string is accepted: besides the product keys, the map holds keys composed per team and keys for surfaces that are not products.+ * @maxLength 128+ */+ product_key?: string;+ /** Whether the intro counts as seen. Send false to show it again. */+ seen?: boolean;+ }+/*** * `app` - app* * `toolbar` - toolbar@@ -101154,5 +101167,7 @@ export namespace Schemas {is_staff?: boolean;};+ export type UsersProductIntroSeenPartialUpdate200 = {[key: string]: boolean};+}