feat(analytics): track onboarding step failures and agent chat sends (#22814)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - On Paperclip Cloud, browser analytics tracks onboarding wizard steps
through PostHog
> - Today, failures on the model connection step and user replies in the
onboarding chat emit no browser analytics events
> - Without those events, teams cannot tell whether users hit an error
during model setup or leave after the automatic welcome greeting
> - This pull request adds structured enum-only browser events for
onboarding step failures and agent chat message sends
> - The benefit is clear visibility into onboarding drop-offs and
post-launch engagement without sending customer text or raw error
strings

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Cloud browser onboarding analytics in
`ui/src/lib/analytics/onboarding-analytics.ts`,
`ui/src/components/OnboardingWizard.tsx`, `ui/src/pages/AgentChat.tsx`,
and `ui/src/pages/IssueDetail.tsx`.

**Subsystem affected**
ui/ — React + Vite board UI

**Current behavior**
The onboarding wizard emits `onboarding_opened`,
`onboarding_step_viewed`, `onboarding_step_completed`, and
`onboarding_dismissed`. Failures during API key storage, subscription
sign-in, adapter environment tests, agent creation, and onboarding
welcome greeting emit no failure event. Onboarding also launches into
Agent Chat (where server-side `task.created` skips conversations), so
user replies after launch emit no distinct engagement event.

**Proposed behavior**
Add two browser analytics events on Cloud (inert on self-hosted installs
and gated on existing analytics consent):
- `onboarding_step_failed` with bounded `step`, `reason`, sanitized
`provider`, and `method` fields.
- `agent_chat_message_sent` with `surface` (`onboarding_chat` or
`agent_chat`).

**Reason and benefit**
Teams can separate actual setup errors (bad API key, failed OAuth,
failed environment test, failed greeting) from user abandonment on the
model-connect step, and separate passive greeting-only visits from
active replies in Agent Chat.

**Breaking changes**
None. Existing event names and properties are unchanged, and no
`PAPERCLIP_EVENTS` server event names are captured from the browser.

## What Changed

- Add `onboarding_step_failed` (`captureOnboardingStepFailed`) and
`agent_chat_message_sent` (`captureAgentChatMessageSent`) to
`ui/src/lib/analytics/onboarding-analytics.ts`, with bounded reason
enums and provider slug validation.
- Wire `captureOnboardingStepFailed` into the failure paths in
`ui/src/components/OnboardingWizard.tsx` (API key save, subscription
sign-in failure, environment test failure, agent creation failure, chat
launch failure) and `ui/src/pages/AgentChat.tsx` (onboarding greeting
failure).
- Wire `captureAgentChatMessageSent` in `ui/src/pages/IssueDetail.tsx`
when a user posts a comment to an Agent Chat conversation.
- Add unit tests in `ui/src/lib/analytics/onboarding-analytics.test.tsx`
covering failure capture, unsafe provider filtering, and chat surface
tagging.

## Verification

- `pnpm --filter @paperclipai/ui typecheck` — passed after rebase onto
`origin/master`.
- `pnpm --filter @paperclipai/ui exec vitest run
src/lib/analytics/onboarding-analytics.test.tsx
src/lib/analytics/product-analytics-events.test.ts
src/lib/analytics/product-analytics.test.ts` — 3 test files, 28/28 tests
passed (including the event-ownership test proving no `PAPERCLIP_EVENTS`
are captured from UI code).
- Prior to rebase, ran the full `ui/src/lib/analytics/` directory — 7
test files, 255/255 tests passed.

## Risks

- Low risk. Browser product analytics stays completely inert on
self-hosted installs and respects Cloud consent gates. No message
content, raw error text, credentials, or PII leave the browser.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Google Gemini (high reasoning mode) in Antigravity, with file editing,
git, and shell tool use.

## 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:
Dotta authored and GitHub committed 2026-11-24 14:24:37 -06:00
1 parent 84e39b7096
commit d128e2db6f
7 files changed
+243 -23

No files matched your search

+50
View File
@@ -2611,6 +2611,10 @@ export type AdapterLoginPanelProps = AdapterLoginDescriptor & {
// the completion failed, or the session failed or ran out of time. The pair
// of `onCodeSubmitted`, so a caller that showed work can stop showing it.
onSubmitFailed?: () => void;
// Fires once per failed sign-in attempt across both displayed-code and
// submitted-code panels (start failure, poll error, session failure, or
// timeout), excluding user cancellations and in-flight retries.
onLoginFailed?: () => void;
onOpenAuthorization?: () => void;
onSubmitReady?: (submit: (() => void) | null) => void;
onRetryReady?: (retry: (() => void) | null) => void;
@@ -2644,6 +2648,30 @@ function adapterLoginTitle(adapterType: string): string {
return provider ? `Sign in to ${provider}` : "Sign in to the environment";
}
export function isReportableAdapterLoginFailure(input: {
active: boolean;
retrying: boolean;
status: AdapterAuthSessionStatus | null | undefined;
hasFailure: boolean;
}): boolean {
return input.active && !input.retrying && input.status !== "cancelled" && input.hasFailure;
}
function useReportLoginFailureOnce(failed: boolean, onLoginFailed?: () => void) {
const onLoginFailedRef = useRef(onLoginFailed);
onLoginFailedRef.current = onLoginFailed;
const reportedFailureRef = useRef(false);
useEffect(() => {
if (!failed) {
reportedFailureRef.current = false;
return;
}
if (reportedFailureRef.current) return;
reportedFailureRef.current = true;
onLoginFailedRef.current?.();
}, [failed]);
}
export function AdapterLoginPanel(props: AdapterLoginPanelProps) {
const getCapabilities = useAdapterCapabilities();
const Panel = getCapabilities(props.adapterType).login?.panelMode === "submitted_browser_code"
@@ -2673,6 +2701,7 @@ function DisplayedCodeLoginPanel({
onPromptReady,
onOpenAuthorization,
onRetryReady,
onLoginFailed,
}: AdapterLoginPanelProps) {
const [sessionId, setSessionId] = useState<string | null>(null);
const automaticComputer = Boolean(requiresAgent && !agentId && aiConnection);
@@ -2994,6 +3023,16 @@ function DisplayedCodeLoginPanel({
return () => onRetryReadyRef.current?.(null);
}, [retryReady]);
useReportLoginFailureOnce(
isReportableAdapterLoginFailure({
active: loginActive,
retrying: retrying || retryLogin.isPending,
status,
hasFailure: Boolean(startError || (isTerminal && status !== "authenticated")),
}),
onLoginFailed,
);
if (chrome === "onboarding") {
const failure = !retryLogin.isPending && (startError || failed)
? status === "timed_out" ? "expired" : "failed"
@@ -3219,6 +3258,7 @@ function SubmittedBrowserCodeLoginPanel({
onConnected,
onCodeSubmitted,
onSubmitFailed,
onLoginFailed,
chrome = "panel",
aiConnection,
onPromptReady,
@@ -3741,6 +3781,16 @@ function SubmittedBrowserCodeLoginPanel({
onSubmitFailedRef.current?.();
}, [codeSubmitted, startError, isFailure, timedOut]);
useReportLoginFailureOnce(
isReportableAdapterLoginFailure({
active: loginActive,
retrying,
status,
hasFailure: Boolean(startError || isFailure || timedOut),
}),
onLoginFailed,
);
const onPromptReadyRef = useRef(onPromptReady);
onPromptReadyRef.current = onPromptReady;
useEffect(() => {
+54 -20
View File
@@ -3,7 +3,7 @@ import { cancelAdapterLoginSession, cancelPendingAdapterLogin, matchesAdapterLog
import { useQueryView } from "@/components/QueryView";
import type { AgentRunner, AgentRunnerChoice } from "@paperclipai/shared";
import { needsClaudeSetupQualification, qualifyClaudeSetup } from "../lib/qualify-claude-setup";
import { runOnboardingConnectionTest } from "../lib/onboarding-connection-test";
import { blocksAgentCreate, runOnboardingConnectionTest } from "../lib/onboarding-connection-test";
import { agentHarnessType, agentRunner } from "@paperclipai/shared";
import { adaptersApi, type AdapterInfo } from "../api/adapters";
import { healthApi } from "@/api/health";
@@ -140,7 +140,11 @@ import { OnboardingHeading } from "./onboarding/OnboardingPrimitives";
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 { captureOnboardingStepCompleted, useOnboardingAnalytics } from "@/lib/analytics/onboarding-analytics";
import {
captureOnboardingStepCompleted,
captureOnboardingStepFailed,
useOnboardingAnalytics,
} from "@/lib/analytics/onboarding-analytics";
import {
ArrowLeft,
ArrowRight,
@@ -165,19 +169,6 @@ function restoreOnboardingAdapterType(savedAdapterType: unknown, provider?: unkn
: "claude_local";
}
/**
* True when an adapter-test result blocks a hire. A `fail` status always
* blocks. A `warn` or a `pass` status blocks too when a check reports
* `ADAPTER_AUTH_MISSING_CHECK_CODE`. That check means the agent has no
* working authentication, so it cannot run. A `warn` with no such check
* still lets the hire proceed. The wizard widened the gate for missing
* authentication only, not for every other warning.
*/
function blocksAgentCreate(result: AdapterEnvironmentTestResult): boolean {
if (result.status === "fail") return true;
return result.checks.some((check) => check.code === ADAPTER_AUTH_MISSING_CHECK_CODE);
}
/** True when `value` is a plain object, so callers can spread it as env config. */
function isEnvRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -1912,6 +1903,7 @@ function OnboardingWizardInner({
navigate(`${prefix ? `/${prefix}` : ""}/chats/${agentId}`);
} catch (err) {
captureOnboardingStepCompleted("launch", "failed");
captureOnboardingStepFailed({ step: "launch", reason: "launch_failed" });
setError(err instanceof Error ? err.message : "Failed to open your chat. Please try again.");
} finally {
setLoading(false);
@@ -1958,11 +1950,19 @@ function OnboardingWizardInner({
apiKeySecretRef.current = { key, companyId, envKey, binding: legacyStored.binding };
return true;
} catch (err) {
if (isCurrent()) setError(
err instanceof Error
? `Could not store the API key: ${describeError(err).body}`
: "Could not store the API key.",
);
if (isCurrent()) {
captureOnboardingStepFailed({
step: "connect_model",
reason: "api_key_save_failed",
provider: managedProvider ?? adapterType,
method: "api_key",
});
setError(
err instanceof Error
? `Could not store the API key: ${describeError(err).body}`
: "Could not store the API key.",
);
}
return false;
}
}
@@ -2184,6 +2184,12 @@ function OnboardingWizardInner({
managedSandboxOnly = experimentalSettings?.enableManagedSandboxOnly === true;
} catch {
if (!testIsCurrent()) return null;
captureOnboardingStepFailed({
step: "connect_model",
reason: "environment_test_failed",
provider: managedProvider ?? adapterType,
method: credentialMode === "api" ? "api_key" : "subscription",
});
setAdapterEnvError(
"Could not load environment settings to determine which environment to test in. Retry the test.",
);
@@ -2274,12 +2280,26 @@ function OnboardingWizardInner({
{ signal },
);
if (!testIsCurrent()) return null;
if (blocksAgentCreate(result)) {
captureOnboardingStepFailed({
step: "connect_model",
reason: "environment_test_failed",
provider: managedProvider ?? adapterType,
method: credentialMode === "api" ? "api_key" : "subscription",
});
}
setAdapterEnvResult(result);
adapterEnvResultAppliedStoredLoginRef.current = appliedStoredClaudeLoginBinding;
return result;
});
} catch (err) {
if (!selectionIsCurrent()) return null;
captureOnboardingStepFailed({
step: "connect_model",
reason: "environment_test_failed",
provider: managedProvider ?? adapterType,
method: credentialMode === "api" ? "api_key" : "subscription",
});
adapterEnvErrorSelectionRef.current = selection || null;
setAdapterEnvError(
err instanceof Error ? err.message : "Adapter environment test failed"
@@ -2600,6 +2620,12 @@ function OnboardingWizardInner({
setStep(5);
} catch (err) {
if (!isCurrent()) return;
captureOnboardingStepFailed({
step: "connect_model",
reason: "agent_create_failed",
provider: managedProvider ?? adapterType,
method: credentialMode === "api" ? "api_key" : "subscription",
});
setError(err instanceof Error ? err.message : "Failed to create agent");
} finally {
if (hiringAgentRef.current === attempt) hiringAgentRef.current = null;
@@ -3248,6 +3274,14 @@ function OnboardingWizardInner({
phaseBeforeSubmitRef.current === "ready" ? "ready" : "waiting",
);
}}
onLoginFailed={() => {
captureOnboardingStepFailed({
step: "connect_model",
reason: "subscription_login_failed",
provider: managedProvider ?? adapterType,
method: "subscription",
});
}}
onConnected={(sessionId) => {
if (managedSubscriptionProvider) managedSubscriptionRef.current = { companyId: createdCompanyId, binding: { provider: managedSubscriptionProvider, method: "subscription", mode: "responsible_user" }, sessionId };
setConnectAuthUrl(null);