Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(analytics): report completed onboarding and invitation actions (#1003)
Gener4f65c83152d1
diff --git a/src/shared/src/db/queries/community/funnel-analytics.test.ts b/src/shared/src/db/queries/community/funnel-analytics.test.tsindex c6789ea72..a6560c26e 100644--- a/src/shared/src/db/queries/community/funnel-analytics.test.ts+++ b/src/shared/src/db/queries/community/funnel-analytics.test.ts@@ -128,6 +128,9 @@ describe("Community funnel analytics ledger", () => {invitedUserId: "joined",now: "2026-09-14T00:00:04.000Z",})+ await recordInvitedHumanJoinedStatement(db, {+ ownerUserId: "owner", membershipId: "membership", invitedUserId: "joined",+ })await recordInvitedHumanJoinedStatement(db, {ownerUserId: "owner",membershipId: "bot-membership",@@ -140,7 +143,10 @@ describe("Community funnel analytics ledger", () => {expect(sqlite.prepare("SELECT source_id FROM community_funnel_analytics_event WHERE event_name = ?").get("first_agent_reply_persisted")).toEqual({ source_id: "message-first" })await expect(claimPendingEvents(db, "other")).resolves.toEqual([])- const events = await claimPendingEvents(db, "owner", "2026-09-14T00:01:00.000Z")+ const events = [+ ...await claimPendingEvents(db, "owner", "legacy", "2026-09-14T00:01:00.000Z"),+ ...await claimPendingEvents(db, "owner", "invited_human_joined", "2026-09-14T00:01:00.000Z"),+ ]expect(events.sort((a, b) => a.event.localeCompare(b.event))).toEqual([{ event: "first_agent_reply_persisted", surface: "community", conversation_type: "thread" },{ event: "invited_human_joined", surface: "community" },@@ -150,6 +156,28 @@ describe("Community funnel analytics ledger", () => {await expect(claimPendingEvents(db, "owner")).resolves.toEqual([])})++ it("keeps join facts with their inviter until a narrow claim, without competing claims stealing them", async () => {+ const insert = sqlite.prepare(`INSERT INTO community_funnel_analytics_event+ (id, owner_user_id, event_name, source_id, dedupe_key, created_at)+ VALUES (?, ?, ?, ?, ?, ?)`)+ for (const [id, owner, event] of [["runtime", "owner", "runtime_connected"], ["join", "owner", "invited_human_joined"], ["other-join", "other", "invited_human_joined"]]) {+ insert.run(id, owner, event, id, id, "2026-09-14T00:00:00.000Z")+ }+ await expect(claimPendingEvents(db, "owner")).resolves.toEqual([+ { event: "runtime_connected", surface: "community", connection_type: "local_daemon" },+ ])+ expect(sqlite.prepare("SELECT claimed_at FROM community_funnel_analytics_event WHERE id = 'join'").get()).toEqual({ claimed_at: null })+ const claimed = await Promise.all([+ claimPendingEvents(db, "owner", "invited_human_joined"),+ claimPendingEvents(db, "owner", "invited_human_joined"),+ claimPendingEvents(db, "owner"),+ ])+ expect(claimed.flat()).toEqual([{ event: "invited_human_joined", surface: "community" }])+ expect(sqlite.prepare("SELECT claimed_at FROM community_funnel_analytics_event WHERE id = 'other-join'").get()).toEqual({ claimed_at: null })+ await expect(claimPendingEvents(db, "other", "invited_human_joined")).resolves.toEqual([{ event: "invited_human_joined", surface: "community" }])+ })+it("rejects invalid event and conversation combinations at the migration boundary", () => {expect(() => sqlite.prepare(`INSERT INTO community_funnel_analytics_eventdiff --git a/src/shared/src/db/queries/community/funnel-analytics.ts b/src/shared/src/db/queries/community/funnel-analytics.tsindex 33160d888..95bd394b5 100644--- a/src/shared/src/db/queries/community/funnel-analytics.ts+++ b/src/shared/src/db/queries/community/funnel-analytics.ts@@ -1,4 +1,4 @@-import { and, eq, exists, isNull, sql } from "drizzle-orm";+import { and, eq, exists, isNull, or, sql } from "drizzle-orm";import { alias } from "drizzle-orm/sqlite-core";import { nanoid } from "nanoid";import {@@ -144,10 +144,16 @@ export function recordInvitedHumanJoinedStatement(db: Database, input: {))).onConflictDoNothing();}-export async function claimPendingEvents(db: Database, ownerUserId: string, now = new Date().toISOString()) {+export async function claimPendingEvents(db: Database, ownerUserId: string, scope: "legacy" | "invited_human_joined" = "legacy", now = new Date().toISOString()) {const rows = await db.update(communityFunnelAnalyticsEvent).set({ claimedAt: now }).where(and(eq(communityFunnelAnalyticsEvent.ownerUserId, ownerUserId),isNull(communityFunnelAnalyticsEvent.claimedAt),+ scope === "invited_human_joined"+ ? eq(communityFunnelAnalyticsEvent.eventName, "invited_human_joined")+ : or(+ eq(communityFunnelAnalyticsEvent.eventName, "runtime_connected"),+ eq(communityFunnelAnalyticsEvent.eventName, "first_agent_reply_persisted"),+ ),)).returning({eventName: communityFunnelAnalyticsEvent.eventName,conversationType: communityFunnelAnalyticsEvent.conversationType,diff --git a/src/shared/src/db/queries/community/invite-funnel-analytics.test.ts b/src/shared/src/db/queries/community/invite-funnel-analytics.test.tsindex 565bfd817..6b40b1846 100644--- a/src/shared/src/db/queries/community/invite-funnel-analytics.test.ts+++ b/src/shared/src/db/queries/community/invite-funnel-analytics.test.ts@@ -98,7 +98,7 @@ describe("invite membership funnel boundary", () => {invite: { id: "invite-human", createdBy: "owner" },member: { userId: "human", userName: "Human" },})- await expect(claimPendingEvents(db, "owner")).resolves.toEqual([+ await expect(claimPendingEvents(db, "owner", "invited_human_joined")).resolves.toEqual([{ event: "invited_human_joined", surface: "community" },])expect(sqlite.prepare("SELECT uses FROM community_server_invite WHERE id = ?").get("invite-human"))@@ -111,6 +111,6 @@ describe("invite membership funnel boundary", () => {await expect(useInvite(db, "token-bot", "bot")).resolves.toMatchObject({member: { userId: "bot" },})- await expect(claimPendingEvents(db, "owner")).resolves.toEqual([])+ await expect(claimPendingEvents(db, "owner", "invited_human_joined")).resolves.toEqual([])})})diff --git a/src/web/public/analytics-events.html b/src/web/public/analytics-events.htmlindex bda564ab0..2109d2618 100644--- a/src/web/public/analytics-events.html+++ b/src/web/public/analytics-events.html@@ -8,8 +8,12 @@ gtag('js', new Date());const fields = { page_location: 'https://alook.ai/analytics/product', page_referrer: '', page_title: 'Alook' };gtag('config', 'G-STBCL8F4ZY', { send_page_view: false, allow_google_signals: false, allow_ad_personalization_signals: false, ...fields });window.sendProductEvent = function ({ event, params }) {- if (!['landing_cta_clicked', 'login_page_view', 'sign_up', 'sign_in_success', 'sign_in_failed', 'onboarding_enter_clicked', 'onboarding_first_message', 'invitation_link_visit'].includes(event)) return;- gtag('event', event, { ...params, ...fields, send_to: 'G-STBCL8F4ZY' });+ if (!['landing_cta_clicked', 'login_page_view', 'sign_up', 'sign_in_success', 'sign_in_failed', 'onboarding_enter_clicked', 'onboarding_first_message', 'invitation_link_visit', 'community_onboarding_completed', 'human_invitation_sent', 'human_invitation_copied', 'invited_human_joined'].includes(event)) return;+ const safe = {};+ if (event === 'landing_cta_clicked' && typeof params?.cta_name === 'string') safe.cta_name = params.cta_name;+ if (['sign_up', 'sign_in_success', 'sign_in_failed'].includes(event) && ['email', 'email_otp', 'github', 'google', 'apple', 'development_password'].includes(params?.method)) safe.method = params.method;+ if (event === 'sign_in_failed' && ['send_code', 'verify_code', 'social_start', 'provider_callback'].includes(params?.failure_stage)) safe.failure_stage = params.failure_stage;+ gtag('event', event, { ...safe, ...fields, send_to: 'G-STBCL8F4ZY' });};</script><script async src="https://www.googletagmanager.com/gtag/js?id=G-STBCL8F4ZY"></script>diff --git a/src/web/src/app/api/community/analytics/funnel-events/route.test.ts b/src/web/src/app/api/community/analytics/funnel-events/route.test.tsindex ce2e9bb53..7bb9501b4 100644--- a/src/web/src/app/api/community/analytics/funnel-events/route.test.ts+++ b/src/web/src/app/api/community/analytics/funnel-events/route.test.ts@@ -1,5 +1,5 @@import { NextRequest } from "next/server"-import { describe, expect, it, vi } from "vitest"+import { beforeEach, describe, expect, it, vi } from "vitest"const mocks = vi.hoisted(() => ({db: { primary: true },@@ -27,6 +27,8 @@ vi.mock("@/lib/middleware/auth", () => ({import { POST } from "./route"+beforeEach(() => vi.clearAllMocks())+describe("POST /api/community/analytics/funnel-events", () => {it("claims only the authenticated account and disables caching", async () => {mocks.claimPendingEvents.mockResolvedValueOnce([@@ -38,7 +40,7 @@ describe("POST /api/community/analytics/funnel-events", () => {{ method: "POST", headers: { Origin: "https://alook.ai" } },))- expect(mocks.claimPendingEvents).toHaveBeenCalledWith(mocks.db, "session-user")+ expect(mocks.claimPendingEvents).toHaveBeenCalledWith(mocks.db, "session-user", "legacy")expect(response.status).toBe(200)expect(response.headers.get("Cache-Control")).toBe("no-store")expect(await response.json()).toEqual({ events: [@@ -46,3 +48,27 @@ describe("POST /api/community/analytics/funnel-events", () => {] })})})++it("claims only joins for the authenticated inviter when consent is not denied", async () => {+ mocks.claimPendingEvents.mockResolvedValueOnce([{ event: "invited_human_joined", surface: "community" }])+ const response = await POST(new NextRequest("https://alook.ai/api/community/analytics/funnel-events?event=invited_human_joined", { method: "POST" }))+ expect(mocks.claimPendingEvents).toHaveBeenLastCalledWith(mocks.db, "session-user", "invited_human_joined")+ expect(await response.json()).toEqual({ events: [{ event: "invited_human_joined", surface: "community" }] })+})++it("does not consume joins for a denied cookie", async () => {+ mocks.claimPendingEvents.mockClear()+ const response = await POST(new NextRequest("https://alook.ai/api/community/analytics/funnel-events?event=invited_human_joined", {+ method: "POST", headers: { Cookie: "alook_analytics_consent=v1.denied" },+ }))+ expect(mocks.claimPendingEvents).not.toHaveBeenCalled()+ expect(await response.json()).toEqual({ events: [] })+ expect(response.headers.get("Cache-Control")).toBe("no-store")+})++it("rejects arbitrary claim categories before the database write", async () => {+ mocks.claimPendingEvents.mockClear()+ const response = await POST(new NextRequest("https://alook.ai/api/community/analytics/funnel-events?event=all", { method: "POST" }))+ expect(response.status).toBe(400)+ expect(mocks.claimPendingEvents).not.toHaveBeenCalled()+})diff --git a/src/web/src/app/api/community/analytics/funnel-events/route.ts b/src/web/src/app/api/community/analytics/funnel-events/route.tsindex 91b98e015..df4d95d95 100644--- a/src/web/src/app/api/community/analytics/funnel-events/route.ts+++ b/src/web/src/app/api/community/analytics/funnel-events/route.ts@@ -1,12 +1,16 @@import { queries } from "@alook/shared"import { getPrimaryDb } from "@/lib/db"import { withCookieHumanAuth } from "@/lib/middleware/auth"-import { writeJSON } from "@/lib/middleware/helpers"+import { readAnalyticsConsent } from "@/lib/analytics-consent"+import { writeError, writeJSON } from "@/lib/middleware/helpers"-export const POST = withCookieHumanAuth(async (_req, ctx) => {- const events = await queries.communityFunnelAnalytics.claimPendingEvents(+export const POST = withCookieHumanAuth(async (req, ctx) => {+ const scope = req.nextUrl.searchParams.get("event") ?? "legacy"+ if (scope !== "legacy" && scope !== "invited_human_joined") return writeError("invalid event scope", 400)+ const events = scope === "invited_human_joined" && readAnalyticsConsent(req.headers.get("cookie") ?? "") === "denied" ? [] : await queries.communityFunnelAnalytics.claimPendingEvents(getPrimaryDb(ctx.env.DB),ctx.userId,+ scope,)const response = writeJSON({ events })response.headers.set("Cache-Control", "no-store")diff --git a/src/web/src/components/community/onboarding/community-onboarding-form.navigation.dom.test.ts b/src/web/src/components/community/onboarding/community-onboarding-form.navigation.dom.test.tsindex 5110265ee..cbebb8091 100644--- a/src/web/src/components/community/onboarding/community-onboarding-form.navigation.dom.test.ts+++ b/src/web/src/components/community/onboarding/community-onboarding-form.navigation.dom.test.ts@@ -28,7 +28,7 @@ const mocks = vi.hoisted(() => ({} as Record<string, unknown>,}))-vi.mock("@/lib/product-analytics", () => ({ beginOnboardingAnalytics: (_userId: string, serverId: string) => mocks.capture({ event: "onboarding_enter_clicked", serverId }) }))+vi.mock("@/lib/product-analytics", () => ({ captureProductAnalytics: (input: unknown) => mocks.capture(input), beginOnboardingAnalytics: (_userId: string, serverId: string) => mocks.capture({ event: "onboarding_enter_clicked", serverId }) }))vi.mock("next/navigation", () => ({usePathname: () => mocks.pathname,}))@@ -131,6 +131,9 @@ describe("CommunityOnboardingForm room navigation", () => {mocks.pathname = "/c/channels/server-1/channel-1"rendered.rerender(createElement(CommunityOnboardingForm))expect(mocks.complete).toHaveBeenCalledTimes(1)+ expect(mocks.capture).toHaveBeenCalledWith({ event: "community_onboarding_completed" })+ rendered.rerender(createElement(CommunityOnboardingForm))+ expect(mocks.capture.mock.calls.filter(([input]) => input.event === "community_onboarding_completed")).toHaveLength(1)})it("counts Enter even when the shell cannot navigate to the room", async () => {diff --git a/src/web/src/components/community/onboarding/community-onboarding-form.tsx b/src/web/src/components/community/onboarding/community-onboarding-form.tsxindex 73b08211e..f7873e039 100644--- a/src/web/src/components/community/onboarding/community-onboarding-form.tsx+++ b/src/web/src/components/community/onboarding/community-onboarding-form.tsx@@ -115,7 +115,7 @@ export function CommunityOnboardingForm() {useEffect(() => {const pendingDestination = protocol?.pendingDestinationif (!pendingDestination || pathname !== pendingDestination) return- completeCommunityOnboarding(communityRuntime)+ completeCommunityOnboarding(communityRuntime, pathname)}, [pathname, protocol?.pendingDestination, communityRuntime])const mutateInitialization = initialization.mutateAsyncdiff --git a/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts b/src/web/src/components/community/onboarding/onboarding-preview-flow.test.tsindex 450048e43..36f4961a6 100644--- a/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts+++ b/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts@@ -95,7 +95,7 @@ describe("onboarding preview flow", () => {/onContinue=\{async \(\) => \{[\s\S]*?pendingDestination: destination[\s\S]*?navigate\(initializationResult\.serverId, initializationResult\.publicChannelId\)/,)expect(onboardingFormSource).toMatch(- /const pendingDestination = protocol\?\.pendingDestination[\s\S]*?pathname !== pendingDestination[\s\S]*?completeCommunityOnboarding\(communityRuntime\)/,+ /const pendingDestination = protocol\?\.pendingDestination[\s\S]*?pathname !== pendingDestination[\s\S]*?completeCommunityOnboarding\(communityRuntime, pathname\)/,)})})diff --git a/src/web/src/components/community/social/invite-dialog.test.ts b/src/web/src/components/community/social/invite-dialog.test.tsindex 035ea8f95..48d708dbf 100644--- a/src/web/src/components/community/social/invite-dialog.test.ts+++ b/src/web/src/components/community/social/invite-dialog.test.ts@@ -59,9 +59,11 @@ vi.mock("@/hooks/community/use-dm-message-sender", () => ({vi.mock("@/contexts/community/current-user", () => ({useCurrentUser: () => ({ id: "viewer", name: "Viewer", avatar: "V" }),}))-vi.mock("@/lib/analytics", () => ({- trackHumanInvitationSent: mocks.trackHumanInvitationSent,- trackHumanInvitationCopied: mocks.trackHumanInvitationCopied,+vi.mock("@/lib/product-analytics", () => ({+ captureProductAnalytics: ({ event }: { event: string }) => {+ if (event === "human_invitation_sent") mocks.trackHumanInvitationSent()+ if (event === "human_invitation_copied") mocks.trackHumanInvitationCopied()+ },}))vi.mock("@/components/ui/dialog", async () => {const { createElement } = await import("react")@@ -371,3 +373,10 @@ describe("invite funnel completion boundaries", () => {expect(mocks.trackHumanInvitationCopied).not.toHaveBeenCalled()})})++it("does not count a retired invite owner after the receipt commits", async () => {+ const assert = () => { throw new DOMException("retired", "AbortError") }+ const publish = vi.fn()+ await expect(awaitCommittedInvite({ accepted: true, nonce: "nonce", committed: Promise.resolve({ ok: true, message: { id: "message", seq: 1 } }) }, () => { assert(); publish() })).rejects.toThrow("retired")+ expect(publish).not.toHaveBeenCalled()+})diff --git a/src/web/src/components/community/social/invite-dialog.tsx b/src/web/src/components/community/social/invite-dialog.tsxindex eb5cb08a5..17d913546 100644--- a/src/web/src/components/community/social/invite-dialog.tsx+++ b/src/web/src/components/community/social/invite-dialog.tsx@@ -21,7 +21,7 @@ import { useCommunityViewSource } from "@/hooks/community/use-community-view-souimport { useInvites } from "@/hooks/community/use-server-panels"import { isAbortError } from "@/lib/errors"import type { Friend } from "@/lib/community/models/people"-import { trackHumanInvitationCopied, trackHumanInvitationSent } from "@/lib/analytics"+import { captureProductAnalytics } from "@/lib/product-analytics"const INVITE_ORIGIN =typeof window !== "undefined" ? window.location.origin : ""@@ -110,7 +110,7 @@ export async function runInviteFriend(export async function awaitCommittedInvite(receipt: DmSendReceipt,- onCommitted: () => void = trackHumanInvitationSent,+ onCommitted: () => void = () => { void captureProductAnalytics({ event: "human_invitation_sent" }) },) {if (!receipt.accepted) throw new Error("Couldn't send invite")const committed = await receipt.committed@@ -121,7 +121,7 @@ export async function awaitCommittedInvite(export async function copyInviteLink(url: string,writeText: (value: string) => Promise<void>,- onCopied: () => void = trackHumanInvitationCopied,+ onCopied: () => void = () => { void captureProductAnalytics({ event: "human_invitation_copied" }) },) {await writeText(url)onCopied()@@ -183,7 +183,7 @@ export function InviteDialog({const { conversation } = await createOrGetDm.mutateAsync({ userId, assertActive: assert })assert()const receipt = acceptDmMessage({ dmId: conversation.id, content: inviteUrl(token), author, assertActive: assert })- await awaitCommittedInvite(receipt, () => { assert(); trackHumanInvitationSent() })+ await awaitCommittedInvite(receipt, () => { assert(); void captureProductAnalytics({ event: "human_invitation_sent" }, assert) })assert()ui.setState((state) => ({ ...state, invitedUserIds: new Set(state.invitedUserIds).add(userId) }))},@@ -198,7 +198,7 @@ export function InviteDialog({gcTime: 0,mutationFn: async ({ token, assert }: { token: string; assert: ReturnType<typeof view.capture> }) => {assert()- await copyInviteLink(inviteUrl(token), (value) => { assert(); return navigator.clipboard.writeText(value) }, () => { assert(); trackHumanInvitationCopied() })+ await copyInviteLink(inviteUrl(token), (value) => { assert(); return navigator.clipboard.writeText(value) }, () => { assert(); void captureProductAnalytics({ event: "human_invitation_copied" }, assert) })assert()toast("Invite link copied")},diff --git a/src/web/src/hooks/community/use-community-ws.dom.test.ts b/src/web/src/hooks/community/use-community-ws.dom.test.tsindex c3c718b1b..8089cf9f8 100644--- a/src/web/src/hooks/community/use-community-ws.dom.test.ts+++ b/src/web/src/hooks/community/use-community-ws.dom.test.ts@@ -1,3 +1,6 @@+import { act, fireEvent } from "@/test/react-dom-harness"+import { ANALYTICS_CONSENT_CHANGE_EVENT } from "@/lib/analytics-consent"+import * as funnel from "@/lib/community/funnel-analytics"import { getCapturedRuntime } from "./community-ws/test-harness"/*** Root Community WebSocket boundary and transport-ownership tests.@@ -273,3 +276,14 @@ describe("useCommunityWs — double-mount detection", () => {}})})++it("requests inviter joins on current-account authentication and consent changes", async () => {+ const joined = vi.spyOn(funnel, "drainInvitedHumanJoined").mockResolvedValue(undefined)+ await mountHook({ viewerUserId: "u_me" })+ await act(async () => { await capturedUseUserWsOptions?.onAuthenticated?.() })+ expect(joined).toHaveBeenCalledWith(getCapturedRuntime().lifecycle)+ const before = joined.mock.calls.length+ fireEvent(window, new Event(ANALYTICS_CONSENT_CHANGE_EVENT))+ expect(joined).toHaveBeenCalledTimes(before + 1)+ expect(joined).toHaveBeenLastCalledWith(getCapturedRuntime().lifecycle)+})diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex 623788541..b4fcedd11 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -50,7 +50,8 @@ import {createCommunityWsConnectionStatusController,type CommunityWsConnectionStatusController,} from "@/hooks/community/community-ws/connection-status"-import { drainCommunityFunnelEvents } from "@/lib/community/funnel-analytics"+import { ANALYTICS_CONSENT_CHANGE_EVENT } from "@/lib/analytics-consent"+import { drainCommunityFunnelEvents, drainInvitedHumanJoined } from "@/lib/community/funnel-analytics"export type {Subscription,@@ -491,6 +492,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {)if (hasCommunityFunnelTrigger(decoded.events)) {void drainCommunityFunnelEvents()+ void drainInvitedHumanJoined(runtime.lifecycle)}return}@@ -511,6 +513,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {await dispatchCommunityWsEvent(decoded.event, context("single"))if (hasCommunityFunnelTrigger([decoded.event])) {void drainCommunityFunnelEvents()+ void drainInvitedHumanJoined(runtime.lifecycle)}},[queryClient, runtime.lifecycle, runtime.ui, runtime.ws, scheduleInboxInvalidate],@@ -527,6 +530,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {}}, [queryClient])const handleAuthenticated = useCallback(async () => {+ void drainInvitedHumanJoined(runtime.lifecycle)runtime.ws.actions.markAccessConnected()const viewerId = viewerUserIdRef.currentif (viewerId) {@@ -538,7 +542,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {scheduleAccountAttentionReconcile(queryClient)}await reconcileAccountReadState(queryClient, { surfaceMode: "non-inbox" })- }, [queryClient, runtime.ws.actions])+ }, [queryClient, runtime.ws.actions, runtime.lifecycle])const handleForeground = useCallback(() => {if (inboxRefreshOwner.current?.disposed|| viewerUserIdRef.current !== viewerUserId@@ -559,6 +563,12 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {reconnectTransportRef.current = reconnectNow}, [reconnectNow])+ useEffect(() => {+ const drain = () => { void drainInvitedHumanJoined(runtime.lifecycle) }+ window.addEventListener(ANALYTICS_CONSENT_CHANGE_EVENT, drain)+ return () => window.removeEventListener(ANALYTICS_CONSENT_CHANGE_EVENT, drain)+ }, [runtime.lifecycle])+useEffect(() => {if (typeof document === "undefined" || typeof window === "undefined") returnconst reconcileVisible = () => {diff --git a/src/web/src/lib/community-onboarding.test.ts b/src/web/src/lib/community-onboarding.test.tsindex d2f22d1ab..d2699b94c 100644--- a/src/web/src/lib/community-onboarding.test.ts+++ b/src/web/src/lib/community-onboarding.test.ts@@ -5,6 +5,7 @@ const analytics = vi.hoisted(() => ({stageCompleted: vi.fn(),completed: vi.fn(),skipped: vi.fn(),+ product: vi.fn(),}));vi.mock("@/lib/analytics", () => ({@@ -14,6 +15,8 @@ vi.mock("@/lib/analytics", () => ({trackCommunityOnboardingSkipped: analytics.skipped,}));+vi.mock("@/lib/product-analytics", () => ({ captureProductAnalytics: analytics.product }));+import { QueryClient } from "@tanstack/react-query";import { createCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections";@@ -27,6 +30,7 @@ import {startCommunityOnboarding,subscribeCommunityOnboarding,updateCommunityOnboardingResources,+ updateCommunityOnboardingInitialization,} from "./community-onboarding";describe("community onboarding journey", () => {@@ -129,12 +133,31 @@ describe("community onboarding journey", () => {advanceCommunityOnboarding(runtime(), "harness", "machine");advanceCommunityOnboarding(runtime(), "machine", "identity");advanceCommunityOnboarding(runtime(), "identity", "initializing");- completeCommunityOnboarding(runtime());+ const result = { serverId: "server", publicChannelId: "channel", privateChannelId: "private", leadBotId: "lead", bots: [] };+ updateCommunityOnboardingInitialization(runtime(), current => ({ ...current, result, pendingDestination: "/c/channels/server/channel" }));+ completeCommunityOnboarding(runtime(), "/c/channels/server/channel");+ completeCommunityOnboarding(runtime(), "/c/channels/server/channel");expect(readCommunityOnboardingState(runtime())).toBeNull();+ expect(analytics.product).toHaveBeenCalledOnce();+ expect(analytics.product).toHaveBeenCalledWith({ event: "community_onboarding_completed" }, expect.any(Function));expect(analytics.stageCompleted).toHaveBeenLastCalledWith("initializing");expect(analytics.completed).not.toHaveBeenCalled();});+ it("does not clear or emit for a pending initialization or an uncommitted destination", () => {+ startCommunityOnboarding(runtime());+ advanceCommunityOnboarding(runtime(), "harness", "initializing");+ completeCommunityOnboarding(runtime(), "/c/channels/server/channel");+ expect(readCommunityOnboardingState(runtime())?.stage).toBe("initializing");+ const result = { serverId: "server", publicChannelId: "channel", privateChannelId: "private", leadBotId: "lead", bots: [] };+ updateCommunityOnboardingInitialization(runtime(), current => ({ ...current, result, pendingDestination: "/c/channels/server/channel" }));+ completeCommunityOnboarding(runtime(), "/c/me");+ expect(readCommunityOnboardingState(runtime())?.stage).toBe("initializing");+ skipCommunityOnboarding(runtime());+ completeCommunityOnboarding(runtime(), "/c/channels/server/channel");+ expect(analytics.product).not.toHaveBeenCalled();+ });+it("does not complete before initialization finishes", () => {startCommunityOnboarding(runtime());expect(completeCommunityOnboarding(runtime())).toEqual({ status: "active", stage: "harness" });diff --git a/src/web/src/lib/community-onboarding.ts b/src/web/src/lib/community-onboarding.tsindex 73e6939f1..6071bb404 100644--- a/src/web/src/lib/community-onboarding.ts+++ b/src/web/src/lib/community-onboarding.ts@@ -1,5 +1,7 @@"use client";+import { captureProductAnalytics } from "@/lib/product-analytics";+import { useSelector } from "@tanstack/react-store";import { useCommunityRuntime, type CommunityRuntime } from "@/stores/community/runtime";import type { OnboardingInitializationProtocol } from "./community/models/onboarding";@@ -103,13 +105,20 @@ export function recoverCommunityOnboardingMachine(runtime: CommunityRuntime) {return publish(runtime, { ...currentState, machineRecovery: true });}-export function completeCommunityOnboarding(runtime: CommunityRuntime) {+export function completeCommunityOnboarding(runtime: CommunityRuntime, pathname?: string) {const currentState = readCommunityOnboardingState(runtime);if (currentState?.status !== "active" || currentState.stage !== "initializing") {return currentState;}+ const protocol = currentState.initialization;+ const result = protocol?.result;+ if (!result || protocol.pendingDestination !== `/c/channels/${result.serverId}/${result.publicChannelId}` || pathname !== protocol.pendingDestination) return currentState;+ const generation = runtime.lifecycle.get().generation;publish(runtime, null);trackCommunityOnboardingStageCompleted("initializing");+ void captureProductAnalytics({ event: "community_onboarding_completed" }, () => {+ if (!runtime.lifecycle.get().active || runtime.lifecycle.get().generation !== generation) throw new DOMException("Retired onboarding owner", "AbortError");+ });return null;}diff --git a/src/web/src/lib/community/funnel-analytics.test.ts b/src/web/src/lib/community/funnel-analytics.test.tsindex c79abf41f..e9c5aeeb6 100644--- a/src/web/src/lib/community/funnel-analytics.test.ts+++ b/src/web/src/lib/community/funnel-analytics.test.ts@@ -1,9 +1,12 @@-import { beforeEach, describe, expect, it, vi } from "vitest"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"const mocks = vi.hoisted(() => ({runtime: vi.fn(),reply: vi.fn(),joined: vi.fn(),+ product: vi.fn(),+ native: false,+ consent: null as string | null,}))vi.mock("@/lib/analytics", () => ({@@ -12,7 +15,13 @@ vi.mock("@/lib/analytics", () => ({trackInvitedHumanJoined: mocks.joined,}))+vi.mock("@alook/shared", () => ({ isTauri: () => mocks.native }))+vi.mock("@/lib/analytics-consent", () => ({ readAnalyticsConsent: () => mocks.consent }))+vi.mock("@/lib/product-analytics", () => ({ captureProductAnalytics: mocks.product }))+import { createStore } from "@tanstack/store"+import {+ drainInvitedHumanJoined,_resetCommunityFunnelAnalyticsForTesting,decodeCommunityFunnelEvents,drainCommunityFunnelEvents,@@ -70,7 +79,8 @@ describe("Community funnel analytics drain", () => {})expect(mocks.runtime).toHaveBeenCalledOnce()expect(mocks.reply).toHaveBeenCalledWith("thread")- expect(mocks.joined).toHaveBeenCalledOnce()+ expect(mocks.joined).not.toHaveBeenCalled()+ expect(mocks.product).not.toHaveBeenCalled()})it("fails open on fetch errors and non-success responses", async () => {@@ -84,3 +94,94 @@ describe("Community funnel analytics drain", () => {expect(mocks.runtime).not.toHaveBeenCalled()})})++describe("inviter Web join drain", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ _resetCommunityFunnelAnalyticsForTesting()+ mocks.native = false+ mocks.consent = null+ vi.stubGlobal("window", {})+ })+ afterEach(() => vi.unstubAllGlobals())+ const joined = { event: "invited_human_joined", surface: "community" }++ it.each([null, "granted"])("claims only joins and publishes through the finite sender with %s consent", async (consent) => {+ mocks.consent = consent+ const lifecycle = createStore({ active: true, generation: 1 })+ const fetchMock = vi.fn().mockResolvedValue(response({ events: [joined, { event: "runtime_connected", surface: "community", connection_type: "local_daemon" }] }))+ vi.stubGlobal("fetch", fetchMock)+ await drainInvitedHumanJoined(lifecycle)+ expect(fetchMock).toHaveBeenCalledWith("/api/community/analytics/funnel-events?event=invited_human_joined", expect.objectContaining({ method: "POST", credentials: "same-origin", cache: "no-store", signal: expect.any(AbortSignal) }))+ expect(mocks.product).toHaveBeenCalledOnce()+ expect(mocks.product).toHaveBeenCalledWith({ event: "invited_human_joined" }, expect.any(Function))+ expect(mocks.runtime).not.toHaveBeenCalled()+ })++ it("does not claim under denied, Native or retired ownership", async () => {+ const lifecycle = createStore({ active: true, generation: 1 })+ const fetchMock = vi.fn()+ vi.stubGlobal("fetch", fetchMock)+ mocks.consent = "denied"+ await drainInvitedHumanJoined(lifecycle)+ mocks.consent = null; mocks.native = true+ await drainInvitedHumanJoined(lifecycle)+ mocks.native = false+ lifecycle.setState(state => ({ ...state, active: false }))+ await drainInvitedHumanJoined(lifecycle)+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it.each(["owner", "consent"])("rejects a late receipt and aborts retired requests after %s changes", async (change) => {+ const lifecycle = createStore({ active: true, generation: 1 })+ let finish!: (response: Response) => void+ const pending = new Promise<Response>(resolve => { finish = resolve })+ const fetchMock = vi.fn().mockReturnValue(pending)+ vi.stubGlobal("fetch", fetchMock)+ const drain = drainInvitedHumanJoined(lifecycle)+ const signal: AbortSignal = fetchMock.mock.calls[0][1].signal+ if (change === "owner") lifecycle.setState(state => ({ ...state, active: false, generation: state.generation + 1 }))+ else mocks.consent = "denied"+ if (change === "owner") expect(signal.aborted).toBe(true)+ finish(response({ events: [joined] }))+ await drain+ expect(mocks.product).not.toHaveBeenCalled()+ })++ it("coalesces within one owner and lets an independent replacement claim immediately", async () => {+ const lifecycle = createStore({ active: true, generation: 1 })+ const replacement = createStore({ active: true, generation: 1 })+ let finish!: (response: Response) => void+ const fetchMock = vi.fn().mockReturnValueOnce(new Promise<Response>(resolve => { finish = resolve }))+ .mockResolvedValue(response({ events: [] }))+ vi.stubGlobal("fetch", fetchMock)+ const original = drainInvitedHumanJoined(lifecycle)+ expect(drainInvitedHumanJoined(lifecycle)).toBe(original)+ await drainInvitedHumanJoined(replacement)+ finish(response({ events: [joined] }))+ await original+ expect(fetchMock).toHaveBeenCalledTimes(3)+ const guard = mocks.product.mock.calls[0][1] as () => void+ lifecycle.setState(state => ({ ...state, active: false }))+ expect(guard).toThrow("Retired invitation analytics owner")+ })++ it("leaves business execution unaffected by network and rejected responses", async () => {+ const lifecycle = createStore({ active: true, generation: 1 })+ vi.stubGlobal("fetch", vi.fn().mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce(response({}, false)))+ await expect(drainInvitedHumanJoined(lifecycle)).resolves.toBeUndefined()+ await expect(drainInvitedHumanJoined(lifecycle)).resolves.toBeUndefined()+ expect(mocks.product).not.toHaveBeenCalled()+ })+})++it("does not claim a browser event without a browser", async () => {+ const lifecycle = createStore({ active: true, generation: 1 })+ const fetchMock = vi.fn()+ vi.stubGlobal("window", undefined)+ vi.stubGlobal("fetch", fetchMock)+ try {+ await drainInvitedHumanJoined(lifecycle)+ expect(fetchMock).not.toHaveBeenCalled()+ } finally { vi.unstubAllGlobals() }+})diff --git a/src/web/src/lib/community/funnel-analytics.ts b/src/web/src/lib/community/funnel-analytics.tsindex c945db46b..9e94058d8 100644--- a/src/web/src/lib/community/funnel-analytics.ts+++ b/src/web/src/lib/community/funnel-analytics.ts@@ -1,10 +1,12 @@"use client"-import type { CommunityFunnelAnalyticsEvent } from "@alook/shared"+import { isTauri, type CommunityFunnelAnalyticsEvent } from "@alook/shared"+import { readAnalyticsConsent } from "@/lib/analytics-consent"+import { captureProductAnalytics } from "@/lib/product-analytics"+import type { CommunityRuntime } from "@/stores/community/runtime"import {trackCommunityRuntimeConnected,trackFirstAgentReplyPersisted,- trackInvitedHumanJoined,} from "@/lib/analytics"let inFlight: Promise<void> | null = null@@ -62,8 +64,6 @@ function publishCommunityFunnelEvent(event: CommunityFunnelAnalyticsEvent) {trackCommunityRuntimeConnected()} else if (event.event === "first_agent_reply_persisted") {trackFirstAgentReplyPersisted(event.conversation_type)- } else {- trackInvitedHumanJoined()}}@@ -103,4 +103,58 @@ export function drainCommunityFunnelEvents(): Promise<void> {export function _resetCommunityFunnelAnalyticsForTesting() {inFlight = nullrerun = false+ joinDrains = new WeakMap()+}+++type Lifecycle = CommunityRuntime["lifecycle"]+type JoinDrain = { generation: number; rerun: boolean; inFlight: Promise<void> }+let joinDrains = new WeakMap<Lifecycle, JoinDrain>()++export function drainInvitedHumanJoined(lifecycle: Lifecycle): Promise<void> {+ const generation = lifecycle.get().generation+ const eligible = () => typeof window !== "undefined" && !isTauri()+ && readAnalyticsConsent() !== "denied"+ && lifecycle.get().active && lifecycle.get().generation === generation+ if (!eligible()) return Promise.resolve()+ const existing = joinDrains.get(lifecycle)+ if (existing?.generation === generation) {+ existing.rerun = true+ return existing.inFlight+ }+ const assertCurrent = () => {+ if (!eligible()) throw new DOMException("Retired invitation analytics owner", "AbortError")+ }+ const controller = new AbortController()+ const subscription = lifecycle.subscribe(() => {+ if (!lifecycle.get().active || lifecycle.get().generation !== generation) controller.abort()+ })+ const drain: JoinDrain = { generation, rerun: false, inFlight: Promise.resolve() }+ drain.inFlight = (async () => {+ do {+ drain.rerun = false+ assertCurrent()+ const response = await fetch("/api/community/analytics/funnel-events?event=invited_human_joined", {+ method: "POST",+ cache: "no-store",+ credentials: "same-origin",+ signal: controller.signal,+ })+ assertCurrent()+ if (!response.ok) return+ const payload: unknown = await response.json()+ assertCurrent()+ for (const event of decodeCommunityFunnelEvents(payload)) {+ if (event.event === "invited_human_joined") {+ await captureProductAnalytics({ event: "invited_human_joined" }, assertCurrent)+ }+ }+ } while (drain.rerun)+ })().catch(() => undefined).finally(() => {+ subscription.unsubscribe()+ controller.abort()+ if (joinDrains.get(lifecycle) === drain) joinDrains.delete(lifecycle)+ })+ joinDrains.set(lifecycle, drain)+ return drain.inFlight}diff --git a/src/web/src/lib/product-analytics-contract.ts b/src/web/src/lib/product-analytics-contract.tsindex 8bfd648db..eb2d99b69 100644--- a/src/web/src/lib/product-analytics-contract.ts+++ b/src/web/src/lib/product-analytics-contract.ts@@ -3,3 +3,9 @@ export const LANDING_CTA_NAMES = ["pricing_open_app", "pricing_get_started", "templates_open_app", "templates_get_started", "closing_open_app", "closing_get_started",...["product", "identity", "continuity", "reach", "ownership"].flatMap(section => [`${section}_open_app`, `${section}_get_started`]),] as const++export const PRODUCT_ANALYTICS_EVENTS = [+ "landing_cta_clicked", "login_page_view", "sign_up", "sign_in_success", "sign_in_failed",+ "onboarding_enter_clicked", "onboarding_first_message", "invitation_link_visit",+ "community_onboarding_completed", "human_invitation_sent", "human_invitation_copied", "invited_human_joined",+] as constdiff --git a/src/web/src/lib/product-analytics-document.test.ts b/src/web/src/lib/product-analytics-document.test.tsnew file mode 100644index 000000000..80a6bef5d--- /dev/null+++ b/src/web/src/lib/product-analytics-document.test.ts@@ -0,0 +1,37 @@+import { readFileSync } from "node:fs"+import { runInNewContext } from "node:vm"+import { describe, expect, it } from "vitest"+import { PRODUCT_ANALYTICS_EVENTS } from "./product-analytics-contract"++function documentSender() {+ const html = readFileSync(new URL("../../public/analytics-events.html", import.meta.url), "utf8")+ const script = html.match(/<script>([\s\S]*?)<\/script>/)?.[1]+ if (!script) throw new Error("missing event document script")+ const window = { dataLayer: [] as ArrayLike<unknown>[], sendProductEvent: (_input: { event: string; params: Record<string, string> }) => {} }+ runInNewContext(script, { window })+ window.dataLayer.length = 0+ return window+}++describe("actual isolated product-event document", () => {+ it("accepts exactly the twelve finite names while keeping fixed private-page metadata", () => {+ const document = documentSender()+ for (const event of PRODUCT_ANALYTICS_EVENTS) document.sendProductEvent({ event, params: { private_id: "secret", page_location: "https://private.test/token", method: "private", failure_stage: "private" } })+ document.sendProductEvent({ event: "unknown", params: {} })+ const commands = document.dataLayer.map(command => Array.from(command))+ expect(commands).toHaveLength(12)+ expect(commands.map(command => command[1])).toEqual([...PRODUCT_ANALYTICS_EVENTS])+ for (const command of commands) expect(command[2]).toEqual({ page_location: "https://alook.ai/analytics/product", page_referrer: "", page_title: "Alook", send_to: "G-STBCL8F4ZY" })+ expect(JSON.stringify(commands)).not.toContain("secret")+ })+})++it("retains the existing allowed authentication dimensions in the actual event document", () => {+ const document = documentSender()+ document.sendProductEvent({ event: "sign_up", params: { method: "email" } })+ document.sendProductEvent({ event: "sign_in_failed", params: { method: "github", failure_stage: "social_start" } })+ document.sendProductEvent({ event: "landing_cta_clicked", params: { cta_name: "get_started" } })+ expect(Array.from(document.dataLayer[0])[2]).toMatchObject({ method: "email" })+ expect(Array.from(document.dataLayer[1])[2]).toMatchObject({ method: "github", failure_stage: "social_start" })+ expect(Array.from(document.dataLayer[2])[2]).toMatchObject({ cta_name: "get_started" })+})diff --git a/src/web/src/lib/product-analytics.dom.test.ts b/src/web/src/lib/product-analytics.dom.test.tsindex 257ffcd35..7acceb032 100644--- a/src/web/src/lib/product-analytics.dom.test.ts+++ b/src/web/src/lib/product-analytics.dom.test.ts@@ -1,9 +1,12 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { fireEvent } from "@/test/react-dom-harness"+import { QueryClient } from "@tanstack/react-query"+import { createCommunityDbRegistry, registerCommunityDbRegistry } from "@/lib/community-db/collections"+import { advanceCommunityOnboarding, completeCommunityOnboarding, readCommunityOnboardingState, startCommunityOnboarding, updateCommunityOnboardingInitialization } from "./community-onboarding"const mocks = vi.hoisted(() => ({ native: false, consent: null as string | null }))vi.mock("@alook/shared", async original => ({ ...await original<typeof import("@alook/shared")>(), isTauri: () => mocks.native }))vi.mock("@/lib/analytics-consent", async original => ({ ...await original<typeof import("@/lib/analytics-consent")>(), readAnalyticsConsent: () => mocks.consent }))-import { beginOnboardingAnalytics, captureOnboardingFirstMessage, captureProductAnalytics } from "./product-analytics"+import { beginOnboardingAnalytics, captureOnboardingFirstMessage, captureProductAnalytics, type ProductAnalyticsInput } from "./product-analytics"beforeEach(() => {window.history.replaceState(null, "", "/sign-in")@@ -110,3 +113,90 @@ describe("frontend product analytics", () => {expect(send.mock.calls.map(([input]) => input.event)).toEqual(["onboarding_enter_clicked", "onboarding_first_message", "onboarding_enter_clicked", "onboarding_first_message"])})})++const addedEvents = ["community_onboarding_completed", "human_invitation_sent", "human_invitation_copied", "invited_human_joined"] as const+it.each(addedEvents)("sends only the finite %s name, without private or unrelated business fields", async (event) => {+ await captureProductAnalytics({ event, method: "email", serverId: "private-id", token: "private-token" } as ProductAnalyticsInput)+ const { send } = loadFrame()+ expect(send).toHaveBeenCalledOnce()+ expect(send).toHaveBeenCalledWith({ event, params: {} })+})++it.each(addedEvents)("does not send or attach %s for Native or explicit denial", async event => {+ mocks.native = true+ await captureProductAnalytics({ event })+ mocks.native = false; mocks.consent = "denied"+ await captureProductAnalytics({ event })+ expect(document.getElementById("alook-product-events")).toBeNull()+})++it("rejects unknown event names before either public or isolated transport", async () => {+ const input: ProductAnalyticsInput = JSON.parse('{"event":"private-arbitrary-event"}')+ await captureProductAnalytics(input)+ window.history.replaceState(null, "", "/")+ await captureProductAnalytics(input)+ expect(document.getElementById("alook-product-events")).toBeNull()+ expect(window.dataLayer).toEqual([])+})++it("does not publish a queued event after its original owner retires", async () => {+ let active = true+ await captureProductAnalytics({ event: "invited_human_joined" }, () => { if (!active) throw new Error("retired") })+ active = false+ const { send } = loadFrame()+ expect(send).not.toHaveBeenCalled()+})++it.each(["active", "retired", "reactivated"] as const)("qualifies delayed onboarding completion against its %s original owner", async ownership => {+ const client = new QueryClient()+ const registry = createCommunityDbRegistry(client, "onboarding-owner")+ const retire = registerCommunityDbRegistry(registry)+ const pathname = "/c/channels/server/channel"+ window.history.replaceState(null, "", pathname)+ try {+ startCommunityOnboarding(registry.runtime)+ advanceCommunityOnboarding(registry.runtime, "harness", "initializing")+ const result = { serverId: "server", publicChannelId: "channel", privateChannelId: "private", leadBotId: "lead", bots: [] }+ updateCommunityOnboardingInitialization(registry.runtime, current => ({ ...current, result, pendingDestination: pathname }))++ expect(completeCommunityOnboarding(registry.runtime, pathname)).toBeNull()+ expect(readCommunityOnboardingState(registry.runtime)).toBeNull()+ expect(document.getElementById("alook-product-events")).not.toBeNull()+ expect(document.getElementById("alook-product-events")?.getAttribute("data-ready")).toBeNull()+ completeCommunityOnboarding(registry.runtime, pathname)++ if (ownership !== "active") retire()+ if (ownership === "reactivated") registerCommunityDbRegistry(registry)+ const { send } = loadFrame()+ if (ownership === "active") {+ expect(send).toHaveBeenCalledOnce()+ expect(send).toHaveBeenCalledWith({ event: "community_onboarding_completed", params: {} })+ } else {+ expect(send).not.toHaveBeenCalled()+ }+ } finally {+ await registry.cleanup()+ client.clear()+ }+})++it.each([+ { event: "sign_up", method: "email" },+ { event: "sign_in_success", method: "google" },+ { event: "sign_in_failed", method: "github", failureStage: "social_start" },+] as const)("retains the existing $event dimensions", async input => {+ await captureProductAnalytics(input)+ const { send } = loadFrame()+ expect(send).toHaveBeenCalledWith({ event: input.event, params: { method: input.method, ...("failureStage" in input ? { failure_stage: input.failureStage } : {}) } })+})++it("does not send a detached event frame after consent is granted again", async () => {+ await captureProductAnalytics({ event: "invited_human_joined" })+ const frame = document.getElementById("alook-product-events") as HTMLIFrameElement+ const send = vi.fn()+ Object.defineProperty(frame.contentWindow, "sendProductEvent", { value: send, configurable: true })+ frame.remove()+ mocks.consent = "granted"+ fireEvent.load(frame)+ expect(send).not.toHaveBeenCalled()+})diff --git a/src/web/src/lib/product-analytics.ts b/src/web/src/lib/product-analytics.tsindex e22298770..d5b5aeed5 100644--- a/src/web/src/lib/product-analytics.ts+++ b/src/web/src/lib/product-analytics.ts@@ -2,7 +2,7 @@import { isTauri } from "@alook/shared"import { googleCommand, isPublicAnalyticsPath, readAnalyticsConsent } from "@/lib/analytics-consent"-import { LANDING_CTA_NAMES } from "@/lib/product-analytics-contract"+import { LANDING_CTA_NAMES, PRODUCT_ANALYTICS_EVENTS } from "@/lib/product-analytics-contract"export type ProductAnalyticsInput =| { event: "landing_cta_clicked"; ctaName: string }@@ -12,6 +12,7 @@ export type ProductAnalyticsInput =| { event: "onboarding_enter_clicked"; serverId: string }| { event: "onboarding_first_message" }| { event: "invitation_link_visit"; token: string }+ | { event: "community_onboarding_completed" | "human_invitation_sent" | "human_invitation_copied" | "invited_human_joined" }type EventPayload = { event: ProductAnalyticsInput["event"]; params: Record<string, string> }type EventFrameWindow = Window & { sendProductEvent?: (input: EventPayload) => void }@@ -37,13 +38,15 @@ function prepareProductAnalytics(): HTMLIFrameElement | null {} catch { return null }}-export async function captureProductAnalytics(input: ProductAnalyticsInput): Promise<void> {+export async function captureProductAnalytics(input: ProductAnalyticsInput, assertCurrent?: () => void): Promise<void> {try {if (typeof window === "undefined" || isTauri() || readAnalyticsConsent() === "denied") return+ assertCurrent?.()+ if (!PRODUCT_ANALYTICS_EVENTS.some(event => event === input.event)) returnconst params: Record<string, string> = {}- if ("ctaName" in input && LANDING_CTA_NAMES.some(name => name === input.ctaName)) params.cta_name = input.ctaName- if ("method" in input && ["email", "email_otp", "github", "google", "apple", "development_password"].includes(input.method)) params.method = input.method- if ("failureStage" in input) params.failure_stage = input.failureStage+ if (input.event === "landing_cta_clicked" && LANDING_CTA_NAMES.some(name => name === input.ctaName)) params.cta_name = input.ctaName+ if ((input.event === "sign_up" || input.event === "sign_in_success" || input.event === "sign_in_failed") && ["email", "email_otp", "github", "google", "apple", "development_password"].includes(input.method)) params.method = input.method+ if (input.event === "sign_in_failed" && ["send_code", "verify_code", "social_start", "provider_callback"].includes(input.failureStage)) params.failure_stage = input.failureStageif (isPublicAnalyticsPath(window.location.pathname)) {googleCommand("event", input.event, { ...params, send_to: "G-STBCL8F4ZY" })return@@ -53,7 +56,11 @@ export async function captureProductAnalytics(input: ProductAnalyticsInput): Proconst target = frameconst send = () => {if (readAnalyticsConsent() === "denied") { target.remove(); return }- try { (target.contentWindow as EventFrameWindow | null)?.sendProductEvent?.({ event: input.event, params }) } catch {}+ try {+ assertCurrent?.()+ if (!target.isConnected || isTauri()) return+ (target.contentWindow as EventFrameWindow | null)?.sendProductEvent?.({ event: input.event, params })+ } catch {}}if (frame.dataset.ready === "true") send()else frame.addEventListener("load", send, { once: true })