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.
feat(frontend): preferences v2 page (SECRT-2279) (#12925)
Abhimanyu Yadav3c08b90500cc
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/__tests__/SettingsMobileNav.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/__tests__/SettingsMobileNav.test.tsxindex 04b4a22b15..0ad965de83 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/__tests__/SettingsMobileNav.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/__tests__/SettingsMobileNav.test.tsx@@ -70,7 +70,7 @@ describe("SettingsMobileNav", () => {"Creator Dashboard","Billing","Integrations",- "Settings",+ "Preferences","AutoGPT API Keys","OAuth Apps",];diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/__tests__/SettingsSidebar.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/__tests__/SettingsSidebar.test.tsxindex 844e2258c8..bb1990b964 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/__tests__/SettingsSidebar.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/__tests__/SettingsSidebar.test.tsx@@ -44,7 +44,7 @@ const expectedItems = [{ label: "Creator Dashboard", href: "/settings/creator-dashboard" },{ label: "Billing", href: "/settings/billing" },{ label: "Integrations", href: "/settings/integrations" },- { label: "Settings", href: "/settings/preferences" },+ { label: "Preferences", href: "/settings/preferences" },{ label: "AutoGPT API Keys", href: "/settings/api-keys" },{ label: "OAuth Apps", href: "/settings/oauth-apps" },];diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/__tests__/placeholder-pages.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/__tests__/placeholder-pages.test.tsxindex 1c4064e55c..f448bd1908 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/__tests__/placeholder-pages.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/__tests__/placeholder-pages.test.tsx@@ -2,13 +2,11 @@ import { render, screen } from "@/tests/integrations/test-utils";import { describe, expect, it } from "vitest";import SettingsCreatorDashboardPage from "../creator-dashboard/page";import SettingsBillingPage from "../billing/page";-import SettingsPreferencesPage from "../preferences/page";import SettingsOAuthAppsPage from "../oauth-apps/page";const pages = [{ Component: SettingsCreatorDashboardPage, title: "Creator Dashboard" },{ Component: SettingsBillingPage, title: "Billing" },- { Component: SettingsPreferencesPage, title: "Settings" },{ Component: SettingsOAuthAppsPage, title: "OAuth Apps" },];diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/components/SettingsSidebar/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/settings/components/SettingsSidebar/helpers.tsindex 56af74ffb5..0a194a8353 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/components/SettingsSidebar/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/settings/components/SettingsSidebar/helpers.ts@@ -1,11 +1,11 @@import {+ ChartLineUpIcon,CreditCardIcon,- GearIcon,IdentificationBadgeIcon,KeyIcon,PlugsConnectedIcon,- SquaresFourIcon,- UserCircleIcon,+ SlidersHorizontalIcon,+ UserIcon,type Icon as PhosphorIcon,} from "@phosphor-icons/react";@@ -16,11 +16,11 @@ export interface SettingsNavItem {}export const settingsNavItems: SettingsNavItem[] = [- { label: "Profile", href: "/settings/profile", Icon: UserCircleIcon },+ { label: "Profile", href: "/settings/profile", Icon: UserIcon },{label: "Creator Dashboard",href: "/settings/creator-dashboard",- Icon: SquaresFourIcon,+ Icon: ChartLineUpIcon,},{ label: "Billing", href: "/settings/billing", Icon: CreditCardIcon },{@@ -28,7 +28,11 @@ export const settingsNavItems: SettingsNavItem[] = [href: "/settings/integrations",Icon: PlugsConnectedIcon,},- { label: "Settings", href: "/settings/preferences", Icon: GearIcon },+ {+ label: "Preferences",+ href: "/settings/preferences",+ Icon: SlidersHorizontalIcon,+ },{ label: "AutoGPT API Keys", href: "/settings/api-keys", Icon: KeyIcon },{label: "OAuth Apps",diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/preferences/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/__tests__/main.test.tsxnew file mode 100644index 0000000000..69464c8354--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/__tests__/main.test.tsx@@ -0,0 +1,338 @@+import type { ReactNode } from "react";+import { beforeEach, describe, expect, test, vi } from "vitest";++import {+ getGetV1GetNotificationPreferencesMockHandler,+ getGetV1GetUserTimezoneMockHandler,+ getPostV1UpdateNotificationPreferencesMockHandler,+ getPostV1UpdateUserEmailMockHandler,+ getPostV1UpdateUserTimezoneMockHandler,+} from "@/app/api/__generated__/endpoints/auth/auth.msw";+import { server } from "@/mocks/mock-server";+import {+ fireEvent,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";++import SettingsPreferencesPage from "../page";++const mockUseSupabase = vi.hoisted(() => vi.fn());++vi.mock("@/providers/onboarding/onboarding-provider", () => ({+ default: ({ children }: { children: ReactNode }) => <>{children}</>,+}));++vi.mock("@/lib/supabase/hooks/useSupabase", () => ({+ useSupabase: mockUseSupabase,+}));++const testUser = {+ id: "user-1",+ email: "[email protected]",+ app_metadata: {},+ user_metadata: {},+ aud: "authenticated",+ created_at: "2026-01-01T00:00:00.000Z",+};++const baseDate = new Date("2026-01-01T00:00:00.000Z");++const allFalsePreferences = {+ AGENT_RUN: false,+ ZERO_BALANCE: false,+ LOW_BALANCE: false,+ BLOCK_EXECUTION_FAILED: false,+ CONTINUOUS_AGENT_ERROR: false,+ DAILY_SUMMARY: false,+ WEEKLY_SUMMARY: false,+ MONTHLY_SUMMARY: false,+ AGENT_APPROVED: false,+ AGENT_REJECTED: false,+};++function setupBaseHandlers(+ options: { timezone?: string; preferences?: Record<string, boolean> } = {},+) {+ server.use(+ getGetV1GetNotificationPreferencesMockHandler({+ user_id: "user-1",+ email: "[email protected]",+ preferences: options.preferences ?? allFalsePreferences,+ daily_limit: 0,+ emails_sent_today: 0,+ last_reset_date: baseDate,+ }),+ getGetV1GetUserTimezoneMockHandler({+ timezone: options.timezone ?? "Asia/Kolkata",+ }),+ getPostV1UpdateUserEmailMockHandler({}),+ getPostV1UpdateNotificationPreferencesMockHandler({+ user_id: "user-1",+ email: "[email protected]",+ preferences: {},+ daily_limit: 0,+ emails_sent_today: 0,+ last_reset_date: baseDate,+ }),+ getPostV1UpdateUserTimezoneMockHandler({+ timezone: "Europe/London",+ }),+ );+}++describe("SettingsPreferencesPage", () => {+ beforeEach(() => {+ mockUseSupabase.mockReturnValue({+ user: testUser,+ isLoggedIn: true,+ isUserLoading: false,+ supabase: {},+ });+ });++ test("renders Account card with current email and reset password link", async () => {+ setupBaseHandlers();++ render(<SettingsPreferencesPage />);++ expect(await screen.findByText("Account")).toBeDefined();+ expect(screen.getByText("[email protected]")).toBeDefined();+ expect(screen.getByText("Email")).toBeDefined();+ expect(screen.getByText("Password")).toBeDefined();++ const resetLink = screen.getByRole("link", { name: "Reset password" });+ expect(resetLink.getAttribute("href")).toBe("/reset-password");+ });++ test("opens email update dialog and closes on Cancel", async () => {+ setupBaseHandlers();++ render(<SettingsPreferencesPage />);++ const editButton = await screen.findByRole("button", {+ name: "Edit email",+ });+ fireEvent.click(editButton);++ const dialogInput = await screen.findByLabelText("Email");+ expect((dialogInput as HTMLInputElement).value).toBe("[email protected]");++ const updateButton = screen.getByRole("button", { name: "Update email" });+ expect((updateButton as HTMLButtonElement).disabled).toBe(true);++ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));++ await waitFor(() => {+ expect(screen.queryByLabelText("Email")).toBeNull();+ });+ });++ test("renders Time zone card with info tooltip trigger", async () => {+ setupBaseHandlers({ timezone: "Asia/Kolkata" });++ render(<SettingsPreferencesPage />);++ expect(await screen.findByText("Time zone")).toBeDefined();+ expect(+ screen.getByRole("button", { name: "Time zone info" }),+ ).toBeDefined();+ });++ test("Save and Discard buttons start disabled when nothing has changed", async () => {+ setupBaseHandlers();++ render(<SettingsPreferencesPage />);++ const saveButton = await screen.findByRole("button", {+ name: "Save changes",+ });+ const discardButton = screen.getByRole("button", { name: "Discard" });++ expect((saveButton as HTMLButtonElement).disabled).toBe(true);+ expect((discardButton as HTMLButtonElement).disabled).toBe(true);+ });++ test("toggling a notification enables Save and persists on click", async () => {+ let submittedPreferences:+ | { email: string; preferences: Record<string, boolean> }+ | undefined;++ server.use(+ getGetV1GetNotificationPreferencesMockHandler({+ user_id: "user-1",+ email: "[email protected]",+ preferences: allFalsePreferences,+ daily_limit: 0,+ emails_sent_today: 0,+ last_reset_date: baseDate,+ }),+ getGetV1GetUserTimezoneMockHandler({ timezone: "Asia/Kolkata" }),+ getPostV1UpdateUserEmailMockHandler({}),+ getPostV1UpdateUserTimezoneMockHandler({ timezone: "Asia/Kolkata" }),+ getPostV1UpdateNotificationPreferencesMockHandler(async ({ request }) => {+ submittedPreferences = (await request.json()) as {+ email: string;+ preferences: Record<string, boolean>;+ };+ return {+ user_id: "user-1",+ email: submittedPreferences.email,+ preferences: submittedPreferences.preferences,+ daily_limit: 0,+ emails_sent_today: 0,+ last_reset_date: baseDate,+ };+ }),+ );++ render(<SettingsPreferencesPage />);++ const saveButton = await screen.findByRole("button", {+ name: "Save changes",+ });+ expect((saveButton as HTMLButtonElement).disabled).toBe(true);++ const switches = await screen.findAllByRole("switch");+ fireEvent.click(switches[0]);++ await waitFor(() => {+ expect((saveButton as HTMLButtonElement).disabled).toBe(false);+ });++ fireEvent.click(saveButton);++ await waitFor(() => {+ expect(submittedPreferences).toBeDefined();+ });+ const flippedKey = Object.entries(submittedPreferences!.preferences).find(+ ([, v]) => v === true,+ )?.[0];+ expect(flippedKey).toBeDefined();+ });++ test("saving a timezone change posts the new value", async () => {+ let submittedTimezone: string | undefined;++ server.use(+ getGetV1GetNotificationPreferencesMockHandler({+ user_id: "user-1",+ email: "[email protected]",+ preferences: allFalsePreferences,+ daily_limit: 0,+ emails_sent_today: 0,+ last_reset_date: baseDate,+ }),+ getGetV1GetUserTimezoneMockHandler({ timezone: "Asia/Kolkata" }),+ getPostV1UpdateUserEmailMockHandler({}),+ getPostV1UpdateNotificationPreferencesMockHandler({+ user_id: "user-1",+ email: "[email protected]",+ preferences: {},+ daily_limit: 0,+ emails_sent_today: 0,+ last_reset_date: baseDate,+ }),+ getPostV1UpdateUserTimezoneMockHandler(async ({ request }) => {+ const body = (await request.json()) as { timezone: string };+ submittedTimezone = body.timezone;+ return { timezone: body.timezone };+ }),+ );++ render(<SettingsPreferencesPage />);++ const select = await screen.findByRole("combobox", { name: "Timezone" });+ fireEvent.click(select);++ const option = await screen.findByRole("option", {+ name: /London/i,+ });+ fireEvent.click(option);++ const saveButton = screen.getByRole("button", { name: "Save changes" });++ await waitFor(() => {+ expect((saveButton as HTMLButtonElement).disabled).toBe(false);+ });++ fireEvent.click(saveButton);++ await waitFor(() => {+ expect(submittedTimezone).toBe("Europe/London");+ });+ });++ test("submitting a new email closes the dialog and calls the update endpoint", async () => {+ const fetchMock = vi.fn(async () =>+ Promise.resolve(+ new Response(JSON.stringify({ ok: true }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ setupBaseHandlers();++ render(<SettingsPreferencesPage />);++ fireEvent.click(await screen.findByRole("button", { name: "Edit email" }));++ const dialogInput = (await screen.findByLabelText(+ "Email",+ )) as HTMLInputElement;+ fireEvent.change(dialogInput, { target: { value: "[email protected]" } });++ const updateButton = screen.getByRole("button", { name: "Update email" });+ await waitFor(() => {+ expect((updateButton as HTMLButtonElement).disabled).toBe(false);+ });++ fireEvent.click(updateButton);++ await waitFor(() => {+ expect(fetchMock).toHaveBeenCalledWith(+ "/api/auth/user",+ expect.objectContaining({ method: "PUT" }),+ );+ });++ await waitFor(() => {+ expect(screen.queryByLabelText("Email")).toBeNull();+ });++ vi.unstubAllGlobals();+ });++ test("Discard reverts unsaved notification toggles", async () => {+ setupBaseHandlers();++ render(<SettingsPreferencesPage />);++ const saveButton = await screen.findByRole("button", {+ name: "Save changes",+ });+ const discardButton = screen.getByRole("button", { name: "Discard" });++ const switches = await screen.findAllByRole("switch");+ const targetSwitch = switches[0] as HTMLInputElement;+ const initialChecked = targetSwitch.getAttribute("aria-checked");++ fireEvent.click(targetSwitch);++ await waitFor(() => {+ expect((saveButton as HTMLButtonElement).disabled).toBe(false);+ expect((discardButton as HTMLButtonElement).disabled).toBe(false);+ });++ fireEvent.click(discardButton);++ await waitFor(() => {+ expect((saveButton as HTMLButtonElement).disabled).toBe(true);+ expect(targetSwitch.getAttribute("aria-checked")).toBe(initialChecked);+ });+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/AccountCard/AccountCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/AccountCard/AccountCard.tsxnew file mode 100644index 0000000000..a2d1a1ca65--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/AccountCard/AccountCard.tsx@@ -0,0 +1,176 @@+"use client";++import type { User } from "@supabase/supabase-js";+import { PencilSimpleIcon } from "@phosphor-icons/react";+import { motion, useReducedMotion } from "framer-motion";+import { useState } from "react";++import { Button } from "@/components/atoms/Button/Button";+import { Input } from "@/components/atoms/Input/Input";+import { Text } from "@/components/atoms/Text/Text";+import { Dialog } from "@/components/molecules/Dialog/Dialog";+import {+ Form,+ FormControl,+ FormField,+ FormItem,+} from "@/components/molecules/Form/Form";++import { EASE_OUT } from "../../helpers";+import { useAccountCard } from "./useAccountCard";++interface Props {+ user: User;+ index?: number;+}++export function AccountCard({ user, index = 0 }: Props) {+ const reduceMotion = useReducedMotion();+ const [emailDialogOpen, setEmailDialogOpen] = useState(false);+ const { emailForm, onSubmitEmail, isUpdatingEmail, currentEmail } =+ useAccountCard({ user });++ const watchedEmail = emailForm.watch("email");+ const emailHasError = Object.keys(emailForm.formState.errors).length > 0;+ const isSameEmail = watchedEmail === currentEmail;+ const disableEmailSubmit = emailHasError || isSameEmail;++ async function handleEmailSubmit(values: { email: string }) {+ if (disableEmailSubmit) return;+ const didUpdate = await onSubmitEmail(values);+ if (didUpdate) {+ setEmailDialogOpen(false);+ }+ }++ return (+ <motion.section+ initial={reduceMotion ? false : { opacity: 0, y: 12 }}+ animate={reduceMotion ? undefined : { opacity: 1, y: 0 }}+ transition={+ reduceMotion+ ? undefined+ : {+ duration: 0.32,+ ease: EASE_OUT,+ delay: 0.04 + index * 0.05,+ }+ }+ className="flex w-full flex-col gap-2"+ >+ <div className="flex flex-col gap-1 px-4">+ <Text variant="body-medium" as="span" className="text-textBlack">+ Account+ </Text>+ <Text variant="small" className="text-zinc-500">+ Manage your sign-in details.+ </Text>+ </div>++ <div className="flex flex-col divide-y divide-zinc-200 rounded-[18px] border border-zinc-200 bg-white shadow-[0_1px_2px_rgba(15,15,20,0.04)]">+ <div className="flex items-center justify-between gap-4 px-4 py-4">+ <Text variant="body-medium" as="span" className="text-textBlack">+ </Text>++ <div className="flex min-w-0 items-center gap-3">+ <Text+ variant="body"+ as="span"+ className="min-w-0 truncate text-textBlack"+ >+ {currentEmail}+ </Text>++ <Dialog+ title="Update email"+ styling={{ maxWidth: "420px" }}+ controlled={{+ isOpen: emailDialogOpen,+ set: (open) => {+ setEmailDialogOpen(open);+ if (open) emailForm.reset({ email: currentEmail });+ },+ }}+ >+ <Dialog.Trigger>+ <Button+ variant="secondary"+ size="small"+ aria-label="Edit email"+ className="h-7 min-w-0 px-1.5 py-0.5"+ >+ <PencilSimpleIcon size={14} weight="duotone" />+ </Button>+ </Dialog.Trigger>+ <Dialog.Content>+ <Form form={emailForm} onSubmit={handleEmailSubmit}>+ <div className="flex flex-col gap-4">+ <Text variant="small" as="span" className="text-zinc-500">+ We'll send a confirmation link to verify your new+ address.+ </Text>+ <FormField+ control={emailForm.control}+ name="email"+ render={({ field, fieldState }) => (+ <FormItem className="space-y-0">+ <FormControl>+ <Input+ id={field.name}+ label="Email"+ type="email"+ autoComplete="email"+ size="medium"+ className="w-full"+ wrapperClassName="!mb-0"+ error={fieldState.error?.message}+ {...field}+ />+ </FormControl>+ </FormItem>+ )}+ />+ </div>+ <Dialog.Footer>+ <Button+ type="button"+ variant="ghost"+ size="small"+ onClick={() => setEmailDialogOpen(false)}+ >+ Cancel+ </Button>+ <Button+ type="submit"+ size="small"+ disabled={disableEmailSubmit}+ loading={isUpdatingEmail}+ >+ {isUpdatingEmail ? "Saving" : "Update email"}+ </Button>+ </Dialog.Footer>+ </Form>+ </Dialog.Content>+ </Dialog>+ </div>+ </div>++ <div className="flex items-center justify-between gap-4 px-4 py-4">+ <Text variant="body-medium" as="span" className="text-textBlack">+ Password+ </Text>++ <Button+ as="NextLink"+ href="/reset-password"+ size="small"+ variant="secondary"+ >+ Reset password+ </Button>+ </div>+ </div>+ </motion.section>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/AccountCard/useAccountCard.ts b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/AccountCard/useAccountCard.tsnew file mode 100644index 0000000000..2cade500a6--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/AccountCard/useAccountCard.ts@@ -0,0 +1,76 @@+"use client";++import { zodResolver } from "@hookform/resolvers/zod";+import type { User } from "@supabase/supabase-js";+import { useForm } from "react-hook-form";+import { z } from "zod";++import { usePostV1UpdateUserEmail } from "@/app/api/__generated__/endpoints/auth/auth";+import { toast } from "@/components/molecules/Toast/use-toast";++const emailSchema = z.object({+ email: z+ .string()+ .min(1, "Email is required")+ .email("Enter a valid email address"),+});++type EmailFormValues = z.infer<typeof emailSchema>;++async function updateEmailViaSupabase(email: string) {+ const response = await fetch("/api/auth/user", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ email }),+ });++ if (!response.ok) {+ const error = await response.json().catch(() => ({}));+ throw new Error(error.error ?? "Failed to update email");+ }++ return response.json();+}++export function useAccountCard({ user }: { user: User }) {+ const currentEmail = user.email ?? "";++ const emailForm = useForm<EmailFormValues>({+ resolver: zodResolver(emailSchema),+ defaultValues: { email: currentEmail },+ mode: "onChange",+ });++ const updateEmailServer = usePostV1UpdateUserEmail();++ async function onSubmitEmail(values: EmailFormValues): Promise<boolean> {+ if (values.email === currentEmail) return false;++ try {+ await Promise.all([+ updateEmailViaSupabase(values.email),+ updateEmailServer.mutateAsync({ data: values.email }),+ ]);+ toast({+ title: "Email update sent",+ description: "Check your inbox to confirm the change.",+ variant: "success",+ });+ return true;+ } catch (err) {+ toast({+ title: "Couldn't update email",+ description: err instanceof Error ? err.message : undefined,+ variant: "destructive",+ });+ return false;+ }+ }++ return {+ emailForm,+ onSubmitEmail,+ isUpdatingEmail: updateEmailServer.isPending,+ currentEmail,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/NotificationsCard/NotificationsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/NotificationsCard/NotificationsCard.tsxnew file mode 100644index 0000000000..6eac940adc--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/NotificationsCard/NotificationsCard.tsx@@ -0,0 +1,174 @@+"use client";++import { useState } from "react";+import { AnimatePresence, motion, useReducedMotion } from "framer-motion";++import { Switch } from "@/components/atoms/Switch/Switch";+import { Text } from "@/components/atoms/Text/Text";+import {+ TabsLine,+ TabsLineList,+ TabsLineTrigger,+} from "@/components/molecules/TabsLine/TabsLine";+import { cn } from "@/lib/utils";++import {+ EASE_OUT,+ NOTIFICATION_GROUPS,+ type NotificationFlags,+ type NotificationGroup,+ type NotificationItem,+ type NotificationKey,+} from "../../helpers";++interface Props {+ values: NotificationFlags;+ onToggle: (key: NotificationKey, value: boolean) => void;+ index?: number;+}++type TabId = NotificationGroup["id"];++export function NotificationsCard({ values, onToggle, index = 0 }: Props) {+ const reduceMotion = useReducedMotion();+ const [activeTab, setActiveTab] = useState<TabId>(NOTIFICATION_GROUPS[0].id);++ const tabs: { id: TabId; label: string; count: number }[] =+ NOTIFICATION_GROUPS.map((group) => ({+ id: group.id,+ label: group.title,+ count: group.items.filter((item) => values[item.key]).length,+ }));++ const visibleGroups: NotificationGroup[] = NOTIFICATION_GROUPS.filter(+ (g) => g.id === activeTab,+ );++ return (+ <motion.section+ initial={reduceMotion ? false : { opacity: 0, y: 12 }}+ animate={reduceMotion ? undefined : { opacity: 1, y: 0 }}+ transition={+ reduceMotion+ ? undefined+ : {+ duration: 0.32,+ ease: EASE_OUT,+ delay: 0.04 + index * 0.05,+ }+ }+ className="flex w-full flex-col gap-2 pt-0"+ >+ <div className="flex flex-col gap-1 px-4">+ <Text variant="body-medium" as="span" className="text-textBlack">+ Notifications+ </Text>+ <Text variant="small" className="text-zinc-500">+ Filter by category, or scan everything in one place.+ </Text>+ </div>++ <div className="flex flex-col gap-3 rounded-[18px] border border-zinc-200 bg-white px-4 pb-4 pt-0 shadow-[0_1px_2px_rgba(15,15,20,0.04)]">+ <TabsLine+ value={activeTab}+ onValueChange={(v) => setActiveTab(v as TabId)}+ >+ <TabsLineList>+ {tabs.map((tab) => (+ <TabsLineTrigger key={tab.id} value={tab.id}>+ {tab.label}+ <span className="ml-2 inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-zinc-100 px-1 text-[11px] font-medium tabular-nums text-zinc-500">+ {tab.count}+ </span>+ </TabsLineTrigger>+ ))}+ </TabsLineList>+ </TabsLine>++ <AnimatePresence initial={false} mode="wait">+ <motion.div+ key={activeTab}+ initial={reduceMotion ? false : { opacity: 0, y: 6 }}+ animate={reduceMotion ? undefined : { opacity: 1, y: 0 }}+ exit={reduceMotion ? undefined : { opacity: 0, y: -6 }}+ transition={+ reduceMotion ? undefined : { duration: 0.2, ease: EASE_OUT }+ }+ className="flex flex-col gap-1"+ >+ {visibleGroups.map((group) => (+ <NotificationGroupSection+ key={group.id}+ group={group}+ values={values}+ onToggle={onToggle}+ />+ ))}+ </motion.div>+ </AnimatePresence>+ </div>+ </motion.section>+ );+}++function NotificationGroupSection({+ group,+ values,+ onToggle,+}: {+ group: NotificationGroup;+ values: NotificationFlags;+ onToggle: (key: NotificationKey, value: boolean) => void;+}) {+ return (+ <div className="flex flex-col">+ {group.items.map((item, i) => (+ <NotificationRow+ key={item.key}+ item={item}+ value={values[item.key]}+ onChange={(checked) => onToggle(item.key, checked)}+ isLast={i === group.items.length - 1}+ />+ ))}+ </div>+ );+}++function NotificationRow({+ item,+ value,+ onChange,+ isLast,+}: {+ item: NotificationItem;+ value: boolean;+ onChange: (value: boolean) => void;+ isLast: boolean;+}) {+ const id = `notif-${item.key}`;+ return (+ <label+ htmlFor={id}+ className={cn(+ "group flex cursor-pointer items-center justify-between gap-4 rounded-[12px] px-4 py-3 transition-colors duration-150 ease-out hover:bg-zinc-50",+ !isLast && "mb-0.5",+ )}+ >+ <div className="flex min-w-0 flex-col">+ <Text variant="body-medium" as="span" className="text-textBlack">+ {item.title}+ </Text>+ <Text variant="small" as="span" className="text-zinc-500">+ {item.description}+ </Text>+ </div>+ <Switch+ id={id}+ aria-label={item.title}+ checked={value}+ onCheckedChange={onChange}+ />+ </label>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/PreferencesHeader/PreferencesHeader.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/PreferencesHeader/PreferencesHeader.tsxnew file mode 100644index 0000000000..7f23dd24a8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/PreferencesHeader/PreferencesHeader.tsx@@ -0,0 +1,27 @@+"use client";++import { motion, useReducedMotion } from "framer-motion";++import { Text } from "@/components/atoms/Text/Text";++import { EASE_OUT } from "../../helpers";++export function PreferencesHeader() {+ const reduceMotion = useReducedMotion();++ return (+ <motion.header+ initial={reduceMotion ? false : { opacity: 0, y: 8 }}+ animate={reduceMotion ? undefined : { opacity: 1, y: 0 }}+ transition={reduceMotion ? undefined : { duration: 0.32, ease: EASE_OUT }}+ className="flex min-w-0 flex-col pb-2 pl-4"+ >+ <Text variant="h4" as="h1" className="leading-[28px] text-textBlack">+ Preferences+ </Text>+ <Text variant="body" className="mt-4 max-w-[600px] text-zinc-700">+ Tune your account, time zone, and which notifications reach you.+ </Text>+ </motion.header>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/PreferencesSkeleton/PreferencesSkeleton.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/PreferencesSkeleton/PreferencesSkeleton.tsxnew file mode 100644index 0000000000..9a188a7785--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/PreferencesSkeleton/PreferencesSkeleton.tsx@@ -0,0 +1,96 @@+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";++export function PreferencesSkeleton() {+ return (+ <div className="flex flex-col gap-6 pb-8" aria-busy="true">+ <div className="flex min-w-0 flex-col gap-3 pb-2 pl-4">+ <Skeleton className="h-7 w-32" />+ <Skeleton className="mt-2 h-4 w-[420px] max-w-full" />+ </div>++ <AccountSkeleton />+ <TimezoneSkeleton />+ <NotificationsSkeleton />++ <div className="flex items-center justify-end gap-2 px-4">+ <Skeleton className="h-12 w-32 rounded-full" />+ <Skeleton className="h-12 w-28 rounded-full" />+ </div>+ </div>+ );+}++function AccountSkeleton() {+ return (+ <div className="flex w-full flex-col gap-2">+ <div className="flex flex-col gap-1 px-4">+ <Skeleton className="h-5 w-24" />+ <Skeleton className="h-3.5 w-56" />+ </div>+ <div className="flex flex-col divide-y divide-zinc-200 rounded-[18px] border border-zinc-200 bg-white shadow-[0_1px_2px_rgba(15,15,20,0.04)]">+ <div className="flex items-center justify-between gap-4 px-4 py-4">+ <Skeleton className="h-4 w-14" />+ <div className="flex items-center gap-3">+ <Skeleton className="h-4 w-48" />+ <Skeleton className="h-7 w-7 rounded-full" />+ </div>+ </div>+ <div className="flex items-center justify-between gap-4 px-4 py-4">+ <Skeleton className="h-4 w-20" />+ <Skeleton className="h-9 w-32 rounded-full" />+ </div>+ </div>+ </div>+ );+}++function TimezoneSkeleton() {+ return (+ <div className="flex w-full flex-col">+ <div className="flex flex-col gap-3 rounded-[18px] border border-zinc-200 bg-white px-4 py-3 shadow-[0_1px_2px_rgba(15,15,20,0.04)]">+ <div className="flex items-center justify-between gap-4">+ <div className="flex items-center gap-2">+ <Skeleton className="h-4 w-20" />+ <Skeleton className="h-4 w-4 rounded-full" />+ </div>+ <div className="flex items-center gap-2">+ <Skeleton className="h-9 w-40 rounded-full" />+ <Skeleton className="h-7 w-20 rounded-full" />+ </div>+ </div>+ </div>+ </div>+ );+}++function NotificationsSkeleton() {+ return (+ <div className="flex w-full flex-col gap-2">+ <div className="flex flex-col gap-1 px-4">+ <Skeleton className="h-5 w-32" />+ <Skeleton className="h-3.5 w-72" />+ </div>+ <div className="flex flex-col gap-3 rounded-[18px] border border-zinc-200 bg-white px-4 pb-4 pt-0 shadow-[0_1px_2px_rgba(15,15,20,0.04)]">+ <div className="flex items-center gap-6 border-b border-zinc-100 pb-3 pt-3">+ {Array.from({ length: 3 }).map((_, i) => (+ <Skeleton key={i} className="h-5 w-28" />+ ))}+ </div>+ <div className="flex flex-col">+ {Array.from({ length: 4 }).map((_, i) => (+ <div+ key={i}+ className="flex items-center justify-between gap-4 rounded-[12px] px-4 py-3"+ >+ <div className="flex min-w-0 flex-col gap-2">+ <Skeleton className="h-4 w-56" />+ <Skeleton className="h-3 w-72" />+ </div>+ <Skeleton className="h-5 w-9 rounded-full" />+ </div>+ ))}+ </div>+ </div>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/SaveBar/SaveBar.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/SaveBar/SaveBar.tsxnew file mode 100644index 0000000000..0da775c539--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/SaveBar/SaveBar.tsx@@ -0,0 +1,34 @@+"use client";++import { Button } from "@/components/atoms/Button/Button";++interface Props {+ visible: boolean;+ saving: boolean;+ onDiscard: () => void;+ onSave: () => void;+}++export function SaveBar({ visible, saving, onDiscard, onSave }: Props) {+ return (+ <div className="flex items-center justify-end gap-2 px-4">+ <Button+ variant="primary"+ size="large"+ onClick={onSave}+ loading={saving}+ disabled={saving || !visible}+ >+ Save changes+ </Button>+ <Button+ variant="secondary"+ size="large"+ onClick={onDiscard}+ disabled={saving || !visible}+ >+ Discard+ </Button>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/TimezoneCard/TimezoneCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/TimezoneCard/TimezoneCard.tsxnew file mode 100644index 0000000000..6f845a9c14--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/components/TimezoneCard/TimezoneCard.tsx@@ -0,0 +1,137 @@+"use client";++import { ClockIcon, GlobeIcon, InfoIcon } from "@phosphor-icons/react";+import { AnimatePresence, motion, useReducedMotion } from "framer-motion";++import { Select } from "@/components/atoms/Select/Select";+import { Text } from "@/components/atoms/Text/Text";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/atoms/Tooltip/BaseTooltip";++import {+ EASE_OUT,+ TIMEZONES,+ detectBrowserTimezone,+ findTimezoneLabel,+ formatGmtOffset,+} from "../../helpers";++interface Props {+ value: string;+ initialValue: string;+ onChange: (timezone: string) => void;+ index?: number;+}++export function TimezoneCard({+ value,+ initialValue,+ onChange,+ index = 0,+}: Props) {+ const reduceMotion = useReducedMotion();+ const browserTz = detectBrowserTimezone();+ const offset = formatGmtOffset(value);+ const browserLabel = findTimezoneLabel(browserTz);++ const showAutoDetect = initialValue !== browserTz && value !== browserTz;++ const options = TIMEZONES.some((t) => t.value === value)+ ? TIMEZONES+ : [{ value, label: findTimezoneLabel(value) }, ...TIMEZONES];++ return (+ <motion.section+ initial={reduceMotion ? false : { opacity: 0, y: 12 }}+ animate={reduceMotion ? undefined : { opacity: 1, y: 0 }}+ transition={+ reduceMotion+ ? undefined+ : {+ duration: 0.32,+ ease: EASE_OUT,+ delay: 0.04 + index * 0.05,+ }+ }+ className="flex w-full flex-col"+ >+ <div className="flex h-fit flex-col justify-center gap-3 rounded-[18px] border border-zinc-200 bg-white px-4 py-3 shadow-[0_1px_2px_rgba(15,15,20,0.04)]">+ <div className="flex items-center justify-between gap-4">+ <div className="flex items-center gap-2">+ <Text variant="body-medium" as="span" className="text-textBlack">+ Time zone+ </Text>+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ aria-label="Time zone info"+ className="flex items-center text-zinc-400 transition-colors hover:text-zinc-600 focus-visible:text-zinc-600 focus-visible:outline-none"+ >+ <InfoIcon size={16} weight="duotone" />+ </button>+ </TooltipTrigger>+ <TooltipContent>+ Used for run schedules, summaries, and timestamps.+ </TooltipContent>+ </Tooltip>+ </div>++ <div className="flex h-fit items-center gap-2">+ <Select+ id="timezone"+ label="Timezone"+ hideLabel+ value={value}+ onValueChange={onChange}+ options={options}+ placeholder="Select your timezone"+ size="small"+ wrapperClassName="!mb-0 w-fit"+ />+ {offset ? (+ <div className="flex h-fit shrink-0 items-center gap-1.5 rounded-full border border-zinc-200 bg-zinc-50 px-3 py-1.5 tabular-nums text-zinc-600">+ <ClockIcon size={14} weight="duotone" />+ <Text+ variant="small-medium"+ as="span"+ className="text-zinc-600"+ >+ {offset}+ </Text>+ </div>+ ) : null}+ </div>+ </div>++ <AnimatePresence initial={false}>+ {showAutoDetect ? (+ <motion.button+ key="autodetect"+ type="button"+ onClick={() => onChange(browserTz)}+ initial={reduceMotion ? false : { opacity: 0, y: -4, height: 0 }}+ animate={+ reduceMotion ? undefined : { opacity: 1, y: 0, height: "auto" }+ }+ exit={reduceMotion ? undefined : { opacity: 0, y: -4, height: 0 }}+ transition={+ reduceMotion ? undefined : { duration: 0.22, ease: EASE_OUT }+ }+ className="flex w-fit items-center gap-2 self-end overflow-hidden rounded-full border border-violet-300 bg-violet-50/60 px-3 py-1.5 text-left text-violet-800 transition-colors duration-150 ease-out hover:bg-violet-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-400 focus-visible:ring-offset-2"+ >+ <GlobeIcon size={16} weight="duotone" />+ <Text variant="small" as="span" className="text-violet-800">+ Looks like you're in{" "}+ <span className="font-medium">{browserLabel}</span>. Use that?+ </Text>+ </motion.button>+ ) : null}+ </AnimatePresence>+ </div>+ </motion.section>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/preferences/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/helpers.tsnew file mode 100644index 0000000000..8eda005119--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/helpers.ts@@ -0,0 +1,289 @@+import {+ BellSimpleRingingIcon,+ ChartLineUpIcon,+ CoinsIcon,+ RobotIcon,+ StorefrontIcon,+} from "@phosphor-icons/react";+import type { Icon } from "@phosphor-icons/react";++import type { NotificationPreference } from "@/app/api/__generated__/models/notificationPreference";++export const EASE_OUT = [0.16, 1, 0.3, 1] as const;+export const EASE_IOS = [0.32, 0.72, 0, 1] as const;+export const EASE_IN_OUT = [0.4, 0, 0.2, 1] as const;++export type NotificationKey =+ | "notifyOnAgentRun"+ | "notifyOnBlockExecutionFailed"+ | "notifyOnContinuousAgentError"+ | "notifyOnAgentApproved"+ | "notifyOnAgentRejected"+ | "notifyOnZeroBalance"+ | "notifyOnLowBalance"+ | "notifyOnDailySummary"+ | "notifyOnWeeklySummary"+ | "notifyOnMonthlySummary";++export type NotificationFlags = Record<NotificationKey, boolean>;++export interface PreferencesFormState {+ timezone: string;+ notifications: NotificationFlags;+}++export interface NotificationItem {+ key: NotificationKey;+ title: string;+ description: string;+}++export interface NotificationGroup {+ id: "agents" | "store" | "balance" | "summary";+ title: string;+ caption: string;+ icon: Icon;+ accent: string;+ items: NotificationItem[];+}++export const NOTIFICATION_GROUPS: NotificationGroup[] = [+ {+ id: "agents",+ title: "Agent activity",+ caption: "Heads-up when your agents do something — or stop doing it.",+ icon: RobotIcon,+ accent: "from-violet-500/15 to-violet-500/0 text-violet-700",+ items: [+ {+ key: "notifyOnAgentRun",+ title: "Run started or completed",+ description: "Hear from us when an agent kicks off or finishes a run.",+ },+ {+ key: "notifyOnBlockExecutionFailed",+ title: "Block execution failed",+ description: "Get notified the moment a block fails mid-run.",+ },+ {+ key: "notifyOnContinuousAgentError",+ title: "Continuous errors",+ description:+ "Alert me when an agent runs into the same error repeatedly.",+ },+ ],+ },+ {+ id: "store",+ title: "Marketplace",+ caption: "Updates on agents you've published to the store.",+ icon: StorefrontIcon,+ accent: "from-amber-400/15 to-amber-500/0 text-amber-700",+ items: [+ {+ key: "notifyOnAgentApproved",+ title: "Agent approved",+ description: "Your submission is live in the store.",+ },+ {+ key: "notifyOnAgentRejected",+ title: "Agent needs changes",+ description: "Reviewers have feedback before your agent can go live.",+ },+ ],+ },+ {+ id: "balance",+ title: "Credits & balance",+ caption: "Stay ahead of an empty tank.",+ icon: CoinsIcon,+ accent: "from-emerald-400/15 to-emerald-500/0 text-emerald-700",+ items: [+ {+ key: "notifyOnLowBalance",+ title: "Running low",+ description: "Warn me before I run out of credits.",+ },+ {+ key: "notifyOnZeroBalance",+ title: "Empty balance",+ description: "Let me know when my balance hits zero.",+ },+ ],+ },+ {+ id: "summary",+ title: "Summaries",+ caption: "Recap emails to keep tabs on your account at a glance.",+ icon: ChartLineUpIcon,+ accent: "from-sky-400/15 to-sky-500/0 text-sky-700",+ items: [+ {+ key: "notifyOnDailySummary",+ title: "Daily summary",+ description: "A short daily digest of activity.",+ },+ {+ key: "notifyOnWeeklySummary",+ title: "Weekly summary",+ description: "A weekly overview of performance.",+ },+ {+ key: "notifyOnMonthlySummary",+ title: "Monthly summary",+ description: "A comprehensive monthly report.",+ },+ ],+ },+];++export const NOTIFICATIONS_FALLBACK_ICON = BellSimpleRingingIcon;++const PREFERENCE_API_KEYS: Record<NotificationKey, string> = {+ notifyOnAgentRun: "AGENT_RUN",+ notifyOnBlockExecutionFailed: "BLOCK_EXECUTION_FAILED",+ notifyOnContinuousAgentError: "CONTINUOUS_AGENT_ERROR",+ notifyOnAgentApproved: "AGENT_APPROVED",+ notifyOnAgentRejected: "AGENT_REJECTED",+ notifyOnZeroBalance: "ZERO_BALANCE",+ notifyOnLowBalance: "LOW_BALANCE",+ notifyOnDailySummary: "DAILY_SUMMARY",+ notifyOnWeeklySummary: "WEEKLY_SUMMARY",+ notifyOnMonthlySummary: "MONTHLY_SUMMARY",+};++export function preferencesToFlags(+ preferences: NotificationPreference,+): NotificationFlags {+ const raw = preferences.preferences ?? {};+ return Object.fromEntries(+ (Object.keys(PREFERENCE_API_KEYS) as NotificationKey[]).map((key) => [+ key,+ Boolean(raw[PREFERENCE_API_KEYS[key]]),+ ]),+ ) as NotificationFlags;+}++export function flagsToPreferenceMap(+ flags: NotificationFlags,+): Record<string, boolean> {+ return Object.fromEntries(+ (Object.keys(PREFERENCE_API_KEYS) as NotificationKey[]).map((key) => [+ PREFERENCE_API_KEYS[key],+ flags[key],+ ]),+ );+}++export function detectBrowserTimezone(): string {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";+ } catch {+ return "UTC";+ }+}++export function isFormDirty(+ initial: PreferencesFormState,+ current: PreferencesFormState,+): boolean {+ if (initial.timezone !== current.timezone) return true;+ for (const key of Object.keys(initial.notifications) as NotificationKey[]) {+ if (initial.notifications[key] !== current.notifications[key]) return true;+ }+ return false;+}++export function dirtyKinds(+ initial: PreferencesFormState,+ current: PreferencesFormState,+): { timezone: boolean; notifications: boolean } {+ const timezone = initial.timezone !== current.timezone;+ let notifications = false;+ for (const key of Object.keys(initial.notifications) as NotificationKey[]) {+ if (initial.notifications[key] !== current.notifications[key]) {+ notifications = true;+ break;+ }+ }+ return { timezone, notifications };+}++const TIMEZONE_LIST: { value: string; label: string }[] = [+ { value: "UTC", label: "UTC (Coordinated Universal Time)" },+ { value: "America/Los_Angeles", label: "Los Angeles (US - Pacific)" },+ { value: "America/Denver", label: "Denver (US - Mountain)" },+ { value: "America/Chicago", label: "Chicago (US - Central)" },+ { value: "America/New_York", label: "New York (US - Eastern)" },+ { value: "America/Toronto", label: "Toronto (Canada - Eastern)" },+ { value: "America/Mexico_City", label: "Mexico City (Mexico)" },+ { value: "America/Sao_Paulo", label: "São Paulo (Brazil)" },+ { value: "America/Buenos_Aires", label: "Buenos Aires (Argentina)" },+ { value: "America/Bogota", label: "Bogotá (Colombia)" },+ { value: "America/Lima", label: "Lima (Peru)" },+ { value: "America/Santiago", label: "Santiago (Chile)" },+ { value: "Europe/London", label: "London (UK)" },+ { value: "Europe/Dublin", label: "Dublin (Ireland)" },+ { value: "Europe/Lisbon", label: "Lisbon (Portugal)" },+ { value: "Europe/Madrid", label: "Madrid (Spain)" },+ { value: "Europe/Paris", label: "Paris (France)" },+ { value: "Europe/Amsterdam", label: "Amsterdam (Netherlands)" },+ { value: "Europe/Brussels", label: "Brussels (Belgium)" },+ { value: "Europe/Berlin", label: "Berlin (Germany)" },+ { value: "Europe/Zurich", label: "Zurich (Switzerland)" },+ { value: "Europe/Rome", label: "Rome (Italy)" },+ { value: "Europe/Vienna", label: "Vienna (Austria)" },+ { value: "Europe/Prague", label: "Prague (Czechia)" },+ { value: "Europe/Warsaw", label: "Warsaw (Poland)" },+ { value: "Europe/Stockholm", label: "Stockholm (Sweden)" },+ { value: "Europe/Oslo", label: "Oslo (Norway)" },+ { value: "Europe/Copenhagen", label: "Copenhagen (Denmark)" },+ { value: "Europe/Helsinki", label: "Helsinki (Finland)" },+ { value: "Europe/Athens", label: "Athens (Greece)" },+ { value: "Europe/Istanbul", label: "Istanbul (Türkiye)" },+ { value: "Europe/Moscow", label: "Moscow (Russia)" },+ { value: "Africa/Cairo", label: "Cairo (Egypt)" },+ { value: "Africa/Lagos", label: "Lagos (Nigeria)" },+ { value: "Africa/Nairobi", label: "Nairobi (Kenya)" },+ { value: "Africa/Johannesburg", label: "Johannesburg (South Africa)" },+ { value: "Asia/Dubai", label: "Dubai (UAE)" },+ { value: "Asia/Tehran", label: "Tehran (Iran)" },+ { value: "Asia/Karachi", label: "Karachi (Pakistan)" },+ { value: "Asia/Kolkata", label: "Kolkata (India)" },+ { value: "Asia/Dhaka", label: "Dhaka (Bangladesh)" },+ { value: "Asia/Bangkok", label: "Bangkok (Thailand)" },+ { value: "Asia/Jakarta", label: "Jakarta (Indonesia)" },+ { value: "Asia/Singapore", label: "Singapore" },+ { value: "Asia/Manila", label: "Manila (Philippines)" },+ { value: "Asia/Hong_Kong", label: "Hong Kong" },+ { value: "Asia/Shanghai", label: "Shanghai (China)" },+ { value: "Asia/Taipei", label: "Taipei (Taiwan)" },+ { value: "Asia/Seoul", label: "Seoul (South Korea)" },+ { value: "Asia/Tokyo", label: "Tokyo (Japan)" },+ { value: "Australia/Perth", label: "Perth (Australia - West)" },+ { value: "Australia/Adelaide", label: "Adelaide (Australia - Central)" },+ { value: "Australia/Brisbane", label: "Brisbane (Australia - East)" },+ { value: "Australia/Sydney", label: "Sydney (Australia - East)" },+ { value: "Pacific/Auckland", label: "Auckland (New Zealand)" },+ { value: "Pacific/Honolulu", label: "Honolulu (US - Hawaii)" },+];++export const TIMEZONES = TIMEZONE_LIST;++export function findTimezoneLabel(value: string): string {+ return TIMEZONES.find((t) => t.value === value)?.label ?? value;+}++export function formatGmtOffset(timezone: string): string | null {+ try {+ const formatter = new Intl.DateTimeFormat("en-US", {+ timeZone: timezone,+ timeZoneName: "shortOffset",+ });+ const parts = formatter.formatToParts(new Date());+ const offset = parts.find((p) => p.type === "timeZoneName")?.value;+ return offset ?? null;+ } catch {+ return null;+ }+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/preferences/page.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/page.tsxindex 2febeea2ba..b728a1b722 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/preferences/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/page.tsx@@ -1,16 +1,81 @@"use client";-import { Text } from "@/components/atoms/Text/Text";+import { useEffect } from "react";++import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";++import { AccountCard } from "./components/AccountCard/AccountCard";+import { NotificationsCard } from "./components/NotificationsCard/NotificationsCard";+import { PreferencesHeader } from "./components/PreferencesHeader/PreferencesHeader";+import { PreferencesSkeleton } from "./components/PreferencesSkeleton/PreferencesSkeleton";+import { SaveBar } from "./components/SaveBar/SaveBar";+import { TimezoneCard } from "./components/TimezoneCard/TimezoneCard";+import { usePreferencesPage } from "./usePreferencesPage";export default function SettingsPreferencesPage() {+ useEffect(() => {+ document.title = "Preferences – AutoGPT Platform";+ }, []);++ const {+ user,+ isLoading,+ isError,+ error,+ refetch,+ formState,+ savedState,+ dirty,+ isSaving,+ setTimezone,+ toggleNotification,+ discardChanges,+ savePreferences,+ } = usePreferencesPage();++ if (isError) {+ return (+ <ErrorCard+ context="settings"+ responseError={+ error ? { detail: (error as { detail?: string }).detail } : undefined+ }+ onRetry={() => {+ void refetch();+ }}+ />+ );+ }++ if (isLoading || !user) {+ return <PreferencesSkeleton />;+ }+return (- <>- <Text variant="h4" className="text-[#1F1F20]">- Settings- </Text>- <Text variant="large" className="mt-2 text-zinc-600">- Coming soon.- </Text>- </>+ <div className="flex flex-col gap-6 pb-8">+ <PreferencesHeader />++ <AccountCard user={user} index={0} />++ <TimezoneCard+ value={formState.timezone}+ initialValue={savedState.timezone}+ onChange={setTimezone}+ index={1}+ />++ <NotificationsCard+ values={formState.notifications}+ onToggle={toggleNotification}+ index={2}+ />++ <SaveBar+ visible={dirty}+ saving={isSaving}+ onDiscard={discardChanges}+ onSave={savePreferences}+ />+ </div>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/preferences/usePreferencesPage.ts b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/usePreferencesPage.tsnew file mode 100644index 0000000000..c532feb413--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/usePreferencesPage.ts@@ -0,0 +1,238 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";++import {+ getGetV1GetNotificationPreferencesQueryKey,+ getGetV1GetUserTimezoneQueryKey,+ useGetV1GetNotificationPreferences,+ useGetV1GetUserTimezone,+ usePostV1UpdateNotificationPreferences,+ usePostV1UpdateUserTimezone,+} from "@/app/api/__generated__/endpoints/auth/auth";+import type { UpdateTimezoneRequestTimezone } from "@/app/api/__generated__/models/updateTimezoneRequestTimezone";+import { okData } from "@/app/api/helpers";+import { toast } from "@/components/molecules/Toast/use-toast";+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";++import {+ detectBrowserTimezone,+ dirtyKinds,+ flagsToPreferenceMap,+ isFormDirty,+ preferencesToFlags,+ type NotificationFlags,+ type NotificationKey,+ type PreferencesFormState,+} from "./helpers";++const EMPTY_FLAGS: NotificationFlags = {+ notifyOnAgentRun: false,+ notifyOnBlockExecutionFailed: false,+ notifyOnContinuousAgentError: false,+ notifyOnAgentApproved: false,+ notifyOnAgentRejected: false,+ notifyOnZeroBalance: false,+ notifyOnLowBalance: false,+ notifyOnDailySummary: false,+ notifyOnWeeklySummary: false,+ notifyOnMonthlySummary: false,+};++export function usePreferencesPage() {+ const { user } = useSupabase();+ const queryClient = useQueryClient();++ const preferencesQuery = useGetV1GetNotificationPreferences({+ query: {+ enabled: !!user,+ select: okData,+ },+ });++ const timezoneQuery = useGetV1GetUserTimezone({+ query: {+ enabled: !!user,+ select: (res) => okData(res)?.timezone ?? "not-set",+ },+ });++ const isLoading =+ !user ||+ preferencesQuery.isLoading ||+ timezoneQuery.isLoading ||+ !preferencesQuery.data;++ const initialTimezone =+ timezoneQuery.data && timezoneQuery.data !== "not-set"+ ? timezoneQuery.data+ : detectBrowserTimezone();+ const initialFlags = preferencesQuery.data+ ? preferencesToFlags(preferencesQuery.data)+ : EMPTY_FLAGS;+ const initialState: PreferencesFormState = {+ timezone: initialTimezone,+ notifications: initialFlags,+ };++ const [formState, setFormState] = useState<PreferencesFormState>({+ timezone: detectBrowserTimezone(),+ notifications: EMPTY_FLAGS,+ });+ const [savedState, setSavedState] = useState<PreferencesFormState>({+ timezone: detectBrowserTimezone(),+ notifications: EMPTY_FLAGS,+ });+ const [isSaving, setIsSaving] = useState(false);+ const hasInitializedFormState = useRef(false);++ useEffect(+ function syncFormStateOnce() {+ if (hasInitializedFormState.current) return;+ if (!preferencesQuery.isSuccess) return;+ if (!timezoneQuery.isSuccess) return;+ setFormState(initialState);+ setSavedState(initialState);+ hasInitializedFormState.current = true;+ },+ [initialState, preferencesQuery.isSuccess, timezoneQuery.isSuccess],+ );++ const dirty = isFormDirty(savedState, formState);+ const dirtyParts = dirtyKinds(savedState, formState);++ function setTimezone(value: string) {+ setFormState((prev) => ({ ...prev, timezone: value }));+ }++ function toggleNotification(key: NotificationKey, value: boolean) {+ setFormState((prev) => ({+ ...prev,+ notifications: { ...prev.notifications, [key]: value },+ }));+ }++ function setAllInGroup(keys: NotificationKey[], value: boolean) {+ setFormState((prev) => {+ const next = { ...prev.notifications };+ for (const key of keys) next[key] = value;+ return { ...prev, notifications: next };+ });+ }++ function discardChanges() {+ setFormState(savedState);+ }++ const updateTimezone = usePostV1UpdateUserTimezone();+ const updateNotifications = usePostV1UpdateNotificationPreferences();++ async function savePreferences() {+ if (!dirty || isSaving || !user) return;++ const snapshot = formState;+ const partsAtSubmit = dirtyParts;++ setIsSaving(true);++ let timezoneSaved = !partsAtSubmit.timezone;+ let notificationsSaved = !partsAtSubmit.notifications;+ const failures: string[] = [];++ if (partsAtSubmit.timezone) {+ try {+ await updateTimezone.mutateAsync({+ data: {+ timezone: snapshot.timezone as UpdateTimezoneRequestTimezone,+ },+ });+ queryClient.setQueryData(+ getGetV1GetUserTimezoneQueryKey(),+ (prev: unknown) => {+ if (+ prev &&+ typeof prev === "object" &&+ "data" in (prev as Record<string, unknown>)+ ) {+ return {+ ...(prev as Record<string, unknown>),+ data: { timezone: snapshot.timezone },+ };+ }+ return { status: 200, data: { timezone: snapshot.timezone } };+ },+ );+ setSavedState((prev) => ({ ...prev, timezone: snapshot.timezone }));+ timezoneSaved = true;+ } catch (err) {+ failures.push(+ `Time zone: ${err instanceof Error ? err.message : "unknown error"}`,+ );+ }+ }++ if (partsAtSubmit.notifications) {+ try {+ await updateNotifications.mutateAsync({+ data: {+ email: user.email ?? "",+ preferences: flagsToPreferenceMap(snapshot.notifications),+ daily_limit: 0,+ },+ });+ await queryClient.invalidateQueries({+ queryKey: getGetV1GetNotificationPreferencesQueryKey(),+ });+ setSavedState((prev) => ({+ ...prev,+ notifications: snapshot.notifications,+ }));+ notificationsSaved = true;+ } catch (err) {+ failures.push(+ `Notifications: ${err instanceof Error ? err.message : "unknown error"}`,+ );+ }+ }++ setIsSaving(false);++ if (failures.length === 0) {+ toast({ title: "Preferences saved", variant: "success" });+ } else if (timezoneSaved || notificationsSaved) {+ toast({+ title: "Preferences partially saved",+ description: failures.join("; "),+ variant: "destructive",+ });+ } else {+ toast({+ title: "Couldn't save preferences",+ description: failures.join("; "),+ variant: "destructive",+ });+ }+ }++ return {+ user,+ isLoading,+ isError: preferencesQuery.isError || timezoneQuery.isError,+ error: preferencesQuery.error ?? timezoneQuery.error,+ refetch: () => {+ void preferencesQuery.refetch();+ void timezoneQuery.refetch();+ },+ formState,+ savedState,+ rawTimezone: timezoneQuery.data,+ dirty,+ isSaving,+ setTimezone,+ toggleNotification,+ setAllInGroup,+ discardChanges,+ savePreferences,+ };+}