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
feat: add analytics consent controls (#802)
Generc8cb1fbe80bf
diff --git a/src/web/blog/src/app/layout.test.ts b/src/web/blog/src/app/layout.test.tsnew file mode 100644index 000000000..4891e9afc--- /dev/null+++ b/src/web/blog/src/app/layout.test.ts@@ -0,0 +1,58 @@+import { createElement } from "react";+import { describe, expect, it, vi } from "vitest";++vi.mock("@/components/analytics-consent", () => ({+ AnalyticsConsent: "analytics-consent",+}));++vi.mock("@/components/theme-color-sync", () => ({+ ThemeColorSync: "theme-color-sync",+}));++vi.mock("@/components/theme-provider", () => ({+ ThemeProvider: "theme-provider",+}));++vi.mock("@/app/fonts", () => ({+ caveat: { variable: "caveat" },+ dmMono: { variable: "dm-mono" },+ dmSans: { variable: "dm-sans" },+ instrumentSerif: { variable: "instrument-serif" },+ literata: { variable: "literata" },+ vt323: { variable: "vt323" },+}));++const seo = vi.hoisted(() => ({+ metadata: { title: "Alook" },+ structuredData: { "@type": "Organization" },+ viewport: { width: "device-width" },+}));++vi.mock("@/lib/seo/site-metadata", () => ({+ siteMetadata: seo.metadata,+ siteStructuredData: seo.structuredData,+ siteViewport: seo.viewport,+}));++import BlogRootLayout, { metadata, viewport } from "./layout";++describe("BlogRootLayout", () => {+ it("renders the shared analytics consent control after blog content", () => {+ const child = createElement("main", null, "Post");+ const layout = BlogRootLayout({ children: child });++ expect(metadata).toBe(seo.metadata);+ expect(viewport).toBe(seo.viewport);+ expect(layout.type).toBe("html");++ const body = layout.props.children[1];+ const provider = body.props.children[1];++ expect(provider.type).toBe("theme-provider");+ expect(provider.props.children).toEqual([+ expect.objectContaining({ type: "theme-color-sync" }),+ child,+ expect.objectContaining({ type: "analytics-consent" }),+ ]);+ });+});diff --git a/src/web/blog/src/app/layout.tsx b/src/web/blog/src/app/layout.tsxindex 624c2cbc6..112a8eea0 100644--- a/src/web/blog/src/app/layout.tsx+++ b/src/web/blog/src/app/layout.tsx@@ -1,5 +1,5 @@-import { GoogleTagManager } from "@next/third-parties/google";import type { Metadata, Viewport } from "next";+import { AnalyticsConsent } from "@/components/analytics-consent";import { caveat, dmMono, dmSans, instrumentSerif, literata, vt323 } from "@/app/fonts";import { ThemeColorSync } from "@/components/theme-color-sync";import { ThemeProvider } from "@/components/theme-provider";@@ -25,7 +25,6 @@ export default function BlogRootLayout({<meta name="mobile-web-app-capable" content="yes" /><meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" /></head>- <GoogleTagManager gtmId="GTM-56VHCCQZ" /><body className="min-h-full flex flex-col"><scripttype="application/ld+json"@@ -34,6 +33,7 @@ export default function BlogRootLayout({<ThemeProvider attribute="class" defaultTheme="system" enableSystem><ThemeColorSync />{children}+ <AnalyticsConsent /></ThemeProvider></body></html>diff --git a/src/web/src/app/api/privacy/analytics-consent/route.test.ts b/src/web/src/app/api/privacy/analytics-consent/route.test.tsnew file mode 100644index 000000000..b86723292--- /dev/null+++ b/src/web/src/app/api/privacy/analytics-consent/route.test.ts@@ -0,0 +1,125 @@+import { NextRequest } from "next/server"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { verifyAnalyticsConsentProof } from "@/lib/analytics-consent-server"++const mocks = vi.hoisted(() => ({+ env: { BETTER_AUTH_SECRET: "route-consent-signing-secret" },+}))++vi.mock("@/lib/middleware/env", () => ({+ withEnv: (handler: (request: NextRequest, context: { env: typeof mocks.env }) => Promise<Response>) =>+ (request: NextRequest) => handler(request, { env: mocks.env }),+}))++import { POST } from "./route"++function request(+ body: unknown,+ origin = "https://alook.ai",+ url = "https://alook.ai/api/privacy/analytics-consent",+) {+ return new NextRequest(url, {+ method: "POST",+ headers: { Origin: origin, "Content-Type": "application/json" },+ body: JSON.stringify(body),+ })+}++beforeEach(() => {+ mocks.env.BETTER_AUTH_SECRET = "route-consent-signing-secret"+})++describe("POST /api/privacy/analytics-consent", () => {+ it.each(["granted", "denied"] as const)("sets the readable and signed %s cookies", async (decision) => {+ const response = await POST(request({ decision }))+ const cookies = response.headers.getSetCookie()++ expect(response.status).toBe(200)+ expect(response.headers.get("Cache-Control")).toBe("no-store, max-age=0")+ expect(await response.json()).toEqual({ decision })+ expect(cookies).toHaveLength(2)+ expect(cookies[0]).toContain(`alook_analytics_consent=v1.${decision}`)+ expect(cookies[0]).toContain("Path=/")+ expect(cookies[0]).toContain("Max-Age=15552000")+ expect(cookies[0]).toContain("SameSite=lax")+ expect(cookies[0]).toContain("Secure")+ expect(cookies[0]).not.toContain("HttpOnly")+ expect(cookies[1]).toContain("alook_analytics_consent_proof=")+ expect(cookies[1]).toContain("HttpOnly")+ expect(cookies[1]).toContain("Secure")++ const proof = cookies[1].match(/^[^=]+=([^;]+)/u)?.[1]+ await expect(verifyAnalyticsConsentProof(+ proof,+ mocks.env.BETTER_AUTH_SECRET,+ )).resolves.toBe(decision)+ })++ it("allows local HTTP while omitting Secure", async () => {+ const response = await POST(request(+ { decision: "denied" },+ "http://localhost:3000",+ "http://localhost:3000/api/privacy/analytics-consent",+ ))+ expect(response.status).toBe(200)+ expect(response.headers.getSetCookie().every((cookie) => !cookie.includes("Secure"))).toBe(true)+ })++ it("uses the browser origin behind a local reverse proxy", async () => {+ const response = await POST(new NextRequest(+ "https://localhost:3001/api/privacy/analytics-consent",+ {+ method: "POST",+ headers: {+ Origin: "http://127.0.0.1:3000",+ Host: "127.0.0.1:3000",+ "X-Forwarded-Host": "127.0.0.1:3000",+ "X-Forwarded-Proto": "https",+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ decision: "granted" }),+ },+ ))++ expect(response.status).toBe(200)+ expect(response.headers.getSetCookie().every((cookie) => !cookie.includes("Secure"))).toBe(true)+ })++ it.each([+ ["cross-origin", request({ decision: "granted" }, "https://evil.example"), 403],+ ["non-HTTP origin", request({ decision: "granted" }, "ftp://alook.ai"), 403],+ ["malformed origin", request({ decision: "granted" }, "not-a-url"), 403],+ ["missing origin", new NextRequest("https://alook.ai/api/privacy/analytics-consent", {+ method: "POST",+ body: JSON.stringify({ decision: "granted" }),+ }), 403],+ ["unknown decision", request({ decision: "maybe" }), 400],+ ["extra fields", request({ decision: "granted", userId: "other" }), 400],+ ["null body", request(null), 400],+ ] as const)("rejects %s", async (_name, input, status) => {+ const response = await POST(input)+ expect(response.status).toBe(status)+ expect(response.headers.getSetCookie()).toEqual([])+ })++ it("rejects malformed JSON", async () => {+ const response = await POST(new NextRequest(+ "https://alook.ai/api/privacy/analytics-consent",+ {+ method: "POST",+ headers: { Origin: "https://alook.ai", "Content-Type": "application/json" },+ body: "{",+ },+ ))++ expect(response.status).toBe(400)+ expect(response.headers.getSetCookie()).toEqual([])+ })++ it("fails closed without a signing secret", async () => {+ mocks.env.BETTER_AUTH_SECRET = ""+ const response = await POST(request({ decision: "granted" }))+ expect(response.status).toBe(503)+ expect(response.headers.getSetCookie()).toEqual([])+ })+})diff --git a/src/web/src/app/api/privacy/analytics-consent/route.ts b/src/web/src/app/api/privacy/analytics-consent/route.tsnew file mode 100644index 000000000..68bf68161--- /dev/null+++ b/src/web/src/app/api/privacy/analytics-consent/route.ts@@ -0,0 +1,70 @@+import { NextResponse, type NextRequest } from "next/server"+import { withEnv } from "@/lib/middleware/env"+import {+ ANALYTICS_CONSENT_COOKIE,+ ANALYTICS_CONSENT_MAX_AGE_SECONDS,+ ANALYTICS_CONSENT_PROOF_COOKIE,+ analyticsConsentCookieValue,+ type AnalyticsConsentDecision,+} from "@/lib/analytics-consent"+import { createAnalyticsConsentProof } from "@/lib/analytics-consent-server"++function sameOriginUrl(request: NextRequest): URL | null {+ const origin = request.headers.get("Origin")+ if (!origin) return null+ try {+ const url = new URL(origin)+ if ((url.protocol !== "http:" && url.protocol !== "https:") || origin !== url.origin) {+ return null+ }+ const forwardedHost = request.headers.get("x-forwarded-host")?.split(",", 1)[0]?.trim()+ const requestHost = request.headers.get("host")?.trim()+ const expectedHost = forwardedHost || requestHost || request.nextUrl.host+ return expectedHost.toLowerCase() === url.host.toLowerCase() ? url : null+ } catch {+ return null+ }+}++function parseDecision(value: unknown): AnalyticsConsentDecision | null {+ if (!value || typeof value !== "object" || Array.isArray(value)) return null+ const keys = Object.keys(value)+ if (keys.length !== 1 || keys[0] !== "decision") return null+ const decision = (value as { decision?: unknown }).decision+ return decision === "granted" || decision === "denied" ? decision : null+}++export const POST = withEnv(async (request, ctx) => {+ const origin = sameOriginUrl(request)+ if (!origin) {+ return NextResponse.json({ error: "forbidden" }, { status: 403 })+ }+ const decision = parseDecision(await request.json().catch(() => null))+ if (!decision) {+ return NextResponse.json({ error: "invalid request body" }, { status: 400 })+ }+ if (!ctx.env.BETTER_AUTH_SECRET) {+ return NextResponse.json({ error: "temporarily unavailable" }, { status: 503 })+ }++ const response = NextResponse.json({ decision })+ const secure = origin.protocol === "https:"+ const shared = {+ path: "/",+ sameSite: "lax" as const,+ secure,+ maxAge: ANALYTICS_CONSENT_MAX_AGE_SECONDS,+ }+ response.cookies.set(+ ANALYTICS_CONSENT_COOKIE,+ analyticsConsentCookieValue(decision),+ shared,+ )+ response.cookies.set(+ ANALYTICS_CONSENT_PROOF_COOKIE,+ await createAnalyticsConsentProof(decision, ctx.env.BETTER_AUTH_SECRET),+ { ...shared, httpOnly: true },+ )+ response.headers.set("Cache-Control", "no-store, max-age=0")+ return response+})diff --git a/src/web/src/app/layout.tsx b/src/web/src/app/layout.tsxindex 1049e378b..7feb3a814 100644--- a/src/web/src/app/layout.tsx+++ b/src/web/src/app/layout.tsx@@ -1,5 +1,5 @@import type { Metadata, Viewport } from "next";-import { GoogleTagManager } from "@next/third-parties/google";+import { AnalyticsConsent } from "@/components/analytics-consent";import { ThemeProvider } from "@/components/theme-provider";import { ToasterProvider } from "@/components/toaster-provider";import { MessageNotificationToaster } from "@/components/ui/toast";@@ -33,7 +33,6 @@ export default function RootLayout({document.addEventListener('gesturestart', function(e) { e.preventDefault(); });`}} /></head>- <GoogleTagManager gtmId="GTM-56VHCCQZ" /><bodyclassName="min-h-full flex flex-col">@@ -52,6 +51,7 @@ export default function RootLayout({{children}</TooltipProvider><ToasterProvider />+ <AnalyticsConsent /></ThemeProvider></body></html>diff --git a/src/web/src/components/analytics-consent.dom.test.tsx b/src/web/src/components/analytics-consent.dom.test.tsxnew file mode 100644index 000000000..c006f9858--- /dev/null+++ b/src/web/src/components/analytics-consent.dom.test.tsx@@ -0,0 +1,167 @@+import { fireEvent, render, screen, waitFor, within } from "@/test/react-dom-harness"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"++const platform = vi.hoisted(() => ({+ isTauri: vi.fn(() => false),+ isMobile: vi.fn(() => false),+}))++vi.mock("@alook/shared", async importOriginal => ({+ ...await importOriginal<typeof import("@alook/shared")>(),+ isTauri: platform.isTauri,+ isMobile: platform.isMobile,+}))++vi.mock("@next/third-parties/google", () => ({+ GoogleTagManager: ({ gtmId }: { gtmId: string }) => (+ <div data-testid="google-tag-manager" data-gtm-id={gtmId} />+ ),+}))++import { AnalyticsConsent, AnalyticsPreferenceControl } from "./analytics-consent"+import { tid } from "@/lib/community/testids"++function clearCookies() {+ for (const cookie of document.cookie.split(";")) {+ const name = cookie.split("=", 1)[0]?.trim()+ if (name) document.cookie = `${name}=; Max-Age=0; Path=/`+ }+}++function successfulFetch(decision: "granted" | "denied") {+ return vi.fn(async () => new Response(+ JSON.stringify({ decision }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ))+}++beforeEach(() => {+ clearCookies()+ platform.isTauri.mockReset().mockReturnValue(false)+ platform.isMobile.mockReset().mockReturnValue(false)+ window.dataLayer = []+})++afterEach(() => {+ clearCookies()+ vi.unstubAllGlobals()+ delete window.dataLayer+})++describe("AnalyticsConsent", () => {+ it("shows a first-visit banner without loading GTM", async () => {+ render(<AnalyticsConsent />)+ const banner = await screen.findByTestId(tid.analyticsConsentBanner)+ expect(within(banner).getByText("Analytics, only if you want")).toBeVisible()+ expect(within(banner).getByRole("button", { name: "Only necessary" })).toBeVisible()+ expect(within(banner).getByRole("button", { name: "Allow analytics" })).toBeVisible()+ expect(within(banner).getByTestId(tid.analyticsConsentAvatarCluster).querySelectorAll("svg"))+ .toHaveLength(3)+ expect(screen.queryByTestId("google-tag-manager")).not.toBeInTheDocument()+ })++ it("hides the first-visit banner in native mobile clients", async () => {+ platform.isTauri.mockReturnValue(true)+ platform.isMobile.mockReturnValue(true)++ render(<AnalyticsConsent />)++ await waitFor(() => {+ expect(platform.isMobile).toHaveBeenCalled()+ })+ expect(screen.queryByTestId(tid.analyticsConsentBanner)).not.toBeInTheDocument()+ expect(screen.queryByTestId("google-tag-manager")).not.toBeInTheDocument()+ })++ it("loads GTM only after the API confirms a grant", async () => {+ const fetcher = successfulFetch("granted")+ vi.stubGlobal("fetch", fetcher)+ render(<AnalyticsConsent />)+ const banner = await screen.findByTestId(tid.analyticsConsentBanner)++ fireEvent.click(within(banner).getByRole("button", { name: "Allow analytics" }))++ expect(await screen.findByTestId("google-tag-manager")).toHaveAttribute(+ "data-gtm-id",+ "GTM-56VHCCQZ",+ )+ expect(screen.queryByTestId(tid.analyticsConsentBanner)).not.toBeInTheDocument()+ expect(window.dataLayer?.[0]).toEqual([+ "consent",+ "default",+ expect.objectContaining({ analytics_storage: "granted", ad_storage: "denied" }),+ ])+ expect(fetcher).toHaveBeenCalledWith(+ "/api/privacy/analytics-consent",+ expect.objectContaining({+ method: "POST",+ credentials: "same-origin",+ body: JSON.stringify({ decision: "granted" }),+ }),+ )+ })++ it("stores a denial without loading GTM", async () => {+ vi.stubGlobal("fetch", successfulFetch("denied"))+ render(<AnalyticsConsent />)+ const banner = await screen.findByTestId(tid.analyticsConsentBanner)++ fireEvent.click(within(banner).getByRole("button", { name: "Only necessary" }))++ await waitFor(() => {+ expect(screen.queryByTestId(tid.analyticsConsentBanner)).not.toBeInTheDocument()+ })+ expect(screen.queryByTestId("google-tag-manager")).not.toBeInTheDocument()+ })++ it("honors stored grant and denial choices on mount", async () => {+ document.cookie = "alook_analytics_consent=v1.granted; Path=/"+ const granted = render(<AnalyticsConsent />)+ expect(await screen.findByTestId("google-tag-manager")).toBeInTheDocument()+ expect(screen.queryByTestId(tid.analyticsConsentBanner)).not.toBeInTheDocument()+ granted.unmount()++ clearCookies()+ document.cookie = "alook_analytics_consent=v1.denied; Path=/"+ render(<AnalyticsConsent />)+ await waitFor(() => {+ expect(screen.queryByTestId(tid.analyticsConsentBanner)).not.toBeInTheDocument()+ })+ expect(screen.queryByTestId("google-tag-manager")).not.toBeInTheDocument()+ })++ it("keeps the banner open and explains a save failure", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response(+ JSON.stringify({ error: "unavailable" }),+ { status: 503, headers: { "Content-Type": "application/json" } },+ )))+ render(<AnalyticsConsent />)+ const banner = await screen.findByTestId(tid.analyticsConsentBanner)+ fireEvent.click(within(banner).getByRole("button", { name: "Allow analytics" }))+ expect(await within(banner).findByRole("alert")).toHaveTextContent("Couldn’t save this choice")+ expect(screen.queryByTestId("google-tag-manager")).not.toBeInTheDocument()+ })++ it("changes a stored preference from the Privacy control", async () => {+ document.cookie = "alook_analytics_consent=v1.denied; Path=/"+ vi.stubGlobal("fetch", successfulFetch("granted"))+ render(+ <>+ <AnalyticsConsent />+ <AnalyticsPreferenceControl />+ </>,+ )+ const control = await screen.findByTestId(tid.analyticsPreferenceControl)+ expect(within(control).getByText(/Only necessary cookies/u)).toBeVisible()++ fireEvent.click(within(control).getByRole("button", { name: "Allow analytics" }))++ expect(await within(control).findByText(/Optional analytics allowed/u)).toBeVisible()+ expect(await screen.findByTestId("google-tag-manager")).toBeInTheDocument()+ expect(window.dataLayer?.[0]).toEqual([+ "consent",+ "update",+ expect.objectContaining({ analytics_storage: "granted", ad_storage: "denied" }),+ ])+ })+})diff --git a/src/web/src/components/analytics-consent.module.css b/src/web/src/components/analytics-consent.module.cssnew file mode 100644index 000000000..de8fe1d22--- /dev/null+++ b/src/web/src/components/analytics-consent.module.css@@ -0,0 +1,308 @@+.banner,+.preferenceControl {+ --consent-paper: #f4f9e9;+ --consent-surface: #ddedb7;+ --consent-ink: #1b271f;+ --consent-muted: #47633b;+ --consent-accent: #356f95;+ --consent-accent-dark: #294f6a;+ --consent-border: rgb(27 39 31 / 42%);++ position: relative;+ isolation: isolate;+ border: 1px solid var(--consent-border);+ border-radius: 3px;+ background: var(--consent-paper);+ color: var(--consent-ink);+ box-shadow: 5px 5px 0 rgb(27 39 31 / 14%);+}++.banner::before,+.preferenceControl::before {+ position: absolute;+ z-index: -1;+ inset: 0;+ background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='0.12'/%3E%3C/svg%3E");+ content: "";+ opacity: 0.16;+ pointer-events: none;+}++.banner {+ position: fixed;+ z-index: 100;+ right: 16px;+ bottom: 16px;+ left: 16px;+ width: min(880px, calc(100vw - 32px));+ margin-inline: auto;+ padding: 16px 18px;+}++.bannerContent {+ display: flex;+ align-items: center;+ gap: 28px;+}++.copy {+ min-width: 0;+ flex: 1;+}++.eyebrow {+ margin: 0 0 3px;+ color: var(--consent-accent-dark);+ font-family: var(--font-mono);+ font-size: 9px;+ font-weight: 600;+ letter-spacing: 0.14em;+ line-height: 1.4;+}++.headline,+.preferenceHeading {+ margin: 0;+ color: var(--consent-ink);+ font-family: var(--font-vt323);+ font-size: 24px;+ font-weight: 400;+ letter-spacing: 0.01em;+ line-height: 1;+}++.preferenceHeading {+ font-size: 30px;+}++.description,+.error {+ margin: 5px 0 0;+ font-family: var(--font-mono);+ font-size: 11px;+ line-height: 1.65;+}++.description {+ color: var(--consent-muted);+}++.error {+ color: var(--destructive);+}++.privacyLink {+ color: var(--consent-ink);+ font-weight: 600;+ text-decoration: underline;+ text-decoration-color: rgb(27 39 31 / 42%);+ text-underline-offset: 3px;+}++.privacyLink:hover {+ text-decoration-color: var(--consent-ink);+}++.privacyLink:focus-visible,+.necessaryButton:focus-visible,+.allowButton:focus-visible {+ outline: 2px solid var(--consent-ink);+ outline-offset: 3px;+}++.actions {+ display: grid;+ flex-shrink: 0;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ align-items: end;+ gap: 9px;+}++.necessaryButton,+.allowButton {+ position: relative;+ z-index: 1;+ min-height: 44px;+ border-radius: 0;+ padding: 0 16px;+ font-family: var(--font-mono);+ font-size: 10px;+ font-weight: 600;+ letter-spacing: 0.08em;+ line-height: 1;+ text-transform: uppercase;+ transition: background-color 150ms ease-out, color 150ms ease-out, transform 150ms ease-out;+ white-space: nowrap;+}++.necessaryButton {+ border: 1px solid var(--consent-ink);+ background: transparent;+ color: var(--consent-ink);+}++.necessaryButton:hover:not(:disabled) {+ background: var(--consent-surface);+}++.allowWrap {+ position: relative;+ display: block;+ padding-top: 30px;+}++.allowButton {+ width: 100%;+ border: 1px solid var(--consent-accent);+ background: var(--consent-accent);+ color: var(--consent-paper);+}++.allowButton:hover:not(:disabled) {+ background: var(--consent-accent-dark);+ transform: translateY(-1px);+}++.necessaryButton:disabled,+.allowButton:disabled {+ cursor: not-allowed;+ opacity: 0.55;+}++.allowAvatars {+ position: absolute;+ z-index: 0;+ top: 0;+ right: 8px;+ display: block;+ width: 90px;+ height: 32px;+ pointer-events: none;+}++.allowAvatar {+ --avatar-tilt: 0deg;+ position: absolute;+ bottom: 0;+ display: block;+ width: 30px;+ height: 30px;+ filter: drop-shadow(0 4px 5px rgb(27 39 31 / 18%));+ transform: translateY(10px) rotate(var(--avatar-tilt));+ transform-origin: 50% 100%;+ animation: consent-avatar-peek 620ms ease-out forwards;+}++.allowAvatar:nth-child(1) {+ --avatar-tilt: -7deg;+ left: 0;+ animation-delay: 50ms;+}++.allowAvatar:nth-child(2) {+ --avatar-tilt: 3deg;+ left: 29px;+ animation-delay: 110ms;+}++.allowAvatar:nth-child(3) {+ --avatar-tilt: 8deg;+ left: 58px;+ animation-delay: 170ms;+}++.allowWrap:hover .allowAvatar,+.allowWrap:focus-within .allowAvatar {+ animation: consent-avatar-wave 520ms ease-in-out;+}++.generatedAvatar {+ width: 100%;+ height: 100%;+ border-radius: 10px;+}++.preferenceControl {+ display: grid;+ grid-template-columns: minmax(0, 1fr) auto;+ align-items: center;+ gap: 24px;+ margin-bottom: 48px;+ padding: 22px;+}++@keyframes consent-avatar-peek {+ 0% {+ opacity: 0;+ transform: translateY(18px) rotate(var(--avatar-tilt)) scale(0.82);+ }++ 58% {+ opacity: 1;+ transform: translateY(-4px) rotate(-3deg) scale(1.03);+ }++ 100% {+ opacity: 1;+ transform: translateY(1px) rotate(var(--avatar-tilt)) scale(1);+ }+}++@keyframes consent-avatar-wave {+ 0%,+ 100% {+ transform: translateY(1px) rotate(var(--avatar-tilt));+ }++ 45% {+ transform: translateY(-8px) rotate(-6deg);+ }+}++@media (max-width: 639px) {+ .banner {+ padding: 16px;+ }++ .bannerContent,+ .preferenceControl {+ align-items: stretch;+ grid-template-columns: 1fr;+ }++ .bannerContent {+ flex-direction: column;+ gap: 12px;+ }++ .preferenceControl {+ gap: 14px;+ }++ .headline {+ font-size: 23px;+ }++ .description {+ font-size: 10px;+ }++ .actions {+ width: 100%;+ }+}++@media (prefers-reduced-motion: reduce) {+ .allowAvatar,+ .allowWrap:hover .allowAvatar,+ .allowWrap:focus-within .allowAvatar {+ animation: none;+ opacity: 1;+ transform: translateY(1px) rotate(var(--avatar-tilt));+ }++ .necessaryButton,+ .allowButton {+ transition: none;+ }+}diff --git a/src/web/src/components/analytics-consent.tsx b/src/web/src/components/analytics-consent.tsxnew file mode 100644index 000000000..766732ce7--- /dev/null+++ b/src/web/src/components/analytics-consent.tsx@@ -0,0 +1,232 @@+"use client"++import { GoogleTagManager } from "@next/third-parties/google"+import { isMobile, isTauri } from "@alook/shared"+import { useCallback, useEffect, useRef, useState } from "react"+import { GeneratedAvatar } from "@/components/avatar"+import {+ ANALYTICS_CONSENT_CHANGE_EVENT,+ announceAnalyticsConsent,+ applyGoogleConsent,+ persistAnalyticsConsent,+ readAnalyticsConsent,+ type AnalyticsConsentDecision,+} from "@/lib/analytics-consent"+import { tid } from "@/lib/community/testids"+import styles from "./analytics-consent.module.css"++const GTM_ID = "GTM-56VHCCQZ"++function useStoredAnalyticsConsent(syncGoogleConsent = false) {+ const [ready, setReady] = useState(false)+ const [decision, setDecision] = useState<AnalyticsConsentDecision | null>(null)+ const [nativeMobile, setNativeMobile] = useState(false)+ const decisionRef = useRef<AnalyticsConsentDecision | null>(null)++ useEffect(() => {+ const stored = readAnalyticsConsent()+ if (syncGoogleConsent && stored === "granted") applyGoogleConsent(stored, "default")+ decisionRef.current = stored+ setDecision(stored)+ setNativeMobile(isTauri() && isMobile())+ setReady(true)++ const onChange = (event: Event) => {+ const next = (event as CustomEvent<AnalyticsConsentDecision>).detail+ if (next !== "granted" && next !== "denied") return+ if (syncGoogleConsent) {+ applyGoogleConsent(next, decisionRef.current === null ? "default" : "update")+ }+ decisionRef.current = next+ setDecision(next)+ }+ window.addEventListener(ANALYTICS_CONSENT_CHANGE_EVENT, onChange)+ return () => window.removeEventListener(ANALYTICS_CONSENT_CHANGE_EVENT, onChange)+ }, [syncGoogleConsent])++ return { ready, decision, nativeMobile }+}++function useAnalyticsConsentChoice() {+ const [saving, setSaving] = useState<AnalyticsConsentDecision | null>(null)+ const [error, setError] = useState(false)++ const choose = useCallback(async (decision: AnalyticsConsentDecision) => {+ setSaving(decision)+ setError(false)+ try {+ await persistAnalyticsConsent(decision)+ announceAnalyticsConsent(decision)+ } catch {+ setError(true)+ } finally {+ setSaving(null)+ }+ }, [])++ return { choose, saving, error }+}++function ConsentButtons({+ saving,+ onChoose,+}: {+ saving: AnalyticsConsentDecision | null+ onChoose: (decision: AnalyticsConsentDecision) => void+}) {+ const [avatarSeeds, setAvatarSeeds] = useState([+ "analytics-consent-lantern",+ "analytics-consent-pocket",+ "analytics-consent-orbit",+ ])++ useEffect(() => {+ setAvatarSeeds(Array.from({ length: 3 }, (_, index) => (+ globalThis.crypto?.randomUUID?.() ?? `analytics-consent-${Date.now()}-${index}`+ )))+ }, [])++ return (+ <div className={styles.actions}>+ <button+ type="button"+ className={styles.necessaryButton}+ disabled={saving !== null}+ data-testid={tid.analyticsConsentNecessary}+ onClick={() => onChoose("denied")}+ >+ {saving === "denied" ? "Saving…" : "Only necessary"}+ </button>+ <span className={styles.allowWrap}>+ <span+ className={styles.allowAvatars}+ aria-hidden="true"+ data-testid={tid.analyticsConsentAvatarCluster}+ >+ {avatarSeeds.map((seed) => (+ <span className={styles.allowAvatar} key={seed}>+ <GeneratedAvatar seed={seed} size="100%" className={styles.generatedAvatar} />+ </span>+ ))}+ </span>+ <button+ type="button"+ className={styles.allowButton}+ disabled={saving !== null}+ data-testid={tid.analyticsConsentAllow}+ onClick={() => onChoose("granted")}+ >+ {saving === "granted" ? "Saving…" : "Allow analytics"}+ </button>+ </span>+ </div>+ )+}++export function AnalyticsConsent() {+ const { ready, decision, nativeMobile } = useStoredAnalyticsConsent(true)+ const { choose, saving, error } = useAnalyticsConsentChoice()+ const bannerRef = useRef<HTMLElement>(null)++ useEffect(() => {+ if (!ready || decision !== null || !bannerRef.current) return+ const root = document.documentElement+ const banner = bannerRef.current+ const updateInset = () => {+ root.style.setProperty(+ "--analytics-consent-inset",+ `${Math.ceil(banner.getBoundingClientRect().height) + 32}px`,+ )+ }+ root.dataset.analyticsConsentPending = "true"+ updateInset()+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(updateInset)+ observer?.observe(banner)+ window.addEventListener("resize", updateInset)+ return () => {+ observer?.disconnect()+ window.removeEventListener("resize", updateInset)+ delete root.dataset.analyticsConsentPending+ root.style.removeProperty("--analytics-consent-inset")+ }+ }, [decision, ready])++ return (+ <>+ <style>{`+ html[data-analytics-consent-pending="true"] body {+ padding-bottom: var(--analytics-consent-inset);+ }+ html[data-analytics-consent-pending="true"] .hero-section,+ html[data-analytics-consent-pending="true"] .workspace-shell {+ height: calc(100dvh - var(--analytics-consent-inset));+ }+ `}</style>+ {ready && decision === "granted" ? <GoogleTagManager gtmId={GTM_ID} /> : null}+ {ready && !nativeMobile && decision === null ? (+ <section+ ref={bannerRef}+ aria-label="Analytics choices"+ className={styles.banner}+ data-testid={tid.analyticsConsentBanner}+ >+ <div className={styles.bannerContent}>+ <div className={styles.copy}>+ <p className={styles.eyebrow}>PRIVACY · OPTIONAL SIGNAL</p>+ <h2 className={styles.headline}>Analytics, only if you want</h2>+ <p className={styles.description}>+ Optional analytics help us understand which parts of Alook are useful. No ad+ tracking. Read our{" "}+ <a+ href="/privacy#analytics-choices"+ className={styles.privacyLink}+ >+ privacy details+ </a>{"."}+ </p>+ {error ? (+ <p className={styles.error} role="alert">+ Couldn’t save this choice. Try again.+ </p>+ ) : null}+ </div>+ <ConsentButtons saving={saving} onChoose={choose} />+ </div>+ </section>+ ) : null}+ </>+ )+}++export function AnalyticsPreferenceControl() {+ const { ready, decision } = useStoredAnalyticsConsent()+ const { choose, saving, error } = useAnalyticsConsentChoice()+ const status = decision === "granted"+ ? "Optional analytics allowed"+ : decision === "denied"+ ? "Only necessary cookies"+ : "No choice saved"++ return (+ <section+ id="analytics-choices"+ className={styles.preferenceControl}+ data-testid={tid.analyticsPreferenceControl}+ >+ <div className={styles.copy}>+ <p className={styles.eyebrow}>PRIVACY · BROWSER PREFERENCE</p>+ <h2 className={styles.preferenceHeading}>Analytics choices</h2>+ <p className={styles.description}>+ {ready ? status : "Reading this browser’s choice…"}. Necessary cookies keep sign-in and+ security working either way.+ </p>+ {error ? (+ <p className={styles.error} role="alert">+ Couldn’t save this choice. Try again.+ </p>+ ) : null}+ </div>+ <ConsentButtons saving={saving} onChoose={choose} />+ </section>+ )+}diff --git a/src/web/src/components/privacy/privacy-policy-content.test.ts b/src/web/src/components/privacy/privacy-policy-content.test.tsindex a2d3dfdb8..027651f78 100644--- a/src/web/src/components/privacy/privacy-policy-content.test.ts+++ b/src/web/src/components/privacy/privacy-policy-content.test.ts@@ -20,6 +20,14 @@ describe("shared Privacy policy", () => {expect(html).not.toContain("durable background job")})+ it("places analytics preferences after the policy content", () => {+ const html = renderToStaticMarkup(createElement(PrivacyPolicyContent))++ expect(html.indexOf("Analytics choices")).toBeGreaterThan(html.indexOf("Contact Us"))+ expect(html).toContain('<div class="mt-12"><section id="analytics-choices"')+ expect(html).toContain("using the preference control below at any time")+ })+it("is the body source for both public and Settings entry points", () => {const publicPage = readFileSync(new URL("../../app/privacy/page.tsx", import.meta.url), "utf8")const userSettings = readFileSync(diff --git a/src/web/src/components/privacy/privacy-policy-content.tsx b/src/web/src/components/privacy/privacy-policy-content.tsxindex 9dd1ee71b..2434d6504 100644--- a/src/web/src/components/privacy/privacy-policy-content.tsx+++ b/src/web/src/components/privacy/privacy-policy-content.tsx@@ -1,9 +1,10 @@import { cn } from "@/lib/utils"+import { AnalyticsPreferenceControl } from "@/components/analytics-consent"export const PRIVACY_POLICY = {title: "Privacy Policy",description: "How Alook collects, uses, and protects your personal information.",- lastUpdated: "May 22, 2026",+ lastUpdated: "September 17, 2026",} as constconst linkClass =@@ -51,10 +52,9 @@ export function PrivacyPolicyContent({ className }: { className?: string }) {<h4 className="mt-6 mb-2 text-base font-medium">Usage Data</h4><p className="text-foreground/80">- Usage Data is collected automatically when using the Service. It may include- information such as Your device's IP address, browser type, browser version,- the pages of our Service that You visit, the time and date of Your visit,- the time spent on those pages, and other diagnostic data.+ Necessary diagnostic data may be processed to keep the Service secure and reliable.+ Optional analytics, such as the pages You visit and how You interact with product+ features, is collected only after You choose to allow analytics in this browser.</p><h4 className="mt-6 mb-2 text-base font-medium">@@ -69,10 +69,11 @@ export function PrivacyPolicyContent({ className }: { className?: string }) {<h4 className="mt-6 mb-2 text-base font-medium">Tracking Technologies and Cookies</h4><p className="text-foreground/80">- We use cookies and similar tracking technologies to track activity on Our Service- and store certain information. These are used to analyze trends, administer the- site, and gather demographic information. You can instruct Your browser to refuse- all cookies or to indicate when a cookie is being sent.+ We use necessary cookies to provide sign-in, security, and saved preferences. We use+ optional analytics cookies only after You allow them. Your analytics choice is saved+ in a first-party cookie for 180 days and can be changed using the preference control+ below at any time. Choosing only necessary cookies keeps Google Tag Manager and+ optional analytics disabled.</p></section>@@ -202,6 +203,10 @@ export function PrivacyPolicyContent({ className }: { className?: string }) {</p></section></div>++ <div className="mt-12">+ <AnalyticsPreferenceControl />+ </div></div>)}diff --git a/src/web/src/components/signin-tracker.test.ts b/src/web/src/components/signin-tracker.test.tsindex 1c6f5fad9..7a88290f7 100644--- a/src/web/src/components/signin-tracker.test.ts+++ b/src/web/src/components/signin-tracker.test.ts@@ -4,6 +4,9 @@ const mockSendGTMEvent = vi.fn()vi.mock("@next/third-parties/google", () => ({sendGTMEvent: (...args: unknown[]) => mockSendGTMEvent(...args),}))+vi.mock("@/lib/analytics-consent", () => ({+ hasAnalyticsConsent: () => true,+}))vi.mock("react", () => ({useEffect: (fn: () => void) => fn(),diff --git a/src/web/src/components/signup-tracker.test.ts b/src/web/src/components/signup-tracker.test.tsindex fc2b35fcf..cbc95ac8b 100644--- a/src/web/src/components/signup-tracker.test.ts+++ b/src/web/src/components/signup-tracker.test.ts@@ -10,6 +10,9 @@ const mocks = vi.hoisted(() => ({vi.mock("@next/third-parties/google", () => ({sendGTMEvent: (...args: unknown[]) => mocks.sendGTMEvent(...args),}))+vi.mock("@/lib/analytics-consent", () => ({+ hasAnalyticsConsent: () => true,+}))vi.mock("next/navigation", () => ({useRouter: () => ({ replace: mocks.replaceRoute }),}))diff --git a/src/web/src/components/workspace-shell.tsx b/src/web/src/components/workspace-shell.tsxindex 42b54fd6b..489cc3300 100644--- a/src/web/src/components/workspace-shell.tsx+++ b/src/web/src/components/workspace-shell.tsx@@ -29,7 +29,7 @@ export function WorkspaceShell({ children }: { children: ReactNode }) {return (<SidebarTriggerContext.Provider value={() => setSidebarOpen(true)}><AgentChatSheetProvider>- <div ref={shellRef} className="flex flex-col h-dvh overflow-hidden relative">+ <div ref={shellRef} className="workspace-shell flex flex-col h-dvh overflow-hidden relative"><AppBackground /><div className="flex-1 min-h-0 px-2 pb-2 pt-2 flex flex-col"><MobileTopBar />@@ -52,7 +52,7 @@ export function WorkspaceShell({ children }: { children: ReactNode }) {return (<AgentChatSheetProvider>- <div ref={shellRef} className="flex h-dvh overflow-hidden relative">+ <div ref={shellRef} className="workspace-shell flex h-dvh overflow-hidden relative"><AppBackground /><AppSidebar /><div className="flex-1 flex flex-col min-w-0 pt-2 pr-2 pb-2">diff --git a/src/web/src/lib/analytics-consent-server.test.ts b/src/web/src/lib/analytics-consent-server.test.tsnew file mode 100644index 000000000..4e127b065--- /dev/null+++ b/src/web/src/lib/analytics-consent-server.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from "vitest"+import {+ ANALYTICS_CONSENT_MAX_AGE_SECONDS,+} from "./analytics-consent"+import {+ createAnalyticsConsentProof,+ verifyAnalyticsConsentProof,+} from "./analytics-consent-server"++const SECRET = "test-consent-signing-secret"+const NOW = Date.UTC(2026, 8, 17, 4, 0, 0)++describe("analytics consent proof", () => {+ it.each(["granted", "denied"] as const)("round-trips %s", async (decision) => {+ const proof = await createAnalyticsConsentProof(decision, SECRET, NOW)+ await expect(verifyAnalyticsConsentProof(proof, SECRET, NOW)).resolves.toBe(decision)+ })++ it("rejects a changed decision or signature", async () => {+ const proof = await createAnalyticsConsentProof("granted", SECRET, NOW)+ await expect(verifyAnalyticsConsentProof(+ proof.replace(".granted.", ".denied."),+ SECRET,+ NOW,+ )).resolves.toBeNull()+ await expect(verifyAnalyticsConsentProof(`${proof.slice(0, -1)}x`, SECRET, NOW)).resolves.toBeNull()+ })++ it("rejects stale, future, malformed, and wrong-secret proofs", async () => {+ const stale = await createAnalyticsConsentProof(+ "granted",+ SECRET,+ NOW - (ANALYTICS_CONSENT_MAX_AGE_SECONDS + 1) * 1000,+ )+ const future = await createAnalyticsConsentProof("granted", SECRET, NOW + 301_000)+ const current = await createAnalyticsConsentProof("granted", SECRET, NOW)++ await expect(verifyAnalyticsConsentProof(stale, SECRET, NOW)).resolves.toBeNull()+ await expect(verifyAnalyticsConsentProof(future, SECRET, NOW)).resolves.toBeNull()+ await expect(verifyAnalyticsConsentProof("v1.granted.nope.signature", SECRET, NOW)).resolves.toBeNull()+ await expect(verifyAnalyticsConsentProof(+ `v1.granted.${Math.floor(NOW / 1000)}.A`,+ SECRET,+ NOW,+ )).resolves.toBeNull()+ await expect(verifyAnalyticsConsentProof(current, "other-secret", NOW)).resolves.toBeNull()+ })+})diff --git a/src/web/src/lib/analytics-consent-server.ts b/src/web/src/lib/analytics-consent-server.tsnew file mode 100644index 000000000..3b17bb2fc--- /dev/null+++ b/src/web/src/lib/analytics-consent-server.ts@@ -0,0 +1,80 @@+import {+ ANALYTICS_CONSENT_MAX_AGE_SECONDS,+ ANALYTICS_CONSENT_VERSION,+ type AnalyticsConsentDecision,+} from "@/lib/analytics-consent"++const encoder = new TextEncoder()++async function consentSigningKey(secret: string): Promise<CryptoKey> {+ return crypto.subtle.importKey(+ "raw",+ encoder.encode(secret),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign", "verify"],+ )+}++function toBase64Url(bytes: Uint8Array): string {+ let binary = ""+ for (const byte of bytes) binary += String.fromCharCode(byte)+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "")+}++function fromBase64Url(value: string): Uint8Array<ArrayBuffer> | null {+ if (!/^[A-Za-z0-9_-]+$/u.test(value)) return null+ const normalized = value.replaceAll("-", "+").replaceAll("_", "/")+ const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=")+ try {+ const binary = atob(padded)+ const bytes = new Uint8Array(new ArrayBuffer(binary.length))+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index)+ return bytes+ } catch {+ return null+ }+}++export async function createAnalyticsConsentProof(+ decision: AnalyticsConsentDecision,+ secret: string,+ issuedAtMs = Date.now(),+): Promise<string> {+ const issuedAtSeconds = Math.floor(issuedAtMs / 1000)+ const payload = `${ANALYTICS_CONSENT_VERSION}.${decision}.${issuedAtSeconds}`+ const signature = await crypto.subtle.sign(+ "HMAC",+ await consentSigningKey(secret),+ encoder.encode(payload),+ )+ return `${payload}.${toBase64Url(new Uint8Array(signature))}`+}++export async function verifyAnalyticsConsentProof(+ proof: string | null | undefined,+ secret: string,+ nowMs = Date.now(),+): Promise<AnalyticsConsentDecision | null> {+ const parts = proof?.split(".") ?? []+ if (parts.length !== 4) return null+ const [version, decision, issuedAtRaw, signatureRaw] = parts+ if (version !== ANALYTICS_CONSENT_VERSION) return null+ if (decision !== "granted" && decision !== "denied") return null+ if (!/^\d+$/u.test(issuedAtRaw)) return null+ const issuedAtSeconds = Number(issuedAtRaw)+ const nowSeconds = Math.floor(nowMs / 1000)+ if (!Number.isSafeInteger(issuedAtSeconds)) return null+ if (issuedAtSeconds > nowSeconds + 300) return null+ if (nowSeconds - issuedAtSeconds > ANALYTICS_CONSENT_MAX_AGE_SECONDS) return null+ const signature = fromBase64Url(signatureRaw)+ if (!signature) return null+ const payload = `${version}.${decision}.${issuedAtRaw}`+ const valid = await crypto.subtle.verify(+ "HMAC",+ await consentSigningKey(secret),+ signature,+ encoder.encode(payload),+ )+ return valid ? decision : null+}diff --git a/src/web/src/lib/analytics-consent.test.ts b/src/web/src/lib/analytics-consent.test.tsnew file mode 100644index 000000000..712bf2a26--- /dev/null+++ b/src/web/src/lib/analytics-consent.test.ts@@ -0,0 +1,115 @@+import { afterEach, describe, expect, it, vi } from "vitest"+import {+ ANALYTICS_CONSENT_CHANGE_EVENT,+ analyticsConsentCookieValue,+ announceAnalyticsConsent,+ applyGoogleConsent,+ hasAnalyticsConsent,+ parseAnalyticsConsentCookie,+ persistAnalyticsConsent,+ readAnalyticsConsent,+} from "./analytics-consent"++afterEach(() => {+ vi.unstubAllGlobals()+})++describe("analytics consent browser contract", () => {+ it("accepts only the current version and bounded decisions", () => {+ expect(analyticsConsentCookieValue("granted")).toBe("v1.granted")+ expect(parseAnalyticsConsentCookie("v1.granted")).toBe("granted")+ expect(parseAnalyticsConsentCookie("v1.denied")).toBe("denied")+ expect(parseAnalyticsConsentCookie("v0.granted")).toBeNull()+ expect(parseAnalyticsConsentCookie("v1.maybe")).toBeNull()+ })++ it("reads the exact first-party cookie without accepting malformed values", () => {+ expect(readAnalyticsConsent("session=x; alook_analytics_consent=v1.granted; other=y")).toBe("granted")+ expect(hasAnalyticsConsent("alook_analytics_consent=v1.denied")).toBe(false)+ expect(readAnalyticsConsent("alook_analytics_consent=%E0%A4%A")).toBeNull()+ expect(readAnalyticsConsent("other=v1.granted")).toBeNull()+ })++ it("queues the exact Google Consent Mode command", () => {+ const browser = { dataLayer: [] as unknown[] }+ vi.stubGlobal("window", browser)++ applyGoogleConsent("granted", "default")++ expect(browser.dataLayer).toHaveLength(1)+ expect(browser.dataLayer[0]).toEqual([+ "consent",+ "default",+ {+ analytics_storage: "granted",+ ad_storage: "denied",+ ad_user_data: "denied",+ ad_personalization: "denied",+ },+ ])++ applyGoogleConsent("denied")++ expect(browser.dataLayer[1]).toEqual([+ "consent",+ "update",+ {+ analytics_storage: "denied",+ ad_storage: "denied",+ ad_user_data: "denied",+ ad_personalization: "denied",+ },+ ])+ })++ it("persists only after the API confirms the same decision", async () => {+ const fetcher = vi.fn(async () => new Response(+ JSON.stringify({ decision: "granted" }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ))+ vi.stubGlobal("fetch", fetcher)++ await persistAnalyticsConsent("granted")++ expect(fetcher).toHaveBeenCalledWith("/api/privacy/analytics-consent", {+ method: "POST",+ credentials: "same-origin",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ decision: "granted" }),+ })+ })++ it("rejects a mismatched API response", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response(+ JSON.stringify({ decision: "denied" }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ )))+ await expect(persistAnalyticsConsent("granted")).rejects.toThrow("was not saved")+ })++ it("rejects a malformed API response", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response("not json", { status: 200 })))+ await expect(persistAnalyticsConsent("granted")).rejects.toThrow("was not saved")+ })++ it("announces the exact saved decision", () => {+ const dispatchEvent = vi.fn()+ vi.stubGlobal("window", { dispatchEvent })+ vi.stubGlobal("CustomEvent", class TestCustomEvent {+ type: string+ detail: unknown+ constructor(type: string, init: { detail: unknown }) {+ this.type = type+ this.detail = init.detail+ }+ })++ announceAnalyticsConsent("denied")++ expect(dispatchEvent).toHaveBeenCalledOnce()+ expect(dispatchEvent.mock.calls[0][0]).toMatchObject({+ type: ANALYTICS_CONSENT_CHANGE_EVENT,+ detail: "denied",+ })+ })+})diff --git a/src/web/src/lib/analytics-consent.ts b/src/web/src/lib/analytics-consent.tsnew file mode 100644index 000000000..7ae49318c--- /dev/null+++ b/src/web/src/lib/analytics-consent.ts@@ -0,0 +1,74 @@+export const ANALYTICS_CONSENT_COOKIE = "alook_analytics_consent"+export const ANALYTICS_CONSENT_PROOF_COOKIE = "alook_analytics_consent_proof"+export const ANALYTICS_CONSENT_VERSION = "v1"+export const ANALYTICS_CONSENT_MAX_AGE_SECONDS = 60 * 60 * 24 * 180+export const ANALYTICS_CONSENT_CHANGE_EVENT = "alook:analytics-consent-change"++export type AnalyticsConsentDecision = "granted" | "denied"++export function analyticsConsentCookieValue(decision: AnalyticsConsentDecision): string {+ return `${ANALYTICS_CONSENT_VERSION}.${decision}`+}++export function parseAnalyticsConsentCookie(value: string | null | undefined): AnalyticsConsentDecision | null {+ if (value === analyticsConsentCookieValue("granted")) return "granted"+ if (value === analyticsConsentCookieValue("denied")) return "denied"+ return null+}++export function readAnalyticsConsent(cookieHeader?: string): AnalyticsConsentDecision | null {+ const source = cookieHeader ?? (typeof document === "undefined" ? "" : document.cookie)+ let value: string | null = null+ for (const part of source.split(";")) {+ const separator = part.indexOf("=")+ if (separator < 0) continue+ const name = part.slice(0, separator).trim()+ if (name !== ANALYTICS_CONSENT_COOKIE) continue+ try {+ value = decodeURIComponent(part.slice(separator + 1).trim())+ } catch {+ return null+ }+ }+ return parseAnalyticsConsentCookie(value)+}++export function hasAnalyticsConsent(cookieHeader?: string): boolean {+ return readAnalyticsConsent(cookieHeader) === "granted"+}++export function applyGoogleConsent(+ decision: AnalyticsConsentDecision,+ mode: "default" | "update" = "update",+): void {+ if (typeof window === "undefined") return+ window.dataLayer ??= []+ function gtag(...args: unknown[]) {+ window.dataLayer?.push(args)+ }+ gtag("consent", mode, {+ analytics_storage: decision,+ ad_storage: "denied",+ ad_user_data: "denied",+ ad_personalization: "denied",+ })+}++export async function persistAnalyticsConsent(decision: AnalyticsConsentDecision): Promise<void> {+ const response = await fetch("/api/privacy/analytics-consent", {+ method: "POST",+ credentials: "same-origin",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ decision }),+ })+ const body = await response.json().catch(() => null) as { decision?: unknown } | null+ if (!response.ok || body?.decision !== decision) throw new Error("analytics consent was not saved")+}++export function announceAnalyticsConsent(decision: AnalyticsConsentDecision): void {+ if (typeof window === "undefined") return+ window.dispatchEvent(new CustomEvent<AnalyticsConsentDecision>(+ ANALYTICS_CONSENT_CHANGE_EVENT,+ { detail: decision },+ ))+}diff --git a/src/web/src/lib/analytics.test.ts b/src/web/src/lib/analytics.test.tsindex 0b5a53e0d..defd2600b 100644--- a/src/web/src/lib/analytics.test.ts+++ b/src/web/src/lib/analytics.test.ts@@ -1,10 +1,18 @@import { describe, it, expect, vi, beforeEach } from "vitest"-const mockSendGTMEvent = vi.fn()+const mocks = vi.hoisted(() => ({+ hasAnalyticsConsent: vi.fn(() => true),+ sendGTMEvent: vi.fn(),+}))vi.mock("@next/third-parties/google", () => ({- sendGTMEvent: (...args: unknown[]) => mockSendGTMEvent(...args),+ sendGTMEvent: (...args: unknown[]) => mocks.sendGTMEvent(...args),+}))+vi.mock("./analytics-consent", () => ({+ hasAnalyticsConsent: () => mocks.hasAnalyticsConsent(),}))+const mockSendGTMEvent = mocks.sendGTMEvent+import {trackSignUp,trackSignInSuccess,@@ -27,6 +35,10 @@ import {trackAgentLinkCreated,trackRuntimeConnected,trackCommunityRuntimeConnected,+ trackCommunityOnboardingCompleted,+ trackCommunityOnboardingSkipped,+ trackCommunityOnboardingStageCompleted,+ trackCommunityOnboardingStarted,trackFirstAgentReplyPersisted,trackHumanInvitationSent,trackHumanInvitationCopied,@@ -54,6 +66,15 @@ import {describe("analytics utility", () => {beforeEach(() => {vi.clearAllMocks()+ mocks.hasAnalyticsConsent.mockReturnValue(true)+ })++ it("drops events while analytics consent is absent or denied", () => {+ mocks.hasAnalyticsConsent.mockReturnValue(false)+ trackSignUp("github")+ trackPricingView({ auth_state: "guest", current_plan: "none" })+ trackCommunityRuntimeConnected()+ expect(mockSendGTMEvent).not.toHaveBeenCalled()})describe("P0 — Core Funnel Events", () => {@@ -241,6 +262,20 @@ describe("analytics utility", () => {])})+ it("sends the exact Community onboarding payloads", () => {+ trackCommunityOnboardingStarted()+ trackCommunityOnboardingStageCompleted("harness")+ trackCommunityOnboardingCompleted()+ trackCommunityOnboardingSkipped("complete")++ expect(mockSendGTMEvent.mock.calls).toEqual([+ [{ event: "community_onboarding_started" }],+ [{ event: "community_onboarding_stage_completed", stage: "harness" }],+ [{ event: "community_onboarding_completed" }],+ [{ event: "community_onboarding_skipped", stage: "complete" }],+ ])+ })+it("fails open when the tag manager rejects a Community funnel event", () => {mockSendGTMEvent.mockImplementationOnce(() => {throw new Error("tag manager unavailable")diff --git a/src/web/src/lib/analytics.ts b/src/web/src/lib/analytics.tsindex 875839bff..2c4b336ca 100644--- a/src/web/src/lib/analytics.ts+++ b/src/web/src/lib/analytics.ts@@ -1,6 +1,7 @@"use client";import { sendGTMEvent } from "@next/third-parties/google";+import { hasAnalyticsConsent } from "@/lib/analytics-consent"const analyticsAuthStates = ["guest", "signed_in"] as constconst analyticsPlanIds = ["free", "studio", "house"] as const@@ -36,6 +37,15 @@ const pricingCtaIdByEntryPoint: Record<BillingEntryPoint, Partial<Record<Analyticonst analyticsPlanIdSet = new Set<string>(analyticsPlanIds)+function sendConsentAwareGTMEvent(payload: Record<string, unknown>) {+ if (!hasAnalyticsConsent()) return+ try {+ sendGTMEvent(payload)+ } catch {+ return+ }+}+export function toAnalyticsPlanId(value: string): AnalyticsPlanId | null {return analyticsPlanIdSet.has(value) ? value as AnalyticsPlanId : null}@@ -47,7 +57,7 @@ export function toAnalyticsCurrentPlan(value: string, isFounder = false): Analytfunction sendCommercialEvent(payload: Record<string, unknown>) {try {- sendGTMEvent(payload)+ sendConsentAwareGTMEvent(payload)} catch {return}@@ -55,7 +65,7 @@ function sendCommercialEvent(payload: Record<string, unknown>) {function sendFunnelEvent(payload: Record<string, unknown>) {try {- sendGTMEvent(payload)+ sendConsentAwareGTMEvent(payload)} catch {return}@@ -98,15 +108,15 @@ export function trackBeginCheckout(params: {// ─── P0 — Core Funnel Events ───────────────────────────────────────────────export function trackSignUp(method: string) {- sendGTMEvent({ event: "sign_up", method });+ sendConsentAwareGTMEvent({ event: "sign_up", method });}export function trackSignInSuccess(method: string) {- sendGTMEvent({ event: "sign_in_success", method });+ sendConsentAwareGTMEvent({ event: "sign_in_success", method });}export function trackWorkspaceCreated(source: "onboarding" | "manual") {- sendGTMEvent({ event: "workspace_created", source });+ sendConsentAwareGTMEvent({ event: "workspace_created", source });}export function trackAgentCreated(params: {@@ -114,28 +124,28 @@ export function trackAgentCreated(params: {has_email: boolean;template_id?: string;}) {- sendGTMEvent({ event: "agent_created", ...params });+ sendConsentAwareGTMEvent({ event: "agent_created", ...params });}export function trackOnboardingCompleted(params: {template_used?: string;agent_count: number;}) {- sendGTMEvent({ event: "onboarding_completed", ...params });+ sendConsentAwareGTMEvent({ event: "onboarding_completed", ...params });}export function trackAgentChatOpened(params: {agent_id: string;is_first_chat: boolean;}) {- sendGTMEvent({ event: "agent_chat_opened", ...params });+ sendConsentAwareGTMEvent({ event: "agent_chat_opened", ...params });}export function trackMessageSent(params: {agent_id: string;message_length: number;}) {- sendGTMEvent({ event: "message_sent", ...params });+ sendConsentAwareGTMEvent({ event: "message_sent", ...params });}// ─── P1 — Feature Usage Events ─────────────────────────────────────────────@@ -144,25 +154,25 @@ export function trackEmailComposed(params: {agent_id: string;has_attachments: boolean;}) {- sendGTMEvent({ event: "email_composed", ...params });+ sendConsentAwareGTMEvent({ event: "email_composed", ...params });}export function trackEmailReceived(params: {agent_id: string;mailbox_type: "alook" | "imap";}) {- sendGTMEvent({ event: "email_received", ...params });+ sendConsentAwareGTMEvent({ event: "email_received", ...params });}export function trackCalendarEventCreated(params: {agent_id: string;is_recurring: boolean;}) {- sendGTMEvent({ event: "calendar_event_created", ...params });+ sendConsentAwareGTMEvent({ event: "calendar_event_created", ...params });}export function trackIssueCreated(params: { agent_id: string }) {- sendGTMEvent({ event: "issue_created", ...params });+ sendConsentAwareGTMEvent({ event: "issue_created", ...params });}export function trackIssueStatusChanged(params: {@@ -170,52 +180,52 @@ export function trackIssueStatusChanged(params: {to: string;method: "drag" | "button";}) {- sendGTMEvent({ event: "issue_status_changed", ...params });+ sendConsentAwareGTMEvent({ event: "issue_status_changed", ...params });}export function trackThreadViewed(params: {agent_count: number;status: string;}) {- sendGTMEvent({ event: "thread_viewed", ...params });+ sendConsentAwareGTMEvent({ event: "thread_viewed", ...params });}export function trackTemplateUsed(params: {template_id: string;template_name: string;}) {- sendGTMEvent({ event: "template_used", ...params });+ sendConsentAwareGTMEvent({ event: "template_used", ...params });}export function trackCustomEmailConnected(params: { email_domain: string }) {- sendGTMEvent({ event: "custom_email_connected", ...params });+ sendConsentAwareGTMEvent({ event: "custom_email_connected", ...params });}// ─── P2 — Growth & Retention Signals ───────────────────────────────────────export function trackTeamMemberInvited(params: { workspace_id: string }) {- sendGTMEvent({ event: "team_member_invited", ...params });+ sendConsentAwareGTMEvent({ event: "team_member_invited", ...params });}export function trackInviteAccepted(params: { workspace_id: string }) {- sendGTMEvent({ event: "invite_accepted", ...params });+ sendConsentAwareGTMEvent({ event: "invite_accepted", ...params });}export function trackSecondAgentCreated(params: { total_agents: number }) {- sendGTMEvent({ event: "second_agent_created", ...params });+ sendConsentAwareGTMEvent({ event: "second_agent_created", ...params });}export function trackAgentLinkCreated(params: {source_agent: string;target_agent: string;}) {- sendGTMEvent({ event: "agent_link_created", ...params });+ sendConsentAwareGTMEvent({ event: "agent_link_created", ...params });}export function trackRuntimeConnected(params: {runtime_type: "desktop" | "cloud";}) {- sendGTMEvent({ event: "runtime_connected", ...params });+ sendConsentAwareGTMEvent({ event: "runtime_connected", ...params });}export type GithubOutboundSurface = "landing" | "blog" | "public_nav" | "public_footer"@@ -276,23 +286,23 @@ export type CommunityOnboardingStage =| "server";export function trackCommunityOnboardingStarted() {- sendGTMEvent({ event: "community_onboarding_started" });+ sendConsentAwareGTMEvent({ event: "community_onboarding_started" });}export function trackCommunityOnboardingStageCompleted(stage: CommunityOnboardingStage,) {- sendGTMEvent({ event: "community_onboarding_stage_completed", stage });+ sendConsentAwareGTMEvent({ event: "community_onboarding_stage_completed", stage });}export function trackCommunityOnboardingCompleted() {- sendGTMEvent({ event: "community_onboarding_completed" });+ sendConsentAwareGTMEvent({ event: "community_onboarding_completed" });}export function trackCommunityOnboardingSkipped(stage: CommunityOnboardingStage | "complete",) {- sendGTMEvent({ event: "community_onboarding_skipped", stage });+ sendConsentAwareGTMEvent({ event: "community_onboarding_skipped", stage });}export type CommunityWsFrameDropReason =@@ -391,7 +401,7 @@ function boundedCommunityWsInteger(value: number, maximum: number): number {function sendCommunityWsGTMEvent(payload: Record<string, unknown>) {try {- sendGTMEvent(payload)+ sendConsentAwareGTMEvent(payload)} catch {return}@@ -506,17 +516,17 @@ export function trackCommunityWsRetryScheduled(params: {// ─── P3 — Page-Level Behavior ───────────────────────────────────────────────export function trackLandingCtaClicked(params: { cta_name: string }) {- sendGTMEvent({ event: "landing_cta_clicked", ...params });+ sendConsentAwareGTMEvent({ event: "landing_cta_clicked", ...params });}export function trackTemplatesBrowsed(params: { category_filter: string }) {- sendGTMEvent({ event: "templates_browsed", ...params });+ sendConsentAwareGTMEvent({ event: "templates_browsed", ...params });}export function trackSettingsUpdated(params: { setting_tab: string }) {- sendGTMEvent({ event: "settings_updated", ...params });+ sendConsentAwareGTMEvent({ event: "settings_updated", ...params });}export function trackCanvasLayoutChanged(params: { layout_type: string }) {- sendGTMEvent({ event: "canvas_layout_changed", ...params });+ sendConsentAwareGTMEvent({ event: "canvas_layout_changed", ...params });}diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex 026b4a7fa..d7b605be0 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -38,6 +38,11 @@ export const tid = {settingsClose: "community-settings-close",settingsLabel: "community-settings-label",settingsWebVersion: "community-settings-web-version",+ analyticsConsentBanner: "analytics-consent-banner",+ analyticsPreferenceControl: "analytics-preference-control",+ analyticsConsentNecessary: "analytics-consent-necessary",+ analyticsConsentAllow: "analytics-consent-allow",+ analyticsConsentAvatarCluster: "analytics-consent-avatar-cluster",accountDeletionOpen: "community-account-deletion-open",accountDeletionFlow: "community-account-deletion-flow",accountDeletionSendCode: "community-account-deletion-send-code",diff --git a/src/web/src/test/e2e-ui/_setup/auth.ts b/src/web/src/test/e2e-ui/_setup/auth.tsindex 266dab88e..0688acd64 100644--- a/src/web/src/test/e2e-ui/_setup/auth.ts+++ b/src/web/src/test/e2e-ui/_setup/auth.ts@@ -1,4 +1,8 @@import type { Browser, Page } from "@playwright/test"+import {+ ANALYTICS_CONSENT_COOKIE,+ analyticsConsentCookieValue,+} from "../../../lib/analytics-consent"import { WEB_URL } from "./paths"import { emailFor, type SeededUser, type UserKey } from "./users"@@ -54,6 +58,17 @@ export async function loginAndSaveState(}const me = (await meRes.json()) as { userId: string }+ // Ordinary product journeys start from the safe necessary-only state so+ // the global banner does not obscure unrelated controls. A direct denied+ // cookie cannot enable tracking; the signed persistence endpoint itself is+ // covered by its dedicated route suite.+ await context.addCookies([{+ name: ANALYTICS_CONSENT_COOKIE,+ value: analyticsConsentCookieValue("denied"),+ url: WEB_URL,+ sameSite: "Lax",+ }])+await context.clearCookies({ name: /^(?:is_new_signup|is_sign_in)$/ })await context.storageState({ path: storageStatePath })return { key, email, name, userId: me.userId, storageState: storageStatePath }