Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(agent): Agent avatars act out their runs and can be picked as a character (#23671)

Rdmclin2930fefdc53b9
diff --git a/package.json b/package.json
index 6c86cb15ed0..3f4c6d6cd1c 100644
--- a/package.json
+++ b/package.json
@@ -348,7 +348,7 @@
"@lobehub/icons": "^6.15.2",
"@lobehub/market-sdk": "0.46.0",
"@lobehub/tts": "^6.1.0",
- "@lobehub/ui": "^6.18.0",
+ "@lobehub/ui": "^6.19.0",
"@modelcontextprotocol/client": "~2.4.0",
"@modelcontextprotocol/ext-apps": "^2.0.3",
"@neondatabase/serverless": "^1.1.0",
diff --git a/src/components/AgentAvatar/HoverFollowAgentAvatar.tsx b/src/components/AgentAvatar/HoverFollowAgentAvatar.tsx
new file mode 100644
index 00000000000..1ca22d8c2c5
--- /dev/null
+++ b/src/components/AgentAvatar/HoverFollowAgentAvatar.tsx
@@ -0,0 +1,40 @@
+import { useState } from 'react';
+
+import AgentAvatar from './index';
+
+/**
+ * An Agent author's avatar in the message list: still until hovered, then it plays its idle loop
+ * and turns toward the pointer. A feed holds many of them, so only the hovered one animates.
+ */
+export function HoverFollowAgentAvatar({
+ agentId,
+ avatar,
+ name,
+ size,
+}: {
+ agentId: string;
+ avatar?: string | null;
+ name?: string | null;
+ size: number;
+}) {
+ const [hovered, setHovered] = useState(false);
+
+ return (
+ <span
+ data-hovered={hovered || undefined}
+ style={{ display: 'inline-flex' }}
+ onMouseEnter={() => setHovered(true)}
+ onMouseLeave={() => setHovered(false)}
+ >
+ <AgentAvatar
+ agentId={agentId}
+ animated={hovered}
+ avatar={avatar}
+ followPointer={hovered}
+ name={name}
+ shape={'circle'}
+ size={size}
+ />
+ </span>
+ );
+}
diff --git a/src/components/AgentAvatar/index.tsx b/src/components/AgentAvatar/index.tsx
index 470b8941910..028ff755d87 100644
--- a/src/components/AgentAvatar/index.tsx
+++ b/src/components/AgentAvatar/index.tsx
@@ -22,6 +22,11 @@ export interface AgentAvatarProps extends Omit<AvatarProps, 'avatar' | 'brokenFa
* legacy default image) draws the character generated from the id.
*/
avatar?: string | null;
+ /**
+ * Turn the generated character's eyes and body toward the pointer. Only applies while it is
+ * `animated`.
+ */
+ followPointer?: boolean;
/** Display name: labels the avatar and seeds the character when `agentId` is absent. */
name?: string | null;
/** Activity state of the generated character. */
@@ -40,6 +45,7 @@ const AgentAvatar = memo<AgentAvatarProps>(
avatar,
background,
className,
+ followPointer,
name,
onClick,
ref,
@@ -65,6 +71,7 @@ const AgentAvatar = memo<AgentAvatarProps>(
<GeneratedAgentAvatar
{...(resolved.kind === 'generated' ? resolved.choice : undefined)}
animated={animated}
+ followPointer={followPointer}
name={resolved.label}
seed={resolved.seed}
size={size}
diff --git a/src/components/AgentAvatar/pickerTab.test.ts b/src/components/AgentAvatar/pickerTab.test.ts
new file mode 100644
index 00000000000..060aa6d121c
--- /dev/null
+++ b/src/components/AgentAvatar/pickerTab.test.ts
@@ -0,0 +1,25 @@
+import { getAgentAvatarTraits } from '@lobehub/ui';
+import { describe, expect, it } from 'vitest';
+
+import { agentAvatarPickerDefault } from './pickerTab';
+
+describe('agentAvatarPickerDefault', () => {
+ it('opens on the character the agent picked', () => {
+ expect(agentAvatarPickerDefault('agent-avatar:rocket:cyan', 'agt_1')).toEqual({
+ color: 'cyan',
+ shape: 'rocket',
+ });
+ });
+
+ // Opening the picker on an empty selection would hide which character the agent wears now.
+ it('opens on the character its id generates when none was picked', () => {
+ const { color, shape } = getAgentAvatarTraits('agt_1');
+
+ expect(agentAvatarPickerDefault(undefined, 'agt_1')).toEqual({ color, shape });
+ expect(agentAvatarPickerDefault('🤖', 'agt_1')).toEqual({ color, shape });
+ });
+
+ it('has nothing to open on without a pick or an id', () => {
+ expect(agentAvatarPickerDefault(undefined)).toBeUndefined();
+ });
+});
diff --git a/src/components/AgentAvatar/pickerTab.tsx b/src/components/AgentAvatar/pickerTab.tsx
new file mode 100644
index 00000000000..c308132332b
--- /dev/null
+++ b/src/components/AgentAvatar/pickerTab.tsx
@@ -0,0 +1,42 @@
+'use client';
+
+import {
+ AgentAvatarPicker,
+ createAgentAvatarTab,
+ type EmojiPickerProps,
+ getAgentAvatarTraits,
+ parseAgentAvatar,
+ stringifyAgentAvatar,
+} from '@lobehub/ui';
+
+type EmojiPickerCustomTab = NonNullable<EmojiPickerProps['customTabs']>[number];
+
+/**
+ * The shape and color the picker opens on: the character the agent picked, else the one its id
+ * generates — so opening the picker shows what the agent wears now, not an empty selection.
+ */
+export const agentAvatarPickerDefault = (avatar?: string | null, agentId?: string | null) => {
+ const picked = parseAgentAvatar(avatar);
+ if (picked) return picked;
+ if (!agentId) return undefined;
+
+ const { color, shape } = getAgentAvatarTraits(agentId);
+ return { color, shape };
+};
+
+/**
+ * The `EmojiPicker` tab for picking an Agent's character. Same tab as `@lobehub/ui`'s
+ * `createAgentAvatarTab`, except that it opens on the character the agent wears now. A pick keeps
+ * the popup open so shapes and colors can be tried in a row; the value is an
+ * `agent-avatar:<shape>:<color>` string, drawn by `AgentAvatar`.
+ */
+export const createAgentCharacterTab = (agentId?: string | null): EmojiPickerCustomTab => ({
+ ...createAgentAvatarTab(),
+ render: (handleAvatarChange, avatar) => (
+ <AgentAvatarPicker
+ defaultValue={agentAvatarPickerDefault(avatar, agentId)}
+ style={{ width: 300 }}
+ onChange={(choice) => handleAvatarChange(stringifyAgentAvatar(choice), { keepOpen: true })}
+ />
+ ),
+});
diff --git a/src/features/AgentAvatarActivity/useAgentAvatarActivity.test.ts b/src/features/AgentAvatarActivity/useAgentAvatarActivity.test.ts
new file mode 100644
index 00000000000..97d5b200dfd
--- /dev/null
+++ b/src/features/AgentAvatarActivity/useAgentAvatarActivity.test.ts
@@ -0,0 +1,121 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useChatStore } from '@/store/chat';
+import type { Operation } from '@/store/chat/slices/operation/types';
+
+import { AGENT_AVATAR_DONE_MS, useAgentAvatarActivity } from './useAgentAvatarActivity';
+
+const setRun = (
+ status?: Operation['status'],
+ metadata?: Record<string, unknown>,
+ agentId = 'agent',
+) => {
+ const run = {
+ context: { agentId },
+ id: 'run',
+ metadata: { startTime: 1, ...metadata },
+ status,
+ type: 'execAgentRuntime',
+ } as unknown as Operation;
+ act(() => {
+ useChatStore.setState({
+ operations: status ? { run } : {},
+ operationsByType: (status ? { execAgentRuntime: ['run'] } : {}) as never,
+ });
+ });
+};
+
+describe('useAgentAvatarActivity', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ useChatStore.setState({ operations: {}, operationsByType: {} as never, topicDataMap: {} });
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('stays still until hovered, then idles and follows the pointer', () => {
+ const { result } = renderHook(() => useAgentAvatarActivity('agent'));
+ expect(result.current.avatar).toEqual({
+ animated: false,
+ followPointer: false,
+ state: undefined,
+ });
+
+ act(() => result.current.hover.onMouseEnter());
+ expect(result.current.avatar).toMatchObject({ animated: true, followPointer: true });
+
+ act(() => result.current.hover.onMouseLeave());
+ expect(result.current.avatar).toMatchObject({ animated: false, followPointer: false });
+ });
+
+ it('plays the run, celebrates a completed one briefly, then idles', () => {
+ const { result } = renderHook(() => useAgentAvatarActivity('agent'));
+
+ setRun('running');
+ expect(result.current.avatar).toMatchObject({ animated: true, state: 'working' });
+
+ setRun('completed');
+ expect(result.current.state).toBe('done');
+
+ act(() => {
+ vi.advanceTimersByTime(AGENT_AVATAR_DONE_MS);
+ });
+ expect(result.current.state).toBeUndefined();
+ expect(result.current.avatar.animated).toBe(false);
+ });
+
+ // A client run hides its loading state first and is marked completed a moment later.
+ it('celebrates a run that is marked completed after it stopped showing as busy', () => {
+ const { result } = renderHook(() => useAgentAvatarActivity('agent'));
+
+ setRun('running');
+ setRun('running', { visibleLoadingDone: true });
+ expect(result.current.state).toBeUndefined();
+
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+ setRun('completed', { visibleLoadingDone: true });
+ expect(result.current.state).toBe('done');
+ });
+
+ it('does not celebrate a run already completed before it mounted', () => {
+ setRun('completed');
+ const { result } = renderHook(() => useAgentAvatarActivity('agent'));
+ expect(result.current.state).toBeUndefined();
+ });
+
+ it('does not carry a celebration over to another Agent', () => {
+ const { rerender, result } = renderHook(({ id }) => useAgentAvatarActivity(id), {
+ initialProps: { id: 'agent' },
+ });
+ setRun('running');
+ setRun('completed');
+ expect(result.current.state).toBe('done');
+
+ rerender({ id: 'other' });
+ expect(result.current.state).toBeUndefined();
+ });
+
+ it('does not credit a running Agent with the completed run of the next one', () => {
+ const { rerender, result } = renderHook(({ id }) => useAgentAvatarActivity(id), {
+ initialProps: { id: 'agent' },
+ });
+ setRun('running');
+ expect(result.current.state).toBe('working');
+
+ setRun('completed', undefined, 'other');
+ rerender({ id: 'other' });
+ expect(result.current.state).toBeUndefined();
+ });
+
+ it.each(['failed', 'cancelled'] as const)('does not celebrate a %s run', (status) => {
+ const { result } = renderHook(() => useAgentAvatarActivity('agent'));
+
+ setRun('running');
+ setRun(status);
+ expect(result.current.state).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentAvatarActivity/useAgentAvatarActivity.ts b/src/features/AgentAvatarActivity/useAgentAvatarActivity.ts
new file mode 100644
index 00000000000..f8c4df3f9fd
--- /dev/null
+++ b/src/features/AgentAvatarActivity/useAgentAvatarActivity.ts
@@ -0,0 +1,76 @@
+import type { AgentAvatarState } from '@lobehub/ui';
+import { useEffect, useMemo, useRef, useState } from 'react';
+
+import { useChatStore } from '@/store/chat';
+import {
+ agentRunAvatarState,
+ isLatestAgentRunCompleted,
+} from '@/store/chat/slices/operation/agentRunAvatarState';
+
+/** How long a finished run celebrates (`done`: smiling eyes, two small hops) before idling. */
+export const AGENT_AVATAR_DONE_MS = 2400;
+
+/**
+ * How long after a run stops showing as busy it may still report how it ended. A client run hides
+ * its loading state before its operation is marked completed.
+ */
+export const AGENT_AVATAR_SETTLE_MS = 8000;
+
+const idle = () => undefined;
+const never = () => false;
+const isProducing = (state?: AgentAvatarState) => state === 'working' || state === 'thinking';
+
+/**
+ * What an Agent's avatar acts out, plus its hover: the avatar plays its run state, and otherwise
+ * idles and follows the pointer only while hovered, so a list of idle Agents stays still.
+ * `done` plays once, briefly, when a run finishes by itself.
+ */
+export const useAgentAvatarActivity = (agentId?: string | null) => {
+ const busy = useChatStore(agentId ? agentRunAvatarState(agentId) : idle);
+ const completed = useChatStore(agentId ? isLatestAgentRunCompleted(agentId) : never);
+ const [hovered, setHovered] = useState(false);
+ // Held per Agent: a shared surface such as the sidebar header changes `agentId` while mounted.
+ const [doneAgentId, setDoneAgentId] = useState<string | null>(null);
+ const done = !!agentId && doneAgentId === agentId;
+ const trackedAgentId = useRef(agentId);
+ const previous = useRef(busy);
+ const settlingUntil = useRef(0);
+
+ useEffect(() => {
+ const was = trackedAgentId.current === agentId ? previous.current : undefined;
+ if (trackedAgentId.current !== agentId) settlingUntil.current = 0;
+ trackedAgentId.current = agentId;
+ previous.current = busy;
+ if (busy) {
+ settlingUntil.current = 0;
+ setDoneAgentId(null);
+ return;
+ }
+ if (isProducing(was)) settlingUntil.current = Date.now() + AGENT_AVATAR_SETTLE_MS;
+ if (!completed || Date.now() > settlingUntil.current) return;
+
+ settlingUntil.current = 0;
+ setDoneAgentId(agentId ?? null);
+ }, [agentId, busy, completed]);
+
+ useEffect(() => {
+ if (!doneAgentId) return;
+ const timer = setTimeout(() => setDoneAgentId(null), AGENT_AVATAR_DONE_MS);
+ return () => clearTimeout(timer);
+ }, [doneAgentId]);
+
+ const state: AgentAvatarState | undefined = busy ?? (done ? 'done' : undefined);
+ const hover = useMemo(
+ () => ({
+ onMouseEnter: () => setHovered(true),
+ onMouseLeave: () => setHovered(false),
+ }),
+ [],
+ );
+
+ return {
+ avatar: { animated: !!state || hovered, followPointer: hovered, state },
+ hover,
+ state,
+ };
+};
diff --git a/src/features/AgentIdentityModal/CreateContent.tsx b/src/features/AgentIdentityModal/CreateContent.tsx
index 2b96e03e1fd..c6e522928b0 100644
--- a/src/features/AgentIdentityModal/CreateContent.tsx
+++ b/src/features/AgentIdentityModal/CreateContent.tsx
@@ -5,6 +5,7 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import AgentAvatar from '@/components/AgentAvatar';
+import { createAgentCharacterTab } from '@/components/AgentAvatar/pickerTab';
import EmojiPicker from '@/components/EmojiPicker';
import CreateVisibilityField, { useCreateVisibility } from '@/features/CreateVisibilityField';
import { useGlobalStore } from '@/store/global';
@@ -47,6 +48,7 @@ const CreateAgentIdentityContent = memo<CreateAgentIdentityContentProps>(
<EmojiPicker
allowUpload
allowDelete={!!form.avatar}
+ customTabs={[createAgentCharacterTab()]}
loading={form.uploading}
locale={locale}
popupProps={{ placement: 'bottom' }}
diff --git a/src/features/AgentProfileArtwork/index.test.tsx b/src/features/AgentProfileArtwork/index.test.tsx
new file mode 100644
index 00000000000..2ca08bf8059
--- /dev/null
+++ b/src/features/AgentProfileArtwork/index.test.tsx
@@ -0,0 +1,41 @@
+import { render } from '@testing-library/react';
+import { useEffect } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentProfileArtwork } from './index';
+
+const mounts = vi.hoisted(() => ({ count: 0 }));
+
+vi.mock('@/components/EmojiPicker', () => {
+ const MockEmojiPicker = () => {
+ useEffect(() => {
+ mounts.count += 1;
+ }, []);
+ return <div data-testid="picker" />;
+ };
+ return { default: MockEmojiPicker };
+});
+
+const props = {
+ agentId: 'agent',
+ canEdit: true,
+ locale: 'en-US',
+ onAvatarChange: vi.fn(),
+ onBackgroundChange: vi.fn(),
+};
+
+describe('AgentProfileArtwork', () => {
+ beforeEach(() => {
+ mounts.count = 0;
+ });
+
+ // A remount closes the popup, so picking a second shape or color would need reopening it.
+ it('keeps the avatar picker mounted while a character is picked', () => {
+ const { rerender } = render(<AgentProfileArtwork {...props} avatar="agent-avatar:cat:green" />);
+
+ rerender(<AgentProfileArtwork {...props} avatar="agent-avatar:rocket:green" />);
+ rerender(<AgentProfileArtwork {...props} avatar="agent-avatar:rocket:cyan" />);
+
+ expect(mounts.count).toBe(1);
+ });
+});
diff --git a/src/features/AgentProfileArtwork/index.tsx b/src/features/AgentProfileArtwork/index.tsx
index 5ae5ab96385..a2482039e62 100644
--- a/src/features/AgentProfileArtwork/index.tsx
+++ b/src/features/AgentProfileArtwork/index.tsx
@@ -25,6 +25,7 @@ import { memo, useCallback, useId, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import AgentAvatar from '@/components/AgentAvatar';
+import { createAgentCharacterTab } from '@/components/AgentAvatar/pickerTab';
import EmojiPicker from '@/components/EmojiPicker';
import {
openAgentArtworkStudio,
@@ -478,18 +479,15 @@ export const AgentProfileArtwork = memo<AgentProfileArtworkProps>(
) : null}
</div>
<div className={`${styles.avatar} agent-avatar-entry`}>
- {/* Uploading an image lives in the studio, so the picker keeps only
- emoji plus the studio launcher tab; the launcher tab is ordered
- first and auto-selected on open, preserving the old generate-tab
- position. */}
- {/* Keyed by the url for the same reason as the studio preview: the
- underlying Avatar latches its image-error state, so without a
- remount a newly generated avatar stays invisible whenever the
- previous one failed to load. */}
+ {/* Uploading an image lives in the studio, so the picker keeps the
+ character tab (first, and where it opens), emoji and the studio
+ launcher tab. */}
+ {/* Not keyed by the avatar: a remount would close the popup on every
+ character pick. The trigger's AgentAvatar resets a broken image
+ itself when the url changes. */}
<EmojiPicker
allowModelAvatar
allowDelete={canEdit && !!avatar}
- key={avatarRemountKey(avatar)}
locale={locale}
open={canEdit ? undefined : false}
popupClassName="agent-avatar-artwork-picker"
@@ -509,6 +507,7 @@ export const AgentProfileArtwork = memo<AgentProfileArtworkProps>(
/>
)}
customTabs={[
+ createAgentCharacterTab(agentId),
{
label: (
<Tooltip title={t('settingAgent.artwork.avatar.image')}>
@@ -540,14 +539,6 @@ export const AgentProfileArtwork = memo<AgentProfileArtworkProps>(
]}
onChange={(value) => onAvatarChange(value)}
onDelete={() => onAvatarChange(null)}
- onOpenChange={(open) => {
- if (!open) return;
-
- requestAnimationFrame(() => {
- const tabs = document.querySelectorAll('.agent-avatar-artwork-picker [role="tab"]');
- (tabs.item(tabs.length - 1) as HTMLElement | null)?.click();
- });
- }}
/>
{generating === 'avatar' ? (
<Center className={styles.avatarGenerating}>
diff --git a/src/features/AgentSidebar/Header/Agent/index.tsx b/src/features/AgentSidebar/Header/Agent/index.tsx
index 3d4295a5ad9..bfc077bb3e3 100644
--- a/src/features/AgentSidebar/Header/Agent/index.tsx
+++ b/src/features/AgentSidebar/Header/Agent/index.tsx
@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next';
import AgentAvatar from '@/components/AgentAvatar';
import { DEFAULT_INBOX_AVATAR } from '@/const/meta';
+import { useAgentAvatarActivity } from '@/features/AgentAvatarActivity/useAgentAvatarActivity';
import { SkeletonItem } from '@/features/NavPanel/components/SkeletonList';
import { useNavItemMetrics } from '@/features/NavPanel/density';
import { SidebarHeaderSelectTrigger } from '@/features/NavPanel/SidebarHeaderSelect';
@@ -28,6 +29,8 @@ const Agent = memo<PropsWithChildren>(() => {
agentSelectors.currentAgentBackgroundColor(s),
]);
+ const activity = useAgentAvatarActivity(agentId);
+
const displayTitle = isInbox
? title || DEFAULT_INBOX_TITLE
: title || t('defaultSession', { ns: 'common' });
@@ -41,6 +44,8 @@ const Agent = memo<PropsWithChildren>(() => {
title={displayTitle}
avatarNode={
<AgentAvatar
+ {...activity.avatar}
+ {...activity.hover}
agentId={agentId}
avatar={isInbox ? avatar || DEFAULT_INBOX_AVATAR : avatar}
background={backgroundColor || undefined}
diff --git a/src/features/AgentViewAll/SidebarItemAvatar.tsx b/src/features/AgentViewAll/SidebarItemAvatar.tsx
index 9524f8456e5..8a747d140f5 100644
--- a/src/features/AgentViewAll/SidebarItemAvatar.tsx
+++ b/src/features/AgentViewAll/SidebarItemAvatar.tsx
@@ -4,6 +4,7 @@ import { agentDisplayName, type SidebarAgentItem } from '@lobechat/types';
import { memo } from 'react';
import AgentAvatar from '@/components/AgentAvatar';
+import { useAgentAvatarActivity } from '@/features/AgentAvatarActivity/useAgentAvatarActivity';
import AgentGroupAvatar from '@/features/AgentGroupAvatar';
interface SidebarItemAvatarProps {
@@ -16,6 +17,7 @@ interface SidebarItemAvatarProps {
/** Agent avatar that renders the stacked group variant for group chats. */
const SidebarItemAvatar = memo<SidebarItemAvatarProps>(({ item, shape, size }) => {
const { avatar, backgroundColor, id, type } = item;
+ const activity = useAgentAvatarActivity(type === 'group' ? undefined : id);
return type === 'group' ? (
<AgentGroupAvatar
@@ -26,6 +28,8 @@ const SidebarItemAvatar = memo<SidebarItemAvatarProps>(({ item, shape, size }) =
/>
) : (
<AgentAvatar
+ {...activity.avatar}
+ {...activity.hover}
agentId={id}
avatar={typeof avatar === 'string' ? avatar : undefined}
background={backgroundColor || undefined}
diff --git a/src/features/Channels/ChannelMessage.tsx b/src/features/Channels/ChannelMessage.tsx
index 19c041612b9..ff022055532 100644
--- a/src/features/Channels/ChannelMessage.tsx
+++ b/src/features/Channels/ChannelMessage.tsx
@@ -25,6 +25,7 @@ import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import AgentAvatar from '@/components/AgentAvatar';
+import { HoverFollowAgentAvatar } from '@/components/AgentAvatar/HoverFollowAgentAvatar';
import CollapsibleContent from '@/components/CollapsibleContent';
import AgentProfilePopup from '@/features/AgentProfileCard/AgentProfilePopup';
import { ChatItem } from '@/features/Conversation/ChatItem';
@@ -258,11 +259,10 @@ export const ChannelMessage = ({
}}
>
<span style={{ cursor: 'pointer', display: 'inline-flex' }}>
- <AgentAvatar
+ <HoverFollowAgentAvatar
agentId={agentAuthorId}
avatar={message.author.avatar}
name={message.author.name}
- shape={'circle'}
size={36}
/>
</span>
diff --git a/src/features/Conversation/ChatItem/components/Avatar.tsx b/src/features/Conversation/ChatItem/components/Avatar.tsx
index e68588b4077..97b1c0b0c42 100644
--- a/src/features/Conversation/ChatItem/components/Avatar.tsx
+++ b/src/features/Conversation/ChatItem/components/Avatar.tsx
@@ -1,6 +1,6 @@
import { agentDisplayName } from '@lobechat/types';
import { type CSSProperties, type MouseEventHandler } from 'react';
-import { memo } from 'react';
+import { memo, useState } from 'react';
import AgentAvatar from '@/components/AgentAvatar';
import A from '@/components/Avatar';
@@ -25,6 +25,8 @@ const Avatar = memo<AvatarProps>(
({ agentId, loading, avatar, unoptimized, onClick, shape = 'square', size = 28, style, alt }) => {
const displayName = agentDisplayName(avatar);
const contextAgentId = useConversationStore(contextSelectors.agentId);
+ // A feed holds many of these, so only a generating or hovered character animates.
+ const [hovered, setHovered] = useState(false);
// A custom node (rather than an emoji or image URL) is rendered as given.
const agentAvatar =
@@ -37,16 +39,21 @@ const Avatar = memo<AvatarProps>(
<AgentAvatar
agentId={agentId || contextAgentId}
alt={alt || displayName}
+ animated={!!loading || hovered}
animation={loading}
avatar={agentAvatar}
background={avatar.backgroundColor}
+ followPointer={hovered}
name={displayName}
shape={shape}
size={size}
+ state={loading ? 'working' : undefined}
style={style}
title={displayName}
unoptimized={unoptimized}
onClick={onClick}
+ onMouseEnter={() => setHovered(true)}
+ onMouseLeave={() => setHovered(false)}
/>
);
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
index b0284d74974..943fc916e0b 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
@@ -8,8 +8,9 @@ import { type CSSProperties, type DragEvent } from 'react';
import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import AgentAvatar from '@/components/AgentAvatar';
+import AgentAvatar, { isGeneratedAgentAvatar } from '@/components/AgentAvatar';
import PrivateLockIcon from '@/components/PrivateLockIcon';
+import { useAgentAvatarActivity } from '@/features/AgentAvatarActivity/useAgentAvatarActivity';
import AgentProfilePopup from '@/features/AgentProfileCard/AgentProfilePopup';
import NavItem from '@/features/NavPanel/components/NavItem';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
@@ -106,6 +107,10 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate, se
// Separate loading state from chat store - only show loading for this specific agent
const isLoading = useChatStore(operationSelectors.isAgentVisiblyRunning(id));
+ // The row's hover wakes the character; a run plays on it without a hover.
+ const { avatar: avatarActivity, hover: rowHover } = useAgentAvatarActivity(id);
+ // A generated character acts the run out, so only an emoji or image needs the spinner.
+ const showRunningBadge = isLoading && !isGeneratedAgentAvatar(avatarUrl);
// Name-first label with fallback (see agentDisplayName)
const displayTitle = agentDisplayName(item, t('untitledAgent'));
@@ -118,7 +123,8 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate, se
// Memoize event handlers
const handleMouseEnter = useCallback(() => {
prefetchAgent(id);
- }, [id, prefetchAgent]);
+ rowHover.onMouseEnter();
+ }, [id, prefetchAgent, rowHover]);
const handleDoubleClick = useCallback(() => {
openAgentInNewWindow(id);
@@ -173,6 +179,7 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate, se
const avatarNode = (
<AgentAvatar
+ {...avatarActivity}
agentId={id}
avatar={avatarUrl}
background={backgroundColor || undefined}
@@ -192,7 +199,7 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate, se
>
<span {...stylex.props(styles.wrapper)}>
{avatarNode}
- {isLoading ? (
+ {showRunningBadge ? (
<span {...stylex.props(styles.runningBadge)}>
<Spin size={9} style={{ color: 'inherit' }} />
</span>
@@ -204,7 +211,8 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate, se
);
}, [
isUpdating,
- isLoading,
+ showRunningBadge,
+ avatarActivity,
id,
avatarUrl,
backgroundColor,
@@ -240,6 +248,7 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate, se
to={agentUrl}
onClick={onNavigate}
onMouseEnter={handleMouseEnter}
+ onMouseLeave={rowHover.onMouseLeave}
>
<NavItem
className={className}
diff --git a/src/routes/(main)/agent/features/Conversation/Header/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/index.tsx
index 644e577bcff..8888222849b 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/index.tsx
@@ -4,6 +4,7 @@ import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';
import { memo } from 'react';
import AgentAvatar from '@/components/AgentAvatar';
+import { useAgentAvatarActivity } from '@/features/AgentAvatarActivity/useAgentAvatarActivity';
import { AgentMigrationBadge, useAgentTransferJob } from '@/features/AgentTransferMigration';
import { useAgentContext } from '@/features/Conversation/useAgentContext';
import NavHeader from '@/features/NavHeader';
@@ -147,6 +148,8 @@ const Header = memo(() => {
// the rest of the migration UI, so this adds no extra polling.
const { data: transferJob } = useAgentTransferJob({ agentId });
+ const avatarActivity = useAgentAvatarActivity(splitView ? agentId : undefined);
+
return (
<div className={headerStyles.container}>
<NavHeader
@@ -160,6 +163,8 @@ const Header = memo(() => {
>
{splitView && agentMeta && (
<AgentAvatar
+ {...avatarActivity.avatar}
+ {...avatarActivity.hover}
agentId={agentId}
alt={agentMeta.title}
avatar={agentMeta.avatar}
diff --git a/src/routes/(main)/group/profile/features/MemberProfile/AgentHeader.tsx b/src/routes/(main)/group/profile/features/MemberProfile/AgentHeader.tsx
index 1f8f6c23905..dd85434ce45 100644
--- a/src/routes/(main)/group/profile/features/MemberProfile/AgentHeader.tsx
+++ b/src/routes/(main)/group/profile/features/MemberProfile/AgentHeader.tsx
@@ -18,6 +18,7 @@ import { memo, Suspense, useCallback, useEffect, useMemo, useState } from 'react
import { useTranslation } from 'react-i18next';
import AgentAvatar from '@/components/AgentAvatar';
+import { createAgentCharacterTab } from '@/components/AgentAvatar/pickerTab';
import { isDefaultAgentAvatar } from '@/components/AgentAvatar/resolve';
import EmojiPicker from '@/components/EmojiPicker';
import BackgroundSwatches from '@/features/AgentSetting/AgentMeta/BackgroundSwatches';
@@ -193,7 +194,7 @@ const AgentHeader = memo<AgentHeaderProps>(({ readOnly, disabled: disabledProp }
<SupervisorAvatar size={72} />
</Block>
)
- : // A character picked in Lobot is no emoji or image; the picker would print its text.
+ : // A picked character is no emoji or image; the picker would print its text.
parseAgentAvatar(agentMeta.avatar)
? () => (
<Block clickable height={72} width={72}>
@@ -203,6 +204,7 @@ const AgentHeader = memo<AgentHeaderProps>(({ readOnly, disabled: disabledProp }
: undefined
}
customTabs={[
+ createAgentCharacterTab(agentId),
{
label: (
<Tooltip title={t('settingAgent.backgroundColor.title', { ns: 'setting' })}>
diff --git a/src/store/chat/slices/operation/agentRunAvatarState.test.ts b/src/store/chat/slices/operation/agentRunAvatarState.test.ts
new file mode 100644
index 00000000000..d8aa3d816f1
--- /dev/null
+++ b/src/store/chat/slices/operation/agentRunAvatarState.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it } from 'vitest';
+
+import { type ChatStoreState } from '../../initialState';
+import { topicMapKey } from '../../utils/topicMapKey';
+import { agentRunAvatarState, isLatestAgentRunCompleted } from './agentRunAvatarState';
+import type { Operation } from './types';
+
+const op = (
+ id: string,
+ type: Operation['type'],
+ overrides: {
+ agentId?: string;
+ metadata?: Record<string, unknown>;
+ status?: Operation['status'];
+ topicId?: string;
+ } = {},
+) =>
+ ({
+ context: { agentId: overrides.agentId ?? 'agent', topicId: overrides.topicId },
+ id,
+ metadata: { startTime: 1, ...overrides.metadata },
+ status: overrides.status ?? 'running',
+ type,
+ }) as unknown as Operation;
+
+const store = (ops: Operation[], topics: { id: string; status: string }[] = []) => {
+ const operationsByType: Record<string, string[]> = {};
+ for (const item of ops) (operationsByType[item.type] ??= []).push(item.id);
+ return {
+ operations: Object.fromEntries(ops.map((item) => [item.id, item])),
+ operationsByType,
+ topicDataMap: { [topicMapKey({ agentId: 'agent' })]: { items: topics } },
+ } as unknown as ChatStoreState;
+};
+
+describe('agentRunAvatarState', () => {
+ it('is idle without a visible run', () => {
+ expect(agentRunAvatarState('agent')(store([]))).toBeUndefined();
+ expect(
+ agentRunAvatarState('agent')(
+ store([op('a', 'execAgentRuntime', { metadata: { visibleLoadingDone: true } })]),
+ ),
+ ).toBeUndefined();
+ expect(
+ agentRunAvatarState('agent')(
+ store([op('a', 'execAgentRuntime', { metadata: { isAborting: true } })]),
+ ),
+ ).toBeUndefined();
+ });
+
+ it('ignores the runs of other agents', () => {
+ expect(
+ agentRunAvatarState('agent')(store([op('a', 'execAgentRuntime', { agentId: 'other' })])),
+ ).toBeUndefined();
+ });
+
+ it.each(['execAgentRuntime', 'execHeterogeneousAgent', 'execServerAgentRuntime'] as const)(
+ 'works during %s',
+ (type) => {
+ expect(agentRunAvatarState('agent')(store([op('a', type)]))).toBe('working');
+ },
+ );
+
+ it('thinks while the run reasons', () => {
+ expect(
+ agentRunAvatarState('agent')(store([op('a', 'execAgentRuntime'), op('b', 'reasoning')])),
+ ).toBe('thinking');
+ });
+
+ it('is blocked while a topic waits for a person', () => {
+ expect(agentRunAvatarState('agent')(store([], [{ id: 't', status: 'waitingForHuman' }]))).toBe(
+ 'blocked',
+ );
+ });
+
+ it('reads a run paused on a person as blocked, not working', () => {
+ expect(
+ agentRunAvatarState('agent')(
+ store(
+ [op('a', 'execServerAgentRuntime', { topicId: 't' })],
+ [{ id: 't', status: 'waitingForHuman' }],
+ ),
+ ),
+ ).toBe('blocked');
+ });
+
+ it('keeps working when another topic is the one waiting', () => {
+ expect(
+ agentRunAvatarState('agent')(
+ store(
+ [op('a', 'execAgentRuntime', { topicId: 'busy' })],
+ [{ id: 'other', status: 'waitingForHuman' }],
+ ),
+ ),
+ ).toBe('working');
+ });
+});
+
+describe('isLatestAgentRunCompleted', () => {
+ it('follows the newest run', () => {
+ const older = op('a', 'execAgentRuntime', { metadata: { startTime: 1 }, status: 'failed' });
+ const newer = op('b', 'execAgentRuntime', { metadata: { startTime: 2 }, status: 'completed' });
+ expect(isLatestAgentRunCompleted('agent')(store([older, newer]))).toBe(true);
+ });
+
+ it.each(['failed', 'cancelled'] as const)('is false for a %s run', (status) => {
+ expect(
+ isLatestAgentRunCompleted('agent')(store([op('a', 'execAgentRuntime', { status })])),
+ ).toBe(false);
+ });
+
+ it('is false for a run stopped elsewhere, which is stored as completed', () => {
+ const stopped = op('a', 'execServerAgentRuntime', {
+ metadata: { endedWithoutCompletion: true },
+ status: 'completed',
+ });
+ expect(isLatestAgentRunCompleted('agent')(store([stopped]))).toBe(false);
+ });
+
+ it('is false without runs', () => {
+ expect(isLatestAgentRunCompleted('agent')(store([]))).toBe(false);
+ });
+});
diff --git a/src/store/chat/slices/operation/agentRunAvatarState.ts b/src/store/chat/slices/operation/agentRunAvatarState.ts
new file mode 100644
index 00000000000..d9167c6c1ed
--- /dev/null
+++ b/src/store/chat/slices/operation/agentRunAvatarState.ts
@@ -0,0 +1,55 @@
+import type { AgentAvatarState } from '@lobehub/ui';
+
+import { type ChatStoreState } from '../../initialState';
+import { topicMapKey } from '../../utils/topicMapKey';
+import { AI_RUNTIME_OPERATION_TYPES, type Operation } from './types';
+
+const isVisiblyRunning = (op: Operation) =>
+ op.status === 'running' && !op.metadata.isAborting && !op.metadata.visibleLoadingDone;
+
+const operationsOfType = (
+ s: ChatStoreState,
+ type: Operation['type'],
+ agentId: string,
+): Operation[] =>
+ (s.operationsByType[type] ?? []).flatMap((id) => {
+ const op = s.operations[id];
+ return op?.context.agentId === agentId ? [op] : [];
+ });
+
+/**
+ * What an Agent's avatar acts out for its runs: `thinking` while a run reasons, `working` while it
+ * runs otherwise, `blocked` when a topic waits for a person (a tool approval or a question).
+ * Undefined when nothing is pending. Only topics loaded on this client can report `blocked`.
+ */
+export const agentRunAvatarState =
+ (agentId: string) =>
+ (s: ChatStoreState): AgentAvatarState | undefined => {
+ const topics = s.topicDataMap[topicMapKey({ agentId })]?.items;
+ const isWaiting = (topicId?: string | null) =>
+ !!topicId && topics?.some((t) => t.id === topicId && t.status === 'waitingForHuman');
+
+ // A run paused on a person may keep its operation open; it is waiting, not working.
+ const running = AI_RUNTIME_OPERATION_TYPES.some((type) =>
+ operationsOfType(s, type, agentId).some(
+ (op) => isVisiblyRunning(op) && !isWaiting(op.context.topicId),
+ ),
+ );
+ if (running)
+ return operationsOfType(s, 'reasoning', agentId).some(isVisiblyRunning)
+ ? 'thinking'
+ : 'working';
+
+ return topics?.some((t) => t.status === 'waitingForHuman') ? 'blocked' : undefined;
+ };
+
+/** Whether the Agent's latest run finished by itself, rather than failing or being stopped. */
+export const isLatestAgentRunCompleted =
+ (agentId: string) =>
+ (s: ChatStoreState): boolean => {
+ const runs = AI_RUNTIME_OPERATION_TYPES.flatMap((type) => operationsOfType(s, type, agentId));
+ if (runs.length === 0) return false;
+ const latest = runs.reduce((a, b) => (b.metadata.startTime > a.metadata.startTime ? b : a));
+ // A run stopped from another tab, device or the API is stored as completed with this flag.
+ return latest.status === 'completed' && !latest.metadata.endedWithoutCompletion;
+ };