Skip to content

Open source alternative to Semrush and Ahrefs

Track the onboarding funnel in PostHog (EVE-436) (#992)

Carter Smithba6d311d2974
diff --git a/src/client/features/billing/FreePlanBanner.tsx b/src/client/features/billing/FreePlanBanner.tsx
index 38a7a7a0..beb05ae6 100644
--- a/src/client/features/billing/FreePlanBanner.tsx
+++ b/src/client/features/billing/FreePlanBanner.tsx
@@ -1,7 +1,9 @@
+import { useEffect } from "react";
import { Link } from "@tanstack/react-router";
import { AppBanner } from "@/client/layout/AppBanner";
import { BASE_PLAN_OFFER } from "@/client/features/billing/plan-offers";
import { useCreditBalance } from "@/client/features/billing/useCreditBalance";
+import { captureClientEvent } from "@/client/lib/posthog";
import { useCanManageBilling } from "@/client/features/team/organizationQueries";
import { BILLING_ROUTE, SUBSCRIBE_ROUTE } from "@/shared/billing";
@@ -9,6 +11,12 @@ export function FreePlanBanner() {
const { accountQuery, isFreePlan, isOutOfCredits, isLowCredits, refillDate } =
useCreditBalance();
const canManageBilling = useCanManageBilling();
+ const showsOutOfCredits = Boolean(accountQuery.data) && isOutOfCredits;
+
+ useEffect(() => {
+ if (showsOutOfCredits)
+ captureClientEvent("billing:out_of_credits_shown", { surface: "banner" });
+ }, [showsOutOfCredits]);
if (!accountQuery.data) {
return null;
diff --git a/src/client/features/billing/InsufficientCreditsError.tsx b/src/client/features/billing/InsufficientCreditsError.tsx
index 5dd83ef8..667676b8 100644
--- a/src/client/features/billing/InsufficientCreditsError.tsx
+++ b/src/client/features/billing/InsufficientCreditsError.tsx
@@ -1,10 +1,11 @@
-import type { ReactElement } from "react";
+import { useEffect, type ReactElement } from "react";
import { Link } from "@tanstack/react-router";
import { ErrorState } from "@/client/components/ErrorState";
import { Button } from "@/client/components/ui/button";
import { BASE_PLAN_OFFER } from "@/client/features/billing/plan-offers";
import { useCreditBalance } from "@/client/features/billing/useCreditBalance";
import { getStandardErrorMessage } from "@/client/lib/error-messages";
+import { captureClientEvent } from "@/client/lib/posthog";
import { BILLING_ROUTE, SUBSCRIBE_ROUTE } from "@/shared/billing";
/**
@@ -23,7 +24,7 @@ export function InsufficientCreditsError({
variant?: "inline" | "card" | "page";
title?: string;
}) {
- const { message, action } = useCreditsOffer();
+ const { message, action } = useCreditsOffer("card");
return (
<ErrorState
variant={variant}
@@ -36,12 +37,16 @@ export function InsufficientCreditsError({
/** The card's button alone, for a spot too small for the card. */
export function GetCreditsButton() {
- return useCreditsOffer().action;
+ return useCreditsOffer("button").action;
}
-function useCreditsOffer() {
+function useCreditsOffer(surface: "card" | "button") {
const { accountQuery, isFreePlan, refillDate } = useCreditBalance();
+ useEffect(() => {
+ captureClientEvent("billing:out_of_credits_shown", { surface });
+ }, [surface]);
+
let message: string;
let action: ReactElement;
if (!accountQuery.data) {
diff --git a/src/client/features/integrations/GoogleConnectionCard.tsx b/src/client/features/integrations/GoogleConnectionCard.tsx
index e7caaf1b..1e69dfb1 100644
--- a/src/client/features/integrations/GoogleConnectionCard.tsx
+++ b/src/client/features/integrations/GoogleConnectionCard.tsx
@@ -23,7 +23,6 @@ import {
} from "@/client/features/integrations/googleProviders";
import { useGooglePickerResume } from "@/client/features/integrations/useGooglePickerResume";
import { getStandardErrorMessage } from "@/client/lib/error-messages";
-import { captureClientEvent } from "@/client/lib/posthog";
/**
* Connects one project to Search Console or Google Analytics: link a Google
@@ -109,7 +108,6 @@ export function GoogleConnectionCard({
(current: GoogleConnection | undefined) =>
current ? { ...current, ...saved } : current,
);
- captureClientEvent(`${provider}:property_select`);
toast.success(`${config.name} connected`);
afterChange();
},
diff --git a/src/client/features/onboarding/SearchConsoleOnboardingStep.tsx b/src/client/features/onboarding/SearchConsoleOnboardingStep.tsx
index 3363bbd2..7a3cb70d 100644
--- a/src/client/features/onboarding/SearchConsoleOnboardingStep.tsx
+++ b/src/client/features/onboarding/SearchConsoleOnboardingStep.tsx
@@ -18,6 +18,8 @@ import {
startGoogleLink,
useGoogleLinkPending,
} from "@/client/features/integrations/startGoogleLink";
+import { hasNoGscWebsites } from "@/client/features/integrations/GscPropertySetupHelp";
+import { getErrorCode } from "@/client/lib/error-messages";
import { captureClientEvent } from "@/client/lib/posthog";
import { Button } from "@/client/components/ui/button";
import { Spinner as SpinnerIcon } from "@/client/components/ui/spinner";
@@ -120,11 +122,24 @@ function GscConnect({
void queryClient.invalidateQueries({ queryKey: GRANT_STATUS_KEY });
}, [requiresReconnect, queryClient, projectId]);
+ const noWebsites = hasNoGscWebsites(
+ accounts,
+ sitesQuery.isLoading,
+ sitesQuery.isError,
+ );
+ React.useEffect(() => {
+ if (noWebsites) captureClientEvent("onboarding:gsc_no_properties");
+ }, [noWebsites]);
+
const setSiteMutation = useMutation({
mutationFn: (selected: GooglePickerSelection) =>
googleProviders.gsc.save(projectId, selected),
+ onError: (error) => {
+ captureClientEvent("onboarding:gsc_property_select_failed", {
+ error_code: getErrorCode(error) ?? "UNKNOWN",
+ });
+ },
onSuccess: () => {
- captureClientEvent("gsc:property_select");
void queryClient.invalidateQueries({ queryKey: connectionKey });
// The dashboard checklist reads the same connection state.
void queryClient.invalidateQueries({
diff --git a/src/client/features/onboarding/WebsiteOnboardingStep.tsx b/src/client/features/onboarding/WebsiteOnboardingStep.tsx
index 4d5955e7..2ebdaefd 100644
--- a/src/client/features/onboarding/WebsiteOnboardingStep.tsx
+++ b/src/client/features/onboarding/WebsiteOnboardingStep.tsx
@@ -127,7 +127,11 @@ function WebsiteForm({
try {
await saveMutation.mutateAsync(value);
} catch (error) {
- if (getErrorCode(error) === "VALIDATION_ERROR")
+ const errorCode = getErrorCode(error);
+ captureClientEvent("onboarding:website_save_failed", {
+ error_code: errorCode ?? "UNKNOWN",
+ });
+ if (errorCode === "VALIDATION_ERROR")
formApi.setErrorMap({
onSubmit: {
fields: { domain: "Enter a valid domain, like acme.com." },
diff --git a/src/client/lib/posthog.test.ts b/src/client/lib/posthog.test.ts
new file mode 100644
index 00000000..51da34e2
--- /dev/null
+++ b/src/client/lib/posthog.test.ts
@@ -0,0 +1,50 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const client = vi.hoisted(() => ({
+ init: vi.fn(),
+ capture: vi.fn(),
+ opt_in_capturing: vi.fn(),
+ opt_out_capturing: vi.fn(),
+ startSessionRecording: vi.fn(),
+ stopSessionRecording: vi.fn(),
+}));
+
+vi.mock("posthog-js", () => ({ default: client }));
+vi.mock("@/lib/auth-mode", () => ({ isHostedClientAuthMode: () => true }));
+
+// The module keeps the capture state for the page's lifetime, so each test
+// loads a fresh copy.
+async function loadPostHog() {
+ vi.resetModules();
+ return import("./posthog");
+}
+
+describe("events reported before the privacy choices are known", () => {
+ beforeEach(() => {
+ vi.stubGlobal("window", {});
+ vi.stubEnv("POSTHOG_PUBLIC_KEY", "phc_test");
+ vi.stubEnv("POSTHOG_HOST", "https://posthog.test");
+ });
+
+ it("are sent once analytics starts", async () => {
+ const posthog = await loadPostHog();
+ posthog.captureClientEvent("onboarding:step_viewed", { step: 0 });
+ posthog.startAnalyticsCapture({ replay: false });
+
+ await vi.waitFor(() =>
+ expect(client.capture).toHaveBeenCalledWith("onboarding:step_viewed", {
+ step: 0,
+ }),
+ );
+ });
+
+ it("are dropped when analytics stays off", async () => {
+ const posthog = await loadPostHog();
+ posthog.captureClientEvent("onboarding:step_viewed", { step: 0 });
+ posthog.stopAnalyticsCapture();
+ posthog.startAnalyticsCapture({ replay: false });
+
+ await vi.waitFor(() => expect(client.opt_in_capturing).toHaveBeenCalled());
+ expect(client.capture).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/client/lib/posthog.ts b/src/client/lib/posthog.ts
index 69c8987e..60edcbc5 100644
--- a/src/client/lib/posthog.ts
+++ b/src/client/lib/posthog.ts
@@ -13,6 +13,12 @@ let browserPostHogClientPromise: Promise<BrowserPostHogClient | null> | null =
// Off until PrivacyBootstrap applies the visitor's choices, so nothing is
// captured before we know whether analytics is allowed.
let analyticsCaptureEnabled = false;
+// Events reported before then, such as a page's first view: the choices can
+// resolve after the page mounts. Sent if analytics starts, dropped if it
+// doesn't. Null once the choices are known.
+let eventsBeforeChoices:
+ | [string, Record<string, unknown> | undefined][]
+ | null = [];
let clientErrorCaptureStopped = false;
type ExceptionEntry = {
@@ -171,7 +177,11 @@ export function captureClientEvent(
event: string,
properties?: Record<string, unknown>,
) {
- if (!analyticsCaptureEnabled) return;
+ if (!analyticsCaptureEnabled) {
+ if (eventsBeforeChoices && eventsBeforeChoices.length < 50)
+ eventsBeforeChoices.push([event, properties]);
+ return;
+ }
withPostHogClient((client) => client.capture(event, properties));
}
@@ -197,6 +207,7 @@ export function resetAnalyticsUser() {
export function stopAnalyticsCapture() {
analyticsCaptureEnabled = false;
+ eventsBeforeChoices = null;
// Chained even while PostHog is still loading, so this runs after a pending
// start and the stop wins.
withExistingPostHogClient((client) => {
@@ -207,11 +218,15 @@ export function stopAnalyticsCapture() {
export function startAnalyticsCapture({ replay }: { replay: boolean }) {
analyticsCaptureEnabled = true;
+ const pending = eventsBeforeChoices ?? [];
+ eventsBeforeChoices = null;
withPostHogClient((client) => {
if (!analyticsCaptureEnabled) return;
client.opt_in_capturing({ captureEventName: false });
if (replay) client.startSessionRecording();
else client.stopSessionRecording();
+ for (const [event, properties] of pending)
+ client.capture(event, properties);
});
}
diff --git a/src/lib/auth-redirect.ts b/src/lib/auth-redirect.ts
index 44b8fa73..6055ffbc 100644
--- a/src/lib/auth-redirect.ts
+++ b/src/lib/auth-redirect.ts
@@ -1,4 +1,4 @@
-const OAUTH_AUTHORIZE_PATH = "/api/auth/oauth2/authorize";
+export const OAUTH_AUTHORIZE_PATH = "/api/auth/oauth2/authorize";
const OAUTH_SIGNED_QUERY_END = "sig";
const OAUTH_AUTHORIZE_MARKERS = ["response_type", "client_id", "redirect_uri"];
diff --git a/src/lib/auth.ts b/src/lib/auth.ts
index b85e1504..8a0a9e4d 100644
--- a/src/lib/auth.ts
+++ b/src/lib/auth.ts
@@ -24,6 +24,7 @@ import { onInvitationAccepted } from "@/server/auth/invited-member";
import { AuthRepository } from "@/server/auth/repositories/AuthRepository";
import { captureDubReferralSignup } from "@/server/referrals/dub";
import { captureMetaSignup } from "@/server/referrals/meta";
+import { captureSignUpCompleted } from "@/server/auth/sign-up-analytics";
import {
productUpdatesOnByDefault,
requestPrivacyChoices,
@@ -280,6 +281,9 @@ function createAuth() {
}
// Sent only if the separate advertising (Meta) choice allows it.
captureMetaSignup(ctx?.request);
+ await captureSignUpCompleted(user, ctx).catch((error) =>
+ console.error("sign-up analytics failed", error),
+ );
}
},
},
diff --git a/src/routes/_authenticated.onboarding.index.tsx b/src/routes/_authenticated.onboarding.index.tsx
index 6b21406c..0e6be3d6 100644
--- a/src/routes/_authenticated.onboarding.index.tsx
+++ b/src/routes/_authenticated.onboarding.index.tsx
@@ -1,3 +1,4 @@
+import { useEffect } from "react";
import { useMutation } from "@tanstack/react-query";
import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";
import { PlanPageAccountMenu } from "@/client/features/billing/PlanPageAccountMenu";
@@ -65,6 +66,15 @@ function OnboardingPage() {
}),
});
+ // Pageviews drop the query string, `?step=` included, so each step reports
+ // itself.
+ useEffect(() => {
+ captureClientEvent("onboarding:step_viewed", {
+ step,
+ step_name: ONBOARDING_STEPS[step],
+ });
+ }, [step]);
+
const goToStep = (next: number) =>
void navigate({
to: "/onboarding",
@@ -97,9 +107,6 @@ function OnboardingPage() {
// Keep the user here to retry; an unsaved completion would redirect back.
return;
}
- captureClientEvent("onboarding:completed", {
- from_free_check: Boolean(domain),
- });
// Visitors who signed up from the free keyword check came to see the rest
// of its results, so land them on the saved website's keywords ranking
// #4-20 instead of the dashboard.
diff --git a/src/server/auth/sign-up-analytics.test.ts b/src/server/auth/sign-up-analytics.test.ts
new file mode 100644
index 00000000..91b2fba0
--- /dev/null
+++ b/src/server/auth/sign-up-analytics.test.ts
@@ -0,0 +1,63 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { captureSignUpCompleted } from "./sign-up-analytics";
+
+const mocks = vi.hoisted(() => ({
+ captureServerEvent: vi.fn(),
+ getOAuthState: vi.fn(),
+}));
+
+vi.mock("cloudflare:workers", () => ({
+ waitUntil: (promise: Promise<unknown>) => promise,
+}));
+vi.mock("better-auth/api", () => ({ getOAuthState: mocks.getOAuthState }));
+vi.mock("@/server/lib/posthog", () => ({
+ captureServerEvent: mocks.captureServerEvent,
+}));
+
+const user = { id: "user_1", analyticsOptedOut: false };
+const mcpAuthorize = "/api/auth/oauth2/authorize?client_id=c&sig=s";
+
+describe("captureSignUpCompleted", () => {
+ beforeEach(() => {
+ mocks.getOAuthState.mockResolvedValue(null);
+ });
+
+ it("finds an MCP consent sign-up behind email verification", async () => {
+ await captureSignUpCompleted(user, {
+ path: "/sign-up/email",
+ body: {
+ callbackURL: `https://openseo.so/verify-email?redirect=${encodeURIComponent(mcpAuthorize)}`,
+ },
+ });
+
+ expect(mocks.captureServerEvent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ properties: { method: "email", entry: "mcp", from_free_check: false },
+ }),
+ );
+ });
+
+ it("reads a Google sign-up's destination from the OAuth state", async () => {
+ mocks.getOAuthState.mockResolvedValue({
+ callbackURL: "https://openseo.so/",
+ newUserURL: "https://openseo.so/onboarding?domain=openseo.so",
+ });
+
+ await captureSignUpCompleted(user, { path: "/callback/google" });
+
+ expect(mocks.captureServerEvent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ properties: { method: "google", entry: "app", from_free_check: true },
+ }),
+ );
+ });
+
+ it("sends nothing for a visitor who has not allowed analytics", async () => {
+ await captureSignUpCompleted(
+ { ...user, analyticsOptedOut: true },
+ { path: "/callback/google" },
+ );
+
+ expect(mocks.captureServerEvent).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/auth/sign-up-analytics.ts b/src/server/auth/sign-up-analytics.ts
new file mode 100644
index 00000000..5d4e5dd1
--- /dev/null
+++ b/src/server/auth/sign-up-analytics.ts
@@ -0,0 +1,62 @@
+import { waitUntil } from "cloudflare:workers";
+import { getOAuthState } from "better-auth/api";
+import { z } from "zod";
+import { OAUTH_AUTHORIZE_PATH } from "@/lib/auth-redirect";
+import { captureServerEvent } from "@/server/lib/posthog";
+
+const emailSignUpBodySchema = z.object({ callbackURL: z.string() });
+
+/**
+ * `auth:sign_up_completed`, sent once the user row exists. Google sign-ups end
+ * in a full-page redirect, so the browser never reports them as complete.
+ * `entry` separates sign-ups an MCP client's OAuth consent started (the
+ * authorize URL rides along as the sign-up redirect) from app sign-ups.
+ */
+export async function captureSignUpCompleted(
+ user: { id: string; analyticsOptedOut?: unknown },
+ ctx: { path?: string; body?: unknown } | null | undefined,
+) {
+ // Set from the visitor's privacy choices in the create hook. The new row
+ // may not be visible yet to captureServerEvent's own opt-out read.
+ if (user.analyticsOptedOut !== false) return;
+ const method = ctx?.path === "/sign-up/email" ? "email" : "google";
+ const target = signUpTarget(
+ method === "email"
+ ? emailSignUpBodySchema.safeParse(ctx?.body).data?.callbackURL
+ : await getOAuthState().then(
+ (state) => state?.newUserURL ?? state?.callbackURL,
+ () => undefined,
+ ),
+ );
+ waitUntil(
+ captureServerEvent({
+ distinctId: user.id,
+ event: "auth:sign_up_completed",
+ organizationId: null,
+ properties: {
+ method,
+ entry: target?.pathname === OAUTH_AUTHORIZE_PATH ? "mcp" : "app",
+ // Signed up from the marketing site's free keyword check.
+ from_free_check:
+ target?.pathname === "/onboarding" &&
+ target.searchParams.has("domain"),
+ },
+ }),
+ );
+}
+
+/** Where the new user goes after sign-up. */
+function signUpTarget(callbackURL: string | undefined) {
+ if (!callbackURL) return null;
+ try {
+ const url = new URL(callbackURL, "https://openseo.local");
+ // Email sign-ups verify first, and carry the destination as `redirect`.
+ const redirect =
+ url.pathname === "/verify-email"
+ ? url.searchParams.get("redirect")
+ : null;
+ return redirect ? new URL(redirect, url) : url;
+ } catch {
+ return null;
+ }
+}
diff --git a/src/server/features/activation/mcpActivation.ts b/src/server/features/activation/mcpActivation.ts
index 6a86e44a..5301e769 100644
--- a/src/server/features/activation/mcpActivation.ts
+++ b/src/server/features/activation/mcpActivation.ts
@@ -1,4 +1,6 @@
+import { waitUntil } from "cloudflare:workers";
import { ActivationRepository } from "@/server/features/activation/repositories/ActivationRepository";
+import { captureServerEvent } from "@/server/lib/posthog";
// Orgs whose activation milestones are already recorded (or in flight) in
// this isolate. Only *first* timestamps matter, so after one successful write
@@ -40,3 +42,30 @@ export async function recordExternalMcpToolCall(
console.error("activation: recordExternalMcpToolCall failed", error);
}
}
+
+/**
+ * An agent's first connection or first project finishes the user's
+ * onboarding. Reports the completion only from the call that made it.
+ * Best-effort like the milestones above: the agent's action already worked.
+ */
+export async function completeOnboardingFromAgent(
+ user: { userId: string; organizationId: string },
+ via: "agent_connect" | "agent_project",
+): Promise<void> {
+ const completed = await ActivationRepository.markOnboardingCompleted(
+ user.userId,
+ user.organizationId,
+ ).catch((error: unknown) => {
+ console.error(`activation: onboarding completion (${via}) failed`, error);
+ return false;
+ });
+ if (!completed) return;
+ waitUntil(
+ captureServerEvent({
+ distinctId: user.userId,
+ event: "onboarding:completed",
+ organizationId: user.organizationId,
+ properties: { via },
+ }),
+ );
+}
diff --git a/src/server/features/activation/repositories/ActivationRepository.ts b/src/server/features/activation/repositories/ActivationRepository.ts
index a435e5f7..776da9cf 100644
--- a/src/server/features/activation/repositories/ActivationRepository.ts
+++ b/src/server/features/activation/repositories/ActivationRepository.ts
@@ -73,13 +73,13 @@ async function recordFirstMcpToolCall(organizationId: string): Promise<void> {
// An agent that creates a project through MCP has done the wizard's main job,
// so the app stops sending the user to onboarding. COALESCE keeps an earlier
// completion. The Search Console nudge stays pending: the user never saw that
-// step.
+// step. Returns whether this call completed onboarding.
async function markOnboardingCompleted(
userId: string,
organizationId: string,
-): Promise<void> {
+): Promise<boolean> {
const now = new Date().toISOString();
- await db
+ const [row] = await db
.insert(userOnboardingAnswers)
.values({ userId, organizationId, completedAt: now, updatedAt: now })
.onConflictDoUpdate({
@@ -88,7 +88,9 @@ async function markOnboardingCompleted(
completedAt: sql`coalesce(${userOnboardingAnswers.completedAt}, ${now})`,
updatedAt: now,
},
- });
+ })
+ .returning({ completedAt: userOnboardingAnswers.completedAt });
+ return row?.completedAt === now;
}
const clickStepColumns = {
diff --git a/src/server/features/dashboard/services/DashboardFirstAuditService.ts b/src/server/features/dashboard/services/DashboardFirstAuditService.ts
index ec2c627d..0ca569f5 100644
--- a/src/server/features/dashboard/services/DashboardFirstAuditService.ts
+++ b/src/server/features/dashboard/services/DashboardFirstAuditService.ts
@@ -1,9 +1,11 @@
+import { waitUntil } from "cloudflare:workers";
import { shouldCaptureAppErrorCode } from "@/shared/error-codes";
import { AuditService } from "@/server/features/audit/services/AuditService";
import { AuditRepository } from "@/server/features/audit/repositories/AuditRepository";
import { DataRefreshClaimRepository } from "../repositories/DataRefreshClaimRepository";
import { buildCacheKey } from "@/server/lib/r2-cache";
import { asAppError } from "@/server/lib/errors";
+import { captureServerEvent } from "@/server/lib/posthog";
import type { BillingCustomerContext } from "@/server/billing/subscription";
async function start(
@@ -48,6 +50,20 @@ async function start(
});
auditStarted = true;
await DataRefreshClaimRepository.finish(key, token, 100 * 365 * 86400_000);
+ waitUntil(
+ captureServerEvent({
+ distinctId: customer.userId,
+ event: "site_audit:start",
+ organizationId: customer.organizationId,
+ properties: {
+ project_id: projectId,
+ max_pages: 50,
+ run_lighthouse: false,
+ plan_tier: limitTier,
+ source: "first_audit",
+ },
+ }),
+ );
return { status: "started" as const };
} catch (error) {
if (key && token)
diff --git a/src/server/lib/posthog.ts b/src/server/lib/posthog.ts
index 7168bab0..08ae2595 100644
--- a/src/server/lib/posthog.ts
+++ b/src/server/lib/posthog.ts
@@ -76,7 +76,8 @@ export async function captureServerEvent(args: {
distinctId: string;
event: string;
properties?: Record<string, unknown>;
- organizationId: string;
+ /** Null only before the user has an organization (sign-up). */
+ organizationId: string | null;
}) {
if (!(await isHostedServerAuthMode())) {
return;
@@ -103,9 +104,9 @@ export async function captureServerEvent(args: {
distinctId: args.distinctId,
event: args.event,
properties: args.properties,
- groups: {
- organization: args.organizationId,
- },
+ groups: args.organizationId
+ ? { organization: args.organizationId }
+ : undefined,
});
} catch (posthogError) {
console.error("posthog server capture failed", posthogError);
diff --git a/src/server/mcp/oauth-provider.test.ts b/src/server/mcp/oauth-provider.test.ts
index a387c424..32ef2403 100644
--- a/src/server/mcp/oauth-provider.test.ts
+++ b/src/server/mcp/oauth-provider.test.ts
@@ -97,6 +97,7 @@ vi.mock("@/middleware/ensure-user/hosted", () => ({
vi.mock("@/server/features/activation/mcpActivation", () => ({
recordMcpAuthorized: vi.fn(),
+ completeOnboardingFromAgent: vi.fn(),
}));
vi.mock("@/server/lib/posthog", () => ({
diff --git a/src/server/mcp/oauth-provider.ts b/src/server/mcp/oauth-provider.ts
index 0e952ea5..e9bb7141 100644
--- a/src/server/mcp/oauth-provider.ts
+++ b/src/server/mcp/oauth-provider.ts
@@ -9,14 +9,17 @@ import {
} from "@cloudflare/workers-oauth-provider";
import { z } from "zod";
import { getHostedBaseUrl } from "@/lib/auth";
+import { OAUTH_AUTHORIZE_PATH } from "@/lib/auth-redirect";
import {
getMcpResource,
MCP_OAUTH_SCOPES,
MCP_SCOPE,
} from "@/lib/oauth-resource";
import { asAppError } from "@/server/lib/errors";
-import { recordMcpAuthorized } from "@/server/features/activation/mcpActivation";
-import { ActivationRepository } from "@/server/features/activation/repositories/ActivationRepository";
+import {
+ completeOnboardingFromAgent,
+ recordMcpAuthorized,
+} from "@/server/features/activation/mcpActivation";
import { markOnboardingMilestone } from "@/server/email/onboarding-drip";
import { captureServerEvent } from "@/server/lib/posthog";
import {
@@ -30,7 +33,6 @@ import { getPublicOrigin } from "@/server/mcp/public-origin";
import { resolveHostedContext } from "@/middleware/ensure-user/hosted";
import { handleMcpApiKeyRequest } from "@/server/mcp/api-key-auth";
-const OAUTH_AUTHORIZE_PATH = "/api/auth/oauth2/authorize";
const OAUTH_TOKEN_PATH = "/api/auth/oauth2/token";
const OAUTH_REGISTER_PATH = "/api/auth/oauth2/register";
@@ -360,13 +362,8 @@ async function handleOAuthConsentResponse(
await recordMcpAuthorized(context.organizationId);
// Connecting an agent is the last onboarding step, so this finishes
// onboarding for people who paste the setup prompt and never return to the
- // wizard. Best-effort: the authorization already succeeded.
- await ActivationRepository.markOnboardingCompleted(
- context.userId,
- context.organizationId,
- ).catch((error: unknown) => {
- console.error("oauth consent: onboarding completion failed", error);
- });
+ // wizard.
+ await completeOnboardingFromAgent(context, "agent_connect");
await markOnboardingMilestone(context, "mcpConnected");
waitUntil(
diff --git a/src/server/mcp/oauth-refresh.e2e.test.ts b/src/server/mcp/oauth-refresh.e2e.test.ts
index 99b088bf..6fbb9f77 100644
--- a/src/server/mcp/oauth-refresh.e2e.test.ts
+++ b/src/server/mcp/oauth-refresh.e2e.test.ts
@@ -40,6 +40,7 @@ vi.mock("@/middleware/ensure-user/hosted", () => ({
vi.mock("@/server/features/activation/mcpActivation", () => ({
recordMcpAuthorized: () => Promise.resolve(),
+ completeOnboardingFromAgent: () => Promise.resolve(),
}));
vi.mock("@/server/lib/posthog", () => ({
diff --git a/src/server/mcp/tools/create-project.test.ts b/src/server/mcp/tools/create-project.test.ts
index e4eae9c0..4597ff60 100644
--- a/src/server/mcp/tools/create-project.test.ts
+++ b/src/server/mcp/tools/create-project.test.ts
@@ -6,6 +6,7 @@ const mocks = vi.hoisted(() => ({
createProject: vi.fn(),
listMembershipsForUser: vi.fn(),
markOnboardingCompleted: vi.fn(),
+ captureServerEvent: vi.fn(),
}));
vi.mock("@/server/features/projects/services/ProjectService", () => ({
@@ -23,6 +24,14 @@ vi.mock(
}),
);
+vi.mock("cloudflare:workers", () => ({
+ waitUntil: (promise: Promise<unknown>) => promise,
+}));
+
+vi.mock("@/server/lib/posthog", () => ({
+ captureServerEvent: mocks.captureServerEvent,
+}));
+
vi.mock("@/server/auth/repositories/AuthRepository", () => ({
AuthRepository: {
listMembershipsForUser: mocks.listMembershipsForUser,
@@ -125,7 +134,7 @@ describe("create_project with a user-scoped credential", () => {
languageCode: "en",
});
mocks.listMembershipsForUser.mockResolvedValue(memberships);
- mocks.markOnboardingCompleted.mockResolvedValue(undefined);
+ mocks.markOnboardingCompleted.mockResolvedValue(false);
});
it("errors with the organization list when no organizationId is given and the user has several", async () => {
@@ -192,4 +201,20 @@ describe("create_project with a user-scoped credential", () => {
"org_a",
);
});
+
+ it("reports onboarding completion only from the call that completed it", async () => {
+ mocks.listMembershipsForUser.mockResolvedValue([memberships[0]]);
+ mocks.markOnboardingCompleted.mockResolvedValueOnce(true);
+
+ await createProjectTool.handler({ name: "Acme" }, userScopedContext);
+ await createProjectTool.handler({ name: "Acme" }, userScopedContext);
+
+ expect(mocks.captureServerEvent).toHaveBeenCalledTimes(1);
+ expect(mocks.captureServerEvent).toHaveBeenCalledWith({
+ distinctId: "user_123",
+ event: "onboarding:completed",
+ organizationId: "org_a",
+ properties: { via: "agent_project" },
+ });
+ });
});
diff --git a/src/server/mcp/tools/create-project.ts b/src/server/mcp/tools/create-project.ts
index fa27ebf5..917012b7 100644
--- a/src/server/mcp/tools/create-project.ts
+++ b/src/server/mcp/tools/create-project.ts
@@ -1,6 +1,6 @@
import { requireOrgPermission } from "@/server/auth/org-gate";
import { AuthRepository } from "@/server/auth/repositories/AuthRepository";
-import { ActivationRepository } from "@/server/features/activation/repositories/ActivationRepository";
+import { completeOnboardingFromAgent } from "@/server/features/activation/mcpActivation";
import { ProjectService } from "@/server/features/projects/services/ProjectService";
import { AppError } from "@/server/lib/errors";
import { mcpResponse } from "@/server/mcp/formatters";
@@ -156,12 +156,10 @@ export const createProjectTool = {
// Best-effort: the project already exists, and an error here would make
// the agent retry and create a duplicate.
if (auth.orgScope === "user") {
- await ActivationRepository.markOnboardingCompleted(
- auth.userId,
- target.organizationId,
- ).catch((error: unknown) => {
- console.error("create_project: onboarding completion failed", error);
- });
+ await completeOnboardingFromAgent(
+ { userId: auth.userId, organizationId: target.organizationId },
+ "agent_project",
+ );
}
return mcpResponse({
text: `Created project ${project.id} ${project.name}${
diff --git a/src/serverFunctions/onboarding.ts b/src/serverFunctions/onboarding.ts
index 7ec3c98f..c99b6866 100644
--- a/src/serverFunctions/onboarding.ts
+++ b/src/serverFunctions/onboarding.ts
@@ -1,8 +1,10 @@
+import { waitUntil } from "cloudflare:workers";
import { createServerFn } from "@tanstack/react-start";
-import { eq } from "drizzle-orm";
+import { eq, sql } from "drizzle-orm";
import { z } from "zod";
import { user, userOnboardingAnswers } from "@/db/schema";
import { db } from "@/db";
+import { captureServerEvent } from "@/server/lib/posthog";
import { requireAuthenticatedContext } from "@/serverFunctions/middleware";
const onboardingAnswersSchema = z.object({
@@ -78,14 +80,18 @@ export const saveOnboardingAnswers = createServerFn({ method: "POST" })
...(data.foundVia !== undefined ? { foundVia: data.foundVia } : {}),
// Completing onboarding means the user passed the Search Console step, so
// resolve the GSC prompt — the legacy re-engagement nudge must not fire
- // for anyone who already saw that step.
+ // for anyone who already saw that step. COALESCE keeps an earlier
+ // completion, such as an agent's create_project.
...(completedAt !== undefined
- ? { completedAt, gscNudgeDismissedAt: completedAt }
+ ? {
+ completedAt: sql`coalesce(${userOnboardingAnswers.completedAt}, ${completedAt})`,
+ gscNudgeDismissedAt: completedAt,
+ }
: {}),
updatedAt: now,
};
- await db
+ const [saved] = await db
.insert(userOnboardingAnswers)
.values({
userId: context.userId,
@@ -101,7 +107,19 @@ export const saveOnboardingAnswers = createServerFn({ method: "POST" })
.onConflictDoUpdate({
target: userOnboardingAnswers.userId,
set,
- });
+ })
+ .returning({ completedAt: userOnboardingAnswers.completedAt });
+
+ if (completedAt && saved?.completedAt === completedAt) {
+ waitUntil(
+ captureServerEvent({
+ distinctId: context.userId,
+ event: "onboarding:completed",
+ organizationId: context.organizationId,
+ properties: { via: "wizard" },
+ }),
+ );
+ }
return { ok: true };
});