mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 20:09:33 +01:00
feat(analytics): move onboarding funnel telemetry server-side and add granular step instrumentation (#23403)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted Paperclip Cloud tracks user onboarding conversion in PostHog
across server-side events and browser events
> - Onboarding funnel events (`onboarding_opened`,
`onboarding_step_viewed`, `onboarding_step_completed`,
`onboarding_step_failed`, `onboarding_dismissed`) currently fire only
from browser `posthog-js`
> - Browser `posthog-js` loads lazily after `whenPageSettles` (up to 15
seconds), drops events captured before `startProductAnalytics`
initializes, and can be blocked by privacy extensions, causing
artificial dropoff between server-side `workspace_entry` and
`onboarding_opened`
> - Step 1 (`name_org`) is unmapped in `WIZARD_STEPS`, and
`connect_model` lacks sub-step visibility (provider selection,
credential mode switch, OAuth progress, API key submission, Cloud trial
CTA, mobile handoff)
> - This pull request routes all onboarding funnel events through a
first-party `POST /api/onboarding/telemetry` endpoint backed by
`trackCloudPostHogEvent` (`posthog-node`), preserves every existing
event name verbatim, adds granular step and sub-step instrumentation,
and fixes the pre-start queue drop in `product-analytics.ts`
> - The benefit is adblocker-proof, race-free server-side onboarding
analytics in PostHog with complete step-by-step dropoff visibility and
zero breaking changes to existing insights
## Linked Issues or Issue Description
**What existing behavior does this improve?**
Cloud onboarding funnel analytics in
`ui/src/lib/analytics/onboarding-analytics.ts`,
`ui/src/lib/analytics/product-analytics.ts`,
`ui/src/components/OnboardingWizard.tsx`, and `server/src/telemetry.ts`.
**Subsystem affected**
Cross-cutting (multiple of the above)
**Current behavior**
Onboarding funnel events fire only from browser `posthog-js`. Events
captured before `ProductAnalyticsGate` calls `startProductAnalytics` are
silently dropped, queued events are lost if the user leaves before
`/_ph/static/array.js` loads, Step 1 (`name_org`) is unmapped, and
`connect_model` sub-steps (OAuth link open, code submit, retry, abandon,
provider tile click, Cloud trial CTA, mobile desktop handoff) are not
instrumented.
**Proposed behavior**
All onboarding funnel and interaction events are sent via
`fetch("/api/onboarding/telemetry", { method: "POST", keepalive: true
})` to a board-authenticated, strictly Zod-validated Express route that
forwards them server-side to PostHog via `trackCloudPostHogEvent`.
Existing event names are preserved verbatim and removed from
`posthog-js` to guarantee a single sender per event. Pre-start browser
events in `product-analytics.ts` are also buffered until
`startProductAnalytics` runs.
**Reason and benefit**
Adblockers and browser script lazy-load races can no longer drop
onboarding funnel events. Product analytics can now separate
`workspace_entry` -> `onboarding_workspace_loaded` ->
`onboarding_opened` and pinpoint exact dropoff points on every step and
`connect_model` sub-step.
**Breaking changes**
None. Existing PostHog event names (`onboarding_opened`,
`onboarding_step_viewed`, `onboarding_step_completed`,
`onboarding_step_failed`, `onboarding_dismissed`,
`agent_chat_message_sent`) are preserved verbatim. On self-hosted
installs, `trackCloudPostHogEvent` is a no-op and the endpoint returns
`204 No Content`.
## What Changed
- Added `packages/shared/src/onboarding-telemetry.ts` (exported from
`packages/shared/src/index.ts`) with strict Zod discriminated-union
schemas (`onboardingTelemetryEventSchema`), canonical event names
(`ONBOARDING_TELEMETRY_EVENTS`), and snake_case PostHog property mapping
(`onboardingTelemetryEventToPostHogProperties`).
- Added `server/src/routes/onboarding-telemetry.ts` (`POST
/api/onboarding/telemetry`), mounted in `server/src/app.ts`, enforcing
`assertBoard(req)`, `assertCompanyAccess(req, companyId)` when
`companyId` is present, strict schema validation, and server-side
delivery via `trackCloudPostHogEvent`.
- Updated `ui/src/lib/analytics/onboarding-analytics.ts` to send all
onboarding events to `/api/onboarding/telemetry` with `keepalive: true`
(removing duplicate browser `posthog-js` sends), mapped Step 1 to
`name_org`, fixed `1 -> 3` forward step completion ordering, and added
granular capture helpers.
- Instrumented `ui/src/hooks/useAgentlessOnboardingAutoOpen.ts`
(`onboarding_workspace_loaded`),
`ui/src/components/onboarding/MobileDesktopNudge.tsx`
(`onboarding_mobile_handoff_action`), and
`ui/src/components/OnboardingWizard.tsx` (all step submissions,
back/jump navigation, Cloud trial CTA, model source selection,
credential mode switching, OAuth progress stages, API key submission,
advanced toggle, and launch click). Note: `OnboardingWizard.tsx` is an
existing large file (>1,000 lines); all schema and transport logic lives
in `packages/shared/src/onboarding-telemetry.ts` and
`ui/src/lib/analytics/onboarding-analytics.ts`, with only call-site
wiring added to the wizard.
- Fixed `ui/src/lib/analytics/product-analytics.ts` to buffer events
captured before `startProductAnalytics` runs (still bounded to 50 events
and cleared on user change).
- Added server route tests in
`server/src/__tests__/onboarding-telemetry-routes.test.ts` and expanded
`ui/src/lib/analytics/onboarding-analytics.test.tsx`.
- Updated `tests/runner-e2e/source-sdk-public-inputs.json` for the new
`@paperclipai/shared` export.
## Verification
- `pnpm --filter @paperclipai/shared build` — passed.
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm --filter @paperclipai/server typecheck` — passed.
- `pnpm vitest run
server/src/__tests__/onboarding-telemetry-routes.test.ts
ui/src/lib/analytics/onboarding-analytics.test.tsx
ui/src/lib/analytics/product-analytics.test.ts
ui/src/lib/analytics/product-analytics-events.test.ts
ui/src/components/ProductAnalyticsGate.test.tsx
ui/src/hooks/useAgentlessOnboardingAutoOpen.test.tsx` — 6/6 test files
passed (41/41 tests).
- `pnpm verify` — exited with code 2 because
`tests/runner-e2e/source-sdk-public-inputs.json` requires broad CI
coverage; relying on required CI checks for the remaining broad suites.
## Risks
- Low risk: `POST /api/onboarding/telemetry` performs no database
writes, validates all fields against a strict allowlist (enums,
booleans, bounded integers, safe regex slugs), enforces board auth and
company access, and is a no-op returning `204` on self-hosted instances.
- Browser telemetry calls swallow network failures so analytics can
never block or break onboarding.
## Model Used
- Google Gemini (Gemini 4 Neon, Medium) via Antigravity agentic coding
environment with tool use and local command execution.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
1 parent
689bfd04ac
commit
c0edaa21a3
18 files changed
+1877
-182
No files matched your search
@@ -203,9 +203,20 @@ import { DEFAULT_AGENT_ROLE } from "../lib/onboarding-agent-role";
|
||||
import { capsuleHeroMotion, capsuleRoomEnter, capsuleRoomExit, heroRoomArrival, heroRoomMotion, ledeMotion, stepContentMotion, titleSwapMotion } from "./onboarding/onboarding-motion";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
captureOnboardingAdvancedToggled,
|
||||
captureOnboardingApiKeySubmitted,
|
||||
captureOnboardingCredentialModeSwitched,
|
||||
captureOnboardingLaunchClicked,
|
||||
captureOnboardingModelSourceSelected,
|
||||
captureOnboardingOAuthProgress,
|
||||
captureOnboardingStepCompleted,
|
||||
captureOnboardingStepFailed,
|
||||
captureOnboardingStepNavigated,
|
||||
captureOnboardingStepSubmitted,
|
||||
captureOnboardingTrialCtaClicked,
|
||||
onboardingAnalyticsStepFor,
|
||||
useOnboardingAnalytics,
|
||||
type OnboardingAnalyticsOutcome,
|
||||
} from "@/lib/analytics/onboarding-analytics";
|
||||
import {
|
||||
ArrowLeft,
|
||||
@@ -664,10 +675,25 @@ function OnboardingWizardInner({
|
||||
(savedKeys.subscriptions.length > 0 || (adapterType === "claude_local" && savedKeys.storedLogin.data))
|
||||
? "subscription" : savedKeys.options.length || adapterType === "opencode_local" ? "api" : "subscription"
|
||||
);
|
||||
const [connectAnalyticsOverride, setConnectAnalyticsOverride] = useState<{
|
||||
outcome: OnboardingAnalyticsOutcome;
|
||||
adapterType: string;
|
||||
provider: string;
|
||||
} | null>(null);
|
||||
const onboardingAnalytics = useOnboardingAnalytics({
|
||||
open: effectiveOnboardingOpen,
|
||||
step,
|
||||
connectOutcome: credentialMode === "api" ? "api_key" : "subscription",
|
||||
connectOutcome: connectAnalyticsOverride?.outcome ?? (credentialMode === "api" ? "api_key" : "subscription"),
|
||||
companyId: createdCompanyId,
|
||||
provider: connectAnalyticsOverride?.provider ?? aiProviderForAdapter(adapterType),
|
||||
adapterType: connectAnalyticsOverride?.adapterType ?? adapterType,
|
||||
role: agentRole,
|
||||
connectPhase,
|
||||
hadError: Boolean(error),
|
||||
stepViewMeta: {
|
||||
savedKeysCount: savedKeys.options.length,
|
||||
hasExistingSubscription: savedKeys.subscriptions.length > 0,
|
||||
},
|
||||
});
|
||||
const [createdCompanyPrefix, setCreatedCompanyPrefix] = useState<
|
||||
string | null
|
||||
@@ -829,7 +855,21 @@ function OnboardingWizardInner({
|
||||
setEntryStep(initialStepRef.current);
|
||||
}
|
||||
if (!previousRequest?.open) {
|
||||
onboardingAnalytics.opened(initialStepRef.current && !resumesRouteDraft ? initialStepRef.current : step, step);
|
||||
const targetEntryStep = initialStepRef.current && !resumesRouteDraft ? initialStepRef.current : step;
|
||||
const openSource = resumesRouteDraft
|
||||
? "resume_draft"
|
||||
: !onboardingOpen
|
||||
? "route"
|
||||
: routeCompanyId
|
||||
? "auto_open"
|
||||
: "manual";
|
||||
onboardingAnalytics.opened(targetEntryStep, step, {
|
||||
companyId: routeCompanyId ?? createdCompanyIdRef.current,
|
||||
source: openSource,
|
||||
isMobile: mobileOnboardingViewport,
|
||||
resumedDraft: resumesRouteDraft,
|
||||
hasExistingCompany: Boolean(routeCompanyId || createdCompanyIdRef.current),
|
||||
});
|
||||
}
|
||||
if (routeCompanyId) {
|
||||
// Claim ownership only when the route *introduces* a company. A route
|
||||
@@ -1002,6 +1042,7 @@ function OnboardingWizardInner({
|
||||
|
||||
async function handleStartWithCloudTrial(options?: { launchToChat?: boolean }) {
|
||||
if (!createdCompanyId || startingCloudTrial || loading) return;
|
||||
captureOnboardingTrialCtaClicked({ companyId: createdCompanyId });
|
||||
setStartingCloudTrial(true);
|
||||
setError(null);
|
||||
try {
|
||||
@@ -1042,9 +1083,18 @@ function OnboardingWizardInner({
|
||||
agentId = hire.agent.id;
|
||||
setCreatedAgentId(agentId);
|
||||
}
|
||||
setConnectAnalyticsOverride({
|
||||
outcome: "cloud_trial",
|
||||
adapterType: "paperclip_runner",
|
||||
provider: "opencode",
|
||||
});
|
||||
if (options?.launchToChat) {
|
||||
await prepareChat(createdCompanyId, agentId).issue;
|
||||
captureOnboardingStepCompleted("launch", "succeeded");
|
||||
captureOnboardingStepCompleted("launch", "succeeded", {
|
||||
companyId: createdCompanyId,
|
||||
adapterType: "paperclip_runner",
|
||||
provider: "opencode",
|
||||
});
|
||||
if (!stillTheSameCompany(createdCompanyId)) return;
|
||||
onboardingAnalytics.finished();
|
||||
const prefix = createdCompanyPrefix;
|
||||
@@ -1059,8 +1109,22 @@ function OnboardingWizardInner({
|
||||
}
|
||||
} catch (err) {
|
||||
if (options?.launchToChat) {
|
||||
captureOnboardingStepCompleted("launch", "failed");
|
||||
captureOnboardingStepFailed({ step: "launch", reason: "launch_failed" });
|
||||
captureOnboardingStepCompleted("launch", "failed", { companyId: createdCompanyId });
|
||||
captureOnboardingStepFailed({
|
||||
step: "launch",
|
||||
reason: "launch_failed",
|
||||
companyId: createdCompanyId,
|
||||
provider: "opencode",
|
||||
adapterType: "paperclip_runner",
|
||||
});
|
||||
} else {
|
||||
captureOnboardingStepFailed({
|
||||
step: "connect_model",
|
||||
reason: "cloud_trial_failed",
|
||||
companyId: createdCompanyId,
|
||||
provider: "opencode",
|
||||
adapterType: "paperclip_runner",
|
||||
});
|
||||
}
|
||||
setError(err instanceof Error ? err.message : "Could not start right away");
|
||||
} finally {
|
||||
@@ -1808,6 +1872,15 @@ function OnboardingWizardInner({
|
||||
|
||||
|
||||
function unwindConnectStep() {
|
||||
if (credentialMode !== "api" && connectPhase !== "idle" && connectPhase !== "unwindRow") {
|
||||
captureOnboardingOAuthProgress({
|
||||
stage: "abandoned",
|
||||
provider: managedProvider ?? adapterType,
|
||||
adapterType,
|
||||
phase: connectPhase,
|
||||
companyId: createdCompanyId,
|
||||
});
|
||||
}
|
||||
setOpenedClaudeSessionId(null);
|
||||
localLogin.cancel();
|
||||
localLoginPrimary.resetSubmitting();
|
||||
@@ -1843,6 +1916,13 @@ function OnboardingWizardInner({
|
||||
*/
|
||||
function openConnectAuthorization() {
|
||||
if ((connectPhase !== "ready" && connectPhase !== "waiting") || !connectAuthUrl || retryLogin) return;
|
||||
captureOnboardingOAuthProgress({
|
||||
stage: "auth_link_opened",
|
||||
provider: managedProvider ?? adapterType,
|
||||
adapterType,
|
||||
phase: connectPhase,
|
||||
companyId: createdCompanyId,
|
||||
});
|
||||
window.open(connectAuthUrl, "_blank", "noreferrer,noopener");
|
||||
setConnectPhase("waiting");
|
||||
}
|
||||
@@ -1851,6 +1931,13 @@ function OnboardingWizardInner({
|
||||
if (setupError) { setSetupError(false); setSetupAttempt(value => value + 1); setError(null); return; }
|
||||
if (browserSignInUnavailable) return;
|
||||
if (retryLogin) {
|
||||
captureOnboardingOAuthProgress({
|
||||
stage: "retried",
|
||||
provider: managedProvider ?? adapterType,
|
||||
adapterType,
|
||||
phase: connectPhase,
|
||||
companyId: createdCompanyId,
|
||||
});
|
||||
setConnectAuthUrl(null);
|
||||
setSubmitLoginCode(null);
|
||||
setRetryLogin(null);
|
||||
@@ -1869,12 +1956,38 @@ function OnboardingWizardInner({
|
||||
openConnectAuthorization();
|
||||
return;
|
||||
}
|
||||
if (localLoginPrimary.runPrimary()) return;
|
||||
if (localLoginPrimary.runPrimary()) {
|
||||
const stage =
|
||||
localLoginAction?.kind === "retry"
|
||||
? "retried"
|
||||
: localLoginAction?.kind === "open_sign_in"
|
||||
? "auth_link_opened"
|
||||
: null;
|
||||
if (stage) {
|
||||
captureOnboardingOAuthProgress({
|
||||
stage,
|
||||
provider: managedProvider ?? adapterType,
|
||||
adapterType,
|
||||
phase: connectPhase,
|
||||
companyId: createdCompanyId,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
// The hold owns the hire once "Connecting" is showing. That now starts at
|
||||
// the paste, before the credential exists, so Cmd+Enter here would hire
|
||||
// against a source with nothing to run on.
|
||||
if (connectPhase === "connecting") return;
|
||||
if (connectStepLoggingIn) return;
|
||||
if (credentialMode === "api") {
|
||||
captureOnboardingApiKeySubmitted({
|
||||
provider: managedProvider ?? adapterType,
|
||||
adapterType,
|
||||
usedSavedKey: Boolean(selectedApiKey),
|
||||
companyId: createdCompanyId,
|
||||
});
|
||||
}
|
||||
setConnectAnalyticsOverride(null);
|
||||
void handleGiveHeartbeat();
|
||||
}
|
||||
|
||||
@@ -2087,6 +2200,21 @@ function OnboardingWizardInner({
|
||||
setCreatedCompanyGoalId(null);
|
||||
}
|
||||
|
||||
function navigateToStep(nextStep: Step, via: "back_button" | "step_indicator") {
|
||||
const fromStep = onboardingAnalyticsStepFor(step);
|
||||
const toStep = onboardingAnalyticsStepFor(nextStep);
|
||||
if (fromStep && toStep && fromStep !== toStep) {
|
||||
captureOnboardingStepNavigated({
|
||||
fromStep,
|
||||
toStep,
|
||||
direction: nextStep < step ? "back" : "jump",
|
||||
via,
|
||||
companyId: createdCompanyId,
|
||||
});
|
||||
}
|
||||
setStep(nextStep);
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
onboardingAnalytics.dismissed(step);
|
||||
reset();
|
||||
@@ -2165,10 +2293,24 @@ function OnboardingWizardInner({
|
||||
}
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
captureOnboardingStepCompleted("review");
|
||||
const launchAdapterType = connectAnalyticsOverride?.adapterType ?? adapterType;
|
||||
const launchProvider = connectAnalyticsOverride?.provider ?? (managedProvider ?? adapterType);
|
||||
const launchOutcome =
|
||||
connectAnalyticsOverride?.outcome ?? (credentialMode === "api" ? "api_key" : "subscription");
|
||||
captureOnboardingLaunchClicked({
|
||||
companyId: createdCompanyId,
|
||||
adapterType: launchAdapterType,
|
||||
provider: launchProvider,
|
||||
outcome: launchOutcome,
|
||||
});
|
||||
captureOnboardingStepCompleted("review", undefined, { companyId: createdCompanyId });
|
||||
try {
|
||||
await prepareChat(createdCompanyId, createdAgentId).issue;
|
||||
captureOnboardingStepCompleted("launch", "succeeded");
|
||||
captureOnboardingStepCompleted("launch", "succeeded", {
|
||||
companyId: createdCompanyId,
|
||||
adapterType: launchAdapterType,
|
||||
provider: launchProvider,
|
||||
});
|
||||
if (!stillTheSameCompany(createdCompanyId)) return;
|
||||
onboardingAnalytics.finished();
|
||||
const prefix = createdCompanyPrefix;
|
||||
@@ -2179,8 +2321,14 @@ function OnboardingWizardInner({
|
||||
closeOnboarding();
|
||||
navigate(`${prefix ? `/${prefix}` : ""}/chats/${agentId}`, { state: { onboardingWelcome: true } });
|
||||
} catch (err) {
|
||||
captureOnboardingStepCompleted("launch", "failed");
|
||||
captureOnboardingStepFailed({ step: "launch", reason: "launch_failed" });
|
||||
captureOnboardingStepCompleted("launch", "failed", { companyId: createdCompanyId });
|
||||
captureOnboardingStepFailed({
|
||||
step: "launch",
|
||||
reason: "launch_failed",
|
||||
companyId: createdCompanyId,
|
||||
adapterType: launchAdapterType,
|
||||
provider: launchProvider,
|
||||
});
|
||||
setError(err instanceof Error ? err.message : "Failed to open your chat. Please try again.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@@ -2635,6 +2783,10 @@ function OnboardingWizardInner({
|
||||
setSelectedCompanyId(company.id);
|
||||
setStep(3);
|
||||
} catch (err) {
|
||||
captureOnboardingStepFailed({
|
||||
step: "name_org",
|
||||
reason: "company_create_failed",
|
||||
});
|
||||
setError(err instanceof Error ? err.message : "Failed to create organization");
|
||||
} finally {
|
||||
creatingCompanyRef.current = false;
|
||||
@@ -3002,8 +3154,11 @@ function OnboardingWizardInner({
|
||||
// handler whose guard is a piece of state the first one has not set
|
||||
// yet — two organizations for one name, two agents for one hire.
|
||||
if (loading) return;
|
||||
if (step === 1 && companyName.trim()) void handleCreateCompany();
|
||||
else if (step === 3 && agentName.trim()) {
|
||||
if (step === 1 && companyName.trim()) {
|
||||
captureOnboardingStepSubmitted({ step: "name_org", via: "enter", companyId: createdCompanyId });
|
||||
void handleCreateCompany();
|
||||
} else if (step === 3 && agentName.trim()) {
|
||||
captureOnboardingStepSubmitted({ step: "create_agent", via: "enter", companyId: createdCompanyId });
|
||||
if (isFreeInferenceOnboarding) {
|
||||
void handleStartWithCloudTrial({ launchToChat: true });
|
||||
} else {
|
||||
@@ -3023,9 +3178,10 @@ function OnboardingWizardInner({
|
||||
agentName.trim() &&
|
||||
connectStepReady &&
|
||||
(retryLogin || submitLoginCode || Boolean(localLoginAction && !localLoginAction.disabled) || !connectStepLoggingIn)
|
||||
)
|
||||
) {
|
||||
captureOnboardingStepSubmitted({ step: "connect_model", via: "enter", companyId: createdCompanyId });
|
||||
handleConnectStepPrimary();
|
||||
else if (step === 5) handleLaunchToChat();
|
||||
} else if (step === 5) handleLaunchToChat();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3172,7 +3328,7 @@ function OnboardingWizardInner({
|
||||
}}
|
||||
onJumpToStep={(target) => {
|
||||
const targetSteps = isFreeInferenceOnboarding ? [1, 3] : ONBOARDING_WIZARD_STEPS;
|
||||
setStep(targetSteps[target - 1]! as Step);
|
||||
navigateToStep(targetSteps[target - 1]! as Step, "step_indicator");
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
@@ -3190,7 +3346,7 @@ function OnboardingWizardInner({
|
||||
entryStep,
|
||||
})
|
||||
}
|
||||
onJumpToStep={(target) => setStep(AGENT_ARC_WIZARD_STEPS[target - 1]! as Step)}
|
||||
onJumpToStep={(target) => navigateToStep(AGENT_ARC_WIZARD_STEPS[target - 1]! as Step, "step_indicator")}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -3412,10 +3568,15 @@ function OnboardingWizardInner({
|
||||
</div>
|
||||
)}
|
||||
{mobileDesktopHandoffAvailable && createdCompanyId && desktopOnboardingDestination && (
|
||||
<MobileDesktopNudge key={createdCompanyId} destination={desktopOnboardingDestination} onDismiss={() => {
|
||||
setDesktopNudgeDismissedFor(createdCompanyId);
|
||||
modelSourceContainer.current?.querySelector<HTMLElement>('[role="radio"]')?.focus();
|
||||
}} />
|
||||
<MobileDesktopNudge
|
||||
key={createdCompanyId}
|
||||
destination={desktopOnboardingDestination}
|
||||
companyId={createdCompanyId}
|
||||
onDismiss={() => {
|
||||
setDesktopNudgeDismissedFor(createdCompanyId);
|
||||
modelSourceContainer.current?.querySelector<HTMLElement>('[role="radio"]')?.focus();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<div ref={modelSourceContainer}>
|
||||
<ModelSourceTiles
|
||||
@@ -3436,6 +3597,12 @@ function OnboardingWizardInner({
|
||||
settling={connectPhase === "unwindRow"}
|
||||
onSelect={(id) => {
|
||||
if (connectPhase !== "idle" && connectPhase !== "unwindRow") return;
|
||||
captureOnboardingModelSourceSelected({
|
||||
adapterType: id,
|
||||
provider: aiProviderForAdapter(id) ?? id,
|
||||
credentialMode: credentialMode === "api" ? "api_key" : "subscription",
|
||||
companyId: createdCompanyId,
|
||||
});
|
||||
autoConnectStartedRef.current = false;
|
||||
setSourcePicked(true);
|
||||
setAdapterType(id);
|
||||
@@ -3481,7 +3648,20 @@ function OnboardingWizardInner({
|
||||
transition={{ opacity: SOURCE_LINK_EXIT, height: MAKE_ROOM }}
|
||||
>
|
||||
<div className="-ml-3 mt-1">
|
||||
<CredentialModeLink mode={credentialMode} onChange={setCredentialMode} />
|
||||
<CredentialModeLink
|
||||
mode={credentialMode}
|
||||
onChange={(nextMode) => {
|
||||
if (nextMode !== credentialMode) {
|
||||
captureOnboardingCredentialModeSwitched({
|
||||
fromMode: credentialMode === "api" ? "api_key" : "subscription",
|
||||
toMode: nextMode === "api" ? "api_key" : "subscription",
|
||||
adapterType: sourcePicked ? adapterType : undefined,
|
||||
companyId: createdCompanyId,
|
||||
});
|
||||
}
|
||||
setCredentialMode(nextMode);
|
||||
}}
|
||||
/>
|
||||
{savedKeys.options.length > 0 && <p className="px-3 text-sm text-muted-foreground">{savedKeys.options.length} saved API {savedKeys.options.length === 1 ? "key available" : "keys available"}.</p>}
|
||||
{credentialMode === "subscription" && authSignalStatus === "present" && <p className="px-3 text-sm text-muted-foreground">An existing provider connection is available.</p>}
|
||||
</div>
|
||||
@@ -3623,6 +3803,15 @@ function OnboardingWizardInner({
|
||||
active={connectCardLive}
|
||||
onPromptReady={(url) => {
|
||||
if (!connectCardLive) return;
|
||||
if (url && url !== connectAuthUrl) {
|
||||
captureOnboardingOAuthProgress({
|
||||
stage: "started",
|
||||
provider: managedProvider ?? adapterType,
|
||||
adapterType,
|
||||
phase: connectPhase,
|
||||
companyId: createdCompanyId,
|
||||
});
|
||||
}
|
||||
setConnectAuthUrl(url);
|
||||
// The prompt arriving is what ends the waiting beat.
|
||||
if (url) setConnectPhase((p) => (p === "loading" ? "ready" : p));
|
||||
@@ -3633,6 +3822,13 @@ function OnboardingWizardInner({
|
||||
}}
|
||||
onSubmitReady={submit => setSubmitLoginCode(() => submit)}
|
||||
onCodeSubmitted={() => {
|
||||
captureOnboardingOAuthProgress({
|
||||
stage: "code_submitted",
|
||||
provider: managedProvider ?? adapterType,
|
||||
adapterType,
|
||||
phase: connectPhase,
|
||||
companyId: createdCompanyId,
|
||||
});
|
||||
// The button reacts to the paste, not to the server.
|
||||
// Waiting for the login to be stored left about a
|
||||
// second of a button still reading "Waiting for code"
|
||||
@@ -3663,11 +3859,20 @@ function OnboardingWizardInner({
|
||||
captureOnboardingStepFailed({
|
||||
step: "connect_model",
|
||||
reason: "subscription_login_failed",
|
||||
companyId: createdCompanyId,
|
||||
provider: managedProvider ?? adapterType,
|
||||
adapterType,
|
||||
method: "subscription",
|
||||
});
|
||||
}}
|
||||
onConnected={(sessionId) => {
|
||||
captureOnboardingOAuthProgress({
|
||||
stage: "connected",
|
||||
provider: managedProvider ?? adapterType,
|
||||
adapterType,
|
||||
phase: connectPhase,
|
||||
companyId: createdCompanyId,
|
||||
});
|
||||
if (managedSubscriptionProvider) managedSubscriptionRef.current = { companyId: createdCompanyId, binding: { provider: managedSubscriptionProvider, method: "subscription", mode: "responsible_user" }, sessionId };
|
||||
setConnectAuthUrl(null);
|
||||
// Not into a card the customer has left. The panel is
|
||||
@@ -3714,17 +3919,44 @@ function OnboardingWizardInner({
|
||||
{...localLoginPrimary.instructionsProps}
|
||||
authorizationOpened={Boolean(openedClaudeSessionId && openedClaudeSessionId === localLogin.sessionId)}
|
||||
onOpenAuthorization={adapterType === "claude_local" ? (address) => {
|
||||
captureOnboardingOAuthProgress({
|
||||
stage: "auth_link_opened",
|
||||
provider: managedProvider ?? adapterType,
|
||||
adapterType,
|
||||
companyId: createdCompanyId,
|
||||
});
|
||||
setOpenedClaudeSessionId(localLogin.sessionId ?? null);
|
||||
window.open(address, "_blank", "noopener,noreferrer");
|
||||
} : undefined}
|
||||
login={{ ...localLogin, retry: () => { prepareLocalLoginRetry(); localLogin.retry(); } }}
|
||||
login={{
|
||||
...localLogin,
|
||||
retry: () => {
|
||||
captureOnboardingOAuthProgress({
|
||||
stage: "retried",
|
||||
provider: managedProvider ?? adapterType,
|
||||
adapterType,
|
||||
companyId: createdCompanyId,
|
||||
});
|
||||
prepareLocalLoginRetry();
|
||||
localLogin.retry();
|
||||
},
|
||||
}}
|
||||
/>
|
||||
) : browserSignInUnavailable ? <p role="status" className="text-xs text-muted-foreground">This environment does not support browser sign-in. Go back to use an API key or choose another model.</p> : null
|
||||
) : null}
|
||||
</OnboardingSignInRetry.Provider>
|
||||
</OnboardingSignInMark.Provider>
|
||||
{showAdvancedSetup && (
|
||||
<details className="mt-2 space-y-3">
|
||||
<details
|
||||
className="mt-2 space-y-3"
|
||||
onToggle={(event) => {
|
||||
captureOnboardingAdvancedToggled({
|
||||
adapterType,
|
||||
open: event.currentTarget.open,
|
||||
companyId: createdCompanyId,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<summary className="cursor-pointer text-sm text-muted-foreground">Advanced</summary>
|
||||
<OnboardingGatewaySetup
|
||||
companyId={createdCompanyId} agentId={setupAgentId ?? undefined} environmentId={resolvedLoginEnvironmentId ?? undefined}
|
||||
@@ -3925,7 +4157,7 @@ function OnboardingWizardInner({
|
||||
step === 4 && connectPhase !== "idle"
|
||||
? unwindConnectStep
|
||||
: canGoBackFromOnboardingStep({ currentStep: step, entryStep })
|
||||
? () => setStep(backStepFrom(step))
|
||||
? () => navigateToStep(backStepFrom(step), "back_button")
|
||||
: undefined
|
||||
}
|
||||
// The prototype's cloud flow hires on this step and calls the
|
||||
@@ -3971,8 +4203,11 @@ function OnboardingWizardInner({
|
||||
: loading || launchStateIncomplete
|
||||
}
|
||||
onPrimary={() => {
|
||||
if (step === 1) void handleCreateCompany();
|
||||
else if (step === 3) {
|
||||
if (step === 1) {
|
||||
captureOnboardingStepSubmitted({ step: "name_org", via: "button", companyId: createdCompanyId });
|
||||
void handleCreateCompany();
|
||||
} else if (step === 3) {
|
||||
captureOnboardingStepSubmitted({ step: "create_agent", via: "button", companyId: createdCompanyId });
|
||||
if (isFreeInferenceOnboarding) {
|
||||
void handleStartWithCloudTrial({ launchToChat: true });
|
||||
} else {
|
||||
@@ -3982,8 +4217,10 @@ function OnboardingWizardInner({
|
||||
// One button, two jobs — start the sign-in, or hire — and
|
||||
// Cmd+Enter has to do the same thing. See
|
||||
// `handleConnectStepPrimary`.
|
||||
else if (step === 4) handleConnectStepPrimary();
|
||||
else handleLaunchToChat();
|
||||
else if (step === 4) {
|
||||
captureOnboardingStepSubmitted({ step: "connect_model", via: "button", companyId: createdCompanyId });
|
||||
handleConnectStepPrimary();
|
||||
} else handleLaunchToChat();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useId, useRef, useState, useSyncExternalStore } from "react"
|
||||
import { Check, Copy, Monitor } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { captureOnboardingMobileHandoffAction } from "@/lib/analytics/onboarding-analytics";
|
||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||
|
||||
const DESKTOP_WIDTH = "(min-width: 40rem)";
|
||||
@@ -20,7 +21,15 @@ export function useMobileOnboardingViewport() {
|
||||
);
|
||||
}
|
||||
|
||||
export function MobileDesktopNudge({ destination, onDismiss }: { destination: string; onDismiss: () => void }) {
|
||||
export function MobileDesktopNudge({
|
||||
destination,
|
||||
companyId,
|
||||
onDismiss,
|
||||
}: {
|
||||
destination: string;
|
||||
companyId?: string | null;
|
||||
onDismiss: () => void;
|
||||
}) {
|
||||
const headingId = useId();
|
||||
const handoffId = useId();
|
||||
const linkId = useId();
|
||||
@@ -29,6 +38,10 @@ export function MobileDesktopNudge({ destination, onDismiss }: { destination: st
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [copyState, setCopyState] = useState<"idle" | "copied" | "manual">("idle");
|
||||
|
||||
useEffect(() => {
|
||||
captureOnboardingMobileHandoffAction({ action: "shown", companyId });
|
||||
}, [companyId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (expanded) handoffRef.current?.scrollIntoView({ block: "nearest" });
|
||||
}, [expanded]);
|
||||
@@ -37,8 +50,10 @@ export function MobileDesktopNudge({ destination, onDismiss }: { destination: st
|
||||
try {
|
||||
await copyTextToClipboard(destination);
|
||||
setCopyState("copied");
|
||||
captureOnboardingMobileHandoffAction({ action: "copy_link", companyId });
|
||||
} catch {
|
||||
setCopyState("manual");
|
||||
captureOnboardingMobileHandoffAction({ action: "copy_link_manual", companyId });
|
||||
linkRef.current?.focus();
|
||||
linkRef.current?.select();
|
||||
}
|
||||
@@ -54,10 +69,31 @@ export function MobileDesktopNudge({ destination, onDismiss }: { destination: st
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
<Button type="button" variant="outline" className="h-(--sz-44px) px-2" aria-controls={handoffId} aria-expanded={expanded} onClick={() => setExpanded((open) => !open)}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-(--sz-44px) px-2"
|
||||
aria-controls={handoffId}
|
||||
aria-expanded={expanded}
|
||||
onClick={() => {
|
||||
const next = !expanded;
|
||||
setExpanded(next);
|
||||
if (next) captureOnboardingMobileHandoffAction({ action: "expanded", companyId });
|
||||
}}
|
||||
>
|
||||
Continue on desktop
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" className="h-(--sz-44px) px-2" onClick={onDismiss}>Keep going here</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="h-(--sz-44px) px-2"
|
||||
onClick={() => {
|
||||
captureOnboardingMobileHandoffAction({ action: "dismissed", companyId });
|
||||
onDismiss();
|
||||
}}
|
||||
>
|
||||
Keep going here
|
||||
</Button>
|
||||
</div>
|
||||
<div id={handoffId} ref={handoffRef} hidden={!expanded}>
|
||||
{expanded && (
|
||||
|
||||
@@ -3,6 +3,11 @@ import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
resetOnboardingTelemetryForTest,
|
||||
setOnboardingTelemetrySenderForTest,
|
||||
type OnboardingTelemetryEventInput,
|
||||
} from "@/lib/analytics/onboarding-analytics";
|
||||
import { resetOnboardingOffers } from "@/lib/onboarding-auto-open";
|
||||
import { ONBOARDING_AGENT_STEP } from "@/lib/onboarding-route";
|
||||
import { useAgentlessOnboardingAutoOpen } from "./useAgentlessOnboardingAutoOpen";
|
||||
@@ -33,23 +38,40 @@ async function mount() {
|
||||
};
|
||||
}
|
||||
|
||||
let sentEvents: OnboardingTelemetryEventInput[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
resetOnboardingOffers();
|
||||
sentEvents = [];
|
||||
setOnboardingTelemetrySenderForTest((event) => sentEvents.push(event));
|
||||
localStorage.clear();
|
||||
});
|
||||
afterEach(() => resetOnboardingOffers());
|
||||
afterEach(() => {
|
||||
resetOnboardingOffers();
|
||||
resetOnboardingTelemetryForTest();
|
||||
});
|
||||
|
||||
describe("useAgentlessOnboardingAutoOpen", () => {
|
||||
it("offers onboarding once for a company with no agent, from whichever page is home", async () => {
|
||||
fixture.agents.mockResolvedValue([]);
|
||||
let unmount = await mount();
|
||||
expect(fixture.openOnboarding).toHaveBeenCalledExactlyOnceWith({ companyId: "company-1", initialStep: ONBOARDING_AGENT_STEP });
|
||||
expect(sentEvents).toEqual([
|
||||
expect.objectContaining({
|
||||
event: "onboarding_workspace_loaded",
|
||||
hasCompany: true,
|
||||
hasAgent: false,
|
||||
willAutoOpen: true,
|
||||
}),
|
||||
]);
|
||||
await unmount();
|
||||
|
||||
// Coming back to the home page does not reopen a wizard that was closed.
|
||||
// Coming back to the home page does not reopen a wizard that was closed,
|
||||
// and does not re-emit a false willAutoOpen: true event.
|
||||
unmount = await mount();
|
||||
expect(fixture.openOnboarding).toHaveBeenCalledOnce();
|
||||
expect(sentEvents).toHaveLength(1);
|
||||
await unmount();
|
||||
});
|
||||
|
||||
@@ -57,6 +79,15 @@ describe("useAgentlessOnboardingAutoOpen", () => {
|
||||
fixture.agents.mockResolvedValue([{ id: "agent-1", companyId: "company-1", status: "idle", pauseReason: null }]);
|
||||
const unmount = await mount();
|
||||
expect(fixture.openOnboarding).not.toHaveBeenCalled();
|
||||
expect(sentEvents).toEqual([
|
||||
expect.objectContaining({
|
||||
event: "onboarding_workspace_loaded",
|
||||
hasCompany: true,
|
||||
hasAgent: true,
|
||||
willAutoOpen: false,
|
||||
skipReason: "has_agent",
|
||||
}),
|
||||
]);
|
||||
await unmount();
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,13 @@ import { useLocation } from "@/lib/router";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { useCompany } from "@/context/CompanyContext";
|
||||
import { useDialogActions } from "@/context/DialogContext";
|
||||
import { claimOnboardingOffer, dashboardOnboardingOptions } from "@/lib/onboarding-auto-open";
|
||||
import { captureOnboardingWorkspaceLoaded } from "@/lib/analytics/onboarding-analytics";
|
||||
import {
|
||||
claimOnboardingOffer,
|
||||
claimOnboardingWorkspaceReport,
|
||||
dashboardOnboardingOptions,
|
||||
hasClaimedOnboardingOffer,
|
||||
} from "@/lib/onboarding-auto-open";
|
||||
import { shouldRouteAgentlessCompanyToOnboarding } from "@/lib/onboarding-route";
|
||||
import { onboardingDraftStorage } from "@/lib/onboarding-state";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
@@ -52,13 +58,47 @@ export function useAgentlessOnboardingAutoOpen() {
|
||||
agentCount: onboardingOptions ? 0 : agents?.length ?? 0,
|
||||
});
|
||||
|
||||
// Auto-open once per company. Every input sits behind a query, so a refetch
|
||||
// re-runs this, and the customer can navigate away and back; both would
|
||||
// otherwise reopen a wizard that was deliberately closed.
|
||||
// `claimOnboardingOffer` holds the companies already offered.
|
||||
// Auto-open once per company and report workspace arrival with the exact
|
||||
// same lifetime as `claimOnboardingOffer` so remounts never falsely report
|
||||
// `willAutoOpen: true` after the offer was already claimed.
|
||||
useEffect(() => {
|
||||
if (!shouldOpenOnboarding || !selectedCompanyId || !onboardingInitialStep) return;
|
||||
if (!claimOnboardingOffer(selectedCompanyId)) return;
|
||||
openOnboarding({ companyId: selectedCompanyId, initialStep: onboardingInitialStep });
|
||||
}, [shouldOpenOnboarding, selectedCompanyId, onboardingInitialStep, openOnboarding]);
|
||||
if (!selectedCompanyId || agents === undefined || agentsRefreshing) return;
|
||||
const alreadyOffered = hasClaimedOnboardingOffer(selectedCompanyId);
|
||||
const canOpen = Boolean(shouldOpenOnboarding && onboardingInitialStep);
|
||||
const willAutoOpen = canOpen && !alreadyOffered && claimOnboardingOffer(selectedCompanyId);
|
||||
if (claimOnboardingWorkspaceReport(selectedCompanyId)) {
|
||||
const hasAgent = !onboardingOptions && agents.length > 0;
|
||||
const isMobile =
|
||||
typeof window !== "undefined" && typeof window.matchMedia === "function"
|
||||
? window.matchMedia("(min-width: 40rem)").matches === false
|
||||
: undefined;
|
||||
captureOnboardingWorkspaceLoaded({
|
||||
companyId: selectedCompanyId,
|
||||
hasCompany: true,
|
||||
hasAgent,
|
||||
willAutoOpen,
|
||||
...(!willAutoOpen
|
||||
? {
|
||||
skipReason: canOpen && alreadyOffered
|
||||
? "already_offered"
|
||||
: hasAgent
|
||||
? "has_agent"
|
||||
: "not_home_route",
|
||||
}
|
||||
: {}),
|
||||
...(typeof isMobile === "boolean" ? { isMobile } : {}),
|
||||
});
|
||||
}
|
||||
if (willAutoOpen && onboardingInitialStep) {
|
||||
openOnboarding({ companyId: selectedCompanyId, initialStep: onboardingInitialStep });
|
||||
}
|
||||
}, [
|
||||
selectedCompanyId,
|
||||
agents,
|
||||
agentsRefreshing,
|
||||
onboardingOptions,
|
||||
shouldOpenOnboarding,
|
||||
onboardingInitialStep,
|
||||
openOnboarding,
|
||||
]);
|
||||
}
|
||||
@@ -3,7 +3,12 @@
|
||||
import { act, createElement } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { ADAPTER_AUTH_MISSING_CHECK_CODE, type BrowserAnalyticsConfig } from "@paperclipai/shared";
|
||||
import {
|
||||
ADAPTER_AUTH_MISSING_CHECK_CODE,
|
||||
onboardingTelemetryEventSchema,
|
||||
type BrowserAnalyticsConfig,
|
||||
type OnboardingTelemetryEventInput,
|
||||
} from "@paperclipai/shared";
|
||||
import { blocksAgentCreate } from "@/lib/onboarding-connection-test";
|
||||
import { isReportableAdapterLoginFailure } from "@/components/AgentConfigForm";
|
||||
import {
|
||||
@@ -15,9 +20,23 @@ import {
|
||||
} from "./product-analytics";
|
||||
import {
|
||||
captureAgentChatMessageSent,
|
||||
captureOnboardingAdvancedToggled,
|
||||
captureOnboardingApiKeySubmitted,
|
||||
captureOnboardingCredentialModeSwitched,
|
||||
captureOnboardingLaunchClicked,
|
||||
captureOnboardingMobileHandoffAction,
|
||||
captureOnboardingModelSourceSelected,
|
||||
captureOnboardingOAuthProgress,
|
||||
captureOnboardingStepCompleted,
|
||||
captureOnboardingStepFailed,
|
||||
captureOnboardingStepNavigated,
|
||||
captureOnboardingStepSubmitted,
|
||||
captureOnboardingTrialCtaClicked,
|
||||
captureOnboardingWorkspaceLoaded,
|
||||
resetOnboardingTelemetryForTest,
|
||||
setOnboardingTelemetrySenderForTest,
|
||||
useOnboardingAnalytics,
|
||||
type OnboardingAnalyticsOutcome,
|
||||
} from "./onboarding-analytics";
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
@@ -75,39 +94,54 @@ async function flush() {
|
||||
|
||||
let client: ReturnType<typeof mockClient>;
|
||||
let scheduled: (() => void) | null;
|
||||
let sentServerEvents: OnboardingTelemetryEventInput[];
|
||||
const load = () => Promise.resolve(client as unknown as ProductAnalyticsClient);
|
||||
const schedule = (start: () => void) => {
|
||||
scheduled = start;
|
||||
return () => { scheduled = null; };
|
||||
};
|
||||
|
||||
async function startAnalytics() {
|
||||
startProductAnalytics(config, { load, schedule });
|
||||
scheduled?.();
|
||||
await flush();
|
||||
}
|
||||
|
||||
function captured() {
|
||||
function capturedBrowser() {
|
||||
return client.capture.mock.calls.map(([event, properties]) => [event, properties]);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
client = mockClient();
|
||||
scheduled = null;
|
||||
sentServerEvents = [];
|
||||
setOnboardingTelemetrySenderForTest((payload) => {
|
||||
// Every payload emitted by the UI must pass the server's strict Zod contract.
|
||||
sentServerEvents.push(onboardingTelemetryEventSchema.parse(payload));
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const unmount of unmounts.splice(0)) unmount();
|
||||
resetProductAnalyticsForTest();
|
||||
resetOnboardingTelemetryForTest();
|
||||
});
|
||||
|
||||
describe("browser product events", () => {
|
||||
it("captures nothing when browser analytics is off", async () => {
|
||||
captureProductAnalyticsEvent("onboarding_opened", { step: "create_agent" });
|
||||
captureProductAnalyticsEvent("ui_interaction", { surface: "test" });
|
||||
await flush();
|
||||
expect(client.capture).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("holds events captured before startProductAnalytics and flushes them once posthog-js loads", async () => {
|
||||
captureProductAnalyticsEvent("early_event", { step: "create_agent" });
|
||||
startProductAnalytics(config, { load, schedule });
|
||||
expect(client.capture).not.toHaveBeenCalled();
|
||||
scheduled!();
|
||||
await flush();
|
||||
expect(client.capture).toHaveBeenCalledTimes(1);
|
||||
expect(client.capture).toHaveBeenCalledWith(
|
||||
"early_event",
|
||||
{ step: "create_agent" },
|
||||
{ timestamp: expect.any(Date) },
|
||||
);
|
||||
});
|
||||
|
||||
it("holds events from before posthog-js loads and sends them with their own time", async () => {
|
||||
startProductAnalytics(config, { load, schedule });
|
||||
captureProductAnalyticsEvent("onboarding_opened", { step: "create_agent" });
|
||||
@@ -131,7 +165,7 @@ describe("browser product events", () => {
|
||||
scheduled!();
|
||||
await flush();
|
||||
expect(client.capture).toHaveBeenCalledTimes(50);
|
||||
expect(captured()).not.toContainEqual(["onboarding_step_viewed", { step: "review" }]);
|
||||
expect(capturedBrowser()).not.toContainEqual(["onboarding_step_viewed", { step: "review" }]);
|
||||
});
|
||||
|
||||
it("drops held events on a person change before posthog-js loads", async () => {
|
||||
@@ -143,7 +177,7 @@ describe("browser product events", () => {
|
||||
captureProductAnalyticsEvent("onboarding_opened", { step: "connect_model" });
|
||||
scheduled!();
|
||||
await flush();
|
||||
expect(captured()).toEqual([["onboarding_opened", { step: "connect_model" }]]);
|
||||
expect(capturedBrowser()).toEqual([["onboarding_opened", { step: "connect_model" }]]);
|
||||
expect(client.identify).toHaveBeenCalledWith("user-2", {});
|
||||
});
|
||||
|
||||
@@ -154,23 +188,23 @@ describe("browser product events", () => {
|
||||
setProductAnalyticsUser({ id: "user-1", email: "jane@example.com", name: null });
|
||||
scheduled!();
|
||||
await flush();
|
||||
expect(captured()).toEqual([["onboarding_opened", { step: "create_agent" }]]);
|
||||
expect(capturedBrowser()).toEqual([["onboarding_opened", { step: "create_agent" }]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("onboarding funnel events", () => {
|
||||
describe("server-side onboarding funnel events", () => {
|
||||
function renderWizard(initial: { open: boolean; step: number }) {
|
||||
return renderHook(
|
||||
(props: { open: boolean; step: number; connectOutcome: "subscription" | "api_key" }) => useOnboardingAnalytics(props),
|
||||
{ initialProps: { ...initial, connectOutcome: "subscription" as "subscription" | "api_key" } },
|
||||
(props: { open: boolean; step: number; connectOutcome: OnboardingAnalyticsOutcome }) =>
|
||||
useOnboardingAnalytics(props),
|
||||
{ initialProps: { ...initial, connectOutcome: "subscription" as OnboardingAnalyticsOutcome } },
|
||||
);
|
||||
}
|
||||
|
||||
it("captures each transition once through the wizard", async () => {
|
||||
await startAnalytics();
|
||||
it("sends each wizard transition server-side (never via posthog-js), including Step 1 name_org -> Step 3 create_agent", () => {
|
||||
const wizard = renderWizard({ open: false, step: 1 });
|
||||
wizard.rerender({ open: true, step: 1, connectOutcome: "subscription" });
|
||||
act(() => wizard.result.current.opened(3, 1));
|
||||
act(() => wizard.result.current.opened(1, 1, { source: "manual", isMobile: false }));
|
||||
wizard.rerender({ open: true, step: 3, connectOutcome: "subscription" });
|
||||
wizard.rerender({ open: true, step: 3, connectOutcome: "subscription" });
|
||||
wizard.rerender({ open: true, step: 4, connectOutcome: "subscription" });
|
||||
@@ -181,33 +215,34 @@ describe("onboarding funnel events", () => {
|
||||
act(() => wizard.result.current.finished());
|
||||
wizard.rerender({ open: false, step: 1, connectOutcome: "subscription" });
|
||||
|
||||
expect(captured()).toEqual([
|
||||
["onboarding_opened", { step: "create_agent" }],
|
||||
["onboarding_step_viewed", { step: "create_agent" }],
|
||||
["onboarding_step_completed", { step: "create_agent" }],
|
||||
["onboarding_step_viewed", { step: "connect_model" }],
|
||||
["onboarding_step_completed", { step: "connect_model", outcome: "api_key" }],
|
||||
["onboarding_step_viewed", { step: "review" }],
|
||||
["onboarding_step_completed", { step: "review" }],
|
||||
["onboarding_step_completed", { step: "launch", outcome: "succeeded" }],
|
||||
expect(client.capture).not.toHaveBeenCalled();
|
||||
expect(sentServerEvents).toEqual([
|
||||
{ event: "onboarding_opened", step: "name_org", source: "manual", isMobile: false },
|
||||
{ event: "onboarding_step_viewed", step: "name_org" },
|
||||
{ event: "onboarding_step_completed", step: "name_org" },
|
||||
{ event: "onboarding_step_viewed", step: "create_agent" },
|
||||
{ event: "onboarding_step_completed", step: "create_agent" },
|
||||
{ event: "onboarding_step_viewed", step: "connect_model" },
|
||||
{ event: "onboarding_step_completed", step: "connect_model", outcome: "api_key" },
|
||||
{ event: "onboarding_step_viewed", step: "review" },
|
||||
{ event: "onboarding_step_completed", step: "review" },
|
||||
{ event: "onboarding_step_completed", step: "launch", outcome: "succeeded" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not count a stale step from the opening render as a view", async () => {
|
||||
await startAnalytics();
|
||||
it("does not count a stale step from the opening render as a view", () => {
|
||||
const wizard = renderWizard({ open: true, step: 5 });
|
||||
act(() => wizard.result.current.opened(3, 5));
|
||||
wizard.rerender({ open: true, step: 5, connectOutcome: "subscription" });
|
||||
wizard.rerender({ open: true, step: 3, connectOutcome: "subscription" });
|
||||
|
||||
expect(captured()).toEqual([
|
||||
["onboarding_opened", { step: "create_agent" }],
|
||||
["onboarding_step_viewed", { step: "create_agent" }],
|
||||
expect(sentServerEvents).toEqual([
|
||||
{ event: "onboarding_opened", step: "create_agent" },
|
||||
{ event: "onboarding_step_viewed", step: "create_agent" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("captures a dismissal once and a reopen as a new session", async () => {
|
||||
await startAnalytics();
|
||||
it("captures a dismissal once and a reopen as a new session", () => {
|
||||
const wizard = renderWizard({ open: true, step: 4 });
|
||||
act(() => wizard.result.current.opened(4, 4));
|
||||
act(() => wizard.result.current.opened(4, 4));
|
||||
@@ -217,54 +252,32 @@ describe("onboarding funnel events", () => {
|
||||
wizard.rerender({ open: true, step: 1, connectOutcome: "subscription" });
|
||||
act(() => wizard.result.current.opened(3, 1));
|
||||
|
||||
expect(captured()).toEqual([
|
||||
["onboarding_opened", { step: "connect_model" }],
|
||||
["onboarding_step_viewed", { step: "connect_model" }],
|
||||
["onboarding_dismissed", { step: "connect_model" }],
|
||||
["onboarding_opened", { step: "create_agent" }],
|
||||
["onboarding_step_viewed", { step: "create_agent" }],
|
||||
expect(sentServerEvents).toEqual([
|
||||
{ event: "onboarding_opened", step: "connect_model" },
|
||||
{ event: "onboarding_step_viewed", step: "connect_model" },
|
||||
{ event: "onboarding_dismissed", step: "connect_model", method: "close_button" },
|
||||
{ event: "onboarding_opened", step: "create_agent" },
|
||||
{ event: "onboarding_step_viewed", step: "create_agent" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("captures a dismissal when the wizard closes before launch", async () => {
|
||||
await startAnalytics();
|
||||
it("captures a dismissal when the wizard closes before launch", () => {
|
||||
const wizard = renderWizard({ open: true, step: 3 });
|
||||
act(() => wizard.result.current.opened(3, 3));
|
||||
wizard.rerender({ open: true, step: 4, connectOutcome: "subscription" });
|
||||
wizard.rerender({ open: false, step: 1, connectOutcome: "subscription" });
|
||||
wizard.rerender({ open: false, step: 1, connectOutcome: "subscription" });
|
||||
|
||||
expect(captured()).toEqual([
|
||||
["onboarding_opened", { step: "create_agent" }],
|
||||
["onboarding_step_viewed", { step: "create_agent" }],
|
||||
["onboarding_step_completed", { step: "create_agent" }],
|
||||
["onboarding_step_viewed", { step: "connect_model" }],
|
||||
["onboarding_dismissed", { step: "connect_model" }],
|
||||
expect(sentServerEvents).toEqual([
|
||||
{ event: "onboarding_opened", step: "create_agent" },
|
||||
{ event: "onboarding_step_viewed", step: "create_agent" },
|
||||
{ event: "onboarding_step_completed", step: "create_agent" },
|
||||
{ event: "onboarding_step_viewed", step: "connect_model" },
|
||||
{ event: "onboarding_dismissed", step: "connect_model", method: "unmount" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("sends queued wizard events once posthog-js loads without reopening the wizard", async () => {
|
||||
startProductAnalytics(config, { load, schedule });
|
||||
const wizard = renderWizard({ open: true, step: 3 });
|
||||
act(() => wizard.result.current.opened(3, 3));
|
||||
wizard.rerender({ open: true, step: 4, connectOutcome: "subscription" });
|
||||
act(() => wizard.result.current.dismissed(4));
|
||||
expect(client.capture).not.toHaveBeenCalled();
|
||||
expect(client.init).not.toHaveBeenCalled();
|
||||
|
||||
scheduled!();
|
||||
await flush();
|
||||
expect(captured()).toEqual([
|
||||
["onboarding_opened", { step: "create_agent" }],
|
||||
["onboarding_step_viewed", { step: "create_agent" }],
|
||||
["onboarding_step_completed", { step: "create_agent" }],
|
||||
["onboarding_step_viewed", { step: "connect_model" }],
|
||||
["onboarding_dismissed", { step: "connect_model" }],
|
||||
]);
|
||||
});
|
||||
|
||||
it("captures structured onboarding failures and drops unsafe provider strings", async () => {
|
||||
await startAnalytics();
|
||||
it("captures structured onboarding failures and drops unsafe provider strings", () => {
|
||||
captureOnboardingStepFailed({
|
||||
step: "connect_model",
|
||||
reason: "api_key_save_failed",
|
||||
@@ -281,20 +294,81 @@ describe("onboarding funnel events", () => {
|
||||
step: "launch",
|
||||
reason: "greeting_failed",
|
||||
});
|
||||
expect(captured()).toEqual([
|
||||
["onboarding_step_failed", { step: "connect_model", reason: "api_key_save_failed", provider: "anthropic", method: "api_key" }],
|
||||
["onboarding_step_failed", { step: "connect_model", reason: "subscription_login_failed", method: "subscription" }],
|
||||
["onboarding_step_failed", { step: "launch", reason: "greeting_failed" }],
|
||||
expect(sentServerEvents).toEqual([
|
||||
{ event: "onboarding_step_failed", step: "connect_model", reason: "api_key_save_failed", provider: "anthropic", method: "api_key" },
|
||||
{ event: "onboarding_step_failed", step: "connect_model", reason: "subscription_login_failed", method: "subscription" },
|
||||
{ event: "onboarding_step_failed", step: "launch", reason: "greeting_failed" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("captures agent chat messages with onboarding_chat vs agent_chat surface only", async () => {
|
||||
await startAnalytics();
|
||||
captureAgentChatMessageSent("onboarding_chat");
|
||||
it("captures granular onboarding interaction events matching the server schema", () => {
|
||||
const companyId = "11111111-1111-4111-8111-111111111111";
|
||||
captureOnboardingWorkspaceLoaded({
|
||||
companyId,
|
||||
hasCompany: true,
|
||||
hasAgent: false,
|
||||
willAutoOpen: true,
|
||||
isMobile: false,
|
||||
});
|
||||
captureOnboardingStepSubmitted({ step: "create_agent", via: "button", companyId });
|
||||
captureOnboardingStepNavigated({
|
||||
fromStep: "connect_model",
|
||||
toStep: "create_agent",
|
||||
direction: "back",
|
||||
via: "back_button",
|
||||
companyId,
|
||||
});
|
||||
captureOnboardingMobileHandoffAction({ action: "copy_link", companyId });
|
||||
captureOnboardingTrialCtaClicked({ companyId });
|
||||
captureOnboardingModelSourceSelected({
|
||||
adapterType: "claude_local",
|
||||
provider: "anthropic",
|
||||
credentialMode: "subscription",
|
||||
companyId,
|
||||
});
|
||||
captureOnboardingCredentialModeSwitched({
|
||||
fromMode: "subscription",
|
||||
toMode: "api_key",
|
||||
adapterType: "claude_local",
|
||||
companyId,
|
||||
});
|
||||
captureOnboardingOAuthProgress({
|
||||
stage: "auth_link_opened",
|
||||
provider: "anthropic",
|
||||
adapterType: "claude_local",
|
||||
phase: "ready",
|
||||
companyId,
|
||||
});
|
||||
captureOnboardingApiKeySubmitted({
|
||||
provider: "anthropic",
|
||||
adapterType: "claude_local",
|
||||
usedSavedKey: false,
|
||||
companyId,
|
||||
});
|
||||
captureOnboardingAdvancedToggled({ adapterType: "claude_local", open: true, companyId });
|
||||
captureOnboardingLaunchClicked({
|
||||
adapterType: "claude_local",
|
||||
provider: "anthropic",
|
||||
outcome: "subscription",
|
||||
companyId,
|
||||
});
|
||||
captureAgentChatMessageSent("onboarding_chat", { companyId });
|
||||
captureAgentChatMessageSent("agent_chat");
|
||||
expect(captured()).toEqual([
|
||||
["agent_chat_message_sent", { surface: "onboarding_chat" }],
|
||||
["agent_chat_message_sent", { surface: "agent_chat" }],
|
||||
|
||||
expect(sentServerEvents.map((e) => e.event)).toEqual([
|
||||
"onboarding_workspace_loaded",
|
||||
"onboarding_step_submitted",
|
||||
"onboarding_step_navigated",
|
||||
"onboarding_mobile_handoff_action",
|
||||
"onboarding_trial_cta_clicked",
|
||||
"onboarding_model_source_selected",
|
||||
"onboarding_credential_mode_switched",
|
||||
"onboarding_oauth_progress",
|
||||
"onboarding_api_key_submitted",
|
||||
"onboarding_advanced_toggled",
|
||||
"onboarding_launch_clicked",
|
||||
"agent_chat_message_sent",
|
||||
"agent_chat_message_sent",
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,93 +1,460 @@
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import {
|
||||
ONBOARDING_TELEMETRY_EVENTS,
|
||||
onboardingTelemetryEventToPostHogProperties,
|
||||
type AgentChatSurface,
|
||||
type OnboardingAnalyticsOutcome,
|
||||
type OnboardingAnalyticsStep,
|
||||
type OnboardingCredentialMode,
|
||||
type OnboardingDismissMethod,
|
||||
type OnboardingFailureReason,
|
||||
type OnboardingMobileHandoffAction,
|
||||
type OnboardingOAuthStage,
|
||||
type OnboardingOpenSource,
|
||||
type OnboardingTelemetryEventInput,
|
||||
type OnboardingWorkspaceSkipReason,
|
||||
} from "@paperclipai/shared";
|
||||
import { captureProductAnalyticsEvent } from "./product-analytics";
|
||||
|
||||
export const ONBOARDING_ANALYTICS_EVENTS = {
|
||||
opened: "onboarding_opened",
|
||||
stepViewed: "onboarding_step_viewed",
|
||||
stepCompleted: "onboarding_step_completed",
|
||||
stepFailed: "onboarding_step_failed",
|
||||
dismissed: "onboarding_dismissed",
|
||||
chatMessageSent: "agent_chat_message_sent",
|
||||
} as const;
|
||||
export const ONBOARDING_ANALYTICS_EVENTS = ONBOARDING_TELEMETRY_EVENTS;
|
||||
|
||||
export type OnboardingAnalyticsStep = "create_agent" | "connect_model" | "review" | "launch";
|
||||
export type OnboardingAnalyticsOutcome = "subscription" | "api_key" | "succeeded" | "failed";
|
||||
export type OnboardingFailureReason =
|
||||
| "api_key_save_failed"
|
||||
| "subscription_login_failed"
|
||||
| "environment_test_failed"
|
||||
| "agent_create_failed"
|
||||
| "launch_failed"
|
||||
| "greeting_failed";
|
||||
export type AgentChatSurface = "onboarding_chat" | "agent_chat";
|
||||
export type {
|
||||
AgentChatSurface,
|
||||
OnboardingAnalyticsOutcome,
|
||||
OnboardingAnalyticsStep,
|
||||
OnboardingCredentialMode,
|
||||
OnboardingDismissMethod,
|
||||
OnboardingFailureReason,
|
||||
OnboardingMobileHandoffAction,
|
||||
OnboardingOAuthStage,
|
||||
OnboardingOpenSource,
|
||||
OnboardingTelemetryEventInput,
|
||||
OnboardingWorkspaceSkipReason,
|
||||
};
|
||||
|
||||
const SAFE_PROVIDER_SLUG = /^[a-z0-9_-]{1,32}$/;
|
||||
const SAFE_SLUG = /^[a-z0-9_-]{1,48}$/;
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
const WIZARD_STEPS: Record<number, OnboardingAnalyticsStep> = {
|
||||
1: "name_org",
|
||||
3: "create_agent",
|
||||
4: "connect_model",
|
||||
5: "review",
|
||||
};
|
||||
|
||||
const WIZARD_STEP_ORDER: Record<number, number> = {
|
||||
1: 0,
|
||||
3: 1,
|
||||
4: 2,
|
||||
5: 3,
|
||||
};
|
||||
|
||||
export type OnboardingTelemetrySender = (payload: OnboardingTelemetryEventInput) => void;
|
||||
|
||||
function fallbackToBrowserAnalytics(payload: OnboardingTelemetryEventInput): void {
|
||||
const props = onboardingTelemetryEventToPostHogProperties(payload);
|
||||
const stringProps: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(props)) {
|
||||
stringProps[key] = String(value);
|
||||
}
|
||||
captureProductAnalyticsEvent(payload.event, stringProps);
|
||||
}
|
||||
|
||||
function defaultSendOnboardingTelemetry(payload: OnboardingTelemetryEventInput): void {
|
||||
if (typeof fetch !== "function") return;
|
||||
try {
|
||||
void fetch("/api/onboarding/telemetry", {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
keepalive: true,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
.then((res) => {
|
||||
// Only fall back to browser posthog-js when the server explicitly
|
||||
// reports direct server-side delivery is inactive (e.g.
|
||||
// PAPERCLIP_POSTHOG_DIRECT=0 with browser analytics enabled).
|
||||
if (res.ok && res.headers.get("X-Paperclip-Telemetry-Delivered") === "0") {
|
||||
fallbackToBrowserAnalytics(payload);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
// Best-effort analytics must never interrupt onboarding.
|
||||
});
|
||||
} catch {
|
||||
// Best-effort analytics must never interrupt onboarding.
|
||||
}
|
||||
}
|
||||
|
||||
let sender: OnboardingTelemetrySender = defaultSendOnboardingTelemetry;
|
||||
|
||||
export function setOnboardingTelemetrySenderForTest(next: OnboardingTelemetrySender): void {
|
||||
sender = next;
|
||||
}
|
||||
|
||||
export function resetOnboardingTelemetryForTest(): void {
|
||||
sender = defaultSendOnboardingTelemetry;
|
||||
}
|
||||
|
||||
function sendEvent(payload: OnboardingTelemetryEventInput): void {
|
||||
sender(payload);
|
||||
}
|
||||
|
||||
function normalizeSlug(value?: string | null): string | undefined {
|
||||
const normalized = value?.trim().toLowerCase();
|
||||
return normalized && SAFE_SLUG.test(normalized) ? normalized : undefined;
|
||||
}
|
||||
|
||||
function normalizeCompanyId(value?: string | null): string | undefined {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed && UUID_RE.test(trimmed) ? trimmed : undefined;
|
||||
}
|
||||
|
||||
export function onboardingAnalyticsStepFor(wizardStep: number): OnboardingAnalyticsStep | null {
|
||||
return WIZARD_STEPS[wizardStep] ?? null;
|
||||
}
|
||||
|
||||
function stepProperties(step: OnboardingAnalyticsStep | null, outcome?: OnboardingAnalyticsOutcome) {
|
||||
const properties: Record<string, string> = {};
|
||||
if (step) properties.step = step;
|
||||
if (outcome) properties.outcome = outcome;
|
||||
return properties;
|
||||
export function captureOnboardingWorkspaceLoaded(input: {
|
||||
companyId?: string | null;
|
||||
hasCompany: boolean;
|
||||
hasAgent: boolean;
|
||||
willAutoOpen: boolean;
|
||||
skipReason?: OnboardingWorkspaceSkipReason;
|
||||
isMobile?: boolean;
|
||||
}): void {
|
||||
const companyId = normalizeCompanyId(input.companyId);
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.workspaceLoaded,
|
||||
...(companyId ? { companyId } : {}),
|
||||
hasCompany: input.hasCompany,
|
||||
hasAgent: input.hasAgent,
|
||||
willAutoOpen: input.willAutoOpen,
|
||||
...(input.skipReason ? { skipReason: input.skipReason } : {}),
|
||||
...(typeof input.isMobile === "boolean" ? { isMobile: input.isMobile } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export function captureOnboardingStepCompleted(step: OnboardingAnalyticsStep, outcome?: OnboardingAnalyticsOutcome) {
|
||||
captureProductAnalyticsEvent(ONBOARDING_ANALYTICS_EVENTS.stepCompleted, stepProperties(step, outcome));
|
||||
export function captureOnboardingStepSubmitted(input: {
|
||||
step: OnboardingAnalyticsStep;
|
||||
companyId?: string | null;
|
||||
via?: "button" | "enter";
|
||||
}): void {
|
||||
const companyId = normalizeCompanyId(input.companyId);
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.stepSubmitted,
|
||||
...(companyId ? { companyId } : {}),
|
||||
step: input.step,
|
||||
...(input.via ? { via: input.via } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export function captureOnboardingStepCompleted(
|
||||
step: OnboardingAnalyticsStep,
|
||||
outcome?: OnboardingAnalyticsOutcome,
|
||||
meta?: {
|
||||
companyId?: string | null;
|
||||
provider?: string | null;
|
||||
adapterType?: string | null;
|
||||
role?: string | null;
|
||||
},
|
||||
): void {
|
||||
const companyId = normalizeCompanyId(meta?.companyId);
|
||||
const provider = normalizeSlug(meta?.provider);
|
||||
const adapterType = normalizeSlug(meta?.adapterType);
|
||||
const role = normalizeSlug(meta?.role);
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.stepCompleted,
|
||||
...(companyId ? { companyId } : {}),
|
||||
step,
|
||||
...(outcome ? { outcome } : {}),
|
||||
...(provider ? { provider } : {}),
|
||||
...(adapterType ? { adapterType } : {}),
|
||||
...(role ? { role } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export function captureOnboardingStepFailed(input: {
|
||||
step: OnboardingAnalyticsStep;
|
||||
reason: OnboardingFailureReason;
|
||||
companyId?: string | null;
|
||||
provider?: string | null;
|
||||
method?: "subscription" | "api_key";
|
||||
}) {
|
||||
const properties: Record<string, string> = {
|
||||
adapterType?: string | null;
|
||||
method?: OnboardingCredentialMode;
|
||||
}): void {
|
||||
const companyId = normalizeCompanyId(input.companyId);
|
||||
const provider = normalizeSlug(input.provider);
|
||||
const adapterType = normalizeSlug(input.adapterType);
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.stepFailed,
|
||||
...(companyId ? { companyId } : {}),
|
||||
step: input.step,
|
||||
reason: input.reason,
|
||||
};
|
||||
const provider = input.provider?.trim().toLowerCase();
|
||||
if (provider && SAFE_PROVIDER_SLUG.test(provider)) properties.provider = provider;
|
||||
if (input.method) properties.method = input.method;
|
||||
captureProductAnalyticsEvent(ONBOARDING_ANALYTICS_EVENTS.stepFailed, properties);
|
||||
...(provider ? { provider } : {}),
|
||||
...(adapterType ? { adapterType } : {}),
|
||||
...(input.method ? { method: input.method } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export function captureAgentChatMessageSent(surface: AgentChatSurface) {
|
||||
captureProductAnalyticsEvent(ONBOARDING_ANALYTICS_EVENTS.chatMessageSent, { surface });
|
||||
export function captureOnboardingStepNavigated(input: {
|
||||
fromStep: OnboardingAnalyticsStep;
|
||||
toStep: OnboardingAnalyticsStep;
|
||||
direction: "back" | "jump";
|
||||
via: "back_button" | "step_indicator";
|
||||
companyId?: string | null;
|
||||
}): void {
|
||||
const companyId = normalizeCompanyId(input.companyId);
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.stepNavigated,
|
||||
...(companyId ? { companyId } : {}),
|
||||
fromStep: input.fromStep,
|
||||
toStep: input.toStep,
|
||||
direction: input.direction,
|
||||
via: input.via,
|
||||
});
|
||||
}
|
||||
|
||||
export function captureOnboardingMobileHandoffAction(input: {
|
||||
action: OnboardingMobileHandoffAction;
|
||||
companyId?: string | null;
|
||||
}): void {
|
||||
const companyId = normalizeCompanyId(input.companyId);
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.mobileHandoffAction,
|
||||
...(companyId ? { companyId } : {}),
|
||||
action: input.action,
|
||||
});
|
||||
}
|
||||
|
||||
export function captureOnboardingTrialCtaClicked(input?: {
|
||||
companyId?: string | null;
|
||||
}): void {
|
||||
const companyId = normalizeCompanyId(input?.companyId);
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.trialCtaClicked,
|
||||
...(companyId ? { companyId } : {}),
|
||||
surface: "onboarding_wizard",
|
||||
});
|
||||
}
|
||||
|
||||
export function captureOnboardingModelSourceSelected(input: {
|
||||
adapterType: string;
|
||||
provider?: string | null;
|
||||
credentialMode: OnboardingCredentialMode;
|
||||
companyId?: string | null;
|
||||
}): void {
|
||||
const adapterType = normalizeSlug(input.adapterType);
|
||||
if (!adapterType) return;
|
||||
const companyId = normalizeCompanyId(input.companyId);
|
||||
const provider = normalizeSlug(input.provider);
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.modelSourceSelected,
|
||||
...(companyId ? { companyId } : {}),
|
||||
adapterType,
|
||||
...(provider ? { provider } : {}),
|
||||
credentialMode: input.credentialMode,
|
||||
});
|
||||
}
|
||||
|
||||
export function captureOnboardingCredentialModeSwitched(input: {
|
||||
fromMode: OnboardingCredentialMode;
|
||||
toMode: OnboardingCredentialMode;
|
||||
adapterType?: string | null;
|
||||
companyId?: string | null;
|
||||
}): void {
|
||||
const companyId = normalizeCompanyId(input.companyId);
|
||||
const adapterType = normalizeSlug(input.adapterType);
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.credentialModeSwitched,
|
||||
...(companyId ? { companyId } : {}),
|
||||
fromMode: input.fromMode,
|
||||
toMode: input.toMode,
|
||||
...(adapterType ? { adapterType } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export function captureOnboardingOAuthProgress(input: {
|
||||
stage: OnboardingOAuthStage;
|
||||
provider?: string | null;
|
||||
adapterType?: string | null;
|
||||
phase?: string | null;
|
||||
companyId?: string | null;
|
||||
}): void {
|
||||
const companyId = normalizeCompanyId(input.companyId);
|
||||
const provider = normalizeSlug(input.provider);
|
||||
const adapterType = normalizeSlug(input.adapterType);
|
||||
const phase = normalizeSlug(input.phase);
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.oauthProgress,
|
||||
...(companyId ? { companyId } : {}),
|
||||
stage: input.stage,
|
||||
...(provider ? { provider } : {}),
|
||||
...(adapterType ? { adapterType } : {}),
|
||||
...(phase ? { phase } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export function captureOnboardingApiKeySubmitted(input: {
|
||||
provider?: string | null;
|
||||
adapterType?: string | null;
|
||||
usedSavedKey: boolean;
|
||||
companyId?: string | null;
|
||||
}): void {
|
||||
const companyId = normalizeCompanyId(input.companyId);
|
||||
const provider = normalizeSlug(input.provider);
|
||||
const adapterType = normalizeSlug(input.adapterType);
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.apiKeySubmitted,
|
||||
...(companyId ? { companyId } : {}),
|
||||
...(provider ? { provider } : {}),
|
||||
...(adapterType ? { adapterType } : {}),
|
||||
usedSavedKey: input.usedSavedKey,
|
||||
});
|
||||
}
|
||||
|
||||
export function captureOnboardingAdvancedToggled(input: {
|
||||
adapterType?: string | null;
|
||||
open: boolean;
|
||||
companyId?: string | null;
|
||||
}): void {
|
||||
const companyId = normalizeCompanyId(input.companyId);
|
||||
const adapterType = normalizeSlug(input.adapterType);
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.advancedToggled,
|
||||
...(companyId ? { companyId } : {}),
|
||||
...(adapterType ? { adapterType } : {}),
|
||||
open: input.open,
|
||||
});
|
||||
}
|
||||
|
||||
export function captureOnboardingLaunchClicked(input: {
|
||||
adapterType?: string | null;
|
||||
provider?: string | null;
|
||||
outcome?: OnboardingAnalyticsOutcome;
|
||||
companyId?: string | null;
|
||||
}): void {
|
||||
const companyId = normalizeCompanyId(input.companyId);
|
||||
const adapterType = normalizeSlug(input.adapterType);
|
||||
const provider = normalizeSlug(input.provider);
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.launchClicked,
|
||||
...(companyId ? { companyId } : {}),
|
||||
...(adapterType ? { adapterType } : {}),
|
||||
...(provider ? { provider } : {}),
|
||||
...(input.outcome ? { outcome: input.outcome } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export function captureAgentChatMessageSent(
|
||||
surface: AgentChatSurface,
|
||||
meta?: { companyId?: string | null },
|
||||
): void {
|
||||
const companyId = normalizeCompanyId(meta?.companyId);
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.chatMessageSent,
|
||||
...(companyId ? { companyId } : {}),
|
||||
surface,
|
||||
});
|
||||
}
|
||||
|
||||
export function useOnboardingAnalytics(input: {
|
||||
open: boolean;
|
||||
step: number;
|
||||
connectOutcome: OnboardingAnalyticsOutcome;
|
||||
companyId?: string | null;
|
||||
provider?: string | null;
|
||||
adapterType?: string | null;
|
||||
role?: string | null;
|
||||
connectPhase?: string | null;
|
||||
hadError?: boolean;
|
||||
stepViewMeta?: {
|
||||
cloudTrialAvailable?: boolean;
|
||||
mobileHandoffShown?: boolean;
|
||||
savedKeysCount?: number;
|
||||
hasExistingSubscription?: boolean;
|
||||
};
|
||||
}) {
|
||||
const session = useRef<{ pendingStep: number | null; viewedStep: number } | null>(null);
|
||||
const connectOutcome = useRef(input.connectOutcome);
|
||||
connectOutcome.current = input.connectOutcome;
|
||||
const latest = useRef(input);
|
||||
latest.current = input;
|
||||
|
||||
const opened = useCallback((entryStep: number, renderedStep: number) => {
|
||||
if (session.current) return;
|
||||
session.current = { pendingStep: entryStep === renderedStep ? null : entryStep, viewedStep: entryStep };
|
||||
const step = onboardingAnalyticsStepFor(entryStep);
|
||||
captureProductAnalyticsEvent(ONBOARDING_ANALYTICS_EVENTS.opened, stepProperties(step));
|
||||
if (step) captureProductAnalyticsEvent(ONBOARDING_ANALYTICS_EVENTS.stepViewed, stepProperties(step));
|
||||
}, []);
|
||||
const emitStepViewed = useCallback(
|
||||
(step: OnboardingAnalyticsStep, companyIdOverride?: string | null) => {
|
||||
const companyId = normalizeCompanyId(
|
||||
companyIdOverride !== undefined ? companyIdOverride : latest.current.companyId,
|
||||
);
|
||||
const meta = step === "connect_model" ? latest.current.stepViewMeta : undefined;
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.stepViewed,
|
||||
...(companyId ? { companyId } : {}),
|
||||
step,
|
||||
...(meta && typeof meta.cloudTrialAvailable === "boolean"
|
||||
? { cloudTrialAvailable: meta.cloudTrialAvailable }
|
||||
: {}),
|
||||
...(meta && typeof meta.mobileHandoffShown === "boolean"
|
||||
? { mobileHandoffShown: meta.mobileHandoffShown }
|
||||
: {}),
|
||||
...(meta && typeof meta.savedKeysCount === "number"
|
||||
? { savedKeysCount: meta.savedKeysCount }
|
||||
: {}),
|
||||
...(meta && typeof meta.hasExistingSubscription === "boolean"
|
||||
? { hasExistingSubscription: meta.hasExistingSubscription }
|
||||
: {}),
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const dismissed = useCallback((step: number) => {
|
||||
const opened = useCallback(
|
||||
(
|
||||
entryStep: number,
|
||||
renderedStep: number,
|
||||
meta?: {
|
||||
companyId?: string | null;
|
||||
source?: OnboardingOpenSource;
|
||||
isMobile?: boolean;
|
||||
resumedDraft?: boolean;
|
||||
hasExistingCompany?: boolean;
|
||||
},
|
||||
) => {
|
||||
if (session.current) return;
|
||||
session.current = {
|
||||
pendingStep: entryStep === renderedStep ? null : entryStep,
|
||||
viewedStep: entryStep,
|
||||
};
|
||||
const step = onboardingAnalyticsStepFor(entryStep);
|
||||
const resolvedCompanyId =
|
||||
meta?.companyId !== undefined ? meta.companyId : latest.current.companyId;
|
||||
const companyId = normalizeCompanyId(resolvedCompanyId);
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.opened,
|
||||
...(companyId ? { companyId } : {}),
|
||||
...(step ? { step } : {}),
|
||||
...(meta?.source ? { source: meta.source } : {}),
|
||||
...(typeof meta?.isMobile === "boolean" ? { isMobile: meta.isMobile } : {}),
|
||||
...(typeof meta?.resumedDraft === "boolean" ? { resumedDraft: meta.resumedDraft } : {}),
|
||||
...(typeof meta?.hasExistingCompany === "boolean"
|
||||
? { hasExistingCompany: meta.hasExistingCompany }
|
||||
: {}),
|
||||
});
|
||||
if (step) emitStepViewed(step, resolvedCompanyId);
|
||||
},
|
||||
[emitStepViewed],
|
||||
);
|
||||
|
||||
const dismissed = useCallback((step: number, method: OnboardingDismissMethod = "close_button") => {
|
||||
if (!session.current) return;
|
||||
session.current = null;
|
||||
captureProductAnalyticsEvent(
|
||||
ONBOARDING_ANALYTICS_EVENTS.dismissed,
|
||||
stepProperties(onboardingAnalyticsStepFor(step)),
|
||||
);
|
||||
const companyId = normalizeCompanyId(latest.current.companyId);
|
||||
const analyticsStep = onboardingAnalyticsStepFor(step);
|
||||
const connectPhase = normalizeSlug(latest.current.connectPhase);
|
||||
sendEvent({
|
||||
event: ONBOARDING_TELEMETRY_EVENTS.dismissed,
|
||||
...(companyId ? { companyId } : {}),
|
||||
...(analyticsStep ? { step: analyticsStep } : {}),
|
||||
...(analyticsStep === "connect_model" && connectPhase ? { connectPhase } : {}),
|
||||
...(typeof latest.current.hadError === "boolean" ? { hadError: latest.current.hadError } : {}),
|
||||
method,
|
||||
});
|
||||
}, []);
|
||||
|
||||
const finished = useCallback(() => {
|
||||
@@ -98,7 +465,7 @@ export function useOnboardingAnalytics(input: {
|
||||
useEffect(() => {
|
||||
const current = session.current;
|
||||
if (!open) {
|
||||
if (current) dismissed(current.viewedStep);
|
||||
if (current) dismissed(current.viewedStep, "unmount");
|
||||
return;
|
||||
}
|
||||
if (!current) return;
|
||||
@@ -110,15 +477,25 @@ export function useOnboardingAnalytics(input: {
|
||||
if (previous === step) return;
|
||||
current.viewedStep = step;
|
||||
const previousStep = onboardingAnalyticsStepFor(previous);
|
||||
if (previousStep && step === previous + 1) {
|
||||
const prevOrder = WIZARD_STEP_ORDER[previous];
|
||||
const nextOrder = WIZARD_STEP_ORDER[step];
|
||||
if (previousStep && prevOrder !== undefined && nextOrder !== undefined && nextOrder === prevOrder + 1) {
|
||||
const ctx = latest.current;
|
||||
captureOnboardingStepCompleted(
|
||||
previousStep,
|
||||
previousStep === "connect_model" ? connectOutcome.current : undefined,
|
||||
previousStep === "connect_model" ? ctx.connectOutcome : undefined,
|
||||
{
|
||||
companyId: ctx.companyId,
|
||||
...(previousStep === "create_agent" ? { role: ctx.role } : {}),
|
||||
...(previousStep === "connect_model"
|
||||
? { provider: ctx.provider, adapterType: ctx.adapterType }
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
}
|
||||
const viewed = onboardingAnalyticsStepFor(step);
|
||||
if (viewed) captureProductAnalyticsEvent(ONBOARDING_ANALYTICS_EVENTS.stepViewed, stepProperties(viewed));
|
||||
}, [open, step]);
|
||||
if (viewed) emitStepViewed(viewed);
|
||||
}, [open, step, dismissed, emitStepViewed]);
|
||||
|
||||
return { opened, dismissed, finished };
|
||||
}
|
||||
@@ -253,6 +253,7 @@ const MAX_QUEUED_PRODUCT_EVENTS = 50;
|
||||
let state: State | null = null;
|
||||
let wantedUser: ProductAnalyticsUser | null = null;
|
||||
let identifiedUserId: string | null = null;
|
||||
let preStartQueued: QueuedProductEvent[] = [];
|
||||
|
||||
function createAnalyticsState(config: BrowserAnalyticsConfig): State {
|
||||
return {
|
||||
@@ -301,9 +302,12 @@ function sendProductEvent(client: ProductAnalyticsClient, queued: QueuedProductE
|
||||
}
|
||||
|
||||
export function captureProductAnalyticsEvent(event: string, properties: Record<string, string> = {}): void {
|
||||
const current = state;
|
||||
if (!current) return;
|
||||
const queued = { event, properties: { ...properties }, timestamp: new Date() };
|
||||
const current = state;
|
||||
if (!current) {
|
||||
if (preStartQueued.length < MAX_QUEUED_PRODUCT_EVENTS) preStartQueued.push(queued);
|
||||
return;
|
||||
}
|
||||
if (current.client) {
|
||||
sendProductEvent(current.client, queued);
|
||||
return;
|
||||
@@ -343,6 +347,10 @@ export function startProductAnalytics(
|
||||
): void {
|
||||
if (state) return;
|
||||
const current = createAnalyticsState(config);
|
||||
if (preStartQueued.length > 0) {
|
||||
current.queued.push(...preStartQueued.slice(0, MAX_QUEUED_PRODUCT_EVENTS));
|
||||
preStartQueued = [];
|
||||
}
|
||||
state = current;
|
||||
const load = options.load ?? loadPostHog;
|
||||
current.cancelSchedule = options.schedule(() => {
|
||||
@@ -380,7 +388,10 @@ export function refreshSessionReplay(): void {
|
||||
|
||||
/** Set (or clear, on sign-out) the signed-in user. Safe to call before posthog-js loads. */
|
||||
export function setProductAnalyticsUser(user: ProductAnalyticsUser | null): void {
|
||||
if (wantedUser && wantedUser.id !== user?.id && state) state.queued = [];
|
||||
if (wantedUser && wantedUser.id !== user?.id) {
|
||||
preStartQueued = [];
|
||||
if (state) state.queued = [];
|
||||
}
|
||||
wantedUser = user;
|
||||
if (state?.client) applyIdentity(state.client, state.config);
|
||||
}
|
||||
@@ -410,4 +421,5 @@ export function resetProductAnalyticsForTest(): void {
|
||||
state = null;
|
||||
wantedUser = null;
|
||||
identifiedUserId = null;
|
||||
preStartQueued = [];
|
||||
}
|
||||
@@ -34,6 +34,12 @@ export function dashboardOnboardingOptions(
|
||||
* scope: that is a new visit rather than the same one continuing.
|
||||
*/
|
||||
const offeredCompanyIds = new Set<string>();
|
||||
const workspaceReportedCompanyIds = new Set<string>();
|
||||
|
||||
/** Whether onboarding has already been offered automatically for this company. */
|
||||
export function hasClaimedOnboardingOffer(companyId: string): boolean {
|
||||
return offeredCompanyIds.has(companyId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Records an offer, and reports whether it is the first one for this company.
|
||||
@@ -46,7 +52,15 @@ export function claimOnboardingOffer(companyId: string): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Records a workspace-loaded analytics report once per company per page visit. */
|
||||
export function claimOnboardingWorkspaceReport(companyId: string): boolean {
|
||||
if (workspaceReportedCompanyIds.has(companyId)) return false;
|
||||
workspaceReportedCompanyIds.add(companyId);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Forget every offer. For tests, which must not inherit each other's state. */
|
||||
export function resetOnboardingOffers(): void {
|
||||
offeredCompanyIds.clear();
|
||||
workspaceReportedCompanyIds.clear();
|
||||
}
|
||||
Reference in new issue
Block a user