: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
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import posthog from 'posthog-js'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
import { aiConsentLogic } from '~/layout/ai/aiConsentLogic'
import { ProductKey } from '~/queries/schema/schema-general'
import type { IntegrationType, TeamPublicType, TeamType, UserType } from '~/types'
import {
DEFAULT_ONBOARDING_STEPS,
DEFAULT_STARTER_PROMPTS,
EMPTY_PROJECT_STARTER_PROMPTS,
type OnboardingStep,
} from '../components/onboarding/onboardingSteps'
import { type ComposerSeed, composerSeedLogic } from './composerSeedLogic'
/** 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_ONBOARDING
export interface AiOnboardingLogicProps {
/** The embedded composer's panel key, so a chosen starter prompt reaches the right composer. */
panelId?: string
}
export interface OnboardingReportProperties {
step_key: string
step_index: number
step_count: number
is_replay: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiOnboardingLogicValues {
dataProcessingAccepted: boolean // aiConsentLogic
githubIntegrations: IntegrationType[] // integrationsLogic
integrationsLoading: boolean // integrationsLogic
currentTeam: TeamPublicType | TeamType | null // teamLogic
user: UserType | null // userLogic
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>
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiOnboardingLogicActions {
setSeed: (seed: ComposerSeed) => {
seed: ComposerSeed
} // composerSeedLogic
updateHasSeenProductIntroFor: (
productKey: string,
value?: boolean | undefined
) => {
productKey: string
value: boolean
} // userLogic
clickGithubCta: () => {
value: true
}
closeOnboarding: () => {
value: true
}
markOnboardingSeen: () => {
value: true
}
markStepViewed: (stepKey: string) => {
stepKey: string
}
openOnboarding: (isReplay?: boolean) => {
isReplay: boolean
}
replayMedia: () => {
value: true
}
selectStarterPrompt: (prompt: string) => {
prompt: string
}
setStepIndex: (stepIndex: number) => {
stepIndex: number
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiOnboardingLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
currentStep: (stepIndex: number) => OnboardingStep | null
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
repositoryCount: (githubIntegrations: IntegrationType[]) => number
reportProperties: (
currentStep: OnboardingStep | null,
stepIndex: number,
isReplay: boolean
) => OnboardingReportProperties
}
}
export type aiOnboardingLogicType = MakeLogicType<
aiOnboardingLogicValues,
aiOnboardingLogicActions,
AiOnboardingLogicProps,
aiOnboardingLogicMeta
>
/**
* State and telemetry for the PostHog AI onboarding takeover: which step is showing, what a dismissal
* persists, and what a chosen starter prompt does. Deliberately host-agnostic — it does not know whether
* PostHog AI was opened on `/ai` or in the side panel, nor which runtime is active. The host decides when to
* mount it (see `MaybePhaiOnboarding` in `scenes/max`) and passes the composer's `panelId`.
*
* "Seen" is stored per user on the server rather than per device, so the takeover shows exactly once no
* matter where the user signs in. The replay button re-opens it without clearing that flag.
*/
export const aiOnboardingLogic = kea<aiOnboardingLogicType>([
path(['products', 'posthog_ai', 'frontend', 'logics', 'aiOnboardingLogic']),
props({} as AiOnboardingLogicProps),
key((props) => props.panelId ?? 'scene'),
connect((props: AiOnboardingLogicProps) => ({
values: [
userLogic,
['user'],
teamLogic,
['currentTeam'],
integrationsLogic,
['githubIntegrations', 'integrationsLoading'],
aiConsentLogic,
['dataProcessingAccepted'],
],
actions: [
userLogic,
['updateHasSeenProductIntroFor'],
composerSeedLogic({ panelId: props.panelId }),
['setSeed'],
],
})),
actions({
openOnboarding: (isReplay: boolean = false) => ({ isReplay }),
closeOnboarding: true,
setStepIndex: (stepIndex: number) => ({ stepIndex }),
markStepViewed: (stepKey: string) => ({ stepKey }),
selectStarterPrompt: (prompt: string) => ({ prompt }),
clickGithubCta: true,
replayMedia: true,
markOnboardingSeen: true,
}),
reducers({
isOpen: [
false,
{
openOnboarding: () => true,
closeOnboarding: () => false,
selectStarterPrompt: () => false,
},
],
isReplay: [
false,
{
openOnboarding: (_, { isReplay }) => isReplay,
},
],
stepIndex: [
0,
{
openOnboarding: () => 0,
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>,
{
openOnboarding: () => ({}),
markStepViewed: (state, { stepKey }) => ({ ...state, [stepKey]: true }),
},
],
}),
selectors({
currentStep: [
(s) => [s.stepIndex],
(stepIndex: number): OnboardingStep | null => DEFAULT_ONBOARDING_STEPS[stepIndex] ?? null,
],
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],
(currentTeam: TeamPublicType | TeamType | null): boolean =>
!!currentTeam && 'ingested_event' in currentTeam && !!currentTeam.ingested_event,
],
starterPrompts: [
(s) => [s.projectHasData],
(projectHasData: boolean): readonly string[] =>
projectHasData ? DEFAULT_STARTER_PROMPTS : EMPTY_PROJECT_STARTER_PROMPTS,
],
githubConnected: [
(s) => [s.githubIntegrations],
(githubIntegrations: IntegrationType[]): boolean => githubIntegrations.length > 0,
],
repositoryCount: [
(s) => [s.githubIntegrations],
(githubIntegrations: IntegrationType[]): number => githubIntegrations.length,
],
reportProperties: [
(s) => [s.currentStep, s.stepIndex, s.isReplay],
(currentStep: OnboardingStep | null, stepIndex: number, isReplay: boolean): OnboardingReportProperties => ({
step_key: currentStep?.key ?? 'unknown',
step_index: stepIndex,
step_count: DEFAULT_ONBOARDING_STEPS.length,
is_replay: isReplay,
}),
],
}),
listeners(({ actions, values }) => ({
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
if (!step || values.viewedStepKeys[step.key]) {
return
}
actions.markStepViewed(step.key)
posthog.capture('posthog ai onboarding step viewed', values.reportProperties)
},
closeOnboarding: () => {
// Which step a user bails on is the segment signal the onboarding research relies on, so the
// 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)
// 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()
}
},
selectStarterPrompt: ({ prompt }) => {
posthog.capture('posthog ai onboarding starter prompt clicked', {
...values.reportProperties,
prompt,
})
// Same org-level AI data-processing gate the other seed producers use: without approval the
// 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 })
if (!values.isReplay) {
actions.markOnboardingSeen()
}
},
clickGithubCta: () => {
posthog.capture('posthog ai onboarding github cta clicked', {
...values.reportProperties,
github_connected: values.githubConnected,
})
},
replayMedia: () => {
posthog.capture('posthog ai onboarding media replayed', values.reportProperties)
},
markOnboardingSeen: () => {
// 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.updateHasSeenProductIntroFor(POSTHOG_AI_ONBOARDING_SEEN_KEY)
},
})),
])