From 554227d9263ed4fb1809c050313583bc12b8cae4 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Mon, 30 Nov 2026 13:56:12 -0800 Subject: [PATCH] fix(analytics): send queued product events after consent (#23328) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Hosted workspaces record browser product events for the onboarding funnel. > - The wizard can open before a visitor accepts browser analytics. > - The capture path discarded those events and did not send them after Accept. > - This pull request holds pending events in page memory until the visitor accepts. > - The funnel can then retain the original event order and times. ## Linked Issues or Issue Description **What happened?** A visitor could open onboarding, complete steps, and then accept analytics. The earlier browser events were missing. The funnel could show server events such as workspace entry without the later onboarding events, even when the visitor used the wizard. **Expected behavior** Hold structured product events while consent is pending. Send them once after Accept, with their original order and timestamps. Discard them after Decline or a change of user. Do not load PostHog before consent. **Steps to reproduce** 1. Open a hosted workspace that requires analytics consent, with no stored choice. 2. Open onboarding and complete a step before choosing Accept. 3. Choose Accept. 4. Confirm that the opening and step events reach the analytics client once, with their original timestamps. **Paperclip version or commit** The fix is based on master at `630cf042302`. The tested PR revision is `46df54b9ede8e5757f7af1a9d41b3c3593fe3430`. **Deployment mode** Hosted workspace browser analytics. The regression runs locally in jsdom. Related merged work: #22186 added browser consent; #22814 added onboarding failure and chat events; #23315 enabled draft saving in the naming step. A search found no duplicate PR for this queue fix. ## What Changed - Track pending, granted, and denied consent in the browser analytics state. - Reuse the existing 50-event queue while consent is pending. Flush it on Accept, after the client is ready. - Clear pending events on Decline or a change of user. Apply user identity before sending the queue. - Add regression tests for the Accept button, onboarding events, queue limits, and user changes. Document the queue lifetime. - Remove the retired Runner support assertion that draft saving is limited to step 4. PR #23315 added saving in both naming and connect steps. Retain the other first-agent checks and the existing early-setup browser test for name persistence and draft reuse. ## Verification Environment: macOS arm64, Node.js v25.6.1, pnpm 9.15.4. Final local checks use revision `46df54b9ede8e5757f7af1a9d41b3c3593fe3430`. - The Accept-button regression failed before the fix: it expected the earlier events but received an empty capture list. - `pnpm exec vitest run --project @paperclipai/ui ui/src/lib/analytics ui/src/components/ProductAnalyticsGate.test.tsx ui/src/components/ProductAnalyticsSetting.test.tsx`: passed, 289 tests across 9 files. - `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts tests/runner-e2e/chat-catalog-domains/identity-new-company-native.test.ts`: passed, 51 tests. This suite first reproduced the stale draft-step assertion from the failed CI job. - `pnpm --filter @paperclipai/ui typecheck`: passed. - `node scripts/check-test-budget.mjs --files tests/runner-e2e/chat-catalog-domains/identity-new-company-native.test.ts ui/src/components/ProductAnalyticsGate.test.tsx ui/src/lib/analytics/onboarding-analytics.test.tsx`: passed. - `git diff origin/master...HEAD --check`: passed. - `pnpm verify`: exited 2 because `doc/cloud-browser-analytics.md` triggers broader CI coverage. Focused checks above passed; the full local suite was not run. - GitHub Actions CI: [all planned suites passed](https://github.com/paperclipai/paperclip/actions/runs/46519983330/job/142210329280) on `46df54b9ede8e5757f7af1a9d41b3c3593fe3430`, including [typecheck and release registry](https://github.com/paperclipai/paperclip/actions/runs/46519983330/job/142208788257), [build](https://github.com/paperclipai/paperclip/actions/runs/46519983330/job/142208788273), Runner support, general tests, serialized tests, and browser E2E shards. No live PostHog capture was checked. - Greptile: [5/5 on the current revision](https://github.com/paperclipai/paperclip/pull/23328#issuecomment-7292786296), with a successful check and no unresolved review threads. ## Risks - Accept now sends structured product events generated earlier in the same page visit. Nothing is sent while consent is pending. - The queue retains at most 50 events in memory. Further events are dropped until it drains. Reloading the page loses the pending queue. - This change does not record earlier page views or session replay. PostHog still loads only after consent. ## Model Used OpenAI `gpt-6.1-sol`, through the Codex harness in T3 Code, with xhigh reasoning effort and shell/code tools. The harness does not expose the context window size. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/cloud-browser-analytics.md | 13 ++- .../identity-new-company-native.test.ts | 3 +- .../components/ProductAnalyticsGate.test.tsx | 25 ++++- .../analytics/onboarding-analytics.test.tsx | 55 ++++++++++- ui/src/lib/analytics/product-analytics.ts | 91 +++++++++++-------- 5 files changed, 136 insertions(+), 51 deletions(-) diff --git a/doc/cloud-browser-analytics.md b/doc/cloud-browser-analytics.md index 4bd172a0dc5..14c0d081fdf 100644 --- a/doc/cloud-browser-analytics.md +++ b/doc/cloud-browser-analytics.md @@ -237,11 +237,14 @@ This value is used only for location, never for limits. The in-workspace onboarding wizard (`ui/src/components/OnboardingWizard.tsx`) captures four browser events through `ui/src/lib/analytics/onboarding-analytics.ts`. -They follow the same consent rules as every other browser event: without a -browser analytics config or with consent not granted, nothing is captured. -Events from before posthog-js loads wait in a short queue (at most 50) and keep -their original time. Withdrawing consent or a change of signed-in person drops -the queue. +Without a browser analytics config or after consent is declined, these events +are discarded. While the choice is pending, events wait only in page memory +in a bounded queue (at most 50); PostHog does not load and nothing is sent. +Accepting consent flushes that queue after PostHog loads, preserving event +order and original timestamps. This also covers events emitted after consent +while posthog-js is still loading. Declining consent or changing the signed-in +person drops the queue. Reloading the page loses pending events; they are +never persisted in browser storage. | Event | When | Properties | | --- | --- | --- | diff --git a/tests/runner-e2e/chat-catalog-domains/identity-new-company-native.test.ts b/tests/runner-e2e/chat-catalog-domains/identity-new-company-native.test.ts index 8b13339c9ea..386f8eb8b8d 100644 --- a/tests/runner-e2e/chat-catalog-domains/identity-new-company-native.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/identity-new-company-native.test.ts @@ -97,9 +97,8 @@ describe("actual supported route and provider contracts", () => { expect(aiRoutingModel(routing, "opencode_local", NEW_COMPANY_NATIVE_MODEL)).toBe(NEW_COMPANY_NATIVE_MODEL); expect(createAiConnectionSchema.parse({ provider: "openrouter", method: "api_key", name: "My OpenRouter", ownership: "personal", allAgents: false, agentIds: [agentId], routing, apiKey: "synthetic-private-key" })).toMatchObject({ ownership: "personal", agentIds: [agentId], allAgents: false }); }); - it("binds the original production UI draft gate and public first-agent hold/reuse", () => { + it("binds public first-agent hold/reuse", () => { const source = (file: string) => readFileSync(new URL(`../../../${file}`, import.meta.url), "utf8"); - expect(source("ui/src/components/OnboardingWizard.tsx")).toContain('const setupSnapshot = step === 4'); expect(source("ui/src/context/DialogContext.tsx")).toContain('const [onboardingOpen, setOnboardingOpen] = useState(false)'); expect(source("ui/src/components/new-agent/AgentBasicsDialog.tsx")).toContain('role: existing.length ? "general" : "ceo"'); expect(source("ui/src/components/new-agent/AgentBasicsDialog.tsx")).toContain('buildNewAgentRuntimeConfig({ heartbeatEnabled: false })'); diff --git a/ui/src/components/ProductAnalyticsGate.test.tsx b/ui/src/components/ProductAnalyticsGate.test.tsx index 892919c2701..ca3f094770a 100644 --- a/ui/src/components/ProductAnalyticsGate.test.tsx +++ b/ui/src/components/ProductAnalyticsGate.test.tsx @@ -4,7 +4,7 @@ import { act } from "react"; import { createRoot } from "react-dom/client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { resetProductAnalyticsForTest } from "@/lib/analytics/product-analytics"; +import { captureProductAnalyticsEvent, resetProductAnalyticsForTest } from "@/lib/analytics/product-analytics"; import { ANALYTICS_CONSENT_STORAGE_KEY, resetAnalyticsConsentForTest, @@ -20,6 +20,7 @@ const posthogMock = vi.hoisted(() => ({ identify: vi.fn(), group: vi.fn(), reset: vi.fn(), + capture: vi.fn(), opt_out_capturing: vi.fn(), opt_in_capturing: vi.fn(), has_opted_out_capturing: vi.fn(() => false), @@ -185,6 +186,28 @@ describe("ProductAnalyticsGate", () => { act(() => root.unmount()); }); + it("sends events from before Accept once, in order and with their original timestamps", async () => { + getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: true }))); + const root = await renderGate(); + const openedAt = new Date(); + captureProductAnalyticsEvent("onboarding_opened", { step: "create_agent" }); + await act(async () => { await vi.advanceTimersByTimeAsync(1_000); }); + const completedAt = new Date(); + captureProductAnalyticsEvent("onboarding_step_completed", { step: "create_agent" }); + expect(injectedScripts()).toHaveLength(0); + expect(posthogMock.capture).not.toHaveBeenCalled(); + + await act(async () => { bannerButton("Accept").click(); }); + + expect(posthogMock.capture.mock.calls).toEqual([ + ["onboarding_opened", { step: "create_agent" }, { timestamp: openedAt }], + ["onboarding_step_completed", { step: "create_agent" }, { timestamp: completedAt }], + ]); + await settle(); + expect(posthogMock.capture).toHaveBeenCalledTimes(2); + act(() => root.unmount()); + }); + it("keeps analytics off when the visitor declines", async () => { getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: true }))); const root = await renderGate(); diff --git a/ui/src/lib/analytics/onboarding-analytics.test.tsx b/ui/src/lib/analytics/onboarding-analytics.test.tsx index 441ab949d93..8e5b1084f17 100644 --- a/ui/src/lib/analytics/onboarding-analytics.test.tsx +++ b/ui/src/lib/analytics/onboarding-analytics.test.tsx @@ -130,6 +130,43 @@ describe("browser product events", () => { ); }); + it("discards pending events on Decline and ignores events until a later Accept", async () => { + syncProductAnalytics(config, "ask", { load, schedule }); + captureProductAnalyticsEvent("onboarding_opened", { step: "create_agent" }); + syncProductAnalytics(config, "denied", { load, schedule }); + captureProductAnalyticsEvent("onboarding_step_completed", { step: "create_agent" }); + await startAnalytics(); + expect(client.capture).not.toHaveBeenCalled(); + captureProductAnalyticsEvent("onboarding_opened", { step: "connect_model" }); + expect(captured()).toEqual([["onboarding_opened", { step: "connect_model" }]]); + }); + + it("bounds the pending-consent queue to 50 events", async () => { + syncProductAnalytics(config, "ask", { load, schedule }); + for (let index = 0; index < 50; index++) { + captureProductAnalyticsEvent("onboarding_step_viewed", { step: "create_agent" }); + } + captureProductAnalyticsEvent("onboarding_step_viewed", { step: "review" }); + await startAnalytics(); + expect(client.capture).toHaveBeenCalledTimes(50); + expect(captured()).not.toContainEqual(["onboarding_step_viewed", { step: "review" }]); + }); + + it("queues while consent is pending again after the client has initialized", async () => { + setProductAnalyticsUser({ id: "user-1", email: null, name: null }); + await startAnalytics(); + syncProductAnalytics(config, "ask", { load, schedule }); + captureProductAnalyticsEvent("onboarding_opened", { step: "create_agent" }); + expect(client.capture).not.toHaveBeenCalled(); + setProductAnalyticsUser({ id: "user-2", email: null, name: null }); + expect(client.identify).toHaveBeenCalledTimes(1); + captureProductAnalyticsEvent("onboarding_opened", { step: "connect_model" }); + await startAnalytics(); + expect(captured()).toEqual([["onboarding_opened", { step: "connect_model" }]]); + expect(client.identify).toHaveBeenLastCalledWith("user-2", {}); + expect(client.init).toHaveBeenCalledTimes(1); + }); + it("drops held events when consent is withdrawn before posthog-js loads", async () => { syncProductAnalytics(config, "granted", { load, schedule }); captureProductAnalyticsEvent("onboarding_opened", { step: "create_agent" }); @@ -140,13 +177,14 @@ describe("browser product events", () => { expect(client.capture).not.toHaveBeenCalled(); }); - it("drops held events when the signed-in person changes before posthog-js loads", async () => { + it.each(["granted", "ask"] as const)("drops held events on a person change while consent is %s", async (consent) => { setProductAnalyticsUser({ id: "user-1", email: null, name: null }); - syncProductAnalytics(config, "granted", { load, schedule }); + syncProductAnalytics(config, consent, { load, schedule }); captureProductAnalyticsEvent("onboarding_opened", { step: "create_agent" }); setProductAnalyticsUser(null); setProductAnalyticsUser({ id: "user-2", email: null, name: null }); captureProductAnalyticsEvent("onboarding_opened", { step: "connect_model" }); + syncProductAnalytics(config, "granted", { load, schedule }); scheduled!(); await flush(); expect(captured()).toEqual([["onboarding_opened", { step: "connect_model" }]]); @@ -256,13 +294,24 @@ describe("onboarding funnel events", () => { ]); }); - it("captures nothing in the wizard when consent is not granted", async () => { + it("sends queued wizard events after consent without reopening the wizard", async () => { syncProductAnalytics(config, "ask", { load, schedule, immediate: true }); const wizard = renderWizard({ open: true, step: 3 }); act(() => wizard.result.current.opened(3, 3)); wizard.rerender({ open: true, step: 4, connectOutcome: "subscription" }); act(() => wizard.result.current.dismissed(4)); expect(client.capture).not.toHaveBeenCalled(); + expect(client.init).not.toHaveBeenCalled(); + expect(scheduled).toBeNull(); + + await startAnalytics(); + expect(captured()).toEqual([ + ["onboarding_opened", { step: "create_agent" }], + ["onboarding_step_viewed", { step: "create_agent" }], + ["onboarding_step_completed", { step: "create_agent" }], + ["onboarding_step_viewed", { step: "connect_model" }], + ["onboarding_dismissed", { step: "connect_model" }], + ]); }); it("captures structured onboarding failures and drops unsafe provider strings", async () => { diff --git a/ui/src/lib/analytics/product-analytics.ts b/ui/src/lib/analytics/product-analytics.ts index 4bc24f9faa3..d1c414099a0 100644 --- a/ui/src/lib/analytics/product-analytics.ts +++ b/ui/src/lib/analytics/product-analytics.ts @@ -23,6 +23,7 @@ // be captured here; `product-analytics-events.test.ts` enforces that. import type { BrowserAnalyticsConfig } from "@paperclipai/shared"; +import type { AnalyticsConsent } from "./consent"; import { ANALYTICS_MASK_TEXT_SELECTOR, ANALYTICS_NO_CAPTURE_CLASS, @@ -220,7 +221,7 @@ type State = { cancelSchedule: (() => void) | null; pendingClient: ProductAnalyticsClient | null; loading: boolean; - optedOut: boolean; + consent: AnalyticsConsent; queued: QueuedProductEvent[]; }; @@ -236,6 +237,18 @@ let state: State | null = null; let wantedUser: ProductAnalyticsUser | null = null; let identifiedUserId: string | null = null; +function createAnalyticsState(config: BrowserAnalyticsConfig, consent: AnalyticsConsent): State { + return { + config, + client: null, + pendingClient: null, + cancelSchedule: null, + loading: false, + consent, + queued: [], + }; +} + function applyIdentity(client: ProductAnalyticsClient, config: BrowserAnalyticsConfig) { const user = wantedUser; if (user) { @@ -268,9 +281,9 @@ function sendProductEvent(client: ProductAnalyticsClient, queued: QueuedProductE export function captureProductAnalyticsEvent(event: string, properties: Record = {}): void { const current = state; - if (!current || current.optedOut) return; + if (!current || current.consent === "denied") return; const queued = { event, properties: { ...properties }, timestamp: new Date() }; - if (current.client) { + if (current.client && current.consent === "granted") { sendProductEvent(current.client, queued); return; } @@ -287,6 +300,12 @@ function optIn(client: ProductAnalyticsClient, config: BrowserAnalyticsConfig) { if (config.replayEnabled) client.startSessionRecording?.(); } +function flushQueuedProductEvents(current: State, client: ProductAnalyticsClient) { + const queued = current.queued; + current.queued = []; + for (const event of queued) sendProductEvent(client, event); +} + function initialize(current: State, client: ProductAnalyticsClient) { const { config } = current; client.init(config.token, buildPostHogInitOptions(config, window.location.hostname)); @@ -294,9 +313,7 @@ function initialize(current: State, client: ProductAnalyticsClient) { client.register(superProperties(config)); current.client = client; applyIdentity(client, config); - const queued = current.queued; - current.queued = []; - for (const event of queued) sendProductEvent(client, event); + flushQueuedProductEvents(current, client); } /** @@ -308,28 +325,23 @@ export function startProductAnalytics( config: BrowserAnalyticsConfig, options: ProductAnalyticsOptions, ): void { - if (state) { - if (!state.optedOut) return; - state.optedOut = false; - if (state.client) { - optIn(state.client, state.config); - } else if (state.pendingClient) { - const client = state.pendingClient; - state.pendingClient = null; - initialize(state, client); - } + if (state?.consent === "granted") return; + const current = state ?? createAnalyticsState(config, "granted"); + state = current; + current.consent = "granted"; + if (current.client) { + optIn(current.client, current.config); + applyIdentity(current.client, current.config); + flushQueuedProductEvents(current, current.client); return; } - const current: State = { - config, - client: null, - pendingClient: null, - cancelSchedule: null, - loading: false, - optedOut: false, - queued: [], - }; - state = current; + if (current.pendingClient) { + const client = current.pendingClient; + current.pendingClient = null; + initialize(current, client); + return; + } + if (current.loading) return; const load = options.load ?? loadPostHog; current.cancelSchedule = options.schedule(() => { // The scheduler may call back more than once (settled page, deadline). @@ -338,10 +350,10 @@ export function startProductAnalytics( cancel?.(); if (state !== current || current.loading) return; current.loading = true; - load(config) + load(current.config) .then((client) => { if (state !== current) return; - if (current.optedOut) current.pendingClient = client; + if (current.consent !== "granted") current.pendingClient = client; else initialize(current, client); }) .catch(() => { @@ -356,7 +368,7 @@ export function startProductAnalytics( export function setProductAnalyticsUser(user: ProductAnalyticsUser | null): void { if (wantedUser && wantedUser.id !== user?.id && state) state.queued = []; wantedUser = user; - if (state?.client) applyIdentity(state.client, state.config); + if (state?.client && state.consent === "granted") applyIdentity(state.client, state.config); } /** @@ -379,25 +391,24 @@ export function cancelPendingProductAnalytics(): void { state = null; } -function stopProductAnalytics(): void { +function stopProductAnalytics(consent: "ask" | "denied"): void { if (!state) return; - if (!state.client && !state.pendingClient && !state.loading) { - state.cancelSchedule?.(); - state = null; - return; - } - state.optedOut = true; - state.queued = []; - if (state.client) optOut(state.client); + state.cancelSchedule?.(); + state.cancelSchedule = null; + const wasGranted = state.consent === "granted"; + state.consent = consent; + if (consent === "denied") state.queued = []; + if (state.client && wasGranted) optOut(state.client); } export function syncProductAnalytics( config: BrowserAnalyticsConfig, - consent: "granted" | "denied" | "ask", + consent: AnalyticsConsent, options: ProductAnalyticsOptions & { immediate?: boolean }, ): () => void { if (consent !== "granted") { - stopProductAnalytics(); + if (!state && consent === "ask") state = createAnalyticsState(config, consent); + stopProductAnalytics(consent); return () => undefined; } const schedule: ProductAnalyticsOptions["schedule"] = options.immediate