Commit Graph
3 Commits
Author SHA1 Message Date
Michael NguyenandClaude fc09515c7e Emit Cloud chat.started when a chat with an agent starts (#23558)
<!-- claude-projects-attribution: {"github_login":"nguyenm7"} -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Cloud measures activation with a funnel: account created,
org named, agent named, model connected, chat launched, first agent run
succeeded, first task created
> - `model.connected`, `agent.task_run` and `task.created` come from the
server, but "chat launched" comes only from the browser
(`onboarding_step_completed` with `step=launch`)
> - `task.created` skips chats on purpose, so a person who only chats
with their agent has no server-side step after "first agent run"
> - #23403 added a Cloud-only direct PostHog path
(`trackCloudPostHogEvent`) for onboarding events that must not depend on
the browser
> - This pull request uses that path to emit `chat.started` when the
chat owner's first message or first question-card answer commits
> - The benefit is a server-side "chat started" step that counts a real
action by the person, once per chat, whichever way they reached the chat

## Linked Issues or Issue Description

Refs #23403

**What existing behavior does this improve?**
Server-side activation funnels on Paperclip Cloud.

**Current behavior**
The only "chat launched" signal is the browser `launch` step. Browser
events can be lost (wizard skipped or resumed, navigation, ad blockers
on older builds). On the server, a chat creates an issue but
`emitTaskCreatedAfterCommit` returns early for it, so no event records
that the chat started.

**Proposed behavior**
When the chat owner's first turn commits (their first message, or their
first answer to a question card such as the onboarding welcome card),
the server emits the Cloud-only event `chat.started` with `surface`
(`onboarding_chat` | `agent_chat`) and `agent_id`. Creating or preparing
a chat emits nothing, because onboarding prepares the chat before the
person clicks Launch. The Launch click itself is already relayed
server-side as `onboarding_step_completed` (`step=launch`).

**Reason and benefit**
Funnel steps should come from real product actions that the server
records. With `chat.started`, a funnel can count "chat launched" from
the server and see people who chat but never create a task.

**Breaking changes**
None. The event is new and is Cloud-only.

## What Changed

- `server/src/services/product-telemetry.ts`: add `CHAT_STARTED_EVENT`
and `emitChatStartedIfFirstOwnerTurn`. It runs inside the transaction
that wrote the person's turn and locks the chat's issue row. It checks
that the actor is the chat owner (not an agent, run, or system actor),
and that the owner has no other message and no other answered question
card in the chat. Cancelled or skipped cards do not count. Then it emits
`chat.started` through `trackCloudPostHogEvent` after commit.
- Callers: `addComment` (`issues.ts`), `answerQuestions`
(`issue-thread-interactions.ts`), both headless comment paths
(`headless-comment-group-commit.ts` and the serialized insert in
`routes/headless-channels-schemas.ts`), and the headless one-line
resolve (`headless-events-schedules-interactions.ts`).
- `server/src/__tests__/chat-started-telemetry.test.ts`: unit tests for
the first turn, both surfaces, and every case that must not emit.
- `server/src/__tests__/product-telemetry.test.ts`: embedded-Postgres
tests. Chat creation and system or other-person messages emit nothing.
The owner's first message emits once. A first message after a cancelled
card still emits. A rolled-back first message and a task comment emit
nothing.
- `docs/api/onboarding-telemetry.md`: document the server-emitted
`chat.started` event.

## Verification

- `npx vitest run server/src/__tests__/chat-started-telemetry.test.ts`:
10 passed (helper unit tests).
- `pnpm --filter @paperclipai/server typecheck`: passed.
- The cases in `product-telemetry.test.ts` need embedded Postgres, which
could not start in my environment (it runs as root). CI runs them.

## Risks

- Low. The event is fire-and-forget after commit, inside a `try`. It
does nothing on self-hosted installs, when `PAPERCLIP_POSTHOG_DIRECT=0`,
or when the PostHog environment is not set.
- One event per chat: the check runs under the chat's issue row lock,
and a rolled-back write emits nothing. `/new` in an existing chat does
not emit again.
- Two extra indexed reads run on a person's chat message or answer, and
only on chats.

### Open questions for reviewers

1. **Consent.** Like `model.connected` and the #23403 relay, this server
event is not gated by the browser cookie banner. This PR does not add a
consent check. The only switch is the existing
`PAPERCLIP_POSTHOG_DIRECT=0`. If people who decline cookies must be
excluded from server-side product events, that should be one rule for
all Cloud direct events, not a rule in this PR.
2. **New name or existing name.** This PR adds a new name,
`chat.started`, instead of emitting `onboarding_step_completed`
(`step=launch`) from the server. A new name keeps the browser and server
signals separate, so the two funnels can be compared and the existing
insights do not double count. The other choice is to emit the existing
name with a `source: server` property. Please say which one you prefer.

Not in this PR: "Agent named" has no clean server moment (the setup
agent is saved with a default name before the person names it, and
`agent.created` fires at launch), and `agent.task_run` still does not
say whether a run was a chat reply or a task. That needs a new
registered dimension in the telemetry contract, so it is a follow-up.

## Model Used

Claude Code (Anthropic Claude, agentic coding with tool use and code
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)
- [ ] 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

https://claude.ai/code/session_01KmUZthscGtSrd1KaWnwzWm

---
_Generated by [Claude Code](https://claude.ai/code)_

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-12-02 20:20:25 -08:00
scotttong b0f682b66b Measure when users see a reply to their onboarding chat input (#23574) 2026-12-02 18:03:08 -08:00
Dotta c0edaa21a3 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
2026-12-01 21:17:54 +00:00