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);
@@ -3,7 +3,9 @@
import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { BrowserAnalyticsConfig } from "@paperclipai/shared";
import { ADAPTER_AUTH_MISSING_CHECK_CODE, type BrowserAnalyticsConfig } from "@paperclipai/shared";
import { blocksAgentCreate } from "@/lib/onboarding-connection-test";
import { isReportableAdapterLoginFailure } from "@/components/AgentConfigForm";
import {
captureProductAnalyticsEvent,
resetProductAnalyticsForTest,
@@ -11,7 +13,12 @@ import {
syncProductAnalytics,
type ProductAnalyticsClient,
} from "./product-analytics";
import { captureOnboardingStepCompleted, useOnboardingAnalytics } from "./onboarding-analytics";
import {
captureAgentChatMessageSent,
captureOnboardingStepCompleted,
captureOnboardingStepFailed,
useOnboardingAnalytics,
} from "./onboarding-analytics";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -257,4 +264,79 @@ describe("onboarding funnel events", () => {
act(() => wizard.result.current.dismissed(4));
expect(client.capture).not.toHaveBeenCalled();
});
it("captures structured onboarding failures and drops unsafe provider strings", async () => {
await startAnalytics();
captureOnboardingStepFailed({
step: "connect_model",
reason: "api_key_save_failed",
provider: "Anthropic",
method: "api_key",
});
captureOnboardingStepFailed({
step: "connect_model",
reason: "subscription_login_failed",
provider: "secret token=sk-123",
method: "subscription",
});
captureOnboardingStepFailed({
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" }],
]);
});
it("captures agent chat messages with onboarding_chat vs agent_chat surface only", async () => {
await startAnalytics();
captureAgentChatMessageSent("onboarding_chat");
captureAgentChatMessageSent("agent_chat");
expect(captured()).toEqual([
["agent_chat_message_sent", { surface: "onboarding_chat" }],
["agent_chat_message_sent", { surface: "agent_chat" }],
]);
});
it("blocksAgentCreate flags fail results and warn/pass results with missing-auth checks", () => {
const base = {
adapterType: "codex_local",
testedAt: "2026-01-01T00:00:00.000Z",
};
expect(blocksAgentCreate({ ...base, status: "fail", checks: [] })).toBe(true);
expect(
blocksAgentCreate({
...base,
status: "warn",
checks: [{ code: ADAPTER_AUTH_MISSING_CHECK_CODE, level: "warn", message: "Auth required" }],
}),
).toBe(true);
expect(
blocksAgentCreate({
...base,
status: "pass",
checks: [{ code: ADAPTER_AUTH_MISSING_CHECK_CODE, level: "warn", message: "Auth required" }],
}),
).toBe(true);
expect(
blocksAgentCreate({
...base,
status: "warn",
checks: [{ code: "other_warning", level: "warn", message: "Non-blocking warning" }],
}),
).toBe(false);
expect(blocksAgentCreate({ ...base, status: "pass", checks: [] })).toBe(false);
});
it("isReportableAdapterLoginFailure covers start/poll/timeout failures and excludes cancellation and retries", () => {
expect(isReportableAdapterLoginFailure({ active: true, retrying: false, status: "failed", hasFailure: true })).toBe(true);
expect(isReportableAdapterLoginFailure({ active: true, retrying: false, status: "timed_out", hasFailure: true })).toBe(true);
expect(isReportableAdapterLoginFailure({ active: true, retrying: false, status: undefined, hasFailure: true })).toBe(true);
expect(isReportableAdapterLoginFailure({ active: true, retrying: false, status: "cancelled", hasFailure: true })).toBe(false);
expect(isReportableAdapterLoginFailure({ active: true, retrying: true, status: "failed", hasFailure: true })).toBe(false);
expect(isReportableAdapterLoginFailure({ active: false, retrying: false, status: "failed", hasFailure: true })).toBe(false);
expect(isReportableAdapterLoginFailure({ active: true, retrying: false, status: "waiting_for_user", hasFailure: false })).toBe(false);
});
});
@@ -5,11 +5,23 @@ 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 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";
const SAFE_PROVIDER_SLUG = /^[a-z0-9_-]{1,32}$/;
const WIZARD_STEPS: Record<number, OnboardingAnalyticsStep> = {
3: "create_agent",
@@ -32,6 +44,26 @@ export function captureOnboardingStepCompleted(step: OnboardingAnalyticsStep, ou
captureProductAnalyticsEvent(ONBOARDING_ANALYTICS_EVENTS.stepCompleted, stepProperties(step, outcome));
}
export function captureOnboardingStepFailed(input: {
step: OnboardingAnalyticsStep;
reason: OnboardingFailureReason;
provider?: string | null;
method?: "subscription" | "api_key";
}) {
const properties: Record<string, string> = {
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);
}
export function captureAgentChatMessageSent(surface: AgentChatSurface) {
captureProductAnalyticsEvent(ONBOARDING_ANALYTICS_EVENTS.chatMessageSent, { surface });
}
export function useOnboardingAnalytics(input: {
open: boolean;
step: number;
+12
View File
@@ -1,5 +1,17 @@
import { ADAPTER_AUTH_MISSING_CHECK_CODE, type AdapterEnvironmentTestResult } from "@paperclipai/shared";
export const ONBOARDING_CONNECTION_TEST_TIMEOUT_MS = 120_000;
/**
* Whether an adapter environment test result blocks creating the onboarding
* agent. True on `status === "fail"` and on `warn`/`pass` results carrying
* `ADAPTER_AUTH_MISSING_CHECK_CODE`.
*/
export function blocksAgentCreate(result: AdapterEnvironmentTestResult): boolean {
if (result.status === "fail") return true;
return result.checks.some((check) => check.code === ADAPTER_AUTH_MISSING_CHECK_CODE);
}
/** Bound the entire check, including environment preparation and response parsing. */
export async function runOnboardingConnectionTest<T>(
operation: (signal: AbortSignal) => Promise<T>,
+5 -1
View File
@@ -13,6 +13,7 @@ import { agentRouteRef } from "@/lib/utils";
import { TaskDetailSurface } from "./IssueDetail";
import { isUuidLike, type Issue } from "@paperclipai/shared";
import { afterVisibleConversationPaint } from "@/lib/onboarding-chat";
import { captureOnboardingStepFailed } from "@/lib/analytics/onboarding-analytics";
import { Button } from "@/components/ui/button";
export function AgentChat() {
@@ -73,7 +74,10 @@ export function AgentChat() {
void agentChatsApi.greet(selectedCompanyId, agent.id).then(() => {
if (!cancelled) void client.invalidateQueries({ queryKey: queryKeys.issues.detail(chat.data!.id) });
}).catch(error => {
if (!cancelled) setGreetingError(error instanceof Error ? error.message : "The welcome could not start.");
if (!cancelled) {
captureOnboardingStepFailed({ step: "launch", reason: "greeting_failed" });
setGreetingError(error instanceof Error ? error.message : "The welcome could not start.");
}
});
});
return () => { cancelled = true; cancelPaint(); };
+6
View File
@@ -31,6 +31,7 @@ import { mergeComposerRunSettings, type ComposerRunSettings } from "@/components
import { AgentIdentity } from "@/components/AgentIdentity";
import { clearLegacyChatMessageRequests } from "@/lib/chat-message-request";
import { agentChatDraft } from "@/lib/agent-chat-draft";
import { captureAgentChatMessageSent } from "@/lib/analytics/onboarding-analytics";
import { trackRecentProject } from "@/lib/recent-projects";
import { ExecutionBlockerNotice } from "../components/ExecutionBlockerNotice";
import type { TaskComposerPause } from "../components/task-chat/TaskChatPausedTakeover";
@@ -5264,6 +5265,11 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
queryKey: queryKeys.issues.queuedComments(issueId ?? comment.issueId),
});
}
if (issue?.conversationAgentId) {
captureAgentChatMessageSent(
issue.originKind === "onboarding_chat" ? "onboarding_chat" : "agent_chat",
);
}
if (context?.optimisticCommentId) {
commentRenderKeys.current.set(comment.id, context.optimisticCommentId);
}