mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +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
@@ -0,0 +1,64 @@
|
||||
---
|
||||
title: Onboarding Telemetry
|
||||
summary: First-party server-side onboarding funnel telemetry endpoint
|
||||
---
|
||||
|
||||
# Onboarding Telemetry API
|
||||
|
||||
First-party board endpoint for recording structured onboarding funnel and interaction events server-side on Paperclip Cloud.
|
||||
|
||||
## Record Onboarding Telemetry Event
|
||||
|
||||
```
|
||||
POST /api/onboarding/telemetry
|
||||
```
|
||||
|
||||
Requires an authenticated board session (`assertBoard`). When `companyId` is included in the request body, the caller must also have access to that company (`assertCompanyAccess`). Pre-company Step 1 (`name_org`) events omit `companyId`.
|
||||
|
||||
### Request Body
|
||||
|
||||
A strict discriminated union keyed by `event` (`onboardingTelemetryEventSchema` in `@paperclipai/shared`). All fields are constrained to enums, booleans, bounded integers, UUIDs (`companyId`), or lowercase safe slugs (`^[a-z0-9_-]{1,48}$`) — free-form text and secrets are rejected.
|
||||
|
||||
Supported `event` values:
|
||||
|
||||
| Event | Purpose |
|
||||
| --- | --- |
|
||||
| `onboarding_workspace_loaded` | Workspace arrival and auto-open eligibility (`hasCompany`, `hasAgent`, `willAutoOpen`, optional `skipReason`, `isMobile`) |
|
||||
| `onboarding_opened` | Wizard opened (`step`, `source`, `isMobile`, `resumedDraft`, `hasExistingCompany`) |
|
||||
| `onboarding_step_viewed` | Wizard step rendered (`step`, optional `cloudTrialAvailable`, `mobileHandoffShown`, `savedKeysCount`, `hasExistingSubscription`) |
|
||||
| `onboarding_step_submitted` | Primary action submitted (`step`, optional `via`: `button` \| `enter`) |
|
||||
| `onboarding_step_completed` | Step completed (`step`, optional `outcome`, `provider`, `adapterType`, `role`) |
|
||||
| `onboarding_step_failed` | Structured step failure (`step`, `reason`, optional `provider`, `adapterType`, `method`) |
|
||||
| `onboarding_step_navigated` | Back button or step indicator jump (`fromStep`, `toStep`, `direction`, `via`) |
|
||||
| `onboarding_dismissed` | Wizard closed before launch (`step`, optional `connectPhase`, `hadError`, `method`) |
|
||||
| `onboarding_mobile_handoff_action` | Mobile desktop-handoff card interaction (`action`) |
|
||||
| `onboarding_trial_cta_clicked` | Cloud starter trial CTA clicked (`surface`) |
|
||||
| `onboarding_model_source_selected` | Provider tile clicked on `connect_model` (`adapterType`, optional `provider`, `credentialMode`) |
|
||||
| `onboarding_credential_mode_switched` | Switched between `subscription` and `api_key` (`fromMode`, `toMode`, optional `adapterType`) |
|
||||
| `onboarding_oauth_progress` | Granular OAuth sub-step (`stage`, optional `provider`, `adapterType`, `phase`) |
|
||||
| `onboarding_api_key_submitted` | API key submitted (`usedSavedKey`, optional `provider`, `adapterType`) |
|
||||
| `onboarding_advanced_toggled` | Advanced gateway setup toggled (`open`, optional `adapterType`) |
|
||||
| `onboarding_launch_clicked` | Launch CTA clicked on `review` (optional `adapterType`, `provider`, `outcome`) |
|
||||
| `agent_chat_message_sent` | Chat message sent (`surface`: `onboarding_chat` \| `agent_chat`) |
|
||||
|
||||
Example:
|
||||
|
||||
```json
|
||||
{
|
||||
"event": "onboarding_step_completed",
|
||||
"companyId": "11111111-1111-4111-8111-111111111111",
|
||||
"step": "connect_model",
|
||||
"outcome": "subscription",
|
||||
"provider": "anthropic",
|
||||
"adapterType": "claude_local"
|
||||
}
|
||||
```
|
||||
|
||||
### Responses
|
||||
|
||||
| Status | Meaning |
|
||||
| --- | --- |
|
||||
| `204` | Event accepted. Sets header `X-Paperclip-Telemetry-Delivered: 1` when direct server-side PostHog delivery is active, or `0` when direct delivery is inactive (self-hosted installs, `PAPERCLIP_POSTHOG_DIRECT=0`, or missing `PAPERCLIP_POSTHOG_ENVIRONMENT`). |
|
||||
| `400` | Validation error (unknown event name, disallowed extra property, or invalid slug/enum). |
|
||||
| `403` | Unauthenticated, non-board actor, or caller lacks access to `companyId`. |
|
||||
| `429` | Per-actor rate limit exceeded (default 120 events per 60 seconds). |
|
||||
@@ -3189,5 +3189,6 @@ export type { TailscaleConnection, TailscaleDeviceLogin } from "./types/tailscal
|
||||
export * from "./agent-setup-progress.js";
|
||||
export { antigravitySwarmAvailable, antigravitySwarmWorkModeAllows, isAntigravityAgent, parseLeadingUserCommand, SWARM_REQUEST_MAX_CHARS, type LeadingUserCommand } from "./leading-user-command.js";
|
||||
export * from "./cloud-inference.js";
|
||||
export * from "./onboarding-telemetry.js";
|
||||
export * from "./upstream-failure-codes.js";
|
||||
export * from "./headless/index.js";
|
||||
@@ -0,0 +1,384 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* Canonical onboarding funnel event names.
|
||||
*
|
||||
* Existing names (`onboarding_opened`, `onboarding_step_viewed`,
|
||||
* `onboarding_step_completed`, `onboarding_step_failed`, `onboarding_dismissed`,
|
||||
* `agent_chat_message_sent`) are preserved verbatim so existing PostHog
|
||||
* insights continue working seamlessly once emitted server-side.
|
||||
*/
|
||||
export const ONBOARDING_TELEMETRY_EVENTS = {
|
||||
workspaceLoaded: "onboarding_workspace_loaded",
|
||||
opened: "onboarding_opened",
|
||||
stepViewed: "onboarding_step_viewed",
|
||||
stepSubmitted: "onboarding_step_submitted",
|
||||
stepCompleted: "onboarding_step_completed",
|
||||
stepFailed: "onboarding_step_failed",
|
||||
stepNavigated: "onboarding_step_navigated",
|
||||
dismissed: "onboarding_dismissed",
|
||||
mobileHandoffAction: "onboarding_mobile_handoff_action",
|
||||
trialCtaClicked: "onboarding_trial_cta_clicked",
|
||||
modelSourceSelected: "onboarding_model_source_selected",
|
||||
credentialModeSwitched: "onboarding_credential_mode_switched",
|
||||
oauthProgress: "onboarding_oauth_progress",
|
||||
apiKeySubmitted: "onboarding_api_key_submitted",
|
||||
advancedToggled: "onboarding_advanced_toggled",
|
||||
launchClicked: "onboarding_launch_clicked",
|
||||
chatMessageSent: "agent_chat_message_sent",
|
||||
} as const;
|
||||
|
||||
export const ONBOARDING_ANALYTICS_STEPS = [
|
||||
"name_org",
|
||||
"create_agent",
|
||||
"connect_model",
|
||||
"review",
|
||||
"launch",
|
||||
] as const;
|
||||
export type OnboardingAnalyticsStep = (typeof ONBOARDING_ANALYTICS_STEPS)[number];
|
||||
|
||||
export const ONBOARDING_ANALYTICS_OUTCOMES = [
|
||||
"subscription",
|
||||
"api_key",
|
||||
"cloud_trial",
|
||||
"succeeded",
|
||||
"failed",
|
||||
] as const;
|
||||
export type OnboardingAnalyticsOutcome = (typeof ONBOARDING_ANALYTICS_OUTCOMES)[number];
|
||||
|
||||
export const ONBOARDING_FAILURE_REASONS = [
|
||||
"company_create_failed",
|
||||
"api_key_save_failed",
|
||||
"api_key_rejected",
|
||||
"subscription_login_failed",
|
||||
"environment_test_failed",
|
||||
"agent_create_failed",
|
||||
"cloud_trial_failed",
|
||||
"launch_failed",
|
||||
"greeting_failed",
|
||||
] as const;
|
||||
export type OnboardingFailureReason = (typeof ONBOARDING_FAILURE_REASONS)[number];
|
||||
|
||||
export const AGENT_CHAT_SURFACES = ["onboarding_chat", "agent_chat"] as const;
|
||||
export type AgentChatSurface = (typeof AGENT_CHAT_SURFACES)[number];
|
||||
|
||||
export const ONBOARDING_CREDENTIAL_MODES = ["subscription", "api_key"] as const;
|
||||
export type OnboardingCredentialMode = (typeof ONBOARDING_CREDENTIAL_MODES)[number];
|
||||
|
||||
export const ONBOARDING_OPEN_SOURCES = [
|
||||
"auto_open",
|
||||
"route",
|
||||
"manual",
|
||||
"resume_draft",
|
||||
] as const;
|
||||
export type OnboardingOpenSource = (typeof ONBOARDING_OPEN_SOURCES)[number];
|
||||
|
||||
export const ONBOARDING_WORKSPACE_SKIP_REASONS = [
|
||||
"has_agent",
|
||||
"not_home_route",
|
||||
"already_offered",
|
||||
"no_company",
|
||||
] as const;
|
||||
export type OnboardingWorkspaceSkipReason = (typeof ONBOARDING_WORKSPACE_SKIP_REASONS)[number];
|
||||
|
||||
export const ONBOARDING_DISMISS_METHODS = [
|
||||
"close_button",
|
||||
"escape",
|
||||
"backdrop",
|
||||
"unmount",
|
||||
] as const;
|
||||
export type OnboardingDismissMethod = (typeof ONBOARDING_DISMISS_METHODS)[number];
|
||||
|
||||
export const ONBOARDING_MOBILE_HANDOFF_ACTIONS = [
|
||||
"shown",
|
||||
"expanded",
|
||||
"copy_link",
|
||||
"copy_link_manual",
|
||||
"dismissed",
|
||||
] as const;
|
||||
export type OnboardingMobileHandoffAction = (typeof ONBOARDING_MOBILE_HANDOFF_ACTIONS)[number];
|
||||
|
||||
export const ONBOARDING_OAUTH_STAGES = [
|
||||
"started",
|
||||
"auth_link_opened",
|
||||
"code_submitted",
|
||||
"connected",
|
||||
"retried",
|
||||
"abandoned",
|
||||
] as const;
|
||||
export type OnboardingOAuthStage = (typeof ONBOARDING_OAUTH_STAGES)[number];
|
||||
|
||||
const safeSlugSchema = z.string().regex(/^[a-z0-9_-]{1,48}$/);
|
||||
const optionalCompanyIdSchema = z.string().uuid().optional();
|
||||
|
||||
export const onboardingTelemetryEventSchema = z.discriminatedUnion("event", [
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.workspaceLoaded),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
hasCompany: z.boolean(),
|
||||
hasAgent: z.boolean(),
|
||||
willAutoOpen: z.boolean(),
|
||||
skipReason: z.enum(ONBOARDING_WORKSPACE_SKIP_REASONS).optional(),
|
||||
isMobile: z.boolean().optional(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.opened),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
step: z.enum(ONBOARDING_ANALYTICS_STEPS).optional(),
|
||||
source: z.enum(ONBOARDING_OPEN_SOURCES).optional(),
|
||||
isMobile: z.boolean().optional(),
|
||||
resumedDraft: z.boolean().optional(),
|
||||
hasExistingCompany: z.boolean().optional(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.stepViewed),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
step: z.enum(ONBOARDING_ANALYTICS_STEPS),
|
||||
cloudTrialAvailable: z.boolean().optional(),
|
||||
mobileHandoffShown: z.boolean().optional(),
|
||||
savedKeysCount: z.number().int().nonnegative().max(1000).optional(),
|
||||
hasExistingSubscription: z.boolean().optional(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.stepSubmitted),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
step: z.enum(ONBOARDING_ANALYTICS_STEPS),
|
||||
via: z.enum(["button", "enter"]).optional(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.stepCompleted),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
step: z.enum(ONBOARDING_ANALYTICS_STEPS),
|
||||
outcome: z.enum(ONBOARDING_ANALYTICS_OUTCOMES).optional(),
|
||||
provider: safeSlugSchema.optional(),
|
||||
adapterType: safeSlugSchema.optional(),
|
||||
role: safeSlugSchema.optional(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.stepFailed),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
step: z.enum(ONBOARDING_ANALYTICS_STEPS),
|
||||
reason: z.enum(ONBOARDING_FAILURE_REASONS),
|
||||
provider: safeSlugSchema.optional(),
|
||||
adapterType: safeSlugSchema.optional(),
|
||||
method: z.enum(ONBOARDING_CREDENTIAL_MODES).optional(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.stepNavigated),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
fromStep: z.enum(ONBOARDING_ANALYTICS_STEPS),
|
||||
toStep: z.enum(ONBOARDING_ANALYTICS_STEPS),
|
||||
direction: z.enum(["back", "jump"]),
|
||||
via: z.enum(["back_button", "step_indicator"]),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.dismissed),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
step: z.enum(ONBOARDING_ANALYTICS_STEPS).optional(),
|
||||
connectPhase: safeSlugSchema.optional(),
|
||||
hadError: z.boolean().optional(),
|
||||
method: z.enum(ONBOARDING_DISMISS_METHODS).optional(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.mobileHandoffAction),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
action: z.enum(ONBOARDING_MOBILE_HANDOFF_ACTIONS),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.trialCtaClicked),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
surface: z.enum(["onboarding_wizard"]).default("onboarding_wizard"),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.modelSourceSelected),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
adapterType: safeSlugSchema,
|
||||
provider: safeSlugSchema.optional(),
|
||||
credentialMode: z.enum(ONBOARDING_CREDENTIAL_MODES),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.credentialModeSwitched),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
fromMode: z.enum(ONBOARDING_CREDENTIAL_MODES),
|
||||
toMode: z.enum(ONBOARDING_CREDENTIAL_MODES),
|
||||
adapterType: safeSlugSchema.optional(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.oauthProgress),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
stage: z.enum(ONBOARDING_OAUTH_STAGES),
|
||||
provider: safeSlugSchema.optional(),
|
||||
adapterType: safeSlugSchema.optional(),
|
||||
phase: safeSlugSchema.optional(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.apiKeySubmitted),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
provider: safeSlugSchema.optional(),
|
||||
adapterType: safeSlugSchema.optional(),
|
||||
usedSavedKey: z.boolean(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.advancedToggled),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
adapterType: safeSlugSchema.optional(),
|
||||
open: z.boolean(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.launchClicked),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
adapterType: safeSlugSchema.optional(),
|
||||
provider: safeSlugSchema.optional(),
|
||||
outcome: z.enum(ONBOARDING_ANALYTICS_OUTCOMES).optional(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
event: z.literal(ONBOARDING_TELEMETRY_EVENTS.chatMessageSent),
|
||||
companyId: optionalCompanyIdSchema,
|
||||
surface: z.enum(AGENT_CHAT_SURFACES),
|
||||
})
|
||||
.strict(),
|
||||
]);
|
||||
|
||||
export type OnboardingTelemetryEventInput = z.infer<typeof onboardingTelemetryEventSchema>;
|
||||
|
||||
/**
|
||||
* Converts a validated onboarding telemetry payload into flat snake_case
|
||||
* PostHog event properties (excluding `event` and `companyId`, which belong
|
||||
* to the event name and context respectively).
|
||||
*/
|
||||
export function onboardingTelemetryEventToPostHogProperties(
|
||||
input: OnboardingTelemetryEventInput,
|
||||
): Record<string, string | number | boolean> {
|
||||
const props: Record<string, string | number | boolean> = {};
|
||||
const set = (key: string, value: string | number | boolean | undefined) => {
|
||||
if (value !== undefined) props[key] = value;
|
||||
};
|
||||
|
||||
switch (input.event) {
|
||||
case ONBOARDING_TELEMETRY_EVENTS.workspaceLoaded:
|
||||
set("has_company", input.hasCompany);
|
||||
set("has_agent", input.hasAgent);
|
||||
set("will_auto_open", input.willAutoOpen);
|
||||
set("skip_reason", input.skipReason);
|
||||
set("is_mobile", input.isMobile);
|
||||
break;
|
||||
case ONBOARDING_TELEMETRY_EVENTS.opened:
|
||||
set("step", input.step);
|
||||
set("source", input.source);
|
||||
set("is_mobile", input.isMobile);
|
||||
set("resumed_draft", input.resumedDraft);
|
||||
set("has_existing_company", input.hasExistingCompany);
|
||||
break;
|
||||
case ONBOARDING_TELEMETRY_EVENTS.stepViewed:
|
||||
set("step", input.step);
|
||||
set("cloud_trial_available", input.cloudTrialAvailable);
|
||||
set("mobile_handoff_shown", input.mobileHandoffShown);
|
||||
set("saved_keys_count", input.savedKeysCount);
|
||||
set("has_existing_subscription", input.hasExistingSubscription);
|
||||
break;
|
||||
case ONBOARDING_TELEMETRY_EVENTS.stepSubmitted:
|
||||
set("step", input.step);
|
||||
set("via", input.via);
|
||||
break;
|
||||
case ONBOARDING_TELEMETRY_EVENTS.stepCompleted:
|
||||
set("step", input.step);
|
||||
set("outcome", input.outcome);
|
||||
set("provider", input.provider);
|
||||
set("adapter_type", input.adapterType);
|
||||
set("role", input.role);
|
||||
break;
|
||||
case ONBOARDING_TELEMETRY_EVENTS.stepFailed:
|
||||
set("step", input.step);
|
||||
set("reason", input.reason);
|
||||
set("provider", input.provider);
|
||||
set("adapter_type", input.adapterType);
|
||||
set("method", input.method);
|
||||
break;
|
||||
case ONBOARDING_TELEMETRY_EVENTS.stepNavigated:
|
||||
set("from_step", input.fromStep);
|
||||
set("to_step", input.toStep);
|
||||
set("direction", input.direction);
|
||||
set("via", input.via);
|
||||
break;
|
||||
case ONBOARDING_TELEMETRY_EVENTS.dismissed:
|
||||
set("step", input.step);
|
||||
set("connect_phase", input.connectPhase);
|
||||
set("had_error", input.hadError);
|
||||
set("method", input.method);
|
||||
break;
|
||||
case ONBOARDING_TELEMETRY_EVENTS.mobileHandoffAction:
|
||||
set("action", input.action);
|
||||
break;
|
||||
case ONBOARDING_TELEMETRY_EVENTS.trialCtaClicked:
|
||||
set("surface", input.surface);
|
||||
break;
|
||||
case ONBOARDING_TELEMETRY_EVENTS.modelSourceSelected:
|
||||
set("adapter_type", input.adapterType);
|
||||
set("provider", input.provider);
|
||||
set("credential_mode", input.credentialMode);
|
||||
break;
|
||||
case ONBOARDING_TELEMETRY_EVENTS.credentialModeSwitched:
|
||||
set("from_mode", input.fromMode);
|
||||
set("to_mode", input.toMode);
|
||||
set("adapter_type", input.adapterType);
|
||||
break;
|
||||
case ONBOARDING_TELEMETRY_EVENTS.oauthProgress:
|
||||
set("stage", input.stage);
|
||||
set("provider", input.provider);
|
||||
set("adapter_type", input.adapterType);
|
||||
set("phase", input.phase);
|
||||
break;
|
||||
case ONBOARDING_TELEMETRY_EVENTS.apiKeySubmitted:
|
||||
set("provider", input.provider);
|
||||
set("adapter_type", input.adapterType);
|
||||
set("used_saved_key", input.usedSavedKey);
|
||||
break;
|
||||
case ONBOARDING_TELEMETRY_EVENTS.advancedToggled:
|
||||
set("adapter_type", input.adapterType);
|
||||
set("open", input.open);
|
||||
break;
|
||||
case ONBOARDING_TELEMETRY_EVENTS.launchClicked:
|
||||
set("adapter_type", input.adapterType);
|
||||
set("provider", input.provider);
|
||||
set("outcome", input.outcome);
|
||||
break;
|
||||
case ONBOARDING_TELEMETRY_EVENTS.chatMessageSent:
|
||||
set("surface", input.surface);
|
||||
break;
|
||||
}
|
||||
|
||||
return props;
|
||||
}
|
||||
@@ -34,6 +34,7 @@ const ROUTES_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "routes")
|
||||
// when the value cannot reveal whether a cross-tenant resource exists.
|
||||
const REQUEST_INPUT_ALLOWLIST = new Set([
|
||||
"companies.ts:target", // import target chosen by the caller (req.body.target)
|
||||
"onboarding-telemetry.ts:body", // optional companyId supplied in request body
|
||||
"plugins.ts:runContext", // run context supplied in the request body
|
||||
]);
|
||||
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { errorHandler } from "../middleware/index.js";
|
||||
|
||||
const mockTrackCloudPostHogEvent = vi.hoisted(() => vi.fn());
|
||||
const mockIsPostHogDirectTelemetryActive = vi.hoisted(() => vi.fn(() => true));
|
||||
|
||||
vi.mock("../telemetry.js", () => ({
|
||||
isPostHogDirectTelemetryActive: mockIsPostHogDirectTelemetryActive,
|
||||
trackCloudPostHogEvent: mockTrackCloudPostHogEvent,
|
||||
}));
|
||||
|
||||
import {
|
||||
onboardingTelemetryRoutes,
|
||||
TELEMETRY_DELIVERED_HEADER,
|
||||
type OnboardingTelemetryRouteOptions,
|
||||
} from "../routes/onboarding-telemetry.js";
|
||||
|
||||
const COMPANY_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const OTHER_COMPANY_ID = "22222222-2222-4222-8222-222222222222";
|
||||
|
||||
function createTestApp(
|
||||
actor: Express.Request["actor"],
|
||||
options?: OnboardingTelemetryRouteOptions,
|
||||
) {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
req.actor = actor;
|
||||
next();
|
||||
});
|
||||
app.use("/api", onboardingTelemetryRoutes(options));
|
||||
app.use(errorHandler);
|
||||
return app;
|
||||
}
|
||||
|
||||
describe("POST /api/onboarding/telemetry", () => {
|
||||
beforeEach(() => {
|
||||
mockTrackCloudPostHogEvent.mockReset();
|
||||
mockIsPostHogDirectTelemetryActive.mockReset();
|
||||
mockIsPostHogDirectTelemetryActive.mockReturnValue(true);
|
||||
});
|
||||
|
||||
it("forwards validated onboarding events to PostHog with board user and company context", async () => {
|
||||
const app = createTestApp({
|
||||
type: "board",
|
||||
userId: "paperclip-id:user-1",
|
||||
source: "cloud_tenant",
|
||||
isInstanceAdmin: false,
|
||||
companyIds: [COMPANY_ID],
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({
|
||||
event: "onboarding_step_completed",
|
||||
companyId: COMPANY_ID,
|
||||
step: "connect_model",
|
||||
outcome: "subscription",
|
||||
provider: "anthropic",
|
||||
adapterType: "claude_local",
|
||||
});
|
||||
|
||||
expect(res.status).toBe(204);
|
||||
expect(mockTrackCloudPostHogEvent).toHaveBeenCalledExactlyOnceWith(
|
||||
"onboarding_step_completed",
|
||||
{
|
||||
step: "connect_model",
|
||||
outcome: "subscription",
|
||||
provider: "anthropic",
|
||||
adapter_type: "claude_local",
|
||||
},
|
||||
{
|
||||
userId: "paperclip-id:user-1",
|
||||
companyId: COMPANY_ID,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts pre-company Step 1 events without a companyId", async () => {
|
||||
const app = createTestApp({
|
||||
type: "board",
|
||||
userId: "paperclip-id:user-1",
|
||||
source: "cloud_tenant",
|
||||
isInstanceAdmin: false,
|
||||
companyIds: [],
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({
|
||||
event: "onboarding_opened",
|
||||
step: "name_org",
|
||||
source: "manual",
|
||||
isMobile: false,
|
||||
resumedDraft: false,
|
||||
hasExistingCompany: false,
|
||||
});
|
||||
|
||||
expect(res.status).toBe(204);
|
||||
expect(mockTrackCloudPostHogEvent).toHaveBeenCalledExactlyOnceWith(
|
||||
"onboarding_opened",
|
||||
{
|
||||
step: "name_org",
|
||||
source: "manual",
|
||||
is_mobile: false,
|
||||
resumed_draft: false,
|
||||
has_existing_company: false,
|
||||
},
|
||||
{
|
||||
userId: "paperclip-id:user-1",
|
||||
companyId: null,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("forwards granular connect-model and workspace-loaded events with snake_case properties", async () => {
|
||||
const app = createTestApp({
|
||||
type: "board",
|
||||
userId: "paperclip-id:user-2",
|
||||
source: "cloud_tenant",
|
||||
isInstanceAdmin: false,
|
||||
companyIds: [COMPANY_ID],
|
||||
});
|
||||
|
||||
const loaded = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({
|
||||
event: "onboarding_workspace_loaded",
|
||||
companyId: COMPANY_ID,
|
||||
hasCompany: true,
|
||||
hasAgent: false,
|
||||
willAutoOpen: true,
|
||||
isMobile: true,
|
||||
});
|
||||
expect(loaded.status).toBe(204);
|
||||
|
||||
const oauth = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({
|
||||
event: "onboarding_oauth_progress",
|
||||
companyId: COMPANY_ID,
|
||||
stage: "auth_link_opened",
|
||||
provider: "anthropic",
|
||||
adapterType: "claude_local",
|
||||
phase: "ready",
|
||||
});
|
||||
expect(oauth.status).toBe(204);
|
||||
|
||||
expect(mockTrackCloudPostHogEvent.mock.calls).toEqual([
|
||||
[
|
||||
"onboarding_workspace_loaded",
|
||||
{
|
||||
has_company: true,
|
||||
has_agent: false,
|
||||
will_auto_open: true,
|
||||
is_mobile: true,
|
||||
},
|
||||
{ userId: "paperclip-id:user-2", companyId: COMPANY_ID },
|
||||
],
|
||||
[
|
||||
"onboarding_oauth_progress",
|
||||
{
|
||||
stage: "auth_link_opened",
|
||||
provider: "anthropic",
|
||||
adapter_type: "claude_local",
|
||||
phase: "ready",
|
||||
},
|
||||
{ userId: "paperclip-id:user-2", companyId: COMPANY_ID },
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects unauthenticated and agent actors", async () => {
|
||||
const unauthApp = createTestApp({ type: "none", source: "none" });
|
||||
const unauthRes = await request(unauthApp)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({ event: "onboarding_opened", step: "create_agent" });
|
||||
expect(unauthRes.status).toBe(403);
|
||||
|
||||
const agentApp = createTestApp({
|
||||
type: "agent",
|
||||
agentId: "agent-1",
|
||||
companyId: COMPANY_ID,
|
||||
source: "agent_key",
|
||||
});
|
||||
const agentRes = await request(agentApp)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({ event: "onboarding_opened", step: "create_agent" });
|
||||
expect(agentRes.status).toBe(403);
|
||||
expect(mockTrackCloudPostHogEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects cross-company telemetry when the user lacks access to companyId", async () => {
|
||||
const app = createTestApp({
|
||||
type: "board",
|
||||
userId: "paperclip-id:user-1",
|
||||
source: "cloud_tenant",
|
||||
isInstanceAdmin: false,
|
||||
companyIds: [COMPANY_ID],
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({
|
||||
event: "onboarding_opened",
|
||||
companyId: OTHER_COMPANY_ID,
|
||||
step: "create_agent",
|
||||
});
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(mockTrackCloudPostHogEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects unknown events, extra properties, and unsafe slug strings", async () => {
|
||||
const app = createTestApp({
|
||||
type: "board",
|
||||
userId: "paperclip-id:user-1",
|
||||
source: "cloud_tenant",
|
||||
isInstanceAdmin: false,
|
||||
companyIds: [COMPANY_ID],
|
||||
});
|
||||
|
||||
const unknownEvent = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({ event: "arbitrary_event" });
|
||||
expect(unknownEvent.status).toBe(400);
|
||||
|
||||
const unsafeProvider = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({
|
||||
event: "onboarding_step_failed",
|
||||
step: "connect_model",
|
||||
reason: "api_key_save_failed",
|
||||
provider: "sk-secret-key with spaces",
|
||||
});
|
||||
expect(unsafeProvider.status).toBe(400);
|
||||
|
||||
const extraField = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({
|
||||
event: "onboarding_opened",
|
||||
step: "create_agent",
|
||||
email: "user@example.com",
|
||||
});
|
||||
expect(extraField.status).toBe(400);
|
||||
expect(mockTrackCloudPostHogEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("signals X-Paperclip-Telemetry-Delivered: 0 when direct delivery is inactive", async () => {
|
||||
mockIsPostHogDirectTelemetryActive.mockReturnValue(false);
|
||||
const app = createTestApp({
|
||||
type: "board",
|
||||
userId: "paperclip-id:user-1",
|
||||
source: "cloud_tenant",
|
||||
isInstanceAdmin: false,
|
||||
companyIds: [COMPANY_ID],
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({ event: "onboarding_opened", step: "create_agent" });
|
||||
|
||||
expect(res.status).toBe(204);
|
||||
expect(res.headers[TELEMETRY_DELIVERED_HEADER.toLowerCase()]).toBe("0");
|
||||
expect(mockTrackCloudPostHogEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rate limits excessive events per actor", async () => {
|
||||
let clock = 1_000;
|
||||
const app = createTestApp(
|
||||
{
|
||||
type: "board",
|
||||
userId: "paperclip-id:user-1",
|
||||
source: "cloud_tenant",
|
||||
isInstanceAdmin: false,
|
||||
companyIds: [COMPANY_ID],
|
||||
},
|
||||
{ maxEventsPerWindow: 2, windowMs: 60_000, now: () => clock },
|
||||
);
|
||||
|
||||
const first = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({ event: "onboarding_opened", step: "create_agent" });
|
||||
const second = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({ event: "onboarding_step_viewed", step: "create_agent" });
|
||||
const third = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({ event: "onboarding_step_viewed", step: "connect_model" });
|
||||
|
||||
expect(first.status).toBe(204);
|
||||
expect(first.headers[TELEMETRY_DELIVERED_HEADER.toLowerCase()]).toBe("1");
|
||||
expect(second.status).toBe(204);
|
||||
expect(third.status).toBe(429);
|
||||
expect(mockTrackCloudPostHogEvent).toHaveBeenCalledTimes(2);
|
||||
|
||||
// After the window advances, the actor can send again.
|
||||
clock += 60_001;
|
||||
const afterWindow = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({ event: "onboarding_step_viewed", step: "connect_model" });
|
||||
expect(afterWindow.status).toBe(204);
|
||||
expect(mockTrackCloudPostHogEvent).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -49,6 +49,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"email.ts": "/api",
|
||||
"cloud.ts": "/api/cloud",
|
||||
"cloud-inference.ts": "/api",
|
||||
"onboarding-telemetry.ts": "/api",
|
||||
"customer-success.ts": "/api/customer-success/v1",
|
||||
"companies.ts": "/api/companies",
|
||||
"company-skills.ts": "/api",
|
||||
|
||||
@@ -102,6 +102,7 @@ import { cloudControlMiddleware } from "./middleware/cloud-control.js";
|
||||
import { runnerCallOutcomeMiddleware } from "./middleware/runner-call-outcome.js";
|
||||
import { cloudRoutes } from "./routes/cloud.js";
|
||||
import { cloudInferenceInternalProxyRoutes, cloudInferenceRoutes } from "./routes/cloud-inference.js";
|
||||
import { onboardingTelemetryRoutes } from "./routes/onboarding-telemetry.js";
|
||||
import {
|
||||
createCloudTrialInferenceController,
|
||||
setDefaultCloudTrialInferenceController,
|
||||
@@ -782,6 +783,7 @@ export async function createApp(
|
||||
api.use(openApiRoutes());
|
||||
api.use("/cloud", cloudRoutes());
|
||||
api.use(cloudInferenceRoutes(db, cloudTrialInferenceController));
|
||||
api.use(onboardingTelemetryRoutes());
|
||||
api.use(headlessIdentityRoutes(db, { deploymentMode: opts.deploymentMode }));
|
||||
api.use("/companies", companyRoutes(db, opts.storageService));
|
||||
api.use(llmRoutes(db));
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { Router } from "express";
|
||||
import {
|
||||
onboardingTelemetryEventSchema,
|
||||
onboardingTelemetryEventToPostHogProperties,
|
||||
type OnboardingTelemetryEventInput,
|
||||
} from "@paperclipai/shared";
|
||||
import { validate } from "../middleware/validate.js";
|
||||
import { isPostHogDirectTelemetryActive, trackCloudPostHogEvent } from "../telemetry.js";
|
||||
import { assertBoard, assertCompanyAccess, getActorInfo } from "./authz.js";
|
||||
|
||||
const DEFAULT_RATE_LIMIT_WINDOW_MS = 60_000;
|
||||
const DEFAULT_MAX_EVENTS_PER_WINDOW = 120;
|
||||
const MAX_TRACKED_ACTORS = 2_000;
|
||||
|
||||
export const TELEMETRY_DELIVERED_HEADER = "X-Paperclip-Telemetry-Delivered";
|
||||
|
||||
export interface OnboardingTelemetryRouteOptions {
|
||||
windowMs?: number;
|
||||
maxEventsPerWindow?: number;
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
/**
|
||||
* First-party board endpoint for server-side onboarding funnel telemetry.
|
||||
*
|
||||
* Events are validated against a strict allowlist schema (enums, booleans,
|
||||
* bounded integers, and safe slugs only — never free-form text or secrets)
|
||||
* and forwarded straight to PostHog via `posthog-node` on Paperclip Cloud.
|
||||
* Routing onboarding funnel events through the server avoids adblockers and
|
||||
* browser `posthog-js` lazy-load races.
|
||||
*
|
||||
* The response sets `X-Paperclip-Telemetry-Delivered: 1` when direct PostHog
|
||||
* delivery is active and `0` when it is inactive (self-hosted installs,
|
||||
* `PAPERCLIP_POSTHOG_DIRECT=0`, or missing `PAPERCLIP_POSTHOG_ENVIRONMENT`).
|
||||
* Browser callers can fall back to `posthog-js` only when the header is `0`,
|
||||
* guaranteeing single-sender delivery with no silent loss in hybrid configs.
|
||||
*/
|
||||
export function onboardingTelemetryRoutes(options: OnboardingTelemetryRouteOptions = {}) {
|
||||
const router = Router();
|
||||
const windowMs = options.windowMs ?? DEFAULT_RATE_LIMIT_WINDOW_MS;
|
||||
const maxEventsPerWindow = options.maxEventsPerWindow ?? DEFAULT_MAX_EVENTS_PER_WINDOW;
|
||||
const now = options.now ?? Date.now;
|
||||
const actorBuckets = new Map<string, { windowStart: number; count: number }>();
|
||||
|
||||
function allowActor(actorKey: string): boolean {
|
||||
const current = now();
|
||||
const bucket = actorBuckets.get(actorKey);
|
||||
if (!bucket || current - bucket.windowStart >= windowMs) {
|
||||
if (actorBuckets.size >= MAX_TRACKED_ACTORS) {
|
||||
for (const [key, entry] of actorBuckets) {
|
||||
if (current - entry.windowStart >= windowMs) actorBuckets.delete(key);
|
||||
}
|
||||
if (actorBuckets.size >= MAX_TRACKED_ACTORS) {
|
||||
const oldestKey = actorBuckets.keys().next().value;
|
||||
if (oldestKey !== undefined) actorBuckets.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
actorBuckets.set(actorKey, { windowStart: current, count: 1 });
|
||||
return true;
|
||||
}
|
||||
if (bucket.count >= maxEventsPerWindow) return false;
|
||||
bucket.count += 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
router.post(
|
||||
"/onboarding/telemetry",
|
||||
validate(onboardingTelemetryEventSchema),
|
||||
(req, res) => {
|
||||
assertBoard(req);
|
||||
const body = req.body as OnboardingTelemetryEventInput;
|
||||
if (body.companyId) {
|
||||
assertCompanyAccess(req, body.companyId);
|
||||
}
|
||||
const actor = getActorInfo(req);
|
||||
if (!allowActor(actor.actorId)) {
|
||||
res.status(429).json({ error: "Too many onboarding telemetry events" });
|
||||
return;
|
||||
}
|
||||
const delivered = isPostHogDirectTelemetryActive();
|
||||
if (delivered) {
|
||||
const properties = onboardingTelemetryEventToPostHogProperties(body);
|
||||
trackCloudPostHogEvent(body.event, properties, {
|
||||
userId: actor.actorId,
|
||||
companyId: body.companyId ?? null,
|
||||
});
|
||||
}
|
||||
res.setHeader(TELEMETRY_DELIVERED_HEADER, delivered ? "1" : "0");
|
||||
res.status(204).end();
|
||||
},
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
experimentalApiQueries,
|
||||
} from "./experimental-api-paths.js";
|
||||
import { Router } from "express";
|
||||
import { subscriptionPriceSchema, mergeSubscriptionsSchema, CLOUD_TRIAL_INFERENCE_STATUSES, cloudTrialTelemetryEventSchema, migrateCloudTrialAgentsSchema } from "@paperclipai/shared";
|
||||
import { subscriptionPriceSchema, mergeSubscriptionsSchema, CLOUD_TRIAL_INFERENCE_STATUSES, cloudTrialTelemetryEventSchema, migrateCloudTrialAgentsSchema, onboardingTelemetryEventSchema } from "@paperclipai/shared";
|
||||
import { z } from "zod";
|
||||
import { getHiddenSettings } from "../services/settings-visibility.js";
|
||||
import {
|
||||
@@ -1551,6 +1551,7 @@ const BOARD_ONLY_OPERATIONS = new Set([
|
||||
"GET /api/companies/{companyId}/cloud-inference/status",
|
||||
"POST /api/companies/{companyId}/cloud-inference/migrate",
|
||||
"POST /api/companies/{companyId}/cloud-inference/telemetry",
|
||||
"POST /api/onboarding/telemetry",
|
||||
"GET /api/companies",
|
||||
"POST /api/companies",
|
||||
"GET /api/companies/stats",
|
||||
@@ -2255,6 +2256,24 @@ registry.registerPath({
|
||||
},
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/api/onboarding/telemetry",
|
||||
tags: ["cloud"],
|
||||
summary: "Record server-side onboarding funnel telemetry",
|
||||
description:
|
||||
"Requires an authenticated board session (and company access when companyId is supplied). Validates strict allowlisted event fields and forwards Cloud-only PostHog funnel events server-side. Sets X-Paperclip-Telemetry-Delivered to 1 when direct PostHog delivery is active, or 0 otherwise.",
|
||||
request: {
|
||||
body: jsonBody(onboardingTelemetryEventSchema),
|
||||
},
|
||||
responses: {
|
||||
204: { description: "Accepted" },
|
||||
400: r.badRequest,
|
||||
403: r.forbidden,
|
||||
429: { description: "Rate limit exceeded" },
|
||||
},
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/companies",
|
||||
|
||||
@@ -290,7 +290,7 @@
|
||||
"packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d",
|
||||
"packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca",
|
||||
"packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699",
|
||||
"packages/shared/src/index.ts": "98149289a57cc0fd6738bbb3c12e06eb00c86988",
|
||||
"packages/shared/src/index.ts": "776afee882c64d1eaa5736b8a971a521232c02e8",
|
||||
"packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca",
|
||||
"packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075",
|
||||
"packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9",
|
||||
@@ -327,6 +327,7 @@
|
||||
"packages/shared/src/node-version.ts": "9a7766a8324122ce41738918bb0125398b9657e1",
|
||||
"packages/shared/src/oauth-endpoint-url.test.ts": "7f7ad634b3de7f25513e6c8b6426e1285d079e12",
|
||||
"packages/shared/src/oauth-endpoint-url.ts": "5ea73648dc5df103881e40e8ed920e38d901760a",
|
||||
"packages/shared/src/onboarding-telemetry.ts": "758da7421779d5ca20e83ac7222cc8c67714f278",
|
||||
"packages/shared/src/openrouter-attribution.test.ts": "ddc980f9d06fac708d02dcef8a8962e9887d6854",
|
||||
"packages/shared/src/openrouter-attribution.ts": "b77e887721cbf6bd882004f07df2405b6e58e52c",
|
||||
"packages/shared/src/paperclip-peer.test.ts": "304c9db3bb82871834f4e8970d334cb21bb9de7a",
|
||||
|
||||
@@ -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