Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): align public Faro consent with website analytics (#1046)

Gustavo Ye11ad548f7c5f
diff --git a/src/web/src/lib/observability/client-public-consent.dom.test.ts b/src/web/src/lib/observability/client-public-consent.dom.test.ts
new file mode 100644
index 000000000..334a76d38
--- /dev/null
+++ b/src/web/src/lib/observability/client-public-consent.dom.test.ts
@@ -0,0 +1,86 @@
+import type { Faro } from "@grafana/faro-web-sdk"
+import { afterEach, expect, it, vi } from "vitest"
+import { act } from "@/test/react-dom-harness"
+import { announceAnalyticsConsent } from "../analytics-consent"
+
+const native = vi.hoisted(() => ({ faro: undefined as Faro | undefined }))
+vi.mock("@grafana/faro-web-sdk", async importOriginal => {
+ const real = await importOriginal<typeof import("@grafana/faro-web-sdk")>()
+ return { ...real, initializeFaro: (...args: Parameters<typeof real.initializeFaro>) => {
+ native.faro = real.initializeFaro(...args)
+ return native.faro
+ } }
+})
+afterEach(async () => {
+ document.cookie = "alook_analytics_consent=v1.denied; path=/"
+ announceAnalyticsConsent("denied")
+ await vi.advanceTimersByTimeAsync(0)
+ vi.useRealTimers(); vi.unstubAllEnvs(); vi.unstubAllGlobals()
+})
+
+it("collects fresh public document vitals, stops at private navigation and denial, then resumes public collection", async () => {
+ vi.useFakeTimers(); sessionStorage.clear()
+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")
+ vi.spyOn(performance, "getEntriesByType").mockReturnValue([])
+ document.cookie = "alook_analytics_consent=; max-age=0; path=/"
+ window.history.replaceState(null, "", "/")
+ const sent: Array<{ measurements?: Array<{ values: Record<string, number> }>; events?: Array<{ name: string; attributes?: Record<string, string> }> }> = []
+ vi.stubGlobal("fetch", vi.fn(async (_url: unknown, options?: RequestInit) => {
+ if (options?.body) sent.push(JSON.parse(String(options.body)))
+ return new Response(null, { status: 204 })
+ }))
+ const { bootstrapObservability, onObservedRouterTransition, onObservedRouteCommit } = await import("./client")
+ const { emitTelemetry, isTelemetryEligible } = await import("./telemetry")
+ await act(async () => { bootstrapObservability("web"); await Promise.resolve() })
+ await vi.waitFor(() => expect(native.faro).toBeDefined())
+ await vi.advanceTimersByTimeAsync(1500)
+ expect(isTelemetryEligible()).toBe(true)
+ native.faro!.api.pushMeasurement({ type: "web-vitals", values: { lcp: 125, fcp: 50, ttfb: 25 } })
+ await vi.advanceTimersByTimeAsync(1500)
+ expect(sent.flatMap(body => body.measurements ?? []).some(row => row.values.lcp === 125)).toBe(true)
+ expect(document.cookie).not.toContain("alook_analytics_consent")
+
+ const privateLink = document.createElement("a")
+ privateLink.href = "/c/me/friends"
+ privateLink.addEventListener("click", event => event.preventDefault())
+ document.body.append(privateLink)
+ privateLink.click()
+ await vi.advanceTimersByTimeAsync(1500)
+ expect(JSON.stringify(sent)).not.toContain("/c/me/friends")
+ privateLink.remove()
+ onObservedRouterTransition("/c/me/friends")
+ expect(isTelemetryEligible()).toBe(false)
+ const privateTimestamp = Date.now()
+ const count = sent.length
+ window.history.pushState(null, "", "/c/me/friends")
+ onObservedRouteCommit()
+ emitTelemetry("business.result", { outcome: "success" })
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(sent).toHaveLength(count)
+
+ for (const path of ["/demo", "/auth", "/c/invite/secret"]) {
+ window.history.pushState(null, "", path)
+ window.dispatchEvent(new PopStateEvent("popstate"))
+ await vi.advanceTimersByTimeAsync(1500)
+ expect(isTelemetryEligible()).toBe(false)
+ expect(sent).toHaveLength(count)
+ }
+
+ onObservedRouterTransition("/pricing")
+ window.history.pushState(null, "", "/pricing")
+ onObservedRouteCommit()
+ await vi.waitFor(() => expect(isTelemetryEligible()).toBe(true))
+ native.faro!.api.pushEvent("faro.performance.resource", { name: window.location.origin + "/c/me/friends", duration: "777" }, undefined, { timestampOverwriteMs: privateTimestamp })
+ emitTelemetry("business.result", { outcome: "success" })
+ await vi.advanceTimersByTimeAsync(1500)
+ expect(sent.flatMap(body => body.events ?? []).some(event => event.attributes?.duration === "777")).toBe(false)
+ expect(sent.length).toBeGreaterThan(count)
+
+ document.cookie = "alook_analytics_consent=v1.denied; path=/"
+ announceAnalyticsConsent("denied")
+ const deniedCount = sent.length
+ emitTelemetry("business.result", { outcome: "success" })
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(isTelemetryEligible()).toBe(false)
+ expect(sent).toHaveLength(deniedCount)
+})
diff --git a/src/web/src/lib/observability/client-runtime.dom.test.ts b/src/web/src/lib/observability/client-runtime.dom.test.ts
index 24a84f23d..29e0504fb 100644
--- a/src/web/src/lib/observability/client-runtime.dom.test.ts
+++ b/src/web/src/lib/observability/client-runtime.dom.test.ts
@@ -23,10 +23,15 @@ it("exports canonical native entry and frontend version on real SDK and business
if (options?.body) sent.push(JSON.parse(String(options.body)))
return new Response(null, { status: 204 })
}))
- document.cookie = "alook_analytics_consent=v1.granted; path=/"
+ document.cookie = "alook_analytics_consent=; max-age=0; path=/"
const { bootstrapObservability } = await import("./client")
const { emitTelemetry, isTelemetryEligible } = await import("./telemetry")
await act(async () => { bootstrapObservability("web"); await Promise.resolve() })
+ await vi.advanceTimersByTimeAsync(1500)
+ expect(isTelemetryEligible()).toBe(false)
+ expect(sent).toEqual([])
+ document.cookie = "alook_analytics_consent=v1.granted; path=/"
+ announceAnalyticsConsent("granted")
await vi.waitFor(() => expect(isTelemetryEligible()).toBe(true))
emitTelemetry("business.result", { outcome: "success", frontend_surface: "web", client_platform: "browser", app_version: "9.9.9" })
await vi.advanceTimersByTimeAsync(1500)
diff --git a/src/web/src/lib/observability/client.ts b/src/web/src/lib/observability/client.ts
index dbd27b87b..31e0f1531 100644
--- a/src/web/src/lib/observability/client.ts
+++ b/src/web/src/lib/observability/client.ts
@@ -1,7 +1,7 @@
import type { Faro, FetchTransport } from "@grafana/faro-web-sdk"
import type { getDefaultOTELInstrumentations } from "@grafana/faro-web-tracing"
import { isMobile, isTauri } from "@alook/shared"
-import { ANALYTICS_CONSENT_CHANGE_EVENT, hasAnalyticsConsent } from "../analytics-consent"
+import { ANALYTICS_CONSENT_CHANGE_EVENT, isPublicAnalyticsPath, readAnalyticsConsent } from "../analytics-consent"
import { capabilityLimits, routeTemplate } from "./coverage"
import { ROOT_CONTEXT } from "@opentelemetry/api"
import { actionSequence, beginNavigation, clearActions, installActionSpans, telemetryId, currentPageObservation, actionAttributes, startPageOperation, finishPageOperation } from "./context"
@@ -16,6 +16,14 @@ import { resolveObservationLabels } from "./build"
import { finishTransportClock } from "./clock"
import { observeResourceResponse } from "./resource"
+function hasObservationConsent(href = typeof window === "undefined" ? undefined : window.location.href) {
+ const decision = readAnalyticsConsent()
+ if (decision !== null) return decision === "granted"
+ if (isTauri() || typeof window === "undefined" || !href) return false
+ const url = new URL(href, window.location.origin)
+ return url.origin === window.location.origin && isPublicAnalyticsPath(url.pathname)
+}
+
type BuildProfile = { url?: string; environment?: string; release?: string; release_status: string; environment_status: string }
function validBuildProfile(profile: BuildProfile) {
try {
@@ -39,14 +47,14 @@ let pendingInitialNavigation = false
let makeTransport: (() => FetchTransport) | undefined
let stopNavigationFetch: (() => void) | undefined
let stopBrowser: (() => void) | undefined
-let documentVitalsEligible = hasAnalyticsConsent()
+let documentVitalsEligible = hasObservationConsent()
let eligibleSince = 0
let eligibleTimestamp = Date.now() - (typeof performance === "undefined" ? 0 : performance.now())
let identity = resolveFrontendIdentity("web", false, false, process.env.NEXT_PUBLIC_APP_VERSION)
let userKey: string | undefined
let identityEstablished = false
let identityRevision = 0
-let mayResumeNativeSession = hasAnalyticsConsent()
+let mayResumeNativeSession = hasObservationConsent()
let clearNativeSession: (() => void) | undefined
let httpInstrumentations: ReturnType<typeof getDefaultOTELInstrumentations> = []
const pageId = telemetryId()
@@ -70,7 +78,7 @@ function configure() {
configureTelemetry({ release: build.release, environment: build.environment, release_status: build.release_status, environment_status: build.environment_status, ...identity, page_instance_id: pageId, session_id: sessionId, user_key: userKey }, true)
}
async function activate() {
- if (documentSuspended || !hasAnalyticsConsent() || !validBuildProfile(build)) return
+ if (documentSuspended || !hasObservationConsent() || !validBuildProfile(build)) return
const route = routeTemplate(window.location.href, window.location.origin)
const communityOwner = (route === "/c" || route.startsWith("/c/")) && resolveCommunityModulePlan(window.location.pathname).route !== "public-invite"
if (!identityEstablished && communityOwner) return
@@ -83,7 +91,7 @@ async function activate() {
import("@grafana/faro-web-sdk"), import("@grafana/faro-web-tracing"), import("./clock-tracing"),
])
clearNativeSession = () => VolatileSessionsManager.removeUserSession()
- if (documentSuspended || !hasAnalyticsConsent() || capturedSession !== sessionId || !isTelemetryEligible()) return
+ if (documentSuspended || !hasObservationConsent() || capturedSession !== sessionId || !isTelemetryEligible()) return
mayResumeNativeSession = false
makeTransport = () => {
controller = new AbortController()
@@ -112,7 +120,7 @@ async function activate() {
ignoreUrls: [build.url!],
webVitalsInstrumentation: { trackAttributionSources: false },
batching: { enabled: true, itemLimit: 40, sendTimeout: 1000 },
- beforeSend: item => hasAnalyticsConsent() && isTelemetryEligible() ? sanitizeItem(item, sessionId, window.location.origin, identity, eligibleTimestamp, documentVitalsEligible, eligibleTimestamp, eligibleSince) : null,
+ beforeSend: item => hasObservationConsent() && isTelemetryEligible() ? sanitizeItem(item, sessionId, window.location.origin, identity, eligibleTimestamp, documentVitalsEligible, eligibleTimestamp, eligibleSince) : null,
})
const initialized = faro?.api.getSession()
if (!faro || !initialized?.id || !/^[a-zA-Z0-9_-]{1,80}$/.test(initialized.id) || initialized.attributes?.alook_account !== accountScope) { deactivate(); return }
@@ -147,12 +155,12 @@ async function activate() {
}
function connectSink() {
installTelemetrySink(event => {
- if (!hasAnalyticsConsent() || !isTelemetryEligible()) return
+ if (!hasObservationConsent() || !isTelemetryEligible()) return
faro?.api.pushEvent(event.name, event.attributes, "alook.frontend", { skipDedupe: true, timestampOverwriteMs: event.timestamp })
})
}
function adoptNativeSession(next: string) {
- if (next === sessionId || !/^[a-zA-Z0-9_-]{1,80}$/.test(next) || !hasAnalyticsConsent() || !isTelemetryEligible()) return
+ if (next === sessionId || !/^[a-zA-Z0-9_-]{1,80}$/.test(next) || !hasObservationConsent() || !isTelemetryEligible()) return
retireTelemetry("native_session")
clearActions()
stopBrowser?.()
@@ -170,7 +178,7 @@ function adoptNativeSession(next: string) {
}
function reconcile() {
if (documentSuspended) return
- if (!hasAnalyticsConsent()) { documentVitalsEligible = false; mayResumeNativeSession = false; clearNativeSession?.(); deactivate(); return }
+ if (!hasObservationConsent()) { documentVitalsEligible = false; mayResumeNativeSession = false; clearNativeSession?.(); deactivate(); return }
if (load) { pendingReconcile = true; return }
if (isTelemetryEligible()) return
load = activate().catch(() => { deactivate() }).finally(() => {
@@ -190,7 +198,7 @@ export function setTelemetryUser(key: string | null) {
if (!firstIdentity) { eligibleSince = performance.now(); eligibleTimestamp = Date.now() }
userKey = next
sessionId = telemetryId()
- if (wasEligible || hasAnalyticsConsent()) reconcile()
+ if (wasEligible || hasObservationConsent()) reconcile()
}
export function captureTelemetryIdentityRetirement() {
const original = userKey, revision = identityRevision
@@ -200,9 +208,9 @@ export function bootstrapObservability(nextSurface: "web" | "blog") {
if (started || typeof window === "undefined") return
started = true
identity = resolveFrontendIdentity(nextSurface, isTauri(), isMobile(), process.env.NEXT_PUBLIC_APP_VERSION)
- pendingInitialNavigation = hasAnalyticsConsent() && validBuildProfile(build)
- window.addEventListener(ANALYTICS_CONSENT_CHANGE_EVENT, () => { eligibleSince = performance.now(); eligibleTimestamp = Date.now(); if (!hasAnalyticsConsent()) pendingInitialNavigation = false; reconcile() })
- window.addEventListener("popstate", () => { if (isTelemetryEligible()) beginNavigation(window.location.href) })
+ pendingInitialNavigation = hasObservationConsent() && validBuildProfile(build)
+ window.addEventListener(ANALYTICS_CONSENT_CHANGE_EVENT, () => { eligibleSince = performance.now(); eligibleTimestamp = Date.now(); if (!hasObservationConsent()) pendingInitialNavigation = false; reconcile() })
+ window.addEventListener("popstate", () => { onObservedRouteCommit(); if (isTelemetryEligible()) beginNavigation(window.location.href) })
document.addEventListener("visibilitychange", () => {
if (isTelemetryEligible()) { reportTelemetryDrops("transport_failure"); emitTelemetry("telemetry.coverage", { visibility: document.visibilityState, capability: "limited" }) }
})
@@ -227,6 +235,7 @@ export function bootstrapObservability(nextSurface: "web" | "blog") {
if (!isTelemetryEligible() || !(event.target instanceof Element)) return
const control = event.target.closest("a,button,[role=button],input[type=checkbox],select")
if (!control) return
+ if (control instanceof HTMLAnchorElement && !hasObservationConsent(control.href)) return
if (control instanceof HTMLAnchorElement && control.href && control.origin === window.location.origin && !control.download && control.target !== "_blank" && !(event instanceof MouseEvent && (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey)) && routeTemplate(control.href, window.location.origin) !== "/unmapped") beginNavigation(control.href, "gesture")
else {
const before = actionSequence(), generation = telemetryGeneration(), owner = currentPageObservation(), interactionStart = performance.now()
@@ -240,6 +249,19 @@ export function bootstrapObservability(nextSurface: "web" | "blog") {
}, { capture: true, passive: true })
reconcile()
}
+export function onObservedRouteCommit() {
+ if (!started) return
+ if (!isTelemetryEligible()) { eligibleSince = performance.now(); eligibleTimestamp = Date.now() }
+ reconcile()
+}
export function onObservedRouterTransition(url: string) {
+ if (!hasObservationConsent(url)) {
+ documentVitalsEligible = false
+ pendingInitialNavigation = false
+ mayResumeNativeSession = false
+ clearNativeSession?.()
+ deactivate()
+ return
+ }
if (isTelemetryEligible()) beginNavigation(url, "transport")
}
diff --git a/src/web/src/lib/observability/regions.tsx b/src/web/src/lib/observability/regions.tsx
index 4cb17ee2d..a22ee443a 100644
--- a/src/web/src/lib/observability/regions.tsx
+++ b/src/web/src/lib/observability/regions.tsx
@@ -59,6 +59,7 @@ export function useObservedRegion(region: Attributes["region"], ready: boolean,
function RouteCommit() {
const pathname = usePathname(), search = useSearchParams().toString()
useEffect(() => {
+ void import("./client").then(({ onObservedRouteCommit }) => onObservedRouteCommit())
if (pathname.startsWith("/c")) return
commitNavigation(pathname + (search ? "?" + search : ""), "page")
}, [pathname, search])
diff --git a/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts b/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts
index c2e72b4a6..a8dead0ee 100644
--- a/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts
+++ b/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts
@@ -149,8 +149,11 @@ test("real bot avatars become unreadable after single delete and authenticated m
expect(await avatarFrame.boundingBox()).toEqual(pendingFrame)
failAvatar = false
+ const requestsBeforeReload = avatarRequests
await alice.page.reload({ waitUntil: "commit" })
- await expect.poll(() => avatarRequests).toBeGreaterThan(1)
+ await expect(alice.page.getByText(botName, { exact: true })).toBeVisible()
+ await expect.poll(() => avatarRequests).toBeGreaterThan(requestsBeforeReload)
+ await expect(avatar).toHaveCount(1)
await expect(avatar).toHaveAttribute("data-remote-image-state", "ready")
const readyFrame = await avatarFrame.boundingBox()
expect(readyFrame).toEqual(pendingFrame)