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
refactor(web): own website settings dialog sessions (#43525)
yyh78f941d3de5c
diff --git a/web/app/components/app/access-point/__tests__/built-in-access-points.spec.tsx b/web/app/components/app/access-point/__tests__/built-in-access-points.spec.tsxindex 004da25a563..0be97cea37e 100644--- a/web/app/components/app/access-point/__tests__/built-in-access-points.spec.tsx+++ b/web/app/components/app/access-point/__tests__/built-in-access-points.spec.tsx@@ -60,9 +60,8 @@ vi.mock('@/service/use-workflow', () => ({vi.mock('../shared/use-access-point-actions', () => ({useAccessPointActions: () => ({- handleResult: vi.fn(),refreshAppDetail: vi.fn(),- saveSiteConfig: vi.fn(),+ saveSiteConfig: vi.fn().mockResolvedValue(true),}),}))diff --git a/web/app/components/app/access-point/__tests__/environment-access-point-cards.spec.tsx b/web/app/components/app/access-point/__tests__/environment-access-point-cards.spec.tsxindex 507012a5029..5bdcc6ca4f5 100644--- a/web/app/components/app/access-point/__tests__/environment-access-point-cards.spec.tsx+++ b/web/app/components/app/access-point/__tests__/environment-access-point-cards.spec.tsx@@ -1,9 +1,11 @@import type { ReactElement } from 'react'-import { QueryClientProvider } from '@tanstack/react-query'import { screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'import { toast } from '@/app/notifications'import { consoleQuery } from '@/service/console'+import { seedFeatures, seedSystemFeatures } from '@/test/console/query-data'+import { QueryClientTestProvider } from '@/test/console/query-provider'import { render } from '@/test/console/render'import { createAppDetailFixture, createAppSiteFixture } from '@/test/fixtures/app'import { createTestQueryClient } from '@/test/query-client'@@ -13,6 +15,7 @@ import { EnvironmentWebAppCard } from '../deployed-environment-access-points/envconst mocks = vi.hoisted(() => ({getApi: vi.fn(),+ saveSiteConfig: vi.fn(),getSite: vi.fn(),getSubjects: vi.fn(),resetSite: vi.fn(),@@ -41,15 +44,10 @@ vi.mock('@/app/components/base/app-icon', () => ({vi.mock('@/app/components/app/access-point/shared/use-access-point-actions', () => ({useAccessPointActions: () => ({- saveSiteConfig: vi.fn(),+ saveSiteConfig: mocks.saveSiteConfig,}),}))-vi.mock('@/app/components/app/overview/settings', () => ({- default: ({ isShow }: { isShow: boolean }) =>- isShow ? <div role="dialog" aria-label="environment settings" /> : null,-}))-vi.mock('../deployed-environment-access-points/environment-access-control', () => ({EnvironmentAccessControl: (props: {appId: string@@ -105,6 +103,8 @@ const api = {}function renderCard(ui: ReactElement, queryClient = createTestQueryClient()) {+ seedFeatures(queryClient)+ seedSystemFeatures(queryClient)queryClient.setQueryData(consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: 'app-1' } } }),createAppDetailFixture({@@ -121,7 +121,11 @@ function renderCard(ui: ReactElement, queryClient = createTestQueryClient()) {},})- return render(<QueryClientProvider client={queryClient}>{ui}</QueryClientProvider>)+ return render(+ <NuqsTestingAdapter>+ <QueryClientTestProvider queryClient={queryClient}>{ui}</QueryClientTestProvider>+ </NuqsTestingAdapter>,+ )}function createDeferredPromise<T>() {@@ -141,6 +145,7 @@ afterAll(() => vi.unstubAllGlobals())describe('environment access point cards', () => {beforeEach(() => {vi.clearAllMocks()+ mocks.saveSiteConfig.mockResolvedValue(true)mockAppMode = AppModeEnum.WORKFLOWvi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => {const request = new Request(input, init)@@ -401,7 +406,19 @@ describe('environment access point cards', () => {await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())await user.click(screen.getByRole('button', { name: /settings\.settings/ }))- expect(screen.getByRole('dialog', { name: 'environment settings' })).toBeInTheDocument()+ const settings = await screen.findByRole('dialog', {+ name: 'appOverview.overview.appInfo.settings.title',+ })+ await user.clear(within(settings).getByPlaceholderText('app.appNamePlaceholder'))+ await user.type(+ within(settings).getByPlaceholderText('app.appNamePlaceholder'),+ 'Environment portal',+ )+ await user.click(within(settings).getByRole('button', { name: 'common.operation.save' }))+ expect(mocks.saveSiteConfig).toHaveBeenCalledWith(+ expect.objectContaining({ title: 'Environment portal' }),+ )+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())})it('keeps view actions available while disabling deployed Web App management', async () => {diff --git a/web/app/components/app/access-point/__tests__/use-access-point-actions.spec.ts b/web/app/components/app/access-point/__tests__/use-access-point-actions.spec.tsindex 82dd1c690a6..75cd5775196 100644--- a/web/app/components/app/access-point/__tests__/use-access-point-actions.spec.ts+++ b/web/app/components/app/access-point/__tests__/use-access-point-actions.spec.ts@@ -105,7 +105,9 @@ describe('useAccessPointActions', () => {it('reports a failed save without invalidating app details', async () => {mocks.updateAppSiteConfig.mockRejectedValueOnce(new Error('request failed'))const { result } = renderActions()- await act(async () => result.current.saveSiteConfig(siteConfig))+ await act(async () => {+ expect(await result.current.saveSiteConfig(siteConfig)).toBe(false)+ })expect(mocks.fetchAppDetail).not.toHaveBeenCalled()expect(mocks.toast).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully', {type: 'error',@@ -117,7 +119,7 @@ describe('useAccessPointActions', () => {const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')await act(async () => {- await result.current.saveSiteConfig(siteConfig)+ expect(await result.current.saveSiteConfig(siteConfig)).toBe(true)})expect(mocks.updateAppSiteConfig).toHaveBeenCalledWith({@@ -145,7 +147,7 @@ describe('useAccessPointActions', () => {const { result } = renderActions('app-1', false)await act(async () => {- await result.current.saveSiteConfig(siteConfig)+ expect(await result.current.saveSiteConfig(siteConfig)).toBe(false)})expect(mocks.updateAppSiteConfig).not.toHaveBeenCalled()diff --git a/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx b/web/app/components/app/access-point/__tests__/web-app-card.spec.tsxindex 51bbe652e25..abdfc33d7a4 100644--- a/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx+++ b/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx@@ -92,10 +92,6 @@ vi.mock('@/context/i18n', () => ({useDocLink: () => (path: string) => `https://docs.example.test/en${path}`,}))-vi.mock('@/app/components/app/overview/settings', () => ({- default: () => null,-}))-function createAppInfo(mode: AppModeEnum): AppDetailWithSite {return createAppDetailFixture({access_mode: AccessMode.PUBLIC,@@ -182,7 +178,7 @@ function QueryConnectedWebAppCard({canManageAccessPoint={canManageAccessPoint}showAccessControl={showAccessControl}onRefreshApp={onRefreshApp}- onSaveSiteConfig={vi.fn().mockResolvedValue(undefined)}+ onSaveSiteConfig={vi.fn().mockResolvedValue(true)}workflow={workflow}/>)diff --git a/web/app/components/app/access-point/built-in-access-points/web-app-card.tsx b/web/app/components/app/access-point/built-in-access-points/web-app-card.tsxindex 6ef9b1b6fba..47699bfb05b 100644--- a/web/app/components/app/access-point/built-in-access-points/web-app-card.tsx+++ b/web/app/components/app/access-point/built-in-access-points/web-app-card.tsx@@ -24,7 +24,7 @@ import { useTranslation } from 'react-i18next'import AccessControl from '@/app/components/app/app-access-control'import { CustomizeDialog } from '@/app/components/app/overview/customize'import { EmbeddedDialogContent } from '@/app/components/app/overview/embedded'-import SettingsModal from '@/app/components/app/overview/settings'+import { SettingsDialog } from '@/app/components/app/overview/settings'import { WorkflowLaunchDialog } from '@/app/components/app/overview/workflow-launch-dialog'import { AccessPointCard } from '@/app/components/base/access-point/card'import { getAccessPointStatus } from '@/app/components/base/access-point/status'@@ -67,7 +67,7 @@ type WebAppAccessPointCardProps = {highlighted?: booleanshowAccessControl: booleanonRefreshApp: () => Promise<void>- onSaveSiteConfig: (params: AppSiteUpdatePayload) => Promise<void>+ onSaveSiteConfig: (params: AppSiteUpdatePayload) => Promise<boolean>workflow: PublishedWorkflow}@@ -90,7 +90,6 @@ export function WebAppAccessPointCard({'deployments','navigation',])- const [showSettings, setShowSettings] = useState(false)const [showAccess, setShowAccess] = useState(false)const [showRegenerate, setShowRegenerate] = useState(false)const [showWorkflowLaunch, setShowWorkflowLaunch] = useState(false)@@ -227,15 +226,16 @@ export function WebAppAccessPointCard({mode={appInfo.mode}disabled={!actionsAvailable || !canManageAccessPoint}/>- <Button- className="flex items-center gap-1 px-3"- variant="secondary"+ <SettingsDialog+ key={appInfo.id}+ isChat={+ appInfo.mode !== AppModeEnum.COMPLETION && appInfo.mode !== AppModeEnum.WORKFLOW+ }+ canDeploy={canDeploy}+ appInfo={site ? { id: appInfo.id, mode: appInfo.mode, site } : undefined}disabled={siteAvailability !== 'available' || !canManageAccessPoint}- onClick={() => setShowSettings(true)}- >- <span aria-hidden className="i-ri-equalizer-2-line size-4" />- {t(($) => $['settings.settings'], { ns: 'navigation' })}- </Button>+ onSave={onSaveSiteConfig}+ /></>}>@@ -277,16 +277,6 @@ export function WebAppAccessPointCard({))}</AccessPointCard>- {site && (- <SettingsModal- isChat={appInfo.mode !== AppModeEnum.COMPLETION && appInfo.mode !== AppModeEnum.WORKFLOW}- canDeploy={canDeploy}- appInfo={{ id: appInfo.id, mode: appInfo.mode, site }}- isShow={showSettings}- onClose={() => setShowSettings(false)}- onSave={onSaveSiteConfig}- />- )}{showAccess && (<AccessControlapp={appInfo}diff --git a/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-card.tsx b/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-card.tsxindex a036550bf13..cc8f0a2a08c 100644--- a/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-card.tsx+++ b/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-card.tsx@@ -9,12 +9,11 @@ import {AlertDialogFooter,AlertDialogTitle,} from '@langgenius/dify-ui/alert-dialog'-import { Button } from '@langgenius/dify-ui/button'import { useMutation, useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'import { useState } from 'react'import { useTranslation } from 'react-i18next'import { CustomizeDialog } from '@/app/components/app/overview/customize'-import SettingsModal from '@/app/components/app/overview/settings'+import { SettingsDialog } from '@/app/components/app/overview/settings'import { AccessPointCard } from '@/app/components/base/access-point/card'import { AccessPointUrl } from '@/app/components/base/access-point/url'import AppIcon from '@/app/components/base/app-icon'@@ -65,7 +64,6 @@ export function EnvironmentWebAppCard({)const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const actions = useAccessPointActions(appId, canManageAccessPoint)- const [showSettings, setShowSettings] = useState(false)const [showAccess, setShowAccess] = useState(false)const [showRegenerate, setShowRegenerate] = useState(false)const params = {@@ -195,15 +193,18 @@ export function EnvironmentWebAppCard({mode={appInfo?.mode}disabled={!actionsAvailable || !apiQuery.isSuccess || !canManageAccessPoint}/>- <Button- className="flex items-center gap-1 px-3"- variant="secondary"- disabled={!appInfo?.site || !siteQuery.isSuccess || !canManageAccessPoint}- onClick={() => setShowSettings(true)}- >- <span aria-hidden className="i-ri-equalizer-2-line size-4" />- {t(($) => $['settings.settings'], { ns: 'navigation' })}- </Button>+ <SettingsDialog+ key={appId}+ isChat={false}+ canDeploy+ appInfo={+ appInfo?.site+ ? { id: appInfo.id, mode: appInfo.mode, site: appInfo.site }+ : undefined+ }+ disabled={!siteQuery.isSuccess || !canManageAccessPoint}+ onSave={actions.saveSiteConfig}+ /></>}>@@ -242,16 +243,6 @@ export function EnvironmentWebAppCard({))}</AccessPointCard>- {appInfo?.site && (- <SettingsModal- isChat={false}- canDeploy- appInfo={{ id: appInfo.id, mode: appInfo.mode, site: appInfo.site }}- isShow={showSettings}- onClose={() => setShowSettings(false)}- onSave={actions.saveSiteConfig}- />- )}{showAccess && (<EnvironmentAccessControlappId={appId}diff --git a/web/app/components/app/access-point/shared/use-access-point-actions.ts b/web/app/components/app/access-point/shared/use-access-point-actions.tsindex 83f6e8b7531..774096745c3 100644--- a/web/app/components/app/access-point/shared/use-access-point-actions.ts+++ b/web/app/components/app/access-point/shared/use-access-point-actions.ts@@ -25,8 +25,8 @@ export function useAccessPointActions(appId: string, canManageAccessPoint: boole)const saveSiteConfig = useCallback(- async (params: AppSiteUpdatePayload) => {- if (!canManageAccessPoint) return+ async (params: AppSiteUpdatePayload): Promise<boolean> => {+ if (!canManageAccessPoint) return falseconst [error] = await asyncRunSafe(updateSiteConfig({params: { app_id: appId },@@ -41,6 +41,7 @@ export function useAccessPointActions(appId: string, canManageAccessPoint: booletype: error ? 'error' : 'success',},)+ return !error},[appId, canManageAccessPoint, t, updateSiteConfig],)diff --git a/web/app/components/app/overview/settings/__tests__/index.spec.tsx b/web/app/components/app/overview/settings/__tests__/index.spec.tsxindex f6c06fd66bc..7705cc89756 100644--- a/web/app/components/app/overview/settings/__tests__/index.spec.tsx+++ b/web/app/components/app/overview/settings/__tests__/index.spec.tsx@@ -1,6 +1,7 @@+import type { AppSiteUpdatePayload } from '@dify/contracts/api/console/apps/types.gen'import type { ReactElement, ReactNode } from 'react'import type { SettingsAppInfo } from '../index'-import { fireEvent, screen, waitFor } from '@testing-library/react'+import { act, fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { NuqsTestingAdapter } from 'nuqs/adapters/testing'import { consoleQuery } from '@/service/console'@@ -10,7 +11,7 @@ import {} from '@/test/console/query-data'import { createAppSiteFixture } from '@/test/fixtures/app'import { AppModeEnum } from '@/types/app'-import SettingsModal from '../index'+import { SettingsDialog } from '../index'const onPricingUrlUpdate = vi.hoisted(() => vi.fn())@@ -64,8 +65,7 @@ vi.mock('@/app/notifications', () => ({promise: toastMocks.promise,}),}))-const mockOnClose = vi.fn()-const mockOnSave = vi.fn()+const mockOnSave = vi.fn<(params: AppSiteUpdatePayload) => Promise<boolean>>()vi.mock('@/context/i18n', async () => {const actual = await vi.importActual<typeof import('@/context/i18n')>('@/context/i18n')@@ -97,17 +97,16 @@ const mockAppInfo = {mode: AppModeEnum.ADVANCED_CHAT,} satisfies SettingsAppInfo-const renderSettingsModal = (appInfo: SettingsAppInfo = mockAppInfo, canDeploy = false) =>- render(- <SettingsModal- isChat- canDeploy={canDeploy}- isShow- appInfo={appInfo}- onClose={mockOnClose}- onSave={mockOnSave}- />,+const triggerName = 'navigation.settings.settings'+const dialogName = 'appOverview.overview.appInfo.settings.title'++const renderSettingsDialog = async (appInfo: SettingsAppInfo = mockAppInfo, canDeploy = false) => {+ const view = render(+ <SettingsDialog isChat canDeploy={canDeploy} appInfo={appInfo} onSave={mockOnSave} />,)+ await userEvent.setup().click(screen.getByRole('button', { name: triggerName }))+ return view+}const inputPlaceholderName = 'appOverview.overview.appInfo.settings.more.inputPlaceholder'@@ -120,11 +119,10 @@ function render(...args: Parameters<typeof renderWithData>) {return { ...result, rerender: (ui: ReactElement) => result.rerender(wrap(ui)) }}-describe('SettingsModal', () => {+describe('SettingsDialog', () => {beforeEach(() => {toastMocks.call.mockClear()- mockOnClose.mockClear()- mockOnSave.mockClear()+ mockOnSave.mockReset().mockResolvedValue(true)onPricingUrlUpdate.mockClear()deploymentEdition = 'CLOUD'copyrightEnabled = true@@ -135,7 +133,11 @@ describe('SettingsModal', () => {})it('edits a site with nullable optional fields as empty form values', async () => {- renderSettingsModal({ id: 'app-null-fields', mode: 'chat', site: createAppSiteFixture() })+ await renderSettingsDialog({+ id: 'app-null-fields',+ mode: 'chat',+ site: createAppSiteFixture(),+ })expect(screen.getByRole('textbox', { name: inputPlaceholderName })).toHaveValue('')fireEvent.click(screen.getByText('common.operation.save'))@@ -154,11 +156,13 @@ describe('SettingsModal', () => {}),),)- expect(mockOnClose).toHaveBeenCalledOnce()+ await waitFor(() =>+ expect(screen.queryByRole('dialog', { name: dialogName })).not.toBeInTheDocument(),+ )})it('should render the modal with all settings exposed by default', async () => {- renderSettingsModal()+ await renderSettingsDialog()expect(screen.getByText('appOverview.overview.appInfo.settings.title')).toBeInTheDocument()expect(screen.queryByRole('status')).not.toBeInTheDocument()@@ -178,8 +182,8 @@ describe('SettingsModal', () => {).toBeInTheDocument()})- it('should explain that Web app settings apply to every environment when ACL allows deploy', () => {- renderSettingsModal(mockAppInfo, true)+ it('should explain that Web app settings apply to every environment when ACL allows deploy', async () => {+ await renderSettingsDialog(mockAppInfo, true)expect(screen.getByRole('status')).toHaveTextContent('appOverview.overview.appInfo.settings.multiEnvironmentNotice',@@ -188,7 +192,7 @@ describe('SettingsModal', () => {it('names the Inverted switch from its visible label and exposes its state', async () => {const user = userEvent.setup()- renderSettingsModal()+ await renderSettingsDialog()const invertedSwitch = screen.getByRole('switch', {name: 'appOverview.overview.appInfo.settings.chatColorThemeInverted',@@ -201,7 +205,7 @@ describe('SettingsModal', () => {})it('should notify the user when the name is empty', async () => {- renderSettingsModal()+ await renderSettingsDialog()const nameInput = screen.getByPlaceholderText('app.appNamePlaceholder')fireEvent.change(nameInput, { target: { value: '' } })fireEvent.click(screen.getByText('common.operation.save'))@@ -215,7 +219,7 @@ describe('SettingsModal', () => {})it('should validate the theme color and show an error when the hex is invalid', async () => {- renderSettingsModal()+ await renderSettingsDialog()const colorInput = screen.getByPlaceholderText('E.g #A020F0')fireEvent.change(colorInput, { target: { value: 'not-a-hex' } })@@ -231,7 +235,7 @@ describe('SettingsModal', () => {})it('should validate the privacy policy URL', async () => {- renderSettingsModal()+ await renderSettingsDialog()const privacyInput = screen.getByPlaceholderText('appOverview.overview.appInfo.settings.more.privacyPolicyPlaceholder',)@@ -250,8 +254,8 @@ describe('SettingsModal', () => {})it('should save valid settings and close the modal', async () => {- mockOnSave.mockResolvedValueOnce(undefined)- renderSettingsModal()+ mockOnSave.mockResolvedValueOnce(true)+ await renderSettingsDialog()fireEvent.click(screen.getByText('common.operation.save'))@@ -275,112 +279,208 @@ describe('SettingsModal', () => {use_icon_as_answer_icon: mockAppInfo.site.use_icon_as_answer_icon,}),)- expect(mockOnClose).toHaveBeenCalled()- })-- it('should not render a show-more trigger', () => {- renderSettingsModal()-- expect(- screen.queryByText('appOverview.overview.appInfo.settings.more.entry'),- ).not.toBeInTheDocument()- expect(- screen.getByPlaceholderText(- 'appOverview.overview.appInfo.settings.more.privacyPolicyPlaceholder',- ),- ).toBeInTheDocument()+ await waitFor(() =>+ expect(screen.queryByRole('dialog', { name: dialogName })).not.toBeInTheDocument(),+ )})- it('should reset local form state when the controlled dialog reopens', () => {- const { rerender } = render(- <SettingsModal- isChat- canDeploy={false}- isShow={true}- appInfo={mockAppInfo}- onClose={mockOnClose}- onSave={mockOnSave}- />,+ it('discards cancelled edits and initializes the next session from committed settings', async () => {+ const user = userEvent.setup()+ await renderSettingsDialog()+ const placeholder = screen.getByRole('textbox', { name: inputPlaceholderName })+ await user.clear(placeholder)+ await user.type(placeholder, 'Cancelled prompt')+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))+ await waitFor(() =>+ expect(screen.queryByRole('dialog', { name: dialogName })).not.toBeInTheDocument(),)- expect(- screen.getByPlaceholderText(- 'appOverview.overview.appInfo.settings.more.privacyPolicyPlaceholder',- ),- ).toBeInTheDocument()+ expect(mockOnSave).not.toHaveBeenCalled()+ await user.click(screen.getByRole('button', { name: triggerName }))+ expect(screen.getByRole('textbox', { name: inputPlaceholderName })).toHaveValue(+ 'Ask me anything',+ )+ })+ it('keeps drafts for equivalent source data and resets them when committed settings change', async () => {+ const user = userEvent.setup()+ const { rerender } = await renderSettingsDialog()+ await user.clear(screen.getByRole('textbox', { name: inputPlaceholderName }))+ await user.type(screen.getByRole('textbox', { name: inputPlaceholderName }), 'Current draft')rerender(- <SettingsModal+ <SettingsDialogisChat- canDeploy={false}- isShow={false}- appInfo={mockAppInfo}- onClose={mockOnClose}+ appInfo={{ ...mockAppInfo, site: { ...mockAppInfo.site } }}onSave={mockOnSave}/>,)+ expect(screen.getByRole('textbox', { name: inputPlaceholderName })).toHaveValue('Current draft')rerender(- <SettingsModal+ <SettingsDialogisChat- canDeploy={false}- isShow={true}- appInfo={mockAppInfo}- onClose={mockOnClose}+ appInfo={{+ ...mockAppInfo,+ site: { ...mockAppInfo.site, input_placeholder: 'Updated prompt' },+ }}onSave={mockOnSave}/>,)-- expect(- screen.queryByText('appOverview.overview.appInfo.settings.more.entry'),- ).not.toBeInTheDocument()- expect(- screen.getByPlaceholderText(- 'appOverview.overview.appInfo.settings.more.privacyPolicyPlaceholder',- ),- ).toBeInTheDocument()+ expect(screen.getByRole('textbox', { name: inputPlaceholderName })).toHaveValue(+ 'Updated prompt',+ )})- it('should reset the input placeholder when app info changes while open', () => {- const { rerender } = render(- <SettingsModal+ it.each(['false', 'rejection'] as const)(+ 'retains the draft after a %s save result and permits retry',+ async (failure) => {+ const user = userEvent.setup()+ if (failure === 'false') mockOnSave.mockResolvedValueOnce(false)+ else mockOnSave.mockRejectedValueOnce(new Error('Unexpected failure'))+ await renderSettingsDialog()+ const name = screen.getByPlaceholderText('app.appNamePlaceholder')+ await user.clear(name)+ await user.type(name, 'Unsaved title')+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))+ await waitFor(() => expect(name).not.toHaveAttribute('readonly'))+ expect(screen.getByRole('dialog', { name: dialogName })).toBeInTheDocument()+ expect(name).toHaveValue('Unsaved title')+ expect(toastMocks.call).not.toHaveBeenCalled()+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))+ await waitFor(() =>+ expect(screen.queryByRole('dialog', { name: dialogName })).not.toBeInTheDocument(),+ )+ expect(mockOnSave).toHaveBeenCalledTimes(2)+ expect(mockOnSave).toHaveBeenLastCalledWith(+ expect.objectContaining({ title: 'Unsaved title' }),+ )+ },+ )++ it('keeps the pending lock when committed metadata replaces the form draft', async () => {+ const user = userEvent.setup()+ let finishSave!: (saved: boolean) => void+ mockOnSave.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishSave = resolve+ }),+ )+ const { rerender } = await renderSettingsDialog()+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))+ rerender(+ <SettingsDialogisChat- canDeploy={false}- isShow={true}- appInfo={mockAppInfo}- onClose={mockOnClose}+ appInfo={{ ...mockAppInfo, site: { ...mockAppInfo.site, title: 'Refreshed title' } }}onSave={mockOnSave}/>,)- expect(screen.getByRole('textbox', { name: inputPlaceholderName })).toHaveValue(- 'Ask me anything',+ const name = screen.getByPlaceholderText('app.appNamePlaceholder')+ expect(name).toHaveValue('Refreshed title')+ expect(name).toHaveAttribute('readonly')+ await user.type(name, 'ignored')+ expect(name).toHaveValue('Refreshed title')+ expect(screen.getByRole('button', { name: 'app.iconPicker.title' })).toBeDisabled()+ expect(screen.getByRole('button', { name: 'common.operation.close' })).toBeDisabled()+ expect(screen.getByRole('button', { name: 'common.operation.cancel' })).toBeDisabled()+ const invertedSwitch = screen.getByRole('switch', {+ name: 'appOverview.overview.appInfo.settings.chatColorThemeInverted',+ })+ await user.click(invertedSwitch)+ expect(invertedSwitch).toBeChecked()+ const language = screen.getByRole('combobox', {+ name: 'appOverview.overview.appInfo.settings.language',+ })+ const currentLanguage = language.textContent+ await user.click(language)+ await user.click(screen.getByRole('option', { name: '简体中文' }))+ expect(language).toHaveTextContent(currentLanguage!)+ await user.keyboard('{Escape}')+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))+ await user.keyboard('{Escape}')+ expect(mockOnSave).toHaveBeenCalledOnce()+ expect(screen.getByRole('dialog', { name: dialogName })).toBeInTheDocument()+ await act(async () => {+ finishSave(true)+ })+ await waitFor(() =>+ expect(screen.queryByRole('dialog', { name: dialogName })).not.toBeInTheDocument(),)+ })- rerender(- <SettingsModal- isChat- canDeploy={false}- isShow={true}- appInfo={{- ...mockAppInfo,- site: {- ...mockAppInfo.site,- input_placeholder: 'Updated prompt',- },- }}- onClose={mockOnClose}- onSave={mockOnSave}- />,+ it.each(['missing-data', 'disabled'] as const)(+ 'keeps an unavailable %s entry visible until ready',+ async (unavailable) => {+ const user = userEvent.setup()+ const { rerender } = render(+ <SettingsDialog+ isChat+ appInfo={unavailable === 'missing-data' ? undefined : mockAppInfo}+ disabled={unavailable === 'disabled'}+ onSave={mockOnSave}+ />,+ )+ const trigger = screen.getByRole('button', { name: triggerName })+ expect(trigger).toBeDisabled()+ await user.click(trigger)+ expect(screen.queryByRole('dialog', { name: dialogName })).not.toBeInTheDocument()+ rerender(<SettingsDialog isChat appInfo={mockAppInfo} onSave={mockOnSave} />)+ await user.click(screen.getByRole('button', { name: triggerName }))+ expect(screen.getByRole('dialog', { name: dialogName })).toBeInTheDocument()+ },+ )++ it('keeps the open draft and blocks saving while the entry is disabled', async () => {+ const user = userEvent.setup()+ const { rerender } = await renderSettingsDialog()+ const name = screen.getByPlaceholderText('app.appNamePlaceholder')+ await user.clear(name)+ await user.type(name, 'Draft title')+ rerender(<SettingsDialog isChat appInfo={mockAppInfo} disabled onSave={mockOnSave} />)+ expect(screen.getByRole('dialog', { name: dialogName })).toBeInTheDocument()+ expect(name).toHaveValue('Draft title')+ const save = screen.getByRole('button', { name: 'common.operation.save' })+ expect(save).toBeDisabled()+ await user.type(name, '{Enter}')+ expect(mockOnSave).not.toHaveBeenCalled()+ rerender(<SettingsDialog isChat appInfo={mockAppInfo} onSave={mockOnSave} />)+ await user.click(save)+ expect(mockOnSave).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ title: 'Draft title' }),)- expect(screen.getByRole('textbox', { name: inputPlaceholderName })).toHaveValue(- 'Updated prompt',+ })++ it('keeps an unfinished save locked when the settings source disappears and returns', async () => {+ const user = userEvent.setup()+ let finishSave!: (saved: boolean) => void+ mockOnSave.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishSave = resolve+ }),)+ const { rerender } = await renderSettingsDialog()+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))+ rerender(<SettingsDialog isChat onSave={mockOnSave} />)+ expect(screen.queryByRole('dialog', { name: dialogName })).not.toBeInTheDocument()+ rerender(<SettingsDialog isChat appInfo={mockAppInfo} onSave={mockOnSave} />)+ const trigger = screen.getByRole('button', { name: triggerName })+ expect(trigger).toBeDisabled()+ await user.click(trigger)+ expect(screen.queryByRole('dialog', { name: dialogName })).not.toBeInTheDocument()+ await act(async () => {+ finishSave(true)+ })+ await waitFor(() => expect(trigger).toBeEnabled())+ await user.click(trigger)+ expect(screen.getByRole('dialog', { name: dialogName })).toBeInTheDocument()+ expect(mockOnSave).toHaveBeenCalledOnce()})it('should preserve restricted settings when saving other Cloud settings', async () => {- mockOnSave.mockResolvedValueOnce(undefined)+ mockOnSave.mockResolvedValueOnce(true)deploymentEdition = 'CLOUD'copyrightEnabled = false- renderSettingsModal()+ await renderSettingsDialog()const inputPlaceholder = screen.getByRole('textbox', { name: inputPlaceholderName })expect(inputPlaceholder).toBeDisabled()@@ -404,11 +504,11 @@ describe('SettingsModal', () => {})it('should keep the input placeholder editable when billing is disabled', async () => {- mockOnSave.mockResolvedValueOnce(undefined)+ mockOnSave.mockResolvedValueOnce(true)deploymentEdition = 'COMMUNITY'copyrightEnabled = false- renderSettingsModal()+ await renderSettingsDialog()const inputPlaceholder = screen.getByRole('textbox', { name: inputPlaceholderName })fireEvent.change(inputPlaceholder, { target: { value: 'Self-hosted prompt' } })fireEvent.click(screen.getByText('common.operation.save'))@@ -429,7 +529,7 @@ describe('SettingsModal', () => {deploymentEdition = 'CLOUD'copyrightEnabled = false- renderSettingsModal()+ await renderSettingsDialog()fireEvent.click((await screen.findAllByText('billing.upgradeBtn.encourageShort'))[0]!)await waitFor(() =>@@ -441,14 +541,14 @@ describe('SettingsModal', () => {deploymentEdition = 'CLOUD'copyrightEnabled = true- renderSettingsModal()+ await renderSettingsDialog()await waitFor(() => {expect(screen.queryByText('billing.upgradeBtn.encourageShort')).not.toBeInTheDocument()})})it('should preserve image icons and apply textarea or switch changes when saving image-based settings', async () => {- mockOnSave.mockResolvedValueOnce(undefined)+ mockOnSave.mockResolvedValueOnce(true)const imageAppInfo = {...mockAppInfo,site: {@@ -460,7 +560,7 @@ describe('SettingsModal', () => {},} satisfies SettingsAppInfo- renderSettingsModal(imageAppInfo)+ await renderSettingsDialog(imageAppInfo)fireEvent.change(screen.getByDisplayValue('A description'), {target: { value: 'Updated description' },@@ -511,12 +611,13 @@ it('saves unrelated settings while entitlements are pending without clearing pro...consoleQuery.features.get.queryOptions(),queryFn: () => new Promise(() => {}),})- const onSave = vi.fn().mockResolvedValue(undefined)- render(<SettingsModal isChat isShow appInfo={mockAppInfo} onClose={vi.fn()} onSave={onSave} />, {+ const onSave = vi.fn().mockResolvedValue(true)+ render(<SettingsDialog isChat appInfo={mockAppInfo} onSave={onSave} />, {queryClient,features: undefined,systemFeatures: { deployment_edition: 'CLOUD' },})+ await userEvent.setup().click(screen.getByRole('button', { name: triggerName }))expect(screen.getByRole('textbox', { name: inputPlaceholderName })).toBeDisabled()expect(screen.queryByText('billing.upgradeBtn.encourageShort')).not.toBeInTheDocument()fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))diff --git a/web/app/components/app/overview/settings/__tests__/settings-dialog.browser.spec.tsx b/web/app/components/app/overview/settings/__tests__/settings-dialog.browser.spec.tsxnew file mode 100644index 00000000000..1b24c063c60--- /dev/null+++ b/web/app/components/app/overview/settings/__tests__/settings-dialog.browser.spec.tsx@@ -0,0 +1,260 @@+import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'+import { QueryClient, useQuery } from '@tanstack/react-query'+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'+import { userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import { useAccessPointActions } from '@/app/components/app/access-point/shared/use-access-point-actions'+import { emojiCatalogOptions } from '@/app/components/base/icon-picker/emoji-data'+import { consoleQuery } from '@/service/console'+import { seedFeatures, seedSystemFeatures } from '@/test/console/query-data'+import { QueryClientTestProvider } from '@/test/console/query-provider'+import { createAppDetailFixture, createAppSiteFixture } from '@/test/fixtures/app'+import { SettingsDialog } from '../index'++const { saveSite, fetchApp, notify } = vi.hoisted(() => ({+ saveSite: vi.fn(),+ fetchApp: vi.fn(),+ notify: vi.fn(),+}))++vi.mock('@/app/notifications', () => ({+ toast: Object.assign(notify, { success: notify, error: notify, warning: notify, info: notify }),+}))+vi.mock('@/next/navigation', () => ({ useParams: () => ({}) }))++const settingsTitle = 'appOverview.overview.appInfo.settings.title'+const titleLabel = 'appOverview.overview.appInfo.settings.webName'+const triggerLabel = 'navigation.settings.settings'+const appQuery = consoleQuery.apps.byAppId.get.queryOptions({+ input: { params: { app_id: 'settings-app' } },+})++function createApp(title = 'Original app'): AppDetailWithSite {+ return createAppDetailFixture({+ id: 'settings-app',+ mode: 'advanced-chat',+ site: createAppSiteFixture({+ title,+ description: 'Original description',+ icon_type: 'emoji',+ icon: '😀',+ icon_background: '#FEF3F2',+ default_language: 'en-US',+ }),+ })+}++function SettingsOwner() {+ const { data: appInfo } = useQuery(appQuery)+ const { saveSiteConfig } = useAccessPointActions('settings-app', true)+ return (+ <SettingsDialog+ isChat+ appInfo={+ appInfo?.site ? { id: appInfo.id, mode: appInfo.mode, site: appInfo.site } : undefined+ }+ onSave={saveSiteConfig}+ />+ )+}++async function renderSettings() {+ const client = new QueryClient({+ defaultOptions: { queries: { staleTime: Infinity, retry: false } },+ })+ client.setQueryData(appQuery.queryKey, createApp())+ seedSystemFeatures(client, { deployment_edition: 'COMMUNITY' })+ seedFeatures(client, { webapp_copyright_enabled: true })+ client.setQueryData(emojiCatalogOptions.queryKey, [+ {+ id: 'faces',+ label: 'Faces',+ items: [{ emoji: '😎', label: 'Cool face', version: 1 }],+ },+ ])+ const screen = await render(+ <QueryClientTestProvider queryClient={client}>+ <NuqsTestingAdapter>+ <SettingsOwner />+ </NuqsTestingAdapter>+ </QueryClientTestProvider>,+ )+ return { screen, client }+}++beforeEach(() => {+ vi.clearAllMocks()+ vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => {+ const request = new Request(input, init)+ const appId = /\/apps\/([^/]+)/.exec(new URL(request.url).pathname)?.[1]+ if (request.method === 'GET')+ return Response.json(await fetchApp({ params: { app_id: appId } }))+ return Response.json(+ await saveSite({+ params: { app_id: appId },+ body: await request.json(),+ }),+ )+ })+})+afterEach(() => {+ vi.unstubAllGlobals()+})++it('retains a failed save draft and closes a successful retry before the background refresh finishes', async () => {+ let rejectSave!: (error: Error) => void+ saveSite.mockReturnValueOnce(+ new Promise((_, reject) => {+ rejectSave = reject+ }),+ )+ saveSite.mockResolvedValueOnce({})+ let finishRefresh!: (value: AppDetailWithSite) => void+ fetchApp.mockReturnValueOnce(+ new Promise<AppDetailWithSite>((resolve) => {+ finishRefresh = resolve+ }),+ )+ const { screen, client } = await renderSettings()+ const trigger = screen.getByRole('button', { name: triggerLabel })+ await trigger.click()+ const dialog = screen.getByRole('dialog', { name: settingsTitle })+ const title = dialog.getByRole('textbox', { name: titleLabel })+ await title.fill('Saved after retry')+ const save = dialog.getByRole('button', { name: 'common.operation.save' })+ await save.click()+ await expect.element(save).toHaveFocus()+ await expect.element(save).toHaveAttribute('aria-disabled', 'true')+ await expect.element(title).toHaveAttribute('readonly')+ await expect+ .element(dialog.getByRole('button', { name: 'common.operation.close' }))+ .toBeDisabled()+ await expect+ .element(dialog.getByRole('button', { name: 'common.operation.cancel' }))+ .toBeDisabled()+ await userEvent.keyboard('{Enter}{Escape}')+ await expect.element(dialog).toBeVisible()+ expect(saveSite).toHaveBeenCalledTimes(1)+ expect(fetchApp).not.toHaveBeenCalled()+ rejectSave(new Error('Save failed'))+ await expect.element(save).not.toHaveAttribute('aria-disabled', 'true')+ await expect.element(title).not.toHaveAttribute('readonly')+ await expect.element(title).toHaveValue('Saved after retry')+ await expect.element(dialog).toBeVisible()++ await save.click()+ await expect.poll(() => fetchApp.mock.calls.length).toBe(1)+ await expect.element(dialog).not.toBeInTheDocument()+ await expect.element(trigger).toHaveFocus()+ expect(saveSite).toHaveBeenCalledTimes(2)+ expect(client.getQueryData(appQuery.queryKey)?.site?.title).toBe('Original app')+ const refreshed = createApp('Saved after retry')+ finishRefresh(refreshed)+ await expect.poll(() => client.getQueryData(appQuery.queryKey)).toEqual(refreshed)+ await trigger.click()+ await expect.element(title).toHaveValue('Saved after retry')+ await dialog.getByRole('button', { name: 'common.operation.close' }).click()+ await expect.element(dialog).not.toBeInTheDocument()+ expect(saveSite).toHaveBeenLastCalledWith({+ params: { app_id: 'settings-app' },+ body: expect.objectContaining({ title: 'Saved after retry' }),+ })+ client.clear()+})++it('closes after a successful POST even when the background detail refresh fails', async () => {+ saveSite.mockResolvedValueOnce({})+ fetchApp.mockRejectedValueOnce(new Error('Refresh failed'))+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})+ const { screen, client } = await renderSettings()+ const trigger = screen.getByRole('button', { name: triggerLabel })+ await trigger.click()+ const dialog = screen.getByRole('dialog', { name: settingsTitle })+ await dialog.getByRole('textbox', { name: titleLabel }).fill('Saved remotely')+ await dialog.getByRole('button', { name: 'common.operation.save' }).click()+ await expect.element(dialog).not.toBeInTheDocument()+ await expect.element(trigger).toHaveFocus()+ await expect.poll(() => fetchApp.mock.calls.length).toBe(1)+ expect(notify).toHaveBeenCalledExactlyOnceWith('common.actionMsg.modifiedSuccessfully', {+ type: 'success',+ })+ expect(saveSite).toHaveBeenCalledTimes(1)+ client.clear()+ consoleError.mockRestore()+})++it('keeps the draft through the exit animation and reopens with the latest owner metadata', async () => {+ vi.stubGlobal('BASE_UI_ANIMATIONS_DISABLED', false)+ const { screen, client } = await renderSettings()+ const trigger = screen.getByRole('button', { name: triggerLabel })+ await userEvent.tab()+ await expect.element(trigger).toHaveFocus()+ await userEvent.keyboard('{Enter}')+ const dialog = screen.getByRole('dialog', { name: settingsTitle })+ const title = dialog.getByRole('textbox', { name: titleLabel })+ await title.fill('Cancelled draft')+ const popup = dialog.element()+ const input = title.element() as HTMLInputElement+ await expect.poll(() => getComputedStyle(popup).opacity).toBe('1')+ const exitFrame = new Promise<{ value: string; opacity: number }>((resolve) => {+ const onTransition = (event: Event) => {+ if (event.target !== popup || (event as TransitionEvent).propertyName !== 'opacity') return+ popup.removeEventListener('transitionrun', onTransition)+ resolve({ value: input.value, opacity: Number(getComputedStyle(popup).opacity) })+ }+ popup.addEventListener('transitionrun', onTransition)+ })+ await dialog.getByRole('button', { name: 'common.operation.cancel' }).click()+ const closing = await exitFrame+ expect(closing.value).toBe('Cancelled draft')+ expect(closing.opacity).toBeGreaterThan(0)+ await expect.element(dialog).not.toBeInTheDocument()+ await expect.element(trigger).toHaveFocus()+ client.setQueryData(appQuery.queryKey, createApp('Fresh metadata'))+ await userEvent.keyboard(' ')+ await expect.element(title).toHaveValue('Fresh metadata')+ await title.fill('Another local draft')+ client.setQueryData(appQuery.queryKey, createApp('Changed while open'))+ await expect.element(title).toHaveValue('Changed while open')+ await expect+ .poll(() => {+ const close = dialog.getByRole('button', { name: 'common.operation.close' }).element()+ return document.activeElement === title.element() || document.activeElement === close+ ? 'settings control'+ : document.activeElement?.tagName+ })+ .toBe('settings control')+ await dialog.getByRole('button', { name: 'common.operation.close' }).click()+ await expect.element(dialog).not.toBeInTheDocument()+ await expect.element(trigger).toHaveFocus()+ expect(saveSite).not.toHaveBeenCalled()+ client.clear()+})++it('keeps icon search and confirmation inside the nested picker without submitting Settings', async () => {+ const { screen, client } = await renderSettings()+ await screen.getByRole('button', { name: triggerLabel }).click()+ const settings = screen.getByRole('dialog', { name: settingsTitle })+ const title = settings.getByRole('textbox', { name: titleLabel })+ await title.fill('Keep this draft')+ const iconTrigger = settings.getByRole('button', { name: 'app.iconPicker.title' })+ await iconTrigger.click()+ const picker = screen.getByRole('dialog', { name: 'app.iconPicker.title' })+ await picker.getByRole('combobox', { name: 'app.iconPicker.search' }).fill('Cool')+ await userEvent.keyboard('{ArrowDown}{Enter}')+ expect(saveSite).not.toHaveBeenCalled()+ await picker.getByRole('button', { name: 'app.iconPicker.ok' }).click()+ await expect.element(picker).not.toBeInTheDocument()+ await expect.element(settings).toBeVisible()+ await expect.element(iconTrigger).toHaveFocus()+ await expect.element(title).toHaveValue('Keep this draft')+ expect(saveSite).not.toHaveBeenCalled()+ await userEvent.keyboard('{Enter}')+ await expect.element(picker).toBeVisible()+ await userEvent.keyboard('{Escape}')+ await expect.element(picker).not.toBeInTheDocument()+ await expect.element(settings).toBeVisible()+ await expect.element(iconTrigger).toHaveFocus()+ expect(saveSite).not.toHaveBeenCalled()+ client.clear()+})diff --git a/web/app/components/app/overview/settings/index.tsx b/web/app/components/app/overview/settings/index.tsxindex 848885f672d..8b49bc7ed7e 100644--- a/web/app/components/app/overview/settings/index.tsx+++ b/web/app/components/app/overview/settings/index.tsx@@ -5,12 +5,19 @@ import type {AppDetailWithSite,AppSiteUpdatePayload,} from '@dify/contracts/api/console/apps/types.gen'-import type { FC } from 'react'+import type { DialogActions } from '@langgenius/dify-ui/dialog'import type { IconPickerValue } from '@/app/components/base/icon-picker'import type { Language } from '@/types/app'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'-import { Dialog, DialogClose, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogTitle,+ DialogTrigger,+} from '@langgenius/dify-ui/dialog'import { Field, FieldDescription, FieldLabel } from '@langgenius/dify-ui/field'import { Form } from '@langgenius/dify-ui/form'import { IconButton } from '@langgenius/dify-ui/icon-button'@@ -38,7 +45,7 @@ import { useQuery } from '@tanstack/react-query'import { useAtomValue } from 'jotai'import { useQueryState } from 'nuqs'import * as React from 'react'-import { useCallback, useState } from 'react'+import { useCallback, useRef, useState } from 'react'import { Trans, useTranslation } from 'react-i18next'import {IconPicker,@@ -58,14 +65,13 @@ import Link from '@/next/link'import { consoleQuery } from '@/service/console'import { AppModeEnum } from '@/types/app'-type ISettingsModalProps = {+type SettingsDialogProps = {isChat: booleancanDeploy?: boolean- appInfo: SettingsAppInfo- isShow: boolean- defaultValue?: string- onClose: () => void- onSave?: (params: AppSiteUpdatePayload) => Promise<void>+ appInfo?: SettingsAppInfo+ disabled?: boolean+ triggerLabel?: string+ onSave: (params: AppSiteUpdatePayload) => Promise<boolean>}type SettingsSiteInfo = Pick<@@ -117,7 +123,7 @@ type SelectOption = {const LANGUAGE_OPTIONS: SelectOption[] = languages.filter((item) => item.supported)-const createInputInfo = (appInfo: ISettingsModalProps['appInfo']) => {+const createInputInfo = (appInfo: SettingsAppInfo) => {const {title,description,@@ -146,7 +152,7 @@ const createInputInfo = (appInfo: ISettingsModalProps['appInfo']) => {}}-const createAppIcon = (appInfo: ISettingsModalProps['appInfo']): SettingsAppIconSelection => {+const createAppIcon = (appInfo: SettingsAppInfo): SettingsAppIconSelection => {const { icon_type, icon, icon_background, icon_url } = appInfo.siteif (icon_type === 'image' && icon) return { type: 'image', url: icon_url ?? '', fileId: icon }@@ -159,7 +165,7 @@ const createAppIcon = (appInfo: ISettingsModalProps['appInfo']): SettingsAppIconreturn null}-const getSettingsResetKey = (appInfo: ISettingsModalProps['appInfo']) =>+const getSettingsResetKey = (appInfo: SettingsAppInfo) =>JSON.stringify([appInfo.id,appInfo.site.title,@@ -179,28 +185,33 @@ const getSettingsResetKey = (appInfo: ISettingsModalProps['appInfo']) =>appInfo.site.use_icon_as_answer_icon,])-const SettingsModal: FC<ISettingsModalProps> = ({+function SettingsForm({isChat,canDeploy = false,appInfo,- isShow = false,- onClose,- onSave,-}) => {+ disabled,+ pending,+ onSubmit,+}: Pick<SettingsDialogProps, 'isChat' | 'canDeploy' | 'disabled'> & {+ appInfo: SettingsAppInfo+ pending: boolean+ onSubmit: (params: AppSiteUpdatePayload) => Promise<void>+}) {const [inputPlaceholderFocused, setInputPlaceholderFocused] = useState(false)- const { default_language } = appInfo.site- const nextInputInfo = createInputInfo(appInfo)- const nextAppIcon = createAppIcon(appInfo)- const settingsResetKey = getSettingsResetKey(appInfo)- const [inputInfo, setInputInfo] = useState(nextInputInfo)- const [language, setLanguage] = useState(default_language)- const [saveLoading, setSaveLoading] = useState(false)+ const [inputInfo, setInputInfo] = useState(() => createInputInfo(appInfo))+ const [language, setLanguage] = useState(appInfo.site.default_language)const { t } = useTranslation(['app', 'appOverview', 'billing', 'common'])-- const [appIcon, setAppIcon] = useState<SettingsAppIconSelection>(nextAppIcon)- const [previousIsShow, setPreviousIsShow] = useState(isShow)+ const [appIcon, setAppIcon] = useState<SettingsAppIconSelection>(() => createAppIcon(appInfo))+ const settingsResetKey = getSettingsResetKey(appInfo)const [previousSettingsResetKey, setPreviousSettingsResetKey] = useState(settingsResetKey)+ if (previousSettingsResetKey !== settingsResetKey) {+ setPreviousSettingsResetKey(settingsResetKey)+ setInputInfo(createInputInfo(appInfo))+ setLanguage(appInfo.site.default_language)+ setAppIcon(createAppIcon(appInfo))+ }+const deploymentEdition = useAtomValue(deploymentEditionAtom)const { data: webappCopyrightEnabled } = useQuery(consoleQuery.features.get.queryOptions({@@ -228,6 +239,7 @@ const SettingsModal: FC<ISettingsModalProps> = ({)}><input+ readOnly={pending}type="text"name="input_placeholder"value={inputPlaceholderValue}@@ -267,23 +279,8 @@ const SettingsModal: FC<ISettingsModalProps> = ({setPricing('open')}, [setPricing])- const shouldResetForm =- isShow && (!previousIsShow || settingsResetKey !== previousSettingsResetKey)- if (isShow !== previousIsShow || shouldResetForm) {- setPreviousIsShow(isShow)- if (shouldResetForm) {- setInputInfo(nextInputInfo)- setLanguage(default_language)- setAppIcon(nextAppIcon)- setPreviousSettingsResetKey(settingsResetKey)- }- }-- const handleClose = () => {- onClose()- }-const handleFormSubmit = async () => {+ if (pending) returnif (!inputInfo.title) {toast.error(t(($) => $['newApp.nameNotEmpty'], { ns: 'app' }))return@@ -314,7 +311,6 @@ const SettingsModal: FC<ISettingsModalProps> = ({}}- setSaveLoading(true)const params = {title: inputInfo.title,description: inputInfo.desc,@@ -348,9 +344,7 @@ const SettingsModal: FC<ISettingsModalProps> = ({show_workflow_steps: inputInfo.show_workflow_steps,use_icon_as_answer_icon: inputInfo.use_icon_as_answer_icon,}- await onSave?.(params)- setSaveLoading(false)- handleClose()+ await onSubmit(params)}const onChange = (field: string) => {@@ -368,456 +362,514 @@ const SettingsModal: FC<ISettingsModalProps> = ({}return (- <>- <Dialog open={isShow} onOpenChange={(open) => !open && handleClose()} disablePointerDismissal>- <DialogContent className="grid max-h-[calc(100dvh-2rem)] w-130 grid-rows-[auto_minmax(0,1fr)] overflow-hidden p-0">- {/* header */}- <div className="shrink-0 pt-5 pr-5 pb-3 pl-6">- <div className="flex items-center gap-1">- <DialogTitle className="grow title-2xl-semi-bold text-text-primary">- {t(($) => $[`${prefixSettings}.title`], { ns: 'appOverview' })}- </DialogTitle>- <DialogClose- render={- <IconButton- aria-label={t(($) => $['operation.close'], { ns: 'common' })}- size="sm"- className="relative top-auto right-auto shrink-0 rounded-2xl"- >- <span aria-hidden className="i-ri-close-line size-4" />- </IconButton>- }+ <Form+ className="grid min-h-0 grid-rows-[auto_minmax(0,1fr)_auto]"+ onFormSubmit={handleFormSubmit}+ >+ {canDeploy && (+ <div className="row-start-1 px-6 py-2">+ <div+ role="status"+ aria-live="polite"+ aria-atomic="true"+ className="relative flex min-h-10 items-start gap-0.5 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-2 shadow-xs shadow-shadow-shadow-3 backdrop-blur-[5px]"+ >+ <div+ aria-hidden="true"+ className="absolute -inset-px bg-linear-to-r from-components-badge-status-light-normal-halo to-background-gradient-mask-transparent opacity-40"+ />+ <div className="relative flex size-6 shrink-0 items-center justify-center p-1">+ <span+ aria-hidden="true"+ className="i-ri-information-2-fill size-4 text-text-accent"/></div>- <div className="mt-0.5 system-xs-regular text-text-tertiary">- <span>{t(($) => $[`${prefixSettings}.modalTip`], { ns: 'appOverview' })}</span>- </div>+ <p className="relative min-w-0 flex-1 py-1 system-xs-medium wrap-break-word text-text-primary">+ {t(($) => $[`${prefixSettings}.multiEnvironmentNotice`], {+ ns: 'appOverview',+ })}+ </p></div>- <Form- className="grid min-h-0 grid-rows-[auto_minmax(0,1fr)_auto]"- onFormSubmit={handleFormSubmit}- >- {canDeploy && (- <div className="row-start-1 px-6 py-2">- <div- role="status"- aria-live="polite"- aria-atomic="true"- className="relative flex min-h-10 items-start gap-0.5 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-2 shadow-xs shadow-shadow-shadow-3 backdrop-blur-[5px]"+ </div>+ )}+ {/* form body */}+ <ScrollArea className="row-start-2 min-h-0 overflow-hidden">+ <ScrollAreaViewport className="overscroll-contain">+ <ScrollAreaContent className="flex flex-col gap-y-5 px-6 py-3" style={{ minWidth: 0 }}>+ {/* name & icon */}+ <div className="flex gap-4">+ <Field name="title" className="grow">+ <FieldLabel>+ {t(($) => $[`${prefixSettings}.webName`], { ns: 'appOverview' })}+ </FieldLabel>+ <Input+ readOnly={pending}+ value={inputInfo.title}+ onValueChange={(value) => setInputInfo((item) => ({ ...item, title: value }))}+ placeholder={t(($) => $.appNamePlaceholder, { ns: 'app' }) || ''}+ />+ </Field>+ <IconPicker+ value={+ appIcon ??+ (appInfo.site.icon_type === 'emoji' && appInfo.site.icon+ ? {+ type: 'emoji',+ icon: appInfo.site.icon,+ background: appInfo.site.icon_background,+ }+ : undefined)+ }+ onValueChange={setAppIcon}+ >+ <IconPickerTrigger+ disabled={pending}+ aria-label={t(($) => $['iconPicker.title'], { ns: 'app' })}+ className="mt-2 shrink-0 cursor-pointer rounded-2xl">- <div- aria-hidden="true"- className="absolute -inset-px bg-linear-to-r from-components-badge-status-light-normal-halo to-background-gradient-mask-transparent opacity-40"+ <IconPickerIcon size="xxl" />+ </IconPickerTrigger>+ <IconPickerContent />+ </IconPicker>+ </div>+ {/* description */}+ <Field name="description">+ <FieldLabel>+ {t(($) => $[`${prefixSettings}.webDesc`], { ns: 'appOverview' })}+ </FieldLabel>+ <Textarea+ readOnly={pending}+ value={inputInfo.desc}+ onValueChange={onDesChange}+ placeholder={+ t(($) => $[`${prefixSettings}.webDescPlaceholder`], {+ ns: 'appOverview',+ }) as string+ }+ />+ <FieldDescription>+ {t(($) => $[`${prefixSettings}.webDescTip`], { ns: 'appOverview' })}+ </FieldDescription>+ </Field>+ <Separator className="my-0" />+ {/* answer icon */}+ {isChat && (+ <Field name="use_icon_as_answer_icon" className="w-full">+ <div className="flex items-center justify-between gap-3">+ <FieldLabel>{t(($) => $['answerIcon.title'], { ns: 'app' })}</FieldLabel>+ <Switch+ readOnly={pending}+ checked={inputInfo.use_icon_as_answer_icon}+ onCheckedChange={(v) =>+ setInputInfo({ ...inputInfo, use_icon_as_answer_icon: v })+ }/>- <div className="relative flex size-6 shrink-0 items-center justify-center p-1">- <span- aria-hidden="true"- className="i-ri-information-2-fill size-4 text-text-accent"- />+ </div>+ <FieldDescription>+ {t(($) => $['answerIcon.description'], { ns: 'app' })}+ </FieldDescription>+ </Field>+ )}+ {/* language */}+ <div className="flex items-center">+ <div className={cn('grow py-1 system-sm-semibold text-text-secondary')}>+ {t(($) => $[`${prefixSettings}.language`], { ns: 'appOverview' })}+ </div>+ <Select+ readOnly={pending}+ value={selectedLanguage?.value ?? null}+ onValueChange={handleLanguageChange}+ >+ <SelectTrigger+ aria-label={t(($) => $[`${prefixSettings}.language`], {+ ns: 'appOverview',+ })}+ size="medium"+ className="w-50"+ >+ {selectedLanguage?.name ?? t(($) => $['placeholder.select'], { ns: 'common' })}+ </SelectTrigger>+ <SelectContent>+ {LANGUAGE_OPTIONS.map((item) => (+ <SelectItem key={item.value} value={item.value}>+ <SelectItemText>{item.name}</SelectItemText>+ <SelectItemIndicator />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ {/* theme color */}+ {isChat && (+ <div className="flex items-center">+ <div className="grow">+ <div className={cn('py-1 system-sm-semibold text-text-secondary')}>+ {t(($) => $[`${prefixSettings}.chatColorTheme`], { ns: 'appOverview' })}</div>- <p className="relative min-w-0 flex-1 py-1 system-xs-medium wrap-break-word text-text-primary">- {t(($) => $[`${prefixSettings}.multiEnvironmentNotice`], {+ <div className="pb-0.5 body-xs-regular text-text-tertiary">+ {t(($) => $[`${prefixSettings}.chatColorThemeDesc`], {ns: 'appOverview',})}- </p>+ </div></div>+ <Field name="chat_color_theme" className="w-50 shrink-0">+ <Input+ readOnly={pending}+ aria-label={t(($) => $[`${prefixSettings}.chatColorTheme`], {+ ns: 'appOverview',+ })}+ className="mb-1"+ value={inputInfo.chatColorTheme ?? ''}+ onValueChange={(value) =>+ setInputInfo((item) => ({ ...item, chatColorTheme: value }))+ }+ placeholder="E.g #A020F0"+ />+ <div className="flex items-center justify-between gap-2 body-xs-regular text-text-tertiary">+ <span id={invertedThemeLabelId}>+ {t(($) => $[`${prefixSettings}.chatColorThemeInverted`], {+ ns: 'appOverview',+ })}+ </span>+ <Switch+ readOnly={pending}+ aria-labelledby={invertedThemeLabelId}+ checked={inputInfo.chatColorThemeInverted}+ onCheckedChange={(v) =>+ setInputInfo({ ...inputInfo, chatColorThemeInverted: v })+ }+ ></Switch>+ </div>+ </Field></div>)}- {/* form body */}- <ScrollArea className="row-start-2 min-h-0 overflow-hidden">- <ScrollAreaViewport className="overscroll-contain">- <ScrollAreaContent- className="flex flex-col gap-y-5 px-6 py-3"- style={{ minWidth: 0 }}- >- {/* name & icon */}- <div className="flex gap-4">- <Field name="title" className="grow">- <FieldLabel>- {t(($) => $[`${prefixSettings}.webName`], { ns: 'appOverview' })}- </FieldLabel>- <Input- value={inputInfo.title}- onValueChange={(value) =>- setInputInfo((item) => ({ ...item, title: value }))- }- placeholder={t(($) => $.appNamePlaceholder, { ns: 'app' }) || ''}- />- </Field>- <IconPicker- value={- appIcon ??- (appInfo.site.icon_type === 'emoji' && appInfo.site.icon- ? {- type: 'emoji',- icon: appInfo.site.icon,- background: appInfo.site.icon_background,- }- : undefined)- }- onValueChange={setAppIcon}- >- <IconPickerTrigger- aria-label={t(($) => $['iconPicker.title'], { ns: 'app' })}- className="mt-2 shrink-0 cursor-pointer rounded-2xl"+ {/* workflow detail */}+ <Field name="show_workflow_steps" className="w-full">+ <div className="flex items-center justify-between gap-3">+ <FieldLabel>+ {t(($) => $[`${prefixSettings}.workflow.subTitle`], { ns: 'appOverview' })}+ </FieldLabel>+ <Switch+ readOnly={pending}+ disabled={+ !(+ appInfo.mode === AppModeEnum.WORKFLOW ||+ appInfo.mode === AppModeEnum.ADVANCED_CHAT+ )+ }+ checked={inputInfo.show_workflow_steps}+ onCheckedChange={(v) => setInputInfo({ ...inputInfo, show_workflow_steps: v })}+ />+ </div>+ <FieldDescription>+ {t(($) => $[`${prefixSettings}.workflow.showDesc`], { ns: 'appOverview' })}+ </FieldDescription>+ </Field>+ <Separator className="my-0" />+ <div className="space-y-5">+ {INPUT_PLACEHOLDER_SUPPORTED_MODES.includes(appInfo.mode) && (+ <div className="w-full">+ <div className="flex items-center">+ <div className="flex grow items-center">+ <div+ id={inputPlaceholderLabelId}+ className={cn('mr-1 py-1 system-sm-semibold text-text-secondary')}>- <IconPickerIcon size="xxl" />- </IconPickerTrigger>- <IconPickerContent />- </IconPicker>- </div>- {/* description */}- <Field name="description">- <FieldLabel>- {t(($) => $[`${prefixSettings}.webDesc`], { ns: 'appOverview' })}- </FieldLabel>- <Textarea- value={inputInfo.desc}- onValueChange={onDesChange}- placeholder={- t(($) => $[`${prefixSettings}.webDescPlaceholder`], {+ {t(($) => $[`${prefixSettings}.more.inputPlaceholder`], {ns: 'appOverview',- }) as string- }- />- <FieldDescription>- {t(($) => $[`${prefixSettings}.webDescTip`], { ns: 'appOverview' })}- </FieldDescription>- </Field>- <Separator className="my-0" />- {/* answer icon */}- {isChat && (- <Field name="use_icon_as_answer_icon" className="w-full">- <div className="flex items-center justify-between gap-3">- <FieldLabel>{t(($) => $['answerIcon.title'], { ns: 'app' })}</FieldLabel>- <Switch- checked={inputInfo.use_icon_as_answer_icon}- onCheckedChange={(v) =>- setInputInfo({ ...inputInfo, use_icon_as_answer_icon: v })- }- />+ })}</div>- <FieldDescription>- {t(($) => $['answerIcon.description'], { ns: 'app' })}- </FieldDescription>- </Field>- )}- {/* language */}- <div className="flex items-center">- <div className={cn('grow py-1 system-sm-semibold text-text-secondary')}>- {t(($) => $[`${prefixSettings}.language`], { ns: 'appOverview' })}+ {deploymentEdition === 'CLOUD' && webappCopyrightEnabled === false && (+ <div className="h-4.5 select-none">+ <PremiumBadgeButton size="s" color="blue" onClick={handlePlanClick}>+ <span+ aria-hidden="true"+ className="i-custom-public-common-sparkles-soft flex h-3.5 w-3.5 items-center [background-clip:content-box] [background-origin:content-box] [mask-clip:content-box] [mask-origin:content-box] py-px pl-0.75 text-components-premium-badge-indigo-text-stop-0"+ />+ <div className="system-xs-medium">+ <span className="p-1">+ {t(($) => $['upgradeBtn.encourageShort'], { ns: 'billing' })}+ </span>+ </div>+ </PremiumBadgeButton>+ </div>+ )}</div>- <Select- value={selectedLanguage?.value ?? null}- onValueChange={handleLanguageChange}- >- <SelectTrigger- aria-label={t(($) => $[`${prefixSettings}.language`], {+ </div>+ <p+ id={inputPlaceholderDescriptionId}+ className="pb-0.5 body-xs-regular text-text-tertiary"+ >+ {t(($) => $[`${prefixSettings}.more.inputPlaceholderTip`], {+ ns: 'appOverview',+ })}+ </p>+ {deploymentEdition === 'CLOUD' && webappCopyrightEnabled === false ? (+ <Tooltip>+ <TooltipTrigger render={inputPlaceholderField} />+ <TooltipContent className="w-45">+ {t(($) => $[`${prefixSettings}.more.inputPlaceholderTooltip`], {ns: 'appOverview',})}- size="medium"- className="w-50"- >- {selectedLanguage?.name ??- t(($) => $['placeholder.select'], { ns: 'common' })}- </SelectTrigger>- <SelectContent>- {LANGUAGE_OPTIONS.map((item) => (- <SelectItem key={item.value} value={item.value}>- <SelectItemText>{item.name}</SelectItemText>- <SelectItemIndicator />- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- {/* theme color */}- {isChat && (- <div className="flex items-center">- <div className="grow">- <div className={cn('py-1 system-sm-semibold text-text-secondary')}>- {t(($) => $[`${prefixSettings}.chatColorTheme`], { ns: 'appOverview' })}- </div>- <div className="pb-0.5 body-xs-regular text-text-tertiary">- {t(($) => $[`${prefixSettings}.chatColorThemeDesc`], {- ns: 'appOverview',- })}- </div>- </div>- <Field name="chat_color_theme" className="w-50 shrink-0">- <Input- aria-label={t(($) => $[`${prefixSettings}.chatColorTheme`], {- ns: 'appOverview',- })}- className="mb-1"- value={inputInfo.chatColorTheme ?? ''}- onValueChange={(value) =>- setInputInfo((item) => ({ ...item, chatColorTheme: value }))- }- placeholder="E.g #A020F0"- />- <div className="flex items-center justify-between gap-2 body-xs-regular text-text-tertiary">- <span id={invertedThemeLabelId}>- {t(($) => $[`${prefixSettings}.chatColorThemeInverted`], {- ns: 'appOverview',- })}- </span>- <Switch- aria-labelledby={invertedThemeLabelId}- checked={inputInfo.chatColorThemeInverted}- onCheckedChange={(v) =>- setInputInfo({ ...inputInfo, chatColorThemeInverted: v })- }- ></Switch>- </div>- </Field>+ </TooltipContent>+ </Tooltip>+ ) : (+ inputPlaceholderField+ )}+ {canCustomizePlaceholder && (+ <div className="mt-1 text-right body-xs-regular text-text-tertiary">+ {`${inputInfo.inputPlaceholder?.length ?? 0} / ${INPUT_PLACEHOLDER_MAX_LENGTH}`}</div>)}- {/* workflow detail */}- <Field name="show_workflow_steps" className="w-full">- <div className="flex items-center justify-between gap-3">- <FieldLabel>- {t(($) => $[`${prefixSettings}.workflow.subTitle`], { ns: 'appOverview' })}- </FieldLabel>- <Switch- disabled={- !(- appInfo.mode === AppModeEnum.WORKFLOW ||- appInfo.mode === AppModeEnum.ADVANCED_CHAT- )- }- checked={inputInfo.show_workflow_steps}- onCheckedChange={(v) =>- setInputInfo({ ...inputInfo, show_workflow_steps: v })- }- />+ </div>+ )}+ {/* copyright */}+ <div className="w-full">+ <div className="flex items-center">+ <div className="flex grow items-center">+ <div className={cn('mr-1 py-1 system-sm-semibold text-text-secondary')}>+ {t(($) => $[`${prefixSettings}.more.copyright`], { ns: 'appOverview' })}</div>- <FieldDescription>- {t(($) => $[`${prefixSettings}.workflow.showDesc`], { ns: 'appOverview' })}- </FieldDescription>- </Field>- <Separator className="my-0" />- <div className="space-y-5">- {INPUT_PLACEHOLDER_SUPPORTED_MODES.includes(appInfo.mode) && (- <div className="w-full">- <div className="flex items-center">- <div className="flex grow items-center">- <div- id={inputPlaceholderLabelId}- className={cn('mr-1 py-1 system-sm-semibold text-text-secondary')}- >- {t(($) => $[`${prefixSettings}.more.inputPlaceholder`], {- ns: 'appOverview',- })}- </div>- {deploymentEdition === 'CLOUD' && webappCopyrightEnabled === false && (- <div className="h-4.5 select-none">- <PremiumBadgeButton size="s" color="blue" onClick={handlePlanClick}>- <span- aria-hidden="true"- className="i-custom-public-common-sparkles-soft flex h-3.5 w-3.5 items-center [background-clip:content-box] [background-origin:content-box] [mask-clip:content-box] [mask-origin:content-box] py-px pl-0.75 text-components-premium-badge-indigo-text-stop-0"- />- <div className="system-xs-medium">- <span className="p-1">- {t(($) => $['upgradeBtn.encourageShort'], { ns: 'billing' })}- </span>- </div>- </PremiumBadgeButton>- </div>- )}- </div>- </div>- <p- id={inputPlaceholderDescriptionId}- className="pb-0.5 body-xs-regular text-text-tertiary"- >- {t(($) => $[`${prefixSettings}.more.inputPlaceholderTip`], {- ns: 'appOverview',- })}- </p>- {deploymentEdition === 'CLOUD' && webappCopyrightEnabled === false ? (- <Tooltip>- <TooltipTrigger render={inputPlaceholderField} />- <TooltipContent className="w-45">- {t(($) => $[`${prefixSettings}.more.inputPlaceholderTooltip`], {- ns: 'appOverview',- })}- </TooltipContent>- </Tooltip>- ) : (- inputPlaceholderField- )}- {canCustomizePlaceholder && (- <div className="mt-1 text-right body-xs-regular text-text-tertiary">- {`${inputInfo.inputPlaceholder?.length ?? 0} / ${INPUT_PLACEHOLDER_MAX_LENGTH}`}+ {/* upgrade button */}+ {deploymentEdition === 'CLOUD' && webappCopyrightEnabled === false && (+ <div className="h-4.5 select-none">+ <PremiumBadgeButton size="s" color="blue" onClick={handlePlanClick}>+ <span+ aria-hidden="true"+ className="i-custom-public-common-sparkles-soft flex h-3.5 w-3.5 items-center [background-clip:content-box] [background-origin:content-box] [mask-clip:content-box] [mask-origin:content-box] py-px pl-0.75 text-components-premium-badge-indigo-text-stop-0"+ />+ <div className="system-xs-medium">+ <span className="p-1">+ {t(($) => $['upgradeBtn.encourageShort'], { ns: 'billing' })}+ </span></div>- )}+ </PremiumBadgeButton></div>)}- {/* copyright */}- <div className="w-full">- <div className="flex items-center">- <div className="flex grow items-center">- <div className={cn('mr-1 py-1 system-sm-semibold text-text-secondary')}>- {t(($) => $[`${prefixSettings}.more.copyright`], { ns: 'appOverview' })}- </div>- {/* upgrade button */}- {deploymentEdition === 'CLOUD' && webappCopyrightEnabled === false && (- <div className="h-4.5 select-none">- <PremiumBadgeButton size="s" color="blue" onClick={handlePlanClick}>- <span- aria-hidden="true"- className="i-custom-public-common-sparkles-soft flex h-3.5 w-3.5 items-center [background-clip:content-box] [background-origin:content-box] [mask-clip:content-box] [mask-origin:content-box] py-px pl-0.75 text-components-premium-badge-indigo-text-stop-0"- />- <div className="system-xs-medium">- <span className="p-1">- {t(($) => $['upgradeBtn.encourageShort'], { ns: 'billing' })}- </span>- </div>- </PremiumBadgeButton>- </div>- )}- </div>- {webappCopyrightEnabled !== false ? (- <Switch- disabled={webappCopyrightEnabled !== true}- aria-label={t(($) => $[`${prefixSettings}.more.copyright`], {- ns: 'appOverview',- })}- checked={copyrightSwitchValue}- onCheckedChange={(v) =>- setInputInfo({ ...inputInfo, copyrightSwitchValue: v })- }- />- ) : (- <Tooltip>- <TooltipTrigger- render={- <div>- <Switch- aria-label={t(($) => $[`${prefixSettings}.more.copyright`], {- ns: 'appOverview',- })}- disabled- checked={copyrightSwitchValue}- onCheckedChange={(v) =>- setInputInfo({ ...inputInfo, copyrightSwitchValue: v })- }- />- </div>- }- />- <TooltipContent className="w-45">- {t(($) => $[`${prefixSettings}.more.copyrightTooltip`], {+ </div>+ {webappCopyrightEnabled !== false ? (+ <Switch+ readOnly={pending}+ disabled={webappCopyrightEnabled !== true}+ aria-label={t(($) => $[`${prefixSettings}.more.copyright`], {+ ns: 'appOverview',+ })}+ checked={copyrightSwitchValue}+ onCheckedChange={(v) =>+ setInputInfo({ ...inputInfo, copyrightSwitchValue: v })+ }+ />+ ) : (+ <Tooltip>+ <TooltipTrigger+ render={+ <div>+ <Switch+ readOnly={pending}+ aria-label={t(($) => $[`${prefixSettings}.more.copyright`], {ns: 'appOverview',})}- </TooltipContent>- </Tooltip>- )}- </div>- <p className="pb-0.5 body-xs-regular text-text-tertiary">- {t(($) => $[`${prefixSettings}.more.copyrightTip`], { ns: 'appOverview' })}- </p>- {copyrightSwitchValue && (- <Input- aria-label={t(($) => $[`${prefixSettings}.more.copyright`], {- ns: 'appOverview',- })}- className="mt-2 h-10"- disabled={webappCopyrightEnabled !== true}- value={inputInfo.copyright}- onChange={onChange('copyright')}- placeholder={- t(($) => $[`${prefixSettings}.more.copyRightPlaceholder`], {- ns: 'appOverview',- }) as string- }- />- )}- </div>- {/* privacy policy */}- <div className="w-full">- <div className={cn('py-1 system-sm-semibold text-text-secondary')}>- {t(($) => $[`${prefixSettings}.more.privacyPolicy`], { ns: 'appOverview' })}- </div>- <p className={cn('pb-0.5 body-xs-regular text-text-tertiary')}>- <Trans- i18nKey={($) => $[`${prefixSettings}.more.privacyPolicyTip`]}- ns="appOverview"- components={{- privacyPolicyLink: (- <Link- href="https://dify.ai/privacy"- target="_blank"- rel="noopener noreferrer"- className="text-text-accent"- />- ),- }}- />- </p>- <Input- aria-label={t(($) => $[`${prefixSettings}.more.privacyPolicy`], {- ns: 'appOverview',- })}- className="mt-1"- value={inputInfo.privacyPolicy}- onChange={onChange('privacyPolicy')}- placeholder={- t(($) => $[`${prefixSettings}.more.privacyPolicyPlaceholder`], {- ns: 'appOverview',- }) as string+ disabled+ checked={copyrightSwitchValue}+ onCheckedChange={(v) =>+ setInputInfo({ ...inputInfo, copyrightSwitchValue: v })+ }+ />+ </div>}/>- </div>- {/* custom disclaimer */}- <div className="w-full">- <div className={cn('py-1 system-sm-semibold text-text-secondary')}>- {t(($) => $[`${prefixSettings}.more.customDisclaimer`], {- ns: 'appOverview',- })}- </div>- <p className={cn('pb-0.5 body-xs-regular text-text-tertiary')}>- {t(($) => $[`${prefixSettings}.more.customDisclaimerTip`], {- ns: 'appOverview',- })}- </p>- <Textarea- aria-label={t(($) => $[`${prefixSettings}.more.customDisclaimer`], {+ <TooltipContent className="w-45">+ {t(($) => $[`${prefixSettings}.more.copyrightTooltip`], {ns: 'appOverview',})}- className="mt-1"- value={inputInfo.customDisclaimer}- onValueChange={(value) =>- setInputInfo((item) => ({ ...item, customDisclaimer: value }))- }- placeholder={- t(($) => $[`${prefixSettings}.more.customDisclaimerPlaceholder`], {- ns: 'appOverview',- }) as string- }- />- </div>- </div>- </ScrollAreaContent>- </ScrollAreaViewport>- <ScrollAreaScrollbar>- <ScrollAreaThumb />- </ScrollAreaScrollbar>- </ScrollArea>- {/* footer */}- <div className="row-start-3 flex shrink-0 justify-end p-6 pt-5">- <Button type="button" className="mr-2" onClick={handleClose}>- {t(($) => $['operation.cancel'], { ns: 'common' })}- </Button>- <Button type="submit" variant="primary" loading={saveLoading}>- {t(($) => $['operation.save'], { ns: 'common' })}- </Button>+ </TooltipContent>+ </Tooltip>+ )}+ </div>+ <p className="pb-0.5 body-xs-regular text-text-tertiary">+ {t(($) => $[`${prefixSettings}.more.copyrightTip`], { ns: 'appOverview' })}+ </p>+ {copyrightSwitchValue && (+ <Input+ readOnly={pending}+ aria-label={t(($) => $[`${prefixSettings}.more.copyright`], {+ ns: 'appOverview',+ })}+ className="mt-2 h-10"+ disabled={webappCopyrightEnabled !== true}+ value={inputInfo.copyright}+ onChange={onChange('copyright')}+ placeholder={+ t(($) => $[`${prefixSettings}.more.copyRightPlaceholder`], {+ ns: 'appOverview',+ }) as string+ }+ />+ )}+ </div>+ {/* privacy policy */}+ <div className="w-full">+ <div className={cn('py-1 system-sm-semibold text-text-secondary')}>+ {t(($) => $[`${prefixSettings}.more.privacyPolicy`], { ns: 'appOverview' })}+ </div>+ <p className={cn('pb-0.5 body-xs-regular text-text-tertiary')}>+ <Trans+ i18nKey={($) => $[`${prefixSettings}.more.privacyPolicyTip`]}+ ns="appOverview"+ components={{+ privacyPolicyLink: (+ <Link+ href="https://dify.ai/privacy"+ target="_blank"+ rel="noopener noreferrer"+ className="text-text-accent"+ />+ ),+ }}+ />+ </p>+ <Input+ readOnly={pending}+ aria-label={t(($) => $[`${prefixSettings}.more.privacyPolicy`], {+ ns: 'appOverview',+ })}+ className="mt-1"+ value={inputInfo.privacyPolicy}+ onChange={onChange('privacyPolicy')}+ placeholder={+ t(($) => $[`${prefixSettings}.more.privacyPolicyPlaceholder`], {+ ns: 'appOverview',+ }) as string+ }+ />+ </div>+ {/* custom disclaimer */}+ <div className="w-full">+ <div className={cn('py-1 system-sm-semibold text-text-secondary')}>+ {t(($) => $[`${prefixSettings}.more.customDisclaimer`], {+ ns: 'appOverview',+ })}+ </div>+ <p className={cn('pb-0.5 body-xs-regular text-text-tertiary')}>+ {t(($) => $[`${prefixSettings}.more.customDisclaimerTip`], {+ ns: 'appOverview',+ })}+ </p>+ <Textarea+ readOnly={pending}+ aria-label={t(($) => $[`${prefixSettings}.more.customDisclaimer`], {+ ns: 'appOverview',+ })}+ className="mt-1"+ value={inputInfo.customDisclaimer}+ onValueChange={(value) =>+ setInputInfo((item) => ({ ...item, customDisclaimer: value }))+ }+ placeholder={+ t(($) => $[`${prefixSettings}.more.customDisclaimerPlaceholder`], {+ ns: 'appOverview',+ }) as string+ }+ />+ </div></div>- </Form>- </DialogContent>- </Dialog>- </>+ </ScrollAreaContent>+ </ScrollAreaViewport>+ <ScrollAreaScrollbar>+ <ScrollAreaThumb />+ </ScrollAreaScrollbar>+ </ScrollArea>+ {/* footer */}+ <div className="row-start-3 flex shrink-0 justify-end p-6 pt-5">+ <DialogClose disabled={pending} render={<Button className="mr-2" />}>+ {t(($) => $['operation.cancel'], { ns: 'common' })}+ </DialogClose>+ <Button type="submit" variant="primary" loading={pending} disabled={disabled}>+ {t(($) => $['operation.save'], { ns: 'common' })}+ </Button>+ </div>+ </Form>+ )+}++export function SettingsDialog({+ appInfo,+ isChat,+ canDeploy,+ disabled,+ triggerLabel,+ onSave,+}: SettingsDialogProps) {+ const { t } = useTranslation(['appOverview', 'common', 'navigation'])+ const [pending, setPending] = useState(false)+ const pendingRef = useRef(false)+ const actionsRef = useRef<DialogActions>(null)+ const unavailable = disabled || !appInfo+ const trigger = (+ <Button variant="secondary" disabled={unavailable || pending} className="px-3">+ <span aria-hidden className="i-ri-equalizer-2-line size-4" />+ {triggerLabel ?? t(($) => $['settings.settings'], { ns: 'navigation' })}+ </Button>+ )++ const handleSave = async (params: AppSiteUpdatePayload) => {+ if (pendingRef.current || unavailable) return+ pendingRef.current = true+ setPending(true)+ try {+ if ((await onSave(params)) === true) actionsRef.current?.close()+ } catch {+ // Request owners report failures; keep the draft on unexpected rejection too.+ } finally {+ pendingRef.current = false+ setPending(false)+ }+ }++ if (!appInfo) return trigger++ return (+ <Dialog+ actionsRef={actionsRef}+ disablePointerDismissal+ onOpenChange={(_open, details) => {+ if (pendingRef.current && details.reason !== 'imperative-action') details.cancel()+ }}+ >+ <DialogTrigger render={trigger} />+ <DialogContent className="grid max-h-[calc(100dvh-2rem)] w-130 grid-rows-[auto_minmax(0,1fr)] overflow-hidden p-0">+ <div className="shrink-0 pt-5 pr-5 pb-3 pl-6">+ <div className="flex items-center gap-1">+ <DialogTitle className="grow title-2xl-semi-bold text-text-primary">+ {t(($) => $[`${prefixSettings}.title`], { ns: 'appOverview' })}+ </DialogTitle>+ <DialogClose+ disabled={pending}+ render={+ <IconButton+ aria-label={t(($) => $['operation.close'], { ns: 'common' })}+ size="sm"+ className="relative top-auto right-auto shrink-0 rounded-2xl"+ >+ <span aria-hidden className="i-ri-close-line size-4" />+ </IconButton>+ }+ />+ </div>+ <DialogDescription className="mt-0.5 system-xs-regular text-text-tertiary">+ {t(($) => $[`${prefixSettings}.modalTip`], { ns: 'appOverview' })}+ </DialogDescription>+ </div>+ <SettingsForm+ key={appInfo.id}+ appInfo={appInfo}+ isChat={isChat}+ canDeploy={canDeploy}+ disabled={disabled}+ pending={pending}+ onSubmit={handleSave}+ />+ </DialogContent>+ </Dialog>)}-export default React.memo(SettingsModal)diff --git a/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsxindex 65a1d971677..5a8430648cb 100644--- a/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx+++ b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx@@ -4,8 +4,8 @@ import type {} from '@dify/contracts/api/console/agent/types.gen'import type { AppDetail } from '@dify/contracts/api/console/apps/types.gen'import type React from 'react'-import { QueryClient } from '@tanstack/react-query'-import { render, screen, waitFor, within } from '@testing-library/react'+import { QueryClient, useQuery } from '@tanstack/react-query'+import { act, render, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { NuqsTestingAdapter } from 'nuqs/adapters/testing'import { toast } from '@/app/notifications'@@ -23,6 +23,7 @@ import { WebAppAccessCard } from '../web-app-access-card'const mocks = vi.hoisted(() => ({getUserCanAccess:vi.fn<(appId: string, isInstalledApp: boolean) => Promise<{ result: boolean }>>(),+ agentDetailQueryFn: vi.fn(),apiAccessQueryFn: vi.fn(),apiKeysQueryFn: vi.fn(),siteEnableMutation: vi.fn(),@@ -176,7 +177,7 @@ vi.mock('@/service/console', () => ({get: {queryOptions: ({ input }: { input: { params: { agent_id: string } } }) => ({queryKey: ['agent-detail', input.params.agent_id],- queryFn: async () => createAgent(),+ queryFn: () => mocks.agentDetailQueryFn(),staleTime: Infinity,}),queryKey: ({ input }: { input: { params: { agent_id: string } } }) => [@@ -337,6 +338,15 @@ function createConsoleQueryClient(webAppAuthEnabled = true) {return queryClient}+function QueryOwnedWebAppCard() {+ const { data: agent, isPending } = useQuery(+ consoleQuery.agent.byAgentId.get.queryOptions({+ input: { params: { agent_id: 'agent-1' } },+ }),+ )+ return <WebAppAccessCard agent={agent} agentId="agent-1" isLoading={isPending} />+}+function createDeferredPromise<T>() {let resolve!: (value: T) => voidlet reject!: (reason?: unknown) => void@@ -351,6 +361,7 @@ function createDeferredPromise<T>() {describe('Agent access surface cards', () => {beforeEach(() => {vi.clearAllMocks()+ mocks.agentDetailQueryFn.mockResolvedValue(createAgent())mocks.getUserCanAccess.mockResolvedValue({ result: true })mocks.accessSubjectsQueryFn.mockResolvedValue({ groups: [], members: [] })})@@ -823,6 +834,72 @@ describe('Agent access surface cards', () => {})})+ it('preserves the draft after POST failure and closes on retry before detail refresh completes', async () => {+ const user = userEvent.setup()+ const refreshed = createDeferredPromise<AgentAppDetailWithSite>()+ mocks.siteMutation.mockResolvedValue({}).mockRejectedValueOnce(new Error('Save failed'))+ const queryClient = renderWithQueryClient(<QueryOwnedWebAppCard />)+ const trigger = screen.getByRole('button', {+ name: 'agentV2.agentDetail.access.webApp.actions.settings',+ })+ await user.click(trigger)+ const dialog = await screen.findByRole('dialog', {+ name: 'appOverview.overview.appInfo.settings.title',+ })+ const name = within(dialog).getByPlaceholderText('app.appNamePlaceholder')+ await user.clear(name)+ await user.type(name, 'Committed portal')+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))+ await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1))+ expect(dialog).toBeInTheDocument()+ expect(name).toHaveValue('Committed portal')+ expect(mocks.agentDetailQueryFn).not.toHaveBeenCalled()++ mocks.agentDetailQueryFn.mockReturnValueOnce(refreshed.promise)+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ expect(toast.success).toHaveBeenCalledTimes(1)+ expect(mocks.agentDetailQueryFn).toHaveBeenCalledTimes(1)+ const updated = createAgent({+ site: { ...createAgent().site!, title: 'Committed portal', chat_color_theme: '#123456' },+ })+ await act(async () => refreshed.resolve(updated))+ await waitFor(() =>+ expect(queryClient.getQueryData(['agent-detail', 'agent-1'])).toEqual(updated),+ )+ await user.click(trigger)+ const reopened = await screen.findByRole('dialog', {+ name: 'appOverview.overview.appInfo.settings.title',+ })+ expect(within(reopened).getByPlaceholderText('app.appNamePlaceholder')).toHaveValue(+ 'Committed portal',+ )+ expect(within(reopened).getByPlaceholderText('E.g #A020F0')).toHaveValue('#123456')+ })++ it('closes after a successful POST even when background agent refresh fails', async () => {+ const user = userEvent.setup()+ mocks.siteMutation.mockResolvedValue({})+ mocks.agentDetailQueryFn.mockRejectedValueOnce(new Error('Refresh failed'))+ const queryClient = renderWithQueryClient(<QueryOwnedWebAppCard />)+ await user.click(+ screen.getByRole('button', {+ name: 'agentV2.agentDetail.access.webApp.actions.settings',+ }),+ )+ const dialog = await screen.findByRole('dialog', {+ name: 'appOverview.overview.appInfo.settings.title',+ })+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))++ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ await waitFor(() =>+ expect(queryClient.getQueryState(['agent-detail', 'agent-1'])?.status).toBe('error'),+ )+ expect(toast.success).toHaveBeenCalledTimes(1)+ expect(toast.error).not.toHaveBeenCalled()+ })+it('should fall back to the Agent icon tuple when WebApp site icon data is missing', async () => {const user = userEvent.setup()const agent = createAgent({diff --git a/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx b/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsxindex 47f24beb121..a3f5ee21286 100644--- a/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx+++ b/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx@@ -16,7 +16,7 @@ import {} from '@/app/components/app/access-point/shared/web-app-access-control'import { CustomizeDialog } from '@/app/components/app/overview/customize'import { EmbeddedDialogContent } from '@/app/components/app/overview/embedded'-import SettingsModal from '@/app/components/app/overview/settings'+import { SettingsDialog } from '@/app/components/app/overview/settings'import { AccessPointCard } from '@/app/components/base/access-point/card'import { AccessPointUrl } from '@/app/components/base/access-point/url'import AppIcon from '@/app/components/base/app-icon'@@ -74,7 +74,6 @@ export function WebAppAccessCard({appId,}: null- const [showSettingsModal, setShowSettingsModal] = useState(false)const [showAccessControl, setShowAccessControl] = useState(false)const accessControl = useWebAppAccessControl(agent, isLoading)const agentDetailQueryKey = consoleQuery.agent.byAgentId.get.queryKey({@@ -183,8 +182,8 @@ export function WebAppAccessCard({})}- async function handleSaveSettings(params: AppSiteUpdatePayload) {- if (!appId || !canManageWebApp) return+ async function handleSaveSettings(params: AppSiteUpdatePayload): Promise<boolean> {+ if (!appId || !canManageWebApp) return falseconst sitePayload = params satisfies AppSiteUpdatePayload@@ -195,10 +194,12 @@ export function WebAppAccessCard({},body: sitePayload,})- await queryClient.invalidateQueries({ queryKey: agentDetailQueryKey })+ void queryClient.invalidateQueries({ queryKey: agentDetailQueryKey })toast.success(tCommon(($) => $['actionMsg.modifiedSuccessfully']))+ return true} catch {toast.error(tCommon(($) => $['actionMsg.modifiedUnsuccessfully']))+ return false}}@@ -263,15 +264,13 @@ export function WebAppAccessCard({{t(($) => $['agentDetail.access.webApp.actions.customFrontend'])}</Button>)}- <Button- variant="secondary"- disabled={!canManageWebApp || !settingsAppInfo || updateSiteMutation.isPending}- onClick={() => setShowSettingsModal(true)}- className="flex items-center gap-1 px-3"- >- <span aria-hidden className="i-ri-equalizer-2-line size-4" />- {t(($) => $['agentDetail.access.webApp.actions.settings'])}- </Button>+ <SettingsDialog+ key={appId}+ isChat+ appInfo={canManageWebApp && settingsAppInfo ? settingsAppInfo : undefined}+ onSave={handleSaveSettings}+ triggerLabel={t(($) => $['agentDetail.access.webApp.actions.settings'])}+ /></>}>@@ -316,15 +315,6 @@ export function WebAppAccessCard({)}</AccessPointCard>- {canManageWebApp && settingsAppInfo && (- <SettingsModal- isChat- appInfo={settingsAppInfo}- isShow={showSettingsModal}- onClose={() => setShowSettingsModal(false)}- onSave={handleSaveSettings}- />- )}{canManageAccessPoint && showAccessControl && accessControl.state === 'ready' && (<AccessControlapp={accessControl.app}