Skip to content

armgit / dify

Public Imported from GitHub
0

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.

refactor(web): migrate account name and avatar updates to profile API (#42843)

非法操作ff27ef544e67
diff --git a/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx b/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx
index 1aaaebf3d4e..269ab557f14 100644
--- a/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx
+++ b/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx
@@ -8,6 +8,7 @@ import { Avatar } from '@langgenius/dify-ui/avatar'
import { Button } from '@langgenius/dify-ui/button'
import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { Separator } from '@langgenius/dify-ui/separator'
+import { useMutation } from '@tanstack/react-query'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -15,16 +16,18 @@ import ImageInput from '@/app/components/base/app-icon-picker/ImageInput'
import { useLocalFileUploader } from '@/app/components/base/image-uploader/hooks'
import { toast } from '@/app/notifications'
import { DISABLE_UPLOAD_IMAGE_AS_ICON } from '@/config'
-import { updateUserProfile } from '@/service/common'
+import { consoleQuery } from '@/service/console'
import { createAvatarImageFile, createCroppedAvatarImage } from './avatar-image'
type InputImageInfo =
| { file: File }
| { tempUrl: string; croppedAreaPixels: Area; fileName: string }
-type AvatarWithEditProps = AvatarProps & { onSave?: () => void }
-const AvatarWithEdit = ({ onSave, ...props }: AvatarWithEditProps) => {
+const AvatarWithEdit = (props: AvatarProps) => {
const { t } = useTranslation(['app', 'common'])
+ const { mutateAsync: updateProfile } = useMutation(
+ consoleQuery.account.profile.patch.mutationOptions(),
+ )
const [inputImageInfo, setInputImageInfo] = useState<InputImageInfo>()
const [isShowAvatarPicker, setIsShowAvatarPicker] = useState(false)
@@ -57,27 +60,25 @@ const AvatarWithEdit = ({ onSave, ...props }: AvatarWithEditProps) => {
const handleSaveAvatar = useCallback(
async (uploadedFileId: string) => {
try {
- await updateUserProfile({ url: 'account/avatar', body: { avatar: uploadedFileId } })
+ await updateProfile({ body: { avatar: uploadedFileId } })
setIsShowAvatarPicker(false)
- onSave?.()
toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
} catch (e) {
toast.error((e as Error).message)
}
},
- [onSave, t],
+ [t, updateProfile],
)
const handleDeleteAvatar = useCallback(async () => {
try {
- await updateUserProfile({ url: 'account/avatar', body: { avatar: '' } })
+ await updateProfile({ body: { avatar: '' } })
toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
setIsShowDeleteConfirm(false)
- onSave?.()
} catch (e) {
toast.error((e as Error).message)
}
- }, [onSave, t])
+ }, [t, updateProfile])
const handleDeleteAvatarClick = useCallback(() => {
setIsShowAvatarPicker(false)
diff --git a/web/app/account/(commonLayout)/account-page/__tests__/AvatarWithEdit.spec.tsx b/web/app/account/(commonLayout)/account-page/__tests__/AvatarWithEdit.spec.tsx
index 96bcab92141..88cab526160 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,10 @@
import type { OnImageInput } from '@/app/components/base/app-icon-picker/ImageInput'
import type { ImageFile } from '@/types/app'
+import { QueryClientProvider } from '@tanstack/react-query'
import { 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'
import { createCroppedAvatarImage } from '../avatar-image'
import AvatarWithEdit from '../AvatarWithEdit'
@@ -12,9 +15,18 @@ type LocalFileUploaderOptions = {
const mocks = vi.hoisted(() => ({
animatedFile: new File(['animated'], 'avatar.gif', { type: 'image/gif' }),
handleLocalFileUpload: vi.fn<(file: File) => void>(),
+ onUpload: null as ((imageFile: ImageFile) => void) | null,
+ request: vi.fn(),
}))
-vi.mock('@/config', () => ({ DISABLE_UPLOAD_IMAGE_AS_ICON: false }))
+vi.mock('@/config', () => ({
+ API_PREFIX: '/console/api',
+ DISABLE_UPLOAD_IMAGE_AS_ICON: false,
+}))
+
+vi.mock('@/service/base', () => ({
+ request: mocks.request,
+}))
vi.mock('@/app/components/base/app-icon-picker/ImageInput', () => ({
default: ({ onImageInput }: { onImageInput?: OnImageInput }) => (
@@ -40,9 +52,10 @@ vi.mock('@/app/components/base/app-icon-picker/ImageInput', () => ({
}))
vi.mock('@/app/components/base/image-uploader/hooks', () => ({
- useLocalFileUploader: (_options: LocalFileUploaderOptions) => ({
- handleLocalFileUpload: mocks.handleLocalFileUpload,
- }),
+ useLocalFileUploader: (options: LocalFileUploaderOptions) => {
+ mocks.onUpload = options.onUpload
+ return { handleLocalFileUpload: mocks.handleLocalFileUpload }
+ },
}))
vi.mock('../avatar-image', async (importOriginal) => {
@@ -55,16 +68,49 @@ vi.mock('../avatar-image', async (importOriginal) => {
const mockedCreateCroppedAvatarImage = vi.mocked(createCroppedAvatarImage)
+const createImageFile = (fileId = 'uploaded-avatar-id'): ImageFile => ({
+ type: TransferMethod.local_file,
+ _id: 'test-image-id',
+ fileId,
+ progress: 100,
+ url: 'https://example.com/avatar.png',
+})
+
+const createAccountResponse = (avatar = '') => ({
+ id: 'user-id',
+ name: 'Alice',
+ email: '[email protected]',
+ avatar,
+ avatar_url: avatar ? 'https://example.com/avatar.png' : null,
+ is_password_set: false,
+})
+
+const renderAvatar = (avatar: string | null = null) => {
+ const queryClient = createTestQueryClient()
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <AvatarWithEdit avatar={avatar} name="Alice" size="3xl" />
+ </QueryClientProvider>,
+ )
+}
+
describe('AvatarWithEdit', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mocks.onUpload = null
+ mocks.request.mockImplementation(
+ async () =>
+ new Response(JSON.stringify(createAccountResponse('uploaded-avatar-id')), {
+ headers: { 'content-type': 'application/json' },
+ }),
+ )
})
it('uploads the bounded crop for a static avatar', async () => {
const user = userEvent.setup()
const blob = new Blob(['bounded-avatar'], { type: 'image/png' })
mockedCreateCroppedAvatarImage.mockResolvedValue(blob)
- render(<AvatarWithEdit avatar={null} name="Alice" size="3xl" />)
+ renderAvatar()
await user.click(screen.getByRole('button', { name: /avatar\.editAction/i }))
await user.click(screen.getByRole('button', { name: 'Select static avatar' }))
@@ -82,9 +128,11 @@ describe('AvatarWithEdit', () => {
})
})
- it('keeps the existing original-file upload path for animated avatars', async () => {
+ it('updates an animated avatar through the account profile endpoint', async () => {
const user = userEvent.setup()
- render(<AvatarWithEdit avatar={null} name="Alice" size="3xl" />)
+ const uploadedAvatar = createImageFile()
+ mocks.handleLocalFileUpload.mockImplementation(() => mocks.onUpload?.(uploadedAvatar))
+ renderAvatar()
await user.click(screen.getByRole('button', { name: /avatar\.editAction/i }))
await user.click(screen.getByRole('button', { name: 'Select animated avatar' }))
@@ -92,5 +140,29 @@ describe('AvatarWithEdit', () => {
expect(mockedCreateCroppedAvatarImage).not.toHaveBeenCalled()
expect(mocks.handleLocalFileUpload).toHaveBeenCalledWith(mocks.animatedFile)
+ await waitFor(() => {
+ expect(mocks.request).toHaveBeenCalled()
+ })
+ expect(mocks.request.mock.calls[0]?.[0]).toEqual(expect.stringContaining('/account/profile'))
+ const request = mocks.request.mock.calls[0]?.[2]?.request as Request
+ expect(request.method).toBe('PATCH')
+ await expect(request.json()).resolves.toEqual({ avatar: uploadedAvatar.fileId })
+ })
+
+ it('clears the avatar through the account profile endpoint', async () => {
+ const user = userEvent.setup()
+ renderAvatar('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==')
+
+ await user.click(screen.getByRole('button', { name: /avatar\.editAction/i }))
+ await user.click(screen.getByRole('button', { name: /operation\.delete/i }))
+ await user.click(await screen.findByRole('button', { name: /operation\.delete/i }))
+
+ await waitFor(() => {
+ expect(mocks.request).toHaveBeenCalled()
+ })
+ expect(mocks.request.mock.calls[0]?.[0]).toEqual(expect.stringContaining('/account/profile'))
+ const request = mocks.request.mock.calls[0]?.[2]?.request as Request
+ expect(request.method).toBe('PATCH')
+ await expect(request.json()).resolves.toEqual({ avatar: '' })
})
})
diff --git a/web/app/account/(commonLayout)/account-page/__tests__/index.spec.tsx b/web/app/account/(commonLayout)/account-page/__tests__/index.spec.tsx
new file mode 100644
index 00000000000..1471c40a596
--- /dev/null
+++ b/web/app/account/(commonLayout)/account-page/__tests__/index.spec.tsx
@@ -0,0 +1,84 @@
+import type { GetAccountProfileResponse } from '@dify/contracts/api/console/account/types.gen'
+import { screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { consoleQuery } from '@/service/console'
+import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
+import AccountPage from '../index'
+
+const mocks = vi.hoisted(() => ({
+ get: vi.fn(),
+ request: vi.fn(),
+}))
+
+vi.mock('@/service/base', () => ({
+ del: vi.fn(),
+ get: mocks.get,
+ patch: vi.fn(),
+ post: vi.fn(),
+ request: mocks.request,
+ sseGeneratorPost: vi.fn(),
+}))
+
+const createAccountResponse = (name = 'Alice'): GetAccountProfileResponse => ({
+ id: 'user-id',
+ name,
+ email: '[email protected]',
+ avatar: '',
+ avatar_url: null,
+ is_password_set: false,
+ interface_language: 'en-US',
+ timezone: 'UTC',
+})
+
+const renderPage = () => {
+ const queryClient = createConsoleQueryClient()
+ queryClient.setQueryData(
+ consoleQuery.apps.get.queryOptions({
+ input: { query: { page: 1, limit: 100, name: '' } },
+ }).queryKey,
+ { data: [], has_more: false, limit: 100, page: 1, total: 0 },
+ )
+
+ return renderWithConsoleQuery(<AccountPage />, {
+ queryClient,
+ accountProfile: createAccountResponse(),
+ features: { education: { enabled: false } },
+ })
+}
+
+describe('AccountPage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.get.mockImplementation(
+ async () =>
+ new Response(JSON.stringify(createAccountResponse('Alice Cooper')), {
+ headers: { 'content-type': 'application/json' },
+ }),
+ )
+ mocks.request.mockImplementation(
+ async () =>
+ new Response(JSON.stringify(createAccountResponse('Alice Cooper')), {
+ headers: { 'content-type': 'application/json' },
+ }),
+ )
+ })
+
+ it('updates the account name through the profile endpoint', async () => {
+ const user = userEvent.setup()
+ renderPage()
+
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
+ const nameInput = await screen.findByRole('textbox', { name: 'common.account.name' })
+ await user.clear(nameInput)
+ await user.type(nameInput, 'Alice Cooper')
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+
+ await waitFor(() => {
+ expect(mocks.request).toHaveBeenCalled()
+ })
+ expect(mocks.request.mock.calls[0]?.[0]).toEqual(expect.stringContaining('/account/profile'))
+ const request = mocks.request.mock.calls[0]?.[2]?.request as Request
+ expect(request.method).toBe('PATCH')
+ await expect(request.json()).resolves.toEqual({ name: 'Alice Cooper' })
+ })
+})
diff --git a/web/app/account/(commonLayout)/account-page/index.tsx b/web/app/account/(commonLayout)/account-page/index.tsx
index e96945b1146..fd8a8c99018 100644
--- a/web/app/account/(commonLayout)/account-page/index.tsx
+++ b/web/app/account/(commonLayout)/account-page/index.tsx
@@ -8,7 +8,7 @@ import { Field, FieldLabel } from '@langgenius/dify-ui/field'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Input } from '@langgenius/dify-ui/input'
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
-import { useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
+import { useMutation, useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
import { useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
@@ -49,6 +49,7 @@ export default function AccountPage() {
)
const apps = appList?.data || []
const queryClient = useQueryClient()
+ const updateProfile = useMutation(consoleQuery.account.profile.patch.mutationOptions())
// Cache is hydrated by CommonLayoutHydrationBoundary; this hits cache synchronously.
const { data: userProfileResp } = useSuspenseQuery(userProfileQueryOptions())
const userProfile = userProfileResp.profile
@@ -87,9 +88,8 @@ export default function AccountPage() {
const handleSaveName = async () => {
try {
setEditing(true)
- await updateUserProfile({ url: 'account/name', body: { name: editName } })
+ await updateProfile.mutateAsync({ body: { name: editName } })
toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
- mutateUserProfile()
setEditNameModalVisible(false)
setEditing(false)
} catch (e) {
@@ -172,12 +172,7 @@ export default function AccountPage() {
</h4>
</div>
<div className="mb-8 flex items-center rounded-xl bg-linear-to-r from-background-gradient-bg-fill-chat-bg-2 to-background-gradient-bg-fill-chat-bg-1 p-6">
- <AvatarWithEdit
- avatar={userProfile.avatar_url}
- name={userProfile.name}
- onSave={mutateUserProfile}
- size="3xl"
- />
+ <AvatarWithEdit avatar={userProfile.avatar_url} name={userProfile.name} size="3xl" />
<div className="ml-4">
<p className="system-xl-semibold text-text-primary">
{userProfile.name}