diff --git a/ui/src/components/AgentConfigForm.tsx b/ui/src/components/AgentConfigForm.tsx index b6d4b3440c4..37debe807ea 100644 --- a/ui/src/components/AgentConfigForm.tsx +++ b/ui/src/components/AgentConfigForm.tsx @@ -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(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(() => { diff --git a/ui/src/components/OnboardingWizard.tsx b/ui/src/components/OnboardingWizard.tsx index 1027fa2fd79..410b6801ff9 100644 --- a/ui/src/components/OnboardingWizard.tsx +++ b/ui/src/components/OnboardingWizard.tsx @@ -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 { 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); diff --git a/ui/src/lib/analytics/onboarding-analytics.test.tsx b/ui/src/lib/analytics/onboarding-analytics.test.tsx index 37abe17685c..441ab949d93 100644 --- a/ui/src/lib/analytics/onboarding-analytics.test.tsx +++ b/ui/src/lib/analytics/onboarding-analytics.test.tsx @@ -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); + }); }); diff --git a/ui/src/lib/analytics/onboarding-analytics.ts b/ui/src/lib/analytics/onboarding-analytics.ts index 271a732aaff..542ed444777 100644 --- a/ui/src/lib/analytics/onboarding-analytics.ts +++ b/ui/src/lib/analytics/onboarding-analytics.ts @@ -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 = { 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 = { + 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; diff --git a/ui/src/lib/onboarding-connection-test.ts b/ui/src/lib/onboarding-connection-test.ts index a3f4fdbf5b2..4b00d4df2b2 100644 --- a/ui/src/lib/onboarding-connection-test.ts +++ b/ui/src/lib/onboarding-connection-test.ts @@ -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( operation: (signal: AbortSignal) => Promise, diff --git a/ui/src/pages/AgentChat.tsx b/ui/src/pages/AgentChat.tsx index 329596bfb0d..4c59283d009 100644 --- a/ui/src/pages/AgentChat.tsx +++ b/ui/src/pages/AgentChat.tsx @@ -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(); }; diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index 66135638a4a..9c4b8cbdd3b 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -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); }