Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
feat(dify-ui): compose avatars and refine picker focus (#43939)
yyh0838e2511da0
diff --git a/packages/dify-ui/docs/authoring.md b/packages/dify-ui/docs/authoring.mdindex 41bd413164d..f838a443e4a 100644--- a/packages/dify-ui/docs/authoring.md+++ b/packages/dify-ui/docs/authoring.md@@ -41,9 +41,7 @@ public utility subpaths. Components share code through the owning component's enexplicit internal module, not another component's implementation files.Use the primitive name without a `Root` suffix for the canonical boundary and matching props type:-`Select` and `SelectProps`, `Drawer` and `DrawerProps`. Keep `Root` only when the same subpath-exports both low-level anatomy and a higher-level convenience component, such as `AvatarRoot`-and `Avatar`.+`Select` and `SelectProps`, `Drawer` and `DrawerProps`.Every runtime component must have an accurate, importable props type with the matching name. Use adirect alias for an unchanged Base UI part. Define Dify-authored composite props at the Dify UIdiff --git a/packages/dify-ui/src/avatar/__tests__/index.spec.tsx b/packages/dify-ui/src/avatar/__tests__/index.spec.tsxindex f959083425c..8dd8618906b 100644--- a/packages/dify-ui/src/avatar/__tests__/index.spec.tsx+++ b/packages/dify-ui/src/avatar/__tests__/index.spec.tsx@@ -1,76 +1,63 @@import { render } from 'vitest-browser-react'-import { Avatar } from '..'+import { Avatar, AvatarFallback, AvatarGroup, AvatarGroupCount, AvatarImage } from '..'const avatarDataUrl = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=='-function stubImageLoader() {- const originalImage = window.Image- const images: HTMLImageElement[] = []-- function TestImage(_width?: number, _height?: number): HTMLImageElement {- const image = {- complete: false,- crossOrigin: null,- naturalWidth: 0,- onerror: null,- onload: null,- referrerPolicy: '',- sizes: '',- src: '',- srcset: '',- } as unknown as HTMLImageElement- images.push(image)- return image- }-- Object.defineProperty(window, 'Image', {- configurable: true,- value: TestImage,- writable: true,- })-- return {- images,- restore: () => {- window.Image = originalImage- },- }-}--describe('Avatar', () => {- describe('Rendering', () => {- it('should render fallback with uppercase initial when avatar is null', async () => {- const screen = await render(<Avatar name="alice" avatar={null} />)-- expect(screen.container.querySelector('img')).not.toBeInTheDocument()- await expect.element(screen.getByText('A')).toBeInTheDocument()- })- })-- describe('onLoadingStatusChange', () => {- it('should show fallback until the image loads and forward status changes', async () => {- const { images, restore } = stubImageLoader()- const onStatusChange = vi.fn()-- try {- const screen = await render(- <Avatar name="John" avatar={avatarDataUrl} onLoadingStatusChange={onStatusChange} />,- )-- await expect.element(screen.getByText('J')).toBeVisible()- await vi.waitFor(() => {- expect(onStatusChange).toHaveBeenCalledWith('loading')- })-- images.at(-1)?.onload?.(new Event('load'))+it('shares the group size through wrappers and keeps explicit avatar sizes', async () => {+ const screen = await render(+ <AvatarGroup size="sm">+ <button type="button" aria-label="Open Alice">+ <Avatar aria-hidden="true">+ <AvatarFallback>A</AvatarFallback>+ </Avatar>+ </button>+ <Avatar size="xs" role="img" aria-label="Bob">+ <AvatarFallback>B</AvatarFallback>+ </Avatar>+ <AvatarGroupCount role="img" aria-label="2 more people">+ +2+ </AvatarGroupCount>+ </AvatarGroup>,+ )++ const button = screen.getByRole('button', { name: 'Open Alice' }).element()+ const fallback = screen.getByText('A').element()+ const avatar = fallback.parentElement!+ expect(avatar.getBoundingClientRect().width).toBe(24)+ expect(fallback.getBoundingClientRect().width).toBe(24)+ expect(getComputedStyle(button).borderWidth).toBe('0px')+ expect(getComputedStyle(button).boxShadow).toBe('none')+ expect(getComputedStyle(avatar).boxShadow).not.toBe('none')+ expect(screen.getByRole('img', { name: 'Bob' }).element().getBoundingClientRect().width).toBe(20)+ expect(+ screen.getByRole('img', { name: '2 more people' }).element().getBoundingClientRect().width,+ ).toBe(24)+})- await vi.waitFor(() => {- expect(onStatusChange).toHaveBeenCalledWith('loaded')- })- await expect.element(screen.getByRole('img', { name: 'John' })).toBeVisible()- } finally {- restore()- }- })+it('keeps a failed mounted image from covering the fallback and displays its replacement', async () => {+ const screen = await render(+ <Avatar role="img" aria-label="Alice">+ <AvatarFallback>A</AvatarFallback>+ <AvatarImage keepMounted src="data:image/png;base64,broken" alt="" />+ </Avatar>,+ )++ await expect.element(screen.getByText('A')).toBeVisible()+ const image = screen.container.querySelector('img')!+ await vi.waitFor(() => {+ expect(image).not.toBeVisible()+ expect(image.getBoundingClientRect().width).toBeGreaterThan(0)})+ await expect.element(screen.getByRole('img', { name: 'Alice' })).toBeVisible()++ await screen.rerender(+ <Avatar role="img" aria-label="Alice">+ <AvatarFallback>A</AvatarFallback>+ <AvatarImage keepMounted src={avatarDataUrl} alt="" />+ </Avatar>,+ )++ await vi.waitFor(() => expect(image).toBeVisible())+ await expect.element(screen.getByText('A')).not.toBeInTheDocument()+ await expect.element(screen.getByRole('img', { name: 'Alice' })).toBeVisible()})diff --git a/packages/dify-ui/src/avatar/index.stories.tsx b/packages/dify-ui/src/avatar/index.stories.tsxindex d54b8a243ab..cf6c9c1dee3 100644--- a/packages/dify-ui/src/avatar/index.stories.tsx+++ b/packages/dify-ui/src/avatar/index.stories.tsx@@ -1,84 +1,137 @@import type { Meta, StoryObj } from '@storybook/react-vite'-import { Avatar, AvatarFallback, AvatarRoot } from '.'+import { expect, waitFor, within } from 'storybook/test'+import { Avatar, AvatarFallback, AvatarGroup, AvatarGroupCount, AvatarImage } from '.'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuLinkItem,+ DropdownMenuTrigger,+} from '../dropdown-menu'+import { IconButton } from '../icon-button'++const avatarUrl = 'https://i.pravatar.cc/96?u=avatar-default'const meta = {title: 'Base/UI/Avatar',component: Avatar,+ subcomponents: { AvatarImage, AvatarFallback, AvatarGroup, AvatarGroupCount },parameters: {docs: {description: {- component:- 'Initials or image-based avatar built on Base UI. Falls back to the first letter when the image fails to load.',- },- source: {- language: 'tsx',- code: `-<Avatar name="Alex Doe" avatar="https://i.pravatar.cc/96?u=avatar-default" size="xl" />- `.trim(),+ component: `Compose an image and fallback inside Avatar. Import these components and their matching props types from \`@langgenius/dify-ui/avatar\`.++| Part | Responsibility |+| --- | --- |+| \`Avatar\` | Styles Base UI Root and owns the shared size. Defaults to \`md\` (32px). |+| \`AvatarImage\` | Uses Base UI image loading, error handling, and source changes. Accepts native image props, \`keepMounted\`, and \`onLoadingStatusChange\`. |+| \`AvatarFallback\` | Owns the default background and displays caller-provided content while the image is unavailable. Inherits size from Avatar and supports Base UI \`delay\`. |+| \`AvatarGroup\` | Dify visual extension for overlapping children by 4px. Avatars and counts use a 1px panel ring, including inside wrappers. Supplies their default size; explicit child sizes win. Callers control stacking with \`z-index\`. |+| \`AvatarGroupCount\` | Dify visual extension for caller-provided overflow text such as \`+2\`. Inherits Group size, or defaults to \`md\` (32px) outside a group, matching Avatar. |++Without an explicit size, children inherit the enclosing group's size or fall back to \`md\`. Override a grouped ring with \`group-[&]/avatar-group:ring-0\`; ring colors use ordinary \`ring-*\` classes.++The first three parts preserve Base UI \`render\`, refs, and state-aware \`className\` / \`style\` props. See the [Base UI Avatar documentation](https://base-ui.com/react/components/avatar) for their underlying API. Group and GroupCount accept native span props; they do not expose Base UI render or state callbacks.++Callers own names, initial extraction, colors, and image URLs. Apply custom fallback colors to AvatarFallback; Avatar has no default background, so transparent images retain their transparency. For an independent identity, give Avatar \`role="img"\` and the full name through \`aria-label\`, with an empty image \`alt\`. This keeps the accessible name stable when the image fails. When adjacent text or the surrounding control already identifies the person, hide the avatar with \`aria-hidden="true"\`.++Group only owns presentation. Callers choose which avatars to show, compute overflow, localize its label, and provide any interaction. It renders children unchanged, including arrays and fragments. Give earlier avatars a higher \`z-index\` when they should overlap later avatars.`,},},},tags: ['autodocs'],- args: {- name: 'Alex Doe',- avatar: 'https://i.pravatar.cc/96?u=avatar-default',- size: 'xl',+ argTypes: {+ size: {+ control: 'select',+ options: ['xxs', 'xs', 'sm', 'md', 'lg', 'xl', '2xl', '3xl'],+ description: 'Shared image and fallback size: 16, 20, 24, 32, 36, 40, 48, or 64px.',+ table: { defaultValue: { summary: 'md' } },+ },},+ args: { size: 'xl' },+ render: (args) => (+ <Avatar {...args} role="img" aria-label="Alex Doe">+ <AvatarFallback>A</AvatarFallback>+ <AvatarImage src={avatarUrl} alt="" />+ </Avatar>+ ),} satisfies Meta<typeof Avatar>export default metatype Story = StoryObj<typeof meta>-export const Default: Story = {}+export const Default: Story = {+ parameters: {+ docs: {+ description: {+ story: 'A standalone identity with a stable accessible name. The example uses xl (40px).',+ },+ source: {+ code: `import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'-export const WithFallback: Story = {- args: {- avatar: null,- name: 'Fallback',+<Avatar size="xl" role="img" aria-label="Alex Doe">+ <AvatarFallback>A</AvatarFallback>+ <AvatarImage src="https://i.pravatar.cc/96?u=avatar-default" alt="" />+</Avatar>`,+ },+ },},+}++export const WithFallback: Story = {parameters: {docs: {- source: {- language: 'tsx',- code: `-<Avatar name="Fallback" avatar={null} size="xl" />- `.trim(),+ description: {+ story:+ 'An image is optional. Supply initials or an icon as fallback content; Avatar does not derive them from a name. The same fallback appears when an image fails.',},},},+ render: (args) => (+ <Avatar {...args} role="img" aria-label="Alex Doe">+ <AvatarFallback>A</AvatarFallback>+ </Avatar>+ ),}export const AllSizes: Story = {- render: (args) => (+ parameters: {+ docs: {+ description: {+ story: 'Set size on Avatar. Image dimensions and fallback typography follow the root.',+ },+ },+ },+ render: () => (<div className="flex items-end gap-4">{(['xxs', 'xs', 'sm', 'md', 'lg', 'xl', '2xl', '3xl'] as const).map((size) => (<div key={size} className="flex flex-col items-center gap-2">- <Avatar {...args} size={size} avatar="https://i.pravatar.cc/96?u=size-test" />+ <Avatar size={size} role="img" aria-label="Alex Doe">+ <AvatarFallback>A</AvatarFallback>+ <AvatarImage src={avatarUrl} alt="" />+ </Avatar><span className="text-xs text-text-tertiary">{size}</span></div>))}</div>),+}++export const AllFallbackSizes: Story = {parameters: {docs: {- source: {- language: 'tsx',- code: `-{(['xxs', 'xs', 'sm', 'md', 'lg', 'xl', '2xl', '3xl'] as const).map(size => (- <Avatar key={size} name="Size Test" size={size} avatar="https://i.pravatar.cc/96?u=size-test" />-))}- `.trim(),+ description: {+ story:+ 'Fallback typography across all eight sizes. AvatarFallback has no independent size prop.',},},},-}--export const AllFallbackSizes: Story = {- render: (args) => (+ render: () => (<div className="flex items-end gap-4">{(['xxs', 'xs', 'sm', 'md', 'lg', 'xl', '2xl', '3xl'] as const).map((size) => (<div key={size} className="flex flex-col items-center gap-2">- <Avatar {...args} size={size} avatar={null} name="Alex" />+ <Avatar size={size} role="img" aria-label="Alex Doe">+ <AvatarFallback>A</AvatarFallback>+ </Avatar><span className="text-xs text-text-tertiary">{size}</span></div>))}@@ -86,26 +139,138 @@ export const AllFallbackSizes: Story = {),}-export const ComposedFallback: Story = {+export const Decorative: Story = {+ parameters: {+ docs: {+ description: {+ story:+ 'The adjacent name already identifies the person. Hide the entire avatar to avoid announcing the name or initial twice.',+ },+ },+ },+ render: (args) => (+ <div className="flex items-center gap-2">+ <Avatar {...args} aria-hidden="true">+ <AvatarFallback>A</AvatarFallback>+ <AvatarImage src={avatarUrl} alt="" />+ </Avatar>+ <span>Alex Doe</span>+ </div>+ ),+}++export const LazyImage: Story = {+ parameters: {+ docs: {+ description: {+ story:+ 'Combine keepMounted with native loading="lazy" so the browser can load the rendered image. Place Fallback before Image. Dify hides loading and failed images with visibility: hidden, preserving their layout for lazy loading. Base UI owns loading status and fallback visibility.',+ },+ },+ },+ render: (args) => (+ <Avatar {...args} role="img" aria-label="Alex Doe">+ <AvatarFallback>A</AvatarFallback>+ <AvatarImage keepMounted loading="lazy" src={avatarUrl} alt="" />+ </Avatar>+ ),+}++export const Group: Story = {+ parameters: {+ docs: {+ description: {+ story:+ 'Dify adds Group and GroupCount; they are not Base UI Avatar parts. This Design Kit example uses sm (24px): three avatars and one count overlap by 4px for a total width of 84px. Group supplies the shared sm size; the caller supplies the stacking order, +2, and its accessible label; the group does not slice a member list or calculate the count.',+ },+ },+ },render: () => (- <AvatarRoot size="xl">- <AvatarFallback size="xl" style={{ backgroundColor: '#2563eb' }}>- C- </AvatarFallback>- </AvatarRoot>+ <AvatarGroup size="sm">+ <Avatar role="img" aria-label="Alex Doe" className="z-30">+ <AvatarFallback>A</AvatarFallback>+ <AvatarImage src={avatarUrl} alt="" />+ </Avatar>+ <Avatar role="img" aria-label="Emma" className="z-20">+ <AvatarFallback className="bg-components-icon-bg-blue-solid">E</AvatarFallback>+ </Avatar>+ <Avatar role="img" aria-label="Sam" className="z-10">+ <AvatarFallback className="bg-components-icon-bg-orange-dark-solid">S</AvatarFallback>+ </Avatar>+ <AvatarGroupCount role="img" aria-label="2 more people">+ +2+ </AvatarGroupCount>+ </AvatarGroup>),+}++const collaborators = [+ { name: 'Emma', initial: 'E', color: 'bg-components-icon-bg-blue-solid', href: '#emma' },+ { name: 'Sam', initial: 'S', color: 'bg-components-icon-bg-orange-dark-solid', href: '#sam' },+ { name: 'Robin', initial: 'R', color: 'bg-components-icon-bg-teal-solid', href: '#robin' },+ { name: 'Alex', initial: 'A', color: 'bg-components-icon-bg-midnight-solid', href: '#alex' },+]++export const Collaborators: Story = {parameters: {docs: {- source: {- language: 'tsx',- code: `-<AvatarRoot size="xl">- <AvatarFallback size="xl" style={{ backgroundColor: '#2563eb' }}>- C- </AvatarFallback>-</AvatarRoot>- `.trim(),+ description: {+ story:+ 'A Design Kit collaborator control: 24px avatars inside a rounded panel button with a 12px chevron. Compose the trigger with IconButton through render to retain button styling and cursor behavior. This capsule supplies its own dimensions instead of an IconButton square size. DropdownMenu owns keyboard navigation, expanded state, and focus restoration; the avatars inside its named trigger are decorative. The example links represent collaborator profiles.',},},},+ render: () => (+ <div className="flex min-h-32 items-center justify-center rounded-xl bg-background-section p-8">+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <IconButton+ aria-label="View 4 collaborators"+ variant="secondary"+ size={null}+ className="rounded-2xl bg-components-panel-bg-blur py-1 pr-1.5 pl-1 inset-ring-components-panel-border hover:bg-components-panel-bg hover:inset-ring-components-panel-border data-popup-open:bg-components-panel-bg"+ >+ <span aria-hidden="true" className="inline-flex items-center gap-px">+ <AvatarGroup size="sm">+ {collaborators.slice(0, 2).map((person, index) => (+ <Avatar key={person.name} style={{ zIndex: 2 - index }}>+ <AvatarFallback className={`${person.color} text-[13px] font-semibold`}>+ <span className="bg-linear-to-b from-components-avatar-shape-fill-stop-0 to-components-avatar-shape-fill-stop-100 bg-clip-text text-transparent opacity-90">+ {person.initial}+ </span>+ </AvatarFallback>+ </Avatar>+ ))}+ <AvatarGroupCount>+{collaborators.length - 2}</AvatarGroupCount>+ </AvatarGroup>+ <span className="i-ri-arrow-down-s-line size-3 text-text-tertiary" />+ </span>+ </IconButton>+ }+ />+ <DropdownMenuContent>+ {collaborators.map((person) => (+ <DropdownMenuLinkItem key={person.name} href={person.href}>+ <Avatar size="sm" aria-hidden="true">+ <AvatarFallback className={person.color}>{person.initial}</AvatarFallback>+ </Avatar>+ {person.name}+ </DropdownMenuLinkItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ ),+ play: async ({ canvas, canvasElement, userEvent }) => {+ const trigger = canvas.getByRole('button', { name: 'View 4 collaborators' })+ trigger.focus()+ await userEvent.keyboard('{Enter}')+ const body = within(canvasElement.ownerDocument.body)+ await expect(await body.findByRole('menuitem', { name: 'Emma' })).toBeVisible()+ await expect(trigger).toHaveAttribute('aria-expanded', 'true')+ await userEvent.keyboard('{Escape}')+ await waitFor(() => expect(trigger).toHaveFocus())+ await expect(trigger).toHaveAttribute('aria-expanded', 'false')+ },}diff --git a/packages/dify-ui/src/avatar/index.tsx b/packages/dify-ui/src/avatar/index.tsxindex bb7528bc5ee..4d33646b682 100644--- a/packages/dify-ui/src/avatar/index.tsx+++ b/packages/dify-ui/src/avatar/index.tsx@@ -1,57 +1,52 @@'use client'+import type { VariantProps } from 'class-variance-authority'+import type * as React from 'react'import { Avatar as BaseAvatar } from '@base-ui/react/avatar'+import { cva } from 'class-variance-authority'import { cn } from '../cn'import { resolveClassName } from '../internal/resolve-class-name'-const avatarSizeClasses = {- xxs: { root: 'size-4', text: 'text-[7px]' },- xs: { root: 'size-5', text: 'text-[8px]' },- sm: { root: 'size-6', text: 'text-[10px]' },- md: { root: 'size-8', text: 'text-xs' },- lg: { root: 'size-9', text: 'text-sm' },- xl: { root: 'size-10', text: 'text-base' },- '2xl': { root: 'size-12', text: 'text-xl' },- '3xl': { root: 'size-16', text: 'text-2xl' },-} as const+const avatarSizeVariants = cva('', {+ variants: {+ size: {+ xxs: '[--avatar-font-size:7px] [--avatar-size:--spacing(4)]',+ xs: '[--avatar-font-size:8px] [--avatar-size:--spacing(5)]',+ sm: '[--avatar-font-size:10px] [--avatar-size:--spacing(6)]',+ md: '[--avatar-font-size:var(--text-xs)] [--avatar-size:--spacing(8)]',+ lg: '[--avatar-font-size:var(--text-sm)] [--avatar-size:--spacing(9)]',+ xl: '[--avatar-font-size:var(--text-base)] [--avatar-size:--spacing(10)]',+ '2xl': '[--avatar-font-size:var(--text-xl)] [--avatar-size:--spacing(12)]',+ '3xl': '[--avatar-font-size:var(--text-2xl)] [--avatar-size:--spacing(16)]',+ },+ },+})-type AvatarSize = keyof typeof avatarSizeClasses+const avatarClassName =+ 'relative inline-flex size-[var(--avatar-size,--spacing(8))] shrink-0 items-center justify-center overflow-hidden rounded-full align-middle text-[length:var(--avatar-font-size,var(--text-xs))] ring-components-panel-bg select-none group-[&]/avatar-group:ring-1'-type AvatarProps = Pick<BaseAvatar.Image.Props, 'onLoadingStatusChange'> & {- name: string- avatar: string | null- size?: AvatarSize- className?: string-}+type AvatarSize = NonNullable<VariantProps<typeof avatarSizeVariants>['size']>+type AvatarProps = BaseAvatar.Root.Props & { size?: AvatarSize }-type AvatarRootProps = BaseAvatar.Root.Props & {- size?: AvatarSize-}-function AvatarRoot({ size = 'md', className, ...props }: AvatarRootProps) {+function Avatar({ size, className, ...props }: AvatarProps) {return (<BaseAvatar.RootclassName={(state) =>- cn(- 'relative inline-flex shrink-0 items-center justify-center overflow-hidden rounded-full bg-primary-600 select-none',- avatarSizeClasses[size].root,- resolveClassName(className, state),- )+ cn(avatarClassName, avatarSizeVariants({ size }), resolveClassName(className, state))}{...props}/>)}-type AvatarFallbackProps = BaseAvatar.Fallback.Props & {- size?: AvatarSize-}-function AvatarFallback({ size = 'md', className, ...props }: AvatarFallbackProps) {+type AvatarFallbackProps = BaseAvatar.Fallback.Props++function AvatarFallback({ className, ...props }: AvatarFallbackProps) {return (<BaseAvatar.FallbackclassName={(state) =>cn(- 'flex size-full items-center justify-center font-medium text-white',- avatarSizeClasses[size].text,+ 'absolute inset-0 flex size-full items-center justify-center bg-primary-600 font-medium text-white',resolveClassName(className, state),)}@@ -61,28 +56,62 @@ function AvatarFallback({ size = 'md', className, ...props }: AvatarFallbackProp}type AvatarImageProps = BaseAvatar.Image.Props+function AvatarImage({ className, ...props }: AvatarImageProps) {return (<BaseAvatar.ImageclassName={(state) =>- cn('absolute inset-0 size-full object-cover', resolveClassName(className, state))+ cn(+ 'absolute inset-0 size-full object-cover data-error:invisible data-loading:invisible',+ resolveClassName(className, state),+ )}{...props}/>)}-function Avatar({ name, avatar, size = 'md', className, onLoadingStatusChange }: AvatarProps) {+type AvatarGroupProps = React.ComponentProps<'span'> & { size?: AvatarSize }++function AvatarGroup({ size, className, ...props }: AvatarGroupProps) {return (- <AvatarRoot size={size} className={className}>- {avatar && (- <AvatarImage src={avatar} alt={name} onLoadingStatusChange={onLoadingStatusChange} />+ <span+ className={cn(+ 'group/avatar-group isolate inline-flex items-center -space-x-1 align-middle',+ avatarSizeVariants({ size }),+ className,)}- <AvatarFallback size={size}>{name?.[0]?.toLocaleUpperCase()}</AvatarFallback>- </AvatarRoot>+ {...props}+ />)}-export { Avatar, AvatarFallback, AvatarImage, AvatarRoot }+type AvatarGroupCountProps = React.ComponentProps<'span'> & { size?: AvatarSize }++function AvatarGroupCount({ size, className, children, ...props }: AvatarGroupCountProps) {+ return (+ <span+ className={cn(+ avatarClassName,+ avatarSizeVariants({ size }),+ 'bg-components-icon-bg-midnight-solid',+ className,+ )}+ {...props}+ >+ <span className="bg-linear-to-b from-components-avatar-shape-fill-stop-0 to-components-avatar-shape-fill-stop-100 bg-clip-text font-semibold text-transparent opacity-90">+ {children}+ </span>+ </span>+ )+}-export type { AvatarFallbackProps, AvatarImageProps, AvatarProps, AvatarRootProps, AvatarSize }+export { Avatar, AvatarFallback, AvatarGroup, AvatarGroupCount, AvatarImage }+export type {+ AvatarFallbackProps,+ AvatarGroupCountProps,+ AvatarGroupProps,+ AvatarImageProps,+ AvatarProps,+ AvatarSize,+}diff --git a/packages/dify-ui/src/checkbox/index.tsx b/packages/dify-ui/src/checkbox/index.tsxindex 588d33c7ebd..1fcaec57aea 100644--- a/packages/dify-ui/src/checkbox/index.tsx+++ b/packages/dify-ui/src/checkbox/index.tsx@@ -52,9 +52,7 @@ function Checkbox({ className, ...props }: CheckboxProps) {)}-type CheckboxSkeletonProps = Omit<React.ComponentProps<'div'>, 'className'> & {- className?: string-}+type CheckboxSkeletonProps = React.ComponentProps<'div'>function CheckboxSkeleton({ className, ...props }: CheckboxSkeletonProps) {return <div className={cn(checkboxSkeletonClassName, className)} {...props} />diff --git a/packages/dify-ui/src/date-time/date-picker/__tests__/behavior.spec.tsx b/packages/dify-ui/src/date-time/date-picker/__tests__/behavior.spec.tsxindex cce8a7681a0..d80b0109a03 100644--- a/packages/dify-ui/src/date-time/date-picker/__tests__/behavior.spec.tsx+++ b/packages/dify-ui/src/date-time/date-picker/__tests__/behavior.spec.tsx@@ -318,6 +318,25 @@ it('opens on the allowed month and retains a visible focus target if every date.toHaveFocus()})+it('focuses the month title after applying a month with no available dates', async () => {+ const screen = await render(+ <DatePicker defaultValue="2025-01-15" isDateUnavailable={(date) => date.startsWith('2025-02')}>+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <Parts />+ </DatePicker>,+ )+ await screen.getByRole('button', { name: 'Date Jan 15, 2025' }).click()+ await screen.getByRole('button', { name: 'Choose month and year: January 2025' }).click()+ await screen.getByRole('option', { name: 'February' }).click()+ await expect.element(screen.getByRole('option', { name: 'February' })).toHaveFocus()+ await screen.getByRole('button', { name: 'OK' }).click()++ await expect.element(screen.getByRole('grid', { name: 'February 2025' })).toBeInTheDocument()+ await expect+ .element(screen.getByRole('button', { name: 'Choose month and year: February 2025' }))+ .toHaveFocus()+})+it('keeps adjacent-month dates selectable by pointer', async () => {const screen = await render(<DatePicker defaultValue="2025-01-15">diff --git a/packages/dify-ui/src/date-time/date-time-picker/__tests__/index.spec.tsx b/packages/dify-ui/src/date-time/date-time-picker/__tests__/index.spec.tsxindex 5ff2a0ff554..b6b0cfc509d 100644--- a/packages/dify-ui/src/date-time/date-time-picker/__tests__/index.spec.tsx+++ b/packages/dify-ui/src/date-time/date-time-picker/__tests__/index.spec.tsx@@ -168,6 +168,29 @@ it.each(['ltr', 'rtl'] as const)()describe('DateTimePicker', () => {+ it('focuses the selected day on opening and after returning from the time view', async () => {+ const screen = await render(+ <DateTimePicker timeZone="UTC" defaultValue={new Date('2025-01-15T13:30:00Z')}>+ <DateTimePickerLabel className="sr-only">Meeting</DateTimePickerLabel>+ <DateTimePickerTrigger />+ <DateTimePickerContent />+ </DateTimePicker>,+ )+ await screen.getByRole('button', { name: 'Meeting Jan 15, 2025, 1:30 PM' }).click()+ const selectedDay = screen.getByRole('button', {+ name: 'Wednesday, January 15th, 2025, selected',+ })+ await expect.element(selectedDay).toHaveFocus()++ await screen.getByRole('button', { name: 'Pick Time: 1:30 PM' }).click()+ await expect+ .element(screen.getByRole('listbox', { name: 'Hour' }).getByRole('option', { name: '1' }))+ .toHaveFocus()+ await screen.getByRole('button', { name: 'Pick Date' }).click()++ await expect.element(selectedDay).toHaveFocus()+ })+it('discards a draft on Escape and leaves the existing instant unchanged on OK', async () => {const original = new Date('2024-11-03T06:30:00.000Z')const onValueChange = vi.fn()diff --git a/packages/dify-ui/src/date-time/date-time-picker/index.tsx b/packages/dify-ui/src/date-time/date-time-picker/index.tsxindex f1613effcab..2d6b7d1b7a7 100644--- a/packages/dify-ui/src/date-time/date-time-picker/index.tsx+++ b/packages/dify-ui/src/date-time/date-time-picker/index.tsx@@ -210,16 +210,17 @@ function Session() {setDisplayMonth(getInitialMonth(next.date, minDate, maxDate))}const errorId = React.useId()- React.useEffect(() => {- const frame = requestAnimationFrame(() => {- const target =- ref.current?.querySelector<HTMLElement>(- '[role="grid"] button[tabindex="0"], [role="option"][aria-selected="true"]',- ) ?? ref.current?.querySelector<HTMLElement>('button:not(:disabled)')- target?.focus({ preventScroll: true })- target?.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'instant' })- })- return () => cancelAnimationFrame(frame)+ const previousViewRef = React.useRef(view)+ React.useLayoutEffect(() => {+ // PickerContent owns initial focus; this effect handles only internal view changes.+ if (previousViewRef.current === view) return+ previousViewRef.current = view+ const target =+ ref.current?.querySelector<HTMLElement>(+ '[role="grid"] button[tabindex="0"], [role="option"][aria-selected="true"]',+ ) ?? ref.current?.querySelector<HTMLElement>('button:not(:disabled)')+ target?.focus({ preventScroll: true })+ target?.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'instant' })}, [view])function changeView(next: 'date' | 'time') {ref.current?.closest<HTMLElement>('[role="dialog"]')?.focus({ preventScroll: true })diff --git a/packages/dify-ui/src/date-time/internal/calendar-panel.tsx b/packages/dify-ui/src/date-time/internal/calendar-panel.tsxindex 866caad87fc..28c3d1aab25 100644--- a/packages/dify-ui/src/date-time/internal/calendar-panel.tsx+++ b/packages/dify-ui/src/date-time/internal/calendar-panel.tsx@@ -52,13 +52,18 @@ function CalendarPanel({const [focusCalendar, setFocusCalendar] = React.useState(false)const panelRef = React.useRef<HTMLDivElement>(null)const headerRef = React.useRef<HTMLButtonElement>(null)- React.useEffect(() => {- if (choosingMonth || !focusCalendar) return- const frame = requestAnimationFrame(() => {- if (!panelRef.current?.querySelector('[role="grid"] button[tabindex="0"]'))- headerRef.current?.focus()- })- return () => cancelAnimationFrame(frame)+ const restoreHeaderFocusRef = React.useRef(false)+ React.useLayoutEffect(() => {+ if (choosingMonth) return+ if (restoreHeaderFocusRef.current) {+ restoreHeaderFocusRef.current = false+ headerRef.current?.focus()+ } else if (+ focusCalendar &&+ !panelRef.current?.querySelector('[role="grid"] button[tabindex="0"]')+ ) {+ headerRef.current?.focus()+ }}, [choosingMonth, focusCalendar])const year = Number(draftMonth.slice(0, 4))const month = Number(draftMonth.slice(5, 7))@@ -101,10 +106,10 @@ function CalendarPanel({function finish(apply: boolean) {if (apply && outOfBounds(draftMonth)) returnfocusPopup()+ restoreHeaderFocusRef.current = !applysetFocusCalendar(apply)if (apply) onDisplayMonthChange(draftMonth)setMonthPickerHeight(null)- if (!apply) requestAnimationFrame(() => headerRef.current?.focus())}const monthTrigger = (<Buttondiff --git a/packages/dify-ui/src/date-time/internal/option-column.tsx b/packages/dify-ui/src/date-time/internal/option-column.tsxindex affaec2e5f4..265e80ebef2 100644--- a/packages/dify-ui/src/date-time/internal/option-column.tsx+++ b/packages/dify-ui/src/date-time/internal/option-column.tsx@@ -121,14 +121,11 @@ function OptionColumn({if (selected) scrollToOption(selected)}, [scrollRequest, cancelGesture, scrollToOption])- React.useEffect(() => {+ React.useLayoutEffect(() => {if (!focusOnMount) return- const frame = requestAnimationFrame(() =>- ref.current- ?.querySelector<HTMLElement>('[aria-selected="true"]')- ?.focus({ preventScroll: true }),- )- return () => cancelAnimationFrame(frame)+ ref.current+ ?.querySelector<HTMLElement>('[aria-selected="true"]')+ ?.focus({ preventScroll: true })}, [focusOnMount])function focusValue(next: number, smooth = false) {diff --git a/packages/dify-ui/src/pagination/__tests__/index.spec.tsx b/packages/dify-ui/src/pagination/__tests__/index.spec.tsxindex ae852ccee51..4fb86988edb 100644--- a/packages/dify-ui/src/pagination/__tests__/index.spec.tsx+++ b/packages/dify-ui/src/pagination/__tests__/index.spec.tsx@@ -195,42 +195,69 @@ describe('Pagination primitive', () => {.toBeInTheDocument()})- it('commits the page input editing mode with Enter', async () => {- const { screen } = await renderPagination()+ it.each([+ {+ name: 'Enter and restores summary focus',+ key: 'Enter',+ focusedButton: 'Edit page number, current page 2 of 200',+ },+ { name: 'Tab and moves focus forward', key: 'Tab', focusedButton: 'Next page' },+ ])('commits the edited page with $name', async ({ key, focusedButton }) => {+ const { screen, onPageChange } = await renderPagination()await screen.getByRole('button', { name: 'Edit page number, current page 2 of 200' }).click()- await expect.element(screen.getByRole('textbox', { name: 'Page number' })).toBeInTheDocument()- const input = asHTMLElement(- screen.getByRole('textbox', { name: 'Page number' }).element(),- ) as HTMLInputElement+ const input = screen.getByRole('textbox', { name: 'Page number' })+ await input.fill('7')+ await expect.element(input).toHaveFocus()+ const inputElement = input.element()+ expect(onPageChange).not.toHaveBeenCalled()- await vi.waitFor(() => {- expect(document.activeElement).toBe(input)- })+ await userEvent.keyboard(`{${key}}`)- await userEvent.keyboard('{Enter}')+ expect(onPageChange).toHaveBeenCalledExactlyOnceWith(7)+ await expect.element(screen.getByRole('button', { name: focusedButton })).toHaveFocus()+ expect(inputElement).not.toBeInTheDocument()+ })- const summaryButton = screen.getByRole('button', {- name: 'Edit page number, current page 2 of 200',- })- await expect.element(summaryButton).toBeInTheDocument()- await vi.waitFor(() => {- expect(document.activeElement).toBe(summaryButton.element())- })+ it('commits the edited page without interrupting an outside button click', async () => {+ const onPageChange = vi.fn()+ const onClick = vi.fn()+ const screen = await render(+ <React.Fragment>+ <PaginationRoot page={2} totalPages={200} onPageChange={onPageChange}>+ <PaginationPageJump />+ </PaginationRoot>+ <button type="button" onClick={onClick}>+ Outside action+ </button>+ </React.Fragment>,+ )++ await screen.getByRole('button', { name: 'Edit page number, current page 2 of 200' }).click()+ const input = screen.getByRole('textbox', { name: 'Page number' })+ await input.fill('7')+ await expect.element(input).toHaveFocus()+ expect(onPageChange).not.toHaveBeenCalled()+ expect(onClick).not.toHaveBeenCalled()++ const outsideButton = screen.getByRole('button', { name: 'Outside action' })+ await outsideButton.click()++ expect(onPageChange).toHaveBeenCalledExactlyOnceWith(7)+ expect(onClick).toHaveBeenCalledOnce()+ await expect.element(outsideButton).toHaveFocus()+ await expect+ .element(screen.getByRole('button', { name: 'Edit page number, current page 2 of 200' }))+ .toBeInTheDocument()})it('cancels the page input editing mode with Escape', async () => {const { screen, onPageChange } = await renderPagination()await screen.getByRole('button', { name: 'Edit page number, current page 2 of 200' }).click()- await expect.element(screen.getByRole('textbox', { name: 'Page number' })).toBeInTheDocument()- const input = asHTMLElement(- screen.getByRole('textbox', { name: 'Page number' }).element(),- ) as HTMLInputElement-- await vi.waitFor(() => {- expect(document.activeElement).toBe(input)- })+ const input = screen.getByRole('textbox', { name: 'Page number' })+ await input.fill('7')+ await expect.element(input).toHaveFocus()await userEvent.keyboard('{Escape}')diff --git a/packages/dify-ui/src/pagination/index.tsx b/packages/dify-ui/src/pagination/index.tsxindex 6f0f7e5d662..e2d25b3726f 100644--- a/packages/dify-ui/src/pagination/index.tsx+++ b/packages/dify-ui/src/pagination/index.tsx@@ -1,7 +1,6 @@'use client'import { Button as BaseButton } from '@base-ui/react/button'-import { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect'import * as React from 'react'import { cn } from '../cn'import { focusRingClassName } from '../internal/focus'@@ -315,7 +314,7 @@ function PaginationPageJump({const restoreSummaryFocusRef = React.useRef(false)const mergedSummaryRef = useMergedRefs(summaryButtonRef, ref)- useIsoLayoutEffect(() => {+ React.useLayoutEffect(() => {if (editing || !restoreSummaryFocusRef.current) returnrestoreSummaryFocusRef.current = false@@ -355,11 +354,8 @@ function PaginationPageJump({// oxlint-disable-next-line jsx-a11y/no-autofocus -- Editing starts after an explicit user action and focus must move to the replacement input.autoFocusclassName="px-2 py-1.5 text-center system-xs-medium tabular-nums"- onBlur={() => requestAnimationFrame(() => setEditing(false))}- onFocus={(event) => {- const input = event.currentTarget- requestAnimationFrame(() => input.select())- }}+ onBlur={() => setEditing(false)}+ onFocus={(event) => event.currentTarget.select()}onKeyDown={(event) => {if (event.key === 'Enter') {event.preventDefault()diff --git a/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx b/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsxindex 4f577a4fc37..3c8a72bf434 100644--- a/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx+++ b/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx@@ -3,7 +3,7 @@import type { AvatarProps } from '@langgenius/dify-ui/avatar'import type { ImageIconInputValue } from '@/app/components/base/icon-picker/image-input'import type { ImageFile } from '@/types/app'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { Button } from '@langgenius/dify-ui/button'import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'import { Separator } from '@langgenius/dify-ui/separator'@@ -16,9 +16,16 @@ import { useLocalFileUploader } from '@/app/components/base/image-uploader/hooksimport { toast } from '@/app/notifications'import { DISABLE_UPLOAD_IMAGE_AS_ICON } from '@/config'import { consoleQuery } from '@/service/console'+import { getAvatarInitial } from '@/utils/avatar'import { createAvatarImageFile, createCroppedAvatarImage } from './avatar-image'-const AvatarWithEdit = (props: AvatarProps) => {+type AvatarWithEditProps = {+ avatar: string | null+ name: string+ size?: AvatarProps['size']+}++const AvatarWithEdit = ({ avatar, name, size }: AvatarWithEditProps) => {const { t } = useTranslation(['app', 'common'])const { mutateAsync: updateProfile } = useMutation(consoleQuery.account.profile.patch.mutationOptions(),@@ -29,8 +36,7 @@ const AvatarWithEdit = (props: AvatarProps) => {const [uploading, setUploading] = useState(false)const [isShowDeleteConfirm, setIsShowDeleteConfirm] = useState(false)- const [onAvatarError, setOnAvatarError] = useState(false)- const canDeleteAvatar = !!props.avatar && !onAvatarError+ const canDeleteAvatar = !!avatarconst handleSaveAvatar = useCallback(async (uploadedFileId: string) => {@@ -89,7 +95,14 @@ const AvatarWithEdit = (props: AvatarProps) => {handleLocalFileUpload(file)}, [handleLocalFileUpload, inputImageInfo])- if (DISABLE_UPLOAD_IMAGE_AS_ICON) return <Avatar {...props} />+ if (DISABLE_UPLOAD_IMAGE_AS_ICON) {+ return (+ <Avatar size={size} aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(name)}</AvatarFallback>+ <AvatarImage src={avatar || undefined} alt="" />+ </Avatar>+ )+ }return (<>@@ -103,10 +116,10 @@ const AvatarWithEdit = (props: AvatarProps) => {setIsShowAvatarPicker(true)}}>- <Avatar- {...props}- onLoadingStatusChange={(status) => setOnAvatarError(status === 'error')}- />+ <Avatar size={size} aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(name)}</AvatarFallback>+ <AvatarImage src={avatar || undefined} alt="" />+ </Avatar><span className="pointer-events-none absolute inset-0 flex items-center justify-center rounded-full bg-black/50 text-white opacity-0 group-hover:opacity-100 motion-safe:transition-opacity"><span aria-hidden="true" className="i-ri-pencil-line size-5" /></span>diff --git a/web/app/account/(commonLayout)/account-page/__tests__/AvatarWithEdit.spec.tsx b/web/app/account/(commonLayout)/account-page/__tests__/AvatarWithEdit.spec.tsxindex f137813984c..ae579b16f91 100644--- a/web/app/account/(commonLayout)/account-page/__tests__/AvatarWithEdit.spec.tsx+++ b/web/app/account/(commonLayout)/account-page/__tests__/AvatarWithEdit.spec.tsx@@ -1,7 +1,7 @@import type { ImageIconInputProps } from '@/app/components/base/icon-picker/image-input'import type { ImageFile } from '@/types/app'import { QueryClientProvider } from '@tanstack/react-query'-import { render, screen, waitFor } from '@testing-library/react'+import { act, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { createTestQueryClient } from '@/test/query-client'import { TransferMethod } from '@/types/app'@@ -149,9 +149,24 @@ describe('AvatarWithEdit', () => {await expect(request.json()).resolves.toEqual({ avatar: uploadedAvatar.fileId })})- it('clears the avatar through the account profile endpoint', async () => {+ it('clears a saved avatar even after its image fails to load', async () => {+ const images: HTMLImageElement[] = []+ const NativeImage = window.Image+ const imageLoader = vi.spyOn(window, 'Image').mockImplementation(+ class extends NativeImage {+ constructor() {+ super()+ images.push(this)+ }+ },+ )const user = userEvent.setup()- renderAvatar('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==')+ renderAvatar('https://example.com/broken.png')+ await waitFor(() => expect(images.length).toBeGreaterThan(0))+ await act(async () => {+ for (const image of images) image.dispatchEvent(new Event('error'))+ })+ imageLoader.mockRestore()await user.click(screen.getByRole('button', { name: /avatar\.editAction/i }))await user.click(screen.getByRole('button', { name: /operation\.delete/i }))diff --git a/web/app/account/(commonLayout)/avatar.tsx b/web/app/account/(commonLayout)/avatar.tsxindex eb499f5ddad..4fa8730bb86 100644--- a/web/app/account/(commonLayout)/avatar.tsx+++ b/web/app/account/(commonLayout)/avatar.tsx@@ -1,5 +1,5 @@'use client'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'import {DropdownMenu,@@ -13,6 +13,7 @@ import PremiumBadge from '@/app/components/base/premium-badge'import { userProfileQueryOptions } from '@/features/account-profile/client'import { consoleQuery } from '@/service/console'import { useLogout } from '@/service/use-common'+import { getAvatarInitial } from '@/utils/avatar'export default function AppSelector() {const { t } = useTranslation(['common'])@@ -44,7 +45,10 @@ export default function AppSelector() {'hover:opacity-80 active:opacity-70 data-popup-open:opacity-80',)}>- <Avatar avatar={userProfile.avatar_url} name={userProfile.name} />+ <Avatar aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>+ <AvatarImage src={userProfile.avatar_url || undefined} alt="" />+ </Avatar></DropdownMenuTrigger><DropdownMenuContentplacement="bottom-end"@@ -67,7 +71,10 @@ export default function AppSelector() {{userProfile.email}</div></div>- <Avatar avatar={userProfile.avatar_url} name={userProfile.name} />+ <Avatar aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>+ <AvatarImage src={userProfile.avatar_url || undefined} alt="" />+ </Avatar></div></div><div className="p-1">diff --git a/web/app/account/oauth/authorize/page.tsx b/web/app/account/oauth/authorize/page.tsxindex 080f1258f77..2bcf2c00871 100644--- a/web/app/account/oauth/authorize/page.tsx+++ b/web/app/account/oauth/authorize/page.tsx@@ -1,6 +1,6 @@'use client'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { Button, buttonVariants } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import {@@ -22,6 +22,7 @@ import Link from '@/next/link'import { useRouter, useSearchParams } from '@/next/navigation'import { consoleQuery } from '@/service/console'import { useLogout } from '@/service/use-common'+import { getAvatarInitial } from '@/utils/avatar'import { buildOAuthCallbackUrl, buildReturnUrl, useSilentAuthorize } from './use-silent-authorize'export default function OAuthAuthorize() {@@ -197,7 +198,10 @@ export default function OAuthAuthorize() {{isLoggedIn && userProfile && (<div className="flex items-center justify-between rounded-xl bg-background-section-burn-inverted p-3"><div className="flex items-center gap-2.5">- <Avatar avatar={userProfile.avatar_url} name={userProfile.name} size="lg" />+ <Avatar size="lg" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>+ <AvatarImage src={userProfile.avatar_url || undefined} alt="" />+ </Avatar><div><div className="text-text-secondary">{userProfile.name}</div><div className="system-xs-regular text-text-tertiary">{userProfile.email}</div>diff --git a/web/app/components/access-rules-editor/add-access-subject-menu.tsx b/web/app/components/access-rules-editor/add-access-subject-menu.tsxindex e78419fc033..597acfb2233 100644--- a/web/app/components/access-rules-editor/add-access-subject-menu.tsx+++ b/web/app/components/access-rules-editor/add-access-subject-menu.tsx@@ -1,6 +1,6 @@'use client'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import {@@ -19,6 +19,7 @@ import { memo } from 'react'import { useTranslation } from 'react-i18next'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import { consoleQuery } from '@/service/console'+import { getAvatarInitial } from '@/utils/avatar'import { DEFAULT_ACCESS_POLICY_ID } from './constants'type AddAccessSubjectMenuProps = {@@ -97,14 +98,12 @@ function AddAccessSubjectMenuContent({)}onClick={() => onAddAccessSubject(member.id, [DEFAULT_ACCESS_POLICY_ID])}>- <span aria-hidden="true" className="shrink-0">- <Avatar- avatar={member.avatar_url ?? member.avatar ?? null}- name={memberName}- size="sm"- className="bg-components-icon-bg-blue-solid"- />- </span>+ <Avatar size="sm" aria-hidden="true">+ <AvatarFallback className="bg-components-icon-bg-blue-solid">+ {getAvatarInitial(memberName)}+ </AvatarFallback>+ <AvatarImage src={(member.avatar_url ?? member.avatar) || undefined} alt="" />+ </Avatar><span className="min-w-0 flex-1"><span className="block truncate system-sm-medium text-text-secondary">{memberName}diff --git a/web/app/components/access-rules-editor/user-access-policy-row.tsx b/web/app/components/access-rules-editor/user-access-policy-row.tsxindex eea9df6bcbd..e2ac9187ea4 100644--- a/web/app/components/access-rules-editor/user-access-policy-row.tsx+++ b/web/app/components/access-rules-editor/user-access-policy-row.tsx@@ -1,7 +1,7 @@'use client'import type { ResourceUserAccessPolicies } from '@dify/contracts/api/console/workspaces/types.gen'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { Checkbox } from '@langgenius/dify-ui/checkbox'import { cn } from '@langgenius/dify-ui/cn'import {@@ -15,6 +15,7 @@ import {} from '@langgenius/dify-ui/select'import { memo, useCallback } from 'react'import { useTranslation } from 'react-i18next'+import { getAvatarInitial } from '@/utils/avatar'import { ACCESS_RULE_TABLE_GRID, DEFAULT_ACCESS_POLICY_ID } from './constants'import { isWorkspaceAdminRole } from './is-workspace-admin-role'@@ -90,12 +91,12 @@ function UserAccessPolicyRow({disabled={isSelectionDisabled}onCheckedChange={(checked) => onSelectedChange?.(accountId, checked)}/>- <Avatar- avatar={setting.account.avatar ?? null}- name={accountName}- size="md"- className="bg-components-icon-bg-blue-solid"- />+ <Avatar size="md" aria-hidden="true">+ <AvatarFallback className="bg-components-icon-bg-blue-solid">+ {getAvatarInitial(accountName)}+ </AvatarFallback>+ <AvatarImage src={setting.account.avatar || undefined} alt="" />+ </Avatar><div className="min-w-0"><div className="flex min-w-0 items-center gap-1.5"><span className="truncate system-md-medium text-text-secondary">{accountName}</span>diff --git a/web/app/components/app/app-access-control/add-member-or-group-pop/subject-item.tsx b/web/app/components/app/app-access-control/add-member-or-group-pop/subject-item.tsxindex a9d90d4385e..75741cc0031 100644--- a/web/app/components/app/app-access-control/add-member-or-group-pop/subject-item.tsx+++ b/web/app/components/app/app-access-control/add-member-or-group-pop/subject-item.tsx@@ -8,7 +8,7 @@ import type {SubjectAccount,SubjectGroup,} from '@/models/access-control'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback } from '@langgenius/dify-ui/avatar'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { Toggle } from '@langgenius/dify-ui/toggle'@@ -16,6 +16,7 @@ import { useSuspenseQuery } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'import { userProfileQueryOptions } from '@/features/account-profile/client'import { SubjectType } from '@/models/access-control'+import { getAvatarInitial } from '@/utils/avatar'type SubjectItemProps = {subject: Subject@@ -109,7 +110,9 @@ function MemberItem({<SubjectToggleButton selected={selected} onToggle={onToggle} className="pr-3"><div className="mr-2 size-5 shrink-0 overflow-hidden rounded-full bg-components-icon-bg-blue-solid"><div className="bg-access-app-icon-mask-bg flex size-full items-center justify-center">- <Avatar size="xxs" avatar={null} name={member.name} />+ <Avatar size="xxs" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(member.name)}</AvatarFallback>+ </Avatar></div></div><span className="mr-1 min-w-0 truncate system-sm-medium text-text-secondary">diff --git a/web/app/components/app/app-access-control/specific-groups-or-members.tsx b/web/app/components/app/app-access-control/specific-groups-or-members.tsxindex 1e9ce0f67e5..d8ad836a81f 100644--- a/web/app/components/app/app-access-control/specific-groups-or-members.tsx+++ b/web/app/components/app/app-access-control/specific-groups-or-members.tsx@@ -1,11 +1,12 @@'use client'import type { AccessControlAccount, AccessControlGroup } from '@/models/access-control'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback } from '@langgenius/dify-ui/avatar'import { Button } from '@langgenius/dify-ui/button'import { IconButton } from '@langgenius/dify-ui/icon-button'import { useTranslation } from 'react-i18next'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import { AccessMode } from '@/models/access-control'+import { getAvatarInitial } from '@/utils/avatar'import AddMemberOrGroupDialog from './add-member-or-group-pop'export type AccessControlSubjects = {@@ -178,7 +179,14 @@ type MemberItemProps = {function MemberItem({ member, onRemove }: MemberItemProps) {return (- <BaseItem icon={<Avatar size="xxs" avatar={null} name={member.name} />} onRemove={onRemove}>+ <BaseItem+ icon={+ <Avatar size="xxs" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(member.name)}</AvatarFallback>+ </Avatar>+ }+ onRemove={onRemove}+ ><p className="system-xs-regular text-text-primary">{member.name}</p></BaseItem>)diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/chat-item.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/chat-item.tsxindex 7b01d82c8f3..48d6ed13a4f 100644--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/chat-item.tsx+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/chat-item.tsx@@ -2,7 +2,7 @@ import type { FC } from 'react'import type { ModelAndParameter } from '../types'import type { InputForm } from '@/app/components/base/chat/chat/type'import type { ChatConfig, OnSend } from '@/app/components/base/chat/types'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { useQuery, useSuspenseQuery } from '@tanstack/react-query'import { memo, useCallback, useMemo } from 'react'import { toast } from '@/app/components/app/configuration/toast'@@ -23,6 +23,7 @@ import {fetchSuggestedQuestions,stopChatMessageResponding,} from '@/service/debug'+import { getAvatarInitial } from '@/utils/avatar'import { matchesProviderReference } from '@/utils/provider-reference'import { useConfigFromDebugContext, useFormattingChangedSubscription } from '../hooks'import { APP_CHAT_WITH_MULTIPLE_MODEL, APP_CHAT_WITH_MULTIPLE_MODEL_RESTART } from '../types'@@ -167,7 +168,12 @@ const ChatItem: FC<ChatItemProps> = ({ modelAndParameter }) => {suggestedQuestions={suggestedQuestions}onSend={doSend}onOpenLog={onOpenLog}- questionIcon={<Avatar avatar={userProfile.avatar_url} name={userProfile.name} size="xl" />}+ questionIcon={+ <Avatar size="xl" role="img" aria-label={userProfile.name}>+ <AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>+ <AvatarImage src={userProfile.avatar_url || undefined} alt="" />+ </Avatar>+ }allToolIcons={allToolIcons}noSpacing/>diff --git a/web/app/components/app/configuration/debug/debug-with-single-model/index.tsx b/web/app/components/app/configuration/debug/debug-with-single-model/index.tsxindex ab115352c08..7234903ae1a 100644--- a/web/app/components/app/configuration/debug/debug-with-single-model/index.tsx+++ b/web/app/components/app/configuration/debug/debug-with-single-model/index.tsx@@ -2,7 +2,7 @@ import type { Ref } from 'react'import type { IChatItem, InputForm } from '@/app/components/base/chat/chat/type'import type { ChatConfig, ChatItem, OnSend } from '@/app/components/base/chat/types'import type { FileEntity } from '@/app/components/base/file-uploader/types'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { useSuspenseQuery } from '@tanstack/react-query'import { memo, useCallback, useImperativeHandle, useMemo } from 'react'import { toast } from '@/app/components/app/configuration/toast'@@ -17,6 +17,7 @@ import {fetchSuggestedQuestions,stopChatMessageResponding,} from '@/service/debug'+import { getAvatarInitial } from '@/utils/avatar'import { matchesProviderReference } from '@/utils/provider-reference'import { useConfigFromDebugContext, useFormattingChangedSubscription } from '../hooks'@@ -201,7 +202,12 @@ const DebugWithSingleModel = ({onStopResponding={handleStop}onOpenLog={onOpenLog}chatContainerRef={chatContainerRef}- questionIcon={<Avatar avatar={userProfile.avatar_url} name={userProfile.name} size="xl" />}+ questionIcon={+ <Avatar size="xl" role="img" aria-label={userProfile.name}>+ <AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>+ <AvatarImage src={userProfile.avatar_url || undefined} alt="" />+ </Avatar>+ }allToolIcons={allToolIcons}onAnnotationEdited={canManageAnnotation ? handleAnnotationEdited : undefined}onAnnotationAdded={canManageAnnotation ? handleAnnotationAdded : undefined}diff --git a/web/app/components/apps/__tests__/creators-filter.spec.tsx b/web/app/components/apps/__tests__/creators-filter.spec.tsxindex 2b16f309643..0cecea6cff9 100644--- a/web/app/components/apps/__tests__/creators-filter.spec.tsx+++ b/web/app/components/apps/__tests__/creators-filter.spec.tsx@@ -25,6 +25,8 @@ vi.mock('@/service/use-common', () => ({{ id: 'member-2', name: 'Alice', avatar_url: null, status: 'active' },{ id: 'member-3', name: 'Bob', avatar_url: null, status: 'active' },{ id: 'member-4', name: 'Pending User', avatar_url: null, status: 'pending' },+ { id: 'member-5', name: 'Charlie', avatar_url: null, status: 'active' },+ { id: 'member-6', name: 'Robin', avatar_url: null, status: 'active' },],},}),@@ -46,6 +48,8 @@ describe('CreatorsFilter', () => {expect(options.map((option) => option.textContent)).toEqual([expect.stringContaining('Alice'),expect.stringContaining('Bob'),+ expect.stringContaining('Charlie'),+ expect.stringContaining('Robin'),expect.stringContaining('Zoe'),])expect(screen.getByText('app.studio.filters.you')).toBeInTheDocument()@@ -117,9 +121,45 @@ describe('CreatorsFilter', () => {const trigger = screen.getByRole('combobox', { name: 'app.studio.filters.creators' })const selectedCount = within(trigger).getByText('common.dynamicSelect.selected:{"count":2}')expect(selectedCount).toHaveClass('sr-only')- expect(within(trigger).getByText('+2').parentElement).toHaveAttribute('aria-hidden', 'true')+ expect(within(trigger).queryByText(/^\+\d+$/)).not.toBeInTheDocument()})+ it.each([+ { value: ['member-2'], visibleInitials: ['A'], remainingCount: 0 },+ {+ value: ['member-2', 'member-3', 'member-1'],+ visibleInitials: ['A', 'B', 'Z'],+ remainingCount: 0,+ },+ {+ value: ['member-2', 'member-3', 'member-1', 'member-5'],+ visibleInitials: ['A', 'B', 'Z'],+ remainingCount: 1,+ },+ {+ value: ['member-2', 'member-3', 'member-1', 'member-5', 'member-6'],+ visibleInitials: ['A', 'B', 'Z'],+ remainingCount: 2,+ },+ ])(+ 'shows only the $remainingCount undisplayed creators in the overflow count',+ ({ value, visibleInitials, remainingCount }) => {+ render(<CreatorsFilter value={value} onChange={mockOnChange} />)++ const trigger = screen.getByRole('combobox', { name: 'app.studio.filters.creators' })+ for (const initial of visibleInitials) {+ expect(within(trigger).getByText(initial, { exact: true })).toBeInTheDocument()+ }+ expect(within(trigger).queryByText('C', { exact: true })).not.toBeInTheDocument()+ expect(within(trigger).queryByText('R', { exact: true })).not.toBeInTheDocument()+ if (remainingCount > 0) {+ expect(within(trigger).getByText(`+${remainingCount}`)).toBeInTheDocument()+ } else {+ expect(within(trigger).queryByText(/^\+\d+$/)).not.toBeInTheDocument()+ }+ },+ )+it('should expose the creator picker as a named combobox with keyboard-owned options', async () => {const user = userEvent.setup()render(<CreatorsFilter value={[]} onChange={mockOnChange} />)diff --git a/web/app/components/apps/__tests__/list.spec.tsx b/web/app/components/apps/__tests__/list.spec.tsxindex 88fce2a74c6..d9d08e617a0 100644--- a/web/app/components/apps/__tests__/list.spec.tsx+++ b/web/app/components/apps/__tests__/list.spec.tsx@@ -1168,7 +1168,7 @@ describe('List', () => {})describe('Creators Filter', () => {- it('should handle creator selection', async () => {+ it('should show the selected creator without an overflow count', async () => {const user = userEvent.setup()renderList()@@ -1176,7 +1176,11 @@ describe('List', () => {await user.click(trigger)await user.click(screen.getByRole('option', { name: /Bob/ }))- expect(trigger).toHaveTextContent('+1')+ expect(within(trigger).getByText('B')).toBeInTheDocument()+ expect(+ within(trigger).getByText('common.dynamicSelect.selected:{"count":1}'),+ ).toBeInTheDocument()+ expect(within(trigger).queryByText(/^\+\d+$/)).not.toBeInTheDocument()})})diff --git a/web/app/components/apps/creators-filter.tsx b/web/app/components/apps/creators-filter.tsxindex 22c2652ce5f..3cb382a6060 100644--- a/web/app/components/apps/creators-filter.tsx+++ b/web/app/components/apps/creators-filter.tsx@@ -1,6 +1,12 @@'use client'-import { Avatar } from '@langgenius/dify-ui/avatar'+import {+ Avatar,+ AvatarFallback,+ AvatarGroup,+ AvatarGroupCount,+ AvatarImage,+} from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'import {Combobox,@@ -24,6 +30,7 @@ import { useCallback, useMemo, useRef } from 'react'import { useTranslation } from 'react-i18next'import { userProfileQueryOptions } from '@/features/account-profile/client'import { useMembers } from '@/service/use-common'+import { getAvatarInitial } from '@/utils/avatar'type CreatorsFilterProps = {value: string[]@@ -92,6 +99,7 @@ const CreatorsFilter = ({ value, onChange }: CreatorsFilterProps) => {const selectedCount = value.lengthconst selectedAvatarCreators = selectedCreators.slice(0, 3)+ const remainingCount = selectedCount - selectedAvatarCreators.lengthconst creatorFilterLabel = t(($) => $['studio.filters.creators'], { ns: 'app' })const resetLabel = t(($) => $['studio.filters.reset'], { ns: 'app' })const selectedCountLabel =@@ -116,7 +124,7 @@ const CreatorsFilter = ({ value, onChange }: CreatorsFilterProps) => {aria-label={creatorFilterLabel}className={cn(baseChipClassName,- 'group/creators-trigger peer/creators-trigger w-auto min-w-0 gap-0.5 border-components-button-secondary-border bg-components-button-secondary-bg py-2 pr-8 text-start system-sm-regular shadow-xs hover:bg-state-base-hover-alt focus-visible:bg-state-base-hover-alt data-placeholder:border-transparent data-placeholder:bg-components-input-bg-normal data-placeholder:pr-2 data-placeholder:text-text-tertiary data-placeholder:shadow-none data-placeholder:hover:bg-components-input-bg-hover data-popup-open:bg-state-base-hover-alt',+ 'group/creators-trigger peer/creators-trigger w-auto min-w-0 gap-0.5 border-components-button-secondary-border bg-components-button-secondary-bg py-2 pr-7 text-start system-sm-regular shadow-xs hover:bg-state-base-hover-alt focus-visible:bg-state-base-hover-alt data-placeholder:border-transparent data-placeholder:bg-components-input-bg-normal data-placeholder:pr-2 data-placeholder:text-text-tertiary data-placeholder:shadow-none data-placeholder:hover:bg-components-input-bg-hover data-popup-open:bg-state-base-hover-alt',)}><ComboboxValue<string, true>>@@ -125,20 +133,19 @@ const CreatorsFilter = ({ value, onChange }: CreatorsFilterProps) => {{creatorFilterLabel}</span>{selectedCount > 0 ? (- <>- <span className="flex items-center pr-1">- {selectedAvatarCreators.map((creator, index) => (- <Avatar- key={creator.id}- avatar={creator.avatarUrl}- name={creator.name}- size="xs"- className={cn('border border-components-panel-bg', index > 0 && '-ml-1')}- />- ))}- </span>- <span className="text-xs leading-4 font-medium text-text-tertiary group-data-popup-open/creators-trigger:text-text-secondary">{`+${selectedCount}`}</span>- </>+ <AvatarGroup size="xs">+ {selectedAvatarCreators.map((creator, index) => (+ <Avatar+ key={creator.id}+ aria-hidden="true"+ style={{ zIndex: selectedAvatarCreators.length - index }}+ >+ <AvatarFallback>{getAvatarInitial(creator.name)}</AvatarFallback>+ <AvatarImage src={creator.avatarUrl || undefined} alt="" />+ </Avatar>+ ))}+ {remainingCount > 0 && <AvatarGroupCount>+{remainingCount}</AvatarGroupCount>}+ </AvatarGroup>) : (<span className="i-ri-arrow-down-s-line h-4 w-4 shrink-0 text-text-tertiary group-data-popup-open/creators-trigger:text-text-secondary" />)}@@ -190,14 +197,10 @@ const CreatorsFilter = ({ value, onChange }: CreatorsFilterProps) => {<ComboboxItemIndicator className="ms-0 size-3 text-components-checkbox-icon" /></span><ComboboxItemText className="flex items-center gap-2 px-1 font-normal">- <span aria-hidden>- <Avatar- avatar={creator.avatarUrl}- name={creator.name}- size="xs"- className="border-[0.5px] border-divider-regular"- />- </span>+ <Avatar size="xs" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(creator.name)}</AvatarFallback>+ <AvatarImage src={creator.avatarUrl || undefined} alt="" />+ </Avatar><span className="flex min-w-0 grow items-center justify-between gap-2"><span className="truncate text-sm text-text-secondary">{creator.name}</span>{creator.isYou && (diff --git a/web/app/components/base/chat/chat-with-history/chat-wrapper.tsx b/web/app/components/base/chat/chat-with-history/chat-wrapper.tsxindex 7e8cc81c392..c9061e303ec 100644--- a/web/app/components/base/chat/chat-with-history/chat-wrapper.tsx+++ b/web/app/components/base/chat/chat-with-history/chat-wrapper.tsx@@ -1,7 +1,7 @@import type { FileEntity } from '../../file-uploader/types'import type { SpeechToTextTarget } from '../../voice-input/types'import type { ChatConfig, ChatItem, ChatItemInTree, OnSend } from '../types'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'import { RiArrowDownSLine, RiArrowUpSLine } from '@remixicon/react'import { useCallback, useEffect, useMemo, useState } from 'react'@@ -23,6 +23,7 @@ import {} from '@/service/share'import { submitHumanInputForm as submitHumanInputFormService } from '@/service/workflow'import { TransferMethod } from '@/types/app'+import { getAvatarInitial } from '@/utils/avatar'import { formatBooleanInputs } from '@/utils/model-config'import Chat from '../chat'import { useChat } from '../chat/hooks'@@ -468,11 +469,10 @@ const ChatWrapper = () => {renderAgentContent={renderAgentContent}questionIcon={initUserVariables?.avatar_url ? (- <Avatar- avatar={initUserVariables.avatar_url}- name={initUserVariables.name || 'user'}- size="xl"- />+ <Avatar size="xl" role="img" aria-label={initUserVariables.name || 'user'}>+ <AvatarFallback>{getAvatarInitial(initUserVariables.name || 'user')}</AvatarFallback>+ <AvatarImage src={initUserVariables.avatar_url} alt="" />+ </Avatar>) : undefined}/>diff --git a/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx b/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsxindex 7b90bcea322..fb955eb2688 100644--- a/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx+++ b/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx@@ -1,7 +1,7 @@import type { FileEntity } from '../../file-uploader/types'import type { HumanInputFormSubmitData } from '../chat/answer/human-input-content/type'import type { ChatConfig, ChatItem, ChatItemInTree, OnSend } from '../types'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'import { RiArrowDownSLine, RiArrowUpSLine } from '@remixicon/react'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'@@ -23,6 +23,7 @@ import {} from '@/service/share'import { submitHumanInputForm as submitHumanInputFormService } from '@/service/workflow'import { TransferMethod } from '@/types/app'+import { getAvatarInitial } from '@/utils/avatar'import Chat from '../chat'import { useChat } from '../chat/hooks'import { getLastAnswer, isValidGeneratedAnswer } from '../utils'@@ -475,11 +476,10 @@ const ChatWrapper = () => {sendOnEnter={sendOnEnter}questionIcon={initUserVariables?.avatar_url ? (- <Avatar- avatar={initUserVariables.avatar_url}- name={initUserVariables.name || 'user'}- size="xl"- />+ <Avatar size="xl" role="img" aria-label={initUserVariables.name || 'user'}>+ <AvatarFallback>{getAvatarInitial(initUserVariables.name || 'user')}</AvatarFallback>+ <AvatarImage src={initUserVariables.avatar_url} alt="" />+ </Avatar>) : undefined}/>diff --git a/web/app/components/base/user-avatar-list/index.spec.tsx b/web/app/components/base/user-avatar-list/index.spec.tsxnew file mode 100644index 00000000000..09854336aa0--- /dev/null+++ b/web/app/components/base/user-avatar-list/index.spec.tsx@@ -0,0 +1,31 @@+import { screen } from '@testing-library/react'+import { createConsoleQueryWrapper } from '@/test/console/query-data'+import { render } from '@/test/console/render'+import { UserAvatarList } from '.'++it('counts people once across multiple connections and keeps them until their last connection leaves', () => {+ const alice = { id: 'alice', name: 'Alice' }+ const bob = { id: 'bob', name: 'Bob' }+ const carol = { id: 'carol', name: 'Carol' }+ const dave = { id: 'dave', name: 'Dave' }+ const { rerender } = render(<UserAvatarList users={[alice, alice, bob, carol, dave]} />, {+ wrapper: createConsoleQueryWrapper({ accountProfile: { id: 'alice' } }).wrapper,+ })++ expect(screen.getAllByRole('img', { name: 'Alice' })).toHaveLength(1)+ expect(screen.getByRole('img', { name: 'Bob' })).toBeInTheDocument()+ expect(screen.getByText('+2')).toBeInTheDocument()++ rerender(<UserAvatarList users={[alice, bob, carol, dave]} />)+ expect(screen.getAllByRole('img', { name: 'Alice' })).toHaveLength(1)+ expect(screen.getByText('+2')).toBeInTheDocument()++ rerender(<UserAvatarList users={[bob, carol, dave]} />)+ expect(screen.queryByRole('img', { name: 'Alice' })).not.toBeInTheDocument()+ expect(screen.getAllByRole('img').map((avatar) => avatar.getAttribute('aria-label'))).toEqual([+ 'Bob',+ 'Carol',+ 'Dave',+ ])+ expect(screen.queryByText(/^\+\d+$/)).not.toBeInTheDocument()+})diff --git a/web/app/components/base/user-avatar-list/index.tsx b/web/app/components/base/user-avatar-list/index.tsxindex 19342801814..baad405c416 100644--- a/web/app/components/base/user-avatar-list/index.tsx+++ b/web/app/components/base/user-avatar-list/index.tsx@@ -1,10 +1,18 @@import type { AvatarSize } from '@langgenius/dify-ui/avatar'import type { FC } from 'react'-import { AvatarFallback, AvatarImage, AvatarRoot } from '@langgenius/dify-ui/avatar'+import {+ Avatar,+ AvatarFallback,+ AvatarGroup,+ AvatarGroupCount,+ AvatarImage,+} from '@langgenius/dify-ui/avatar'import { useSuspenseQuery } from '@tanstack/react-query'+import { uniqBy } from 'es-toolkit'import { memo } from 'react'import { getUserColor } from '@/app/components/workflow/collaboration/utils/user-color'import { userProfileQueryOptions } from '@/features/account-profile/client'+import { getAvatarInitial } from '@/utils/avatar'type User = {id: string@@ -20,67 +28,43 @@ type UserAvatarListProps = {showCount?: boolean}-const avatarSizeToPx: Record<AvatarSize, number> = {- xxs: 16,- xs: 20,- sm: 24,- md: 32,- lg: 36,- xl: 40,- '2xl': 48,- '3xl': 64,-}-export const UserAvatarList: FC<UserAvatarListProps> = memo(({ users, maxVisible = 3, size = 'sm', className = '', showCount = true }) => {const { data: currentUserId } = useSuspenseQuery({...userProfileQueryOptions(),select: (data) => data.profile.id,})- if (!users.length) return null+ const uniqueUsers = uniqBy(users, (user) => user.id)+ if (!uniqueUsers.length) return null- const shouldShowCount = showCount && users.length > maxVisible+ const shouldShowCount = showCount && uniqueUsers.length > maxVisibleconst actualMaxVisible = shouldShowCount ? Math.max(1, maxVisible - 1) : maxVisible- const visibleUsers = users.slice(0, actualMaxVisible)- const remainingCount = users.length - actualMaxVisible+ const visibleUsers = uniqueUsers.slice(0, actualMaxVisible)+ const remainingCount = uniqueUsers.length - actualMaxVisiblereturn (- <div className={`flex items-center -space-x-1 ${className}`}>+ <AvatarGroup size={size} className={className}>{visibleUsers.map((user, index) => {const isCurrentUser = user.id === currentUserIdconst userColor = isCurrentUser ? undefined : getUserColor(user.id)return (- <div- key={`${user.id}-${index}`}- className="relative"+ <Avatar+ key={user.id}+ role="img"+ aria-label={user.name}style={{ zIndex: visibleUsers.length - index }}>- <AvatarRoot size={size} className="ring-2 ring-components-panel-bg">- {user.avatar_url && <AvatarImage src={user.avatar_url} alt={user.name} />}- <AvatarFallback- size={size}- style={userColor ? { backgroundColor: userColor } : undefined}- >- {user.name?.[0]?.toLocaleUpperCase()}- </AvatarFallback>- </AvatarRoot>- </div>+ <AvatarFallback style={userColor ? { backgroundColor: userColor } : undefined}>+ {getAvatarInitial(user.name)}+ </AvatarFallback>+ <AvatarImage src={user.avatar_url || undefined} alt="" />+ </Avatar>)})}{shouldShowCount && remainingCount > 0 && (- <div className="relative shrink-0" style={{ zIndex: 0 }}>- <div- className="inline-flex items-center justify-center rounded-full bg-gray-500 text-2xs leading-none text-white ring-2 ring-components-panel-bg"- style={{- width: avatarSizeToPx[size],- height: avatarSizeToPx[size],- }}- >- +{remainingCount}- </div>- </div>+ <AvatarGroupCount>+{remainingCount}</AvatarGroupCount>)}- </div>+ </AvatarGroup>)},)diff --git a/web/app/components/base/workspace-avatar/index.tsx b/web/app/components/base/workspace-avatar/index.tsxindex dc1e0bba2f1..e2118b98894 100644--- a/web/app/components/base/workspace-avatar/index.tsx+++ b/web/app/components/base/workspace-avatar/index.tsx@@ -1,8 +1,9 @@'use client'import type { AvatarSize } from '@langgenius/dify-ui/avatar'-import { AvatarFallback, AvatarRoot } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'+import { getAvatarInitial } from '@/utils/avatar'export type WorkspaceAvatarSize = Extract<AvatarSize, 'xs' | 'sm' | 'lg' | '2xl'>@@ -23,12 +24,12 @@ export function WorkspaceAvatar({className?: string}) {return (- <AvatarRoot+ <Avatar+ aria-hidden="true"size={size}className={cn('shadow-xs', workspaceAvatarClasses[size].root, className)}><AvatarFallback- size={size}className={cn('border border-divider-regular bg-components-icon-bg-orange-dark-solid bg-linear-to-br from-components-avatar-bg-mask-stop-0 to-components-avatar-bg-mask-stop-100 p-1',)}@@ -39,9 +40,9 @@ export function WorkspaceAvatar({workspaceAvatarClasses[size].text,)}>- {name?.[0]?.toLocaleUpperCase() || '?'}+ {getAvatarInitial(name)}</span></AvatarFallback>- </AvatarRoot>+ </Avatar>)}diff --git a/web/app/components/datasets/common/__tests__/credential-icon.spec.tsx b/web/app/components/datasets/common/__tests__/credential-icon.spec.tsxindex d8894b71358..765d1589776 100644--- a/web/app/components/datasets/common/__tests__/credential-icon.spec.tsx+++ b/web/app/components/datasets/common/__tests__/credential-icon.spec.tsx@@ -1,34 +1,41 @@import { fireEvent, render, screen } from '@testing-library/react'import { CredentialIcon } from '../credential-icon'-describe('CredentialIcon', () => {- it('shows the credential initial when there is no avatar', () => {- render(<CredentialIcon name="alice" />)+beforeEach(() => {+ vi.spyOn(HTMLImageElement.prototype, 'complete', 'get').mockReturnValue(false)+})- expect(screen.getByText('A').parentElement).toHaveAttribute('aria-hidden', 'true')- })+afterEach(() => {+ vi.restoreAllMocks()+})- it('hides the credential avatar from the accessibility tree', () => {- const { container } = render(- <CredentialIcon avatarUrl="https://example.com/avatar.png" name="Alice" />,- )+it('keeps decorative credential images and fallback text out of the accessibility tree', () => {+ const { container } = render(<CredentialIcon name="Alice" />)- const image = container.querySelector('img')+ expect(screen.getByText('A').closest('[aria-hidden="true"]')).not.toBeNull()+ expect(container.querySelector('img')).toHaveAttribute('alt', '')+ expect(screen.queryByRole('img')).not.toBeInTheDocument()+})- expect(image).toHaveAttribute('src', 'https://example.com/avatar.png')- expect(image).toHaveAttribute('alt', '')- expect(image?.parentElement).toHaveAttribute('aria-hidden', 'true')+it.each([undefined, 'default', 'https://example.com/broken.png'])(+ 'loads the newly selected credential after the previous avatar was %s',+ (previousUrl) => {+ const { container, rerender } = render(<CredentialIcon avatarUrl={previousUrl} name="Alice" />)+ if (previousUrl && previousUrl !== 'default') {+ const previousImage = container.querySelector('img')!+ expect(previousImage).not.toHaveAttribute('data-error')+ fireEvent.error(previousImage)+ expect(previousImage).toHaveAttribute('data-error')+ }+ expect(screen.getByText('A')).toBeInTheDocument()++ rerender(<CredentialIcon avatarUrl="https://example.com/bob.png" name="Bob" />)+ const image = container.querySelector('img')!+ expect(image).toHaveAttribute('src', 'https://example.com/bob.png')+ fireEvent.load(image)++ expect(screen.queryByText('A')).not.toBeInTheDocument()+ expect(screen.queryByText('B')).not.toBeInTheDocument()expect(screen.queryByRole('img')).not.toBeInTheDocument()- })-- it('falls back to the credential initial when the avatar fails to load', () => {- const { container } = render(- <CredentialIcon avatarUrl="https://example.com/missing.png" name="Alice" />,- )-- fireEvent.error(container.querySelector('img')!)-- expect(container.querySelector('img')).not.toBeInTheDocument()- expect(screen.getByText('A').parentElement).toHaveAttribute('aria-hidden', 'true')- })-})+ },+)diff --git a/web/app/components/datasets/common/credential-icon.tsx b/web/app/components/datasets/common/credential-icon.tsxindex b69ae3f4be3..96d6595cfbc 100644--- a/web/app/components/datasets/common/credential-icon.tsx+++ b/web/app/components/datasets/common/credential-icon.tsx@@ -1,6 +1,6 @@+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'-import * as React from 'react'-import { useCallback, useMemo, useState } from 'react'+import { getAvatarInitial } from '@/utils/avatar'type CredentialIconProps = {avatarUrl?: string@@ -16,58 +16,29 @@ const ICON_BG_COLORS = ['bg-components-icon-bg-teal-solid',]-export const CredentialIcon: React.FC<CredentialIconProps> = ({- avatarUrl,- name,- size = 20,- className = '',-}) => {- const [showAvatar, setShowAvatar] = useState(!!avatarUrl && avatarUrl !== 'default')- const firstLetter = useMemo(() => name.charAt(0).toUpperCase(), [name])- const bgColor = useMemo(- () => ICON_BG_COLORS[firstLetter.charCodeAt(0) % ICON_BG_COLORS.length],- [firstLetter],- )-- const onImgLoadError = useCallback(() => {- setShowAvatar(false)- }, [])-- if (avatarUrl && avatarUrl !== 'default' && showAvatar) {- return (- <div- aria-hidden="true"- className={cn(- 'flex shrink-0 items-center justify-center overflow-hidden rounded-md border border-divider-regular',- className,- )}- style={{ width: `${size}px`, height: `${size}px` }}- >- <img- alt=""- src={avatarUrl}- width={size}- height={size}- className="shrink-0 object-contain"- onError={onImgLoadError}- />- </div>- )- }+export function CredentialIcon({ avatarUrl, name, size = 20, className }: CredentialIconProps) {+ const initial = getAvatarInitial(name)+ const bgColor = ICON_BG_COLORS[initial.codePointAt(0)! % ICON_BG_COLORS.length]return (- <div+ <Avatararia-hidden="true"- className={cn(- 'flex shrink-0 items-center justify-center rounded-md border border-divider-regular',- bgColor,- className,- )}- style={{ width: `${size}px`, height: `${size}px` }}+ className={cn('rounded-md border border-divider-regular', className)}+ style={{ width: size, height: size }}>- <span className="bg-linear-to-b from-components-avatar-shape-fill-stop-0 to-components-avatar-shape-fill-stop-100 bg-clip-text text-[13px] leading-[1.2] font-semibold text-transparent opacity-90">- {firstLetter}- </span>- </div>+ <AvatarFallback className={bgColor}>+ <span className="bg-linear-to-b from-components-avatar-shape-fill-stop-0 to-components-avatar-shape-fill-stop-100 bg-clip-text text-[13px] leading-[1.2] font-semibold text-transparent opacity-90">+ {initial}+ </span>+ </AvatarFallback>+ <AvatarImage+ keepMounted+ src={avatarUrl && avatarUrl !== 'default' ? avatarUrl : undefined}+ alt=""+ width={size}+ height={size}+ className="object-contain"+ />+ </Avatar>)}diff --git a/web/app/components/datasets/settings/permission-selector/index.tsx b/web/app/components/datasets/settings/permission-selector/index.tsxindex f9a621ac828..78b3bc321a2 100644--- a/web/app/components/datasets/settings/permission-selector/index.tsx+++ b/web/app/components/datasets/settings/permission-selector/index.tsx@@ -1,5 +1,5 @@import type { Member } from '@/models/common'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@langgenius/dify-ui/popover'import { RadioGroup } from '@langgenius/dify-ui/radio-group'@@ -11,6 +11,7 @@ import { SearchInput } from '@/app/components/base/search-input'import { userProfileQueryOptions } from '@/features/account-profile/client'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { DatasetPermission } from '@/models/datasets'+import { getAvatarInitial } from '@/utils/avatar'import MemberItem from './member-item'import PermissionItem from './permission-item'@@ -102,7 +103,10 @@ const PermissionSelector = ({{!isDisabledByRbac && isOnlyMe && (<><div className="flex size-6 shrink-0 items-center justify-center">- <Avatar avatar={userProfile.avatar_url} name={userProfile.name} size="xs" />+ <Avatar size="xs" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>+ <AvatarImage src={userProfile.avatar_url || undefined} alt="" />+ </Avatar></div><div className="grow p-1 system-sm-regular text-components-input-text-filled">{t(($) => $['form.permissionsOnlyMe'], { ns: 'datasetSettings' })}@@ -123,26 +127,21 @@ const PermissionSelector = ({<><div className="relative flex size-6 shrink-0 items-center justify-center">{selectedMembers.length === 1 && (- <Avatar- avatar={selectedMembers[0]!.avatar_url}- name={selectedMembers[0]!.name}- size="xs"- />+ <Avatar size="xs" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(selectedMembers[0]!.name)}</AvatarFallback>+ <AvatarImage src={selectedMembers[0]!.avatar_url || undefined} alt="" />+ </Avatar>)}{selectedMembers.length >= 2 && (<>- <Avatar- avatar={selectedMembers[0]!.avatar_url}- name={selectedMembers[0]!.name}- className="absolute top-0 left-0 z-0"- size="xxs"- />- <Avatar- avatar={selectedMembers[1]!.avatar_url}- name={selectedMembers[1]!.name}- className="absolute right-0 bottom-0 z-10"- size="xxs"- />+ <Avatar className="absolute top-0 left-0 z-0" size="xxs" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(selectedMembers[0]!.name)}</AvatarFallback>+ <AvatarImage src={selectedMembers[0]!.avatar_url || undefined} alt="" />+ </Avatar>+ <Avatar className="absolute right-0 bottom-0 z-10" size="xxs" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(selectedMembers[1]!.name)}</AvatarFallback>+ <AvatarImage src={selectedMembers[1]!.avatar_url || undefined} alt="" />+ </Avatar></>)}</div>@@ -184,12 +183,10 @@ const PermissionSelector = ({value={DatasetPermission.onlyMe}closeOnSelectleftIcon={- <Avatar- avatar={userProfile.avatar_url}- name={userProfile.name}- className="shrink-0"- size="sm"- />+ <Avatar className="shrink-0" size="sm" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>+ <AvatarImage src={userProfile.avatar_url || undefined} alt="" />+ </Avatar>}text={t(($) => $['form.permissionsOnlyMe'], { ns: 'datasetSettings' })}isSelected={isOnlyMe}@@ -236,12 +233,10 @@ const PermissionSelector = ({{showMe && (<MemberItemleftIcon={- <Avatar- avatar={userProfile.avatar_url}- name={userProfile.name}- className="shrink-0"- size="sm"- />+ <Avatar className="shrink-0" size="sm" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>+ <AvatarImage src={userProfile.avatar_url || undefined} alt="" />+ </Avatar>}name={userProfile.name}email={userProfile.email}@@ -253,12 +248,10 @@ const PermissionSelector = ({<MemberItemkey={member.id}leftIcon={- <Avatar- avatar={member.avatar_url}- name={member.name}- className="shrink-0"- size="sm"- />+ <Avatar className="shrink-0" size="sm" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(member.name)}</AvatarFallback>+ <AvatarImage src={member.avatar_url || undefined} alt="" />+ </Avatar>}name={member.name}email={member.email}diff --git a/web/app/components/header/account-dropdown/index.tsx b/web/app/components/header/account-dropdown/index.tsxindex 2a8655c7841..d905a5c8149 100644--- a/web/app/components/header/account-dropdown/index.tsx+++ b/web/app/components/header/account-dropdown/index.tsx@@ -2,7 +2,7 @@import type { ReactElement, ReactNode } from 'react'import type { Theme } from '@/app/components/base/theme-selector'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'import {DropdownMenu,@@ -33,6 +33,7 @@ import { userProfileQueryOptions } from '@/features/account-profile/client'import Link from '@/next/link'import { consoleQuery } from '@/service/console'import { useLogout } from '@/service/use-common'+import { getAvatarInitial } from '@/utils/avatar'import { ExternalLinkIndicator, MenuItemContent } from './menu-item-content'type AccountDropdownProps = {@@ -165,12 +166,10 @@ function MainNavMenuContent({ onLogout }: MainNavMenuContentProps) {{userProfile.email}</div></div>- <Avatar- avatar={userProfile.avatar_url}- name={userProfile.name}- size="lg"- className="shrink-0"- />+ <Avatar size="lg" className="shrink-0" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>+ <AvatarImage src={userProfile.avatar_url || undefined} alt="" />+ </Avatar></div></DropdownMenuGroup><DropdownMenuGroup className="p-1">diff --git a/web/app/components/header/account-setting/members-page/member-details-modal/index.tsx b/web/app/components/header/account-setting/members-page/member-details-modal/index.tsxindex 08f2a8b9e68..8fda9a369d6 100644--- a/web/app/components/header/account-setting/members-page/member-details-modal/index.tsx+++ b/web/app/components/header/account-setting/members-page/member-details-modal/index.tsx@@ -1,7 +1,7 @@'use client'import type { Role } from '@/models/access-control'import type { Member } from '@/models/common'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { Button } from '@langgenius/dify-ui/button'import { Dialog, DialogClose, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'import { IconButton } from '@langgenius/dify-ui/icon-button'@@ -11,6 +11,7 @@ import { useLocale } from '#i18n'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import { getAccessControlTemplateLanguage } from '@/i18n/language'import { useRolesOfMember } from '@/service/access-control/use-member-roles'+import { getAvatarInitial } from '@/utils/avatar'import AssignRolesModal from '../assign-roles-modal'import PermissionRoleChip from './permission-role-chip'@@ -128,7 +129,10 @@ const MemberDetailsModal = ({</DialogTitle><div className="mt-5 flex items-center gap-3">- <Avatar avatar={member.avatar_url} name={member.name} size="2xl" />+ <Avatar size="2xl" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(member.name)}</AvatarFallback>+ <AvatarImage src={member.avatar_url || undefined} alt="" />+ </Avatar><div className="min-w-0 flex-1"><div className="truncate system-md-semibold text-text-primary">{member.name}</div><div className="truncate system-xs-regular text-text-tertiary">{member.email}</div>diff --git a/web/app/components/header/account-setting/members-page/member-row.tsx b/web/app/components/header/account-setting/members-page/member-row.tsxindex ab2d2776723..117be0b02b4 100644--- a/web/app/components/header/account-setting/members-page/member-row.tsx+++ b/web/app/components/header/account-setting/members-page/member-row.tsx@@ -1,10 +1,11 @@'use client'import type { MouseEvent } from 'react'import type { Member } from '@/models/common'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { memo, useCallback } from 'react'import { useTranslation } from 'react-i18next'import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'+import { getAvatarInitial } from '@/utils/avatar'import MemberMenu from './member-menu'import RoleBadges from './role-badges'@@ -63,7 +64,10 @@ const MemberRow = ({><td className="px-3 py-2"><div className="flex min-w-0 items-center">- <Avatar avatar={member.avatar_url} size="sm" className="mr-2" name={member.name} />+ <Avatar size="sm" className="mr-2" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(member.name)}</AvatarFallback>+ <AvatarImage src={member.avatar_url || undefined} alt="" />+ </Avatar><div className="min-w-0"><div className="system-sm-medium text-text-secondary"><buttondiff --git a/web/app/components/header/account-setting/members-page/transfer-ownership-modal/member-selector.tsx b/web/app/components/header/account-setting/members-page/transfer-ownership-modal/member-selector.tsxindex 5f2614c6213..f79fd972c1d 100644--- a/web/app/components/header/account-setting/members-page/transfer-ownership-modal/member-selector.tsx+++ b/web/app/components/header/account-setting/members-page/transfer-ownership-modal/member-selector.tsx@@ -1,12 +1,13 @@'use client'import type { FC } from 'react'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'import * as React from 'react'import { useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { useMembers } from '@/service/use-common'+import { getAvatarInitial } from '@/utils/avatar'type Props = Readonly<{value?: string@@ -60,9 +61,10 @@ const MemberSelector: FC<Props> = ({ value, onSelect, exclude = [] }) => {)}{currentValue && (<>- <span aria-hidden>- <Avatar avatar={currentValue.avatar_url} size="sm" name={currentValue.name} />- </span>+ <Avatar size="sm" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(currentValue.name)}</AvatarFallback>+ <AvatarImage src={currentValue.avatar_url || undefined} alt="" />+ </Avatar><span className="grow truncate system-sm-medium text-text-secondary">{currentValue.name}</span>@@ -110,9 +112,10 @@ const MemberSelector: FC<Props> = ({ value, onSelect, exclude = [] }) => {setOpen(false)}}>- <span aria-hidden>- <Avatar avatar={account.avatar_url} size="sm" name={account.name} />- </span>+ <Avatar size="sm" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(account.name)}</AvatarFallback>+ <AvatarImage src={account.avatar_url || undefined} alt="" />+ </Avatar><span className="grow truncate system-sm-medium text-text-secondary">{account.name}</span>diff --git a/web/app/components/main-nav/components/account-section.tsx b/web/app/components/main-nav/components/account-section.tsxindex 8f217a5b914..a2e346ae4b7 100644--- a/web/app/components/main-nav/components/account-section.tsx+++ b/web/app/components/main-nav/components/account-section.tsx@@ -1,10 +1,11 @@'use client'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'import { useSuspenseQuery } from '@tanstack/react-query'import AccountDropdown from '@/app/components/header/account-dropdown'import { userProfileQueryOptions } from '@/features/account-profile/client'+import { getAvatarInitial } from '@/utils/avatar'type AccountSectionProps = {compact?: boolean@@ -28,14 +29,10 @@ const AccountSection = ({ compact = false }: AccountSectionProps) => {'data-popup-open:bg-state-base-hover',)}>- <span aria-hidden="true" className="flex size-7 shrink-0">- <Avatar- avatar={userProfile.avatar_url}- name={userProfile.name}- size="md"- className="size-7"- />- </span>+ <Avatar size="md" className="size-7" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>+ <AvatarImage src={userProfile.avatar_url || undefined} alt="" />+ </Avatar>{!compact && (<span className="min-w-0 flex-1 truncate system-md-medium" title={userProfile.name}>{userProfile.name}diff --git a/web/app/components/plugins/marketplace/creator-profile/publisher-avatar.tsx b/web/app/components/plugins/marketplace/creator-profile/publisher-avatar.tsxindex 2776410cd51..0a0500f8a01 100644--- a/web/app/components/plugins/marketplace/creator-profile/publisher-avatar.tsx+++ b/web/app/components/plugins/marketplace/creator-profile/publisher-avatar.tsx@@ -1,8 +1,9 @@'use client'import type { CSSProperties } from 'react'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'-import { useState } from 'react'+import { getAvatarInitial } from '@/utils/avatar'type PublisherAvatarProps = {avatarUrl: string@@ -36,40 +37,24 @@ export default function PublisherAvatar({size = 24,className,}: PublisherAvatarProps) {- const [failedAvatarUrl, setFailedAvatarUrl] = useState<string | null>(null)const shapeClass = isOrganization ? 'rounded-md' : 'rounded-full'- const shouldShowImage = Boolean(avatarUrl) && failedAvatarUrl !== avatarUrl- const fallbackLetter = name?.[0]?.toUpperCase() || 'U'+ const fallbackLetter = getAvatarInitial(name)return (- <div+ <Avatar+ aria-hidden="true"style={{ width: size, height: size }}- className={cn(- 'relative shrink-0 overflow-hidden border-[0.5px] border-divider-regular',- shapeClass,- className,- )}+ className={cn('border-[0.5px] border-divider-regular', shapeClass, className)}>- {shouldShowImage ? (- <img- src={avatarUrl}- alt={name}- className={cn('size-full object-cover', shapeClass)}- onError={() => setFailedAvatarUrl(avatarUrl)}- />- ) : (- <div- className={cn('flex size-full items-center justify-center', shapeClass)}- style={{ background: DEFAULT_AVATAR_BG }}+ <AvatarFallback style={{ background: DEFAULT_AVATAR_BG }}>+ <span+ className={cn(getFallbackTextClass(size), 'font-semibold')}+ style={DEFAULT_AVATAR_LETTER_STYLE}>- <span- className={cn(getFallbackTextClass(size), 'font-semibold')}- style={DEFAULT_AVATAR_LETTER_STYLE}- >- {fallbackLetter}- </span>- </div>- )}- </div>+ {fallbackLetter}+ </span>+ </AvatarFallback>+ <AvatarImage keepMounted src={avatarUrl || undefined} alt="" />+ </Avatar>)}diff --git a/web/app/components/plugins/plugin-auth/authorize/permission-selector.tsx b/web/app/components/plugins/plugin-auth/authorize/permission-selector.tsxindex 34aa0ca936a..eedf233355b 100644--- a/web/app/components/plugins/plugin-auth/authorize/permission-selector.tsx+++ b/web/app/components/plugins/plugin-auth/authorize/permission-selector.tsx@@ -1,5 +1,5 @@import type { CredentialPermission } from '@/models/permission'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'import {DropdownMenu,@@ -13,6 +13,7 @@ import { useSuspenseQuery } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'import { userProfileQueryOptions } from '@/features/account-profile/client'import { PermissionLevel } from '@/models/permission'+import { getAvatarInitial } from '@/utils/avatar'type PermissionSelectorProps = {disabled?: boolean@@ -48,7 +49,10 @@ const PermissionSelector = ({ disabled, permission, onChange }: PermissionSelect{isOnlyMe && (<><div className="flex size-6 shrink-0 items-center justify-center">- <Avatar avatar={userProfile.avatar_url} name={userProfile.name} size="xs" />+ <Avatar size="xs" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>+ <AvatarImage src={userProfile.avatar_url || undefined} alt="" />+ </Avatar></div><div className="grow p-1 system-sm-regular text-components-input-text-filled">{onlyMeLabel}@@ -86,12 +90,10 @@ const PermissionSelector = ({ disabled, permission, onChange }: PermissionSelectcloseOnClickclassName="touch-manipulation">- <Avatar- avatar={userProfile.avatar_url}- name={userProfile.name}- className="shrink-0"- size="sm"- />+ <Avatar className="shrink-0" size="sm" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>+ <AvatarImage src={userProfile.avatar_url || undefined} alt="" />+ </Avatar><div className="min-w-0 grow px-1 system-md-regular text-text-secondary">{onlyMeLabel}</div>diff --git a/web/app/components/workflow/comment/comment-input.tsx b/web/app/components/workflow/comment/comment-input.tsxindex b213ba1d7ad..a922ecbae97 100644--- a/web/app/components/workflow/comment/comment-input.tsx+++ b/web/app/components/workflow/comment/comment-input.tsx@@ -1,11 +1,12 @@import type { FC, PointerEvent as ReactPointerEvent } from 'react'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'import { IconButton } from '@langgenius/dify-ui/icon-button'import { useSuspenseQuery } from '@tanstack/react-query'import { memo, useCallback, useEffect, useId, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { userProfileQueryOptions } from '@/features/account-profile/client'+import { getAvatarInitial } from '@/utils/avatar'import { getKeyboardMovement } from '../utils/keyboard-movement'import { MentionInput } from './mention-input'@@ -178,12 +179,10 @@ export const CommentInput: FC<CommentInputProps> = memo(><div className="relative aspect-square h-8 w-8 shrink-0 rounded-tl-full rounded-tr-full rounded-br-full bg-primary-500 p-0.5"><div className="flex size-full items-center justify-center overflow-hidden rounded-tl-full rounded-tr-full rounded-br-full bg-components-panel-bg-blur p-0.5">- <Avatar- avatar={userProfile.avatar_url}- name={userProfile.name}- size="sm"- className="block size-full rounded-full"- />+ <Avatar size="sm" className="block size-full rounded-full" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>+ <AvatarImage src={userProfile.avatar_url || undefined} alt="" />+ </Avatar></div></div></IconButton>diff --git a/web/app/components/workflow/comment/mention-input.tsx b/web/app/components/workflow/comment/mention-input.tsxindex c7d75b3aa80..ab13b429665 100644--- a/web/app/components/workflow/comment/mention-input.tsx+++ b/web/app/components/workflow/comment/mention-input.tsx@@ -2,7 +2,7 @@import type { ReactNode } from 'react'import type { UserProfile } from '@/app/components/workflow/comment/types'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { IconButton } from '@langgenius/dify-ui/icon-button'@@ -22,6 +22,7 @@ import { useTranslation } from 'react-i18next'import Textarea from 'react-textarea-autosize'import { useParams } from '@/next/navigation'import { consoleClient } from '@/service/console'+import { getAvatarInitial } from '@/utils/avatar'import { useStore, useWorkflowStore } from '../store'type MentionInputProps = {@@ -660,12 +661,10 @@ const MentionInputInner = forwardRef<HTMLTextAreaElement, MentionInputProps>()}onClick={() => insertMention(user)}>- <Avatar- avatar={user.avatar_url || null}- name={user.name}- size="sm"- className="shrink-0"- />+ <Avatar size="sm" className="shrink-0" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(user.name)}</AvatarFallback>+ <AvatarImage src={user.avatar_url || undefined} alt="" />+ </Avatar><div className="min-w-0 flex-1"><div className="truncate text-sm font-medium text-text-primary">{user.name}diff --git a/web/app/components/workflow/comment/thread.tsx b/web/app/components/workflow/comment/thread.tsxindex 1e34128891b..a11bf428ad8 100644--- a/web/app/components/workflow/comment/thread.tsx+++ b/web/app/components/workflow/comment/thread.tsx@@ -14,7 +14,7 @@ import {AlertDialogFooter,AlertDialogTitle,} from '@langgenius/dify-ui/alert-dialog'-import { Avatar, AvatarFallback, AvatarImage, AvatarRoot } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'import {DropdownMenu,@@ -41,6 +41,7 @@ import { getUserColor } from '@/app/components/workflow/collaboration/utils/userimport { userProfileQueryOptions } from '@/features/account-profile/client'import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'import { useParams } from '@/next/navigation'+import { getAvatarInitial } from '@/utils/avatar'import { useStore } from '../store'import { MentionInput } from './mention-input'@@ -156,12 +157,12 @@ function ThreadMessage({return (<div className={cn('flex gap-3 pt-1', className)}><div className="shrink-0">- <AvatarRoot size="sm" className={cn('size-8 rounded-full')}>- {avatarUrl && <AvatarImage src={avatarUrl} alt={authorName} />}- <AvatarFallback size="sm" style={userColor ? { backgroundColor: userColor } : undefined}>- {authorName?.[0]?.toLocaleUpperCase()}+ <Avatar size="md" aria-hidden="true">+ <AvatarFallback style={userColor ? { backgroundColor: userColor } : undefined}>+ {getAvatarInitial(authorName)}</AvatarFallback>- </AvatarRoot>+ <AvatarImage src={avatarUrl || undefined} alt="" />+ </Avatar></div><div className="min-w-0 flex-1 pb-4 text-text-primary last:pb-0"><div className="flex flex-wrap items-center gap-x-2 gap-y-1">@@ -603,15 +604,15 @@ function CommentThreadComponent({{isCommentEditing ? (<div className="flex gap-3 pt-1"><div className="shrink-0">- <Avatar- name={- comment.created_by_account?.name ||- t(($) => $['comments.fallback.user'], { ns: 'workflowComments' })- }- avatar={comment.created_by_account?.avatar_url || null}- size="sm"- className="size-8 rounded-full"- />+ <Avatar size="md" aria-hidden="true">+ <AvatarFallback>+ {getAvatarInitial(+ comment.created_by_account?.name ||+ t(($) => $['comments.fallback.user'], { ns: 'workflowComments' }),+ )}+ </AvatarFallback>+ <AvatarImage src={comment.created_by_account?.avatar_url || undefined} alt="" />+ </Avatar></div><div className="min-w-0 flex-1"><div className="rounded-xl border border-components-chat-input-border bg-components-panel-bg-blur p-1 shadow-md backdrop-blur-[10px]">@@ -714,15 +715,18 @@ function CommentThreadComponent({{isReplyEditing ? (<div className="flex gap-3 pt-1"><div className="shrink-0">- <Avatar- name={- reply.created_by_account?.name ||- t(($) => $['comments.fallback.user'], { ns: 'workflowComments' })- }- avatar={reply.created_by_account?.avatar_url || null}- size="sm"- className="size-8 rounded-full"- />+ <Avatar size="md" aria-hidden="true">+ <AvatarFallback>+ {getAvatarInitial(+ reply.created_by_account?.name ||+ t(($) => $['comments.fallback.user'], { ns: 'workflowComments' }),+ )}+ </AvatarFallback>+ <AvatarImage+ src={reply.created_by_account?.avatar_url || undefined}+ alt=""+ />+ </Avatar></div><div className="min-w-0 flex-1"><div className="rounded-xl border border-components-chat-input-border bg-components-panel-bg-blur p-1 shadow-md backdrop-blur-[10px]">@@ -774,12 +778,12 @@ function CommentThreadComponent({{onReply && (<div className="border-t border-components-panel-border px-4 py-3"><div className="flex items-center gap-3">- <Avatar- avatar={userProfile?.avatar_url || null}- name={userProfile?.name || t(($) => $.you, { ns: 'common' })}- size="sm"- className="size-8"- />+ <Avatar size="md" aria-hidden="true">+ <AvatarFallback>+ {getAvatarInitial(userProfile?.name || t(($) => $.you, { ns: 'common' }))}+ </AvatarFallback>+ <AvatarImage src={userProfile?.avatar_url || undefined} alt="" />+ </Avatar><div className="flex-1 rounded-xl border border-components-chat-input-border bg-components-panel-bg-blur p-0.5 shadow-sm"><MentionInputref={replyInputRef}diff --git a/web/app/components/workflow/header/online-users.tsx b/web/app/components/workflow/header/online-users.tsxindex 516d787a738..b56e12cd8c0 100644--- a/web/app/components/workflow/header/online-users.tsx+++ b/web/app/components/workflow/header/online-users.tsx@@ -2,7 +2,7 @@import type { OnlineUser } from '../collaboration/types/collaboration'import { ChevronDownIcon } from '@heroicons/react/20/solid'-import { AvatarFallback, AvatarImage, AvatarRoot } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'@@ -12,6 +12,7 @@ import { useTranslation } from 'react-i18next'import { useReactFlow } from 'reactflow'import { userProfileQueryOptions } from '@/features/account-profile/client'import { getAvatar } from '@/service/common'+import { getAvatarInitial } from '@/utils/avatar'import { useCollaboration } from '../collaboration/hooks/use-collaboration'import { getUserColor } from '../collaboration/utils/user-color'import { useHooksStore } from '../hooks-store'@@ -122,15 +123,12 @@ const OnlineUsers = () => {const avatarUrl = getAvatarUrl(user)const displayName = user.username || fallbackUsernameconst avatar = (- <AvatarRoot size="sm" className="ring-1 ring-components-panel-bg">- {avatarUrl && <AvatarImage src={avatarUrl} alt={displayName} />}- <AvatarFallback- size="sm"- style={userColor ? { backgroundColor: userColor } : undefined}- >- {displayName?.[0]?.toLocaleUpperCase()}+ <Avatar size="sm" aria-hidden="true" className="ring-1 ring-components-panel-bg">+ <AvatarFallback style={userColor ? { backgroundColor: userColor } : undefined}>+ {getAvatarInitial(displayName)}</AvatarFallback>- </AvatarRoot>+ <AvatarImage src={avatarUrl || undefined} alt="" />+ </Avatar>)const triggerClassName = cn('relative flex size-6 items-center justify-center',@@ -143,12 +141,18 @@ const OnlineUsers = () => {<TooltipTriggerrender={isCurrentUser ? (- <div className={triggerClassName} style={triggerStyle}>+ <div+ role="img"+ aria-label={displayName}+ className={triggerClassName}+ style={triggerStyle}+ >{avatar}</div>) : (<buttontype="button"+ aria-label={displayName}className={triggerClassName}style={triggerStyle}onClick={() => jumpToUserCursor(user.user_id)}@@ -215,15 +219,14 @@ const OnlineUsers = () => {}}><div className="relative">- <AvatarRoot size="sm">- {avatarUrl && <AvatarImage src={avatarUrl} alt={displayName} />}+ <Avatar size="sm" aria-hidden="true"><AvatarFallback- size="sm"style={userColor ? { backgroundColor: userColor } : undefined}>- {displayName?.[0]?.toLocaleUpperCase()}+ {getAvatarInitial(displayName)}</AvatarFallback>- </AvatarRoot>+ <AvatarImage src={avatarUrl || undefined} alt="" />+ </Avatar></div>{renderDisplayName(user,diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-item.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-item.tsxindex 512619ec29c..2b28df0239c 100644--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-item.tsx+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-item.tsx@@ -1,10 +1,11 @@import type { Recipient as RecipientItem } from '../../../types'import type { Member } from '@/models/common'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'import { RiCloseCircleFill, RiErrorWarningFill } from '@remixicon/react'import * as React from 'react'import { useTranslation } from 'react-i18next'+import { getAvatarInitial } from '@/utils/avatar'type Props = Readonly<{email: string@@ -26,7 +27,12 @@ const EmailItem = ({ email, data, onDelete, disabled = false, isError }: Props)onClick={(e) => e.stopPropagation()}>{isError && <RiErrorWarningFill className="size-4 text-text-destructive" />}- {!isError && <Avatar avatar={data.avatar_url} size="xxs" name={data.name || data.email} />}+ {!isError && (+ <Avatar size="xxs" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(data.name || data.email)}</AvatarFallback>+ <AvatarImage src={data.avatar_url || undefined} alt="" />+ </Avatar>+ )}<div title={data.email} className="max-w-125 truncate system-xs-regular text-text-primary">{email === data.email ? data.name : data.email}{email === data.email && (diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/member-list.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/member-list.tsxindex 8d8aea5d785..b93b7ccf4fc 100644--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/member-list.tsx+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/member-list.tsx@@ -2,11 +2,12 @@import type { FC } from 'react'import type { Recipient } from '@/app/components/workflow/nodes/human-input/types'import type { Member } from '@/models/common'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'import { useMemo } from 'react'import { useTranslation } from 'react-i18next'+import { getAvatarInitial } from '@/utils/avatar'const i18nPrefix = 'nodes.humanInput'@@ -86,12 +87,10 @@ const MemberList: FC<Props> = ({)}onClick={() => onSelect(account.id)}>- <Avatar- className={cn(isSelected && 'opacity-50')}- avatar={account.avatar_url}- size="sm"- name={account.name}- />+ <Avatar className={cn(isSelected && 'opacity-50')} size="sm" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(account.name)}</AvatarFallback>+ <AvatarImage src={account.avatar_url || undefined} alt="" />+ </Avatar><div className={cn('grow', isSelected && 'opacity-50')}><div className="system-sm-medium text-text-secondary">{account.name}diff --git a/web/app/device/components/authorize-account.tsx b/web/app/device/components/authorize-account.tsxindex d7a6c2cf0bd..e62bdd3a142 100644--- a/web/app/device/components/authorize-account.tsx+++ b/web/app/device/components/authorize-account.tsx@@ -1,11 +1,12 @@'use client'import type { FC } from 'react'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { Button } from '@langgenius/dify-ui/button'import { useState } from 'react'import { useTranslation } from 'react-i18next'import { deviceApproveAccount, deviceDenyAccount } from '@/service/device-flow'+import { getAvatarInitial } from '@/utils/avatar'import { approveErrorCopy } from '../utils/error-copy'type Props = {@@ -73,11 +74,10 @@ const AuthorizeAccount: FC<Props> = ({</p></div><div className="flex items-center gap-2.5 rounded-lg bg-background-section-burn px-3 py-2.5">- <Avatar- size="md"- avatar={accountAvatarUrl ?? null}- name={accountName || accountEmail || ''}- />+ <Avatar size="md" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(accountName || accountEmail || '')}</AvatarFallback>+ <AvatarImage src={accountAvatarUrl || undefined} alt="" />+ </Avatar><div>{accountName && <p className="text-sm font-semibold text-text-primary">{accountName}</p>}{accountEmail && <p className="text-xs text-text-secondary">{accountEmail}</p>}diff --git a/web/app/device/components/authorize-sso.tsx b/web/app/device/components/authorize-sso.tsxindex 3e3cde706cb..fd8544f5341 100644--- a/web/app/device/components/authorize-sso.tsx+++ b/web/app/device/components/authorize-sso.tsx@@ -2,11 +2,12 @@import type { FC } from 'react'import type { ApprovalContext } from '@/service/device-flow'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback } from '@langgenius/dify-ui/avatar'import { Button } from '@langgenius/dify-ui/button'import { useEffect, useState } from 'react'import { Trans, useTranslation } from 'react-i18next'import { approveExternal, fetchApprovalContext } from '@/service/device-flow'+import { getAvatarInitial } from '@/utils/avatar'import { approveErrorCopy } from '../utils/error-copy'type Props = {@@ -97,7 +98,9 @@ const AuthorizeSSO: FC<Props> = ({ onApproved, onError }) => {<p className="mt-2 text-sm text-text-secondary">{t(($) => $['authorize.ssoSubtitle'])}</p></div><div className="flex items-center gap-2.5 rounded-lg bg-background-section-burn px-3 py-2.5">- <Avatar size="md" avatar={null} name={ctx.subject_email} />+ <Avatar size="md" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(ctx.subject_email)}</AvatarFallback>+ </Avatar><div><p className="text-sm font-semibold text-text-primary">{ctx.subject_email}</p><p className="text-xs text-text-secondary">{t(($) => $['authorize.viaSSO'])}</p>diff --git a/web/app/education/user-info.tsx b/web/app/education/user-info.tsxindex 4036212d3cc..7338200d828 100644--- a/web/app/education/user-info.tsx+++ b/web/app/education/user-info.tsx@@ -1,9 +1,10 @@-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { Button } from '@langgenius/dify-ui/button'import { useSuspenseQuery } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'import { userProfileQueryOptions } from '@/features/account-profile/client'import { useLogout } from '@/service/use-common'+import { getAvatarInitial } from '@/utils/avatar'const UserInfo = () => {const { t } = useTranslation(['common', 'education'])@@ -26,12 +27,10 @@ const UserInfo = () => {/></div><div className="flex items-center">- <Avatar- className="mr-4"- avatar={userProfile.avatar_url}- name={userProfile.name}- size="2xl"- />+ <Avatar className="mr-4" size="2xl" aria-hidden="true">+ <AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>+ <AvatarImage src={userProfile.avatar_url || undefined} alt="" />+ </Avatar><div className="pt-1.5"><div className="system-md-semibold text-text-primary">{userProfile.name}</div><div className="system-sm-regular text-text-secondary">{userProfile.email}</div>diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/chat-conversation.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/chat-conversation.tsxindex 2df9253a359..0b125efb89b 100644--- a/web/features/agent-v2/agent-detail/configure/components/preview/chat-conversation.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/preview/chat-conversation.tsx@@ -10,7 +10,7 @@ import type { FileEntity } from '@/app/components/base/file-uploader/types'import type { SpeechToTextTarget } from '@/app/components/base/voice-input/types'import type { AgentComposerModel } from '@/features/agent-v2/agent-composer/form-state'import type { Inputs } from '@/models/debug'-import { Avatar } from '@langgenius/dify-ui/avatar'+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query'import dynamic from 'next/dynamic'@@ -23,6 +23,7 @@ import { toast } from '@/app/notifications'import { useDocLink } from '@/context/i18n'import { userProfileQueryOptions } from '@/features/account-profile/client'import { consoleClient, consoleQuery } from '@/service/console'+import { getAvatarInitial } from '@/utils/avatar'import { getAgentSoulInputs, getAgentSoulInputsForm } from './chat-config'const Chat = dynamic(() => import('@/app/components/base/chat/chat'), { ssr: false })@@ -340,7 +341,12 @@ export function AgentPreviewChatConversation({onStopResponding={doStopResponding}noChatInputshowRegenerate- questionIcon={<Avatar avatar={userProfile.avatar_url} name={userProfile.name} size="xl" />}+ questionIcon={+ <Avatar size="xl" role="img" aria-label={userProfile.name}>+ <AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>+ <AvatarImage src={userProfile.avatar_url || undefined} alt="" />+ </Avatar>+ }onAnnotationEdited={handleAnnotationEdited}onAnnotationAdded={handleAnnotationAdded}onAnnotationRemoved={handleAnnotationRemoved}diff --git a/web/utils/avatar.spec.ts b/web/utils/avatar.spec.tsnew file mode 100644index 00000000000..285b7026fe0--- /dev/null+++ b/web/utils/avatar.spec.ts@@ -0,0 +1,15 @@+import { getAvatarInitial } from './avatar'++describe('getAvatarInitial', () => {+ it.each([+ [' alice ', 'A'],+ ['🧑💻 Alex', '🧑💻'],+ ['𠮷田', '𠮷'],+ ['e\u0301mile', 'E\u0301'],+ ['', '?'],+ [' ', '?'],+ [undefined, '?'],+ ])('uses the first complete grapheme of %s', (name, expected) => {+ expect(getAvatarInitial(name)).toBe(expected)+ })+})diff --git a/web/utils/avatar.ts b/web/utils/avatar.tsnew file mode 100644index 00000000000..4c7fcf3c92c--- /dev/null+++ b/web/utils/avatar.ts@@ -0,0 +1,7 @@+const avatarInitialSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' })++export function getAvatarInitial(name: string | null | undefined): string {+ for (const { segment } of avatarInitialSegmenter.segment(name?.trim() ?? ''))+ return segment.toUpperCase()+ return '?'+}