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(platform): small fixes and stagger animations on settings pages (#12937)
Abhimanyu Yadavae4a4216201a
diff --git a/autogpt_platform/backend/backend/data/user.py b/autogpt_platform/backend/backend/data/user.pyindex dc29458fcd..86f9535f5d 100644--- a/autogpt_platform/backend/backend/data/user.py+++ b/autogpt_platform/backend/backend/data/user.py@@ -509,8 +509,15 @@ async def update_user_timezone(user_id: str, timezone: str) -> User:if not user:raise ValueError(f"User not found with ID: {user_id}")- # Invalidate cache for this user+ # Invalidate user caches so subsequent reads see the new timezone.+ # get_user_by_id and get_user_by_email are keyed by a single value+ # and can be deleted surgically; get_or_create_user is keyed by the+ # JWT-payload dict so we can't delete a single entry — clear it+ # entirely.get_user_by_id.cache_delete(user_id)+ if user.email:+ get_user_by_email.cache_delete(user.email)+ get_or_create_user.cache_clear()return User.from_db(user)except Exception as e:diff --git a/autogpt_platform/backend/backend/data/user_test.py b/autogpt_platform/backend/backend/data/user_test.pynew file mode 100644index 0000000000..f2b1829280--- /dev/null+++ b/autogpt_platform/backend/backend/data/user_test.py@@ -0,0 +1,66 @@+"""Unit tests for helpers in backend.data.user."""++from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.data import user as user_module+from backend.data.user import update_user_timezone+from backend.util.exceptions import DatabaseError+++class TestUpdateUserTimezone:+ @pytest.mark.asyncio+ async def test_invalidates_all_three_user_caches(self):+ prisma_user = MagicMock(id="user-1", email="[email protected]")+ sentinel_user = MagicMock()++ with (+ patch.object(user_module, "PrismaUser") as mock_prisma_user,+ patch.object(user_module.User, "from_db", return_value=sentinel_user),+ patch.object(user_module.get_user_by_id, "cache_delete") as by_id_del,+ patch.object(user_module.get_user_by_email, "cache_delete") as by_email_del,+ patch.object(user_module.get_or_create_user, "cache_clear") as goc_clear,+ ):+ mock_prisma_user.prisma.return_value.update = AsyncMock(+ return_value=prisma_user+ )+ result = await update_user_timezone("user-1", "Europe/London")++ assert result is sentinel_user+ by_id_del.assert_called_once_with("user-1")+ by_email_del.assert_called_once_with("[email protected]")+ goc_clear.assert_called_once_with()++ @pytest.mark.asyncio+ async def test_skips_email_cache_invalidation_when_email_missing(self):+ prisma_user = MagicMock(id="user-1", email=None)+ sentinel_user = MagicMock()++ with (+ patch.object(user_module, "PrismaUser") as mock_prisma_user,+ patch.object(user_module.User, "from_db", return_value=sentinel_user),+ patch.object(user_module.get_user_by_id, "cache_delete") as by_id_del,+ patch.object(user_module.get_user_by_email, "cache_delete") as by_email_del,+ patch.object(user_module.get_or_create_user, "cache_clear") as goc_clear,+ ):+ mock_prisma_user.prisma.return_value.update = AsyncMock(+ return_value=prisma_user+ )+ await update_user_timezone("user-1", "Europe/London")++ by_id_del.assert_called_once_with("user-1")+ by_email_del.assert_not_called()+ goc_clear.assert_called_once_with()++ @pytest.mark.asyncio+ async def test_wraps_prisma_errors_in_database_error(self):+ with patch.object(user_module, "PrismaUser") as mock_prisma_user:+ mock_prisma_user.prisma.return_value.update = AsyncMock(+ side_effect=RuntimeError("connection lost")+ )+ with pytest.raises(DatabaseError) as exc:+ await update_user_timezone("user-1", "Europe/London")++ assert "user-1" in str(exc.value)+ assert "connection lost" in str(exc.value)diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/api-keys/components/APIKeyList/APIKeyList.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/api-keys/components/APIKeyList/APIKeyList.tsxindex ccec7ff672..83662d04b3 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/api-keys/components/APIKeyList/APIKeyList.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/api-keys/components/APIKeyList/APIKeyList.tsx@@ -1,6 +1,7 @@"use client";import { AnimatePresence, motion, useReducedMotion } from "framer-motion";+import type { Variants } from "framer-motion";import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";@@ -11,6 +12,22 @@ import { APIKeySelectionBar } from "../APIKeySelectionBar/APIKeySelectionBar";import { DeleteAPIKeyDialog } from "../DeleteAPIKeyDialog/DeleteAPIKeyDialog";import { useAPIKeyListView } from "./useAPIKeyListView";+const LIST_CONTAINER_VARIANTS: Variants = {+ hidden: {},+ show: {+ transition: { staggerChildren: 0.04, delayChildren: 0.04 },+ },+};++const LIST_ITEM_VARIANTS: Variants = {+ hidden: { opacity: 0, y: 6 },+ show: {+ opacity: 1,+ y: 0,+ transition: { duration: 0.28, ease: [0.16, 1, 0.3, 1] },+ },+};+export function APIKeyList() {const {keys,@@ -77,17 +94,26 @@ export function APIKeyList() {)}</AnimatePresence>- <div className="flex flex-col divide-y divide-zinc-200 overflow-hidden rounded-[8px] border border-zinc-200 bg-white">+ <motion.div+ className="flex flex-col divide-y divide-zinc-200 overflow-hidden rounded-[8px] border border-zinc-200 bg-white"+ initial={reduceMotion ? false : "hidden"}+ animate={reduceMotion ? undefined : "show"}+ variants={reduceMotion ? undefined : LIST_CONTAINER_VARIANTS}+ >{keys.map((key) => (- <APIKeyRow+ <motion.divkey={key.id}- apiKey={key}- selected={selection.isSelected(key.id)}- onToggleSelected={() => selection.toggle(key.id)}- onDelete={() => requestDelete([key.id])}- />+ variants={reduceMotion ? undefined : LIST_ITEM_VARIANTS}+ >+ <APIKeyRow+ apiKey={key}+ selected={selection.isSelected(key.id)}+ onToggleSelected={() => selection.toggle(key.id)}+ onDelete={() => requestDelete([key.id])}+ />+ </motion.div>))}- </div>+ </motion.div>{deleteTarget && (<DeleteAPIKeyDialogdiff --git a/autogpt_platform/frontend/src/app/(platform)/settings/api-keys/components/APIKeyListSkeleton/APIKeyListSkeleton.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/api-keys/components/APIKeyListSkeleton/APIKeyListSkeleton.tsxindex 9525e32eff..73ed1c3e78 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/api-keys/components/APIKeyListSkeleton/APIKeyListSkeleton.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/api-keys/components/APIKeyListSkeleton/APIKeyListSkeleton.tsx@@ -1,20 +1,45 @@"use client";+import { motion, useReducedMotion } from "framer-motion";+import type { Variants } from "framer-motion";+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";const PLACEHOLDER_ROWS = Array.from({ length: 6 }, (_, i) => i);+const SKELETON_CONTAINER_VARIANTS: Variants = {+ hidden: {},+ show: {+ transition: { staggerChildren: 0.04, delayChildren: 0.04 },+ },+};++const SKELETON_ITEM_VARIANTS: Variants = {+ hidden: { opacity: 0, y: 6 },+ show: {+ opacity: 1,+ y: 0,+ transition: { duration: 0.28, ease: [0.16, 1, 0.3, 1] },+ },+};+export function APIKeyListSkeleton() {+ const reduceMotion = useReducedMotion();+return (- <div+ <motion.divrole="status"aria-label="Loading API keys"className="flex w-full flex-col divide-y divide-zinc-200 overflow-hidden rounded-[8px] border border-zinc-200 bg-white"+ initial={reduceMotion ? false : "hidden"}+ animate={reduceMotion ? undefined : "show"}+ variants={reduceMotion ? undefined : SKELETON_CONTAINER_VARIANTS}>{PLACEHOLDER_ROWS.map((i) => (- <div+ <motion.divkey={i}className="flex items-center justify-between py-4 pl-3 pr-5"+ variants={reduceMotion ? undefined : SKELETON_ITEM_VARIANTS}><div className="flex items-center gap-3"><Skeleton className="h-5 w-5" />@@ -24,8 +49,8 @@ export function APIKeyListSkeleton() {</div></div><Skeleton className="h-5 w-5" />- </div>+ </motion.div>))}- </div>+ </motion.div>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/IntegrationsList/IntegrationsList.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/IntegrationsList/IntegrationsList.tsxindex c8237c36ed..8bba1d4702 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/IntegrationsList/IntegrationsList.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/IntegrationsList/IntegrationsList.tsx@@ -2,6 +2,7 @@import { useState } from "react";import { AnimatePresence, motion, useReducedMotion } from "framer-motion";+import type { Variants } from "framer-motion";import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";@@ -13,6 +14,27 @@ import { ProviderGroup } from "../ProviderGroup/ProviderGroup";import { IntegrationsListSkeleton } from "./IntegrationsListSkeleton";import { useIntegrationsList } from "./useIntegrationsList";+const LIST_CONTAINER_VARIANTS: Variants = {+ hidden: {},+ show: {+ transition: { staggerChildren: 0.08, delayChildren: 0.05 },+ },+};++const LIST_ITEM_VARIANTS: Variants = {+ hidden: { opacity: 0, y: 16 },+ show: {+ opacity: 1,+ y: 0,+ transition: { duration: 0.3, ease: [0.16, 1, 0.3, 1] },+ },+};++const REDUCED_MOTION_ITEM_VARIANTS: Variants = {+ hidden: { opacity: 0 },+ show: { opacity: 1 },+};+export function IntegrationsList() {const {query,@@ -128,18 +150,29 @@ export function IntegrationsList() {{isEmpty ? (<IntegrationsListEmpty query={query} />) : (- <div className="flex flex-col gap-3 pb-4">+ <motion.div+ className="flex flex-col gap-3 pb-4"+ initial={reduceMotion ? false : "hidden"}+ animate={reduceMotion ? undefined : "show"}+ variants={reduceMotion ? undefined : LIST_CONTAINER_VARIANTS}+ >{providers.map((provider) => (- <ProviderGroup+ <motion.divkey={provider.id}- provider={provider}- isSelected={selection.isSelected}- onToggleSelected={selection.toggle}- onDelete={(id) => askDelete([id])}- isDeletingId={isDeletingId}- />+ variants={+ reduceMotion ? REDUCED_MOTION_ITEM_VARIANTS : LIST_ITEM_VARIANTS+ }+ >+ <ProviderGroup+ provider={provider}+ isSelected={selection.isSelected}+ onToggleSelected={selection.toggle}+ onDelete={(id) => askDelete([id])}+ isDeletingId={isDeletingId}+ />+ </motion.div>))}- </div>+ </motion.div>)}<DeleteConfirmDialogdiff --git a/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/IntegrationsList/IntegrationsListSkeleton.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/IntegrationsList/IntegrationsListSkeleton.tsxindex 8383fcf11a..0042396ba0 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/IntegrationsList/IntegrationsListSkeleton.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/integrations/components/IntegrationsList/IntegrationsListSkeleton.tsx@@ -1,17 +1,51 @@+"use client";++import { motion, useReducedMotion } from "framer-motion";+import type { Variants } from "framer-motion";+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";+const SKELETON_CONTAINER_VARIANTS: Variants = {+ hidden: {},+ show: {+ transition: { staggerChildren: 0.08, delayChildren: 0.05 },+ },+};++const SKELETON_ITEM_VARIANTS: Variants = {+ hidden: { opacity: 0, y: 16 },+ show: {+ opacity: 1,+ y: 0,+ transition: { duration: 0.3, ease: [0.16, 1, 0.3, 1] },+ },+};++const REDUCED_MOTION_ITEM_VARIANTS: Variants = {+ hidden: { opacity: 0 },+ show: { opacity: 1 },+};+export function IntegrationsListSkeleton() {+ const reduceMotion = useReducedMotion();+return (- <div+ <motion.divclassName="flex flex-col gap-3"aria-busy="true"aria-label="Loading integrations"+ initial={reduceMotion ? false : "hidden"}+ animate={reduceMotion ? undefined : "show"}+ variants={reduceMotion ? undefined : SKELETON_CONTAINER_VARIANTS}>{[0, 1, 2].map((i) => (- <div+ <motion.divkey={i}data-testid="integration-skeleton-item"className="w-full overflow-hidden rounded-lg border border-[#DADADC] bg-white"+ variants={+ reduceMotion ? REDUCED_MOTION_ITEM_VARIANTS : SKELETON_ITEM_VARIANTS+ }>{/* Mirrors ProviderGroup accordion trigger row */}<div className="flex items-center justify-between px-3 py-3 pr-5">@@ -36,8 +70,8 @@ export function IntegrationsListSkeleton() {</div><Skeleton className="size-5 rounded" /></div>- </div>+ </motion.div>))}- </div>+ </motion.div>);}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.tsxindex 69464c8354..c6ed047335 100644--- 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.tsx@@ -264,6 +264,67 @@ describe("SettingsPreferencesPage", () => {});});+ test("Save is enabled on first paint when server timezone is not-set, and saves the detected browser tz", async () => {+ const STUBBED_BROWSER_TZ = "America/New_York";+ const resolvedOptionsSpy = vi+ .spyOn(Intl.DateTimeFormat.prototype, "resolvedOptions")+ .mockReturnValue({+ timeZone: STUBBED_BROWSER_TZ,+ } as Intl.ResolvedDateTimeFormatOptions);++ 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: "not-set" }),+ 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 };+ }),+ );++ try {+ render(<SettingsPreferencesPage />);++ const saveButton = await screen.findByRole("button", {+ name: "Save changes",+ });++ await waitFor(() => {+ expect((saveButton as HTMLButtonElement).disabled).toBe(false);+ });++ fireEvent.click(saveButton);++ await waitFor(() => {+ expect(submittedTimezone).toBe(STUBBED_BROWSER_TZ);+ });++ await waitFor(() => {+ expect((saveButton as HTMLButtonElement).disabled).toBe(true);+ });+ } finally {+ resolvedOptionsSpy.mockRestore();+ }+ });+test("submitting a new email closes the dialog and calls the update endpoint", async () => {const fetchMock = vi.fn(async () =>Promise.resolve(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.tsxindex 6f845a9c14..fbaf8bca8a 100644--- 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.tsx@@ -1,7 +1,7 @@"use client";-import { ClockIcon, GlobeIcon, InfoIcon } from "@phosphor-icons/react";-import { AnimatePresence, motion, useReducedMotion } from "framer-motion";+import { ClockIcon, InfoIcon } from "@phosphor-icons/react";+import { motion, useReducedMotion } from "framer-motion";import { Select } from "@/components/atoms/Select/Select";import { Text } from "@/components/atoms/Text/Text";@@ -14,30 +14,19 @@ import {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) {+export function TimezoneCard({ value, 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@@ -106,31 +95,6 @@ export function TimezoneCard({) : 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/page.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/page.tsxindex b728a1b722..2002c24055 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/preferences/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/page.tsx@@ -24,7 +24,6 @@ export default function SettingsPreferencesPage() {error,refetch,formState,- savedState,dirty,isSaving,setTimezone,@@ -59,7 +58,6 @@ export default function SettingsPreferencesPage() {<TimezoneCardvalue={formState.timezone}- initialValue={savedState.timezone}onChange={setTimezone}index={1}/>diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/preferences/usePreferencesPage.ts b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/usePreferencesPage.tsindex c532feb413..c27c1d4419 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/preferences/usePreferencesPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/settings/preferences/usePreferencesPage.ts@@ -64,15 +64,18 @@ export function usePreferencesPage() {timezoneQuery.isLoading ||!preferencesQuery.data;- const initialTimezone =- timezoneQuery.data && timezoneQuery.data !== "not-set"- ? timezoneQuery.data- : detectBrowserTimezone();+ const serverTimezone = timezoneQuery.data ?? "not-set";+ const formTimezone =+ serverTimezone !== "not-set" ? serverTimezone : detectBrowserTimezone();const initialFlags = preferencesQuery.data? preferencesToFlags(preferencesQuery.data): EMPTY_FLAGS;- const initialState: PreferencesFormState = {- timezone: initialTimezone,+ const initialFormState: PreferencesFormState = {+ timezone: formTimezone,+ notifications: initialFlags,+ };+ const initialSavedState: PreferencesFormState = {+ timezone: serverTimezone,notifications: initialFlags,};@@ -92,11 +95,16 @@ export function usePreferencesPage() {if (hasInitializedFormState.current) return;if (!preferencesQuery.isSuccess) return;if (!timezoneQuery.isSuccess) return;- setFormState(initialState);- setSavedState(initialState);+ setFormState(initialFormState);+ setSavedState(initialSavedState);hasInitializedFormState.current = true;},- [initialState, preferencesQuery.isSuccess, timezoneQuery.isSuccess],+ [+ initialFormState,+ initialSavedState,+ preferencesQuery.isSuccess,+ timezoneQuery.isSuccess,+ ],);const dirty = isFormDirty(savedState, formState);@@ -142,28 +150,17 @@ export function usePreferencesPage() {if (partsAtSubmit.timezone) {try {- await updateTimezone.mutateAsync({+ const result = 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 }));+ await queryClient.invalidateQueries({+ queryKey: getGetV1GetUserTimezoneQueryKey(),+ });+ const persistedTimezone =+ (result.status === 200 && result.data?.timezone) || snapshot.timezone;+ setSavedState((prev) => ({ ...prev, timezone: persistedTimezone }));timezoneSaved = true;} catch (err) {failures.push(diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/profile/components/ProfileForm/ProfileForm.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/profile/components/ProfileForm/ProfileForm.tsxindex cf0cf92f28..e629a330ad 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/profile/components/ProfileForm/ProfileForm.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/profile/components/ProfileForm/ProfileForm.tsx@@ -255,7 +255,7 @@ export function ProfileForm({ formState, errors, onChange }: Props) {value={formState.description}error={errors.description}onChange={(e) => onChange("description", e.target.value)}- className="!rounded-3xl"+ className="!rounded-3xl !rounded-tr-md scrollbar-thin scrollbar-track-transparent scrollbar-thumb-zinc-200 hover:scrollbar-thumb-zinc-300"/>)}</motion.div>