: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(desktop): put github repos and cloud defaults first in onboarding (#85453)
Adam Bowker49f53519510b
diff --git a/products/desktop/packages/core/src/git-interaction/gitInteractionLogic.test.ts b/products/desktop/packages/core/src/git-interaction/gitInteractionLogic.test.tsindex 1f6fdf510810..bd3a21a112ab 100644--- a/products/desktop/packages/core/src/git-interaction/gitInteractionLogic.test.ts+++ b/products/desktop/packages/core/src/git-interaction/gitInteractionLogic.test.ts@@ -29,6 +29,55 @@ function actionIds(result: ReturnType<typeof computeGitInteractionState>) {}describe("computeGitInteractionState", () => {+ describe("github cli environment gaps", () => {+ it.each([+ {+ name: "missing",+ ghStatus: { installed: false, authenticated: false },+ reason: "Install GitHub CLI: `brew install gh`",+ },+ {+ name: "unauthenticated",+ ghStatus: { installed: true, authenticated: false },+ reason: "Authenticate GitHub CLI with `gh auth login`",+ },+ ])(+ "keeps create-pr visible but disabled when gh is $name",+ ({ ghStatus, reason }) => {+ const result = computeGitInteractionState(+ makeState({ hasChanges: true, aheadOfRemote: 1, ghStatus }),+ );+ const createPr = result.actions.find((a) => a.id === "create-pr");+ expect(createPr).toBeDefined();+ expect(createPr?.enabled).toBe(false);+ expect(createPr?.disabledReason).toBe(reason);+ expect(result.primaryAction.id).not.toBe("create-pr");+ },+ );++ it("still drops create-pr for routine states like an existing PR", () => {+ const result = computeGitInteractionState(+ makeState({+ hasChanges: true,+ prStatus: {+ prExists: true,+ baseBranch: "main",+ headBranch: "feature/test",+ prUrl: "https://github.com/test/test/pull/1",+ },+ }),+ );+ expect(actionIds(result)).not.toContain("create-pr");+ });++ it("does not surface create-pr while gh status is still loading", () => {+ const result = computeGitInteractionState(+ makeState({ hasChanges: true, aheadOfRemote: 1, ghStatus: null }),+ );+ expect(actionIds(result)).not.toContain("create-pr");+ });+ });+describe("on default branch with changes", () => {it("returns create-pr as primary action", () => {const result = computeGitInteractionState(diff --git a/products/desktop/packages/core/src/git-interaction/gitInteractionLogic.ts b/products/desktop/packages/core/src/git-interaction/gitInteractionLogic.tsindex 8ac016848c2a..1c8772d02cb8 100644--- a/products/desktop/packages/core/src/git-interaction/gitInteractionLogic.ts+++ b/products/desktop/packages/core/src/git-interaction/gitInteractionLogic.ts@@ -1,6 +1,6 @@import type { GitMenuAction, GitMenuActionId } from "./types";-interface GitState {+export interface GitState {repoPath?: string;isRepo: boolean;isRepoLoading: boolean;@@ -98,26 +98,52 @@ function getPushDisabledReason(return null;}-function getCreatePrDisabledReason(- s: GitState,- repoReason: string | null,-): string | null {- if (repoReason) return repoReason;- if (!s.isOnline) return OFFLINE_REASON;+interface CreatePrGate {+ reason: string | null;+ /** An environment gap the user can fix (missing or logged-out GitHub CLI)+ * keeps the disabled entry visible with its fix in the tooltip; routine+ * states (PR exists, nothing to ship) hide the entry instead. */+ visibleWhenDisabled: boolean;+}- if (!s.ghStatus) return "Checking GitHub CLI status...";- if (!s.ghStatus.installed) return "Install GitHub CLI: `brew install gh`";- if (!s.ghStatus.authenticated)- return "Authenticate GitHub CLI with `gh auth login`";- if (!s.repoInfo) return "No GitHub remote detected.";+function getCreatePrGate(s: GitState, repoReason: string | null): CreatePrGate {+ if (repoReason) return { reason: repoReason, visibleWhenDisabled: false };+ if (!s.isOnline)+ return { reason: OFFLINE_REASON, visibleWhenDisabled: false };- if (s.prStatus?.prExists) return "PR already exists.";+ if (!s.ghStatus) {+ return {+ reason: "Checking GitHub CLI status...",+ visibleWhenDisabled: false,+ };+ }+ if (!s.ghStatus.installed) {+ return {+ reason: "Install GitHub CLI: `brew install gh`",+ visibleWhenDisabled: true,+ };+ }+ if (!s.ghStatus.authenticated) {+ return {+ reason: "Authenticate GitHub CLI with `gh auth login`",+ visibleWhenDisabled: true,+ };+ }+ if (!s.repoInfo) {+ return { reason: "No GitHub remote detected.", visibleWhenDisabled: false };+ }++ if (s.prStatus?.prExists) {+ return { reason: "PR already exists.", visibleWhenDisabled: false };+ }const hasShippableWork =s.hasChanges || s.aheadOfRemote > 0 || s.aheadOfDefault > 0 || !s.hasRemote;- if (!hasShippableWork) return "No changes to ship.";+ if (!hasShippableWork) {+ return { reason: "No changes to ship.", visibleWhenDisabled: false };+ }- return null;+ return { reason: null, visibleWhenDisabled: false };}function getCommitAction(@@ -190,7 +216,8 @@ export function computeGitInteractionState(input: GitState): GitComputed {}const onDefaultBranch = isOnDefaultBranch(input);- const createPrDisabledReason = getCreatePrDisabledReason(input, repoReason);+ const createPrGate = getCreatePrGate(input, repoReason);+ const createPrDisabledReason = createPrGate.reason;const createPrAction = getCreatePrAction(createPrDisabledReason);if (onDefaultBranch) {@@ -231,7 +258,9 @@ export function computeGitInteractionState(input: GitState): GitComputed {);const actions: GitMenuAction[] = [];- if (createPrAction.enabled) actions.push(createPrAction);+ if (createPrAction.enabled || createPrGate.visibleWhenDisabled) {+ actions.push(createPrAction);+ }actions.push(commitAction, pushAction);if (viewPrAction) actions.push(viewPrAction);diff --git a/products/desktop/packages/core/src/onboarding/spaceRepoAssignment.test.ts b/products/desktop/packages/core/src/onboarding/spaceRepoAssignment.test.tsnew file mode 100644index 000000000000..29a1ceb25628--- /dev/null+++ b/products/desktop/packages/core/src/onboarding/spaceRepoAssignment.test.ts@@ -0,0 +1,110 @@+import { describe, expect, it } from "vitest";+import {+ type AssignableChannel,+ planSpaceRepoAssignments,+ resolveRepoIntegrationId,+} from "./spaceRepoAssignment";++function channel(overrides: Partial<AssignableChannel>): AssignableChannel {+ return {+ id: "id",+ name: "name",+ channel_type: "public",+ system_role: null,+ ...overrides,+ };+}++const personal = channel({+ id: "personal-id",+ name: "me",+ channel_type: "personal",+ system_role: "personal",+});+const general = channel({+ id: "general-id",+ name: "general",+ system_role: "general",+});++describe("spaceRepoAssignment", () => {+ const bothCreated = { personalCreated: true, generalCreated: true };+ const nothingCreated = { personalCreated: false, generalCreated: false };++ describe("planSpaceRepoAssignments", () => {+ it("targets both just-created spaces", () => {+ expect(+ planSpaceRepoAssignments([personal, general], bothCreated),+ ).toEqual(["personal-id", "general-id"]);+ });++ it("still fills an unconfigured pre-existing personal space", () => {+ expect(+ planSpaceRepoAssignments([personal, general], nothingCreated),+ ).toEqual(["personal-id"]);+ });++ it("keeps a configured personal space on re-onboarding", () => {+ // Wiped local storage re-runs onboarding; the pick must not clobber the+ // repos the user already configured on their own space.+ const configured = channel({+ ...personal,+ repositories: ["example/mine"],+ });+ expect(+ planSpaceRepoAssignments([configured, general], nothingCreated),+ ).toEqual([]);+ });++ it("skips an inherited #general even when its repository list is empty", () => {+ expect(+ planSpaceRepoAssignments([personal, general], {+ personalCreated: true,+ generalCreated: false,+ }),+ ).toEqual(["personal-id"]);+ });++ it("skips a just-created #general that a teammate already configured", () => {+ const configured = channel({+ ...general,+ repositories: ["example/app"],+ });+ expect(+ planSpaceRepoAssignments([personal, configured], bothCreated),+ ).toEqual(["personal-id"]);+ });++ it("returns no targets when neither space exists", () => {+ expect(+ planSpaceRepoAssignments(+ [channel({ id: "other", name: "random" })],+ bothCreated,+ ),+ ).toEqual([]);+ });+ });++ describe("resolveRepoIntegrationId", () => {+ const integrations = [+ { id: 1, config: { account: { name: "ExampleOrg" } } },+ { id: 2, config: { account: { name: "other" } } },+ ];++ it("matches the repo owner to the integration account", () => {+ expect(resolveRepoIntegrationId("exampleorg/app", integrations)).toBe(1);+ });++ it("falls back to a sole integration when the owner does not match", () => {+ expect(resolveRepoIntegrationId("unrelated/app", [integrations[0]])).toBe(+ 1,+ );+ });++ it("refuses to guess between several non-matching integrations", () => {+ expect(resolveRepoIntegrationId("unrelated/app", integrations)).toBe(+ null,+ );+ });+ });+});diff --git a/products/desktop/packages/core/src/onboarding/spaceRepoAssignment.ts b/products/desktop/packages/core/src/onboarding/spaceRepoAssignment.tsnew file mode 100644index 000000000000..717b887c04a1--- /dev/null+++ b/products/desktop/packages/core/src/onboarding/spaceRepoAssignment.ts@@ -0,0 +1,68 @@+import {+ type ChannelIdentity,+ isGeneralChannel,+ isPersonalChannel,+} from "../canvas/channelName";++export interface AssignableChannel extends ChannelIdentity {+ id: string;+ repositories?: string[];+}++export interface AssignableGithubIntegration {+ id: number;+ config?: { account?: { name?: string | null } | null };+}++/**+ * Matched by account name, falling back to a sole integration. Returns null+ * rather than guessing between several that do not match the owner.+ */+export function resolveRepoIntegrationId(+ repo: string,+ integrations: AssignableGithubIntegration[],+): number | null {+ const owner = repo.split("/")[0]?.toLowerCase();+ if (owner) {+ const match = integrations.find(+ (integration) =>+ integration.config?.account?.name?.toLowerCase() === owner,+ );+ if (match) return match.id;+ }+ return integrations.length === 1 ? integrations[0].id : null;+}++export interface SpaceRepoAssignmentFlags {+ personalCreated: boolean;+ generalCreated: boolean;+}++/**+ * Which spaces the onboarding repo pick becomes the default for. Re-onboarding+ * (wiped local storage) must not clobber what a user or their team set up, and+ * an empty inherited #general is not the same signal as a just-created one:+ * a teammate may have emptied it on purpose.+ */+export function planSpaceRepoAssignments(+ channels: AssignableChannel[],+ flags: SpaceRepoAssignmentFlags,+): string[] {+ const targets: string[] = [];+ const personal = channels.find((channel) => isPersonalChannel(channel));+ if (+ personal &&+ (flags.personalCreated || (personal.repositories ?? []).length === 0)+ ) {+ targets.push(personal.id);+ }+ const general = channels.find((channel) => isGeneralChannel(channel));+ if (+ general &&+ flags.generalCreated &&+ (general.repositories ?? []).length === 0+ ) {+ targets.push(general.id);+ }+ return targets;+}diff --git a/products/desktop/packages/core/src/onboarding/steps.test.ts b/products/desktop/packages/core/src/onboarding/steps.test.tsindex 2fa10316c6e2..9eb7067dda77 100644--- a/products/desktop/packages/core/src/onboarding/steps.test.ts+++ b/products/desktop/packages/core/src/onboarding/steps.test.ts@@ -11,24 +11,69 @@ import {stepDirection,} from "./steps";+const allSteps = {+ hasCodeAccess: false,+ hasImportableConfig: true,+ hasGithubIntegration: undefined,+ projectCount: 2,+};+describe("computeActiveSteps", () => {it("drops invite-code when the user already has code access", () => {- expect(computeActiveSteps(true, true)).not.toContain("invite-code");+ expect(+ computeActiveSteps({ ...allSteps, hasCodeAccess: true }),+ ).not.toContain("invite-code");});it("keeps invite-code when access is unknown or false", () => {- expect(computeActiveSteps(false, true)).toEqual(ONBOARDING_STEPS);- expect(computeActiveSteps(null, true)).toEqual(ONBOARDING_STEPS);- expect(computeActiveSteps(undefined, true)).toEqual(ONBOARDING_STEPS);+ expect(computeActiveSteps(allSteps)).toEqual(ONBOARDING_STEPS);+ expect(computeActiveSteps({ ...allSteps, hasCodeAccess: null })).toEqual(+ ONBOARDING_STEPS,+ );+ expect(+ computeActiveSteps({ ...allSteps, hasCodeAccess: undefined }),+ ).toEqual(ONBOARDING_STEPS);});it("drops import-config when there is no importable config", () => {- expect(computeActiveSteps(false, false)).not.toContain("import-config");+ expect(+ computeActiveSteps({ ...allSteps, hasImportableConfig: false }),+ ).not.toContain("import-config");+ });++ it("drops project-select only when there is exactly one project", () => {+ expect(computeActiveSteps({ ...allSteps, projectCount: 1 })).not.toContain(+ "project-select",+ );+ expect(computeActiveSteps({ ...allSteps, projectCount: 2 })).toContain(+ "project-select",+ );+ expect(+ computeActiveSteps({ ...allSteps, projectCount: undefined }),+ ).toContain("project-select");+ expect(computeActiveSteps({ ...allSteps, projectCount: 0 })).toContain(+ "project-select",+ );+ });++ it("drops install-cli only on a confirmed github connection", () => {+ expect(+ computeActiveSteps({ ...allSteps, hasGithubIntegration: true }),+ ).not.toContain("install-cli");+ expect(+ computeActiveSteps({ ...allSteps, hasGithubIntegration: false }),+ ).toContain("install-cli");+ expect(computeActiveSteps(allSteps)).toContain("install-cli");});});describe("nearestActiveStep", () => {- const withoutConditionals = computeActiveSteps(true, false);+ const withoutConditionals = computeActiveSteps({+ hasCodeAccess: true,+ hasImportableConfig: false,+ hasGithubIntegration: undefined,+ projectCount: 2,+ });it("returns the step itself while it is still active", () => {expect(nearestActiveStep(ONBOARDING_STEPS, "import-config")).toBe(@@ -61,7 +106,12 @@ describe("nearestActiveStep", () => {});describe("step navigation", () => {- const steps = computeActiveSteps(true, true);+ const steps = computeActiveSteps({+ hasCodeAccess: true,+ hasImportableConfig: true,+ hasGithubIntegration: undefined,+ projectCount: 2,+ });it("identifies first and last steps", () => {expect(isFirstStep(0)).toBe(true);diff --git a/products/desktop/packages/core/src/onboarding/steps.ts b/products/desktop/packages/core/src/onboarding/steps.tsindex 896584f5785e..5d7f34b6a12d 100644--- a/products/desktop/packages/core/src/onboarding/steps.ts+++ b/products/desktop/packages/core/src/onboarding/steps.ts@@ -25,13 +25,21 @@ export interface DetectedRepo {branch?: string;}-export function computeActiveSteps(- hasCodeAccess: boolean | null | undefined,- hasImportableConfig: boolean,-): OnboardingStep[] {+export function computeActiveSteps(options: {+ hasCodeAccess: boolean | null | undefined;+ hasImportableConfig: boolean;+ /** Undefined while the integrations query is loading; the step only drops on a confirmed connection. */+ hasGithubIntegration: boolean | undefined;+ /** Undefined until the project list has loaded, so a slow list cannot skip a real choice. */+ projectCount: number | undefined;+}): OnboardingStep[] {return ONBOARDING_STEPS.filter((step) => {- if (step === "invite-code" && hasCodeAccess === true) return false;- if (step === "import-config" && !hasImportableConfig) return false;+ if (step === "project-select" && options.projectCount === 1) return false;+ if (step === "invite-code" && options.hasCodeAccess === true) return false;+ if (step === "import-config" && !options.hasImportableConfig) return false;+ if (step === "install-cli" && options.hasGithubIntegration === true) {+ return false;+ }return true;});}diff --git a/products/desktop/packages/ui/src/features/git-interaction/components/TaskActionsMenu.stories.tsx b/products/desktop/packages/ui/src/features/git-interaction/components/TaskActionsMenu.stories.tsxnew file mode 100644index 000000000000..970ef7d50f28--- /dev/null+++ b/products/desktop/packages/ui/src/features/git-interaction/components/TaskActionsMenu.stories.tsx@@ -0,0 +1,88 @@+import {+ computeGitInteractionState,+ type GitState,+} from "@posthog/core/git-interaction/gitInteractionLogic";+import type { Meta, StoryObj } from "@storybook/react";+import { GitActionControl } from "./TaskActionsMenu";++// Runs the real computeGitInteractionState over a realistic GitState, so the+// stories show exactly what the task header offers in each environment,+// including which actions are dropped rather than disabled.+const baseState: GitState = {+ repoPath: "/Users/dev/example-repo",+ isRepo: true,+ isRepoLoading: false,+ hasChanges: true,+ aheadOfRemote: 2,+ behind: 0,+ aheadOfDefault: 2,+ hasRemote: true,+ isFeatureBranch: true,+ currentBranch: "feature/add-export",+ defaultBranch: "main",+ ghStatus: { installed: true, authenticated: true },+ repoInfo: { owner: "example", repo: "example-repo" },+ prStatus: {+ prExists: false,+ baseBranch: null,+ headBranch: null,+ prUrl: null,+ },+ isOnline: true,+};++function ControlFor({ state }: { state: GitState }) {+ const computed = computeGitInteractionState(state);+ return (+ <div className="flex flex-col gap-3 p-4">+ <GitActionControl+ primaryAction={computed.primaryAction}+ actions={computed.actions}+ isBusy={false}+ onSelect={() => {}}+ />+ <div className="text-(--gray-10) text-[12px]">+ actions: {computed.actions.map((a) => a.id).join(", ")}+ {computed.createPrDisabledReason+ ? ` · create-pr reason: ${computed.createPrDisabledReason}`+ : ""}+ </div>+ </div>+ );+}++const meta: Meta<typeof ControlFor> = {+ title: "Features/GitInteraction/TaskActionsMenu",+ component: ControlFor,+};+export default meta;++type Story = StoryObj<typeof ControlFor>;++export const Ready: Story = {+ render: () => <ControlFor state={baseState} />,+};++/** How a user gets here: onboarding skipped install-cli because GitHub was+ * connected, then they run a local task. */+export const GhCliMissing: Story = {+ render: () => (+ <ControlFor+ state={{+ ...baseState,+ ghStatus: { installed: false, authenticated: false },+ }}+ />+ ),+};++export const GhCliUnauthenticated: Story = {+ render: () => (+ <ControlFor+ state={{+ ...baseState,+ ghStatus: { installed: true, authenticated: false },+ }}+ />+ ),+};diff --git a/products/desktop/packages/ui/src/features/git-interaction/components/TaskActionsMenu.tsx b/products/desktop/packages/ui/src/features/git-interaction/components/TaskActionsMenu.tsxindex 1cbfd1839943..c9c38fd101b3 100644--- a/products/desktop/packages/ui/src/features/git-interaction/components/TaskActionsMenu.tsx+++ b/products/desktop/packages/ui/src/features/git-interaction/components/TaskActionsMenu.tsx@@ -431,7 +431,7 @@ interface GitActionControlProps {onSelect: (id: GitMenuActionId) => void;}-function GitActionControl({+export function GitActionControl({primaryAction,actions,isBusy,diff --git a/products/desktop/packages/ui/src/features/onboarding/components/ImportConfigStep.tsx b/products/desktop/packages/ui/src/features/onboarding/components/ImportConfigStep.tsxindex 465eafd48df0..43e58ff82c6e 100644--- a/products/desktop/packages/ui/src/features/onboarding/components/ImportConfigStep.tsx+++ b/products/desktop/packages/ui/src/features/onboarding/components/ImportConfigStep.tsx@@ -236,7 +236,7 @@ export function ImportConfigStep({ onNext, onBack }: ImportConfigStepProps) {<ArrowLeft size={16} weight="bold" />Back</Button>- <Button size="3" onClick={onNext}>+ <Button size="3" onClick={() => onNext()}>Continue<ArrowRight size={16} weight="bold" /></Button>diff --git a/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsx b/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsxindex c23086956a65..cce35c2c5143 100644--- a/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsx+++ b/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsx@@ -1,13 +1,27 @@import { ArrowRight, SignOut } from "@phosphor-icons/react";+import { getAuthIdentity } from "@posthog/core/auth/authIdentity";+import { integrationKeys } from "@posthog/core/integrations/repositoryKeys";+import {+ classifyIntegrations,+ type Integration,+} from "@posthog/core/integrations/selectors";import {buildAbandonedProps,buildCompletedProps,buildStepCompletedProps,type StepCompletedContext,} from "@posthog/core/onboarding/analytics";+import {+ planSpaceRepoAssignments,+ resolveRepoIntegrationId,+} from "@posthog/core/onboarding/spaceRepoAssignment";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";+import type { TaskChannel } from "@posthog/shared/domain-types";+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";import { useAuthStateValue } from "@posthog/ui/features/auth/store";import { useLogoutMutation } from "@posthog/ui/features/auth/useAuthMutations";+import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";+import { TASK_CHANNELS_QUERY_KEY } from "@posthog/ui/features/canvas/hooks/useTaskChannels";import { useUserGithubIntegrations } from "@posthog/ui/features/integrations/useIntegrations";import { ConnectGitHubStep } from "@posthog/ui/features/onboarding/components/ConnectGitHubStep";import { ImportConfigStep } from "@posthog/ui/features/onboarding/components/ImportConfigStep";@@ -16,11 +30,16 @@ import { StepIndicator } from "@posthog/ui/features/onboarding/components/StepInimport { WelcomeScreen } from "@posthog/ui/features/onboarding/components/WelcomeScreen";import { useOnboardingFlow } from "@posthog/ui/features/onboarding/hooks/useOnboardingFlow";import { useOnboardingStore } from "@posthog/ui/features/onboarding/onboardingStore";+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";import { shipIt } from "@posthog/ui/primitives/confetti";import { FullScreenLayout } from "@posthog/ui/primitives/FullScreenLayout";import { openTaskInput } from "@posthog/ui/router/useOpenTask";import { track } from "@posthog/ui/shell/analytics";+import { logger } from "@posthog/ui/shell/logger";+import { primeStartupProvision } from "@posthog/ui/shell/startupLocation";+import { useHostCapabilities } from "@posthog/ui/shell/useHostCapabilities";import { Button, Flex } from "@radix-ui/themes";+import { useQueryClient } from "@tanstack/react-query";import { AnimatePresence, LayoutGroup, motion } from "framer-motion";import { useEffect, useRef } from "react";import { useHotkeys } from "react-hotkeys-hook";@@ -30,6 +49,8 @@ import { SelectRepoStep } from "./SelectRepoStep";const IS_DEV = import.meta.env.DEV;+const log = logger.scope("onboarding-flow");+const stepVariants = {enter: (dir: number) => ({ opacity: 0, x: dir * 20 }),center: { opacity: 1, x: 0 },@@ -37,6 +58,7 @@ const stepVariants = {};export function OnboardingFlow() {+ const queryClient = useQueryClient();const {currentStep,currentIndex,@@ -48,6 +70,9 @@ export function OnboardingFlow() {detectedRepo,isDetectingRepo,handleDirectoryChange,+ selectedCloudRepo,+ handleCloudRepoChange,+ hasGithubIntegration,} = useOnboardingFlow();const completeOnboarding = useOnboardingStore((state) => state.completeOnboarding,@@ -58,6 +83,77 @@ export function OnboardingFlow() {(state) => state.status === "authenticated",);const { data: githubUserIntegrations = [] } = useUserGithubIntegrations();+ const setLastUsedWorkspaceMode = useSettingsStore(+ (state) => state.setLastUsedWorkspaceMode,+ );+ const apiClient = useOptionalAuthenticatedClient();+ const { localWorkspaces } = useHostCapabilities();+ const startupIdentity = useAuthStateValue(getAuthIdentity);++ // Best-effort. The response also seeds the channel cache that the first-run+ // landing reads moments later.+ const assignRepoToSpaces = async (): Promise<void> => {+ if (!apiClient) return;+ // Prime the in-flight promise before the first await so startup consumes+ // this result instead of provisioning again and reading false created+ // flags. This runs synchronously before completeOnboarding mounts the main+ // app, which is what wins the race against startup's own provisioning.+ const provisionPromise = apiClient.provisionDefaultTaskChannels();+ if (startupIdentity)+ primeStartupProvision(startupIdentity, provisionPromise);+ const provisioned = await provisionPromise;+ // Set before the entry exists: setQueryData builds the query from the defaults in+ // place at that moment, and an unmarked entry survives clearAuthScopedQueries and+ // hands the next account these channels. Every mounted read of this key is already+ // auth-scoped via useAuthenticatedQuery; this covers the one write that precedes them.+ queryClient.setQueryDefaults(TASK_CHANNELS_QUERY_KEY, {+ meta: AUTH_SCOPED_QUERY_META,+ });+ queryClient.setQueryData(TASK_CHANNELS_QUERY_KEY, provisioned.channels);+ // Cloud-only hosts keep the picked GitHub repo in selectedDirectory (they+ // never set selectedCloudRepo). On local-workspace hosts selectedDirectory+ // can be a filesystem path, so only the explicit cloud pick is a valid+ // "owner/repo" space default there.+ const cloudRepo = localWorkspaces+ ? selectedCloudRepo+ : selectedDirectory || null;+ if (!cloudRepo) return;+ // Fetched directly: the integrations store only fills once the main app's+ // hooks mount, which has not happened during onboarding.+ const integrations = await queryClient.fetchQuery({+ queryKey: integrationKeys.list(),+ queryFn: () => apiClient.getIntegrations() as Promise<Integration[]>,+ staleTime: 60_000,+ meta: AUTH_SCOPED_QUERY_META,+ });+ const integrationId = resolveRepoIntegrationId(+ cloudRepo,+ classifyIntegrations(integrations).githubIntegrations,+ );+ // Channels only accept a team integration alongside repositories, so a+ // user-level-only GitHub connection cannot set a space default.+ if (integrationId == null) return;+ for (const channelId of planSpaceRepoAssignments(provisioned.channels, {+ personalCreated: provisioned.personal_created,+ generalCreated: provisioned.general_created,+ })) {+ const updated = await apiClient.updateTaskChannelRepositories(+ channelId,+ integrationId,+ [cloudRepo],+ );+ // The direct API call bypasses the standard mutation's cache sync, so+ // patch the seeded channel cache with the assigned repository. Otherwise+ // consumers stay on the repository-less provision response until the poll.+ queryClient.setQueryData<TaskChannel[]>(+ TASK_CHANNELS_QUERY_KEY,+ (channels) =>+ channels?.map((channel) =>+ channel.id === updated.id ? updated : channel,+ ),+ );+ }+ };const flowStartedAtRef = useRef(Date.now());const stepEnteredAtRef = useRef(Date.now());@@ -113,7 +209,11 @@ export function OnboardingFlow() {};const handleNext = (context?: StepCompletedContext) => {- trackStepCompleted(context);+ // `onClick={onNext}` would pass the click event here; a DOM event spread+ // into capture properties poisons the whole analytics batch.+ const safeContext =+ context && "nativeEvent" in context ? undefined : context;+ trackStepCompleted(safeContext);trackStepViewed(currentIndex + 1);next();};@@ -147,6 +247,19 @@ export function OnboardingFlow() {repoSkipped,}),);+ if (githubUserIntegrations.length > 0) {+ // GitHub connected defaults the run mode to cloud (overriding a local+ // mode left behind by an earlier session), but an explicit local folder+ // pick in this step must win over that default. On cloud-only hosts+ // selectedDirectory holds an "owner/repo" value, not a local path, so+ // only treat it as a local pick on local-workspace hosts.+ const pickedLocalRepo =+ localWorkspaces && !selectedCloudRepo && !!selectedDirectory;+ setLastUsedWorkspaceMode(pickedLocalRepo ? "local" : "cloud");+ }+ assignRepoToSpaces().catch((error) =>+ log.warn("Failed to save onboarding repo to spaces", { error }),+ );shipIt();completeOnboarding();openTaskInput();@@ -316,6 +429,9 @@ export function OnboardingFlow() {detectedRepo={detectedRepo}isDetectingRepo={isDetectingRepo}onDirectoryChange={handleDirectoryChange}+ selectedCloudRepo={selectedCloudRepo}+ onCloudRepoChange={handleCloudRepoChange}+ hasGithubIntegration={hasGithubIntegration}/></motion.div>)}diff --git a/products/desktop/packages/ui/src/features/onboarding/components/SelectRepoStep.tsx b/products/desktop/packages/ui/src/features/onboarding/components/SelectRepoStep.tsxindex 828bcfe07ab3..e07842d4abba 100644--- a/products/desktop/packages/ui/src/features/onboarding/components/SelectRepoStep.tsx+++ b/products/desktop/packages/ui/src/features/onboarding/components/SelectRepoStep.tsx@@ -11,7 +11,7 @@ import { cn } from "@posthog/quill";import { useHostCapabilities } from "@posthog/ui/shell/useHostCapabilities";import { Box, Button, Flex, Text } from "@radix-ui/themes";import { AnimatePresence, motion } from "framer-motion";-import { useMemo } from "react";+import { useMemo, useState } from "react";import { builderHog } from "../../../assets/hedgehogs";import { OnboardingHogTip } from "../../../primitives/OnboardingHogTip";import { FolderPicker } from "../../folder-picker/FolderPicker";@@ -29,8 +29,13 @@ interface SelectRepoStepProps {detectedRepo: DetectedRepo | null;isDetectingRepo: boolean;onDirectoryChange: (path: string) => void;+ selectedCloudRepo: string | null;+ onCloudRepoChange: (repo: string | null) => void;+ hasGithubIntegration: boolean | undefined;}+type RepoSource = "github" | "local";+export function SelectRepoStep({onComplete,onBack,@@ -38,6 +43,9 @@ export function SelectRepoStep({detectedRepo,isDetectingRepo,onDirectoryChange,+ selectedCloudRepo,+ onCloudRepoChange,+ hasGithubIntegration,}: SelectRepoStepProps) {const { localWorkspaces } = useHostCapabilities();const {@@ -47,11 +55,24 @@ export function SelectRepoStep({refreshRepositories,} = useUserRepositoryIntegration();+ // `null` follows the default source until the user switches explicitly.+ const [chosenSource, setChosenSource] = useState<RepoSource | null>(null);+ const showSourceSwitch = localWorkspaces && hasGithubIntegration === true;+ const repoSource: RepoSource = !localWorkspaces+ ? "github"+ : (chosenSource ?? (hasGithubIntegration ? "github" : "local"));+const repoMatchesGitHub = useMemo(() => repoMatchesGitHubRepos(detectedRepo, repositories),[detectedRepo, repositories],);+ // Cloud-only hosts keep the picked repo in selectedDirectory.+ const hasSelection =+ localWorkspaces && repoSource === "github"+ ? !!selectedCloudRepo+ : !!selectedDirectory;+return (<Flex align="center" height="100%" px="8"><Flex@@ -104,31 +125,62 @@ export function SelectRepoStep({</Text></Flex><Text className="text-(--gray-11) text-sm">- {localWorkspaces- ? "Select a single repository folder, not a parent folder that contains multiple repos."- : "Pick a repository from your connected GitHub organizations."}+ {repoSource === "github"+ ? "Pick a repository from your connected GitHub organizations. Tasks on it run in cloud sandboxes."+ : "Select a single repository folder, not a parent folder that contains multiple repos."}</Text></Flex>- {localWorkspaces ? (- <FolderPicker- variant="field"- value={selectedDirectory}- onChange={onDirectoryChange}- placeholder="Select repository..."- />- ) : (+ {repoSource === "github" ? (<GitHubRepoPicker- value={selectedDirectory || null}- onChange={(repo) => onDirectoryChange(repo ?? "")}+ value={+ localWorkspaces+ ? selectedCloudRepo+ : selectedDirectory || null+ }+ onChange={(repo) =>+ localWorkspaces+ ? onCloudRepoChange(repo)+ : onDirectoryChange(repo ?? "")+ }repositories={repositories}isLoading={isLoadingRepos}onRefresh={refreshRepositories}isRefreshing={isRefreshingRepos}placeholder="Select repository..."/>+ ) : (+ <FolderPicker+ variant="field"+ value={selectedDirectory}+ onChange={onDirectoryChange}+ placeholder="Select repository..."+ />+ )}+ {showSourceSwitch && (+ <button+ type="button"+ onClick={() => {+ const nextSource =+ repoSource === "github" ? "local" : "github";+ // Clear the source being left so a later Skip cannot+ // silently assign or persist a repo the user+ // navigated away from.+ if (nextSource === "local") {+ onCloudRepoChange(null);+ } else {+ onDirectoryChange("");+ }+ setChosenSource(nextSource);+ }}+ className="cursor-pointer self-start border-0 bg-transparent p-0 text-(--gray-10) text-[13px] underline hover:text-(--gray-11)"+ >+ {repoSource === "github"+ ? "Use a local folder instead"+ : "Back to GitHub repos"}+ </button>)}<AnimatePresence mode="wait">- {localWorkspaces && isDetectingRepo && (+ {repoSource === "local" && isDetectingRepo && (<motion.divkey="detecting"initial={{ opacity: 0 }}@@ -147,7 +199,7 @@ export function SelectRepoStep({</Flex></motion.div>)}- {localWorkspaces &&+ {repoSource === "local" &&!isDetectingRepo &&selectedDirectory &&detectedRepo && (@@ -183,7 +235,7 @@ export function SelectRepoStep({</Flex></motion.div>)}- {localWorkspaces &&+ {repoSource === "local" &&!isDetectingRepo &&selectedDirectory &&!detectedRepo && (@@ -236,7 +288,7 @@ export function SelectRepoStep({<ArrowLeft size={16} weight="bold" />Back</Button>- {selectedDirectory ? (+ {hasSelection ? (<Button size="3" onClick={() => onComplete(false)}>Get started<ArrowRight size={16} weight="bold" />diff --git a/products/desktop/packages/ui/src/features/onboarding/components/WelcomeScreen.tsx b/products/desktop/packages/ui/src/features/onboarding/components/WelcomeScreen.tsxindex e22d0ac68c3c..f767c832b7cb 100644--- a/products/desktop/packages/ui/src/features/onboarding/components/WelcomeScreen.tsx+++ b/products/desktop/packages/ui/src/features/onboarding/components/WelcomeScreen.tsx@@ -310,7 +310,7 @@ export function WelcomeScreen({ onNext }: WelcomeScreenProps) {message="Let's get you set up! It only takes a minute."/><StepActions delay={0.25}>- <Button size="3" onClick={onNext}>+ <Button size="3" onClick={() => onNext()}>Start shipping<ArrowRight size={16} weight="bold" /></Button>diff --git a/products/desktop/packages/ui/src/features/onboarding/hooks/useOnboardingFlow.ts b/products/desktop/packages/ui/src/features/onboarding/hooks/useOnboardingFlow.tsindex 0798414e10e8..83ab96529d16 100644--- a/products/desktop/packages/ui/src/features/onboarding/hooks/useOnboardingFlow.ts+++ b/products/desktop/packages/ui/src/features/onboarding/hooks/useOnboardingFlow.ts@@ -15,7 +15,11 @@ import {} from "@posthog/core/onboarding/steps";import { useHostTRPCClient } from "@posthog/host-router/react";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";-import { useAuthStateValue } from "@posthog/ui/features/auth/store";+import {+ useAuthStateFetched,+ useAuthStateValue,+} from "@posthog/ui/features/auth/store";+import { useUserGithubIntegrations } from "@posthog/ui/features/integrations/useIntegrations";import { useOnboardingStore } from "@posthog/ui/features/onboarding/onboardingStore";import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";import { useActiveRepoStore } from "@posthog/ui/shell/activeRepoStore";@@ -55,6 +59,25 @@ export function useOnboardingFlow() {.finally(() => setIsDetectingRepo(false));}, [selectedDirectory, hostClient, localWorkspaces]);+ const [selectedCloudRepo, setSelectedCloudRepo] = useState<string | null>(+ null,+ );+ const handleCloudRepoChange = useCallback(+ (repo: string | null) => {+ setSelectedCloudRepo(repo);+ setLastUsedCloudRepository(repo);+ if (repo) {+ setSelectedDirectory("");+ setDetectedRepo(null);+ track(ANALYTICS_EVENTS.ONBOARDING_FOLDER_SELECTED, {+ has_git_remote: true,+ repository_provider: "github",+ });+ }+ },+ [setLastUsedCloudRepository, setSelectedDirectory],+ );+const handleDirectoryChange = useCallback(async (path: string) => {setSelectedDirectory(path);@@ -71,6 +94,9 @@ export function useOnboardingFlow() {return;}+ setSelectedCloudRepo(null);+ setLastUsedCloudRepository(null);+if (!path) return;setIsDetectingRepo(true);@@ -105,10 +131,34 @@ export function useOnboardingFlow() {const hasCodeAccess = useAuthStateValue((state) => state.hasCodeAccess);const hasImportableConfig = useHasImportableConfig();+ const { data: githubUserIntegrations } = useUserGithubIntegrations();+ const hasGithubIntegration = githubUserIntegrations+ ? githubUserIntegrations.length > 0+ : undefined;+ // Counted off the store rather than through useProjects, whose auto-select+ // effect would then run in a second place and re-clear the query cache.+ const orgProjectsMap = useAuthStateValue((state) => state.orgProjectsMap);+ const authFetched = useAuthStateFetched();+ const projectCount = useMemo(+ () =>+ authFetched+ ? Object.values(orgProjectsMap).reduce(+ (total, org) => total + org.projects.length,+ 0,+ )+ : undefined,+ [authFetched, orgProjectsMap],+ );const activeSteps = useMemo(- () => computeActiveSteps(hasCodeAccess, hasImportableConfig),- [hasCodeAccess, hasImportableConfig],+ () =>+ computeActiveSteps({+ hasCodeAccess,+ hasImportableConfig,+ hasGithubIntegration,+ projectCount,+ }),+ [hasCodeAccess, hasImportableConfig, hasGithubIntegration, projectCount],);useEffect(() => {@@ -157,5 +207,8 @@ export function useOnboardingFlow() {detectedRepo,isDetectingRepo,handleDirectoryChange,+ selectedCloudRepo,+ handleCloudRepoChange,+ hasGithubIntegration,};}diff --git a/products/desktop/packages/ui/src/shell/startupLocation.test.ts b/products/desktop/packages/ui/src/shell/startupLocation.test.tsindex 6fbe95b7be60..ec89a69ae1e1 100644--- a/products/desktop/packages/ui/src/shell/startupLocation.test.ts+++ b/products/desktop/packages/ui/src/shell/startupLocation.test.ts@@ -113,14 +113,45 @@ describe("startup location", () => {expect(removeItem).not.toHaveBeenCalled();});+ it("ignores a hand-off primed by a different account", async () => {+ // A logout or account switch between priming and consuming would otherwise hand the+ // next account the previous project's channels.+ vi.spyOn(stateStorage, "getItem").mockResolvedValue(null);+ const client = {+ provisionDefaultTaskChannels: vi.fn().mockResolvedValue({+ channels: [personal, general],+ personal_created: false,+ general_created: false,+ }),+ startOnboardingSession: vi.fn().mockResolvedValue(true),+ };+ primeStartupProvision(+ "someone-else",+ Promise.resolve({+ channels: [personal, general],+ personal_created: true,+ general_created: true,+ }),+ );++ await expect(resolveStartupLocation("project", client)).resolves.toEqual({+ href: "/website/general-id",+ firstRun: null,+ });+ expect(client.provisionDefaultTaskChannels).toHaveBeenCalledOnce();+ });+it("consumes a primed provisioning result exactly once", async () => {vi.spyOn(stateStorage, "getItem").mockResolvedValue(null);const client = { provisionDefaultTaskChannels: vi.fn() };- primeStartupProvision({- channels: [personal, general],- personal_created: true,- general_created: false,- });+ primeStartupProvision(+ "project",+ Promise.resolve({+ channels: [personal, general],+ personal_created: true,+ general_created: false,+ }),+ );await expect(resolveStartupLocation("project", client)).resolves.toEqual({href: "/website/general-id",diff --git a/products/desktop/packages/ui/src/shell/startupLocation.ts b/products/desktop/packages/ui/src/shell/startupLocation.tsindex 15f76dda3ba7..b20abd7c2ccc 100644--- a/products/desktop/packages/ui/src/shell/startupLocation.ts+++ b/products/desktop/packages/ui/src/shell/startupLocation.ts@@ -19,15 +19,43 @@ interface StartupLocation {firstRun: { generalChannelId: string } | null;}-let primedProvision: ProvisionedTaskChannels | null = null;+let primedProvision: {+ identity: string;+ result: Promise<ProvisionedTaskChannels>;+} | null = null;/*** Whoever provisions first consumes the created flags, so a flow that provisions* before the app mounts has to hand its result over rather than let startup- * provision again and read false flags.+ * provision again and read false flags. The in-flight promise is handed over+ * (not the resolved value) so the hand-off wins the race synchronously, before+ * the caller mounts the app, even while the network call is still pending.*/-export function primeStartupProvision(result: ProvisionedTaskChannels): void {- primedProvision = result;+export function primeStartupProvision(+ identity: string,+ result: Promise<ProvisionedTaskChannels>,+): void {+ primedProvision = { identity, result };+}++async function consumePrimedProvision(+ identity: string,+ client: StartupLocationClient,+): Promise<ProvisionedTaskChannels> {+ const primed = primedProvision;+ primedProvision = null;+ // Keyed by identity because a logout or account switch between priming and+ // consuming would otherwise hand the next account the previous project's+ // channels. Everything else in this module is already keyed the same way.+ if (primed && primed.identity === identity) {+ try {+ return await primed.result;+ } catch {+ // A failed hand-off must not cost the user their provisioning, so fall+ // back to provisioning here as if nothing had been primed.+ }+ }+ return client.provisionDefaultTaskChannels();}export async function resolveStartupLocation(@@ -48,9 +76,7 @@ export async function resolveStartupLocation(return { href: legacy, firstRun: null };}- const provisioned =- primedProvision ?? (await client.provisionDefaultTaskChannels());- primedProvision = null;+ const provisioned = await consumePrimedProvision(identity, client);const general = provisioned.channels.find((channel) =>isGeneralChannel(channel),);