mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
Measure when users see a reply to their onboarding chat input (#23574)
This commit is contained in:
1 parent
2b65b97cae
commit
b0f682b66b
17 files changed
+367
-7
No files matched your search
@@ -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.
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -563,6 +563,9 @@ export function activityService(db: Db) {
|
||||
// Queued messages this run's own accepted first turn took.
|
||||
firstTurnCommentIds: acceptedFirstTurnCommentIdsSql(heartbeatRuns),
|
||||
queuedCommentSourceWakeIds: sql<string[] | null>`${heartbeatRuns.contextSnapshot} -> 'queuedCommentSourceWakeIds'`,
|
||||
triggeringChatInputId: sql<string | null>`case when ${heartbeatRuns.contextSnapshot} ->> 'wakeReason' = 'issue_commented'
|
||||
then coalesce(${heartbeatRuns.contextSnapshot} ->> 'interactionId',
|
||||
${heartbeatRuns.contextSnapshot} ->> 'wakeCommentId', ${heartbeatRuns.contextSnapshot} ->> 'commentId') end`,
|
||||
wakeCommentId: sql<string | null>`${heartbeatRuns.contextSnapshot} ->> 'wakeCommentId'`,
|
||||
contextCommentId: sql<string | null>`${heartbeatRuns.contextSnapshot} ->> 'commentId'`,
|
||||
contextIssueId: sql<string | null>`${heartbeatRuns.contextSnapshot} ->> 'issueId'`,
|
||||
|
||||
@@ -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<string, string> }[] = [];
|
||||
await page.exposeFunction("recordChatDisplay", (actor: string, properties: Record<string, string>) => {
|
||||
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);
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -83,6 +83,7 @@ export function TaskChatActivityPhase({
|
||||
<div
|
||||
className="min-w-0 px-1 text-sm text-foreground/90"
|
||||
data-testid="task-chat-phase-interstitial"
|
||||
data-reply-run={item.interstitial.channel === "final" ? item.interstitial.sourceRunId : undefined}
|
||||
data-conversation-text={item.interstitial.channel === "final" ? "final" : "progress"}
|
||||
>
|
||||
<MarkdownBody softBreaks linkIssueReferences>
|
||||
|
||||
@@ -304,6 +304,8 @@ function TaskChatBubbleContent({
|
||||
) : null}
|
||||
{bodyText.length > 0 ? (
|
||||
<div
|
||||
data-reply-run={item.author === "agent" && !item.optimistic && item.origin !== "fast_response"
|
||||
&& (item.origin === "comment" || item.channel === "final") ? item.sourceRunId : undefined}
|
||||
data-conversation-text={isHuman ? (isOwnMessage ? "human" : "progress") : item.channel === "progress" ? "progress" : "final"}
|
||||
// Stable hook so the TaskChatLab bubble-treatment explorations
|
||||
// (PAP-501) can scope background/border overrides to the agent
|
||||
|
||||
@@ -618,6 +618,7 @@ export function TaskChatRunnerActivityGroup({
|
||||
<div
|
||||
className="min-w-0 px-1 text-sm text-foreground/90"
|
||||
data-testid="task-chat-phase-interstitial"
|
||||
data-reply-run={item.interstitial.channel === "final" ? item.interstitial.sourceRunId : undefined}
|
||||
data-conversation-text={item.interstitial.channel === "final" ? "final" : "progress"}
|
||||
>
|
||||
<MarkdownBody softBreaks linkIssueReferences>
|
||||
|
||||
@@ -133,6 +133,7 @@ export function TaskChatTurn({
|
||||
<div className="w-full" data-testid="task-chat-final-response">
|
||||
<div
|
||||
className="break-words px-1 py-2 text-sm text-foreground"
|
||||
data-reply-run={item.finalResponse.sourceRunId}
|
||||
data-testid="task-chat-agent-bubble"
|
||||
>
|
||||
<MarkdownBody softBreaks linkIssueReferences>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 <div ref={ref}><div className="task-chat-scroll-viewport">
|
||||
{runs.map(run => <div key={run.runId} data-reply-run={run.runId}><div className="paperclip-markdown">
|
||||
<p>{run.runId === "response" ? text : run.runId}</p>
|
||||
</div></div>)}
|
||||
</div></div>;
|
||||
}
|
||||
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(<Thread text="" />));
|
||||
paint();
|
||||
expect(captureProductAnalyticsEvent).not.toHaveBeenCalled();
|
||||
await act(async () => root.render(<Thread text="The first streamed words" />));
|
||||
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(<Thread text="The first streamed words and the rest" />));
|
||||
paint();
|
||||
expect(captureProductAnalyticsEvent).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
host.remove();
|
||||
Reflect.deleteProperty(document, "elementFromPoint");
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
@@ -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<IssueComment, "id" | "issueId" | "authorType" | "authorUserId" | "deletedAt" | "createdByRunId">;
|
||||
|
||||
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<string, string>();
|
||||
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<HTMLDivElement>(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<HTMLElement>("[data-reply-run]")) {
|
||||
const messageId = inputs.get(reply.dataset.replyRun!);
|
||||
const body = reply.querySelector<HTMLElement>(":scope > .paperclip-markdown");
|
||||
const viewport = reply.closest<HTMLElement>(".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;
|
||||
}
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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!();
|
||||
|
||||
@@ -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<string>();
|
||||
|
||||
type QueuedProductEvent = {
|
||||
scope?: CaptureScope;
|
||||
event: string;
|
||||
properties: Record<string, string>;
|
||||
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<string, string> = {}): 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<string, string> = {}, 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<s
|
||||
sendProductEvent(current.client, queued);
|
||||
return;
|
||||
}
|
||||
if (scope && current.queued.some(entry => 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;
|
||||
|
||||
@@ -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({
|
||||
</div>
|
||||
) : null;
|
||||
|
||||
const replyDisplayRef = useOnboardingReplyDisplay(onboardingAnalyticsUserId, issueId, linkedRuns, comments, welcomeChoice);
|
||||
const savedThread = (
|
||||
<div
|
||||
ref={replyDisplayRef}
|
||||
className={
|
||||
classicTaskInterfaceEnabled
|
||||
? "space-y-3"
|
||||
@@ -5311,6 +5316,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
if (issue?.conversationAgentId) {
|
||||
captureAgentChatMessageSent(
|
||||
issue.originKind === "onboarding_chat" ? "onboarding_chat" : "agent_chat",
|
||||
{ companyId: comment.companyId, chatId: comment.issueId, messageId: comment.id },
|
||||
);
|
||||
}
|
||||
if (context?.optimisticCommentId) {
|
||||
@@ -5498,6 +5504,13 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
answers: AskUserQuestionsAnswer[];
|
||||
}) => 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",
|
||||
|
||||
Reference in new issue
Block a user