: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): add organization consent onboarding (#87554)
Adam Bowkerc5f021b8314b
diff --git a/products/desktop/packages/core/src/onboarding/steps.test.ts b/products/desktop/packages/core/src/onboarding/steps.test.tsindex 9eb7067dda77..5d9bd14e9d44 100644--- a/products/desktop/packages/core/src/onboarding/steps.test.ts+++ b/products/desktop/packages/core/src/onboarding/steps.test.ts@@ -16,6 +16,7 @@ const allSteps = {hasImportableConfig: true,hasGithubIntegration: undefined,projectCount: 2,+ consentRequired: true,};describe("computeActiveSteps", () => {@@ -65,6 +66,18 @@ describe("computeActiveSteps", () => {).toContain("install-cli");expect(computeActiveSteps(allSteps)).toContain("install-cli");});++ it("includes consent from the sampled requirement", () => {+ expect(ONBOARDING_STEPS.indexOf("consent")).toBe(+ ONBOARDING_STEPS.indexOf("invite-code") + 1,+ );+ expect(+ computeActiveSteps({ ...allSteps, consentRequired: undefined }),+ ).toContain("consent");+ expect(+ computeActiveSteps({ ...allSteps, consentRequired: false }),+ ).not.toContain("consent");+ });});describe("nearestActiveStep", () => {@@ -73,6 +86,7 @@ describe("nearestActiveStep", () => {hasImportableConfig: false,hasGithubIntegration: undefined,projectCount: 2,+ consentRequired: true,});it("returns the step itself while it is still active", () => {@@ -85,7 +99,7 @@ describe("nearestActiveStep", () => {// import-config vanished under the user: continue forward to select-repo,// not back to welcome (the regression that reset onboarding mid-flow).{ removed: "import-config", expected: "select-repo" },- { removed: "invite-code", expected: "connect-github" },+ { removed: "invite-code", expected: "consent" },])("moves forward to $expected when $removed drops out",({ removed, expected }) => {@@ -111,6 +125,7 @@ describe("step navigation", () => {hasImportableConfig: true,hasGithubIntegration: undefined,projectCount: 2,+ consentRequired: true,});it("identifies first and last steps", () => {diff --git a/products/desktop/packages/core/src/onboarding/steps.ts b/products/desktop/packages/core/src/onboarding/steps.tsindex 5d7f34b6a12d..9525bca608f3 100644--- a/products/desktop/packages/core/src/onboarding/steps.ts+++ b/products/desktop/packages/core/src/onboarding/steps.ts@@ -2,6 +2,7 @@ export type OnboardingStep =| "welcome"| "project-select"| "invite-code"+ | "consent"| "connect-github"| "install-cli"| "import-config"@@ -11,6 +12,7 @@ export const ONBOARDING_STEPS: OnboardingStep[] = ["welcome","project-select","invite-code",+ "consent","connect-github","install-cli","import-config",@@ -32,10 +34,12 @@ export function computeActiveSteps(options: {hasGithubIntegration: boolean | undefined;/** Undefined until the project list has loaded, so a slow list cannot skip a real choice. */projectCount: number | undefined;+ consentRequired: boolean | undefined;}): OnboardingStep[] {return ONBOARDING_STEPS.filter((step) => {if (step === "project-select" && options.projectCount === 1) return false;if (step === "invite-code" && options.hasCodeAccess === true) return false;+ if (step === "consent" && options.consentRequired === false) return false;if (step === "import-config" && !options.hasImportableConfig) return false;if (step === "install-cli" && options.hasGithubIntegration === true) {return false;diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.tsindex 2749e6e183fe..0a38616b53c0 100644--- a/products/desktop/packages/shared/src/analytics-events.ts+++ b/products/desktop/packages/shared/src/analytics-events.ts@@ -482,6 +482,7 @@ export type OnboardingStepId =| "welcome"| "project-select"| "invite-code"+ | "consent"| "connect-github"| "install-cli"| "import-config"@@ -579,6 +580,9 @@ export interface OnboardingAbandonedProperties {export interface AiConsentGateShownProperties {is_org_admin: boolean;+ outstanding_ai_consent: boolean;+ outstanding_beta_terms: boolean;+ surface: "onboarding_step" | "standalone_gate";}// Setup / onboarding events@@ -1465,6 +1469,8 @@ export const ANALYTICS_EVENTS = {AI_CONSENT_GATE_SHOWN: "Ai consent gate shown",AI_CONSENT_APPROVED: "Ai consent approved",AI_CONSENT_GRANTED_INAPP: "Ai consent granted in-app",+ DESKTOP_BETA_TERMS_ACCEPTED: "Desktop beta terms accepted",+ DESKTOP_BETA_TERMS_ACCEPTED_INAPP: "Desktop beta terms accepted in-app",// Setup / onboarding eventsSETUP_DISCOVERY_STARTED: "Setup discovery started",@@ -1654,6 +1660,8 @@ export type EventPropertyMap = {[ANALYTICS_EVENTS.AI_CONSENT_GATE_SHOWN]: AiConsentGateShownProperties;[ANALYTICS_EVENTS.AI_CONSENT_APPROVED]: never;[ANALYTICS_EVENTS.AI_CONSENT_GRANTED_INAPP]: never;+ [ANALYTICS_EVENTS.DESKTOP_BETA_TERMS_ACCEPTED]: never;+ [ANALYTICS_EVENTS.DESKTOP_BETA_TERMS_ACCEPTED_INAPP]: never;// Setup / onboarding events[ANALYTICS_EVENTS.SETUP_DISCOVERY_STARTED]: SetupDiscoveryStartedProperties;diff --git a/products/desktop/packages/ui/src/features/ai-approval/AiApprovalScreen.test.tsx b/products/desktop/packages/ui/src/features/ai-approval/AiApprovalScreen.test.tsxdeleted file mode 100644index 3dd2030b8917..000000000000--- a/products/desktop/packages/ui/src/features/ai-approval/AiApprovalScreen.test.tsx+++ /dev/null@@ -1,105 +0,0 @@-import { Theme } from "@radix-ui/themes";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { render, screen, waitFor } from "@testing-library/react";-import userEvent from "@testing-library/user-event";-import { beforeEach, describe, expect, it, vi } from "vitest";--// Hoisted so the spies are initialized before the hoisted vi.mock factories-// that reference them run.-const { approveAiDataProcessing, logoutMutate, openSettings } = vi.hoisted(- () => ({- approveAiDataProcessing: vi.fn(),- logoutMutate: vi.fn(),- openSettings: vi.fn(),- }),-);--vi.mock("@posthog/ui/features/auth/authClient", () => ({- useAuthenticatedClient: () => ({ approveAiDataProcessing }),-}));--vi.mock("@posthog/ui/features/auth/useAuthMutations", () => ({- useLogoutMutation: () => ({ mutate: logoutMutate }),-}));--vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({- authKeys: { currentUsers: () => ["auth", "current-user"] },-}));--vi.mock("@posthog/ui/features/settings/SettingsDialog", () => ({- SettingsDialog: () => null,- openSettingsDialog: openSettings,-}));--vi.mock("@posthog/ui/shell/analytics", () => ({ track: vi.fn() }));--import { AiApprovalScreen } from "./AiApprovalScreen";--function renderInTheme(isAdmin: boolean) {- const queryClient = new QueryClient({- defaultOptions: { mutations: { retry: false }, queries: { retry: false } },- });- return render(- <QueryClientProvider client={queryClient}>- <Theme>- <AiApprovalScreen- organizationId="org-id"- orgName="Acme"- isAdmin={isAdmin}- />- </Theme>- </QueryClientProvider>,- );-}--describe("AiApprovalScreen", () => {- beforeEach(() => {- approveAiDataProcessing.mockReset();- logoutMutate.mockReset();- openSettings.mockReset();- });-- it("calls approveAiDataProcessing once when the admin clicks the button", async () => {- approveAiDataProcessing.mockResolvedValueOnce(undefined);- const user = userEvent.setup();-- renderInTheme(true);-- const button = screen.getByRole("button", {- name: /Approve AI data processing/i,- });- await user.click(button);-- await waitFor(() =>- expect(approveAiDataProcessing).toHaveBeenCalledExactlyOnceWith("org-id"),- );- });-- it("renders the ask-admin copy and no approve button for non-admin users", () => {- renderInTheme(false);-- expect(- screen.getByText(- /Ask an organization admin to approve AI data processing/i,- ),- ).toBeInTheDocument();- expect(- screen.queryByRole("button", { name: /Approve AI data processing/i }),- ).not.toBeInTheDocument();- });-- it("shows an error callout when the approval request rejects", async () => {- approveAiDataProcessing.mockRejectedValueOnce(new Error("forbidden"));- const user = userEvent.setup();-- renderInTheme(true);-- await user.click(- screen.getByRole("button", { name: /Approve AI data processing/i }),- );-- expect(- await screen.findByText(/Could not approve AI data processing/i),- ).toBeInTheDocument();- });-});diff --git a/products/desktop/packages/ui/src/features/ai-approval/AiApprovalScreen.tsx b/products/desktop/packages/ui/src/features/ai-approval/AiApprovalScreen.tsxdeleted file mode 100644index 570e53e73dee..000000000000--- a/products/desktop/packages/ui/src/features/ai-approval/AiApprovalScreen.tsx+++ /dev/null@@ -1,191 +0,0 @@-import { GearSix, Robot, SignOut, WarningCircle } from "@phosphor-icons/react";-import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";-import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import { useLogoutMutation } from "@posthog/ui/features/auth/useAuthMutations";-import { authKeys } from "@posthog/ui/features/auth/useCurrentUser";-import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";-import { openSettingsDialog } from "@posthog/ui/features/settings/SettingsDialog";-import { FullScreenLayout } from "@posthog/ui/primitives/FullScreenLayout";-import { track } from "@posthog/ui/shell/analytics";-import { Button, Callout, Flex, Spinner, Text } from "@radix-ui/themes";-import { useMutation, useQueryClient } from "@tanstack/react-query";-import { motion } from "framer-motion";-import { type ReactNode, useEffect } from "react";-import { useHotkeys } from "react-hotkeys-hook";--interface AiApprovalScreenProps {- organizationId: string;- orgName: string | null;- isAdmin: boolean;- banner?: ReactNode;- onOpenSupport?: () => void;- settingsDialog?: ReactNode;-}--export function AiApprovalScreen({- organizationId,- orgName,- isAdmin,- banner,- onOpenSupport,- settingsDialog,-}: AiApprovalScreenProps) {- const logoutMutation = useLogoutMutation();- const client = useAuthenticatedClient();- const queryClient = useQueryClient();-- const approveMutation = useMutation({- mutationFn: async () => {- await client.approveAiDataProcessing(organizationId);- },- onSuccess: async () => {- track(ANALYTICS_EVENTS.AI_CONSENT_GRANTED_INAPP);- await queryClient.invalidateQueries({- queryKey: authKeys.currentUsers(),- });- },- });-- // biome-ignore lint/correctness/useExhaustiveDependencies: fire once on mount; later isAdmin changes from query resolution should not re-fire- useEffect(() => {- track(ANALYTICS_EVENTS.AI_CONSENT_GATE_SHOWN, { is_org_admin: isAdmin });- }, []);-- useHotkeys(SHORTCUTS.SETTINGS, () => openSettingsDialog(), {- preventDefault: true,- enableOnFormTags: true,- });-- const footerLeft = (- <Button- size="1"- variant="ghost"- color="gray"- onClick={() => openSettingsDialog()}- className="opacity-70"- >- <GearSix size={14} />- Settings- </Button>- );-- const footerRight = (- <Button- size="1"- variant="ghost"- color="gray"- onClick={() => logoutMutation.mutate()}- className="opacity-50"- >- <SignOut size={14} />- Log out- </Button>- );-- return (- <>- <FullScreenLayout- footerLeft={footerLeft}- footerRight={footerRight}- banner={banner}- onOpenSupport={onOpenSupport}- >- <Flex align="center" justify="center" height="100%" px="8">- <Flex- direction="column"- className="w-full max-w-[560px] pt-[24px] pb-[40px]"- >- <motion.div- initial={{ opacity: 0, y: 8 }}- animate={{ opacity: 1, y: 0 }}- transition={{ duration: 0.3 }}- >- <Flex direction="column" gap="4">- <Flex direction="column" gap="2">- <Flex align="center" gap="2">- <Robot- size={22}- weight="duotone"- color="var(--accent-10)"- />- <Text className="font-bold text-(--gray-12) text-2xl">- PostHog AI needs your approval- </Text>- </Flex>- <Text className="text-(--gray-11) text-sm">- {orgName ? (- <>- Your "<strong>{orgName}</strong>" organization hasn't- approved AI data processing yet.- </>- ) : (- "Your organization hasn't approved AI data processing yet."- )}- </Text>- <Text className="text-(--gray-11) text-sm">- PostHog AI features process identifying user data with- external AI providers.- <br />- Importantly: Your data won't be used for training models by- these providers.- </Text>- </Flex>-- <Callout.Root color="amber" size="1" variant="soft">- <Callout.Icon>- <WarningCircle />- </Callout.Icon>- <Callout.Text>- <h4 className="mb-1 font-bold">- Legal bits about Protected Health Information- </h4>- This app isn't <i>yet</i> HIPAA-compliant and is not- intended for processing of Protected Health Information- ("PHI").- <br />- If you've entered into a Business Associate Agreement- ("BAA") with PostHog, it does not currently apply to PostHog- Code features.- </Callout.Text>- </Callout.Root>-- {isAdmin ? (- <Flex direction="column" gap="2">- <Button- size="3"- onClick={() => approveMutation.mutate()}- disabled={approveMutation.isPending}- className="w-full"- >- {approveMutation.isPending ? (- <Spinner size="2" />- ) : (- "Approve AI data processing"- )}- </Button>- {approveMutation.isError && (- <Callout.Root color="red" size="1">- <Callout.Icon>- <WarningCircle />- </Callout.Icon>- <Callout.Text>- Could not approve AI data processing. Try again or- contact support.- </Callout.Text>- </Callout.Root>- )}- </Flex>- ) : (- <Text className="text-(--gray-11) text-sm">- Ask an organization admin to approve AI data processing.- </Text>- )}- </Flex>- </motion.div>- </Flex>- </Flex>- </FullScreenLayout>- {settingsDialog}- </>- );-}diff --git a/products/desktop/packages/ui/src/features/consent/ConsentErrorContent.tsx b/products/desktop/packages/ui/src/features/consent/ConsentErrorContent.tsxnew file mode 100644index 000000000000..4bdf64f30c5b--- /dev/null+++ b/products/desktop/packages/ui/src/features/consent/ConsentErrorContent.tsx@@ -0,0 +1,22 @@+import { Button, Text } from "@posthog/quill";++interface ConsentErrorContentProps {+ onRetry: () => void;+}++export function ConsentErrorContent({ onRetry }: ConsentErrorContentProps) {+ return (+ <div className="flex w-full max-w-[520px] flex-col gap-4 text-center">+ <h1 className="font-bold text-2xl text-foreground">+ Could not check organization consent+ </h1>+ <Text size="sm" variant="muted">+ Check your connection and try again. If this keeps happening, contact+ support.+ </Text>+ <Button variant="primary" size="lg" onClick={onRetry}>+ Retry+ </Button>+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/consent/ConsentPanel.test.tsx b/products/desktop/packages/ui/src/features/consent/ConsentPanel.test.tsxnew file mode 100644index 000000000000..5cce5a7e8f9b--- /dev/null+++ b/products/desktop/packages/ui/src/features/consent/ConsentPanel.test.tsx@@ -0,0 +1,127 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it, vi } from "vitest";++const { acceptBetaTerms, approveAiDataProcessing } = vi.hoisted(() => ({+ acceptBetaTerms: vi.fn(),+ approveAiDataProcessing: vi.fn(),+}));++vi.mock("@posthog/ui/features/auth/authClient", () => ({+ useAuthenticatedClient: () => ({+ acceptDesktopBetaTerms: acceptBetaTerms,+ approveAiDataProcessing,+ }),+}));++vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({+ authKeys: { currentUsers: () => ["auth", "current-user"] },+ useCurrentUser: () => ({+ data: { organization: { id: "org-id", name: "Example Org" } },+ }),+}));++vi.mock("@posthog/ui/shell/analytics", () => ({ track: vi.fn() }));++import { ConsentPanel } from "./ConsentPanel";++function renderPanel(+ needsAiConsent: boolean,+ needsBetaTerms: boolean,+ isAdmin = true,+ requirements?: {+ needsAiConsent: boolean;+ needsBetaTerms: boolean;+ },+) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={queryClient}>+ <ConsentPanel+ consent={{+ status: "resolved",+ organizationId: "org-id",+ needsAiConsent,+ needsBetaTerms,+ satisfied: !needsAiConsent && !needsBetaTerms,+ }}+ requirements={requirements}+ isAdmin={isAdmin}+ />+ </QueryClientProvider>,+ );+}++describe("ConsentPanel", () => {+ beforeEach(() => {+ acceptBetaTerms.mockReset();+ approveAiDataProcessing.mockReset();+ });++ it("shows and accepts only the outstanding beta terms", async () => {+ acceptBetaTerms.mockResolvedValue(undefined);+ const user = userEvent.setup();+ renderPanel(false, true);++ expect(+ screen.queryByRole("button", { name: "Approve AI data processing" }),+ ).not.toBeInTheDocument();+ expect(screen.getByText("PostHog Desktop beta terms")).toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Accept beta terms" }));++ await waitFor(() =>+ expect(acceptBetaTerms).toHaveBeenCalledExactlyOnceWith("org-id"),+ );+ expect(approveAiDataProcessing).not.toHaveBeenCalled();+ });++ it("presents separate actions and keeps legal detail optional", async () => {+ const user = userEvent.setup();+ renderPanel(true, true);++ expect(+ screen.getByRole("button", { name: "Approve AI data processing" }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Accept beta terms" }),+ ).toBeInTheDocument();+ const details = screen.getAllByRole("button", { name: "Details" });+ expect(details[0]).toHaveAttribute("aria-expanded", "false");+ await user.click(details[0]);+ expect(details[0]).toHaveAttribute("aria-expanded", "true");+ });++ it("keeps each decision visible and marks it accepted", () => {+ renderPanel(false, false, true, {+ needsAiConsent: true,+ needsBetaTerms: true,+ });++ expect(screen.getAllByRole("button", { name: "Accepted" })).toHaveLength(2);+ });++ it("keeps one failed decision recoverable without retrying the other", async () => {+ approveAiDataProcessing.mockResolvedValue(undefined);+ acceptBetaTerms.mockRejectedValue(new Error("reauth required"));+ const user = userEvent.setup();+ renderPanel(true, true);++ await user.click(+ screen.getByRole("button", { name: "Approve AI data processing" }),+ );+ await user.click(screen.getByRole("button", { name: "Accept beta terms" }));++ expect(await screen.findByRole("alert")).toBeInTheDocument();+ expect(approveAiDataProcessing).toHaveBeenCalledExactlyOnceWith("org-id");+ expect(acceptBetaTerms).toHaveBeenCalledExactlyOnceWith("org-id");+ });++ it("asks members to contact an admin without rendering an accept button", () => {+ renderPanel(true, true, false);++ expect(screen.queryByText("Accept beta terms")).not.toBeInTheDocument();+ });+});diff --git a/products/desktop/packages/ui/src/features/consent/ConsentPanel.tsx b/products/desktop/packages/ui/src/features/consent/ConsentPanel.tsxnew file mode 100644index 000000000000..38a90a197bc0--- /dev/null+++ b/products/desktop/packages/ui/src/features/consent/ConsentPanel.tsx@@ -0,0 +1,262 @@+import { CheckCircle } from "@phosphor-icons/react";+import {+ Button,+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+ Text,+} from "@posthog/quill";+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";+import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import {+ authKeys,+ useCurrentUser,+} from "@posthog/ui/features/auth/useCurrentUser";+import { track } from "@posthog/ui/shell/analytics";+import { useQueryClient } from "@tanstack/react-query";+import { type ReactNode, useState } from "react";+import { desktopBetaTermsKeys, type OrgConsent } from "./useOrgConsent";++interface ConsentPanelProps {+ consent: Extract<OrgConsent, { status: "resolved" }>;+ requirements?: {+ needsAiConsent: boolean;+ needsBetaTerms: boolean;+ };+ isAdmin: boolean;+ onSubmittingChange?: (isSubmitting: boolean) => void;+}++export function ConsentPanel({+ consent,+ requirements,+ isAdmin,+ onSubmittingChange,+}: ConsentPanelProps) {+ const client = useAuthenticatedClient();+ const queryClient = useQueryClient();+ const { data: currentUser } = useCurrentUser({+ client,+ refetchOnWindowFocus: "always",+ });+ const [submitting, setSubmitting] = useState<"ai" | "beta" | null>(null);+ const [error, setError] = useState<string | null>(null);+ const organization = currentUser?.organization;+ const showAiConsent = requirements?.needsAiConsent ?? consent.needsAiConsent;+ const showBetaTerms = requirements?.needsBetaTerms ?? consent.needsBetaTerms;++ const accept = async (kind: "ai" | "beta"): Promise<void> => {+ if (!organization || submitting) return;+ setError(null);+ setSubmitting(kind);+ onSubmittingChange?.(true);++ try {+ if (kind === "ai") {+ await client.approveAiDataProcessing(organization.id);+ track(ANALYTICS_EVENTS.AI_CONSENT_GRANTED_INAPP);+ await queryClient.invalidateQueries({+ queryKey: authKeys.currentUsers(),+ });+ } else {+ await client.acceptDesktopBetaTerms(organization.id);+ track(ANALYTICS_EVENTS.DESKTOP_BETA_TERMS_ACCEPTED_INAPP);+ await queryClient.invalidateQueries({+ queryKey: desktopBetaTermsKeys.all(),+ });+ }+ } catch {+ setError(+ kind === "ai"+ ? "Could not approve AI data processing. Try again or contact support."+ : "Desktop beta terms acceptance could not be saved. Try again or contact support.",+ );+ } finally {+ setSubmitting(null);+ onSubmittingChange?.(false);+ }+ };++ return (+ <div className="flex w-full max-w-[560px] flex-col gap-5">+ <div className="flex flex-col gap-2">+ <h1 className="font-bold text-2xl text-foreground tracking-[-0.02em]">+ Before you continue+ </h1>+ <Text size="sm" variant="muted">+ {organization?.name+ ? `Review the required items for ${organization.name}.`+ : "Review the required items for your organization."}+ </Text>+ </div>++ {showAiConsent && (+ <ConsentDecision+ title="PostHog AI needs your approval"+ summary={+ organization?.name ? (+ <>+ Your "<strong>{organization.name}</strong>" organization hasn't+ approved AI data processing yet.+ </>+ ) : (+ "Your organization hasn't approved AI data processing yet."+ )+ }+ actionLabel="Approve AI data processing"+ adminHelp="Ask an organization admin to approve AI data processing."+ accepted={!consent.needsAiConsent}+ isAdmin={isAdmin}+ isLoading={submitting === "ai"}+ isDisabled={submitting !== null || !organization}+ onAccept={() => void accept("ai")}+ >+ <div className="flex flex-col gap-3">+ <Text size="sm" variant="muted">+ PostHog AI features process identifying user data with external AI+ providers.+ <br />+ Importantly: Your data won't be used for training models by these+ providers.+ </Text>+ <div>+ <Text size="sm" weight="semibold">+ Legal bits about Protected Health Information+ </Text>+ <Text className="mt-1" size="sm" variant="muted">+ This app isn't <i>yet</i> HIPAA-compliant and is not intended+ for processing of Protected Health Information ("PHI").+ <br />+ If you've entered into a Business Associate Agreement ("BAA")+ with PostHog, it does not currently apply to PostHog Code+ features.+ </Text>+ </div>+ </div>+ </ConsentDecision>+ )}++ {showBetaTerms && (+ <ConsentDecision+ title="PostHog Desktop beta terms"+ summary="Accept the additional data-processing terms for the PostHog Desktop beta."+ actionLabel="Accept beta terms"+ adminHelp="Ask an organization admin to accept the Desktop beta terms."+ accepted={!consent.needsBetaTerms}+ isAdmin={isAdmin}+ isLoading={submitting === "beta"}+ isDisabled={submitting !== null || !organization}+ onAccept={() => void accept("beta")}+ >+ <div className="flex flex-col gap-2">+ <Text size="sm" variant="muted">+ PostHog Desktop uses Baseten and Modal to process customer data,+ personal data, and PII. They are not currently listed as PostHog+ subprocessors for this feature.+ </Text>+ <Text size="sm" variant="muted">+ Your organization agrees to proceed notwithstanding that status.+ If this feature becomes generally available, PostHog will update+ the DPA and provide notice. This beta may change or be+ discontinued.+ </Text>+ <a+ href="https://posthog.com/subprocessors"+ target="_blank"+ rel="noreferrer"+ className="w-fit text-link text-sm hover:underline"+ >+ View PostHog subprocessors+ </a>+ </div>+ </ConsentDecision>+ )}++ {error && (+ <div+ role="alert"+ className="rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-destructive-foreground text-sm"+ >+ {error}+ </div>+ )}+ </div>+ );+}++interface ConsentDecisionProps {+ title: string;+ summary: ReactNode;+ actionLabel: string;+ adminHelp: string;+ accepted: boolean;+ isAdmin: boolean;+ isLoading: boolean;+ isDisabled: boolean;+ onAccept: () => void;+ children: ReactNode;+}++function ConsentDecision({+ title,+ summary,+ actionLabel,+ adminHelp,+ accepted,+ isAdmin,+ isLoading,+ isDisabled,+ onAccept,+ children,+}: ConsentDecisionProps) {+ return (+ <section+ className="rounded-lg border border-border bg-surface-primary px-4 py-4 transition-colors data-[accepted=true]:border-success-foreground/25"+ data-accepted={accepted}+ >+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">+ <div className="min-w-0">+ <h2 className="font-semibold text-base text-foreground">{title}</h2>+ <Text className="mt-1" size="sm" variant="muted">+ {summary}+ </Text>+ </div>+ {accepted ? (+ <Button+ variant="outline"+ size="lg"+ className="h-9 shrink-0 px-3 text-sm text-success-foreground"+ disabled+ >+ <CheckCircle size={16} />+ Accepted+ </Button>+ ) : isAdmin ? (+ <Button+ variant="primary"+ size="lg"+ className="h-9 shrink-0 px-3 text-sm"+ loading={isLoading}+ disabled={isDisabled}+ onClick={onAccept}+ >+ {actionLabel}+ </Button>+ ) : null}+ </div>+ {!accepted && !isAdmin && (+ <Text className="mt-3" size="sm" variant="muted">+ {adminHelp}+ </Text>+ )}+ <Collapsible className="mt-3 border-border border-t pt-2">+ <CollapsibleTrigger className="-ml-2 h-7 rounded-md px-2 text-muted-foreground hover:bg-fill-hover hover:text-foreground">+ Details+ </CollapsibleTrigger>+ <CollapsibleContent className="mt-1 ml-1 border-border border-l py-1 pl-3 text-sm leading-relaxed">+ {children}+ </CollapsibleContent>+ </Collapsible>+ </section>+ );+}diff --git a/products/desktop/packages/ui/src/features/consent/ConsentScreen.tsx b/products/desktop/packages/ui/src/features/consent/ConsentScreen.tsxnew file mode 100644index 000000000000..ee53d9159ee1--- /dev/null+++ b/products/desktop/packages/ui/src/features/consent/ConsentScreen.tsx@@ -0,0 +1,76 @@+import { GearSix, Lifebuoy, SignOut } from "@phosphor-icons/react";+import { Button } from "@posthog/quill";+import { useLogoutMutation } from "@posthog/ui/features/auth/useAuthMutations";+import { useIsOrgAdmin } from "@posthog/ui/features/auth/useOrgRole";+import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";+import { openSettingsDialog } from "@posthog/ui/features/settings/SettingsDialog";+import { FullScreenLayout } from "@posthog/ui/primitives/FullScreenLayout";+import type { ReactNode } from "react";+import { useHotkeys } from "react-hotkeys-hook";+import { ConsentErrorContent } from "./ConsentErrorContent";+import { ConsentPanel } from "./ConsentPanel";+import { useOrgConsent } from "./useOrgConsent";++interface ConsentScreenProps {+ banner?: ReactNode;+ onOpenSupport?: () => void;+ settingsDialog?: ReactNode;+}++export function ConsentScreen({+ banner,+ onOpenSupport,+ settingsDialog,+}: ConsentScreenProps) {+ const consent = useOrgConsent();+ const { isAdmin } = useIsOrgAdmin();+ const logoutMutation = useLogoutMutation();+ useHotkeys(SHORTCUTS.SETTINGS, () => openSettingsDialog(), {+ preventDefault: true,+ enableOnFormTags: true,+ });++ const footerLeft = (+ <div className="flex items-center gap-3">+ <Button+ variant="link-muted"+ size="xs"+ onClick={() => openSettingsDialog()}+ >+ <GearSix size={14} />+ Settings+ </Button>+ <Button variant="link-muted" size="xs" onClick={onOpenSupport}>+ <Lifebuoy size={14} />+ Get support+ </Button>+ {banner}+ </div>+ );+ const footerRight = (+ <Button+ variant="link-muted"+ size="xs"+ loading={logoutMutation.isPending}+ onClick={() => logoutMutation.mutate()}+ >+ <SignOut size={14} />+ Log out+ </Button>+ );++ return (+ <>+ <FullScreenLayout footerLeft={footerLeft} footerRight={footerRight}>+ <div className="flex h-full items-center justify-center overflow-y-auto px-8 py-16">+ {consent.status === "error" ? (+ <ConsentErrorContent onRetry={consent.retry} />+ ) : consent.status === "resolved" ? (+ <ConsentPanel consent={consent} isAdmin={isAdmin === true} />+ ) : null}+ </div>+ </FullScreenLayout>+ {settingsDialog}+ </>+ );+}diff --git a/products/desktop/packages/ui/src/features/consent/ConsentStep.tsx b/products/desktop/packages/ui/src/features/consent/ConsentStep.tsxnew file mode 100644index 000000000000..83c0aea094bf--- /dev/null+++ b/products/desktop/packages/ui/src/features/consent/ConsentStep.tsx@@ -0,0 +1,96 @@+import { ArrowLeft, ArrowRight } from "@phosphor-icons/react";+import { Button, Spinner } from "@posthog/quill";+import { useIsOrgAdmin } from "@posthog/ui/features/auth/useOrgRole";+import { StepActions } from "@posthog/ui/features/onboarding/components/StepActions";+import { AnimatePresence, motion } from "framer-motion";+import { useState } from "react";+import { ConsentErrorContent } from "./ConsentErrorContent";+import { ConsentPanel } from "./ConsentPanel";+import { useConsentAnalytics } from "./consentAnalytics";+import { useOrgConsent } from "./useOrgConsent";++interface ConsentStepProps {+ onNext: () => void;+ onBack: () => void;+ requirements?: {+ needsAiConsent: boolean;+ needsBetaTerms: boolean;+ };+ onSubmittingChange?: (isSubmitting: boolean) => void;+}++export function ConsentStep({+ onNext,+ onBack,+ requirements,+ onSubmittingChange,+}: ConsentStepProps) {+ const consent = useOrgConsent();+ const { isAdmin } = useIsOrgAdmin();+ const [isSubmitting, setIsSubmitting] = useState(false);+ useConsentAnalytics(consent, isAdmin === true, "onboarding_step");++ return (+ <div className="flex h-full items-center px-8">+ <div className="flex h-full w-full flex-col items-center pt-[24px] pb-[40px]">+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto">+ <div className="m-auto w-full max-w-[560px]">+ <AnimatePresence mode="wait" initial={false}>+ <motion.div+ key={consent.status}+ initial={{ opacity: 0, y: 4 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: -4 }}+ transition={{ duration: 0.16 }}+ >+ {consent.status === "loading" ? (+ <div className="flex w-full justify-center">+ <Spinner />+ </div>+ ) : consent.status === "error" ? (+ <ConsentErrorContent onRetry={consent.retry} />+ ) : (+ <ConsentPanel+ consent={consent}+ requirements={requirements}+ isAdmin={isAdmin === true}+ onSubmittingChange={(submitting) => {+ setIsSubmitting(submitting);+ onSubmittingChange?.(submitting);+ }}+ />+ )}+ </motion.div>+ </AnimatePresence>+ </div>+ </div>+ <StepActions>+ <Button+ variant="outline"+ size="lg"+ className="h-10 px-4 text-sm"+ disabled={isSubmitting}+ onClick={onBack}+ >+ <ArrowLeft size={16} />+ Back+ </Button>+ <Button+ variant="primary"+ size="lg"+ className="h-10 px-4 text-sm"+ disabled={+ isSubmitting ||+ consent.status !== "resolved" ||+ !consent.satisfied+ }+ onClick={onNext}+ >+ Next+ <ArrowRight size={16} />+ </Button>+ </StepActions>+ </div>+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/consent/consentAnalytics.ts b/products/desktop/packages/ui/src/features/consent/consentAnalytics.tsnew file mode 100644index 000000000000..7966c0b86d49--- /dev/null+++ b/products/desktop/packages/ui/src/features/consent/consentAnalytics.ts@@ -0,0 +1,46 @@+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";+import { track } from "@posthog/ui/shell/analytics";+import { useEffect, useRef } from "react";+import type { OrgConsent } from "./useOrgConsent";++export type ConsentSurface = "onboarding_step" | "standalone_gate";++export function useConsentAnalytics(+ consent: OrgConsent,+ isAdmin: boolean,+ surface: ConsentSurface,+): void {+ const needsAiConsent =+ consent.status === "resolved" ? consent.needsAiConsent : undefined;+ const needsBetaTerms =+ consent.status === "resolved" ? consent.needsBetaTerms : undefined;+ const previousAi = useRef<boolean | undefined>(undefined);+ const previousBeta = useRef<boolean | undefined>(undefined);+ const gateTracked = useRef(false);++ useEffect(() => {+ if (+ !gateTracked.current &&+ (needsAiConsent === true || needsBetaTerms === true)+ ) {+ gateTracked.current = true;+ track(ANALYTICS_EVENTS.AI_CONSENT_GATE_SHOWN, {+ is_org_admin: isAdmin,+ outstanding_ai_consent: needsAiConsent === true,+ outstanding_beta_terms: needsBetaTerms === true,+ surface,+ });+ }+ }, [isAdmin, needsAiConsent, needsBetaTerms, surface]);++ useEffect(() => {+ if (previousAi.current === true && needsAiConsent === false) {+ track(ANALYTICS_EVENTS.AI_CONSENT_APPROVED);+ }+ if (previousBeta.current === true && needsBetaTerms === false) {+ track(ANALYTICS_EVENTS.DESKTOP_BETA_TERMS_ACCEPTED);+ }+ previousAi.current = needsAiConsent;+ previousBeta.current = needsBetaTerms;+ }, [needsAiConsent, needsBetaTerms]);+}diff --git a/products/desktop/packages/ui/src/features/consent/useOrgConsent.ts b/products/desktop/packages/ui/src/features/consent/useOrgConsent.tsnew file mode 100644index 000000000000..fa9bf296ffec--- /dev/null+++ b/products/desktop/packages/ui/src/features/consent/useOrgConsent.ts@@ -0,0 +1,78 @@+import { isNotAuthenticatedError } from "@posthog/shared";+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import {+ AUTH_SCOPED_QUERY_META,+ useCurrentUser,+} from "@posthog/ui/features/auth/useCurrentUser";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { useCallback } from "react";++export type OrgConsent =+ | { status: "loading"; organizationId?: string }+ | { status: "error"; organizationId?: string; retry: () => void }+ | {+ status: "resolved";+ organizationId: string;+ needsAiConsent: boolean;+ needsBetaTerms: boolean;+ satisfied: boolean;+ };++export const desktopBetaTermsKeys = {+ all: () => ["auth", "desktop-beta-terms"] as const,+ acceptance: (identity: string) =>+ [...desktopBetaTermsKeys.all(), identity] as const,+};++export function useDesktopBetaTerms(+ organizationId: string | undefined,+ enabled = true,+) {+ const client = useOptionalAuthenticatedClient();+ return useQuery({+ queryKey: desktopBetaTermsKeys.acceptance(organizationId ?? "unknown"),+ queryFn: async () => {+ if (!client || !organizationId) throw new Error("Not authenticated");+ return await client.areDesktopBetaTermsAccepted(organizationId);+ },+ enabled: enabled && !!client && !!organizationId,+ staleTime: 5 * 60 * 1000,+ refetchOnWindowFocus: "always",+ meta: AUTH_SCOPED_QUERY_META,+ });+}++export function useOrgConsent(enabled = true): OrgConsent {+ const client = useOptionalAuthenticatedClient();+ const currentUserQuery = useCurrentUser({+ client,+ enabled,+ refetchOnWindowFocus: "always",+ });+ const organization = currentUserQuery.data?.organization;+ const betaTermsQuery = useDesktopBetaTerms(organization?.id, enabled);+ const queryClient = useQueryClient();+ const retry = useCallback(() => {+ void queryClient.invalidateQueries({ queryKey: ["auth"] });+ }, [queryClient]);++ const reportableError = [currentUserQuery.error, betaTermsQuery.error].some(+ (error) => error != null && !isNotAuthenticatedError(error),+ );+ if (reportableError) {+ return { status: "error", organizationId: organization?.id, retry };+ }+ if (!organization || betaTermsQuery.data === undefined) {+ return { status: "loading", organizationId: organization?.id };+ }++ const needsAiConsent = organization.is_ai_data_processing_approved !== true;+ const needsBetaTerms = !betaTermsQuery.data;+ return {+ status: "resolved",+ organizationId: organization.id,+ needsAiConsent,+ needsBetaTerms,+ satisfied: !needsAiConsent && !needsBetaTerms,+ };+}diff --git a/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsx b/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsxindex ec2baf785759..a7f61b9de09b 100644--- a/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsx+++ b/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsx@@ -22,6 +22,7 @@ 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 { ConsentStep } from "@posthog/ui/features/consent/ConsentStep";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";@@ -41,7 +42,7 @@ 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 { useEffect, useRef, useState } from "react";import { useHotkeys } from "react-hotkeys-hook";import { InviteCodeStep } from "./InviteCodeStep";import { ProjectSelectStep } from "./ProjectSelectStep";@@ -57,7 +58,12 @@ const stepVariants = {exit: (dir: number) => ({ opacity: 0, x: dir * -20 }),};-export function OnboardingFlow() {+interface OnboardingFlowProps {+ onOpenSupport?: () => void;+}++export function OnboardingFlow({ onOpenSupport }: OnboardingFlowProps) {+ const [consentSubmitting, setConsentSubmitting] = useState(false);const queryClient = useQueryClient();const {currentStep,@@ -73,6 +79,8 @@ export function OnboardingFlow() {selectedCloudRepo,handleCloudRepoChange,hasGithubIntegration,+ consentSatisfied,+ consentRequirement,} = useOnboardingFlow();const completeOnboarding = useOnboardingStore((state) => state.completeOnboarding,@@ -203,6 +211,12 @@ export function OnboardingFlow() {};const handleNext = (context?: StepCompletedContext) => {+ if (+ currentStep === "consent" &&+ (consentSatisfied !== true || consentSubmitting)+ ) {+ return;+ }// `onClick={onNext}` would pass the click event here; a DOM event spread// into capture properties poisons the whole analytics batch.const safeContext =@@ -213,6 +227,7 @@ export function OnboardingFlow() {};const handleBack = () => {+ if (currentStep === "consent" && consentSubmitting) return;trackStepViewed(currentIndex - 1);back();};@@ -312,7 +327,7 @@ export function OnboardingFlow() {);return (- <FullScreenLayout footerRight={footerRight}>+ <FullScreenLayout footerRight={footerRight} onOpenSupport={onOpenSupport}><LayoutGroup><AnimatePresence mode="wait" custom={direction}>{currentStep === "welcome" && (@@ -360,6 +375,26 @@ export function OnboardingFlow() {</motion.div>)}+ {currentStep === "consent" && (+ <motion.div+ key="consent"+ custom={direction}+ initial="enter"+ animate="center"+ exit="exit"+ variants={stepVariants}+ transition={{ duration: 0.3 }}+ className="min-h-0 w-full flex-1"+ >+ <ConsentStep+ onNext={handleNext}+ onBack={handleBack}+ requirements={consentRequirement}+ onSubmittingChange={setConsentSubmitting}+ />+ </motion.div>+ )}+{currentStep === "connect-github" && (<motion.divkey="connect-github"diff --git a/products/desktop/packages/ui/src/features/onboarding/hooks/consentRequirement.test.ts b/products/desktop/packages/ui/src/features/onboarding/hooks/consentRequirement.test.tsnew file mode 100644index 000000000000..993947686737--- /dev/null+++ b/products/desktop/packages/ui/src/features/onboarding/hooks/consentRequirement.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from "vitest";+import { sampleConsentRequirement } from "./consentRequirement";++describe("sampleConsentRequirement", () => {+ it("keeps a required consent step after the organization accepts", () => {+ const initial = sampleConsentRequirement(undefined, "org-1", true, false);++ expect(sampleConsentRequirement(initial, "org-1", false, false)).toBe(+ initial,+ );+ expect(initial.required).toBe(true);+ expect(initial.needsAiConsent).toBe(true);+ });++ it("samples consent again when the organization changes", () => {+ const initial = sampleConsentRequirement(undefined, "org-1", false, false);+ const switched = sampleConsentRequirement(initial, "org-2", false, true);++ expect(initial.required).toBe(false);+ expect(switched).toEqual({+ organizationId: "org-2",+ required: true,+ needsAiConsent: false,+ needsBetaTerms: true,+ });+ });+});diff --git a/products/desktop/packages/ui/src/features/onboarding/hooks/consentRequirement.ts b/products/desktop/packages/ui/src/features/onboarding/hooks/consentRequirement.tsnew file mode 100644index 000000000000..620ff8724591--- /dev/null+++ b/products/desktop/packages/ui/src/features/onboarding/hooks/consentRequirement.ts@@ -0,0 +1,21 @@+export interface ConsentRequirement {+ organizationId: string;+ required: boolean;+ needsAiConsent: boolean;+ needsBetaTerms: boolean;+}++export function sampleConsentRequirement(+ current: ConsentRequirement | undefined,+ organizationId: string,+ needsAiConsent: boolean,+ needsBetaTerms: boolean,+): ConsentRequirement {+ if (current?.organizationId === organizationId) return current;+ return {+ organizationId,+ required: needsAiConsent || needsBetaTerms,+ needsAiConsent,+ needsBetaTerms,+ };+}diff --git a/products/desktop/packages/ui/src/features/onboarding/hooks/useOnboardingFlow.ts b/products/desktop/packages/ui/src/features/onboarding/hooks/useOnboardingFlow.tsindex 83ab96529d16..4cf38fa64004 100644--- a/products/desktop/packages/ui/src/features/onboarding/hooks/useOnboardingFlow.ts+++ b/products/desktop/packages/ui/src/features/onboarding/hooks/useOnboardingFlow.ts@@ -19,6 +19,7 @@ import {useAuthStateFetched,useAuthStateValue,} from "@posthog/ui/features/auth/store";+import { useOrgConsent } from "@posthog/ui/features/consent/useOrgConsent";import { useUserGithubIntegrations } from "@posthog/ui/features/integrations/useIntegrations";import { useOnboardingStore } from "@posthog/ui/features/onboarding/onboardingStore";import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";@@ -26,6 +27,10 @@ import { useActiveRepoStore } from "@posthog/ui/shell/activeRepoStore";import { track } from "@posthog/ui/shell/analytics";import { useHostCapabilities } from "@posthog/ui/shell/useHostCapabilities";import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ type ConsentRequirement,+ sampleConsentRequirement,+} from "./consentRequirement";import { useHasImportableConfig } from "./useHasImportableConfig";export type { DetectedRepo };@@ -149,6 +154,32 @@ export function useOnboardingFlow() {: undefined,[authFetched, orgProjectsMap],);+ const consent = useOrgConsent(hasCodeAccess === true);+ const consentSatisfied =+ consent.status === "resolved" ? consent.satisfied : undefined;+ const [consentRequirement, setConsentRequirement] =+ useState<ConsentRequirement>();++ useEffect(() => {+ if (consent.status !== "resolved") return;+ setConsentRequirement((current) =>+ sampleConsentRequirement(+ current,+ consent.organizationId,+ consent.needsAiConsent,+ consent.needsBetaTerms,+ ),+ );+ }, [consent]);++ const consentRequired =+ consentRequirement?.organizationId === consent.organizationId+ ? consentRequirement?.required+ : undefined;+ const sampledConsentRequirement =+ consentRequirement?.organizationId === consent.organizationId+ ? consentRequirement+ : undefined;const activeSteps = useMemo(() =>@@ -157,8 +188,15 @@ export function useOnboardingFlow() {hasImportableConfig,hasGithubIntegration,projectCount,+ consentRequired,}),- [hasCodeAccess, hasImportableConfig, hasGithubIntegration, projectCount],+ [+ hasCodeAccess,+ hasImportableConfig,+ hasGithubIntegration,+ projectCount,+ consentRequired,+ ],);useEffect(() => {@@ -210,5 +248,7 @@ export function useOnboardingFlow() {selectedCloudRepo,handleCloudRepoChange,hasGithubIntegration,+ consentSatisfied,+ consentRequirement: sampledConsentRequirement,};}diff --git a/products/desktop/packages/ui/src/features/settings/SettingsDialog.tsx b/products/desktop/packages/ui/src/features/settings/SettingsDialog.tsxindex 1fe38177f722..d480ba2415e3 100644--- a/products/desktop/packages/ui/src/features/settings/SettingsDialog.tsx+++ b/products/desktop/packages/ui/src/features/settings/SettingsDialog.tsx@@ -5,7 +5,7 @@ import { useEffect, useState } from "react";/*** Modal/overlay form of the settings UI. Used in pre-router shells (e.g.- * `AiApprovalScreen`) where the routed `/settings/$category` page isn't+ * `ConsentScreen`) where the routed `/settings/$category` page isn't* available because RouterProvider hasn't mounted yet. Inside the main app,* settings is a real route — see `router/routes/settings/$category.tsx`.*diff --git a/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx b/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsxindex 4a98d31cf735..1b5a298f083e 100644--- a/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx+++ b/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx@@ -120,7 +120,7 @@ export interface SettingsPanelProps {/*** Override the active category. Defaults to the `$category` URL param* (which is what every in-app entry point uses). Provided for the- * pre-router `AiApprovalScreen` shell where RouterProvider isn't mounted.+ * pre-router `ConsentScreen` shell where RouterProvider isn't mounted.*/activeCategory?: SettingsCategory;/** Override the close handler. Defaults to router history back. */diff --git a/products/desktop/packages/ui/src/shell/App.tsx b/products/desktop/packages/ui/src/shell/App.tsxindex 03bce07df7c2..f45e426e7e3d 100644--- a/products/desktop/packages/ui/src/shell/App.tsx+++ b/products/desktop/packages/ui/src/shell/App.tsx@@ -1,13 +1,8 @@import { getAuthIdentity } from "@posthog/core/auth/authIdentity";import { ToastProvider } from "@posthog/quill";import { EXTERNAL_LINKS, isNotAuthenticatedError } from "@posthog/shared";-import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";-import { AiApprovalScreen } from "@posthog/ui/features/ai-approval/AiApprovalScreen";import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";-import {- useAuthStateValue,- useCurrentUser,-} from "@posthog/ui/features/auth/authQueries";+import { useAuthStateValue } from "@posthog/ui/features/auth/authQueries";import { AuthScreen } from "@posthog/ui/features/auth/components/AuthScreen";import { InviteCodeScreen } from "@posthog/ui/features/auth/components/InviteCodeScreen";import { ScopeReauthPrompt } from "@posthog/ui/features/auth/components/ScopeReauthPrompt";@@ -17,6 +12,9 @@ import { CanvasGenerationToaster } from "@posthog/ui/features/canvas/freeform/usimport { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";import { showChannelList } from "@posthog/ui/features/canvas/stores/channelPaneStore";import { useSpaceTreeStore } from "@posthog/ui/features/canvas/stores/spaceTreeStore";+import { ConsentScreen } from "@posthog/ui/features/consent/ConsentScreen";+import { useConsentAnalytics } from "@posthog/ui/features/consent/consentAnalytics";+import { useOrgConsent } from "@posthog/ui/features/consent/useOrgConsent";import { AddDirectoryDialog } from "@posthog/ui/features/folder-picker/AddDirectoryDialog";import { ErrorDetailsDialog } from "@posthog/ui/features/notifications/ErrorDetailsDialog";import { OnboardingFlow } from "@posthog/ui/features/onboarding/components/OnboardingFlow";@@ -26,9 +24,8 @@ import { UpdateBanner } from "@posthog/ui/features/sidebar/components/UpdateBannimport { PendingPromptRecovery } from "@posthog/ui/features/task-detail/components/PendingPromptRecovery";import { router } from "@posthog/ui/router/router";import { AppLoadingScreen } from "@posthog/ui/shell/AppLoadingScreen";-import { track } from "@posthog/ui/shell/analytics";import { ErrorBoundary } from "@posthog/ui/shell/ErrorBoundary";-import { beginFirstRun } from "@posthog/ui/shell/firstRun";+import { ensureSession } from "@posthog/ui/shell/firstRun";import { logger } from "@posthog/ui/shell/logger";import { openExternalUrl } from "@posthog/ui/shell/openExternal";import {@@ -65,33 +62,26 @@ function App({ devToolbar }: AppProps) {const needsInviteCode =isAuthenticated && hasCodeAccess === false && hasCompletedOnboarding;- const isCheckingAccess =- isAuthenticated && hasCodeAccess === null && hasCompletedOnboarding;-const authenticatedClient = useOptionalAuthenticatedClient();- const { data: currentUser } = useCurrentUser({- client: authenticatedClient,- enabled:- isAuthenticated && hasCompletedOnboarding && hasCodeAccess === true,- refetchOnWindowFocus: "always",- });- const currentOrg = currentUser?.organization;- const needsAiApproval =+ const consent = useOrgConsent(isAuthenticated && hasCodeAccess === true);+ const needsConsent =isAuthenticated &&hasCompletedOnboarding &&hasCodeAccess === true &&- currentOrg != null &&- currentOrg.is_ai_data_processing_approved !== true;+ consent.status === "resolved" &&+ !consent.satisfied;+ const isCheckingAccess =+ isAuthenticated &&+ hasCompletedOnboarding &&+ (hasCodeAccess === null ||+ (hasCodeAccess === true && consent.status === "loading"));const { isAdmin: isOrgAdmin } = useIsOrgAdmin();const isAdmin = isOrgAdmin === true;-- const wasShowingAiGateRef = useRef(false);- useEffect(() => {- if (wasShowingAiGateRef.current && !needsAiApproval && currentOrg != null) {- track(ANALYTICS_EVENTS.AI_CONSENT_APPROVED);- }- wasShowingAiGateRef.current = needsAiApproval;- }, [needsAiApproval, currentOrg]);+ useConsentAnalytics(+ hasCompletedOnboarding ? consent : { status: "loading" },+ isAdmin,+ "standalone_gate",+ );const spacesLayoutEnabled = useChannelsLayout();// Read through a ref so a flag arriving mid-startup cannot re-run the resolve and replace@@ -105,17 +95,15 @@ function App({ devToolbar }: AppProps) {hasCompletedOnboarding &&!isCheckingAccess &&!needsInviteCode &&- !needsAiApproval;+ consent.status === "resolved" &&+ consent.satisfied;const startupIdentity = getAuthIdentity(authState);- // Provision, and open the first session, as soon as the user is through the access check.- // Onboarding runs next and takes far longer than either call, so starting here is what keeps- // the session ready by the time the route resolves instead of the route waiting on it.useEffect(() => {- if (!isAuthenticated || hasCodeAccess !== true) return;+ if (consent.status !== "resolved" || !consent.satisfied) return;if (!startupIdentity || !authenticatedClient) return;- beginFirstRun(startupIdentity, authenticatedClient);- }, [isAuthenticated, hasCodeAccess, startupIdentity, authenticatedClient]);+ void ensureSession(startupIdentity, authenticatedClient);+ }, [consent, startupIdentity, authenticatedClient]);// Resolve and load the initial route before mounting the router. Reset when// the user leaves the main app so a later re-entry starts fresh.@@ -191,7 +179,9 @@ function App({ devToolbar }: AppProps) {initial={{ opacity: 1 }}className="h-full">- <OnboardingFlow />+ <OnboardingFlow+ onOpenSupport={() => openExternalUrl(EXTERNAL_LINKS.discord)}+ /></motion.div>);}@@ -216,17 +206,10 @@ function App({ devToolbar }: AppProps) {);}- if (needsAiApproval) {+ if (consent.status === "error" || needsConsent) {return (- <motion.div- key="ai-approval"- initial={{ opacity: 1 }}- className="h-full"- >- <AiApprovalScreen- organizationId={currentOrg.id}- orgName={currentOrg?.name ?? null}- isAdmin={isAdmin}+ <motion.div key="consent" initial={{ opacity: 1 }} className="h-full">+ <ConsentScreenbanner={<UpdateBanner variant="compact" />}onOpenSupport={() => openExternalUrl(EXTERNAL_LINKS.discord)}settingsDialog={<SettingsDialog />}diff --git a/products/desktop/packages/ui/src/shell/firstRun.ts b/products/desktop/packages/ui/src/shell/firstRun.tsindex faeb5deb26f6..bada94defe00 100644--- a/products/desktop/packages/ui/src/shell/firstRun.ts+++ b/products/desktop/packages/ui/src/shell/firstRun.ts@@ -9,8 +9,6 @@ export type FirstRunClient = Pick<export interface FirstRun {/** ``null`` when provisioning failed, which must not stop the app opening. */provisioned: Promise<ProvisionedTaskChannels | null>;- /** ``null`` unless this is the first run and the backend opened a session. */- sessionTaskId: Promise<string | null>;}/**@@ -24,39 +22,55 @@ export function isFirstRun(return Boolean(provisioned?.general_created || provisioned?.personal_created);}-let started: (FirstRun & { identity: string }) | null = null;+type FirstRunEntry = FirstRun & {+ identity: string;+ sessionTaskId?: Promise<string | null>;+};-function begin(identity: string, client: FirstRunClient): FirstRun {+let started: FirstRunEntry | null = null;++function begin(identity: string, client: FirstRunClient): FirstRunEntry {const provisioned = client.provisionDefaultTaskChannels().catch(() => {// Dropped so a later caller provisions again rather than inheriting the failure.if (started?.identity === identity) started = null;return null;});- const entry = {+ const entry: FirstRunEntry = {identity,provisioned,- // Its own promise, not awaited into `provisioned`, so a hung scrape cannot hold up- // the callers that only need the channels.- sessionTaskId: provisioned.then((channels) =>- isFirstRun(channels)- ? client.startOnboardingSession().catch(() => null)- : null,- ),};started = entry;return entry;}/**- * Start provisioning and, on a first run, the session the user will land in. Called as soon as- * the user is through the access check, so the work overlaps onboarding instead of following it.+ * Start provisioning as soon as the user is through the access check.*/-export function beginFirstRun(identity: string, client: FirstRunClient): void {+export function beginProvisioning(+ identity: string,+ client: FirstRunClient,+): void {if (started?.identity !== identity) begin(identity, client);}+export const beginFirstRun = beginProvisioning;++export function ensureSession(+ identity: string,+ client: FirstRunClient,+): Promise<string | null> {+ const entry =+ started?.identity === identity ? started : begin(identity, client);+ entry.sessionTaskId ??= entry.provisioned.then((channels) =>+ isFirstRun(channels)+ ? client.startOnboardingSession().catch(() => null)+ : null,+ );+ return entry.sessionTaskId;+}+/**- * The result of {@link beginFirstRun}, shared rather than consumed: `personal_created` and+ * The result of {@link beginProvisioning}, shared rather than consumed: `personal_created` and* `general_created` are true only for whoever provisions first, so every reader has to see the* same response or the later ones decide this is not a first run.*/diff --git a/products/desktop/packages/ui/src/shell/startupLocation.test.ts b/products/desktop/packages/ui/src/shell/startupLocation.test.tsindex d416043b68a6..b99c55be0e8a 100644--- a/products/desktop/packages/ui/src/shell/startupLocation.test.ts+++ b/products/desktop/packages/ui/src/shell/startupLocation.test.ts@@ -1,6 +1,7 @@+import type { ProvisionedTaskChannels } from "@posthog/shared/domain-types";import { stateStorage } from "@posthog/ui/shell/rendererStorage";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { beginFirstRun, firstRun } from "./firstRun";+import { beginFirstRun, ensureSession, firstRun } from "./firstRun";import { resolveStartupLocation } from "./startupLocation";const personal = {@@ -325,6 +326,36 @@ describe("startup location", () => {expect(client.startOnboardingSession).toHaveBeenCalledOnce();});+ it("shares one session between consent prefetch and startup", async () => {+ vi.spyOn(stateStorage, "getItem").mockResolvedValue(null);+ let finishProvisioning!: (value: ProvisionedTaskChannels) => void;+ const provisioned = new Promise<ProvisionedTaskChannels>((resolve) => {+ finishProvisioning = resolve;+ });+ const client = {+ provisionDefaultTaskChannels: vi.fn().mockReturnValue(provisioned),+ startOnboardingSession: vi.fn().mockResolvedValue("session-id"),+ };++ beginFirstRun(identity, client);+ const prefetchedSession = ensureSession(identity, client);+ const startup = resolveStartupLocation(identity, client, true);++ expect(client.startOnboardingSession).not.toHaveBeenCalled();+ finishProvisioning({+ channels: [personal, general],+ personal_created: true,+ general_created: false,+ });++ await expect(prefetchedSession).resolves.toBe("session-id");+ await expect(startup).resolves.toEqual({+ href: "/spaces/general-id/tasks/session-id",+ firstRun: { generalChannelId: "general-id" },+ });+ expect(client.startOnboardingSession).toHaveBeenCalledOnce();+ });+it("provisions again when an earlier attempt failed", async () => {vi.spyOn(stateStorage, "getItem").mockResolvedValue(null);const failed = firstRun(identity, {diff --git a/products/desktop/packages/ui/src/shell/startupLocation.ts b/products/desktop/packages/ui/src/shell/startupLocation.tsindex 37ea2fe82e20..994a105403e7 100644--- a/products/desktop/packages/ui/src/shell/startupLocation.ts+++ b/products/desktop/packages/ui/src/shell/startupLocation.ts@@ -1,6 +1,7 @@import { isGeneralChannel } from "@posthog/core/canvas/channelName";import { rewriteLegacyHref } from "@posthog/ui/router/legacyPaths";import {+ ensureSession,type FirstRunClient,firstRun,isFirstRun,@@ -19,10 +20,10 @@ interface StartupLocation {}/**- * The session is started at sign-in and normally settles while onboarding is still on screen, so- * this wait is only ever paid by someone who got through onboarding faster than the scrape. The- * cap is what stops a hung one holding the app shut: past it the feed opens, and the session- * shows up there instead.+ * The session starts as soon as consent permits and normally settles while onboarding is still on+ * screen, so this wait is only ever paid by someone who got through onboarding faster than the+ * scrape. The cap is what stops a hung one holding the app shut: past it the feed opens, and the+ * session shows up there instead.*/const SESSION_WAIT_MS = 15_000;@@ -46,6 +47,7 @@ export async function resolveStartupLocation(// where the user was last. A saved location is written on every navigation and is shared by every// account on the project, so it answers neither question reliably.const run = firstRun(identity, client);+ const sessionTaskIdPromise = ensureSession(identity, client);const provisioned = await run.provisioned;// The old key predates the created flags, so its presence is the only proof this install was@@ -77,7 +79,7 @@ export async function resolveStartupLocation(// land on /code once, which costs them a click rather than the session.if (!spacesEnabled) return { href: "/code", firstRun: null };- const sessionTaskId = await cappedSessionTaskId(run.sessionTaskId);+ const sessionTaskId = await cappedSessionTaskId(sessionTaskIdPromise);return {href: sessionTaskId? `/spaces/${general.id}/tasks/${sessionTaskId}`