Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(frontend): queue DataFast events fired before the script loads (#13644)

Ubbe803cab513821
diff --git a/autogpt_platform/frontend/src/services/analytics/index.test.ts b/autogpt_platform/frontend/src/services/analytics/index.test.ts
new file mode 100644
index 0000000000..ec91a4e299
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/index.test.ts
@@ -0,0 +1,159 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { consent } from "@/services/consent/cookies";
+import { analytics, flushDatafastQueue } from "./index";
+
+vi.mock("@/services/consent/cookies", () => ({
+ consent: { hasConsentFor: vi.fn() },
+}));
+
+function drainQueue() {
+ window.datafast = vi.fn();
+ flushDatafastQueue();
+ delete window.datafast;
+}
+
+describe("sendDatafastEvent", () => {
+ beforeEach(() => {
+ drainQueue();
+ vi.mocked(consent.hasConsentFor).mockReturnValue(true);
+ window.history.pushState({}, "", "/");
+ });
+
+ afterEach(() => {
+ drainQueue();
+ });
+
+ it("sends immediately when the DataFast script has loaded", () => {
+ const datafast = vi.fn();
+ window.datafast = datafast;
+
+ analytics.sendDatafastEvent("tour_scenario_start", {
+ scenario: "chat",
+ step: 2,
+ });
+
+ expect(datafast).toHaveBeenCalledWith("tour_scenario_start", {
+ scenario: "chat",
+ step: 2,
+ });
+ });
+
+ it("queues events fired before the script loads and flushes them in order", () => {
+ analytics.sendDatafastEvent("tour_start", {});
+ analytics.sendDatafastEvent("tour_scenario_start", { scenario: "x" });
+
+ const datafast = vi.fn();
+ window.datafast = datafast;
+ flushDatafastQueue();
+
+ expect(datafast.mock.calls).toEqual([
+ ["tour_start", {}],
+ ["tour_scenario_start", { scenario: "x" }],
+ ]);
+ });
+
+ it("keeps events queued when flushing before the script loads", () => {
+ analytics.sendDatafastEvent("tour_start", {});
+ flushDatafastQueue();
+
+ const datafast = vi.fn();
+ window.datafast = datafast;
+ flushDatafastQueue();
+
+ expect(datafast).toHaveBeenCalledTimes(1);
+ expect(datafast).toHaveBeenCalledWith("tour_start", {});
+ });
+
+ it("does not replay events after a flush", () => {
+ analytics.sendDatafastEvent("tour_start", {});
+
+ const datafast = vi.fn();
+ window.datafast = datafast;
+ flushDatafastQueue();
+ flushDatafastQueue();
+
+ expect(datafast).toHaveBeenCalledTimes(1);
+ });
+
+ it("flushes the backlog before sending when the script loads without onLoad", () => {
+ analytics.sendDatafastEvent("tour_start", {});
+
+ const datafast = vi.fn();
+ window.datafast = datafast;
+ analytics.sendDatafastEvent("tour_cta_click", { label: "pricing" });
+
+ expect(datafast.mock.calls).toEqual([
+ ["tour_start", {}],
+ ["tour_cta_click", { label: "pricing" }],
+ ]);
+ });
+
+ it("does not queue pre-consent events outside the tour", () => {
+ vi.mocked(consent.hasConsentFor).mockReturnValue(false);
+
+ analytics.sendDatafastEvent("run_agent", { agent_name: "x" });
+
+ const datafast = vi.fn();
+ window.datafast = datafast;
+ flushDatafastQueue();
+
+ expect(datafast).not.toHaveBeenCalled();
+ });
+
+ it("queues pre-consent events on the consent-exempt tour pages", () => {
+ vi.mocked(consent.hasConsentFor).mockReturnValue(false);
+ window.history.pushState({}, "", "/tour/chat");
+
+ analytics.sendDatafastEvent("tour_start", {});
+
+ const datafast = vi.fn();
+ window.datafast = datafast;
+ flushDatafastQueue();
+
+ expect(datafast).toHaveBeenCalledWith("tour_start", {});
+ });
+
+ it("does not treat /tourism as a consent-exempt tour page", () => {
+ vi.mocked(consent.hasConsentFor).mockReturnValue(false);
+ window.history.pushState({}, "", "/tourism");
+
+ analytics.sendDatafastEvent("tour_start", {});
+
+ const datafast = vi.fn();
+ window.datafast = datafast;
+ flushDatafastQueue();
+
+ expect(datafast).not.toHaveBeenCalled();
+ });
+
+ it("warns again when the queue overflows after a successful flush", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ for (let i = 0; i < 101; i++) {
+ analytics.sendDatafastEvent("tour_start", {});
+ }
+ drainQueue();
+ for (let i = 0; i < 101; i++) {
+ analytics.sendDatafastEvent("tour_start", {});
+ }
+
+ expect(warn).toHaveBeenCalledTimes(2);
+ warn.mockRestore();
+ });
+
+ it("caps the queue at 100, keeps the earliest events, and warns once", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ for (let i = 0; i < 150; i++) {
+ analytics.sendDatafastEvent("tour_start", { i });
+ }
+
+ const datafast = vi.fn();
+ window.datafast = datafast;
+ flushDatafastQueue();
+
+ expect(datafast.mock.calls.map(([, metadata]) => metadata)).toEqual(
+ Array.from({ length: 100 }, (_, i) => ({ i })),
+ );
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockRestore();
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/index.tsx b/autogpt_platform/frontend/src/services/analytics/index.tsx
index b98afe2def..4d0f8a8705 100644
--- a/autogpt_platform/frontend/src/services/analytics/index.tsx
+++ b/autogpt_platform/frontend/src/services/analytics/index.tsx
@@ -12,9 +12,11 @@ import Script from "next/script";
import { useEffect, useState } from "react";
import { environment } from "../environment";
+type DatafastEvent = [name: string, metadata: Record<string, unknown>];
+
declare global {
interface Window {
- datafast: (name: string, metadata: Record<string, unknown>) => void;
+ datafast?: (...event: DatafastEvent) => void;
[key: string]: unknown[] | ((...args: unknown[]) => void) | unknown;
}
}
@@ -43,7 +45,7 @@ export function SetupAnalytics(props: SetupProps) {
// the consent gate — otherwise tour funnel events would never fire for
// first-touch visitors.
const pathname = usePathname();
- const isPublicTourPage = pathname?.startsWith("/tour") ?? false;
+ const isPublicTourPage = isTourPath(pathname);
// Datafa.st journey analytics only on production AND with consent
const dataFastEnabled =
@@ -95,13 +97,15 @@ export function SetupAnalytics(props: SetupProps) {
/>
</>
) : null}
- {/* Datafa.st */}
+ {/* Datafa.st — onLoad is load-bearing: it delivers the events that were
+ queued before the script finished loading */}
{dataFastEnabled ? (
<Script
strategy="afterInteractive"
data-website-id="dfid_g5wtBIiHUwSkWKcGz80lu"
data-domain="agpt.co"
src="https://datafa.st/js/script.js"
+ onLoad={flushDatafastQueue}
/>
) : null}
</>
@@ -127,7 +131,58 @@ function sendGAEvent(...args: unknown[]) {
}
}
+// Module scope means the queue survives client-side navigation: queued events
+// are delivered wherever the script loads next, so metadata must never carry
+// PII. On overflow the earliest events win — funnel starts fire first. The cap
+// bounds memory when the script never loads (ad blockers, non-production
+// domains where dataFastEnabled is false).
+const MAX_QUEUED_DATAFAST_EVENTS = 100;
+const datafastQueue: DatafastEvent[] = [];
+let datafastQueueOverflowWarned = false;
+
function sendDatafastEvent(name: string, metadata: Record<string, unknown>) {
+ if (typeof window === "undefined") return;
+ if (window.datafast) {
+ // Self-heal if the Script's onLoad never fired (e.g. consent toggle
+ // remounted it after the script had already loaded): replay the backlog
+ // first so queued events keep their order ahead of this one.
+ flushDatafastQueue();
+ window.datafast(name, metadata);
+ return;
+ }
+ // The script loads afterInteractive, so mount-time events (tour_start,
+ // tour_scenario_start) fire before window.datafast exists. Queue them and
+ // flush from the Script's onLoad instead of dropping them. Pre-consent
+ // events must not queue — they would be replayed once consent is granted.
+ // /tour is exempt: it loads DataFast without consent by design.
+ const consentExempt = isTourPath(window.location.pathname);
+ if (!consentExempt && !consent.hasConsentFor("analytics")) return;
+ if (datafastQueue.length >= MAX_QUEUED_DATAFAST_EVENTS) {
+ if (!datafastQueueOverflowWarned) {
+ datafastQueueOverflowWarned = true;
+ console.warn(
+ `DataFast queue full (${MAX_QUEUED_DATAFAST_EVENTS} events); dropping new events until the script loads`,
+ );
+ }
+ return;
+ }
+ datafastQueue.push([name, metadata]);
+}
+
+export function flushDatafastQueue() {
if (typeof window === "undefined" || !window.datafast) return;
- window.datafast(name, metadata);
+ const datafast = window.datafast;
+ datafastQueue
+ .splice(0, datafastQueue.length)
+ .forEach(([name, metadata]) => datafast(name, metadata));
+ // A successful drain ends the blocked episode; warn again if a later one
+ // overflows too.
+ datafastQueueOverflowWarned = false;
+}
+
+// Segment-boundary match: /tourism must not inherit the tour's consent
+// exemption.
+function isTourPath(pathname: string | null): boolean {
+ if (!pathname) return false;
+ return pathname === "/tour" || pathname.startsWith("/tour/");
}