From b0f682b66bccd9674efe2c4d97e76cf538e89bee Mon Sep 17 00:00:00 2001 From: scotttong Date: Wed, 2 Dec 2026 18:03:08 -0800 Subject: [PATCH] Measure when users see a reply to their onboarding chat input (#23574) --- docs/api/onboarding-telemetry.md | 13 +++ packages/shared/src/onboarding-telemetry.ts | 4 + server/src/services/activity.ts | 3 + .../e2e/conference-room-typing-intro.spec.ts | 53 ++++++++++ .../runner-e2e/source-sdk-public-inputs.json | 2 +- ui/src/api/activity.ts | 1 + .../task-chat/TaskChatActivityPhase.tsx | 1 + .../components/task-chat/TaskChatBubble.tsx | 2 + .../task-chat/TaskChatRunnerActivityGroup.tsx | 1 + ui/src/components/task-chat/TaskChatTurn.tsx | 1 + .../task-chat/transcript-adapter.ts | 1 + .../hooks/useOnboardingReplyDisplay.test.tsx | 93 ++++++++++++++++++ ui/src/hooks/useOnboardingReplyDisplay.ts | 98 +++++++++++++++++++ ui/src/lib/analytics/onboarding-analytics.ts | 4 +- .../lib/analytics/product-analytics.test.ts | 37 +++++++ ui/src/lib/analytics/product-analytics.ts | 45 ++++++++- ui/src/pages/IssueDetail.tsx | 15 +++ 17 files changed, 367 insertions(+), 7 deletions(-) create mode 100644 ui/src/hooks/useOnboardingReplyDisplay.test.tsx create mode 100644 ui/src/hooks/useOnboardingReplyDisplay.ts diff --git a/docs/api/onboarding-telemetry.md b/docs/api/onboarding-telemetry.md index 89f7ea60c07..5fc0ecde607 100644 --- a/docs/api/onboarding-telemetry.md +++ b/docs/api/onboarding-telemetry.md @@ -62,3 +62,16 @@ Example: | `400` | Validation error (unknown event name, disallowed extra property, or invalid slug/enum). | | `403` | Unauthenticated, non-board actor, or caller lacks access to `companyId`. | | `429` | Per-actor rate limit exceeded (default 120 events per 60 seconds). | + +The chat send event includes the submitted input UUID (`message_id`) and its +conversation UUID (`chat_id`). A composer send uses its saved comment ID. Explicitly sending an onboarding +welcome answer uses the answered interaction ID. Selecting an option alone +produces no event. + +The Cloud browser emits `agent_chat_reply_displayed` when the signed-in chat +owner can see reply text in the focused onboarding chat. The event carries +`surface=onboarding_chat`, `reply_kind=response_to_user`, and the same chat +and triggering message IDs as the send. It uses the run's triggering input to +attribute the reply. A stored browser receipt suppresses repeat displays in +the same chat, including after reload. Count unique people in the funnel. +Historical run success cannot establish that a person saw a reply. diff --git a/packages/shared/src/onboarding-telemetry.ts b/packages/shared/src/onboarding-telemetry.ts index 758da742177..c959a1d091d 100644 --- a/packages/shared/src/onboarding-telemetry.ts +++ b/packages/shared/src/onboarding-telemetry.ts @@ -268,6 +268,8 @@ export const onboardingTelemetryEventSchema = z.discriminatedUnion("event", [ event: z.literal(ONBOARDING_TELEMETRY_EVENTS.chatMessageSent), companyId: optionalCompanyIdSchema, surface: z.enum(AGENT_CHAT_SURFACES), + chatId: z.string().uuid().optional(), + messageId: z.string().uuid().optional(), }) .strict(), ]); @@ -377,6 +379,8 @@ export function onboardingTelemetryEventToPostHogProperties( break; case ONBOARDING_TELEMETRY_EVENTS.chatMessageSent: set("surface", input.surface); + set("chat_id", input.chatId); + set("message_id", input.messageId); break; } diff --git a/server/src/services/activity.ts b/server/src/services/activity.ts index b5604f18e99..6b433c3e7e8 100644 --- a/server/src/services/activity.ts +++ b/server/src/services/activity.ts @@ -563,6 +563,9 @@ export function activityService(db: Db) { // Queued messages this run's own accepted first turn took. firstTurnCommentIds: acceptedFirstTurnCommentIdsSql(heartbeatRuns), queuedCommentSourceWakeIds: sql`${heartbeatRuns.contextSnapshot} -> 'queuedCommentSourceWakeIds'`, + triggeringChatInputId: sql`case when ${heartbeatRuns.contextSnapshot} ->> 'wakeReason' = 'issue_commented' + then coalesce(${heartbeatRuns.contextSnapshot} ->> 'interactionId', + ${heartbeatRuns.contextSnapshot} ->> 'wakeCommentId', ${heartbeatRuns.contextSnapshot} ->> 'commentId') end`, wakeCommentId: sql`${heartbeatRuns.contextSnapshot} ->> 'wakeCommentId'`, contextCommentId: sql`${heartbeatRuns.contextSnapshot} ->> 'commentId'`, contextIssueId: sql`${heartbeatRuns.contextSnapshot} ->> 'issueId'`, diff --git a/tests/e2e/conference-room-typing-intro.spec.ts b/tests/e2e/conference-room-typing-intro.spec.ts index 2b56df57296..a4b2bcf7c72 100644 --- a/tests/e2e/conference-room-typing-intro.spec.ts +++ b/tests/e2e/conference-room-typing-intro.spec.ts @@ -324,6 +324,59 @@ test.describe("Chat launch after onboarding wizard", () => { await page.screenshot({ path: test.info().outputPath("onboarding-chat.png"), fullPage: true }); }); + test.describe("browser analytics", () => { + test.use({ serviceWorkers: "block" }); + + for (const input of ["composer", "welcome answer"] as const) { + test(`measures the first displayed reply to the onboarding ${input}`, async ({ page, baseURL }) => { + test.setTimeout(180_000); + await installLaunchIntercepts(page, baseURL, true); + await page.route("**/api/auth/get-session", async route => { + const response = await route.fetch(); + const session = await response.json(); + await route.fulfill({ response, json: { ...session, browserAnalytics: { + token: "test", apiHost: "/analytics-fixture", uiHost: null, environment: "test", + stackId: "test", replayEnabled: false, + } } }); + }); + const captures: { actor: string; properties: Record }[] = []; + await page.exposeFunction("recordChatDisplay", (actor: string, properties: Record) => { + captures.push({ actor, properties }); + }); + await page.route("**/analytics-fixture/static/array.js", route => route.fulfill({ + contentType: "text/javascript", + body: `window.posthog = { init() {}, register() {}, group() {}, reset() {}, identify(id) { this.actor = id; }, + capture(event, properties) { if (event === 'agent_chat_reply_displayed') window.recordChatDisplay(this.actor, properties); } };`, + })); + await runOnboardingWizard(page, `E2E-ChatDisplay-${Date.now()}`); + await expect(page).toHaveURL(/\/chats\/[^/]+$/); + const choices = page.getByTestId("task-chat-composer-takeover"); + const sent = page.waitForRequest(req => req.url().endsWith("/api/onboarding/telemetry") + && req.postDataJSON()?.event === "agent_chat_message_sent"); + if (input === "composer") { + await choices.getByRole("button", { name: /^Dismiss / }).click(); + const editor = page.getByTestId("task-chat-composer-input").locator('[contenteditable="true"]'); + await editor.fill("build a website"); + await page.getByTestId("task-chat-composer-send").click(); + } else { + await choices.getByRole("radio", { name: "Interview me about my goals" }).click(); + expect(captures).toHaveLength(0); + await choices.getByRole("button", { name: /send|submit|continue/i }).click(); + } + const reply = input === "composer" ? typedFixtureReply : choiceReplies.interview; + const { chatId, messageId } = (await sent).postDataJSON(); + expect(chatId).toBeTruthy(); + expect(messageId).toBeTruthy(); + await expect(page.getByText(reply, { exact: true })).toBeVisible({ timeout: 30_000 }); + await expect.poll(() => captures).toEqual([{ actor: "local-board", + properties: { surface: "onboarding_chat", reply_kind: "response_to_user", chat_id: chatId, message_id: messageId } }]); + await page.reload(); + await expect(page.getByText(reply, { exact: true })).toBeVisible(); + expect(captures).toHaveLength(1); + }); + } + }); + test("warms the welcome during review, then animates it before showing the real choice card", async ({ page, baseURL }) => { test.setTimeout(180_000); await installLaunchIntercepts(page, baseURL, true); diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 56c2d6c91e4..31f3cff7ccd 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -327,7 +327,7 @@ "packages/shared/src/node-version.ts": "9a7766a8324122ce41738918bb0125398b9657e1", "packages/shared/src/oauth-endpoint-url.test.ts": "7f7ad634b3de7f25513e6c8b6426e1285d079e12", "packages/shared/src/oauth-endpoint-url.ts": "5ea73648dc5df103881e40e8ed920e38d901760a", - "packages/shared/src/onboarding-telemetry.ts": "758da7421779d5ca20e83ac7222cc8c67714f278", + "packages/shared/src/onboarding-telemetry.ts": "c959a1d091d81d2379d22d066490931fa74c586c", "packages/shared/src/openrouter-attribution.test.ts": "ddc980f9d06fac708d02dcef8a8962e9887d6854", "packages/shared/src/openrouter-attribution.ts": "b77e887721cbf6bd882004f07df2405b6e58e52c", "packages/shared/src/paperclip-peer.test.ts": "304c9db3bb82871834f4e8970d334cb21bb9de7a", diff --git a/ui/src/api/activity.ts b/ui/src/api/activity.ts index 75ca32163d2..19ce9e661b2 100644 --- a/ui/src/api/activity.ts +++ b/ui/src/api/activity.ts @@ -37,6 +37,7 @@ export interface RunForIssue { continuationAttempt?: number; lastUsefulActionAt?: string | null; nextAction?: string | null; + triggeringChatInputId?: string | null; wakeCommentIds?: string[] | null; /** Queued messages this run's first provider turn took while it was starting. */ firstTurnCommentIds?: string[] | null; diff --git a/ui/src/components/task-chat/TaskChatActivityPhase.tsx b/ui/src/components/task-chat/TaskChatActivityPhase.tsx index 127699ff31e..3b7692c853f 100644 --- a/ui/src/components/task-chat/TaskChatActivityPhase.tsx +++ b/ui/src/components/task-chat/TaskChatActivityPhase.tsx @@ -83,6 +83,7 @@ export function TaskChatActivityPhase({
diff --git a/ui/src/components/task-chat/TaskChatBubble.tsx b/ui/src/components/task-chat/TaskChatBubble.tsx index 668b8560487..e05f680d862 100644 --- a/ui/src/components/task-chat/TaskChatBubble.tsx +++ b/ui/src/components/task-chat/TaskChatBubble.tsx @@ -304,6 +304,8 @@ function TaskChatBubbleContent({ ) : null} {bodyText.length > 0 ? (
diff --git a/ui/src/components/task-chat/TaskChatTurn.tsx b/ui/src/components/task-chat/TaskChatTurn.tsx index 24f0ab34909..c6ddb1fe55d 100644 --- a/ui/src/components/task-chat/TaskChatTurn.tsx +++ b/ui/src/components/task-chat/TaskChatTurn.tsx @@ -133,6 +133,7 @@ export function TaskChatTurn({
diff --git a/ui/src/components/task-chat/transcript-adapter.ts b/ui/src/components/task-chat/transcript-adapter.ts index 3e186a7b966..78e07f84359 100644 --- a/ui/src/components/task-chat/transcript-adapter.ts +++ b/ui/src/components/task-chat/transcript-adapter.ts @@ -879,6 +879,7 @@ export function transcriptToTaskChatItems( author: "agent", authorName: agentName, text: entry.text, + ...(channel === "final" ? { sourceRunId: runId } : {}), channel, streaming: running, // Explicit final-answer items stream durably. Unclassified text diff --git a/ui/src/hooks/useOnboardingReplyDisplay.test.tsx b/ui/src/hooks/useOnboardingReplyDisplay.test.tsx new file mode 100644 index 00000000000..72ab4e9feb3 --- /dev/null +++ b/ui/src/hooks/useOnboardingReplyDisplay.test.tsx @@ -0,0 +1,93 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vitest"; +import type { RunForIssue } from "@/api/activity"; +import { captureProductAnalyticsEvent } from "@/lib/analytics/product-analytics"; +import { useOnboardingReplyDisplay } from "./useOnboardingReplyDisplay"; +import { transcriptToTaskChatItems, paperclipRunnerFinalResponse } from "@/components/task-chat/transcript-adapter"; + +vi.mock("@/lib/analytics/product-analytics", () => ({ + captureProductAnalyticsEvent: vi.fn(), hasCapturedProductEvent: () => false, +})); + +it("attributes only provider final text to its run during streaming and replay", () => { + const options = { runId: "turn", running: true }; + const entries = transcriptToTaskChatItems([ + { kind: "assistant", ts: "2026-12-01", channel: "progress", text: "Reading" }, + { kind: "assistant", ts: "2026-12-01", channel: "final", text: "Here" }, + ], options); + expect(entries[0]).not.toHaveProperty("sourceRunId"); + expect(paperclipRunnerFinalResponse(entries)).toMatchObject({ sourceRunId: "turn", text: "Here", streaming: true }); + expect(paperclipRunnerFinalResponse([], { runId: "turn", fallbackSummary: "Run completed" })).not.toHaveProperty("sourceRunId"); +}); + +it("waits for the owner's reply text to enter a visible, focused viewport", async () => { + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + const runs = [ + { runId: "welcome", triggeringChatInputId: null, firstTurnCommentIds: ["sent"], contextIssueId: "chat" }, + { runId: "foreign", triggeringChatInputId: "other-user", contextIssueId: "chat" }, + { runId: "wrong-chat", triggeringChatInputId: "sent", contextIssueId: "other" }, + { runId: "response", triggeringChatInputId: "sent", contextIssueId: "chat" }, + ] as RunForIssue[]; + const comments = ["sent", "other-user"].map(id => ({ + id, issueId: "chat", authorType: "user" as const, authorUserId: id === "sent" ? "owner" : "other", + createdByRunId: null, deletedAt: null, + })); + function Thread({ text }: { text: string }) { + const ref = useOnboardingReplyDisplay("owner", "chat", runs, comments); + return
+ {runs.map(run =>
+

{run.runId === "response" ? text : run.runId}

+
)} +
; + } + let nextFrame: FrameRequestCallback | undefined; + let focused = true, visible = true, top = 200, covered = false; + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => { nextFrame = callback; return 1; }); + vi.stubGlobal("cancelAnimationFrame", () => {}); + vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} }); + vi.spyOn(document, "hasFocus").mockImplementation(() => focused); + vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visible ? "visible" : "hidden"); + vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 150, 100)); + const range = document.createRange(); + const textNode = () => host.querySelector('[data-reply-run=response] p'); + vi.spyOn(document, "createRange").mockReturnValue(Object.assign(range, { + getClientRects: () => [new DOMRect(0, top, 100, 20), new DOMRect(0, top + 120, 100, 20)], + })); + Object.defineProperty(document, "elementFromPoint", { configurable: true, value: () => covered ? host : textNode() }); + const paint = () => { const cb = nextFrame; nextFrame = undefined; cb?.(0); }; + try { + await act(async () => root.render()); + paint(); + expect(captureProductAnalyticsEvent).not.toHaveBeenCalled(); + await act(async () => root.render()); + paint(); + expect(captureProductAnalyticsEvent).not.toHaveBeenCalled(); + top = -80; + visible = false; + window.dispatchEvent(new Event("scroll")); paint(); + visible = true; focused = false; + document.dispatchEvent(new Event("visibilitychange")); paint(); + focused = true; covered = true; + window.dispatchEvent(new Event("focus")); paint(); + expect(captureProductAnalyticsEvent).not.toHaveBeenCalled(); + covered = false; + window.dispatchEvent(new Event("focus")); paint(); + expect(captureProductAnalyticsEvent).toHaveBeenCalledExactlyOnceWith("agent_chat_reply_displayed", { + surface: "onboarding_chat", reply_kind: "response_to_user", chat_id: "chat", message_id: "sent", + }, { userId: "owner", onceKey: "paperclip:first-chat-reply:owner:chat" }); + await act(async () => root.render()); + paint(); + expect(captureProductAnalyticsEvent).toHaveBeenCalledTimes(1); + } finally { + await act(async () => root.unmount()); + host.remove(); + Reflect.deleteProperty(document, "elementFromPoint"); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + } +}); diff --git a/ui/src/hooks/useOnboardingReplyDisplay.ts b/ui/src/hooks/useOnboardingReplyDisplay.ts new file mode 100644 index 00000000000..6f0ca0f223c --- /dev/null +++ b/ui/src/hooks/useOnboardingReplyDisplay.ts @@ -0,0 +1,98 @@ +import { useEffect, useRef } from "react"; +import type { IssueComment, IssueThreadInteraction } from "@paperclipai/shared"; +import type { RunForIssue } from "@/api/activity"; +import { captureProductAnalyticsEvent, hasCapturedProductEvent } from "@/lib/analytics/product-analytics"; + +type ChatInput = Pick; + +function replyInputs(userId: string, chatId: string, runs: readonly RunForIssue[], comments: readonly ChatInput[], + welcomeChoice?: IssueThreadInteraction) { + const own = new Set(comments.filter(comment => + comment.issueId === chatId && comment.authorType === "user" && comment.authorUserId === userId + && !comment.deletedAt && !comment.createdByRunId, + ).map(comment => comment.id)); + if (welcomeChoice?.issueId === chatId && welcomeChoice.status === "answered" && welcomeChoice.resolvedByUserId === userId) { + own.add(welcomeChoice.id); + } + const inputs = new Map(); + for (const run of runs) { + const messageId = run.triggeringChatInputId; + if (run.contextIssueId === chatId && messageId && own.has(messageId)) { + inputs.set(run.runId, messageId); + } + } + return inputs; +} + +function visibleReplyText(body: HTMLElement, viewport: HTMLElement) { + if (body.closest("[inert], [aria-hidden=true]")) return false; + if (body.checkVisibility && !body.checkVisibility({ opacityProperty: true, visibilityProperty: true })) return false; + const bounds = viewport.getBoundingClientRect(); + const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT); + const range = document.createRange(); + for (let node = walker.nextNode(); node; node = walker.nextNode()) { + const element = node.parentElement; + if (!node.textContent?.trim() || !element || element.closest("button, [aria-hidden=true]")) continue; + range.selectNodeContents(node); + for (const rect of range.getClientRects()) { + const left = Math.max(0, rect.left, bounds.left); + const right = Math.min(innerWidth, rect.right, bounds.right); + const top = Math.max(0, rect.top, bounds.top); + const bottom = Math.min(innerHeight, rect.bottom, bounds.bottom); + if (right > left && bottom > top && element.contains(document.elementFromPoint((left + right) / 2, (top + bottom) / 2))) { + return true; + } + } + } + return false; +} + +export function useOnboardingReplyDisplay( + userId: string | undefined, chatId: string, runs: readonly RunForIssue[], + comments: readonly ChatInput[], welcomeChoice?: IssueThreadInteraction, +) { + const ref = useRef(null); + useEffect(() => { + const thread = ref.current; + if (!thread || !userId) return; + const onceKey = `paperclip:first-chat-reply:${userId}:${chatId}`; + if (hasCapturedProductEvent(onceKey)) return; + const inputs = replyInputs(userId, chatId, runs, comments, welcomeChoice); + if (!inputs.size) return; + const listeners = new AbortController(); + const options = { signal: listeners.signal, capture: true }; + let frame = 0; + const check = () => { + frame = 0; + if (document.visibilityState !== "visible" || !document.hasFocus()) return; + for (const reply of thread.querySelectorAll("[data-reply-run]")) { + const messageId = inputs.get(reply.dataset.replyRun!); + const body = reply.querySelector(":scope > .paperclip-markdown"); + const viewport = reply.closest(".task-chat-scroll-viewport"); + if (!messageId || !body || !viewport || !visibleReplyText(body, viewport)) continue; + captureProductAnalyticsEvent("agent_chat_reply_displayed", { + surface: "onboarding_chat", reply_kind: "response_to_user", chat_id: chatId, message_id: messageId, + }, { userId, onceKey }); + stop(); + break; + } + }; + const schedule = () => { if (!frame) frame = requestAnimationFrame(check); }; + const observer = new MutationObserver(schedule); + observer.observe(thread, { subtree: true, childList: true, characterData: true, attributes: true, + attributeFilter: ["data-reply-run", "inert", "class", "style", "aria-hidden"] }); + const size = new ResizeObserver(schedule); + size.observe(thread); + for (const event of ["scroll", "resize", "load", "focus", "animationend", "transitionend"]) window.addEventListener(event, schedule, options); + document.addEventListener("visibilitychange", schedule, options); + function stop() { + observer.disconnect(); + size.disconnect(); + listeners.abort(); + cancelAnimationFrame(frame); + } + schedule(); + return stop; + }, [userId, chatId, runs, comments, welcomeChoice]); + return ref; +} diff --git a/ui/src/lib/analytics/onboarding-analytics.ts b/ui/src/lib/analytics/onboarding-analytics.ts index 96c11555a4e..f408e4577c3 100644 --- a/ui/src/lib/analytics/onboarding-analytics.ts +++ b/ui/src/lib/analytics/onboarding-analytics.ts @@ -346,11 +346,13 @@ export function captureOnboardingLaunchClicked(input: { export function captureAgentChatMessageSent( surface: AgentChatSurface, - meta?: { companyId?: string | null }, + meta?: { companyId?: string | null; chatId?: string; messageId?: string }, ): void { const companyId = normalizeCompanyId(meta?.companyId); sendEvent({ event: ONBOARDING_TELEMETRY_EVENTS.chatMessageSent, + ...(meta?.chatId && UUID_RE.test(meta.chatId) ? { chatId: meta.chatId } : {}), + ...(meta?.messageId && UUID_RE.test(meta.messageId) ? { messageId: meta.messageId } : {}), ...(companyId ? { companyId } : {}), surface, }); diff --git a/ui/src/lib/analytics/product-analytics.test.ts b/ui/src/lib/analytics/product-analytics.test.ts index de08a7abaca..02ea65f81c9 100644 --- a/ui/src/lib/analytics/product-analytics.test.ts +++ b/ui/src/lib/analytics/product-analytics.test.ts @@ -5,6 +5,7 @@ import type { BrowserAnalyticsConfig } from "@paperclipai/shared"; import { buildPostHogInitOptions, cancelPendingProductAnalytics, + captureProductAnalyticsEvent, resetProductAnalyticsForTest, scrubCapturedEvent, setProductAnalyticsUser, @@ -119,6 +120,42 @@ describe("product analytics", () => { expect(client.identify).toHaveBeenLastCalledWith("user-2", {}); }); + it("binds queued first displays to the original identity and honors consent and reload receipts", async () => { + const capture = vi.fn(); + const optedOut = vi.fn(() => false); + Object.assign(client, { capture, has_opted_out_capturing: optedOut }); + const scope = { userId: "owner", onceKey: "fixture:first-display" }; + const send = () => captureProductAnalyticsEvent("display", {}, scope); + const start = async (userId: string) => { + setProductAnalyticsUser({ id: userId, email: null, name: null }); + startProductAnalytics(config, { load, schedule }); + scheduled!(); + await flush(); + }; + try { + send(); + await start("other"); + expect(capture).not.toHaveBeenCalled(); + setProductAnalyticsUser({ id: "owner", email: null, name: null }); + localStorage.setItem("paperclip.analyticsConsent", "denied"); + send(); + localStorage.removeItem("paperclip.analyticsConsent"); + optedOut.mockReturnValue(true); + send(); + expect(capture).not.toHaveBeenCalled(); + optedOut.mockReturnValue(false); + send(); + send(); + resetProductAnalyticsForTest(); + await start("owner"); + send(); + expect(capture).toHaveBeenCalledTimes(1); + } finally { + localStorage.removeItem(scope.onceKey); + localStorage.removeItem("paperclip.analyticsConsent"); + } + }); + it("does not reset an anonymous visitor", async () => { startProductAnalytics(config, { load, schedule }); scheduled!(); diff --git a/ui/src/lib/analytics/product-analytics.ts b/ui/src/lib/analytics/product-analytics.ts index 3a7373e0dc8..84704c70e3f 100644 --- a/ui/src/lib/analytics/product-analytics.ts +++ b/ui/src/lib/analytics/product-analytics.ts @@ -239,10 +239,15 @@ type State = { client: ProductAnalyticsClient | null; cancelSchedule: (() => void) | null; loading: boolean; + optedOutAtLoad: boolean; queued: QueuedProductEvent[]; }; +type CaptureScope = { userId: string; onceKey: string }; +const capturedThisPage = new Set(); + type QueuedProductEvent = { + scope?: CaptureScope; event: string; properties: Record; timestamp: Date; @@ -261,6 +266,7 @@ function createAnalyticsState(config: BrowserAnalyticsConfig): State { client: null, cancelSchedule: null, loading: false, + optedOutAtLoad: false, queued: [], }; } @@ -297,12 +303,38 @@ function applyIdentity(client: ProductAnalyticsClient, config: BrowserAnalyticsC } } -function sendProductEvent(client: ProductAnalyticsClient, queued: QueuedProductEvent) { - client.capture?.(queued.event, queued.properties, { timestamp: queued.timestamp }); +export function hasCapturedProductEvent(onceKey: string) { + if (capturedThisPage.has(onceKey)) return true; + try { return window.localStorage.getItem(onceKey) === "1"; } catch { return false; } } -export function captureProductAnalyticsEvent(event: string, properties: Record = {}): void { - const queued = { event, properties: { ...properties }, timestamp: new Date() }; +function scopedCaptureAllowed() { + const nav = navigator as Navigator & { globalPrivacyControl?: boolean }; + if (state?.optedOutAtLoad || nav.globalPrivacyControl || nav.doNotTrack === "1") return false; + try { + const choice = window.localStorage.getItem("paperclip.analyticsConsent"); + return choice !== "denied" && (!state?.config.consentRequired || choice === "granted"); + } catch { + return false; + } +} + +function sendProductEvent(client: ProductAnalyticsClient, queued: QueuedProductEvent) { + const scope = queued.scope; + if (scope) { + if (scope.userId !== identifiedUserId || !scopedCaptureAllowed() || client.has_opted_out_capturing?.() || !client.capture) return; + if (hasCapturedProductEvent(scope.onceKey)) return; + } + client.capture?.(queued.event, queued.properties, { timestamp: queued.timestamp }); + if (scope) { + capturedThisPage.add(scope.onceKey); + try { window.localStorage.setItem(scope.onceKey, "1"); } catch { return; } + } +} + +export function captureProductAnalyticsEvent(event: string, properties: Record = {}, scope?: CaptureScope): void { + if (scope && (!scopedCaptureAllowed() || hasCapturedProductEvent(scope.onceKey))) return; + const queued = { scope, event, properties: { ...properties }, timestamp: new Date() }; const current = state; if (!current) { if (preStartQueued.length < MAX_QUEUED_PRODUCT_EVENTS) preStartQueued.push(queued); @@ -312,6 +344,7 @@ export function captureProductAnalyticsEvent(event: string, properties: Record entry.scope?.onceKey === scope.onceKey)) return; if (current.queued.length < MAX_QUEUED_PRODUCT_EVENTS) current.queued.push(queued); } @@ -329,7 +362,8 @@ function flushQueuedProductEvents(current: State, client: ProductAnalyticsClient function initialize(current: State, client: ProductAnalyticsClient) { const { config } = current; client.init(config.token, buildPostHogInitOptions(config, window.location.hostname)); - if (client.has_opted_out_capturing?.()) optIn(client, config); + current.optedOutAtLoad = client.has_opted_out_capturing?.() === true; + if (current.optedOutAtLoad) optIn(client, config); client.register(superProperties(config)); current.client = client; applyIdentity(client, config); @@ -417,6 +451,7 @@ export function cancelPendingProductAnalytics(): void { } export function resetProductAnalyticsForTest(): void { + capturedThisPage.clear(); state?.cancelSchedule?.(); state = null; wantedUser = null; diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index 490e80d9d4c..5769820db0b 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -32,6 +32,7 @@ import { AgentIdentity } from "@/components/AgentIdentity"; import { clearLegacyChatMessageRequests } from "@/lib/chat-message-request"; import { isOnboardingWelcomeChoice, OnboardingWelcomeContext, type WelcomeAnimation } from "@/lib/onboarding-chat"; import { agentChatDraft } from "@/lib/agent-chat-draft"; +import { useOnboardingReplyDisplay } from "@/hooks/useOnboardingReplyDisplay"; import { captureAgentChatMessageSent } from "@/lib/analytics/onboarding-analytics"; import { trackRecentProject } from "@/lib/recent-projects"; import { ExecutionBlockerNotice } from "../components/ExecutionBlockerNotice"; @@ -1326,6 +1327,7 @@ type IssueDetailChatTabProps = { suggestedAssigneeValue: string; mentions: MentionOption[]; conversationMode?: boolean; + onboardingAnalyticsUserId?: string; composerPause?: TaskComposerPause | null; composerDisabledReason: string | null; composerHint: string | null; @@ -1472,6 +1474,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ suggestedAssigneeValue, mentions, conversationMode, + onboardingAnalyticsUserId, composerPause, composerDisabledReason, composerHint, @@ -2681,8 +2684,10 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({
) : null; + const replyDisplayRef = useOnboardingReplyDisplay(onboardingAnalyticsUserId, issueId, linkedRuns, comments, welcomeChoice); const savedThread = (
issuesApi.respondToInteraction(issueId!, interaction.id, { answers }), onSuccess: (interaction) => { + if (issue?.originKind === "onboarding_chat" && issue.id === interaction.issueId + && currentUserId && issue.conversationUserId === currentUserId && interaction.resolvedByUserId === currentUserId + && interaction.status === "answered" && isOnboardingWelcomeChoice(interaction)) { + captureAgentChatMessageSent("onboarding_chat", { + companyId: interaction.companyId, chatId: interaction.issueId, messageId: interaction.id, + }); + } upsertInteractionInCache(interaction); invalidateIssueDetail(); invalidateIssueCollections(); @@ -8945,6 +8958,8 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS suggestedAssigneeValue={suggestedAssigneeValue} mentions={mentionOptions} conversationMode={!!issue.conversationAgentId} + onboardingAnalyticsUserId={conversation && session?.browserAnalytics && issue.originKind === "onboarding_chat" + && issue.conversationUserId === session.session.userId ? session.session.userId : undefined} composerPause={activePauseHold ? { scope: activePauseHold.isRoot && childIssues.length === 0 ? "leaf" : "subtree", pending: executeTreeControl.isPending && executeTreeControl.variables?.mode === "resume",