: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, listeners, path, reducers, selectors } from 'kea'
import { router } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
import { SetupTaskId } from 'lib/components/ProductSetup'
import { sceneLogic } from 'scenes/sceneLogic'
import { teamLogic as globalTeamLogic } from 'scenes/teamLogic'
import { ProductKey } from '~/queries/schema/schema-general'
import { ActivationTaskStatus } from '~/types'
import type { AvailableSetupTaskIdsEnumApi } from '../../../generated/core/api.schemas'
import { PRODUCTS_WITH_SETUP } from './productSetupRegistry'
import type { SetupHighlight } from './types'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface globalSetupLogicValues {
location: {
pathname: string
search: string
hash: string
} // router
activeSceneProductKey: ProductKey | null // sceneLogic
availableProducts: ProductKey[]
highlight: SetupHighlight | null
isGlobalModalOpen: boolean
isProductSelectionLocked: boolean
optimisticTaskStatuses: Record<string, ActivationTaskStatus | null>
sceneHasNoSetup: boolean
sceneProductKey: ProductKey | null
selectedProduct: ProductKey
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface globalSetupLogicActions {
clearHighlight: () => {
value: true
}
clearOptimisticTaskStatuses: (taskIds: SetupTaskId[]) => {
taskIds: AvailableSetupTaskIdsEnumApi[]
}
closeGlobalSetup: () => {
value: true
}
markTaskAsCompleted: (taskIdOrIds: SetupTaskId | SetupTaskId[]) => {
taskIdOrIds: AvailableSetupTaskIdsEnumApi | AvailableSetupTaskIdsEnumApi[]
}
markTaskAsSkipped: (taskIdOrIds: SetupTaskId | SetupTaskId[]) => {
taskIdOrIds: AvailableSetupTaskIdsEnumApi | AvailableSetupTaskIdsEnumApi[]
}
openGlobalSetup: () => {
value: true
}
setHighlight: (
selector: string,
pathname: string
) => {
pathname: string
selector: string
}
setOptimisticTaskStatuses: (statuses: Record<string, ActivationTaskStatus | null>) => {
statuses: Record<string, ActivationTaskStatus | null>
}
setSelectedProduct: (productKey: ProductKey) => {
productKey: ProductKey
}
unmarkTaskAsCompleted: (taskIdOrIds: SetupTaskId | SetupTaskId[]) => {
taskIdOrIds: AvailableSetupTaskIdsEnumApi | AvailableSetupTaskIdsEnumApi[]
}
unmarkTaskAsSkipped: (taskIdOrIds: SetupTaskId | SetupTaskId[]) => {
taskIdOrIds: AvailableSetupTaskIdsEnumApi | AvailableSetupTaskIdsEnumApi[]
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface globalSetupLogicMeta {
__keaTypeGenInternalSelectorTypes: {
sceneProductKey: (activeSceneProductKey: ProductKey | null) => ProductKey | null
sceneHasNoSetup: (activeSceneProductKey: ProductKey | null) => boolean
isProductSelectionLocked: (sceneProductKey: ProductKey | null) => boolean
}
}
export type globalSetupLogicType = MakeLogicType<
globalSetupLogicValues,
globalSetupLogicActions,
Record<string, any>,
globalSetupLogicMeta
>
/**
* Global setup logic - the single source of truth for task completion and UI state.
*
* This logic handles:
* 1. Task completion/skipping (called from anywhere via findMounted())
* 2. UI state for the global setup popover (selectedProduct, isGlobalModalOpen)
*
* External logics should call globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(taskId)
* to mark tasks as complete. This updates team.onboarding_tasks and tracks analytics.
*/
export const globalSetupLogic = kea<globalSetupLogicType>([
path(['lib', 'components', 'ProductSetup', 'globalSetupLogic']),
connect(() => ({
values: [router, ['location'], sceneLogic, ['activeSceneProductKey']],
})),
actions({
// Task actions - single source of truth for task state updates
// All actions accept either a single task ID or an array of task IDs
markTaskAsCompleted: (taskIdOrIds: SetupTaskId | SetupTaskId[]) => ({ taskIdOrIds }),
markTaskAsSkipped: (taskIdOrIds: SetupTaskId | SetupTaskId[]) => ({ taskIdOrIds }),
unmarkTaskAsCompleted: (taskIdOrIds: SetupTaskId | SetupTaskId[]) => ({ taskIdOrIds }),
unmarkTaskAsSkipped: (taskIdOrIds: SetupTaskId | SetupTaskId[]) => ({ taskIdOrIds }),
// Internal actions for optimistic updates
// null value means "this task should appear as unmarked"
setOptimisticTaskStatuses: (statuses: Record<string, ActivationTaskStatus | null>) => ({ statuses }),
clearOptimisticTaskStatuses: (taskIds: SetupTaskId[]) => ({ taskIds }),
// UI actions for the global setup popover
setSelectedProduct: (productKey: ProductKey) => ({ productKey }),
openGlobalSetup: true,
closeGlobalSetup: true,
// Element highlighting after navigation
setHighlight: (selector: string, pathname: string) => ({ selector, pathname }),
clearHighlight: true,
}),
reducers({
// Currently selected product in the global setup popover
selectedProduct: [
ProductKey.PRODUCT_ANALYTICS as ProductKey,
{
setSelectedProduct: (_, { productKey }) => productKey,
},
],
// Whether the global setup popover is open
isGlobalModalOpen: [
false,
{
openGlobalSetup: () => true,
closeGlobalSetup: () => false,
},
],
// Element to highlight after navigation, bound to the route that asked for it. An unbound
// highlight outlives its route and pulses whatever matches on a page opened later.
highlight: [
null as SetupHighlight | null,
{
setHighlight: (_, { selector, pathname }) => ({ selector, pathname }),
clearHighlight: () => null,
},
],
// Optimistic task statuses - updated immediately before API call completes
// This allows the UI to respond instantly to user actions
// null means "this task should appear as unmarked" (for undo operations)
optimisticTaskStatuses: [
{} as Record<string, ActivationTaskStatus | null>,
{
setOptimisticTaskStatuses: (state, { statuses }) => ({ ...state, ...statuses }),
clearOptimisticTaskStatuses: (state, { taskIds }) => {
const newState = { ...state }
for (const taskId of taskIds) {
// Set to null instead of deleting - null means "unmarked"
newState[taskId] = null
}
return newState
},
},
],
}),
selectors({
availableProducts: [() => [], () => PRODUCTS_WITH_SETUP],
// The product key from the current scene - filtered to only include products with setup
// Used for auto-selecting the product in the popover
sceneProductKey: [
(s) => [s.activeSceneProductKey],
(activeSceneProductKey: ProductKey | null): ProductKey | null => {
if (activeSceneProductKey && PRODUCTS_WITH_SETUP.includes(activeSceneProductKey)) {
return activeSceneProductKey
}
return null
},
],
// Whether the current scene has a product key that doesn't have setup configured
// Used to hide the Quick Start button on scenes for products without onboarding
sceneHasNoSetup: [
(s) => [s.activeSceneProductKey],
(activeSceneProductKey: ProductKey | null): boolean => {
return activeSceneProductKey !== null && !PRODUCTS_WITH_SETUP.includes(activeSceneProductKey)
},
],
// Whether the product selection is locked to the current scene
isProductSelectionLocked: [
(s) => [s.sceneProductKey],
(sceneProductKey: ProductKey | null) => sceneProductKey !== null,
],
}),
// NOTE: Not using `connect` here because the teamLogic might not have mounted yet
// by the time this logic is mounted
listeners(({ actions, values }) => ({
markTaskAsCompleted: async ({ taskIdOrIds }) => {
const taskIds = Array.isArray(taskIdOrIds) ? taskIdOrIds : [taskIdOrIds]
const teamLogic = globalTeamLogic.findMounted()
if (!teamLogic) {
return
}
const currentTeam = teamLogic.values.currentTeam
if (!currentTeam || !('onboarding_tasks' in currentTeam)) {
return
}
// If all tasks already completed, don't do anything
if (taskIds.every((taskId) => currentTeam.onboarding_tasks?.[taskId] === ActivationTaskStatus.COMPLETED)) {
return
}
// Optimistically update UI immediately
const optimisticStatuses: Record<string, ActivationTaskStatus> = {}
for (const taskId of taskIds) {
optimisticStatuses[taskId] = ActivationTaskStatus.COMPLETED
}
actions.setOptimisticTaskStatuses(optimisticStatuses)
// Only re-open the popover if it was already open — avoids the popover popping
// open uninvited on top of other surfaces (e.g. the welcome dialog) when team
// settings get updated during onboarding and silently complete a task.
if (values.isGlobalModalOpen) {
actions.openGlobalSetup()
}
// Track analytics for each task
for (const taskId of taskIds) {
posthog.capture('product setup task completed', { task: taskId })
}
// Persist to server in the background
const onboardingTasks = { ...currentTeam.onboarding_tasks, ...optimisticStatuses }
teamLogic.actions.updateCurrentTeam({ onboarding_tasks: onboardingTasks })
},
markTaskAsSkipped: async ({ taskIdOrIds }) => {
const taskIds = Array.isArray(taskIdOrIds) ? taskIdOrIds : [taskIdOrIds]
const teamLogic = globalTeamLogic.findMounted()
if (!teamLogic) {
return
}
const currentTeam = teamLogic.values.currentTeam
if (!currentTeam || !('onboarding_tasks' in currentTeam)) {
return
}
// If all tasks already skipped, don't do anything
if (taskIds.every((taskId) => currentTeam.onboarding_tasks?.[taskId] === ActivationTaskStatus.SKIPPED)) {
return
}
// Optimistically update UI immediately
const optimisticStatuses: Record<string, ActivationTaskStatus> = {}
for (const taskId of taskIds) {
optimisticStatuses[taskId] = ActivationTaskStatus.SKIPPED
}
actions.setOptimisticTaskStatuses(optimisticStatuses)
// Track analytics for each task
for (const taskId of taskIds) {
posthog.capture('product setup task skipped', { task: taskId })
}
const onboardingTasks = { ...currentTeam.onboarding_tasks, ...optimisticStatuses }
teamLogic.actions.updateCurrentTeam({ onboarding_tasks: onboardingTasks })
},
unmarkTaskAsCompleted: async ({ taskIdOrIds }) => {
const taskIds = Array.isArray(taskIdOrIds) ? taskIdOrIds : [taskIdOrIds]
// Clear optimistic statuses immediately for instant UI feedback
actions.clearOptimisticTaskStatuses(taskIds)
// Track analytics for each task
for (const taskId of taskIds) {
posthog.capture('product setup task uncompleted', { task: taskId })
}
// Persist to server in the background
const teamLogic = globalTeamLogic.findMounted()
if (!teamLogic) {
return
}
const currentTeam = teamLogic.values.currentTeam
if (!currentTeam || !('onboarding_tasks' in currentTeam)) {
return
}
const onboardingTasks = { ...currentTeam.onboarding_tasks }
for (const taskId of taskIds) {
delete onboardingTasks[taskId]
}
teamLogic.actions.updateCurrentTeam({ onboarding_tasks: onboardingTasks })
},
unmarkTaskAsSkipped: async ({ taskIdOrIds }) => {
const taskIds = Array.isArray(taskIdOrIds) ? taskIdOrIds : [taskIdOrIds]
// Clear optimistic statuses immediately for instant UI feedback
actions.clearOptimisticTaskStatuses(taskIds)
// Track analytics for each task
for (const taskId of taskIds) {
posthog.capture('product setup task unskipped', { task: taskId })
}
// Persist to server in the background
const teamLogic = globalTeamLogic.findMounted()
if (!teamLogic) {
return
}
const currentTeam = teamLogic.values.currentTeam
if (!currentTeam || !('onboarding_tasks' in currentTeam)) {
return
}
const onboardingTasks = { ...currentTeam.onboarding_tasks }
for (const taskId of taskIds) {
delete onboardingTasks[taskId]
}
teamLogic.actions.updateCurrentTeam({ onboarding_tasks: onboardingTasks })
},
})),
subscriptions(({ actions, values }) => ({
// Drop a pending highlight as soon as the user leaves the route that asked for it
location: ({ pathname }: { pathname: string }) => {
if (values.highlight && values.highlight.pathname !== pathname) {
actions.clearHighlight()
}
},
// When the scene product key changes, auto-select it in the popover
sceneProductKey: (sceneProductKey: ProductKey | null) => {
if (sceneProductKey && sceneProductKey !== values.selectedProduct) {
actions.setSelectedProduct(sceneProductKey)
}
},
})),
])