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): scope account editing sessions to dialog popups (#43514)

yyhb859881ca9d4
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index f75a7a398e5..c01d623d60f 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -4252,7 +4252,7 @@
"count": 1
},
"typescript/no-explicit-any": {
- "count": 5
+ "count": 4
}
},
"web/service/datasets.ts": {
diff --git a/web/app/account/(commonLayout)/account-page/__tests__/index.spec.tsx b/web/app/account/(commonLayout)/account-page/__tests__/index.spec.tsx
index a03fe5430e7..8d3a19fdc63 100644
--- a/web/app/account/(commonLayout)/account-page/__tests__/index.spec.tsx
+++ b/web/app/account/(commonLayout)/account-page/__tests__/index.spec.tsx
@@ -1,6 +1,8 @@
import type { GetAccountProfileResponse } from '@dify/contracts/api/console/account/types.gen'
-import { screen, waitFor } from '@testing-library/react'
+import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { toast } from '@/app/notifications'
+import { userProfileQueryOptions } from '@/features/account-profile/client'
import { consoleQuery } from '@/service/console'
import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
import AccountPage from '../index'
@@ -30,7 +32,7 @@ const createAccountResponse = (name = 'Alice'): GetAccountProfileResponse => ({
timezone: 'UTC',
})
-const renderPage = () => {
+const renderPage = ({ isPasswordSet = false, passwordLoginEnabled = true } = {}) => {
const queryClient = createConsoleQueryClient()
queryClient.setQueryData(
consoleQuery.apps.get.queryOptions({
@@ -39,16 +41,26 @@ const renderPage = () => {
{ data: [], has_more: false, limit: 100, page: 1, total: 0 },
)
- return renderWithConsoleQuery(<AccountPage />, {
+ renderWithConsoleQuery(<AccountPage />, {
queryClient,
- accountProfile: createAccountResponse(),
+ accountProfile: { ...createAccountResponse(), is_password_set: isPasswordSet },
+ systemFeatures: { enable_email_password_login: passwordLoginEnabled },
features: { education: { enabled: false } },
})
+ return { queryClient }
+}
+
+function pendingResponse() {
+ let resolve!: (response: Response) => void
+ const promise = new Promise<Response>((resolveResponse) => {
+ resolve = resolveResponse
+ })
+ return { promise, resolve }
}
describe('AccountPage', () => {
beforeEach(() => {
- vi.clearAllMocks()
+ vi.resetAllMocks()
mocks.get.mockImplementation(
async () =>
new Response(JSON.stringify(createAccountResponse('Alice Cooper')), {
@@ -80,5 +92,342 @@ describe('AccountPage', () => {
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' })
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(screen.getAllByText('Alice Cooper')).toHaveLength(2)
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
+ expect(screen.getByRole('textbox', { name: 'accountSettings.account.name' })).toHaveValue(
+ 'Alice Cooper',
+ )
+ })
+
+ it.each(['cancel', 'escape', 'backdrop'])(
+ 'discards a name draft after closing with %s',
+ async (dismissal) => {
+ const user = userEvent.setup()
+ renderPage()
+
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
+ const nameInput = screen.getByRole('textbox', { name: 'accountSettings.account.name' })
+ await user.clear(nameInput)
+ await user.type(nameInput, 'Unsaved name')
+ if (dismissal === 'cancel')
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ else if (dismissal === 'escape') await user.keyboard('{Escape}')
+ else await user.click(document.body)
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
+
+ expect(screen.getByRole('textbox', { name: 'accountSettings.account.name' })).toHaveValue(
+ 'Alice',
+ )
+ expect(mocks.request).not.toHaveBeenCalled()
+ },
+ )
+
+ it('keeps the name draft after failure and allows retry through Enter', async () => {
+ const user = userEvent.setup()
+ mocks.request.mockRejectedValueOnce(new Error('Name update failed'))
+ renderPage()
+
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
+ const nameInput = screen.getByRole('textbox', { name: 'accountSettings.account.name' })
+ await user.clear(nameInput)
+ await user.type(nameInput, 'Alice Cooper{Enter}')
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'common.operation.save' })).not.toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ ),
+ )
+ expect(
+ screen.getByRole('dialog', { name: 'accountSettings.account.editName' }),
+ ).toBeInTheDocument()
+ expect(nameInput).toHaveValue('Alice Cooper')
+ expect(mocks.request).toHaveBeenCalledOnce()
+
+ await user.click(nameInput)
+ await user.keyboard('{Enter}')
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(mocks.request).toHaveBeenCalledTimes(2)
+ })
+
+ it('keeps name editing open until both saving and profile refresh finish', async () => {
+ const user = userEvent.setup()
+ const saving = pendingResponse()
+ const refreshing = pendingResponse()
+ mocks.request.mockReturnValueOnce(saving.promise)
+ mocks.get.mockReturnValueOnce(refreshing.promise)
+ renderPage()
+
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
+ await user.type(
+ screen.getByRole('textbox', { name: 'accountSettings.account.name' }),
+ ' Cooper',
+ )
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+ const dialog = screen.getByRole('dialog', { name: 'accountSettings.account.editName' })
+ const cancel = within(dialog).getByRole('button', { name: 'common.operation.cancel' })
+ expect(cancel).toBeDisabled()
+ expect(within(dialog).getByRole('button', { name: 'common.operation.save' })).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ )
+ await user.click(cancel)
+ await user.keyboard('{Escape}')
+ await user.click(document.body)
+ expect(dialog).toBeInTheDocument()
+ expect(mocks.request).toHaveBeenCalledOnce()
+
+ await act(async () =>
+ saving.resolve(new Response(JSON.stringify(createAccountResponse('Alice Cooper')))),
+ )
+ await waitFor(() => expect(mocks.get).toHaveBeenCalled())
+ expect(cancel).toBeDisabled()
+ expect(within(dialog).getByRole('button', { name: 'common.operation.save' })).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ )
+ await user.keyboard('{Escape}')
+ expect(dialog).toBeInTheDocument()
+
+ await act(async () =>
+ refreshing.resolve(new Response(JSON.stringify(createAccountResponse('Alice Cooper')))),
+ )
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(screen.getAllByText('Alice Cooper')).toHaveLength(2)
+ })
+
+ it.each([false, true])(
+ 'starts a fresh password session when isPasswordSet=%s',
+ async (isPasswordSet) => {
+ const user = userEvent.setup()
+ renderPage({ isPasswordSet })
+ const triggerName = isPasswordSet
+ ? 'accountSettings.account.resetPassword'
+ : 'accountSettings.account.setPassword'
+ const passwordName = isPasswordSet
+ ? 'accountSettings.account.newPassword'
+ : 'accountSettings.account.password'
+ await user.click(screen.getByRole('button', { name: triggerName }))
+
+ if (isPasswordSet) {
+ const current = screen.getByLabelText('accountSettings.account.currentPassword')
+ expect(current).toHaveAttribute('autocomplete', 'current-password')
+ await user.type(current, 'Current123')
+ } else {
+ expect(
+ screen.queryByLabelText('accountSettings.account.currentPassword'),
+ ).not.toBeInTheDocument()
+ }
+ const password = screen.getByLabelText(passwordName)
+ const confirm = screen.getByLabelText('accountSettings.account.confirmPassword')
+ expect(password).toHaveAttribute('autocomplete', 'new-password')
+ expect(confirm).toHaveAttribute('autocomplete', 'new-password')
+ await user.type(password, 'NewPassword123')
+ await user.type(confirm, 'NewPassword123')
+ for (const toggle of screen.getAllByRole('button', { name: 'login.showPassword' })) {
+ await user.click(toggle)
+ }
+ expect(password).toHaveAttribute('type', 'text')
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await user.click(screen.getByRole('button', { name: triggerName }))
+
+ expect(screen.getByLabelText(passwordName)).toHaveValue('')
+ expect(screen.getByLabelText(passwordName)).toHaveAttribute('type', 'password')
+ expect(screen.getByLabelText('accountSettings.account.confirmPassword')).toHaveValue('')
+ expect(screen.getByLabelText('accountSettings.account.confirmPassword')).toHaveAttribute(
+ 'type',
+ 'password',
+ )
+ if (isPasswordSet) {
+ expect(screen.getByLabelText('accountSettings.account.currentPassword')).toHaveValue('')
+ expect(screen.getByLabelText('accountSettings.account.currentPassword')).toHaveAttribute(
+ 'type',
+ 'password',
+ )
+ }
+ expect(mocks.request).not.toHaveBeenCalled()
+ },
+ )
+
+ it('keeps all password values after a failed reset and retries the generated endpoint', async () => {
+ const user = userEvent.setup()
+ mocks.request.mockRejectedValueOnce(new Error('Password update failed'))
+ mocks.get.mockResolvedValue(
+ new Response(JSON.stringify({ ...createAccountResponse(), is_password_set: true })),
+ )
+ renderPage({ isPasswordSet: true })
+ await user.click(screen.getByRole('button', { name: 'accountSettings.account.resetPassword' }))
+ await user.type(screen.getByLabelText('accountSettings.account.currentPassword'), 'Current123')
+ await user.type(screen.getByLabelText('accountSettings.account.newPassword'), 'NewPassword123')
+ await user.type(
+ screen.getByLabelText('accountSettings.account.confirmPassword'),
+ 'NewPassword123{Enter}',
+ )
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'common.operation.reset' })).not.toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ ),
+ )
+
+ expect(screen.getByLabelText('accountSettings.account.currentPassword')).toHaveValue(
+ 'Current123',
+ )
+ expect(screen.getByLabelText('accountSettings.account.newPassword')).toHaveValue(
+ 'NewPassword123',
+ )
+ expect(screen.getByLabelText('accountSettings.account.confirmPassword')).toHaveValue(
+ 'NewPassword123',
+ )
+ expect(mocks.request).toHaveBeenCalledOnce()
+ await user.click(screen.getByRole('button', { name: 'common.operation.reset' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(mocks.request).toHaveBeenCalledTimes(2)
+ const request = mocks.request.mock.calls[1]?.[2]?.request as Request
+ expect(request.method).toBe('POST')
+ expect(request.url).toContain('/account/password')
+ await expect(request.json()).resolves.toEqual({
+ password: 'Current123',
+ new_password: 'NewPassword123',
+ repeat_new_password: 'NewPassword123',
+ })
+ })
+
+ it('closes password setting once the request succeeds and refreshes the profile in the background', async () => {
+ const user = userEvent.setup()
+ const saving = pendingResponse()
+ const refreshing = pendingResponse()
+ mocks.request.mockReturnValueOnce(saving.promise)
+ mocks.get.mockReturnValueOnce(refreshing.promise)
+ renderPage()
+ await user.click(screen.getByRole('button', { name: 'accountSettings.account.setPassword' }))
+ await user.type(screen.getByLabelText('accountSettings.account.password'), 'NewPassword123')
+ await user.type(
+ screen.getByLabelText('accountSettings.account.confirmPassword'),
+ 'NewPassword123{Enter}',
+ )
+ const dialog = screen.getByRole('dialog', { name: 'accountSettings.account.setPassword' })
+ const cancel = within(dialog).getByRole('button', { name: 'common.operation.cancel' })
+ expect(cancel).toBeDisabled()
+ expect(within(dialog).getByRole('button', { name: 'common.operation.save' })).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ )
+ await user.click(cancel)
+ await user.keyboard('{Escape}')
+ await user.click(document.body)
+ expect(dialog).toBeInTheDocument()
+ expect(mocks.request).toHaveBeenCalledOnce()
+
+ await act(async () =>
+ saving.resolve(
+ new Response(JSON.stringify({ ...createAccountResponse(), is_password_set: true })),
+ ),
+ )
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(mocks.get).toHaveBeenCalled()
+ expect(
+ screen.getByRole('button', { name: 'accountSettings.account.setPassword' }),
+ ).toBeInTheDocument()
+
+ await act(async () =>
+ refreshing.resolve(
+ new Response(JSON.stringify({ ...createAccountResponse(), is_password_set: true })),
+ ),
+ )
+ expect(
+ await screen.findByRole('button', { name: 'accountSettings.account.resetPassword' }),
+ ).toBeInTheDocument()
+ const request = mocks.request.mock.calls[0]?.[2]?.request as Request
+ await expect(request.json()).resolves.toEqual({
+ password: '',
+ new_password: 'NewPassword123',
+ repeat_new_password: 'NewPassword123',
+ })
+ })
+
+ it('keeps the set-password form when the profile reports a password during the session', async () => {
+ const user = userEvent.setup()
+ const { queryClient } = renderPage()
+ await user.click(screen.getByRole('button', { name: 'accountSettings.account.setPassword' }))
+ const dialog = screen.getByRole('dialog', { name: 'accountSettings.account.setPassword' })
+
+ act(() => {
+ queryClient.setQueryData(userProfileQueryOptions().queryKey, (current) =>
+ current ? { ...current, profile: { ...current.profile, is_password_set: true } } : current,
+ )
+ })
+
+ // The page behind the modal already reflects the refreshed profile.
+ await waitFor(() =>
+ expect(
+ screen.getByRole('button', { name: 'accountSettings.account.resetPassword', hidden: true }),
+ ).toBeInTheDocument(),
+ )
+ expect(dialog).toHaveAccessibleName('accountSettings.account.setPassword')
+ expect(
+ within(dialog).queryByLabelText('accountSettings.account.currentPassword'),
+ ).not.toBeInTheDocument()
+ expect(
+ within(dialog).getByRole('button', { name: 'common.operation.save' }),
+ ).toBeInTheDocument()
+ })
+
+ it.each(['name', 'password'])(
+ 'leaves a server-reported %s failure to the request layer',
+ async (field) => {
+ // The request layer reports the server message and rejects with the Response.
+ const error = vi.spyOn(toast, 'error')
+ const user = userEvent.setup()
+ mocks.request.mockRejectedValueOnce(
+ new Response(JSON.stringify({ code: 'invalid_param', message: 'Rejected', status: 400 }), {
+ status: 400,
+ }),
+ )
+ renderPage({ isPasswordSet: true })
+
+ if (field === 'name') {
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
+ await user.type(
+ screen.getByRole('textbox', { name: 'accountSettings.account.name' }),
+ ' Cooper{Enter}',
+ )
+ } else {
+ await user.click(
+ screen.getByRole('button', { name: 'accountSettings.account.resetPassword' }),
+ )
+ await user.type(
+ screen.getByLabelText('accountSettings.account.currentPassword'),
+ 'Current123',
+ )
+ await user.type(
+ screen.getByLabelText('accountSettings.account.newPassword'),
+ 'NewPassword123',
+ )
+ await user.type(
+ screen.getByLabelText('accountSettings.account.confirmPassword'),
+ 'NewPassword123{Enter}',
+ )
+ }
+
+ await waitFor(() => expect(mocks.request).toHaveBeenCalledOnce())
+ const submit = within(screen.getByRole('dialog')).getByRole('button', {
+ name: field === 'name' ? 'common.operation.save' : 'common.operation.reset',
+ })
+ await waitFor(() => expect(submit).not.toHaveAttribute('aria-disabled', 'true'))
+ expect(error).not.toHaveBeenCalled()
+ },
+ )
+
+ it('does not offer password editing when password login is disabled', () => {
+ renderPage({ passwordLoginEnabled: false })
+ expect(
+ screen.queryByRole('button', { name: 'accountSettings.account.setPassword' }),
+ ).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: 'accountSettings.account.resetPassword' }),
+ ).not.toBeInTheDocument()
})
})
diff --git a/web/app/account/(commonLayout)/account-page/__tests__/password-focus.browser.spec.tsx b/web/app/account/(commonLayout)/account-page/__tests__/password-focus.browser.spec.tsx
new file mode 100644
index 00000000000..0595b9e0ba9
--- /dev/null
+++ b/web/app/account/(commonLayout)/account-page/__tests__/password-focus.browser.spec.tsx
@@ -0,0 +1,87 @@
+import type { GetAccountProfileResponse } from '@dify/contracts/api/console/account/types.gen'
+import { QueryClientProvider } from '@tanstack/react-query'
+import { userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { createTestQueryClient } from '@/test/query-client'
+import { ChangePasswordDialog } from '../change-password-dialog'
+
+const mocks = vi.hoisted(() => ({ request: vi.fn() }))
+
+vi.mock('@/service/base', () => ({
+ del: vi.fn(),
+ get: vi.fn(),
+ patch: vi.fn(),
+ post: vi.fn(),
+ request: mocks.request,
+ sseGeneratorPost: vi.fn(),
+}))
+
+function pendingResponse() {
+ let resolve!: (response: Response) => void
+ let reject!: (error: Error) => void
+ const promise = new Promise<Response>((resolveResponse, rejectResponse) => {
+ resolve = resolveResponse
+ reject = rejectResponse
+ })
+ return { promise, resolve, reject }
+}
+
+it('keeps native submit focus during password saving and supports retry without leaving the dialog', async () => {
+ // Chromium proves native Enter submission and focus preservation when pending controls change.
+ const firstSave = pendingResponse()
+ const retry = pendingResponse()
+ mocks.request.mockReset()
+ mocks.request.mockReturnValueOnce(firstSave.promise).mockReturnValueOnce(retry.promise)
+ const screen = await render(
+ <QueryClientProvider client={createTestQueryClient()}>
+ <ChangePasswordDialog isPasswordSet />
+ </QueryClientProvider>,
+ )
+ const trigger = screen.getByRole('button', { name: 'accountSettings.account.resetPassword' })
+ await trigger.click()
+ const dialog = screen.getByRole('dialog', { name: 'accountSettings.account.resetPassword' })
+ await dialog.getByLabelText('accountSettings.account.currentPassword').fill('Current123')
+ await dialog.getByLabelText('accountSettings.account.newPassword').fill('NewPassword123')
+ const confirmPassword = dialog.getByLabelText('accountSettings.account.confirmPassword')
+ await confirmPassword.fill('NewPassword123')
+ await userEvent.keyboard('{Enter}')
+
+ const save = dialog.getByRole('button', { name: 'common.operation.reset' })
+ await expect.element(save).toHaveAttribute('aria-disabled', 'true')
+ await expect.element(confirmPassword).toHaveFocus()
+ await expect.element(confirmPassword).toHaveAttribute('readonly')
+ await userEvent.keyboard('{Escape}')
+ await expect.element(dialog).toBeVisible()
+ await expect.element(confirmPassword).toHaveFocus()
+ expect(mocks.request).toHaveBeenCalledOnce()
+
+ firstSave.reject(new Error('Password update failed'))
+ await expect.element(save).not.toHaveAttribute('aria-disabled', 'true')
+ await expect.element(confirmPassword).not.toHaveAttribute('readonly')
+ await expect.element(confirmPassword).toHaveFocus()
+ await expect.element(confirmPassword).toHaveValue('NewPassword123')
+ await save.click()
+ await expect.element(save).toHaveAttribute('aria-disabled', 'true')
+ await expect.element(save).toHaveFocus()
+ await userEvent.keyboard('{Escape}')
+ await expect.element(dialog).toBeVisible()
+ await expect.element(save).toHaveFocus()
+ expect(mocks.request).toHaveBeenCalledTimes(2)
+
+ retry.resolve(
+ new Response(
+ JSON.stringify({
+ id: 'user-id',
+ name: 'Alice',
+ email: '[email protected]',
+ avatar: '',
+ avatar_url: null,
+ is_password_set: true,
+ timezone: 'UTC',
+ } satisfies GetAccountProfileResponse),
+ { headers: { 'content-type': 'application/json' } },
+ ),
+ )
+ await expect.element(dialog).not.toBeInTheDocument()
+ await expect.element(trigger).toHaveFocus()
+})
diff --git a/web/app/account/(commonLayout)/account-page/change-password-dialog.tsx b/web/app/account/(commonLayout)/account-page/change-password-dialog.tsx
new file mode 100644
index 00000000000..727cd5a0fdf
--- /dev/null
+++ b/web/app/account/(commonLayout)/account-page/change-password-dialog.tsx
@@ -0,0 +1,200 @@
+'use client'
+
+import type { AccountPasswordPayload } from '@dify/contracts/api/console/account/types.gen'
+import type { DialogActions } from '@langgenius/dify-ui/dialog'
+import { Button } from '@langgenius/dify-ui/button'
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogTitle,
+ DialogTrigger,
+} from '@langgenius/dify-ui/dialog'
+import { Field, FieldLabel } from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
+import { IconButton } from '@langgenius/dify-ui/icon-button'
+import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { toast } from '@/app/notifications'
+import { validPassword } from '@/config'
+import { userProfileQueryOptions } from '@/features/account-profile/client'
+import { consoleQuery } from '@/service/console'
+
+type ChangePasswordFormValues = {
+ 'current-password'?: string
+ 'new-password': string
+ 'confirm-password': string
+}
+
+type PasswordFieldProps = {
+ name: keyof ChangePasswordFormValues
+ label: string
+ autoComplete: 'current-password' | 'new-password'
+ readOnly: boolean
+ className?: string
+}
+
+function PasswordField({ name, label, autoComplete, readOnly, className }: PasswordFieldProps) {
+ const { t } = useTranslation(['login'])
+ const [visible, setVisible] = useState(false)
+
+ return (
+ <Field name={name} className={className}>
+ <FieldLabel className="system-sm-semibold">{label}</FieldLabel>
+ <InputGroup>
+ <InputGroupInput
+ type={visible ? 'text' : 'password'}
+ autoComplete={autoComplete}
+ spellCheck={false}
+ readOnly={readOnly}
+ />
+ <InputGroupAddon align="inline-end">
+ <IconButton
+ size="lg"
+ aria-label={t(($) => $[visible ? 'hidePassword' : 'showPassword'], { ns: 'login' })}
+ onClick={() => setVisible(!visible)}
+ >
+ <span aria-hidden="true">{visible ? '👀' : '😝'}</span>
+ </IconButton>
+ </InputGroupAddon>
+ </InputGroup>
+ </Field>
+ )
+}
+
+type ChangePasswordFormProps = {
+ isPasswordSet: boolean
+ isPending: boolean
+ onSave: (password: AccountPasswordPayload) => Promise<void>
+}
+
+function ChangePasswordForm({
+ isPasswordSet: initialIsPasswordSet,
+ isPending,
+ onSave,
+}: ChangePasswordFormProps) {
+ const { t } = useTranslation(['common', 'login', 'accountSettings'])
+ // A successful first save refreshes the profile while the popup is still exiting.
+ // Keep the mode this session opened with instead of switching to the reset form.
+ const [isPasswordSet] = useState(initialIsPasswordSet)
+
+ const handleSubmit = (values: ChangePasswordFormValues) => {
+ if (isPending) return
+ const password = values['new-password']
+ const confirmPassword = values['confirm-password']
+ if (!password.trim()) {
+ toast.error(t(($) => $['error.passwordEmpty'], { ns: 'login' }))
+ return
+ }
+ if (!validPassword.test(password)) {
+ toast.error(t(($) => $['error.passwordInvalid'], { ns: 'login' }))
+ return
+ }
+ if (password !== confirmPassword) {
+ toast.error(t(($) => $['account.notEqual'], { ns: 'accountSettings' }))
+ return
+ }
+ void onSave({
+ password: values['current-password'] ?? '',
+ new_password: password,
+ repeat_new_password: confirmPassword,
+ })
+ }
+
+ return (
+ <Form<ChangePasswordFormValues> onFormSubmit={handleSubmit}>
+ <DialogTitle className="mb-6 title-2xl-semi-bold text-text-primary">
+ {isPasswordSet
+ ? t(($) => $['account.resetPassword'], { ns: 'accountSettings' })
+ : t(($) => $['account.setPassword'], { ns: 'accountSettings' })}
+ </DialogTitle>
+ {isPasswordSet && (
+ <PasswordField
+ name="current-password"
+ label={t(($) => $['account.currentPassword'], { ns: 'accountSettings' })}
+ autoComplete="current-password"
+ readOnly={isPending}
+ />
+ )}
+ <PasswordField
+ name="new-password"
+ label={
+ isPasswordSet
+ ? t(($) => $['account.newPassword'], { ns: 'accountSettings' })
+ : t(($) => $['account.password'], { ns: 'accountSettings' })
+ }
+ autoComplete="new-password"
+ readOnly={isPending}
+ className="mt-8"
+ />
+ <PasswordField
+ name="confirm-password"
+ label={t(($) => $['account.confirmPassword'], { ns: 'accountSettings' })}
+ autoComplete="new-password"
+ readOnly={isPending}
+ className="mt-8"
+ />
+ <div className="mt-10 flex justify-end">
+ <DialogClose render={<Button className="mr-2" disabled={isPending} />}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </DialogClose>
+ <Button type="submit" loading={isPending} variant="primary">
+ {isPasswordSet
+ ? t(($) => $['operation.reset'], { ns: 'common' })
+ : t(($) => $['operation.save'], { ns: 'common' })}
+ </Button>
+ </div>
+ </Form>
+ )
+}
+
+export function ChangePasswordDialog({ isPasswordSet }: { isPasswordSet: boolean }) {
+ const { t } = useTranslation(['common', 'accountSettings'])
+ const actionsRef = useRef<DialogActions>(null)
+ const queryClient = useQueryClient()
+ const updatePassword = useMutation(
+ consoleQuery.account.password.post.mutationOptions({
+ onSuccess: () => {
+ // The request alone decides success; a slow profile refresh must not keep the dialog locked.
+ void queryClient.invalidateQueries({ queryKey: userProfileQueryOptions().queryKey })
+ },
+ }),
+ )
+
+ const handleSave = async (password: AccountPasswordPayload) => {
+ try {
+ await updatePassword.mutateAsync({ body: password })
+ toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
+ actionsRef.current?.close()
+ } catch (error) {
+ // The request layer already reports every error the server answered with.
+ // Only report a failure that never produced a response.
+ if (error instanceof Error && error.message) toast.error(error.message)
+ }
+ }
+
+ return (
+ <Dialog
+ actionsRef={actionsRef}
+ onOpenChange={(open, details) => {
+ if (!open && updatePassword.isPending && details.reason !== 'imperative-action')
+ details.cancel()
+ }}
+ >
+ <DialogTrigger render={<Button />}>
+ {isPasswordSet
+ ? t(($) => $['account.resetPassword'], { ns: 'accountSettings' })
+ : t(($) => $['account.setPassword'], { ns: 'accountSettings' })}
+ </DialogTrigger>
+ <DialogContent className="w-105! p-6!">
+ <ChangePasswordForm
+ isPasswordSet={isPasswordSet}
+ isPending={updatePassword.isPending}
+ onSave={handleSave}
+ />
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/web/app/account/(commonLayout)/account-page/edit-account-name-dialog.tsx b/web/app/account/(commonLayout)/account-page/edit-account-name-dialog.tsx
new file mode 100644
index 00000000000..a0ca87e19cd
--- /dev/null
+++ b/web/app/account/(commonLayout)/account-page/edit-account-name-dialog.tsx
@@ -0,0 +1,96 @@
+'use client'
+
+import type { DialogActions } from '@langgenius/dify-ui/dialog'
+import { Button } from '@langgenius/dify-ui/button'
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogTitle,
+ DialogTrigger,
+} from '@langgenius/dify-ui/dialog'
+import { Field, FieldLabel } from '@langgenius/dify-ui/field'
+import { Input } from '@langgenius/dify-ui/input'
+import { useMutation } from '@tanstack/react-query'
+import { useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { toast } from '@/app/notifications'
+import { consoleQuery } from '@/service/console'
+
+type EditAccountNameFormProps = {
+ name: string
+ isPending: boolean
+ onSave: (name: string) => Promise<void>
+}
+
+function EditAccountNameForm({ name, isPending, onSave }: EditAccountNameFormProps) {
+ const { t } = useTranslation(['common', 'accountSettings'])
+ const [draftName, setDraftName] = useState(name)
+
+ return (
+ <form
+ onSubmit={(event) => {
+ event.preventDefault()
+ if (!isPending && draftName) void onSave(draftName)
+ }}
+ >
+ <DialogTitle className="mb-6 title-2xl-semi-bold text-text-primary">
+ {t(($) => $['account.editName'], { ns: 'accountSettings' })}
+ </DialogTitle>
+ <Field name="name" className="gap-0">
+ <FieldLabel className="py-0 system-sm-semibold text-text-secondary">
+ {t(($) => $['account.name'], { ns: 'accountSettings' })}
+ </FieldLabel>
+ <Input
+ className="mt-2"
+ value={draftName}
+ onValueChange={setDraftName}
+ readOnly={isPending}
+ />
+ </Field>
+ <div className="mt-10 flex justify-end">
+ <DialogClose render={<Button className="mr-2" disabled={isPending} />}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </DialogClose>
+ <Button type="submit" disabled={!draftName} loading={isPending} variant="primary">
+ {t(($) => $['operation.save'], { ns: 'common' })}
+ </Button>
+ </div>
+ </form>
+ )
+}
+
+export function EditAccountNameDialog({ name }: { name: string }) {
+ const { t } = useTranslation(['common'])
+ const actionsRef = useRef<DialogActions>(null)
+ const updateProfile = useMutation(consoleQuery.account.profile.patch.mutationOptions())
+
+ const handleSave = async (name: string) => {
+ try {
+ await updateProfile.mutateAsync({ body: { name } })
+ toast.success(t(($) => $['actionMsg.modifiedSuccessfully']))
+ actionsRef.current?.close()
+ } catch (error) {
+ // The request layer already reports every error the server answered with.
+ // Only report a failure that never produced a response.
+ if (error instanceof Error && error.message) toast.error(error.message)
+ }
+ }
+
+ return (
+ <Dialog
+ actionsRef={actionsRef}
+ onOpenChange={(open, details) => {
+ if (!open && updateProfile.isPending && details.reason !== 'imperative-action')
+ details.cancel()
+ }}
+ >
+ <DialogTrigger className="cursor-pointer rounded-lg bg-components-button-tertiary-bg px-3 py-2 system-sm-medium text-components-button-tertiary-text focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-state-accent-solid">
+ {t(($) => $['operation.edit'])}
+ </DialogTrigger>
+ <DialogContent className="w-105 p-6">
+ <EditAccountNameForm name={name} isPending={updateProfile.isPending} onSave={handleSave} />
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/web/app/account/(commonLayout)/account-page/index.tsx b/web/app/account/(commonLayout)/account-page/index.tsx
index 672b647713d..a8f85b1489e 100644
--- a/web/app/account/(commonLayout)/account-page/index.tsx
+++ b/web/app/account/(commonLayout)/account-page/index.tsx
@@ -3,25 +3,19 @@ import type { AppPartial } from '@dify/contracts/api/console/apps/types.gen'
import type { IItem } from '@/app/components/header/account-setting/collapse'
import { zIconType } from '@dify/contracts/api/console/apps/zod.gen'
import { Button } from '@langgenius/dify-ui/button'
-import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
-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 { useMutation, useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
-import { useId, useState } from 'react'
+import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
+import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
import PremiumBadge from '@/app/components/base/premium-badge'
import Collapse from '@/app/components/header/account-setting/collapse'
-import { toast } from '@/app/notifications'
-import { validPassword } from '@/config'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
-import { updateUserProfile } from '@/service/common'
import { consoleQuery } from '@/service/console'
import DeleteAccount from '../delete-account'
import AvatarWithEdit from './AvatarWithEdit'
+import { ChangePasswordDialog } from './change-password-dialog'
+import { EditAccountNameDialog } from './edit-account-name-dialog'
import EmailChangeModal from './email-change-modal'
const titleClassName = `
@@ -33,8 +27,7 @@ const descriptionClassName = `
type AccountAppItem = AppPartial & IItem
export default function AccountPage() {
- const { t } = useTranslation(['common', 'login', 'accountSettings'])
- const editNameInputId = useId()
+ const { t } = useTranslation(['common', 'accountSettings'])
const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { data: appList } = useQuery(
consoleQuery.apps.get.queryOptions({
@@ -48,13 +41,9 @@ 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
- const mutateUserProfile = () =>
- queryClient.invalidateQueries({ queryKey: userProfileQueryOptions().queryKey })
const { data: enableEducationPlan } = useQuery(
consoleQuery.features.get.queryOptions({
select: (features) => features.education.enabled,
@@ -66,86 +55,11 @@ export default function AccountPage() {
select: ({ is_student }) => is_student ?? false,
}),
)
- const [editNameModalVisible, setEditNameModalVisible] = useState(false)
- const [editName, setEditName] = useState('')
- const [editing, setEditing] = useState(false)
- const [editPasswordModalVisible, setEditPasswordModalVisible] = useState(false)
- const [currentPassword, setCurrentPassword] = useState('')
- const [password, setPassword] = useState('')
- const [confirmPassword, setConfirmPassword] = useState('')
const [showDeleteAccountModal, setShowDeleteAccountModal] = useState(false)
- const [showCurrentPassword, setShowCurrentPassword] = useState(false)
- const [showPassword, setShowPassword] = useState(false)
- const [showConfirmPassword, setShowConfirmPassword] = useState(false)
const [showUpdateEmail, setShowUpdateEmail] = useState(false)
if (!userProfile) return null
- const handleEditName = () => {
- setEditNameModalVisible(true)
- setEditName(userProfile.name)
- }
- const handleSaveName = async () => {
- try {
- setEditing(true)
- await updateProfile.mutateAsync({ body: { name: editName } })
- toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
- setEditNameModalVisible(false)
- setEditing(false)
- } catch (e) {
- toast.error((e as Error).message)
- setEditing(false)
- }
- }
-
- const showErrorMessage = (message: string) => {
- toast.error(message)
- }
- const valid = () => {
- if (!password.trim()) {
- showErrorMessage(t(($) => $['error.passwordEmpty'], { ns: 'login' }))
- return false
- }
- if (!validPassword.test(password)) {
- showErrorMessage(t(($) => $['error.passwordInvalid'], { ns: 'login' }))
- return false
- }
- if (password !== confirmPassword) {
- showErrorMessage(t(($) => $['account.notEqual'], { ns: 'accountSettings' }))
- return false
- }
-
- return true
- }
- const resetPasswordForm = () => {
- setCurrentPassword('')
- setPassword('')
- setConfirmPassword('')
- }
- const handleSavePassword = async () => {
- if (!valid()) return
- try {
- setEditing(true)
- await updateUserProfile({
- url: 'account/password',
- body: {
- password: currentPassword,
- new_password: password,
- repeat_new_password: confirmPassword,
- },
- })
- toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
- mutateUserProfile()
- setEditPasswordModalVisible(false)
- resetPasswordForm()
- setEditing(false)
- } catch (e) {
- toast.error((e as Error).message)
- setEditPasswordModalVisible(false)
- setEditing(false)
- }
- }
-
const renderAppItem = (item: AccountAppItem) => {
const appIconType = zIconType.safeParse(item.icon_type).data ?? null
return (
@@ -194,13 +108,7 @@ export default function AccountPage() {
<div className="flex-1 rounded-lg bg-components-input-bg-normal p-2 system-sm-regular text-components-input-text-filled">
<span className="pl-1">{userProfile.name}</span>
</div>
- <button
- type="button"
- className="cursor-pointer rounded-lg bg-components-button-tertiary-bg px-3 py-2 system-sm-medium text-components-button-tertiary-text"
- onClick={handleEditName}
- >
- {t(($) => $['operation.edit'], { ns: 'common' })}
- </button>
+ <EditAccountNameDialog name={userProfile.name} />
</div>
</div>
<div className="mb-8">
@@ -232,11 +140,7 @@ export default function AccountPage() {
{t(($) => $['account.passwordTip'], { ns: 'accountSettings' })}
</div>
</div>
- <Button onClick={() => setEditPasswordModalVisible(true)}>
- {userProfile.is_password_set
- ? t(($) => $['account.resetPassword'], { ns: 'accountSettings' })
- : t(($) => $['account.setPassword'], { ns: 'accountSettings' })}
- </Button>
+ <ChangePasswordDialog isPasswordSet={userProfile.is_password_set} />
</div>
)}
<div className="mb-6 border border-divider-subtle" />
@@ -264,140 +168,6 @@ export default function AccountPage() {
</Button>
)}
</div>
- <Dialog
- open={editNameModalVisible}
- onOpenChange={(open) => !open && setEditNameModalVisible(false)}
- >
- <DialogContent className="w-105 p-6">
- <div className="mb-6 title-2xl-semi-bold text-text-primary">
- {t(($) => $['account.editName'], { ns: 'accountSettings' })}
- </div>
- <label htmlFor={editNameInputId} className={`block ${titleClassName}`}>
- {t(($) => $['account.name'], { ns: 'accountSettings' })}
- </label>
- <Input
- id={editNameInputId}
- className="mt-2"
- value={editName}
- onChange={(e) => setEditName(e.target.value)}
- />
- <div className="mt-10 flex justify-end">
- <Button className="mr-2" onClick={() => setEditNameModalVisible(false)}>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </Button>
- <Button disabled={editing || !editName} variant="primary" onClick={handleSaveName}>
- {t(($) => $['operation.save'], { ns: 'common' })}
- </Button>
- </div>
- </DialogContent>
- </Dialog>
- <Dialog
- open={editPasswordModalVisible}
- onOpenChange={(open) => !open && (setEditPasswordModalVisible(false), resetPasswordForm())}
- >
- <DialogContent className="w-105! p-6!">
- <div className="mb-6 title-2xl-semi-bold text-text-primary">
- {userProfile.is_password_set
- ? t(($) => $['account.resetPassword'], { ns: 'accountSettings' })
- : t(($) => $['account.setPassword'], { ns: 'accountSettings' })}
- </div>
- {userProfile.is_password_set && (
- <Field name="current-password">
- <FieldLabel className="system-sm-semibold">
- {t(($) => $['account.currentPassword'], { ns: 'accountSettings' })}
- </FieldLabel>
- <InputGroup>
- <InputGroupInput
- type={showCurrentPassword ? 'text' : 'password'}
- value={currentPassword}
- onValueChange={setCurrentPassword}
- autoComplete="current-password"
- spellCheck={false}
- />
- <InputGroupAddon align="inline-end">
- <IconButton
- size="lg"
- aria-label={t(($) => $[showCurrentPassword ? 'hidePassword' : 'showPassword'], {
- ns: 'login',
- })}
- onClick={() => setShowCurrentPassword(!showCurrentPassword)}
- >
- <span aria-hidden="true">{showCurrentPassword ? '👀' : '😝'}</span>
- </IconButton>
- </InputGroupAddon>
- </InputGroup>
- </Field>
- )}
- <Field name="new-password" className="mt-8">
- <FieldLabel className="system-sm-semibold">
- {userProfile.is_password_set
- ? t(($) => $['account.newPassword'], { ns: 'accountSettings' })
- : t(($) => $['account.password'], { ns: 'accountSettings' })}
- </FieldLabel>
- <InputGroup>
- <InputGroupInput
- type={showPassword ? 'text' : 'password'}
- value={password}
- onValueChange={setPassword}
- autoComplete="new-password"
- spellCheck={false}
- />
- <InputGroupAddon align="inline-end">
- <IconButton
- size="lg"
- aria-label={t(($) => $[showPassword ? 'hidePassword' : 'showPassword'], {
- ns: 'login',
- })}
- onClick={() => setShowPassword(!showPassword)}
- >
- <span aria-hidden="true">{showPassword ? '👀' : '😝'}</span>
- </IconButton>
- </InputGroupAddon>
- </InputGroup>
- </Field>
- <Field name="confirm-password" className="mt-8">
- <FieldLabel className="system-sm-semibold">
- {t(($) => $['account.confirmPassword'], { ns: 'accountSettings' })}
- </FieldLabel>
- <InputGroup>
- <InputGroupInput
- type={showConfirmPassword ? 'text' : 'password'}
- value={confirmPassword}
- onValueChange={setConfirmPassword}
- autoComplete="new-password"
- spellCheck={false}
- />
- <InputGroupAddon align="inline-end">
- <IconButton
- size="lg"
- aria-label={t(($) => $[showConfirmPassword ? 'hidePassword' : 'showPassword'], {
- ns: 'login',
- })}
- onClick={() => setShowConfirmPassword(!showConfirmPassword)}
- >
- <span aria-hidden="true">{showConfirmPassword ? '👀' : '😝'}</span>
- </IconButton>
- </InputGroupAddon>
- </InputGroup>
- </Field>
- <div className="mt-10 flex justify-end">
- <Button
- className="mr-2"
- onClick={() => {
- setEditPasswordModalVisible(false)
- resetPasswordForm()
- }}
- >
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </Button>
- <Button disabled={editing} variant="primary" onClick={handleSavePassword}>
- {userProfile.is_password_set
- ? t(($) => $['operation.reset'], { ns: 'common' })
- : t(($) => $['operation.save'], { ns: 'common' })}
- </Button>
- </div>
- </DialogContent>
- </Dialog>
{showDeleteAccountModal && (
<DeleteAccount
onCancel={() => setShowDeleteAccountModal(false)}
diff --git a/web/service/common.ts b/web/service/common.ts
index 100cbc486cc..f02a8f26913 100644
--- a/web/service/common.ts
+++ b/web/service/common.ts
@@ -60,16 +60,6 @@ export const fetchInitValidateStatus = (): Promise<InitValidateStatusResponse> =
export const fetchSetupStatus = (): Promise<SetupStatusResponse> => {
return get<SetupStatusResponse>('/setup')
}
-export const updateUserProfile = ({
- url,
- body,
-}: {
- url: string
- body: Record<string, any>
-}): Promise<CommonResponse> => {
- return post<CommonResponse>(url, { body })
-}
-
export const deleteMemberOrCancelInvitation = ({
url,
}: {