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.

feat(workflows): guide push setup with a checklist and a live device check (#122197)

Daniel Marchuk695081da7915
diff --git a/products/workflows/frontend/setupGuide/wizard/WizardPushStep.tsx b/products/workflows/frontend/setupGuide/wizard/WizardPushStep.tsx
index 987126325d96..91190cabaf9c 100644
--- a/products/workflows/frontend/setupGuide/wizard/WizardPushStep.tsx
+++ b/products/workflows/frontend/setupGuide/wizard/WizardPushStep.tsx
@@ -1,24 +1,71 @@
import { useActions, useValues } from 'kea'
-import { Link } from '@posthog/lemon-ui'
+import { IconAndroid, IconApple, IconCheckCircle } from '@posthog/icons'
+import { LemonSegmentedButton, Link, Spinner } from '@posthog/lemon-ui'
+import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import { SetupTaskId } from 'lib/components/ProductSetup'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { apiHostOrigin } from 'lib/utils/apiHost'
+import { teamLogic } from 'scenes/teamLogic'
import { ChannelCatalogCard } from '../../Channels/ChannelCatalogCard'
import { ChannelSetupModal } from '../../Channels/ChannelSetupModal'
import { summarizeChannel } from '../../Channels/channelSummary'
+import { PushPlatform, pushDeviceCheckLogic } from './pushDeviceCheckLogic'
-const SDK_REQUIREMENTS = [
- { platform: 'iOS', version: '3.69.0' },
- { platform: 'Android', version: '3.58.0' },
- { platform: 'React Native', version: '4.62.0, with @posthog/react-native-plugin' },
- { platform: 'Flutter', version: '5.35.0' },
-]
+const PLATFORMS: Record<PushPlatform, { label: string; provider: 'apns' | 'firebase'; minVersion: string }> = {
+ ios: { label: 'iOS', provider: 'apns', minVersion: '3.69.0' },
+ android: { label: 'Android', provider: 'firebase', minVersion: '3.58.0' },
+}
+
+function sdkSnippet(platform: PushPlatform, token: string, host: string, appId: string | undefined): string {
+ if (platform === 'ios') {
+ return `let config = PostHogConfig(apiKey: "${token}", host: "${host}")
+config.capturePushNotificationSubscriptions = true // on by default
+PostHogSDK.shared.setup(config)
+
+// Ask for permission. The SDK registers the device token for you.
+UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, _ in
+ if granted {
+ DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() }
+ }
+}`
+ }
+ return `val config = PostHogAndroidConfig(apiKey = "${token}", host = "${host}").apply {
+ capturePushNotificationSubscriptions = true // on by default, needs firebase-messaging
+}
+PostHogAndroid.setup(this, config)
+
+// In your FirebaseMessagingService, so a refreshed token registers right away
+override fun onNewToken(token: String) {
+ PostHog.registerPushNotificationToken(token, "${appId ?? '<firebase project id>'}")
+}`
+}
+
+function StepTitle({ index, done, children }: { index: number; done: boolean; children: string }): JSX.Element {
+ return (
+ <div className="flex items-center gap-2">
+ {done ? (
+ <IconCheckCircle className="text-success text-lg shrink-0" />
+ ) : (
+ <span className="flex items-center justify-center size-5 rounded-full border text-xs font-semibold shrink-0">
+ {index}
+ </span>
+ )}
+ <span className="font-semibold">{children}</span>
+ </div>
+ )
+}
export function WizardPushStep(): JSX.Element {
const { integrations, setupModalOpen, setupModalType, selectedIntegration } = useValues(integrationsLogic)
const { closeSetupModal, markTaskAsCompleted } = useActions(integrationsLogic)
+ const { platform, providerConnected, appId, appIds, registeredDeviceCount, deviceRegistered } =
+ useValues(pushDeviceCheckLogic)
+ const { setPlatform } = useActions(pushDeviceCheckLogic)
+ const { currentTeam } = useValues(teamLogic)
+ const { label, provider, minVersion } = PLATFORMS[platform]
return (
<>
@@ -32,38 +79,91 @@ export function WizardPushStep(): JSX.Element {
closeSetupModal()
}}
/>
- <div className="@container flex flex-col gap-4">
- <p className="mb-0 text-secondary">
- Connect the platforms your app runs on. You can connect one now and the other later.
- </p>
- <div className="grid grid-cols-1 gap-3 @2xl:grid-cols-2">
- <ChannelCatalogCard
- channel={summarizeChannel('firebase', integrations ?? [])}
- disabledReason={null}
+ <div className="flex flex-col gap-6" data-attr="workflows-onboarding-wizard-push">
+ <div className="flex flex-wrap items-center gap-3">
+ <span className="font-semibold">Your app runs on</span>
+ <LemonSegmentedButton
+ value={platform}
+ onChange={(value) => setPlatform(value)}
+ options={[
+ { value: 'ios', label: 'iOS', icon: <IconApple />, 'data-attr': 'push-platform-ios' },
+ {
+ value: 'android',
+ label: 'Android',
+ icon: <IconAndroid />,
+ 'data-attr': 'push-platform-android',
+ },
+ ]}
+ size="small"
/>
- <ChannelCatalogCard channel={summarizeChannel('apns', integrations ?? [])} disabledReason={null} />
+ <span className="text-secondary text-sm">On both? Set up one now and the other after.</span>
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <StepTitle index={1} done={providerConnected}>
+ {`Connect ${provider === 'apns' ? 'Apple Push Notifications' : 'Firebase Cloud Messaging'}`}
+ </StepTitle>
+ <div className="ps-7">
+ <ChannelCatalogCard
+ channel={summarizeChannel(provider, integrations ?? [])}
+ disabledReason={null}
+ />
+ </div>
</div>
- <div className="flex flex-col gap-2 rounded border p-4">
- <span className="font-semibold">Add PostHog to your app</span>
- <span className="text-secondary text-sm">
- The PostHog SDK registers each device for push on its own. Your app still needs push set up, and
- it must ask people for permission to send notifications. Use at least these SDK versions:
- </span>
- <ul className="mb-0 list-disc ps-5 text-sm">
- {SDK_REQUIREMENTS.map(({ platform, version }) => (
- <li key={platform}>
- {platform}: {version}
- </li>
- ))}
- </ul>
- <Link
- to="https://posthog.com/docs/workflows/push-notifications"
- target="_blank"
- className="text-sm"
- data-attr="workflows-onboarding-wizard-push-docs"
- >
- Read the push setup guide
- </Link>
+
+ <div className="flex flex-col gap-2">
+ <StepTitle index={2} done={deviceRegistered}>
+ Turn on push in the PostHog SDK
+ </StepTitle>
+ <div className="ps-7 flex flex-col gap-2">
+ <span className="text-secondary text-sm">
+ {`Use the ${label} SDK ${minVersion} or later. Your app still needs push set up, and it must ask people for permission.`}
+ </span>
+ <CodeSnippet language={platform === 'ios' ? Language.Swift : Language.Kotlin} wrap>
+ {sdkSnippet(
+ platform,
+ currentTeam?.api_token ?? '<project token>',
+ apiHostOrigin(),
+ appId ?? undefined
+ )}
+ </CodeSnippet>
+ <span className="text-secondary text-sm">
+ Using React Native or Flutter?{' '}
+ <Link
+ to="https://posthog.com/docs/workflows/push-notifications"
+ target="_blank"
+ data-attr="workflows-onboarding-wizard-push-docs"
+ >
+ Read the push setup guide
+ </Link>
+ .
+ </span>
+ </div>
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <StepTitle index={3} done={deviceRegistered}>
+ Open your app on a device
+ </StepTitle>
+ <div className="ps-7 text-sm" data-attr="workflows-onboarding-wizard-push-device-status">
+ {!providerConnected ? (
+ <span className="text-secondary">
+ {`Devices can register once ${provider === 'apns' ? 'Apple Push Notifications is' : 'Firebase is'} connected.`}
+ </span>
+ ) : deviceRegistered ? (
+ <span>
+ <strong>
+ {registeredDeviceCount === 1 ? '1 person' : `${registeredDeviceCount} people`}
+ </strong>{' '}
+ can get push notifications from this app. You're ready to send.
+ </span>
+ ) : (
+ <span className="flex items-center gap-2 text-secondary">
+ <Spinner textColored />
+ {`Waiting for a device${appIds.length > 1 ? ` on ${appId}` : ''}. Open your app and allow notifications. You can also continue and come back later.`}
+ </span>
+ )}
+ </div>
</div>
</div>
</>
diff --git a/products/workflows/frontend/setupGuide/wizard/pushDeviceCheckLogic.test.ts b/products/workflows/frontend/setupGuide/wizard/pushDeviceCheckLogic.test.ts
new file mode 100644
index 000000000000..7e654e17294c
--- /dev/null
+++ b/products/workflows/frontend/setupGuide/wizard/pushDeviceCheckLogic.test.ts
@@ -0,0 +1,148 @@
+import { expectLogic } from 'kea-test-utils'
+
+import api from 'lib/api'
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+
+import { useMocks } from '~/mocks/jest'
+import type { HogQLQueryResponse } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+import { IntegrationType } from '~/types'
+
+import { pushDeviceCheckLogic } from './pushDeviceCheckLogic'
+
+const PUSH_INTEGRATIONS = [
+ {
+ id: 1,
+ kind: 'apns',
+ display_name: 'APNs',
+ icon_url: '',
+ created_at: '',
+ config: { bundle_id: 'com.example.app' },
+ },
+ {
+ id: 3,
+ kind: 'apns',
+ display_name: 'APNs',
+ icon_url: '',
+ created_at: '',
+ config: { bundle_id: 'com.example.other' },
+ },
+ {
+ id: 2,
+ kind: 'firebase',
+ display_name: 'Firebase',
+ icon_url: '',
+ created_at: '',
+ config: { project_id: 'example-project' },
+ },
+] as IntegrationType[]
+
+function deferredCount(): { promise: Promise<HogQLQueryResponse>; resolve: (count: number) => void } {
+ let resolve: (count: number) => void = () => {}
+ const promise = new Promise<HogQLQueryResponse>((res) => {
+ resolve = (count) => res({ results: [[count]] } as HogQLQueryResponse)
+ })
+ return { promise, resolve }
+}
+
+describe('pushDeviceCheckLogic', () => {
+ let logic: ReturnType<typeof pushDeviceCheckLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/environments/:team_id/integrations': { results: PUSH_INTEGRATIONS, next: null },
+ '/api/projects/:project_id/integrations': { results: PUSH_INTEGRATIONS, next: null },
+ },
+ })
+ initKeaTests()
+ jest.useFakeTimers()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ jest.useRealTimers()
+ jest.restoreAllMocks()
+ })
+
+ it('drops a count for the old platform that arrives after switching platforms', async () => {
+ const iosQuery = deferredCount()
+ const androidQuery = deferredCount()
+ jest.spyOn(api, 'queryHogQL')
+ .mockReturnValueOnce(iosQuery.promise)
+ .mockReturnValueOnce(androidQuery.promise)
+ .mockImplementation(() => new Promise(() => {}))
+
+ logic = pushDeviceCheckLogic()
+ logic.mount()
+ await expectLogic(logic, () => {
+ integrationsLogic.actions.loadIntegrationsSuccess(PUSH_INTEGRATIONS)
+ }).toDispatchActions(['loadRegisteredDeviceCount'])
+ expect(logic.values.platform).toEqual('ios')
+
+ logic.actions.setPlatform('android')
+ androidQuery.resolve(0)
+ await expectLogic(logic).toDispatchActions(['loadRegisteredDeviceCountSuccess'])
+ iosQuery.resolve(3)
+ await Promise.resolve()
+ await Promise.resolve()
+
+ expect(logic.values).toMatchObject({ platform: 'android', registeredDeviceCount: 0, deviceRegistered: false })
+ })
+
+ it('checks one app with a full count, then confirms its recent registrations, one check at a time', async () => {
+ const slowQuery = deferredCount()
+ const queryHogQL = jest
+ .spyOn(api, 'queryHogQL')
+ .mockReturnValueOnce(slowQuery.promise)
+ .mockResolvedValue({ results: [[0]] } as HogQLQueryResponse)
+
+ logic = pushDeviceCheckLogic()
+ logic.mount()
+ await expectLogic(logic, () => {
+ integrationsLogic.actions.loadIntegrationsSuccess(PUSH_INTEGRATIONS)
+ }).toDispatchActions(['loadRegisteredDeviceCount'])
+
+ jest.advanceTimersByTime(30_000)
+ expect(queryHogQL).toHaveBeenCalledTimes(1)
+
+ slowQuery.resolve(0)
+ await expectLogic(logic).toDispatchActions(['loadRegisteredDeviceCountSuccess'])
+ jest.advanceTimersByTime(5_000)
+ expect(queryHogQL).toHaveBeenCalledTimes(2)
+
+ const [fullCount, recentCheck] = queryHogQL.mock.calls.map(([query]) => String(query))
+ expect(logic.values.appId).toEqual('com.example.app')
+ expect(fullCount).toContain('FROM persons')
+ expect(recentCheck).toContain('FROM events')
+ for (const query of [fullCount, recentCheck]) {
+ expect(query).toContain("'$device_push_subscription_com.example.app'")
+ expect(query).not.toContain('com.example.other')
+ }
+ await expectLogic(logic).toDispatchActions(['loadRegisteredDeviceCountSuccess'])
+
+ // A registration event lands before its person row, which looks the same as a device that unsubscribed.
+ const registrationEvents = 1
+ let subscribedPersons = 0
+ queryHogQL.mockImplementation((query) =>
+ Promise.resolve({
+ results: [[String(query).includes('FROM persons') ? subscribedPersons : registrationEvents]],
+ } as HogQLQueryResponse)
+ )
+ const personScans = (): number =>
+ queryHogQL.mock.calls.filter(([query]) => String(query).includes('FROM persons')).length
+ const runCheck = async (): Promise<void> => {
+ jest.advanceTimersByTime(30_000)
+ await expectLogic(logic).toDispatchActions(['loadRegisteredDeviceCountSuccess'])
+ }
+ await runCheck()
+ await runCheck()
+ expect(personScans()).toEqual(2)
+ expect(logic.values.deviceRegistered).toEqual(false)
+
+ subscribedPersons = 1
+ await runCheck()
+ expect(personScans()).toEqual(3)
+ expect(logic.values).toMatchObject({ registeredDeviceCount: 1, deviceRegistered: true })
+ })
+})
diff --git a/products/workflows/frontend/setupGuide/wizard/pushDeviceCheckLogic.ts b/products/workflows/frontend/setupGuide/wizard/pushDeviceCheckLogic.ts
new file mode 100644
index 000000000000..413f5e1e422a
--- /dev/null
+++ b/products/workflows/frontend/setupGuide/wizard/pushDeviceCheckLogic.ts
@@ -0,0 +1,271 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+
+import api from 'lib/api'
+import { dayjs } from 'lib/dayjs'
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+
+import { hogql } from '~/queries/utils'
+import { IntegrationType } from '~/types'
+
+export type PushPlatform = 'ios' | 'android'
+
+// Mirrors DEVICE_SUBSCRIPTION_PREFIX in nodejs/src/cdp/utils/push-subscription-utils.ts.
+const DEVICE_SUBSCRIPTION_PREFIX = '$device_push_subscription_'
+const DEVICE_POLL_INTERVAL_MS = 5000
+const MAX_DEVICE_POLL_INTERVAL_MS = 30_000
+const POLLS_PER_INTERVAL_STEP = 12
+const MAX_BACKOFF_STEPS = 4
+// Covers clock skew and ingestion lag between the full count and the first look at recent events.
+const RECENT_REGISTRATION_MARGIN_MINUTES = 10
+const PERSONS_RECHECK_INTERVAL_MS = 60_000
+
+const PROVIDER_FOR_PLATFORM: Record<PushPlatform, 'apns' | 'firebase'> = {
+ ios: 'apns',
+ android: 'firebase',
+}
+
+function pushAppId(integration: IntegrationType): string | null {
+ const appId = integration.kind === 'apns' ? integration.config?.bundle_id : integration.config?.project_id
+ return typeof appId === 'string' && appId ? appId : null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pushDeviceCheckLogicValues {
+ integrations: IntegrationType[] | null // integrationsLogic
+ appId: string | null
+ appIds: string[]
+ deviceRegistered: boolean
+ platform: PushPlatform
+ providerConnected: boolean
+ providerIntegrations: IntegrationType[]
+ pushIntegrations: IntegrationType[]
+ registeredDeviceCount: number | null
+ registeredDeviceCountLoading: boolean
+ selectedPlatform: PushPlatform | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pushDeviceCheckLogicActions {
+ loadIntegrationsSuccess: (
+ integrations: IntegrationType[],
+ payload?: any
+ ) => {
+ integrations: IntegrationType[]
+ payload?: any
+ } // integrationsLogic
+ loadRegisteredDeviceCount: (_?: any) => any
+ loadRegisteredDeviceCountFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadRegisteredDeviceCountSuccess: (
+ registeredDeviceCount: number | null,
+ payload?: any
+ ) => {
+ registeredDeviceCount: number | null
+ payload?: any
+ }
+ setPlatform: (platform: PushPlatform) => {
+ platform: PushPlatform
+ }
+ syncPolling: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pushDeviceCheckLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ pushIntegrations: (integrations: IntegrationType[] | null) => IntegrationType[]
+ platform: (selectedPlatform: PushPlatform | null, pushIntegrations: IntegrationType[]) => PushPlatform
+ providerIntegrations: (pushIntegrations: IntegrationType[], platform: PushPlatform) => IntegrationType[]
+ providerConnected: (providerIntegrations: IntegrationType[]) => boolean
+ appIds: (providerIntegrations: IntegrationType[]) => string[]
+ appId: (appIds: string[]) => string | null
+ deviceRegistered: (registeredDeviceCount: number | null) => boolean
+ }
+}
+
+export type pushDeviceCheckLogicType = MakeLogicType<
+ pushDeviceCheckLogicValues,
+ pushDeviceCheckLogicActions,
+ Record<string, any>,
+ pushDeviceCheckLogicMeta
+>
+
+export const pushDeviceCheckLogic = kea<pushDeviceCheckLogicType>([
+ path(['products', 'workflows', 'frontend', 'setupGuide', 'wizard', 'pushDeviceCheckLogic']),
+ connect(() => ({
+ values: [integrationsLogic, ['integrations']],
+ actions: [integrationsLogic, ['loadIntegrationsSuccess']],
+ })),
+ actions({
+ setPlatform: (platform: PushPlatform) => ({ platform }),
+ syncPolling: true,
+ }),
+ reducers({
+ selectedPlatform: [
+ null as PushPlatform | null,
+ {
+ setPlatform: (_, { platform }) => platform,
+ },
+ ],
+ }),
+ loaders(({ values, cache }) => ({
+ registeredDeviceCount: [
+ null as number | null,
+ {
+ loadRegisteredDeviceCount: async (_ = null, breakpoint): Promise<number | null> => {
+ const appId = values.appId
+ if (!appId) {
+ return 0
+ }
+ const legacyKey = `${DEVICE_SUBSCRIPTION_PREFIX}${appId}`
+ const tags = { productKey: 'workflows', scene: 'Workflows', name: 'push_setup_registered_devices' }
+ // The default refresh mode serves a cached count for hours, so a new device would never show.
+ const refresh = { refresh: 'force_blocking' as const }
+ // Match the key or the key plus `:`, so `com.app` never counts devices of `com.app.dev`.
+ const countSubscribedPersons = async (): Promise<number> => {
+ const response = await api.queryHogQL<[number][]>(
+ hogql`SELECT count() FROM persons WHERE arrayExists(key -> key = ${legacyKey} OR startsWith(key, ${`${legacyKey}:`}), JSONExtractKeys(properties))`,
+ tags,
+ refresh
+ )
+ breakpoint()
+ return response.results?.[0]?.[0] ?? 0
+ }
+ if (cache.countedAppId !== appId) {
+ const since = dayjs().subtract(RECENT_REGISTRATION_MARGIN_MINUTES, 'minute')
+ const count = await countSubscribedPersons()
+ cache.countedAppId = appId
+ cache.recentSince = since
+ cache.checkedRegistrations = 0
+ cache.personsCheckedAt = Date.now()
+ cache.successfulChecks = 0
+ return count
+ }
+ // The person scan above found no device, so only a registration since then can change the answer.
+ const response = await api.queryHogQL<[number][]>(
+ hogql`SELECT count() FROM events WHERE event = '$set' AND timestamp >= ${cache.recentSince} AND arrayExists(key -> key = ${legacyKey} OR startsWith(key, ${`${legacyKey}:`}), JSONExtractKeys(properties.$set))`,
+ { ...tags, name: 'push_setup_recent_device_registrations' },
+ refresh
+ )
+ breakpoint()
+ const registrations = response.results?.[0]?.[0] ?? 0
+ // A person row can land after its event, so an unconfirmed registration is rechecked, at most once a minute.
+ const recheckDue =
+ registrations > 0 && Date.now() - cache.personsCheckedAt >= PERSONS_RECHECK_INTERVAL_MS
+ if (registrations <= cache.checkedRegistrations && !recheckDue) {
+ return 0
+ }
+ // A registration event stays after the device unsubscribes, so the person count decides.
+ const count = await countSubscribedPersons()
+ cache.checkedRegistrations = registrations
+ cache.personsCheckedAt = Date.now()
+ return count
+ },
+ },
+ ],
+ })),
+ reducers({
+ registeredDeviceCount: {
+ setPlatform: () => null,
+ },
+ }),
+ selectors({
+ pushIntegrations: [
+ (s) => [s.integrations],
+ (integrations: IntegrationType[] | null): IntegrationType[] =>
+ integrations?.filter((integration) => integration.kind === 'apns' || integration.kind === 'firebase') ??
+ [],
+ ],
+ platform: [
+ (s) => [s.selectedPlatform, s.pushIntegrations],
+ (selectedPlatform: PushPlatform | null, pushIntegrations: IntegrationType[]): PushPlatform =>
+ selectedPlatform ??
+ (pushIntegrations.some((integration) => integration.kind === 'firebase') &&
+ !pushIntegrations.some((integration) => integration.kind === 'apns')
+ ? 'android'
+ : 'ios'),
+ ],
+ providerIntegrations: [
+ (s) => [s.pushIntegrations, s.platform],
+ (pushIntegrations: IntegrationType[], platform: PushPlatform): IntegrationType[] =>
+ pushIntegrations.filter((integration) => integration.kind === PROVIDER_FOR_PLATFORM[platform]),
+ ],
+ providerConnected: [
+ (s) => [s.providerIntegrations],
+ (providerIntegrations: IntegrationType[]): boolean => providerIntegrations.length > 0,
+ ],
+ appIds: [
+ (s) => [s.providerIntegrations],
+ (providerIntegrations: IntegrationType[]): string[] =>
+ providerIntegrations.map(pushAppId).filter((appId): appId is string => appId !== null),
+ ],
+ // The snippet and the device check both use this one app, so a device on another app never marks it ready.
+ appId: [(s) => [s.appIds], (appIds: string[]): string | null => appIds[0] ?? null],
+ deviceRegistered: [(s) => [s.registeredDeviceCount], (count: number | null): boolean => (count ?? 0) > 0],
+ }),
+ listeners(({ actions, values, cache }) => {
+ const shouldPoll = (): boolean => values.providerConnected && !values.deviceRegistered
+ const scheduleNextCheck = (delayMs: number): void => {
+ cache.checkScheduled = true
+ cache.disposables.add(() => {
+ const timer = window.setTimeout(() => {
+ cache.checkScheduled = false
+ actions.loadRegisteredDeviceCount()
+ }, delayMs)
+ return () => window.clearTimeout(timer)
+ }, 'devicePoll')
+ }
+ const stopChecking = (): void => {
+ cache.checkScheduled = false
+ cache.disposables.dispose('devicePoll')
+ }
+
+ return {
+ syncPolling: () => {
+ if (!shouldPoll()) {
+ stopChecking()
+ } else if (!cache.checkScheduled && !values.registeredDeviceCountLoading) {
+ actions.loadRegisteredDeviceCount()
+ }
+ },
+ setPlatform: () => {
+ stopChecking()
+ cache.failedChecks = 0
+ // Also supersedes a check still running for the old platform, so its count is dropped.
+ actions.loadRegisteredDeviceCount()
+ },
+ loadIntegrationsSuccess: () => actions.syncPolling(),
+ loadRegisteredDeviceCountSuccess: ({ registeredDeviceCount }) => {
+ cache.failedChecks = 0
+ cache.successfulChecks = (cache.successfulChecks ?? 0) + 1
+ if (registeredDeviceCount) {
+ // pinned: analytics event name - renaming breaks dashboards
+ posthog.capture('workflows onboarding wizard push device detected', { platform: values.platform })
+ }
+ if (shouldPoll()) {
+ const step = Math.floor(cache.successfulChecks / POLLS_PER_INTERVAL_STEP)
+ scheduleNextCheck(Math.min(DEVICE_POLL_INTERVAL_MS * 2 ** step, MAX_DEVICE_POLL_INTERVAL_MS))
+ } else {
+ stopChecking()
+ }
+ },
+ loadRegisteredDeviceCountFailure: () => {
+ cache.failedChecks = (cache.failedChecks ?? 0) + 1
+ if (shouldPoll()) {
+ scheduleNextCheck(DEVICE_POLL_INTERVAL_MS * 2 ** Math.min(cache.failedChecks, MAX_BACKOFF_STEPS))
+ }
+ },
+ }
+ }),
+ afterMount(({ actions }) => {
+ actions.syncPolling()
+ }),
+])