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
fix(web): render auth pages without waiting on client status probes (#45634)
yyh1f0744c2ef5f
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex 00ec846cba7..51f33bc99e1 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -55,11 +55,6 @@"count": 1}},- "web/app/(auth)/init/InitPasswordPopup.tsx": {- "typescript/no-explicit-any": {- "count": 1- }- },"web/app/(auth)/signin/normal-form.tsx": {"@tanstack/query/prefer-query-options": {"count": 1diff --git a/web/app/(auth)/__tests__/server-gates.spec.ts b/web/app/(auth)/__tests__/server-gates.spec.tsnew file mode 100644index 00000000000..58ac4271061--- /dev/null+++ b/web/app/(auth)/__tests__/server-gates.spec.ts@@ -0,0 +1,99 @@+import { ORPCError } from '@orpc/client'+import { QueryClient } from '@tanstack/react-query'+import Install from '../install/page'+import SignIn from '../signin/page'++const { redirect, getSetupStatus, getProfile } = vi.hoisted(() => ({+ redirect: vi.fn((path: string) => {+ throw new Error(`redirect:${path}`)+ }),+ getSetupStatus: vi.fn(),+ getProfile: vi.fn(),+}))++vi.mock('server-only', () => ({}))+vi.mock('@/next/navigation', () => ({ redirect }))+vi.mock('@/app/get-query-client', () => ({ getQueryClient: () => new QueryClient() }))+vi.mock('@/service/console', () => ({ consoleClient: { setup: { get: getSetupStatus } } }))+vi.mock('@/service/console/server', () => ({+ resolveServerConsoleApiPrefix: () => 'http://api.test/console/api',+}))+vi.mock('@/features/account-profile/server', async () => {+ const actual = await vi.importActual<typeof import('@/features/account-profile/server')>(+ '@/features/account-profile/server',+ )+ return {+ redirectForBootstrapError: actual.redirectForBootstrapError,+ serverUserProfileQueryOptions: () => ({+ queryKey: ['profile'],+ queryFn: getProfile,+ retry: false,+ }),+ }+})+vi.mock('@/app/route-metadata', () => ({ getRouteMetadata: vi.fn() }))+vi.mock('../signin/sign-in-page', () => ({ default: () => null }))+vi.mock('../install/installForm', () => ({ default: () => null }))++beforeEach(() => {+ vi.clearAllMocks()+})++describe('install page', () => {+ it('sends a finished instance to sign in', async () => {+ getSetupStatus.mockResolvedValue({ step: 'finished' })++ await expect(Install()).rejects.toThrow('redirect:/signin')+ })++ it('renders the account form while setup has not started', async () => {+ getSetupStatus.mockResolvedValue({ step: 'not_started' })++ await expect(Install()).resolves.toBeTruthy()+ expect(redirect).not.toHaveBeenCalled()+ })++ it('lets a failed status check reach the error boundary', async () => {+ const failure = new Error('Bootstrap unavailable')+ getSetupStatus.mockRejectedValue(failure)++ await expect(Install()).rejects.toBe(failure)+ expect(redirect).not.toHaveBeenCalled()+ })+})++describe('sign in page', () => {+ it.each([+ ['not_setup', '/install'],+ ['not_init_validated', '/init'],+ ])('sends a %s instance to %s', async (code, path) => {+ getProfile.mockRejectedValue(new ORPCError(code, { status: 401 }))++ await expect(SignIn()).rejects.toThrow(`redirect:${path}`)+ })++ it.each([+ ['a signed-out visitor', new ORPCError('unauthorized', { status: 401 })],+ ['an unreachable API', new TypeError('fetch failed')],+ ])('renders the page for %s', async (_, failure) => {+ getProfile.mockRejectedValue(failure)++ await expect(SignIn()).resolves.toBeTruthy()+ expect(redirect).not.toHaveBeenCalled()+ })++ it('renders the page for a signed-in visitor so the client can redirect', async () => {+ getProfile.mockResolvedValue({ profile: { email: '[email protected]' }, meta: {} })++ await expect(SignIn()).resolves.toBeTruthy()+ expect(redirect).not.toHaveBeenCalled()+ })++ it('lets other profile failures reach the error boundary', async () => {+ const failure = new ORPCError('internal_error', { status: 500 })+ getProfile.mockRejectedValue(failure)++ await expect(SignIn()).rejects.toBe(failure)+ expect(redirect).not.toHaveBeenCalled()+ })+})diff --git a/web/app/(auth)/forgot-password/ForgotPasswordForm.spec.tsx b/web/app/(auth)/forgot-password/ForgotPasswordForm.spec.tsxindex d2d6b77282c..3c180b59cc4 100644--- a/web/app/(auth)/forgot-password/ForgotPasswordForm.spec.tsx+++ b/web/app/(auth)/forgot-password/ForgotPasswordForm.spec.tsx@@ -4,43 +4,34 @@ import { consoleClient } from '@/service/console'import { renderWithConsoleQuery as render } from '@/test/console/query-data'import ForgotPasswordForm from './ForgotPasswordForm'-vi.mock('@/service/console', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/service/console')>()),- consoleClient: {- setup: {- get: vi.fn(),- },- init: {- get: vi.fn(),- },- forgotPassword: {- post: vi.fn(),- },- },-}))--const mockFetchSetupStatus = vi.mocked(consoleClient.setup.get)-const mockFetchInitValidateStatus = vi.mocked(consoleClient.init.get)+vi.mock('@/service/console', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/service/console')>()+ const { withConsoleClientResponses, withConsoleResponses } =+ await import('@/test/console/service-responses')+ const responses = { 'forgotPassword.post': vi.fn(), 'init.get': vi.fn() }+ return {+ ...actual,+ consoleClient: withConsoleClientResponses(actual.consoleClient, responses),+ consoleQuery: withConsoleResponses(actual.consoleQuery, responses),+ }+})+const mockSendForgotPasswordEmail = vi.mocked(consoleClient.forgotPassword.post)+const mockFetchInitStatus = vi.mocked(consoleClient.init.get)+const mockReplace = vi.fn()-const prepareLoadedState = () => {- mockFetchSetupStatus.mockResolvedValue({ step: 'not_started' })- mockFetchInitValidateStatus.mockResolvedValue({- status: 'finished',- })-}+vi.mock('@/next/navigation', () => ({ useRouter: () => ({ replace: mockReplace }) }))describe('ForgotPasswordForm', () => {beforeEach(() => {vi.clearAllMocks()- prepareLoadedState()+ mockFetchInitStatus.mockResolvedValue({ status: 'finished' })})- it('should render form after loading', async () => {+ it('should render the form without waiting on a status request', () => {render(<ForgotPasswordForm />)- expect(document.title).toBe('common.loading - Dify')- expect(await screen.findByLabelText('login.email')).toBeInTheDocument()+ expect(screen.getByLabelText('login.email')).toBeInTheDocument()expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('login.forgotPassword')expect(document.title).toBe('login.forgotPassword - Dify')})@@ -138,7 +129,6 @@ describe('ForgotPasswordForm', () => {it('should keep form state when request fails', async () => {const user = userEvent.setup()- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})mockSendForgotPasswordEmail.mockResolvedValue({ result: 'fail', data: 'error' })render(<ForgotPasswordForm />)@@ -155,29 +145,13 @@ describe('ForgotPasswordForm', () => {'aria-disabled','true',)-- consoleSpy.mockRestore()})- it('should redirect to init when status is not started', async () => {- const originalLocation = window.location- Object.defineProperty(window, 'location', {- value: { href: '' },- writable: true,- })- mockFetchInitValidateStatus.mockResolvedValue({- status: 'not_started',- })+ it('should send an instance that still needs its init password to init', async () => {+ mockFetchInitStatus.mockResolvedValue({ status: 'not_started' })render(<ForgotPasswordForm />)- await waitFor(() => {- expect(window.location.href).toBe('/init')- })-- Object.defineProperty(window, 'location', {- value: originalLocation,- writable: true,- })+ await waitFor(() => expect(mockReplace).toHaveBeenCalledWith('/init'))})})diff --git a/web/app/(auth)/forgot-password/ForgotPasswordForm.tsx b/web/app/(auth)/forgot-password/ForgotPasswordForm.tsxindex 29da9d615d3..24366ddb9d2 100644--- a/web/app/(auth)/forgot-password/ForgotPasswordForm.tsx+++ b/web/app/(auth)/forgot-password/ForgotPasswordForm.tsx@@ -4,14 +4,14 @@ import { cn } from '@langgenius/dify-ui/cn'import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'import { Form } from '@langgenius/dify-ui/form'import { Input } from '@langgenius/dify-ui/input'-import { useEffect, useState } from 'react'+import { useMutation, useQuery } from '@tanstack/react-query'+import { useEffect } from 'react'import { useTranslation } from 'react-i18next'import * as z from 'zod'-import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import useDocumentTitle from '@/hooks/use-document-title'import Link from '@/next/link'-import { consoleClient } from '@/service/console'-import { basePath } from '@/utils/var'+import { useRouter } from '@/next/navigation'+import { consoleQuery } from '@/service/console'type ForgotPasswordFormValues = {email: string@@ -23,44 +23,26 @@ const emailSchema = z.email('error.emailInValid').min(1, {const ForgotPasswordForm = () => {const { t } = useTranslation(['common', 'login'])- const [loading, setLoading] = useState(true)- const [isSubmitting, setIsSubmitting] = useState(false)- const [isEmailSent, setIsEmailSent] = useState(false)- const documentTitle = loading- ? t(($) => $.loading, { ns: 'common' })- : isEmailSent- ? t(($) => $.resetLinkSent, { ns: 'login' })- : t(($) => $.forgotPassword, { ns: 'login' })+ const router = useRouter()+ const initStatus = useQuery(consoleQuery.init.get.queryOptions({ retry: false }))+ const isInitPending = initStatus.data?.status === 'not_started'+ const sendResetLink = useMutation(consoleQuery.forgotPassword.post.mutationOptions())+ const isEmailSent = sendResetLink.data?.result === 'success'+ const documentTitle = isEmailSent+ ? t(($) => $.resetLinkSent, { ns: 'login' })+ : t(($) => $.forgotPassword, { ns: 'login' })useDocumentTitle(documentTitle)- const handleSubmit = async ({ email }: ForgotPasswordFormValues) => {- if (isSubmitting) return-- setIsSubmitting(true)- try {- const res = await consoleClient.forgotPassword.post({ body: { email } })- if (res.result === 'success') setIsEmailSent(true)- else console.error('Email verification failed')- } catch (error) {- console.error('Request failed:', error)- } finally {- setIsSubmitting(false)- }+ const handleSubmit = ({ email }: ForgotPasswordFormValues) => {+ if (sendResetLink.isPending) return+ sendResetLink.mutate({ body: { email } })}useEffect(() => {- consoleClient.setup.get().then(() => {- consoleClient.init.get().then((res) => {- if (res.status === 'not_started') window.location.href = `${basePath}/init`- })-- setLoading(false)- })- }, [])+ if (isInitPending) router.replace('/init')+ }, [isInitPending, router])- return loading ? (- <LoadingPlaceholder />- ) : (+ return (<><div><h1 className="text-[32px] font-bold text-text-primary">@@ -76,11 +58,7 @@ const ForgotPasswordForm = () => {</div><div className="mt-8"><div className="relative">- <Form<ForgotPasswordFormValues>- onFormSubmit={(value) => {- void handleSubmit(value)- }}- >+ <Form<ForgotPasswordFormValues> onFormSubmit={handleSubmit}>{!isEmailSent && (<Fieldname="email"@@ -107,7 +85,12 @@ const ForgotPasswordForm = () => {{t(($) => $.backToSignIn, { ns: 'login' })}</Link>) : (- <Button type="submit" variant="primary" className="w-full" loading={isSubmitting}>+ <Button+ type="submit"+ variant="primary"+ className="w-full"+ loading={sendResetLink.isPending}+ >{t(($) => $.sendResetLink, { ns: 'login' })}</Button>)}diff --git a/web/app/(auth)/forgot-password/page.tsx b/web/app/(auth)/forgot-password/page.tsxindex 9c6722fd451..68e26a9a747 100644--- a/web/app/(auth)/forgot-password/page.tsx+++ b/web/app/(auth)/forgot-password/page.tsx@@ -1,13 +1,11 @@-'use client'-import ChangePasswordForm from '@/app/(auth)/forgot-password/ChangePasswordForm'-import { useSearchParams } from '@/next/navigation'+import ChangePasswordForm from './ChangePasswordForm'import ForgotPasswordForm from './ForgotPasswordForm'-const ForgotPassword = () => {- const searchParams = useSearchParams()- const token = searchParams.get('token')+type ForgotPasswordPageProps = {+ searchParams: Promise<{ token?: string | string[] }>+}+export default async function ForgotPassword({ searchParams }: ForgotPasswordPageProps) {+ const { token } = await searchParamsreturn token ? <ChangePasswordForm /> : <ForgotPasswordForm />}--export default ForgotPassworddiff --git a/web/app/(auth)/init/InitPasswordPopup.tsx b/web/app/(auth)/init/InitPasswordPopup.tsxindex 2dc7739324e..fe8bd483854 100644--- a/web/app/(auth)/init/InitPasswordPopup.tsx+++ b/web/app/(auth)/init/InitPasswordPopup.tsx@@ -1,78 +1,93 @@'use client'import { Button } from '@langgenius/dify-ui/button'+import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'+import { Form } from '@langgenius/dify-ui/form'import { Input } from '@langgenius/dify-ui/input'-import { useEffect, useState } from 'react'+import { ORPCError } from '@orpc/client'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useEffect, useMemo } from 'react'import { useTranslation } from 'react-i18next'-import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'-import { toast } from '@/app/notifications'import useDocumentTitle from '@/hooks/use-document-title'import { useRouter } from '@/next/navigation'-import { consoleClient } from '@/service/console'-import { basePath } from '@/utils/var'+import { consoleQuery } from '@/service/console'++type InitPasswordFormValues = {+ password: string+}++const isIncorrectPasswordError = (error: Error | null) =>+ error instanceof ORPCError && error.code === 'init_validate_failed'const InitPasswordPopup = () => {- const [password, setPassword] = useState('')- const [loading, setLoading] = useState(true)- const [validated, setValidated] = useState(false)const router = useRouter()-- const { t } = useTranslation(['login'])+ const queryClient = useQueryClient()+ const { t } = useTranslation(['login', 'common'])const pageTitle = t(($) => $.adminInitPassword, { ns: 'login' })useDocumentTitle(pageTitle)- const handleValidation = async () => {- setLoading(true)- try {- const response = await consoleClient.init.post(- { body: { password } },- { context: { silent: true } },- )- if (response.result === 'success') {- setValidated(true)- router.push('/install') // or render setup form- } else {- throw new Error('Validation failed')- }- } catch (e: any) {- toast.error(e.message)- setLoading(false)- }+ const initStatus = useQuery(consoleQuery.init.get.queryOptions({ retry: false }))+ const isInitFinished = initStatus.data?.status === 'finished'+ const validatePassword = useMutation(+ consoleQuery.init.post.mutationOptions({ context: { silent: true } }),+ )+ const isSubmitting = validatePassword.isPending || validatePassword.isSuccess+ const fieldErrors = useMemo(+ () =>+ isIncorrectPasswordError(validatePassword.error)+ ? { password: t(($) => $['error.initPasswordIncorrect'], { ns: 'login' }) }+ : undefined,+ [validatePassword.error, t],+ )+ const hasFormError = validatePassword.isError && !fieldErrors++ const handleSubmit = ({ password }: InitPasswordFormValues) => {+ if (isSubmitting) return+ validatePassword.mutate(+ { body: { password } },+ {+ onSuccess: () => {+ queryClient.setQueryData(consoleQuery.init.get.queryKey(), { status: 'finished' })+ router.replace('/install')+ },+ },+ )}+ const wasFinishedOnArrival = isInitFinished && !validatePassword.isSuccessuseEffect(() => {- consoleClient.init.get().then((res) => {- if (res.status === 'finished') window.location.href = `${basePath}/install`- else setLoading(false)- })- }, [])+ if (wasFinishedOnArrival) router.replace('/install')+ }, [wasFinishedOnArrival, router])- return loading ? (- <LoadingPlaceholder />- ) : (- <div>- {!validated && (- <div className="block min-w-28 sm:mx-12">- <div className="mb-4">- <label htmlFor="password" className="block text-sm font-medium text-text-secondary">- {pageTitle}- </label>- <Input- id="password"- type="password"- autoComplete="off"- className="mt-1"- value={password}- onValueChange={setPassword}- />- </div>- <div className="flex flex-row flex-wrap justify-stretch p-0">- <Button variant="primary" onClick={handleValidation} className="min-w-28 basis-full">- {t(($) => $.validate, { ns: 'login' })}- </Button>- </div>- </div>+ return (+ <Form<InitPasswordFormValues>+ className="block min-w-28 sm:mx-12"+ errors={fieldErrors}+ onFormSubmit={handleSubmit}+ >+ <Field+ name="password"+ validate={(value) => (value ? null : t(($) => $['error.passwordEmpty'], { ns: 'login' }))}+ className="mb-4"+ >+ <FieldLabel>{pageTitle}</FieldLabel>+ <Input+ type="password"+ autoComplete="off"+ onValueChange={() => {+ if (validatePassword.isError) validatePassword.reset()+ }}+ />+ <FieldError />+ </Field>+ {hasFormError && (+ <p role="alert" className="mb-4 system-sm-regular text-text-destructive">+ {t(($) => $['api.actionFailed'], { ns: 'common' })}+ </p>)}- </div>+ <Button type="submit" variant="primary" loading={isSubmitting} className="w-full">+ {t(($) => $.validate, { ns: 'login' })}+ </Button>+ </Form>)}diff --git a/web/app/(auth)/init/__tests__/InitPasswordPopup.browser.spec.tsx b/web/app/(auth)/init/__tests__/InitPasswordPopup.browser.spec.tsxnew file mode 100644index 00000000000..6f6e4fded3e--- /dev/null+++ b/web/app/(auth)/init/__tests__/InitPasswordPopup.browser.spec.tsx@@ -0,0 +1,106 @@+import { ORPCError } from '@orpc/client'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import InitPasswordPopup from '../InitPasswordPopup'++const { validatePassword, getInitStatus, replace } = vi.hoisted(() => ({+ validatePassword: vi.fn(),+ getInitStatus: vi.fn(),+ replace: vi.fn(),+}))++vi.mock('@/service/console', () => ({+ consoleQuery: {+ init: {+ get: {+ queryKey: () => ['console', 'init', 'get'],+ queryOptions: (options: object) => ({+ ...options,+ queryKey: ['console', 'init', 'get'],+ queryFn: getInitStatus,+ }),+ },+ post: { mutationOptions: () => ({ mutationFn: validatePassword }) },+ },+ },+}))+vi.mock('@/next/navigation', () => ({ useRouter: () => ({ replace }) }))+vi.mock('@/hooks/use-document-title', () => ({ default: () => {} }))++const renderPopup = () =>+ render(+ <QueryClientProvider client={new QueryClient()}>+ <InitPasswordPopup />+ </QueryClientProvider>,+ )++beforeEach(() => {+ validatePassword.mockReset()+ replace.mockReset()+ getInitStatus.mockReset().mockResolvedValue({ status: 'not_started' })+})++it('asks for the password before submitting', async () => {+ const screen = await renderPopup()++ await userEvent.click(screen.getByRole('button', { name: 'login.validate' }))++ await expect+ .element(screen.getByLabelText('login.adminInitPassword'))+ .toHaveAccessibleDescription('login.error.passwordEmpty')+ expect(validatePassword).not.toHaveBeenCalled()+})++it('reports an incorrect password on the field until it is edited', async () => {+ validatePassword.mockRejectedValue(new ORPCError('init_validate_failed', { status: 401 }))+ const screen = await renderPopup()+ const password = screen.getByLabelText('login.adminInitPassword')++ await userEvent.fill(password, 'wrong')+ await userEvent.keyboard('{Enter}')++ await expect.element(password).toHaveAttribute('aria-invalid', 'true')+ await expect.element(password).toHaveAccessibleDescription('login.error.initPasswordIncorrect')++ await userEvent.type(password, '!')++ await expect.element(password).not.toHaveAttribute('aria-invalid', 'true')+ expect(replace).not.toHaveBeenCalled()+})++it('reports other failures inside the form until the password is edited', async () => {+ validatePassword.mockRejectedValue(new ORPCError('internal_error', { status: 500 }))+ const screen = await renderPopup()+ const password = screen.getByLabelText('login.adminInitPassword')++ await userEvent.fill(password, 'secret')+ await userEvent.keyboard('{Enter}')++ await expect.element(screen.getByRole('alert')).toHaveTextContent('common.api.actionFailed')+ await expect.element(password).not.toHaveAttribute('aria-invalid', 'true')++ await userEvent.type(password, '!')++ await expect.element(screen.getByRole('alert')).not.toBeInTheDocument()+})++it('continues to install once after a correct password', async () => {+ validatePassword.mockResolvedValue({ result: 'success' })+ const screen = await renderPopup()++ await userEvent.fill(screen.getByLabelText('login.adminInitPassword'), 'correct')+ await userEvent.click(screen.getByRole('button', { name: 'login.validate' }))++ await vi.waitFor(() => expect(replace).toHaveBeenCalledWith('/install'))+ expect(replace).toHaveBeenCalledTimes(1)+})++it('sends an already validated instance to install', async () => {+ getInitStatus.mockResolvedValue({ status: 'finished' })++ await renderPopup()++ await vi.waitFor(() => expect(replace).toHaveBeenCalledWith('/install'))+ expect(validatePassword).not.toHaveBeenCalled()+})diff --git a/web/app/(auth)/init/page.tsx b/web/app/(auth)/init/page.tsxindex 4e1f499071c..33e0a5c1a35 100644--- a/web/app/(auth)/init/page.tsx+++ b/web/app/(auth)/init/page.tsx@@ -5,8 +5,6 @@ export function generateMetadata() {return getRouteMetadata('login', ($) => $.adminInitPassword)}-const Init = () => {+export default function Init() {return <InitPasswordPopup />}--export default Initdiff --git a/web/app/(auth)/install/installForm.spec.tsx b/web/app/(auth)/install/installForm.spec.tsxindex 07a0a7c4fe6..25a6f059ecd 100644--- a/web/app/(auth)/install/installForm.spec.tsx+++ b/web/app/(auth)/install/installForm.spec.tsx@@ -1,10 +1,9 @@import type { ReactElement } from 'react'-import { act, fireEvent, screen, waitFor } from '@testing-library/react'+import { fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import ErrorBoundary from '@/app/components/base/error-boundary'-import { consoleClient, consoleQuery } from '@/service/console'+import { consoleClient } from '@/service/console'import { expectLoadingButton } from '@/test/button'-import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'+import { renderWithConsoleQuery } from '@/test/console/query-data'import { encryptPassword } from '@/utils/encryption'import InstallForm from './installForm'@@ -21,7 +20,6 @@ vi.mock('@/service/console', async (importOriginal) => {const { withConsoleClientResponses, withConsoleResponses } =await import('@/test/console/service-responses')const responses = {- 'setup.get': vi.fn(),'setup.post': vi.fn(),'init.get': vi.fn(),'login.post': vi.fn(),@@ -33,30 +31,14 @@ vi.mock('@/service/console', async (importOriginal) => {}})-const mockFetchSetupStatus = vi.mocked(consoleClient.setup.get)-const mockFetchInitValidateStatus = vi.mocked(consoleClient.init.get)const mockSetup = vi.mocked(consoleClient.setup.post)const mockLogin = vi.mocked(consoleClient.login.post)--const createDeferredResponse = <T,>() => {- let resolve: (value: T) => void- const promise = new Promise<T>((onResolve) => {- resolve = onResolve- })- return { promise, resolve: (value: T) => resolve(value) }-}--const prepareLoadedState = () => {- mockFetchSetupStatus.mockResolvedValue({ step: 'not_started' })- mockFetchInitValidateStatus.mockResolvedValue({- status: 'finished',- })-}+const mockFetchInitStatus = vi.mocked(consoleClient.init.get)describe('InstallForm', () => {beforeEach(() => {vi.resetAllMocks()- prepareLoadedState()+ mockFetchInitStatus.mockResolvedValue({ status: 'finished' })})it('should render form after loading', async () => {@@ -75,92 +57,6 @@ describe('InstallForm', () => {expect(screen.getByRole('button', { name: /login\.installBtn/ })).toBeInTheDocument()})- it('waits for both bootstrap checks before showing the account form', async () => {- const setupStatus =- createDeferredResponse<Awaited<ReturnType<typeof consoleClient.setup.get>>>()- const initStatus = createDeferredResponse<Awaited<ReturnType<typeof consoleClient.init.get>>>()- mockFetchSetupStatus.mockReturnValue(setupStatus.promise)- mockFetchInitValidateStatus.mockReturnValue(initStatus.promise)-- render(<InstallForm />)-- expect(screen.queryByLabelText('login.email')).not.toBeInTheDocument()- expect(mockFetchInitValidateStatus).not.toHaveBeenCalled()-- await act(async () => setupStatus.resolve({ step: 'not_started' }))- await waitFor(() => expect(mockFetchInitValidateStatus).toHaveBeenCalledTimes(1))- expect(screen.queryByLabelText('login.email')).not.toBeInTheDocument()-- await act(async () => initStatus.resolve({ status: 'finished' }))- expect(await screen.findByLabelText('login.email')).toBeInTheDocument()- })-- it('redirects to initialization without showing the account form', async () => {- mockFetchInitValidateStatus.mockResolvedValue({ status: 'not_started' })-- render(<InstallForm />)-- await waitFor(() => expect(mockReplace).toHaveBeenCalledWith('/init'))- expect(screen.queryByLabelText('login.email')).not.toBeInTheDocument()- })-- it('revalidates cached bootstrap state before displaying or redirecting', async () => {- const queryClient = createConsoleQueryClient()- queryClient.setQueryData(consoleQuery.setup.get.queryKey(), { step: 'finished' })- queryClient.setQueryData(consoleQuery.init.get.queryKey(), { status: 'not_started' })- const setupStatus =- createDeferredResponse<Awaited<ReturnType<typeof consoleClient.setup.get>>>()- const initStatus = createDeferredResponse<Awaited<ReturnType<typeof consoleClient.init.get>>>()- mockFetchSetupStatus.mockReturnValue(setupStatus.promise)- mockFetchInitValidateStatus.mockReturnValue(initStatus.promise)-- renderWithConsoleQuery(<InstallForm />, { queryClient })-- expect(mockReplace).not.toHaveBeenCalled()- expect(mockFetchInitValidateStatus).not.toHaveBeenCalled()- expect(screen.queryByLabelText('login.email')).not.toBeInTheDocument()-- await act(async () => setupStatus.resolve({ step: 'not_started' }))- await waitFor(() => expect(mockFetchInitValidateStatus).toHaveBeenCalledTimes(1))- expect(mockReplace).not.toHaveBeenCalled()- expect(screen.queryByLabelText('login.email')).not.toBeInTheDocument()-- await act(async () => initStatus.resolve({ status: 'finished' }))- expect(await screen.findByLabelText('login.email')).toBeInTheDocument()- expect(mockReplace).not.toHaveBeenCalled()- expect(queryClient.getQueryData(consoleQuery.setup.get.queryKey())).toEqual({- step: 'not_started',- })- expect(queryClient.getQueryData(consoleQuery.init.get.queryKey())).toEqual({- status: 'finished',- })- })-- it.each(['setup', 'init'] as const)(- 'passes a failed %s check to the error boundary',- async (stage) => {- const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})- const failedCheck = stage === 'setup' ? mockFetchSetupStatus : mockFetchInitValidateStatus- failedCheck.mockRejectedValue(new Error('Bootstrap unavailable'))-- try {- render(- <ErrorBoundary fallback={<div role="alert">Bootstrap unavailable</div>}>- <InstallForm />- </ErrorBoundary>,- )-- expect(await screen.findByRole('alert')).toHaveTextContent('Bootstrap unavailable')- expect(screen.queryByLabelText('login.email')).not.toBeInTheDocument()- expect(mockReplace).not.toHaveBeenCalled()- expect(failedCheck).toHaveBeenCalledTimes(1)- if (stage === 'setup') expect(mockFetchInitValidateStatus).not.toHaveBeenCalled()- } finally {- consoleError.mockRestore()- }- },- )-it('should reveal and hide the password with an accessible action', async () => {const user = userEvent.setup()render(<InstallForm />)@@ -331,15 +227,11 @@ describe('InstallForm', () => {})})- it('should redirect to sign in when setup is finished', async () => {- mockFetchSetupStatus.mockResolvedValue({ step: 'finished' })+ it('sends an instance that still needs its init password to init', async () => {+ mockFetchInitStatus.mockResolvedValue({ status: 'not_started' })render(<InstallForm />)- await waitFor(() => {- expect(mockReplace).toHaveBeenCalledWith('/signin')- })- expect(mockFetchInitValidateStatus).not.toHaveBeenCalled()- expect(screen.queryByLabelText('login.email')).not.toBeInTheDocument()+ await waitFor(() => expect(mockReplace).toHaveBeenCalledWith('/init'))})})diff --git a/web/app/(auth)/install/installForm.tsx b/web/app/(auth)/install/installForm.tsxindex 3b49f6ccde3..19fcaab0d31 100644--- a/web/app/(auth)/install/installForm.tsx+++ b/web/app/(auth)/install/installForm.tsx@@ -15,12 +15,10 @@ import {PasswordFieldInput,PasswordFieldToggle,} from '@langgenius/dify-ui/password-field'-import { useQuery, useQueryClient } from '@tanstack/react-query'-import * as React from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import { useEffect } from 'react'import { useTranslation } from 'react-i18next'import * as z from 'zod'-import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import { validPassword } from '@/config'import { LICENSE_LINK } from '@/constants/link'import useDocumentTitle from '@/hooks/use-document-title'@@ -43,34 +41,12 @@ const InstallForm = () => {useDocumentTitle(pageTitle)const { replace } = useRouter()const queryClient = useQueryClient()- const [isSubmitting, setIsSubmitting] = React.useState(false)- const setupStatus = useQuery(- consoleQuery.setup.get.queryOptions({- staleTime: 0,- retry: false,- throwOnError: true,- refetchOnWindowFocus: false,- refetchOnReconnect: false,- }),- )const initStatus = useQuery(- consoleQuery.init.get.queryOptions({- enabled:- setupStatus.isSuccess && !setupStatus.isFetching && setupStatus.data.step !== 'finished',- staleTime: 0,- retry: false,- throwOnError: true,- refetchOnWindowFocus: false,- refetchOnReconnect: false,- }),+ consoleQuery.init.get.queryOptions({ retry: false, throwOnError: true }),)-- const handleSubmit = async (value: AccountFormValues) => {- if (isSubmitting) return-- setIsSubmitting(true)- try {- // First, setup the admin account+ const isInitPending = initStatus.data?.status === 'not_started'+ const setupAccount = useMutation({+ mutationFn: async (value: AccountFormValues) => {await consoleClient.setup.post({body: {...value,@@ -78,59 +54,34 @@ const InstallForm = () => {},})- // Then, automatically login with the same credentials- const loginRes = await consoleClient.login.post({+ return consoleClient.login.post({body: {email: value.email,password: encodePassword(value.password),},})-- // Store tokens and redirect if login successful+ },+ onSuccess: async (loginRes) => {if (loginRes.result === 'success') {await queryClient.resetQueries({ queryKey: consoleQuery.account.profile.get.key() })replace('/')} else {- // Fallback to signin page if auto-login failsreplace('/signin')}- } finally {- setIsSubmitting(false)- }+ },+ })+ const isSubmitting = setupAccount.isPending || setupAccount.isSuccess++ const handleSubmit = (value: AccountFormValues) => {+ if (isSubmitting) return+ setupAccount.mutate(value)}useEffect(() => {- if (!setupStatus.isSuccess || setupStatus.isFetching) return- if (setupStatus.data.step === 'finished') {- replace('/signin')- } else if (- initStatus.isSuccess &&- !initStatus.isFetching &&- initStatus.data.status === 'not_started'- ) {- replace('/init')- }- }, [- replace,- setupStatus.isSuccess,- setupStatus.isFetching,- setupStatus.data,- initStatus.isSuccess,- initStatus.isFetching,- initStatus.data,- ])-- const canSetup =- setupStatus.isSuccess &&- !setupStatus.isFetching &&- setupStatus.data.step !== 'finished' &&- initStatus.isSuccess &&- !initStatus.isFetching &&- initStatus.data.status !== 'not_started'+ if (isInitPending) replace('/init')+ }, [isInitPending, replace])- return !canSetup ? (- <LoadingPlaceholder />- ) : (+ return (<><div><h1 className="text-[32px] font-bold text-text-primary">{pageTitle}</h1>@@ -140,7 +91,7 @@ const InstallForm = () => {</div><div className="mt-8"><div className="relative">- <Form<AccountFormValues> onFormSubmit={(value) => void handleSubmit(value)}>+ <Form<AccountFormValues> onFormSubmit={handleSubmit}><Fieldname="email"validate={(value) =>diff --git a/web/app/(auth)/install/page.tsx b/web/app/(auth)/install/page.tsxindex 0ba0678fac1..79f545f6e2c 100644--- a/web/app/(auth)/install/page.tsx+++ b/web/app/(auth)/install/page.tsx@@ -1,7 +1,13 @@+import { redirect } from '@/next/navigation'+import { consoleClient } from '@/service/console'+import { resolveServerConsoleApiPrefix } from '@/service/console/server'import InstallForm from './installForm'-const Install = () => {+export default async function Install() {+ if (resolveServerConsoleApiPrefix()) {+ const setup = await consoleClient.setup.get()+ if (setup.step === 'finished') redirect('/signin')+ }+return <InstallForm />}--export default Installdiff --git a/web/app/(auth)/signin/__tests__/normal-form.spec.tsx b/web/app/(auth)/signin/__tests__/normal-form.spec.tsxindex e4caf16e264..c7fc6e600ef 100644--- a/web/app/(auth)/signin/__tests__/normal-form.spec.tsx+++ b/web/app/(auth)/signin/__tests__/normal-form.spec.tsx@@ -93,6 +93,20 @@ describe('NormalForm', () => {expect(screen.getByRole('heading', { level: 1 })).toBeInTheDocument()})+ it('shows the sign-in form while the login probe is still pending', () => {+ mockQueryResults(nonInviteQueryResult, nonInviteQueryResult)+ const queryClient = createConsoleQueryClient()+ void queryClient.query({+ queryKey: userProfileQueryOptions().queryKey,+ queryFn: () => new Promise(() => {}),+ })++ renderWithConsoleQuery(<NormalForm />, { queryClient, accountProfile: null })++ expect(screen.getByRole('heading', { level: 1 })).toBeInTheDocument()+ expect(mockReplace).not.toHaveBeenCalled()+ })+describe('Default Redirects', () => {it('should send logged-in visitors without a redirect target to the console home', async () => {const searchParams = new URLSearchParams()diff --git a/web/app/(auth)/signin/normal-form.tsx b/web/app/(auth)/signin/normal-form.tsxindex 5dd0482fca5..ac6462118b7 100644--- a/web/app/(auth)/signin/normal-form.tsx+++ b/web/app/(auth)/signin/normal-form.tsx@@ -87,7 +87,7 @@ function NormalForm() {const allMethodsAreDisabled = noLoginMethodsConfigured || isInviteCheckErrorconst shouldRedirectLoggedInUser = isLoggedIn && (!isInviteLink || isInvitationForCurrentAccount)const isLoading =- isCheckLoading || shouldRedirectLoggedInUser || (isInviteLink && isInviteCheckLoading)+ shouldRedirectLoggedInUser || (isInviteLink && (isCheckLoading || isInviteCheckLoading))useEffect(() => {if (!isLoggedIn) returndiff --git a/web/app/(auth)/signin/page.tsx b/web/app/(auth)/signin/page.tsxindex 16c204130d9..7dd19cb61ec 100644--- a/web/app/(auth)/signin/page.tsx+++ b/web/app/(auth)/signin/page.tsx@@ -1,4 +1,12 @@+import { ORPCError } from '@orpc/client'+import { dehydrate, HydrationBoundary } from '@tanstack/react-query'+import { getQueryClient } from '@/app/get-query-client'import { getRouteMetadata } from '@/app/route-metadata'+import {+ redirectForBootstrapError,+ serverUserProfileQueryOptions,+} from '@/features/account-profile/server'+import { resolveServerConsoleApiPrefix } from '@/service/console/server'import SignInPage from './sign-in-page'type SignInPageProps = {@@ -14,6 +22,21 @@ export async function generateMetadata({ searchParams }: SignInPageProps) {: getRouteMetadata('login', ($) => $.signBtn)}-export default function SignIn() {- return <SignInPage />+const handleProfileError = (error: unknown) => {+ if (!(error instanceof ORPCError)) return+ redirectForBootstrapError(error)+ if (error.status !== 401) throw error+}++export default async function SignIn() {+ const queryClient = getQueryClient()++ if (resolveServerConsoleApiPrefix())+ await queryClient.query(serverUserProfileQueryOptions()).catch(handleProfileError)++ return (+ <HydrationBoundary state={dehydrate(queryClient)}>+ <SignInPage />+ </HydrationBoundary>+ )}diff --git a/web/app/(commonLayout)/__tests__/hydration-boundary.spec.tsx b/web/app/(commonLayout)/__tests__/hydration-boundary.spec.tsxindex 4a581d5997f..3198b26ff87 100644--- a/web/app/(commonLayout)/__tests__/hydration-boundary.spec.tsx+++ b/web/app/(commonLayout)/__tests__/hydration-boundary.spec.tsx@@ -21,7 +21,10 @@ const mocks = vi.hoisted(() => ({vi.mock('@/app/get-query-client', () => ({ getQueryClient: () => mocks.queryClient }))vi.mock('@/next/headers', () => ({ headers: () => mocks.headers() }))vi.mock('@/next/navigation', () => ({ redirect: (url: string) => mocks.redirect(url) }))-vi.mock('@/features/account-profile/server', () => ({+vi.mock('@/features/account-profile/server', async (importOriginal) => ({+ redirectForBootstrapError: (+ await importOriginal<typeof import('@/features/account-profile/server')>()+ ).redirectForBootstrapError,serverUserProfileQueryOptions: () => ({queryKey: consoleQueryKey('account.profile.get'),queryFn: mocks.profile,diff --git a/web/app/(commonLayout)/hydration-boundary.tsx b/web/app/(commonLayout)/hydration-boundary.tsxindex 08c52c25797..defa2f12b96 100644--- a/web/app/(commonLayout)/hydration-boundary.tsx+++ b/web/app/(commonLayout)/hydration-boundary.tsx@@ -2,7 +2,10 @@ import type { ReactNode } from 'react'import { ORPCError } from '@orpc/client'import { dehydrate, HydrationBoundary, noop } from '@tanstack/react-query'import { getQueryClient } from '@/app/get-query-client'-import { serverUserProfileQueryOptions } from '@/features/account-profile/server'+import {+ redirectForBootstrapError,+ serverUserProfileQueryOptions,+} from '@/features/account-profile/server'import { headers } from '@/next/headers'import { redirect } from '@/next/navigation'import { consoleQuery } from '@/service/console'@@ -28,8 +31,7 @@ const redirectToAuthRefresh = async () => {const handleProfileError = async (error: unknown) => {if (!(error instanceof ORPCError)) throw error- if (error.code === 'not_setup') redirect('/install')- if (error.code === 'not_init_validated') redirect('/init')+ redirectForBootstrapError(error)if (error.status === 401) await redirectToAuthRefresh()throw errordiff --git a/web/app/(shareLayout)/webapp-signin/normalForm.tsx b/web/app/(shareLayout)/webapp-signin/normalForm.tsxindex f65003795d8..cf85fbe3684 100644--- a/web/app/(shareLayout)/webapp-signin/normalForm.tsx+++ b/web/app/(shareLayout)/webapp-signin/normalForm.tsx@@ -2,10 +2,8 @@import { zLicenseStatus } from '@dify/contracts/api/console/system-features/zod.gen'import { RiContractLine, RiDoorLockLine, RiErrorWarningFill } from '@remixicon/react'import { useSuspenseQuery } from '@tanstack/react-query'-import * as React from 'react'-import { useCallback, useEffect, useState } from 'react'+import { useState } from 'react'import { useTranslation } from 'react-i18next'-import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import Link from '@/next/link'import MailAndCodeAuth from './components/mail-and-code-auth'@@ -15,43 +13,21 @@ import SSOAuth from './components/sso-auth'const NormalForm = () => {const { t } = useTranslation(['login'])- const [isLoading, setIsLoading] = useState(true)const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const isNonCloudEdition =systemFeatures.deployment_edition === 'COMMUNITY' ||systemFeatures.deployment_edition === 'ENTERPRISE'const ssoProtocol = systemFeatures.sso_enforced_for_signin_protocolconst hasSsoLogin = systemFeatures.sso_enforced_for_signin && ssoProtocol !== null- const [authType, updateAuthType] = useState<'code' | 'password'>('password')- const [showORLine, setShowORLine] = useState(false)- const [allMethodsAreDisabled, setAllMethodsAreDisabled] = useState(false)+ const hasEmailLogin =+ systemFeatures.enable_email_code_login || systemFeatures.enable_email_password_login+ const [selectedAuthType, updateAuthType] = useState<'code' | 'password' | null>(null)+ const authType =+ selectedAuthType ?? (systemFeatures.enable_email_password_login ? 'password' : 'code')+ const showORLine = (systemFeatures.enable_social_oauth_login || hasSsoLogin) && hasEmailLogin+ const allMethodsAreDisabled =+ !systemFeatures.enable_social_oauth_login && !hasEmailLogin && !hasSsoLogin- const init = useCallback(async () => {- try {- setAllMethodsAreDisabled(- !systemFeatures.enable_social_oauth_login &&- !systemFeatures.enable_email_code_login &&- !systemFeatures.enable_email_password_login &&- !hasSsoLogin,- )- setShowORLine(- (systemFeatures.enable_social_oauth_login || hasSsoLogin) &&- (systemFeatures.enable_email_code_login || systemFeatures.enable_email_password_login),- )- updateAuthType(systemFeatures.enable_email_password_login ? 'password' : 'code')- } catch (error) {- console.error(error)- setAllMethodsAreDisabled(true)- } finally {- setIsLoading(false)- }- }, [hasSsoLogin, systemFeatures])- useEffect(() => {- init()- }, [init])- if (isLoading) {- return <LoadingPlaceholder />- }if (systemFeatures.license?.status === zLicenseStatus.enum.lost) {return (<div className="mx-auto mt-8 w-full">@@ -147,8 +123,7 @@ const NormalForm = () => {</div></div>)}- {(systemFeatures.enable_email_code_login ||- systemFeatures.enable_email_password_login) && (+ {hasEmailLogin && (<>{systemFeatures.enable_email_code_login && authType === 'code' && (<>diff --git a/web/app/__tests__/route-metadata.spec.ts b/web/app/__tests__/route-metadata.spec.tsindex 10511eb6f85..598c233550e 100644--- a/web/app/__tests__/route-metadata.spec.ts+++ b/web/app/__tests__/route-metadata.spec.ts@@ -23,6 +23,8 @@ vi.mock('@/i18n/server', async (importOriginal) => ({getLocaleOnServer: async () => 'en-US',}))+vi.mock('@/service/console/server', () => ({ resolveServerConsoleApiUrl: () => null }))+vi.mock('@/features/account-profile/server', () => ({ serverUserProfileQueryOptions: vi.fn() }))vi.mock('../(auth)/signin/sign-in-page', () => ({ default: () => null }))vi.mock('../(auth)/init/InitPasswordPopup', () => ({ default: () => null }))vi.mock('@/app/components/apps', () => ({ Apps: () => null }))diff --git a/web/app/components/auth-shell/header.tsx b/web/app/components/auth-shell/header.tsxindex 48542d1c9a8..108b822523d 100644--- a/web/app/components/auth-shell/header.tsx+++ b/web/app/components/auth-shell/header.tsx@@ -1,20 +1,15 @@'use client'import { Separator } from '@langgenius/dify-ui/separator'import { useSuspenseQuery } from '@tanstack/react-query'-import dynamic from 'next/dynamic'import { useLocale } from '#i18n'import { DifyLogo } from '@/app/components/base/logo/dify-logo'+import ThemeSelector from '@/app/components/base/theme-selector'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { setLocaleOnClient } from '@/i18n/client'import { languages } from '@/i18n/language'import { useRouter } from '@/next/navigation'import LocaleMenu from './locale-menu'-const ThemeSelector = dynamic(() => import('@/app/components/base/theme-selector'), {- ssr: false,- loading: () => <div className="size-8 bg-transparent" />,-})-const Header = () => {const locale = useLocale()const router = useRouter()diff --git a/web/app/components/base/__tests__/theme-selector.spec.tsx b/web/app/components/base/__tests__/theme-selector.spec.tsxindex 843c36871af..37c91c7d4bb 100644--- a/web/app/components/base/__tests__/theme-selector.spec.tsx+++ b/web/app/components/base/__tests__/theme-selector.spec.tsx@@ -1,5 +1,6 @@import { render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { renderToString } from 'react-dom/server'import ThemeSelector from '../theme-selector'const setTheme = vi.fn()@@ -13,6 +14,13 @@ describe('ThemeSelector', () => {vi.clearAllMocks()})+ it('renders its trigger in the server HTML', () => {+ const container = document.createElement('div')+ container.innerHTML = renderToString(<ThemeSelector />)++ expect(container.querySelector('button[aria-label="common.theme.theme"]')).not.toBeNull()+ })+it.each([['common.theme.light', 'light'],['common.theme.dark', 'dark'],diff --git a/web/app/components/base/theme-selector.tsx b/web/app/components/base/theme-selector.tsxindex a71f43b6694..d8c56c67fe5 100644--- a/web/app/components/base/theme-selector.tsx+++ b/web/app/components/base/theme-selector.tsx@@ -11,6 +11,7 @@ import {MenuTrigger,} from '@langgenius/dify-ui/menu'import { useTheme } from 'next-themes'+import { useSyncExternalStore } from 'react'import { useTranslation } from 'react-i18next'const THEMES = ['light', 'dark', 'system'] as const@@ -20,14 +21,25 @@ const isTheme = (value: string): value is Theme => {return (THEMES as readonly string[]).includes(value)}+const subscribeToNothing = () => () => {}++const useIsHydrated = () =>+ useSyncExternalStore(+ subscribeToNothing,+ () => true,+ () => false,+ )+export default function ThemeSelector() {const direction = useDirection()const { t } = useTranslation(['common'])const { theme, setTheme } = useTheme()+ const isHydrated = useIsHydrated()const currentTheme: Theme = theme && isTheme(theme) ? theme : 'system'const getCurrentIcon = () => {- switch (theme) {+ if (!isHydrated) return <span aria-hidden className="size-4" />+ switch (currentTheme) {case 'light':return <span aria-hidden className="i-ri-sun-line size-4 text-text-tertiary" />case 'dark':diff --git a/web/features/account-profile/server.ts b/web/features/account-profile/server.tsindex 2745d14e084..dd5637df326 100644--- a/web/features/account-profile/server.ts+++ b/web/features/account-profile/server.ts@@ -1,8 +1,16 @@import type { UserProfileWithMeta } from './client'+import { ORPCError } from '@orpc/client'import { queryOptions } from '@tanstack/react-query'+import { redirect } from '@/next/navigation'import { consoleClient, consoleQuery } from '@/service/console'import '@/service/console/server'+export const redirectForBootstrapError = (error: unknown) => {+ if (!(error instanceof ORPCError)) return+ if (error.code === 'not_setup') redirect('/install')+ if (error.code === 'not_init_validated') redirect('/init')+}+export const serverUserProfileQueryOptions = () =>queryOptions<UserProfileWithMeta>({queryKey: consoleQuery.account.profile.get.queryKey(),diff --git a/web/i18n/locales/ar-TN/login.json b/web/i18n/locales/ar-TN/login.jsonindex 4f738947ce4..5675550087f 100644--- a/web/i18n/locales/ar-TN/login.json+++ b/web/i18n/locales/ar-TN/login.json@@ -25,6 +25,7 @@"enterYourName": "يرجى إدخال اسم المستخدم الخاص بك","error.emailEmpty": "عنوان البريد الإلكتروني مطلوب","error.emailInValid": "يرجى إدخال عنوان بريد إلكتروني صالح",+ "error.initPasswordIncorrect": "كلمة مرور التهيئة غير صحيحة.","error.invalidEmailOrPassword": "بريد إلكتروني أو كلمة مرور غير صالحة.","error.invalidSSOProtocol": "بروتوكول SSO غير صالح","error.nameEmpty": "الاسم مطلوب",diff --git a/web/i18n/locales/az-AZ/login.json b/web/i18n/locales/az-AZ/login.jsonindex 194369a5416..297fb62a9db 100644--- a/web/i18n/locales/az-AZ/login.json+++ b/web/i18n/locales/az-AZ/login.json@@ -25,6 +25,7 @@"enterYourName": "İstifadəçi adınızı daxil edin","error.emailEmpty": "E-poçt ünvanı tələb olunur","error.emailInValid": "Etibarlı e-poçt ünvanı daxil edin",+ "error.initPasswordIncorrect": "İlkin quraşdırma parolu yanlışdır.","error.invalidEmailOrPassword": "Etibarsız e-poçt və ya parol.","error.invalidSSOProtocol": "Etibarsız SSO protokolu","error.nameEmpty": "Ad tələb olunur",diff --git a/web/i18n/locales/de-DE/login.json b/web/i18n/locales/de-DE/login.jsonindex 3e874aa3992..0bb41fd92a9 100644--- a/web/i18n/locales/de-DE/login.json+++ b/web/i18n/locales/de-DE/login.json@@ -25,6 +25,7 @@"enterYourName": "Bitte geben Sie Ihren Benutzernamen ein","error.emailEmpty": "E-Mail-Adresse wird benötigt","error.emailInValid": "Bitte gib eine gültige E-Mail-Adresse ein",+ "error.initPasswordIncorrect": "Das Initialisierungspasswort ist falsch.","error.invalidEmailOrPassword": "Ungültige E-Mail oder Passwort.","error.invalidSSOProtocol": "Ungültiges SSO-Protokoll","error.nameEmpty": "Name wird benötigt",diff --git a/web/i18n/locales/en-US/login.json b/web/i18n/locales/en-US/login.jsonindex 2a38fa7933c..11bf6a662e5 100644--- a/web/i18n/locales/en-US/login.json+++ b/web/i18n/locales/en-US/login.json@@ -25,6 +25,7 @@"enterYourName": "Please enter your username","error.emailEmpty": "Email address is required","error.emailInValid": "Please enter a valid email address",+ "error.initPasswordIncorrect": "Incorrect initialization password.","error.invalidEmailOrPassword": "Invalid email or password.","error.invalidSSOProtocol": "Invalid SSO protocol","error.nameEmpty": "Name is required",diff --git a/web/i18n/locales/es-ES/login.json b/web/i18n/locales/es-ES/login.jsonindex 28e4e0aee36..2f4ca577eee 100644--- a/web/i18n/locales/es-ES/login.json+++ b/web/i18n/locales/es-ES/login.json@@ -25,6 +25,7 @@"enterYourName": "Por favor, introduzca su nombre de usuario","error.emailEmpty": "Se requiere una dirección de correo electrónico","error.emailInValid": "Por favor, ingresa una dirección de correo electrónico válida",+ "error.initPasswordIncorrect": "La contraseña de inicialización es incorrecta.","error.invalidEmailOrPassword": "Correo electrónico o contraseña inválidos.","error.invalidSSOProtocol": "Protocolo SSO inválido","error.nameEmpty": "Se requiere un nombre",diff --git a/web/i18n/locales/fa-IR/login.json b/web/i18n/locales/fa-IR/login.jsonindex 3bed2398903..ae212e2645a 100644--- a/web/i18n/locales/fa-IR/login.json+++ b/web/i18n/locales/fa-IR/login.json@@ -25,6 +25,7 @@"enterYourName": "لطفا نام کاربری خود را وارد کنید","error.emailEmpty": "آدرس ایمیل لازم است","error.emailInValid": "لطفاً یک آدرس ایمیل معتبر وارد کنید",+ "error.initPasswordIncorrect": "رمز عبور راهاندازی اولیه نادرست است.","error.invalidEmailOrPassword": "ایمیل یا رمز عبور نامعتبر است.","error.invalidSSOProtocol": "پروتکل SSO نامعتبر است","error.nameEmpty": "نام لازم است",diff --git a/web/i18n/locales/fr-FR/login.json b/web/i18n/locales/fr-FR/login.jsonindex 6c177a2d8fd..282368b2515 100644--- a/web/i18n/locales/fr-FR/login.json+++ b/web/i18n/locales/fr-FR/login.json@@ -25,6 +25,7 @@"enterYourName": "Veuillez entrer votre nom d’utilisateur","error.emailEmpty": "Une adresse e-mail est requise","error.emailInValid": "Veuillez entrer une adresse email valide",+ "error.initPasswordIncorrect": "Le mot de passe d’initialisation est incorrect.","error.invalidEmailOrPassword": "Adresse e-mail ou mot de passe invalide.","error.invalidSSOProtocol": "Protocole SSO invalide","error.nameEmpty": "Le nom est requis",diff --git a/web/i18n/locales/hi-IN/login.json b/web/i18n/locales/hi-IN/login.jsonindex 6535e372f8a..d05d09d1b82 100644--- a/web/i18n/locales/hi-IN/login.json+++ b/web/i18n/locales/hi-IN/login.json@@ -25,6 +25,7 @@"enterYourName": "कृपया अपना उपयोगकर्ता नाम दर्ज करें","error.emailEmpty": "ईमेल पता आवश्यक है","error.emailInValid": "कृपया एक मान्य ईमेल पता दर्ज करें",+ "error.initPasswordIncorrect": "आरंभीकरण पासवर्ड गलत है।","error.invalidEmailOrPassword": "अमान्य ईमेल या पासवर्ड।","error.invalidSSOProtocol": "अमान्य SSO प्रोटोकॉल","error.nameEmpty": "नाम आवश्यक है",diff --git a/web/i18n/locales/id-ID/login.json b/web/i18n/locales/id-ID/login.jsonindex bb4d52a0f09..7af77d482af 100644--- a/web/i18n/locales/id-ID/login.json+++ b/web/i18n/locales/id-ID/login.json@@ -25,6 +25,7 @@"enterYourName": "Silakan masukkan nama pengguna Anda","error.emailEmpty": "Alamat email diperlukan","error.emailInValid": "Silakan masukkan alamat email yang valid",+ "error.initPasswordIncorrect": "Kata sandi inisialisasi salah.","error.invalidEmailOrPassword": "Email atau kata sandi tidak valid.","error.invalidSSOProtocol": "Protokol SSO tidak valid","error.nameEmpty": "Nama diperlukan",diff --git a/web/i18n/locales/it-IT/login.json b/web/i18n/locales/it-IT/login.jsonindex 620e28375b0..2ea92bd15d8 100644--- a/web/i18n/locales/it-IT/login.json+++ b/web/i18n/locales/it-IT/login.json@@ -25,6 +25,7 @@"enterYourName": "Inserisci il tuo nome utente","error.emailEmpty": "L'indirizzo email è obbligatorio","error.emailInValid": "Per favore inserisci un indirizzo email valido",+ "error.initPasswordIncorrect": "La password di inizializzazione non è corretta.","error.invalidEmailOrPassword": "Email o password non validi.","error.invalidSSOProtocol": "Protocollo SSO non valido","error.nameEmpty": "Il nome è obbligatorio",diff --git a/web/i18n/locales/ja-JP/login.json b/web/i18n/locales/ja-JP/login.jsonindex a425ff99740..54b23346929 100644--- a/web/i18n/locales/ja-JP/login.json+++ b/web/i18n/locales/ja-JP/login.json@@ -25,6 +25,7 @@"enterYourName": "ユーザー名を入力してください","error.emailEmpty": "メールアドレスは必須です","error.emailInValid": "有効なメールアドレスを入力してください",+ "error.initPasswordIncorrect": "初期化パスワードが正しくありません。","error.invalidEmailOrPassword": "無効なメールアドレスまたはパスワードです。","error.invalidSSOProtocol": "無効なSSOプロトコル","error.nameEmpty": "名前は必須です",diff --git a/web/i18n/locales/ko-KR/login.json b/web/i18n/locales/ko-KR/login.jsonindex 3e25bfc9a87..a89aa3249f3 100644--- a/web/i18n/locales/ko-KR/login.json+++ b/web/i18n/locales/ko-KR/login.json@@ -25,6 +25,7 @@"enterYourName": "사용자 이름을 입력해 주세요","error.emailEmpty": "이메일 주소를 입력하세요.","error.emailInValid": "유효한 이메일 주소를 입력하세요.",+ "error.initPasswordIncorrect": "초기화 비밀번호가 올바르지 않습니다.","error.invalidEmailOrPassword": "유효하지 않은 이메일이나 비밀번호입니다.","error.invalidSSOProtocol": "유효하지 않은 SSO 프로토콜","error.nameEmpty": "사용자 이름을 입력하세요.",diff --git a/web/i18n/locales/lo-LA/login.json b/web/i18n/locales/lo-LA/login.jsonindex 4fdb2cb4ed0..9b9f885a7b6 100644--- a/web/i18n/locales/lo-LA/login.json+++ b/web/i18n/locales/lo-LA/login.json@@ -25,6 +25,7 @@"enterYourName": "ກະລຸນາປ້ອນຊື່ຜູ້ໃຊ້ຂອງທ່ານ","error.emailEmpty": "ກະລຸນາປ້ອນທີ່ຢູ່ອີເມວ","error.emailInValid": "ກະລຸນາປ້ອນທີ່ຢູ່ອີເມວທີ່ຖືກຕ້ອງ",+ "error.initPasswordIncorrect": "ລະຫັດຜ່ານການເລີ່ມຕົ້ນບໍ່ຖືກຕ້ອງ.","error.invalidEmailOrPassword": "ອີເມວ ຫຼື ລະຫັດຜ່ານບໍ່ຖືກຕ້ອງ","error.invalidSSOProtocol": "ໂປຣໂຕຄໍ SSO ບໍ່ຖືກຕ້ອງ","error.nameEmpty": "ກະລຸນາປ້ອນຊື່",diff --git a/web/i18n/locales/nl-NL/login.json b/web/i18n/locales/nl-NL/login.jsonindex 2bc5129d522..b9454057ee6 100644--- a/web/i18n/locales/nl-NL/login.json+++ b/web/i18n/locales/nl-NL/login.json@@ -25,6 +25,7 @@"enterYourName": "Please enter your username","error.emailEmpty": "Email address is required","error.emailInValid": "Please enter a valid email address",+ "error.initPasswordIncorrect": "Het initialisatiewachtwoord is onjuist.","error.invalidEmailOrPassword": "Invalid email or password.","error.invalidSSOProtocol": "Ongeldig SSO-protocol","error.nameEmpty": "Name is required",diff --git a/web/i18n/locales/pl-PL/login.json b/web/i18n/locales/pl-PL/login.jsonindex 5a75f4c9812..9f277310c5e 100644--- a/web/i18n/locales/pl-PL/login.json+++ b/web/i18n/locales/pl-PL/login.json@@ -25,6 +25,7 @@"enterYourName": "Podaj swoją nazwę użytkownika","error.emailEmpty": "Adres e-mail jest wymagany","error.emailInValid": "Proszę wpisać prawidłowy adres e-mail",+ "error.initPasswordIncorrect": "Nieprawidłowe hasło inicjalizacji.","error.invalidEmailOrPassword": "Nieprawidłowy adres e-mail lub hasło.","error.invalidSSOProtocol": "Nieprawidłowy protokół SSO","error.nameEmpty": "Nazwa jest wymagana",diff --git a/web/i18n/locales/pt-BR/login.json b/web/i18n/locales/pt-BR/login.jsonindex 17e6c202dc7..03986237f6e 100644--- a/web/i18n/locales/pt-BR/login.json+++ b/web/i18n/locales/pt-BR/login.json@@ -25,6 +25,7 @@"enterYourName": "Por favor, digite seu nome de usuário","error.emailEmpty": "O endereço de e-mail é obrigatório","error.emailInValid": "Digite um endereço de e-mail válido",+ "error.initPasswordIncorrect": "A senha de inicialização está incorreta.","error.invalidEmailOrPassword": "E-mail ou senha inválidos.","error.invalidSSOProtocol": "Protocolo SSO inválido","error.nameEmpty": "O nome é obrigatório",diff --git a/web/i18n/locales/ro-RO/login.json b/web/i18n/locales/ro-RO/login.jsonindex 00a784cc3d9..c4e131bb61f 100644--- a/web/i18n/locales/ro-RO/login.json+++ b/web/i18n/locales/ro-RO/login.json@@ -25,6 +25,7 @@"enterYourName": "Vă rugăm să introduceți numele de utilizator","error.emailEmpty": "Adresa de email este obligatorie","error.emailInValid": "Te rugăm să introduci o adresă de email validă",+ "error.initPasswordIncorrect": "Parola de inițializare este incorectă.","error.invalidEmailOrPassword": "Email sau parolă invalidă.","error.invalidSSOProtocol": "Protocol SSO invalid","error.nameEmpty": "Numele este obligatoriu",diff --git a/web/i18n/locales/ru-RU/login.json b/web/i18n/locales/ru-RU/login.jsonindex f5eef6f0b47..2e36a3b75fc 100644--- a/web/i18n/locales/ru-RU/login.json+++ b/web/i18n/locales/ru-RU/login.json@@ -25,6 +25,7 @@"enterYourName": "Пожалуйста, введите свое имя пользователя","error.emailEmpty": "Адрес электронной почты обязателен","error.emailInValid": "Пожалуйста, введите действительный адрес электронной почты",+ "error.initPasswordIncorrect": "Неверный пароль инициализации.","error.invalidEmailOrPassword": "Неверный адрес электронной почты или пароль.","error.invalidSSOProtocol": "Неверный протокол SSO","error.nameEmpty": "Имя обязательно",diff --git a/web/i18n/locales/sl-SI/login.json b/web/i18n/locales/sl-SI/login.jsonindex 858a9c590a7..bd0bb203a01 100644--- a/web/i18n/locales/sl-SI/login.json+++ b/web/i18n/locales/sl-SI/login.json@@ -25,6 +25,7 @@"enterYourName": "Prosimo, vnesite svoje uporabniško ime","error.emailEmpty": "E-poštni naslov je obvezen","error.emailInValid": "Prosimo, vnesite veljaven e-poštni naslov",+ "error.initPasswordIncorrect": "Inicializacijsko geslo ni pravilno.","error.invalidEmailOrPassword": "Neveljaven e-poštni naslov ali geslo.","error.invalidSSOProtocol": "Neveljaven protokol SSO","error.nameEmpty": "Ime je obvezno",diff --git a/web/i18n/locales/th-TH/login.json b/web/i18n/locales/th-TH/login.jsonindex a2895dc99a1..5361d773dbb 100644--- a/web/i18n/locales/th-TH/login.json+++ b/web/i18n/locales/th-TH/login.json@@ -25,6 +25,7 @@"enterYourName": "โปรดป้อนชื่อผู้ใช้ของคุณ","error.emailEmpty": "ต้องระบุที่อยู่อีเมล","error.emailInValid": "โปรดป้อนที่อยู่อีเมลที่ถูกต้อง",+ "error.initPasswordIncorrect": "รหัสผ่านสำหรับการเริ่มต้นไม่ถูกต้อง","error.invalidEmailOrPassword": "อีเมลหรือรหัสผ่านไม่ถูกต้อง.","error.invalidSSOProtocol": "โปรโตคอล SSO ไม่ถูกต้อง","error.nameEmpty": "ต้องระบุชื่อ",diff --git a/web/i18n/locales/tr-TR/login.json b/web/i18n/locales/tr-TR/login.jsonindex bea1a3f40ce..5a889d07c0b 100644--- a/web/i18n/locales/tr-TR/login.json+++ b/web/i18n/locales/tr-TR/login.json@@ -25,6 +25,7 @@"enterYourName": "Lütfen kullanıcı adınızı giriniz","error.emailEmpty": "E-posta adresi gereklidir","error.emailInValid": "Geçerli bir e-posta adresi girin",+ "error.initPasswordIncorrect": "Başlatma parolası yanlış.","error.invalidEmailOrPassword": "Geçersiz e-posta veya şifre.","error.invalidSSOProtocol": "Geçersiz SSO protokolü","error.nameEmpty": "İsim gereklidir",diff --git a/web/i18n/locales/uk-UA/login.json b/web/i18n/locales/uk-UA/login.jsonindex 7434e9271f6..1323b07b2fe 100644--- a/web/i18n/locales/uk-UA/login.json+++ b/web/i18n/locales/uk-UA/login.json@@ -25,6 +25,7 @@"enterYourName": "Будь ласка, введіть своє ім'я користувача","error.emailEmpty": "Адреса електронної пошти обов'язкова","error.emailInValid": "Введіть дійсну адресу електронної пошти",+ "error.initPasswordIncorrect": "Неправильний пароль ініціалізації.","error.invalidEmailOrPassword": "Невірний електронний лист або пароль.","error.invalidSSOProtocol": "Недійсний протокол SSO","error.nameEmpty": "Ім'я обов'язкове",diff --git a/web/i18n/locales/vi-VN/login.json b/web/i18n/locales/vi-VN/login.jsonindex 1e86a36aa00..e3814f624dd 100644--- a/web/i18n/locales/vi-VN/login.json+++ b/web/i18n/locales/vi-VN/login.json@@ -25,6 +25,7 @@"enterYourName": "Vui lòng nhập tên người dùng của bạn","error.emailEmpty": "Vui lòng nhập địa chỉ email","error.emailInValid": "Vui lòng nhập một địa chỉ email hợp lệ",+ "error.initPasswordIncorrect": "Mật khẩu khởi tạo không chính xác.","error.invalidEmailOrPassword": "Email hoặc mật khẩu không hợp lệ.","error.invalidSSOProtocol": "Giao thức SSO không hợp lệ","error.nameEmpty": "Vui lòng nhập tên",diff --git a/web/i18n/locales/zh-Hans/login.json b/web/i18n/locales/zh-Hans/login.jsonindex ce0ea61d350..ca35488d54b 100644--- a/web/i18n/locales/zh-Hans/login.json+++ b/web/i18n/locales/zh-Hans/login.json@@ -25,6 +25,7 @@"enterYourName": "请输入用户名","error.emailEmpty": "邮箱不能为空","error.emailInValid": "请输入有效的邮箱地址",+ "error.initPasswordIncorrect": "初始化密码不正确。","error.invalidEmailOrPassword": "邮箱或密码错误","error.invalidSSOProtocol": "无效的 SSO 协议","error.nameEmpty": "用户名不能为空",diff --git a/web/i18n/locales/zh-Hant/login.json b/web/i18n/locales/zh-Hant/login.jsonindex fb4611249e9..48d0225fda8 100644--- a/web/i18n/locales/zh-Hant/login.json+++ b/web/i18n/locales/zh-Hant/login.json@@ -25,6 +25,7 @@"enterYourName": "請輸入您的使用者名","error.emailEmpty": "郵箱不能為空","error.emailInValid": "請輸入有效的郵箱地址",+ "error.initPasswordIncorrect": "初始化密碼不正確。","error.invalidEmailOrPassword": "無效的電子郵件或密碼。","error.invalidSSOProtocol": "無效的 SSO 協定","error.nameEmpty": "使用者名稱不能為空",diff --git a/web/i18n/resources.generated.d.ts b/web/i18n/resources.generated.d.tsindex dcd48c7b964..48060ccb99b 100644--- a/web/i18n/resources.generated.d.ts+++ b/web/i18n/resources.generated.d.ts@@ -4141,6 +4141,7 @@ export default interface Resources {enterYourName: 'Please enter your username''error.emailEmpty': 'Email address is required''error.emailInValid': 'Please enter a valid email address'+ 'error.initPasswordIncorrect': 'Incorrect initialization password.''error.invalidEmailOrPassword': 'Invalid email or password.''error.invalidSSOProtocol': 'Invalid SSO protocol''error.nameEmpty': 'Name is required'