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): add generated expert avatars across team and chat surfaces (#14460)
Abhimanyu Yadavcf7dd2020ecc
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db.py b/autogpt_platform/backend/backend/api/features/experts/experts_db.pyindex e7918851c5..f0baf70f96 100644--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py@@ -305,7 +305,7 @@ async def list_expert_identities(user_id: str) -> list[ExpertIdentity]:"""return await query_raw_with_schema("""- SELECT "id", "name", "avatarUrl" AS "avatar_url", "role",+ SELECT "id", "name", "avatarUrl" AS "avatar_url", "color", "role","isArchived" AS "is_archived"FROM {schema_prefix}"Expert"WHERE "ownerUserId" = $1 AND "isTemplate" = falsediff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.pyindex acb3504d1b..bd3ba90117 100644--- a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py@@ -1094,6 +1094,7 @@ async def test_list_expert_identities_is_lightweight_and_includes_archived(identity_ids = {item.id for item in identities}identity = next(item for item in identities if item.id == hired.expert.id)assert identity.name == hired.expert.name+ assert identity.color == hired.expert.colorassert identity.is_archived is Trueactive_identity = next(item for item in identities if item.id == active_hired.expert.id@@ -1199,7 +1200,7 @@ def test_expert_identity_projection_columns_exist_in_schema():model = re.search(r"^model Expert \{(.*?)^\}", schema, re.S | re.M)assert model is not None, "Expert model not found in schema.prisma"fields = set(re.findall(r"^\s{2}(\w+)", model.group(1), re.M))- assert {"id", "name", "avatarUrl", "role", "isArchived"} <= fields+ assert {"id", "name", "avatarUrl", "color", "role", "isArchived"} <= fieldsassert {"ownerUserId", "isTemplate"} <= fieldsdiff --git a/autogpt_platform/backend/backend/api/features/experts/models.py b/autogpt_platform/backend/backend/api/features/experts/models.pyindex 184b20f092..a314a2f28b 100644--- a/autogpt_platform/backend/backend/api/features/experts/models.py+++ b/autogpt_platform/backend/backend/api/features/experts/models.py@@ -123,6 +123,7 @@ class ExpertIdentity(BaseModel):id: strname: stravatar_url: str | None+ color: str | None = Nonerole: stris_archived: booldiff --git a/autogpt_platform/backend/backend/api/features/experts/routes_test.py b/autogpt_platform/backend/backend/api/features/experts/routes_test.pyindex c953a18923..d5c076f3d8 100644--- a/autogpt_platform/backend/backend/api/features/experts/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/experts/routes_test.py@@ -718,6 +718,7 @@ def test_list_expert_identities_returns_lifetime_roster_projection(id="expert-1",name="Maria",avatar_url=None,+ color="orange-500",role="Marketing Specialist",is_archived=True,)@@ -736,6 +737,7 @@ def test_list_expert_identities_returns_lifetime_roster_projection("id": "expert-1","name": "Maria","avatar_url": None,+ "color": "orange-500","role": "Marketing Specialist","is_archived": True,}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/recipient-colors.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/recipient-colors.test.tsxnew file mode 100644index 0000000000..53e6808a1e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/recipient-colors.test.tsx@@ -0,0 +1,83 @@+import {+ render,+ screen,+ waitFor,+ within,+} from "@/tests/integrations/test-utils";+import { server } from "@/mocks/mock-server";+import { http, HttpResponse } from "msw";+import { withNuqsTestingAdapter } from "nuqs/adapters/testing";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import { RecipientChip } from "../components/ChatInput/components/RecipientChip";+import { useRecipientPicker } from "../components/EmptySession/useRecipientPicker";++vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@/services/feature-flags/use-get-flag")+ >()),+ useGetFlag: () => true,+}));+vi.mock("@/components/molecules/BotAvatar/BotAvatar", () => ({+ BotAvatar: ({+ config,+ title,+ }: {+ config: { color: string };+ title: string;+ }) => <span role="img" aria-label={title} data-color={config.color} />,+}));++function Picker() {+ const { recipient, options, selectRecipient } = useRecipientPicker();+ return (+ <RecipientChip+ recipient={recipient}+ options={options}+ onSelect={selectRecipient}+ />+ );+}++describe("recipient colors", () => {+ it("keeps roster colors in the selected avatar and menu", async () => {+ server.use(+ http.get("*/api/experts/identities", () =>+ HttpResponse.json([+ {+ id: "expert-maria",+ name: "Maria",+ color: "orange-500",+ avatar_url: null,+ role: "Marketing",+ is_archived: false,+ },+ ]),+ ),+ );+ const Wrapper = withNuqsTestingAdapter({+ searchParams: "?expertId=expert-maria",+ hasMemory: true,+ });+ render(+ <Wrapper>+ <Picker />+ </Wrapper>,+ );+ const chip = await screen.findByRole("button", {+ name: /Sending to Maria/,+ });+ await waitFor(() =>+ expect(within(chip).getByRole("img").getAttribute("data-color")).toBe(+ "coral",+ ),+ );+ await userEvent.click(chip);+ const menu = await screen.findByRole("menu");+ expect(+ within(menu)+ .getByRole("img", { name: "Maria" })+ .getAttribute("data-color"),+ ).toBe("coral");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ExpertArtifactContent.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ExpertArtifactContent.tsxindex b33fefbf7d..160fcf6fe8 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ExpertArtifactContent.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/ExpertArtifactContent.tsx@@ -75,6 +75,7 @@ export function ExpertArtifactContent({ expert: artifact }: Props) {<ExpertAvatarname={expert.name}avatarUrl={expert.avatarUrl}+ color={expert.color}size={48}/><div className="min-w-0">diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/RecipientChip.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/RecipientChip.tsxindex cd7bc012f0..dce8851ffe 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/RecipientChip.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/RecipientChip.tsx@@ -1,10 +1,5 @@"use client";-import {- Avatar,- AvatarFallback,- AvatarImage,-} from "@/components/atoms/Avatar/Avatar";import {DropdownMenu,DropdownMenuContent,@@ -15,11 +10,13 @@ import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";import { cn } from "@/lib/utils";import { ArrowDown01Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";+import { ExpertAvatar } from "../../ChatMessagesContainer/components/ExpertAvatar/ExpertAvatar";export interface RecipientOption {id: string | null;name: string;avatarUrl: string | null;+ color?: string | null;}interface Props {@@ -89,15 +86,16 @@ export function RecipientChip({);}+// The same face the expert wears in the thread: Autopilot's own avatar for+// the null recipient, the generated one for experts without an upload.function RecipientAvatar({ option }: { option: RecipientOption }) {return (- <Avatar className="h-6 w-6">- {option.avatarUrl ? (- <AvatarImage src={option.avatarUrl} alt={option.name} />- ) : null}- <AvatarFallback className="text-[10px]">- {option.name.slice(0, 2)}- </AvatarFallback>- </Avatar>+ <ExpertAvatar+ name={option.name}+ avatarUrl={option.avatarUrl}+ color={option.color}+ isAutopilot={option.id === null}+ size="sm"+ />);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ExpertAvatar/ExpertAvatar.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ExpertAvatar/ExpertAvatar.tsxindex 788dd3fc9a..afd38ba23a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ExpertAvatar/ExpertAvatar.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ExpertAvatar/ExpertAvatar.tsx@@ -3,12 +3,18 @@ import {AvatarFallback,AvatarImage,} from "@/components/atoms/Avatar/Avatar";-import { AutopilotAvatar } from "@/components/molecules/AutopilotAvatar/AutopilotAvatar";+import { BotAvatar } from "@/components/molecules/BotAvatar/BotAvatar";+import {+ AUTOPILOT_AVATAR,+ expertAvatarConfig,+ isUploadedAvatar,+} from "@/components/molecules/BotAvatar/helpers";import { cn } from "@/lib/utils";interface Props {name: string;avatarUrl: string | null;+ color?: string | null;isAutopilot?: boolean;/** Identity still loading: a muted grey circle, no stand-in identity. */isLoading?: boolean;@@ -18,6 +24,7 @@ interface Props {export function ExpertAvatar({name,avatarUrl,+ color,isAutopilot,isLoading,size,@@ -36,18 +43,31 @@ export function ExpertAvatar({if (isAutopilot && !avatarUrl) {return (- <AutopilotAvatar+ <BotAvatar+ config={AUTOPILOT_AVATAR}+ size={isSmall ? 24 : 36}+ animated={!isSmall}+ showBadge={false}+ title={name}+ />+ );+ }++ if (!isUploadedAvatar(avatarUrl)) {+ return (+ <BotAvatar+ config={expertAvatarConfig({ name, avatarUrl, color })}size={isSmall ? 24 : 36}- className={isSmall ? undefined : "rounded-xl"}+ animated={!isSmall}+ showBadge={false}+ title={name}/>);}return (<Avatar className={sizeClass}>- {avatarUrl ? <AvatarImage src={avatarUrl} alt={name} /> : null}- {/* The fallback seeds a generated avatar off the name, and also covers- an avatar URL that fails to load. */}+ <AvatarImage src={avatarUrl ?? undefined} alt={name} /><AvatarFallback className={sizeClass}>{name}</AvatarFallback></Avatar>);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ThreadHeader.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ThreadHeader.tsxindex b37aeb58ca..ee2958d52b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ThreadHeader.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ThreadHeader.tsx@@ -98,6 +98,7 @@ export function ThreadHeader({<ExpertAvatarname={name}avatarUrl={expertIdentity?.avatarUrl ?? null}+ color={expertIdentity?.color}isAutopilot={!expertIdentity && !isResolving}isLoading={isResolving}size="sm"diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/useRecipientPicker.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/useRecipientPicker.tsindex a38d2449ea..94dd82b73c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/useRecipientPicker.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/useRecipientPicker.ts@@ -43,6 +43,7 @@ export function useRecipientPicker() {id: expert.id,name: expert.name,avatarUrl: expert.avatarUrl,+ color: expert.color,})),];diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsxindex c0f12298f6..e26ad3344f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx@@ -222,6 +222,7 @@ export function ExpertChangeCard({<ExpertAvatarname={name}avatarUrl={str(expert, "avatar_url")}+ color={str(expert, "color")}size={32}/><div className="min-w-0 flex-1">diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/SubSessionLive.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/SubSessionLive.tsxindex 31bb4594ad..841e411ae3 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/SubSessionLive.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/SubSessionLive.tsx@@ -286,6 +286,7 @@ export function SubSessionPendingCard({<ExpertAvatarname={expert?.name ?? "Sub-AutoPilot"}avatarUrl={expert?.avatarUrl ?? null}+ color={expert?.color}size={28}/><p className="min-w-0 flex-1 truncate text-sm font-medium text-zinc-800">diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useExpertMap.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useExpertMap.tsindex 16280b5e7d..29bf5a7147 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useExpertMap.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useExpertMap.ts@@ -13,6 +13,7 @@ export interface ExpertIdentity {id: string;name: string;avatarUrl: string | null;+ color?: string | null;role: string | null;isArchived: boolean;readOnlyReason: ExpertReadOnlyReason | null;@@ -94,6 +95,7 @@ export function useExpertMap() {id: expert.id,name: expert.name,avatarUrl: expert.avatar_url ?? null,+ color: expert.color ?? null,role: expert.role,isArchived: expert.is_archived,readOnlyReason: expert.is_archived ? ("fired" as const) : null,diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertAvatarButton/ExpertAvatarButton.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertAvatarButton/ExpertAvatarButton.tsxindex 693b4141a0..732d37d1e5 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertAvatarButton/ExpertAvatarButton.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertAvatarButton/ExpertAvatarButton.tsx@@ -7,6 +7,11 @@ import {AvatarImage,} from "@/components/atoms/Avatar/Avatar";import { Icon } from "@/components/atoms/Icon/Icon";+import { BotAvatar } from "@/components/molecules/BotAvatar/BotAvatar";+import {+ expertAvatarConfig,+ isUploadedAvatar,+} from "@/components/molecules/BotAvatar/helpers";import { Camera01Icon, Loading03Icon } from "@hugeicons/core-free-icons";import { ChangeEvent, useRef } from "react";import { useExpertAvatarButton } from "./useExpertAvatarButton";@@ -39,17 +44,31 @@ export function ExpertAvatarButton({ expert }: Props) {aria-label={`Change ${expert.name}'s photo`}className="group relative size-24 shrink-0 cursor-pointer rounded-full outline-none transition-transform duration-150 ease-out focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 active:scale-[0.97] disabled:cursor-wait">- <Avatar className="size-24 bg-background ring-4 ring-background">- {expert.avatar_url ? (+ {isUploadedAvatar(expert.avatar_url) ? (+ <Avatar className="size-24 bg-background ring-4 ring-background"><AvatarImage- src={expert.avatar_url}+ src={expert.avatar_url ?? undefined}alt={expert.name}width={192}height={192}/>- ) : null}- <AvatarFallback>{expert.name}</AvatarFallback>- </Avatar>+ <AvatarFallback>{expert.name}</AvatarFallback>+ </Avatar>+ ) : (+ <span className="flex size-24 items-center justify-center rounded-full bg-background ring-4 ring-background">+ <BotAvatar+ config={expertAvatarConfig({+ name: expert.name,+ avatarUrl: expert.avatar_url,+ color: expert.color,+ })}+ size={84}+ trackPointer+ showBadge={false}+ title={expert.name}+ />+ </span>+ )}<spanaria-hiddendiff --git a/autogpt_platform/frontend/src/app/(platform)/team/autopilot/components/AutopilotHeader.tsx b/autogpt_platform/frontend/src/app/(platform)/team/autopilot/components/AutopilotHeader.tsxindex 61dcd2761f..0e235f1409 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/autopilot/components/AutopilotHeader.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/team/autopilot/components/AutopilotHeader.tsx@@ -1,4 +1,5 @@-import { AutoGPTLogo } from "@/components/atoms/AutoGPTLogo/AutoGPTLogo";+import { BotAvatar } from "@/components/molecules/BotAvatar/BotAvatar";+import { AUTOPILOT_AVATAR } from "@/components/molecules/BotAvatar/helpers";import { Button } from "@/components/atoms/Button/Button";import { Icon } from "@/components/atoms/Icon/Icon";import { Text } from "@/components/atoms/Text/Text";@@ -14,7 +15,12 @@ export function AutopilotHeader() {<div className="flex flex-col gap-4 sm:flex-row sm:items-center"><span className="relative z-10 -mt-12 ml-14 flex size-24 shrink-0 items-center justify-center rounded-full bg-white ring-4 ring-white">- <AutoGPTLogo hideText viewBox="47 -1 42 42" className="size-12" />+ <BotAvatar+ config={AUTOPILOT_AVATAR}+ size={80}+ title="Autopilot"+ showBadge={false}+ /></span><div className="min-w-0 flex-1"><div className="flex flex-wrap items-center gap-3">diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/AutopilotCard.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/AutopilotCard.tsxindex 32861e7201..344cc9262a 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/components/AutopilotCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/AutopilotCard.tsx@@ -1,4 +1,5 @@-import { AutoGPTLogo } from "@/components/atoms/AutoGPTLogo/AutoGPTLogo";+import { BotAvatar } from "@/components/molecules/BotAvatar/BotAvatar";+import { AUTOPILOT_AVATAR } from "@/components/molecules/BotAvatar/helpers";import { Button } from "@/components/atoms/Button/Button";import { Icon } from "@/components/atoms/Icon/Icon";import { Text } from "@/components/atoms/Text/Text";@@ -44,8 +45,14 @@ export function AutopilotCard({<ExpertCover color={undefined} status="built-in" /><div className="flex w-full items-start gap-3 px-2">- <span className="relative z-10 -mt-11 ml-1 flex size-[5.25rem] shrink-0 items-center justify-center rounded-full bg-white ring-4 ring-white">- <AutoGPTLogo hideText viewBox="47 -1 42 42" className="size-11" />+ <span className="relative z-10 -mt-12 ml-1 flex size-[5.5rem] shrink-0 items-center justify-center rounded-full bg-white ring-4 ring-white">+ <BotAvatar+ config={AUTOPILOT_AVATAR}+ size={80}+ trackPointer+ title="Autopilot"+ showBadge={false}+ /></span></div>diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/ExpertChatDrawer.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/ExpertChatDrawer.tsxindex 613232fbae..bc031219ea 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/ExpertChatDrawer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/ExpertChatDrawer.tsx@@ -48,6 +48,7 @@ export function ExpertChatDrawer({? {name: target.name,avatarUrl: target.avatarUrl,+ color: target.color,isAutopilot: target.expertId === null,}: null;diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/helpers.tsindex 9235d6bdcc..d62b6ec14e 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/helpers.ts@@ -6,6 +6,7 @@ export interface ChatTarget {name: string;role: string;avatarUrl: string | null;+ color?: string | null;}export const AUTOPILOT_CHAT_TARGET: ChatTarget = {@@ -21,5 +22,6 @@ export function expertToChatTarget(expert: Expert): ChatTarget {name: expert.name,role: expert.role,avatarUrl: expert.avatar_url,+ color: expert.color,};}diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertSidePanel/IdentityAvatar.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertSidePanel/IdentityAvatar.tsxindex 47f62a8511..5ea5fe4d7b 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertSidePanel/IdentityAvatar.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertSidePanel/IdentityAvatar.tsx@@ -1,14 +1,20 @@-import { AutoGPTLogo } from "@/components/atoms/AutoGPTLogo/AutoGPTLogo";import {Avatar,AvatarFallback,AvatarImage,} from "@/components/atoms/Avatar/Avatar";+import { BotAvatar } from "@/components/molecules/BotAvatar/BotAvatar";+import {+ AUTOPILOT_AVATAR,+ expertAvatarConfig,+ isUploadedAvatar,+} from "@/components/molecules/BotAvatar/helpers";import { cn } from "@/lib/utils";export interface PanelIdentity {name: string;avatarUrl: string | null;+ color?: string | null;isAutopilot?: boolean;}@@ -21,26 +27,34 @@ interface Props {export function IdentityAvatar({ identity, className, imageSize }: Props) {if (identity.isAutopilot) {return (- <span- className={cn(- "flex shrink-0 items-center justify-center rounded-full bg-white ring-1 ring-zinc-200",- className,- )}- >- <AutoGPTLogo hideText viewBox="47 -1 42 42" className="size-[55%]" />- </span>+ <BotAvatar+ config={AUTOPILOT_AVATAR}+ size={imageSize}+ showBadge={false}+ title={identity.name}+ className={className}+ />+ );+ }+ if (!isUploadedAvatar(identity.avatarUrl)) {+ return (+ <BotAvatar+ config={expertAvatarConfig(identity)}+ size={imageSize}+ showBadge={false}+ title={identity.name}+ className={className}+ />);}return (<Avatar className={cn("shrink-0", className)}>- {identity.avatarUrl ? (- <AvatarImage- src={identity.avatarUrl}- alt={identity.name}- width={imageSize}- height={imageSize}- />- ) : null}+ <AvatarImage+ src={identity.avatarUrl ?? undefined}+ alt={identity.name}+ width={imageSize}+ height={imageSize}+ /><AvatarFallback>{identity.name}</AvatarFallback></Avatar>);diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/ExpertTeamCard.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/ExpertTeamCard.tsxindex afe3f87b6e..af48c7985b 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/ExpertTeamCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/ExpertTeamCard.tsx@@ -24,6 +24,12 @@ import Link from "next/link";import { MouseEvent } from "react";import { ExpertCover } from "./components/ExpertCover";+import { BotAvatar } from "@/components/molecules/BotAvatar/BotAvatar";+import {+ expertAvatarConfig,+ isUploadedAvatar,+} from "@/components/molecules/BotAvatar/helpers";+import { SpendMeter } from "./components/SpendMeter";import {getExpertBlurb,@@ -93,21 +99,35 @@ export function ExpertTeamCard({<ExpertCover color={expert.color} status={rosterStatus} /><div className="flex w-full items-start gap-3 px-2">- <span className="-mt-11 ml-1 block shrink-0">- <Avatar className="size-[5.25rem] rounded-full ring-4 ring-white">- {expert.avatar_url ? (+ <span className="relative z-10 -mt-12 ml-1 block shrink-0">+ {isUploadedAvatar(expert.avatar_url) ? (+ <Avatar className="size-[5.5rem] rounded-full ring-4 ring-white"><AvatarImage- src={expert.avatar_url}+ src={expert.avatar_url ?? undefined}alt={expert.name}- width={84}- height={84}+ width={88}+ height={88}className="bg-white"/>- ) : null}- <AvatarFallback className="grain-overlay">- {expert.name}- </AvatarFallback>- </Avatar>+ <AvatarFallback className="grain-overlay">+ {expert.name}+ </AvatarFallback>+ </Avatar>+ ) : (+ <span className="flex size-[5.5rem] items-center justify-center rounded-full bg-white ring-4 ring-white">+ <BotAvatar+ config={expertAvatarConfig({+ name: expert.name,+ avatarUrl: expert.avatar_url,+ color: expert.color,+ })}+ status="idle"+ trackPointer+ size={80}+ title={expert.name}+ />+ </span>+ )}</span><div className="mt-2 flex min-w-0 flex-1 flex-col gap-1">diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/SoulDrawer/SoulDrawer.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/SoulDrawer/SoulDrawer.tsxindex a06883193e..4bf0b419ae 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/components/SoulDrawer/SoulDrawer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/SoulDrawer/SoulDrawer.tsx@@ -22,7 +22,13 @@ export function SoulDrawer({ expert, onClose }: Props) {return (<ExpertSidePanelidentity={- expert ? { name: expert.name, avatarUrl: expert.avatar_url } : null+ expert+ ? {+ name: expert.name,+ avatarUrl: expert.avatar_url,+ color: expert.color,+ }+ : null}title={expert ? `${expert.name}'s Soul` : ""}panelId="soul"diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex f6086b19f1..8913623154 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -20729,6 +20729,10 @@"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Avatar Url"},+ "color": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Color"+ },"role": { "type": "string", "title": "Role" },"is_archived": { "type": "boolean", "title": "Is Archived" }},diff --git a/autogpt_platform/frontend/src/app/avatars/[file]/__tests__/route.test.ts b/autogpt_platform/frontend/src/app/avatars/[file]/__tests__/route.test.tsnew file mode 100644index 0000000000..42965bdd47--- /dev/null+++ b/autogpt_platform/frontend/src/app/avatars/[file]/__tests__/route.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";+import { GET } from "../route";++describe("GET /avatars/[file]", () => {+ it("renders a generated avatar as SVG", async () => {+ const response = await GET(new Request("http://localhost/avatars/x"), {+ params: Promise.resolve({ file: "round.sky.none.svg" }),+ });++ expect(response.status).toBe(200);+ expect(response.headers.get("Content-Type")).toContain("image/svg+xml");+ const body = await response.text();+ expect(body.startsWith("<svg xmlns=")).toBe(true);+ });++ it("404s on a file that is not an avatar spec", async () => {+ const response = await GET(new Request("http://localhost/avatars/x"), {+ params: Promise.resolve({ file: "nope.svg" }),+ });++ expect(response.status).toBe(404);+ });+});diff --git a/autogpt_platform/frontend/src/app/avatars/[file]/route.ts b/autogpt_platform/frontend/src/app/avatars/[file]/route.tsnew file mode 100644index 0000000000..4309b51739--- /dev/null+++ b/autogpt_platform/frontend/src/app/avatars/[file]/route.ts@@ -0,0 +1,43 @@+import { BotAvatarSvg } from "@/components/molecules/BotAvatar/BotAvatarSvg";+import { parseAvatarUrl } from "@/components/molecules/BotAvatar/helpers";+import { FRONT_POSE } from "@/components/molecules/BotAvatar/projection";+import { STATIC_ELS } from "@/components/molecules/BotAvatar/svgElements";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server.browser";++export const dynamic = "force-static";++const SVG_XMLNS = 'xmlns="http://www.w3.org/2000/svg"';++// Route handlers run in the server layer, where hooks and framer-motion's+// client components are unavailable — so this renders the avatar at rest+// through the plain-element path rather than BotAvatar itself.+export async function GET(+ _request: Request,+ { params }: { params: Promise<{ file: string }> },+) {+ const { file } = await params;+ const config = parseAvatarUrl(`/avatars/${file}`);+ if (!config) return new Response("Not found", { status: 404 });++ const markup = renderToStaticMarkup(+ createElement(BotAvatarSvg, {+ config,+ status: "idle",+ expression: "neutral",+ pose: FRONT_POSE,+ isLive: false,+ isBlinking: false,+ els: STATIC_ELS,+ idPrefix: "avatar",+ size: 512,+ }),+ ).replace("<svg ", `<svg ${SVG_XMLNS} `);++ return new Response(markup, {+ headers: {+ "Content-Type": "image/svg+xml; charset=utf-8",+ "Cache-Control": "public, max-age=31536000, immutable",+ },+ });+}diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/RecentChats.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/RecentChats.tsxindex b86bf82075..509b5c1734 100644--- a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/RecentChats.tsx+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/RecentChats.tsx@@ -116,7 +116,9 @@ export function RecentChats() {group.expertId ? (expert?.name ?? "Expert") : "Autopilot"}avatarUrl={expert?.avatarUrl ?? null}+ color={expert?.color ?? null}newChatHref={getNewChatHref(group.expertId, activeExpertIds)}+ isAutopilot={!group.expertId}sessions={group.sessions}renderItem={renderItem}/>diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/expert-groups.test.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/expert-groups.test.tsxindex e2e5de771c..85af18e3a2 100644--- a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/expert-groups.test.tsx+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/__tests__/expert-groups.test.tsx@@ -191,12 +191,34 @@ describe("RecentChats — expert groups", () => {const expertGroup = await screen.findByRole("button", {name: "Expert chats",});- expect(- expertGroup.querySelector('svg[aria-label="AutoGPT Logo"]'),- ).not.toBe(null);+ expect(expertGroup.querySelector('svg[data-testid="bot-avatar"]')).not.toBe(+ null,+ );expect(await screen.findByText("expert-ghost chat 1")).toBeDefined();});+ it("colours a generated sidebar avatar with the expert's owner token", async () => {+ const novaExpert: Expert = {+ ...mariaExpert,+ id: "expert-nova",+ name: "Nova",+ avatar_url: null,+ color: "violet-300",+ };+ const sessions = makeSessions(2, novaExpert.id);+ server.use(+ getGetV2ListSessionsMockHandler200({ sessions, total: sessions.length }),+ getListExpertIdentitiesMockHandler([novaExpert]),+ );+ renderRecentChats();++ const expertGroup = await screen.findByRole("button", {+ name: "Nova chats",+ });+ const avatar = expertGroup.querySelector('svg[data-testid="bot-avatar"]');+ expect(avatar?.getAttribute("data-avatar")?.split(".")[1]).toBe("lavender");+ });+it("keeps the group-level and list-level Load more buttons distinct", async () => {const sessions = makeSessions(12);server.use(diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/ExpertChatGroup/ExpertChatGroup.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/ExpertChatGroup/ExpertChatGroup.tsxindex eafa148add..c2aadd72f7 100644--- a/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/ExpertChatGroup/ExpertChatGroup.tsx+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/components/RecentChats/components/ExpertChatGroup/ExpertChatGroup.tsx@@ -6,7 +6,6 @@ import {AvatarFallback,AvatarImage,} from "@/components/atoms/Avatar/Avatar";-import { AutoGPTLogo } from "@/components/atoms/AutoGPTLogo/AutoGPTLogo";import { Icon } from "@/components/atoms/Icon/Icon";import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";import {@@ -15,6 +14,12 @@ import {TooltipPortal,TooltipTrigger,} from "@/components/atoms/Tooltip/BaseTooltip";+import { BotAvatar } from "@/components/molecules/BotAvatar/BotAvatar";+import {+ AUTOPILOT_AVATAR,+ expertAvatarConfig,+ isUploadedAvatar,+} from "@/components/molecules/BotAvatar/helpers";import {Collapsible,CollapsibleContent,@@ -40,6 +45,8 @@ interface Props {label: string;avatarUrl: string | null;newChatHref: string | null;+ color?: string | null;+ isAutopilot?: boolean;sessions: SessionSummaryResponse[];renderItem: (session: SessionSummaryResponse) => ReactNode;}@@ -48,6 +55,8 @@ export function ExpertChatGroup({label,avatarUrl,newChatHref,+ color,+ isAutopilot,sessions,renderItem,}: Props) {@@ -71,14 +80,29 @@ export function ExpertChatGroup({aria-label={`${label} chats`}className="flex min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-0.5 text-left text-sm font-medium text-zinc-900">- <Avatar className="h-6 w-6">- {avatarUrl ? (- <AvatarImage src={avatarUrl} alt={label} width={48} height={48} />- ) : null}- <AvatarFallback>- <AutoGPTLogo hideText viewBox="47 -1 42 42" className="size-4" />- </AvatarFallback>- </Avatar>+ {isUploadedAvatar(avatarUrl) ? (+ <Avatar className="h-6 w-6">+ <AvatarImage+ src={avatarUrl ?? undefined}+ alt={label}+ width={48}+ height={48}+ />+ <AvatarFallback>{label}</AvatarFallback>+ </Avatar>+ ) : (+ <BotAvatar+ config={+ isAutopilot+ ? AUTOPILOT_AVATAR+ : expertAvatarConfig({ name: label, avatarUrl, color })+ }+ size={24}+ animated={false}+ showBadge={false}+ title={label}+ />+ )}<span className="truncate">{label}</span>{newChatHref && (<spandiff --git a/autogpt_platform/frontend/src/components/molecules/BotAvatar/BotAvatar.tsx b/autogpt_platform/frontend/src/components/molecules/BotAvatar/BotAvatar.tsxnew file mode 100644index 0000000000..9df313a812--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/BotAvatar/BotAvatar.tsx@@ -0,0 +1,72 @@+"use client";++import { motion } from "framer-motion";+import { useId, useRef } from "react";+import { BotAvatarSvg } from "./BotAvatarSvg";+import type { ExpressionId } from "./expressions";+import type { AvatarConfig, AvatarStatus } from "./helpers";+import type { Pose } from "./projection";+import { useExpression } from "./useExpression";+import { usePose } from "./usePose";++interface Props {+ config: AvatarConfig;+ status?: AvatarStatus;+ expression?: ExpressionId;+ size?: number;+ animated?: boolean;+ trackPointer?: boolean;+ poseOffset?: Partial<Pose>;+ outline?: boolean;+ showBadge?: boolean;+ title?: string;+ className?: string;+}++export function BotAvatar({+ config,+ status = "idle",+ expression: expressionOverride,+ size = 96,+ animated = true,+ trackPointer = false,+ poseOffset,+ outline = false,+ showBadge = true,+ title,+ className,+}: Props) {+ const svgRef = useRef<SVGSVGElement>(null);+ const idPrefix = useId().replace(/:/g, "");+ const { isLive, pose } = usePose({+ status,+ animated,+ trackPointer,+ poseOffset,+ svgRef,+ });+ const { expression, isBlinking } = useExpression({+ status,+ isLive,+ override: expressionOverride,+ });++ return (+ <BotAvatarSvg+ svgRef={svgRef}+ config={config}+ status={status}+ expression={expression}+ pose={pose}+ isLive={isLive}+ isBlinking={isBlinking}+ els={motion}+ idPrefix={idPrefix}+ size={size}+ outline={outline}+ showBadge={showBadge}+ title={title}+ className={className}+ />+ );+}diff --git a/autogpt_platform/frontend/src/components/molecules/BotAvatar/BotAvatarSvg.tsx b/autogpt_platform/frontend/src/components/molecules/BotAvatar/BotAvatarSvg.tsxnew file mode 100644index 0000000000..ffee865c0a--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/BotAvatar/BotAvatarSvg.tsx@@ -0,0 +1,133 @@+import { cn } from "@/lib/utils";+import type { RefObject } from "react";+import { Accessory } from "./components/Accessory";+import { Face } from "./components/Face";+import { StatusBadge } from "./components/StatusBadge";+import type { ExpressionId } from "./expressions";+import {+ encodeConfig,+ findColor,+ findShape,+ INK,+ VIEWBOX,+ type AvatarConfig,+ type AvatarStatus,+} from "./helpers";+import type { Pose } from "./projection";+import type { SvgEls } from "./svgElements";++interface Props {+ config: AvatarConfig;+ status: AvatarStatus;+ expression: ExpressionId;+ pose: Pose;+ isLive: boolean;+ isBlinking: boolean;+ els: SvgEls;+ /** Prefix for the gradient id — unique per instance on a page. */+ idPrefix: string;+ size?: number;+ outline?: boolean;+ showBadge?: boolean;+ title?: string;+ className?: string;+ svgRef?: RefObject<SVGSVGElement>;+}++// The avatar's markup with every moving part passed in: BotAvatar drives+// it from hooks in the browser; the /avatars/[file] route renders it once,+// at rest, with plain elements.+export function BotAvatarSvg({+ config,+ status,+ expression,+ pose,+ isLive,+ isBlinking,+ els,+ idPrefix,+ size = 96,+ outline = false,+ showBadge = true,+ title,+ className,+ svgRef,+}: Props) {+ const gradientId = `${idPrefix}-body-${config.color}`;+ const shape = findShape(config.shape);+ const color = findColor(config.color);+ const { cx, bottom } = shape.anchors;+ const rollDeg = (pose.roll * 180) / Math.PI;+ const bodyFill = outline ? color.body : `url(#${gradientId})`;++ return (+ <svg+ ref={svgRef}+ viewBox={`0 0 ${VIEWBOX} ${VIEWBOX}`}+ width={size}+ height={size}+ role="img"+ aria-label={+ title ?? `${color.label} ${shape.label.toLowerCase()} avatar, ${status}`+ }+ data-testid="bot-avatar"+ data-avatar={encodeConfig(config)}+ data-status={status}+ data-expression={expression}+ data-outline={outline}+ className={cn("shrink-0 overflow-visible", className)}+ >+ <defs>+ <radialGradient id={gradientId} cx="50%" cy="45%" r="62%">+ <stop offset="0%" stopColor={color.body} />+ <stop offset="100%" stopColor={color.light} />+ </radialGradient>+ </defs>+ <g+ transform={`translate(0 ${-pose.bob}) rotate(${rollDeg} ${cx} ${bottom})`}+ >+ <Accessory+ accessory={config.accessory}+ anchors={shape.anchors}+ pose={pose}+ deep={color.deep}+ outline={outline}+ layer="back"+ />+ <path+ d={shape.path}+ fill={bodyFill}+ stroke={outline ? INK : "none"}+ strokeWidth={3}+ strokeLinejoin="round"+ />+ <Face+ anchors={shape.anchors}+ pose={pose}+ status={status}+ expression={expression}+ blush={color.mid}+ isLive={isLive}+ isBlinking={isBlinking}+ els={els}+ />+ <Accessory+ accessory={config.accessory}+ anchors={shape.anchors}+ pose={pose}+ deep={color.deep}+ outline={outline}+ layer="front"+ />+ </g>+ {showBadge ? (+ <StatusBadge+ status={status}+ anchors={shape.anchors}+ isLive={isLive}+ els={els}+ />+ ) : null}+ </svg>+ );+}diff --git a/autogpt_platform/frontend/src/components/molecules/BotAvatar/__tests__/Accessory.test.tsx b/autogpt_platform/frontend/src/components/molecules/BotAvatar/__tests__/Accessory.test.tsxnew file mode 100644index 0000000000..982cd22292--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/BotAvatar/__tests__/Accessory.test.tsx@@ -0,0 +1,35 @@+import { render } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import { Accessory } from "../components/Accessory";+import { SHAPES, type AccessoryId } from "../helpers";+import { FRONT_POSE } from "../projection";++describe("avatar accessories", () => {+ it.each(["glasses", "headband", "ears"] as AccessoryId[])(+ "keeps %s geometry mounted while the pose changes",+ (accessory) => {+ const props = {+ accessory,+ anchors: SHAPES[0].anchors,+ deep: "#123456",+ outline: true,+ layer: "front" as const,+ };+ const { container, rerender } = render(+ <svg>+ <Accessory {...props} pose={FRONT_POSE} />+ </svg>,+ );+ const nodes = Array.from(container.querySelectorAll("path,circle"));+ expect(nodes.length).toBeGreaterThan(0);+ rerender(+ <svg>+ <Accessory {...props} pose={{ ...FRONT_POSE, yaw: 0.01 }} />+ </svg>,+ );+ const updated = Array.from(container.querySelectorAll("path,circle"));+ expect(updated).toHaveLength(nodes.length);+ for (let i = 0; i < nodes.length; i++) expect(updated[i]).toBe(nodes[i]);+ },+ );+});diff --git a/autogpt_platform/frontend/src/components/molecules/BotAvatar/__tests__/Face.test.tsx b/autogpt_platform/frontend/src/components/molecules/BotAvatar/__tests__/Face.test.tsxnew file mode 100644index 0000000000..24d38c2ce3--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/BotAvatar/__tests__/Face.test.tsx@@ -0,0 +1,35 @@+import { render } from "@testing-library/react";+import { motion } from "framer-motion";+import { describe, expect, it } from "vitest";+import { Face } from "../components/Face";+import { EXPRESSIONS, type ExpressionId } from "../expressions";+import { SHAPES } from "../helpers";+import { FRONT_POSE } from "../projection";++function Expression({ expression }: { expression: ExpressionId }) {+ return (+ <svg>+ <Face+ anchors={SHAPES[0].anchors}+ pose={FRONT_POSE}+ status="idle"+ expression={expression}+ blush="#fff"+ isLive={false}+ isBlinking={false}+ els={motion}+ />+ </svg>+ );+}++describe("avatar mouth", () => {+ it("switches between line, curve and arc expressions with valid geometry", () => {+ const { container, rerender } = render(<Expression expression="neutral" />);+ for (const expression of EXPRESSIONS) {+ rerender(<Expression expression={expression.id} />);+ const paths = container.querySelectorAll("path");+ expect(paths[paths.length - 1].getAttribute("d")).toBe(expression.mouth);+ }+ });+});diff --git a/autogpt_platform/frontend/src/components/molecules/BotAvatar/__tests__/svgElements.test.tsx b/autogpt_platform/frontend/src/components/molecules/BotAvatar/__tests__/svgElements.test.tsxnew file mode 100644index 0000000000..ba8816750d--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/BotAvatar/__tests__/svgElements.test.tsx@@ -0,0 +1,38 @@+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vitest";+import { STATIC_ELS } from "../svgElements";++describe("static SVG transforms", () => {+ it("preserves authored placement when applying the animation resting transform", () => {+ const svg = renderToStaticMarkup(+ <svg>+ <STATIC_ELS.g+ transform="translate(20 30)"+ animate={{ x: 4, y: 5, rotate: 12, scaleX: 2, scaleY: 3 }}+ >+ <circle r={1} />+ </STATIC_ELS.g>+ </svg>,+ );+ expect(svg).toContain(+ 'transform="translate(20 30) translate(4 5) rotate(12) scale(2 3)"',+ );+ expect(svg).not.toContain("animate=");+ });+ it("retains authored transforms for an identity resting frame", () => {+ const svg = renderToStaticMarkup(+ <svg>+ <STATIC_ELS.g transform="rotate(45)" animate={{ x: 0, scale: 1 }} />+ </svg>,+ );+ expect(svg).toContain('transform="rotate(45)"');+ });+ it("emits an animation transform without an authored transform", () => {+ const svg = renderToStaticMarkup(+ <svg>+ <STATIC_ELS.g animate={{ scale: 2 }} />+ </svg>,+ );+ expect(svg).toContain('transform="scale(2 2)"');+ });+});diff --git a/autogpt_platform/frontend/src/components/molecules/BotAvatar/__tests__/useExpression.test.ts b/autogpt_platform/frontend/src/components/molecules/BotAvatar/__tests__/useExpression.test.tsnew file mode 100644index 0000000000..f7abfd4995--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/BotAvatar/__tests__/useExpression.test.ts@@ -0,0 +1,47 @@+import { act, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { AvatarStatus } from "../helpers";+import { useExpression } from "../useExpression";++describe("useExpression", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.spyOn(Math, "random").mockReturnValue(0);+ });+ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it.each([+ { status: "idle", isLive: false },+ { status: "sleeping", isLive: true },+ { status: "failed", isLive: true },+ { status: "working", isLive: true },+ ] as { status: AvatarStatus; isLive: boolean }[])(+ "opens the eyes when interrupted by $status / live=$isLive",+ (next) => {+ const { result, rerender, unmount } = renderHook(useExpression, {+ initialProps: { status: "idle" as AvatarStatus, isLive: true },+ });+ act(() => vi.advanceTimersByTime(5000));+ expect(result.current.isBlinking).toBe(true);+ rerender(next);+ expect(result.current.isBlinking).toBe(false);+ unmount();+ expect(vi.getTimerCount()).toBe(0);+ },+ );++ it("finishes and reschedules a live blink", () => {+ const { result } = renderHook(() =>+ useExpression({ status: "idle", isLive: true }),+ );+ act(() => vi.advanceTimersByTime(5000));+ expect(result.current.isBlinking).toBe(true);+ act(() => vi.advanceTimersByTime(130));+ expect(result.current.isBlinking).toBe(false);+ act(() => vi.advanceTimersByTime(5000));+ expect(result.current.isBlinking).toBe(true);+ });+});diff --git a/autogpt_platform/frontend/src/components/molecules/BotAvatar/components/Accessory.tsx b/autogpt_platform/frontend/src/components/molecules/BotAvatar/components/Accessory.tsxnew file mode 100644index 0000000000..a0caddd2f1--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/BotAvatar/components/Accessory.tsx@@ -0,0 +1,492 @@+import { INK, type AccessoryId, type ShapeAnchors } from "../helpers";+import {+ centroidLayer,+ discProjection,+ discTransform,+ fromSurface,+ isInFront,+ polygonPath,+ rotate,+ samplePolyline,+ splitPolyline,+ toScreen,+ type Layer,+ type Vec3,+} from "../parts";+import {+ ellipsoidFor,+ surfacePointAt,+ type Ellipsoid,+ type Pose,+} from "../projection";++interface Props {+ accessory: AccessoryId;+ anchors: ShapeAnchors;+ pose: Pose;+ deep: string;+ outline: boolean;+ layer: Layer;+}++const STAR =+ "M0,-5.5 L1.6,-1.7 L5.6,-1.6 L2.4,0.9 L3.5,4.8 L0,2.5 L-3.5,4.8 L-2.4,0.9 L-5.6,-1.6 L-1.6,-1.7 Z";+const HALF_PI = Math.PI / 2;++function scale([x, y, z]: Vec3, factor: number): Vec3 {+ return [x * factor, y * factor, z * factor];+}++interface ProjectionProps {+ pose: Pose;+ body: Ellipsoid;+ layer: Layer;+}++interface DiscProps extends ProjectionProps {+ center: Vec3;+ normal: Vec3;+ minDepth?: number;+ hideBelow?: number;+ children: React.ReactNode;+}++function Disc({+ pose,+ body,+ layer,+ center,+ normal,+ minDepth = 0.12,+ hideBelow = -1,+ children,+}: DiscProps) {+ const rotated = rotate(center, pose);+ if (rotated[2] < hideBelow) return null;+ if ((isInFront(rotated) ? "front" : "back") !== layer) return null;+ const projected = discProjection(center, normal, pose, body);+ return <g transform={discTransform(projected, minDepth)}>{children}</g>;+}++interface StrandProps extends ProjectionProps {+ deep: string;+ points: Vec3[];+ width: number;+ color?: string;+}++function Strand({+ pose,+ body,+ layer,+ deep,+ points,+ width,+ color = deep,+}: StrandProps) {+ const path = splitPolyline(samplePolyline(points), pose, body)[layer];+ if (!path) return null;+ return (+ <path+ d={path}+ fill="none"+ stroke={color}+ strokeWidth={width}+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ );+}++interface SlabProps extends ProjectionProps {+ points: Vec3[];+ fill?: string;+ deep: string;+ outline: boolean;+}++function Slab({+ points,+ deep,+ fill = deep,+ pose,+ body,+ layer,+ outline,+}: SlabProps) {+ if (centroidLayer(points, pose) !== layer) return null;+ return (+ <path+ d={polygonPath(points, pose, body)}+ fill={fill}+ stroke={outline ? INK : fill}+ strokeWidth={outline ? 2 : 3.5}+ strokeLinejoin="round"+ strokeLinecap="round"+ />+ );+}++export function Accessory({+ accessory,+ anchors,+ pose,+ deep,+ outline,+ layer,+}: Props) {+ const { cx, eyeY, eyeGap, top, bottom } = anchors;+ const body = ellipsoidFor(anchors);+ const projection = { pose, body, layer };+ const edge = outline ? { stroke: INK, strokeWidth: 2 } : {};+ const soft = outline+ ? { stroke: INK, strokeWidth: 2 }+ : { stroke: deep, strokeWidth: 3 };+ const eyeLat = surfacePointAt(cx, eyeY, body).lat;+ const eyeLon = surfacePointAt(cx + eyeGap / 2, eyeY, body).lon;++ switch (accessory) {+ case "glasses": {+ const lenses = [-1, 1].map((side) =>+ fromSurface(side * eyeLon, eyeLat, 1.02),+ );+ const bridgeVisible = lenses.every((lens) =>+ isInFront(rotate(lens, pose)),+ );+ return (+ <g fill="none" stroke={deep} strokeWidth={2.4} strokeLinecap="round">+ {layer === "front" && bridgeVisible ? (+ <Strand+ {...projection}+ deep={deep}+ points={[+ fromSurface(-eyeLon * 0.45, eyeLat, 1.03),+ fromSurface(eyeLon * 0.45, eyeLat, 1.03),+ ]}+ width={2.4}+ />+ ) : null}+ {[-1, 1].map((side) => (+ <Strand+ {...projection}+ deep={deep}+ key={side}+ points={[+ fromSurface(side * (eyeLon + 0.32), eyeLat, 1.03),+ fromSurface(side * HALF_PI, eyeLat + 0.03, 1.02),+ ]}+ width={2.4}+ />+ ))}+ {lenses.map((lens, index) => (+ <Disc+ {...projection}+ key={index}+ center={lens}+ normal={scale(lens, 1)}+ minDepth={0.15}+ >+ <circle r={9.5} />+ </Disc>+ ))}+ </g>+ );+ }+ case "headset": {+ const bandLat = eyeLat + 0.12;+ const band: Vec3[] = Array.from({ length: 25 }, (_, index) => {+ const theta =+ Math.PI - bandLat - ((Math.PI - 2 * bandLat) * index) / 24;+ return [Math.cos(theta) * 1.05, Math.sin(theta) * 1.05, 0.1];+ });+ const pads = [-1, 1].map((side) =>+ fromSurface(side * HALF_PI, bandLat - 0.02, 1.03),+ );+ const mic: Vec3[] = [+ [1.0, Math.sin(bandLat) - 0.15, 0.25],+ [0.85, -0.25, 0.75],+ [0.3, -0.42, 1.05],+ ];+ return (+ <g>+ <Strand {...projection} deep={deep} points={band} width={3.4} />+ <Strand {...projection} deep={deep} points={mic} width={2.4} />+ <Disc {...projection} center={mic[2]} normal={[0, 0, 1]}>+ <circle r={2.6} fill={deep} />+ </Disc>+ {pads.map((pad, index) => (+ <Disc+ {...projection}+ key={index}+ center={pad}+ normal={[index === 0 ? -1 : 1, 0, 0]}+ minDepth={0.45}+ hideBelow={-0.2}+ >+ <ellipse rx={6} ry={9} fill={deep} {...edge} />+ <ellipse rx={3} ry={5.5} fill="#fff" opacity={0.28} />+ </Disc>+ ))}+ </g>+ );+ }+ case "star": {+ const center = fromSurface(0.85, -0.7, 1.01);+ return (+ <Disc {...projection} center={center} normal={center} minDepth={0.5}>+ <circle r={9} fill={deep} {...edge} />+ <path+ d={STAR}+ fill="#fff"+ stroke="#fff"+ strokeWidth={1.6}+ strokeLinejoin="round"+ />+ </Disc>+ );+ }+ case "bow": {+ const center = fromSurface(-0.95, 0.85, 1.02);+ return (+ <Disc {...projection} center={center} normal={center} minDepth={0.5}>+ <g transform="rotate(-18)">+ <path+ d="M0,0 L-11,-6 L-11,6 Z"+ fill={deep}+ {...soft}+ strokeLinejoin="round"+ />+ <path+ d="M0,0 L11,-6 L11,6 Z"+ fill={deep}+ {...soft}+ strokeLinejoin="round"+ />+ <circle r={2.6} fill={deep} {...edge} />+ </g>+ </Disc>+ );+ }+ case "badge": {+ const center = fromSurface(-0.55, -0.5, 1.01);+ return (+ <Disc {...projection} center={center} normal={center} minDepth={0.3}>+ <rect+ x={-9}+ y={-6}+ width={18}+ height={12}+ rx={2.5}+ fill="#fff"+ stroke={deep}+ strokeWidth={2}+ />+ <circle cx={-4} cy={0} r={2} fill={deep} />+ <path+ d="M0,-1.5 L5.5,-1.5 M0,1.5 L4,1.5"+ stroke={deep}+ strokeWidth={1.6}+ strokeLinecap="round"+ />+ </Disc>+ );+ }+ case "crown": {+ const crownLat = surfacePointAt(cx, top + 16, body).lat;+ const base: Vec3[] = Array.from({ length: 25 }, (_, index) =>+ fromSurface(-Math.PI + (2 * Math.PI * index) / 24, crownLat, 1.04),+ );+ const spikes = [-0.9, -0.3, 0.3, 0.9].map((lon) => [+ fromSurface(lon - 0.3, crownLat, 1.04),+ fromSurface(lon, crownLat + 0.42, 1.36),+ fromSurface(lon + 0.3, crownLat, 1.04),+ ]);+ return (+ <g>+ <Strand {...projection} deep={deep} points={base} width={5.5} />+ {spikes.map((spike, index) => (+ <Slab+ {...projection}+ deep={deep}+ outline={outline}+ key={index}+ points={spike}+ />+ ))}+ </g>+ );+ }+ case "propeller": {+ const capLat = surfacePointAt(cx, top + 14, body).lat;+ const capRadius = 1.08;+ const ring: Vec3[] = Array.from({ length: 41 }, (_, index) =>+ fromSurface(-Math.PI + (2 * Math.PI * index) / 40, capLat, capRadius),+ );+ const front = ring+ .map((point) => rotate(point, pose))+ .filter((point) => point[2] >= 0.02)+ .map((point) => toScreen(point, body));+ const crownScreen = toScreen(+ rotate([0, capRadius + 0.02, 0], pose),+ body,+ );+ const spin = ((pose.bob + 10) * 0.9 + pose.yaw * 6) % (Math.PI * 2);+ const blades: Vec3[] = [+ [Math.cos(spin) * 0.4, capRadius + 0.16, Math.sin(spin) * 0.4],+ [0, capRadius + 0.16, 0],+ [-Math.cos(spin) * 0.4, capRadius + 0.16, -Math.sin(spin) * 0.4],+ ];+ const dome =+ front.length > 2 && layer === "front"+ ? `M${front[0].x},${front[0].y} ${front+ .slice(1)+ .map((point) => `L${point.x},${point.y}`)+ .join(+ " ",+ )} A${body.rx * capRadius},${body.ry * capRadius} 0 0 0 ${front[0].x},${front[0].y} Z`+ : null;+ return (+ <g>+ {dome ? (+ <path d={dome} fill={deep} {...edge} strokeLinejoin="round" />+ ) : null}+ <Strand+ {...projection}+ deep={deep}+ points={[+ [0, capRadius, 0],+ [0, capRadius + 0.16, 0],+ ]}+ width={2.4}+ />+ <Strand {...projection} deep={deep} points={blades} width={4} />+ {layer === "front" ? (+ <circle+ cx={crownScreen.x}+ cy={crownScreen.y - body.ry * 0.16}+ r={2.2}+ fill={deep}+ {...edge}+ />+ ) : null}+ </g>+ );+ }+ case "ears": {+ const ear = (side: number): Vec3[] => [+ fromSurface(side * 0.95, 0.55, 1.0),+ fromSurface(side * 0.75, 1.05, 1.42),+ fromSurface(side * 0.45, 0.85, 1.0),+ ];+ const inner = (side: number): Vec3[] => [+ fromSurface(side * 0.88, 0.62, 1.01),+ fromSurface(side * 0.74, 0.96, 1.3),+ fromSurface(side * 0.55, 0.83, 1.01),+ ];+ return (+ <g>+ {[-1, 1].map((side) => (+ <g key={side}>+ <Slab+ {...projection}+ deep={deep}+ outline={outline}+ points={ear(side)}+ />+ <Slab+ {...projection}+ deep={deep}+ outline={outline}+ points={inner(side)}+ fill="#fff"+ />+ </g>+ ))}+ </g>+ );+ }+ case "flower": {+ const center = fromSurface(-0.95, 0.8, 1.03);+ return (+ <Disc {...projection} center={center} normal={center} minDepth={0.5}>+ {[0, 72, 144, 216, 288].map((angle) => (+ <ellipse+ key={angle}+ cx={0}+ cy={-7.5}+ rx={4.6}+ ry={6.6}+ fill="#fff"+ {...edge}+ transform={`rotate(${angle})`}+ />+ ))}+ <circle r={4.2} fill={deep} {...edge} />+ </Disc>+ );+ }+ case "bowtie": {+ const chin = fromSurface(+ 0,+ surfacePointAt(cx, bottom - 10, body).lat,+ 1.02,+ );+ return (+ <Disc {...projection} center={chin} normal={chin} minDepth={0.35}>+ <g transform="scale(1.35)">+ <path+ d="M0,0 L-11,-6 L-11,6 Z"+ fill={deep}+ {...soft}+ strokeLinejoin="round"+ />+ <path+ d="M0,0 L11,-6 L11,6 Z"+ fill={deep}+ {...soft}+ strokeLinejoin="round"+ />+ <rect+ x={-2.6}+ y={-3}+ width={5.2}+ height={6}+ rx={1.5}+ fill={deep}+ {...edge}+ />+ </g>+ </Disc>+ );+ }+ case "headband": {+ const bandLat = surfacePointAt(cx, eyeY - 16, body).lat;+ const band: Vec3[] = Array.from({ length: 49 }, (_, index) =>+ fromSurface(-Math.PI + (2 * Math.PI * index) / 48, bandLat, 1.03),+ );+ const knot = fromSurface(-1.35, bandLat, 1.05);+ return (+ <g>+ <Strand {...projection} deep={deep} points={band} width={5} />+ <Strand+ {...projection}+ deep={deep}+ points={band}+ width={1.6}+ color="#fff"+ />+ <Disc {...projection} center={knot} normal={knot} minDepth={0.4}>+ <path+ d="M0,0 L-9,4 L-6,10 Z M0,0 L-2,10 L-7,14 Z"+ fill={deep}+ {...soft}+ strokeLinejoin="round"+ />+ </Disc>+ </g>+ );+ }+ default:+ return null;+ }+}diff --git a/autogpt_platform/frontend/src/components/molecules/BotAvatar/components/Face.tsx b/autogpt_platform/frontend/src/components/molecules/BotAvatar/components/Face.tsxnew file mode 100644index 0000000000..dd5b66290f--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/BotAvatar/components/Face.tsx@@ -0,0 +1,196 @@+import {+ findExpression,+ type BrowKind,+ type ExpressionId,+ type EyeSpec,+} from "../expressions";+import { INK, type AvatarStatus, type ShapeAnchors } from "../helpers";+import {+ ellipsoidFor,+ foreshortenTransform,+ isVisible,+ project,+ surfacePointAt,+ type Pose,+} from "../projection";+import type { SvgEls } from "../svgElements";++interface Props {+ anchors: ShapeAnchors;+ pose: Pose;+ status: AvatarStatus;+ expression: ExpressionId;+ blush: string;+ isLive: boolean;+ isBlinking: boolean;+ els: SvgEls;+}++const SPRING = { type: "spring", stiffness: 260, damping: 20 } as const;++const BROWS: Record<Exclude<BrowKind, "none">, (side: number) => string> = {+ raised: () => "M-5,-10 Q0,-13 5,-10",+ wave: () => "M-5,-10 Q-2.5,-13 0,-10 Q2.5,-7 5,-10",+ furrow: (side) => (side < 0 ? "M-5,-10 L5,-8" : "M-5,-8 L5,-10"),+ sad: (side) => (side < 0 ? "M-5,-8 L5,-10.5" : "M-5,-10.5 L5,-8"),+ flat: () => "M-5,-9.5 L5,-9.5",+};++function Eye({+ spec,+ isBlinking,+ isLive,+ els,+}: {+ spec: EyeSpec;+ isBlinking: boolean;+ isLive: boolean;+ els: SvgEls;+}) {+ const popIn = isLive ? { scale: 0.5, opacity: 0 } : false;+ if (spec.kind === "cross") {+ return (+ <els.path+ d="M-4,-4 L4,4 M4,-4 L-4,4"+ fill="none"+ stroke={INK}+ strokeWidth={2.4}+ strokeLinecap="round"+ initial={popIn}+ animate={{ scale: 1, opacity: 1 }}+ transition={SPRING}+ />+ );+ }+ if (spec.kind === "arc") {+ return (+ <els.path+ d="M-5,1 Q0,-5 5,1"+ fill="none"+ stroke={INK}+ strokeWidth={2.6}+ strokeLinecap="round"+ initial={popIn}+ animate={{ scale: 1, opacity: 1 }}+ transition={SPRING}+ />+ );+ }+ const closed = isBlinking || spec.kind === "flat";+ return (+ <els.g+ initial={false}+ animate={{+ x: spec.dx,+ y: spec.dy,+ rotate: spec.tilt,+ scaleY: isBlinking ? 0.08 : 1,+ }}+ transition={isBlinking ? { duration: 0.06 } : SPRING}+ >+ <els.ellipse+ fill={INK}+ initial={false}+ animate={{ rx: spec.rx, ry: spec.ry }}+ transition={SPRING}+ />+ {closed ? null : <circle cx={-1.4} cy={-2.2} r={1.5} fill="#fff" />}+ </els.g>+ );+}++export function Face({+ anchors,+ pose,+ status,+ expression,+ blush,+ isLive,+ isBlinking,+ els,+}: Props) {+ const { cx, eyeY, eyeGap } = anchors;+ const body = ellipsoidFor(anchors);+ const spec = findExpression(expression);+ const sides = [-1, 1] as const;+ const mouth = project(surfacePointAt(cx, eyeY + 13, body), pose, body);+ const browPath = spec.brow === "none" ? null : BROWS[spec.brow];+ const browWaves = spec.brow === "wave" && isLive;++ return (+ <g data-status={status} data-expression={expression}>+ {sides.map((side) => {+ const cheek = project(+ surfacePointAt(cx + side * (eyeGap / 2 + 6), eyeY + 8, body),+ pose,+ body,+ );+ if (!isVisible(cheek)) return null;+ return (+ <els.ellipse+ key={side}+ transform={foreshortenTransform(cheek)}+ rx={4.2}+ ry={2.4}+ fill={blush}+ initial={false}+ animate={{ opacity: spec.blush }}+ />+ );+ })}+ {sides.map((side) => {+ const point = project(+ surfacePointAt(cx + side * (eyeGap / 2), eyeY, body),+ pose,+ body,+ );+ if (!isVisible(point)) return null;+ const eyeSpec = side < 0 ? spec.left : spec.right;+ return (+ <g key={side} transform={foreshortenTransform(point, 0.12)}>+ <Eye+ spec={eyeSpec}+ isBlinking={isBlinking}+ isLive={isLive}+ els={els}+ />+ {browPath ? (+ <els.path+ d={browPath(side)}+ fill="none"+ stroke={INK}+ strokeWidth={2}+ strokeLinecap="round"+ initial={isLive ? { y: 3, opacity: 0 } : false}+ animate={+ browWaves+ ? { y: [0, -2, 0, 2, 0], opacity: 1 }+ : { y: 0, opacity: 1 }+ }+ transition={+ browWaves+ ? { duration: 1.4, repeat: Infinity, ease: "easeInOut" }+ : SPRING+ }+ />+ ) : null}+ </g>+ );+ })}+ {isVisible(mouth) ? (+ <g transform={foreshortenTransform(mouth, 0.2)}>+ <els.path+ fill="none"+ stroke={INK}+ strokeWidth={2.2}+ strokeLinecap="round"+ strokeLinejoin="round"+ initial={false}+ d={spec.mouth}+ transition={SPRING}+ />+ </g>+ ) : null}+ </g>+ );+}diff --git a/autogpt_platform/frontend/src/components/molecules/BotAvatar/components/StatusBadge.tsx b/autogpt_platform/frontend/src/components/molecules/BotAvatar/components/StatusBadge.tsxnew file mode 100644index 0000000000..ff8be083b9--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/BotAvatar/components/StatusBadge.tsx@@ -0,0 +1,104 @@+import type { AvatarStatus, ShapeAnchors } from "../helpers";+import type { SvgEls } from "../svgElements";++interface Props {+ status: AvatarStatus;+ anchors: ShapeAnchors;+ isLive: boolean;+ els: SvgEls;+}++const FILL: Record<Exclude<AvatarStatus, "idle">, string> = {+ thinking: "#7C3AED",+ working: "#3B6FD1",+ waiting: "#E8A317",+ done: "#22A05B",+ failed: "#DC2626",+ sleeping: "#71717A",+};++export function StatusBadge({ status, anchors, isLive, els }: Props) {+ if (status === "idle") return null;+ const x = anchors.cx + anchors.width / 2 - 4;+ const y = anchors.bottom - 6;++ return (+ <g transform={`translate(${x} ${y})`}>+ <els.g+ initial={isLive ? { scale: 0 } : false}+ animate={{ scale: 1 }}+ transition={{ type: "spring", stiffness: 400, damping: 18 }}+ >+ <circle r={8} fill={FILL[status]} stroke="#fff" strokeWidth={2.5} />+ {status === "working" ? (+ <els.circle+ r={3}+ fill="#fff"+ initial={false}+ animate={+ isLive ? { scale: [1, 0.55, 1], opacity: [1, 0.6, 1] } : undefined+ }+ transition={{ duration: 1, repeat: Infinity, ease: "easeInOut" }}+ />+ ) : null}+ {status === "done" ? (+ <path+ d="M-3.5,0.2 L-1,2.8 L3.8,-2.6"+ fill="none"+ stroke="#fff"+ strokeWidth={2.2}+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ ) : null}+ {status === "thinking" ? (+ <g fill="#fff">+ {[-3.2, 0, 3.2].map((x, index) => (+ <els.circle+ key={x}+ cx={x}+ r={1.4}+ initial={false}+ animate={isLive ? { opacity: [0.35, 1, 0.35] } : undefined}+ transition={{+ duration: 1.2,+ repeat: Infinity,+ delay: index * 0.2,+ ease: "easeInOut",+ }}+ />+ ))}+ </g>+ ) : null}+ {status === "failed" ? (+ <path+ d="M-3,-3 L3,3 M3,-3 L-3,3"+ fill="none"+ stroke="#fff"+ strokeWidth={2.2}+ strokeLinecap="round"+ />+ ) : null}+ {status === "sleeping" ? (+ <path+ d="M-3,-3 L3,-3 L-3,3 L3,3"+ fill="none"+ stroke="#fff"+ strokeWidth={1.8}+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ ) : null}+ {status === "waiting" ? (+ <path+ d="M0,-3.6 L0,0.8 M0,3.4 L0,3.5"+ fill="none"+ stroke="#fff"+ strokeWidth={2.4}+ strokeLinecap="round"+ />+ ) : null}+ </els.g>+ </g>+ );+}diff --git a/autogpt_platform/frontend/src/components/molecules/BotAvatar/expressions.ts b/autogpt_platform/frontend/src/components/molecules/BotAvatar/expressions.tsnew file mode 100644index 0000000000..020f93243d--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/BotAvatar/expressions.ts@@ -0,0 +1,246 @@+import type { AvatarStatus } from "./helpers";++export type ExpressionId =+ | "neutral"+ | "soft"+ | "wide"+ | "big"+ | "small"+ | "sleepy"+ | "wink"+ | "angry"+ | "happy"+ | "sad"+ | "suspicious"+ | "curious"+ | "dots"+ | "aside"+ | "focused"+ | "cross";++export type EyeKind = "open" | "arc" | "flat" | "cross";+export type BrowKind = "none" | "raised" | "wave" | "furrow" | "sad" | "flat";++export interface EyeSpec {+ kind: EyeKind;+ rx: number;+ ry: number;+ tilt: number;+ dx: number;+ dy: number;+}++export interface ExpressionSpec {+ id: ExpressionId;+ label: string;+ left: EyeSpec;+ right: EyeSpec;+ brow: BrowKind;+ mouth: string;+ blush: number;+}++const OPEN: EyeSpec = { kind: "open", rx: 4.5, ry: 6, tilt: 0, dx: 0, dy: 0 };++function eye(patch: Partial<EyeSpec>): EyeSpec {+ return { ...OPEN, ...patch };+}++const MOUTH = {+ smile: "M-4,0 Q0,3.5 4,0",+ grin: "M-6,-0.5 Q0,6.5 6,-0.5",+ flat: "M-3.5,0.5 L3.5,0.5",+ o: "M-2.4,0 A2.4,2.4 0 1 0 2.4,0 A2.4,2.4 0 1 0 -2.4,0",+ dot: "M-1.8,0 A1.8,1.8 0 1 0 1.8,0 A1.8,1.8 0 1 0 -1.8,0",+ frown: "M-4,1.5 Q0,-2 4,1.5",+ wobble: "M-5,1 Q-2.5,-2 0,1 Q2.5,4 5,1",+ smirk: "M-3,0.5 Q0,2 3,-0.5",+ tiny: "M-2,0.5 L2,0.5",+};++export const EXPRESSIONS: ExpressionSpec[] = [+ {+ id: "neutral",+ label: "Neutral",+ left: OPEN,+ right: OPEN,+ brow: "none",+ mouth: MOUTH.smile,+ blush: 0.5,+ },+ {+ id: "soft",+ label: "Soft",+ left: eye({ ry: 5.2 }),+ right: eye({ ry: 5.2 }),+ brow: "none",+ mouth: MOUTH.smirk,+ blush: 0.55,+ },+ {+ id: "wide",+ label: "Wide",+ left: eye({ rx: 5.4, ry: 7.2, dy: -0.5 }),+ right: eye({ rx: 5.4, ry: 7.2, dy: -0.5 }),+ brow: "raised",+ mouth: MOUTH.o,+ blush: 0.5,+ },+ {+ id: "big",+ label: "Big",+ left: eye({ rx: 5, ry: 8.5, dy: -0.8 }),+ right: eye({ rx: 5, ry: 8.5, dy: -0.8 }),+ brow: "raised",+ mouth: MOUTH.grin,+ blush: 0.75,+ },+ {+ id: "small",+ label: "Small",+ left: eye({ rx: 3.4, ry: 4.2, dy: 0.6 }),+ right: eye({ rx: 3.4, ry: 4.2, dy: 0.6 }),+ brow: "none",+ mouth: MOUTH.tiny,+ blush: 0.85,+ },+ {+ id: "sleepy",+ label: "Sleepy",+ left: eye({ kind: "flat", rx: 5, ry: 1.6 }),+ right: eye({ kind: "flat", rx: 5, ry: 1.6 }),+ brow: "none",+ mouth: MOUTH.dot,+ blush: 0.4,+ },+ {+ id: "wink",+ label: "Wink",+ left: OPEN,+ right: eye({ kind: "arc" }),+ brow: "none",+ mouth: MOUTH.smirk,+ blush: 0.6,+ },+ {+ id: "angry",+ label: "Angry",+ left: eye({ ry: 4.6, tilt: -18, dy: 0.6 }),+ right: eye({ ry: 4.6, tilt: 18, dy: 0.6 }),+ brow: "furrow",+ mouth: MOUTH.flat,+ blush: 0.4,+ },+ {+ id: "happy",+ label: "Happy",+ left: eye({ kind: "arc" }),+ right: eye({ kind: "arc" }),+ brow: "none",+ mouth: MOUTH.grin,+ blush: 0.85,+ },+ {+ id: "sad",+ label: "Sad",+ left: eye({ ry: 5.4, tilt: 16, dy: 0.8 }),+ right: eye({ ry: 5.4, tilt: -16, dy: 0.8 }),+ brow: "sad",+ mouth: MOUTH.frown,+ blush: 0.35,+ },+ {+ id: "suspicious",+ label: "Suspicious",+ left: eye({ ry: 4.4, dy: 0.5 }),+ right: eye({ kind: "flat", rx: 5, ry: 1.8, dy: 0.5 }),+ brow: "flat",+ mouth: MOUTH.smirk,+ blush: 0.4,+ },+ {+ id: "curious",+ label: "Curious",+ left: eye({ rx: 5.4, ry: 7.4, dy: -0.6 }),+ right: eye({ rx: 3.8, ry: 4.8, dy: 0.4 }),+ brow: "raised",+ mouth: MOUTH.smirk,+ blush: 0.5,+ },+ {+ id: "dots",+ label: "Dots",+ left: eye({ rx: 3.2, ry: 3.2, dx: 1.5, dy: -2 }),+ right: eye({ rx: 3.2, ry: 3.2, dx: 1.5, dy: -2 }),+ brow: "wave",+ mouth: MOUTH.smirk,+ blush: 0.45,+ },+ {+ id: "aside",+ label: "Aside",+ left: eye({ dx: 2.6, dy: -0.8 }),+ right: eye({ dx: 2.6, dy: -0.8 }),+ brow: "none",+ mouth: MOUTH.tiny,+ blush: 0.5,+ },+ {+ id: "focused",+ label: "Focused",+ left: eye({ ry: 4.2, dx: 0.6, dy: 1 }),+ right: eye({ ry: 4.2, dx: 0.6, dy: 1 }),+ brow: "furrow",+ mouth: MOUTH.flat,+ blush: 0.45,+ },+ {+ id: "cross",+ label: "Cross",+ left: eye({ kind: "cross" }),+ right: eye({ kind: "cross" }),+ brow: "none",+ mouth: MOUTH.wobble,+ blush: 0.35,+ },+];++export const POOLS: Record<AvatarStatus, ExpressionId[]> = {+ idle: ["neutral", "soft", "aside", "small"],+ thinking: ["dots", "aside", "curious", "suspicious"],+ working: ["focused", "neutral", "focused", "soft"],+ waiting: ["wide", "curious", "big", "sad"],+ done: ["happy", "big", "wink"],+ failed: ["cross", "sad", "angry"],+ sleeping: ["sleepy"],+};++export const EXPRESSION_CADENCE_MS: Record<AvatarStatus, [number, number]> = {+ idle: [7000, 14000],+ thinking: [1800, 3400],+ working: [1800, 3200],+ waiting: [2200, 4200],+ done: [2600, 4800],+ failed: [2400, 4000],+ sleeping: [8000, 12000],+};++export const BLINK_CADENCE_MS: Record<AvatarStatus, [number, number] | null> = {+ idle: [5000, 11000],+ thinking: [3500, 7000],+ working: [2800, 5500],+ waiting: [1800, 3500],+ done: [2500, 5000],+ failed: null,+ sleeping: null,+};++export function findExpression(id: ExpressionId) {+ return (+ EXPRESSIONS.find((expression) => expression.id === id) ?? EXPRESSIONS[0]+ );+}++export function isExpressionId(value: string): value is ExpressionId {+ return EXPRESSIONS.some((expression) => expression.id === value);+}diff --git a/autogpt_platform/frontend/src/components/molecules/BotAvatar/helpers.ts b/autogpt_platform/frontend/src/components/molecules/BotAvatar/helpers.tsnew file mode 100644index 0000000000..ce5d7e8617--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/BotAvatar/helpers.ts@@ -0,0 +1,360 @@+export type ShapeId = "round" | "dome" | "squircle" | "wide" | "bean";+export type ColorId =+ | "lavender"+ | "plum"+ | "amber"+ | "sky"+ | "mint"+ | "coral"+ | "indigo"+ | "butter";+export type AccessoryId =+ | "none"+ | "glasses"+ | "headset"+ | "star"+ | "bow"+ | "badge"+ | "crown"+ | "propeller"+ | "ears"+ | "flower"+ | "bowtie"+ | "headband";+export type AvatarStatus =+ | "idle"+ | "thinking"+ | "working"+ | "waiting"+ | "done"+ | "failed"+ | "sleeping";++export interface AvatarConfig {+ shape: ShapeId;+ color: ColorId;+ accessory: AccessoryId;+}++export interface ShapeAnchors {+ cx: number;+ eyeY: number;+ eyeGap: number;+ top: number;+ bottom: number;+ width: number;+}++export interface ShapeOption {+ id: ShapeId;+ label: string;+ hint: string;+ path: string;+ anchors: ShapeAnchors;+}++export interface ColorOption {+ id: ColorId;+ label: string;+ role: string;+ light: string;+ body: string;+ mid: string;+ deep: string;+}++export interface AccessoryOption {+ id: AccessoryId;+ label: string;+ hint: string;+}++export interface StatusOption {+ id: AvatarStatus;+ label: string;+ hint: string;+}++export const VIEWBOX = 120;+export const INK = "#26262E";++export const SHAPES: ShapeOption[] = [+ {+ id: "round",+ label: "Round",+ hint: "round, friendly",+ path: "M60,22 A42,42 0 1 1 59.9,22 Z",+ anchors: { cx: 60, eyeY: 62, eyeGap: 24, top: 22, bottom: 106, width: 84 },+ },+ {+ id: "dome",+ label: "Dome",+ hint: "closest to Otto",+ path: "M24,102 L24,64 A36,36 0 0 1 96,64 L96,102 Q96,108 90,108 L30,108 Q24,108 24,102 Z",+ anchors: { cx: 60, eyeY: 64, eyeGap: 24, top: 28, bottom: 108, width: 72 },+ },+ {+ id: "squircle",+ label: "Squircle",+ hint: "steady, square",+ path: "M60,24 C92,24 100,32 100,64 C100,96 92,104 60,104 C28,104 20,96 20,64 C20,32 28,24 60,24 Z",+ anchors: { cx: 60, eyeY: 62, eyeGap: 26, top: 24, bottom: 104, width: 80 },+ },+ {+ id: "wide",+ label: "Wide",+ hint: "low and wide",+ path: "M60,38 C92,38 108,52 108,72 C108,92 92,106 60,106 C28,106 12,92 12,72 C12,52 28,38 60,38 Z",+ anchors: { cx: 60, eyeY: 68, eyeGap: 28, top: 38, bottom: 106, width: 96 },+ },+ {+ id: "bean",+ label: "Bean",+ hint: "lively, off-centre",+ path: "M34,40 C36,22 56,16 72,22 C92,30 102,50 98,72 C94,94 76,108 54,104 C32,100 20,80 26,60 C28,52 33,48 34,40 Z",+ anchors: { cx: 62, eyeY: 58, eyeGap: 24, top: 18, bottom: 106, width: 76 },+ },+];++export const COLORS: ColorOption[] = [+ {+ id: "lavender",+ label: "Lavender",+ role: "AutoPilot",+ light: "#c4b5fd",+ body: "#a78bfa",+ mid: "#8b5cf6",+ deep: "#6d28d9",+ },+ {+ id: "plum",+ label: "Plum",+ role: "Marketing",+ light: "#f9a8d4",+ body: "#f472b6",+ mid: "#ec4899",+ deep: "#be185d",+ },+ {+ id: "amber",+ label: "Amber",+ role: "Sales",+ light: "#fcd34d",+ body: "#fbbf24",+ mid: "#f59e0b",+ deep: "#b45309",+ },+ {+ id: "sky",+ label: "Sky",+ role: "Ops",+ light: "#7dd3fc",+ body: "#38bdf8",+ mid: "#0ea5e9",+ deep: "#0369a1",+ },+ {+ id: "mint",+ label: "Mint",+ role: "Finance",+ light: "#6ee7b7",+ body: "#34d399",+ mid: "#10b981",+ deep: "#047857",+ },+ {+ id: "coral",+ label: "Coral",+ role: "Support",+ light: "#fdba74",+ body: "#fb923c",+ mid: "#f97316",+ deep: "#c2410c",+ },+ {+ id: "indigo",+ label: "Indigo",+ role: "Research",+ light: "#a5b4fc",+ body: "#818cf8",+ mid: "#6366f1",+ deep: "#4338ca",+ },+ {+ id: "butter",+ label: "Butter",+ role: "Content",+ light: "#fde047",+ body: "#facc15",+ mid: "#eab308",+ deep: "#a16207",+ },+];++export const ACCESSORIES: AccessoryOption[] = [+ { id: "none", label: "None", hint: "plain" },+ { id: "glasses", label: "Glasses", hint: "research, review" },+ { id: "headset", label: "Headset", hint: "support, ops" },+ { id: "star", label: "Star pin", hint: "a raised favourite" },+ { id: "bow", label: "Bow", hint: "marketing, events" },+ { id: "badge", label: "Badge", hint: "finance, admin" },+ { id: "crown", label: "Crown", hint: "the lead of a pod" },+ { id: "propeller", label: "Propeller", hint: "playful, experiments" },+ { id: "ears", label: "Cat ears", hint: "curious, alert" },+ { id: "flower", label: "Flower", hint: "people, community" },+ { id: "bowtie", label: "Bow tie", hint: "formal, legal" },+ { id: "headband", label: "Headband", hint: "focus, sprints" },+];++export const STATUSES: StatusOption[] = [+ { id: "idle", label: "Idle", hint: "calm, slightly curious" },+ { id: "thinking", label: "Thinking", hint: "brows wave, eyes up" },+ { id: "working", label: "Working", hint: "kicks into gear" },+ { id: "waiting", label: "Needs you", hint: "blocked, asking" },+ { id: "done", label: "Done", hint: "settles, satisfied" },+ { id: "failed", label: "Failed", hint: "falls apart for a beat" },+ { id: "sleeping", label: "Paused", hint: "schedules off, dozing" },+];++export const AUTOPILOT_AVATAR: AvatarConfig = {+ shape: "dome",+ color: "lavender",+ accessory: "none",+};++export const DEFAULT_CONFIG: AvatarConfig = {+ shape: "round",+ color: "lavender",+ accessory: "none",+};++export function findShape(id: ShapeId) {+ return SHAPES.find((shape) => shape.id === id) ?? SHAPES[0];+}++export function findColor(id: ColorId) {+ return COLORS.find((color) => color.id === id) ?? COLORS[0];+}++function isShapeId(value: string): value is ShapeId {+ return SHAPES.some((shape) => shape.id === value);+}++function isColorId(value: string): value is ColorId {+ return COLORS.some((color) => color.id === value);+}++function isAccessoryId(value: string): value is AccessoryId {+ return ACCESSORIES.some((accessory) => accessory.id === value);+}++export function isAvatarStatus(value: string): value is AvatarStatus {+ return STATUSES.some((status) => status.id === value);+}++export function encodeConfig(config: AvatarConfig) {+ return `${config.shape}.${config.color}.${config.accessory}`;+}++export function decodeConfig(value: string | null): AvatarConfig {+ if (!value) return DEFAULT_CONFIG;+ const [shape = "", color = "", accessory = ""] = value.split(".");+ return {+ shape: isShapeId(shape) ? shape : DEFAULT_CONFIG.shape,+ color: isColorId(color) ? color : DEFAULT_CONFIG.color,+ accessory: isAccessoryId(accessory) ? accessory : DEFAULT_CONFIG.accessory,+ };+}++function pick<T>(items: readonly T[], random: () => number) {+ return items[Math.floor(random() * items.length)];+}++export function randomConfig(random: () => number = Math.random): AvatarConfig {+ return {+ shape: pick(SHAPES, random).id,+ color: pick(COLORS, random).id,+ accessory: pick(ACCESSORIES, random).id,+ };+}++export function hashSeed(input: string) {+ let hash = 2166136261;+ for (let index = 0; index < input.length; index += 1) {+ hash ^= input.charCodeAt(index);+ hash = Math.imul(hash, 16777619);+ }+ return hash >>> 0;+}++export function seededRandom(seed: number) {+ let state = seed || 1;+ return function next() {+ state = (Math.imul(state, 1664525) + 1013904223) >>> 0;+ return state / 4294967296;+ };+}++export function configForName(name: string): AvatarConfig {+ return randomConfig(seededRandom(hashSeed(name.toLowerCase())));+}++const AVATAR_URL_PATTERN = /^\/avatars\/([a-z]+)\.([a-z]+)\.([a-z]+)\.svg$/;++export function avatarUrlFor(config: AvatarConfig) {+ return `/avatars/${encodeConfig(config)}.svg`;+}++export function parseAvatarUrl(+ url: string | null | undefined,+): AvatarConfig | null {+ const match = url?.match(AVATAR_URL_PATTERN);+ if (!match) return null;+ const [, shape, color, accessory] = match;+ if (!isShapeId(shape) || !isColorId(color) || !isAccessoryId(accessory))+ return null;+ return { shape, color, accessory };+}++const TOKEN_COLORS: Record<string, ColorId> = {+ rose: "plum",+ red: "coral",+ orange: "coral",+ amber: "amber",+ yellow: "butter",+ lime: "mint",+ green: "mint",+ emerald: "mint",+ teal: "sky",+ cyan: "sky",+ sky: "sky",+ blue: "sky",+ indigo: "indigo",+ violet: "lavender",+ fuchsia: "plum",+};++export function colorForToken(+ token: string | null | undefined,+): ColorId | null {+ const family = token?.split("-")[0];+ return family ? (TOKEN_COLORS[family] ?? null) : null;+}++export interface ExpertLike {+ name: string | null | undefined;+ avatarUrl?: string | null;+ color?: string | null;+}++export function expertAvatarConfig(expert: ExpertLike): AvatarConfig {+ const parsed = parseAvatarUrl(expert.avatarUrl);+ if (parsed) return parsed;+ const seeded = configForName(expert.name ?? "");+ const color = colorForToken(expert.color);+ return color ? { ...seeded, color } : seeded;+}++export function isUploadedAvatar(url: string | null | undefined) {+ return Boolean(url) && !parseAvatarUrl(url);+}diff --git a/autogpt_platform/frontend/src/components/molecules/BotAvatar/parts.ts b/autogpt_platform/frontend/src/components/molecules/BotAvatar/parts.tsnew file mode 100644index 0000000000..39255db007--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/BotAvatar/parts.ts@@ -0,0 +1,110 @@+import type { Ellipsoid, Pose, Projected } from "./projection";++export type Vec3 = [number, number, number];+export type Layer = "front" | "back";++export function fromSurface(lon: number, lat: number, radius = 1): Vec3 {+ const cosLat = Math.cos(lat);+ return [+ radius * cosLat * Math.sin(lon),+ radius * Math.sin(lat),+ radius * cosLat * Math.cos(lon),+ ];+}++export function rotate([x0, y0, z0]: Vec3, pose: Pose): Vec3 {+ const yawCos = Math.cos(pose.yaw);+ const yawSin = Math.sin(pose.yaw);+ const x = x0 * yawCos + z0 * yawSin;+ const z1 = -x0 * yawSin + z0 * yawCos;+ const pitchCos = Math.cos(pose.pitch);+ const pitchSin = Math.sin(pose.pitch);+ return [x, y0 * pitchCos - z1 * pitchSin, y0 * pitchSin + z1 * pitchCos];+}++export function toScreen([x, y]: Vec3, body: Ellipsoid) {+ return { x: body.cx + body.rx * x, y: body.cy - body.ry * y };+}++export function surfaceDepth([x, y]: Vec3) {+ return Math.sqrt(Math.max(0, 1 - x * x - y * y));+}++export function isInFront(point: Vec3, tolerance = 0.015) {+ return point[2] >= surfaceDepth(point) - tolerance;+}++export function layerOf(point: Vec3): Layer {+ return isInFront(point) ? "front" : "back";+}++export function discProjection(+ center: Vec3,+ normal: Vec3,+ pose: Pose,+ body: Ellipsoid,+): Projected {+ const c = rotate(center, pose);+ const n = rotate(normal, pose);+ const screen = toScreen(c, body);+ return {+ x: screen.x,+ y: screen.y,+ depth: Math.abs(n[2]),+ angle: (Math.atan2(-n[1], n[0]) * 180) / Math.PI,+ };+}++export function discTransform(projected: Projected, minDepth = 0.12) {+ const depth = Math.max(minDepth, projected.depth);+ return `translate(${projected.x} ${projected.y}) rotate(${projected.angle}) scale(${depth} 1) rotate(${-projected.angle})`;+}++export function samplePolyline(points: Vec3[], perSegment = 6): Vec3[] {+ const out: Vec3[] = [];+ for (let index = 0; index < points.length - 1; index += 1) {+ const [ax, ay, az] = points[index];+ const [bx, by, bz] = points[index + 1];+ for (let step = 0; step < perSegment; step += 1) {+ const t = step / perSegment;+ out.push([ax + (bx - ax) * t, ay + (by - ay) * t, az + (bz - az) * t]);+ }+ }+ out.push(points[points.length - 1]);+ return out;+}++export function splitPolyline(points: Vec3[], pose: Pose, body: Ellipsoid) {+ const rotated = points.map((point) => rotate(point, pose));+ const paths: Record<Layer, string[]> = { front: [], back: [] };+ let previous: Layer | null = null;+ rotated.forEach((point) => {+ const layer = layerOf(point);+ const { x, y } = toScreen(point, body);+ const command = layer === previous ? "L" : "M";+ if (layer !== previous && previous !== null) {+ paths[previous].push(`L${x.toFixed(2)},${y.toFixed(2)}`);+ }+ paths[layer].push(`${command}${x.toFixed(2)},${y.toFixed(2)}`);+ previous = layer;+ });+ return { front: paths.front.join(" "), back: paths.back.join(" ") };+}++export function polygonPath(points: Vec3[], pose: Pose, body: Ellipsoid) {+ const screen = points.map((point) => toScreen(rotate(point, pose), body));+ return `M${screen.map((point) => `${point.x.toFixed(2)},${point.y.toFixed(2)}`).join(" L")} Z`;+}++export function centroidLayer(points: Vec3[], pose: Pose): Layer {+ const rotated = points.map((point) => rotate(point, pose));+ const center = rotated.reduce<Vec3>(+ (sum, [x, y, z]) => [+ sum[0] + x / rotated.length,+ sum[1] + y / rotated.length,+ sum[2] + z / rotated.length,+ ],+ [0, 0, 0],+ );+ return layerOf(center);+}diff --git a/autogpt_platform/frontend/src/components/molecules/BotAvatar/projection.ts b/autogpt_platform/frontend/src/components/molecules/BotAvatar/projection.tsnew file mode 100644index 0000000000..8e7b413e42--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/BotAvatar/projection.ts@@ -0,0 +1,142 @@+import type { ShapeAnchors } from "./helpers";++export interface Pose {+ yaw: number;+ pitch: number;+ roll: number;+ bob: number;+}++export interface SurfacePoint {+ lon: number;+ lat: number;+}++export interface Projected {+ x: number;+ y: number;+ depth: number;+ angle: number;+}++export interface Ellipsoid {+ cx: number;+ cy: number;+ rx: number;+ ry: number;+}++export const FRONT_POSE: Pose = { yaw: 0, pitch: 0, roll: 0, bob: 0 };++export function ellipsoidFor(anchors: ShapeAnchors): Ellipsoid {+ return {+ cx: anchors.cx,+ cy: (anchors.top + anchors.bottom) / 2,+ rx: anchors.width / 2,+ ry: (anchors.bottom - anchors.top) / 2,+ };+}++export function surfacePointAt(+ x: number,+ y: number,+ body: Ellipsoid,+): SurfacePoint {+ const lat = Math.asin(clamp((body.cy - y) / body.ry, -1, 1));+ const lon = Math.asin(+ clamp((x - body.cx) / (body.rx * Math.cos(lat)), -1, 1),+ );+ return { lon, lat };+}++export function project(+ point: SurfacePoint,+ pose: Pose,+ body: Ellipsoid,+): Projected {+ const cosLat = Math.cos(point.lat);+ let x = cosLat * Math.sin(point.lon);+ let y = Math.sin(point.lat);+ let z = cosLat * Math.cos(point.lon);++ const yawCos = Math.cos(pose.yaw);+ const yawSin = Math.sin(pose.yaw);+ [x, z] = [x * yawCos + z * yawSin, -x * yawSin + z * yawCos];++ const pitchCos = Math.cos(pose.pitch);+ const pitchSin = Math.sin(pose.pitch);+ [y, z] = [y * pitchCos - z * pitchSin, y * pitchSin + z * pitchCos];++ return {+ x: body.cx + body.rx * x,+ y: body.cy - body.ry * y,+ depth: z,+ angle: (Math.atan2(-y, x) * 180) / Math.PI,+ };+}++export function foreshortenTransform(projected: Projected, minDepth = 0) {+ const depth = Math.max(minDepth, projected.depth);+ return `translate(${projected.x} ${projected.y}) rotate(${projected.angle}) scale(${depth} 1) rotate(${-projected.angle})`;+}++export function isVisible(projected: Projected, threshold = 0.02) {+ return projected.depth > threshold;+}++function clamp(value: number, min: number, max: number) {+ return Math.min(max, Math.max(min, value));+}++export function arcPath(+ points: SurfacePoint[],+ pose: Pose,+ body: Ellipsoid,+ minDepth = -0.05,+) {+ const segments: string[] = [];+ let open = false;+ for (const point of points) {+ const projected = project(point, pose, body);+ if (projected.depth < minDepth) {+ open = false;+ continue;+ }+ segments.push(+ `${open ? "L" : "M"}${projected.x.toFixed(2)},${projected.y.toFixed(2)}`,+ );+ open = true;+ }+ return segments.join(" ");+}++export function latitudeRing(+ lat: number,+ steps: number,+ fromLon = -Math.PI,+ toLon = Math.PI,+): SurfacePoint[] {+ return Array.from({ length: steps + 1 }, (_, index) => ({+ lon: fromLon + ((toLon - fromLon) * index) / steps,+ lat,+ }));+}++export function pointFromVector(x: number, y: number, z: number): SurfacePoint {+ const length = Math.hypot(x, y, z) || 1;+ return {+ lat: Math.asin(y / length),+ lon: Math.atan2(x / length, z / length),+ };+}++export function coronalArc(+ fromLat: number,+ steps: number,+ forward: number,+): SurfacePoint[] {+ return Array.from({ length: steps + 1 }, (_, index) => {+ const theta = Math.PI - fromLat - ((Math.PI - 2 * fromLat) * index) / steps;+ return pointFromVector(Math.cos(theta), Math.sin(theta), forward);+ });+}diff --git a/autogpt_platform/frontend/src/components/molecules/BotAvatar/svgElements.tsx b/autogpt_platform/frontend/src/components/molecules/BotAvatar/svgElements.tsxnew file mode 100644index 0000000000..7d5e364f56--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/BotAvatar/svgElements.tsx@@ -0,0 +1,93 @@+import type { SVGMotionProps } from "framer-motion";+import { createElement, forwardRef, type ElementType } from "react";++// The avatar parts draw with motion elements when they're alive in the+// browser and with plain SVG elements when rendered to a static string+// (the /avatars/[file] route runs in the server layer, where framer-motion+// and hooks are off limits). Parts take the element set as a prop so they+// never import framer-motion themselves.+export interface SvgEls {+ path: ElementType<SVGMotionProps<SVGPathElement>>;+ g: ElementType<SVGMotionProps<SVGGElement>>;+ ellipse: ElementType<SVGMotionProps<SVGEllipseElement>>;+ circle: ElementType<SVGMotionProps<SVGCircleElement>>;+}++const MOTION_ONLY_PROPS = new Set([+ "initial",+ "animate",+ "exit",+ "transition",+ "variants",+ "whileHover",+ "whileTap",+ "whileFocus",+ "whileDrag",+ "whileInView",+ "layout",+ "layoutId",+ "onAnimationStart",+ "onAnimationComplete",+ "onUpdate",+]);+const ATTRIBUTE_TARGETS = new Set([+ "d",+ "rx",+ "ry",+ "r",+ "cx",+ "cy",+ "opacity",+]);++function isPlainTarget(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function transformFrom(target: Record<string, unknown>): string | undefined {+ const num = (key: string, fallback: number) =>+ typeof target[key] === "number" ? (target[key] as number) : fallback;+ const parts: string[] = [];+ const x = num("x", 0);+ const y = num("y", 0);+ if (x || y) parts.push(`translate(${x} ${y})`);+ const rotate = num("rotate", 0);+ if (rotate) parts.push(`rotate(${rotate})`);+ const scale = num("scale", 1);+ const scaleX = num("scaleX", scale);+ const scaleY = num("scaleY", scale);+ if (scaleX !== 1 || scaleY !== 1) parts.push(`scale(${scaleX} ${scaleY})`);+ return parts.length ? parts.join(" ") : undefined;+}++// A motion element's resting frame: the `animate` target becomes plain+// attributes (or a transform), and every motion-only prop is dropped.+function staticEl<T extends SVGElement>(tag: string) {+ return forwardRef<T, SVGMotionProps<T>>(function StaticSvgEl(props, ref) {+ const attrs: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(props)) {+ if (!MOTION_ONLY_PROPS.has(key)) attrs[key] = value;+ }+ if (isPlainTarget(props.animate)) {+ for (const [key, value] of Object.entries(props.animate)) {+ if (ATTRIBUTE_TARGETS.has(key) && !Array.isArray(value)) {+ attrs[key] = value;+ }+ }+ const transform = transformFrom(props.animate);+ if (transform) {+ attrs.transform = [attrs.transform, transform]+ .filter(Boolean)+ .join(" ");+ }+ }+ return createElement(tag, { ...attrs, ref });+ });+}++export const STATIC_ELS: SvgEls = {+ path: staticEl<SVGPathElement>("path"),+ g: staticEl<SVGGElement>("g"),+ ellipse: staticEl<SVGEllipseElement>("ellipse"),+ circle: staticEl<SVGCircleElement>("circle"),+};diff --git a/autogpt_platform/frontend/src/components/molecules/BotAvatar/useExpression.ts b/autogpt_platform/frontend/src/components/molecules/BotAvatar/useExpression.tsnew file mode 100644index 0000000000..db389ed910--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/BotAvatar/useExpression.ts@@ -0,0 +1,66 @@+import { useEffect, useState } from "react";+import {+ BLINK_CADENCE_MS,+ EXPRESSION_CADENCE_MS,+ POOLS,+ type ExpressionId,+} from "./expressions";+import type { AvatarStatus } from "./helpers";++const BLINK_MS = 130;++function between([min, max]: [number, number]) {+ return min + Math.random() * (max - min);+}++interface Args {+ status: AvatarStatus;+ isLive: boolean;+ override?: ExpressionId;+}++export function useExpression({ status, isLive, override }: Args) {+ const [expression, setExpression] = useState<ExpressionId>(POOLS[status][0]);+ const [isBlinking, setIsBlinking] = useState(false);++ useEffect(() => {+ setExpression(POOLS[status][0]);+ if (!isLive) return;+ let timer: ReturnType<typeof setTimeout>;+ function schedule() {+ timer = setTimeout(() => {+ setExpression((current) => {+ const alternatives = POOLS[status].filter((id) => id !== current);+ return (+ alternatives[Math.floor(Math.random() * alternatives.length)] ??+ current+ );+ });+ schedule();+ }, between(EXPRESSION_CADENCE_MS[status]));+ }+ schedule();+ return () => clearTimeout(timer);+ }, [status, isLive]);++ useEffect(() => {+ setIsBlinking(false);+ const cadence = BLINK_CADENCE_MS[status];+ if (!isLive || !cadence) return;+ const range: [number, number] = cadence;+ let timer: ReturnType<typeof setTimeout>;+ function schedule() {+ timer = setTimeout(() => {+ setIsBlinking(true);+ timer = setTimeout(() => {+ setIsBlinking(false);+ schedule();+ }, BLINK_MS);+ }, between(range));+ }+ schedule();+ return () => clearTimeout(timer);+ }, [status, isLive]);++ return { expression: override ?? expression, isBlinking };+}diff --git a/autogpt_platform/frontend/src/components/molecules/BotAvatar/usePose.ts b/autogpt_platform/frontend/src/components/molecules/BotAvatar/usePose.tsnew file mode 100644index 0000000000..65dbce0305--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/BotAvatar/usePose.ts@@ -0,0 +1,165 @@+import { useAnimationFrame, useReducedMotion } from "framer-motion";+import { useEffect, useRef, useState, type RefObject } from "react";+import type { AvatarStatus } from "./helpers";+import { FRONT_POSE, type Pose } from "./projection";++const LOOK_REACH_PX = 320;+const LOOK_YAW = 0.55;+const LOOK_PITCH = 0.3;+const SMOOTHING = 0.12;++interface Args {+ status: AvatarStatus;+ animated: boolean;+ trackPointer: boolean;+ poseOffset?: Partial<Pose>;+ svgRef: RefObject<SVGSVGElement | null>;+}++const LOOK_WEIGHT: Record<AvatarStatus, number> = {+ idle: 1,+ thinking: 0.2,+ working: 0.25,+ waiting: 0.6,+ done: 0.9,+ failed: 0.3,+ sleeping: 0,+};++function statusPose(+ status: AvatarStatus,+ t: number,+ sinceChange: number,+): Pose {+ switch (status) {+ case "thinking":+ return {+ yaw: 0.35 + 0.12 * Math.sin(t * 0.9),+ pitch: -0.28 + 0.05 * Math.sin(t * 1.3),+ roll: -0.08 + 0.03 * Math.sin(t * 0.7),+ bob: 0.6 * Math.sin(t * 1.4),+ };+ case "failed": {+ const shake =+ sinceChange < 0.7+ ? Math.sin(sinceChange * 40) * (1 - sinceChange / 0.7)+ : 0;+ return {+ yaw: 0.35 * shake,+ pitch: 0.18 + 0.03 * Math.sin(t * 2),+ roll: 0.12 * shake,+ bob: -2 * (1 - Math.min(1, sinceChange / 0.7)),+ };+ }+ case "sleeping":+ return {+ yaw: 0.05 * Math.sin(t * 0.3),+ pitch: 0.3 + 0.04 * Math.sin(t * 0.7),+ roll: 0.16,+ bob: 1.2 * Math.sin(t * 0.7),+ };+ case "working":+ return {+ yaw: -0.45 + 0.06 * Math.sin(t * 7),+ pitch: 0.3 + 0.1 * Math.sin(t * 9),+ roll: 0.03 * Math.sin(t * 4.5),+ bob: 1.6 * Math.abs(Math.sin(t * 4.5)),+ };+ case "waiting":+ return {+ yaw: 0.75 * Math.sin(t * 1.3),+ pitch: -0.22 + 0.04 * Math.sin(t * 2.6),+ roll: 0.14 * Math.sin(t * 1.3 + 0.8),+ bob: 0,+ };+ case "done": {+ const nod =+ sinceChange < 0.9 ? Math.sin((sinceChange / 0.9) * Math.PI) : 0;+ return {+ yaw: 0.12 * Math.sin(t * 0.5),+ pitch: 0.35 * nod + 0.04 * Math.sin(t * 0.8),+ roll: 0,+ bob: 7 * nod + 0.8 * Math.sin(t * 1.6),+ };+ }+ default:+ return {+ yaw: 0.3 * Math.sin(t * 0.55),+ pitch: 0.08 * Math.sin(t * 0.85 + 1),+ roll: 0.02 * Math.sin(t * 0.4),+ bob: 1.2 * Math.sin(t * 1.7),+ };+ }+}++export function usePose({+ status,+ animated,+ trackPointer,+ poseOffset,+ svgRef,+}: Args) {+ const reducedMotion = useReducedMotion();+ const isLive = animated && !reducedMotion;+ const [pose, setPose] = useState<Pose>(FRONT_POSE);+ const look = useRef({ yaw: 0, pitch: 0 });+ const smoothed = useRef<Pose>(FRONT_POSE);+ const changedAt = useRef<number | null>(null);+ const clock = useRef(0);++ useEffect(() => {+ changedAt.current = clock.current;+ }, [status]);++ useEffect(() => {+ if (!isLive || !trackPointer) return;+ function handleMove(event: PointerEvent) {+ const box = svgRef.current?.getBoundingClientRect();+ if (!box) return;+ const dx = (event.clientX - (box.left + box.width / 2)) / LOOK_REACH_PX;+ const dy = (event.clientY - (box.top + box.height / 2)) / LOOK_REACH_PX;+ look.current = {+ yaw: Math.max(-1, Math.min(1, dx)) * LOOK_YAW,+ pitch: Math.max(-1, Math.min(1, dy)) * LOOK_PITCH,+ };+ }+ window.addEventListener("pointermove", handleMove);+ return () => window.removeEventListener("pointermove", handleMove);+ }, [isLive, trackPointer, svgRef]);++ useAnimationFrame((time) => {+ if (!isLive) return;+ const t = time / 1000;+ clock.current = t;+ const sinceChange = t - (changedAt.current ?? t);+ const base = statusPose(status, t, sinceChange);+ const weight = LOOK_WEIGHT[status];+ const target: Pose = {+ yaw: base.yaw + look.current.yaw * weight + (poseOffset?.yaw ?? 0),+ pitch:+ base.pitch + look.current.pitch * weight + (poseOffset?.pitch ?? 0),+ roll: base.roll + (poseOffset?.roll ?? 0),+ bob: base.bob,+ };+ const previous = smoothed.current;+ const next: Pose = {+ yaw: previous.yaw + (target.yaw - previous.yaw) * SMOOTHING,+ pitch: previous.pitch + (target.pitch - previous.pitch) * SMOOTHING,+ roll: previous.roll + (target.roll - previous.roll) * SMOOTHING,+ bob: target.bob,+ };+ smoothed.current = next;+ setPose(next);+ });++ const resolved = isLive+ ? pose+ : {+ ...FRONT_POSE,+ yaw: poseOffset?.yaw ?? 0,+ pitch: poseOffset?.pitch ?? 0,+ roll: poseOffset?.roll ?? 0,+ };++ return { isLive, pose: resolved };+}diff --git a/autogpt_platform/frontend/src/components/molecules/ExpertAvatar/ExpertAvatar.tsx b/autogpt_platform/frontend/src/components/molecules/ExpertAvatar/ExpertAvatar.tsxindex b74619653a..ac099af5f8 100644--- a/autogpt_platform/frontend/src/components/molecules/ExpertAvatar/ExpertAvatar.tsx+++ b/autogpt_platform/frontend/src/components/molecules/ExpertAvatar/ExpertAvatar.tsx@@ -5,21 +5,38 @@ import {AvatarImage,} from "@/components/atoms/Avatar/Avatar";import { Icon } from "@/components/atoms/Icon/Icon";+import { BotAvatar } from "@/components/molecules/BotAvatar/BotAvatar";+import {+ expertAvatarConfig,+ isUploadedAvatar,+ type AvatarStatus,+} from "@/components/molecules/BotAvatar/helpers";import { cn } from "@/lib/utils";interface Props {name: string | null;avatarUrl: string | null;+ color?: string | null;+ status?: AvatarStatus;+ animated?: boolean;size?: number;className?: string;}/**- * Expert avatar with a generic-agent fallback, shared by the copilot home- * surfaces (briefing card, team strip, needs-attention list) so they stay- * visually consistent.+ * Expert avatar shared by the copilot home surfaces (briefing card, team+ * strip, needs-attention list). Uploaded pictures render as-is; everything+ * else gets the generated shape/colour/accessory face.*/-export function ExpertAvatar({ name, avatarUrl, size = 40, className }: Props) {+export function ExpertAvatar({+ name,+ avatarUrl,+ color,+ status = "idle",+ animated = false,+ size = 40,+ className,+}: Props) {const style = { width: size, height: size };if (!name) {@@ -36,9 +53,23 @@ export function ExpertAvatar({ name, avatarUrl, size = 40, className }: Props) {);}+ if (!isUploadedAvatar(avatarUrl)) {+ return (+ <BotAvatar+ config={expertAvatarConfig({ name, avatarUrl, color })}+ status={status}+ size={size}+ animated={animated}+ showBadge={status !== "idle"}+ title={name}+ className={className}+ />+ );+ }+return (<Avatar style={style} className={cn("shrink-0", className)}>- {avatarUrl ? <AvatarImage src={avatarUrl} alt={name} /> : null}+ <AvatarImage src={avatarUrl ?? undefined} alt={name} /><AvatarFallback>{name}</AvatarFallback></Avatar>);diff --git a/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/__tests__/NeedsAttentionList.test.tsx b/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/__tests__/NeedsAttentionList.test.tsxindex 2a8975f8ba..86bc435163 100644--- a/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/__tests__/NeedsAttentionList.test.tsx+++ b/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/__tests__/NeedsAttentionList.test.tsx@@ -243,10 +243,23 @@ test("a second row's decision does not unlock the first one mid-flight", async (node_exec_id: "ne-2",instructions: "Approve invoice",};+ let finishFirst = () => {};+ let finishSecond = () => {};+ const firstResponse = new Promise<void>((resolve) => {+ finishFirst = resolve;+ });+ const secondResponse = new Promise<void>((resolve) => {+ finishSecond = resolve;+ });server.use(getGetV2GetPendingReviewsMockHandler200([review, other]),- http.post("/api/proxy/api/review/action", async () => {- await new Promise((resolve) => setTimeout(resolve, 300));+ http.post("/api/proxy/api/review/action", async ({ request }) => {+ const body = (await request.json()) as {+ reviews: { node_exec_id: string }[];+ };+ await (body.reviews[0].node_exec_id === "ne-1"+ ? firstResponse+ : secondResponse);return HttpResponse.json({approved_count: 1,rejected_count: 0,@@ -254,19 +267,26 @@ test("a second row's decision does not unlock the first one mid-flight", async (});}),);-render(<NeedsAttentionList />);const buttons = await screen.findAllByRole("button", { name: /^Approve:/ });- await userEvent.click(buttons[0]);- await userEvent.click(buttons[1]);-- await waitFor(() => {- const [first, second] = screen.getAllByRole("button", {- name: /^Approve:/,- }) as HTMLButtonElement[];- // Both in flight -> both locked. A single pending slot would have- // re-enabled the first row here, making it double-submittable.- expect(first.disabled).toBe(true);- expect(second.disabled).toBe(true);- });+ try {+ await userEvent.click(buttons[0]);+ await userEvent.click(buttons[1]);+ await waitFor(() => {+ expect(buttons[0]).toHaveProperty("disabled", true);+ expect(buttons[1]).toHaveProperty("disabled", true);+ });+ finishSecond();+ await waitFor(() => {+ expect(buttons[1]).toHaveProperty("disabled", false);+ expect(buttons[0]).toHaveProperty("disabled", true);+ });+ } finally {+ finishFirst();+ finishSecond();+ await waitFor(() => {+ expect(buttons[0]).toHaveProperty("disabled", false);+ expect(buttons[1]).toHaveProperty("disabled", false);+ });+ }});diff --git a/autogpt_platform/frontend/src/types/react-dom-server-browser.d.ts b/autogpt_platform/frontend/src/types/react-dom-server-browser.d.tsnew file mode 100644index 0000000000..f4a665bef8--- /dev/null+++ b/autogpt_platform/frontend/src/types/react-dom-server-browser.d.ts@@ -0,0 +1,11 @@+// Next.js forbids importing "react-dom/server" from app-router modules; the+// browser build is the sanctioned way to render static markup from a route+// handler, but @types/react-dom only declares "./server".+declare module "react-dom/server.browser" {+ export {+ renderToString,+ renderToStaticMarkup,+ renderToReadableStream,+ version,+ } from "react-dom/server";+}