: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 { router } from 'kea-router'
import posthog from 'posthog-js'
import { SetupTaskId } from 'lib/components/ProductSetup'
import { inviteLogic } from 'lib/logic/inviteLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { organizationLogic } from 'scenes/organizationLogic'
import { teamLogic } from 'scenes/teamLogic'
import { ProductKey } from '~/queries/schema/schema-general'
import { ActivationTaskStatus } from '~/types'
import type { AvailableSetupTaskIdsEnumApi } from '../../../generated/core/api.schemas'
import type { TeamPublicType, TeamType } from '../../../types'
import { reverseProxyCheckerLogic } from '../ReverseProxyChecker/reverseProxyCheckerLogic'
import { globalSetupLogic } from './globalSetupLogic'
import { getProductSetupConfig, getTasksForProduct } from './productSetupRegistry'
import type { SetupTaskWithState } from './types'
import type { ProductSetupConfig, SetupTask } from './types'
export interface ProductSetupLogicProps {
productKey: ProductKey
}
const DISMISSED_STORAGE_KEY = 'posthog_product_setup_dismissed'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productSetupLogicValues {
optimisticTaskStatuses: Record<string, ActivationTaskStatus | null> // globalSetupLogic
isCurrentOrganizationNew: boolean // organizationLogic
isCloudOrDev: boolean | undefined // preflightLogic
hasReverseProxy: boolean | null // reverseProxyCheckerLogic
currentTeam: TeamPublicType | TeamType | null // teamLogic
activeTasks: SetupTaskWithState[]
allTasks: SetupTask[]
completedCount: number
completedTasks: SetupTaskWithState[]
completionPercent: number
firstAvailableTask: SetupTaskWithState | null
isDismissed: boolean
isSetupComplete: boolean
productConfig: ProductSetupConfig | null
remainingCount: number
savedOnboardingTasks: Record<string, ActivationTaskStatus | null>
shouldShowSetup: boolean
showCelebration: boolean
skippedTasks: SetupTaskWithState[]
tasksWithState: SetupTaskWithState[]
totalTasks: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productSetupLogicActions {
clearHighlight: () => {
value: true
} // globalSetupLogic
closeGlobalSetup: () => {
value: true
} // globalSetupLogic
markTaskAsCompleted: (taskIdOrIds: SetupTaskId | SetupTaskId[]) => {
taskIdOrIds: AvailableSetupTaskIdsEnumApi | AvailableSetupTaskIdsEnumApi[]
} // globalSetupLogic
markTaskAsSkipped: (taskIdOrIds: SetupTaskId | SetupTaskId[]) => {
taskIdOrIds: AvailableSetupTaskIdsEnumApi | AvailableSetupTaskIdsEnumApi[]
} // globalSetupLogic
openGlobalSetup: () => {
value: true
} // globalSetupLogic
setHighlight: (
selector: string,
pathname: string
) => {
pathname: string
selector: string
} // globalSetupLogic
unmarkTaskAsCompleted: (taskIdOrIds: SetupTaskId | SetupTaskId[]) => {
taskIdOrIds: AvailableSetupTaskIdsEnumApi | AvailableSetupTaskIdsEnumApi[]
} // globalSetupLogic
unmarkTaskAsSkipped: (taskIdOrIds: SetupTaskId | SetupTaskId[]) => {
taskIdOrIds: AvailableSetupTaskIdsEnumApi | AvailableSetupTaskIdsEnumApi[]
} // globalSetupLogic
showInviteModal: () => {
value: true
} // inviteLogic
dismissSetup: () => {
value: true
}
loadCompletionData: () => {
value: true
}
runTask: (taskId: SetupTaskId) => {
taskId: AvailableSetupTaskIdsEnumApi
}
setExpandedTaskId: (taskId: SetupTaskId | null) => {
taskId: AvailableSetupTaskIdsEnumApi | null
}
setShowCelebration: (show: boolean) => {
show: boolean
}
undismissSetup: () => {
value: true
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productSetupLogicMeta {
key: ProductKey
__keaTypeGenInternalSelectorTypes: {
productConfig: (productKey: ProductKey) => ProductSetupConfig | null
allTasks: (productKey: ProductKey, isCloudOrDev: boolean | undefined) => SetupTask[]
savedOnboardingTasks: (
currentTeam: TeamPublicType | TeamType | null,
optimisticTaskStatuses: Record<string, ActivationTaskStatus | null>
) => Record<string, ActivationTaskStatus | null>
tasksWithState: (
allTasks: SetupTask[],
savedOnboardingTasks: Record<string, ActivationTaskStatus | null>,
hasReverseProxy: boolean | null,
currentTeam: TeamPublicType | TeamType | null
) => SetupTaskWithState[]
activeTasks: (tasksWithState: SetupTaskWithState[]) => SetupTaskWithState[]
completedTasks: (tasksWithState: SetupTaskWithState[]) => SetupTaskWithState[]
skippedTasks: (tasksWithState: SetupTaskWithState[]) => SetupTaskWithState[]
totalTasks: (tasksWithState: SetupTaskWithState[]) => number
completedCount: (completedTasks: SetupTaskWithState[], skippedTasks: SetupTaskWithState[]) => number
remainingCount: (activeTasks: SetupTaskWithState[]) => number
completionPercent: (completedCount: number, totalTasks: number) => number
isSetupComplete: (remainingCount: number) => boolean
shouldShowSetup: (
isSetupComplete: boolean,
productConfig: ProductSetupConfig | null,
isCurrentOrganizationNew: boolean
) => boolean
firstAvailableTask: (activeTasks: SetupTaskWithState[]) => SetupTaskWithState | null
}
}
export type productSetupLogicType = MakeLogicType<
productSetupLogicValues,
productSetupLogicActions,
ProductSetupLogicProps,
productSetupLogicMeta
>
/**
* Product setup logic - handles product-specific state and UI for the setup experience.
*
* This logic is keyed by productKey and handles:
* 1. Reading task state (selectors derive from team.onboarding_tasks)
* 2. Running task actions (navigation, opening modals, etc.)
* 3. Product-specific UI state (isDismissed)
* 4. Product-specific loaders (customEventsCount, hasSentAIEvent)
*
* Task completion is handled by globalSetupLogic - this logic just reads and displays state.
*/
export const productSetupLogic = kea<productSetupLogicType>([
path((key) => ['lib', 'components', 'ProductSetup', 'productSetupLogic', key]),
props({} as ProductSetupLogicProps),
key((props) => props.productKey),
connect(() => ({
values: [
teamLogic,
['currentTeam'],
reverseProxyCheckerLogic,
['hasReverseProxy'],
organizationLogic,
['isCurrentOrganizationNew'],
preflightLogic,
['isCloudOrDev'],
globalSetupLogic,
['optimisticTaskStatuses'],
],
actions: [
inviteLogic,
['showInviteModal'],
globalSetupLogic,
[
'openGlobalSetup',
'closeGlobalSetup',
'markTaskAsCompleted',
'unmarkTaskAsCompleted',
'markTaskAsSkipped',
'unmarkTaskAsSkipped',
'setHighlight',
'clearHighlight',
],
],
})),
actions({
// Task execution action
runTask: (taskId: SetupTaskId) => ({ taskId }),
// UI actions
setExpandedTaskId: (taskId: SetupTaskId | null) => ({ taskId }),
dismissSetup: true,
undismissSetup: true,
setShowCelebration: (show: boolean) => ({ show }),
// Data loading triggers
loadCompletionData: true,
}),
reducers(({ props }) => ({
isDismissed: [
false,
{ persist: true, prefix: `${DISMISSED_STORAGE_KEY}_${props.productKey}` },
{
dismissSetup: () => true,
undismissSetup: () => false,
},
],
showCelebration: [
false,
{
setShowCelebration: (_, { show }) => show,
},
],
})),
selectors({
productConfig: [(_, p) => [p.productKey], (productKey: ProductKey) => getProductSetupConfig(productKey)],
allTasks: [
(s, p) => [p.productKey, s.isCloudOrDev],
(productKey: ProductKey, isCloudOrDev: boolean | undefined) => {
const tasks = getTasksForProduct(productKey)
if (!isCloudOrDev) {
return tasks.filter((task) => task.id !== SetupTaskId.SetUpReverseProxy)
}
return tasks
},
],
// Merge server-saved tasks with optimistic updates (optimistic takes priority for instant feedback)
// null in optimistic means "unmarked" - takes priority over saved status
savedOnboardingTasks: [
(s) => [s.currentTeam, s.optimisticTaskStatuses],
(
currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType,
optimisticTaskStatuses: Record<string, ActivationTaskStatus | null>
): Record<string, ActivationTaskStatus | null> => ({
...currentTeam?.onboarding_tasks,
...optimisticTaskStatuses,
}),
],
tasksWithState: [
(s) => [s.allTasks, s.savedOnboardingTasks, s.hasReverseProxy, s.currentTeam],
(
allTasks: import('lib/components/ProductSetup').SetupTask[],
savedOnboardingTasks: Record<string, ActivationTaskStatus | null>,
hasReverseProxy: boolean | null,
currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType
): SetupTaskWithState[] => {
// A task auto-completes when a team flag already proves it is done, even without a saved status.
const isAutoCompleted = (taskId: SetupTaskId): boolean => {
if (taskId === SetupTaskId.SetUpReverseProxy && hasReverseProxy) {
return true
}
// The install page reads `ingested_event`, so the checklist must trust the same flag.
if (taskId === SetupTaskId.IngestFirstEvent && currentTeam?.ingested_event) {
return true
}
return false
}
// Resolve completion for any task id, including a dependency that this product's list does not
// show, so the checkmark and the dependency gate read one completion rule.
const isCompleted = (taskId: SetupTaskId): boolean =>
isAutoCompleted(taskId) || savedOnboardingTasks[taskId] === ActivationTaskStatus.COMPLETED
// Completion wins over a stale skip: a task the user skipped but later actually finished is
// genuinely done, so it counts once instead of as both completed and skipped.
const isSkipped = (taskId: SetupTaskId): boolean =>
!isCompleted(taskId) && savedOnboardingTasks[taskId] === ActivationTaskStatus.SKIPPED
return allTasks.map((task) => {
// A dependency is satisfied when it is completed or skipped, even when the dependency is not
// itself one of this product's tasks. This matches the checkmark rule.
let lockedReason: string | undefined
if (task.dependsOn) {
for (const depId of task.dependsOn) {
if (!isCompleted(depId) && !isSkipped(depId)) {
const depTask = allTasks.find((t) => t.id === depId)
lockedReason = depTask
? `Complete "${depTask.title}" first`
: 'Complete dependencies first'
break
}
}
}
return {
...task,
completed: isCompleted(task.id),
skipped: isSkipped(task.id),
lockedReason,
}
})
},
],
activeTasks: [
(s) => [s.tasksWithState],
(tasks: SetupTaskWithState[]) => tasks.filter((task) => !task.completed && !task.skipped),
],
completedTasks: [
(s) => [s.tasksWithState],
(tasks: SetupTaskWithState[]) => tasks.filter((task) => task.completed),
],
skippedTasks: [
(s) => [s.tasksWithState],
(tasks: SetupTaskWithState[]) => tasks.filter((task) => task.skipped),
],
totalTasks: [(s) => [s.tasksWithState], (tasks: SetupTaskWithState[]) => tasks.length],
completedCount: [
(s) => [s.completedTasks, s.skippedTasks],
(completed: SetupTaskWithState[], skipped: SetupTaskWithState[]) => completed.length + skipped.length,
],
remainingCount: [(s) => [s.activeTasks], (tasks: SetupTaskWithState[]) => tasks.length],
completionPercent: [
(s) => [s.completedCount, s.totalTasks],
(completed: number, total: number) => {
if (total === 0) {
return 100
}
const percent = Math.round((completed / total) * 100)
return percent >= 5 ? percent : 5 // Min 5% for visibility
},
],
isSetupComplete: [(s) => [s.remainingCount], (remaining: number) => remaining === 0],
shouldShowSetup: [
(s) => [s.isSetupComplete, s.productConfig, s.isCurrentOrganizationNew],
(
isComplete: boolean,
config: null | import('lib/components/ProductSetup').ProductSetupConfig,
isNewOrg: boolean
) => {
// Don't show if no valid config
if (!config || !config.title) {
return false
}
// Don't show for organizations older than 3 months
if (!isNewOrg) {
return false
}
// Don't show if all tasks are complete
return !isComplete
},
],
firstAvailableTask: [
(s) => [s.activeTasks],
(tasks: SetupTaskWithState[]) => tasks.find((t) => !t.lockedReason) ?? null,
],
}),
listeners(({ props, actions, values }) => ({
runTask: async ({ taskId }) => {
const task = values.tasksWithState.find((t) => t.id === taskId)
if (!task) {
return
}
posthog.capture('product setup task run', {
product: props.productKey,
task: taskId,
task_type: task.taskType,
destination: task.getUrl ? 'internal' : task.docsUrl ? 'docs' : 'none',
has_target_selector: !!task.targetSelector,
})
// Each run owns the highlight - a task with no selector must not leave the
// previous one polling
actions.clearHighlight()
// Special cases that need non-navigation actions
switch (taskId) {
case SetupTaskId.SetUpWebAnalyticsConversionGoals:
// Click the filters button after navigation to reveal the conversion goal
// (it's inside a popover in the condensed filter bar)
setTimeout(() => {
const filtersButton = document.querySelector<HTMLElement>(
'[data-attr="web-analytics-unified-filters"]'
)
filtersButton?.click()
}, 300)
break
}
// Use task's getUrl if available, otherwise fall back to docsUrl
if (task.getUrl) {
// Close modal before internal navigation (keeps the full "Quick start" button visible)
actions.closeGlobalSetup()
router.actions.push(task.getUrl())
} else if (task.docsUrl) {
// Keep modal open for external docs links
window.open(task.docsUrl, '_blank')
}
// Bind the highlight to the route we landed on, so it cannot pulse an element
// on a page the user goes to later
if (task.targetSelector) {
actions.setHighlight(task.targetSelector, router.values.location.pathname)
}
},
dismissSetup: () => {
posthog.capture('product setup dismissed', {
product: props.productKey,
completed_count: values.completedCount,
total_count: values.totalTasks,
})
},
})),
])