Measure when users see a reply to their onboarding chat input (#23574)

This commit is contained in:
scotttong authored and GitHub committed 2026-12-02 18:03:08 -08:00
1 parent 2b65b97cae
commit b0f682b66b
17 files changed
+367 -7

No files matched your search

+1
View File
@@ -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();
}
});
+98
View File
@@ -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;
}
+3 -1
View File
@@ -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!();
+40 -5
View File
@@ -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;
+15
View File
@@ -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",