Files
PaperClipAI/ui/src/pages/AgentChat.tsx
T
Dotta d128e2db6f 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
2026-11-24 14:24:37 -06:00

156 lines
7.3 KiB
TypeScript

import { useCallback, useEffect, useRef, useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { agentChatsApi } from "@/api/agentChats";
import { agentsApi } from "@/api/agents";
import { authApi } from "@/api/auth";
import { QueryErrorState, useQueryView } from "@/components/QueryView";
import { useCompany } from "@/context/CompanyContext";
import { useAgentChatEnabled } from "@/hooks/useAgentChatEnabled";
import { recordAgentChatVisit } from "@/lib/recent-agent-chats";
import { queryKeys } from "@/lib/queryKeys";
import { Link, useParams } from "@/lib/router";
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() {
const { agentRef = "" } = useParams<{ agentRef: string }>();
const { selectedCompanyId } = useCompany();
const { enabled, loaded } = useAgentChatEnabled();
const client = useQueryClient();
const agents = useQuery({
queryKey: queryKeys.agents.list(selectedCompanyId!),
queryFn: () => agentsApi.list(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const session = useQuery({
queryKey: queryKeys.auth.session,
queryFn: () => authApi.getSession(),
});
const userId =
session.data?.user?.id ?? session.data?.session?.userId ?? null;
const agentsView = useQueryView(agents);
const rosterAgent = agents.data?.find(
(item) => item.id === agentRef || agentRouteRef(item) === agentRef,
);
const historyAgent = useQuery({
queryKey: queryKeys.agents.detail(agentRef),
queryFn: () => agentsApi.get(agentRef, selectedCompanyId!),
enabled: enabled && !!selectedCompanyId && (agentsView.kind === "ready" || agentsView.kind === "stale")
&& !rosterAgent && isUuidLike(agentRef),
});
const agent = rosterAgent ?? (historyAgent.data?.companyId === selectedCompanyId ? historyAgent.data : undefined);
const chatKey = queryKeys.agentChats.detail(selectedCompanyId, userId, agent?.id);
const chat = useQuery({
queryKey: chatKey,
queryFn: () => agentChatsApi.get(selectedCompanyId!, agent!.id),
initialData: () => enabled && agent && session.isSuccess
? client.getQueryData<Issue[]>(queryKeys.agentChats.list(selectedCompanyId, userId))
?.find(issue => issue.companyId === selectedCompanyId && issue.conversationAgentId === agent?.id)
: undefined,
initialDataUpdatedAt: () => {
const state = client.getQueryState(queryKeys.agentChats.list(selectedCompanyId, userId));
return state?.isInvalidated ? 0 : state?.dataUpdatedAt;
},
enabled: enabled && !!agent && session.isFetched,
});
const sessionView = useQueryView(session);
const historyView = useQueryView(historyAgent);
const chatView = useQueryView(chat);
const creating = useRef<Promise<Issue> | null>(null);
const [readyIssueId, setReadyIssueId] = useState<string | null>(null);
const [greetingError, setGreetingError] = useState<string | null>(null);
const [greetingAttempt, setGreetingAttempt] = useState(0);
const onReady = useCallback(() => setReadyIssueId(chat.data?.id ?? null), [chat.data?.id]);
useEffect(() => {
setGreetingError(null);
if (!enabled || !agent || !selectedCompanyId || !session.isSuccess
|| readyIssueId !== chat.data?.id || chat.data?.originKind !== "onboarding_chat") return;
let cancelled = false;
const cancelPaint = afterVisibleConversationPaint(() => {
void agentChatsApi.greet(selectedCompanyId, agent.id).then(() => {
if (!cancelled) void client.invalidateQueries({ queryKey: queryKeys.issues.detail(chat.data!.id) });
}).catch(error => {
if (!cancelled) {
captureOnboardingStepFailed({ step: "launch", reason: "greeting_failed" });
setGreetingError(error instanceof Error ? error.message : "The welcome could not start.");
}
});
});
return () => { cancelled = true; cancelPaint(); };
}, [enabled, agent?.id, selectedCompanyId, userId, session.isSuccess, readyIssueId, chat.data?.id, chat.data?.originKind, greetingAttempt, client]);
useEffect(() => {
creating.current = null;
}, [selectedCompanyId, userId, agent?.id]);
useEffect(() => {
if (enabled && agent && session.isSuccess && chat.isSuccess)
recordAgentChatVisit(agent.companyId, userId, agent.id, chat.data?.id ?? null);
}, [enabled, agent?.id, agent?.companyId, userId, session.isSuccess, chat.isSuccess, chat.data?.id]);
const ensureIssue = useCallback(async () => {
if (!agent || !selectedCompanyId) throw new Error("Agent not found");
if (chat.data) return chat.data;
const promise = (creating.current ??= agentChatsApi.ensure(
selectedCompanyId,
agent.id,
));
try {
const issue = await promise;
client.setQueryData(queryKeys.issues.detail(issue.id), issue);
client.setQueryData(chatKey, issue);
void client.invalidateQueries({ queryKey: queryKeys.agentChats.list(selectedCompanyId, userId) });
return issue;
} catch (error) {
creating.current = null;
throw error;
}
}, [agent, selectedCompanyId, chat.data, client, userId]);
// An outage before anything loaded keeps the quiet loading copy; loaded
// data renders through it.
const reconnecting = agentsView.kind === "reconnecting" || sessionView.kind === "reconnecting"
|| chatView.kind === "reconnecting" || (!rosterAgent && historyView.kind === "reconnecting");
if (!loaded || agents.isPending || session.isPending || historyAgent.isFetching && !agent || reconnecting)
return (
<p className="text-sm text-muted-foreground">Loading conversation…</p>
);
if (!enabled && !chat.data)
return (
<p className="text-sm text-muted-foreground">
Agent Chat is disabled for this instance. An administrator can enable it in{" "}
<Link className="underline underline-offset-4" to="/company/settings/instance/experimental#experimental-enableAgentChat">Experimental settings</Link>.
{" "}Your workspace preference does not change Chat availability. Existing history remains available through task links.
</p>
);
const failed = [agentsView, chatView, ...(rosterAgent ? [] : [historyView])].find((view) => view.kind === "error");
if (failed)
return (
<QueryErrorState
size="page"
error={failed.error}
action="load this conversation"
onRetry={failed.retry}
retrying={failed.isFetching}
/>
);
if (!agent)
return <p className="text-sm text-destructive">Agent not found.</p>;
if (chat.isPending)
return (
<p className="text-sm text-muted-foreground">Loading conversation…</p>
);
return (
<>
{greetingError && <div role="alert" className="flex items-center gap-2 text-sm text-destructive">
<span>{greetingError}</span>
<Button variant="outline" size="sm" onClick={() => setGreetingAttempt(attempt => attempt + 1)}>Retry welcome</Button>
</div>}
<TaskDetailSurface
key={`${agent.id}:${userId}`}
conversation={{ agent, issue: chat.data ?? null, ensureIssue, onReady }}
/>
</>
);
}