: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
feat(wizard): restore cloud runs in onboarding (#126677)
Fernando Gomes8fdd9b504e78
diff --git a/docs/internal/wizard-runs.md b/docs/internal/wizard-runs.mdindex f686fcc49591..6a5da6c209db 100644--- a/docs/internal/wizard-runs.md+++ b/docs/internal/wizard-runs.md@@ -79,6 +79,15 @@ Run details load only tasks into shared state and use the dialog's existing arti### Onboarding state+The boolean flag `wizard-onboarding-cloud-runs-enabled` adds cloud and local tabs to both the standard and simple installation steps.+Cloud setup also requires `wizard_cloud_run_available` and a Cloud or development instance.+Users connect GitHub, select a repository, and start the `posthog-integration` program through the Wizard Runs API.+GitHub authorization returns to the active installation step.+Creation retries use the same idempotency key until the repository changes or the request succeeds.+The creation response enters shared run state immediately, so progress and Continue do not wait for discovery.+Disabling the flag hides new cloud setup controls but keeps existing run progress and results visible.+Dedicated program steps continue to use their local commands.+Entering onboarding records its start time in local storage, scoped to the project and user.The initial time uses the server's HTTP Date header to avoid browser clock skew, falling back to browser time when unavailable.Only `posthog-integration` runs created at or after that time can replace the installation instructions.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex b98ccb4ea752..a55c2f29e074 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8391,7 +8391,7 @@ snapshots:products-wizard-wizard-run-sidebar-widget--many-runs--light:hash: v1.k794b7964.b36b26edaea9e4b38ea4d4e58b5a8f96e67a76c9d1ed3fb3b0da2f221b8df4e1.s5s9k4NPEkAorFYD0q7WHZ5fxKb3mgiwCLCjGb7HWiIproducts-wizard-wizard-run-sidebar-widget--mixed-statuses--dark:- hash: v1.k794b7964.a568aab28324a5f6fcc42c27af3b986d83f5eb4d0924be41994370dc528e65ca.UHX2cTU9fzVL5Y7y9EZzxH1ELnofkekAyF3THV6pZZM+ hash: v1.k794b7964.2f3c6f3897e172d853d84d0a1d23ccbc62d34df0d899e74a74af0b28fcb37acb.TwQh7FEaJJn9dzJF1GYxQNW2FadsNmW8_2OL7mX8vuMproducts-wizard-wizard-run-sidebar-widget--mixed-statuses--light:hash: v1.k794b7964.578af0b3a9070e00ab4bd95296c174b8b34a7201a5c6cb91a986203af5b66261.5KQ_TlQjfAIBBrbMAGW7VfPWw9fOVNuLpQUwPW2VRyIproducts-wizard-wizard-run-sidebar-widget--multiple-runs--dark:@@ -8403,7 +8403,7 @@ snapshots:products-wizard-wizard-run-sidebar-widget--multiple-runs-hovered--light:hash: v1.k794b7964.6aca699d79bb0dfc80da9305fd8d3c82bf382b4a49f15ae7168d614f8d79139e.YUrKHRPcUUmFf1OpzXRa9ye6ztFFnIA19Xv5W3dDaU4products-wizard-wizard-run-sidebar-widget--multiple-runs-menu-open--dark:- hash: v1.k794b7964.8351d7be45e20c07f1d4c84c7a10801ed43f9fd6545d685507f48c11f0661065.9xzyvC-XzptsaN8OBJROP1gALNCtrKUUSPj2br7BwNU+ hash: v1.k794b7964.26e0d00f12ec11d1fac80a9f6a7070d9f13502a45b803aacb2ae25af2b0bdfdc.HGN_qi6x788DGkNXUWa8u8oQaaKWfASDzJXKmfLbJxEproducts-wizard-wizard-run-sidebar-widget--multiple-runs-menu-open--light:hash: v1.k794b7964.fba9d9d30be910c963a0e7855d175096d3fee41ce157c951149d7a6bd6619f45.gQcXbkwPBk3qcm15uqsLpvTxCY3z6GmBuRLoR9F8yYsproducts-wizard-wizard-run-sidebar-widget--running-stage--dark:@@ -16942,10 +16942,18 @@ snapshots:hash: v1.k794b7964.4035744269184179fc704886ada21debba6c2d8da34866ded90124cc4381955d.gw_mH1sCBx8KU1Fw775gxqvTtxDt8oiQbZ3gEoXDmAAscenes-other-onboarding--workflows-custom-installation-instructions--light:hash: v1.k794b7964.589ec185861125f8803b2fc4e5a79d37fe0577663ef494384f2f5e29b3ccbfcb.EIRXV0l8SHGIJjTAfJZM4ppFd57VW3GT36oKO2bhnLs+ scenes-other-onboarding-install-step--cloud-setup--dark:+ hash: v1.k794b7964.e16e15278ac6e7796143289e7ef98fcea4edcc5ddce6287c5e1d2b0efcaef3ef.oLFAJmSpkoXRazIwPJBS6URhjQc33i7byYH3sn_n6cQ+ scenes-other-onboarding-install-step--cloud-setup--light:+ hash: v1.k794b7964.d5c8bab903b7c00ea1637aadcb42d064eb6e0b7dfd606180a64661da1d92e6e4.zyI-LVRJB4sTsGSW4h5jtZVyEK0_CQnV9T9bz0KTRbIscenes-other-onboarding-install-step--control-arm--dark:hash: v1.k794b7964.85785893b3ee1b41fe89fe73f4074da2f8e08722e4d375dd5301b7033a25660b.8cH01aW_wdljbt8NM5-4YqII7hLHyUIPdAd2DztcRDUscenes-other-onboarding-install-step--control-arm--light:hash: v1.k794b7964.f7351fd5520acef75c9b259b944526603762f6e9e482a94ec56819e2b24ca763.2w9awJZwfumhgF4p5zgQwscMAWuXg2iImb-0IBeDfkg+ scenes-other-onboarding-install-step--simple-cloud-setup--dark:+ hash: v1.k794b7964.02a2ab2f2914eb510613f2ecc023aa79f87d13447383bbb7ab985c5fceb27a07.RndnGzpjr0b-lhaRFL2-fSkfYDn4dmELMNhx-OZXtjU+ scenes-other-onboarding-install-step--simple-cloud-setup--light:+ hash: v1.k794b7964.780a7eda57f684e6e8c0e54d52523c6df0f8e7916cb49bbd4e549f7f2513eb3f.3Nd71rFvRFCXzMxxrHzWk_VS2SqLIG34xwDmqjsD55sscenes-other-onboarding-install-step--simple-flow--dark:hash: v1.k794b7964.82e295b93aca26c287b4207345daa25386169a22f859bcf6ffc826dc119fe753.gcs2PUEkwq8sVKLDiV89qsV53RH8PgsAaC1iPJ9WQ04scenes-other-onboarding-install-step--simple-flow--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 814914b9e386..a3ba54a3eb73 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -613,6 +613,7 @@ export const FEATURE_FLAGS = {WEB_ANALYTICS_TILE_HEADER_V2: 'web-analytics-tile-header-v2', // owner: @jordanm-posthog #team-web-analytics multivariate=control,testWEB_ANALYTICS_TILE_SKELETONS: 'web-analytics-tile-skeletons', // owner: @jordanm-posthog #team-web-analyticsWEB_ANALYTICS_TILE_TOGGLES: 'web-analytics-tile-toggles', // owner: @lricoy #team-web-analytics+ WIZARD_ONBOARDING_CLOUD_RUNS_ENABLED: 'wizard-onboarding-cloud-runs-enabled',WIZARD_UI_ENABLED: 'wizard-ui-enabled', // owner: @fercgomes #team-growth — gates the /wizard/runs interfaceWORKFLOW_ADD_TO_STATIC_COHORT_ACTION: 'workflow-add-to-static-cohort-action', // owner: #team-workflowsWORKFLOW_CLASSIFY_ACTION: 'workflow-classify-action', // owner: #team-workflowsdiff --git a/frontend/src/scenes/onboarding/onboardingLogic.test.ts b/frontend/src/scenes/onboarding/onboardingLogic.test.tsindex b62fade3da4e..0cca04fbb799 100644--- a/frontend/src/scenes/onboarding/onboardingLogic.test.ts+++ b/frontend/src/scenes/onboarding/onboardingLogic.test.ts@@ -561,6 +561,15 @@ describe('onboardingLogic — flow composition', () => {router.actions.push('/onboarding/web_analytics?with=logs,product_analytics')}).toDispatchActions(['setSecondaryProductKeys'])expect(logic.values.secondaryProductKeys).toEqual([ProductKey.LOGS, ProductKey.PRODUCT_ANALYTICS])++ logic.actions.setStepId(`${OnboardingStepKey.INSTALL}:${ProductKey.LOGS}`)+ expect(logic.values.installStepReturnUrl).toBe(+ urls.onboarding({+ productKey: ProductKey.WEB_ANALYTICS,+ step: `${OnboardingStepKey.INSTALL}:${ProductKey.LOGS}`,+ withProducts: [ProductKey.LOGS, ProductKey.PRODUCT_ANALYTICS],+ })+ )})it('filters the primary product out of ?with= (avoids self-secondary)', async () => {diff --git a/frontend/src/scenes/onboarding/onboardingLogic.tsx b/frontend/src/scenes/onboarding/onboardingLogic.tsxindex 4c7e4ad95184..787152b650c5 100644--- a/frontend/src/scenes/onboarding/onboardingLogic.tsx+++ b/frontend/src/scenes/onboarding/onboardingLogic.tsx@@ -243,7 +243,8 @@ export interface onboardingLogicMeta {installStepReturnUrl: (flowVariant: OnboardingFlowVariant,flowUrl: string,- currentStepProductKey: ProductKey | null+ currentStepProductKey: ProductKey | null,+ secondaryProductKeys: ProductKey[]) => stringonCompleteOnboardingRedirectUrl: (flowVariant: OnboardingFlowVariant,@@ -692,17 +693,24 @@ export const onboardingLogic = kea<onboardingLogicType>([// Where an OAuth round trip started from the install step returns to, so the user lands back in// the same flow instead of the default per-product one.installStepReturnUrl: [- (s) => [s.flowVariant, s.flowUrl, s.currentStepProductKey],- (flowVariant: OnboardingFlowVariant, flowUrl: string, currentStepProductKey: ProductKey | null): string => {+ (s) => [s.flowVariant, s.flowUrl, s.currentStepProductKey, s.secondaryProductKeys],+ (+ flowVariant: OnboardingFlowVariant,+ flowUrl: string,+ currentStepProductKey: ProductKey | null,+ secondaryProductKeys: ProductKey[]+ ): string => {if (flowVariant === 'simple') {return combineUrl(flowUrl, {step: `${OnboardingStepKey.INSTALL}:${SIMPLE_ONBOARDING_PRODUCT_KEY}`,}).url}- return urls.onboarding({- productKey: currentStepProductKey ?? undefined,- stepKey: OnboardingStepKey.INSTALL,- })+ return combineUrl(flowUrl, {+ step: currentStepProductKey+ ? `${OnboardingStepKey.INSTALL}:${currentStepProductKey}`+ : OnboardingStepKey.INSTALL,+ ...(secondaryProductKeys.length ? { with: secondaryProductKeys.join(',') } : {}),+ }).url},],onCompleteOnboardingRedirectUrl: [diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.stories.tsx b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.stories.tsxindex 17dce27f3bf1..edd5e3f6f2c8 100644--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.stories.tsx+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.stories.tsx@@ -1,3 +1,5 @@+import { MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER } from 'lib/api.mock'+import { Meta, StoryObj } from '@storybook/react'import { useActions, useMountedLogic } from 'kea'import { router } from 'kea-router'@@ -14,8 +16,80 @@ import preflightJson from '~/mocks/fixtures/_preflight.json'import { ProductKey } from '~/queries/schema/schema-general'import { OnboardingStepKey } from '~/types'+import type { WizardRunApi } from 'products/wizard/frontend/generated/api.schemas'+import { onboardingLogic } from '../../../onboardingLogic'+const cloudRun: WizardRunApi = {+ id: '00000000-0000-4000-8000-000000000001',+ team_id: MOCK_DEFAULT_TEAM.id,+ created_by_id: MOCK_DEFAULT_USER.id,+ created_by: null,+ environment: 'cloud',+ workspace: { type: 'git_repository', repository: 'example/sample-project' },+ program: {+ id: 'posthog-integration',+ name: 'PostHog integration',+ description: 'Install PostHog',+ wizard_version: '2.67.0',+ command: [],+ tags: [],+ required_programs: [],+ supported_environments: ['local', 'cloud'],+ },+ status: 'created',+ stage: 'dispatching',+ created_at: '2023-05-25T00:00:01Z',+ updated_at: null,+ started_at: null,+ finished_at: null,+ deadline_at: null,+ error_code: null,+ error_message: null,+}++const cloudSetupMocks = mswDecorator({+ get: {+ '/_preflight': { ...preflightJson, cloud: true, realm: 'cloud', wizard_cloud_run_available: true },+ '/api/environments/:team_id/integrations/': {+ results: [+ {+ id: 1,+ kind: 'github',+ display_name: 'example',+ config: { account: { name: 'example', type: 'Organization' } },+ created_at: '2023-05-24T00:00:00Z',+ },+ ],+ },+ '/api/environments/:team_id/integrations/:id/github_repos/': {+ repositories: [+ {+ id: 1,+ name: 'sample-project',+ full_name: 'example/sample-project',+ archived: false,+ private: false,+ can_push: true,+ },+ ],+ has_more: false,+ },+ '/api/projects/:team_id/wizard/registry/': {+ count: 1,+ results: [cloudRun.program],+ },+ '/api/projects/:team_id/wizard/runs/': { count: 0, results: [], next: null },+ '/api/projects/:team_id/wizard/runs/:run_id/': cloudRun,+ '/api/projects/:team_id/wizard/runs/:run_id/tasks/': { tasks: [] },+ '/api/projects/:team_id/wizard/runs/:run_id/artifacts/': { count: 0, results: [] },+ '/api/projects/:team_id/wizard/runs/:run_id/stream/': () => [404],+ },+ post: {+ '/api/projects/:team_id/wizard/runs/': cloudRun,+ },+})+/** The onboarding install step: the full layout and the simple flow's compact layout. */const meta: Meta = {@@ -36,6 +110,13 @@ const meta: Meta = {patch: {'/api/environments/:team_id/add_product_intent/': {},},+ post: {+ '/api/projects/:team_id/file_system/home_folder/': {+ id: 'home',+ path: 'Users/Example',+ type: 'folder',+ },+ },}),],}@@ -47,9 +128,11 @@ type Story = StoryObjfunction installStepStory({featureFlags = {},simple = false,+ cloud = false,}: {featureFlags?: Record<string, string | boolean>simple?: boolean+ cloud?: boolean}): Story {return {render: () => {@@ -71,7 +154,12 @@ function installStepStory({return <App />},- parameters: { featureFlags, testOptions: { waitForSelector: '[data-attr="wizard-command-block"]' } },+ parameters: {+ featureFlags,+ testOptions: {+ waitForSelector: cloud ? '[data-attr="wizard-cloud-run-block"]' : '[data-attr="wizard-command-block"]',+ },+ },}}@@ -83,3 +171,20 @@ export const SimpleFlow: Story = installStepStory({simple: true,featureFlags: { [FEATURE_FLAGS.ONBOARDING_SIMPLE_FLOW]: 'test' },})++export const CloudSetup: Story = {+ ...installStepStory({ cloud: true, featureFlags: { [FEATURE_FLAGS.WIZARD_ONBOARDING_CLOUD_RUNS_ENABLED]: true } }),+ decorators: [cloudSetupMocks],+}++export const SimpleCloudSetup: Story = {+ ...installStepStory({+ simple: true,+ cloud: true,+ featureFlags: {+ [FEATURE_FLAGS.ONBOARDING_SIMPLE_FLOW]: 'test',+ [FEATURE_FLAGS.WIZARD_ONBOARDING_CLOUD_RUNS_ENABLED]: true,+ },+ }),+ decorators: [cloudSetupMocks],+}diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.test.tsx b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.test.tsxindex 67c0f46dda4b..aa968d6692d3 100644--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.test.tsx+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/WizardInstallStep.test.tsx@@ -8,8 +8,13 @@ import { Provider } from 'kea'import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { preflightLogic } from 'lib/logic/preflightLogic'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import type { PreflightStatus } from '~/types'import type { WizardRunApi } from 'products/wizard/frontend/generated/api.schemas'import { wizardRunSyncLogic } from 'products/wizard/frontend/logics/wizardRunSyncLogic'@@ -108,6 +113,11 @@ describe('WizardInstallStep with wizardOverrides', () => {})it('shows the ai-observability command and blocks Continue until installation completes', async () => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.WIZARD_ONBOARDING_CLOUD_RUNS_ENABLED]: true })+ preflightLogic.actions.loadPreflightSuccess({+ cloud: true,+ wizard_cloud_run_available: true,+ } as PreflightStatus)const sync = wizardRunSyncLogic({ projectId: String(MOCK_DEFAULT_TEAM.id) })sync.mount()await expectLogic(sync).toFinishAllListeners()@@ -130,9 +140,58 @@ describe('WizardInstallStep with wizardOverrides', () => {expect(await screen.findByText((t) => t.includes('ai-observability') && t.includes('npx'))).toBeInTheDocument()expect(document.querySelector('[data-attr="mock-continue"]')).toHaveAttribute('aria-disabled', 'true')expect(document.querySelector('[data-attr="wizard-install-sync"]')).toBeNull()+ expect(screen.queryByText('Open a pull request')).not.toBeInTheDocument()sync.unmount()})+ it.each([+ [false, false],+ [false, true],+ [true, false],+ [true, true],+ ])(+ 'shows cloud setup only with the boolean flag and keeps local setup available (compact=%s, enabled=%s)',+ async (compact, enabled) => {+ useMocks({+ get: {+ '/api/environments/:team_id/integrations/': { results: [] },+ '/api/projects/:team_id/wizard/registry/': {+ results: [+ {+ id: 'posthog-integration',+ supported_environments: ['cloud'],+ },+ ],+ },+ },+ })+ await expectLogic(preflightLogic).toFinishAllListeners()+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.WIZARD_ONBOARDING_CLOUD_RUNS_ENABLED]: enabled,+ })+ preflightLogic.actions.loadPreflightSuccess({+ cloud: true,+ wizard_cloud_run_available: true,+ } as PreflightStatus)+ render(+ <Provider>+ <WizardInstallStep+ {...AIO_PROPS}+ wizardOverrides={{ ...AIO_PROPS.wizardOverrides!, subcommand: '' }}+ compact={compact}+ />+ </Provider>+ )+ if (enabled) {+ expect(await screen.findByText('Connect GitHub')).toBeInTheDocument()+ fireEvent.click(screen.getByText('Run it yourself'))+ } else {+ expect(screen.queryByText('Open a pull request')).not.toBeInTheDocument()+ }+ expect(screen.getByLabelText('Copy wizard command')).toBeInTheDocument()+ }+ )+it.each([false, true])('allows continuing during setup and keeps result actions in onboarding (compact=%s)',async (compact) => {diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/index.tsx b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/index.tsxindex a4bba7bc8f08..96bf705d84fa 100644--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/index.tsx+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/WizardInstallStep/index.tsx@@ -10,6 +10,7 @@ import { OnboardingStepKey, type SDK } from '~/types'import { wizardRunIsActive } from 'products/wizard/frontend/lib/wizardRunDisplay'import { onboardingWizardRunLogic } from 'products/wizard/frontend/views/onboarding/onboardingWizardRunLogic'import { WizardInstallSync } from 'products/wizard/frontend/views/onboarding/WizardInstallSync'+import { WizardOnboardingCloudRun } from 'products/wizard/frontend/views/onboarding/WizardOnboardingCloudRun'import { OnboardingStep } from '../../../OnboardingStep'import { useWizardCommand } from '../../../shared/useWizardCommand'@@ -32,12 +33,21 @@ function OnboardingInstallOptions({compact?: boolean}): JSX.Element {const { isCloudOrDev } = useWizardCommand()+ const { cloudRunProps } = useValues(wizardInstallStepLogic)+ const { subcommand, description, supports } = wizardOverrides ?? {}+ const localBlock = (+ <WizardCommandBlock+ subcommand={subcommand}+ description={description ?? (compact ? 'Run this in your project folder. No API key needed.' : undefined)}+ hog={compact ? null : undefined}+ />+ )return (<div className="flex flex-col gap-4">{isCloudOrDev && (<div className="pb-2">- {wizardOverrides?.supports ? (- <WizardFrameworkBadges items={wizardOverrides.supports} />+ {supports ? (+ <WizardFrameworkBadges items={supports} />) : compact ? (<WizardFrameworkIcons />) : (@@ -45,14 +55,11 @@ function OnboardingInstallOptions({)}</div>)}- <WizardCommandBlock- subcommand={wizardOverrides?.subcommand}- description={- wizardOverrides?.description ??- (compact ? 'Run this in your project folder. No API key needed.' : undefined)- }- hog={compact ? null : undefined}- />+ {!subcommand && cloudRunProps ? (+ <WizardOnboardingCloudRun {...cloudRunProps}>{localBlock}</WizardOnboardingCloudRun>+ ) : (+ localBlock+ )}</div>)}diff --git a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/wizardInstallStepLogic.ts b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/wizardInstallStepLogic.tsindex 9e88a9d2eaf6..4c6ed55256fe 100644--- a/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/wizardInstallStepLogic.ts+++ b/frontend/src/scenes/onboarding/sdks/OnboardingInstallStep/wizardInstallStepLogic.ts@@ -1,8 +1,24 @@-import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'import posthog from 'posthog-js'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'+import { preflightLogic } from 'lib/logic/preflightLogic'+import { teamLogic } from 'scenes/teamLogic'+import { userLogic } from 'scenes/userLogic'++import type { PreflightStatus, TeamPublicType, TeamType, UserType } from '~/types'++import type { WizardOnboardingCloudRunProps } from 'products/wizard/frontend/views/onboarding/wizardOnboardingCloudRunLogic'+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface wizardInstallStepLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogic+ preflight: PreflightStatus | null // preflightLogic+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ user: UserType | null // userLogic+ cloudRunEnabled: boolean+ cloudRunProps: WizardOnboardingCloudRunProps | nullmanualModalOpen: booleansdkInstructionsOpen: boolean}@@ -17,10 +33,39 @@ export interface wizardInstallStepLogicActions {}}-export type wizardInstallStepLogicType = MakeLogicType<wizardInstallStepLogicValues, wizardInstallStepLogicActions>+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface wizardInstallStepLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ cloudRunEnabled: (featureFlags: FeatureFlagsSet, preflight: PreflightStatus | null) => boolean+ cloudRunProps: (+ cloudRunEnabled: boolean,+ currentTeam: TeamPublicType | TeamType | null,+ user: UserType | null+ ) => WizardOnboardingCloudRunProps | null+ }+}++export type wizardInstallStepLogicType = MakeLogicType<+ wizardInstallStepLogicValues,+ wizardInstallStepLogicActions,+ Record<string, any>,+ wizardInstallStepLogicMeta+>export const wizardInstallStepLogic = kea<wizardInstallStepLogicType>([path(['scenes', 'onboarding', 'wizardInstallStepLogic']),+ connect({+ values: [+ featureFlagLogic,+ ['featureFlags'],+ preflightLogic,+ ['preflight'],+ teamLogic,+ ['currentTeam'],+ userLogic,+ ['user'],+ ],+ }),actions({setManualModalOpen: (open: boolean) => ({ open }),setSdkInstructionsOpen: (open: boolean) => ({ open }),@@ -39,6 +84,24 @@ export const wizardInstallStepLogic = kea<wizardInstallStepLogicType>([},],}),+ selectors({+ cloudRunEnabled: [+ (s) => [s.featureFlags, s.preflight],+ (flags: FeatureFlagsSet, preflight: PreflightStatus | null): boolean =>+ flags[FEATURE_FLAGS.WIZARD_ONBOARDING_CLOUD_RUNS_ENABLED] === true &&+ !!preflight?.wizard_cloud_run_available &&+ !!(preflight.cloud || preflight.is_debug),+ ],+ cloudRunProps: [+ (s) => [s.cloudRunEnabled, s.currentTeam, s.user],+ (+ enabled: boolean,+ team: TeamType | TeamPublicType | null,+ user: UserType | null+ ): WizardOnboardingCloudRunProps | null =>+ enabled && team && user ? { projectId: String(team.id), userId: user.id } : null,+ ],+ }),listeners({setManualModalOpen: ({ open }) => {if (open) {diff --git a/products/wizard/frontend/views/onboarding/WizardOnboardingCloudRun.tsx b/products/wizard/frontend/views/onboarding/WizardOnboardingCloudRun.tsxnew file mode 100644index 000000000000..78e612248513--- /dev/null+++ b/products/wizard/frontend/views/onboarding/WizardOnboardingCloudRun.tsx@@ -0,0 +1,118 @@+import { useActions, useValues } from 'kea'+import type { ReactNode } from 'react'++import { IconCloud, IconGithub, IconTerminal } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonSegmentedButton, Spinner } from '@posthog/lemon-ui'++import { GitHubRepositoryPicker } from 'lib/integrations/GitHubIntegrationHelpers'+import { LemonLabel } from 'lib/lemon-ui/LemonLabel'++import { wizardOnboardingCloudRunLogic, type WizardOnboardingCloudRunProps } from './wizardOnboardingCloudRunLogic'++export function WizardOnboardingCloudRun({+ children,+ ...props+}: WizardOnboardingCloudRunProps & { children: ReactNode }): JSX.Element {+ const logic = wizardOnboardingCloudRunLogic(props)+ const {+ mode,+ runActive,+ repository,+ githubIntegration,+ setupLoading,+ setupError,+ startLabel,+ program,+ createRunRequestLoading,+ createError,+ connectGitHubUrl,+ } = useValues(logic)+ const { setMode, setRepository, startCloudRun, retrySetup } = useActions(logic)++ return (+ <div className="flex flex-col gap-4" data-attr="wizard-onboarding-cloud-options">+ <LemonSegmentedButton+ fullWidth+ value={mode}+ onChange={(value) => {+ if (value !== mode) {+ setMode(value)+ }+ }}+ options={[+ {+ value: 'cloud',+ label: 'Open a pull request',+ icon: <IconCloud />,+ 'data-attr': 'wizard-mode-cloud',+ },+ {+ value: 'local',+ label: 'Run it yourself',+ icon: <IconTerminal />,+ 'data-attr': 'wizard-mode-local',+ },+ ]}+ />+ {mode === 'local' ? (+ children+ ) : (+ <div className="flex flex-col gap-4" data-attr="wizard-cloud-run-block">+ <p className="text-sm text-muted mb-0">+ The setup agent runs in the cloud and opens a pull request. Review and merge the changes when+ you are ready.+ </p>+ {runActive ? (+ <LemonBanner type="info">+ A setup run is in progress. You can continue onboarding and review its results here.+ </LemonBanner>+ ) : setupLoading ? (+ <Spinner />+ ) : setupError ? (+ <LemonBanner type="error" action={{ children: 'Retry', onClick: () => retrySetup() }}>+ {setupError}+ </LemonBanner>+ ) : !program ? (+ <LemonBanner type="warning">+ Cloud setup is not available. Select Run it yourself to use the local command.+ </LemonBanner>+ ) : !githubIntegration ? (+ <LemonButton+ type="secondary"+ icon={<IconGithub />}+ to={connectGitHubUrl}+ disableClientSideRouting+ data-attr="wizard-cloud-run-connect-github"+ className="self-start"+ >+ Connect GitHub+ </LemonButton>+ ) : (+ <>+ <div className="flex flex-col gap-2">+ <LemonLabel>GitHub repository</LemonLabel>+ <GitHubRepositoryPicker+ integrationId={githubIntegration.id}+ value={repository}+ onChange={setRepository}+ valueKey="full_name"+ />+ </div>+ {createError && <LemonBanner type="error">{createError}</LemonBanner>}+ <LemonButton+ type="primary"+ onClick={() => startCloudRun()}+ loading={createRunRequestLoading}+ disabledReason={!repository ? 'Select a repository first' : undefined}+ data-attr="wizard-cloud-run-open-pr"+ className="self-start"+ >+ {startLabel}+ </LemonButton>+ </>+ )}+ </div>+ )}+ </div>+ )+}diff --git a/products/wizard/frontend/views/onboarding/onboardingWizardRunLogic.ts b/products/wizard/frontend/views/onboarding/onboardingWizardRunLogic.tsindex f8b377697e5d..333246926272 100644--- a/products/wizard/frontend/views/onboarding/onboardingWizardRunLogic.ts+++ b/products/wizard/frontend/views/onboarding/onboardingWizardRunLogic.ts@@ -40,6 +40,7 @@ export interface onboardingWizardRunLogicActions {syncRun: () => { value: true }startOnboarding: (timestamp: string) => { timestamp: string }saveRun: (run: SavedOnboardingWizardRun) => { run: SavedOnboardingWizardRun }+ acceptCreatedRun: (run: WizardRunApi) => { run: WizardRunApi }loadRunData: (run: WizardRunApi) => { run: WizardRunApi }watchRuns: (source: string, runIds: string[]) => { source: string; runIds: string[] }clickArtifact: (@@ -67,6 +68,7 @@ export const onboardingWizardRunLogic: LogicWrapper<onboardingWizardRunLogicTypesyncRun: true,startOnboarding: (timestamp: string) => ({ timestamp }),saveRun: (run: SavedOnboardingWizardRun) => ({ run }),+ acceptCreatedRun: (run: WizardRunApi) => ({ run }),clickArtifact: (artifact: WizardRunArtifactApi, clickSource: WizardOnboardingArtifactClickSource) => ({artifact,clickSource,@@ -80,12 +82,18 @@ export const onboardingWizardRunLogic: LogicWrapper<onboardingWizardRunLogicType{startOnboarding: (state, { timestamp }) =>Number.isFinite(Date.parse(state ?? '')) ? state : timestamp,+ // A run created here belongs to this onboarding even after a fallback to browser time.+ acceptCreatedRun: (state, { run }) =>+ state && Date.parse(state) <= Date.parse(run.created_at) ? state : run.created_at,},],savedRun: [null as SavedOnboardingWizardRun | null,{ persist: true, storageKey: `${projectId}.${userId}.onboarding_wizard_run_id` },- { saveRun: (_, { run }) => run },+ {+ saveRun: (_, { run }) => run,+ acceptCreatedRun: (_, { run }) => ({ id: run.id, created_at: run.created_at }),+ },],})),selectors(({ props }) => ({diff --git a/products/wizard/frontend/views/onboarding/wizardOnboardingCloudRunLogic.test.ts b/products/wizard/frontend/views/onboarding/wizardOnboardingCloudRunLogic.test.tsnew file mode 100644index 000000000000..e22443656639--- /dev/null+++ b/products/wizard/frontend/views/onboarding/wizardOnboardingCloudRunLogic.test.ts@@ -0,0 +1,187 @@+import { MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER } from 'lib/api.mock'+import { installMockEventSource } from 'lib/wizard-sync/eventSource.mock'++import { expectLogic } from 'kea-test-utils'++import { ApiError } from 'lib/api-error'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { preflightLogic } from 'lib/logic/preflightLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import type { PreflightStatus } from '~/types'++import { wizardRegistryList, wizardRunsCreate } from '../../generated/api'+import type { WizardProgramApi, WizardRunApi } from '../../generated/api.schemas'+import { wizardRunSyncLogic } from '../../logics/wizardRunSyncLogic'+import { onboardingWizardRunLogic } from './onboardingWizardRunLogic'+import { wizardOnboardingCloudRunLogic } from './wizardOnboardingCloudRunLogic'++jest.mock('../../generated/api', () => ({+ wizardRegistryList: jest.fn(),+ wizardRunsCreate: jest.fn(),+ wizardRunsList: jest.fn().mockResolvedValue({ results: [], next: null }),+ wizardRunsTasksRetrieve: jest.fn().mockResolvedValue({ tasks: [] }),+ getWizardRunsStreamRetrieveUrl: () => '/stream',+}))+jest.mock('../../lib/wizardApi', () => ({+ loadWizardRunArtifacts: jest.fn().mockResolvedValue([]),+ loadWizardOnboardingStartTime: jest.fn().mockImplementation(async () => new Date().toISOString()),+}))++const props = { projectId: String(MOCK_DEFAULT_TEAM.id), userId: MOCK_DEFAULT_USER.id }+const program: WizardProgramApi = {+ id: 'posthog-integration',+ name: 'PostHog integration',+ description: 'Install PostHog',+ wizard_version: '2.67.0',+ command: [],+ tags: [],+ required_programs: [],+ supported_environments: ['cloud', 'local'],+}++describe('wizardOnboardingCloudRunLogic', () => {+ let logic: ReturnType<typeof wizardOnboardingCloudRunLogic.build>+ let restoreEventSource: () => void+ let run: WizardRunApi++ beforeEach(async () => {+ localStorage.clear()+ useMocks({+ get: {+ '/api/environments/:team_id/integrations/': {+ results: [+ {+ id: 1,+ kind: 'github',+ config: { account: { name: 'example', type: 'Organization' } },+ created_at: '2026-01-01T00:00:00Z',+ },+ ],+ },+ },+ })+ initKeaTests()+ restoreEventSource = installMockEventSource()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.WIZARD_ONBOARDING_CLOUD_RUNS_ENABLED]: true })+ preflightLogic.actions.loadPreflightSuccess({+ cloud: true,+ wizard_cloud_run_available: true,+ } as PreflightStatus)+ jest.mocked(wizardRegistryList).mockResolvedValue({ count: 1, results: [program] })+ run = {+ id: 'cloud-installation',+ team_id: MOCK_DEFAULT_TEAM.id,+ created_by_id: props.userId,+ created_by: null,+ program,+ environment: 'cloud',+ workspace: { type: 'git_repository', repository: 'example/sample-project' },+ status: 'created',+ stage: 'dispatching',+ created_at: new Date(Date.now() - 60_000).toISOString(),+ updated_at: null,+ started_at: null,+ finished_at: null,+ deadline_at: null,+ error_code: null,+ error_message: null,+ }+ jest.mocked(wizardRunsCreate).mockReset().mockResolvedValue(run)+ logic = wizardOnboardingCloudRunLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.WIZARD_ONBOARDING_CLOUD_RUNS_ENABLED]: true })+ preflightLogic.actions.loadPreflightSuccess({+ cloud: true,+ wizard_cloud_run_available: true,+ } as PreflightStatus)+ expect(logic.values.githubIntegration?.id).toBe(1)+ expect(logic.values.cloudRunEnabled).toBe(true)+ logic.actions.setRepository('example/sample-project')+ })++ afterEach(() => {+ logic.unmount()+ restoreEventSource()+ localStorage.clear()+ jest.restoreAllMocks()+ })++ it('creates one run and immediately restores progress despite a browser clock ahead of the server', async () => {+ logic.actions.startCloudRun()+ logic.actions.startCloudRun()+ await expectLogic(logic).toFinishAllListeners()+ expect(wizardRunsCreate).toHaveBeenCalledTimes(1)+ expect(wizardRunsCreate).toHaveBeenCalledWith(props.projectId, {+ program_id: program.id,+ wizard_version: program.wizard_version,+ environment: 'cloud',+ workspace: { type: 'git_repository', repository: 'example/sample-project' },+ idempotency_key: expect.any(String),+ })+ expect(onboardingWizardRunLogic(props).values.run).toEqual(run)+ logic.actions.startCloudRun()+ expect(wizardRunsCreate).toHaveBeenCalledTimes(1)+ featureFlagLogic.actions.setFeatureFlags([], {})+ expect(onboardingWizardRunLogic(props).values.run).toEqual(run)+ })++ it('reuses the request key after failure and replaces it for a different repository', async () => {+ jest.mocked(wizardRunsCreate).mockRejectedValue(new Error('offline'))+ const key = logic.values.idempotencyKey+ logic.actions.startCloudRun()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.createError).toContain('try again')+ logic.actions.startCloudRun()+ await expectLogic(logic).toFinishAllListeners()+ expect(jest.mocked(wizardRunsCreate).mock.calls.map(([, body]) => body.idempotency_key)).toEqual([key, key])++ jest.mocked(wizardRunsCreate).mockRejectedValue(+ new ApiError(undefined, 429, undefined, { detail: 'Wait an hour before you start another run.' })+ )+ const failedRun: WizardRunApi = { ...run, status: 'failed' }+ onboardingWizardRunLogic(props).actions.acceptCreatedRun(failedRun)+ wizardRunSyncLogic({ projectId: props.projectId }).actions.runsLoaded([failedRun], true)+ expect(logic.values.startLabel).toBe('Retry cloud setup')+ logic.actions.startCloudRun()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.createError).toBe('Wait an hour before you start another run.')+ logic.actions.startCloudRun()+ await expectLogic(logic).toFinishAllListeners()+ const [, , retryKey, repeatedRetryKey] = jest+ .mocked(wizardRunsCreate)+ .mock.calls.map(([, body]) => body.idempotency_key)+ expect(retryKey).not.toBe(key)+ expect(repeatedRetryKey).toBe(retryKey)++ logic.actions.setRepository('example/another-project')+ expect(logic.values.idempotencyKey).not.toBe(retryKey)+ })++ it.each(['flag', 'instance', 'repository', 'program'])(+ 'does not start a run without the required %s',+ async (missing) => {+ if (missing === 'flag') {+ featureFlagLogic.actions.setFeatureFlags([], {})+ }+ if (missing === 'instance') {+ preflightLogic.actions.loadPreflightSuccess({+ cloud: true,+ wizard_cloud_run_available: false,+ } as PreflightStatus)+ }+ if (missing === 'repository') {+ logic.actions.setRepository('')+ }+ if (missing === 'program') {+ logic.actions.loadRegistrySuccess([{ ...program, supported_environments: ['local'] }])+ }+ logic.actions.startCloudRun()+ await expectLogic(logic).toFinishAllListeners()+ expect(wizardRunsCreate).not.toHaveBeenCalled()+ }+ )+})diff --git a/products/wizard/frontend/views/onboarding/wizardOnboardingCloudRunLogic.ts b/products/wizard/frontend/views/onboarding/wizardOnboardingCloudRunLogic.tsnew file mode 100644index 000000000000..93cd511352aa--- /dev/null+++ b/products/wizard/frontend/views/onboarding/wizardOnboardingCloudRunLogic.ts@@ -0,0 +1,297 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { ApiError } from 'lib/api-error'+import { resolveTeamGitHubIntegration } from 'lib/integrations/GitHubIntegrationHelpers'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { uuid } from 'lib/utils/dom'+import { onboardingLogic } from 'scenes/onboarding/onboardingLogic'+import { wizardInstallStepLogic } from 'scenes/onboarding/sdks/OnboardingInstallStep/wizardInstallStepLogic'++import type { IntegrationType } from '~/types'++import { getIntegrationsAuthorizeRetrieveUrl } from 'products/integrations/frontend/generated/api'++import { wizardRegistryList, wizardRunsCreate } from '../../generated/api'+import type { WizardProgramApi, WizardRunApi, WizardRunCreateRequestApi } from '../../generated/api.schemas'+import { wizardEventProperties } from '../../lib/wizardAnalytics'+import { wizardRunIsActive } from '../../lib/wizardRunDisplay'+import { wizardRunSyncLogic } from '../../logics/wizardRunSyncLogic'+import { onboardingWizardRunLogic } from './onboardingWizardRunLogic'++export interface WizardOnboardingCloudRunProps {+ projectId: string+ userId: number+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface wizardOnboardingCloudRunLogicValues {+ githubIntegrations: IntegrationType[] // integrationsLogic+ integrations: IntegrationType[] | null // integrationsLogic+ integrationsLoading: boolean // integrationsLogic+ installStepReturnUrl: string // onboardingLogic+ run: WizardRunApi | null // onboardingWizardRunLogic+ cloudRunEnabled: boolean // wizardInstallStepLogic+ connectGitHubUrl: string+ createError: string | null+ createRunRequest: WizardRunApi | null+ createRunRequestLoading: boolean+ githubIntegration: IntegrationType | null+ idempotencyKey: string+ mode: 'cloud' | 'local'+ program: WizardProgramApi | null+ registry: WizardProgramApi[] | null+ registryError: boolean+ registryLoading: boolean+ repository: string+ runActive: boolean+ setupError: string | null+ setupLoading: boolean+ startLabel: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface wizardOnboardingCloudRunLogicActions {+ loadIntegrations: (_?: any) => any // integrationsLogic+ createRunRequest: (body: WizardRunCreateRequestApi) => WizardRunCreateRequestApi+ createRunRequestFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ createRunRequestSuccess: (+ createRunRequest: WizardRunApi,+ payload?: WizardRunCreateRequestApi+ ) => {+ createRunRequest: WizardRunApi+ payload?: WizardRunCreateRequestApi+ }+ loadRegistry: () => any+ loadRegistryFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRegistrySuccess: (+ registry: WizardProgramApi[],+ payload?: any+ ) => {+ registry: WizardProgramApi[]+ payload?: any+ }+ retrySetup: () => {+ value: true+ }+ rotateIdempotencyKey: () => {+ value: true+ }+ setMode: (mode: 'cloud' | 'local') => {+ mode: 'cloud' | 'local'+ }+ setRepository: (repository: string) => {+ idempotencyKey: string+ repository: string+ }+ startCloudRun: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface wizardOnboardingCloudRunLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ githubIntegration: (githubIntegrations: IntegrationType[]) => IntegrationType | null+ program: (registry: WizardProgramApi[] | null) => WizardProgramApi | null+ setupLoading: (+ integrationsLoading: boolean,+ registryLoading: boolean,+ registry: WizardProgramApi[] | null,+ registryError: boolean+ ) => boolean+ setupError: (integrations: IntegrationType[] | null, registryError: boolean) => string | null+ startLabel: (run: WizardRunApi | null) => string+ runActive: (run: WizardRunApi | null) => boolean+ connectGitHubUrl: (installStepReturnUrl: string) => string+ }+}++export type wizardOnboardingCloudRunLogicType = MakeLogicType<+ wizardOnboardingCloudRunLogicValues,+ wizardOnboardingCloudRunLogicActions,+ WizardOnboardingCloudRunProps,+ wizardOnboardingCloudRunLogicMeta+>++export const wizardOnboardingCloudRunLogic = kea<wizardOnboardingCloudRunLogicType>([+ props({} as WizardOnboardingCloudRunProps),+ key(({ projectId, userId }) => `${projectId}.${userId}`),+ path((key) => ['products', 'wizard', 'wizardOnboardingCloudRunLogic', key]),+ connect((props: WizardOnboardingCloudRunProps) => ({+ values: [+ integrationsLogic,+ ['githubIntegrations', 'integrations', 'integrationsLoading'],+ wizardInstallStepLogic,+ ['cloudRunEnabled'],+ onboardingLogic,+ ['installStepReturnUrl'],+ onboardingWizardRunLogic(props),+ ['run'],+ ],+ actions: [integrationsLogic, ['loadIntegrations']],+ })),+ actions({+ setMode: (mode: 'cloud' | 'local') => ({ mode }),+ setRepository: (repository: string) => ({ repository, idempotencyKey: uuid() }),+ rotateIdempotencyKey: true,+ startCloudRun: true,+ retrySetup: true,+ }),+ reducers({+ mode: ['cloud' as 'cloud' | 'local', { setMode: (_, { mode }) => mode }],+ repository: ['', { setRepository: (_, { repository }) => repository }],+ idempotencyKey: [+ () => uuid(),+ {+ setRepository: (_, { idempotencyKey }) => idempotencyKey,+ createRunRequestSuccess: () => uuid(),+ rotateIdempotencyKey: () => uuid(),+ },+ ],+ registryError: [false, { loadRegistry: () => false, loadRegistryFailure: () => true }],+ createError: [+ null as string | null,+ {+ createRunRequest: () => null,+ setRepository: () => null,+ // The API explains limits and invalid input in `detail`. Network failures have none.+ createRunRequestFailure: (_, { errorObject }) =>+ errorObject instanceof ApiError && errorObject.detail+ ? errorObject.detail+ : 'Could not start the cloud run. Check the repository and try again.',+ },+ ],+ }),+ loaders(({ props }) => ({+ registry: [+ null as WizardProgramApi[] | null,+ {+ loadRegistry: async () =>+ (await wizardRegistryList(props.projectId, { limit: 100, offset: 0 })).results,+ },+ ],+ createRunRequest: [+ null as WizardRunApi | null,+ {+ createRunRequest: async (body: WizardRunCreateRequestApi) => wizardRunsCreate(props.projectId, body),+ },+ ],+ })),+ selectors(({ props }) => ({+ githubIntegration: [+ (s) => [s.githubIntegrations],+ (integrations: IntegrationType[]): IntegrationType | null =>+ resolveTeamGitHubIntegration(integrations) ?? null,+ ],+ program: [+ (s) => [s.registry],+ (registry: WizardProgramApi[] | null): WizardProgramApi | null =>+ registry?.find(+ (program) =>+ program.id === 'posthog-integration' && program.supported_environments.includes('cloud')+ ) ?? null,+ ],+ setupLoading: [+ (s) => [s.integrationsLoading, s.registryLoading, s.registry, s.registryError],+ (+ integrationsLoading: boolean,+ registryLoading: boolean,+ registry: WizardProgramApi[] | null,+ registryError: boolean+ ): boolean => integrationsLoading || registryLoading || (registry === null && !registryError),+ ],+ setupError: [+ (s) => [s.integrations, s.registryError],+ (integrations: IntegrationType[] | null, registryError: boolean): string | null =>+ !integrations+ ? 'Could not check the GitHub connection. Retry or run it yourself.'+ : registryError+ ? 'Could not load the setup program. Retry or run it yourself.'+ : null,+ ],+ startLabel: [+ (s) => [s.run],+ (run: WizardRunApi | null): string =>+ run && ['failed', 'cancelled'].includes(run.status) ? 'Retry cloud setup' : 'Install PostHog here',+ ],+ runActive: [(s) => [s.run], (run: WizardRunApi | null): boolean => !!run && wizardRunIsActive(run)],+ connectGitHubUrl: [+ (s) => [s.installStepReturnUrl],+ (returnUrl: string): string =>+ `${getIntegrationsAuthorizeRetrieveUrl(props.projectId)}?${new URLSearchParams({ kind: 'github', next: returnUrl })}`,+ ],+ })),+ listeners(({ actions, values, props, cache }) => ({+ retrySetup: () => {+ if (!values.integrations) {+ actions.loadIntegrations()+ } else {+ actions.loadRegistry()+ }+ },+ setMode: ({ mode }) => {+ posthog.capture('onboarding install mode selected', { mode })+ },+ startCloudRun: () => {+ if (+ !values.cloudRunEnabled ||+ values.runActive ||+ values.createRunRequestLoading ||+ !values.githubIntegration ||+ !values.repository ||+ !values.program+ ) {+ return+ }+ // A create request whose response got lost keeps its key, so a retry with that key+ // returns the same run. A retry of a terminal run must start a new run, so rotate the+ // key once per terminal run. Later retries of the same run reuse the key and stay idempotent.+ if (values.run && !wizardRunIsActive(values.run) && cache.retriedRunId !== values.run.id) {+ cache.retriedRunId = values.run.id+ actions.rotateIdempotencyKey()+ }+ posthog.capture('wizard run create requested', {+ ...wizardEventProperties(props.projectId, 'cloud'),+ location: 'onboarding',+ program_id: values.program.id,+ })+ actions.createRunRequest({+ program_id: values.program.id,+ wizard_version: values.program.wizard_version,+ environment: 'cloud',+ workspace: { type: 'git_repository', repository: values.repository },+ idempotency_key: values.idempotencyKey,+ })+ },+ createRunRequestSuccess: ({ createRunRequest: run }) => {+ const onboarding = onboardingWizardRunLogic(props)+ onboarding.actions.acceptCreatedRun(run)+ wizardRunSyncLogic({ projectId: props.projectId }).actions.runsLoaded([run], true)+ },+ createRunRequestFailure: () => {+ posthog.capture('wizard run create failed', {+ ...wizardEventProperties(props.projectId, 'cloud'),+ location: 'onboarding',+ })+ },+ })),+ afterMount(({ actions }) => {+ actions.loadIntegrations()+ actions.loadRegistry()+ }),+])