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): load Tally's script only when someone opens the feedback form (#15750)
Krzysztof Czerwinskife0fa8241803
diff --git a/autogpt_platform/frontend/src/app/__tests__/layout.test.tsx b/autogpt_platform/frontend/src/app/__tests__/layout.test.tsxindex 2183cb445b..95c6127526 100644--- a/autogpt_platform/frontend/src/app/__tests__/layout.test.tsx+++ b/autogpt_platform/frontend/src/app/__tests__/layout.test.tsx@@ -19,9 +19,6 @@ vi.mock("@/app/providers", () => ({vi.mock("@/components/molecules/ErrorBoundary/ErrorBoundary", () => ({ErrorBoundary: ({ children }: { children: ReactNode }) => children,}));-vi.mock("@/components/molecules/TallyPoup/TallyPopup", () => ({- default: () => null,-}));vi.mock("@/components/molecules/Toast/toaster", () => ({Toaster: () => null,}));diff --git a/autogpt_platform/frontend/src/app/layout.tsx b/autogpt_platform/frontend/src/app/layout.tsxindex e652cc1f41..b54191ae22 100644--- a/autogpt_platform/frontend/src/app/layout.tsx+++ b/autogpt_platform/frontend/src/app/layout.tsx@@ -6,7 +6,6 @@ import "./globals.css";import { Providers } from "@/app/providers";import { ErrorBoundary } from "@/components/molecules/ErrorBoundary/ErrorBoundary";-import TallyPopupSimple from "@/components/molecules/TallyPoup/TallyPopup";import { Toaster } from "@/components/molecules/Toast/toaster";import { SetupAnalytics } from "@/services/analytics";import { buildConsentDefaultsScript } from "@/services/analytics/consent-mode";@@ -24,7 +23,6 @@ import { getSiteUrl } from "@/lib/metadata";const isDev = environment.isDev();const isLocal = environment.isLocal();-const isCloud = environment.isCloud();const faviconPath = isDev? "/favicon-dev.ico"@@ -123,7 +121,6 @@ export default async function RootLayout({/><div className="flex min-h-screen flex-col items-stretch justify-items-stretch">{children}- {isCloud && <TallyPopupSimple />}<VercelAnalyticsWrapper />{/* React Query DevTools is only available in development */}diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/AccountMenuNewLayout.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/AccountMenuNewLayout.tsxindex bedf8c8249..b27f3d6eaa 100644--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/AccountMenuNewLayout.tsx+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/AccountMenuNewLayout.tsx@@ -3,6 +3,7 @@ import {PopoverContent,PopoverTrigger,} from "@/components/molecules/Popover/Popover";+import { environment } from "@/services/environment";import * as React from "react";import { MenuItemGroup } from "../../helpers";import { AccountLogoutOption } from "./components/AccountLogoutOption";@@ -129,9 +130,11 @@ export function AccountMenuNewLayout({<li><AccountMenuActivityRow /></li>- <li>- <AccountMenuFeedbackRow />- </li>+ {environment.isCloud() && (+ <li>+ <AccountMenuFeedbackRow />+ </li>+ )}</>)}</ul>diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/__tests__/AccountMenu.test.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/__tests__/AccountMenu.test.tsxindex 39a6a765cc..3fe75a6b78 100644--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/__tests__/AccountMenu.test.tsx+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/__tests__/AccountMenu.test.tsx@@ -1,6 +1,6 @@import { IconType } from "@/components/__legacy__/ui/icons";import { render, screen } from "@/tests/integrations/test-utils";-import { describe, expect, test, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import { AccountMenu } from "../AccountMenu";import { InitialAvatar } from "../components/InitialAvatar";import { MenuItemGroup } from "../../../helpers";@@ -82,6 +82,14 @@ const baseGroups: MenuItemGroup[] = [];describe("AccountMenu", () => {+ beforeEach(() => {+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "CLOUD");+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });+test("renders user name and email when loaded", () => {render(<AccountMenu@@ -205,13 +213,12 @@ describe("AccountMenu", () => {const activity = screen.getByTestId("account-menu-activity-trigger");const feedback = screen.getByRole("button", { name: "Give feedback" });- expect(feedback.getAttribute("data-tally-open")).toBe("3yx2L0");expect(activity.closest("li")?.nextElementSibling).toBe(feedback.closest("li"),);});- test("new layout gives feedback without loading another Tally script", () => {+ test("new layout does not load the Tally script before feedback is asked for", () => {render(<AccountMenuuserName="Ada"@@ -227,6 +234,21 @@ describe("AccountMenu", () => {);});+ test("new layout leaves Give feedback out when not running in the cloud", () => {+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "LOCAL");+ render(+ <AccountMenu+ userName="Ada"+ userEmail="[email protected]"+ menuItemGroups={baseGroups}+ newLayout+ />,+ );++ expect(screen.getByTestId("account-menu-activity-trigger")).toBeDefined();+ expect(screen.queryByRole("button", { name: "Give feedback" })).toBeNull();+ });+test("classic layout does not render org, activity or feedback triggers", () => {render(<AccountMenudiff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/components/AccountMenuFeedbackRow.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/components/AccountMenuFeedbackRow.tsxindex 62fd28316c..e1b6929aaa 100644--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/components/AccountMenuFeedbackRow.tsx+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/components/AccountMenuFeedbackRow.tsx@@ -1,23 +1,22 @@"use client";import { Icon } from "@/components/atoms/Icon/Icon";-import { useTallyPageContext } from "@/components/molecules/TallyPoup/useTallyPopup";+import { useTallyFeedback } from "@/components/molecules/TallyPoup/useTallyFeedback";import { useOptionalSidebar } from "@/components/ui/sidebar";import { useAuth } from "@/lib/auth/hooks/useAuth";import { HelpCircleIcon } from "@hugeicons/core-free-icons";-const FEEDBACK_TALLY_FORM_ID = "3yx2L0";-const rowClasses ="group relative flex w-full items-center gap-3 rounded-lg py-2 pl-3 pr-2 text-left text-sm font-normal text-neutral-700 outline-none transition-colors duration-200 ease-out hover:bg-neutral-100 focus-visible:bg-neutral-100 focus-visible:outline-none";export function AccountMenuFeedbackRow() {- const tally = useTallyPageContext();const { isLoggedIn, isUserLoading } = useAuth();+ const feedback = useTallyFeedback(isUserLoading ? null : isLoggedIn);const sidebar = useOptionalSidebar();function handleClick() {if (sidebar?.isMobile) sidebar.setOpenMobile(false);+ feedback.openFeedbackForm();}return (@@ -25,15 +24,8 @@ export function AccountMenuFeedbackRow() {type="button"className={rowClasses}onClick={handleClick}- data-tally-open={FEEDBACK_TALLY_FORM_ID}- data-tally-emoji-text="π"- data-tally-emoji-animation="wave"- data-sentry-replay-id={tally.sentryReplayId || "not-initialized"}- data-sentry-replay-url={tally.replayUrl || "not-initialized"}- data-page-url={- tally.pageUrl ? tally.pageUrl.split("?")[0] : "not-initialized"- }- data-is-authenticated={isUserLoading ? "unknown" : String(isLoggedIn)}+ aria-busy={feedback.isLoading}+ data-feedback-trigger><spanclassName="absolute left-0 top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-full bg-neutral-900 opacity-0 transition-opacity duration-200 group-hover:opacity-100 group-focus-visible:opacity-100"diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/components/__tests__/AccountMenuFeedbackRow.test.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/components/__tests__/AccountMenuFeedbackRow.test.tsxindex d0587144c2..43640ba216 100644--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/components/__tests__/AccountMenuFeedbackRow.test.tsx+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/components/__tests__/AccountMenuFeedbackRow.test.tsx@@ -4,7 +4,9 @@ import {render,screen,} from "@/tests/integrations/test-utils";-import { beforeEach, describe, expect, test, vi } from "vitest";+import { Toaster } from "@/components/molecules/Toast/toaster";+import { stubTallyEmbed } from "@/tests/integrations/tally";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import { AccountMenuFeedbackRow } from "../AccountMenuFeedbackRow";const mockSidebar = vi.hoisted(() => ({@@ -26,6 +28,10 @@ const mockSentry = vi.hoisted(() => ({getReplay: vi.fn(),}));+const flushReplay = vi.fn();++let tally: ReturnType<typeof stubTallyEmbed>;+const mockUseAuth = vi.hoisted(() => ({current: { isLoggedIn: true, isUserLoading: false },}));@@ -37,7 +43,12 @@ vi.mock("@/lib/auth/hooks/useAuth", () => ({}));async function renderRow() {- render(<AccountMenuFeedbackRow />);+ render(+ <>+ <AccountMenuFeedbackRow />+ <Toaster />+ </>,+ );await act(async () => {});return screen.getByRole("button", { name: "Give feedback" });}@@ -47,35 +58,100 @@ describe("AccountMenuFeedbackRow", () => {mockSidebar.current = null;mockUseAuth.current = { isLoggedIn: true, isUserLoading: false };mockAuth.getCurrentUser.mockReset();- mockSentry.getReplay.mockReturnValue({ getReplayId: () => "replay-123" });+ flushReplay.mockReset();+ mockSentry.getReplay.mockReturnValue({+ getReplayId: () => "replay-123",+ flush: flushReplay,+ });window.history.replaceState({}, "", "/library?sort=updatedAt");+ tally = stubTallyEmbed();});- test("renders a Give feedback button wired to the Tally feedback form", async () => {- const button = await renderRow();+ afterEach(async () => {+ await tally.restore();+ });- expect(button.getAttribute("data-tally-open")).toBe("3yx2L0");- expect(button.getAttribute("data-tally-emoji-text")).toBe("π");- expect(button.getAttribute("data-tally-emoji-animation")).toBe("wave");- expect(button.getAttribute("data-sentry-replay-id")).toBe("replay-123");- expect(button.getAttribute("data-sentry-replay-url")).toBe(- "https://significant-gravitas.sentry.io/replays/replay-123/",- );- expect(button.getAttribute("data-page-url")).toBe(- `${window.location.origin}/library`,+ test("does not load the Tally script until someone asks for feedback", async () => {+ await renderRow();++ expect(tally.scripts).toHaveLength(0);+ });++ test("loads Tally on the first click, then opens the feedback form with the page context", async () => {+ fireEvent.click(await renderRow());++ expect(tally.scripts).toHaveLength(1);+ await tally.finishLoading();++ expect(tally.openPopup).toHaveBeenCalledTimes(1);+ expect(tally.openPopup).toHaveBeenCalledWith(+ "3yx2L0",+ expect.objectContaining({+ emoji: { text: "π", animation: "wave" },+ hiddenFields: {+ sentryReplayId: "replay-123",+ sentryReplayUrl:+ "https://significant-gravitas.sentry.io/replays/replay-123/",+ pageUrl: `${window.location.origin}/library`,+ isAuthenticated: "true",+ },+ }),);- expect(button.getAttribute("data-is-authenticated")).toBe("true");+ });++ test("later clicks open the form without loading Tally again", async () => {+ const button = await renderRow();+ fireEvent.click(button);+ await tally.finishLoading();++ await act(async () => {+ fireEvent.click(button);+ });++ expect(tally.scripts).toHaveLength(1);+ expect(tally.openPopup).toHaveBeenCalledTimes(2);+ });++ test("flushes the Sentry replay once the form is open", async () => {+ fireEvent.click(await renderRow());+ await tally.finishLoading();++ act(() => tally.popupOptions().onOpen());++ expect(flushReplay).toHaveBeenCalledTimes(1);});test("marks values that are not known yet", async () => {mockSentry.getReplay.mockReturnValue(undefined);mockUseAuth.current = { isLoggedIn: false, isUserLoading: true };- const button = await renderRow();+ fireEvent.click(await renderRow());+ await tally.finishLoading();- expect(button.getAttribute("data-sentry-replay-id")).toBe(- "not-initialized",- );- expect(button.getAttribute("data-is-authenticated")).toBe("unknown");+ expect(tally.popupOptions().hiddenFields).toMatchObject({+ sentryReplayId: "not-initialized",+ sentryReplayUrl: "not-initialized",+ isAuthenticated: "unknown",+ });+ });++ test("offers a link to the form when Tally can't load, and tries again on the next click", async () => {+ const button = await renderRow();+ fireEvent.click(button);+ await tally.failLoading();++ expect(+ await screen.findByText("Couldn't open the feedback form"),+ ).toBeDefined();+ expect(+ screen+ .getByRole("link", { name: "Open the form in a new tab" })+ .getAttribute("href"),+ ).toBe("https://tally.so/r/3yx2L0");++ fireEvent.click(button);+ expect(tally.scripts).toHaveLength(2);+ await tally.finishLoading();+ expect(tally.openPopup).toHaveBeenCalledTimes(1);});test("reads auth from the client store, not the getCurrentUser server action", async () => {@@ -99,6 +175,8 @@ describe("AccountMenuFeedbackRow", () => {fireEvent.click(await renderRow());expect(setOpenMobile).toHaveBeenCalledWith(false);+ await tally.finishLoading();+ expect(tally.openPopup).toHaveBeenCalledTimes(1);});test("leaves the desktop sidebar alone", async () => {@@ -108,10 +186,15 @@ describe("AccountMenuFeedbackRow", () => {fireEvent.click(await renderRow());expect(setOpenMobile).not.toHaveBeenCalled();+ await tally.finishLoading();+ expect(tally.openPopup).toHaveBeenCalledTimes(1);});test("works outside a sidebar", async () => {- const button = await renderRow();- expect(() => fireEvent.click(button)).not.toThrow();+ fireEvent.click(await renderRow());++ expect(tally.scripts).toHaveLength(1);+ await tally.finishLoading();+ expect(tally.openPopup).toHaveBeenCalledTimes(1);});});diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/FeedbackButton.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/FeedbackButton.tsxindex e2fd4b91f8..40effafcd5 100644--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/FeedbackButton.tsx+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/FeedbackButton.tsx@@ -1,31 +1,24 @@"use client";-import { useTallyPopup } from "@/components/molecules/TallyPoup/useTallyPopup";+import { useTallyFeedback } from "@/components/molecules/TallyPoup/useTallyFeedback";+import { useAuth } from "@/lib/auth/hooks/useAuth";import { Chatting01Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";export function FeedbackButton() {- const { state } = useTallyPopup();+ const { isLoggedIn, isUserLoading } = useAuth();+ const feedback = useTallyFeedback(isUserLoading ? null : isLoggedIn);- if (state.isFormVisible) return null;+ if (feedback.isFormVisible) return null;return (<buttontype="button"className="group inline-flex overflow-hidden rounded-full active:scale-[0.97] disabled:pointer-events-none disabled:opacity-50"- data-tally-open="3yx2L0"- data-tally-emoji-text="π"- data-tally-emoji-animation="wave"- data-sentry-replay-id={state.sentryReplayId || "not-initialized"}- data-sentry-replay-url={state.replayUrl || "not-initialized"}- data-page-url={- state.pageUrl ? state.pageUrl.split("?")[0] : "not-initialized"- }- data-is-authenticated={- state.isAuthenticated === null- ? "unknown"- : String(state.isAuthenticated)- }+ onClick={feedback.openFeedbackForm}+ disabled={feedback.isLoading}+ aria-label="Give Feedback"+ data-feedback-trigger><div className="rounded-full bg-gradient-to-r from-indigo-100 to-indigo-300 to-zinc-400 p-[1px]"><div className="flex items-center gap-1.5 whitespace-nowrap rounded-full bg-[#FAFAFA]/80 px-3 py-1.5 text-sm font-medium text-neutral-700 backdrop-blur-xl transition-colors duration-150 ease-out group-hover:bg-zinc-100/90">diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/__tests__/FeedbackButton.test.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/__tests__/FeedbackButton.test.tsxnew file mode 100644index 0000000000..282b46c6b8--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/__tests__/FeedbackButton.test.tsx@@ -0,0 +1,66 @@+import {+ act,+ fireEvent,+ render,+ screen,+} from "@/tests/integrations/test-utils";+import { stubTallyEmbed } from "@/tests/integrations/tally";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { FeedbackButton } from "../FeedbackButton";++vi.mock("@sentry/nextjs", () => ({ getReplay: vi.fn() }));+vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({ isLoggedIn: false, isUserLoading: false }),+}));++let tally: ReturnType<typeof stubTallyEmbed>;++function feedbackButton() {+ return screen.getByRole<HTMLButtonElement>("button", {+ name: "Give Feedback",+ });+}++describe("FeedbackButton", () => {+ beforeEach(() => {+ window.history.replaceState({}, "", "/marketplace");+ tally = stubTallyEmbed();+ });++ afterEach(async () => {+ await tally.restore();+ });++ test("loads Tally only after a click and waits for it before opening the form", async () => {+ render(<FeedbackButton />);+ expect(tally.scripts).toHaveLength(0);++ fireEvent.click(feedbackButton());++ expect(tally.scripts).toHaveLength(1);+ expect(feedbackButton().disabled).toBe(true);+ expect(tally.openPopup).not.toHaveBeenCalled();++ await tally.finishLoading();++ expect(feedbackButton().disabled).toBe(false);+ expect(tally.openPopup).toHaveBeenCalledWith(+ "3yx2L0",+ expect.objectContaining({+ hiddenFields: expect.objectContaining({ isAuthenticated: "false" }),+ }),+ );+ });++ test("hides while the form is open and comes back once it closes", async () => {+ render(<FeedbackButton />);+ fireEvent.click(feedbackButton());+ await tally.finishLoading();++ act(() => tally.popupOptions().onOpen());+ expect(screen.queryByRole("button", { name: "Give Feedback" })).toBeNull();++ act(() => tally.popupOptions().onClose());+ expect(feedbackButton()).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/components/molecules/TallyPoup/TallyPopup.tsx b/autogpt_platform/frontend/src/components/molecules/TallyPoup/TallyPopup.tsxdeleted file mode 100644index 2876411b58..0000000000--- a/autogpt_platform/frontend/src/components/molecules/TallyPoup/TallyPopup.tsx+++ /dev/null@@ -1,11 +0,0 @@-"use client";--import { useTallyPopup } from "./useTallyPopup";--export function TallyPopupSimple() {- // Load the Tally script and set up event listeners- useTallyPopup();- return null;-}--export default TallyPopupSimple;diff --git a/autogpt_platform/frontend/src/components/molecules/TallyPoup/__tests__/TallyPopup.test.tsx b/autogpt_platform/frontend/src/components/molecules/TallyPoup/__tests__/TallyPopup.test.tsxdeleted file mode 100644index ed895ffd50..0000000000--- a/autogpt_platform/frontend/src/components/molecules/TallyPoup/__tests__/TallyPopup.test.tsx+++ /dev/null@@ -1,44 +0,0 @@-import { act, render } from "@testing-library/react";-import { StrictMode } from "react";-import { describe, expect, it, vi } from "vitest";-import TallyPopupSimple from "../TallyPopup";--vi.mock("@/lib/auth/actions", () => ({- getCurrentUser: vi.fn().mockResolvedValue({ user: null }),-}));--vi.mock("@sentry/nextjs", () => ({- getReplay: vi.fn(),-}));--const scriptSelector = 'script[src="https://tally.so/widgets/embed.js"]';--describe("Tally popup cleanup", () => {- it("removes its script on unmount after StrictMode remounts", async () => {- const { unmount } = render(- <StrictMode>- <TallyPopupSimple />- </StrictMode>,- );- await act(async () => {});-- expect(document.head.querySelectorAll(scriptSelector)).toHaveLength(1);- unmount();- expect(document.head.querySelector(scriptSelector)).toBeNull();- });-- it("still removes the message listener when its script is already detached", async () => {- const removeListener = vi.spyOn(window, "removeEventListener");- const { unmount } = render(<TallyPopupSimple />);- await act(async () => {});- const script = document.head.querySelector(scriptSelector);- expect(script).not.toBeNull();- script?.remove();-- expect(unmount).not.toThrow();- expect(removeListener).toHaveBeenCalledWith(- "message",- expect.any(Function),- );- });-});diff --git a/autogpt_platform/frontend/src/components/molecules/TallyPoup/helpers.tsx b/autogpt_platform/frontend/src/components/molecules/TallyPoup/helpers.tsxnew file mode 100644index 0000000000..70d951ebc0--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/TallyPoup/helpers.tsx@@ -0,0 +1,96 @@+import { toast } from "@/components/molecules/Toast/use-toast";++const TALLY_EMBED_URL = "https://tally.so/widgets/embed.js";+export const FEEDBACK_TALLY_FORM_ID = "3yx2L0";+const FEEDBACK_FORM_URL = `https://tally.so/r/${FEEDBACK_TALLY_FORM_ID}`;++interface TallyPopupOptions {+ emoji?: { text: string; animation: string };+ hiddenFields?: Record<string, string>;+ onOpen?: () => void;+ onClose?: () => void;+}++interface TallyApi {+ openPopup: (formId: string, options?: TallyPopupOptions) => void;+}++declare global {+ interface Window {+ Tally?: TallyApi;+ }+}++let pendingLoad: Promise<TallyApi> | null = null;++export function loadTallyEmbed(): Promise<TallyApi> {+ if (window.Tally) return Promise.resolve(window.Tally);+ if (pendingLoad) return pendingLoad;++ pendingLoad = new Promise<TallyApi>((resolve, reject) => {+ const script = document.createElement("script");+ script.src = TALLY_EMBED_URL;+ script.async = true;++ script.addEventListener("load", () => {+ pendingLoad = null;+ if (window.Tally) {+ resolve(window.Tally);+ } else {+ script.remove();+ reject(new Error("Tally script loaded without its API"));+ }+ });+ script.addEventListener("error", () => {+ pendingLoad = null;+ script.remove();+ reject(new Error("Tally script failed to load"));+ });++ document.head.appendChild(script);+ });++ return pendingLoad;+}++interface FeedbackContext {+ sentryReplayId: string;+ replayUrl: string;+ pageUrl: string;+ isAuthenticated: boolean | null;+}++export function getFeedbackHiddenFields(context: FeedbackContext) {+ return {+ sentryReplayId: context.sentryReplayId || "not-initialized",+ sentryReplayUrl: context.replayUrl || "not-initialized",+ pageUrl: context.pageUrl+ ? context.pageUrl.split("?")[0]+ : "not-initialized",+ isAuthenticated:+ context.isAuthenticated === null+ ? "unknown"+ : String(context.isAuthenticated),+ };+}++export function showFeedbackLoadError() {+ toast({+ title: "Couldn't open the feedback form",+ description: (+ <>+ It may be blocked by your browser.{" "}+ <a+ href={FEEDBACK_FORM_URL}+ target="_blank"+ rel="noopener noreferrer"+ className="underline"+ >+ Open the form in a new tab+ </a>+ </>+ ),+ variant: "destructive",+ duration: 10000,+ });+}diff --git a/autogpt_platform/frontend/src/components/molecules/TallyPoup/useTallyFeedback.ts b/autogpt_platform/frontend/src/components/molecules/TallyPoup/useTallyFeedback.tsnew file mode 100644index 0000000000..23556d778e--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/TallyPoup/useTallyFeedback.ts@@ -0,0 +1,74 @@+import { usePathname } from "next/navigation";+import { useEffect, useState } from "react";+import * as Sentry from "@sentry/nextjs";+import {+ FEEDBACK_TALLY_FORM_ID,+ getFeedbackHiddenFields,+ loadTallyEmbed,+ showFeedbackLoadError,+} from "./helpers";++export function useTallyPageContext() {+ const [sentryReplayId, setSentryReplayId] = useState("");+ const [replayUrl, setReplayUrl] = useState("");+ const [pageUrl, setPageUrl] = useState("");+ const [userAgent, setUserAgent] = useState("");+ const pathname = usePathname();++ useEffect(() => {+ // Set client-side values+ if (typeof window !== "undefined") {+ setPageUrl(window.location.href);+ setUserAgent(window.navigator.userAgent);++ const replay = Sentry.getReplay();++ if (replay) {+ const replayId = replay.getReplayId();++ if (replayId) {+ setSentryReplayId(replayId);+ const orgSlug = "significant-gravitas";+ setReplayUrl(`https://${orgSlug}.sentry.io/replays/${replayId}/`);+ }+ }+ }+ }, [pathname]);++ return { sentryReplayId, replayUrl, pageUrl, userAgent };+}++export function useTallyFeedback(isAuthenticated: boolean | null) {+ const page = useTallyPageContext();+ const [isFormVisible, setIsFormVisible] = useState(false);+ const [isLoading, setIsLoading] = useState(false);++ function handleFormOpen() {+ setIsFormVisible(true);+ Sentry.getReplay()?.flush();+ }++ function handleFormClose() {+ setIsFormVisible(false);+ }++ async function openFeedbackForm() {+ if (isLoading) return;+ setIsLoading(true);+ try {+ const tally = await loadTallyEmbed();+ tally.openPopup(FEEDBACK_TALLY_FORM_ID, {+ emoji: { text: "π", animation: "wave" },+ hiddenFields: getFeedbackHiddenFields({ ...page, isAuthenticated }),+ onOpen: handleFormOpen,+ onClose: handleFormClose,+ });+ } catch {+ showFeedbackLoadError();+ } finally {+ setIsLoading(false);+ }+ }++ return { isFormVisible, isLoading, openFeedbackForm };+}diff --git a/autogpt_platform/frontend/src/components/molecules/TallyPoup/useTallyPopup.ts b/autogpt_platform/frontend/src/components/molecules/TallyPoup/useTallyPopup.tsdeleted file mode 100644index b217df653c..0000000000--- a/autogpt_platform/frontend/src/components/molecules/TallyPoup/useTallyPopup.ts+++ /dev/null@@ -1,120 +0,0 @@-import { usePathname } from "next/navigation";-import { useEffect, useState } from "react";-import * as Sentry from "@sentry/nextjs";-import { getCurrentUser } from "@/lib/auth/actions";--export function useTallyPageContext() {- const [sentryReplayId, setSentryReplayId] = useState("");- const [replayUrl, setReplayUrl] = useState("");- const [pageUrl, setPageUrl] = useState("");- const [userAgent, setUserAgent] = useState("");- const pathname = usePathname();-- useEffect(() => {- // Set client-side values- if (typeof window !== "undefined") {- setPageUrl(window.location.href);- setUserAgent(window.navigator.userAgent);-- const replay = Sentry.getReplay();-- if (replay) {- const replayId = replay.getReplayId();-- if (replayId) {- setSentryReplayId(replayId);- const orgSlug = "significant-gravitas";- setReplayUrl(`https://${orgSlug}.sentry.io/replays/${replayId}/`);- }- }- }- }, [pathname]);-- return { sentryReplayId, replayUrl, pageUrl, userAgent };-}--export function useTallyContext() {- const page = useTallyPageContext();- const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);- const [userEmail, setUserEmail] = useState<string>("");- const pathname = usePathname();-- useEffect(() => {- // Check authentication status using server action (works with httpOnly cookies)- getCurrentUser().then(({ user }) => {- setIsAuthenticated(user != null);- setUserEmail(user?.email || "");- });- }, [pathname]);-- return { ...page, isAuthenticated, userEmail };-}--export function useTallyPopup() {- const context = useTallyContext();- const [isFormVisible, setIsFormVisible] = useState(false);-- useEffect(() => {- // Load Tally script- const script = document.createElement("script");- script.src = "https://tally.so/widgets/embed.js";- script.async = true;- document.head.appendChild(script);-- // Setup event listeners for Tally events- const handleTallyMessage = (event: MessageEvent) => {- if (typeof event.data === "string") {- // Ignore iframe-resizer messages- if (- event.data.startsWith("[iFrameSize") ||- event.data.startsWith("[iFrameResizer")- ) {- return;- }-- try {- const data = JSON.parse(event.data);-- // Only process Tally events- if (!data.event?.startsWith("Tally.")) {- return;- }-- if (data.event === "Tally.FormLoaded") {- setIsFormVisible(true);-- // Flush Sentry replay when form opens- if (typeof window !== "undefined") {- const replay = Sentry.getReplay();- if (replay) {- replay.flush();- }- }- } else if (data.event === "Tally.PopupClosed") {- setIsFormVisible(false);- }- } catch (error) {- // Only log errors for messages we care about- if (event.data.includes("Tally")) {- console.error("Error parsing Tally message:", error);- }- }- }- };-- window.addEventListener("message", handleTallyMessage);-- return () => {- script.parentNode?.removeChild(script);- window.removeEventListener("message", handleTallyMessage);- };- }, []);-- return {- state: {- ...context,- isFormVisible,- },- handlers: {},- };-}diff --git a/autogpt_platform/frontend/src/playwright/pages/profile-form.page.ts b/autogpt_platform/frontend/src/playwright/pages/profile-form.page.tsindex 9639585970..b1e4da1c42 100644--- a/autogpt_platform/frontend/src/playwright/pages/profile-form.page.ts+++ b/autogpt_platform/frontend/src/playwright/pages/profile-form.page.ts@@ -15,7 +15,7 @@ export class ProfileFormPage extends BasePage {private async hideFloatingWidgets(): Promise<void> {await this.page.addStyleTag({content: `- [data-tally-open] { display: none !important; }+ [data-feedback-trigger] { display: none !important; }`,});}diff --git a/autogpt_platform/frontend/src/tests/integrations/tally.ts b/autogpt_platform/frontend/src/tests/integrations/tally.tsnew file mode 100644index 0000000000..3124f1d4b3--- /dev/null+++ b/autogpt_platform/frontend/src/tests/integrations/tally.ts@@ -0,0 +1,50 @@+import { act } from "@testing-library/react";+import { vi } from "vitest";++const TALLY_EMBED_URL = "https://tally.so/widgets/embed.js";++// happy-dom fails external scripts as soon as they are added, so the stub keeps+// Tally's script out of the document and lets the test settle it.+export function stubTallyEmbed() {+ const scripts: HTMLScriptElement[] = [];+ const unsettled = new Set<HTMLScriptElement>();+ const openPopup = vi.fn();+ const appendChild = document.head.appendChild.bind(document.head);+ const spy = vi+ .spyOn(document.head, "appendChild")+ .mockImplementation(function <T extends Node>(node: T): T {+ if (node instanceof HTMLScriptElement && node.src === TALLY_EMBED_URL) {+ scripts.push(node);+ unsettled.add(node);+ return node;+ }+ return appendChild(node);+ });++ async function settle(script: HTMLScriptElement, event: "load" | "error") {+ unsettled.delete(script);+ if (event === "load") window.Tally = { openPopup };+ await act(async () => {+ script.dispatchEvent(new Event(event));+ });+ }++ function lastScript() {+ const script = scripts.at(-1);+ if (!script) throw new Error("Tally's script was never requested");+ return script;+ }++ return {+ scripts,+ openPopup,+ finishLoading: () => settle(lastScript(), "load"),+ failLoading: () => settle(lastScript(), "error"),+ popupOptions: (call = 0) => openPopup.mock.calls[call][1],+ async restore() {+ for (const script of [...unsettled]) await settle(script, "error");+ spy.mockRestore();+ delete window.Tally;+ },+ };+}